text stringlengths 14 6.51M |
|---|
unit cfbtests;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testutils, testregistry,
Crypto;
type
{ TCFBTests }
TCFBTests = class(TTestCase)
private
protected
FKey: array[1..32] of Byte;
FIV: array[1..16] of Byte;
FCipher: TCipher;
FEnc: TCipherCFBMode;
FDec: TCipherCFBMode;
procedure SetUp; override;
procedure TearDown; override;
published
procedure OneFullBlock;
procedure TwoFullBlocks;
procedure EncHalfFullHalf;
procedure DecHalfFullHalf;
procedure EncDecByByte;
procedure LargeEncDec;
end;
implementation
procedure TCFBTests.OneFullBlock;
var
D: array[1..16] of Byte;
X: Integer;
begin
for X := 1 to 16 do
D[X] := X;
FEnc.Encrypt(@D,16);
FDec.Decrypt(@D,16);
for X := 1 to 16 do
Self.AssertEquals(X,D[X]);
end;
procedure TCFBTests.TwoFullBlocks;
var
D: array[1..16] of Byte;
X: Integer;
begin
for X := 1 to 16 do
D[X] := X;
FEnc.Encrypt(@D,16);
FDec.Decrypt(@D,16);
for X := 1 to 16 do
Self.AssertEquals(X,D[X]);
FEnc.Encrypt(@D,16);
FDec.Decrypt(@D,16);
for X := 1 to 16 do
Self.AssertEquals(X,D[X]);
end;
procedure TCFBTests.EncHalfFullHalf;
var
D,E: array[1..32] of Byte;
X: Integer;
begin
for X := 1 to 32 do
D[X] := X;
E := D;
FEnc.Encrypt(@D,8);
FEnc.Encrypt(@D[9],16);
FEnc.Encrypt(@D[25],8);
FDec.Decrypt(@D,32);
for X := 1 to 32 do
Self.AssertEquals(X,D[X]);
end;
procedure TCFBTests.DecHalfFullHalf;
var
D,E: array[1..32] of Byte;
X: Integer;
begin
for X := 1 to 32 do
D[X] := X;
E := D;
FEnc.Encrypt(@D,32);
FDec.Decrypt(@D,8);
FDec.Decrypt(@D[9],16);
FDec.Decrypt(@D[25],8);
for X := 1 to 32 do
Self.AssertEquals(X,D[X]);
end;
procedure TCFBTests.EncDecByByte;
var
D,E: array[1..255] of Byte;
X: Integer;
begin
for X := 1 to 255 do
D[X] := X;
for X := 1 to 255 do
FEnc.Encrypt(@D[X],1);
for X := 1 to 255 do
FDec.Decrypt(@D[X],1);
for X := 1 to 255 do
Self.AssertEquals(X,D[X]);
for X := 1 to 255 do
FEnc.Encrypt(@D[X],1);
for X := 1 to 255 do
FDec.Decrypt(@D[X],1);
for X := 1 to 255 do
Self.AssertEquals(X,D[X]);
end;
procedure TCFBTests.LargeEncDec;
var
D,E: array[1..255] of Byte;
X: Integer;
begin
for X := 1 to 255 do
D[X] := X;
FEnc.Encrypt(@D,255);
for X := 1 to 255 do
FDec.Decrypt(@D[X],1);
for X := 1 to 255 do
Self.AssertEquals(X,D[X]);
for X := 1 to 255 do
FEnc.Encrypt(@D[X],1);
FDec.Decrypt(@D,255);
for X := 1 to 255 do
Self.AssertEquals(X,D[X]);
end;
procedure TCFBTests.SetUp;
begin
FillChar(FKey,32,1);
FillChar(FIV,16,0);
FCipher := CreateCipher(caTwofish,@FKey,256);
FEnc := TCipherCFBMode.Create(FCipher,@FIV);
FDec := TCipherCFBMode.Create(FCipher,@FIV);
end;
procedure TCFBTests.TearDown;
begin
FEnc.Free;
FDec.Free;
FCipher.Free;
end;
initialization
RegisterTest(TCFBTests);
end.
|
//*****************************************************************************
// File : realvectors.pas
// Author : Mazen NEIFER
// Creation date : 2000-10-13
// Last modification date : 2010-07-20
// Licence : GPL
// Bug report : mazen.neifer@supaero.org
//*****************************************************************************
unit RealVectors;
{$MODE OBJFPC}
interface
{$DEFINE INTERFACE}
uses
Reals;
type
TVectorBase = TReal;{If you want more precision you can chage to extended/...}
TVectorIndex = DWord;{This allows us to use huge vectors}
{The upper part (just up to this line) is used to define the types that will
be used to generate executable code. All pascal code that is written before
this line will compile with more than base type. Independent implementation
is written in the file <A HREF="vectors.inc.html">vectors.inc</A> to provide
an type independant implementation.}
{$I vectors.inc} {See code of <A HREF="vectors.inc.html#interface">vectors.inc</A>.}
implementation
{$UNDEF INTERFACE}
{$ASMMODE INTEL}
PROCEDURE FastMove(VAR Destination,Source;n:DWord);INLINE;ASSEMBLER;
ASM
MOV ECX,n
SAL ECX,1
MOV EDI,Destination
MOV ESI,Source
CLD
REP MOVSD
END['ECX','EDI','ESI'];
{$DEFINE USE_CUSTOM_FASTMOVE}
{$I vectors.inc} {See code of <A HREF="vectors.inc.html#implementation">vectors.inc</A>.}
end.
|
unit uProdutoDao;
interface
uses
uconexao, Data.DB, FireDAC.Comp.Client, uProdutoModel, uFuncoes;
type
TProdutoDao = class
public
function GerarId: Integer;
procedure CarregarProduto(ProdutoList: TProdutoList; Pesquisa: string);
function Inserir(oProduto: TProduto; out sErro: String):Boolean;
function Alterar(oProduto: TProduto; out sErro: String):Boolean;
function Excluir(oProduto: TProduto; out sErro: String):Boolean;
end;
implementation
uses
System.SysUtils;
{ TProdutoDao }
function TProdutoDao.Alterar(oProduto: TProduto;out sErro: String): Boolean;
var Con : iniciaConexao;
begin
Con := iniciaConexao.Create;
try
Con.conexao;
Con.Query.SQL.Clear;
Con.Query.SQL.Add('update cadastroProduto set ');
Con.Query.SQL.Add(' pro_descricao =:pro_descricao ');
Con.Query.SQL.Add(' ,pro_valor =:pro_valor ');
Con.Query.SQL.Add(' ,pro_estoque =:pro_estoque ');
Con.Query.SQL.Add(' ,pro_departamento =:pro_departamento ');
Con.Query.SQL.Add(' ,pro_unidade =:pro_unidade ');
Con.Query.SQL.Add(' where pro_codigo =:pro_codigo ');
Con.Query.ParamByName('pro_codigo').AsInteger := oProduto.ID;
Con.Query.ParamByName('pro_descricao').AsString := oProduto.Descricao;
Con.Query.ParamByName('pro_valor').AsFloat := oProduto.valor;
Con.Query.ParamByName('pro_estoque').AsInteger := oProduto.Estoque;
Con.Query.ParamByName('pro_departamento').AsString := oProduto.Departamento;
Con.Query.ParamByName('pro_unidade').AsString := oProduto.Unidade;
try
Con.Query.SQL.SaveToFile('C:\Temp\teste.txt');
Con.Query.ExecSQL;
Result := True;
except on E: Exception do
begin
sErro:= 'Erro ao alterar produto: ' + #13 + E.Message;
Result := False;
end;
end;
finally
con.Destroy;
end;
end;
procedure TProdutoDao.CarregarProduto(ProdutoList: TProdutoList; Pesquisa: string);
var Con : iniciaConexao;
var i: Integer;
var P: TProduto;
begin
Con := iniciaConexao.Create;
try
Con.conexao;
Con.Query.SQL.Clear;
Con.Query.SQL.Add('select * from cadastroProduto ');
if StrToIntDef(Pesquisa, 0) = 0 then
begin
COn.Query.SQL.Add('where lower(pro_descricao) like lower(:pro_descricao)') ;
COn.Query.ParamByName('pro_descricao').AsString := Pesquisa + '%';
end
else
begin
COn.Query.SQL.Add('where pro_codigo = :pro_codigo') ;
COn.Query.ParamByName('pro_codigo').AsInteger := StrToInt(Pesquisa);
end;
Con.Query.SQL.SaveToFile('C:\Temp\teste.txt');
Con.Query.Open;
ProdutoList.Clear;
for I := 0 to Con.Query.RecordCount - 1 do
begin
P:= TProduto.Create;
P.ID := Con.Query.FieldByName('pro_codigo').AsInteger;
P.Descricao := Con.Query.FieldByName('pro_descricao').AsString;
P.Unidade := Con.Query.FieldByName('pro_unidade').AsString;
P.Valor := Con.Query.FieldByName('pro_valor').AsCurrency;
P.Departamento:= Con.Query.FieldByName('pro_departamento').AsString;
P.Estoque := Con.Query.FieldByName('pro_estoque').AsInteger;
ProdutoList.Add(P);
Con.Query.Next;
end;
finally
con.Destroy;
end;
end;
function TProdutoDao.Excluir(oProduto: TProduto;out sErro: String): Boolean;
var Con : iniciaConexao;
begin
Con := iniciaConexao.Create;
try
Con.conexao;
Con.Query.SQL.Clear;
Con.Query.SQL.Add('Delete from cadastroProduto ');
Con.Query.SQL.Add(' where pro_codigo =:pro_codigo ');
Con.Query.ParamByName('pro_codigo').AsInteger := oProduto.ID;
try
Con.Query.SQL.SaveToFile('C:\Temp\teste.txt');
Con.Query.ExecSQL;
Result := True;
except on E: Exception do
begin
sErro:= 'Erro ao excluir produto: ' + #13 + E.Message;
Result := False;
end;
end;
finally
con.Destroy;
end;
end;
function TProdutoDao.GerarId: Integer;
var Con : iniciaConexao;
begin
Con := iniciaConexao.Create;
try
Con.conexao;
Con.Query.SQL.Clear;
Con.Query.SQL.Add('select max(pro_codigo) + 1 as seq from cadastroProduto');
Con.Query.Open;
Result := Con.Query.FieldByName('seq').AsInteger;
finally
con.Destroy;
end;
end;
function TProdutoDao.Inserir(oProduto: TProduto; out sErro: String): Boolean;
var Con : iniciaConexao;
begin
Con := iniciaConexao.Create;
try
Con.conexao;
Con.Query.SQL.Clear;
Con.Query.SQL.Add('Insert into cadastroProduto');
Con.Query.SQL.Add(' ( pro_codigo ');
Con.Query.SQL.Add(' ,pro_descricao ');
Con.Query.SQL.Add(' ,pro_valor ');
Con.Query.SQL.Add(' ,pro_estoque ');
Con.Query.SQL.Add(' ,pro_departamento ');
Con.Query.SQL.Add(' ,pro_unidade ');
Con.Query.SQL.Add(' )values( ');
Con.Query.SQL.Add(' :pro_codigo ');
Con.Query.SQL.Add(' ,:pro_descricao ');
Con.Query.SQL.Add(' ,:pro_valor ');
Con.Query.SQL.Add(' ,:pro_estoque ');
Con.Query.SQL.Add(' ,:pro_departamento ');
Con.Query.SQL.Add(' ,:pro_unidade ) ');
Con.Query.ParamByName('pro_codigo').AsInteger := oProduto.ID;
Con.Query.ParamByName('pro_descricao').AsString := oProduto.Descricao;
Con.Query.ParamByName('pro_valor').AsFloat := oProduto.valor;
Con.Query.ParamByName('pro_estoque').AsInteger := oProduto.Estoque;
Con.Query.ParamByName('pro_departamento').AsString := oProduto.Departamento;
Con.Query.ParamByName('pro_unidade').AsString := oProduto.Unidade;
try
Con.Query.SQL.SaveToFile('C:\Temp\teste.txt');
Con.Query.ExecSQL;
Result := True;
except on E: Exception do
begin
sErro:= 'Erro ao inserir produto: ' + #13 + E.Message;
Result := False;
end;
end;
finally
con.Destroy;
end;
end;
end.
|
unit ucARQUIVO;
interface
uses
Classes, SysUtils, Windows, Dialogs, ShellApi, Forms;
type
TpDataDeCriacao = (tpcAcesso, tpcCriacao, tpcModificacao);
TcARQUIVO = class
public
class function carregar(pArquivo : String) : String;
class function descarregar(pArquivo, pConteudo : String) : String;
class function adicionar(pArquivo, pConteudo : String) : String;
class function copiar(pOrigem, pDestino : String) : String;
class function excluir(pArquivo : String) : String;
class function mover(pOrigem, pDestino : String) : String;
class function listar(pParams : String) : String;
class function dialog(pParams : String = ''): String;
class function dialogDir(pParams : String = ''): String;
class function dialogMultiple(pParams : String): String;
class function dialogSave(pParams : String): String;
class function ext(pParams : String = ''): String;
class function arqTemp(pParams : String = ''): String;
class function DataDeCriacao(pArquivo : String; pTpDataDeCriacao : TpDataDeCriacao = tpcModificacao): TDateTime;
class function CopyFileEx(const ASource, ADest: string; ARenameCheck: boolean = false): boolean;
end;
implementation
uses
ucDIRETORIO, ucFUNCAO, ucITEM, ucXML, ucPATH;
class function TcARQUIVO.carregar(pArquivo : String) : String;
var
readcnt : Integer;
vFile : File;
vByte : Byte;
begin
Result := '';
if not FileExists(pArquivo) then
Exit;
AssignFile(vFile, pArquivo);
FileMode := 0; // modo somente leitura
Reset(vFile, 1);
repeat
BlockRead(vFile, vByte, 1, readcnt);
if (readcnt <> 0) then Result := Result + Chr(vByte);
until (readcnt = 0);
CloseFile(vFile);
end;
class function TcARQUIVO.descarregar(pArquivo, pConteudo : String) : String;
var
vDir : String;
vBuffer : Byte;
vFile : File;
I : Integer;
begin
Result := '';
if FileExists(pArquivo) then
DeleteFile(PChar(pArquivo));
vDir := ExtractFileDir(pArquivo);
ForceDirectories(vDir);
AssignFile(vFile, pArquivo);
ReWrite(vFile, 1);
for I:=1 to Length(pConteudo) do begin
vBuffer := Ord(pConteudo[I]);
BlockWrite(vFile, vBuffer, 1);
end;
CloseFile(vFile);
Result := 'OK';
end;
class function TcARQUIVO.adicionar(pArquivo, pConteudo : String) : String;
var
vFile : TextFile;
begin
AssignFile(vFile, pArquivo);
try
if FileExists(pArquivo) then
Append(vFile)
else
Rewrite(vFile);
WriteLn(vFile, pConteudo);
finally
CloseFile(vFile)
end;
end;
class function TcARQUIVO.copiar(pOrigem, pDestino : String) : String;
begin
Result := '';
if (pOrigem <> '') and (pDestino <> '') then
if FileExists(pOrigem) then
CopyFile(PChar(pOrigem), PChar(pDestino), True);
end;
class function TcARQUIVO.excluir(pArquivo : String): String;
var
vArq : String;
begin
Result := '';
while pArquivo <> '' do begin
vArq := getitem(pArquivo);
if vArq = '' then Break;
delitem(pArquivo);
if FileExists(vArq) then
DeleteFile(PChar(vArq));
end;
end;
class function TcARQUIVO.mover(pOrigem, pDestino : String): String;
begin
Result := '';
if (pOrigem <> '') and (pDestino <> '') then
if FileExists(pOrigem) then
MoveFile(PChar(pOrigem), PChar(pDestino));
end;
class function TcARQUIVO.listar(pParams : String) : String;
const
cMETHOD = 'TcARQUIVO.listar()';
var
vFiltro, vResult,
vLstArquivoDir, vLstArquivo,
vNaoListar, vExtArquivo, vDirOrigem, vExt : String;
vInSubPasta, vInSoArquivo, vInSoDiretorio : Boolean;
SR : TSearchRec;
R : Integer;
begin
Result := '';
vDirOrigem := itemX('DIR_ORIGEM', pParams);
vExtArquivo := itemX('EXT_ARQUIVO', pParams);
vNaoListar := itemX('NAO_LISTAR', pParams);
vInSubPasta := itemXB('IN_SUBPASTA', pParams);
vInSoArquivo := IfNullB(itemX('IN_SOARQUIVO', pParams), True);
vInSoDiretorio := itemXB('IN_SODIRETORIO', pParams);
vFiltro := IfNullS(itemX('DS_FILTRO', pParams), '*.*');
if vDirOrigem = '' then
raise Exception.Create('Diretório deve ser informado! / ' + cMETHOD);
vLstArquivoDir := '';
vLstArquivo := '';
R := FindFirst(vDirOrigem + vFiltro, faAnyFile, SR);
while R = 0 do begin
// arquivo
if ((SR.Attr and faDirectory) <> faDirectory) and not (vInSoArquivo) then begin
vExt := UpperCase(ExtractFileExt(SR.Name));
if (vExtArquivo = '') or (PosItem(vExt, vExtArquivo) > 0) then begin
if PosItem(SR.Name, vNaoListar) = 0 then begin
putitem(vLstArquivoDir, vDirOrigem + SR.Name);
putitem(vLstArquivo, SR.Name);
end;
end;
// diretorio
end else begin
if vInSoDiretorio then begin
putitem(vLstArquivoDir, vDirOrigem + SR.Name + '\');
putitem(vLstArquivo, SR.Name);
end;
if vInSubPasta then begin
if Pos(SR.Name, '.|..') = 0 then begin
putitemX(pParams, 'DIR_ORIGEM', vDirOrigem + SR.Name + '\');
vResult := listar(pParams);
if (itemX('LST_ARQUIVODIR', vResult) <> '') then begin
putitem(vLstArquivoDir, itemX('LST_ARQUIVODIR', vResult));
putitem(vLstArquivo, itemX('LST_ARQUIVO', vResult));
end;
end;
end;
end;
R := FindNext(SR);
end;
putitemX(Result, 'LST_ARQUIVODIR', vLstArquivoDir);
putitemX(Result, 'LST_ARQUIVO', vLstArquivo);
end;
//--
class function TcARQUIVO.dialog(pParams : String): String;
var
vDialog : TOpenDialog;
I : Integer;
begin
Result := '';
if itemB('IN_SALVAR', pParams) then begin
vDialog := TSaveDialog.Create(nil);
end else begin
vDialog := TOpenDialog.Create(nil);
end;
with vDialog do begin
Filter := item('DS_FIL', pParams);
DefaultExt := item('DS_EXT', pParams);
InitialDir := item('DS_DIR', pParams);
FileName := item('DS_ARQ', pParams);
if itemB('IN_MULTIPLE', pParams) then
Options := Options + [ofAllowMultiSelect];
if Execute then
if itemB('IN_MULTIPLE', pParams) then begin
for I:=0 to Files.Count-1 do begin
putitem(Result, Files[I]);
end;
end else
Result := FileName;
Free;
end;
end;
class function TcARQUIVO.dialogDir(pParams : String = ''): String;
begin
Result := TcDIRETORIO.dialog(pParams);
end;
class function TcARQUIVO.dialogMultiple(pParams : String): String;
begin
putitem(pParams, 'IN_MULTIPLE', True);
Result := dialog(pParams);
end;
class function TcARQUIVO.dialogSave(pParams : String): String;
begin
putitem(pParams, 'IN_SALVAR', True);
Result := dialog(pParams);
end;
//--
class function TcARQUIVO.ext(pParams : String): String;
begin
Result := ExtractFileName(Result);
Result := LowerCase(Result);
end;
//--
class function TcARQUIVO.arqTemp(pParams : String): String;
begin
Result := TcPATH.Temp() + 'temp.' + FormatDateTime('yyyymmdd.hh_nn_ss', Now) + pParams;
end;
//--
class function TcARQUIVO.DataDeCriacao(pArquivo : String; pTpDataDeCriacao : TpDataDeCriacao): TDateTime;
var
ffd: TWin32FindData;
dft: DWORD;
lft: TFileTime;
h: THandle;
begin
Result := 0;
h := Windows.FindFirstFile(PChar(pArquivo), ffd);
try
if (INVALID_HANDLE_VALUE <> h) then begin
if (pTpDataDeCriacao = tpcAcesso) then FileTimeToLocalFileTime(ffd.ftLastAccessTime, lft) // Acesso
else if (pTpDataDeCriacao = tpcCriacao) then FileTimeToLocalFileTime(ffd.ftCreationTime, lft) // Criacao
else FileTimeToLocalFileTime(ffd.ftLastWriteTime, lft); // Modificacao
FileTimeToDosDateTime(lft, LongRec(dft).Hi, LongRec(dft).Lo);
Result := FileDateToDateTime(dft);
end;
finally
Windows.FindClose(h);
end;
end;
//--
class function TcARQUIVO.CopyFileEx(const ASource, ADest: string; ARenameCheck: boolean = false): boolean;
//example
// CopyFileEx('C:\Windows\System32\drivers\aksclass.sys', 'C:\aksclass.sys');
//uses
// ShellApi;
var
sh: TSHFileOpStruct;
begin
sh.Wnd := Application.Handle;
sh.wFunc := FO_COPY;
// Terminated string must be to put the list end with # 0 # 0
sh.pFrom := PChar(ASource + #0);
sh.pTo := PChar(ADest + #0);
sh.fFlags := fof_Silent or fof_MultiDestFiles;
if ARenameCheck then sh.fFlags := sh.fFlags or fof_RenameOnCollision;
Result := ShFileOperation(sh) = 0;
end;
//--
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Atualização automática de executáveis.
The MIT License
Copyright: Copyright (C) 2012 Albert Eije
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:
alberteije@gmail.com
@author Albert Eije
@version 2.0
******************************************************************************* }
unit UAtualizaEXE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, JvProgressBar, ComCtrls, JvExComCtrls, IniFiles,
ShellApi, Biblioteca;
type
TFAtualizaEXE = class(TForm)
Panel1: TPanel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormActivate(Sender: TObject);
private
PathVenda: String;
{ Private declarations }
public
Tipo: Integer;
NomeArquivo: string;
{ Public declarations }
end;
var
FAtualizaEXE: TFAtualizaEXE;
implementation
uses UMenu, UDataModule;
{$R *.dfm}
procedure TFAtualizaEXE.FormActivate(Sender: TObject);
var
Ini: TIniFile;
ArquivoLocal, ArquivoRemoto: String;
Parametros, Programa: String;
DataArquivoLocal, DataArquivoRemoto: TDateTime;
begin
try
if FileExists(ExtractFilePath(Application.ExeName) + 'Conexao.ini') then
begin
Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'Conexao.ini');
ArquivoLocal := Application.ExeName;
ArquivoRemoto := Ini.ReadString('AtualizaVersao', 'RemotePath', '') + ExtractFileName(Application.ExeName);
end
else
Application.MessageBox('Arquivo de conexão não encontrado - entre em contato com a Software House.', 'Erro', MB_OK + MB_ICONERROR);
finally
Ini.Free;
end;
// Verifica se existe um arquivo no servidor
if not FileExists(ArquivoRemoto) then
begin
Application.CreateForm(TFMenu, FMenu);
Application.CreateForm(TFDataModule, FDataModule);
Close;
Exit;
end;
// Se o arquivo que está no servidor tiver o mesmo MD5, sai do procedimento
if MD5File(ArquivoLocal) = MD5File(ArquivoRemoto) then
begin
Application.CreateForm(TFMenu, FMenu);
Application.CreateForm(TFDataModule, FDataModule);
Close;
Exit;
end;
// Se a data do arquivo remoto for maior que a data do arquivo local, atualiza
DataArquivoLocal := FileDateToDateTime(FileAge(ArquivoLocal));
DataArquivoRemoto := FileDateToDateTime(FileAge(ArquivoRemoto));
if (DataArquivoRemoto > DataArquivoLocal) then
begin
Application.MessageBox('Existe uma nova versão deste módulo e o mesmo será atualizado. Aguarde.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
try
Repaint;
CopyFile(PChar(ArquivoRemoto), PChar(ArquivoLocal + 'Novo'), False);
Sleep(1000);
Parametros := ' "' + ArquivoLocal + '"';
Programa := 'C:\Documents and Settings\Eije\Desktop\T2Ti ERP\Fontes\ERP\Cliente\AtualizaVersao\T2TiAtualizaVersao.exe';
ShellExecute(Handle, 'open', PChar(Programa), PChar(Parametros), '', SW_HIDE);
Application.Terminate;
except
Application.MessageBox('Erro ao tentar executar o módulo.', 'Erro do Sistema', MB_OK + MB_ICONERROR);
end;
end
else
begin
Application.CreateForm(TFMenu, FMenu);
Application.CreateForm(TFDataModule, FDataModule);
Close;
Exit;
end;
end;
procedure TFAtualizaEXE.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
FAtualizaEXE := nil;
end;
end.
|
unit PersistencyDefs;
interface
uses
ShareTools,
SysUtils, Forms, Windows, Registry;
const
RegistryKey = '';
FORMLEFT_KEY = 'Left';
FORMTOP_KEY = 'Top';
FORMVISIBLE_KEY = 'Visible';
REPBASE_KEY = '\Recognized Enviromental Picture\DashBoard\';
procedure LoadFormPosition(KeyName : string; Frm : TForm);
procedure SaveFormPosition(KeyName : string; Frm : TForm);
function GetRegistryValue(KeyName, ValueName : string; DefValue : string): string; overload;
function GetRegistryValue(KeyName, ValueName : string; const DefValue : integer = 0): integer; overload;
procedure SaveRegistryValue(KeyName, ValueName, Value : string); overload;
procedure SaveRegistryValue(KeyName, ValueName : string; Value : integer); overload;
implementation
var
Registry: TRegistry;
function GetRegistryValue(KeyName, ValueName : string; DefValue : string): string;
begin
Registry.OpenKey(REPBASE_KEY + KeyName, False);
Result := Registry.ReadString(ValueName);
end;
function GetRegistryValue(KeyName, ValueName : string; const DefValue : integer = 0): integer; overload;
begin
Result := SafeStrToInt(GetRegistryValue(KeyName, ValueName, ''), DefValue);
end;
procedure SaveRegistryValue(KeyName, ValueName, Value : string);
begin
Registry.OpenKey(REPBASE_KEY + KeyName, true);
Registry.WriteString(ValueName, Value);
end;
procedure SaveRegistryValue(KeyName, ValueName : string; Value : integer);
begin
SaveRegistryValue(KeyName, ValueName, IntToStr(Value));
end;
procedure LoadFormPosition(KeyName : string; Frm : TForm);
begin
if Frm = nil then Exit;
Frm.Left := GetRegistryValue(KeyName, FORMLEFT_KEY, Frm.Left);
Frm.Top := GetRegistryValue(KeyName, FORMTOP_KEY, Frm.Top);
end;
procedure SaveFormPosition(KeyName : string; Frm : TForm);
begin
if Frm = nil then Exit;
SaveRegistryValue(KeyName, FORMLEFT_KEY, Frm.Left);
SaveRegistryValue(KeyName, FORMTOP_KEY, Frm.Top);
end;
initialization
Registry := TRegistry.Create(KEY_ALL_ACCESS);
Registry.RootKey := HKEY_CURRENT_USER;
finalization
Registry.Free;
end.
|
unit Model.Components.Query.FireDac;
interface
uses Model.Components.Query.Interfaces,
Model.Components.Connection.FireDac,
Data.DB,
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.MySQL,
FireDAC.Phys.MySQLDef,
FireDAC.VCLUI.Wait,
FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.DApt.Intf,
FireDAC.DApt,
FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
FireDAC.FMXUI.Wait,
FireDAC.Comp.UI;
type
TModelComponentsQueryFireDac = class(TInterfacedObject,IModelComponentsQueryInterfaces)
private
FQuery:TFDQuery;
public
constructor Create;
destructor Destroy;override;
class function New: IModelComponentsQueryInterfaces;
function Active : Boolean;
function Close : IModelComponentsQueryInterfaces;
function ExecSQL : IModelComponentsQueryInterfaces;
function DataSet : TDataSet;
function Open : IModelComponentsQueryInterfaces;
function ParamByName(aParam:string;aValue:Variant): IModelComponentsQueryInterfaces;
function FiledByName(aField:string):Variant;
function SQLAdd(aSQL:string) : IModelComponentsQueryInterfaces;
function SQLClear : IModelComponentsQueryInterfaces;
end;
implementation
{ TModelComponentsQueryFireDac }
function TModelComponentsQueryFireDac.Active: Boolean;
begin
Result := FQuery.Active;
end;
function TModelComponentsQueryFireDac.Close: IModelComponentsQueryInterfaces;
begin
Result := Self;
FQuery.Close;
end;
constructor TModelComponentsQueryFireDac.Create;
begin
FQuery := TFDQuery.Create(nil);
FQuery.Connection := TModelComponentsConnectionFiredac.Connection;
end;
function TModelComponentsQueryFireDac.DataSet: TDataSet;
begin
Result := FQuery;
end;
destructor TModelComponentsQueryFireDac.Destroy;
begin
FQuery.Free;
inherited;
end;
function TModelComponentsQueryFireDac.ExecSQL: IModelComponentsQueryInterfaces;
begin
Result := Self;
FQuery.ExecSQL;
end;
function TModelComponentsQueryFireDac.FiledByName(aField: string): Variant;
begin
Result := FQuery.FieldByName(aField).Value;
end;
class function TModelComponentsQueryFireDac.New: IModelComponentsQueryInterfaces;
begin
Result := Self.Create;
end;
function TModelComponentsQueryFireDac.Open: IModelComponentsQueryInterfaces;
begin
Result := Self;
FQuery.Open()
end;
function TModelComponentsQueryFireDac.ParamByName(aParam: string; aValue: Variant): IModelComponentsQueryInterfaces;
begin
Result := Self;
FQuery.ParamByName(aParam).Value := aValue;
end;
function TModelComponentsQueryFireDac.SQLAdd(aSQL: string): IModelComponentsQueryInterfaces;
begin
Result := Self;
FQuery.SQL.Add(aSQL);
end;
function TModelComponentsQueryFireDac.SQLClear: IModelComponentsQueryInterfaces;
begin
Result := Self;
FQuery.SQL.Clear;
end;
end.
|
unit GamePlayer;
interface
uses
AvL, avlUtils, avlVectors, GameUnit;
type
TPlayer=class(TObject)
private
FUnits: array of TUnit;
function GetUnitsCount: Integer;
function GetUnit(Index: Integer): TUnit;
public
constructor Create(UnitsCount: Integer);
destructor Destroy; override;
procedure Draw;
procedure Update;
property UnitsCount: Integer read GetUnitsCount;
property Units[Index: Integer]: TUnit read GetUnit;
end;
implementation
constructor TPlayer.Create(UnitsCount: Integer);
var
i: Integer;
begin
inherited Create;
SetLength(FUnits, UnitsCount);
for i:=0 to High(FUnits) do
begin
FUnits[i]:=TUnit.Create;
FUnits[i].Pos:=Vector3D(280, 0, 268+i*8);
end;
end;
destructor TPlayer.Destroy;
var
i: Integer;
begin
for i:=0 to High(FUnits) do
FUnits[i].Free;
Finalize(FUnits);
inherited Destroy;
end;
procedure TPlayer.Draw;
var
i: Integer;
begin
for i:=0 to High(FUnits) do
FUnits[i].Draw;
end;
procedure TPlayer.Update;
var
i: Integer;
begin
for i:=0 to High(FUnits) do
FUnits[i].Update;
end;
function TPlayer.GetUnitsCount: Integer;
begin
Result:=Length(FUnits);
end;
function TPlayer.GetUnit(Index: Integer): TUnit;
begin
if (Index>=Low(FUnits)) and (Index<=High(FUnits))
then Result:=FUnits[Index]
else Result:=nil;
end;
end.
|
//
// hook1 is basic driver with unload support, logs every action too DebugView
// enjoy your first lesson
//
unit hook1;
interface
//
// the most important unit is DDDK which source is in inc directory
// it contains everything we need to work with kernel functions
//
uses DDDK;
const
DeviceName='\Device\hook1';
DosDeviceName='\DosDevices\hook1';
//
// this is the must, when one say you can name your driver entry with your name
// in DDK, you have to leave _DriverEntry name of entry in DDDK unless you know
// what you are dealing with
//
function _DriverEntry(ADriverObject:PDriverObject;ARegistryPath:PUnicodeString):NTSTATUS; stdcall;
function Hook1Create(ADeviceObject:PDeviceObject;AIrp:PIrp):NTSTATUS; stdcall;
function Hook1Close(ADeviceObject:PDeviceObject;AIrp:PIrp):NTSTATUS; stdcall;
function Hook1DeviceControl(ADeviceObject:PDeviceObject;AIrp:PIrp):NTSTATUS; stdcall;
procedure Hook1Unload(ADriverObject:PDriverObject); stdcall;
implementation
var
// dos device name is global variable because we use it in unload too,
// we can always make another RtlInitUnicodeString if we don't like global vars
DosDevName:TUnicodeString;
//
// create function is called everytime CreateFile is called on our device
//
function Hook1Create(ADeviceObject:PDeviceObject;AIrp:PIrp):NTSTATUS; stdcall;
begin
DbgMsg('hook1.pas: Hook1Create(ADeviceObject:0x%.8X,AIrp:0x%.8X)',[ADeviceObject,AIrp]);
Result:=STATUS_SUCCESS;
AIrp^.IoStatus.Status:=Result;
IoCompleteRequest(AIrp,IO_NO_INCREMENT);
DbgMsg('hook1.pas: Hook1Create(-):0x%.8X)',[Result]);
end;
//
// close function is called everytime CloseHandle is called on our device
// close is associated with IRP_MJ_CLOSE and it is NOT executed in the context
// of the CloseHandle caller, if we want to make some cleanup in that context
// we rather associate cleanup function with IRP_MJ_CLEANUP
//
function Hook1Close(ADeviceObject:PDeviceObject;AIrp:PIrp):NTSTATUS; stdcall;
begin
DbgMsg('hook1.pas: Hook1Close(ADeviceObject:0x%.8X,AIrp:0x%.8X)',[ADeviceObject,AIrp]);
Result:=STATUS_SUCCESS;
AIrp^.IoStatus.Status:=Result;
IoCompleteRequest(AIrp,IO_NO_INCREMENT);
DbgMsg('hook1.pas: Hook1Close(-):0x%.8X)',[Result]);
end;
//
// device control function is called everytime DeviceIoControl is called on our
// device, it is common way how user mode app communicate with driver
//
function Hook1DeviceControl(ADeviceObject:PDeviceObject;AIrp:PIrp):NTSTATUS; stdcall;
begin
DbgMsg('hook1.pas: Hook1DeviceControl(ADeviceObject:0x%.8X,AIrp:0x%.8X)',[ADeviceObject,AIrp]);
Result:=STATUS_SUCCESS;
AIrp^.IoStatus.Status:=Result;
IoCompleteRequest(AIrp,IO_NO_INCREMENT);
DbgMsg('hook1.pas: Hook1DeviceControl(-):0x%.8X)',[Result]);
end;
//
// unload is called when driver is being unloaded, if we do not implement unload
// function them our driver can't be unloaded dynamically
//
procedure Hook1Unload(ADriverObject:PDriverObject); stdcall;
begin
DbgMsg('hook1.pas: Hook1Unload(ADriverObject:0x%.8X)',[ADriverObject]);
//cleanup everything our driver created - delete symlink and device
IoDeleteSymbolicLink(@DosDevName);
IoDeleteDevice(ADriverObject^.DeviceObject);
DbgMsg('hook1.pas: Hook1Unload(-)',[]);
end;
//
// DriverEntry is common driver entry point
//
function _DriverEntry(ADriverObject:PDriverObject;ARegistryPath:PUnicodeString):NTSTATUS; stdcall;
var
LDevName:TUnicodeString;
LDevObj:PDeviceObject;
begin
DbgMsg('hook1.pas: DriverEntry(ADriverObject:0x%.8X;ARegistryPath:0x%.8X)',[ADriverObject,ARegistryPath]);
RtlInitUnicodeString(@LDevName,DeviceName);
RtlInitUnicodeString(@DosDevName,DosDeviceName);
//
// if we want our driver to be accessible we need to create device for it,
// one driver can have more devices
//
Result:=IoCreateDevice(ADriverObject,0,@LDevName,FILE_DEVICE_UNKNOWN,FILE_DEVICE_SECURE_OPEN,FALSE,LDevObj);
if NT_SUCCESS(Result) then
begin
//
// for some selected major functions we set handlers
//
ADriverObject^.MajorFunction[IRP_MJ_CREATE] := @Hook1Create;
ADriverObject^.MajorFunction[IRP_MJ_CLOSE] := @Hook1Close;
ADriverObject^.MajorFunction[IRP_MJ_DEVICE_CONTROL] := @Hook1DeviceControl;
ADriverObject^.DriverUnload := @Hook1Unload;
//
// this selects the method of IO, we use buffered IO as it is comfortable
// and effective for smaller packets
//
LDevObj^.Flags:=LDevObj^.Flags or DO_BUFFERED_IO;
//
// if we want user mode application to communicate our driver we need to make
// a dos device link
//
Result:=IoCreateSymbolicLink(@DosDevName,@LDevName);
if not NT_SUCCESS(Result) then
begin
DbgMsg('hook1.pas: DriverEntry.IoCreateSymbolicLink failed with status 0x%.8X',[Result]);
IoDeleteDevice(ADriverObject^.DeviceObject);
end;
end else DbgMsg('hook1.pas: DriverEntry.IoCreateDevice failed with status 0x%.8X',[Result]);
DbgMsg('hook1.pas: DriverEntry(-):0x%.8X',[Result]);
end;
end.
|
unit VisibleDSA.AlgoVisualizer;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Graphics,
Forms,
BGRACanvas2D,
VisibleDSA.AlgoVisHelper,
VisibleDSA.MazeData;
type
TAlgoVisualizer = class(TObject)
const
D: TArr2D_int = ((-1, 0), (0, 1), (1, 0), (0, -1));
private
_width: integer;
_height: integer;
_data: TMazeData;
_form: TForm;
procedure __setData(x, y: integer);
public
constructor Create(form: TForm);
destructor Destroy; override;
procedure Paint(canvas: TBGRACanvas2D);
procedure Run;
end;
implementation
uses
VisibleDSA.AlgoForm;
{ TAlgoVisualizer }
constructor TAlgoVisualizer.Create(form: TForm);
var
blockSide: integer;
begin
blockSide := 6;
_data := TMazeData.Create(TMazeData.FILE_NAME);
_form := form;
_form.ClientWidth := blockSide * _data.M;
_form.ClientHeight := blockSide * _data.N;
_width := _form.ClientWidth;
_height := _form.ClientHeight;
_form.Caption := 'Maze solver visualization';
end;
destructor TAlgoVisualizer.Destroy;
begin
FreeAndNil(_data);
inherited Destroy;
end;
procedure TAlgoVisualizer.Paint(canvas: TBGRACanvas2D);
var
w, h: integer;
i, j: integer;
begin
w := _width div _data.N;
h := _height div _data.M;
for i := 0 to _data.N - 1 do
begin
for j := 0 to _data.M - 1 do
begin
if _data.GetMaze(i, j) = TMazeData.WALL then
TAlgoVisHelper.SetFill(CL_LIGHTBLUE)
else
TAlgoVisHelper.SetFill(CL_WHITE);
if _data.Path[i, j] then
TAlgoVisHelper.SetFill(CL_YELLOW);
TAlgoVisHelper.FillRectangle(canvas, j * w, i * h, h, w);
end;
end;
end;
procedure TAlgoVisualizer.Run;
procedure __go__(x, y: integer);
var
i, newX, newY: integer;
begin
if not _data.InArea(x, y) then
raise Exception.Create('X, Y are out of index in go function!');
_data.Visited[x, y] := True;
__setData(x, y);
if (x = _data.ExitX) and (y = _data.ExitY) then
Exit;
for i := 0 to High(D) do
begin
newX := x + D[i, 0];
newY := y + D[i, 1];
if (_data.InArea(newX, newY)) and
(_data.GetMaze(newX, newY) = TMazeData.ROAD) and
(_data.Visited[newX, newY] = False) then
begin
__go__(newX, newY);
end;
end;
end;
begin
__setData(-1, -1);
__go__(_data.EntranceX, _data.EntranceY);
__setData(-1, -1);
end;
procedure TAlgoVisualizer.__setData(x, y: integer);
begin
if _data.InArea(x, y) then
_data.Path[x, y] := True;
TAlgoVisHelper.Pause(0);
AlgoForm.BGRAVirtualScreen.RedrawBitmap;
end;
end.
|
{==============================================================================|
| MicroCoin |
| Copyright (c) 2017-2018 MicroCoin Developers |
|==============================================================================|
| 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 opies 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. |
|==============================================================================|
| File: MicroCoin.Forms.Transaction.CreateSubAccount.pas |
| Created at: 2018-09-25 |
| Purpose: Dialog for create subaccount |
|==============================================================================}
unit MicroCoin.Forms.Transaction.CreateSubAccount;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, PngBitBtn,
MicroCoin.Common,
PngSpeedButton, Vcl.ExtCtrls;
type
TCreateSubaccountForm = class(TForm)
edInitialBalance: TEdit;
Label1: TLabel;
Label2: TLabel;
edBalanceLimit: TEdit;
edDailyLimit: TEdit;
Label3: TLabel;
edPublicKey: TLabeledEdit;
PngBitBtn1: TPngBitBtn;
PngBitBtn2: TPngBitBtn;
procedure edInitialBalanceKeyPress(Sender: TObject; var Key: Char);
private
function GetBalanceLimit: Int64;
function GetDailyLimit: Int64;
function GetInitialBalance: UInt64;
function GetPublicKey: string;
{ Private declarations }
public
property InitialBalance : UInt64 read GetInitialBalance;
property BalanceLimit : Int64 read GetBalanceLimit;
property DailyLimit : Int64 read GetDailyLimit;
property PublicKey : string read GetPublicKey;
end;
var
CreateSubaccountForm: TCreateSubaccountForm;
implementation
{$R *.dfm}
procedure TCreateSubaccountForm.edInitialBalanceKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['0'..'9', '.', ','])
then Key := #0;
end;
function TCreateSubaccountForm.GetBalanceLimit: Int64;
begin
TCurrencyUtils.ParseValue(edBalanceLimit.Text, Result);
end;
function TCreateSubaccountForm.GetDailyLimit: Int64;
begin
TCurrencyUtils.ParseValue(edDailyLimit.Text, Result);
end;
function TCreateSubaccountForm.GetInitialBalance: UInt64;
var
xBal : Int64;
begin
TCurrencyUtils.ParseValue(edInitialBalance.Text, xBal);
Result := xBal;
end;
function TCreateSubaccountForm.GetPublicKey: string;
begin
Result := edPublicKey.Text;
end;
end.
|
unit FHIR.Support.Graphics;
{
Copyright (c) 2010+, Kestral Computing Pty Ltd (http://www.kestral.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
Windows,
SysUtils, Classes, Vcl.Graphics, Types,
GraphicEx, Jpeg, PNGImage,
FHIR.Support.Base, FHIR.Support.Utilities, FHIR.Support.Stream, FHIR.Support.Collections, FHIR.Support.Shell;
Type
TRect = Windows.TRect;
TPoint = Windows.TPoint;
Function Rect(iLeft, iTop, iRight, iBottom : Integer) : TRect; Overload;
Procedure RectZero(Var aRect : TRect); Overload;
Function RectZero : TRect; Overload;
Function RectEmpty(Const aRect : TRect) : Boolean; Overload;
Function RectEqual(Const A, B : TRect) : Boolean; Overload;
Function RectOffset(Const aRect : TRect; iX, iY : Integer) : TRect; Overload;
Function RectIntersect(Const A, B : TRect) : TRect; Overload;
Function RectSubtract(Const A, B : TRect) : TRect; Overload;
Function RectUnion(Const A, B : TRect) : TRect; Overload;
Function RectHasIntersection(Const A, B : TRect) : Boolean; Overload;
Function RectInflate(Const aRect : TRect; iValue : Integer) : TRect; Overload;
Function RectInflate(Const aRect : TRect; iX, iY : Integer) : TRect; Overload;
Function RectWidth(Const aRect : TRect) : Integer; Overload;
Function RectHeight(Const aRect : TRect) : Integer; Overload;
Function RectHit(Const aRect : TRect; Const aPoint : TPoint) : Boolean; Overload;
Function RectBound(Const aRect, aBoundary : TRect) : TRect; Overload;
Type
TFslResourceType = (rtAccelerator, rtAniCursor, rtAniIcon, rtBitmap, rtCursor, rtDialog, rtFont, rtFontDir,
rtGroupCursor, rtGroupIcon, rtIcon, rtMenu, rtMessageTable, rtRCData, rtString, rtVersion);
TFslResourceStream = Class(TFslMemoryStream)
Private
FFilename : String;
FResourceName : String;
FResourceType : TFslResourceType;
FResourceHandle : THandle;
FResourceData : Pointer;
Protected
Function ToWindowsResourceType(oResourceType : TFslResourceType) : PChar;
Public
Constructor Create; Override;
Procedure BeforeDestruction; Override;
Function Link : TFslResourceStream;
Procedure Open;
Procedure Close;
Function Active : Boolean;
Function ExistsAcceleratorTable : Boolean;
Function ExistsAnimatedCursor : Boolean;
Function ExistsAnimatedIcon : Boolean;
Function ExistsBitmap : Boolean;
Function ExistsHardwareDependentCursor : Boolean;
Function ExistsDialogBox : Boolean;
Function ExistsFont : Boolean;
Function ExistsFontDirectory : Boolean;
Function ExistsHardwareIndependentCursor : Boolean;
Function ExistsHardwareIndependentIcon : Boolean;
Function ExistsHardwareDependentIcon : Boolean;
Function ExistsMenu : Boolean;
Function ExistsMessageTableEntry : Boolean;
Function ExistsApplicationDefined : Boolean;
Function ExistsStringTableEntry : Boolean;
Function ExistsVersion : Boolean;
Function ExistsByResourceType(Const aResourceType : TFslResourceType) : Boolean;
Procedure ResourceTypeAcceleratorTable;
Procedure ResourceTypeAnimatedCursor;
Procedure ResourceTypeAnimatedIcon;
Procedure ResourceTypeBitmap;
Procedure ResourceTypeHardwareDependentCursor;
Procedure ResourceTypeDialogBox;
Procedure ResourceTypeFont;
Procedure ResourceTypeFontDirectory;
Procedure ResourceTypeHardwareIndependentCursor;
Procedure ResourceTypeHardwareIndependentIcon;
Procedure ResourceTypeHardwareDependentIcon;
Procedure ResourceTypeMenu;
Procedure ResourceTypeMessageTableEntry;
Procedure ResourceTypeApplicationDefined;
Procedure ResourceTypeStringTableEntry;
Procedure ResourceTypeVersion;
Function IsResourceTypeAcceleratorTable : Boolean;
Function IsResourceTypeAnimatedCursor : Boolean;
Function IsResourceTypeAnimatedIcon : Boolean;
Function IsResourceTypeBitmap : Boolean;
Function IsResourceTypeHardwareDependentCursor : Boolean;
Function IsResourceTypeDialogBox : Boolean;
Function IsResourceTypeFont : Boolean;
Function IsResourceTypeFontDirectory : Boolean;
Function IsResourceTypeHardwareIndependentCursor : Boolean;
Function IsResourceTypeHardwareIndependentIcon : Boolean;
Function IsResourceTypeHardwareDependentIcon : Boolean;
Function IsResourceTypeMenu : Boolean;
Function IsResourceTypeMessageTableEntry : Boolean;
Function IsResourceTypeApplicationDefined : Boolean;
Function IsResourceTypeStringTableEntry : Boolean;
Function IsResourceTypeVersion : Boolean;
Property Filename : String Read FFilename Write FFilename;
Property ResourceName : String Read FResourceName Write FResourceName;
Property ResourceType : TFslResourceType Read FResourceType Write FResourceType;
End;
TFslVCLGraphic = class;
TFslGraphic = Class(TFslObject)
Protected
Function GetWidth: Integer; Virtual;
Procedure SetWidth(Const Value: Integer); Virtual;
Function GetHeight: Integer; Virtual;
Procedure SetHeight(Const Value: Integer); Virtual;
function GetFrameIndex: Integer; Virtual;
procedure SetFrameIndex(const Value: Integer); Virtual;
Public
Function Link : TFslGraphic;
Function Clone : TFslGraphic;
Procedure LoadFromStream(oStream : TFslStream); Virtual;
Procedure SaveToStream(oStream : TFslStream); Virtual;
Procedure LoadFromFile(Const sFilename : String); Virtual;
Procedure SaveToFile(Const sFilename : String); Virtual;
procedure DrawToStream(oStream : TFslStream; width, height : Integer); Virtual;
// information about the graphic
Function TypeName : String; Virtual;
Function Extension : String; Virtual;
Function FrameCount : Integer; Virtual;
// drawing routines
procedure StretchDraw(oCanvas : TCanvas; aRect : TRect); virtual; // draw to a canvas
function AsBitmap : TFslVCLGraphic; virtual; // get a bitmap representation
Property Width : Integer Read GetWidth Write SetWidth;
Property Height : Integer Read GetHeight Write SetHeight;
Property FrameIndex : Integer Read GetFrameIndex write SetFrameIndex;
End;
TFslGraphicList = Class(TFslObjectList)
Private
Function GetGraphic(iIndex: Integer): TFslGraphic;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Graphics[iIndex : Integer] : TFslGraphic Read GetGraphic; Default;
End;
TFslVCLGraphic = Class(TFslGraphic)
Private
FHandle : TGraphic;
FBuffer : TFslBuffer;
Function GetHandle: TGraphic;
Procedure SetHandle(Const Value: TGraphic);
Function GetTransparent: Boolean;
Procedure SetTransparent(Const Value: Boolean);
Protected
Function GetWidth: Integer; Override;
Procedure SetWidth(Const Value: Integer); Override;
Function GetHeight: Integer; Override;
Procedure SetHeight(Const Value: Integer); Override;
Function HandleNew : TGraphic; Virtual;
Function HandleClass : TGraphicClass; Virtual;
Public
Constructor Create; Override;
Destructor Destroy; Override;
Function Link : TFslVCLGraphic;
Function Clone : TFslVCLGraphic;
Procedure Assign(oObject : TFslObject); Override;
Procedure LoadFromStream(oStream : TFslStream); Override;
Procedure SaveToStream(oStream : TFslStream); Override;
procedure DrawToStream(oStream : TFslStream; width, height : Integer); Override;
Procedure LoadFromFile(Const sFilename : String); Override;
Procedure SaveToFile(Const sFilename : String); Override;
Class Function NewFromGraphic(const oGraphic : TGraphic) : TFslVCLGraphic;
Procedure LoadFromGraphic(Const oGraphic : TGraphic);
Function HasHandle : Boolean; Virtual;
Function Empty : Boolean; Virtual;
procedure StretchDraw(oCanvas : TCanvas; aRect : TRect); Override;
Property Handle : TGraphic Read GetHandle Write SetHandle;
Property Transparent : Boolean Read GetTransparent Write SetTransparent;
End;
TFslVCLGraphicList = Class(TFslGraphicList)
Private
Function GetGraphic(iIndex: Integer): TFslVCLGraphic;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property VCLGraphics[iIndex : Integer] : TFslVCLGraphic Read GetGraphic; Default;
End;
TGraphic = Vcl.Graphics.TGraphic;
TGraphicClass = Vcl.Graphics.TGraphicClass;
Type
TFslTIFFGraphic = Class(TFslVCLGraphic)
Private
Function GetHandle: TTIFFGraphic;
Procedure SetHandle(Const Value: TTIFFGraphic);
Protected
Function HandleClass : TGraphicClass; Override;
Function HandleNew : TGraphic; Override;
Public
Function Link : TFslTIFFGraphic;
Function Clone : TFslTIFFGraphic;
Procedure LoadFromResource(Const sResource : String);
Property Handle : TTIFFGraphic Read GetHandle Write SetHandle;
End;
TTIFFGraphic = GraphicEx.TTIFFGraphic;
TFslPortableNetworkGraphic = Class(TFslVCLGraphic)
Private
Function GetHandle: TPNGGraphic;
Procedure SetHandle(Const Value: TPNGGraphic);
Protected
Function HandleClass : TGraphicClass; Override;
Function HandleNew : TGraphic; Override;
Public
Function Link : TFslPortableNetworkGraphic;
Function Clone : TFslPortableNetworkGraphic;
Procedure LoadFromResource(Const sResource : String);
Property Handle : TPNGGraphic Read GetHandle Write SetHandle;
End;
TPNGGraphic = GraphicEx.TPNGGraphic;
TFslGIFGraphic = Class(TFslVCLGraphic)
Private
Function GetHandle: TGIFGraphic;
Procedure SetHandle(Const Value: TGIFGraphic);
Protected
Function HandleClass : TGraphicClass; Override;
Function HandleNew : TGraphic; Override;
Public
Function Link : TFslGIFGraphic;
Function Clone : TFslGIFGraphic;
Procedure LoadFromResource(Const sResource : String);
Property Handle : TGIFGraphic Read GetHandle Write SetHandle;
End;
TGIFGraphic = GraphicEx.TGIFGraphic;
TFslBitmapGraphic = Class(TFslVCLGraphic)
Private
Function GetHandle: TBitmap;
Procedure SetHandle(Const Value: TBitmap);
Protected
Function HandleClass : TGraphicClass; Override;
Function HandleNew : TGraphic; Override;
Function BytesPerLine : Integer;
Public
Function Link : TFslBitmapGraphic;
Function Clone : TFslBitmapGraphic;
Procedure LoadFromResource(Const sResource : String);
Function ConstructRotate(Const AngleOfRotation : Double): TBitmap;
Function ConstructFitToPage(Const iWidth, iHeight : Integer): TFslBitmapGraphic;
Class Function CanLoad(oStream : TStream) : Boolean;
Property Handle : TBitmap Read GetHandle Write SetHandle;
End;
TFslBitmapGraphicList = Class(TFslVCLGraphicList)
Private
Function GetBitmapGraphicByIndex(iIndex: Integer): TFslBitmapGraphic;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property BitmapGraphicByIndex[iIndex : Integer] : TFslBitmapGraphic Read GetBitmapGraphicByIndex; Default;
End;
TBitmap = Vcl.Graphics.TBitmap;
TFslJpegGraphic = Class(TFslVCLGraphic)
Private
Function GetHandle: TJpegImage;
Procedure SetHandle(Const Value: TJpegImage);
Function GetQuality: Integer;
Procedure SetQuality(Const Value: Integer);
Function GetGrayScale: Boolean;
Procedure SetGrayScale(Const Value: Boolean);
Protected
Function HandleClass : TGraphicClass; Override;
Function HandleNew : TGraphic; Override;
Public
Function Link : TFslJpegGraphic;
Function Clone : TFslJpegGraphic;
Function AsBitmap : TFslBitmapGraphic; Reintroduce;
Procedure Compress;
Property Handle : TJpegImage Read GetHandle Write SetHandle;
Property Quality : Integer Read GetQuality Write SetQuality;
Property GrayScale : Boolean Read GetGrayScale Write SetGrayScale;
End;
TJpegImage = Jpeg.TJpegImage;
TFslGraphicMetre = Integer; // 10ths of a millimetre
TFslGraphicMetreRect = TRect;
TFslGraphicHandle = THandle;
TFslGraphicCapability = Class(TFslObject)
Private
FHandle : TFslGraphicHandle;
FPixelsPerInchY : Integer;
FPixelsPerInchX : Integer;
FPixelsPerGraphicMetre : Real;
Protected
Property Handle : TFslGraphicHandle Read FHandle Write FHandle;
Public
Function ToPixel(iValue : TFslGraphicMetre) : Integer; Overload; Virtual;
Function FromPixel(iValue : Integer) : TFslGraphicMetre; Overload; Virtual;
Property PixelsPerGraphicMetre : Real Read FPixelsPerGraphicMetre Write FPixelsPerGraphicMetre;
Property PixelsPerInchX : Integer Read FPixelsPerInchX Write FPixelsPerInchX;
Property PixelsPerInchY : Integer Read FPixelsPerInchY Write FPixelsPerInchY;
End;
TFslGraphicAngle = Word; // 0..360;
TFslGraphicColour = TColour;
TFslGraphicObject = Class (TFslObject)
Private
FHandle : HGDIOBJ;
FOnChange : TNotifyEvent;
FCapability : TFslGraphicCapability;
Function GetHandle : TFslGraphicHandle;
Protected
Function CreateHandle : TFslGraphicHandle; Overload; Virtual;
Procedure Change; Overload; Virtual;
Public
Destructor Destroy; Override;
Procedure AfterConstruction; Override;
Procedure Clear; Overload; Virtual;
Procedure ClearHandle; Overload; Virtual;
Property Handle : TFslGraphicHandle Read GetHandle;
Property Capability : TFslGraphicCapability Read FCapability Write FCapability;
Property OnChange : TNotifyEvent read FOnChange write FOnChange;
End;
TFslPenStyle = (apsSolid, apsDash, apsDashDot, apsDashDotDot, apsDot, apsInsideFrame, apsNone);
TFslPenEndStyle = (apesSquare, apesFlat, apesRound);
TFslPenJoinStyle = (apjsMitre, apjsBevel, apjsRound);
TFslPenWidth = Integer;
TFslPen = Class (TFslGraphicObject)
Private
FWidth : TFslPenWidth;
FColour : TFslGraphicColour;
FEndStyle : TFslPenEndStyle;
FJoinStyle : TFslPenJoinStyle;
FStyle : TFslPenStyle;
Procedure SetColour(Const Value: TFslGraphicColour);
Procedure SetStyle(Const Value: TFslPenStyle);
Procedure SetEndStyle(Const Value: TFslPenEndStyle);
Procedure SetJoinStyle(Const Value: TFslPenJoinStyle);
Procedure SetWidth(Const Value: Integer);
Function GetStyleAsString: String;
Procedure SetStyleAsString(Const Value: String);
Protected
Function CreateHandle : TFslGraphicHandle; Override;
Public
Procedure AfterConstruction; Override;
Function Link : TFslPen;
Function Clone : TFslPen;
Procedure Assign(oObject : TFslObject); Override;
Procedure Clear; Override;
Procedure SetStyleSolid;
Procedure SetStyleDash;
Procedure SetStyleDot;
Procedure SetStyleNone;
Property Width : TFslPenWidth Read FWidth Write SetWidth;
Property Colour : TFslGraphicColour Read FColour Write SetColour;
Property Style : TFslPenStyle Read FStyle Write SetStyle;
Property EndStyle : TFslPenEndStyle Read FEndStyle Write SetEndStyle;
Property JoinStyle : TFslPenJoinStyle Read FJoinStyle Write SetJoinStyle;
Property StyleAsString : String Read GetStyleAsString Write SetStyleAsString;
End;
Const
ADVPENSTYLE_CODES : Array [TFslPenStyle] Of String = ('Solid', 'Dash', 'DashDot', 'DashDotDot', 'Dot', 'InsideFrame', 'None');
ADVPENSTYLE_NAMES : Array [TFslPenStyle] Of String = ('Solid', 'Dash', 'Dash Dot', 'Dash Dot Dot', 'Dot', 'Inside Frame', 'None');
ADVPENSTYLE_VALUES : Array [TFslPenStyle] Of Cardinal = (PS_SOLID, PS_DASH, PS_DASHDOT, PS_DASHDOTDOT, PS_DOT, PS_INSIDEFRAME, PS_NULL);
ADVPENENDSTYLE_CODES : Array [TFslPenEndStyle] Of String = ('Square', 'Flat', 'Round');
ADVPENENDSTYLE_VALUES : Array [TFslPenEndStyle] Of Cardinal = (PS_ENDCAP_SQUARE, PS_ENDCAP_FLAT, PS_ENDCAP_ROUND);
ADVPENJOINSTYLE_CODES : Array [TFslPenJoinStyle] Of String = ('Mitre', 'Bevel', 'Round');
ADVPENJOINSTYLE_VALUES : Array [TFslPenJoinStyle] Of DWord = (PS_JOIN_MITER, PS_JOIN_BEVEL, PS_JOIN_ROUND);
ADVPENSTYLE_VCLVALUES : Array [TFslPenStyle] Of TPenStyle = (psSolid, psDash, psDashDot, psDashDotDot, psDot, psInsideFrame, psClear);
Type
TFslBrushStyle = (absSolid, absNull, absHorizontal, absVertical, absFDiagonal, absBDiagonal, absCross, absDiagCross);
TFslBrush = Class(TFslGraphicObject)
Private
FBitmap : TFslBitmapGraphic;
FColour : TColour;
FStyle : TFslBrushStyle;
Function GetBitmap: TFslBitmapGraphic;
Procedure SetBitmap(Const Value: TFslBitmapGraphic);
Procedure SetColour(Const Value: TColour);
Procedure SetStyle(Const Value: TFslBrushStyle);
Function GetStyleAsString: String;
Procedure SetStyleAsString(Const Value: String);
Protected
Function CreateHandle : TFslGraphicHandle; Override;
Public
Constructor Create; Override;
Destructor Destroy; Override;
Function Link : TFslBrush;
Function Clone : TFslBrush;
Procedure Assign(oObject : TFslObject); Override;
Procedure Clear; Override;
Procedure SetStyleSolid;
Procedure SetStyleClear;
Function HasBitmap : Boolean;
// either a bitmap, or a colour and a style
Property Bitmap : TFslBitmapGraphic Read GetBitmap Write SetBitmap;
Property Colour : TColour Read FColour Write SetColour;
Property Style : TFslBrushStyle Read FStyle Write SetStyle;
Property StyleAsString : String Read GetStyleAsString Write SetStyleAsString;
End;
Const
ADVBRUSHSTYLE_CODES : Array [TFslBrushStyle] Of String =
('Solid', 'Clear', 'Horizontal', 'Vertical', 'FDiagonal', 'BDiagonal', 'Cross', 'DiagCross');
ADVBRUSHSTYLE_NAMES : Array [TFslBrushStyle] Of String =
('Solid', 'Clear', 'Horizontal', 'Vertical', 'Forward Diagonal', 'Backward Diagonal', 'Cross', 'Diagonal Cross');
ADVBRUSHSTYLE_VALUES : Array [TFslBrushStyle] Of Cardinal =
(BS_SOLID, BS_NULL, BS_HATCHED, BS_HATCHED, BS_HATCHED, BS_HATCHED, BS_HATCHED, BS_HATCHED);
ADVBRUSHSTYLE_HASHVALUES : Array [TFslBrushStyle] Of Cardinal =
(0, 0, HS_HORIZONTAL,HS_VERTICAL, HS_FDIAGONAL, HS_BDIAGONAL, HS_CROSS, HS_DIAGCROSS);
Type
TFslFontWeight = (afwUnknown, afwThin, afwExtraLight, afwLight, afwNormal, afwMedium, afwSemiBold, afwBold, afwExtraBold, afwHeavy);
TFslFontFamily = (affDontCare, affDecorative, affModern, affRoman, affScript, affSwiss);
TFslFontPitch = (afpDontCare, afpFixed, afpVariable);
TFslFontSize = Word;
TFslFont = Class (TFslGraphicObject)
Private
FItalic : Boolean;
FUnderline : Boolean;
FStrikeOut : Boolean;
FName : String;
FCharRotation : TFslGraphicAngle;
FColour : TFslGraphicColour;
FFamily : TFslFontFamily;
FPitch : TFslFontPitch;
FWeight : TFslFontWeight;
FSize : TFslFontSize;
FTextRotation : TFslGraphicAngle;
Procedure SetColour(Const Value: TFslGraphicColour);
Procedure SetFamily(Const Value: TFslFontFamily);
Procedure SetItalic(Const Value: Boolean);
Procedure SetName(Const Value: String);
Procedure SetPitch(Const Value: TFslFontPitch);
Procedure SetCharRotation(Const Value: TFslGraphicAngle);
Procedure SetSize(Const Value: Word);
Procedure SetStrikeOut(Const Value: Boolean);
Procedure SetUnderline(Const Value: Boolean);
Procedure SetWeight(Const Value: TFslFontWeight);
Procedure SetTextRotation(Const Value: TFslGraphicAngle);
Function GetBold: Boolean;
Procedure SetBold(Const Value: Boolean);
Function GetWeightAsString: String;
Procedure SetWeightAsString(Const Value: String);
Protected
Function CreateHandle : TFslGraphicHandle; Override;
Public
Constructor Create; Override;
Function Link : TFslFont;
Function Clone : TFslFont;
Procedure Assign(oObject : TFslObject); Override;
Procedure Clear; Override;
Procedure ClearStyles;
Procedure SetVCLFont(oFont : TFont);
Function MakeHandle(iPixelsPerInchY: Integer): TFslGraphicHandle;
Property Colour : TFslGraphicColour Read FColour Write SetColour;
Property Size : TFslFontSize Read FSize Write SetSize; // will be mapped to height internally
// specify either Name or FontFamily and Pitch
Property Name: String Read FName Write SetName;
Property Family : TFslFontFamily Read FFamily Write SetFamily;
Property Pitch : TFslFontPitch Read FPitch Write SetPitch;
Property CharRotation : TFslGraphicAngle Read FCharRotation Write SetCharRotation;
Property TextRotation : TFslGraphicAngle Read FTextRotation Write SetTextRotation;
Property Weight : TFslFontWeight Read FWeight Write SetWeight; // bold := true => weight := fwBold
Property WeightAsString : String Read GetWeightAsString Write SetWeightAsString;
Property Bold : Boolean Read GetBold Write SetBold;
Property Italic : Boolean Read FItalic Write SetItalic;
Property Underline : Boolean Read FUnderline Write SetUnderline;
Property StrikeOut : Boolean Read FStrikeOut Write SetStrikeOut;
End;
Const
ADVFONTWEIGHT_CODES : Array [TFslFontWeight] Of String =
('Unknown', 'Thin', 'ExtraLight', 'Light', 'Normal', 'Medium', 'SemiBold', 'Bold', 'ExtraBold', 'Heavy');
ADVFONTWEIGHT_NAMES : Array [TFslFontWeight] Of String =
('Unknown', 'Thin', 'Extra-Light', 'Light', 'Normal', 'Medium', 'Semi-Bold', 'Bold', 'Extra-Bold', 'Heavy');
ADVFONTWEIGHT_VALUES : Array [TFslFontWeight] Of Cardinal =
(FW_DONTCARE, FW_THIN, FW_EXTRALIGHT, FW_LIGHT, FW_NORMAL, FW_MEDIUM, FW_SEMIBOLD, FW_BOLD, FW_EXTRABOLD, FW_HEAVY);
ADVFONTFAMILY_CODES : Array [TFslFontFamily] Of String =
('Unknown', 'Decorative', 'Modern', 'Roman', 'Script', 'Swiss');
ADVFONTFAMILY_VALUES : Array [TFslFontFamily] Of Cardinal =
(FF_DECORATIVE, FF_DONTCARE, FF_MODERN, FF_ROMAN, FF_SCRIPT, FF_SWISS);
ADVFONTPITCH_CODES : Array [TFslFontPitch] Of String =
('Unknown', 'Fixed', 'Variable');
ADVFONTPITCH_VALUES : Array [TFslFontPitch] Of Cardinal =
(DEFAULT_PITCH, FIXED_PITCH, VARIABLE_PITCH);
ADVFONTPITCH_VCLMAP : Array [TFslFontPitch] Of TFontPitch =
(fpDefault, fpVariable, fpFixed);
Type
TFslMetafile = Class(TFslVCLGraphic)
Private
Function GetHandle: TMetafile;
Procedure SetHandle(Const Value: TMetafile);
Protected
Function HandleClass : TGraphicClass; Overload; Override;
Function HandleNew : TGraphic; Overload; Override;
Public
Property Handle : TMetafile Read GetHandle Write SetHandle;
End;
TFslMetafileList = Class(TFslVCLGraphicList)
Private
Function GetGraphic(iIndex: Integer): TFslMetafile;
Protected
Function ItemClass : TFslObjectClass; Override;
Public
Property Graphics[iIndex : Integer] : TFslMetafile Read GetGraphic; Default;
End;
Type
TFslIconGraphic = Class(TFslVCLGraphic)
Private
Function GetIcon : TIcon;
Procedure SetIcon(Const Value : TIcon);
Protected
Function HandleClass : TGraphicClass; Override;
Public
Function Link : TFslIconGraphic;
Procedure SetMaximumDimensions(Const iWidth, iHeight : Integer);
Procedure LoadFromResource(Const sResourceName : String);
Property Icon : TIcon Read GetIcon Write SetIcon;
End;
implementation
Const
WINDOWS_RESOURCE_TYPES : Array[TFslResourceType] Of PChar =
(RT_ACCELERATOR, RT_ANICURSOR, RT_ANIICON, RT_BITMAP, RT_CURSOR, RT_DIALOG, RT_FONT,
RT_FONTDIR, RT_GROUP_CURSOR, RT_GROUP_ICON, RT_ICON, RT_MENU, RT_MESSAGETABLE, RT_RCDATA, RT_STRING, RT_VERSION);
Constructor TFslResourceStream.Create;
Begin
Inherited;
FResourceType := rtRCData;
FResourceHandle := 0;
End;
Procedure TFslResourceStream.BeforeDestruction;
Begin
Close;
Inherited;
End;
Function TFslResourceStream.Link: TFslResourceStream;
Begin
Result := TFslResourceStream(Inherited Link);
End;
Function TFslResourceStream.ToWindowsResourceType(oResourceType : TFslResourceType) : PChar;
Begin
Result := WINDOWS_RESOURCE_TYPES[oResourceType];
End;
Procedure TFslResourceStream.Open;
Var
hModule : Cardinal;
iResourceSize : Cardinal;
Begin
iResourceSize := 0;
FResourceData := Nil;
hModule := LoadLibrary(PChar(FFilename));
Try
FResourceHandle := FindResource(hModule, PChar(FResourceName), ToWindowsResourceType(FResourceType));
If FResourceHandle <> 0 Then
Begin
iResourceSize := SizeofResource(hModule, FResourceHandle);
If iResourceSize <> 0 Then
Begin
FResourceHandle := LoadResource(hModule, FResourceHandle);
If FResourceHandle <> 0 Then
FResourceData := LockResource(FResourceHandle);
End;
End
Else
Begin
RaiseError('Open', StringFormat('Resource not found "%s"', [FResourceName]));
End;
Size := iResourceSize;
Capacity := iResourceSize;
Move(FResourceData^, DataPointer^, iResourceSize);
Finally
FreeLibrary(hModule);
End;
End;
Function TFslResourceStream.Active: Boolean;
Begin
Result := FResourceHandle <> 0;
End;
Function TFslResourceStream.ExistsByResourceType(Const aResourceType : TFslResourceType) : Boolean;
Var
hModule : Cardinal;
Begin
hModule := LoadLibrary(PChar(FFileName));
Try
Result := FindResource(hModule, PChar(FResourceName), ToWindowsResourceType(aResourceType)) <> 0;
Finally
FreeLibrary(hModule);
End;
End;
Function TFslResourceStream.ExistsAcceleratorTable : Boolean;
Begin
Result := ExistsByResourceType(rtAccelerator);
End;
Function TFslResourceStream.ExistsAnimatedCursor : Boolean;
Begin
Result := ExistsByResourceType(rtAniCursor);
End;
Function TFslResourceStream.ExistsAnimatedIcon : Boolean;
Begin
Result := ExistsByResourceType(rtAniIcon);
End;
Function TFslResourceStream.ExistsBitmap : Boolean;
Begin
Result := ExistsByResourceType(rtBitmap);
End;
Function TFslResourceStream.ExistsHardwareDependentCursor : Boolean;
Begin
Result := ExistsByResourceType(rtCursor);
End;
Function TFslResourceStream.ExistsDialogBox : Boolean;
Begin
Result := ExistsByResourceType(rtDialog);
End;
Function TFslResourceStream.ExistsFont : Boolean;
Begin
Result := ExistsByResourceType(rtFont);
End;
Function TFslResourceStream.ExistsFontDirectory : Boolean;
Begin
Result := ExistsByResourceType(rtFontDir);
End;
Function TFslResourceStream.ExistsHardwareIndependentCursor : Boolean;
Begin
Result := ExistsByResourceType(rtGroupCursor);
End;
Function TFslResourceStream.ExistsHardwareIndependentIcon : Boolean;
Begin
Result := ExistsByResourceType(rtIcon);
End;
Function TFslResourceStream.ExistsHardwareDependentIcon : Boolean;
Begin
Result := ExistsByResourceType(rtGroupIcon);
End;
Function TFslResourceStream.ExistsMenu : Boolean;
Begin
Result := ExistsByResourceType(rtMenu);
End;
Function TFslResourceStream.ExistsMessageTableEntry : Boolean;
Begin
Result := ExistsByResourceType(rtMessageTable);
End;
Function TFslResourceStream.ExistsApplicationDefined : Boolean;
Begin
Result := ExistsByResourceType(rtRCData);
End;
Function TFslResourceStream.ExistsStringTableEntry : Boolean;
Begin
Result := ExistsByResourceType(rtString);
End;
Function TFslResourceStream.ExistsVersion : Boolean;
Begin
Result := ExistsByResourceType(rtVersion);
End;
Procedure TFslResourceStream.ResourceTypeAcceleratorTable;
Begin
FResourceType := rtAccelerator;
End;
Procedure TFslResourceStream.ResourceTypeAnimatedCursor;
Begin
FResourceType := rtAniCursor;
End;
Procedure TFslResourceStream.ResourceTypeAnimatedIcon;
Begin
FResourceType := rtAniIcon;
End;
Procedure TFslResourceStream.ResourceTypeBitmap;
Begin
FResourceType := rtBitmap;
End;
Procedure TFslResourceStream.ResourceTypeHardwareDependentCursor;
Begin
FResourceType := rtCursor;
End;
Procedure TFslResourceStream.ResourceTypeDialogBox;
Begin
FResourceType := rtDialog;
End;
Procedure TFslResourceStream.ResourceTypeFont;
Begin
FResourceType := rtFont;
End;
Procedure TFslResourceStream.ResourceTypeFontDirectory;
Begin
FResourceType := rtFontDir;
End;
Procedure TFslResourceStream.ResourceTypeHardwareIndependentCursor;
Begin
FResourceType := rtGroupCursor;
End;
Procedure TFslResourceStream.ResourceTypeHardwareIndependentIcon;
Begin
FResourceType := rtGroupIcon;
End;
Procedure TFslResourceStream.ResourceTypeHardwareDependentIcon;
Begin
FResourceType := rtIcon;
End;
Procedure TFslResourceStream.ResourceTypeMenu;
Begin
FResourceType := rtMenu;
End;
Procedure TFslResourceStream.ResourceTypeMessageTableEntry;
Begin
FResourceType := rtMessageTable;
End;
Procedure TFslResourceStream.ResourceTypeApplicationDefined;
Begin
FResourceType := rtRCData;
End;
Procedure TFslResourceStream.ResourceTypeStringTableEntry;
Begin
FResourceType := rtString;
End;
Procedure TFslResourceStream.ResourceTypeVersion;
Begin
FResourceType := rtVersion;
End;
Procedure TFslResourceStream.Close;
Begin
// API says no need to call 'FreeResource' in Windows 32 bit.
FResourceHandle := 0;
End;
Function TFslResourceStream.IsResourceTypeAcceleratorTable : Boolean;
Begin
Result := FResourceType = rtAccelerator;
End;
Function TFslResourceStream.IsResourceTypeAnimatedCursor : Boolean;
Begin
Result := FResourceType = rtAniCursor;
End;
Function TFslResourceStream.IsResourceTypeAnimatedIcon : Boolean;
Begin
Result := FResourceType = rtAniIcon;
End;
Function TFslResourceStream.IsResourceTypeBitmap : Boolean;
Begin
Result := FResourceType = rtBitmap;
End;
Function TFslResourceStream.IsResourceTypeHardwareDependentCursor : Boolean;
Begin
Result := FResourceType = rtCursor;
End;
Function TFslResourceStream.IsResourceTypeDialogBox : Boolean;
Begin
Result := FResourceType = rtDialog;
End;
Function TFslResourceStream.IsResourceTypeFont : Boolean;
Begin
Result := FResourceType = rtFont;
End;
Function TFslResourceStream.IsResourceTypeFontDirectory : Boolean;
Begin
Result := FResourceType = rtFontDir;
End;
Function TFslResourceStream.IsResourceTypeHardwareIndependentCursor : Boolean;
Begin
Result := FResourceType = rtGroupCursor;
End;
Function TFslResourceStream.IsResourceTypeHardwareIndependentIcon : Boolean;
Begin
Result := FResourceType = rtIcon;
End;
Function TFslResourceStream.IsResourceTypeHardwareDependentIcon : Boolean;
Begin
Result := FResourceType = rtGroupIcon;
End;
Function TFslResourceStream.IsResourceTypeMenu : Boolean;
Begin
Result := FResourceType = rtMenu;
End;
Function TFslResourceStream.IsResourceTypeMessageTableEntry : Boolean;
Begin
Result := FResourceType = rtMessageTable;
End;
Function TFslResourceStream.IsResourceTypeApplicationDefined : Boolean;
Begin
Result := FResourceType = rtRCData;
End;
Function TFslResourceStream.IsResourceTypeStringTableEntry : Boolean;
Begin
Result := FResourceType = rtString;
End;
Function TFslResourceStream.IsResourceTypeVersion : Boolean;
Begin
Result := FResourceType = rtVersion;
End;
function TFslGraphic.AsBitmap: TFslVCLGraphic;
begin
result := nil;
Invariant('AsBitmap', 'Need to override ' + ClassName + '.AsBitmap');
end;
Function TFslGraphic.Clone: TFslGraphic;
Begin
Result := TFslGraphic(Inherited Clone);
End;
procedure TFslGraphic.DrawToStream(oStream: TFslStream; width, height : Integer);
begin
Invariant('LoadFromFile', 'Need to override ' + ClassName + '.DrawToStream');
end;
Function TFslGraphic.Link: TFslGraphic;
Begin
Result := TFslGraphic(Inherited Link);
End;
Procedure TFslGraphic.LoadFromStream(oStream : TFslStream);
Begin
Invariant('LoadFromStream', 'Need to override ' + ClassName + '.LoadFromStream');
End;
Procedure TFslGraphic.SaveToStream(oStream : TFslStream);
Begin
Invariant('SaveToStream', 'Need to override ' + ClassName + '.SaveToStream');
End;
Procedure TFslGraphic.LoadFromFile(Const sFilename : String);
Begin
Invariant('LoadFromFile', 'Need to override ' + ClassName + '.LoadFromFile');
End;
Procedure TFslGraphic.SaveToFile(Const sFilename : String);
Begin
Invariant('SaveToFile', 'Need to override ' + ClassName + '.SaveToFile');
End;
function TFslGraphic.Extension: String;
begin
result := '???';
end;
function TFslGraphic.FrameCount: Integer;
begin
result := 1;
end;
function TFslGraphic.GetFrameIndex: Integer;
begin
result := 0;
end;
Function TFslGraphic.GetHeight: Integer;
Begin
Invariant('GetHeight', 'Need to override ' + ClassName + '.GetHeight');
Result := 0;
End;
Function TFslGraphic.GetWidth: Integer;
Begin
Invariant('GetWidth', 'Need to override ' + ClassName + '.GetWidth');
Result := 0;
End;
procedure TFslGraphic.SetFrameIndex(const Value: Integer);
begin
if Value >= FrameCount then
RaiseError('SetFrameIndex', 'The maximum Frame Index value for this image is '+inttostr(FrameCount-1));
end;
Procedure TFslGraphic.SetHeight(Const Value: Integer);
Begin
Invariant('SetHeight', 'Need to override ' + ClassName + '.SetHeight');
End;
Procedure TFslGraphic.SetWidth(Const Value: Integer);
Begin
Invariant('SetWidth', 'Need to override ' + ClassName + '.SetWidth');
End;
procedure TFslGraphic.StretchDraw(oCanvas: TCanvas; aRect: TRect);
begin
Invariant('TFslGraphic', 'Need to override ' + ClassName + '.StretchDraw');
end;
Function TFslGraphicList.GetGraphic(iIndex: Integer): TFslGraphic;
Begin
Result := TFslGraphic(ObjectByIndex[iIndex]);
End;
Function TFslGraphicList.ItemClass: TFslObjectClass;
Begin
Result := TFslGraphic;
End;
Constructor TFslVCLGraphic.Create;
Begin
Inherited;
FHandle := HandleNew;
FBuffer := TFslBuffer.Create;
End;
Destructor TFslVCLGraphic.Destroy;
Begin
FHandle.Free;
FBuffer.Free;
Inherited;
End;
procedure TFslVCLGraphic.DrawToStream(oStream: TFslStream; width, height : Integer);
begin
SaveToStream(oStream);
end;
Procedure TFslVCLGraphic.LoadFromStream(oStream: TFslStream);
Var
oAdapter : TVCLStream;
Begin
oAdapter := TVCLStream.Create;
Try
oAdapter.Stream := oStream.Link;
Handle.LoadFromStream(oAdapter);
Finally
oAdapter.Free;
End;
End;
Procedure TFslVCLGraphic.SaveToStream(oStream: TFslStream);
Var
oAdapter : TVCLStream;
Begin
oAdapter := TVCLStream.Create;
Try
oAdapter.Stream := oStream.Link;
Handle.SaveToStream(oAdapter);
Finally
oAdapter.Free;
End;
End;
Class Function TFslVCLGraphic.NewFromGraphic(const oGraphic: TGraphic): TFslVCLGraphic;
Var
oGraphicExGraphicClass : TGraphicExGraphicClass;
oVCLStream : TVCLStream;
Begin
Result := Nil;
oVCLStream := TVCLStream.Create;
Try
oVCLStream.Stream := TFslMemoryStream.Create;
oGraphic.SaveToStream(oVCLStream);
oVCLStream.Position := 0;
oGraphicExGraphicClass := GraphicEx.FileFormatList.GraphicFromContent(oVCLStream);
If Assigned(oGraphicExGraphicClass) Then
Begin
If oGraphicExGraphicClass = TTIFFGraphic Then
Result := TFslTIFFGraphic.Create
Else If oGraphicExGraphicClass = TPNGGraphic Then
Result := TFslPortableNetworkGraphic.Create
Else If oGraphicExGraphicClass = TGIFGraphic Then
Result := TFslGIFGraphic.Create
Else
Raise EFslException.Create('TFslVCLGraphic', 'NewFromGraphic', StringFormat('Image file format ''%s'' is not supported.', [oGraphicExGraphicClass.ClassName]));
End
Else
Begin
// TBitmap, TJpegImage cannot be looked up as they don't descend from TGraphicExGraphic.
If TFslBitmapGraphic.CanLoad(oVCLStream) Then
Result := TFslBitmapGraphic.Create
Else {If TFslJpegImage.CanLoad(oVCLStream) Then}
Result := TFslJPegGraphic.Create;
End;
oVCLStream.Position := 0;
Result.LoadFromStream(oVCLStream.Stream);
Finally
oVCLStream.Free;
End;
End;
Function TFslVCLGraphic.HandleClass: TGraphicClass;
Begin
Result := Nil;
End;
Function TFslVCLGraphic.HandleNew: TGraphic;
Var
aClass : TGraphicClass;
Begin
aClass := HandleClass;
If Assigned(aClass) Then
Begin
Assert(Invariants('HandleNew', aClass, TGraphic, 'aClass'));
Result := aClass.Create;
End
Else
Begin
Result := Nil;
End;
End;
Function TFslVCLGraphic.GetHandle: TGraphic;
Begin
Assert(CheckCondition(HasHandle, 'GetHandle', 'Handle must be assigned.'));
Result := FHandle;
End;
Procedure TFslVCLGraphic.SetHandle(Const Value: TGraphic);
Begin
FHandle.Free;
FHandle := Value;
End;
Function TFslVCLGraphic.Clone: TFslVCLGraphic;
Begin
Result := TFslVCLGraphic(Inherited Clone);
End;
Function TFslVCLGraphic.Link: TFslVCLGraphic;
Begin
Result := TFslVCLGraphic(Inherited Link);
End;
Function TFslVCLGraphic.GetWidth: Integer;
Begin
Result := Handle.Width;
End;
Procedure TFslVCLGraphic.SetWidth(Const Value: Integer);
Begin
Handle.Width := Value;
End;
procedure TFslVCLGraphic.StretchDraw(oCanvas: TCanvas; aRect: TRect);
begin
oCanvas.StretchDraw(aRect, Handle)
end;
Function TFslVCLGraphic.GetHeight: Integer;
Begin
Result := Handle.Height;
End;
Procedure TFslVCLGraphic.SetHeight(Const Value: Integer);
Begin
Handle.Height := Value;
End;
Function TFslVCLGraphic.Empty: Boolean;
Begin
Result := Handle.Empty;
End;
Procedure TFslVCLGraphic.LoadFromFile(Const sFilename: String);
Begin
Handle.LoadFromFile(sFilename);
End;
Procedure TFslVCLGraphic.LoadFromGraphic(const oGraphic: TGraphic);
Var
oStream : TMemoryStream;
Begin
oStream := TMemoryStream.Create;
Try
oGraphic.SaveToStream(oStream);
oStream.Position := 0;
Handle.LoadFromStream(oStream);
Finally
oStream.Free;
End;
End;
Procedure TFslVCLGraphic.SaveToFile(Const sFilename: String);
Begin
Handle.SaveToFile(sFilename);
End;
Procedure TFslVCLGraphic.Assign(oObject: TFslObject);
Begin
Inherited;
Handle.Assign(TFslVCLGraphic(oObject).Handle);
End;
Function TFslVCLGraphic.HasHandle: Boolean;
Begin
Result := Assigned(FHandle);
End;
Function TFslVCLGraphicList.GetGraphic(iIndex: Integer): TFslVCLGraphic;
Begin
Result := TFslVCLGraphic(ObjectByIndex[iIndex]);
End;
Function TFslVCLGraphicList.ItemClass: TFslObjectClass;
Begin
Result := TFslVCLGraphic;
End;
Function TFslVCLGraphic.GetTransparent: Boolean;
Begin
Result := Handle.Transparent;
End;
Procedure TFslVCLGraphic.SetTransparent(Const Value: Boolean);
Begin
Handle.Transparent := True;
End;
Function TFslGraphic.TypeName: String;
Begin
Result := StringExcludeBefore(ClassName, 'TFsl');
End;
Function TFslTIFFGraphic.Link: TFslTIFFGraphic;
Begin
Result := TFslTIFFGraphic(Inherited Link);
End;
Function TFslTIFFGraphic.Clone: TFslTIFFGraphic;
Begin
Result := TFslTIFFGraphic(Inherited Clone);
End;
Function TFslTIFFGraphic.HandleClass : TGraphicClass;
Begin
Result := TTIFFGraphic;
End;
Function TFslTIFFGraphic.HandleNew: TGraphic;
Begin
Result := TTIFFGraphic.Create; // Because TGraphicClass.Create is not a virtual method.
End;
Function TFslTIFFGraphic.GetHandle: TTIFFGraphic;
Begin
Result := TTIFFGraphic(Inherited Handle);
End;
Procedure TFslTIFFGraphic.SetHandle(Const Value: TTIFFGraphic);
Begin
Inherited Handle := Value;
End;
Procedure TFslTIFFGraphic.LoadFromResource(Const sResource: String);
Var
oResourceStream : TFslResourceStream;
oVCLStream : TFslVCLStream;
Begin
oResourceStream := TFslResourceStream.Create;
oVCLStream := TFslVCLStream.Create;
Try
oResourceStream.ResourceTypeApplicationDefined;
oResourceStream.Filename := ProcessName;
oResourceStream.ResourceName := sResource;
oResourceStream.Open;
Try
oVCLStream.Stream.ReadBuffer(oResourceStream.Buffer.Data^, oResourceStream.Buffer.Capacity);
Handle.LoadFromStream(oVCLStream.Stream);
Finally
oResourceStream.Close;
End;
Finally
oVCLStream.Free;
oResourceStream.Free;
End;
End;
Function TFslPortableNetworkGraphic.Link: TFslPortableNetworkGraphic;
Begin
Result := TFslPortableNetworkGraphic(Inherited Link);
End;
Function TFslPortableNetworkGraphic.Clone: TFslPortableNetworkGraphic;
Begin
Result := TFslPortableNetworkGraphic(Inherited Clone);
End;
Function TFslPortableNetworkGraphic.HandleClass : TGraphicClass;
Begin
Result := TPngObject;
End;
Function TFslPortableNetworkGraphic.HandleNew: TGraphic;
Begin
Result := TPngObject.Create; // Because TGraphicClass.Create is not a virtual method.
End;
Function TFslPortableNetworkGraphic.GetHandle: TPNGGraphic;
Begin
Result := TPNGGraphic(Inherited Handle);
End;
Procedure TFslPortableNetworkGraphic.SetHandle(Const Value: TPNGGraphic);
Begin
Inherited Handle := Value;
End;
Procedure TFslPortableNetworkGraphic.LoadFromResource(Const sResource: String);
Var
oResourceStream : TFslResourceStream;
oVCLStream : TFslVCLStream;
Begin
oResourceStream := TFslResourceStream.Create;
oVCLStream := TFslVCLStream.Create;
Try
oResourceStream.ResourceTypeApplicationDefined;
oResourceStream.Filename := ProcessName;
oResourceStream.ResourceName := sResource;
oResourceStream.Open;
Try
oVCLStream.Stream.ReadBuffer(oResourceStream.Buffer.Data^, oResourceStream.Buffer.Capacity);
Handle.LoadFromStream(oVCLStream.Stream);
Finally
oResourceStream.Close;
End;
Finally
oVCLStream.Free;
oResourceStream.Free;
End;
End;
Function TFslGIFGraphic.Link: TFslGIFGraphic;
Begin
Result := TFslGIFGraphic(Inherited Link);
End;
Function TFslGIFGraphic.Clone: TFslGIFGraphic;
Begin
Result := TFslGIFGraphic(Inherited Clone);
End;
Function TFslGIFGraphic.HandleClass : TGraphicClass;
Begin
Result := TGIFGraphic;
End;
Function TFslGIFGraphic.HandleNew: TGraphic;
Begin
Result := TGIFGraphic.Create; // Because TGraphicClass.Create is not a virtual method.
End;
Function TFslGIFGraphic.GetHandle: TGIFGraphic;
Begin
Result := TGIFGraphic(Inherited Handle);
End;
Procedure TFslGIFGraphic.SetHandle(Const Value: TGIFGraphic);
Begin
Inherited Handle := Value;
End;
Procedure TFslGIFGraphic.LoadFromResource(Const sResource: String);
Var
oResourceStream : TFslResourceStream;
oVCLStream : TFslVCLStream;
Begin
oResourceStream := TFslResourceStream.Create;
oVCLStream := TFslVCLStream.Create;
Try
oResourceStream.ResourceTypeApplicationDefined;
oResourceStream.Filename := ProcessName;
oResourceStream.ResourceName := sResource;
oResourceStream.Open;
Try
oVCLStream.Stream.ReadBuffer(oResourceStream.Buffer.Data^, oResourceStream.Buffer.Capacity);
Handle.LoadFromStream(oVCLStream.Stream);
Finally
oResourceStream.Close;
End;
Finally
oVCLStream.Free;
oResourceStream.Free;
End;
End;
Const
PIXELMAX = 32768;
Type
TRGBTripleArray = Array[0..PIXELMAX-1] Of TRGBTriple;
PRGBTripleArray = ^TRGBTripleArray;
Function TFslBitmapGraphic.Link: TFslBitmapGraphic;
Begin
Result := TFslBitmapGraphic(Inherited Link);
End;
Function TFslBitmapGraphic.Clone: TFslBitmapGraphic;
Begin
Result := TFslBitmapGraphic(Inherited Clone);
End;
Function TFslBitmapGraphic.HandleClass : TGraphicClass;
Begin
Result := Vcl.Graphics.TBitmap;
End;
Function TFslBitmapGraphic.HandleNew: TGraphic;
Begin
Result := Vcl.Graphics.TBitmap.Create; // Because TGraphicClass.Create is not a virtual method.
End;
Function TFslBitmapGraphic.GetHandle: TBitmap;
Begin
Result := TBitmap(Inherited Handle);
End;
Procedure TFslBitmapGraphic.SetHandle(Const Value: TBitmap);
Begin
Inherited Handle := Value;
End;
Function TFslBitmapGraphic.BytesPerLine : Integer;
Begin
Case Handle.PixelFormat Of
pf1bit : Result := RealCeiling(Width / 8);
pf4bit : Result := RealCeiling(Width / 2);
pf8bit : Result := Width;
pf15bit : Result := Width * 2; // TODO: what's the calculation for 15 bit?
pf16bit : Result := Width * 2;
pf24bit : Result := Width * 3;
pf32bit : Result := Width * 4;
Else
RaiseError('BytesPerLine', 'PixelFormat not supported.');
Result := 0;
End;
End;
Procedure TFslBitmapGraphic.LoadFromResource(Const sResource: String);
Begin
Handle.LoadFromResourceName(HInstance, sResource);
End;
Function TFslBitmapGraphic.ConstructRotate(Const AngleOfRotation : Double) : TBitmap;
Var
cosTheta : Extended;
i : Integer;
iOriginal : Integer;
iPrime : Integer;
j : Integer;
jOriginal : Integer;
jPrime : Integer;
RowOriginal: pRGBTripleArray;
RowRotated : pRGBTRipleArray;
sinTheta : Extended;
iRotationAxis : Integer;
jRotationAxis : Integer;
Radians : Double;
Begin
Result := TBitmap.Create;
Try
Result.Canvas.Lock;
Handle.Canvas.Lock;
Try
iRotationAxis := Width Div 2;
jRotationAxis := Height Div 2;
If (AngleOfRotation = 90) Or (AngleOfRotation = 270) Then
Begin
Result.Width := Handle.Height;
Result.Height := Handle.Width;
iRotationAxis := Height Div 2;
End
Else
Begin
Result.Width := Handle.Width;
Result.Height := Handle.Height;
End;
Handle.PixelFormat := pf24bit;
Result.PixelFormat := pf24bit; // Force this
// If no math library, then use this:
Radians := -(AngleOfRotation) * PI / 180;
sinTheta := SIN(Radians);//AngleOfRotation);
cosTheta := COS(Radians);//AngleOfRotation);
// Step through each row of rotated image.
For j := Result.Height - 1 DownTo 0 Do
Begin
RowRotated := Result.Scanline[j];
jPrime := j - jRotationAxis;
For i := Result.Width - 1 DownTo 0 Do
Begin
iPrime := i - iRotationAxis;
iOriginal := iRotationAxis + ROUND(iPrime * CosTheta - jPrime * sinTheta);
jOriginal := jRotationAxis + ROUND(iPrime * sinTheta + jPrime * cosTheta);
// Make sure (iOriginal, jOriginal) is in BitmapOriginal. If not,
// assign blue color to corner points.
If (iOriginal >= 0) And (iOriginal <= Handle.Width-1) And (jOriginal >= 0) And (jOriginal <= Handle.Height-1) Then
Begin
// Assign pixel from rotated space to current pixel in BitmapRotated
RowOriginal := Handle.Scanline[jOriginal];
RowRotated[i] := RowOriginal[iOriginal]
End
Else
Begin
RowRotated[i].rgbtBlue := 255; // assign "corner" color
RowRotated[i].rgbtGreen := 0;
RowRotated[i].rgbtRed := 0
End;
End;
End;
Finally
Handle.Canvas.Unlock;
Result.Canvas.Unlock;
End;
Except
Result.Free;
Raise;
End;
End;
Function TFslBitmapGraphic.ConstructFitToPage(Const iWidth, iHeight : Integer) : TFslBitmapGraphic;
Begin
Result := TFslBitmapGraphic.Create;
Try
If Self.Width > Self.Height Then
Begin
Result.Width := iWidth;
If Self.Height > 0 Then
Result.Height := Round(iHeight * (Self.Height / Self.Width))
Else
Result.Height := iHeight;
End
Else If Self.Width < Self.Height Then
Begin
Result.Height := iHeight;
If Self.Width > 0 Then
Result.Width := Round(iWidth * (Self.Width / Self.Height))
Else
Result.Width := iWidth;
End
Else
Begin
Result.Width := iWidth;
Result.Height := iHeight;
End;
Result.Handle.Canvas.StretchDraw(Rect(0, 0, Result.Width, Result.Height), Self.Handle);
Result.Link;
Finally
Result.Free;
End;
End;
Function TFslBitmapGraphicList.GetBitmapGraphicByIndex(iIndex: Integer): TFslBitmapGraphic;
Begin
Result := TFslBitmapGraphic(ObjectByIndex[iIndex]);
End;
Function TFslBitmapGraphicList.ItemClass: TFslObjectClass;
Begin
Result := TFslBitmapGraphic;
End;
Class Function TFslBitmapGraphic.CanLoad(oStream: TStream): Boolean;
Var
aBitmapFileHeader : TBitmapFileHeader;
iLastPosition : Integer;
Begin
Result := (oStream.Size - oStream.Position) > SizeOf(aBitmapFileHeader);
If Result Then
Begin
iLastPosition := oStream.Position;
oStream.ReadBuffer(aBitmapFileHeader, SizeOf(aBitmapFileHeader));
Result := aBitmapFileHeader.bfType = $4D42;
oStream.Position := iLastPosition;
End;
End;
Function TFslJpegGraphic.HandleClass : TGraphicClass;
Begin
Result := TJpegImage;
End;
Function TFslJpegGraphic.HandleNew: TGraphic;
Begin
Result := TJpegImage.Create; // Because TGraphicClass.Create is not a virtual method.
End;
Function TFslJpegGraphic.GetHandle: TJpegImage;
Begin
Result := TJpegImage(Inherited Handle);
End;
Procedure TFslJpegGraphic.SetHandle(Const Value: TJpegImage);
Begin
Inherited Handle := Value;
End;
Function TFslJpegGraphic.AsBitmap: TFslBitmapGraphic;
Begin
Result := TFslBitmapGraphic.Create;
Result.Handle.Assign(Handle);
End;
Function TFslJpegGraphic.GetQuality: Integer;
Begin
Result := Handle.CompressionQuality;
End;
Procedure TFslJpegGraphic.SetQuality(Const Value: Integer);
Begin
Handle.CompressionQuality := Value;
End;
Function TFslJpegGraphic.GetGrayScale: Boolean;
Begin
Result := Handle.GrayScale;
End;
Procedure TFslJpegGraphic.SetGrayScale(Const Value: Boolean);
Begin
Handle.GrayScale := Value;
End;
Procedure TFslJpegGraphic.Compress;
Begin
Handle.Compress;
End;
Function TFslJpegGraphic.Clone: TFslJpegGraphic;
Begin
Result := TFslJpegGraphic(Inherited Clone);
End;
Function TFslJpegGraphic.Link: TFslJpegGraphic;
Begin
Result := TFslJpegGraphic(Inherited Link);
End;
Function TFslPen.Link: TFslPen;
Begin
Result := TFslPen(Inherited Link);
End;
Function TFslPen.Clone: TFslPen;
Begin
Result := TFslPen(Inherited Clone);
End;
Procedure TFslPen.Assign(oObject: TFslObject);
Begin
Inherited;
// using properties is deliberate
Width := TFslPen(oObject).FWidth;
Colour := TFslPen(oObject).FColour;
EndStyle := TFslPen(oObject).FEndStyle;
JoinStyle := TFslPen(oObject).FJoinStyle;
Style := TFslPen(oObject).FStyle;
End;
Procedure TFslPen.Clear;
Begin
Inherited;
FWidth := 0;
FColour := clBlack;
FEndStyle := apesSquare;
FJoinStyle := apjsMitre;
FStyle := apsNone;
End;
Function TFslPen.CreateHandle: TFslGraphicHandle;
Var
aBrush : TLogBrush;
Begin
FillChar(aBrush, SizeOf(TLogBrush), 0);
aBrush.lbStyle := BS_SOLID;
aBrush.lbColor := ColorToRGB(FColour);
aBrush.lbHatch := 0;
Result := ExtCreatePen(
{PenStyle} PS_GEOMETRIC + ADVPENSTYLE_VALUES[FStyle] +ADVPENENDSTYLE_VALUES[FEndStyle] +ADVPENJOINSTYLE_VALUES[FJoinStyle],
{Width } IntegerMax(1, Capability.ToPixel(FWidth)), // pen width can never be less than 1
{Brush} aBrush, 0, Nil);
If Result = 0 Then
RaiseError('CreateHandle', ErrorAsString);
End;
Procedure TFslPen.SetColour(Const Value: TFslGraphicColour);
Begin
If FColour <> Value Then
Begin
ClearHandle;
Change;
FColour := Value;
End;
End;
Procedure TFslPen.SetEndStyle(Const Value: TFslPenEndStyle);
Begin
If FEndStyle <> Value Then
Begin
ClearHandle;
Change;
FEndStyle := Value;
End;
End;
Procedure TFslPen.SetJoinStyle(Const Value: TFslPenJoinStyle);
Begin
If FJoinStyle <> Value Then
Begin
ClearHandle;
Change;
FJoinStyle := Value;
End;
End;
Procedure TFslPen.SetStyle(Const Value: TFslPenStyle);
Begin
If FStyle <> Value Then
Begin
ClearHandle;
Change;
FStyle := Value;
End;
End;
Procedure TFslPen.SetWidth(Const Value: Integer);
Begin
If FWidth <> Value Then
Begin
ClearHandle;
Change;
FWidth := Value;
End;
End;
Procedure TFslPen.AfterConstruction;
Begin
Inherited;
Clear;
End;
Procedure TFslPen.SetStyleNone;
Begin
Style := apsNone;
End;
Procedure TFslPen.SetStyleSolid;
Begin
Style := apsSolid;
End;
Procedure TFslPen.SetStyleDot;
Begin
Style := apsDot;
End;
Procedure TFslPen.SetStyleDash;
Begin
Style := apsDash;
End;
Function TFslPen.GetStyleAsString: String;
Begin
Result := ADVPENSTYLE_NAMES[Style];
End;
Procedure TFslPen.SetStyleAsString(Const Value: String);
Var
iIndex : Integer;
Begin
iIndex := StringArrayIndexOf(ADVPENSTYLE_NAMES, Value);
If iIndex < 0 Then
RaiseError('SetStyleAsString', StringFormat('Pen Style ''%s'' not recognised.', [Value]));
Style := TFslPenStyle(iIndex);
End;
Destructor TFslGraphicObject.Destroy;
Begin
ClearHandle;
Inherited;
End;
Procedure TFslGraphicObject.ClearHandle;
Begin
If FHandle <> 0 Then
DeleteObject(FHandle);
FHandle := 0;
End;
Procedure TFslGraphicObject.Change;
Begin
if assigned(FOnChange) then
FOnChange(self);
End;
Function TFslGraphicObject.CreateHandle : TFslGraphicHandle;
Begin
RaiseError('CreateHandle', 'Need to override in '+ClassName);
Result := 0;
End;
Function TFslGraphicObject.GetHandle: TFslGraphicHandle;
Begin
If FHandle = 0 Then
FHandle := CreateHandle;
Result := FHandle;
End;
Procedure TFslGraphicObject.Clear;
Begin
ClearHandle;
Change;
End;
Procedure TFslGraphicObject.AfterConstruction;
Begin
Inherited;
Clear;
End;
Function TFslGraphicCapability.FromPixel(iValue: Integer): TFslGraphicMetre;
Begin
Result := Round(iValue / FPixelsPerGraphicMetre);
End;
Function TFslGraphicCapability.ToPixel(iValue: TFslGraphicMetre): Integer;
Begin
Result := Round(iValue * FPixelsPerGraphicMetre);
End;
Constructor TFslBrush.Create;
Begin
Inherited;
FBitmap := Nil;
End;
Destructor TFslBrush.Destroy;
Begin
FBitmap.Free;
Inherited;
End;
Procedure TFslBrush.Clear;
Begin
Inherited;
Bitmap := Nil;
FColour := clWhite;
FStyle := absNull;
End;
Type
TLogBrush = Packed Record
lbStyle: UINT;
lbColor: COLORREF;
lbHatch: Cardinal;
End;
Function TFslBrush.CreateHandle: TFslGraphicHandle;
Var
aBrush : TLogBrush;
Begin
FillChar(aBrush, SizeOf(TLogBrush), 0);
If Assigned(FBitmap) Then
Begin
aBrush.lbStyle := BS_PATTERN;
aBrush.lbHatch := FBitmap.Handle.Handle;
End
Else
Begin
aBrush.lbStyle := ADVBRUSHSTYLE_VALUES[FStyle];
aBrush.lbColor := ColorToRGB(FColour);
aBrush.lbHatch := ADVBRUSHSTYLE_HASHVALUES[FStyle];
End;
Result := CreateBrushIndirect(tagLOGBRUSH(aBrush));
If Result = 0 Then
RaiseError('CreateHandle', ErrorAsString);
End;
Function TFslBrush.Clone: TFslBrush;
Begin
Result := TFslBrush(Inherited Clone);
End;
Function TFslBrush.Link: TFslBrush;
Begin
Result := TFslBrush(Inherited Link);
End;
Procedure TFslBrush.Assign(oObject: TFslObject);
Begin
Inherited;
// using properties is deliberate
Bitmap := TFslBrush(oObject).FBitmap.Link;
FColour := TFslBrush(oObject).FColour;
FStyle := TFslBrush(oObject).FStyle;
End;
Function TFslBrush.GetBitmap: TFslBitmapGraphic;
Begin
Assert(Invariants('GetBitmap', FBitmap, TFslBitmapGraphic, 'FBitmap'));
Result := FBitmap;
End;
Procedure TFslBrush.SetBitmap(Const Value: TFslBitmapGraphic);
Begin
Assert(Not Assigned(Value) Or Invariants('SetBitmap', Value, TFslBitmapGraphic, 'Value'));
ClearHandle;
Change;
FBitmap.Free;
FBitmap := Value;
End;
Procedure TFslBrush.SetColour(Const Value: TColour);
Begin
If FColour <> Value Then
Begin
ClearHandle;
Change;
FColour := Value;
End;
End;
Procedure TFslBrush.SetStyle(Const Value: TFslBrushStyle);
Begin
If FStyle <> Value Then
Begin
ClearHandle;
Change;
FStyle := Value;
End;
End;
Procedure TFslBrush.SetStyleClear;
Begin
Style := absNull;
End;
Procedure TFslBrush.SetStyleSolid;
Begin
Style := absSolid;
End;
Function TFslBrush.GetStyleAsString: String;
Begin
Result := ADVBRUSHSTYLE_NAMES[Style];
End;
Procedure TFslBrush.SetStyleAsString(Const Value: String);
Var
iIndex : Integer;
Begin
iIndex := StringArrayIndexOf(ADVBRUSHSTYLE_NAMES, Value);
If iIndex < 0 Then
RaiseError('SetStyleAsString', StringFormat('Brush Style ''%s'' not recognised.', [Value]));
Style := TFslBrushStyle(iIndex);
End;
Function TFslBrush.HasBitmap: Boolean;
Begin
Result := Assigned(FBitmap);
End;
Constructor TFslFont.Create;
Begin
Inherited;
Clear;
End;
Function TFslFont.Clone: TFslFont;
Begin
Result := TFslFont(Inherited Clone);
End;
Function TFslFont.Link: TFslFont;
Begin
Result := TFslFont(Inherited Link);
End;
Procedure TFslFont.Assign(oObject: TFslObject);
Begin
Inherited;
// using properties is deliberate
Italic := TFslFont(oObject).FItalic;
Underline := TFslFont(oObject).FUnderline;
StrikeOut := TFslFont(oObject).FStrikeOut;
Name := TFslFont(oObject).FName;
CharRotation := TFslFont(oObject).FCharRotation;
TextRotation := TFslFont(oObject).FTextRotation;
Colour := TFslFont(oObject).FColour;
Family := TFslFont(oObject).FFamily;
Pitch := TFslFont(oObject).FPitch;
Weight := TFslFont(oObject).FWeight;
Size := TFslFont(oObject).FSize;
End;
Procedure TFslFont.SetColour(Const Value: TFslGraphicColour);
Begin
If FColour <> Value Then
Begin
ClearHandle;
Change;
FColour := Value;
End;
End;
Procedure TFslFont.SetFamily(Const Value: TFslFontFamily);
Begin
If FFamily <> Value Then
Begin
ClearHandle;
Change;
FFamily := Value;
End;
End;
Procedure TFslFont.SetItalic(Const Value: Boolean);
Begin
If FItalic <> Value Then
Begin
ClearHandle;
Change;
FItalic := Value;
End;
End;
Procedure TFslFont.SetName(Const Value: String);
Begin
If FName <> Value Then
Begin
ClearHandle;
Change;
FName := Value;
End;
End;
Procedure TFslFont.SetPitch(Const Value: TFslFontPitch);
Begin
If FPitch <> Value Then
Begin
ClearHandle;
Change;
FPitch := Value;
End;
End;
Procedure TFslFont.SetCharRotation(Const Value: TFslGraphicAngle);
Begin
If FCharRotation <> Value Then
Begin
ClearHandle;
Change;
FCharRotation := Value;
End;
End;
Procedure TFslFont.SetSize(Const Value: Word);
Begin
If FSize <> Value Then
Begin
ClearHandle;
Change;
FSize := Value;
End;
End;
Procedure TFslFont.SetStrikeOut(Const Value: Boolean);
Begin
If FStrikeOut <> Value Then
Begin
ClearHandle;
Change;
FStrikeOut := Value;
End;
End;
Procedure TFslFont.SetUnderline(Const Value: Boolean);
Begin
If FUnderline <> Value Then
Begin
ClearHandle;
Change;
FUnderline := Value;
End;
End;
Procedure TFslFont.SetWeight(Const Value: TFslFontWeight);
Begin
If FWeight <> Value Then
Begin
ClearHandle;
Change;
FWeight := Value;
End;
End;
Procedure TFslFont.SetTextRotation(Const Value: TFslGraphicAngle);
Begin
If FTextRotation <> Value Then
Begin
ClearHandle;
Change;
FTextRotation := Value;
End;
End;
Procedure TFslFont.ClearStyles;
Begin
Weight := afwNormal;
Italic := False;
Underline := False;
StrikeOut := False;
End;
Procedure TFslFont.Clear;
Begin
Inherited;
FName := '';
FFamily := affDontCare;
FPitch := afpDontCare;
FCharRotation := 0;
FTextRotation := 0;
FColour := clBlack;
FWeight := afwNormal;
FSize := 10;
FItalic := False;
FUnderline := False;
FStrikeOut := False;
End;
Function TFslFont.CreateHandle: TFslGraphicHandle;
Begin
Result := MakeHandle(Capability.PixelsPerInchY);
End;
Function TFslFont.MakeHandle(iPixelsPerInchY : Integer): TFslGraphicHandle;
Var
aFont : TLogFont;
Begin
FillChar(aFont, SizeOf(TLogFont), 0);
aFont.lfHeight := -MulDiv(FSize, iPixelsPerInchY, 72);
aFont.lfWidth := 0; // leave to font mapper
aFont.lfEscapement := FTextRotation * 10;
aFont.lfOrientation := (FTextRotation + FCharRotation) * 10;
aFont.lfWeight := ADVFONTWEIGHT_VALUES[FWeight];
aFont.lfItalic := Byte(FItalic);
aFont.lfUnderline := Byte(FUnderline);
aFont.lfStrikeOut := Byte(FStrikeOut);
aFont.lfCharSet := DEFAULT_CHARSET;
aFont.lfOutPrecision := OUT_DEFAULT_PRECIS;
aFont.lfClipPrecision := CLIP_DEFAULT_PRECIS;
aFont.lfQuality := DEFAULT_QUALITY;
aFont.lfPitchAndFamily := ADVFONTPITCH_VALUES[FPitch] + ADVFONTFAMILY_VALUES[FFamily];
If FName <> '' Then
Move(FName[1], aFont.lfFaceName, IntegerMin(LF_FACESIZE, Length(FName)));
Result := CreateFontIndirect(aFont);
If Result = 0 Then
RaiseError('CreateHandle', ErrorAsString);
End;
Procedure TFslFont.SetVCLFont(oFont: TFont);
Var
aStyle : TFontStyles;
Begin
oFont.Color := FColour;
oFont.Name := FName;
oFont.Pitch := ADVFONTPITCH_VCLMAP[FPitch];
oFont.Size := FSize;
aStyle := [];
If Weight >= afwSemiBold Then
Include(aStyle, fsBold);
If Italic Then
Include(aStyle, fsItalic);
If Underline Then
Include(aStyle, fsUnderline);
If StrikeOut Then
Include(aStyle, fsStrikeOut);
oFont.Style := aStyle;
End;
Function TFslFont.GetBold: Boolean;
Begin
Result := Weight >= afwSemiBold;
End;
Procedure TFslFont.SetBold(Const Value: Boolean);
Begin
If Value Then
Weight := afwBold
Else
Weight := afwNormal;
End;
Function TFslFont.GetWeightAsString: String;
Begin
Result := ADVFONTWEIGHT_NAMES[Weight];
End;
Procedure TFslFont.SetWeightAsString(Const Value: String);
Var
iIndex : Integer;
Begin
iIndex := StringArrayIndexOf(ADVFONTWEIGHT_NAMES, Value);
If iIndex < 0 Then
RaiseError('SetWeightAsString', StringFormat('Font Weight ''%s'' not recognised.', [Value]));
Weight := TFslFontWeight(iIndex);
End;
Function TFslMetafile.HandleClass : TGraphicClass;
Begin
Result := TMetafile;
End;
Function TFslMetafile.HandleNew: TGraphic;
Begin
Result := TMetafile.Create; // Because TGraphicClass.Create is not a virtual method.
End;
Function TFslMetafile.GetHandle: TMetafile;
Begin
Result := TMetafile(Inherited Handle);
End;
Procedure TFslMetafile.SetHandle(Const Value: TMetafile);
Begin
Inherited Handle := Value;
End;
Function TFslMetafileList.GetGraphic(iIndex: Integer): TFslMetafile;
Begin
Result := TFslMetafile(ObjectByIndex[iIndex]);
End;
Function TFslMetafileList.ItemClass: TFslObjectClass;
Begin
Result := TFslMetafile;
End;
Function Rect(iLeft, iTop, iRight, iBottom : Integer) : TRect;
Begin
Result.Left := iLeft;
Result.Top := iTop;
Result.Right := iRight;
Result.Bottom := iBottom;
End;
Procedure RectZero(Var aRect : TRect);
Begin
SetRectEmpty(Windows.TRect(aRect));
End;
Function RectZero : TRect;
Begin
RectZero(Result);
End;
Function RectEmpty(Const aRect : TRect) : Boolean;
Begin
Result := Windows.IsRectEmpty(Windows.TRect(aRect));
End;
Function RectEqual(Const A, B : TRect) : Boolean;
Begin
Result := Windows.EqualRect(Windows.TRect(A), Windows.TRect(B));
End;
Function RectOffset(Const aRect : TRect; iX, iY : Integer) : TRect;
Begin
Result := aRect;
OffsetRect(Windows.TRect(Result), iX, iY);
End;
Function RectIntersect(Const A, B : TRect) : TRect;
Begin
Windows.IntersectRect(Windows.TRect(Result), Windows.TRect(A), Windows.TRect(B));
End;
Function RectSubtract(Const A, B : TRect) : TRect;
Begin
Windows.SubtractRect(Windows.TRect(Result), Windows.TRect(A), Windows.TRect(B));
End;
Function RectUnion(Const A, B : TRect) : TRect;
Begin
Windows.UnionRect(Windows.TRect(Result), Windows.TRect(A), Windows.TRect(B));
End;
Function RectHasIntersection(Const A, B : TRect) : Boolean;
Var
aTemp : Windows.TRect;
Begin
Result := Windows.IntersectRect(aTemp, Windows.TRect(A), Windows.TRect(B));
End;
Function RectInflate(Const aRect : TRect; iValue : Integer) : TRect;
Begin
Result := RectInflate(aRect, iValue, iValue);
End;
Function RectInflate(Const aRect : TRect; iX, iY : Integer) : TRect;
Begin
Result := aRect;
Windows.InflateRect(Windows.TRect(Result), iX, iY);
End;
Function RectWidth(Const aRect : TRect) : Integer;
Begin
Result := aRect.Right - aRect.Left;
End;
Function RectHeight(Const aRect : TRect) : Integer;
Begin
Result := aRect.Bottom - aRect.Top;
End;
Function RectHit(Const aRect : TRect; Const aPoint : TPoint) : Boolean;
Begin
Result := Windows.PtInRect(Windows.TRect(aRect), Windows.TPoint(aPoint));
End;
Function RectBound(Const aRect, aBoundary : TRect) : TRect;
Begin
Result.Left := IntegerMax(aRect.Left, aBoundary.Left);
Result.Top := IntegerMax(aRect.Top, aBoundary.Top);
Result.Right := IntegerMin(aRect.Right, aBoundary.Right);
Result.Bottom := IntegerMin(aRect.Bottom, aBoundary.Bottom);
End;
Type
TFslIcon = Class(TIcon)
Private
FMaximumHeight : Integer;
FMaximumWidth : Integer;
Protected
Function GetHeight : Integer; Override;
Procedure SetHeight(Value : Integer); Override;
Function GetWidth : Integer; Override;
Procedure SetWidth(Value : Integer); Override;
End;
Function TFslIcon.GetHeight : Integer;
Begin
Result := FMaximumHeight;
If Result = 0 Then
Result := Inherited GetHeight;
End;
Procedure TFslIcon.SetHeight(Value : Integer);
Begin
FMaximumHeight := Value;
Inherited;
End;
Function TFslIcon.GetWidth : Integer;
Begin
Result := FMaximumWidth;
If Result = 0 Then
Result := Inherited GetWidth;
End;
Procedure TFslIcon.SetWidth(Value : Integer);
Begin
FMaximumWidth := Value;
Inherited;
End;
Function TFslIconGraphic.HandleClass : TGraphicClass;
Begin
Result := TFslIcon;
End;
Function TFslIconGraphic.Link : TFslIconGraphic;
Begin
Result := TFslIconGraphic(Inherited Link);
End;
Procedure TFslIconGraphic.SetMaximumDimensions(Const iWidth, iHeight : Integer);
Begin
// Cannot set width and height with an active icon loaded.
Icon.Handle := 0;
Icon.Width := iWidth;
Icon.Height := iHeight;
End;
Procedure TFslIconGraphic.LoadFromResource(Const sResourceName : String);
Begin
Icon.Handle := LoadImage(HInstance, PChar(sResourceName), IMAGE_ICON, Icon.Width, Icon.Height, LR_MONOCHROME);
End;
Function TFslIconGraphic.GetIcon : TIcon;
Begin
Result := TIcon(Inherited Handle);
End;
Procedure TFslIconGraphic.SetIcon(Const Value : TIcon);
Begin
Inherited Handle := Value;
End;
end.
|
{@unit RLUtils - Rotinas de uso geral. }
unit RLUtils;
interface
{$WARN SYMBOL_PLATFORM OFF}
uses
SysUtils, Classes, Math, Windows, Types, Graphics, Forms;
{@var TempDir - Especifica aonde deverão ser criados os arquivos temporários.
Na inicialização do sistema é atribuido um valor padrão a esta variável. Este valor pode ser alterado depois.
No Windows o diretório padrão é "WINDOWS\TEMP", e no Linux é o "/tmp".
@links GetTempFileName. :/}
var TempDir:String='.';
{@proc FreeObj - Libera objeto se não for nil e em seguida limpa a variável.
@links FreePtr. :/}
procedure FreeObj(var aObj);
{@proc FreePtr - Libera ponteiro se não for nil e em seguida limpa a variável.
@links FreeObj. :/}
procedure FreePtr(var aPtr);
{@func ByteToHex - Retorna o byte em notação hexadecimal de dois dígitos.
@links HexToByte. :/}
function ByteToHex(const aByte:byte):AnsiString;
{@func HexToByte - Retorna o valor hexadecimal como byte.
@links ByteToHex. :/}
function HexToByte(const aHex:AnsiString):byte;
{@func HexToBitmap - Cria bitmap a partir de uma cadeia hexadecimal.
@links HexToGraphic, HexToByte. :/}
function HexToBitmap(const aHex:AnsiString):TBitmap;
{@func HexToGraphic - Cria um gráfico qualquer a partir de uma cadeia hexadecimal.
@links HexToBitmap, HexToByte. :/}
function HexToGraphic(const aHex:AnsiString):TGraphic;
{@func NewComponentName - Cria um nome para um novo componente. :/}
function NewComponentName(aComponent:TComponent):AnsiString;
{@func GetTempFileName - Retorna nome de arquivo temporário.
@links TempDir. :/}
function GetTempFileName:String;
{@func Token - Retorna a parte de número aIndex da string aTokenList cujas partes são separadas pelo caractere aTokenSeparator. :/}
function Token(const aTokenList:AnsiString; aIndex:integer; aTokenSeparator:AnsiChar='|'):AnsiString;overload;
function Token(const aTokenList:String; aIndex:integer; aTokenSeparator:AnsiChar='|'):String;overload;
{@func ThreadIt - Executa um método ou procedure em segundo plano. :}
function ThreadIt(aMethod:TThreadMethod; aLoop:boolean=false):TThread; overload;
function ThreadIt(aProc:TProcedure; aLoop:boolean=false):TThread; overload;
{/@func}
{@func FormatFileExt - Adiciona ponto a uma extensão, se não houver. :/}
function FormatFileExt(const aExt:String):String;
{@func AddFileFilter - Adiciona filtro de arquivos com nome aFilter, descrição aDescription e extensão padrão aExt. :/}
function AddFileFilter(const aFilter, aDescription, aExt:String):String;
{@func GetFileFilterExt - Devolve a extensão padrão para arquivos correspondentes ao filtro aFilter. :/}
function GetFileFilterExt(const aFilter:AnsiString; aIndex:integer):String;
{@func RotatePoints - Rotaciona os pontos aPoints em 2D de acordo com o ângulo aAngle.
@links RotateBitmap. :/}
procedure RotatePoints(var aPoints:array of TPoint; const aAngle:double);
{@func RotateBitmap - Rotaciona o bitmap TBitmap em 2D de acordo com o ângulo aAngle e devolve em aDest.
Nota: O bitmap aDest deve ter tamanho suficiente para a imagem rotacionada. Este cálculo pode ser feito
previamente com a proc RotatePoints.
@links RotatePoints, RotatedBitmap. :/}
procedure RotateBitmap(aSource,aDest:TBitmap; aAngle:double; aAxis,aOffset:TPoint);
{@func RotatedBitmap - Cria e devolve um bitmap compatível com o bitmap aSource rotacionado em 2D de acordo com o ângulo aAngle com
tamanho calculado.
@links RotateBitmap. :/}
function RotatedBitmap(aSource:TBitmap; aAngle:double):TBitmap;
{@func PointsRect - Retorna um retângulo delimitando a área definida pelos pontos aPoints.
@links PointsSize. :/}
function PointsRect(const aPoints:array of TPoint):TRect;
{@func PointsSize - Retorna o tamanho da área definida pelos pontos aPoints.
@links PointsRect. :/}
function PointsSize(const aPoints:array of TPoint):TPoint;
{@func ScalePoints - Modifica as dimensões dos pontos aPoints para que caibam no retângulo definido por aRect respeitando a proporção.
@links PointsRect. :/}
procedure ScalePoints(var aPoints:array of TPoint; const aRect:TRect);
{@func StretchPoints - Amplia ou reduz as dimensões dos pontos aPoints para que caibam no retângulo definido por aRect.
@links PointsRect. :/}
procedure StretchPoints(var aPoints:array of TPoint; const aRect:TRect);
{@func CenterPoints - Centraliza os pontos aPoints no retâgulo aRect.
@links PointsRect. :/}
procedure CenterPoints(var aPoints:array of TPoint; const aRect:TRect);
{@func TextBounds - Calcula as dimensões do texto aText de acordo com a fonte aFont e opcionalmente rotacionado em
2D de acordo com o ângulo aAngle.
@links PointsRect. :/}
function TextBounds(const aText:AnsiString; aFont:TFont; aAngle:double):TPoint;
{@proc MoveRect - Desloca o retângulo horizontalmente de acordo com aX e verticalmente de acordo com aY.
Nota: Valores positivos deslocam o retângulo para a direita ou abaixo. :/}
procedure MoveRect(var aRect:TRect; aX,aY:integer);
{@func RectWidth - Retorna a largura do retângulo aRect.
@links RectHeight. :/}
function RectWidth(const aRect:TRect):integer;
{@func RectHeight - Retorna a largura do retângulo aRect.
@links RectWidth. :/}
function RectHeight(const aRect:TRect):integer;
{@func ReduceRect - Retorna o retângulo aRect reduzido de acordo com os decrementos especificados em aPixels. :/}
function ReduceRect(const aRect:TRect; aPixels:TRect):TRect;
{@func IncreaseRect - Retorna o retângulo aRect ampliado de acordo com os incrementos especificados em aPixels. :/}
function IncreaseRect(const aRect:TRect; aPixels:TRect):TRect;
{@func DiffRect - Retorna a diferença entre os retângulos aRectOut e aRectIn, desde que aRectIn esteja dentro
de aRectOut. :/}
function DiffRect(const aRectOut,aRectIn:TRect):TRect;
{@func IterateJustification - Faz a justificação do texto distribuindo espaços. A função deve ser executada até
se obter a largura total do texto. :/}
function IterateJustification(var aText:AnsiString; var aIndex:integer):boolean;
{@func ScaleRect - Calcula a maior amostra do retângulo aSource escalonado de modo a caber em aTarget. :/}
function ScaleRect(const aSource,aTarget:TRect; aCenter:boolean):TRect;
procedure StreamWrite(aStream:TStream; const aStr:AnsiString);
procedure StreamWriteLn(aStream:TStream; const aStr:AnsiString='');
{@proc RegisterTempFile - Registra um arquivo temporário para ser excluído na finalização. :/}
procedure RegisterTempFile(const aFileName:String);
{@proc UnregisterTempFile - Retira arquivo temporário da lista de arquivos a excluir na finalizacão. :/}
procedure UnregisterTempFile(const aFileName:String);
{@proc ClearTempFiles - Destroi arquivos temporários registrados pela proc RegisterTempFile. :/}
procedure ClearTempFiles;
procedure CRC16Add(var Result:word; Data:AnsiChar);
function CRC16(const Data; DataLen:integer):word; overload;
function CRC16(const Str:AnsiString):word; overload;
function CRC16(Stream:TStream):word; overload;
var
LogFileName:String='rlib.log';
procedure LogClear;
procedure Log(const aMsg:String);
type
{$ifdef KYLIX}
TRGBQuad=packed record
rgbBlue :byte;
rgbGreen :byte;
rgbRed :byte;
rgbReserved:byte;
end;
{$endif}
TRGBArray=array[0..0] of TRGBQuad;
PRGBArray=^TRGBArray;
{$ifdef KYLIX}
function RGB(r, g, b: Byte): TColor;
{$endif}
function NeedAuxBitmap: TBitmap;
function NewBitmap: TBitmap; overload;
function NewBitmap(Width, Height: Integer): TBitmap; overload;
{/@unit}
type
TRLBitmap = class(TBitmap)
end;
implementation
function NewBitmap: TBitmap;
begin
Result := NewBitmap(1, 1);
end;
function NewBitmap(Width, Height: Integer): TBitmap;
begin
Result := TBitmap.Create;
Result.Width := Width;
Result.Height := Height;
Result.PixelFormat := pf32bit;
end;
var
AuxBitmap: TBitmap;
function NeedAuxBitmap: TBitmap;
begin
if AuxBitmap = nil then
begin
AuxBitmap := TRLBitmap.Create;
AuxBitmap.Width := 1;
AuxBitmap.Height := 1;
end;
Result := AuxBitmap;
end;
procedure LogClear;
begin
if FileExists(LogFileName) then
SysUtils.DeleteFile(LogFileName);
end;
procedure Log(const aMsg:String);
var
loghandle:textfile;
begin
AssignFile(loghandle,LogFileName);
if FileExists(LogFileName) then
Append(loghandle)
else
Rewrite(loghandle);
WriteLn(loghandle,TimeToStr(Time)+': '+aMsg);
CloseFile(loghandle);
end;
type
dw=record
h,l:word;
end;
const
HEXDIGITS:String[16]='0123456789ABCDEF';
function ByteToHex(const aByte:byte):AnsiString;
begin
Result:=HEXDIGITS[(aByte and $f0) shr 4+1]+HEXDIGITS[(aByte and $0f)+1];
end;
function HexToByte(const aHex:AnsiString):byte;
begin
Result:=(Pos(UpCase(aHex[1]),HEXDIGITS)-1)*16+Pos(UpCase(aHex[2]),HEXDIGITS)-1;
end;
procedure FreeObj(var aObj);
begin
if assigned(TObject(aObj)) then
TObject(aObj).free;
TObject(aObj):=nil;
end;
procedure FreePtr(var aPtr);
begin
if assigned(pointer(aPtr)) then
FreeMem(pointer(aPtr));
pointer(aPtr):=nil;
end;
{$ifdef KYLIX}
function RGB(r, g, b: Byte): TColor;
begin
Result := (r or (g shl 8) or (b shl 16));
end;
{$endif}
type
TPublicGraphic=class(TGraphic)
end;
function HexToBitmap(const aHex:AnsiString):TBitmap;
var
stream:TStringStream;
i,l :integer;
begin
stream:=TStringStream.Create('');
try
// traduz string hex em binária
l:=Length(aHex);
i:=1;
while i<l do
begin
stream.WriteString(String(AnsiChar(HexToByte(aHex[i]+aHex[i+1])))); //bds2010
inc(i,2);
end;
// procura referência para a classe
Result:=TBitmap.Create;
try
stream.Seek(0,0);
TPublicGraphic(Result).ReadData(stream);
except
FreeObj(Result);
raise;
end;
finally
FreeObj(stream);
end;
end;
function HexToGraphic(const aHex:AnsiString):TGraphic;
var
graphclassname:String[63];
graphclass :TGraphicClass;
stream :TStringStream;
i,l :integer;
begin
Result:=nil;
stream:=TStringStream.Create('');
try
// traduz string hex em binária
l:=Length(aHex);
i:=1;
while i<l do
begin
stream.WriteString(String(AnsiChar(HexToByte(aHex[i]+aHex[i+1]))));//bds2010
inc(i,2);
end;
// pega o nome da classe
stream.Seek(0,0);
stream.Read(graphclassname[0],1);
stream.Read(graphclassname[1],byte(graphclassname[0]));
// procura referência para a classe
graphclassname:=AnsiString(UpperCase(String(graphclassname)));//bds2010
if graphclassname='TBITMAP' then
graphclass:=TBitmap
else if graphclassname='TICON' then
graphclass:=TIcon
else
graphclass:=nil;
// instancia e carrega o grafico
if graphclass<>nil then
begin
Result:=graphclass.Create;
try
TPublicGraphic(Result).ReadData(stream);
except
FreeObj(Result);
raise;
end;
end;
finally
FreeObj(stream);
end;
end;
// diretório temporário
function GetTempDir:String;
{$ifndef LINUX}
var
p:array[0..255] of Char;
h:String;
{$endif}
begin
{$ifndef LINUX}
GetDir(0,h); // salva diretório atual
GetWindowsDirectory(@p,256); // diretório do windows
ChDir(strpas(p));
try
GetTempPath(256,@p);
Result:=strpas(p);
finally
ChDir(h);
end;
{$else}
Result:='/tmp';
{$endif}
end;
function NewComponentName(aComponent:TComponent):AnsiString;
var
p,n:String; //bds2010
i,m:integer;
begin
p:=aComponent.ClassName;
if UpperCase(p[1])='T' then
delete(p,1,1);
m:=0;
for i:=0 to aComponent.Owner.ComponentCount-1 do
begin
n:=aComponent.Owner.Components[i].Name;
if AnsiSameText(Copy(n,1,Length(p)),p) then
m:=Max(m,StrToIntDef(Copy(n,Length(p)+1,Length(n)),0));
end;
Result:=AnsiString(p+IntToStr(m+1));//bds2010
end;
function GetTempFileName:String;
var
tmppath:String;
begin
Randomize;
tmppath:=TempDir;
if tmppath<>'' then
tmppath:=IncludeTrailingBackslash(tmppath);
repeat
Result:=tmppath+'~fr'+IntToStr(Random(MaxInt))+'.tmp';
until not FileExists(Result);
end;
function Token(const aTokenList:AnsiString; aIndex:integer; aTokenSeparator:AnsiChar='|'):AnsiString;
var
i,m,count:integer;
begin
Result:='';
count:=0;
i:=1;
while i<=Length(aTokenList) do
begin
m:=i;
while (i<=Length(aTokenList)) and (aTokenList[i]<>aTokenSeparator) do
inc(i);
inc(count);
if count=aIndex then
begin
Result:=Copy(aTokenList,m,i-m);
break;
end;
inc(i);
end;
end;
function Token(const aTokenList:String; aIndex:integer; aTokenSeparator:AnsiChar='|'):String;
begin
Result := String(Token(AnsiString(aTokenList), aIndex, aTokenSeparator));
end;
type
TInternalThread=class(TThread)
protected
fMethod:TThreadMethod;
fProc :TProcedure;
fLoop :boolean;
//
procedure Execute; override;
//
procedure Call;
public
constructor Create(aMethod:TThreadMethod; aLoop:boolean); overload;
constructor Create(aProc:TProcedure; aLoop:boolean); overload;
end;
constructor TInternalThread.Create(aMethod:TThreadMethod; aLoop:boolean);
begin
FreeOnTerminate:=true;
fMethod :=aMethod;
fProc :=nil;
fLoop :=aLoop;
//
inherited Create(false);
end;
constructor TInternalThread.Create(aProc:TProcedure; aLoop:boolean);
begin
FreeOnTerminate:=true;
fMethod :=nil;
fProc :=aProc;
fLoop :=aLoop;
//
inherited Create(false);
end;
procedure TInternalThread.Call;
begin
while fLoop and not Terminated do
begin
if assigned(@fProc) then
fProc;
if assigned(@fMethod) then
fMethod;
end;
end;
procedure TInternalThread.Execute;
begin
Synchronize(Call);
end;
function ThreadIt(aMethod:TThreadMethod; aLoop:boolean=false):TThread;
begin
Result:=TInternalThread.Create(aMethod,aLoop);
end;
function ThreadIt(aProc:TProcedure; aLoop:boolean=false):TThread;
begin
Result:=TInternalThread.Create(aProc,aLoop);
end;
function FormatFileExt(const aExt:String):String;
begin
if (aExt<>'') and (aExt[1]<>'.') then
Result:='.'+aExt
else
Result:=aExt;
end;
function AddFileFilter(const aFilter,aDescription, aExt:String):String;
begin
Result:=aFilter;
if Result<>'' then
Result:=Result+'|';
Result:=Result+aDescription+' (*'+FormatFileExt(aExt)+')';
{$ifdef VCL}
Result:=Result+'|*'+FormatFileExt(aExt);
{$else} {$ifdef DELPHI7}
Result:=Result+'|*'+FormatFileExt(aExt);
{$endif}
{$endif}
end;
function GetFileFilterExt(const aFilter:AnsiString; aIndex:integer):String;
var
p,i:integer;
m:String;
begin
if aIndex=0 then
aIndex:=1;
i:=1;
while i<=aIndex do
begin
m:=String(Token(aFilter,i,'|'));//bds2010
p:=Pos('(',m);
if p>0 then
delete(m,1,p);
p:=Pos(')',m);
if p>0 then
m:=Copy(m,1,p-1);
inc(i);
{$ifdef VCL}
inc(i);
{$else} {$ifdef DELPHI7}
inc(i);
{$endif}
{$endif}
end;
p:=Pos('.',m);
if p>0 then
delete(m,1,p);
Result:=FormatFileExt(m);
end;
procedure RotatePoints(var aPoints:array of TPoint; const aAngle:double);
var
theta :double;
costheta:double;
sintheta:double;
center :TPoint;
i,q :integer;
procedure RotatePoint(var aPoint:TPoint);
var
saved:TPoint;
begin
saved :=aPoint;
aPoint.x:=round(saved.x*costheta-saved.y*sintheta);
aPoint.y:=round(saved.x*sintheta+saved.y*costheta);
end;
begin
theta :=-aAngle*pi/180; // radians
sintheta:=sin(theta);
costheta:=cos(theta);
// calcula centro
center.x:=0;
center.y:=0;
q:=High(aPoints)+1;
for i:=0 to q-1 do
begin
inc(center.x,aPoints[i].x);
inc(center.y,aPoints[i].y);
end;
center.x:=round(center.x/q);
center.y:=round(center.y/q);
// roda
for i:=0 to q-1 do
begin
dec(aPoints[i].x,center.x);
dec(aPoints[i].y,center.y);
RotatePoint(aPoints[i]);
inc(aPoints[i].x,center.x);
inc(aPoints[i].y,center.y);
end;
end;
procedure RotateBitmap(aSource,aDest:TBitmap; aAngle:double; aAxis,aOffset:TPoint);
type
{$ifdef KYLIX}
TRGBQuad=packed record
rgbBlue :byte;
rgbGreen :byte;
rgbRed :byte;
rgbReserved:byte;
end;
{$endif}
PRGBArray=^TRGBArray;
TRGBArray=array[0..0] of TRGBQuad;
const
RGBBlack:TRGBQuad=(rgbBlue:0; rgbGreen:0; rgbRed:0; rgbReserved:0);
var
x :integer;
xDest :integer;
xOriginal :integer;
xPrime :integer;
xPrimeRotated:integer;
//
y :integer;
yDest :integer;
yOriginal :integer;
yPrime :integer;
yPrimeRotated:integer;
//
RowSource :PRGBArray;
RowDest :PRGBArray;
//
Radians :double;
RadiansCos :double;
RadiansSin :double;
begin
// Convert degrees to radians. Use minus sign to force clockwise rotation.
Radians :=aAngle*PI/180;
RadiansSin:=sin(Radians);
RadiansCos:=cos(Radians);
// Step through each row of rotated image.
for y:=0 to aDest.Height-1 do
begin
RowDest:=aDest.ScanLine[y];
yDest :=y-aOffset.y;
yPrime :=2*(yDest-aAxis.y)+1; // center y: -1,0,+1
// Step through each col of rotated image.
for x:=0 to aDest.Width-1 do
begin
xDest :=x-aOffset.x;
xPrime:=2*(xDest-aAxis.x)+1; // center x: -1,0,+1
// Rotate (xPrime, yPrime) to location of desired pixel
// Note: There is negligible difference between floating point and scaled integer arithmetic here, so keep the math simple (and readable).
xPrimeRotated:=round(xPrime*RadiansCos-yPrime*RadiansSin);
yPrimeRotated:=round(xPrime*RadiansSin+yPrime*RadiansCos);
// Transform back to pixel coordinates of image, including translation
// of origin from axis of rotation to origin of image.
xOriginal:=(xPrimeRotated-1) div 2+aAxis.x;
yOriginal:=(yPrimeRotated-1) div 2+aAxis.y;
// Make sure (xOriginal, yOriginal) is in aSource. If not, assign blue color to corner points.
if (xOriginal>=0) and (xOriginal<=aSource.Width-1) and (yOriginal>=0) and (yOriginal<=aSource.Height-1) then
begin
// Assign pixel from rotated space to current pixel in aDest
RowSource :=aSource.ScanLine[yOriginal];
RowDest[x]:=RowSource[xOriginal];
end
else if aSource.Height>0 then
begin
RowSource :=aSource.ScanLine[0];
RowDest[x]:=RowSource[0];
end
else
RowDest[x]:=RGBBlack;
end;
end;
end;
function RotatedBitmap(aSource:TBitmap; aAngle:double):TBitmap;
var
p:array[0..3] of TPoint;
r:TRect;
begin
p[0]:=Point(0,0);
p[1]:=Point(aSource.Width-1,0);
p[2]:=Point(aSource.Width-1,aSource.Height-1);
p[3]:=Point(0,aSource.Height-1);
RotatePoints(p,aAngle);
r:=PointsRect(p);
//
Result:=TBitmap.Create;
try
Result.PixelFormat :=pf32bit;
Result.Width :=r.Right-r.Left;
Result.Height :=r.Bottom-r.Top;
Result.Transparent :=aSource.Transparent;
Result.TransparentColor:=aSource.TransparentColor;
Result.TransparentMode :=aSource.TransparentMode;
RotateBitmap(aSource,Result,aAngle,Point(aSource.Width div 2,aSource.Height div 2),Point(-r.Left,-r.Top));
except
Result.free;
raise;
end;
end;
function PointsRect(const aPoints:array of TPoint):TRect;
var
i:integer;
begin
for i:=0 to High(aPoints) do
if i=0 then
begin
Result.Left :=aPoints[i].x;
Result.Top :=aPoints[i].y;
Result.Right :=aPoints[i].x;
Result.Bottom:=aPoints[i].y;
end
else
begin
Result.Left :=Min(Result.Left ,aPoints[i].x);
Result.Top :=Min(Result.Top ,aPoints[i].y);
Result.Right :=Max(Result.Right ,aPoints[i].x);
Result.Bottom:=Max(Result.Bottom,aPoints[i].y);
end;
end;
function PointsSize(const aPoints:array of TPoint):TPoint;
begin
with PointsRect(aPoints) do
begin
Result.x:=Right-Left;
Result.y:=Bottom-Top;
end;
end;
procedure ScalePoints(var aPoints:array of TPoint; const aRect:TRect);
var
bounds:TRect;
fx,fy :double;
i,len :integer;
begin
bounds:=PointsRect(aPoints);
if RectWidth(bounds)<>0 then
fx:=RectWidth(aRect)/RectWidth(bounds)
else
fx:=0;
if RectHeight(bounds)<>0 then
fy:=RectHeight(aRect)/RectHeight(bounds)
else
fy:=0;
if fx=0 then
fx:=fy;
if fy=0 then
fy:=fx;
if (fx=0) or (fy=0) then
Exit;
if fx<fy then
fy:=fx
else
fx:=fy;
len:=High(aPoints)+1;
for i:=0 to len-1 do
with aPoints[i] do
begin
x:=Round((x-bounds.Left)*fx)+aRect.Left;
y:=Round((y-bounds.Top)*fy)+aRect.Top;
end;
end;
procedure StretchPoints(var aPoints:array of TPoint; const aRect:TRect);
var
bounds:TRect;
fx,fy :double;
i,len :integer;
begin
bounds:=PointsRect(aPoints);
if RectWidth(bounds)<>0 then
fx:=RectWidth(aRect)/RectWidth(bounds)
else
fx:=0;
if RectHeight(bounds)<>0 then
fy:=RectHeight(aRect)/RectHeight(bounds)
else
fy:=0;
if fx=0 then
fx:=1;
if fy=0 then
fy:=1;
if (fx=0) or (fy=0) then
Exit;
len:=High(aPoints)+1;
for i:=0 to len-1 do
with aPoints[i] do
begin
x:=Round((x-bounds.Left)*fx)+aRect.Left;
y:=Round((y-bounds.Top)*fy)+aRect.Top;
end;
end;
procedure CenterPoints(var aPoints:array of TPoint; const aRect:TRect);
var
bounds :TRect;
ofx,ofy:integer;
i,len :integer;
begin
bounds:=PointsRect(aPoints);
ofx :=(RectWidth(aRect)-RectWidth(bounds)) div 2;
ofy :=(RectHeight(aRect)-RectHeight(bounds)) div 2;
len :=High(aPoints)+1;
for i:=0 to len-1 do
with aPoints[i] do
begin
x:=x-bounds.Left+aRect.Left+ofx;
y:=y-bounds.Top+aRect.Top+ofy;
end;
end;
function TextBounds(const aText:AnsiString; aFont:TFont; aAngle:double):TPoint;
var
b:TBitmap;
p:array[0..3] of TPoint;
begin
b:=TBitmap.Create;
try
b.Width :=1;
b.Height:=1;
b.Canvas.Font.Assign(aFont);
Result.x:=b.Canvas.TextWidth(String(aText));//bds2010
Result.y:=b.Canvas.TextHeight(String(aText));//bds2010
if aAngle<>0 then
begin
p[0]:=Point(0,0);
p[1]:=Point(Result.x,0);
p[2]:=Point(Result.x,Result.y);
p[3]:=Point(0,Result.y);
RotatePoints(p,aAngle);
Result:=PointsSize(p);
end;
finally
b.free;
end;
end;
procedure MoveRect(var aRect:TRect; aX,aY:integer);
begin
OffsetRect(aRect,-aRect.Left+aX,-aRect.Top+aY);
end;
function RectWidth(const aRect:TRect):integer;
begin
Result:=aRect.Right-aRect.Left;
end;
function RectHeight(const aRect:TRect):integer;
begin
Result:=aRect.Bottom-aRect.Top;
end;
function ReduceRect(const aRect:TRect; aPixels:TRect):TRect;
begin
Result.Left :=aRect.Left +aPixels.Left;
Result.Top :=aRect.Top +aPixels.Top;
Result.Right :=aRect.Right -aPixels.Right;
Result.Bottom:=aRect.Bottom-aPixels.Bottom;
end;
function IncreaseRect(const aRect:TRect; aPixels:TRect):TRect;
begin
Result.Left :=aRect.Left -aPixels.Left;
Result.Top :=aRect.Top -aPixels.Top;
Result.Right :=aRect.Right +aPixels.Right;
Result.Bottom:=aRect.Bottom+aPixels.Bottom;
end;
function DiffRect(const aRectOut,aRectIn:TRect):TRect;
begin
Result.Left :=aRectIn.Left +aRectOut.Left;
Result.Top :=aRectIn.Top +aRectOut.Top;
Result.Right :=aRectOut.Right -aRectIn.Right;
Result.Bottom:=aRectOut.Bottom-aRectIn.Bottom;
end;
function IterateJustification(var aText:AnsiString; var aIndex:integer):boolean;
function FindSpc:boolean;
const
SPC=[#32,#9,#13,#10];
begin
Result:=false;
while (aIndex>0) and (aText[aIndex] in SPC) do
Dec(aIndex);
while aIndex>0 do
if aText[aIndex] in SPC then
begin
while (aIndex>0) and (aText[aIndex] in SPC) do
Dec(aIndex);
if aIndex>0 then
begin
Insert(#32,aText,aIndex+1);
Result:=true;
end;
break;
end
else
Dec(aIndex);
end;
begin
Result:=FindSpc;
if not Result then
begin
aIndex:=Length(aText);
Result:=FindSpc;
end;
end;
function ScaleRect(const aSource,aTarget:TRect; aCenter:boolean):TRect;
var
sw,sh,tw,th,w,h:integer;
fw,fh:double;
begin
sw:=aSource.Right-aSource.Left;
sh:=aSource.Bottom-aSource.Top;
tw:=aTarget.Right-aTarget.Left;
th:=aTarget.Bottom-aTarget.Top;
// calcula o maior dos fatores de proporção entre largura e altura
fw:=tw/sw;
fh:=th/sh;
if fw>fh then
begin
h:=th;
w:=round(h*sw/sh);
end
else
begin
w:=tw;
h:=round(w*sh/sw);
end;
Result.Left :=aTarget.Left;
Result.Top :=aTarget.Top;
Result.Right :=Result.Left+w;
Result.Bottom:=Result.Top+h;
if aCenter then
OffsetRect(Result,(tw-w) div 2,(th-h) div 2);
end;
procedure StreamWrite(aStream:TStream; const aStr:AnsiString);
begin
if aStr<>'' then
aStream.Write(aStr[1],Length(aStr));
end;
procedure StreamWriteLn(aStream:TStream; const aStr:AnsiString='');
begin
StreamWrite(aStream,aStr);
StreamWrite(aStream,#13#10);
end;
var
TempFileNames:TStringList=nil;
procedure RegisterTempFile(const aFileName:String);
begin
if not Assigned(TempFileNames) then
TempFileNames:=TStringList.Create;
TempFileNames.Add(aFileName);
end;
procedure UnregisterTempFile(const aFileName:String);
var
i:integer;
begin
if Assigned(TempFileNames) then
begin
i:=TempFileNames.IndexOf(aFileName);
if i<>-1 then
TempFileNames.Delete(i);
end;
end;
procedure ClearTempFiles;
var
i:integer;
begin
if Assigned(TempFileNames) then
begin
for i:=0 to TempFileNames.Count-1 do
SysUtils.DeleteFile(TempFileNames[i]);
TempFileNames.Free;
TempFileNames:=nil;
end;
end;
const
tab:array[0..255] of word=(
$0000, $1021, $2042, $3063, $4084, $50a5, $60c6, $70e7,
$8108, $9129, $a14a, $b16b, $c18c, $d1ad, $e1ce, $f1ef,
$1231, $0210, $3273, $2252, $52b5, $4294, $72f7, $62d6,
$9339, $8318, $b37b, $a35a, $d3bd, $c39c, $f3ff, $e3de,
$2462, $3443, $0420, $1401, $64e6, $74c7, $44a4, $5485,
$a56a, $b54b, $8528, $9509, $e5ee, $f5cf, $c5ac, $d58d,
$3653, $2672, $1611, $0630, $76d7, $66f6, $5695, $46b4,
$b75b, $a77a, $9719, $8738, $f7df, $e7fe, $d79d, $c7bc,
$48c4, $58e5, $6886, $78a7, $0840, $1861, $2802, $3823,
$c9cc, $d9ed, $e98e, $f9af, $8948, $9969, $a90a, $b92b,
$5af5, $4ad4, $7ab7, $6a96, $1a71, $0a50, $3a33, $2a12,
$dbfd, $cbdc, $fbbf, $eb9e, $9b79, $8b58, $bb3b, $ab1a,
$6ca6, $7c87, $4ce4, $5cc5, $2c22, $3c03, $0c60, $1c41,
$edae, $fd8f, $cdec, $ddcd, $ad2a, $bd0b, $8d68, $9d49,
$7e97, $6eb6, $5ed5, $4ef4, $3e13, $2e32, $1e51, $0e70,
$ff9f, $efbe, $dfdd, $cffc, $bf1b, $af3a, $9f59, $8f78,
$9188, $81a9, $b1ca, $a1eb, $d10c, $c12d, $f14e, $e16f,
$1080, $00a1, $30c2, $20e3, $5004, $4025, $7046, $6067,
$83b9, $9398, $a3fb, $b3da, $c33d, $d31c, $e37f, $f35e,
$02b1, $1290, $22f3, $32d2, $4235, $5214, $6277, $7256,
$b5ea, $a5cb, $95a8, $8589, $f56e, $e54f, $d52c, $c50d,
$34e2, $24c3, $14a0, $0481, $7466, $6447, $5424, $4405,
$a7db, $b7fa, $8799, $97b8, $e75f, $f77e, $c71d, $d73c,
$26d3, $36f2, $0691, $16b0, $6657, $7676, $4615, $5634,
$d94c, $c96d, $f90e, $e92f, $99c8, $89e9, $b98a, $a9ab,
$5844, $4865, $7806, $6827, $18c0, $08e1, $3882, $28a3,
$cb7d, $db5c, $eb3f, $fb1e, $8bf9, $9bd8, $abbb, $bb9a,
$4a75, $5a54, $6a37, $7a16, $0af1, $1ad0, $2ab3, $3a92,
$fd2e, $ed0f, $dd6c, $cd4d, $bdaa, $ad8b, $9de8, $8dc9,
$7c26, $6c07, $5c64, $4c45, $3ca2, $2c83, $1ce0, $0cc1,
$ef1f, $ff3e, $cf5d, $df7c, $af9b, $bfba, $8fd9, $9ff8,
$6e17, $7e36, $4e55, $5e74, $2e93, $3eb2, $0ed1, $1ef0);
procedure CRC16Add(var Result:word; Data:AnsiChar);
begin
Result:=((Hi(tab[Hi(Result)]) xor Lo(Result)) shl 8)+(Lo(tab[Hi(Result)]) xor Byte(Data));
end;
function CRC16(const Data; DataLen:integer):word;
var
i:integer;
p:PAnsiChar;
begin
Result:=0;
p:=@Data;
for i:=0 to DataLen-1 do
CRC16Add(Result,p[i]);
end;
function CRC16(const Str:AnsiString):word;
var
len:integer;
begin
len:=Length(Str);
if len=0 then
result:=0
else
result:=CRC16(Str[1],len);
end;
function CRC16(Stream:TStream):word;
const
MaxBuffer=16384;
var
Buffer:packed array[0..MaxBuffer-1] of AnsiChar;
BufferLength,i:integer;
begin
Result:=0;
repeat
BufferLength:=Stream.Read(Buffer,MaxBuffer);
if BufferLength=0 then
Break;
for i:=0 to BufferLength-1 do
CRC16Add(Result,Buffer[i]);
until False;
end;
initialization
LogFileName:=IncludeTrailingBackslash(ExtractFilePath(ParamStr(0)))+'RLib.log';
TempDir:=GetTempDir;
AuxBitmap := nil;
LogClear;
finalization
ClearTempFiles;
FreeObj(AuxBitmap);
end.
|
unit CRWellQuickInfoViewFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, BaseObjects, CoreCollection;
type
TfrmWellSlottingInfoQuickView = class(TFrame, IVisitor)
lwProperties: TListView;
procedure lwPropertiesAdvancedCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage;
var DefaultDraw: Boolean);
procedure lwPropertiesDblClick(Sender: TObject);
private
{ Private declarations }
FFakeObject: TObject;
FActiveObject: TIDObject;
procedure AddItem(AName, AValue: string; AData: TObject);
protected
function GetActiveObject: TIDObject;
procedure SetActiveObject(const Value: TIDObject);
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
{ Public declarations }
procedure VisitWell(AWell: TIDObject);
procedure VisitGenSection(AGenSection: TIDObject);
procedure VisitTestInterval(ATestInterval: TIDObject);
procedure VisitLicenseZone(ALicenseZone: TIDObject);
procedure VisitSlotting(ASlotting: TIDObject);
procedure VisitGenSectionSlotting(ASlotting: TIDObject);
procedure VisitCollectionWell(AWell: TIDObject);
procedure VisitCollectionSample(ASample: TIDObject);
procedure VisitDenudation(ADenudation: TIDObject);
procedure VisitWellCandidate(AWellCandidate: TIDObject);
procedure Clear;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses Well, Slotting, BaseConsts, GeneralizedSection, StrViewForm;
{$R *.dfm}
type
TFakeObject = class(TObject)
end;
function TfrmWellSlottingInfoQuickView.GetActiveObject: TIDObject;
begin
Result := FActiveObject;
end;
procedure TfrmWellSlottingInfoQuickView.lwPropertiesAdvancedCustomDrawItem(
Sender: TCustomListView; Item: TListItem; State: TCustomDrawState;
Stage: TCustomDrawStage; var DefaultDraw: Boolean);
var r: TRect;
begin
try
r := Item.DisplayRect(drBounds);
if Item.Index = lwProperties.Items.Count - 1 then
begin
lwProperties.Canvas.Pen.Color := $00ACB9AF;
lwProperties.Canvas.MoveTo(r.Left, r.Bottom);
lwProperties.Canvas.LineTo(r.Right, r.Bottom);
lwProperties.Canvas.Brush.Color := $00FFFFFF;//$00F7F4E1;//$00F2EDDF;//$00DCF5D6;//$00FBFAF0;//$00DAFCDB;//$00EFFAEB;
lwProperties.Canvas.FillRect(r);
lwProperties.Canvas.Font.Style := [];
lwProperties.Canvas.TextOut(r.Left + 2, r.Top, Item.Caption);
end;
if not Assigned(Item.Data) then
begin
DefaultDraw := false;
lwProperties.Canvas.Brush.Color := $00EFEFEF;//$00F7F4E1;//$00F2EDDF;//$00DCF5D6;//$00FBFAF0;//$00DAFCDB;//$00EFFAEB;
lwProperties.Canvas.FillRect(r);
lwProperties.Canvas.Font.Color := $00ACB9AF;//clGray;
lwProperties.Canvas.Font.Style := [fsBold];
if (Item.Index < lwProperties.Items.Count - 1)
and (TIDObject(lwProperties.Items[Item.Index + 1].Data) = IVisitor(Self).ActiveObject) then
lwProperties.Canvas.Font.Color := lwProperties.Canvas.Font.Color + $00330000;
lwProperties.Canvas.TextOut(r.Left + 2, r.Top, Item.Caption);
end
else
begin
if (TObject(Item.Data) is TFakeObject) then
begin
DefaultDraw := false;
lwProperties.Canvas.Brush.Color := $00E4EAD7;//$00FBFAF0;//$00DAFCDB;//$00EFFAEB;
lwProperties.Canvas.FillRect(r);
lwProperties.Canvas.Font.Color := $00ACB9AF;//clGray;
lwProperties.Canvas.Font.Style := [fsBold];
if (Item.Index < lwProperties.Items.Count - 2)
and (TIDObject(lwProperties.Items[Item.Index + 2].Data) = IVisitor(Self).ActiveObject) then
lwProperties.Canvas.Font.Color := lwProperties.Canvas.Font.Color + $0000AA00;
lwProperties.Canvas.TextOut(r.Left + r.Right - lwProperties.Canvas.TextWidth(Item.Caption), r.Top, Item.Caption);
end
end;
except
end;
end;
function TfrmWellSlottingInfoQuickView._AddRef: Integer;
begin
Result := -1;
end;
function TfrmWellSlottingInfoQuickView._Release: Integer;
begin
Result := -1;
end;
procedure TfrmWellSlottingInfoQuickView.SetActiveObject(
const Value: TIDObject);
begin
FActiveObject := Value;
end;
procedure TfrmWellSlottingInfoQuickView.VisitWell(AWell: TIDObject);
var w: TWell;
begin
lwProperties.Items.BeginUpdate;
lwProperties.Items.Clear;
try
w := AWell as TWell;
AddItem('Скважина ', '', FFakeObject);
AddItem('UIN', IntToStr(AWell.ID), AWell);
AddItem('Наименование скважины', w.NumberWell + ' - ' + (AWell as TWell).Area.Name, AWell);
AddItem('Синоним наименования', w.Name, AWell);
if w.TrueDepth > 0 then
AddItem('Забой', Format('%.2f', [w.TrueDepth]), AWell)
else
AddItem('Забой', '<не указан>', AWell);
if w.Altitude > 0 then
AddItem('Альтитуда', Format('%.2f', [w.Altitude]), AWell)
else
AddItem('Альтитуда', '<не указан>', AWell);
AddItem('Категория', w.Category.List, AWell);
if Assigned(w.State) then
AddItem('Состоян+ие', w.State.List, AWell);
if Assigned(w.WellPosition) and Assigned(w.WellPosition.NewNGR) then
AddItem('НГР', w.WellPosition.NewNGR.List, AWell);
if w.DtDrillingStart <> 0 then
AddItem('Дата начала бурения', DateToStr(w.DtDrillingStart), AWell)
else
AddItem('Дата начала бурения', '<не указана>', AWell);
if w.DtDrillingFinish <> 0 then
AddItem('Дата окончания бурения', DateToStr(w.DtDrillingFinish), AWell)
else
AddItem('Дата окончания бурения', '<не указана>', AWell);
AddItem('Поступило керна', Format('%.2f', [w.SlottingPlacement.CoreYieldWithGenSection]), AWell);
AddItem('Выход керна', Format('%.2f', [w.SlottingPlacement.CoreFinalYieldWithGenSection]), AWell);
AddItem('История обработки', w.SlottingPlacement.TransferHistory, AWell);
IVisitor(Self).ActiveObject := AWell;
except
end;
lwProperties.Items.EndUpdate;
end;
procedure TfrmWellSlottingInfoQuickView.VisitLicenseZone(
ALicenseZone: TIDObject);
begin
end;
procedure TfrmWellSlottingInfoQuickView.VisitTestInterval(
ATestInterval: TIDObject);
begin
end;
procedure TfrmWellSlottingInfoQuickView.Clear;
begin
lwProperties.Items.Clear;
end;
constructor TfrmWellSlottingInfoQuickView.Create(AOwner: TComponent);
begin
inherited;
FFakeObject := TFakeObject.Create;
end;
destructor TfrmWellSlottingInfoQuickView.Destroy;
begin
FFakeObject.Free;
inherited;
end;
procedure TfrmWellSlottingInfoQuickView.AddItem(AName, AValue: string;
AData: TObject);
var li: TListItem;
begin
li := lwProperties.Items.Add;
li.Caption := AName;
if not (AData is TFakeObject) then
begin
li := lwProperties.Items.Add;
li.Caption := Trim(AValue);
li.Data := AData;
end
else li.Data := AData;
end;
procedure TfrmWellSlottingInfoQuickView.VisitSlotting(
ASlotting: TIDObject);
var s: TSimpleSlotting;
begin
lwProperties.Items.BeginUpdate;
lwProperties.Items.Clear;
try
s := ASlotting as TSimpleSlotting;
if s.Owner is TSimpleWell then
VisitWell(s.Owner)
else if s.Owner is TGeneralizedSection then
begin
VisitGenSection(s.Owner);
VisitWell((s as TGeneralizedSectionSlotting).Well);
end;
AddItem('Интервал отбора керна ', '', FFakeObject);
AddItem('UIN', IntToStr(ASlotting.ID), ASlotting);
AddItem('Глубины',
Format('%.2f', [s.Top]) + ' - ' + Format('%.2f', [s.Bottom]),
ASlotting);
AddItem('Проходка', Format('%.2f', [s.Digging]), ASlotting);
AddItem('Выход керна', Format('%.2f', [s.CoreYield]), ASlotting);
AddItem('Фактический выход керна', Format('%.2f', [s.CoreFinalYield]), ASlotting);
AddItem('Диаметр', Format('%.2f', [s.Diameter]), ASlotting);
AddItem('Дата отбора', DateToStr(s.CoreTakeDate), ASlotting);
AddItem('Механическое состояние', s.CoreMechanicalStates.List(loBrief), ASlotting);
(* if (s is TSlotting) then
begin
ss := s as TSlotting;
w := s.Owner as TWell;
if Assigned(w.SlottingPlacement) and Assigned(w.SlottingPlacement.StatePartPlacement) then
if (w.SlottingPlacement.StatePartPlacement.ID = CORE_MAIN_GARAGE_ID) then
AddItem('Местоположение', ' ' + ss.Boxes.Racks.List, ASlotting);
end; *)
IVisitor(Self).ActiveObject := ASlotting;
except
end;
lwProperties.Items.EndUpdate;
end;
procedure TfrmWellSlottingInfoQuickView.VisitCollectionWell(
AWell: TIDObject);
var w: TCollectionWell;
begin
lwProperties.Items.BeginUpdate;
lwProperties.Items.Clear;
try
w := AWell as TCollectionWell;
AddItem('Скважина ', '', FFakeObject);
AddItem('UIN', IntToStr(AWell.ID), AWell);
AddItem('Наименование скважины', w.NumberWell + ' - ' + w.Area.List(loBrief), AWell);
AddItem('Забой', Format('%.2f', [w.TrueDepth]), AWell);
AddItem('Альтитуда', Format('%.2f', [w.Altitude]), AWell);
AddItem('Категория', w.Category.List, AWell);
if Assigned(w.State) then
AddItem('Состояние', w.State.List, AWell);
AddItem('Дата начала бурения', DateToStr(w.DtDrillingStart), AWell);
AddItem('Дата окончания бурения', DateToStr(w.DtDrillingFinish), AWell);
AddItem('Количество образцов', IntToStr(w.CollectionSamples.Count), AWell);
IVisitor(Self).ActiveObject := AWell;
except
end;
lwProperties.Items.EndUpdate;
end;
procedure TfrmWellSlottingInfoQuickView.VisitCollectionSample(
ASample: TIDObject);
var s: TCollectionSample;
begin
lwProperties.Items.BeginUpdate;
lwProperties.Items.Clear;
try
s := ASample as TCollectionSample;
AddItem('Образец ', '', FFakeObject);
AddItem('UIN', IntToStr(s.ID), s);
if Trim(s.AdditionalNumber) = '' then
AddItem('Номер', s.SlottingNumber + ' / ' + s.SampleNumber, s)
else
AddItem('Номер', s.SlottingNumber + ' / ' + s.SampleNumber + '(' + Trim(s.AdditionalNumber) + ')', s);
AddItem('Абсолютная глубина отбора, м', Format('%.2f', [s.RealDepth]), s);
AddItem('Интервал отбора, м', Format('%.2f', [s.Top]) + ' - ' + Format('%.2f', [s.Bottom]), s);
if s.DepthFromTop > 0 then
AddItem('Глубина отбора от верха керна, м', Format('%.2f', [s.DepthFromTop]), s)
else if s.DepthFromBottom > 0 then
AddItem('Глубина отбора от низа керна, м', Format('%.2f', [s.DepthFromBottom]), s);
if s.ListStrat <> '' then
AddItem('Стратиграфическая привязка', s.ListStrat, s)
else
AddItem('Стратиграфическая привязка', 'нет данных', s);
AddItem('Лаб. №', s.LabNumber, s);
AddItem('Описания ', '', FFakeObject);
if s.IsDescripted then
AddItem('Наличие определений', 'Есть', s)
else
AddItem('Наличие определений', 'Нет', s);
if s.IsElectroDescription then
AddItem('Наличие определений в эл. виде', 'Есть', s)
else
AddItem('Наличие определений в эл. виде', 'Нет', s);
AddItem('Место хранения ', '', FFakeObject);
AddItem('Кабинет', IntToStr(s.RoomNum), s);
AddItem('Коробка', s.BoxNumber, s);
IVisitor(Self).ActiveObject := s;
except
end;
lwProperties.Items.EndUpdate;
end;
procedure TfrmWellSlottingInfoQuickView.VisitDenudation(
ADenudation: TIDObject);
var d: TDenudation;
begin
lwProperties.Items.BeginUpdate;
lwProperties.Items.Clear;
try
d := ADenudation as TDenudation;
AddItem('Обнажение ', '', FFakeObject);
AddItem('UIN', IntToStr(d.ID), d);
AddItem('Наименование обнажения', d.Name, d);
AddItem('Номер обнажения', d.Number, d);
AddItem('Количество образцов', IntToStr(d.DenudationSamples.Count), d);
IVisitor(Self).ActiveObject := d;
except
end;
lwProperties.Items.EndUpdate;
end;
procedure TfrmWellSlottingInfoQuickView.VisitWellCandidate(
AWellCandidate: TIDObject);
var w: TWellCandidate;
begin
lwProperties.Items.BeginUpdate;
lwProperties.Items.Clear;
try
w := AWellCandidate as TWellCandidate;
AddItem('Скважина-кандидат', '', FFakeObject);
AddItem('UIN', IntToStr(w.ID), w);
AddItem('Наименование площади', w.AreaName, w);
AddItem('Номер скважины', w.WellNum, w);
AddItem('Причина', w.Reason, w);
AddItem('Дата занесения', DateToStr(w.PlacingDate), w);
AddItem('Количество образцов', IntToStr(w.WellCandidateSamples.Count), w);
IVisitor(Self).ActiveObject := w;
except
end;
lwProperties.Items.EndUpdate;
end;
procedure TfrmWellSlottingInfoQuickView.VisitGenSection(
AGenSection: TIDObject);
var s: TGeneralizedSection;
begin
lwProperties.Items.BeginUpdate;
lwProperties.Items.Clear;
try
s := AGenSection as TGeneralizedSection;
AddItem('Сводный разрез ', '', FFakeObject);
AddItem('ID', IntToStr(s.ID), AGenSection);
AddItem('Наименование', s.Name, AGenSection);
AddItem('Стратиграфия', s.Stratigraphy, AGenSection);
AddItem('История обработки', s.SlottingPlacement.TransferHistory, AGenSection);
IVisitor(Self).ActiveObject := s;
except
end;
lwProperties.Items.EndUpdate;
end;
procedure TfrmWellSlottingInfoQuickView.VisitGenSectionSlotting(
ASlotting: TIDObject);
var s: TGeneralizedSectionSlotting;
begin
lwProperties.Items.BeginUpdate;
lwProperties.Items.Clear;
try
s := ASlotting as TGeneralizedSectionSlotting;
if s.Owner is TGeneralizedSection then
begin
VisitGenSection(s.Owner);
end;
AddItem('Интервал отбора керна ', '', FFakeObject);
AddItem('UIN', IntToStr(ASlotting.ID), ASlotting);
AddItem('Скважина', s.Well.List(loBrief), ASlotting);
AddItem('Глубины',
Format('%.2f', [s.Top]) + ' - ' + Format('%.2f', [s.Bottom]),
ASlotting);
AddItem('Проходка', Format('%.2f', [s.Digging]), ASlotting);
AddItem('Выход керна', Format('%.2f', [s.CoreYield]), ASlotting);
AddItem('Фактический выход керна', Format('%.2f', [s.CoreFinalYield]), ASlotting);
AddItem('Диаметр', Format('%.2f', [s.Diameter]), ASlotting);
AddItem('Дата отбора', DateToStr(s.CoreTakeDate), ASlotting);
IVisitor(Self).ActiveObject := ASlotting;
except
end;
lwProperties.Items.EndUpdate;
end;
procedure TfrmWellSlottingInfoQuickView.lwPropertiesDblClick(
Sender: TObject);
begin
if Assigned(lwProperties.Selected) and (Assigned(lwProperties.Selected.Data)) and (Trim(lwProperties.Selected.Caption) <> '') then
begin
if not Assigned(frmStringView) then frmStringView := TfrmStringView.Create(Self);
frmStringView.Text := lwProperties.Selected.Caption;
frmStringView.Show;
end;
end;
end.
|
unit uRuntimeTypeInformation;
interface
uses
System.Classes, System.Rtti, System.Contnrs;
type
TRuntimeTypeInformation = class
private
FList: TObjectList;
public
constructor Create(List: TObjectList);
procedure GetObjectRTTI(LinesReturn: TStrings);
end;
implementation
{ TRuntimeTypeInformation }
constructor TRuntimeTypeInformation.Create(List: TObjectList);
begin
FList := List;
end;
procedure TRuntimeTypeInformation.GetObjectRTTI(LinesReturn: TStrings);
var
typRtti: TRttiType;
ctxRtti: TRttiContext;
proRtti: TRttiProperty;
MetRtti: TRttiMethod;
oAtt: TCustomAttribute;
Objeto: TObject;
FTab: string;
i: Integer;
begin
if not Assigned(FList) then
Exit;
for i := 0 to FList.Count-1 do
begin
Objeto := FList[i];
ctxRtti := TRttiContext.Create;
try
typRtti := ctxRtti.GetType(Objeto.ClassType);
LinesReturn.Add(Objeto.ClassName);
FTab := ' ';
for proRTTI in typRtti.GetProperties do
begin
LinesReturn.Add(FTab + proRtti.Name + ' = ' + proRTTI.GetValue(Objeto).ToString);
FTab := ' ';
for oAtt in proRTTI.GetAttributes do
begin
LinesReturn.Add(FTab + 'CustomAttribute: ' + oAtt.ToString);
end;
FTab := ' ';
end;
LinesReturn.Add('');
for MetRtti in typRtti.GetMethods do
if MetRtti.Parent.Name = Objeto.ClassName then
LinesReturn.Add(FTab + 'Method: ' + typRtti.Name + '.' + MetRtti.Name);
FTab := '';
LinesReturn.Add('----------');
finally
ctxRtti.Free;
end;
end;
end;
end.
|
{ Subroutine TYPE1_SHADER_PHONG (RAY, HIT_INFO, COLOR)
*
* Return the ray color for a given intersection in COLOR. RAY is the ray
* descriptor. HIT_INFO is all the intermediate data returned by the object
* intersect check routine.
}
module type1_shader_phong;
define type1_shader_phong;
%include 'ray_type1_2.ins.pas';
procedure type1_shader_phong ( {shader using Phong lighting model}
in var ray: type1_ray_t; {handle to the ray}
in var hit_info: ray_hit_info_t; {info about specific intersection}
out color: type1_color_t); {returned ray color}
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
geom_info: ray_geom_info_t; {returned geometric info about hit}
hit_geom_p: {pointer to object private hit geom block}
type1_hit_geom_p_t;
visprop_p: type1_visprop_p_t; {local copy of pointer to visprop block}
liparm_p: type1_liparm_p_t; {local copy of pointer to liparm block}
ray2: type1_ray_t; {ray descriptor for recursive rays}
i: sys_int_machine_t; {scratch integer and loop counter}
dot: real; {result of dot product}
alpha: real; {opacity at hit point weighted by ray energy}
light_red, light_grn, light_blu: real; {color fractions of current light source}
above_hitp: vect_3d_t; {point just above actual hit point}
m: real; {scratch multiplication factor}
r: real; {scratch real number}
refl_x, refl_y, refl_z: real; {scratch light reflection vector}
ray_p: ^type1_ray_t; {kluge to allow writing to RAY}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
label
done_spec, leave;
{
********************************************************************************
*
* Local subroutine LIGHT_RAY
*
* Determine the coupling factor between the hit point and a light source. A
* ray will be launched to a light source to determine the coupling factor.
* The following fields are assumed to be set in RAY2, which will be the
* descriptor for the recusive ray:
*
* BASE - Mandatory basic ray info.
*
* VECT - Unit vector to the light source.
*
* GENERATION - Recursive generation counter.
*
* MAX_DIST - Distance to the light source.
*
* RAY2.ENERGY will be the returned coupling factor for this light source into
* the final top generation ray color. It will be 0.0 when the light source is
* completely occluded, and ALPHA when it is completely visible from the hit
* point.
}
procedure light_ray;
var
hit_info: ray_hit_info_t; {hit info block for recursive rays}
shader: ray_shader_t; {unused shader handle}
hit_geom_p: {pointer to object private hit geom block}
type1_hit_geom_p_t;
geom_info: ray_geom_info_t; {returned geometric info about hit}
m: real; {scratch multiplier factor}
label
hit_loop;
begin
ray2.point := above_hitp; {start ray just above surface from hit point}
ray2.energy := alpha; {importance of this ray}
ray2.min_dist := 0.0; {start looking for objects immediately}
hit_loop: {back here after each new hit}
if ray2.energy < 0.001 then begin {too little left to make a difference ?}
ray2.energy := 0.0;
return;
end;
if not {hit nothing, so got to the light source ?}
ray2.base.context_p^.top_level_obj_p^.class_p^.intersect_check^ ( {hit ?}
ray2, {the ray descriptor}
ray2.base.context_p^.top_level_obj_p^, {object to intersect ray with}
ray2.base.context_p^.object_parms_p, {run time parameters for top level object}
hit_info, {specific data returned about this hit}
shader) {unused, we just want to know if it hit}
then return; {RAY2.ENERGY is all set}
{
* This light ray hit something on the way to the light source.
}
hit_info.object_p^.class_p^.hit_geom^ ( {make valid VISPROP, get SHNORM}
hit_info, {info about this intersection}
[ray_geom_unorm], {we only need to know shading normal vector}
geom_info); {returned data}
hit_geom_p := {get pointer to shader parameter pointers}
type1_hit_geom_p_t(hit_info.shader_parms_p);
with hit_geom_p^.visprop_p^: visprop do begin {VISPROP is visual prop of hit obj}
if not visprop.opac_on then begin {object is opaque ?}
ray2.energy := 0.0;
return;
end;
{
* The object the ray hit is partially transparent.
}
if visprop.opac_front = visprop.opac_side
then begin {transparency is independent of angle}
ray2.energy := {weight remaining after passing thru this obj}
ray2.energy * (1.0 - visprop.opac_front);
end
else begin {transparency is a function of hit angle}
m := abs( {cosine between normal and ray vectors}
(ray2.vect.x * geom_info.unorm.x) +
(ray2.vect.y * geom_info.unorm.y) +
(ray2.vect.z * geom_info.unorm.z));
m := {blended opacity between front and side values}
(m * visprop.opac_front) +
((1.0 - m) * visprop.opac_side);
ray2.energy := {weight remaining after passing thru this obj}
ray2.energy * (1.0 - m);
end
; {new RAY2.ENERGY all set}
ray2.min_dist := hit_info.distance + 1.0E-4; {step past object we just hit}
goto hit_loop; {continue tracing ray after this object}
end; {done with VISPROP abbreviation}
end;
{
********************************************************************************
*
* Start of main routine.
}
begin
if {don't take this ray seriously ?}
(ray.generation > type1_max_generation_k) or
(ray.energy < type1_min_energy_k)
then begin
color.red := 0.30 * ray.energy; {pass back neutral gray}
color.grn := 0.30 * ray.energy;
color.blu := 0.30 * ray.energy;
color.alpha := ray.energy;
goto leave;
end;
hit_info.object_p^.class_p^.hit_geom^ ( {get geom info about this hit}
hit_info, {info about this intersection}
[ray_geom_unorm, ray_geom_point], {list of requested info}
geom_info); {returned data}
hit_geom_p := {get pointer to shader parameter pointers}
type1_hit_geom_p_t(hit_info.shader_parms_p);
visprop_p := hit_geom_p^.visprop_p; {make local copy of visprop pointer}
liparm_p := hit_geom_p^.liparm_p; {make local copy of liparm pointer}
with
liparm_p^: liparm, {light source descriptor block}
visprop_p^: visprop, {object visual properties block}
geom_info.point: hitp, {coordinate of hit point}
geom_info.unorm: shnorm {unit surface normal vector for shading}
do begin
{
* The following abbreviations have been set up:
*
* LIPARM - LIPARM light source properties block.
* VISPROP - VISPROP object visual properties block.
* HITP - Coordinate of hit point.
* SHNORM - Unit surface normal vector to use for shading
*
* Initialize RAY2, the ray descriptor for any recursive or light source rays.
* We will fill in the fields that won't change for all the various rays we
* might launch.
}
ray2.base := ray.base; {copy over the mandatory fields}
ray2.generation := ray.generation+1; {this is yet another recursive ray generation}
{
* Init the returned color to the emissive color and whatever is shining thru
* the object. Our local value ALPHA will be set to the 1.0 to 0.0 weighted
* opacity fraction for later use. This will take into account the weighting
* of the original ray.
}
if visprop.opac_on
then begin {transparency is enabled}
if visprop.opac_front = visprop.opac_side
then begin {transparency value is fixed}
alpha := visprop.opac_front;
end
else begin {transparency is a function of angle}
dot := abs( {cosine between normal and eye vectors}
(ray.vect.x * shnorm.x) +
(ray.vect.y * shnorm.y) +
(ray.vect.z * shnorm.z));
alpha := {blend opacity between front and side values}
(dot * visprop.opac_front) +
((1.0 - dot) * visprop.opac_side);
end
; {ALPHA is unweighted opacity at hit point}
ray2.point := ray.point; {start point of recursive ray}
ray2.vect := ray.vect; {unit ray vector}
ray2.energy := ray.energy * (1.0 - alpha); {weighting factor for this ray}
ray2.min_dist := hit_info.distance + 1.0E-4; {start a little past hit point}
ray2.max_dist := ray.max_dist; {distance to farthest acceptable hit point}
ray_trace (ray2, color); {init color from transparent part}
alpha := ray.energy * alpha; {make final weighted opacity fraction}
color.red := color.red + (visprop.emis_red * alpha); {emissive contribution}
color.grn := color.grn + (visprop.emis_grn * alpha);
color.blu := color.blu + (visprop.emis_blu * alpha);
color.alpha := color.alpha + alpha; {all remaining contributions are opaque}
end
else begin {transparency is disabled}
alpha := ray.energy; {set total fraction for opaque part}
color.red := visprop.emis_red * alpha;
color.grn := visprop.emis_grn * alpha;
color.blu := visprop.emis_blu * alpha;
color.alpha := alpha;
end
;
{
*******************
*
* Sum all the color contributions that are a function of the light sources.
}
above_hitp.x := hitp.x + (shnorm.x * 3.0E-4); {point to launch light rays from}
above_hitp.y := hitp.y + (shnorm.y * 3.0E-4);
above_hitp.z := hitp.z + (shnorm.z * 3.0E-4);
for i := 1 to liparm.n_lights do begin {once for each light source}
with liparm.light[i]: light do begin {LIGHT is descriptor for this light source}
case light.ltype of {different code for each type of light source}
{
* Light source is turned off.
}
type1_ltype_off_k: begin
next; {go on to next light source}
end;
{
* Ambient light source.
}
type1_ltype_ambient_k: begin
color.red := color.red +
(light.amb_red * visprop.diff_red * alpha);
color.grn := color.grn +
(light.amb_grn * visprop.diff_grn * alpha);
color.blu := color.blu +
(light.amb_blu * visprop.diff_blu * alpha);
next; {go on to next light source}
end;
{
* Directional light source.
}
type1_ltype_directional_k: begin
ray2.vect := light.dir_uvect; {get unit vector to light source}
ray2.max_dist := 1.0E30; {set max allowed hit distance to infinity}
light_ray; {follow ray towards light source}
if ray2.energy < 0.001 then next; {light source totally blocked ?}
light_red := light.dir_red * ray2.energy; {get light source raw colors}
light_grn := light.dir_grn * ray2.energy;
light_blu := light.dir_blu * ray2.energy;
end;
{
* Point light source with no light fall off.
}
type1_ltype_point_constant_k: begin
ray2.vect.x := {make ununitized vector to light source}
light.pcon_coor.x - hitp.x;
ray2.vect.y :=
light.pcon_coor.y - hitp.y;
ray2.vect.z :=
light.pcon_coor.z - hitp.z;
ray2.max_dist := sqrt( {find distance to this light source}
sqr(ray2.vect.x) + sqr(ray2.vect.y) + sqr(ray2.vect.z));
m := 1.0/ray2.max_dist; {make scale factor to unitize vector}
ray2.vect.x := ray2.vect.x*m; {make unit vector towards light source}
ray2.vect.y := ray2.vect.y*m;
ray2.vect.z := ray2.vect.z*m;
light_ray; {follow ray towards light source}
if ray2.energy < 0.001 then next; {light source totally blocked ?}
light_red := light.pcon_red * ray2.energy; {get light source raw colors}
light_grn := light.pcon_grn * ray2.energy;
light_blu := light.pcon_blu * ray2.energy;
end;
{
* Point light source with 1/R**2 falloff.
}
type1_ltype_point_r2_k: begin
ray2.vect.x := {make ununitized vector to light source}
light.pr2_coor.x - hitp.x;
ray2.vect.y :=
light.pr2_coor.y - hitp.y;
ray2.vect.z :=
light.pr2_coor.z - hitp.z;
r := {square of distance to light source}
sqr(ray2.vect.x) + sqr(ray2.vect.y) + sqr(ray2.vect.z);
ray2.max_dist := sqrt(r); {find distance to light source}
m := 1.0/ray2.max_dist; {make scale factor to unitize vector}
ray2.vect.x := ray2.vect.x*m; {make unit vector towards light source}
ray2.vect.y := ray2.vect.y*m;
ray2.vect.z := ray2.vect.z*m;
light_ray; {follow ray towards light source}
if ray2.energy < 0.001 then next; {light source totally blocked ?}
m := ray2.energy / r; {scale factor for 1/R**2 falloff}
light_red := light.pcon_red * m; {get light source raw colors}
light_grn := light.pcon_grn * m;
light_blu := light.pcon_blu * m;
end;
{
* Unrecognized light source ID.
}
otherwise
sys_msg_parm_int (msg_parm[1], ord(light.ltype));
sys_message_bomb ('ray_type1', 'light_id_bad', msg_parm, 1);
end; {done with all the light source types}
{
*******************
*
* The current light source is meaningful, and has been reduced to the
* following state:
*
* RAY2.VECT - Unit vector to light source.
*
* LIGHT_RED, LIGHT_GRN, LIGHT_BLU - Weighted occluded light source color
* at hit point. These are the color contributions to the top level ray
* for the full light at the hit point.
*
* Now handle the surface properties that are a function of the incoming light.
* VISPROP is the visual properties block.
*
* Diffuse reflections.
}
if visprop.diff_on then begin {diffuse color turned on ?}
dot := abs( {coupling factor due to incident angle}
(ray2.vect.x * shnorm.x) +
(ray2.vect.y * shnorm.y) +
(ray2.vect.z * shnorm.z));
color.red := color.red + {add in diffuse contribution for this light}
visprop.diff_red * light_red * dot;
color.grn := color.grn +
visprop.diff_grn * light_grn * dot;
color.blu := color.blu +
visprop.diff_blu * light_blu * dot;
end; {done handling diffuse reflections}
{
* Specular reflections.
}
if visprop.spec_on then begin {specular reflections turned on ?}
dot := {dot product of light and shading normal}
(ray2.vect.x * shnorm.x) +
(ray2.vect.y * shnorm.y) +
(ray2.vect.z * shnorm.z);
if dot <= 0.0 then goto done_spec; {light coming from other side of object ?}
dot := {dot product used for making light refl vect}
2.0*(ray2.vect.x*shnorm.x + ray2.vect.y*shnorm.y + ray2.vect.z*shnorm.z);
refl_x := {make unit light reflection vector}
dot*shnorm.x - ray2.vect.x;
refl_y :=
dot*shnorm.y - ray2.vect.y;
refl_z :=
dot*shnorm.z - ray2.vect.z;
dot := {dot product of reflection and view vectors}
-(refl_x*ray.vect.x + refl_y*ray.vect.y + refl_z*ray.vect.z);
if dot <= 0.0 then goto done_spec; {negative dot product is like zero}
dot := dot ** visprop.spec_exp; {apply specular exponent}
color.red := color.red + {add in specular contribution for this light}
visprop.spec_red * light_red * dot;
color.grn := color.grn +
visprop.spec_grn * light_grn * dot;
color.blu := color.blu +
visprop.spec_blu * light_blu * dot;
done_spec: {jump here to abort specular calculations}
end;
end; {done with LIGHT abbreviation}
end; {back and do next light source}
{
*******************
*
* Done looping thru all the light sources.
}
ray_p := addr(ray);
ray_p^.max_dist := hit_info.distance;
end; {done LIPARM, VISPROP, HITP, SHORM abbrevs}
leave: {common exit point}
if ray.generation <= 1 then begin {this is a top level ray ?}
next_mem := 0; {reset DAG path scratch memory to all free}
end;
end;
|
unit FifoBasics;
{$mode objfpc}{$H+}{$interfaces corba}
interface
uses
Classes, SysUtils;
type
TIFifo = interface
function Push(p: Pointer): Boolean;
function Pop(out p: Pointer): Boolean;
function GetPendingQty:Integer;
function GetAvailableQty:Integer;
property RdIdx: Integer;
property WrIdx: Integer;
property Size: Integer;
end;
TCFifo = class(TIFifo)
private
Sz:Integer;
Rd:Integer;
Wr:Integer;
Buffer:Array Of Pointer;
public
constructor Create(Size: Integer);
function Push(p: Pointer): Boolean;
function Pop(out p: Pointer): Boolean;
function GetPendingQty:Integer;
function GetAvailableQty:Integer;
destructor Destroy; override;
property RdIdx: Integer read Rd;
property WrIdx: Integer read Wr;
property Size: Integer read Sz;
end;
implementation
constructor TCFifo.Create(Size:Integer);
var
i:Integer;
begin
Sz := Size + 1;
{Usally allocate Sz + 1 elements as fifo is full when Wr = Rd + 1 mod Sz}
SetLength(Buffer, Sz + 1);
Rd := 0;
Wr := 0;
For i := 0 to Sz Do
Buffer[i] := Nil;
end;
destructor TCFifo.Destroy;
begin
SetLength(Buffer, 0);
end;
function TCFifo.Push(p:Pointer):Boolean;
var
nWr:Integer;
begin
nWr := Wr + 1;
if nWr > Sz then
nWr := 0;
if nWr = Rd then
Result := False
else if Buffer[nWr] <> Nil then
Result := False //TODO: should raise an exception here
else begin
Buffer[Wr] := p;
Wr := nWr;
Result := True;
end;
end;
function TCFifo.Pop(out p: Pointer): Boolean;
begin
if Rd = Wr then
Result := False
else begin
p := Buffer[Rd];
Buffer[Rd] := Nil;
Rd := Rd + 1;
if Rd > Sz then
Rd := 0;
Result := True;
end;
end;
function TCFifo.GetPendingQty:Integer;
begin
Result := Wr - Rd;
if Result < 0 then
Result := Result + Sz + 1;
end;
function TCFifo.GetAvailableQty:Integer;
begin
Result := Sz - GetPendingQty - 1;
end;
end.
|
unit RT_GeneratorUpdater;
interface
uses
Classes, SysUtils,
RT_SQL;
type
TRT_GeneratorUpdater = class (TObject)
class procedure UpdateGenerator(TableName: String);
class procedure UpdateAllGenerators;
end;
implementation
uses jvuib;
class procedure TRT_GeneratorUpdater.UpdateGenerator(TableName: String);
var
CurrentMaxValue: Integer;
CurrentGenValue: Integer;
begin
with TSQL.Instance.CreateQuery do
try
SQL.Text := Format('SELECT Max(Id) FROM %s', [TableName]);
Open;
if not Eof then
CurrentMaxValue := Fields.AsInteger[0]
else
CurrentMaxValue := -1;
Close;
SQL.Text := Format('SELECT GEN_ID(%s_ID, 0) FROM RDB$DATABASE', [TableName]);
Open;
CurrentGenValue := Fields.AsInteger[0];
Close;
if CurrentGenValue < CurrentMaxValue then
begin
SQL.Text := Format('SET GENERATOR %s_ID TO %d', [TableName, CurrentMaxValue + 1]);
Execute;
Transaction.Commit;
end; finally
Free;
end;
end;
class procedure TRT_GeneratorUpdater.UpdateAllGenerators;
begin
TRT_GeneratorUpdater.UpdateGenerator('KURS');
TRT_GeneratorUpdater.UpdateGenerator('POSTOJ');
TRT_GeneratorUpdater.UpdateGenerator('TAKSOWKA');
TRT_GeneratorUpdater.UpdateGenerator('ULICA');
TRT_GeneratorUpdater.UpdateGenerator('KLIENT');
end;
end.
|
unit uPedidos;
interface
uses FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.Comp.Client, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Phys.SQLiteVDataSet, FireDAC.VCLUI.Wait, dtmBanco, Datasnap.DBClient,
SysUtils;
type
TPedidosClass = class
private
public
procedure Salva(numero, emissao, cliente : string; total : Double; tblPedItens : TClientDataSet);
function getDescricaoProduto(codigo : string) : string;
function getDescricaoCliente(codigo : string) : string;
function getItensPedido(numero : string) : TFDQuery;
end;
var
pedClass : TPedidosClass;
implementation
{ TPedidos }
function TPedidosClass.getDescricaoCliente(codigo: string): string;
var
sqlQuery : TFDQuery;
begin
sqlQuery := TFDQuery.Create(nil);
sqlQuery.Connection := dtmMysql.cnt1;
sqlQuery.SQL.Text := 'SELECT NOME FROM CLIENTES WHERE ID = :id';
sqlQuery.ParamByName('id').AsString := codigo;
sqlQuery.Open;
Result := sqlQuery.FieldByName('NOME').AsString;
sqlQuery.Free;
end;
function TPedidosClass.getDescricaoProduto(codigo: string): string;
var
sqlQuery : TFDQuery;
begin
sqlQuery := TFDQuery.Create(nil);
sqlQuery.Connection := dtmMysql.cnt1;
sqlQuery.SQL.Text := 'SELECT DESCRICAO FROM PRODUTOS WHERE CODIGO = :id';
sqlQuery.ParamByName('id').AsString := codigo;
sqlQuery.Open;
if sqlQuery.FieldByName('DESCRICAO').AsString = '' then
begin
sqlQuery.Close;
sqlQuery.SQL.Text := 'SELECT DESCRICAO FROM PRODUTOS WHERE ID = :id';
sqlQuery.ParamByName('id').AsString := codigo;
sqlQuery.Open;
end;
Result := sqlQuery.FieldByName('DESCRICAO').AsString;
if sqlQuery.FieldByName('DESCRICAO').AsString = '' then
Result := 'Produto não encontrado';
sqlQuery.Free;
end;
function TPedidosClass.getItensPedido(numero: string): TFDQuery;
var
sqlQuery : TFDQuery;
begin
sqlQuery := TFDQuery.Create(nil);
sqlQuery.Connection := dtmMysql.cnt1;
sqlQuery.SQL.Text := 'SELECT * FROM ITENSPEDIDOS WHERE ID_PEDIDO = :id';
sqlQuery.ParamByName('id').AsString := numero;
sqlQuery.Open;
Result := sqlQuery;
end;
procedure TPedidosClass.Salva(numero, emissao, cliente : string; total : Double; tblPedItens : TClientDataSet);
var
sqlQuery : TFDQuery;
sql : string;
begin
if tblPedItens.RecordCount = 0 then
raise Exception.Create('Não há itens para gravar.');
sqlQuery := TFDQuery.Create(nil);
sqlQuery.Connection := dtmMysql.cnt1;
dtmMysql.sqlPed.Close;
dtmMysql.sqlPed.Open;
if not dtmMysql.cnt1.InTransaction then
dtmMysql.cnt1.StartTransaction;
try
//sqlQuery.Close;
//if (numero <> '') and (dtmMysql.sqlPed.Locate('ID', numero, [])) then
//begin
// sqlQuery.SQL.Text := 'UPDATE PEDIDOS SET DATA_EMISSAO = :data, CLIENTE = :cliente, TOTAL = :total WHERE ID = :id';
// sqlQuery.ParamByName('id').AsString := numero;
//end
//else
// sqlQuery.SQL.Text := 'INSERT INTO PEDIDOS (DATA_EMISSAO, CLIENTE, TOTAL) VALUES (:data, :cliente, :total);';
//sqlQuery.ParamByName('data').AsDate := StrToDateDef(emissao, 0);
//sqlQuery.ParamByName('cliente').AsString := cliente;
//sqlQuery.ParamByName('total').AsFloat := total;
//sqlQuery.ExecSQL;
if (numero <> '') and (dtmMysql.sqlPed.Locate('ID', numero, [])) then
dtmMysql.sqlPed.Edit
else
dtmMysql.sqlPed.Insert;
dtmMysql.sqlPed.FieldByName('DATA_EMISSAO').AsString := emissao;
dtmMysql.sqlPed.FieldByName('CLIENTE').AsString := cliente;
dtmMysql.sqlPed.FieldByName('TOTAL').AsFloat := total;
dtmMysql.sqlPed.Post;
dtmMysql.sqlPed.ApplyUpdates(0);
if dtmMysql.cnt1.InTransaction then
dtmMysql.cnt1.Commit;
except
dtmMysql.cnt1.Rollback;
end;
//Itens
if not dtmMysql.cnt1.InTransaction then
dtmMysql.cnt1.StartTransaction;
try
sqlQuery.SQL.Text := 'DELETE FROM ITENSPEDIDOS WHERE ID_PEDIDO = :id';
sqlQuery.ParamByName('id').AsString := dtmMysql.sqlPed.FieldByName('ID').AsString;
sqlQuery.ExecSQL;
if dtmMysql.cnt1.InTransaction then
dtmMysql.cnt1.Commit;
except
dtmMysql.cnt1.Rollback;
end;
dtmMysql.sqlPedItens.Close;
dtmMysql.sqlPedItens.Open;
if not dtmMysql.cnt1.InTransaction then
dtmMysql.cnt1.StartTransaction;
try
//tblPedItens.First;
//while not tblPedItens.Eof do
//begin
// dtmMysql.sqlPedItens.Insert;
// dtmMysql.sqlPedItens.FieldByName('ID_PEDIDO').AsString := dtmMysql.sqlPed.FieldByName('ID').AsString;
// dtmMysql.sqlPedItens.FieldByName('CODIGOPRODUTO').AsString := tblPedItens.FieldByName('CODIGOPRODUTO').AsString;
// dtmMysql.sqlPedItens.FieldByName('QUANTIDADE').AsString := tblPedItens.FieldByName('QUANTIDADE').AsString;
// dtmMysql.sqlPedItens.FieldByName('VALORUNITARIO').AsString := tblPedItens.FieldByName('VALORUNITARIO').AsString;
// dtmMysql.sqlPedItens.FieldByName('VALORTOTAL').AsString := tblPedItens.FieldByName('VALORTOTAL').AsString;
// dtmMysql.sqlPedItens.Post;
// dtmMysql.sqlPedItens.ApplyUpdates(0);
// tblPedItens.Next;
//end;
tblPedItens.First;
while not tblPedItens.Eof do
begin
sqlQuery.Close;
sqlQuery.SQL.Text := 'INSERT INTO ITENSPEDIDOS (ID_PEDIDO, CODIGOPRODUTO, QUANTIDADE, VALORUNITARIO, VALORTOTAL) ' +
'VALUES (:idPed, :codProd, :qtd, :valUni, :valTot); ';
sqlQuery.ParamByName('idPed').AsString := dtmMysql.sqlPed.FieldByName('ID').AsString;
sqlQuery.ParamByName('codProd').AsString := tblPedItens.FieldByName('CODIGOPRODUTO').AsString;
sqlQuery.ParamByName('qtd').AsFloat := tblPedItens.FieldByName('QUANTIDADE').AsFloat;
sqlQuery.ParamByName('valUni').AsFloat := tblPedItens.FieldByName('VALORUNITARIO').AsFloat;
sqlQuery.ParamByName('valTot').AsFloat := tblPedItens.FieldByName('VALORTOTAL').AsFloat;
sqlQuery.ExecSQL;
tblPedItens.Next;
end;
if dtmMysql.cnt1.InTransaction then
dtmMysql.cnt1.Commit;
except
dtmMysql.cnt1.Rollback;
end;
sqlQuery.Free;
end;
end.
|
unit uCommandSampleOptions;
interface
type
TGlobalOptions = class
public class var
Verbose: Boolean;
OutPath: string;
end;
TInstallOptions = class
public class var
InstallPath: string;
OutPath: string;
end;
TUninstallOptions = class
public class var
KeepSettings: Boolean;
end;
TInstallLicense = class
public class var
LicenseFile: string;
end;
THelpOptions = class
public class var
HelpCommand: string;
end;
implementation
end.
|
unit GN_RadioGroup;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, StdCtrls, ExtCtrls ;
Type
TCustomGNRadioGroup = class(TCustomGroupBox)
private
FButtons: TList;
FItems: TStrings;
FDBItems : TStrings ;
FItemIndex: Integer;
FColumns: Integer;
FReading: Boolean;
FUpdating: Boolean;
FFieldName : String ;
FItemChoice : String ;
procedure ArrangeButtons;
procedure ButtonClick(Sender: TObject);
procedure ItemsChange(Sender: TObject);
procedure SetButtonCount(Value: Integer);
procedure SetColumns(Value: Integer);
procedure SetItemIndex(Value: Integer);
procedure SetItems(Value: TStrings);
procedure SetDBItems(Value: TStrings);
procedure SetItemChoice (Value: String);
procedure UpdateButtons;
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
protected
procedure ReadState(Reader: TReader); override;
function CanModify: Boolean; virtual;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
property Columns: Integer read FColumns write SetColumns default 1;
property ItemIndex: Integer read FItemIndex write SetItemIndex default -1;
property Items: TStrings read FItems write SetItems;
property DBItems: TStrings read FDBItems write SetDBItems;
property FieldName : String read FFieldName Write FFieldName ;
property ItemChoice : String read FItemChoice Write SetItemChoice ;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure FlipChildren(AllLevels: Boolean); override;
end;
TGNRadioGroup = class(TCustomGNRadioGroup)
published
property Align;
property Anchors;
property BiDiMode;
property Caption;
property Color;
property Columns;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property ItemIndex;
property ItemChoice ;
property Items;
property DBItems ;
property Constraints;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property FieldName ;
property OnClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnStartDock;
property OnStartDrag;
end;
procedure Register;
Var
FCNCmd : Boolean ;
implementation
{ TGroupButton }
type
TGroupButton = class(TRadioButton)
private
FInClick: Boolean;
procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;
protected
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
public
constructor InternalCreate(RadioGroup: TCustomGNRadioGroup);
destructor Destroy; override;
end;
constructor TGroupButton.InternalCreate(RadioGroup: TCustomGNRadioGroup);
begin
inherited Create(RadioGroup);
RadioGroup.FButtons.Add(Self);
Visible := False;
Enabled := RadioGroup.Enabled;
ParentShowHint := False;
OnClick := RadioGroup.ButtonClick;
Parent := RadioGroup;
end;
destructor TGroupButton.Destroy;
begin
TCustomGNRadioGroup(Owner).FButtons.Remove(Self);
inherited Destroy;
end;
procedure TGroupButton.CNCommand(var Message: TWMCommand);
begin
if not FInClick then
begin
FInClick := True;
try
if ((Message.NotifyCode = BN_CLICKED) or
(Message.NotifyCode = BN_DOUBLECLICKED)) and
TCustomGNRadioGroup(Parent).CanModify then
If ( Not FCNCmd ) Then
inherited ;
except
Application.HandleException(Self);
end;
FInClick := False;
FCNCmd := False ;
end;
end;
procedure TGroupButton.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
TCustomGNRadioGroup(Parent).KeyPress(Key);
if (Key = #8) or (Key = ' ') then
begin
if not TCustomGNRadioGroup(Parent).CanModify then Key := #0;
end;
end;
procedure TGroupButton.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
TCustomGNRadioGroup(Parent).KeyDown(Key, Shift);
end;
{ TCustomGNRadioGroup }
constructor TCustomGNRadioGroup.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csSetCaption, csDoubleClicks];
FButtons := TList.Create;
FItems := TStringList.Create;
TStringList(FItems).OnChange := ItemsChange;
FDBItems := TStringList.Create;
TStringList(FDBItems).OnChange := ItemsChange;
FItemIndex := -1;
FColumns := 1;
FFieldName := '' ;
FCNCmd := False ;
end;
destructor TCustomGNRadioGroup.Destroy;
begin
SetButtonCount(0);
TStringList(FItems).OnChange := nil;
FItems.Free;
TStringList(FDBItems).OnChange := nil;
FDBItems.Free;
FButtons.Free;
inherited Destroy;
end;
procedure TCustomGNRadioGroup.FlipChildren(AllLevels: Boolean);
begin
{ The radio buttons are flipped using BiDiMode }
end;
procedure TCustomGNRadioGroup.ArrangeButtons;
var
ButtonsPerCol, ButtonWidth, ButtonHeight, TopMargin, I: Integer;
DC: HDC;
SaveFont: HFont;
Metrics: TTextMetric;
DeferHandle: THandle;
ALeft: Integer;
begin
if (FButtons.Count <> 0) and not FReading then
begin
DC := GetDC(0);
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
ReleaseDC(0, DC);
ButtonsPerCol := (FButtons.Count + FColumns - 1) div FColumns;
ButtonWidth := (Width - 10) div FColumns;
I := Height - Metrics.tmHeight - 5;
ButtonHeight := I div ButtonsPerCol;
TopMargin := Metrics.tmHeight + 1 + (I mod ButtonsPerCol) div 2;
DeferHandle := BeginDeferWindowPos(FButtons.Count);
try
for I := 0 to FButtons.Count - 1 do
with TGroupButton(FButtons[I]) do
begin
BiDiMode := Self.BiDiMode;
ALeft := (I div ButtonsPerCol) * ButtonWidth + 8;
if UseRightToLeftAlignment then
ALeft := Self.ClientWidth - ALeft - ButtonWidth;
DeferHandle := DeferWindowPos(DeferHandle, Handle, 0,
ALeft,
(I mod ButtonsPerCol) * ButtonHeight + TopMargin,
ButtonWidth, ButtonHeight,
SWP_NOZORDER or SWP_NOACTIVATE);
Visible := True;
end;
finally
EndDeferWindowPos(DeferHandle);
end;
end;
end;
procedure TCustomGNRadioGroup.ButtonClick(Sender: TObject);
begin
if not FUpdating then
begin
FItemIndex := FButtons.IndexOf(Sender);
FItemChoice := FDBItems[FItemIndex] ;
Changed;
Click;
end;
end;
procedure TCustomGNRadioGroup.ItemsChange(Sender: TObject);
begin
if not FReading then
begin
if FItemIndex >= FItems.Count then FItemIndex := FItems.Count - 1;
UpdateButtons;
end;
end;
procedure TCustomGNRadioGroup.ReadState(Reader: TReader);
begin
FReading := True;
inherited ReadState(Reader);
FReading := False;
UpdateButtons;
end;
procedure TCustomGNRadioGroup.SetButtonCount(Value: Integer);
begin
while FButtons.Count < Value do TGroupButton.InternalCreate(Self);
while FButtons.Count > Value do TGroupButton(FButtons.Last).Free;
end;
procedure TCustomGNRadioGroup.SetColumns(Value: Integer);
begin
if Value < 1 then Value := 1;
if Value > 16 then Value := 16;
if FColumns <> Value then
begin
FColumns := Value;
ArrangeButtons;
Invalidate;
end;
end;
procedure TCustomGNRadioGroup.SetItemIndex(Value: Integer);
begin
if FReading then FItemIndex := Value else
begin
FItemChoice := '' ;
if Value < -1 then Value := -1;
if Value >= FButtons.Count then Value := FButtons.Count - 1;
if FItemIndex <> Value then
begin
if FItemIndex >= 0 then
TGroupButton(FButtons[FItemIndex]).Checked := False;
FItemIndex := Value;
if FItemIndex >= 0 then
Begin
TGroupButton(FButtons[FItemIndex]).Checked := True;
End ;
end;
end;
end;
procedure TCustomGNRadioGroup.SetItems(Value: TStrings);
begin
FItems.Assign(Value);
end;
procedure TCustomGNRadioGroup.SetDBItems(Value: TStrings);
begin
FDBItems.Assign(Value);
end;
Procedure TCustomGNRadioGroup.SetItemChoice ( Value : String ) ;
Var
i : Integer ;
Begin
FItemChoice := Value ;
For i:=0 To FDBItems.Count-1 Do
Begin
If ( FDBItems[i] = Value ) Then
Begin
FCNCmd := True ;
If ( Value = '' ) Then
SetItemIndex(-2)
Else
SetItemIndex(i) ;
Break ;
End ;
End ;
End ;
procedure TCustomGNRadioGroup.UpdateButtons;
var
I: Integer;
begin
SetButtonCount(FItems.Count);
for I := 0 to FButtons.Count - 1 do
TGroupButton(FButtons[I]).Caption := FItems[I];
if FItemIndex >= 0 then
begin
FUpdating := True;
TGroupButton(FButtons[FItemIndex]).Checked := True;
FItemChoice := FDBItems[FItemIndex] ;
FUpdating := False;
end;
ArrangeButtons;
Invalidate;
end;
procedure TCustomGNRadioGroup.CMEnabledChanged(var Message: TMessage);
var
I: Integer;
begin
inherited;
for I := 0 to FButtons.Count - 1 do
TGroupButton(FButtons[I]).Enabled := Enabled;
end;
procedure TCustomGNRadioGroup.CMFontChanged(var Message: TMessage);
begin
inherited;
ArrangeButtons;
end;
procedure TCustomGNRadioGroup.WMSize(var Message: TWMSize);
begin
inherited;
ArrangeButtons;
end;
function TCustomGNRadioGroup.CanModify: Boolean;
begin
Result := True;
end;
procedure TCustomGNRadioGroup.GetChildren(Proc: TGetChildProc; Root: TComponent);
begin
end;
procedure Register;
begin
RegisterComponents('GlobalNet', [TGNRadioGroup]);
end;
end.
|
Unit AdvStreamFilers;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
MathSupport, HashSupport,
AdvItems, AdvObjects, AdvPersistents, AdvStreams, AdvFilers, AdvHashes;
Type
TAdvStreamFilerReferenceHashEntry = Class(TAdvHashEntry)
Private
FKey : Pointer;
FValue : Pointer;
Procedure SetKey(Const Value: Pointer);
Protected
Procedure Generate; Override;
Public
Procedure Assign(oSource : TAdvObject); Override;
Property Key : Pointer Read FKey Write SetKey;
Property Value : Pointer Read FValue Write FValue;
End;
TAdvStreamFilerReferenceHashTable = Class(TAdvHashTable)
Protected
Function ItemClass : TAdvHashEntryClass; Override;
Function Equal(oA, oB : TAdvHashEntry) : Integer; Override;
End;
TAdvStreamFilerReferenceManager = Class(TAdvObject)
Private
FHashTable : TAdvStreamFilerReferenceHashTable;
FLookupHashEntry : TAdvStreamFilerReferenceHashEntry;
Public
Constructor Create; Override;
Destructor Destroy; Override;
Function Link : TAdvStreamFilerReferenceManager;
Procedure Clear;
Procedure Bind(oKey, oValue : TAdvPersistent);
Function Get(oKey : TAdvPersistent) : TAdvPersistent;
Function Exists(oKey : TAdvPersistent) : Boolean;
Property HashTable : TAdvStreamFilerReferenceHashTable Read FHashTable;
End;
TAdvStreamFilerResourceManager = Class(TAdvObject)
Public
Function Link : TAdvStreamFilerResourceManager;
Procedure Clear; Virtual;
Function ResolveObject(Const sResource : String; Const aClass : TAdvObjectClass) : TAdvObject; Virtual;
Function ResolveID(Const oObject : TAdvObject) : String; Virtual;
End;
TAdvStreamFiler = Class(TAdvFiler)
Private
FStream : TAdvStream;
FReferenceManager : TAdvStreamFilerReferenceManager;
FResourceManager : TAdvStreamFilerResourceManager;
FReferential : Boolean;
FPermitExternalStreamManipulation : Boolean;
{$IFOPT C+}
Function GetResourceManager: TAdvStreamFilerResourceManager;
{$ENDIF}
Procedure SetResourceManager(Const Value: TAdvStreamFilerResourceManager);
{$IFOPT C+}
Function GetReferenceManager: TAdvStreamFilerReferenceManager;
{$ENDIF}
Procedure SetReferenceManager(Const Value: TAdvStreamFilerReferenceManager);
{$IFOPT C+}
Function GetStream: TAdvStream;
{$ENDIF}
Procedure SetStream(oStream : TAdvStream);
Protected
Procedure ApplyStream; Virtual;
Public
Constructor Create; Override;
Destructor Destroy; Override;
Function Link : TAdvStreamFiler;
Procedure Clear; Virtual;
Function HasResourceManager : Boolean;
Function HasReferenceManager : Boolean;
Function HasStream : Boolean;
Property Stream : TAdvStream Read {$IFOPT C+}GetStream{$ELSE}FStream{$ENDIF} Write SetStream;
Property ResourceManager : TAdvStreamFilerResourceManager Read {$IFOPT C+}GetResourceManager{$ELSE}FResourceManager{$ENDIF} Write SetResourceManager;
Property ReferenceManager : TAdvStreamFilerReferenceManager Read {$IFOPT C+}GetReferenceManager{$ELSE}FReferenceManager{$ENDIF} Write SetReferenceManager;
Property Referential : Boolean Read FReferential Write FReferential;
Property PermitExternalStreamManipulation : Boolean Read FPermitExternalStreamManipulation Write FPermitExternalStreamManipulation;
End;
TAdvStreamFilerClass = Class Of TAdvStreamFiler;
TAdvObject = AdvObjects.TAdvObject;
TAdvObjectClass = AdvObjects.TAdvObjectClass;
Implementation
Procedure TAdvStreamFilerReferenceHashEntry.Assign(oSource: TAdvObject);
Begin
Inherited;
Key := TAdvStreamFilerReferenceHashEntry(oSource).Key;
Value := TAdvStreamFilerReferenceHashEntry(oSource).Value;
End;
Function TAdvStreamFilerReferenceHashTable.Equal(oA, oB: TAdvHashEntry): Integer;
Begin
Result := Inherited Equal(oA, oB);
If Result = 0 Then
Result := IntegerCompare(Integer(TAdvStreamFilerReferenceHashEntry(oA).Key), Integer(TAdvStreamFilerReferenceHashEntry(oB).Key));
End;
Function TAdvStreamFilerReferenceHashTable.ItemClass: TAdvHashEntryClass;
Begin
Result := TAdvStreamFilerReferenceHashEntry;
End;
Procedure TAdvStreamFilerReferenceHashEntry.Generate;
Begin
Inherited;
Code := HashIntegerToCode32(Integer(FKey));
End;
Procedure TAdvStreamFilerReferenceHashEntry.SetKey(Const Value: Pointer);
Begin
If FKey <> Value Then
Begin
FKey := Value;
Generate;
End;
End;
Constructor TAdvStreamFilerReferenceManager.Create;
Begin
Inherited;
FHashTable := TAdvStreamFilerReferenceHashTable.Create;
FHashTable.Capacity := 47;
FLookupHashEntry := TAdvStreamFilerReferenceHashEntry.Create;
End;
Destructor TAdvStreamFilerReferenceManager.Destroy;
Begin
FHashTable.Free;
FLookupHashEntry.Free;
Inherited;
End;
Function TAdvStreamFilerReferenceManager.Link: TAdvStreamFilerReferenceManager;
Begin
Result := TAdvStreamFilerReferenceManager(Inherited Link);
End;
Procedure TAdvStreamFilerReferenceManager.Clear;
Begin
FHashTable.Clear;
End;
Procedure TAdvStreamFilerReferenceManager.Bind(oKey, oValue: TAdvPersistent);
Var
oHashEntry : TAdvStreamFilerReferenceHashEntry;
Begin
If Assigned(oKey) Then
Begin
oHashEntry := TAdvStreamFilerReferenceHashEntry.Create;
oHashEntry.Key := Pointer(oKey);
oHashEntry.Value := Pointer(oValue);
FHashTable.Add(oHashEntry);
End;
End;
Function TAdvStreamFilerReferenceManager.Get(oKey : TAdvPersistent): TAdvPersistent;
Var
oHashEntry : TAdvStreamFilerReferenceHashEntry;
Begin
FLookupHashEntry.Key := Pointer(oKey);
oHashEntry := TAdvStreamFilerReferenceHashEntry(FHashTable.Get(FLookupHashEntry));
If Assigned(oHashEntry) Then
Result := TAdvPersistent(oHashEntry.Value)
Else
Result := Nil;
End;
Function TAdvStreamFilerReferenceManager.Exists(oKey: TAdvPersistent): Boolean;
Begin
FLookupHashEntry.Key := Pointer(oKey);
Result := FHashTable.Exists(FLookupHashEntry);
End;
Procedure TAdvStreamFilerResourceManager.Clear;
Begin
End;
Function TAdvStreamFilerResourceManager.ResolveObject(Const sResource: String; Const aClass : TAdvObjectClass): TAdvObject;
Begin
RaiseError('ResolveObject', 'ResolveObject must be overriden.');
Result := Nil;
End;
Function TAdvStreamFilerResourceManager.ResolveID(Const oObject: TAdvObject): String;
Begin
RaiseError('ResolveID', 'ResolveObject must be overriden.');
Result := '';
End;
Function TAdvStreamFilerResourceManager.Link : TAdvStreamFilerResourceManager;
Begin
Result := TAdvStreamFilerResourceManager(Inherited Link);
End;
Constructor TAdvStreamFiler.Create;
Begin
Inherited;
FReferenceManager := TAdvStreamFilerReferenceManager.Create;
FResourceManager := Nil;
FStream := Nil;
FReferential := True;
End;
Destructor TAdvStreamFiler.Destroy;
Begin
FStream.Free;
FReferenceManager.Free;
FResourceManager.Free;
Inherited;
End;
Function TAdvStreamFiler.Link : TAdvStreamFiler;
Begin
Result := TAdvStreamFiler(Inherited Link);
End;
{$IFOPT C+}
Function TAdvStreamFiler.GetStream: TAdvStream;
Begin
Assert(Invariants('GetStream', FStream, TAdvStream, 'FStream'));
Result := FStream;
End;
{$ENDIF}
Procedure TAdvStreamFiler.SetStream(oStream : TAdvStream);
Begin
Assert(Not Assigned(oStream) Or Invariants('SetStream', oStream, TAdvStream, 'oStream'));
FStream.Free;
FStream := oStream;
ApplyStream;
Clear;
End;
Function TAdvStreamFiler.HasStream: Boolean;
Begin
Result := Assigned(FStream);
End;
{$IFOPT C+}
Function TAdvStreamFiler.GetResourceManager : TAdvStreamFilerResourceManager;
Begin
Assert(Invariants('GetResourceManager', FResourceManager, TAdvStreamFilerResourceManager, 'FResourceManager'));
Result := FResourceManager;
End;
{$ENDIF}
Procedure TAdvStreamFiler.SetResourceManager(Const Value: TAdvStreamFilerResourceManager);
Begin
Assert((Not Assigned(Value)) Or Invariants('SetResourceManager', Value, TAdvStreamFilerResourceManager, 'Value'));
FResourceManager.Free;
FResourceManager := Value;
End;
Function TAdvStreamFiler.HasResourceManager : Boolean;
Begin
Result := Assigned(FResourceManager);
End;
{$IFOPT C+}
Function TAdvStreamFiler.GetReferenceManager : TAdvStreamFilerReferenceManager;
Begin
Assert(Invariants('GetReferenceManager', FReferenceManager, TAdvStreamFilerReferenceManager, 'FReferenceManager'));
Result := FReferenceManager;
End;
{$ENDIF}
Procedure TAdvStreamFiler.SetReferenceManager(Const Value: TAdvStreamFilerReferenceManager);
Begin
Assert((Not Assigned(Value)) Or Invariants('SetReferenceManager', Value, TAdvStreamFilerReferenceManager, 'Value'));
FReferenceManager.Free;
FReferenceManager := Value;
End;
Function TAdvStreamFiler.HasReferenceManager : Boolean;
Begin
Result := Assigned(FReferenceManager);
End;
Procedure TAdvStreamFiler.ApplyStream;
Begin
End;
Procedure TAdvStreamFiler.Clear;
Begin
If HasReferenceManager Then
ReferenceManager.Clear;
If HasResourceManager Then
ResourceManager.Clear;
End;
End. // AdvStreamFilers //
|
unit unModeloConsulta;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, StdCtrls, Buttons, DBClient, Grids, DBGrids,
Mask, StrUtils, SqlExpr, Provider, Data.FMTBcd, uniGUIForm, uniGUIBaseClasses,
uniGUIClasses, uniLabel, uniButton, uniBitBtn, uniMultiItem, uniComboBox,
uniEdit, uniBasicGrid, uniDBGrid, uniGUIApplication;
type
TfrmModeloConsulta = class(TUniForm)
dsPadrao: TDataSource;
sqldPesquisa: TSQLDataSet;
dspPesquisa: TDataSetProvider;
cdsPesquisa: TClientDataSet;
lbCampo: TUniLabel;
lbCondicao: TUniLabel;
lbDados: TUniLabel;
lbNumRegs: TUniLabel;
btnBuscar: TUniBitBtn;
btnOk: TUniBitBtn;
btnCancelar: TUniBitBtn;
cmbCondicao: TUniComboBox;
cmbCampo: TUniComboBox;
edtPesquisa: TUniEdit;
Grade: TUniDBGrid;
procedure btnCancelarClick(Sender: TObject);
procedure btnBuscarClick(Sender: TObject);
procedure GradeDblClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
procedure NumeroResgistros;
procedure ExecPesquisa(Valor, Campo: String; Condicao: Integer);
public
class function Execute(const Titulo, Table, FieldNames, DisplayLabels: String;
owner: TComponent): Integer;
end;
var
frmModeloConsulta: TfrmModeloConsulta;
implementation
uses Funcoes, VarGlobal;
{$R *.dfm}
procedure TfrmModeloConsulta.btnCancelarClick(Sender: TObject);
begin
Close;
end;
procedure TfrmModeloConsulta.btnBuscarClick(Sender: TObject);
begin
ExecPesquisa(edtPesquisa.Text, cdsPesquisa.Fields[ cmbCampo.ItemIndex ].FieldName,
cmbCondicao.ItemIndex);
end;
procedure TfrmModeloConsulta.GradeDblClick(Sender: TObject);
begin
btnOK.Click;
end;
procedure TfrmModeloConsulta.btnOkClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
class function TfrmModeloConsulta.Execute(const Titulo,
Table, FieldNames, DisplayLabels: String; owner: TComponent): Integer;
begin
Result := 0;
frmModeloConsulta := TfrmModeloConsulta.Create(owner);
with frmModeloConsulta do
try
Caption := Titulo;
cdsPesquisa.Close;
cdsPesquisa.CommandText := 'select * from '+Table;
cdsPesquisa.PacketRecords := -1;
cdsPesquisa.Open;
cdsPesquisa.FieldDefs.GetItemNames(cmbCampo.Items);
lbNumRegs.Caption := '';
ShowModal(procedure (Sender: TComponent; AResult: Integer)
begin
//FreeAndNil(frmModeloConsulta);
end);
finally
end;
end;
procedure TfrmModeloConsulta.ExecPesquisa(Valor, Campo: String; Condicao: Integer);
begin
// implementar
end;
procedure TfrmModeloConsulta.FormCreate(Sender: TObject);
begin
sqldPesquisa.SQLConnection := GetConnection;
end;
procedure TfrmModeloConsulta.NumeroResgistros;
begin
lbNumRegs.Caption := '';
if cdsPesquisa.Active then
begin
if cdsPesquisa.RecordCount = 1 then
lbNumRegs.Caption := '1 registro encontrado'
else if cdsPesquisa.RecordCount > 1 then
lbNumRegs.Caption := IntToStr(cdsPesquisa.RecordCount) + ' registros encontrados'
else
lbNumRegs.Caption := 'Nenhum registro encontrado.';
end
else
lbNumRegs.Caption := 'Nenhum registro encontrado.';
end;
procedure TfrmModeloConsulta.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
btnCancelar.Click;
if Key = VK_RETURN then
btnOk.Click;
end;
end.
|
inherited FrmRelTreinamento: TFrmRelTreinamento
Caption = 'Relatorio por Treinamento'
ClientWidth = 1021
ExplicitWidth = 1037
ExplicitHeight = 513
PixelsPerInch = 96
TextHeight = 13
inherited PanFundo: TPanel
Width = 1021
ExplicitWidth = 1021
inherited PanTitulo: TPanel
Top = 121
Width = 1017
ExplicitTop = 121
ExplicitWidth = 1017
inherited ImaBarraSup: TImage
Width = 1013
ExplicitWidth = 1013
end
end
inherited ToolBar: TToolBar
Width = 1017
ExplicitWidth = 1017
inherited ButPesquisar: TcxButton
OnClick = ButPesquisarClick
end
inherited ButImprimir: TcxButton
OnClick = ButImprimirClick
end
object ButExcel: TcxButton
Left = 167
Top = 0
Width = 36
Height = 33
Hint = 'Exportar para Excel (Alt+E)'
Caption = ' &E'
LookAndFeel.Kind = lfOffice11
LookAndFeel.NativeStyle = False
LookAndFeel.SkinName = 'Office2007Blue'
OptionsImage.Glyph.Data = {
36090000424D3609000000000000360000002800000018000000180000000100
2000000000000009000000000000000000000000000000000000000000090312
086B1E542ED771A680D2274F3398081F0E6001060328020202140808082E0202
0212000000030000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000184927CA1467
2EFF1E793BFEC2E5CDFFB0D8BFFFB4DAC2FFAADBB9FEA4CEB3F8E7EDECFABEC0
C0E5848585BF4B4C4C8E1D1D1D590707072A0101010D00000002000000000000
00000000000000000000000000000000000000000000000000000F4D23D61C78
3AFF208843FFB3DDC0FF7FCB9FFF87D9ABFF82DCA9FFA2D9BBFFFEFFFFFFF8FB
F9FFFFFFFFFFFFFFFFFFFDFEFEFEEEF0F0FABBBDBDE27E7F7FB9424343861717
1751040404220000000800000000000000000000000000000000115126D42080
41FF259149FFB1DBBFFF78C899FF80D6A6FF85DFAEFFAFE3C8FFFBFDFCFF8ECE
A9FFA5DCBCFFADDABEFFB1DCBFFFE6F3E9FFF7FBF9FFFCFEFDFFFFFFFFFFFEFF
FFFFE8ECECF9B0B4B3DD6E7271B03437367A0F10104501010111125227D32384
44FF28954DFFB2DABFFF72C493FF78D19EFF7EDAA7FFB2E1C9FFF2F9F5FF78C9
9EFF86D5ACFF79C99CFF64B883FFCBE4D2FFC5E5D2FF9EDBB9FFA6D9BAFFAEDB
BDFFEDF6F0FFEFF7F2FFF9FCFAFFFEFFFFFFF8FCFCFE4D52518F135127D12485
45FF2A964EFFB2DABFFF6ABE8BFF70CA95FF74D49EFFB6E1CBFFE8F4EDFF8CD9
B4FF8ED8B0FF89D2A8FF7DC598FFD9EADEFFB3DEC7FF86D6AEFF7CCC9FFF63B7
82FFE0EEE4FFB8E2CBFF95D7B2FF95D0ABFFC7E6D1FF4B4F4E89145229D02685
47FF2B9850FFB2D9BFFF62B783FF67C38CFF6ACC93FFBBE0CDFFF4FAF6FFD5F0
E0FFCFEBDAFFCBEAD6FFC6E6D0FFEBF4EDFFB9E6CFFFA0E1BFFF9ADAB5FF92D0
A8FFECF5EFFFA9DEC3FF86D6ACFF73C594FFACD4BAFF41464580155229CF2887
49FF2C9951FFB1D9BFFF5AB07AFF5EBB82FF60C388FFC1E1D0FFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF4FAF6FFE3F2E9FFDDF0E4FFD8ED
DEFFF9FBF9FFC1E8D4FFAAE0C2FFABDFBFFFD2EADBFF383C3B7716532ACF2A88
4AFF2E9A53FFB1D8BEFF52A872FF56B379FF57BA7EFFC9E3D6FFF8FBF9FFF7FB
F8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5F9F6FFC7E0CFFFD9E6DDFFF2F6
F3FFFFFFFFFFFEFEFEFFFFFFFFFFF8FDFCFFF2FBF9FF2F33326E17522BCE2C89
4CFF309B54FFB2D8BFFF4CA26BFF51AD73FF51B376FFD3E7DDFFF8FBF9FFADDD
C0FF9CD7B5FF82C69FFF8CC8A5FF98C9AAFF509C68FF228B45FF2C8349FF79B2
89FFF1F4F1FFA6DABDFFA0DAB9FF9ED4B2FFCAE9D7FF2A2D2C6518542DCF2E8A
4EFF319D56FFB2D7BFFF489D67FF52AA72FF52AE74FFDEECE6FFFFFFFFFFF0F7
F3FFA6DCBEFF91DAB5FF75C99CFF31874FFF1C793CFF277F46FF66A278FFEDF3
EEFFFFFFFFFF8FD4B1FF83D3A8FF6EC18FFFB3DAC3FF2023235B1A552DCF308B
50FF329E57FFB2D6BEFF449962FF51A770FF4FA76FFFEAF3EFFFFFFFFFFFFFFF
FFFFE3F1E8FF97D5B2FF398F58FF288347FF338951FF599B6FFF53AA71FFC4E4
CDFFFFFFFFFFA2DFC0FF9FDCBAFFAEE2C2FFD1ECDEFF1B1D1D521C5730D1328D
52FF34A059FFB1D5BDFF449861FF54A872FF51A46FFFF4F9F8FFFFFFFFFFFFFF
FFFFF8FBF9FF509566FF1D7E3EFF228142FF489160FFCBDFD1FFDAECDFFFD5E9
DAFFFFFFFFFFFFFFFFFFF9FCFAFFECF5EFFFEDF9F5FF151616481D5931D3348E
54FF35A25AFFAED3BBFF449962FF5BAD78FF5BA877FFF9FDFCFFFFFFFFFFF9FB
FAFF5F9F73FF208241FF228444FF43915DFF5FB280FF85BF99FFFDFEFEFFFFFF
FFFFFFFFFFFFADDDC1FFACDCC0FF9ED4B1FFD5EEE1FF111212401F5A33D5368F
56FF35A45AFFAED3BBFF48A168FF68B786FF6DB388FFFBFEFEFFF9FBFAFF7BB7
8CFF459860FF48A266FF50A26AFF8EC2A0FF68BB89FF5DB27DFFA8D2B5FFFFFF
FFFFFDFEFEFF7ECDA4FF80D0A5FF69BC89FFCAE6D7FF0D0E0E37205C34D73891
58FF39A75DFFB2D7BFFF48A76BFF7AC599FF83C29EFFFCFEFEFFDBE9DEFFACD1
B6FFA5CAB0FF9FCFAEFFDBECE0FFFBFDFBFF9BC9ABFF8FC4A1FF8DCB9FFFEAF3
ECFFFAFDFBFF94DCB8FF9FDEBBFFABE0BFFFDDF0E7FF090A0A2D225D35D83A92
59FF42A965FFB9DFC6FF42AB69FF8FD3AEFF98CEB2FFFCFEFEFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFEFEFEFFE9F6EEFFE7F3EBFFE4F0E8FFEAF6F3FE07070724225C36D83C92
5BFF4BA86CFFC3EBCFFF40AF68FF9EDEBFFFA8D7C0FFE2F1ECFFE6F3EDFFE3F2
EAFFDFEFE6FFDBEDE3FFD7EBE0FFD3E9DCFFCEE7D8FFC9E5D4FFC2E0CEFFB9DB
C6FFADD4BDFFAACFB8FFA9BCB1DB616464964F55548F0101010D225232C74A99
66FF46A167FF98D9ADFF8ED3A7FF92DDB6FFABE5C9FFA0DDBDFF92D3ADFF83C8
9EFF78C193FF74BF8FFF6FBC8AFF68B885FF61B37EFF58AF77FF4FA96FFF3F9F
61FF298E4DFF2D884EFF496E54AA000000000000000000000000102C1A95398A
56FF459E66FF5FB97EFFD6F1DFFF7DD69FFFB8EAD1FFACE1C4FF9CD7B4FF8DCD
A5FF81C59AFF7CC295FF77BF91FF70BB8BFF69B685FF60B17DFF56AC75FF45A0
66FF2C8D4EFF298449FF50785BB200000000000000000000000002060436337F
4DFE419660FF49A36AFF7FCC99FFD6F0DFFF82CE9FFFA1D9B8FFA2D6B6FF93CC
A8FF87C59DFF84C39AFF7FC096FF78BC90FF70B78AFF68B283FF5DAC79FF4CA0
6AFF2D8A4EFF2A8149FF567E63B900000000000000000000000000000000112D
1A96378553FF429661FF48A068FF73C48EFFC8EDD3FFBCDDC8FF9FCEB0FF92C5
A5FF8AC09DFF85BD99FF81BA95FF79B78FFF72B389FF68AC80FF5FA779FF4E9C
6AFF358A53FF3A8855FF668A71C0000000000000000000000000000000000000
00030F27188D337C4DFB3C8C59FF41935FFF4BA169FF58B476FF74C48DFF80CA
97FF85CD9BFF8AD09FFF8FD3A4FF94D5A8FF97D6AAFF9AD8ADFF9BD9AEFF9CD9
AFFF9EDAB0FFB1E3C0FF6C9077C7000000000000000000000000000000000000
000000000000010302260E241685255335C536744BE732784AF032794BF1347A
4DF4347C4DF6357D4EF8357E4EFA35804FFB35804FFB35804FFB35804FFD3980
51FD337148F00F26168E0102011F000000000000000000000000}
OptionsImage.Margin = 5
TabOrder = 4
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = [fsBold]
ParentFont = False
OnClick = ButExcelClick
end
end
inherited StatusBar: TdxStatusBar
Width = 1017
ExplicitWidth = 1017
end
object cxFiltro: TcxGroupBox
Left = 2
Top = 2
Align = alTop
Caption = 'Parametros'
ParentFont = False
Style.Font.Charset = DEFAULT_CHARSET
Style.Font.Color = clWindowText
Style.Font.Height = -10
Style.Font.Name = 'MS Sans Serif'
Style.Font.Style = [fsBold]
Style.IsFontAssigned = True
TabOrder = 3
Height = 119
Width = 1017
object Panel1: TPanel
Tag = -1
Left = 10
Top = 18
Width = 707
Height = 27
Alignment = taLeftJustify
BevelInner = bvLowered
Caption = ' Treinamento'
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 0
object spbLimpaTreinamento: TcxButton
Left = 675
Top = 3
Width = 26
Height = 23
Hint = 'Limpar campo Treinamento'
OptionsImage.Glyph.Data = {
F6000000424DF600000000000000760000002800000010000000100000000100
0400000000008000000000000000000000001000000000000000000000000000
80000080000000808000800000008000800080800000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777777777777777777777000000077777777077777700777777707777770307
77777077777703307777770FBFBFB03307777770FBFBFB03307777770FBFBFB0
3307777770FBFBFB03077777770FBFBFB00777777770FBFBFB07777777770000
0077777777777777777777777777777777777777777777777777}
ParentShowHint = False
ShowHint = True
TabOrder = 0
OnClick = spbLimpaTreinamentoClick
end
object EditBuscaTreinamento: TEditBusca
Left = 198
Top = 3
Width = 466
Height = 22
TabOrder = 1
ClickOnArrow = True
ClickOnReturn = False
bs_HeightForm = 0
bs_WidthForm = 0
bs_SetCPF = False
bs_SetCNPJ = False
bs_SetPlaca = False
bs_LoadConsulta = False
bs_Distinct = False
bs_SetColor = False
bs_NomeCor = clBlack
bs_IndiceCampo = 0
bs_Imagem = False
bs_HideTop = False
bs_Top100 = False
end
end
object Panel11: TPanel
Tag = -1
Left = 10
Top = 75
Width = 707
Height = 33
Alignment = taLeftJustify
BevelInner = bvLowered
Caption = ' Obrigat'#243'rio para Cargo ou Fun'#231#227'o'
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 1
object rgObrigacao: TcxRadioGroup
Tag = -2
Left = 198
Top = 1
ParentFont = False
Properties.Columns = 3
Properties.Items = <
item
Caption = 'Sim'
Value = 'S'
end
item
Caption = 'N'#227'o'
Value = 'N'
end
item
Caption = 'Ambos'
end>
ItemIndex = 0
Style.Font.Charset = DEFAULT_CHARSET
Style.Font.Color = clWindowText
Style.Font.Height = -10
Style.Font.Name = 'MS Sans Serif'
Style.Font.Style = [fsBold]
Style.IsFontAssigned = True
TabOrder = 0
Height = 29
Width = 223
end
end
object Panel10: TPanel
Tag = -1
Left = 10
Top = 47
Width = 707
Height = 27
Alignment = taLeftJustify
BevelInner = bvLowered
Caption = ' Periodicidade'
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 2
object editxtPeriodicidade: TrsSuperEdit
Tag = -1
Left = 327
Top = 11
Width = 0
Height = 22
Alignment = taRightJustify
Format = foInteger
TagName = 'TRE_PERIODICIDADE'
CT_NumFields = 0
CT_RetField1 = 0
CT_RetField2 = 0
CT_Test = False
CT_ConsTab = False
CT_Search = False
Text = ''
Font.Charset = ANSI_CHARSET
Font.Color = clBlack
Font.Height = -11
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 0
Visible = False
end
object spbLimpaPeriodicidade: TcxButton
Left = 675
Top = 2
Width = 26
Height = 23
Hint = 'Limpar campo Periodicidade'
OptionsImage.Glyph.Data = {
F6000000424DF600000000000000760000002800000010000000100000000100
0400000000008000000000000000000000001000000000000000000000000000
80000080000000808000800000008000800080800000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00777777777777
7777777777777777777777000000077777777077777700777777707777770307
77777077777703307777770FBFBFB03307777770FBFBFB03307777770FBFBFB0
3307777770FBFBFB03077777770FBFBFB00777777770FBFBFB07777777770000
0077777777777777777777777777777777777777777777777777}
ParentShowHint = False
ShowHint = True
TabOrder = 1
OnClick = spbLimpaPeriodicidadeClick
end
object EditBuscaPeriodo: TEditBusca
Left = 198
Top = 3
Width = 466
Height = 22
TabOrder = 2
ClickOnArrow = True
ClickOnReturn = False
bs_HeightForm = 0
bs_WidthForm = 0
bs_SetCPF = False
bs_SetCNPJ = False
bs_SetPlaca = False
bs_LoadConsulta = False
bs_Distinct = False
bs_SetColor = False
bs_NomeCor = clBlack
bs_IndiceCampo = 0
bs_Imagem = False
bs_HideTop = False
bs_Top100 = False
end
end
end
object cxGrid1: TcxGrid
Left = 2
Top = 123
Width = 1017
Height = 291
Align = alClient
TabOrder = 4
object cxGrid1DBTableView1: TcxGridDBTableView
Navigator.Buttons.CustomButtons = <>
DataController.DataSource = DSGrid
DataController.Summary.DefaultGroupSummaryItems = <>
DataController.Summary.FooterSummaryItems = <>
DataController.Summary.SummaryGroups = <>
OptionsData.CancelOnExit = False
OptionsData.Deleting = False
OptionsData.DeletingConfirmation = False
OptionsData.Editing = False
OptionsData.Inserting = False
OptionsView.Indicator = True
object cxGrid1DBTableView1CUR_NOMCURSO: TcxGridDBColumn
Caption = 'Nome do Treinamento'
DataBinding.FieldName = 'CUR_NOMCURSO'
Width = 193
end
object cxGrid1DBTableView1INS_NOMINSTRUTOR: TcxGridDBColumn
Caption = 'Instrutor'
DataBinding.FieldName = 'INS_NOMINSTRUTOR'
Width = 243
end
object cxGrid1DBTableView1TRE_DTREALIZACAO: TcxGridDBColumn
Caption = 'Dt Inicio'
DataBinding.FieldName = 'TRE_DTREALIZACAO'
Width = 101
end
object cxGrid1DBTableView1TRE_DTTERMINO: TcxGridDBColumn
Caption = 'Dt T'#233'rmino'
DataBinding.FieldName = 'TRE_DTTERMINO'
Width = 103
end
object cxGrid1DBTableView1DESCRICAO: TcxGridDBColumn
Caption = 'Periodicidade'
DataBinding.FieldName = 'DESCRICAO'
Width = 282
end
object cxGrid1DBTableView1TRE_OBRIGATORIO: TcxGridDBColumn
Caption = 'Obrigat'#243'rio'
DataBinding.FieldName = 'TRE_OBRIGATORIO'
Width = 75
end
end
object cxGrid1Level1: TcxGridLevel
GridView = cxGrid1DBTableView1
end
end
end
inherited DSGrid: TDataSource
DataSet = QGrid
Left = 549
Top = 206
end
inherited TimerCad: TTimer
Left = 666
Top = 234
end
inherited dspGrid: TDataSetProvider
Left = 579
Top = 316
end
inherited cdsGrid: TClientDataSet
Left = 612
Top = 320
object cdsGridCUR_NOMCURSO: TStringField
FieldName = 'CUR_NOMCURSO'
Size = 100
end
object cdsGridTRE_DTREALIZACAO: TSQLTimeStampField
FieldName = 'TRE_DTREALIZACAO'
end
object cdsGridTRE_DTTERMINO: TSQLTimeStampField
FieldName = 'TRE_DTTERMINO'
end
object cdsGridDESCRICAO: TStringField
FieldName = 'DESCRICAO'
Size = 50
end
object cdsGridTRE_OBRIGATORIO: TStringField
FieldName = 'TRE_OBRIGATORIO'
FixedChar = True
Size = 1
end
end
object dxComponentPrinter: TdxComponentPrinter [5]
CurrentLink = dxPrinterGrid
Options = [cpoAutoRebuildBeforePreview, cpoAutoRebuildBeforePrint, cpoGenerateReportProgressEvent, cpoDropStorageModeAfterPreview]
Version = 0
Left = 424
Top = 232
object dxPrinterGrid: TdxGridReportLink
Component = cxGrid1
PageNumberFormat = pnfNumeral
PrinterPage.DMPaper = 9
PrinterPage.Footer = 6350
PrinterPage.Header = 6350
PrinterPage.Margins.Bottom = 12700
PrinterPage.Margins.Left = 12700
PrinterPage.Margins.Right = 12700
PrinterPage.Margins.Top = 12700
PrinterPage.PageSize.X = 210000
PrinterPage.PageSize.Y = 297000
PrinterPage._dxMeasurementUnits_ = 0
PrinterPage._dxLastMU_ = 2
ReportTitle.Text = 'Relat'#243'rio por Treinamento'
AssignedFormatValues = [fvDate, fvTime, fvPageNumber]
BuiltInReportLink = True
end
end
object SaveDialog: TSaveDialog [6]
DefaultExt = '*.xlsx'
Filter = 'Arquivos Excel|*.xlsx'
Left = 432
Top = 320
end
inherited QGrid: TFDQuery
SQL.Strings = (
'Select T.CUR_NOMCURSO, T.TRE_DTREALIZACAO,'
' T.TRE_DTTERMINO, PR.DESCRICAO, T.TRE_OBRIGATORIO, I.INS_NOMINST' +
'RUTOR'
' from TRE_TREINAMENTO T'
' inner join TRE_TREINAMENTO P on P.TRE_TREINAMENTO_ID = T.TRE_TR' +
'EINAMENTO_ID'
' inner join TRE_FUNCIONARIO F on F.FUN_MATRICULA = P.FUN_MATRICU' +
'LA'
' inner join TRE_PERIODICIDADE PR on PR.PERIODICIDADE_ID = T.TRE_' +
'PERIODICIDADE'
' INNER JOIN TRE_INSTRUTOR I ON I.INS_ID = T.INS_ID'
' Where 1 = 1')
Left = 608
Top = 208
object QGridCUR_NOMCURSO: TStringField
FieldName = 'CUR_NOMCURSO'
Origin = 'CUR_NOMCURSO'
Size = 100
end
object QGridTRE_DTREALIZACAO: TSQLTimeStampField
FieldName = 'TRE_DTREALIZACAO'
Origin = 'TRE_DTREALIZACAO'
end
object QGridTRE_DTTERMINO: TSQLTimeStampField
FieldName = 'TRE_DTTERMINO'
Origin = 'TRE_DTTERMINO'
end
object QGridDESCRICAO: TStringField
FieldName = 'DESCRICAO'
Origin = 'DESCRICAO'
Size = 50
end
object QGridTRE_OBRIGATORIO: TStringField
FieldName = 'TRE_OBRIGATORIO'
Origin = 'TRE_OBRIGATORIO'
FixedChar = True
Size = 1
end
object QGridINS_NOMINSTRUTOR: TStringField
FieldName = 'INS_NOMINSTRUTOR'
Origin = 'INS_NOMINSTRUTOR'
Size = 100
end
end
end
|
unit fmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TfrmMain = class(TForm)
led1: TLabeledEdit;
btStart: TButton;
btStop: TButton;
laThreadsRunning: TLabel;
procedure btStartClick(Sender: TObject);
procedure btStopClick(Sender: TObject);
private
FThreadList :TList;
procedure ThreadTerminated(Sender: TObject);
procedure UpdateThreadCount;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
var
frmMain: TfrmMain;
implementation
uses
unClientUpdateThread;
{$R *.dfm}
procedure TfrmMain.AfterConstruction;
begin
inherited;
FThreadList := TList.Create;
laThreadsRunning.Caption := Format('%d Threads are Running',[FThreadList.Count]);
end;
procedure TfrmMain.BeforeDestruction;
begin
FThreadList.Free;
inherited;
end;
procedure TfrmMain.btStartClick(Sender: TObject);
var
nMax,
I :integer;
aThread :TUpdateClientThread;
begin
nMax := StrToInt(led1.Text);
for I := 1 to nMax do
begin
aThread := TUpdateClientThread.Create(True);
aThread.URI := 'http://localhost:8080/soap/IUpdateService';
aThread.OnTerminate := ThreadTerminated;
aThread.FreeOnTerminate := False;
FThreadList.Add(aThread);
aThread.Resume;
ThreadTerminated(Self);
end;
end;
procedure TfrmMain.btStopClick(Sender: TObject);
var
I :integer;
aThread :TUpdateClientThread;
begin
for I := FThreadList.Count -1 downto 0 do
begin
aThread := TUpdateClientThread(FThreadList[I]);
FThreadList.Remove(aThread);
aThread.Terminate;
aThread.WaitFor;
aThread.Free;
ThreadTerminated(Self);
end;
end;
procedure TfrmMain.ThreadTerminated(Sender: TObject);
begin
UpdateThreadCount;
end;
procedure TfrmMain.UpdateThreadCount;
begin
laThreadsRunning.Caption := Format('%d Threads are Running',[FThreadList.Count]);
Application.ProcessMessages;
end;
end.
|
{
Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit DataGrabber.DataView.cxGrid;
interface
{$I DataGrabber.inc}
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus,
Vcl.ActnList, Vcl.ToolWin, Vcl.ComCtrls,
Data.DB,
cxStyles, cxCustomData, cxGraphics, cxDataStorage, cxEdit,
cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxInplaceContainer,
cxVGrid, cxOI, cxGridCustomPopupMenu, cxGridPopupMenu,
cxLookAndFeels, cxLookAndFeelPainters, cxGridCardView, cxGridBandedTableView,
cxGridDBCardView, cxGridDBBandedTableView, cxNavigator, cxFilter, cxData,
DataGrabber.Interfaces, DataGrabber.DataView.Base;
type
TfrmcxGrid = class(TBaseDataView, IDataView, IGroupable, IMergable)
grdMain : TcxGrid;
grlMain : TcxGridLevel;
ppmMain : TcxGridPopupMenu;
tvwMain : TcxGridDBTableView;
procedure tvwMainCustomDrawGroupSummaryCell(
Sender : TObject;
ACanvas : TcxCanvas;
ARow : TcxGridGroupRow;
AColumn : TcxGridColumn;
ASummaryItem : TcxDataSummaryItem;
AViewInfo : TcxCustomGridViewCellViewInfo;
var ADone : Boolean
);
procedure tvwMainCustomDrawCell(
Sender : TcxCustomGridTableView;
ACanvas : TcxCanvas;
AViewInfo : TcxGridTableDataCellViewInfo;
var ADone : Boolean
);
procedure tvwMainCustomDrawColumnHeader(
Sender : TcxGridTableView;
ACanvas : TcxCanvas;
AViewInfo : TcxGridColumnHeaderViewInfo;
var ADone : Boolean
);
private
FMergeColumnCells : Boolean;
FAutoSizeCols : Boolean;
protected
{$REGION 'property access methods'}
function GetRecordCount: Integer; override;
function GetMergeColumnCells: Boolean;
procedure SetMergeColumnCells(const Value: Boolean);
function GetAutoSizeCols: Boolean;
procedure SetAutoSizeCols(const Value: Boolean);
function GetPopupMenu: TPopupMenu; reintroduce;
procedure SetPopupMenu(const Value: TPopupMenu); override;
function GetGridType: string; override;
{$ENDREGION}
procedure ApplyGridSettings; override;
procedure CopySelectionToClipboard(
AController : TcxGridTableController;
AIncludeHeader : Boolean = False
);
function ResultsToWikiTable(
AIncludeHeader: Boolean = False
): string; virtual;
function ResultsToTextTable(
AIncludeHeader: Boolean = False
): string; virtual;
function SelectionToDelimitedTable(
AController : TcxGridTableController;
ADelimiter : string = #9; // TAB
AIncludeHeader : Boolean = True
): string; reintroduce; overload;
function SelectionToCommaText(
AController : TcxGridTableController;
AQuoteItems : Boolean = True
): string; reintroduce; overload;
function SelectionToFields(
AController : TcxGridTableController;
AQuoteItems : Boolean = True
): string; reintroduce; overload;
function SelectionToTextTable(
AController : TcxGridTableController;
AIncludeHeader : Boolean = False
): string; reintroduce; overload;
function SelectionToWikiTable(
AController : TcxGridTableController;
AIncludeHeader : Boolean = False
): string; reintroduce; overload;
public
procedure AfterConstruction; override;
procedure HideSelectedColumns; override;
procedure MergeAllColumnCells(AActive: Boolean);
procedure AutoSizeColumns; override;
procedure GroupBySelectedColumns;
procedure ExpandAll;
procedure CollapseAll;
procedure ClearGrouping;
procedure Copy; override;
procedure Inspect; override;
procedure UpdateView; override;
procedure BeginUpdate; override;
procedure EndUpdate; override;
function SelectionToWikiTable(
AIncludeHeader : Boolean = False
): string; overload; override;
function SelectionToTextTable(
AIncludeHeader : Boolean = False
): string; overload; override;
function SelectionToDelimitedTable(
ADelimiter : string = #9; // TAB
AIncludeHeader : Boolean = True
): string; overload; override;
function SelectionToCommaText(
AQuoteItems : Boolean = True
): string; overload; override;
function SelectionToFields(
AQuoteItems : Boolean = True
): string; overload; override;
property MergeColumnCells: Boolean
read GetMergeColumnCells write SetMergeColumnCells;
property AutoSizeCols: Boolean
read GetAutoSizeCols write SetAutoSizeCols;
property PopupMenu: TPopupMenu
read GetPopupMenu write SetPopupMenu;
end;
implementation
{$R *.dfm}
uses
System.StrUtils, System.UITypes,
Vcl.Clipbrd,
cxGridDBDataDefinitions, cxGridCommon,
DDuce.ObjectInspector.zObjectInspector, DDuce.Logger,
DataGrabber.Utils;
{$REGION 'construction and destruction'}
procedure TfrmcxGrid.AfterConstruction;
begin
inherited AfterConstruction;
FAutoSizeCols := True;
UpdateView;
end;
{$ENDREGION}
{$REGION 'property access methods'}
function TfrmcxGrid.GetRecordCount: Integer;
begin
Result := tvwMain.DataController.RecordCount;
end;
function TfrmcxGrid.GetMergeColumnCells: Boolean;
begin
Result := FMergeColumnCells;
end;
procedure TfrmcxGrid.SetMergeColumnCells(const Value: Boolean);
begin
if Value <> MergeColumnCells then
begin
FMergeColumnCells := Value;
MergeAllColumnCells(Value);
end;
end;
function TfrmcxGrid.GetPopupMenu: TPopupMenu;
begin
Result := TPopupMenu(grdMain.PopupMenu);
end;
procedure TfrmcxGrid.SetPopupMenu(const Value: TPopupMenu);
begin
grdMain.PopupMenu := Value;
end;
function TfrmcxGrid.GetGridType: string;
begin
Result := 'cxGrid';
end;
function TfrmcxGrid.GetAutoSizeCols: Boolean;
begin
Result := FAutoSizeCols;
end;
procedure TfrmcxGrid.SetAutoSizeCols(const Value: Boolean);
begin
if Value <> AutoSizeCols then
begin
FAutoSizeCols := Value;
if Value then
begin
tvwMain.OptionsBehavior.BestFitMaxRecordCount := 100;
AutoSizeColumns;
end;
end;
end;
{$ENDREGION}
{$REGION 'event handlers'}
procedure TfrmcxGrid.tvwMainCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
var
VTC: TcxValueTypeClass;
begin
if Assigned(Settings) and Settings.GridCellColoring then
begin
if AViewInfo.Text = '0' then
ACanvas.Font.Color := clBlue;
if AViewInfo.Text = '' then
begin
ACanvas.Brush.Color := $00EFEFEF;
end
else
begin
VTC := AViewInfo.Item.DataBinding.ValueTypeClass;
if (VTC = TcxDateTimeValueType) or (VTC = TcxSQLTimeStampValueType) then
begin
ACanvas.Brush.Color := Settings.DataTypeColors[dtDateTime];
end
else if (VTC = TcxStringValueType) or (VTC = TcxWideStringValueType) then
begin
ACanvas.Brush.Color := Settings.DataTypeColors[dtString];
end
else if (VTC = TcxIntegerValueType) or (VTC = TcxWordValueType)
or (VTC = TcxSmallintValueType) or (VTC = TcxLargeIntValueType) then
begin
ACanvas.Brush.Color := Settings.DataTypeColors[dtInteger];
end
else if (VTC = TcxFloatValueType) or (VTC = TcxCurrencyValueType)
or (VTC = TcxFMTBcdValueType) then
begin
ACanvas.Brush.Color := Settings.DataTypeColors[dtFloat];
end
else if VTC = TcxBooleanValueType then
begin
ACanvas.Brush.Color := Settings.DataTypeColors[dtBoolean];
end;
end;
if AViewInfo.Selected then
begin
ACanvas.Brush.Color := clGray;
ACanvas.Font.Color := clWhite;
end;
end;
end;
procedure TfrmcxGrid.tvwMainCustomDrawColumnHeader(Sender: TcxGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridColumnHeaderViewInfo;
var ADone: Boolean);
begin
ACanvas.Font.Style := ACanvas.Font.Style + [fsBold];
end;
procedure TfrmcxGrid.tvwMainCustomDrawGroupSummaryCell(Sender: TObject;
ACanvas: TcxCanvas; ARow: TcxGridGroupRow; AColumn: TcxGridColumn;
ASummaryItem: TcxDataSummaryItem;
AViewInfo: TcxCustomGridViewCellViewInfo; var ADone: Boolean);
begin
if not ARow.Selected then
ACanvas.Font.Color := clBlue
else
ACanvas.Font.Color := clWhite;
end;
{$ENDREGION}
{$REGION 'private methods'}
procedure TfrmcxGrid.Copy;
begin
Clipboard.AsText := Trim(SelectionToDelimitedTable(#9, False));
end;
procedure TfrmcxGrid.CopySelectionToClipboard(AController: TcxGridTableController;
AIncludeHeader: Boolean);
var
X, Y : Integer;
S, T : string;
V : Variant;
SL : TStringList;
begin
SL := TStringList.Create;
try
if AIncludeHeader then
begin
S := ',';
for X := 0 to AController.SelectedColumnCount -1 do
begin
S := S + tvwMain.Columns[AController.SelectedColumns[X].Index].Caption + ',';
end;
SL.Add(S);
end;
for Y := 0 to AController.SelectedRowCount - 1 do
begin
S := ',';
for X := 0 to AController.SelectedColumnCount -1 do
begin
V := AController.SelectedRows[Y].Values[AController.SelectedColumns[X].Index];
T := VarToStr(V);
if T = '' then
T := ' ';
S := S + T + ',';
end;
SL.Add(S);
end;
Clipboard.AsText := SL.Text;
finally
FreeAndNil(SL);
end;
end;
procedure TfrmcxGrid.EndUpdate;
begin
tvwMain.EndUpdate;
end;
procedure TfrmcxGrid.ClearGrouping;
var
I : Integer;
begin
for I := 0 to tvwMain.GroupedColumnCount - 1 do
begin
tvwMain.GroupedColumns[I].GroupIndex := -1;
end;
end;
procedure TfrmcxGrid.CollapseAll;
begin
tvwMain.ViewData.Collapse(True);
end;
procedure TfrmcxGrid.ExpandAll;
begin
tvwMain.ViewData.Expand(True);
end;
function TfrmcxGrid.SelectionToDelimitedTable(
AController: TcxGridTableController; ADelimiter: string;
AIncludeHeader: Boolean): string;
var
X, Y : Integer;
S, T : string;
V : Variant;
SL : TStringList;
begin
SL := TStringList.Create;
try
S := '';
if AIncludeHeader then
begin
for X := 0 to AController.SelectedColumnCount -1 do
begin
S := S + tvwMain.Columns[AController.SelectedColumns[X].Index].Caption ;
if X < AController.SelectedColumnCount -1 then
S := S + ADelimiter;
end;
SL.Add(S);
end;
for Y := 0 to AController.SelectedRowCount - 1 do
begin
S := '';
for X := 0 to AController.SelectedColumnCount -1 do
begin
V := AController.SelectedRows[Y].Values[AController.SelectedColumns[X].Index];
T := VarToStr(V);
S := S + T;
if X < AController.SelectedColumnCount -1 then
S := S + ADelimiter;
end;
SL.Add(S);
end;
Result := SL.Text;
finally
FreeAndNil(SL);
end;
end;
function TfrmcxGrid.SelectionToWikiTable(AController: TcxGridTableController;
AIncludeHeader: Boolean): string;
var
X, Y : Integer;
S, T : string;
V : Variant;
SL : TStringList;
begin
SL := TStringList.Create;
try
if AIncludeHeader then
begin
S := '||';
for X := 0 to AController.SelectedColumnCount -1 do
begin
S := S + tvwMain.Columns[AController.SelectedColumns[X].Index].Caption + '||';
end;
SL.Add(S);
end;
for Y := 0 to AController.SelectedRowCount - 1 do
begin
S := '|';
for X := 0 to AController.SelectedColumnCount -1 do
begin
V := AController.SelectedRows[Y].Values[AController.SelectedColumns[X].Index];
T := VarToStr(V);
if T = '' then
T := ' ';
S := S + T + '|';
end;
SL.Add(S);
end;
Result := SL.Text;
finally
FreeAndNil(SL);
end;
end;
function TfrmcxGrid.SelectionToCommaText(AController: TcxGridTableController;
AQuoteItems: Boolean): string;
var
X, Y : Integer;
S, T : string;
V : Variant;
CCount : Integer;
RCount : Integer;
begin
S := '';
CCount := AController.SelectedColumnCount;
RCount := AController.SelectedRowCount;
for Y := 0 to RCount - 1 do
begin
for X := 0 to CCount - 1 do
begin
V := AController.SelectedRows[Y].Values[AController.SelectedColumns[X].Index];
T := VarToStr(V);
if AQuoteItems then
T := QuotedStr(T);
S := S + T;
if X < CCount -1 then
S := S + ', ';
end;
if (CCount = 1) and (Y < RCount - 1) then
S := S + ', '
else if Y < RCount - 1 then
S := S + #13#10
end;
Result := S;
end;
function TfrmcxGrid.SelectionToTextTable(AController: TcxGridTableController;
AIncludeHeader: Boolean): string;
var
X, Y : Integer;
S : string;
V : Variant;
F : TField;
I : Integer;
N : Integer;
sTxt : string;
sLine : string;
sFmt : string;
Widths : array of Integer;
SL : TStringList;
begin
SetLength(Widths, AController.SelectedColumnCount);
try
SL := TStringList.Create;
try
for X := 0 to AController.SelectedColumnCount -1 do
begin
I := AController.SelectedColumns[X].Index;
SL.Clear;
if AIncludeHeader then
begin
F := tvwMain.Columns[I].DataBinding.Field;
SL.Add(F.FieldName);
end;
for Y := 0 to AController.SelectedRowCount - 1 do
begin
V := AController.SelectedRows[Y].Values[I];
S := VarToStr(V);
SL.Add(S);
end;
Widths[X] := GetMaxTextWidth(SL);
end;
finally
FreeAndNil(SL);
end;
if AIncludeHeader then
begin
for X := 0 to AController.SelectedColumnCount -1 do
begin
I := AController.SelectedColumns[X].Index;
F := tvwMain.Columns[I].DataBinding.Field;
N := Widths[X];
sFmt := '%-' + IntToStr(N) + 's';
sLine := sLine + '+' + Format(sFmt, [DupeString('-', N)]);
sTxt := sTxt + '|' + Format(sFmt, [F.FieldName]);
end;
sTxt := sTxt + '|';
sLine := sLine + '+';
Result := sLine + #13#10 + sTxt + #13#10 + sLine;
end;
for Y := 0 to AController.SelectedRowCount - 1 do
begin
sTxt := '';
for X := 0 to AController.SelectedColumnCount -1 do
begin
I := AController.SelectedColumns[X].Index;
V := AController.SelectedRows[Y].Values[I];
S := VarToStr(V);
F := tvwMain.Columns[I].DataBinding.Field;
if Assigned(F) then
begin
N := Widths[X];
sFmt := '%-' + IntToStr(N) + 's';
sTxt := sTxt + '|' + Format(sFmt, [S]);
end;
end;
sTxt := sTxt + '|';
Result := Result + #13#10 + sTxt;
sTxt := '';
end;
Result := Result + #13#10 + sLine;
finally
Finalize(Widths);
end;
end;
{$ENDREGION}
{$REGION 'public methods'}
procedure TfrmcxGrid.UpdateView;
begin
if Assigned(DataSet) and DataSet.Active then
begin
tvwMain.ClearItems;
tvwMain.DataController.CreateAllItems;
BeginUpdate;
try
ApplyGridSettings;
AutoSizeColumns;
finally
EndUpdate;
end;
end;
end;
function TfrmcxGrid.SelectionToWikiTable(AIncludeHeader: Boolean): string;
begin
Result := SelectionToWikiTable(tvwMain.Controller, AIncludeHeader);
end;
function TfrmcxGrid.SelectionToCommaText(AQuoteItems: Boolean): string;
begin
Result := SelectionToCommaText(tvwMain.Controller, AQuoteItems);
end;
function TfrmcxGrid.SelectionToTextTable(AIncludeHeader: Boolean): string;
begin
Result := SelectionToTextTable(tvwMain.Controller, AIncludeHeader);
end;
procedure TfrmcxGrid.HideSelectedColumns;
var
C : TcxGridTableController;
I : Integer;
J : Integer;
F : TField;
begin
BeginUpdate;
try
C := tvwMain.Controller;
for I := 0 to C.SelectedColumnCount - 1 do
begin
J := C.SelectedColumns[I].Index;
tvwMain.Columns[J].Visible := False;
F := tvwMain.Columns[J].DataBinding.Field;
Data.HideField(F.DataSet, F.FieldName);
end;
finally
EndUpdate;
end;
end;
procedure TfrmcxGrid.Inspect;
begin
InspectObject(tvwMain);
end;
procedure TfrmcxGrid.MergeAllColumnCells(AActive: Boolean);
var
I: Integer;
begin
BeginUpdate;
try
for I := 0 to tvwMain.ColumnCount - 1 do
begin
tvwMain.Columns[I].Options.CellMerging := AActive;
tvwMain.Columns[I].Options.GroupFooters := True;
end;
finally
EndUpdate;
end;
end;
function TfrmcxGrid.ResultsToTextTable(AIncludeHeader: Boolean): string;
begin
//
end;
function TfrmcxGrid.ResultsToWikiTable(AIncludeHeader: Boolean): string;
var
X, Y : Integer;
S, T : string;
V : Variant;
SL : TStringList;
begin
SL := TStringList.Create;
try
if AIncludeHeader then
begin
S := '||';
for X := 0 to tvwMain.VisibleColumnCount - 1 do
begin
S := S + tvwMain.VisibleColumns[X].Caption + '||';
end;
SL.Add(S);
end;
for Y := 0 to tvwMain.ViewData.RowCount - 1 do
begin
S := '|';
for X := 0 to tvwMain.VisibleColumnCount -1 do
begin
V := tvwMain.ViewData.Rows[Y].Values[tvwMain.VisibleColumns[X].Index];
T := VarToStr(V);
if T = '' then
T := ' ';
S := S + T + '|';
end;
SL.Add(S);
end;
Result := SL.Text;
finally
FreeAndNil(SL);
end;
end;
procedure TfrmcxGrid.AutoSizeColumns;
var
I: Integer;
begin
BeginUpdate;
try
tvwMain.ApplyBestFit;
for I := 0 to tvwMain.ColumnCount - 1 do
begin
tvwMain.Columns[I].Width := tvwMain.Columns[I].Width + 10;
end;
finally
EndUpdate;
end;
end;
procedure TfrmcxGrid.BeginUpdate;
begin
tvwMain.BeginUpdate;
end;
procedure TfrmcxGrid.GroupBySelectedColumns;
var
C : TcxGridTableController;
I : Integer;
Col : TcxGridDBColumn;
GroupIndex : Integer;
begin
BeginUpdate;
try
C := tvwMain.Controller;
for I := 0 to C.SelectedColumnCount - 1 do
begin
Col := tvwMain.Columns[C.SelectedColumns[I].Index];
if Col.GroupIndex <> -1 then
GroupIndex := -1
else
GroupIndex := tvwMain.GroupedColumnCount;
Col.GroupBy(GroupIndex);
end;
finally
EndUpdate;
end;
end;
function TfrmcxGrid.SelectionToDelimitedTable(ADelimiter: string;
AIncludeHeader: Boolean): string;
begin
Result :=
SelectionToDelimitedTable(tvwMain.Controller, ADelimiter, AIncludeHeader);
end;
function TfrmcxGrid.SelectionToFields(AController: TcxGridTableController;
AQuoteItems: Boolean): string;
var
X : Integer;
S, T : string;
SL : TStringList;
begin
SL := TStringList.Create;
try
S := '';
for X := 0 to AController.SelectedColumnCount -1 do
begin
T := tvwMain.Columns[AController.SelectedColumns[X].Index].Caption;
if AQuoteItems then
T := QuotedStr(T);
S := S + T;
if X < AController.SelectedColumnCount -1 then
S := S + ',';
end;
SL.Add(S);
Result := SL.Text;
finally
FreeAndNil(SL);
end;
end;
function TfrmcxGrid.SelectionToFields(AQuoteItems: Boolean): string;
begin
Result := SelectionToFields(tvwMain.Controller, AQuoteItems);
end;
procedure TfrmcxGrid.ApplyGridSettings;
var
GL: TcxGridLines;
begin
if Assigned(Settings) then
begin
GL := glNone;
if Settings.ShowHorizontalGridLines then
begin
if Settings.ShowVerticalGridLines then
GL := glBoth
else
GL := glHorizontal;
end
else if Settings.ShowVerticalGridLines then
begin
GL := glVertical;
end;
tvwMain.OptionsView.GridLines := GL;
tvwMain.OptionsView.GroupByBox := Settings.GroupByBoxVisible;
MergeColumnCells := Settings.MergeColumnCells;
grdMain.Font.Assign(Settings.GridFont);
end;
end;
{$ENDREGION}
end.
|
unit ArrayListTestCase;
interface
uses
TestFrameWork, HproseCommon;
type
TArrayListTestCase = class(TTestCase)
private
procedure CheckEqualsList(Expected: IList; Actual: IList; Msg: string = '');
published
procedure TestCreate;
procedure TestAdd;
procedure TestAddAll;
procedure TestInsert;
procedure TestInsertRange;
procedure TestMove;
procedure TestExchange;
procedure TestContains;
procedure TestIndexOf;
procedure TestLastIndexOf;
procedure TestDelete;
procedure TestDeleteRange;
procedure TestRemove;
procedure TestClear;
procedure TestAssign;
procedure TestToArray;
{$IF RTLVersion >= 17.00} // Delphi 2005 or later
procedure TestForIn;
{$IFEND}
procedure TestSplit;
procedure TestJoin;
procedure TestItem;
procedure TestPack;
procedure TestReverse;
procedure TestSort;
procedure TestShuffle;
procedure TestVariantPut;
end;
implementation
uses Variants;
{ TArrayListTestCase }
procedure TArrayListTestCase.CheckEqualsList(Expected: IList; Actual: IList; Msg: string);
var
I: Integer;
begin
Check(Expected.Count = Actual.Count, Msg);
for I := 0 to Expected.Count - 1 do Check(Expected[I] = Actual[I], Msg);
end;
procedure TArrayListTestCase.TestCreate;
var
L: IArrayList;
begin
L := ArrayList([1, 2, 3]);
Check(L[0] = 1);
Check(L[1] = 2);
Check(L[2] = 3);
L := TArrayList.Create(L);
Check(L[0] = 1);
Check(L[1] = 2);
Check(L[2] = 3);
L := TArrayList.Create(L.ToArray);
Check(L[0] = 1);
Check(L[1] = 2);
Check(L[2] = 3);
L := TArrayList.Create();
Check(L.Count = 0);
L := TArrayList.Create(False, True);
L.BeginRead;
L.EndRead;
L.BeginWrite;
L.EndWrite;
end;
procedure TArrayListTestCase.TestAdd;
var
L: IArrayList;
begin
L := ArrayList([1, 2, 3]);
L.Add('Hello');
L.Add(3.14);
L.Add(True);
L.Add(ArrayList(['a', 'b', 'c']));
Check(L.Count = 7);
Check(L[3] = 'Hello');
Check(L[4] = 3.14);
Check(L[5] = True);
Check(L[6].Get(0) = 'a');
Check(L[6].Get(1) = 'b');
Check(L[6].Get(2) = 'c');
end;
procedure TArrayListTestCase.TestAddAll;
var
L: Variant;
begin
L := ArrayList([1, 2, 3]);
Check(L.Count = 3);
L.AddAll(ArrayList(['a', 'b', 'c']));
Check(L.Count = 6);
L.AddAll(L);
Check(L.Count = 12);
Check(L.Get(3) = 'a');
Check(L.Get(4) = 'b');
Check(L.Get(5) = 'c');
Check(L.Get(6) = 1);
Check(L.Get(7) = 2);
Check(L.Get(8) = 3);
end;
procedure TArrayListTestCase.TestInsert;
var
L: Variant;
L2: IArrayList;
I: Integer;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L.Insert(0, 'top');
L.Insert(3, 'middle');
L.Insert(6, 'bottom');
L2 := ArrayList([1, 'abc', 3.14, True]);
L2.Insert(0, 'top');
L2.Insert(3, 'middle');
L2.Insert(6, 'bottom');
for I := 0 to 6 do Check(L.Get(I) = L2[I]);
end;
procedure TArrayListTestCase.TestInsertRange;
var
L: Variant;
L2: IArrayList;
I: Integer;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L.InsertRange(2, ArrayList([1, 2, 3]));
L2 := ArrayList([1, 'abc', 3.14, True]);
L2.InsertRange(2, [1, 2, 3]);
for I := 0 to 6 do Check(L.Get(I) = L2[I]);
end;
procedure TArrayListTestCase.TestMove;
var
L: Variant;
L2: IArrayList;
I: Integer;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L.Move(2, 0);
L2 := ArrayList([3.14, 1, 'abc', True]);
for I := 0 to 3 do Check(L.Get(I) = L2[I]);
end;
procedure TArrayListTestCase.TestExchange;
var
L: Variant;
L2: IArrayList;
I: Integer;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L.Exchange(2, 0);
L2 := ArrayList([3.14, 'abc', 1, True]);
for I := 0 to 3 do Check(L.Get(I) = L2[I]);
end;
procedure TArrayListTestCase.TestContains;
var
L: IList;
begin
L := ArrayList([1, 'abc', 3.14, True, 'abc']);
Check(L.Contains('hello') = False);
Check(L.Contains('abc') = True);
end;
procedure TArrayListTestCase.TestIndexOf;
var
L: IList;
begin
L := ArrayList([1, 'abc', 3.14, True, 'abc']);
Check(L.IndexOf(1.0) = -1);
Check(L.IndexOf(1) = 0);
Check(L.IndexOf(3.14) = 2);
Check(L.IndexOf(False) = -1);
Check(L.IndexOf('abc') = 1);
Check(L.IndexOf('abc', 1) = 1);
Check(L.IndexOf('abc', 2) = 4);
Check(L.IndexOf('abc', 2, 2) = -1);
end;
procedure TArrayListTestCase.TestLastIndexOf;
var
L: IList;
begin
L := ArrayList([1, 'abc', 3.14, True, 'abc']);
Check(L.LastIndexOf(1) = 0);
Check(L.LastIndexOf('hello') = -1);
Check(L.LastIndexOf('abc') = 4);
Check(L.LastIndexOf('abc', 3) = 1);
Check(L.LastIndexOf('abc', 4) = 4);
Check(L.LastIndexOf('abc', 3, 2) = -1);
end;
procedure TArrayListTestCase.TestDelete;
var
L: IList;
begin
L := ArrayList([1, 'abc', 3.14, True]);
Check(L.Delete(2) = 3.14);
Check(L.Delete(2) = True);
end;
procedure TArrayListTestCase.TestDeleteRange;
var
L: IList;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L.DeleteRange(1, 2);
CheckEqualsList(L, ArrayList([1, True]));
end;
procedure TArrayListTestCase.TestRemove;
var
L: IList;
begin
L := ArrayList([1, 'abc', 3.14, True, 'abc']);
Check(L.Remove('abc', FromEnd) = 4);
Check(L.Remove('abc', FromBeginning) = 1);
Check(L.Remove(True) = 2);
end;
procedure TArrayListTestCase.TestClear;
var
L: IList;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L.Clear;
Check(L.Count = 0);
end;
procedure TArrayListTestCase.TestAssign;
var
L: IList;
L2: Variant;
I: Integer;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L2 := ArrayList([1, 2, 3]);
Check(L2.Assign(L) = True);
for I := 0 to 3 do Check(L[I] = L2.Get(I));
end;
procedure TArrayListTestCase.TestToArray;
var
L: IList;
A: array of Integer;
I: Integer;
begin
L := ArrayList([1, 3, 4, 5, 9]);
A := L.ToArray(varInteger);
for I := 0 to Length(A) - 1 do Check(L[I] = A[I]);
end;
{$IF RTLVersion >= 17.00} // Delphi 2005 or later
procedure TArrayListTestCase.TestForIn;
var
L, L2: IList;
V: Variant;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L2 := TArrayList.Create;
for V in L do L2.Add(V);
CheckEqualsList(L, L2);
end;
{$IFEND}
procedure TArrayListTestCase.TestSplit;
var
S: String;
begin
S := 'Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday,';
CheckEqualsList(
TArrayList.Split(S),
ArrayList(['Monday', ' Tuesday', ' Wednesday', ' Thursday', ' Friday', ' Saturday', ' Sunday', '']),
'Split 1 failed'
);
CheckEqualsList(
TArrayList.Split(S, ', '),
ArrayList(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday,']),
'Split 2 failed'
);
CheckEqualsList(
TArrayList.Split(S, ',', 4),
ArrayList(['Monday', ' Tuesday', ' Wednesday', ' Thursday, Friday, Saturday, Sunday,']),
'Split 3 failed'
);
CheckEqualsList(
TArrayList.Split(S, ',', 0, true),
ArrayList(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', '']),
'Split 4 failed'
);
CheckEqualsList(
TArrayList.Split(S, ',', 0, true, true),
ArrayList(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']),
'Split 5 failed'
);
end;
procedure TArrayListTestCase.TestJoin;
var
S: String;
L: IList;
begin
S := 'Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday';
L := TArrayList.Split(S);
Check(L.Join('; ') = 'Monday; Tuesday; Wednesday; Thursday; Friday; Saturday; Sunday');
Check(L.Join('", "', '["', '"]') = '["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]');
end;
procedure TArrayListTestCase.TestItem;
var
L: IList;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L[10] := 'test';
Check(VarIsEmpty(L[9]));
Check(L[10] = 'test');
L.Put(12, 'hello');
Check(VarIsEmpty(L.Get(11)));
Check(L.Get(12) = 'hello');
Check(VarIsEmpty(L.Get(-1)));
end;
procedure TArrayListTestCase.TestPack;
var
L: IList;
N: Integer;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L[10] := 'test';
Check(L.Count = 11);
Check(L[10] = 'test');
N := L.Capacity;
L.Pack;
Check(L.Count = 5);
Check(L[4] = 'test');
Check(L.Capacity = N);
L.TrimExcess;
Check(L.Capacity <> N);
Check(L.Count = L.Capacity);
end;
procedure TArrayListTestCase.TestReverse;
var
L: IList;
begin
L := ArrayList([1, 'abc', 3.14, True]);
L.Reverse;
CheckEqualsList(L, ArrayList([True, 3.14, 'abc', 1]));
end;
procedure TArrayListTestCase.TestSort;
var
L: IList;
begin
L := ArrayList([3, 5, 1, 2, 4, 9, 7, 6, 8]);
L.Sort;
CheckEqualsList(L, ArrayList([1, 2, 3, 4, 5, 6, 7, 8, 9]));
end;
procedure TArrayListTestCase.TestShuffle;
var
Src, Dest: IList;
Statistics: IList;
M: IMap;
I, J, N: Integer;
begin
Src := ArrayList([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
Statistics := TArrayList.Create(Src.Count);
for I := 0 to Src.Count - 1 do
Statistics[I] := HashMap([0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9, 0]);
for I := 0 to 99999 do begin
Dest := TArrayList.Create(Src);
Dest.Shuffle;
for J := 0 to Statistics.Count - 1 do begin
M := VarToMap(Statistics[J]);
N := M.Get(Dest[J]);
Inc(N);
M.Put(Dest[J], N);
end;
end;
for I := 0 to Statistics.Count - 1 do begin
for J := 0 to Statistics[I].Count - 1 do begin
N := Statistics[I].Values.Get(J);
Check((9500 < N) and (N < 10500), Variant(N));
end;
end;
end;
procedure TArrayListTestCase.TestVariantPut;
var
L: IList;
N: Integer;
V: Variant;
begin
L := ArrayList([1, 'abc', 3.14, True]);
N := 10;
L.Put(3, N);
Check(L.Get(3) = 10);
N := 11;
Check(L.Get(3) = 10);
N := 10;
L.Put(3, Variant(N));
Check(L.Get(3) = 10);
N := 11;
Check(L.Get(3) = 10);
V := 10;
L.Put(3, V);
Check(L.Get(3) = 10);
V := 11;
Check(L.Get(3) = 10);
V := 10;
L.Put(3, VarRef(V));
Check(L.Get(3) = 10);
V := 11;
Check(L.Get(3) = 11);
end;
initialization
TestFramework.RegisterTest(TArrayListTestCase.Suite);
end.
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
{$CODEPAGE UTF8}
unit json;
interface
//{$DEFINE TESTS}
uses
hashtable, stringutils;
// This is a read-only JSON interface.
// The JSON specs (there's at least 3) are a bit vague about some
// details, so I've made the following decisions for the purposes of
// this implementation:
// - the only supported input encoding is UTF-8
// - the root can be any value (this contradicts RFC4627, but matches
// RFC7159 and ECMA404, JSON.org is silent on this)
// - whitespace is allowed before or after any token (this contradicts
// the json.org description, but matches the RFCs, and more or less
// matches ECMA404)
// - duplicate keys are fatally invalid (this contradicts all the
// specs, especially the RFC)
// - key order for keys in objects is lost
// - lone surrogate escapes are invalid (this contradicts all the specs
// but is required if we're parsing to UTF-8)
type
TJSONKey = record
private
type
TJSONKeyMode = (kmNumeric, kmString);
var
Mode: TJSONKeyMode;
NumericValue: Cardinal;
StringValue: UTF8String;
end;
operator := (const Value: Cardinal): TJSONKey;
operator := (const Value: UTF8String): TJSONKey;
type
TJSON = class;
TJSONEnumerator = class
strict protected
function GetCurrent(): TJSON; virtual;
public
function MoveNext(): Boolean; virtual;
property Current: TJSON read GetCurrent;
end;
TJSON = class abstract
strict protected
function GetItem(const Key: TJSONKey): TJSON; virtual;
function GetLength(): Cardinal; virtual;
public
property Items[const Key: TJSONKey]: TJSON read GetItem; default;
property Length: Cardinal read GetLength;
function GetEnumerator(): TJSONEnumerator; virtual;
end;
type
TJSONObject = class(TJSON)
protected
type
TJSONHashTable = specialize THashTable <UTF8String, TJSON, UTF8StringUtils>;
TEnumerator = class(TJSONEnumerator)
strict protected
FEnumerator: TJSONHashTable.TValueEnumerator;
function GetCurrent(): TJSON; override;
private
constructor Create(const Home: TJSONObject);
public
destructor Destroy(); override;
function MoveNext(): Boolean; override;
end;
var
FItems: TJSONHashTable;
function GetItem(const Key: TJSONKey): TJSON; override;
function GetLength(): Cardinal; override;
public
type
TKeyEnumerator = TJSONHashTable.TKeyEnumerator;
destructor Destroy(); override;
function GetEnumerator(): TJSONEnumerator; override;
function Keys(): TKeyEnumerator;
end;
operator := (const Value: TJSON): TJSONObject;
type
TJSONArray = class(TJSON)
protected
type
TEnumerator = class(TJSONEnumerator)
strict protected
FHome: TJSONArray;
FCurrent: TJSON;
FPosition: Cardinal;
private
constructor Create(Home: TJSONArray);
public
function GetCurrent(): TJSON; override;
function MoveNext(): Boolean; override;
end;
var
FItems: array of TJSON;
function GetItem(const Key: TJSONKey): TJSON; override;
function GetLength(): Cardinal; override;
public
destructor Destroy(); override;
function GetEnumerator(): TJSONEnumerator; override;
end;
operator := (const Value: TJSON): TJSONArray;
type
TJSONNumber = class(TJSON)
protected
FValue: Double;
end;
operator := (const Value: TJSON): Double;
operator = (const Op1: TJSON; const Op2: Double): Boolean;
type
TJSONString = class(TJSON)
protected
FValue: UTF8String;
end;
operator := (const Value: TJSON): UTF8String;
operator = (const Op1: TJSON; const Op2: UTF8String): Boolean;
type
TJSONBoolean = class(TJSON)
protected
FValue: Boolean;
end;
operator := (const Value: TJSON): Boolean;
operator = (const Op1: TJSON; const Op2: Boolean): Boolean;
// XXX should probably have the reverse = operators too
function ParseJSON(const Input: UTF8String): TJSON;
implementation
uses
{$IFDEF TESTS} utf8, resutils, {$ENDIF}
unicode, hashfunctions, exceptions, sysutils;
operator := (const Value: Cardinal): TJSONKey;
begin
Result.Mode := kmNumeric;
Result.NumericValue := Value;
end;
operator := (const Value: UTF8String): TJSONKey;
begin
Result.Mode := kmString;
Result.StringValue := Value;
end;
function TJSONEnumerator.GetCurrent(): TJSON;
begin
Result := nil;
end;
function TJSONEnumerator.MoveNext(): Boolean;
begin
Result := False;
end;
function TJSON.GetItem(const Key: TJSONKey): TJSON;
begin
if (Key.Mode = kmNumeric) then
raise EConvertError.Create('Not an array')
else
raise EConvertError.Create('Not an object');
Result := nil;
end;
function TJSON.GetLength(): Cardinal;
begin
raise EConvertError.Create('Not an array or object');
Result := 0;
end;
function TJSON.GetEnumerator(): TJSONEnumerator;
begin
Result := TJSONEnumerator.Create();
end;
constructor TJSONObject.TEnumerator.Create(const Home: TJSONObject);
begin
inherited Create();
FEnumerator := Home.FItems.Values;
end;
destructor TJSONObject.TEnumerator.Destroy();
begin
FEnumerator.Free();
inherited;
end;
function TJSONObject.TEnumerator.GetCurrent(): TJSON;
begin
Result := FEnumerator.Current;
end;
function TJSONObject.TEnumerator.MoveNext(): Boolean;
begin
Result := FEnumerator.MoveNext()
end;
function TJSONObject.GetItem(const Key: TJSONKey): TJSON;
begin
if (Key.Mode = kmString) then
Result := FItems[Key.StringValue]
else
Result := inherited;
end;
function TJSONObject.GetLength(): Cardinal;
begin
Result := FItems.Count;
end;
destructor TJSONObject.Destroy();
var
Child: TJSON;
begin
for Child in FItems.Values do
Child.Free();
FItems.Free();
inherited;
end;
function TJSONObject.GetEnumerator(): TJSONEnumerator;
begin
Result := TEnumerator.Create(Self);
end;
function TJSONObject.Keys(): TJSONHashTable.TKeyEnumerator;
begin
Result := FItems.GetEnumerator();
end;
operator := (const Value: TJSON): TJSONObject;
begin
Result := Value as TJSONObject;
end;
constructor TJSONArray.TEnumerator.Create(Home: TJSONArray);
begin
inherited Create();
FHome := Home;
end;
function TJSONArray.TEnumerator.GetCurrent(): TJSON;
begin
Result := FCurrent;
end;
function TJSONArray.TEnumerator.MoveNext(): Boolean;
begin
if (FPosition < FHome.Length) then
begin
FCurrent := FHome[FPosition];
Inc(FPosition);
Result := True;
end
else
Result := False;
end;
function TJSONArray.GetItem(const Key: TJSONKey): TJSON;
begin
Assert(Assigned(FItems));
if (Key.Mode = kmNumeric) then
Result := FItems[Key.NumericValue]
else
Result := inherited;
end;
function TJSONArray.GetLength(): Cardinal;
begin
Result := System.Length(FItems); // $R-
end;
destructor TJSONArray.Destroy();
var
Child: TJSON;
begin
for Child in FItems do {BOGUS Warning: Type size mismatch, possible loss of data / range check error}
Child.Free();
inherited;
end;
function TJSONArray.GetEnumerator(): TJSONEnumerator;
begin
Result := TEnumerator.Create(Self);
end;
operator := (const Value: TJSON): TJSONArray;
begin
Result := Value as TJSONArray;
end;
operator := (const Value: TJSON): Double;
begin
Result := (Value as TJSONNumber).FValue;
end;
operator = (const Op1: TJSON; const Op2: Double): Boolean;
begin
Result := AssigneD(Op1) and (Op1 is TJSONNumber) and ((Op1 as TJSONNumber).FValue = Op2);
end;
operator := (const Value: TJSON): UTF8String;
begin
Result := (Value as TJSONString).FValue;
end;
operator = (const Op1: TJSON; const Op2: UTF8String): Boolean;
begin
Result := Assigned(Op1) and (Op1 is TJSONString) and ((Op1 as TJSONString).FValue = Op2);
end;
operator := (const Value: TJSON): Boolean;
begin
Result := (Value as TJSONBoolean).FValue;
end;
operator = (const Op1: TJSON; const Op2: Boolean): Boolean;
begin
Result := Assigned(Op1) and (Op1 is TJSONBoolean) and ((Op1 as TJSONBoolean).FValue = Op2);
end;
function ParseJSON(const Input: UTF8String): TJSON;
var
Enumerator: UTF8StringEnumerator;
CurrentCharacter: TUnicodeCodepoint;
Line, Column: Cardinal;
function GetNextCharacter(): TUnicodeCodepoint; inline;
begin
if (Enumerator.MoveNext()) then
CurrentCharacter := Enumerator.Current
else
CurrentCharacter := kEOF;
if (CurrentCharacter = $000A) then
begin
Inc(Line);
Column := 1;
end
else
Inc(Column);
Result := CurrentCharacter;
//if (Result <> kEOF) then
// Writeln(CodepointToUTF8(Result).AsString);
end;
procedure Error(const Message: UTF8String);
begin
raise ESyntaxError.CreateFmt('Invalid JSON: %s at line %d column %d', [Message, Line, Column]);
end;
procedure SkipWhitespace();
begin
repeat
GetNextCharacter();
until (CurrentCharacter <> $0020) and
(CurrentCharacter <> $0009) and
(CurrentCharacter <> $000A) and
(CurrentCharacter <> $000D);
end;
procedure SkipWhitespaceFromCurrent();
begin
while ((CurrentCharacter = $0020) or
(CurrentCharacter = $0009) or
(CurrentCharacter = $000A) or
(CurrentCharacter = $000D)) do
GetNextCharacter();
end;
function ParseValue(): TJSON; forward;
function ParseNumber(): TJSONNumber;
var
IsNegative, IsNegativeExponent: Boolean;
IntegerComponent, FractionalComponentValue, FractionalComponentLength, Exponent: Int64;
begin
{$PUSH}
{$OVERFLOWCHECKS ON}
{$RANGECHECKS ON}
if (CurrentCharacter = Ord('-')) then
begin
IsNegative := True;
GetNextCharacter();
end
else
IsNegative := False;
IntegerComponent := 0;
if (CurrentCharacter <> Ord('0')) then
begin
repeat
case (CurrentCharacter.Value) of
Ord('0'): IntegerComponent := IntegerComponent * 10;
Ord('1'): IntegerComponent := IntegerComponent * 10 + 1;
Ord('2'): IntegerComponent := IntegerComponent * 10 + 2;
Ord('3'): IntegerComponent := IntegerComponent * 10 + 3;
Ord('4'): IntegerComponent := IntegerComponent * 10 + 4;
Ord('5'): IntegerComponent := IntegerComponent * 10 + 5;
Ord('6'): IntegerComponent := IntegerComponent * 10 + 6;
Ord('7'): IntegerComponent := IntegerComponent * 10 + 7;
Ord('8'): IntegerComponent := IntegerComponent * 10 + 8;
Ord('9'): IntegerComponent := IntegerComponent * 10 + 9;
else
Break;
end;
GetNextCharacter();
until false;
end
else
GetNextCharacter();
if (CurrentCharacter.Value = Ord('.')) then
begin
FractionalComponentLength := 1;
FractionalComponentValue := 0;
repeat
GetNextCharacter();
FractionalComponentLength := FractionalComponentLength * 10;
case (CurrentCharacter.Value) of
Ord('0'): FractionalComponentValue := FractionalComponentValue * 10;
Ord('1'): FractionalComponentValue := FractionalComponentValue * 10 + 1;
Ord('2'): FractionalComponentValue := FractionalComponentValue * 10 + 2;
Ord('3'): FractionalComponentValue := FractionalComponentValue * 10 + 3;
Ord('4'): FractionalComponentValue := FractionalComponentValue * 10 + 4;
Ord('5'): FractionalComponentValue := FractionalComponentValue * 10 + 5;
Ord('6'): FractionalComponentValue := FractionalComponentValue * 10 + 6;
Ord('7'): FractionalComponentValue := FractionalComponentValue * 10 + 7;
Ord('8'): FractionalComponentValue := FractionalComponentValue * 10 + 8;
Ord('9'): FractionalComponentValue := FractionalComponentValue * 10 + 9;
else
Break;
end;
until false;
end
else
begin
FractionalComponentLength := 1;
FractionalComponentValue := 0;
end;
if ((CurrentCharacter = Ord('e')) or (CurrentCharacter = Ord('E'))) then
begin
GetNextCharacter();
IsNegativeExponent := False;
if (CurrentCharacter = Ord('+')) then
begin
GetNextCharacter();
end
else
if (CurrentCharacter = Ord('-')) then
begin
IsNegativeExponent := True;
GetNextCharacter();
end;
Exponent := 0;
repeat
case (CurrentCharacter.Value) of
Ord('0'): Exponent := Exponent * 10;
Ord('1'): Exponent := Exponent * 10 + 1;
Ord('2'): Exponent := Exponent * 10 + 2;
Ord('3'): Exponent := Exponent * 10 + 3;
Ord('4'): Exponent := Exponent * 10 + 4;
Ord('5'): Exponent := Exponent * 10 + 5;
Ord('6'): Exponent := Exponent * 10 + 6;
Ord('7'): Exponent := Exponent * 10 + 7;
Ord('8'): Exponent := Exponent * 10 + 8;
Ord('9'): Exponent := Exponent * 10 + 9;
else
Break;
end;
GetNextCharacter();
until false;
if (IsNegativeExponent) then
Exponent := -Exponent;
end
else
begin
Exponent := 0;
end;
Result := TJSONNumber.Create();
Result.FValue := (IntegerComponent + FractionalComponentValue / FractionalComponentLength) * Exp(Exponent*Ln(10)); // $R-
if (IsNegative) then
Result.FValue := -Result.FValue;
{$POP}
end;
function ParseFourHexadecimalDigitsToUnicodeCodepoint(): TUnicodeCodepointRange;
function GetHexDigit: Byte;
begin
case GetNextCharacter().Value of
Ord('0'): Result := 0;
Ord('1'): Result := 1;
Ord('2'): Result := 2;
Ord('3'): Result := 3;
Ord('4'): Result := 4;
Ord('5'): Result := 5;
Ord('6'): Result := 6;
Ord('7'): Result := 7;
Ord('8'): Result := 8;
Ord('9'): Result := 9;
Ord('A'), Ord('a'): Result := 10;
Ord('B'), Ord('b'): Result := 11;
Ord('C'), Ord('c'): Result := 12;
Ord('D'), Ord('d'): Result := 13;
Ord('E'), Ord('e'): Result := 14;
Ord('F'), Ord('f'): Result := 15;
else
Error('invalid hex digit');
Result := $FF;
end;
end;
begin
Result := GetHexDigit() shl 12 + // $R-
GetHexDigit() shl 8 +
GetHexDigit() shl 4 +
GetHexDigit();
end;
function ParseString(): UTF8String;
var
StartPointer, DestinationPointer, BookmarkPointer: TUTF8StringPointer;
EscapedCharacter1, EscapedCharacter2: TUnicodeCodepointRange;
HadEscapes: Boolean;
begin
StartPointer := Enumerator.GetPointer();
StartPointer.AdvanceToAfter();
DestinationPointer := StartPointer;
// DestinationPointer.SetToZeroWidth(); // if we ever make TUTF8StringPointer support actually advancing through the string, then we'll need to zero-out the end pointer here
Assert(Input.Extract(StartPointer, DestinationPointer).IsEmpty);
HadEscapes := False;
while (GetNextCharacter() <> Ord('"')) do
begin
case (CurrentCharacter.Value) of
Ord('\'):
begin
HadEscapes := True;
case (GetNextCharacter().Value) of
Ord('"'): Input.InplaceReplace(Ord('"'), DestinationPointer);
Ord('\'): Input.InplaceReplace(Ord('\'), DestinationPointer);
Ord('/'): Input.InplaceReplace(Ord('/'), DestinationPointer);
Ord('b'): Input.InplaceReplace($0008, DestinationPointer);
Ord('f'): Input.InplaceReplace($000C, DestinationPointer);
Ord('n'): Input.InplaceReplace($000A, DestinationPointer);
Ord('r'): Input.InplaceReplace($000D, DestinationPointer);
Ord('t'): Input.InplaceReplace($0009, DestinationPointer);
Ord('u'):
begin
EscapedCharacter1 := ParseFourHexadecimalDigitsToUnicodeCodepoint();
BookmarkPointer := Enumerator.GetPointer();
if ((EscapedCharacter1 >= $D800) and (EscapedCharacter1 <= $DBFF) and
(GetNextCharacter() = Ord('\')) and
(GetNextCharacter() = Ord('u'))) then
begin
EscapedCharacter2 := ParseFourHexadecimalDigitsToUnicodeCodepoint();
if ((EscapedCharacter2 >= $DC00) and (EscapedCharacter2 <= $DFFF)) then
begin
Input.InplaceReplace($10000 + (EscapedCharacter1 - $D800) * $400 + (EscapedCharacter2 - $DC00), DestinationPointer); // $R-
end
else
begin
Input.InplaceReplace(EscapedCharacter1, DestinationPointer);
Input.InplaceReplace(EscapedCharacter2, DestinationPointer);
end;
end
else
begin
Input.InplaceReplace(EscapedCharacter1, DestinationPointer);
Enumerator.ReturnToPointer(BookmarkPointer);
end;
end;
else
Error('invalid string escape');
end;
end;
$0000..$001F: Error('control character in string');
kEOF: Error('unexpected end of file in string');
else
if (HadEscapes) then
Input.InplaceReplace(CurrentCharacter, DestinationPointer)
else
DestinationPointer.AdvanceToAfter(CurrentCharacter);
end;
end;
Result := Input.Extract(StartPointer, DestinationPointer).AsString;
end;
function ParseStringAsValue(): TJSONString;
var
Value: UTF8String;
begin
Value := ParseString();
Result := TJSONString.Create();
Result.FValue := Value;
end;
function ParseTrue(): TJSONBoolean;
begin
if ((GetNextCharacter() <> Ord('r')) or
(GetNextCharacter() <> Ord('u')) or
(GetNextCharacter() <> Ord('e'))) then
Error('unrecognised keyword');
Result := TJSONBoolean.Create();
Result.FValue := True;
end;
function ParseFalse(): TJSONBoolean;
begin
if ((GetNextCharacter() <> Ord('a')) or
(GetNextCharacter() <> Ord('l')) or
(GetNextCharacter() <> Ord('s')) or
(GetNextCharacter() <> Ord('e'))) then
Error('unrecognised keyword');
Result := TJSONBoolean.Create();
end;
function ParseNull(): TJSON;
begin
if ((GetNextCharacter() <> Ord('u')) or
(GetNextCharacter() <> Ord('l')) or
(GetNextCharacter() <> Ord('l'))) then
Error('unrecognised keyword');
Result := nil;
end;
function ParseObject(): TJSONObject;
var
Key: UTF8String;
begin
Result := TJSONObject.Create();
Result.FItems := TJSONObject.TJSONHashTable.Create(@UTF8StringHash32);
try
SkipWhitespace();
if (CurrentCharacter <> Ord('}')) then
repeat
if (CurrentCharacter <> Ord('"')) then
Error('invalid key in object');
Key := ParseString();
if (Result.FItems.Has(Key)) then
Error('duplicate key in object');
SkipWhitespace();
if (CurrentCharacter <> Ord(':')) then
Error('missing colon after object key');
SkipWhitespace();
Result.FItems[Key] := ParseValue();
if (CurrentCharacter <> Ord(',')) then
Break;
SkipWhitespace();
until False;
if (CurrentCharacter <> Ord('}')) then
Error('missing comma or closing brace after object value');
except
Result.Free();
raise;
end;
end;
function ParseArray(): TJSONArray;
begin
Result := TJSONArray.Create();
try
SkipWhitespace();
if (CurrentCharacter <> Ord(']')) then
repeat
SetLength(Result.FItems, Length(Result.FItems)+1);
Result.FItems[High(Result.FItems)] := ParseValue();
if (CurrentCharacter <> Ord(',')) then
Break;
SkipWhitespace();
until False;
if (CurrentCharacter <> Ord(']')) then
Error('missing comma or closing bracket after array value');
except
Result.Free();
raise;
end;
end;
function ParseValue(): TJSON;
begin
case (CurrentCharacter.Value) of
Ord('{'): begin Result := ParseObject(); SkipWhitespace(); end;
Ord('['): begin Result := ParseArray(); SkipWhitespace(); end;
Ord('-'), Ord('0')..Ord('9'): begin Result := ParseNumber(); SkipWhitespaceFromCurrent(); end;
Ord('"'): begin Result := ParseStringAsValue(); SkipWhitespace(); end;
Ord('t'): begin Result := ParseTrue(); SkipWhitespace(); end;
Ord('f'): begin Result := ParseFalse(); SkipWhitespace(); end;
Ord('n'): begin Result := ParseNull(); SkipWhitespace(); end;
else
Error('invalid value');
Result := nil;
end;
end;
begin
Enumerator := Input.GetEnumerator();
Line := 1;
Column := 0;
try
SkipWhitespace();
Result := ParseValue();
if (CurrentCharacter <> kEOF) then
SkipWhitespace();
if (CurrentCharacter <> kEOF) then
begin
Result.Free();
Error('trailing garbage');
end;
finally
Enumerator.Free();
end;
end;
{$IFDEF TESTS}
{$IFOPT C+} {$ELSE} {$FATAL Can't run tests without assertion support} {$ENDIF}
{$RESOURCE tests/json.rc}
procedure TestJSON();
var
ParsedData: TJSON;
function ReadTestData(const TestName: AnsiString): AnsiString;
procedure ConvertToString(const Data: Pointer; const Size: Cardinal);
begin
SetLength(Result, Size);
Move(Data^, Result[1], Size);
end;
begin
{$IFOPT C+} Result := #0#0#0; {$ENDIF}
ReadFromResources('testdata', TestName, @ConvertToString);
{$IFOPT C+} Assert(Result <> #0#0#0); {$ENDIF}
end;
begin
ParsedData := ParseJSON(ReadTestData('json1'));
Assert(Assigned(ParsedData));
Assert(ParsedData is TJSONArray);
Assert(Assigned(ParsedData[0]));
Assert(ParsedData[0] is TJSONObject);
Assert(Assigned(ParsedData[0]['object']));
Assert(ParsedData[0]['object'] is TJSONObject);
Assert(ParsedData[0]['object'].Length = 0);
Assert(ParsedData[0]['array'] is TJSONArray);
Assert(ParsedData[0]['array'].Length = 0);
Assert(ParsedData[0]['number'] is TJSONNumber);
Assert(ParsedData[0]['number'] = 0);
Assert(ParsedData[0]['string'] is TJSONString);
Assert(ParsedData[0]['string'] = '');
Assert(ParsedData[0]['true'] is TJSONBoolean);
Assert(ParsedData[0]['true'] = True);
Assert(ParsedData[0]['false'] is TJSONBoolean);
Assert(ParsedData[0]['false'] = False);
Assert(ParsedData[0]['null'] = nil);
Assert(ParsedData[0].Length = 7);
Assert(ParsedData[1]['object']['foo'] = 'bar');
Assert(ParsedData[1]['object'].Length = 1);
Assert(ParsedData[1]['array'][0] = 'foo');
Assert(ParsedData[1]['array'][1] = 'bar');
Assert(ParsedData[1]['array'].Length = 2);
Assert(ParsedData[1]['number'] = 900);
Assert(ParsedData[1]['string'] = 'foo');
Assert(ParsedData[2]['string'] = 'a"\/'#$8#$C#$A#$D#$9#$E2#$98#$BA#$F0#$9D#$84#$9E'b');
Assert(ParsedData[2]['number'] = 900);
Assert(ParsedData[2].Length = 2);
Assert(ParsedData.Length = 3);
FreeAndNil(ParsedData);
ParsedData := ParseJSON(ReadTestData('json2'));
Assert(Assigned(ParsedData));
Assert(ParsedData is TJSONArray);
Assert(ParsedData.Length = 0);
FreeAndNil(ParsedData);
ParsedData := ParseJSON(ReadTestData('json3'));
Assert(Assigned(ParsedData));
Assert(ParsedData is TJSONArray);
Assert(ParsedData[0] = nil);
Assert(ParsedData[1] = nil);
Assert(ParsedData[2] = nil);
Assert(ParsedData[3] = False);
Assert(ParsedData[4] = 0);
Assert(ParsedData[5] = '');
Assert(ParsedData[6] = nil);
Assert(ParsedData.Length = 7);
FreeAndNil(ParsedData);
ParsedData := ParseJSON(ReadTestData('json4'));
Assert(Assigned(ParsedData));
Assert(ParsedData is TJSONObject);
Assert(ParsedData[''] = 'this should parse, despite starting with a space character, tab, and newline');
Assert(ParsedData.Length = 1);
FreeAndNil(ParsedData);
ParsedData := ParseJSON(ReadTestData('json5'));
Assert(Assigned(ParsedData));
Assert(ParsedData is TJSONObject);
Assert(ParsedData[''] = #0 + CodepointToUTF8($FFFF));
Assert(ParsedData['0'] = False);
Assert(ParsedData['1'] is TJSONArray);
Assert(ParsedData['1'][0] is TJSONArray);
Assert(ParsedData['1'][0].Length = 0);
Assert(ParsedData['1'][1] is TJSONArray);
Assert(ParsedData['1'][1].Length = 0);
Assert(ParsedData['1'][2] is TJSONArray);
Assert(ParsedData['1'][2].Length = 0);
Assert(ParsedData['1'][3] is TJSONArray);
Assert(ParsedData['1'][3].Length = 0);
Assert(ParsedData['1'][4] is TJSONArray);
Assert(ParsedData['1'][4].Length = 0);
Assert(ParsedData['1'][5] is TJSONObject);
Assert(ParsedData['1'][5].Length = 0);
Assert(ParsedData['1'][6] is TJSONObject);
Assert(ParsedData['1'][6].Length = 0);
Assert(ParsedData['1'].Length = 7);
Assert(ParsedData.Length = 3);
FreeAndNil(ParsedData);
ParsedData := ParseJSON(ReadTestData('json6'));
Assert(not Assigned(ParsedData));
FreeAndNil(ParsedData); // redundant, hopefully...
ParsedData := ParseJSON(ReadTestData('json7'));
Assert(Assigned(ParsedData));
Assert(ParsedData = False);
FreeAndNil(ParsedData);
ParsedData := ParseJSON(ReadTestData('json8'));
Assert(Assigned(ParsedData));
Assert(ParsedData = True);
FreeAndNil(ParsedData);
ParsedData := ParseJSON(ReadTestData('json9'));
Assert(Assigned(ParsedData));
Assert(ParsedData = #9);
FreeAndNil(ParsedData);
ParsedData := ParseJSON(ReadTestData('json10'));
Assert(Assigned(ParsedData));
Assert(ParsedData = 0);
FreeAndNil(ParsedData);
ParsedData := ParseJSON(ReadTestData('json11'));
Assert(Assigned(ParsedData));
Assert(ParsedData = #$E2#$98#$BA, (ParsedData as TJSONString).FValue);
FreeAndNil(ParsedData);
end;
{$ENDIF}
initialization
{$IFDEF TESTS} TestJSON(); {$ENDIF}
end.
|
unit Load;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;
type
TfrmLoad = class(TForm)
anmWait: TAnimate;
prgb: TProgressBar;
stMessage: TStaticText;
public
class function GetInstance: TfrmLoad;
procedure Load(ACommonAVI: TCommonAVI; ACaption: TCaption = 'Пожалуйста, подождите'; AStep: integer = 50; AMax: integer = 100);
procedure BeforeClose;
procedure MakeStep(AStepName: string = '');
// функции отключения мерчания формы при загрузке массива данных
procedure BeginScreenUpdate(hwnd: THandle);
procedure EndScreenUpdate(hwnd: THandle; erase: Boolean);
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
frmLoad: TfrmLoad;
implementation
{$R *.dfm}
{ TfrmLoad }
procedure TfrmLoad.BeforeClose;
begin
anmWait.Visible := false;
anmWait.Active := false;
Close;
end;
procedure TfrmLoad.BeginScreenUpdate(hwnd: THandle);
begin
if (hwnd = 0) then hwnd := Application.MainForm.Handle;
SendMessage(hwnd, WM_SETREDRAW, 0, 0);
end;
constructor TfrmLoad.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TfrmLoad.Destroy;
begin
inherited;
end;
procedure TfrmLoad.EndScreenUpdate(hwnd: THandle; erase: Boolean);
begin
if (hwnd = 0) then hwnd := Application.MainForm.Handle;
SendMessage(hwnd, WM_SETREDRAW, 1, 0);
RedrawWindow(hwnd, nil, 0, RDW_FRAME + RDW_INVALIDATE + RDW_ALLCHILDREN + RDW_NOINTERNALPAINT);
if (erase) then Windows.InvalidateRect(hwnd, nil, True);
end;
class function TfrmLoad.GetInstance: TfrmLoad;
const FInstance: TfrmLoad = nil;
begin
if not Assigned(FInstance) then
FInstance := TfrmLoad.Create(Application.MainForm);
Result := FInstance;
end;
procedure TfrmLoad.Load(ACommonAVI: TCommonAVI; ACaption: TCaption; AStep: integer; AMax: integer);
begin
Caption := ACaption;
anmWait.CommonAVI := ACommonAVI;
anmWait.Visible := true;
anmWait.Active := true;
anmWait.Update;
prgb.Step := AStep;
prgb.Max := AMax;
Show;
end;
procedure TfrmLoad.MakeStep(AStepName: string = '');
begin
prgb.StepIt;
stMessage.Caption := ' ' + AStepName;
Update;
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado aos procedimentos de venda
The MIT License
Copyright: Copyright (C) 2010 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</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit VendaController;
interface
uses
Classes, SysUtils, EcfVendaCabecalhoVO, EcfVendaDetalheVO, Generics.Collections,
DB, VO, Controller, DBClient, Biblioteca, EcfTotalTipoPagamentoVO;
type
TVendaController = class(TController)
private
class var FDataSet: TClientDataSet;
public
class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
class function ConsultaLista(pFiltro: String): TObjectList<TEcfVendaCabecalhoVO>;
class function ConsultaObjeto(pFiltro: String): TEcfVendaCabecalhoVO;
class procedure VendaCabecalho(pFiltro: String);
class procedure VendaDetalhe(pFiltro: String);
class procedure ExisteVendaAberta;
class procedure Insere(pObjeto: TEcfVendaCabecalhoVO);
class procedure InsereItem(pObjeto: TEcfVendaDetalheVO);
class function Altera(pObjeto: TEcfVendaCabecalhoVO): Boolean;
class function CancelaVenda(pObjeto: TEcfVendaCabecalhoVO): Boolean;
class function CancelaItemVenda(pObjeto: TEcfVendaDetalheVO): Boolean;
class function GetDataSet: TClientDataSet; override;
class procedure SetDataSet(pDataSet: TClientDataSet); override;
class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
end;
implementation
uses T2TiORM;
class procedure TVendaController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
Retorno: TObjectList<TEcfVendaCabecalhoVO>;
begin
try
Retorno := TT2TiORM.Consultar<TEcfVendaCabecalhoVO>(pFiltro, pPagina, pConsultaCompleta);
TratarRetorno<TEcfVendaCabecalhoVO>(Retorno);
finally
end;
end;
class function TVendaController.ConsultaLista(pFiltro: String): TObjectList<TEcfVendaCabecalhoVO>;
begin
try
Result := TT2TiORM.Consultar<TEcfVendaCabecalhoVO>(pFiltro, '-1', True);
finally
end;
end;
class function TVendaController.ConsultaObjeto(pFiltro: String): TEcfVendaCabecalhoVO;
begin
try
Result := TT2TiORM.ConsultarUmObjeto<TEcfVendaCabecalhoVO>(pFiltro, True);
finally
end;
end;
class procedure TVendaController.VendaCabecalho(pFiltro: String);
var
ObjetoLocal: TEcfVendaCabecalhoVO;
begin
try
ObjetoLocal := TT2TiORM.ConsultarUmObjeto<TEcfVendaCabecalhoVO>(pFiltro, True);
TratarRetorno<TEcfVendaCabecalhoVO>(ObjetoLocal);
finally
end;
end;
class procedure TVendaController.VendaDetalhe(pFiltro: String);
var
ObjetoLocal: TEcfVendaDetalheVO;
begin
try
ObjetoLocal := TT2TiORM.ConsultarUmObjeto<TEcfVendaDetalheVO>(pFiltro, True);
TratarRetorno<TEcfVendaDetalheVO>(ObjetoLocal);
finally
end;
end;
class procedure TVendaController.ExisteVendaAberta;
var
Filtro: String;
Retorno: TObjectList<TEcfVendaCabecalhoVO>;
begin
try
Filtro := 'STATUS_VENDA = ' + QuotedStr('A');
Retorno := TT2TiORM.Consultar<TEcfVendaCabecalhoVO>(Filtro, '0', False);
TratarRetorno(Retorno.Count > 0);
finally
FreeAndNil(Retorno);
end;
end;
class procedure TVendaController.Insere(pObjeto: TEcfVendaCabecalhoVO);
var
UltimoID: Integer;
begin
try
pObjeto.SerieEcf := Sessao.Configuracao.EcfImpressoraVO.Serie;
UltimoID := TT2TiORM.Inserir(pObjeto);
VendaCabecalho('ID = ' + IntToStr(UltimoID));
finally
end;
end;
class procedure TVendaController.InsereItem(pObjeto: TEcfVendaDetalheVO);
var
UltimoID: Integer;
begin
try
if pObjeto.EcfProdutoVO.EcfIcmsSt = 'NN' then
pObjeto.EcfIcmsSt := 'N'
else if pObjeto.EcfProdutoVO.EcfIcmsSt = 'FF' then
pObjeto.EcfIcmsSt := 'F'
else if pObjeto.EcfProdutoVO.EcfIcmsSt = 'II' then
pObjeto.EcfIcmsSt := 'I'
else
begin
if copy(pObjeto.TotalizadorParcial, 3, 1) = 'S' then
pObjeto.EcfIcmsSt := copy(pObjeto.TotalizadorParcial, 4, 4)
else if copy(pObjeto.TotalizadorParcial, 3, 1) = 'T' then
pObjeto.EcfIcmsSt := copy(pObjeto.TotalizadorParcial, 4, 4)
else if pObjeto.TotalizadorParcial = 'Can-T' then
pObjeto.EcfIcmsSt := 'CANC'
else
begin
pObjeto.EcfIcmsSt := '1700';
end;
end;
pObjeto.Cancelado := 'N';
if (pObjeto.EcfProdutoVO.EcfIcmsSt = 'II') or (pObjeto.EcfProdutoVO.EcfIcmsSt = 'NN') then
pObjeto.TaxaICMS := 0;
pObjeto.SerieEcf := Sessao.Configuracao.EcfImpressoraVO.Serie;
FormatSettings.DecimalSeparator := '.';
pObjeto.HashRegistro := '0';
pObjeto.HashRegistro := MD5String(pObjeto.ToJSONString);
UltimoID := TT2TiORM.Inserir(pObjeto);
VendaDetalhe('ID = ' + IntToStr(UltimoID));
finally
FormatSettings.DecimalSeparator := ',';
end;
end;
class function TVendaController.Altera(pObjeto: TEcfVendaCabecalhoVO): Boolean;
begin
try
FormatSettings.DecimalSeparator := '.';
pObjeto.HashRegistro := '0';
pObjeto.HashRegistro := MD5String(pObjeto.ToJSONString);
Result := TT2TiORM.Alterar(pObjeto);
TController.ExecutarMetodo('LogssController.TLogssController', 'AtualizarQuantidades', [], 'POST', 'Boolean');
finally
FormatSettings.DecimalSeparator := ',';
end;
end;
class function TVendaController.CancelaVenda(pObjeto: TEcfVendaCabecalhoVO): Boolean;
var
DetalheEnumerator: TEnumerator<TEcfVendaDetalheVO>;
PagamentoEnumerator: TEnumerator<TEcfTotalTipoPagamentoVO>;
begin
try
FormatSettings.DecimalSeparator := '.';
pObjeto.HashRegistro := '0';
pObjeto.HashRegistro := MD5String(pObjeto.ToJSONString);
Result := TT2TiORM.Alterar(pObjeto);
// Detalhes
try
DetalheEnumerator := pObjeto.ListaEcfVendaDetalheVO.GetEnumerator;
with DetalheEnumerator do
begin
while MoveNext do
begin
Current.TotalizadorParcial := 'Can-T';
Current.Cancelado := 'S';
Current.Ccf := pObjeto.Ccf;
Current.Coo := pObjeto.Coo;
Current.HashRegistro := '0';
Current.HashRegistro := MD5String(Current.ToJSONString);
Result := TT2TiORM.Alterar(Current)
end;
end;
finally
FreeAndNil(DetalheEnumerator);
end;
// Detalhes
try
PagamentoEnumerator := pObjeto.ListaEcfTotalTipoPagamentoVO.GetEnumerator;
with PagamentoEnumerator do
begin
while MoveNext do
begin
Current.Estorno := 'S';
Current.HashRegistro := '0';
Current.HashRegistro := MD5String(Current.ToJSONString);
Result := TT2TiORM.Alterar(Current)
end;
end;
finally
FreeAndNil(PagamentoEnumerator);
end;
finally
FormatSettings.DecimalSeparator := ',';
end;
end;
class function TVendaController.CancelaItemVenda(pObjeto: TEcfVendaDetalheVO): Boolean;
begin
try
FormatSettings.DecimalSeparator := '.';
pObjeto.HashRegistro := '0';
pObjeto.HashRegistro := MD5String(pObjeto.ToJSONString);
Result := TT2TiORM.Alterar(pObjeto);
finally
FormatSettings.DecimalSeparator := ',';
end;
end;
class function TVendaController.GetDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
class procedure TVendaController.SetDataSet(pDataSet: TClientDataSet);
begin
FDataSet := pDataSet;
end;
class procedure TVendaController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
try
TratarRetorno<TEcfVendaCabecalhoVO>(TObjectList<TEcfVendaCabecalhoVO>(pListaObjetos));
finally
FreeAndNil(pListaObjetos);
end;
end;
initialization
Classes.RegisterClass(TVendaController);
finalization
Classes.UnRegisterClass(TVendaController);
end.
|
{
Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit DataGrabber.Interfaces;
{ Application interfaces }
interface
uses
System.Classes, System.TimeSpan,
Vcl.Graphics, Vcl.Controls, Vcl.Menus, Vcl.Forms, Vcl.ActnList,
Data.DB,
FireDAC.Comp.Client, FireDAC.Stan.Intf, FireDAC.Comp.DataSet,
Spring, Spring.Collections,
DataGrabber.ConnectionProfiles, DataGrabber.FormSettings,
DataGrabber.ConnectionSettings;
type
TDataType = (
dtBoolean,
dtString,
dtInteger,
dtFloat,
dtDate,
dtTime,
dtDateTime,
dtNULL
);
TResultDisplayLayout = (
Tabbed,
Horizontal,
Vertical
);
const
DEFAULT_DATATYPE_COLORS : array [TDataType] of TColor = (
$00DFDFDF,
$00E1FFE1, // Green
$00DFDFFF, // Red
$00DFDFFF,
$00FFEBD7, // Blue
$00FFEBD7,
$00FFEBD7,
clSilver
);
WHERE_IN = 'where' + #13#10 + ' %s in (%s)';
type
IEditorView = interface;
IData = interface;
IResultSet = interface
['{2A65FFAE-DA27-4088-B9E5-EB055A0E46A0}']
{$REGION 'property access methods'}
function GetConstantFields: IList<TField>;
function GetEmptyFields: IList<TField>;
function GetNonEmptyFields: IList<TField>;
function GetHiddenFields: IList<TField>;
function GetConstantFieldsVisible: Boolean;
function GetEmptyFieldsVisible: Boolean;
procedure SetConstantFieldsVisible(const Value: Boolean);
procedure SetEmptyFieldsVisible(const Value: Boolean);
function GetDataSet: TFDDataSet;
function GetData: IData;
{$ENDREGION}
property Data: IData
read GetData;
property DataSet: TFDDataSet
read GetDataSet;
property ConstantFields: IList<TField>
read GetConstantFields;
property EmptyFields: IList<TField>
read GetEmptyFields;
property NonEmptyFields: IList<TField>
read GetNonEmptyFields;
property HiddenFields: IList<TField>
read GetHiddenFields;
function ShowAllFields: Boolean;
property ConstantFieldsVisible: Boolean
read GetConstantFieldsVisible write SetConstantFieldsVisible;
property EmptyFieldsVisible: Boolean
read GetEmptyFieldsVisible write SetEmptyFieldsVisible;
end;
IData = interface
['{0E8958C3-CECD-4E3F-A990-B73635E50F26}']
{$REGION 'property access methods'}
function GetDataSet : TFDDataSet;
function GetRecordCount : Integer;
function GetActive: Boolean;
function GetSQL: string;
procedure SetSQL(const Value: string);
function GetCanModify: Boolean;
function GetConnectionSettings: TConnectionSettings;
function GetConnection: TFDConnection;
function GetItem(AIndex: Integer): IResultSet;
function GetDataSetCount: Integer;
function GetOnAfterExecute: IEvent<TNotifyEvent>;
function GetOnBeforeExecute: IEvent<TNotifyEvent>;
function GetMultipleResultSets: Boolean;
procedure SetMultipleResultSets(const Value: Boolean);
function GetElapsedTime: TTimeSpan;
function GetFieldListsUpdated: Boolean;
function GetDataEditMode: Boolean;
procedure SetDataEditMode(const Value: Boolean);
function GetResultSet: IResultSet;
{$ENDREGION}
procedure Execute;
procedure HideField(
ADataSet : TDataSet;
const AFieldName : string
);
procedure SaveToFile(
const AFileName : string = '';
AFormat : TFDStorageFormat = sfAuto
); overload;
procedure SaveToFile(
ADataSet : TDataSet;
const AFileName : string = '';
AFormat : TFDStorageFormat = sfAuto
); overload;
procedure LoadFromFile(
const AFileName : string = '';
AFormat : TFDStorageFormat = sfAuto
); overload;
procedure LoadFromFile(
ADataSet : TDataSet;
const AFileName : string = '';
AFormat : TFDStorageFormat = sfAuto
); overload;
procedure Sort(
const AFieldName : string;
ADescending : Boolean = False
); overload;
procedure Sort(
ADataSet : TDataSet;
const AFieldName : string;
ADescending : Boolean = False
); overload;
property SQL: string
read GetSQL write SetSQL;
property ResultSet: IResultSet
read GetResultSet;
// property DataSet: TFDDataSet
// read GetDataSet;
property Connection: TFDConnection
read GetConnection;
property Active: Boolean
read GetActive;
property CanModify: Boolean
read GetCanModify;
property DataEditMode: Boolean
read GetDataEditMode write SetDataEditMode;
property RecordCount: Integer
read GetRecordCount;
property ConnectionSettings: TConnectionSettings
read GetConnectionSettings;
property ElapsedTime: TTimeSpan
read GetElapsedTime;
property Items[AIndex: Integer]: IResultSet
read GetItem; default;
property DataSetCount: Integer
read GetDataSetCount;
property MultipleResultSets: Boolean
read GetMultipleResultSets write SetMultipleResultSets;
property OnAfterExecute: IEvent<TNotifyEvent>
read GetOnAfterExecute;
property OnBeforeExecute: IEvent<TNotifyEvent>
read GetOnBeforeExecute;
end;
IDataViewSettings = interface
['{62EF3A18-73C5-4FAA-BBA1-D203AD028F38}']
{$REGION 'property access methods'}
function GetDataTypeColor(Index: TDataType): TColor;
function GetFieldTypeColor(Index: TFieldType): TColor;
procedure SetDataTypeColor(Index: TDataType; const Value: TColor);
function GetGridCellColoring: Boolean;
procedure SetGridCellColoring(const Value: Boolean);
function GetShowHorizontalGridLines: Boolean;
function GetShowVerticalGridLines: Boolean;
procedure SetShowHorizontalGridLines(const Value: Boolean);
procedure SetShowVerticalGridLines(const Value: Boolean);
function GetGroupByBoxVisible: Boolean;
procedure SetGroupByBoxVisible(const Value: Boolean);
function GetOnChanged: IEvent<TNotifyEvent>;
function GetMergeColumnCells: Boolean;
procedure SetMergeColumnCells(const Value: Boolean);
function GetGridFont: TFont;
procedure SetGridFont(const Value: TFont);
{$ENDREGION}
property DataTypeColors[Index: TDataType]: TColor
read GetDataTypeColor write SetDataTypeColor;
property FieldTypeColors[Index: TFieldType]: TColor
read GetFieldTypeColor;
property GridFont: TFont
read GetGridFont write SetGridFont;
property GridCellColoring: Boolean
read GetGridCellColoring write SetGridCellColoring;
property ShowHorizontalGridLines: Boolean
read GetShowHorizontalGridLines write SetShowHorizontalGridLines;
property ShowVerticalGridLines: Boolean
read GetShowVerticalGridLines write SetShowVerticalGridLines;
property GroupByBoxVisible: Boolean
read GetGroupByBoxVisible write SetGroupByBoxVisible;
property MergeColumnCells: Boolean
read GetMergeColumnCells write SetMergeColumnCells;
property OnChanged: IEvent<TNotifyEvent>
read GetOnChanged;
end;
IDataView = interface
['{50D61670-EBD1-4A52-8915-C8006053E2B2}']
{$REGION 'property access methods'}
function GetName: string;
function GetGridType: string;
function GetSettings: IDataViewSettings;
function GetData: IData;
function GetRecordCount: Integer;
function GetPopupMenu: TPopupMenu;
procedure SetPopupMenu(const Value: TPopupMenu);
function GetDataSet: TDataSet;
function GetResultSet: IResultSet;
{$ENDREGION}
procedure AssignParent(AParent: TWinControl);
procedure UpdateView;
procedure HideSelectedColumns;
function IsActiveDataView: Boolean;
procedure Inspect;
procedure AutoSizeColumns;
procedure Copy;
procedure Close;
procedure BeginUpdate;
procedure EndUpdate;
function ResultsToWikiTable(AIncludeHeader: Boolean = False): string;
function ResultsToTextTable(AIncludeHeader: Boolean = False): string;
function SelectionToCommaText(AQuoteItems: Boolean = True): string;
function SelectionToDelimitedTable(
ADelimiter : string = #9;
AIncludeHeader : Boolean = True
): string;
function SelectionToTextTable(AIncludeHeader: Boolean = False): string;
function SelectionToWikiTable(AIncludeHeader: Boolean = False): string;
function SelectionToFields(AQuoteItems: Boolean = True): string;
property Name: string
read GetName;
property GridType: string
read GetGridType;
property DataSet: TDataSet
read GetDataSet;
property ResultSet: IResultSet
read GetResultSet;
// property Data: IData
// read GetData;
property RecordCount: Integer
read GetRecordCount;
property Settings: IDataViewSettings
read GetSettings;
property PopupMenu: TPopupMenu
read GetPopupMenu write SetPopupMenu;
end;
ISettings = interface
['{C6E48393-6FBA-451B-A565-921F11E433F0}']
{$REGION 'property access methods'}
function GetGridCellColoring: Boolean;
procedure SetGridCellColoring(const Value: Boolean);
function GetFieldTypeColor(Index: TFieldType): TColor;
function GetDataTypeColor(Index: TDataType): TColor;
procedure SetDataTypeColor(Index: TDataType; const Value: TColor);
function GetConnectionProfiles: TConnectionProfiles;
procedure SetConnectionProfiles(const Value: TConnectionProfiles);
function GetFormSettings: TFormSettings;
procedure SetFormSettings(const Value: TFormSettings);
function GetConnectionSettings: TConnectionSettings;
function GetDataInspectorVisible: Boolean;
function GetDefaultConnectionProfile: string;
procedure SetConnectionSettings(const Value: TConnectionSettings);
procedure SetDataInspectorVisible(const Value: Boolean);
procedure SetDefaultConnectionProfile(const Value: string);
function GetGridType: string;
procedure SetGridType(const Value: string);
function GetFileName: string;
procedure SetFileName(const Value: string);
function GetShowHorizontalGridLines: Boolean;
function GetShowVerticalGridLines: Boolean;
procedure SetShowHorizontalGridLines(const Value: Boolean);
procedure SetShowVerticalGridLines(const Value: Boolean);
function GetResultDisplayLayout: TResultDisplayLayout;
procedure SetResultDisplayLayout(const Value: TResultDisplayLayout);
function GetGroupByBoxVisible: Boolean;
procedure SetGroupByBoxVisible(const Value: Boolean);
function GetOnChanged: IEvent<TNotifyEvent>;
function GetMergeColumnCells: Boolean;
procedure SetMergeColumnCells(const Value: Boolean);
function GetEditorFont: TFont;
procedure SetEditorFont(const Value: TFont);
function GetGridFont: TFont;
procedure SetGridFont(const Value: TFont);
{$ENDREGION}
procedure Load;
procedure Save;
property FileName: string
read GetFileName write SetFileName;
property ConnectionProfiles: TConnectionProfiles
read GetConnectionProfiles write SetConnectionProfiles;
property EditorFont: TFont
read GetEditorFont write SetEditorFont;
property GridFont: TFont
read GetGridFont write SetGridFont;
property GridCellColoring: Boolean
read GetGridCellColoring write SetGridCellColoring;
property FormSettings: TFormSettings
read GetFormSettings write SetFormSettings;
property GridType: string
read GetGridType write SetGridType;
property ConnectionSettings: TConnectionSettings
read GetConnectionSettings write SetConnectionSettings;
property DefaultConnectionProfile: string
read GetDefaultConnectionProfile write SetDefaultConnectionProfile;
property DataInspectorVisible: Boolean
read GetDataInspectorVisible write SetDataInspectorVisible;
property FieldTypeColors[Index: TFieldType]: TColor
read GetFieldTypeColor;
property DataTypeColors[Index: TDataType]: TColor
read GetDataTypeColor write SetDataTypeColor;
property GroupByBoxVisible: Boolean
read GetGroupByBoxVisible write SetGroupByBoxVisible;
property MergeColumnCells: Boolean
read GetMergeColumnCells write SetMergeColumnCells;
property ShowHorizontalGridLines: Boolean
read GetShowHorizontalGridLines write SetShowHorizontalGridLines;
property ShowVerticalGridLines: Boolean
read GetShowVerticalGridLines write SetShowVerticalGridLines;
property ResultDisplayLayout: TResultDisplayLayout
read GetResultDisplayLayout write SetResultDisplayLayout;
property OnChanged: IEvent<TNotifyEvent>
read GetOnChanged;
end;
IConnectionView = interface
['{52F9CB1D-68C8-4E74-B3B7-0A9DDF93A818}']
{$REGION 'property access methods'}
function GetForm: TForm;
function GetActiveConnectionProfile: TConnectionProfile;
function GetActiveDataView: IDataView;
function GetEditorView: IEditorView;
function GetData: IData;
{$ENDREGION}
procedure Copy;
procedure ApplySettings;
function ExportAsWiki: string;
property ActiveDataView: IDataView
read GetActiveDataView;
property Data: IData
read GetData;
property EditorView: IEditorView
read GetEditorView;
property Form: TForm
read GetForm;
property ActiveConnectionProfile: TConnectionProfile
read GetActiveConnectionProfile;
end;
IConnectionViewManager = interface
['{E71C1D68-F201-4A95-9802-1D5B77445FEC}']
{$REGION 'property access methods'}
function GetActiveConnectionView: IConnectionView;
procedure SetActiveConnectionView(const Value: IConnectionView);
function GetSettings: ISettings;
function GetActiveDataView: IDataView;
function GetActiveData: IData;
function GetActionList: TActionList;
function GetAction(AName: string): TCustomAction;
function GetConnectionViewPopupMenu: TPopupMenu;
function GetDefaultConnectionProfile: TConnectionProfile;
function GetItem(AIndex: Integer): IConnectionView;
function GetCount: Integer;
{$ENDREGION}
function AddConnectionView: IConnectionView;
function DeleteConnectionView(AIndex: Integer): Boolean; overload;
function DeleteConnectionView(AConnectionView: IConnectionView): Boolean; overload;
procedure UpdateActions;
property ActiveConnectionView: IConnectionView
read GetActiveConnectionView write SetActiveConnectionView;
property ActiveDataView: IDataView
read GetActiveDataView;
property ActiveData: IData
read GetActiveData;
property Settings: ISettings
read GetSettings;
property ActionList: TActionList
read GetActionList;
property DefaultConnectionProfile: TConnectionProfile
read GetDefaultConnectionProfile;
property Actions[AName: string]: TCustomAction
read GetAction;
property Items[AIndex: Integer]: IConnectionView
read GetItem; default;
property ConnectionViewPopupMenu: TPopupMenu
read GetConnectionViewPopupMenu;
property Count: Integer
read GetCount;
end;
IEditorView = interface
['{9E365515-2202-458B-98C2-6995344E81DD}']
{$REGION 'property access methods'}
function GetText: string;
procedure SetText(const Value: string);
function GetColor: TColor;
procedure SetColor(const Value: TColor);
function GetEditorFocused: Boolean;
function GetPopupMenu: TPopupMenu;
procedure SetPopupMenu(const Value: TPopupMenu);
{$ENDREGION}
procedure AssignParent(AParent: TWinControl);
procedure FillCompletionLists(ATables, AAttributes : TStrings);
procedure CopyToClipboard;
procedure SetFocus;
property PopupMenu: TPopupMenu
read GetPopupMenu write SetPopupMenu;
property EditorFocused: Boolean
read GetEditorFocused;
property Color: TColor
read GetColor write SetColor;
property Text: string
read GetText write SetText;
end;
IGroupable = interface
['{C3E37BA9-5FCF-4AC5-A747-495F0B13E8E4}']
procedure GroupBySelectedColumns;
procedure ClearGrouping;
procedure ExpandAll;
procedure CollapseAll;
end;
IMergable = interface
['{68285D0A-5DE8-4782-BC1F-EF9D4A7A0C7E}']
{$REGION 'property access methods'}
function GetMergeColumnCells: Boolean;
procedure SetMergeColumnCells(const Value: Boolean);
procedure MergeAllColumnCells(AActive: Boolean);
{$ENDREGION}
property MergeColumnCells: Boolean
read GetMergeColumnCells write SetMergeColumnCells;
end;
implementation
end.
|
inherited TourRefBookBusViewForm: TTourRefBookBusViewForm
Caption = 'Виды транспорта'
OldCreateOrder = True
PixelsPerInch = 96
TextHeight = 13
inherited ToolBar: TToolBar
Visible = True
end
inherited ActionList: TActionList
inherited NewAction: TAction
OnExecute = NewActionExecute
end
inherited EditAction: TAction
OnExecute = EditActionExecute
end
end
inherited MainDBGridFilterDialog: TVDBGridFilterDialog
Fields = <
item
Caption = 'Марка'
FieldName = 'bus_model'
end
item
Caption = 'Описание'
FieldName = 'bus_desc'
end
item
Caption = 'Вместительность'
FieldName = 'bus_capacity'
end
item
Caption = 'Скорость'
FieldName = 'bus_speedfactor'
end>
end
inherited MainQuery: TADOQuery
SQL.Strings = (
'SELECT'
' bus_model,'
' bus_desc,'
' bus_capacity,'
' bus_speedfactor'
'FROM'
' bus'
' ')
object MainQuerybus_model: TStringField
DisplayLabel = 'Марка'
FieldName = 'bus_model'
Size = 15
end
object MainQuerybus_desc: TStringField
DisplayLabel = 'Описание'
FieldName = 'bus_desc'
Size = 50
end
object MainQuerybus_capacity: TIntegerField
DisplayLabel = 'Вместительность'
FieldName = 'bus_capacity'
end
object MainQuerybus_speedfactor: TFloatField
DisplayLabel = 'Скорость'
FieldName = 'bus_speedfactor'
end
end
end
|
unit UDAOCarpetaDigital;
interface
uses
SysUtils,StrUtils,Classes,DB,DBClient, zdataset, ZDbcIntfs,
UCarpetaCarpetaDigi, UDMConexion, Variants, FPGenerales;
type
TDAOCarpetaDigital = class
private
FQuery : TZquery;
public
{CONSTRUCTORES Y DESTRUCTORES}
constructor create;
destructor destroy;
{ PROCEDIMIENTOS Y FUNCIONES }
function ConsultarArbolCarpeta(p_CodiCarp: string): TClientDataSet;
function ConsultarDatosCarpeta(P_CodiCarp: string): TCarpetaCarpetaDigi;
function ConsultarDatosMtiAndes(p_identipo: variant; p_numedocu: string;
p_primnomb:string; p_primapel:string;
p_IdenSedo: Variant;
p_fechnoin: string; p_fechnofi: string;
p_FechPagoInic: string; p_FechPagoFina: string;
p_PeriInic: string; p_PeriFina: string;
p_IdenFond: variant): TDataSource;
function ConsultarEmpleados(p_IdenPers: Int32; p_NombPers: string;
p_IdenSedo: Variant;
p_FechNoin: string; p_FechNofi: string;
p_FechPain: string; p_FechPafi: string;
p_PeriInic: string; p_PeriFina: string;
p_IdenFond: variant): TClientDataSet;
function ConsultarFondos(p_TipoFond: string): TDataSource;
function ConsultarSeriesDocumentales: TDataSource;
function ConsultarTiposIdentificacion: TDataSource;
end;
implementation
{$REGION 'METODOS PROPIOS'}
function TDAOCarpetaDigital.ConsultarArbolCarpeta(p_CodiCarp: string): TClientDataSet;
{ FUNCION QUE BUSCA LAS IMAGENES QUE TIENE UNA CARPETA}
var
NumeRegi : Int32;
RegiPadrNiv1: Int32;
SubbSeriDocu: string;
QuerDatoCarp: TZQuery;
begin
try
QuerDatoCarp := TZQuery.Create(nil);
QuerDatoCarp.Connection := DMConexion.ZConexion;
Result:= TClientDataSet.Create(nil);
with Result do
begin
FieldDefs.Add('REGISTRO',ftInteger,0);
FieldDefs.Add('NODO',ftString,200);
FieldDefs.Add('TIPONODO',ftString,1);
FieldDefs.Add('RUTAFTP',ftString,150);
FieldDefs.Add('NOMBREIMAGEN',ftString,100);
FieldDefs.Add('PADRE',ftInteger,0);
CreateDataSet;
end;
with QuerDatoCarp do
begin
Close;
SQL.Clear;
SQL.Add('SELECT descripcionsubseriedocumental, codigofolio, rutaftp, nombreimagen ');
SQL.Add(' FROM (SELECT DISTINCT orden, descripcionsubseriedocumental, idcarpetaaletacrea, ');
SQL.Add(' secuenciavisual, codigofolio, rutaftp, nombreimagen ');
SQL.Add(' FROM (SELECT CASE WHEN TIAL.tipoaleta = ''D'' ');
SQL.Add(' THEN NULL');
SQL.Add(' ELSE SESU.orden');
SQL.Add(' END AS orden, ');
SQL.Add(' CASE WHEN TISD.descripciontiposeriedocumental = ''HISTORIAS LABORALES''');
SQL.Add(' AND TIAL.tipoaleta = ''D'' ');
SQL.Add(' THEN ''DOCUMENTOS DE IDENTIFICACION'' ');
SQL.Add(' ELSE SUBS.descripcionsubseriedocumental');
SQL.Add(' END AS descripcionsubseriedocumental,');
{PARA LA ALETA FICTICIA "DOCUMENTOS DE IDENTIFICACION" SE CONCATENA I O N AL IDCARPETAALETA
PARA PRODUCIR UN ORDENAMIENTO DIFERENTE AL DE LAS ALETAS. SALEN PRIMERO LOS FOLIOS CAPTURABLES
DE LAS ALETAS DE INSERCION Y LUEGO LOS DE CREACION
}
SQL.Add(' CASE WHEN TIAL.tipoaleta = ''D'' ');
SQL.Add(' THEN CASE WHEN FOLI.tipofolio = ''R'' ');
SQL.Add(' THEN ''I'' || CAST(FOLI.idcarpetaaletacrea AS VARCHAR) ');
SQL.Add(' ELSE ''N'' || CAST(FOLI.idcarpetaaletacrea AS VARCHAR) ');
SQL.Add(' END ');
SQL.Add(' ELSE CAST(FOLI.idcarpetaaletacrea AS VARCHAR) ');
SQL.Add(' END idcarpetaaletacrea, ');
SQL.Add(' FOLI.secuenciavisual, FOLI.codigofolio, ');
SQL.Add(' IMAG.rutaftp, IMAG.nombreimagen');
SQL.Add(Format(' FROM %s.CARPETA CARP ', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.CARPETAALETA CAAL ON '
+ 'CAAL.idcarpeta = CARP.idcarpeta', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.SERIEDOCUMENTAL SEDO ON '
+ 'SEDO.idseriedocumental = CARP.idseriedocumental', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.FLUJO FLUJ ON '
+ 'FLUJ.idflujo = CARP.idflujo ', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.TAREA TARE ON '
+ 'TARE.idtarea = FLUJ.idtareaproxima ', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.TIPOSERIEDOCUMENTAL TISD ON '
+ 'TISD.idtiposeriedocumental = SEDO.idtiposeriedocumental ',
[DMConexion.esquema]));
SQL.Add(Format(' LEFT JOIN %s.FOLIO FOLI ON '
+ 'FOLI.idcarpetaaleta = CAAL.idcarpetaaleta ', [DMConexion.esquema]));
SQL.Add(Format(' LEFT JOIN %s.SERIESUBSERIE SESU ON '
+ 'SESU.idseriesubserie = CAAL.idseriesubserie ', [DMConexion.esquema]));
SQL.Add(Format(' LEFT JOIN %s.SUBSERIEDOCUMENTAL SUBS ON '
+ 'SUBS.idsubseriedocumental = SESU.idsubseriedocumental',
[DMConexion.esquema]));
SQL.Add(Format(' LEFT JOIN %s.IMAGEN IMAG ON '
+ 'IMAG.idfolio = FOLI.idfolio, ', [DMConexion.esquema]));
SQL.Add(' (SELECT UNNEST(ARRAY[''N'',''D'']) AS tipoaleta ) AS TIAL ');
SQL.Add(Format(' WHERE CARP.codigocarpeta= ''%s''' , [p_CodiCarp]));
SQL.Add(' AND (IMAG.version = (SELECT MAX(version) ');
SQL.Add(Format(' FROM %s.IMAGEN',[DMConexion.esquema]));
SQL.Add(' WHERE idfolio = FOLI.idfolio');
SQL.Add(' ) OR IMAG.version IS NULL)');
SQL.Add(' AND ((TIAL.tipoaleta = ''D'' ');
SQL.Add(' AND TISD.descripciontiposeriedocumental = ''HISTORIAS LABORALES'' ');
SQL.Add(' AND FOLI.capturable ');
SQL.Add(' AND TARE.descripciontarea IN (''CAPTURA'',''GENERACIÓN XML'',''FIRMA Y ESTAMPA'')');
SQL.Add(' ) OR TIAL.tipoaleta = ''N'') ');
SQL.Add(' ) AS ORDE ');
SQL.Add(' ORDER BY orden NULLS LAST, idcarpetaaletacrea, secuenciavisual ');
SQL.Add(' ) AS TOTA ');
Open;
if NOT IsEmpty then
begin
First;
NumeRegi:=-1;
while not Eof do
begin
Inc(NumeRegi);
RegiPadrNiv1 := NumeRegi;
SubbSeriDocu := FieldByName('descripcionsubseriedocumental').AsString;
Result.Append;
Result.FieldByName('REGISTRO').Value := NumeRegi;
Result.FieldByName('NODO').Value:= SubbSeriDocu;
Result.FieldByName('TIPONODO').Value:= 'T'; {TIPO TITULO, NO MUESTRA IMAGEN}
Result.FieldByName('PADRE').Value:= -1;
while (not eof)
and (SubbSeriDocu = FieldByName('descripcionsubseriedocumental').AsString) do
begin
if FieldByName('codigofolio').AsString <> '' then
begin
Inc(NumeRegi);
Result.Append;
Result.FieldByName('REGISTRO').Value := NumeRegi;
Result.FieldByName('NODO').Value:= 'M' + FieldByName('codigofolio').AsString;
Result.FieldByName('TIPONODO').Value:= 'F'; {TIPO FOLIO, SI MUESTRA IMAGEN}
Result.FieldByName('RUTAFTP').Value:= FieldByName('rutaftp').AsString;
Result.FieldByName('NOMBREIMAGEN').Value:= FieldByName('nombreimagen').asstring;
Result.FieldByName('PADRE').Value:= RegiPadrNiv1;
end;
Next;
end;
end;
end;
end;
except
on E:exception do
raise Exception.Create(format('No es posible consultar las Imágenes para '
+ 'la Carpeta [%s].',[p_CodiCarp]) + #10#13
+ '* '+ e.Message);
end;
end;
function TDAOCarpetaDigital.ConsultarDatosCarpeta(P_CodiCarp: string): TCarpetaCarpetaDigi;
{ FUNCION QUE BUSCA LA INFORMACION DE UN CARPETA }
var
QuerDatoCarp: TZQuery;
begin
try
QuerDatoCarp := TZQuery.Create(nil);
QuerDatoCarp.Connection := DMConexion.ZConexion;
Result:= TCarpetaCarpetaDigi.Create;
with QuerDatoCarp do
begin
Close;
SQL.Clear;
SQL.Add('SELECT DACA.clasecarpeta, ');
SQL.Add(' (SELECT descripciontarea ');
SQL.Add(Format(' FROM %s.FLUJO FLUJ ', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.TAREA TARE ON TARE.idtarea = FLUJ.idtareaproxima ',
[DMConexion.esquema]));
SQL.Add( ' WHERE FLUJ.idflujo = CAST(LEFT(MIN(DACA.flujocarpeta), '
+ 'STRPOS(MIN(DACA.flujocarpeta),''-'') - 1) AS INTEGER)');
SQL.Add( ' ) as etapacarpeta, ');
SQL.Add( '(SELECT habilitado ');
SQL.Add(Format(' FROM %s.CARPETA ',[DMConexion.esquema]));
SQL.Add( ' WHERE idcarpeta = CAST(SUBSTRING(MIN(DACA.flujocarpeta), '
+ 'STRPOS(MIN(DACA.flujocarpeta),''-'') + 1,1000) AS INTEGER)');
SQL.Add( ' ) as estadocarpeta ');
SQL.Add( 'FROM (SELECT CARP.clasecarpeta, CAST(CARP.idflujo AS VARCHAR) || '
+ '''-'' || CAST(MAX(CARP.idcarpeta) AS VARCHAR) flujocarpeta ');
SQL.Add(Format(' FROM %s.CARPETA CARP ', [DMConexion.esquema]));
SQL.Add(Format(' WHERE CARP.codigocarpeta = ''%s'' ', [P_CodiCarp]));
SQL.Add( ' GROUP BY CARP.clasecarpeta, CARP.idflujo');
SQL.Add( ' ) AS DACA');
SQL.Add( 'GROUP BY DACA.clasecarpeta');
SQL.Add( 'ORDER BY DACA.clasecarpeta');
Open;
if NOT IsEmpty then
begin
First;
if FieldByName('clasecarpeta').Value = 'C' then
begin
Result.EstadoCarpetaCrea:= FieldByName('estadocarpeta').Value;
Result.EtapaCarpetaCrea := FieldByName('etapacarpeta').Value;
Next;
if not eof then
begin
if FieldByName('clasecarpeta').Value = 'I' then
begin
Result.EstadoCarpetaInse := FieldByName('estadocarpeta').Value;
Result.EtapaCarpetaInse := FieldByName('etapacarpeta').Value;
end
else
raise Exception.Create (Format('Clase de Carpeta incorrecta: [%s].',
[FieldByName('clasecarpeta').Value = 'I']));
end;
end
else
raise Exception.Create ('No existen datos de Creación.');
end;
end;
except
on E:exception do
raise Exception.Create(format('No es posible consultar la Información de la '
+ ' Carpeta [%s].',[p_CodiCarp]) + #10#13
+ '* '+ e.Message);
end;
end;
function TDAOCarpetaDigital.ConsultarDatosMtiAndes(p_identipo: Variant;
p_numedocu: string; p_primnomb:string; p_primapel:string;
p_IdenSedo: Variant; p_fechnoin: string; p_fechnofi: string;
p_FechPagoInic: string; p_FechPagoFina: string;
p_PeriInic: string; p_PeriFina: string;
p_IdenFond: variant): TDataSource;
{ FUNCION QUE BUSCA DATOS DE PERSONAS EN LA BASE DE DATOS DE MTI }
var
QuerDatosMTAN: TZQuery;
begin
try
QuerDatosMTAN:= TZQuery.Create(nil);
QuerDatosMTAN.Connection:= DMConexion.ZConexion;
Result:= TDataSource.Create(nil);
with QuerDatosMTAN do
begin
Close;
SQL.Clear;
SQL.Add('SELECT TIID.idtipoidentificacion, TIID.descripciontipoidentificacion, ');
SQL.Add(' IDEN.numerodocumento, PERS.idpersona,');
SQL.Add(' PERS.primernombre, PERS.segundonombre, ');
SQL.Add(' CAST(CASE WHEN TRIM(PERS.segundonombre) IS NULL ');
SQL.Add(' THEN TRIM(PERS.primernombre) ');
SQL.Add(' ELSE TRIM(PERS.primernombre) || '' '' || TRIM(PERS.segundonombre)');
SQL.Add(' END AS CHARACTER VARYING) AS nombres , ');
SQL.Add(' PERS.primerapellido, PERS.segundoapellido, ');
SQL.Add(' CAST(CASE WHEN TRIM(PERS.segundoapellido) IS NULL ');
SQL.Add(' THEN TRIM(PERS.primerapellido) ');
SQL.Add(' ELSE TRIM(PERS.primerapellido) || '' '' || TRIM(PERS.segundoapellido)');
SQL.Add(' END AS CHARACTER VARYING) AS apellidos ');
SQL.Add(Format('FROM %s.IDENTIFICACION IDEN ', [DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.PERSONA PERS ON PERS.idpersona = IDEN.idpersona',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.TIPOIDENTIFICACION TIID ON '
+ 'TIID.idtipoidentificacion = IDEN.idtipoidentificacion',
[DMConexion.esquema]));
SQL.Add(' WHERE 1=1');
if p_identipo <> -1 then
SQL.Add(Format(' AND IDEN.idtipoidentificacion = %s ',[p_identipo]));
if p_numedocu <> '' then
SQL.Add(Format(' AND IDEN.numerodocumento LIKE ''%s''',['%' + p_numedocu + '%']));
if p_primnomb <> '' then
SQL.Add(Format(' AND PERS.primernombre LIKE ''%s''',
['%' + StringReplace(p_primnomb,'''','''''',[rfReplaceAll]) + '%'])); {PORQUE PUEDEN HABER APOSTROFES (') DENTRO DE LA CADENA}
if p_primapel <> '' then
SQL.Add(Format(' AND PERS.primerapellido LIKE ''%s''',
['%' + StringReplace(p_primapel,'''','''''',[rfReplaceAll]) + '%'])); {PORQUE PUEDEN HABER APOSTROFES (') DENTRO DE LA CADENA}
if (p_fechnoin <> '') or (p_FechPagoInic <> '') or (p_PeriInic <> '')
or ((p_IdenFond <> -1) and (p_IdenFond <> null)
or ((p_IdenSedo <> -1) and (p_IdenSedo <> null))) then
begin
SQL.Add(' AND EXISTS (SELECT ididentificacion');
SQL.Add(Format(' FROM %s.FOLIOIDENTIFICACION FOID', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.FOLIO FOLI ON FOLI.idfolio = FOID.idfolio',
[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.CARPETAALETA CAAL ON '
+ 'CAAL.idcarpetaaleta = FOLI.idcarpetaaleta',
[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.CARPETA CARP ON '
+ 'CARP.idcarpeta = CAAL.idcarpeta', [DMConexion.esquema]));
if (p_IdenSedo <> -1) and (p_IdenSedo <> null) then
SQL.Add(Format(' INNER JOIN %s.SERIEDOCUMENTAL SEDO ON '
+ 'SEDO.idseriedocumental = CARP.idseriedocumental',
[DMConexion.esquema]));
if (p_fechnoin <> '') or (p_FechPagoInic <> '') or (p_PeriInic <> '')
or ((p_IdenFond <> -1) and (p_IdenFond <> null)) then
SQL.Add(Format(' INNER JOIN %s.DATOPLANILLA DAPL ON '
+ 'DAPL.iddatoplanilla = FOLI.iddatoplanilla',
[DMConexion.esquema]));
if (p_IdenFond <> -1) and (p_IdenFond <> null) then
begin
SQL.Add(Format(' INNER JOIN %s.FONDO FOND ON '
+ 'FOND.idfondo = DAPL.idfondo', [DMConexion.esquema]));
end;
SQL.Add(' WHERE FOID.ididentificacion = IDEN.ididentificacion');
if (p_IdenSedo <> -1) and (p_IdenSedo <> null) then
SQL.Add(Format(' AND SEDO.idseriedocumental = %s ',[p_IdenSedo]));
if (p_fechnoin <> '') then
begin
if p_fechnoin <= p_fechnofi then
SQL.Add(Format(' AND DAPL.fechanomina BETWEEN ''%s'' AND ''%s'' ',
[p_fechnoin, p_fechnofi]))
else
raise Exception.Create('Error en los parámetros de Fecha de Nómina Inicial-Final.');
end
else
begin
if (p_FechPagoInic <> '') then
begin
if p_FechPagoInic <= p_FechPagoFina then
SQL.Add(Format(' AND DAPL.fechapago BETWEEN ''%s'' AND ''%s'' ',
[p_FechPagoInic, p_FechPagoFina]))
else
raise Exception.Create('Error en los parámetros de Fecha de Pago Inicial-Final.');
end
else
if (p_PeriInic <> '') then
begin
if p_PeriInic <= p_PeriFina then
SQL.Add(Format(' AND DAPL.periodocotizacion BETWEEN ''%s'' AND ''%s'' ',
[p_PeriInic, p_PeriFina]))
else
raise Exception.Create('Error en los parámetros de Fecha de Pago Inicial-Final.');
end;
end;
if (p_IdenFond <> -1) and (p_IdenFond <> null) then
begin
SQL.Add(Format(' AND FOND.idfondo = %s ',[p_IdenFond]));
end;
SQL.Add(' )'); {SE CIERRA EL PARENTESIS DEL EXISTS }
end;
SQL.Add(' ORDER BY primernombre,segundonombre NULLS FIRST, primerapellido, '
+ 'segundoapellido NULLS FIRST');
open;
first;
result.DataSet:=QuerDatosMTAN;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar información de Base de Datos MTI-UNIANDES.'
+ #10#13 + '* '+ e.Message);
end;
end;
function TDAOCarpetaDigital.ConsultarEmpleados(p_IdenPers: Int32; p_NombPers: string;
p_IdenSedo: variant;
p_FechNoin: string; p_FechNofi: string;
p_FechPain: string; p_FechPafi: string;
p_PeriInic: string; p_PeriFina: string;
p_IdenFond: variant): TClientDataSet;
{ FUNCION QUE BUSCA LAS IMAGENES QUE TIENE UNA PERSONA}
var
AletBase : string;
CarpAnioBase: string;
CarpAnioLeid: string;
CarpFech : string;
HistLabo : Boolean;
MessBase : string;
NumeRegi : Int32;
RegiPadrNiv1: Int32;
RegiPadrNiv2: Int32;
RegiPadrNiv3: Int32;
SecuAlet : Int32;
SeriDocu : string;
SubsDocu : string;
QuerDatoImag: TZQuery;
begin
try
QuerDatoImag := TZQuery.Create(nil);
QuerDatoImag.Connection := DMConexion.ZConexion;
Result:= TClientDataSet.Create(nil);
with Result do
begin
FieldDefs.Add('REGISTRO',ftInteger,0);
FieldDefs.Add('NODO',ftString,200);
FieldDefs.Add('TIPONODO',ftString,1);
FieldDefs.Add('RUTAFTP',ftString,150);
FieldDefs.Add('NOMBREIMAGEN',ftString,100);
FieldDefs.Add('PADRE',ftInteger,0);
CreateDataSet;
end;
with QuerDatoImag do
begin
Close;
SQL.Clear;
SQL.Add('SELECT descripciontiposeriedocumental, descripcionseriedocumental, carpetafecha, descripcionaleta, ');
SQL.Add(' conperiodo, codigofolio, rutaftp, nombreimagen ');
SQL.Add( 'FROM (SELECT DISTINCT descripciontiposeriedocumental, descripcionseriedocumental, carpetafecha, ');
SQL.Add(' descripcionaleta, conperiodo, codigofolio, rutaftp, nombreimagen, ');
SQL.Add(' orden, idcarpetaaletacrea, secuenciavisual ');
SQL.Add(' FROM (SELECT ALTO.descripciontiposeriedocumental,ALTO.descripcionseriedocumental,');
SQL.Add(' CASE WHEN ALTO.descripciontiposeriedocumental = ''PLANILLAS DE NÓMINA'' ');
SQL.Add(' THEN CAST(ALPE.fechanomina AS CHARACTER VARYING) ');
SQL.Add(' WHEN ALTO.descripciontiposeriedocumental = ''PLANILLAS DE APORTES'' ');
if (p_FechPain <> '') then
SQL.Add(' THEN CAST(ALPE.fechapago AS CHARACTER VARYING)')
else
SQL.Add(' THEN CAST(ALPE.periodocotizacion AS CHARACTER VARYING)');
SQL.Add(' ELSE ALTO.codigocarpeta ');
SQL.Add(' END AS carpetafecha, ');
SQL.Add(' CASE WHEN TIAL.tipoaleta = ''D'' ');
SQL.Add(' THEN NULL ');
SQL.Add(' ELSE ALTO.orden ');
SQL.Add(' END AS orden, ');
SQL.Add(' CASE WHEN TIAL.tipoaleta = ''D'' ');
SQL.Add(' THEN ''DOCUMENTOS DE IDENTIFICACION'' ');
SQL.Add(' ELSE ALTO.descripcionsubseriedocumental ');
SQL.Add(' END AS descripcionaleta, ');
SQL.Add(' CASE WHEN ALTO.descripciontiposeriedocumental = ''PLANILLAS DE NÓMINA'' ');
SQL.Add(' THEN FALSE ');
SQL.Add(' WHEN ALTO.descripciontiposeriedocumental = ''PLANILLAS DE APORTES'' ');
if (p_FechPain <> '') then
SQL.Add(' THEN FALSE ')
else
SQL.Add(' THEN TRUE ');
SQL.Add(' ELSE TRUE ');
SQL.Add(' END AS conperiodo, ');
SQL.Add(' ALPE.codigofolio, ');
{PARA LA ALETA FICTICIA "DOCUMENTOS DE IDENTIFICACION" SE CONCATENA I O N AL IDCARPETAALETA
PARA PRODUCIR UN ORDENAMIENTO DIFERENTE AL DE LAS ALETAS. SALEN PRIMERO LOS FOLIOS CAPTURABLES
DE LAS ALETAS DE INSERCION Y LUEGO LOS DE CREACION
}
SQL.Add(' CASE WHEN TIAL.tipoaleta = ''D'' ');
SQL.Add(' THEN CASE WHEN ALPE.tipofolio = ''R'' ');
SQL.Add(' THEN ''I'' || CAST(ALPE.idcarpetaaletacrea AS VARCHAR) ');
SQL.Add(' ELSE ''N'' || CAST(ALPE.idcarpetaaletacrea AS VARCHAR) ');
SQL.Add(' END ');
SQL.Add(' ELSE CAST(ALPE.idcarpetaaletacrea AS VARCHAR) ');
SQL.Add(' END idcarpetaaletacrea, ');
SQL.Add(' ALPE.secuenciavisual, ALPE.rutaftp, ALPE.nombreimagen ');
SQL.Add(' FROM (SELECT DISTINCT ALET.idcarpetaaleta,TISD.descripciontiposeriedocumental, ');
SQL.Add(' CARP.codigocarpeta, SEDO.descripcionseriedocumental,SESU.orden, ');
SQL.Add(' SUDO.descripcionsubseriedocumental ');
SQL.Add(Format(' FROM %s.IDENTIFICACION IDEN ',[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.FOLIOIDENTIFICACION FOID ON '
+ 'FOID.ididentificacion = IDEN.ididentificacion', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.FOLIO FOLI ON '
+ 'FOLI.idfolio = FOID.idfolio' ,[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.CARPETAALETA CAAL ON '
+ 'CAAL.idcarpetaaleta = FOLI.idcarpetaaleta' ,[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.CARPETAALETA ALET ON '
+ 'ALET.idcarpeta = caal.idcarpeta',[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.CARPETA CARP ON '
+ 'CARP.idcarpeta = ALET.idcarpeta',[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.SERIEDOCUMENTAL SEDO ON '
+ 'SEDO.idseriedocumental = CARP.idseriedocumental',[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.SERIESUBSERIE SESU ON '
+ 'SESU.idseriesubserie = ALET.idseriesubserie',[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.SUBSERIEDOCUMENTAL SUDO ON '
+ 'SUDO.idsubseriedocumental = SESU.idsubseriedocumental',
[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.TIPOSERIEDOCUMENTAL TISD ON '
+ 'TISD.idtiposeriedocumental = SEDO.idtiposeriedocumental',
[DMConexion.esquema]));
SQL.Add(Format(' WHERE IDEN.idpersona = %d' , [p_idenpers]));
if (p_IdenSedo <> -1) and (p_IdenSedo <> null) then
SQL.Add(Format(' AND SEDO.idseriedocumental = %s ',[p_IdenSedo]));
SQL.Add(' ) AS ALTO ');
SQL.Add(' LEFT JOIN (SELECT CAAL.idcarpetaaleta,DAPL.fechanomina,DAPL.fechapago, ');
SQL.Add(' DAPL.periodocotizacion, FOLI.codigofolio, FOLI.tipofolio, ');
SQL.Add(' FOLI.idcarpetaaletacrea,FOLI.secuenciavisual, FOLI.capturable, ');
SQL.Add(' IMAG.rutaftp, IMAG.nombreimagen');
SQL.Add(Format(' FROM %s.IDENTIFICACION IDEN',[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.FOLIOIDENTIFICACION FOID ON '
+ 'FOID.ididentificacion = IDEN.ididentificacion',[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.FOLIO FOLI ON '
+ 'FOLI.idfolio = FOID.idfolio',[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.CARPETAALETA CAAL ON '
+ 'CAAL.idcarpetaaleta = FOLI.idcarpetaaleta',[DMConexion.esquema]));
SQL.Add(Format(' LEFT JOIN %s.IMAGEN IMAG ON '
+ 'IMAG.idfolio = FOLI.idfolio',[DMConexion.esquema]));
SQL.Add(Format(' LEFT JOIN %s.DATOPLANILLA DAPL ON '
+ 'DAPL.iddatoplanilla = FOLI.iddatoplanilla',[DMConexion.esquema]));
if (p_IdenFond <> -1) and (p_IdenFond <> null) then
SQL.Add(Format(' LEFT JOIN %s.FONDO FOND ON '
+ 'FOND.idfondo = DAPL.idfondo', [DMConexion.esquema]));
SQL.Add(Format(' WHERE IDEN.idpersona = %d' , [p_idenpers]));
SQL.Add(' AND (IMAG.version IS NULL ');
SQL.Add(' OR IMAG.version = (SELECT MAX(version)');
SQL.Add(Format(' FROM %s.IMAGEN',[DMConexion.esquema]));
SQL.Add(' WHERE idfolio = FOLI.idfolio))');
if (p_IdenFond <> -1) and (p_IdenFond <> null) then
SQL.Add(Format(' AND FOND.idfondo = %s ',[p_IdenFond]));
if (p_fechnoin <> '') then
begin
if p_fechnoin <= p_fechnofi then
SQL.Add(Format(' AND DAPL.fechanomina BETWEEN ''%s'' AND ''%s'' ',
[p_fechnoin, p_fechnofi]))
else
raise Exception.Create('Error en los parámetros de Fecha de Nómina Inicial-Final.');
end
else
if (p_FechPain <> '') then
begin
if p_FechPain <= p_FechPafi then
SQL.Add(Format(' AND DAPL.fechapago BETWEEN ''%s'' AND ''%s'' ',
[p_FechPain, p_FechPafi]))
else
raise Exception.Create('Error en los parámetros de Fecha de Pago Inicial-Final.');
end
else
if (p_PeriInic <> '') then
begin
if p_PeriInic <= p_PeriFina then
SQL.Add(Format(' AND DAPL.periodocotizacion BETWEEN ''%s'' AND ''%s'' ',
[p_PeriInic, p_PeriFina]))
else
raise Exception.Create('Error en los parámetros de Periodo Cotización '
+ 'Inicial-Final.');
end;
SQL.Add(' )AS ALPE ON ALPE.idcarpetaaleta = ALTO.idcarpetaaleta,');
SQL.Add(' (SELECT UNNEST(ARRAY[''N'',''D''] )AS tipoaleta) AS TIAL');
SQL.Add(' WHERE (TIAL.tipoaleta = ''D'' ');
SQL.Add(' AND ALTO.descripciontiposeriedocumental = ''HISTORIAS LABORALES'' ');
SQL.Add(' AND ALPE.capturable) OR TIAL.tipoaleta = ''N'' ');
SQL.Add(' ) AS ORDE');
SQL.Add(' WHERE carpetafecha IS NOT NULL');
SQL.Add(' ORDER BY descripcionseriedocumental, carpetafecha, orden NULLS LAST, ');
SQL.Add(' idcarpetaaletacrea, secuenciavisual ');
SQL.Add(' ) AS TOTA ');
Open;
if NOT IsEmpty then
begin
First;
NumeRegi:=-1;
while not Eof do
begin
Inc(NumeRegi);
RegiPadrNiv1 := NumeRegi;
SeriDocu := FieldByName('descripcionseriedocumental').AsString;
SubsDocu := FieldByName('descripciontiposeriedocumental').AsString;
if SubsDocu = 'HISTORIAS LABORALES' then
HistLabo:= True
else
HistLabo:= False;
Result.Append;
Result.FieldByName('REGISTRO').Value := NumeRegi;
Result.FieldByName('NODO').Value:= SeriDocu;
Result.FieldByName('TIPONODO').Value:= 'T'; {TIPO TITULO, NO MUESTRA IMAGEN}
Result.FieldByName('PADRE').Value:= -1;
SecuAlet:= 0;
while (not eof) and (SeriDocu = FieldByName('descripcionseriedocumental').AsString) do
begin
Inc(NumeRegi);
RegiPadrNiv2 := NumeRegi;
if HistLabo then
begin
{PARA MOSTRAR NUMERO DE CARPETA Y CODIGO DE LA MISMA COMO ENCABEZADO}
inc(SecuAlet);
CarpAnioBase:= FieldByName('carpetafecha').AsString;
CarpFech := '[Carpeta ' + IntToStr(SecuAlet) + ' - ' + 'M' + CarpAnioBase + ']';
end
else
begin
{PARA MOSTRAR EL AÑO COMO ENCABEZADO}
CarpAnioBase:= AnsiLeftStr(FieldByName('carpetafecha').AsString,4);
CarpFech := CarpAnioBase;
end;
Result.Append;
Result.FieldByName('REGISTRO').Value := NumeRegi;
Result.FieldByName('NODO').Value:= CarpFech;
Result.FieldByName('TIPONODO').Value:= 'T'; {TIPO TITULO, NO MUESTRA IMAGEN}
Result.FieldByName('PADRE').Value:= RegiPadrNiv1;
CarpAnioLeid:= CarpAnioBase;
while (not eof) and (SeriDocu = FieldByName('descripcionseriedocumental').AsString)
and (CarpAnioBase = CarpAnioLeid) do
begin
Inc(NumeRegi);
if HistLabo then
begin
RegiPadrNiv3 := NumeRegi;
AletBase := FieldByName('descripcionaleta').AsString;
Result.Append;
Result.FieldByName('REGISTRO').Value := NumeRegi;
Result.FieldByName('NODO').Value := AletBase;
Result.FieldByName('TIPONODO').Value:= 'T'; {TIPO TITULO, NO MUESTRA IMAGEN}
Result.FieldByName('PADRE').Value := RegiPadrNiv2;
while (not Eof) and (SeriDocu = FieldByName('descripcionseriedocumental').AsString)
and (CarpAnioBase = CarpAnioLeid)
and (AletBase = FieldByName('descripcionaleta').AsString) do
begin
if FieldByName('codigofolio').AsString <> '' then
begin
Inc(NumeRegi);
Result.Append;
Result.FieldByName('REGISTRO').Value := NumeRegi;
Result.FieldByName('NODO').Value:= 'M' + FieldByName('codigofolio').AsString;
Result.FieldByName('TIPONODO').Value:= 'F'; {TIPO FOLIO, SI MUESTRA IMAGEN}
Result.FieldByName('RUTAFTP').Value:= FieldByName('rutaftp').AsString;
Result.FieldByName('NOMBREIMAGEN').Value:= FieldByName('nombreimagen').asstring;
Result.FieldByName('PADRE').Value:= RegiPadrNiv3;
end;
Next;
CarpAnioLeid := FieldByName('carpetafecha').AsString
end;
end
else
begin
if FieldByName('codigofolio').AsString <> '' then
begin
Inc(NumeRegi);
Result.Append;
Result.FieldByName('REGISTRO').Value := NumeRegi;
MessBase:= AnsiMidStr(FieldByName('carpetafecha').AsString,6,2);
if MessBase <> '' then
MessBase:= GeneraNombreMes(StrToInt(MessBase),3,'MY')
+ IfThen(FieldByName('conperiodo').value,'',
'-' + AnsiMidStr(FieldByName('carpetafecha').AsString,9,2));
Result.FieldByName('NODO').Value:= '[' + MessBase + ']-M'
+ FieldByName('codigofolio').AsString;
Result.FieldByName('TIPONODO').Value:= 'F'; {TIPO FOLIO, SI MUESTRA IMAGEN}
Result.FieldByName('RUTAFTP').Value:= FieldByName('rutaftp').AsString;
Result.FieldByName('NOMBREIMAGEN').Value:= FieldByName('nombreimagen').asstring;
Result.FieldByName('PADRE').Value:= RegiPadrNiv2;
end;
Next;
CarpAnioLeid := AnsiLeftStr(FieldByName('carpetafecha').AsString,4);
end;
end;
end;
end;
end;
end;
except
on E:exception do
raise Exception.Create(format('No es posible consultar las Imágenes para '
+ '[%s].',[p_NombPers]) + #10#13 + '* '+ e.Message);
end;
end;
function TDAOCarpetaDigital.ConsultarFondos(p_TipoFond: string): TDataSource;
{ FUNCION QUE BUSCA LOS FONDOS DE PENSIONES, SALUD Y RIESGOS }
var
QuerDatoFond: TZQuery;
begin
try
QuerDatoFond:= TZQuery.Create(nil);
QuerDatoFond.Connection:= DMConexion.ZConexion;
Result:= TDataSource.Create(nil);
with QuerDatoFond do
begin
Close;
SQL.Clear;
SQL.Add('SELECT idfondo, cast(descripcionfondo AS character varying)');
SQL.Add(' FROM (SELECT -1 idfondo, NULL descripcionfondo');
SQL.Add(' UNION');
SQL.Add(' SELECT idfondo, descripcionfondo ' );
SQL.Add(Format(' FROM %s.FONDO FOND', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.TIPOFONDO AS TIFO ON '
+ 'TIFO.idtipofondo = FOND.idtipofondo ', [DMConexion.esquema]));
SQL.Add(Format(' WHERE TIFO.descripciontipofondo = ''%s''' , [p_TipoFond]));
SQL.Add(' ) AS FNDS ');
SQL.Add(' ORDER BY descripcionfondo NULLS FIRST');
open;
first;
result.DataSet:=QuerDatoFond;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar los Fondos.'
+ #10#13 + '* '+ e.Message);
end;
end;
function TDAOCarpetaDigital.ConsultarSeriesDocumentales: TDataSource;
{ FUNCION QUE BUSCA LAS SERIES DOCUMENTALES }
var
QuerDatoSedo: TZQuery;
begin
try
QuerDatoSedo:= TZQuery.Create(nil);
QuerDatoSedo.Connection:= DMConexion.ZConexion;
Result:= TDataSource.Create(nil);
with QuerDatoSedo do
begin
Close;
SQL.Clear;
SQL.Add('SELECT idseriedocumental, descripcionseriedocumental, descripciontiposeriedocumental ');
SQL.Add(Format('FROM %s.SERIEDOCUMENTAL AS SEDO ', [DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.TIPOSERIEDOCUMENTAL AS TIDO ON '
+ 'TIDO.idtiposeriedocumental = SEDO.idtiposeriedocumental',
[DMConexion.esquema]));
SQL.Add(' ORDER BY descripcionseriedocumental NULLS FIRST');
open;
first;
result.DataSet:=QuerDatoSedo;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar las Series Documentales.'
+ #10#13 + '* '+ e.Message);
end;
end;
function TDAOCarpetaDigital.ConsultarTiposIdentificacion: TDataSource;
{ FUNCION QUE BUSCA LOS TIPOS DE IDENTIFICACION }
var
QuerDatoTipi: TZQuery;
begin
try
QuerDatoTipi:= TZQuery.Create(nil);
QuerDatoTipi.Connection:= DMConexion.ZConexion;
Result:= TDataSource.Create(nil);
with QuerDatoTipi do
begin
Close;
SQL.Clear;
SQL.Add('SELECT *');
SQL.Add(' FROM (SELECT -1 idtipoidentificacion, NULL descripciontipoidentificacion');
SQL.Add(' UNION');
SQL.Add(' SELECT idtipoidentificacion, descripciontipoidentificacion');
SQL.Add(Format(' FROM %s.TIPOIDENTIFICACION ) AS TIID ', [DMConexion.esquema]));
SQL.Add(' ORDER BY descripciontipoidentificacion NULLS FIRST');
open;
first;
result.DataSet:=QuerDatoTipi;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar los Tipos de Identificacion.'
+ #10#13 + '* '+ e.Message);
end;
end;
{$ENDREGION}
{$REGION 'CONSTRUCTOR Y DESTRUCTOR'}
constructor TDAOCarpetaDigital.create;
begin
FQuery:= TZQuery.create(nil);
FQuery.Connection:= DMConexion.ZConexion;
end;
destructor TDAOCarpetaDigital.destroy;
begin
FQuery.Close;
FQuery.Connection.Disconnect;
FQuery.free;
end;
{$ENDREGION}
end.
|
unit datetime_lib;
{
Format datetimes in a more Human Readable form
(like tomorow, yesterday, 4 days from now, 6 hours ago, more 3 years ago)
example:
var := DateTimeHuman( theDate);
var := DateTimeHuman( theDate, 7);
var := DateTimeHuman( theDate, 7, 'ddd d mmm yyyy');
var := DateTimeHuman( '2015/12/30');
}
{$mode objfpc}{$H+}
interface
uses
dateutils, common, language_lib, Classes, SysUtils;
function DateTimeHuman(TheDate: string; MaxIntervalDate: integer = 30; FormatDate: string = ''): string;
function DateTimeHuman(TheDate: TDateTime; MaxIntervalDate: integer = 30; FormatDate: string = ''): string;
implementation
function _DateTimeDiff(const ANow, AThen: TDateTime): TDateTime;
begin
Result := ANow - AThen;
if (ANow > 0) and (AThen < 0) then
Result := Result - 0.5
else if (ANow < -1.0) and (AThen > -1.0) then
Result := Result + 0.5;
end;
function DateTimeHuman(TheDate: string; MaxIntervalDate: integer; FormatDate: string): string;
var
sdf: ansistring;
dateTmp: TDateTime;
//ts: TFormatSettings;
begin
//{$WARN SYMBOL_PLATFORM OFF}
//GetLocaleFormatSettings(0, ts);
//{$WARN SYMBOL_PLATFORM ON}
//ts.ShortDateFormat := 'yyyy/MM/dd h:nn';
sdf := DefaultFormatSettings.ShortDateFormat;
DefaultFormatSettings.ShortDateFormat := 'yyyy/MM/dd h:nn';
try
//dateTmp := StrToDateTime(TheDate, ts);
dateTmp := StrToDateTime(TheDate);
Result := DateTimeHuman(dateTmp, MaxIntervalDate, FormatDate);
except
on e: Exception do
begin
Result := e.Message + ': "' + TheDate + '"';
end;
end;
DefaultFormatSettings.ShortDateFormat := sdf;
end;
function _SayDate(TheDate: TDateTime; MaxIntervalDate: integer; FormatDate: string;
Suffix: string = 'ago'; Prefix: string = ''): string;
var
diff, i: integer;
begin
diff := DaysBetween(Now, TheDate);
if diff <= MaxIntervalDate then
begin
i := HoursBetween(Now, TheDate);
if i >= 1 then
begin
if i > 24 then
Result := Format(__('%d days ' + Suffix), [diff])
else
Result := Format(__('%d hours ' + Suffix), [i]);
end
else
begin
i := MinutesBetween(Now, TheDate);
if i = 0 then
Result := Format(__('%d secondss ' + Suffix), [SecondsBetween(Now, TheDate)])
else
Result := Format(__('%d minutes ' + Suffix), [i]);
end;
end
else
begin
if FormatDate = '' then
begin
if diff < 31 then
Result := Format(__('%d days ' + Suffix), [DaysBetween(Now, TheDate)]);
if diff > 30 then
Result := Format(__(Prefix + ' %d months ' + Suffix), [MonthsBetween(Now, TheDate)]);
if diff > 360 then
Result := Format(__(Prefix + ' %d years ' + Suffix), [YearsBetween(Now, TheDate)]);
end
else
begin
DateTimeToString(Result, FormatDate, TheDate);
end;
end;
end;
function DateTimeHuman(TheDate: TDateTime; MaxIntervalDate: integer; FormatDate: string): string;
var
diff: integer;
diffDate: TDateTime;
begin
if MaxIntervalDate = 0 then
MaxIntervalDate := 30;
diffDate := _DateTimeDiff(TheDate, Now);
diff := DaysBetween(Now, TheDate);
if diffDate <= 0 then
begin
if diff = 1 then
Result := __('yesterday')
else
Result := _SayDate(TheDate, MaxIntervalDate, FormatDate, 'ago', 'more');
end
else
begin // present
if diff = 1 then
Result := __('tomorrow')
else
Result := _SayDate(TheDate, MaxIntervalDate, FormatDate, 'from now');
end;
end;
end.
|
unit LocalizeApplications;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils;
procedure TranslateAppFromPoFile(APoFileName : String);
function TranslateWithTranslator(AComponent : TPersistent) : Boolean;
implementation
uses Forms, Translations, LCLTranslator, LResources, LazFileUtils;
function TranslateWithTranslator(AComponent : TPersistent) : Boolean;
begin
Result := False;
if not Assigned(AComponent) then Exit;
if not Assigned(LRSTranslator) then Exit;
if not (LRSTranslator is TPOTranslator) then Exit;
if not (LRSTranslator is TDefaultTranslator) then Exit;
TUpdateTranslator(LRSTranslator).UpdateTranslation(AComponent);
Result := True;
end;
procedure TranslateAppFromPoFile(APoFileName : String);
var LocalTranslator: TPOTranslator;
i, Count : Integer;
begin
if APoFileName = '' then Exit;
if not FileExistsUTF8(APoFileName) then Exit;
LocalTranslator := nil;
Translations.TranslateResourceStrings(APoFileName);
LocalTranslator := TPOTranslator.Create(APoFileName);
if not Assigned(LocalTranslator) then Exit;
if Assigned(LRSTranslator) then FreeAndNil(LRSTranslator);
LRSTranslator := LocalTranslator;
Count := Screen.CustomFormCount - 1;
for i:= 0 to Count do LocalTranslator.UpdateTranslation(Screen.CustomForms[i]);
Count := Screen.DataModuleCount - 1;
for i := 0 to Count do LocalTranslator.UpdateTranslation(Screen.DataModules[i]);
end;
finalization
if Assigned(LRSTranslator) then FreeAndNil(LRSTranslator);
end.
|
unit AlterView;
interface
uses
System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
CreateObjectDialog, Vcl.ImgList, SynEditHighlighter, SynHighlighterSQL, Vcl.ActnList, Vcl.StdCtrls, Vcl.ComCtrls,
Vcl.ToolWin, JvExComCtrls, SynEdit, BCControls.PageControl, BCControls.Edit, DBAccess, Ora, MemDS, Vcl.Buttons,
BCControls.ToolBar, BCControls.DBGrid, Vcl.ExtCtrls, Data.DB, BCDialogs.Dlg, System.Actions, GridsEh, DBAxisGridsEh,
DBGridEh, BCControls.ImageList, JvComCtrls, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh;
type
TAlterViewDialog = class(TCreateObjectBaseDialog)
AddColumnAction: TAction;
ColumnButtonPanel: TPanel;
ColumnCommentsDBGrid: TBCDBGrid;
ColumnCommentsPanel: TPanel;
ColumnCommentsTabSheet: TTabSheet;
ColumnsDataSource: TOraDataSource;
ColumnsDBGrid: TBCDBGrid;
ColumnsPanel: TPanel;
ColumnsQuery: TOraQuery;
ColumnsTabSheet: TTabSheet;
CommentEdit: TBCEdit;
CommnetLabel: TLabel;
DeleteColumnAction: TAction;
MoveDownAction: TAction;
MoveUpAction: TAction;
OriginalColumnsQuery: TOraQuery;
ResetColumnsAction: TAction;
SelectStatementTabSheet: TTabSheet;
SQLPanel: TPanel;
SQLSynEdit: TSynEdit;
ViewNameEdit: TBCEdit;
ViewNameLabel: TLabel;
ColumnsToolBar: TBCToolBar;
MoveUpToolButton: TToolButton;
MoveDownToolButton: TToolButton;
AddColumnToolButton: TToolButton;
DeleteColumnToolButton: TToolButton;
DividerBevel: TBevel;
ResetToolBar: TBCToolBar;
ResetToolButton: TToolButton;
procedure AddColumnActionExecute(Sender: TObject);
procedure ColumnCommentsDBGridGetCellParams(Sender: TObject; Column: TColumnEh; AFont: TFont; var Background: TColor; State: TGridDrawState);
procedure ColumnsDBGridGetCellParams(Sender: TObject; Column: TColumnEh; AFont: TFont; var Background: TColor; State: TGridDrawState);
procedure DeleteColumnActionExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure MoveDownActionExecute(Sender: TObject);
procedure MoveUpActionExecute(Sender: TObject);
procedure PageControlChange(Sender: TObject);
procedure ResetColumnsActionExecute(Sender: TObject);
procedure ColumnsDBGridKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
FMaterialized: Boolean;
FOriginalViewComment: string;
procedure GetViewData;
protected
procedure CreateSQL; override;
function CheckFields: Boolean; override;
procedure Initialize; override;
public
{ Public declarations }
end;
function AlterViewDialog: TAlterViewDialog;
implementation
{$R *.dfm}
uses
DataModule, Lib, Vcl.Themes, Winapi.UxTheme, BCCommon.StyleUtils, BCCommon.Messages, BCCommon.Lib, System.AnsiStrings;
var
FAlterViewDialog: TAlterViewDialog;
function AlterViewDialog: TAlterViewDialog;
begin
if not Assigned(FAlterViewDialog) then
Application.CreateForm(TAlterViewDialog, FAlterViewDialog);
Result := FAlterViewDialog;
SetStyledFormSize(TDialog(Result));
end;
procedure TAlterViewDialog.FormDestroy(Sender: TObject);
begin
inherited;
FAlterViewDialog := nil;
end;
procedure TAlterViewDialog.MoveDownActionExecute(Sender: TObject);
begin
inherited;
Lib.MoveGridRowDown(ColumnsQuery);
end;
procedure TAlterViewDialog.MoveUpActionExecute(Sender: TObject);
begin
inherited;
Lib.MoveGridRowUp(ColumnsQuery);
end;
procedure TAlterViewDialog.PageControlChange(Sender: TObject);
begin
inherited;
if FOriginalViewComment = CommentEdit.Text then
CommentEdit.Font.Color := clWindowText
else
CommentEdit.Font.Color := clRed;
end;
procedure TAlterViewDialog.ResetColumnsActionExecute(Sender: TObject);
begin
inherited;
GetViewData;
end;
procedure TAlterViewDialog.AddColumnActionExecute(Sender: TObject);
begin
inherited;
ColumnsQuery.Append;
end;
procedure TAlterViewDialog.DeleteColumnActionExecute(Sender: TObject);
begin
inherited;
ColumnsQuery.Delete;
end;
procedure TAlterViewDialog.ColumnCommentsDBGridGetCellParams(Sender: TObject; Column: TColumnEh; AFont: TFont;
var Background: TColor; State: TGridDrawState);
var
LStyles: TCustomStyleServices;
LDetails: TThemedElementDetails;
LColor: TColor;
begin
LStyles := StyleServices;
OriginalColumnsQuery.Locate('COLUMN_ID', ColumnsQuery.FieldByName('COLUMN_ID').AsInteger, []);
if (Column.FieldName = 'COLUMN_COMMENT') then
begin
if ColumnsQuery.FieldByName(Column.FieldName).AsString = OriginalColumnsQuery.FieldByName(Column.FieldName).AsString then
begin
if UseThemes then
begin
LDetails := LStyles.GetElementDetails(tgCellNormal);
if not LStyles.GetElementColor(LDetails, ecTextColor, LColor) or (LColor = clNone) then
LColor := LStyles.GetSystemColor(clWindowText);
AFont.Color := LColor;
if not LStyles.GetElementColor(LDetails, ecFillColor, LColor) or (LColor = clNone) then
LColor := LStyles.GetSystemColor(clWindow);
Background := LColor;
end
else
begin
AFont.Color := ColumnCommentsDBGrid.Font.Color;
Background := ColumnCommentsDBGrid.Color;
end;
end
else
begin
AFont.Color := clWhite;
Background := clRed;
end;
end;
if Column.FieldName = 'COLUMN_NAME' then
begin
if UseThemes then
Background := LStyles.GetSystemColor(clBtnFace)
else
Background := clBtnFace;
end;
end;
function TAlterViewDialog.CheckFields: Boolean;
begin
Result := False;
if ColumnsQuery.RecordCount = 0 then
begin
ShowErrorMessage('Set columns.');
Exit;
end;
Result := True;
end;
procedure TAlterViewDialog.ColumnsDBGridGetCellParams(Sender: TObject; Column: TColumnEh;
AFont: TFont; var Background: TColor; State: TGridDrawState);
var
LStyles: TCustomStyleServices;
LDetails: TThemedElementDetails;
LColor: TColor;
begin
LStyles := StyleServices;
OriginalColumnsQuery.Locate('COLUMN_ID', ColumnsQuery.FieldByName('COLUMN_ID').AsInteger, []);
if ColumnsQuery.FieldByName(Column.FieldName).IsNull or
(ColumnsQuery.FieldByName(Column.FieldName).AsString = OriginalColumnsQuery.FieldByName(Column.FieldName).AsString) then
begin
if UseThemes then
begin
LDetails := LStyles.GetElementDetails(tgCellNormal);
if not LStyles.GetElementColor(LDetails, ecTextColor, LColor) or (LColor = clNone) then
LColor := LStyles.GetSystemColor(clWindowText);
AFont.Color := LColor;
if not LStyles.GetElementColor(LDetails, ecFillColor, LColor) or (LColor = clNone) then
LColor := LStyles.GetSystemColor(clWindow);
Background := LColor;
end
else
begin
AFont.Color := ColumnsDBGrid.Font.Color;
Background := ColumnsDBGrid.Color;
end;
end
else
begin
AFont.Color := clWhite;
Background := clRed;
end;
end;
procedure TAlterViewDialog.ColumnsDBGridKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
Key := Char(System.AnsiStrings.StrUpper(@Key)^); { Maybe there's a better way to do this... }
end;
procedure TAlterViewDialog.GetViewData;
var
OraQuery: TOraQuery;
begin
with ColumnsQuery do
begin
Session := FOraSession;
Close;
Open;
end;
with OriginalColumnsQuery do
begin
Session := FOraSession;
Close;
Open;
end;
ViewNameEdit.Text := FObjectName;
FOriginalViewComment := Lib.GetTableOrViewComment(FOraSession, FSchemaParam, FObjectName);
CommentEdit.Text := FOriginalViewComment;
{ columns }
OraQuery := TOraQuery.Create(nil);
OraQuery.Session := FOraSession;
OraQuery.SQL.Add(DM.StringHolder.StringsByName['ViewColumnsSQL'].Text);
with OraQuery do
try
ParamByName('P_VIEW_NAME').AsWideString := FObjectName;
ParamByName('P_OWNER').AsWideString := FSchemaParam;
Prepare;
Open;
while not Eof do
begin
ColumnsQuery.Append;
ColumnsQuery.FieldByName('COLUMN_ID').AsString := FieldByName('COLUMN_ID').AsString;
ColumnsQuery.FieldByName('COLUMN_NAME').AsString := FieldByName('COLUMN_NAME').AsString;
ColumnsQuery.FieldByName('COLUMN_COMMENT').AsString := FieldByName('COMMENTS').AsString;
OriginalColumnsQuery.Append;
OriginalColumnsQuery.FieldByName('COLUMN_ID').AsString := FieldByName('COLUMN_ID').AsString;
OriginalColumnsQuery.FieldByName('COLUMN_NAME').AsString := FieldByName('COLUMN_NAME').AsString;
OriginalColumnsQuery.FieldByName('COLUMN_COMMENT').AsString := FieldByName('COMMENTS').AsString;
Next;
end;
finally
Close;
UnPrepare;
FreeAndNil(OraQuery);
end;
{ select statements }
OraQuery := TOraQuery.Create(nil);
OraQuery.Session := FOraSession;
OraQuery.SQL.Add(DM.StringHolder.StringsByName['ViewTextSQL'].Text);
with OraQuery do
try
ParamByName('P_VIEW_NAME').AsWideString := FObjectName;
ParamByName('P_OWNER').AsWideString := FSchemaParam;
Prepare;
Open;
SQLSynEdit.Text := FieldByName('TEXT').AsWideString;
FMaterialized := FieldByName('TYPE').AsString = 'M';
finally
Close;
UnPrepare;
FreeAndNil(OraQuery);
end;
end;
procedure TAlterViewDialog.Initialize;
begin
inherited;
UpdateMargin(SQLSynEdit);
GetViewData;
end;
procedure TAlterViewDialog.CreateSQL;
var
i: Integer;
Columns: string;
ColumnComments: WideString;
Materialized: string;
begin
SourceSynEdit.Lines.Clear;
SourceSynEdit.Lines.BeginUpdate;
i := 1;
Columns := '(';
with ColumnsQuery do
begin
First;
while not Eof do
begin
Columns := Columns + FieldByName('COLUMN_NAME').AsString;
if not FieldByName('COLUMN_COMMENT').IsNull then
ColumnComments := ColumnComments + Format('COMMENT ON COLUMN %s.%s.%s IS %s;', [FSchemaParam,
ViewNameEdit.Text, Trim(FieldByName('COLUMN_NAME').AsWideString), QuotedStr(FieldByName('COLUMN_COMMENT').AsWideString)]) + CHR_ENTER;
Next;
if not Eof then
Columns := Columns + ', ';
if i mod 5 = 0 then
begin
i := 1;
Columns := Columns + CHR_ENTER + ' ';
end;
Inc(i);
end;
First;
end;
Columns := Columns + ') AS';
SourceSynEdit.Lines.Clear;
SourceSynEdit.Lines.BeginUpdate;
Materialized := '';
if FMaterialized then
Materialized := ' MATERIALIZED';
SourceSynEdit.Lines.Text := Format('CREATE OR REPLACE%s VIEW %s.%s', [Materialized, FSchemaParam, ViewNameEdit.Text]) + CHR_ENTER +
Columns + CHR_ENTER + SQLSynEdit.Text + ';' + CHR_ENTER;
Application.ProcessMessages;
{ comments }
if (CommentEdit.Text <> '') or (ColumnComments <> '') then
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + CHR_ENTER;
if CommentEdit.Text <> '' then
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + Format('COMMENT ON VIEW %s.%s IS %s;', [
FSchemaParam, ViewNameEdit.Text, QuotedStr(CommentEdit.Text)]) + CHR_ENTER;
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + ColumnComments + CHR_ENTER;
Application.ProcessMessages;
SourceSynEdit.Lines.Text := Trim(SourceSynEdit.Lines.Text);
SourceSynEdit.Lines.EndUpdate;
end;
end.
|
unit ImageManager;
interface
uses
System.Generics.Collections, System.Types,
FMX.ImgList, FMX.Types,
ResourcesManager;
type
TImageManager = class
private
loaded: TList<eResource>;
public
procedure add(r: eResource);
procedure remove(r: eResource);
procedure clear;
procedure setSize(img:TGlyph; s:TControlSize); overload;
procedure setSize(img:TGlyph; s:TSizeF); overload;
destructor Destroy; override;
constructor Create;
end;
var
IM: TImageManager;
implementation
uses
System.Math, System.Classes, System.SysUtils,
FMX.Graphics, FMX.MultiResBitmap, FMX.Controls, FMX.Dialogs,
DataUnit;
{TImageManager}
procedure TImageManager.add(r: eResource);
var
res: TStyleBook;
list:TImageList;
Sor: TCustomSourceItem;
i:byte;
procedure LoadPicture(const Source: TCustomSourceItem; const Scale: Single; const pBitmap: TBitmap);
var
BitmapItem: TCustomBitmapItem;
begin
BitmapItem := Source.MultiResBitmap.ItemByScale(Scale, True, True);
if BitmapItem = nil then
begin
BitmapItem := Source.MultiResBitmap.Add;
BitmapItem.Scale := Scale;
end;
BitmapItem.Bitmap.Assign(pBitmap);
end;
begin
res:=nil;
list:=getImgList(r);
if not loaded.Contains(r) then
try
try
Res:=TStyleBook.Create(nil);
Res.LoadFromFile(pathResource(r));
for i:=0 to Res.Style.ChildrenCount-1 do
begin
Sor:=List.Source.AddOrSet(Res.Style.Children.Items[i].StyleName, [],[]);
Sor.MultiResBitmap.SizeKind:=TSizeKind.Source;
LoadPicture(Sor, 1, (Res.Style.Children.Items[i] as TBitmapObject).Bitmap);
end;
except
on E: exception do
showMessage(E.Message);
end;
finally
loaded.Add(r);
Res.Free;
end;
end;
procedure TImageManager.remove(r: eResource);
begin
if loaded.Contains(r) then
begin
getImgList(r).Source.Clear;
loaded.Remove(r);
end;
end;
procedure TImageManager.setSize(img: TGlyph; s:TControlSize);
begin
setSize(img, s.Size);
end;
procedure TImageManager.setSize(img: TGlyph; s:TSizeF);
var
i:byte;
w,h,k:single;
b:TBounds;
begin
w:=0;
h:=0;
with (img.Images.Destination.FindItemID(img.ImageIndex) as TCustomDestinationItem).Layers do
for i:=0 to Count-1 do
begin
b:=items[i].SourceRect;
w:=max(w,b.Width-b.Left);
h:=max(h,b.Height-b.Top);
end;
k:=max(s.Width/w, s.Height/h);
img.Width:=w*k;
img.Height:=h*k;
end;
procedure TImageManager.clear;
var
i:byte;
begin
if loaded.Count>0 then
for i:=0 to loaded.Count-1 do
remove(loaded[i]);
end;
destructor TImageManager.Destroy;
begin
loaded.Free;
inherited;
end;
//Конструктор (загрузка изображений из .style в TImageList)
constructor TImageManager.Create();
begin
loaded:=TList<eResource>.create;
end;
end.
|
(******************************************************************************
* *
* Project: Usermanager, Benutzerverwaltung für Windows NT, 2000, XP, Vista *
* File : Consts, Konstanten *
* *
* Copyright (c) Michael Puff http://www.michael-puff.de *
* *
******************************************************************************)
{$I CompilerSwitches.inc}
unit Consts;
interface
uses
CommCtrl,
Messages;
type
TWaitInfo = record
hParent: THandle;
InfoText: WideString;
Caption: WideString;
end;
PWaitInfo = ^TWaitInfo;
const
APPNAME = 'XP Usermanager';
DESCRIPTION = 'Benutzerverwaltung für Windows XP / Vista / Windows 7';
COPYRIGHT = 'Copyright © Michael Puff';
HOMEPAGE = 'http://www.michael-puff.de';
FONTNAME = 'Tahoma';
FONTSIZE = -20;
HELPFILE = 'hilfe.chm';
LOGFILE = 'import.log';
XPM_REFRESH = WM_USER + 1; // Refresh Message
XPUM_REG_KEY = 'Software\MichaelPuff\XPUsermanager';
// HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\DontShowMeThisDialogAgain
REG_SAVENETUSERNAME = 'SaveNetUserName';
REG_NETUSERNAME = 'NetUserName';
REG_REMOTECOMPUTER = 'RemoteComputer';
REG_HINT_NO_ADMIN = 'XPUsermanager_Hint_No_Adim';
// MainDlg
ID_TV = 10901;
ID_LV = 10903;
ID_STATBAR = 10904;
ID_TAB = 10905;
ID_TOOLBAR = 10906;
ID_MNU_CHOOSE_COMP = 40130;
ID_MNU_LOKAL_COMP = 40160;
ID_MNU_NEW = 40020;
ID_MNU_SAVE = 40030;
ID_MNU_DEL = 40040;
ID_MNU_CLOSE = 40006;
ID_MNU_USER = 40007;
ID_MNU_GROUP = 40008;
ID_MNU_EXPAND = 40009;
ID_MNU_REFRESH = 40140;
ID_MNU_HELP = 40010;
ID_MNU_ABOUT = 40011;
ID_MNU_GRPMNG = 40200;
ID_MNU_EXPORT_CSV = 40201;
ID_MNU_EXPORT_XML = 40202;
ID_MNU_IMPORT_XML = 40203;
ID_ACCEL_NEW = 4002;
ID_ACCEL_SAVE = 4003;
ID_ACCEL_DEL = 4004;
ID_ACCEL_HELP = 4010;
ID_ACCEL_CHOOSE_COMP = 4013;
ID_ACCEL_REFRESH = 4014;
ID_ACCEL_LOCAL_COMP = 4016;
ID_ACCEL_GRPMGN = 4020;
// first tab - Konto
ID_EDT_USER = 10202;
ID_EDT_FULLNAME = 10203;
ID_EDT_DESCRIPTION = 10204;
ID_EDT_PW = 113;
ID_EDT_PW2 = 112;
ID_CHK_RESET_PW = 111;
// second tab - Eigenschaften
ID_CHK_MUST_CHANGE_PW = 221;
ID_CHK_CANT_CHANGE_PW = 222;
ID_CHK_PW_DONT_EXPIRE = 223;
ID_CHK_ACCOUNT_DISABLED = 226;
ID_EDT_HOMEDIR = 125;
ID_BTN_HOMEDIR = 124;
ID_EDT_SCRIPT_PATH = 122;
ID_BTN_SCRIPT_PATH = 123;
// third tab - Login
ID_CHK_AUTO_LOGIN = 231;
ID_EDT_AUTO_LOGIN = 10216;
ID_CHK_HIDE_ACCOUNT = 233;
// fourth tab - Gruppen
ID_LV_USERGROUPS = 141;
// Choose Computer Dlg
ID_BTN_OK_X = 201;
ID_BTN_CLOSE_X = 202;
ID_EDT_ACCOUNT_X = 203;
ID_EDT_PW_X = 204;
ID_CHK_SAVEUSERNAME = 205;
ID_EDT_COMP_X = 206;
ID_BTN_SEARCH_X = 207;
ID_BTN_HELP = 211;
// About Dlg
ID_STC_APPNAME = 301;
ID_STC_DESCRIPTION = 305;
ID_CUSTOM_SCROLL = 302;
ID_STC_COPYRIGHT = 303;
ID_BTN_CLOSE = 304;
ID_STC_DATE = 306;
// Groupmanager
ID_LV_GROUPS = 401;
ID_LV_PRIVILEGES = 402;
ID_BTN_APPLYPRV = 403;
ID_BTN_UNDO = 404;
ID_EDT_GROUP = 405;
ID_EDT_COMMENT = 406;
ID_BTN_SAVE_GRP = 407;
ID_BTN_DEL_GRP = 408;
ID_BTN_GMCLOSE = 409;
ID_BTN_HELP_GM = 410;
SB_SIMPLEID = $00FF;
MODE_NEUTRAL = 0;
MODE_NEWUSER = 1;
MODE_EDIT = 2;
const
CSVFilter = 'CSV-Dateien (*.csv)'#0'*.csv';
XMLFilter = 'XML-Dateien (*.xml)'#0'*.xml';
const
ContextInfo: array[1..22] of string =
('Name des Benutzers, entspricht dem Kontonamen. Wird kein vollständiger Name angegeben, erscheint dieser Name im' +
' Login-Bildschirm von Windows XP.',
'Vollständiger Name des Benutzers. Wird ein vollständiger Name angegeben, erscheint dieser Name im Login-Bildschirm' +
' von Windows XP anstatt des Kontonamens.',
'Nähere Beschreibung des Kontos oder ein frei wählbarer Kommentar.',
'Kennwort für das Benutzerkonto, welches beim Einloggen eingegeben werden muss.' +
' Setzen Sie den Haken bei "zurücksetzen", wenn Sie das Kennwort zurücksetzen wollen.',
'Typ des Kontos.' + #13#10 +
'INTERDOMAIN_TRUST_ACCOUNT: This is a permit to trust account for a domain that trusts other domains.' + #13#10 +
'NORMAL_ACCOUNT: Standard Benutzerkonto' + #13#10 +
'TEMP_DUPLICATE_ACCOUNT: This is an account for users whose primary account is in another domain.' + #13#10 +
' This account provides user access to this domain, but not to any domain that trusts this domain.' + #13#10 +
' The User Manager refers to this account type as a local user account.' + #13#10 +
'WORKSTATION_TRUST_ACCOUNT: Computer Konto für einen Computer, der ein Mitglieder dieser Domain ist.' + #13#10 +
'SERVER_TRUST_ACCOUNT: Computer Konto für einen Backup Domain Controller, der ein Mitglied dieser Domain ist.',
'Bei der nächsten Anmeldung muss der Benutzer das Kennwort bei der Anmeldung ändern.',
'Der Benutzer kann das Kennwort nicht selbst ändern.',
'Das Kennwort läuft nicht ab.',
'Das Konto wurde vom Administrator gesperrt.',
'Stammverzeichnis des Benutzerkontos.',
'Anmeldeskript für das Benutzerkonto, welches bei der Anmeldung ausgeführt wird.',
'Aktivieren Sie diese Checkbox, wenn der ausgewählte Benutzer automatisch beim Start von Windows angemeldet' +
' werden soll. Ist das Konto mit einem Kennwort versehen, geben Sie es in das Eingabefeld "Kennwort" ein.',
'Aktivieren Sie diese Checkbox, wenn das ausgewählte Konto nicht im Anmeldebildschirm von Windows ercheinen soll.' +
' Dies gilt nur für den Anmeldebildschirm von Windows XP.',
'Liste der verfügbaren Benutzergruppen. Ist ein Haken vor einer Benutzergruppe gesetzt, so ist der ausgewählte' +
' Benutzer Mitglied dieser Gruppe. Setzen oder entfernen Sie entsprechend die Häkchen, um einen Benutzer einer' +
' Benutzergruppe hinzuzufügen oder ihn aus einer zu entfernen.',
'Liste der Benutzer und Gruppen. Wählen Sie einen Benutzer aus, um die Kontoeinstellungen zu bearbeiten oder den' +
' Benutzer zu löschen.' + #13#10 +
'Sie können im Menü "Ansicht" diese Ansicht umschalten.',
'Liste der auf dem aktuellen Rechner verfügbaren Benutzergruppen.',
'Liste der verfügbaren Privilegien. Ist ein Haken vor einem Privileg gesetzt, so besitzt diese Benutzergruppe' +
' dieses Privileg.',
'Geben Sie hier den Name der neu zu erstellenden Gruppe ein.',
'Geben Sie hier eine Beschreibung für die neue Gruppe ein. Diese Angabe ist optional.',
'Diese Schaltfläche legt die neue Gruppe an.',
'Diese Schaltfläche löscht die ausgewählte Gruppe.',
'Pay me my money down' + #13#10 + 'Pay me, pay me my money down'#13#10 + 'Pay me or go to jail' + #13#10 +
'Pay me my money down'
);
var
hTabDlgs: array[0..3] of THandle;
EditMode: Integer = 0;
bSetDetails: Boolean;
tbButtons: array[0..6] of TTBButton = (
(iBitmap: 0;
idCommand: ID_MNU_CHOOSE_COMP;
fsState: TBSTATE_ENABLED;
fsStyle: TBSTYLE_BUTTON;
dwData: 0;
iString: 2;
),
(iBitmap: 0;
idCommand: - 1;
fsState: TBSTATE_ENABLED;
fsStyle: TBSTYLE_SEP;
dwData: 0;
iString: - 1;
),
(iBitmap: 1;
idCommand: ID_MNU_NEW;
fsState: TBSTATE_ENABLED;
fsStyle: TBSTYLE_BUTTON;
dwData: 0;
iString: 0;
),
(iBitmap: 2;
idCommand: ID_MNU_SAVE;
fsState: TBSTATE_ENABLED;
fsStyle: TBSTYLE_BUTTON;
dwData: 0;
iString: 0;
),
(iBitmap: 3;
idCommand: ID_MNU_DEL;
fsState: TBSTATE_ENABLED;
fsStyle: TBSTYLE_BUTTON;
dwData: 0;
iString: 2;
),
(iBitmap: 0;
idCommand: - 1;
fsState: TBSTATE_ENABLED;
fsStyle: TBSTYLE_SEP;
dwData: 0;
iString: - 1;
),
(iBitmap: 4;
idCommand: ID_MNU_GRPMNG;
fsState: TBSTATE_ENABLED;
fsStyle: TBSTYLE_BUTTON;
dwData: 0;
iString: - 1;
)
);
implementation
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Profiler;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses {$ifdef windows}Windows,{$else}{$ifdef unix}BaseUnix,Unix,UnixType,{$endif}{$endif}SysUtils,Classes,SyncObjs,PasVulkan.Types;
type TpvProfiler=class
public
class procedure SectionBegin(const Name:ansistring); static; {$ifdef cpu386}register;{$endif}
class procedure SectionEnd; static; {$ifdef cpu386}register;{$endif}
end;
implementation
{$ifdef PasVulkanProfiler}
const HashBits=16;
HashSize=1 shl HashBits;
HashMask=HashSize-1;
type PSectionAddressHashItem=^TSectionAddressHashItem;
TSectionAddressHashItem=record
GarbageCollectorNext:pointer;
Next:PSectionAddressHashItem;
ReturnAddress:pointer;
Name:ansistring;
Count:TpvInt64;
TotalTime:TpvInt64;
MinTime:TpvInt64;
MaxTime:TpvInt64;
end;
PSectionAddressHashTable=^TSectionAddressHashTable;
TSectionAddressHashTable=array[0..HashSize-1] of PSectionAddressHashItem;
PPThreadStackItem=^PThreadStackItem;
PThreadStackItem=^TThreadStackItem;
TThreadStackItem=record
GarbageCollectorNext:pointer;
Next:PThreadStackItem;
SectionAddress:PSectionAddressHashItem;
StartTime:TpvInt64;
end;
PThreadStackHashItem=^TThreadStackHashItem;
TThreadStackHashItem=record
GarbageCollectorNext:pointer;
Next:PThreadStackHashItem;
ID:TpvPtrUInt;
Stack:PThreadStackItem;
end;
PThreadStackHashTable=^TThreadStackHashTable;
TThreadStackHashTable=array[0..HashSize-1] of PThreadStackHashItem;
var CriticalSection:TCriticalSection;
GarbageCollectorRoot:pointer;
SectionAddressHashTable:TSectionAddressHashTable;
ThreadStackHashTable:TThreadStackHashTable;
FreeThreadStackItems:PThreadStackItem;
FrequencyShift,Frequency:TpvInt64;
procedure InitTimer;
begin
FrequencyShift:=0;
{$ifdef windows}
if QueryPerformanceFrequency(Frequency) then begin
while (Frequency and $ffffffffe0000000)<>0 do begin
Frequency:=Frequency shr 1;
inc(FrequencyShift);
end;
end else begin
Frequency:=1000;
end;
{$else}
{$ifdef linux}
Frequency:=1000000000;
{$else}
{$ifdef unix}
Frequency:=1000000;
{$else}
Frequency:=1000;
{$endif}
{$endif}
{$endif}
end;
function GetTime:TpvInt64;
{$ifdef linux}
var NowTimeSpec:TimeSpec;
ia,ib:TpvInt64;
{$else}
{$ifdef unix}
var tv:timeval;
tz:timezone;
ia,ib:TpvInt64;
{$endif}
{$endif}
begin
{$ifdef windows}
if not QueryPerformanceCounter(result) then begin
result:=GetTickCount;
end;
{$else}
{$ifdef linux}
clock_gettime(CLOCK_MONOTONIC,@NowTimeSpec);
ia:=TpvInt64(NowTimeSpec.tv_sec)*TpvInt64(1000000000);
ib:=NowTimeSpec.tv_nsec;
result:=ia+ib;
{$else}
{$ifdef unix}
tz.tz_minuteswest:=0;
tz.tz_dsttime:=0;
fpgettimeofday(@tv,@tz);
ia:=TpvInt64(tv.tv_sec)*TpvInt64(1000000);
ib:=tv.tv_usec;
result:=ia+ib;
{$else}
result:=0;
{$endif}
{$endif}
{$endif}
result:=result shr FrequencyShift;
end;
function GetStackForThread:PPThreadStackItem;
var ID,Hash,Index:TpvPtrUInt;
Item:PThreadStackHashItem;
begin
{$ifdef windows}
ID:=GetCurrentThread;
{$else}
{$ifdef fpc}
ID:=GetThreadID;
{$else}
ID:=0;
{$endif}
{$endif}
Hash:=ID*TpvPtrUInt($9e3779b1);
Index:=Hash and HashMask;
Item:=ThreadStackHashTable[Index];
while assigned(Item) do begin
if Item^.ID=ID then begin
result:=@Item^.Stack;
exit;
end;
Item:=Item^.Next;
end;
GetMem(Item,SizeOf(TThreadStackItem));
FillChar(Item^,SizeOf(TThreadStackItem),AnsiChar(#0));
Item^.GarbageCollectorNext:=GarbageCollectorRoot;
GarbageCollectorRoot:=Item;
Item^.ID:=ID;
Item^.Stack:=nil;
Item^.Next:=ThreadStackHashTable[Index];
ThreadStackHashTable[Index]:=Item;
result:=@Item^.Stack;
end;
function GetSectionAddressHashItem(const Address:pointer):PSectionAddressHashItem;
var Hash,ID,Index:TpvPtrUInt;
begin
ID:=TpvPtrUInt(Address);
Hash:=ID*TpvPtrUInt($9e3779b1);
Index:=Hash and HashMask;
result:=SectionAddressHashTable[Index];
while assigned(result) do begin
if result^.ReturnAddress=Address then begin
exit;
end else begin
result:=result^.Next;
end;
end;
GetMem(result,SizeOf(TSectionAddressHashItem));
FillChar(result^,SizeOf(TSectionAddressHashItem),AnsiChar(#0));
result^.GarbageCollectorNext:=GarbageCollectorRoot;
GarbageCollectorRoot:=result;
result^.ReturnAddress:=Address;
result^.Count:=0;
result^.Next:=SectionAddressHashTable[Index];
SectionAddressHashTable[Index]:=result;
end;
{$endif}
class procedure TpvProfiler.SectionBegin(const Name:ansistring); {$ifdef cpu386}register;{$endif}
{$ifdef PasVulkanProfiler}
var CurrentReturnAddress:pointer;
ThreadStackItem:PThreadStackItem;
SectionAddressHashItem:PSectionAddressHashItem;
SectionBeginStack:PPThreadStackItem;
begin
{$if defined(fpc)}
CurrentReturnAddress:=Get_Caller_Addr(Get_Frame);
{$elseif declared(ReturnAddress)}
CurrentReturnAddress:=System.ReturnAddress;
{$elseif defined(cpu386)}
asm
mov ecx,dword ptr [ebp+4]
mov dword ptr CurrentReturnAddress,ecx
end;
{$else}
// WARNING: Not a clean solution! :-)
CurrentReturnAddress:=pointer(pointer(TpvPtrUInt(TpvPtrUInt(pointer(@Name))+(sizeof(pointer)*2)))^);
{$ifend}
CriticalSection.Enter;
try
SectionAddressHashItem:=GetSectionAddressHashItem(CurrentReturnAddress);
SectionAddressHashItem^.Name:=Name;
inc(SectionAddressHashItem^.Count);
if assigned(FreeThreadStackItems) then begin
ThreadStackItem:=FreeThreadStackItems;
FreeThreadStackItems:=ThreadStackItem^.Next;
end else begin
GetMem(ThreadStackItem,SizeOf(TThreadStackItem));
FillChar(ThreadStackItem^,SizeOf(TThreadStackItem),AnsiChar(#0));
ThreadStackItem^.GarbageCollectorNext:=GarbageCollectorRoot;
GarbageCollectorRoot:=ThreadStackItem;
end;
SectionBeginStack:=GetStackForThread;
ThreadStackItem^.SectionAddress:=SectionAddressHashItem;
ThreadStackItem^.Next:=SectionBeginStack^;
SectionBeginStack^:=ThreadStackItem;
ThreadStackItem^.StartTime:=GetTime;
finally
CriticalSection.Leave;
end;
end;
{$else}
begin
end;
{$endif}
class procedure TpvProfiler.SectionEnd; {$ifdef cpu386}register;{$endif}
{$ifdef PasVulkanProfiler}
var EndTime,TimeDifference:TpvInt64;
SectionBeginStack:PPThreadStackItem;
SectionAddressHashItem:PSectionAddressHashItem;
ThreadStackItem:PThreadStackItem;
begin
EndTime:=GetTime;
CriticalSection.Enter;
try
SectionBeginStack:=GetStackForThread;
if assigned(SectionBeginStack) then begin
SectionAddressHashItem:=SectionBeginStack^^.SectionAddress;
TimeDifference:=EndTime-SectionBeginStack^^.StartTime;
inc(SectionAddressHashItem^.TotalTime,TimeDifference);
if SectionAddressHashItem^.Count<=1 then begin
SectionAddressHashItem^.MinTime:=TimeDifference;
SectionAddressHashItem^.MaxTime:=TimeDifference;
end else begin
if SectionAddressHashItem^.MinTime>TimeDifference then begin
SectionAddressHashItem^.MinTime:=TimeDifference;
end;
if SectionAddressHashItem^.MaxTime<TimeDifference then begin
SectionAddressHashItem^.MaxTime:=TimeDifference;
end;
end;
ThreadStackItem:=SectionBeginStack^^.Next;
SectionBeginStack^^.Next:=FreeThreadStackItems;
FreeThreadStackItems:=SectionBeginStack^;
SectionBeginStack^:=ThreadStackItem;
end;
finally
CriticalSection.Leave;
end;
end;
{$else}
begin
end;
{$endif}
{$ifdef PasVulkanProfiler}
{$ifdef PasVulkanProfilerPopStackAtEnd}
procedure PopStack;
var Index:TpvSizeInt;
EndTime,TimeDifference:TpvInt64;
ThreadStackHashItem:PThreadStackHashItem;
ThreadStackItem:PThreadStackItem;
SectionAddressHashItem:PSectionAddressHashItem;
begin
EndTime:=GetTime;
CriticalSection.Enter;
try
for Index:=low(TThreadStackHashTable) to high(TThreadStackHashTable) do begin
ThreadStackHashItem:=ThreadStackHashTable[Index];
while assigned(ThreadStackHashItem) do begin
ThreadStackItem:=ThreadStackHashItem^.Stack;
while assigned(ThreadStackItem) do begin
if assigned(ThreadStackItem^.SectionAddress) then begin
SectionAddressHashItem:=ThreadStackItem^.SectionAddress;
TimeDifference:=EndTime-ThreadStackItem^.StartTime;
inc(SectionAddressHashItem^.TotalTime,TimeDifference);
if SectionAddressHashItem^.Count<=1 then begin
SectionAddressHashItem^.MinTime:=TimeDifference;
SectionAddressHashItem^.MaxTime:=TimeDifference;
end else begin
if SectionAddressHashItem^.MinTime>TimeDifference then begin
SectionAddressHashItem^.MinTime:=TimeDifference;
end;
if SectionAddressHashItem^.MaxTime<TimeDifference then begin
SectionAddressHashItem^.MaxTime:=TimeDifference;
end;
end;
end;
ThreadStackItem:=ThreadStackItem^.Next;
end;
ThreadStackHashItem:=ThreadStackHashItem^.Next;
end;
end;
finally
CriticalSection.Leave;
end;
end;
{$endif}
procedure OutputResults;
type TItem=record
Name:ansistring;
Count:TpvInt64;
TotalTime:double;
MinTime:double;
MaxTime:double;
AverageTime:double;
end;
PItem=^TItem;
TItems=array of TItem;
var Index,Count:TpvSizeInt;
Items:TItems;
Item:PItem;
TempItem:TItem;
tf:TextFile;
SectionAddressHashItem:PSectionAddressHashItem;
begin
Items:=nil;
try
Count:=0;
for Index:=low(TSectionAddressHashTable) to high(TSectionAddressHashTable) do begin
SectionAddressHashItem:=SectionAddressHashTable[Index];
while assigned(SectionAddressHashItem) do begin
inc(Count);
SectionAddressHashItem:=SectionAddressHashItem^.Next;
end;
end;
SetLength(Items,Count);
Count:=0;
for Index:=low(TSectionAddressHashTable) to high(TSectionAddressHashTable) do begin
SectionAddressHashItem:=SectionAddressHashTable[Index];
while assigned(SectionAddressHashItem) do begin
Item:=@Items[Count];
Item^.Name:=SectionAddressHashItem^.Name;
Item^.Count:=SectionAddressHashItem^.Count;
Item^.TotalTime:=SectionAddressHashItem^.TotalTime/Frequency;
Item^.MinTime:=SectionAddressHashItem^.MinTime/Frequency;
Item^.MaxTime:=SectionAddressHashItem^.MaxTime/Frequency;
Item^.AverageTime:=Item^.TotalTime/Item^.Count;
inc(Count);
SectionAddressHashItem:=SectionAddressHashItem^.Next;
end;
end;
Index:=0;
while (Index+1)<Count do begin
if Items[Index].MaxTime<Items[Index+1].MaxTime then begin
TempItem:=Items[Index];
Items[Index]:=Items[Index+1];
Items[Index+1]:=TempItem;
if Index>0 then begin
dec(Index);
end else begin
inc(Index);
end;
end else begin
inc(Index);
end;
end;
AssignFile(tf,'profiling_results.csv');
try
{$i-}Rewrite(tf);{$i+}
if IOResult=0 then begin
writeln(tf,'Name;Count;Total time (s);Min. time (s);Max. time (s);Average time(s)');
for Index:=0 to Count-1 do begin
Item:=@Items[Index];
writeln(tf,Item^.Name,';',
Item^.Count,';',
Item^.TotalTime:1:16,';',
Item^.MinTime:1:16,';',
Item^.MaxTime:1:16,';',
Item^.AverageTime:1:16);
end;
Flush(tf);
end;
finally
CloseFile(tf);
end;
AssignFile(tf,'profiling_results.txt');
try
{$i-}Rewrite(tf);{$i+}
if IOResult=0 then begin
writeln(tf,'Name':64,' ',
'Count':24,' ',
'Total time (s)':24,' ',
'Min. time (s)':24,' ',
'Max. time (s)':24,' ',
'Average time (s)':24);
for Index:=0 to Count-1 do begin
Item:=@Items[Index];
writeln(tf,Item^.Name:64,' ',
Item^.Count:24,' ',
Item^.TotalTime:24:16,' ',
Item^.MinTime:24:16,' ',
Item^.MaxTime:24:16,' ',
Item^.AverageTime:24:16);
end;
Flush(tf);
end;
finally
CloseFile(tf);
end;
finally
SetLength(Items,0);
end;
end;
procedure CleanUp;
var Current,Next:pointer;
begin
CriticalSection.Enter;
try
Current:=GarbageCollectorRoot;
GarbageCollectorRoot:=nil;
while assigned(Current) do begin
Next:=pointer(Current^);
FreeMem(Current);
Current:=Next;
end;
finally
CriticalSection.Leave;
end;
end;
{$endif}
initialization
{$ifdef PasVulkanProfiler}
InitTimer;
CriticalSection:=TCriticalSection.Create;
GarbageCollectorRoot:=nil;
FillChar(SectionAddressHashTable,SizeOf(TSectionAddressHashTable),AnsiChar(#0));
FillChar(ThreadStackHashTable,SizeOf(ThreadStackHashTable),AnsiChar(#0));
FreeThreadStackItems:=nil;
{$endif}
finalization
{$ifdef PasVulkanProfiler}
{$ifdef PasVulkanProfilerPopStackAtEnd}
PopStack;
{$endif}
OutputResults;
CleanUp;
CriticalSection.Free;
{$endif}
end.
|
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved.
//
// 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 Casbin;
interface
uses
Casbin.Core.Base.Types, Casbin.Types, Casbin.Model.Types,
Casbin.Adapter.Types, Casbin.Core.Logger.Types, Casbin.Functions.Types,
Casbin.Policy.Types, System.TypInfo;
type
TCasbin = class (TBaseInterfacedObject, ICasbin)
private
fModel: IModel;
fPolicy: IPolicyManager;
fLoggerPool: ILoggerPool;
fEnabled: boolean;
fFunctions: IFunctions;
function rolesGsInternal(const Args: array of string): Boolean;
function rolesG(const Args: array of string): Boolean;
function rolesG2(const Args: array of string): Boolean;
private
{$REGION 'Interface'}
function getModel: IModel;
function getPolicy: IPolicyManager;
procedure setModel(const aValue: IModel);
procedure setPolicy(const aValue: IPolicyManager);
function getLoggerPool: ILoggerPool;
procedure setLoggerPool(const aValue: ILoggerPool);
function getEnabled: Boolean;
procedure setEnabled(const aValue: Boolean);
function enforce (const aParams: TEnforceParameters): boolean; overload;
function enforce(const aParams: TEnforceParameters; const aPointer: PTypeInfo;
const aRec): boolean; overload;
{$ENDREGION}
public
constructor Create; overload;
constructor Create(const aModelFile, aPolicyFile: string); overload; //PALOFF
constructor Create(const aModel: IModel; const aPolicyAdapter: IPolicyManager);
overload;
constructor Create(const aModelFile: string; const aPolicyAdapter: IPolicyManager);
overload;
constructor Create(const aModel: IModel; const aPolicyFile: string);
overload;
end;
implementation
uses
Casbin.Exception.Types, Casbin.Model, Casbin.Policy,
Casbin.Core.Logger.Default, System.Generics.Collections, System.SysUtils,
Casbin.Resolve, Casbin.Resolve.Types, Casbin.Model.Sections.Types,
Casbin.Core.Utilities, System.Rtti, Casbin.Effect.Types, Casbin.Effect,
Casbin.Functions, Casbin.Adapter.Memory, Casbin.Adapter.Memory.Policy,
System.SyncObjs, System.Types, System.StrUtils, Casbin.Core.Defaults,
ArrayHelper, Quick.Chrono;
var
criticalSection: TCriticalSection;
constructor TCasbin.Create(const aModelFile, aPolicyFile: string);
var
model: IModel;
policy: IPolicyManager;
begin
if trim(aModelFile)='' then
model:=TModel.Create(TMemoryAdapter.Create)
else
model:=TModel.Create(aModelFile);
if Trim(aPolicyFile)='' then
policy:=TPolicyManager.Create(TPolicyMemoryAdapter.Create)
else
policy:=TPolicyManager.Create(aPolicyFile);
Create(model, policy);
end;
constructor TCasbin.Create(const aModel: IModel; const aPolicyAdapter:
IPolicyManager);
begin
if not Assigned(aModel) then
raise ECasbinException.Create('Model Adapter is nil');
if not Assigned(aPolicyAdapter) then
raise ECasbinException.Create('Policy Manager is nil');
inherited Create;
fModel:=aModel;
fPolicy:=aPolicyAdapter;
fLoggerPool:=TDefaultLoggerPool.Create(TDefaultLogger.Create);
fEnabled:=True;
fFunctions:=TFunctions.Create;
fFunctions.registerFunction('g', rolesG);
fFunctions.registerFunction('g2', rolesG2);
end;
function TCasbin.enforce(const aParams: TEnforceParameters): boolean;
var
rec: string; //PALOFF
begin
Result:=enforce(aParams, nil, rec);
end;
constructor TCasbin.Create;
begin
Create(TModel.Create(TMemoryAdapter.Create), TPolicyManager.Create(
TPolicyMemoryAdapter.Create));
end;
constructor TCasbin.Create(const aModelFile: string;
const aPolicyAdapter: IPolicyManager);
var
model: IModel;
begin
if trim(aModelFile)='' then
model:=TModel.Create(TMemoryAdapter.Create)
else
model:=TModel.Create(aModelFile);
Create(model, aPolicyAdapter);
end;
function TCasbin.enforce(const aParams: TEnforceParameters; const aPointer:
PTypeInfo; const aRec): boolean;
var
item: string;
request: TList<string>;
requestDict: TDictionary<string, string>;
policyDict: TDictionary<string, string>;
requestStr: string;
matcherResult: TEffectResult;
policyList: TList<string>;
effectArray: TEffectArray;
matchString: string;
reqDomain: string;
domainsArrayRec: TArrayRecord<string>;
requestArrayRec: TArrayRecord<string>;
ctx: TRttiContext;
cType: TRttiType;
cField: TRttiField;
abacList: TList<string>;
chrono: TChronometer;
begin
result:=true;
if Length(aParams) = 0 then
Exit;
if not fEnabled then
Exit;
chrono:=TChronometer.Create(true);
chrono.ReportFormatPrecission:=TPrecissionFormat.pfFloat;
requestArrayRec:=TArrayRecord<string>.Create(aParams);
request:=TList<string>.Create;
requestDict:=nil;
abacList:=TList<string>.Create;
criticalSection.Acquire;
try
requestArrayRec.List(request);
requestStr:=string.Join(',', aParams);
fLoggerPool.log('Enforcing request '''+requestStr+'''');
fLoggerPool.log(' Resolving Request...');
// Resolve Request
{$IFDEF DEBUG}
fLoggerPool.log(' Request: '+requestStr);
fLoggerPool.log(' Assertions: ');
if fModel.assertions(stRequestDefinition).Count=0 then
fLoggerPool.log(' No Request Assertions found')
else
for item in fModel.assertions(stRequestDefinition) do
fLoggerPool.log(' '+item);
{$ENDIF}
requestDict:=resolve(request, rtRequest,
fModel.assertions(stRequestDefinition));
// Resolve ABAC record
if Assigned(aPointer) and Assigned(@aRec) then
begin
fLoggerPool.log('Record Identified');
ctx:=TRttiContext.Create;
cType:=ctx.GetType(aPointer);
if fModel.assertions(stRequestDefinition).Count>0 then
begin
abacList.AddRange(fModel.assertions(stRequestDefinition));
fLoggerPool.log('Request identifiers retrieved ('+string.Join(',', abacList.ToArray)+')');
end
else
begin
// This assumes the request uses the letter 'r' and typical 'sub,obj,act'
abacList.Add('r.sub');
abacList.Add('r.obj');
abacList.Add('r.act');
fLoggerPool.log('Default identifiers used (r)');
end;
fLoggerPool.log('Retrieving content of '+cType.Name+' record');
for cField in cType.GetFields do
begin
for item in abacList do
begin
requestDict.Add(UpperCase(item)+'.'+UpperCase(cField.Name),
UpperCase(cField.GetValue(@aRec).AsString));
end;
end;
end;
fLoggerPool.log(' Resolving Policies...');
{$IFDEF DEBUG}
fLoggerPool.log(' Policies: ');
fLoggerPool.log(' Assertions: ');
if fPolicy.policies.Count=0 then
fLoggerPool.log(' No Policy Assertions found')
else
for item in fPolicy.policies do
fLoggerPool.log(' '+item);
fLoggerPool.log(' Assertions: '+requestStr);
for item in fModel.assertions(stPolicyDefinition) do
fLoggerPool.log(' '+item);
{$ENDIF}
{$IFDEF DEBUG}
fLoggerPool.log(' Matchers: '+requestStr);
fLoggerPool.log(' Assertions: ');
if fModel.assertions(stMatchers).Count=0 then
fLoggerPool.log(' No Matcher Assertions found')
else
for item in fModel.assertions(stMatchers) do
fLoggerPool.log(' '+item);
{$ENDIF}
if fModel.assertions(stMatchers).Count>0 then
begin
matchString:=fModel.assertions(stMatchers).Items[0];
// Check for builtin accounts
for item in builtinAccounts do
if matchString.Contains(item) and requestStr.Contains(item) then
Exit;
end
else
matchString:='';
domainsArrayRec:=TArrayRecord<string>.Create(fPolicy.domains.ToArray);
for item in fPolicy.policies do
begin
fLoggerPool.log(' Processing policy: '+item);
// Resolve Policy
policyList:=TList<string>.Create; //PALOFF
policyList.AddRange(item.Split([','])); //PALOFF
// Item 0 has p,g, etc
policyList.Delete(0);
// We look at the relevant policies only
// by working out the domains
reqDomain:=DefaultDomain;
domainsArrayRec.ForEach(procedure(var Value: string; Index: integer)
var
item: string;
begin
for item in policyList do
if Trim(Value) = Trim(item) then
begin
reqDomain:=Trim(Value);
Break;
end;
end);
if fPolicy.linkExists(request[0], reqDomain, policyList[0])
// or
// soundexSimilar(Trim(request[0]), Trim(policyList[0]),
// Trunc(0.50 * Length(request[0]))))
then
begin
policyDict:=resolve(policyList, rtPolicy,
fModel.assertions(stPolicyDefinition));
fLoggerPool.log(' Resolving Functions and Matcher...');
// Resolve Matcher
if string.Compare('indeterminate', Trim(policyList[policyList.Count-1]),
[coIgnoreCase])=0 then
begin
SetLength(effectArray, Length(effectArray)+1);
effectArray[Length(effectArray)-1]:=erIndeterminate; //PALOFF
end
else
begin
/// resolve returns one of the two options erAllow (means the policy is
/// relevant) or erDeny (the policy is not relevant)
matcherResult:=resolve(requestDict, policyDict, fFunctions, matchString);
if matcherResult = erAllow then
begin
if policyList.count = request.Count then
begin
matcherResult:=erAllow;
end
else
begin
if policyList.Count > request.Count then
if policyList[request.Count].Trim.ToUpper.Equals('ALLOW') then
matcherResult:=erAllow
else
matcherResult:=erDeny;
end;
SetLength(effectArray, Length(effectArray)+1);
effectArray[Length(effectArray)-1]:=matcherResult; //PALOFF
end;
end;
policyDict.Free;
end;
policyList.Free;
end;
//Resolve Effector
fLoggerPool.log(' Merging effects...');
Result:=mergeEffects(fModel.effectCondition, effectArray);
chrono.Stop;
fLoggerPool.log('Enforcement completed (Result: '+BoolToStr(Result, true)+') - ' +
chrono.ElapsedTime);
finally
criticalSection.Release;
request.Free;
requestDict.Free;
abacList.Free;
chrono.Free;
end;
end;
{ TCasbin }
function TCasbin.getEnabled: Boolean;
begin
Result:=fEnabled;
end;
function TCasbin.getLoggerPool: ILoggerPool;
begin
Result:=fLoggerPool;
end;
function TCasbin.getModel: IModel;
begin
Result:=fModel;
end;
function TCasbin.getPolicy: IPolicyManager;
begin
Result:=fPolicy;
end;
function TCasbin.rolesG(const Args: array of string): Boolean;
begin
Result:=rolesGsInternal(Args);
end;
function TCasbin.rolesG2(const Args: array of string): Boolean;
begin
Result:=rolesGsInternal(Args);
end;
function TCasbin.rolesGsInternal(const Args: array of string): Boolean;
begin
result:=False;
if (Length(Args)<2) or (Length(Args)>3) then
raise ECasbinException.Create('The arguments are different than expected in '+
'g''s functions');
if Length(Args)=3 then
Result:=fPolicy.linkExists(Args[0], Args[2], Args[1]);
if Length(Args)=2 then
Result:=fPolicy.linkExists(Args[0], Args[1]);
end;
procedure TCasbin.setEnabled(const aValue: Boolean);
begin
fEnabled:=aValue;
end;
procedure TCasbin.setLoggerPool(const aValue: ILoggerPool);
begin
if assigned(aValue) then
begin
fLoggerPool:=nil;
fLoggerPool:=aValue;
end;
end;
procedure TCasbin.setModel(const aValue: IModel);
begin
if not Assigned(aValue) then
raise ECasbinException.Create('Model in nil');
fModel:=aValue;
end;
procedure TCasbin.setPolicy(const aValue: IPolicyManager);
begin
if not Assigned(aValue) then
raise ECasbinException.Create('Policy Manager in nil');
fPolicy:=aValue;
end;
constructor TCasbin.Create(const aModel: IModel; const aPolicyFile: string);
var
policy: IPolicyManager;
begin
if Trim(aPolicyFile)='' then
policy:=TPolicyManager.Create(TPolicyMemoryAdapter.Create)
else
policy:=TPolicyManager.Create(aPolicyFile);
Create(aModel, policy);
end;
initialization
criticalSection:=TCriticalSection.Create;
finalization
criticalSection.Free;
end.
|
library BritishEnglishWords;
{$mode objfpc}{$H+}
uses
Classes;
type
T_tens_words = array[0..9] of string;
T_units_words = array[0..19] of string;
var
is_inited: Boolean;
tens_words: T_tens_words;
units_words: T_units_words;
procedure initLibrary();
begin
tens_words[0] := '';
tens_words[1] := '';
tens_words[2] := 'twenty';
tens_words[3] := 'thirty';
tens_words[4] := 'forty';
tens_words[5] := 'fifty';
tens_words[6] := 'sixty';
tens_words[7] := 'seventy';
tens_words[8] := 'eighty';
tens_words[9] := 'ninety';
units_words[0] := 'zero';
units_words[1] := 'one';
units_words[2] := 'two';
units_words[3] := 'three';
units_words[4] := 'four';
units_words[5] := 'five';
units_words[6] := 'six';
units_words[7] := 'seven';
units_words[8] := 'eight';
units_words[9] := 'nine';
units_words[10] := 'ten';
units_words[11] := 'eleven';
units_words[12] := 'twelve';
units_words[13] := 'thirteen';
units_words[14] := 'fourteen';
units_words[15] := 'fifteen';
units_words[16] := 'sixteen';
units_words[17] := 'seventeen';
units_words[18] := 'eighteen ';
units_words[19] := 'nineteen';
is_inited := True;
end;
function convert(Number: LongInt) : string;
var
Aux: string;
begin
if (is_inited = False) then begin
initLibrary();
end;
if (Number > 999999999) then begin
Result := 'Not able to convert number upper than 999.999.999!'
end
else begin
if (Number < 0) then begin
Result := 'Not able to convert negative numbers!'
end
else begin
if (Number < 20) then begin
Result := units_words[Number]
end
else begin
if (Number < 100) then begin
Aux := tens_words[(Number)DIV(10)];
if ((Number)MOD(10) > 0) then begin
Result := Aux + ' ' + convert((Number)MOD(10))
end
else begin
Result := Aux;
end
end
else begin
if (Number < 1000) then begin
Aux := units_words[(Number)DIV(100)] + ' hundred';
if ((Number)MOD(100) > 0) then begin
Result := Aux + ' and ' + convert((Number)MOD(100))
end
else begin
Result := Aux;
end
end
else begin
if (Number < 1000000) then begin
Aux := convert((Number)DIV(1000)) + ' thousand';
if ((Number)MOD(1000) > 0) then begin
Result := Aux + ' ' + convert((Number)MOD(1000))
end
else begin
Result := Aux;
end
end
else begin
Aux := convert((Number)DIV(1000000)) + ' million';
if ((Number)MOD(1000000) > 0) then begin
Result := Aux + ' ' + convert((Number)MOD(1000000))
end
else begin
Result := Aux;
end
end
end
end
end
end
end
end;
exports
convert;
end.
|
unit PasGlobalConfiguration;
interface
uses
System.SysUtils, System.Classes, System.Rtti, System.IniFiles;
type
TGlobalConfiguration = class
private
FBaseUrl: string;
FWebRoot: string;
FVlcRoot: string;
FYoutubedlRoot: string;
FIniRoot: string;
FPythonRoot: string;
FIni: TIniFile;
constructor realConstructor;
const
iniSelection = 'GlobalConfiguration';
class var instance: TGlobalConfiguration;
protected
public
// 获得相对于程序路径的url
function relativePath(path: string): string;
// 保存配置到硬盘
procedure save;
class function getInstance: TGlobalConfiguration; static;
constructor Create(NoUse: Byte);
// procedure DoNothing; virtual; abstract;
property baseUrl: string read FBaseUrl;
property webRoot: string read FWebRoot;
property vlcRoot: string read FVlcRoot;
property youtubedlRoot: string read FYoutubedlRoot;
property pythonRoot: string read FPythonRoot;
procedure Free;
end;
implementation
{$M+}
uses
Vcl.Forms, CnDebug;
class function TGlobalConfiguration.getInstance: TGlobalConfiguration;
begin
if TGlobalConfiguration.instance = nil then
begin
TGlobalConfiguration.instance := TGlobalConfiguration.realConstructor;
end;
Result := TGlobalConfiguration.instance;
end;
constructor TGlobalConfiguration.Create(NoUse: Byte);
begin
// 公共构造方法抛异常,防止调用Tobject.create
raise Exception.Create('Can not support this operation!');
end;
constructor TGlobalConfiguration.realConstructor;
begin
// set default values
Self.FBaseUrl := ExtractFilePath(Application.ExeName);
Self.FWebRoot := Self.relativePath('dependce/web');
Self.FVlcRoot := Self.relativePath('dependce/vlc');
Self.FYoutubedlRoot := Self.relativePath('dependce/youtube-dl.exe');
Self.FPythonRoot := Self.relativePath('dependce/python/python.exe');
// read ini file
Self.FIniRoot := Self.relativePath('dependce/configuration.bmp');
FIni := TIniFile.Create(Self.FIniRoot);
Self.FWebRoot := FIni.ReadString(Self.iniSelection, 'webRoot', Self.FWebRoot);
Self.FVlcRoot := FIni.ReadString(Self.iniSelection, 'vlcRoot', Self.FVlcRoot);
Self.FYoutubedlRoot := FIni.ReadString(Self.iniSelection, 'youtubedlRoot',
Self.youtubedlRoot);
end;
procedure TGlobalConfiguration.save;
begin
try
FIni.WriteString(Self.iniSelection, 'webRoot', Self.FWebRoot);
FIni.WriteString(Self.iniSelection, 'vlcRoot', Self.FVlcRoot);
FIni.WriteString(Self.iniSelection, 'youtubedlRoot', Self.youtubedlRoot);
except
on E: Exception do
begin
CnDebugger.TraceMsg('Save Err:' + E.ClassName);
CnDebugger.TraceMsg('Message:' + E.Message);
CnDebugger.TraceMsg(E.StackTrace);
end;
end;
end;
{ *------------------------------------------------------------------------------
.
@param path 相对路径
@return 相对于程序目录的绝对路径
------------------------------------------------------------------------------- }
function TGlobalConfiguration.relativePath(path: string): string;
begin
Result := Self.baseUrl + path;
end;
procedure TGlobalConfiguration.Free;
begin
if TGlobalConfiguration.instance <> nil then
begin
TGlobalConfiguration.instance.save;
TGlobalConfiguration.instance.FIni.Free;
FreeAndNil(TGlobalConfiguration.instance);
end;
end;
end.
|
unit qplugins_menusvc;
interface
uses classes, sysutils, qplugins_base;
const
MC_CAPTION = $01;
MC_ICON = $02;
MC_VISIBLE = $04;
MC_ENABLED = $08;
MC_EXTS = $10;
MC_ALIGN = $20;
MC_CHILDREN = $40;
type
IQMenuCategory = interface;
// 图片支持
/// <summary>
/// 图片支持接口,用于跨语言支持图片显示
/// </summary>
/// <remarks>
/// IQImage 支持的常见的位图文件格式,如PNG/JPG,但并不支持编辑,不管原数据格式是啥格式,保存时都会按PNG格式保存。 要创建一个
/// IQImage 接口的实例,使用路径 /Services/Images 下的服务,调用 NewImage 接口创建新的对象。
/// 注意:本单元只包含接口声明,不包含实际实现
/// </remarks>
IQImage = interface
['{013129AD-B177-4D9F-818A-45E09ADDC2ED}']
/// <summary>
/// 从流中加载图片
/// </summary>
/// <param name="AStream">
/// 保存图片的数据流对象
/// </param>
procedure LoadFromStream(AStream: IQStream); stdcall;
/// <summary>
/// 以 PNG 格式保存图片到流中
/// </summary>
/// <param name="AStream">
/// 目标数据流
/// </param>
procedure SaveToStream(AStream: IQStream); stdcall;
/// <summary>
/// 从文件中加载图片
/// </summary>
/// <param name="AFileName">
/// 图片文件名
/// </param>
/// <remarks>
/// 从文件中加载图片时,是通过扩展名来确定文件格式的,所以请保证扩展名与实际格式一致。
/// </remarks>
procedure LoadFromFile(const AFileName: PWideChar); stdcall;
/// <summary>
/// 保存图片数据到PNG文件中
/// </summary>
/// <param name="AFileName">
/// 目标文件名
/// </param>
/// <remarks>
/// 请确认目标目录有写入权限,否则会无法保存
/// </remarks>
procedure SaveToFile(const AFileName: PWideChar); stdcall;
/// <summary>
/// 从 Base64 编码字符串
/// </summary>
/// <param name="ABase64Data">
/// 以 Base 64 编码的图片数据
/// </param>
procedure LoadFromBase64(const ABase64Data: IQString); stdcall;
/// <summary>
/// 保存为 PNG 格式的 Base64 字符串
/// </summary>
/// <returns>
/// 返回值实际类型为IQString,为兼容非 Delphi 语言,改为返回 Pointer,用户需要自行减小引用计数
/// </returns>
function SaveToBase64: Pointer; stdcall;
/// <summary>
/// 获取内部图像的实际宽度
/// </summary>
function GetWidth: Integer; stdcall;
/// <summary>
/// 获取内部图像的实际高度
/// </summary>
function GetHeight: Integer; stdcall;
/// <summary>
/// 以 IQBytes 接口获取PNG格式的数据
/// </summary>
/// <param name="AData">
/// 用于存贮结果数据的缓冲区对象
/// </param>
function GetData(AData: IQBytes): Integer; stdcall;
/// <summary>
/// 获取图像对象末次变更的Id,每加载一次图片,该ID变更一次,以便上层检查图片内容是否发生变动
/// </summary>
function GetLastChangeId: Integer; stdcall;
/// <summary>
/// 从另一个图片中复制一份拷贝
/// </summary>
procedure Assign(ASource: IQImage); stdcall;
/// <summary>
/// 图片末次变更ID
/// </summary>
property LastChangeId: Integer read GetLastChangeId;
end;
/// <summary>
/// 菜单(IQMenuItem) 和分类 (IQMenuCategory )的基类,用于管理菜单类型项目的公有成员
/// </summary>
IQMenuBase = interface
/// <summary>
/// 菜单内部Id,每个菜单项目拥有唯一的编码
/// </summary>
function GetId: Integer; stdcall;
/// <summary>
/// 获取菜单的内部名称,
/// </summary>
function GetName: PWideChar; stdcall;
/// <summary>
/// 设置菜单名称
/// </summary>
/// <param name="AName">
/// 菜单的名称
/// </param>
/// <remarks>
/// 该名称实际上是一个内部标志,调用者应避免重复
/// </remarks>
procedure SetName(AName: PWideChar); stdcall;
/// <summary>
/// 获取菜单显示标题
/// </summary>
/// <remarks>
/// 如果要支持多语言,则需要响应 Language.Changed 通知调用 SetCaption 重新设置标题
/// </remarks>
function GetCaption: PWideChar; stdcall;
/// <summary>
/// 设置菜单标题
/// </summary>
/// <param name="S">
/// 标题内容
/// </param>
procedure SetCaption(const S: PWideChar); stdcall;
/// <summary>
/// 获取菜单的启用状态
/// </summary>
function GetEnabled: Boolean; stdcall;
/// <summary>
/// 设置菜单项目的启用状态
/// </summary>
/// <param name="val">
/// true -> 启用 false->禁用
/// </param>
procedure SetEnabled(const val: Boolean); stdcall;
/// <summary>
/// 获取菜单项目是否可见
/// </summary>
function GetVisible: Boolean; stdcall;
/// <summary>
/// 设置菜单项目是否可见
/// </summary>
/// <param name="val">
/// true->可见,false->不可见
/// </param>
procedure SetVisible(const val: Boolean); stdcall;
/// <summary>
/// 判断是否包含扩展参数列表
/// </summary>
function HasExtParams: Boolean; stdcall;
/// <summary>
/// 获取扩展参数列表
/// </summary>
/// <remarks>
/// 扩展参数列表提供了不修改系统服务的情况下,添加额外数据成员的办法,其它模块可以往内部添加自己的参数标志,以建立关联。
/// </remarks>
function GetExtParams: Pointer; stdcall;
/// <summary>
/// 菜单当前状态发生变更时,会触发该接口。
/// </summary>
/// <remarks>
/// Invalidate 函数触发 MenuService.Validate 通知,程序可以订阅该通知以便进行处理。该通知的 @Sender
/// 参数为菜单实例的 IQMenuBase 接口地址(类型为 64 位整数)
/// </remarks>
procedure Invalidate; stdcall;
/// <summary>
/// 获取菜单末次内容的ID,以便快速判断菜单内容是否发生了变动
/// </summary>
function GetLastChangeId: Integer; stdcall;
/// <summary>
/// 获取自己在父中的索引
/// </summary>
/// <remarks>
/// 父对象为IQMenuCategory类型
/// </remarks>
function GetItemIndex: Integer; stdcall;
/// <summary>
/// 获取父分类对象接口实例,如果是根分类,则为空
/// </summary>
/// <returns>
/// 实际类型为IQMenuCategory,注意使用完成要减小接口的引用计数
/// </returns>
/// <seealso cref="IQMenuCategory">
/// 父接口类型
/// </seealso>
function GetParent: Pointer; stdcall; // IQMenuCategory
/// <summary>
/// 获取项目关联的图片接口实例
/// </summary>
/// <returns>
/// 返回 IQImage 接口实例,注意使用完成接口要减少引用计数
/// </returns>
/// <seealso cref="IQImage">
/// 图像接口
/// </seealso>
function GetImage: Pointer; stdcall; // IQImage
/// <summary>
/// 设置关联图片实例
/// </summary>
/// <param name="AImage">
/// 新的图片实例
/// </param>
/// <remarks>
/// 如果在关联后,直接修改实例的图片内容,并不会触发刷新,需要手动调用菜单项的Invalidate来通知菜单服务更新相应的图标。否则可能会使用旧图标显示。
/// </remarks>
/// <seealso cref="IQImage">
/// 图像接口
/// </seealso>
procedure SetImage(AImage: IQImage); stdcall;
function GetTag: Pointer; stdcall;
procedure SetTag(const V: Pointer); stdcall;
function GetChanges: Integer; stdcall;
procedure BeginUpdate; stdcall;
procedure EndUpdate; stdcall;
/// <summary>
/// 项目标题
/// </summary>
property Caption: PWideChar read GetCaption write SetCaption;
/// <summary>
/// 是否启用
/// </summary>
property Enabled: Boolean read GetEnabled write SetEnabled;
/// <summary>
/// 是否显示
/// </summary>
property Visible: Boolean read GetVisible write SetVisible;
/// <summary>
/// 父分类接口
/// </summary>
property Parent: Pointer read GetParent;
/// <summary>
/// 项目名称
/// </summary>
property Name: PWideChar read GetName write SetName;
/// <summary>
/// 扩展参数
/// </summary>
property ExtParams: Pointer read GetExtParams;
/// <summary>
/// 项目索引
/// </summary>
property ItemIndex: Integer read GetItemIndex;
/// <summary>
/// 末次变更ID
/// </summary>
property LastChangeId: Integer read GetLastChangeId;
property Tag: Pointer read GetTag write SetTag;
property Changes: Integer read GetChanges;
end;
/// <summary>
/// 菜单类型
/// </summary>
TQMenuCheckType = (
/// <summary>
/// 普通菜单
/// </summary>
None,
/// <summary>
/// 单选菜单,同一分类下的单选菜单中,只能有一个被选中
/// </summary>
Radio,
/// <summary>
/// 复选菜单
/// </summary>
CheckBox);
TImageAlignLayout = (alNone, alTop, alLeft, alRight, alBottom, alMostTop,
alMostBottom, alMostLeft, alMostRight, alClient, alContents, alCenter,
alVertCenter, alHorzCenter, alHorizontal, alVertical, alScale, alFit,
alFitLeft, alFitRight);
/// <summary>
/// 菜单项目接口
/// </summary>
IQMenuItem = interface(IQMenuBase)
['{6C53B06C-EA0E-4020-A303-1DBE74755E42}']
/// <summary>
/// 图片对齐方式 ,默认左对齐
/// </summary>
/// <returns>
/// TAlignLayout 的值序列为{None=0, Top, Left, Right, Bottom, MostTop,
/// MostBottom, MostLeft, MostRight, Client, Contents, Center,
/// VertCenter, HorzCenter, Horizontal, Vertical, Scale, Fit, FitLeft,
/// FitRight},默认为Left
/// </returns>
function GetImageAlign: TImageAlignLayout; stdcall;
/// <summary>
/// 设置图片的对齐方式
/// </summary>
/// <param name="Align">
/// 新的对齐方式
/// </param>
/// <remarks>
/// 如果是单选或复选菜单,默认布局则单选或复选框在最左侧,然后是图片,最后是文字。可以通过设置它,来调整图片的位置。
/// </remarks>
procedure SetImageAlign(const Align: TImageAlignLayout); stdcall;
/// <summary>
/// 获取菜单项目单击的响应广播 IQNotifyBroadcast 接口实例
/// </summary>
/// <returns>
/// 实际为 IQNotifyBroadcast 类型的接口地址,用户可以调用其 Add 方法添加响应,用 Remove 移除响应
/// </returns>
/// <remarks>
/// Click 函数会调用此接口,通过 Send 来发送通知给所有的响应者
/// </remarks>
/// <seealso cref="IQNotifyBroadcast">
/// QPlugins 的通知广播接口
/// </seealso>
function GetOnClick: Pointer; stdcall; // IQNotifyBroadcastor
/// <summary>
/// 模拟点击指定的菜单项目
/// </summary>
/// <param name="AParams">
/// 传递给响应接口的参数
/// </param>
procedure Click(AParams: IQParams); stdcall;
/// <summary>
/// 获取当前菜单项目是否已经选中
/// </summary>
function GetIsChecked: Boolean; stdcall;
/// <summary>
/// 设置当前菜单项目是否选中
/// </summary>
procedure SetIsChecked(const Value: Boolean); stdcall;
/// <summary>
/// 获取菜单项目类型
/// </summary>
/// <seealso cref="TQMenuCheckType">
/// 菜单项目类型
/// </seealso>
function GetCheckType: TQMenuCheckType; stdcall;
/// <summary>
/// 设置菜单项目类型
/// </summary>
/// <param name="AType">
/// 新的类型
/// </param>
procedure SetCheckType(const AType: TQMenuCheckType); stdcall;
/// <summary>
/// 菜单图标对齐方式
/// </summary>
property ImageAlign: TImageAlignLayout read GetImageAlign
write SetImageAlign;
/// <summary>
/// 当前 菜单项目类型
/// </summary>
/// <exception cref="TQMenuCheckType">
/// 菜单项目类型
/// </exception>
property CheckType: TQMenuCheckType read GetCheckType write SetCheckType;
/// <summary>
/// 是否选中
/// </summary>
property IsChecked: Boolean read GetIsChecked write SetIsChecked;
end;
/// <summary>
/// 菜单项目分类,用于管理多个菜单及子分类
/// </summary>
/// <remarks>
/// 菜单分类一般不推荐太多级数,一般菜单项目显示区域有限,每一级分类都需要缩进一定的距离,以保证视觉效果。
/// </remarks>
IQMenuCategory = interface(IQMenuBase)
['{FC2909CF-7AD2-450F-B02A-7372886BA43E}']
/// <summary>
/// 获取分类是否处于展开的状态
/// </summary>
function GetIsExpanded: Boolean; stdcall;
/// <summary>
/// 设置分类是否展开
/// </summary>
procedure SetIsExpanded(const val: Boolean); stdcall;
/// <summary>
/// 为分类添加子菜单项目
/// </summary>
/// <returns>
/// 返回的实际接口类型是IQMenuItem,注意用完要减少引用计数
/// </returns>
function AddMenu(const AName, ACaption: PWidechar): Pointer; stdcall;
/// <summary>
/// 添加一个子分类
/// </summary>
/// <returns>
/// 返回的实际接口类型是 IQMenuCategory,注意用完要减少引用计数
/// </returns>
function AddCategory(const AName, ACaption: PWidechar): Pointer; stdcall;
/// <summary>
/// 删除指定索引的子项
/// </summary>
/// <param name="AIndex">
/// 要删除的子项索引
/// </param>
procedure Delete(AIndex: Integer); stdcall;
/// <summary>
/// 清除所有的子项
/// </summary>
procedure Clear; stdcall;
/// <summary>
/// 查找指定的子项的索引序号
/// </summary>
/// <returns>
/// 成功返回 >=0 的索引序号,失败,返回-1
/// </returns>
function IndexOf(AItem: IQMenuBase): Integer; overload; stdcall;
/// <summary>
/// 查找指定名称的子项目索引序号
/// </summary>
/// <param name="AName">
/// 要查找的项目的名称,注意区分大小写
/// </param>
/// <returns>
/// 成功返回 &gt;=0 的索引序号,失败,返回-1
/// </returns>
function IndexOf(AName: PWideChar): Integer; overload; stdcall;
/// <summary>
/// 获取总的子项数量
/// </summary>
function GetCount: Integer; stdcall;
/// <summary>
/// 获取指定索引的子项接口实例地址
/// </summary>
/// <param name="AIndex">
/// 要获取的子项接口索引
/// </param>
/// <returns>
/// 返回的接口实例为 IQMenuBase 接口,注意不要直接转换为 IQMenuItem 或
/// IQMenuCategory,应按相应的规范调用。
/// </returns>
function GetItems(const AIndex: Integer): Pointer; stdcall;
/// <summary>
/// 子项数量,只读
/// </summary>
property Count: Integer read GetCount;
/// <summary>
/// 是否处于展开状态
/// </summary>
property IsExpanded: Boolean read GetIsExpanded write SetIsExpanded;
/// <summary>
/// 子项列表
/// </summary>
/// <param name="AIndex">
/// 子项索引
/// </param>
/// <value>
/// 返回的接口实例为 IQMenuBase 接口,注意不要直接转换为 IQMenuItem 或
/// IQMenuCategory,应按相应的规范调用。
/// </value>
property Items[const AIndex: Integer]: Pointer read GetItems; default;
end;
/// <summary>
/// 菜单服务提供者接口
/// </summary>
/// <remarks>
/// <para>
/// 在菜单项目发生变动或被点击触发时,会生成一系列通知,包括:
/// </para>
/// <list type="bullet">
/// <item>
/// MenuService.ItemClicked : 菜单项目被点击,@Sender 参数为被点击的菜单项目
/// </item>
/// <item>
/// MenuService.ItemAdded : 有项目加入,@Sender 参数为新加的菜单项目
/// </item>
/// <item>
/// MenuService.ItemDeleted :有项目被删除,@Sender 是已被删除的项目
/// </item>
/// <item>
/// MenuService.ItemCleared : 所有的子项都被清理掉了,@sender 参数是被清理的分类对象
/// </item>
/// <item>
/// MenuService.ItemExpand :当一个分类被展开时触发,@Sender 参数为分类对象
/// </item>
/// <item>
/// MenuService.Validate:当一个菜单项目无效时被触发,@Sender 参数为失效的菜单类实像例
/// </item>
/// <item>
/// MenuService.Iconic:当整个菜单在图标和正常状态切换时触发,IsIconic 参数指定了新的状态
/// </item>
/// </list>
/// <para>
/// 上述通知中,@Sender 的类型为64位整数,指向的是 IQMenuBase 类型的接口的地址。
/// </para>
/// </remarks>
IQMenuService = interface
['{EDAE42E6-C53E-4407-862C-AFB4AA910336}']
/// <summary>
/// 添加一个分类
/// </summary>
/// <returns>
/// 实际返回的接口类型为 IQMenuCategory,注意使用完成需要减小引用计数
/// </returns>
function AddCategory(const AName, ACaption: PWidechar): Pointer; stdcall;
/// <summary>
/// 删除指定索引的项目
/// </summary>
/// <param name="AIndex">
/// 要删除的接口索引
/// </param>
procedure Delete(AIndex: Integer); stdcall;
/// <summary>
/// 清除所有的项目
/// </summary>
procedure Clear; stdcall;
/// <summary>获取指定路径的项目地址,路径分隔符以/分隔</summary>
/// <returns>返回对应的路径的IQMenuBase实例地址</returns>
function ItemByPath(APath: PWideChar): Pointer; stdcall; // IQMenuBase
/// <summary>强制创建指定分类路径,路径分隔符以/分隔</summary>
/// <returns>返回对应的路径的IQMenuBase实例地址</returns>
function ForceCategories(APath: PWideChar): Pointer; stdcall;
// IQMenuCategory
/// <summary>
/// 获取指定分类的索引
/// </summary>
/// <param name="ACategory">
/// 要获取的子分类接口
/// </param>
function IndexOf(ACategory: IQMenuCategory): Integer; stdcall;
/// <summary>
/// 获取子分类数量
/// </summary>
function GetCount: Integer; stdcall;
/// <summary>
/// 获取指定索引的子分类接口实例地址
/// </summary>
/// <param name="AIndex">
/// 子分类索引
/// </param>
/// <returns>
/// 实际返回的接口类型为IQMenuCategory,注意使用完成后释放接口引用计数
/// </returns>
function GetItems(const AIndex: Integer): Pointer; stdcall;
/// <summary>
/// 获取当前是否处于图标状态
/// </summary>
/// <remarks>
/// 图标状态下,所有的子项会被收起,只显示根分类的图标列表
/// </remarks>
function GetIsIconic: Boolean; stdcall;
/// <summary>
/// 设置当前是否处于图标状态
/// </summary>
procedure SetIsIconic(const value: Boolean); stdcall;
/// <summary>
/// 子分类数量
/// </summary>
property Count: Integer read GetCount;
/// <summary>
/// 子分类项目
/// </summary>
/// <param name="AIndex">
/// 子分类项目索引
/// </param>
property Items[const AIndex: Integer]: Pointer read GetItems; default;
/// <summary>
/// 是否处于图标状态
/// </summary>
property IsIconic: Boolean read GetIsIconic write SetIsIconic;
end;
/// <summary>
/// 图片服务,注册路径为 /Services/Images
/// </summary>
IQImageService = interface(IQService)
['{4C44E9DD-14A2-4FFF-9003-FC88F4EBA291}']
/// <summary>
/// 获取一个新的IQImage实例
/// </summary>
/// <returns>
/// 返回的是 IQImage 类型的接口地址,注意使用完成减少引用计数
/// </returns>
function NewImage: Pointer; stdcall;
end;
const
MenuServiceRoot: PWideChar = '\Services\Menus';
ImageServiceRoot: PWideChar = '\Services\Images';
implementation
end.
|
unit uProdutoController;
interface
uses
uProdutoModel, uProdutoDao, System.SysUtils;
type
TProdutoController = class
private
FProduto: TProduto;
FProdutoDAO: TProdutoDao;
FProdutoList: TProdutoList;
procedure SetProduto(const Value: TProduto);
procedure SetProdutoDAO(const Value: TProdutoDao);
procedure SetProdutoList(const Value: TProdutoList);
public
constructor Create;
destructor Destroy; override;
function Inserir(var sErro: string): Boolean;
function Alterar(var sErro: string): Boolean;
function Excluir(var sErro: string): Boolean;
function GerarId: Integer;
procedure CarregarProduto(Pesquisa: String);
property Produto : TProduto read FProduto write SetProduto;
property ProdutoDAO : TProdutoDao read FProdutoDAO write SetProdutoDAO;
property ProdutoList: TProdutoList read FProdutoList write SetProdutoList;
end;
implementation
{ TProdutoController }
function TProdutoController.Alterar(var sErro: string): Boolean;
begin
Result:= FProdutoDAO.Alterar(FProduto, sErro);
end;
function TProdutoController.GerarId: Integer;
begin
Result:= FProdutoDAO.GerarId;
end;
procedure TProdutoController.CarregarProduto(Pesquisa: String);
begin
FProdutoDAO.CarregarProduto(FProdutoList, Pesquisa);
end;
constructor TProdutoController.Create;
begin
FProdutoDAO := TProdutoDao.Create;
FProduto := TProduto.Create;
FProdutoList:= TProdutoList.Create;
end;
destructor TProdutoController.Destroy;
begin
FreeAndNil(FProdutoDAO);
FreeAndNil(FProduto);
FreeAndNil(FProdutoList);
inherited;
end;
function TProdutoController.Excluir(var sErro: string): Boolean;
begin
Result:= FProdutoDAO.Excluir(FProduto, sErro);
end;
function TProdutoController.Inserir(var sErro: string): Boolean;
begin
if FProduto.Descricao = EmptyStr then
begin
raise EArgumentException.Create('Nome precisa ser preenchido.');
Result := False
end
else
Result:= FProdutoDAO.Inserir(FProduto, sErro);
end;
procedure TProdutoController.SetProduto(const Value: TProduto);
begin
FProduto := Value;
end;
procedure TProdutoController.SetProdutoDAO(const Value: TProdutoDao);
begin
FProdutoDAO := Value;
end;
procedure TProdutoController.SetProdutoList(const Value: TProdutoList);
begin
FProdutoList := Value;
end;
end.
|
unit DummyCollection;
interface
uses
Classes, Types, Generics.Collections, Operation, CodeELement, DataType, VarDeclaration, ProcDeclaration;
type
TDummyCollection = class(TObject)
private
FVariable: TVarDeclaration;
FOperation: TOperation;
FDataType: TDataType;
FElements: TObjectList<TCodeElement>;
public
constructor Create();
destructor Destroy(); override;
function GetDummyElement(AType: TCodeElementClass): TCodeElement;
property Operation: TOperation read FOperation;
property Variable: TVarDeclaration read FVariable;
property DataType: TDataType read FDataType;
end;
implementation
{ TDummyCollection }
constructor TDummyCollection.Create;
begin
FElements := TObjectList<TCodeElement>.Create(False);
FDataType := TDataType.Create('?', 2, rtNilType);
FOperation := TOperation.Create('?', rtNilType, rtNilType, 2, 2, FDataType, '');
FVariable := TVarDeclaration.Create('?', FDataType);
FElements.Add(FDataType);
FElements.Add(FVariable);
end;
destructor TDummyCollection.Destroy;
begin
FVariable.Free;
FOperation.Free;
FDataType.Free;
FElements.Free;
inherited;
end;
function TDummyCollection.GetDummyElement(
AType: TCodeElementClass): TCodeElement;
var
LElement: TCodeElement;
begin
Result := nil;
for LElement in FElements do
begin
if LElement.InheritsFrom(AType) then
begin
Result := LElement;
Break;
end;
end;
end;
end.
|
{ ------------------------------------
功能说明:Fash窗体接口
创建日期:2008/11/29
作者:wzw
版权:wzw
------------------------------------- }
unit SplashFormIntf;
{$WEAKPACKAGEUNIT on}
interface
type
ISplashForm = interface
['{AE9B77A3-1D67-400B-A03B-428F3A79444D}']
procedure Show;
procedure loading(const msg: String);
function GetWaitTime: Cardinal;
procedure Hide;
end;
implementation
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.StdCtrls, Vcl.ImgList,
Vcl.ComCtrls, Vcl.ToolWin, Vcl.Styles.NC;
type
TFrmMain = class(TForm)
MainMenu1: TMainMenu;
Edit1: TMenuItem;
Undo1: TMenuItem;
Repeat1: TMenuItem;
Cut1: TMenuItem;
Copy1: TMenuItem;
Paste1: TMenuItem;
PasteSpecial1: TMenuItem;
Find1: TMenuItem;
Replace1: TMenuItem;
GoTo1: TMenuItem;
Links1: TMenuItem;
Object1: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
File1: TMenuItem;
New1: TMenuItem;
Open1: TMenuItem;
Save1: TMenuItem;
SaveAs1: TMenuItem;
Print1: TMenuItem;
PrintSetup1: TMenuItem;
Exit1: TMenuItem;
N4: TMenuItem;
N5: TMenuItem;
Help2: TMenuItem;
Contents2: TMenuItem;
Index1: TMenuItem;
Commands1: TMenuItem;
Procedures1: TMenuItem;
Keyboard1: TMenuItem;
SearchforHelpOn2: TMenuItem;
Tutorial1: TMenuItem;
HowtoUseHelp2: TMenuItem;
About2: TMenuItem;
BtnDropDownMenu: TButton;
ImageList1: TImageList;
BtnStyles: TButton;
BtnCustomStyle: TButton;
CheckBoxNCVisible: TCheckBox;
BtnAlpha: TButton;
Label1: TLabel;
BtnStyleTabs: TButton;
procedure FormCreate(Sender: TObject);
procedure BtnDropDownMenuClick(Sender: TObject);
procedure CheckBoxNCVisibleClick(Sender: TObject);
procedure BtnStylesClick(Sender: TObject);
procedure BtnCustomStyleClick(Sender: TObject);
procedure BtnAlphaClick(Sender: TObject);
procedure BtnStyleTabsClick(Sender: TObject);
private
{ Private declarations }
NCControls : TNCControls;
public
{ Public declarations }
procedure ButtonNCClick(Sender: TObject);
end;
var
FrmMain: TFrmMain;
implementation
uses
Vcl.Styles.Utils.SystemMenu,
uButtonsStyles, uCustomStyles, uDropdown, uAlphaGradient, uButtonsTabsStyles;
{$R *.dfm}
procedure TFrmMain.BtnDropDownMenuClick(Sender: TObject);
var
LForm : TFrmDropDown;
begin
LForm:= TFrmDropDown.Create(Self);
LForm.Show();
end;
procedure TFrmMain.BtnStylesClick(Sender: TObject);
var
LForm : TFrmButtonsStyles;
begin
LForm:= TFrmButtonsStyles.Create(Self);
LForm.Show();
end;
procedure TFrmMain.BtnStyleTabsClick(Sender: TObject);
var
LForm : TFrmButtonsTabsStyle;
begin
LForm:= TFrmButtonsTabsStyle.Create(Self);
LForm.Show();
end;
procedure TFrmMain.BtnAlphaClick(Sender: TObject);
var
LForm : TFrmAlphaGradient;
begin
LForm:= TFrmAlphaGradient.Create(Self);
LForm.Show();
end;
procedure TFrmMain.BtnCustomStyleClick(Sender: TObject);
var
LForm : TFrmCustomStyles;
begin
LForm:= TFrmCustomStyles.Create(Self);
LForm.Show();
end;
procedure TFrmMain.ButtonNCClick(Sender: TObject);
begin
if Sender is TNCButton then
ShowMessage(Format('You clicked the button %s', [TNCButton(Sender).Name]));
end;
procedure TFrmMain.CheckBoxNCVisibleClick(Sender: TObject);
begin
NCControls.Visible:=CheckBoxNCVisible.Checked;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
var
i : integer;
begin
ReportMemoryLeaksOnShutdown:=True;
TVclStylesSystemMenu.Create(Self);
NCControls:=TNCControls.Create(Self);
for i:=0 to 10 do
begin
NCControls.Add(TNCButton.Create(NCControls));
NCControls[i].Name := Format('NCButton%d',[i+1]);
NCControls[i].Hint := Format('Hint for NCButton%d',[i+1]);
NCControls[i].ShowHint := True;
NCControls[i].Caption :='';
NCControls[i].Style :=nsTranparent;
NCControls[i].ImageStyle:=isGrayHot;
NCControls[i].Images :=ImageList1;
NCControls[i].ImageIndex:=i;
NCControls[i].ImageAlignment := TImageAlignment.iaCenter;
NCControls[i].BoundsRect:=Rect(30+(i*20),5,50+(i*20),25);
NCControls[i].OnClick := ButtonNCClick;
end;
end;
end.
|
unit hcDeploymentRegion;
interface
uses
hcObject
,hcObjectList
,hcAttribute
;
type
ThcDeploymentRegion = class(ThcObject)
public
class procedure Register; override;
property RegionGUID :ThcAttribute Index 0 read GetAttribute;
property Number :ThcAttribute Index 1 read GetAttribute;
property IsLocalAreaSubFranchised :ThcAttribute Index 2 read GetAttribute;
property Description :ThcAttribute Index 3 read GetAttribute;
property Details :ThcAttribute Index 4 read GetAttribute;
end;
ThcDeploymentRegionList = class(ThcObjectList)
public
procedure AfterConstruction; override;
function Current :ThcDeploymentRegion; reintroduce;
procedure Load; override;
end;
implementation
uses
hcTableDef
,hcCore
,hcMetaData
,hcAttributeDef
,hcPrimaryKeyConstraint
,DB
,hcStdValidators
,SysUtils
,hcQueryIntf
,hcCodeSiteHelper
,hcFactoryPool
,hcTypes
,hcFunctions
,Controls
,Forms
;
class procedure ThcDeploymentRegion.Register;
var
MetaData: ThcMetaData;
PrimaryTableDef :ThcTableDef;
begin
MetaData := ThcMetaData.Create;
with MetaData do
begin
TableDefs.Clear;
PrimaryTableDef := TableDefs.AddTableDef('Region','R',[tpReadOnly]);
with PrimaryTableDef do
begin
with AttributeDefs do
begin
PrimaryKey := ThcPrimaryKeyConstraint.Create(kgtServerGeneratedBeforeInsert,[{ 0} AddDef('RegionGUID',ftGuid,'RegionGUID',ftGuid,[])]);
OID := PrimaryKey;
{ 1} AddDef('Number',ftSmallint,'Number',ftSmallint,[]);
{ 2} AddDef('IsLocalAreaSubFranchised',ftBoolean,'IsLocalAreaSubFranchised',ftBoolean,[]);
{ 3} AddDef('Description',ftString,'Description',ftString,[]);
{ 4} AddDef('Details',ftString,'Details',ftString,[]);
end;
end;
end;
ObjectRegistry.RegisterObject(Self,MetaData);
end;
procedure ThcDeploymentRegionList.Load;
const
FSQL :string =
' select r.RegionGUID, r.Number, r.IsLocalAreaSubFranchised, r.Description, r.Details '+
' from Region r '+
' where LocalAreaEmployeeGUID is not null '+ //exclude HeadOffice
' order by Description asc ';
var
saveCursor: TCursor;
aQuery: IhcQuery;
begin
saveCursor := Screen.Cursor;
Screen.Cursor := crHourGlass;
try
PreLoad;
aQuery := ThcFactoryPool(FactoryPool).CreateQuery;
with aQuery do
begin
SQL.Text := FSQL;
LogQueryOpen(aQuery);
while not EOF do
begin
Self.Append;
with Current as ThcDeploymentRegion do
begin
SetObjectState(osReading); //prevent calcs while loading
RegionGUID.Assign(FieldByName('RegionGUID'));
Number.Assign(FieldByName('Number'));
IsLocalAreaSubFranchised.Assign(FieldByName('IsLocalAreaSubFranchised'));
Description.Assign(FieldByName('Description'));
Details.Assign(FieldByName('Details'));
ObjectExistsInStore;
end; //with
aQuery.Next;
end; //while
end; //with
finally
PostLoad;
Screen.Cursor := saveCursor;
end; //try/finally
end;
function ThcDeploymentRegionList.Current :ThcDeploymentRegion;
begin
Result := ThcDeploymentRegion(inherited Current);
end;
procedure ThcDeploymentRegionList.AfterConstruction;
begin
inherited AfterConstruction;
ObjectClassName := ThcDeploymentRegion.ClassName;
end;
initialization
ThcDeploymentRegion.Register;
finalization
ThcDeploymentRegion.UnRegister;
end.
|
unit DMedicamentos;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ADPadrao, Db, DBTables;
type
TPosicionaCamposFMedicamentos = (
pcFMedicamentosNenhum,
pcFMedicamentosCODMedicamento,
pcFMedicamentosDesMedicamento);
TDmMedicamentos = class(TADmPadrao)
QryCadastroCODMEDICAMENTO: TIntegerField;
QryCadastroDESMEDICAMENTO: TStringField;
QryCadastroVLRMEDICAMENTO: TFloatField;
procedure QryCadastroBeforePost(DataSet: TDataSet);
procedure QryCadastroAfterPost(DataSet: TDataSet);
private
FPosicionaCamposFMedicamentos: TPosicionaCamposFMedicamentos;
procedure ValidaCampos(DataSet: TDataSet);
procedure SetPosicionaCamposFMedicamentos(
const Value: TPosicionaCamposFMedicamentos);
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
procedure GravaTodasTabelas;
property PosicionaCamposFMedicamentos: TPosicionaCamposFMedicamentos
read FPosicionaCamposFMedicamentos write SetPosicionaCamposFMedicamentos;
function Pesquisa(vpsChaveDeBusca: String; vptBtnCadastro: TObject = nil): String;
{ Public declarations }
end;
var
DmMedicamentos: TDmMedicamentos;
implementation
uses
UFerramentas, UFerramentasB, DConexao, SPesquisa, DGeral;
{$R *.DFM}
constructor TDmMedicamentos.Create(AOwner: TComponent);
begin
NomeEntidade := 'Medicamento';
NomeCampoChave := 'CodMedicamento';
inherited Create(AOwner);
end;
procedure TDmMedicamentos.QryCadastroBeforePost(DataSet: TDataSet);
begin
inherited;
ValidaCampos(DataSet);
end;
procedure TDmMedicamentos.ValidaCampos(DataSet: TDataSet);
begin
PosicionaCamposFMedicamentos := pcFMedicamentosNenhum;
if (DataSet.State in [dsEdit]) then
begin
if DataSet.FieldByName('CodMedicamento').AsString = '' then
begin
PosicionaCamposFMedicamentos := pcFMedicamentosCodMedicamento;
raise Exception.Create('O código do Medicamento é obrigatório! ');
end;
end;
if DataSet.FieldByName('DesMedicamento').AsString = '' then
begin
PosicionaCamposFMedicamentos := pcFMedicamentosDesMedicamento;
raise Exception.Create('O descrição do Medicamento é obrigatório! ');
end;
end;
procedure TDmMedicamentos.GravaTodasTabelas;
begin
if (QryCadastro.State in [dsEdit, dsInsert]) then
QryCadastro.Post;
Atualizar;
end;
procedure TDmMedicamentos.SetPosicionaCamposFMedicamentos(
const Value: TPosicionaCamposFMedicamentos);
begin
FPosicionaCamposFMedicamentos := Value;
end;
procedure TDmMedicamentos.QryCadastroAfterPost(DataSet: TDataSet);
begin
inherited;
QryCadastro.Last;
end;
function TDmMedicamentos.Pesquisa(vpsChaveDeBusca: String; vptBtnCadastro: TObject = nil): String;
begin
try
Result :=
FNCPesquisa(
vptBtnCadastro,
'Cadastro dos medicamento',
vpsChaveDeBusca,
'CODMedicamento AS Codigo',
DmConexao.DbsConexao.DatabaseName,
'Medicamento',
'CODMedicamento AS Codigo',
'DesMedicamento AS Nome',
'VlrMedicamento as Valor',
'',
'',
'');
except
on E: Exception do
raise Exception.Create(
'Erro na pesquisa! ' + #13 + #13 +
'[' + E.Message + ']!');
end;
end;
end.
|
unit Storages;
interface
uses
System.Classes,
MapTypes,
Features;
type
{
Reading simplest text file. Each feature starts of number of points,
then point list it self. After the last feature's point one line is skipped.
Example:
N
X1 Y1
X2 Y2
...
XN YN
<empty line>
and so on
Features must have LineString/LinearRing geometry only.
}
TTxtStorage = class(TStorage)
private
FFeature: TGeometryEnabledFeature;
FDataLine: Integer;
FDataStrings: TStringList;
FModel: TModel;
{ Low level helpers }
function HasData: Boolean;
procedure MoveToNextData;
function CurrentData: string;
{ Overriden methods }
procedure LoadMetaData; virtual;
function LoadNext: TGeometryEnabledFeature; virtual;
{ Template methods }
function GetFeature: TGeometryEnabledFeature;
function HasNext: Boolean;
public
constructor Create(AFileName: string);
destructor Destroy; override;
procedure LoadTo(AModel: TModel); override;
end;
TMifStorage = class(TTxtStorage)
private
type
TColumnDef = record
Name: string;
Kind: string;
Width: Integer;
Decimals: Integer;
end;
TColumnDefDynArray = array of TColumnDef;
private
FAttrFileName: string;
FAttrLine: Integer;
FAttrStrings: TStringList;
FAttrDelimiter: Char;
FColumnDefs: TColumnDefDynArray;
FColumnsCount: Integer;
function HasAttribute: Boolean;
procedure MoveToNextAttribute;
function CurrentAttribute: string;
procedure LoadMetaData; override;
function LoadNext: TGeometryEnabledFeature; override;
public
constructor Create(AFileName: string);
destructor Destroy; override;
end;
implementation
uses
System.SysUtils,
CommonGeometry,
GeosGeometry,
System.RegularExpressions,
Properties;
{ RegEx helpers }
const
cVersionPattern = '^\s*VERSION';
cCharsetPattern = '^\s*CHARSET';
cDelimiterPattern = '^\s*DELIMITER\s+"(?P<delimiter>.)"';
cCoordsysPattern = '^\s*COORDSYS';
cColumnsCountPattern = '^\s*COLUMNS\s+(?P<column_count>\d+)';
cColumnDefPattern = '^\s*(?P<name>\w+)\s+(?P<kind>\w+)(\s*\((?P<width>\d+)(,?(?P<decimals>\d+)?)\))?';
cAttributePattern = '(,|^)("(?:[^"]|"")*"|[^,]*)?';
cDataPattern = '^\s*DATA';
cPointPattern = '^\s*POINT\s+(?P<x>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))\s+(?P<y>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))';
cLinePattern = '^\s*LINE\s+(?P<x1>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))\s+(?P<y1>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))\s+(?P<x2>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))\s+(?P<y2>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))';
cPlinePattern = '^\s*PLINE\s+(?P<vertex_count>\d+)';
cRegionPattern = '^\s*REGION\s+(?P<polygon_count>\d+)';
cCountPattern = '^\s*(?P<count>\d+)';
cXYPairPattern = '^\s*(?P<x>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))\s+(?P<y>[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+))';
cPenPattern = '^\s*PEN';
cBrushPattern = '^\s*BRUSH';
cSymbolPattern = '^\s*SYMBOL';
cSmoothPattern = '^\s*SMOOTH';
cCenterPattern = '^\s*CENTER';
var
VersionRegExp: TRegEx;
CharsetRegExp: TRegEx;
DelimeterRegExp: TRegEx;
CoordsysRegExp: TRegEx;
ColumnsCountRegExp: TRegEx;
ColumnDefRegExp: TRegEx;
AttributeRegExp: TRegEx;
DataRegExp: TRegEx;
PointRegExp: TRegEx;
LineRegExp: TRegEx;
PlineRegExp: TRegEx;
RegionRegExp: TRegEx;
CountRegExp: TRegEx;
XYPairRegExp: TRegEx;
PenRegExp: TRegEx;
BrushRegExp: TRegEx;
SymbolRegExp: TRegEx;
SmoothRegExp: TRegEx;
CenterRegExp: TRegEx;
procedure InitRegExpMatchers;
begin
VersionRegExp := TRegEx.Create(cVersionPattern, [roIgnoreCase, roCompiled]);
CharsetRegExp := TRegEx.Create(cCharsetPattern, [roIgnoreCase, roCompiled]);
DelimeterRegExp := TRegEx.Create(cDelimiterPattern, [roIgnoreCase, roCompiled]);
CoordsysRegExp := TRegEx.Create(cCoordsysPattern, [roIgnoreCase, roCompiled]);
ColumnsCountRegExp := TRegEx.Create(cColumnsCountPattern, [roIgnoreCase, roCompiled]);
ColumnDefRegExp := TRegEx.Create(cColumnDefPattern, [roIgnoreCase, roCompiled]);
AttributeRegExp := TRegEx.Create(cAttributePattern, [roIgnoreCase, roCompiled]);
DataRegExp := TRegEx.Create(cDataPattern, [roIgnoreCase, roCompiled]);
PointRegExp := TRegEx.Create(cPointPattern, [roIgnoreCase, roCompiled]);
LineRegExp := TRegEx.Create(cLinePattern, [roIgnoreCase, roCompiled]);
PlineRegExp := TRegEx.Create(cPlinePattern, [roIgnoreCase, roCompiled]);
RegionRegExp := TRegEx.Create(cRegionPattern, [roIgnoreCase, roCompiled]);
CountRegExp := TRegEx.Create(cCountPattern, [roCompiled]);
XYPairRegExp := TRegEx.Create(cXYPairPattern, [roCompiled]);
PenRegExp := TRegEx.Create(cPenPattern, [roIgnoreCase, roCompiled]);
BrushRegExp := TRegEx.Create(cBrushPattern, [roIgnoreCase, roCompiled]);
SymbolRegExp := TRegEx.Create(cSymbolPattern, [roIgnoreCase, roCompiled]);
SmoothRegExp := TRegEx.Create(cSmoothPattern, [roIgnoreCase, roCompiled]);
CenterRegExp := TRegEx.Create(cCenterPattern, [roIgnoreCase, roCompiled]);
end;
{ TTxtStorage }
constructor TTxtStorage.Create(AFileName: string);
begin
inherited;
FDataStrings := TStringList.Create;
FDataStrings.LoadFromFile(FFileName);
FDataLine := 0;
end;
destructor TTxtStorage.Destroy;
begin
FDataStrings.Free;
inherited;
end;
function TTxtStorage.CurrentData: string;
begin
Result := FDataStrings[FDataLine];
end;
function TTxtStorage.GetFeature: TGeometryEnabledFeature;
begin
Result := FFeature;
end;
function TTxtStorage.HasNext: Boolean;
begin
FFeature := LoadNext;
Result := Assigned(FFeature);
end;
function TTxtStorage.HasData: Boolean;
begin
Result := FDataLine < FDataStrings.Count;
end;
procedure TTxtStorage.LoadTo(AModel: TModel);
begin
FModel := AModel;
LoadMetaData;
while HasNext do
AModel.Add(GetFeature);
end;
procedure TTxtStorage.MoveToNextData;
begin
FDataLine := FDataLine + 1;
end;
procedure TTxtStorage.LoadMetaData;
begin
// do nothing
end;
function TTxtStorage.LoadNext: TGeometryEnabledFeature;
var
LCurrentStr: string;
LVertexCount, I: Integer;
X, Y : Double;
LStringPartList : TStringList;
LVertices: TVertexList;
begin
Result := nil;
LStringPartList := TStringList.Create;
try
if HasData then
begin
LCurrentStr := CurrentData;
LVertexCount := StrToInt(LCurrentStr);
LVertices := TVertexList.Create;
try
for I := 1 to LVertexCount do
begin
MoveToNextData;
LCurrentStr := CurrentData;
LStringPartList.DelimitedText := LCurrentStr;
X := StrToFloat(LStringPartList.Strings[0]);
Y := StrToFloat(LStringPartList.Strings[1]);
LStringPartList.Clear;
LVertices.Add(
//file keeps coordinates in Decart order, our model does so too
MakeVertex(X, Y)
);
end;
MoveToNextData;
MoveToNextData;
Result := TLinearFeature.Create(FModel, LVertices);
Result.ClassifierTag := 'Атрибут ' + IntToStr(LVertexCount mod 3);
finally
LVertices.Free;
end;
end;
finally
LStringPartList.Free;
end;
end;
{ TMifStorage }
constructor TMifStorage.Create(AFileName: string);
begin
inherited Create(AFileName);
FAttrFileName := ChangeFileExt(AFileName, '.mid');
FAttrStrings := TStringList.Create;
FAttrStrings.LoadFromFile(FAttrFileName);
FAttrLine := 0;
FAttrDelimiter := #09;
InitRegExpMatchers;
end;
destructor TMifStorage.Destroy;
begin
FAttrStrings.Free;
inherited;
end;
function TMifStorage.CurrentAttribute: string;
begin
Result := FAttrStrings[FAttrLine];
end;
function TMifStorage.HasAttribute: Boolean;
begin
Result := FAttrLine < FAttrStrings.Count;
end;
procedure TMifStorage.LoadMetaData;
procedure LoadHeaderData;
begin
if HasData and VersionRegExp.IsMatch(CurrentData) then
MoveToNextData;
if HasData and CharsetRegExp.IsMatch(CurrentData) then
MoveToNextData;
if HasData and DelimeterRegExp.IsMatch(CurrentData) then begin
FAttrDelimiter := DelimeterRegExp.Match(CurrentData).Groups['delimiter'].Value[1];
MoveToNextData;
end;
if HasData and CoordsysRegExp.IsMatch(CurrentData) then
MoveToNextData;
end;
procedure LoadColumnDefs;
var
I: Integer;
begin
FColumnsCount := 0;
Assert(ColumnsCountRegExp.IsMatch(CurrentData));
if HasData and ColumnsCountRegExp.IsMatch(CurrentData) then begin
FColumnsCount := StrToInt(ColumnsCountRegExp.Match(CurrentData).Groups['column_count'].Value);
MoveToNextData;
end;
SetLength(FColumnDefs, FColumnsCount);
for I := 0 to FColumnsCount - 1 do begin
Assert(ColumnDefRegExp.IsMatch(CurrentData));
FColumnDefs[I].Name := UpperCase(ColumnDefRegExp.Match(CurrentData).Groups['name'].Value);
FColumnDefs[I].Kind := UpperCase(ColumnDefRegExp.Match(CurrentData).Groups['kind'].Value);
if FColumnDefs[I].Kind = 'CHAR' then
FColumnDefs[I].Width := StrToInt(ColumnDefRegExp.Match(CurrentData).Groups['width'].Value);
if FColumnDefs[I].Kind = 'DECIMAL' then begin
FColumnDefs[I].Width := StrToInt(ColumnDefRegExp.Match(CurrentData).Groups['width'].Value);
FColumnDefs[I].Decimals := StrToInt(ColumnDefRegExp.Match(CurrentData).Groups['decimals'].Value);
end;
MoveToNextData;
end;
if HasData and DataRegExp.IsMatch(CurrentData) then
MoveToNextData;
end;
procedure ApplyColumnDefsToModel;
var
I: Integer;
PropDef: TPropertyDef;
begin
for I := 0 to FColumnsCount - 1 do begin
PropDef := TPropertyDef.Create(FColumnDefs[I].Name);
FModel.PropertyDefTable.Add(PropDef);
end;
end;
begin
LoadHeaderData;
LoadColumnDefs;
ApplyColumnDefsToModel;
end;
function TMifStorage.LoadNext: TGeometryEnabledFeature;
procedure LoadVertices(out Vertices: TVertexList; Count: Integer);
var
I: Integer;
X, Y : Double;
Match: TMatch;
begin
for I := 1 to Count do begin
MoveToNextData;
Assert(HasData);
Match := XYPairRegExp.Match(CurrentData);
Assert(Match.Success, 'Input Line: ' + IntToStr(FDataLine) + ' Data: ' + CurrentData);
X := StrToFloat(Match.Groups['x'].Value);
Y := StrToFloat(Match.Groups['y'].Value);
Vertices.Add(
//file keeps coordinates in Decart order, our model does so too
MakeVertex(X, Y)
);
end;
end;
function LoadPoint: TGeometryEnabledFeature;
var
Vertex: TVertex;
X, Y : Double;
Match: TMatch;
begin
Match := PointRegExp.Match(CurrentData);
X := StrToFloat(Match.Groups['x'].Value);
Y := StrToFloat(Match.Groups['y'].Value);
Vertex := MakeVertex(X, Y);
MoveToNextData;
if HasData and SymbolRegExp.IsMatch(CurrentData) then
MoveToNextData;
Result := TPointFeature.Create(FModel, Vertex);
end;
function LoadLine: TGeometryEnabledFeature;
var
Vertices: TVertexList;
X1, Y1, X2, Y2 : Double;
Match: TMatch;
begin
Vertices := TVertexList.Create;
try
Match := LineRegExp.Match(CurrentData);
X1 := StrToFloat(Match.Groups['x1'].Value);
Y1 := StrToFloat(Match.Groups['y1'].Value);
Vertices.Add(
MakeVertex(X1, Y1)
);
X2 := StrToFloat(Match.Groups['x2'].Value);
Y2 := StrToFloat(Match.Groups['y2'].Value);
Vertices.Add(
MakeVertex(X2, Y2)
);
MoveToNextData;
if HasData and PenRegExp.IsMatch(CurrentData) then
MoveToNextData;
Result := TLinearFeature.Create(FModel, Vertices);
finally
Vertices.Free;
end;
end;
function LoadPline: TGeometryEnabledFeature;
var
VertexCount: Integer;
Vertices: TVertexList;
begin
VertexCount := StrToInt(PlineRegExp.Match(CurrentData).Groups['vertex_count'].Value);
Vertices := TVertexList.Create;
try
LoadVertices(Vertices, VertexCount);
MoveToNextData;
if HasData and PenRegExp.IsMatch(CurrentData) then
MoveToNextData;
if HasData and SmoothRegExp.IsMatch(CurrentData) then
MoveToNextData;
Result := TLinearFeature.Create(FModel, Vertices);
finally
Vertices.Free;
end;
end;
function LoadRegion: TGeometryEnabledFeature;
var
I, PolygonCount: Integer;
VertexCount: Integer;
Vertices: TVertexList;
Polygon: TGeosPolygonWrapper;
Shell: TGeosLinearRingWrapper;
Rings: array of TGeosLinearRingWrapper;
begin
PolygonCount := StrToInt(RegionRegExp.Match(CurrentData).Groups['polygon_count'].Value);
MoveToNextData;
Assert(HasData);
VertexCount := StrToInt(CountRegExp.Match(CurrentData).Groups['count'].Value);
Vertices := TVertexList.Create;
try
LoadVertices(Vertices, VertexCount);
Shell := TGeosLinearRingWrapper.Create(Vertices);
finally
Vertices.Free;
end;
if PolygonCount > 1 then begin
SetLength(Rings, PolygonCount - 1);
for I := 1 to PolygonCount - 1 do begin
MoveToNextData;
Assert(HasData);
VertexCount := StrToInt(CountRegExp.Match(CurrentData).Groups['count'].Value);
Vertices := TVertexList.Create;
try
LoadVertices(Vertices, VertexCount);
Rings[I - 1] := TGeosLinearRingWrapper.Create(Vertices);
finally
Vertices.Free;
end;
end;
end;
MoveToNextData;
if HasData and PenRegExp.IsMatch(CurrentData) then
MoveToNextData;
if HasData and BrushRegExp.IsMatch(CurrentData) then
MoveToNextData;
if HasData and CenterRegExp.IsMatch(CurrentData) then
MoveToNextData;
Polygon := TGeosPolygonWrapper.Create(Shell, Rings);
Result := TPolygonFeature.Create(FModel, Polygon);
end;
procedure LoadAttributes(AFeature: TGeometryEnabledFeature);
var
I: Integer;
From: Integer;
Matches: TMatchCollection;
begin
From := 0;
if (FColumnsCount > 0) then begin
Assert(HasAttribute);
if (FColumnsCount = 1) and (CurrentAttribute = '') then
AFeature.PropertyByName[FColumnDefs[0].Name] := ''
else begin
Assert(AttributeRegExp.IsMatch(CurrentAttribute));
Matches := AttributeRegExp.Matches(CurrentAttribute);
if Pos(',', CurrentAttribute) = 1 then begin
Assert(Matches.Count = FColumnsCount - 1);
AFeature.PropertyByName[FColumnDefs[0].Name] := '';
From := 1;
end
else
Assert(Matches.Count = FColumnsCount);
for I := From to FColumnsCount - 1 do begin
AFeature.PropertyByName[FColumnDefs[I].Name] :=
Matches.Item[I - From].Groups[2].Value;
end;
end;
MoveToNextAttribute;
end;
end;
begin
Result := nil;
if HasData then
begin
if PointRegExp.IsMatch(CurrentData) then begin
Result := LoadPoint;
end
else if LineRegExp.IsMatch(CurrentData) then begin
Result := LoadLine;
end
else if PlineRegExp.IsMatch(CurrentData) then begin
Result := LoadPline;
end
else if RegionRegExp.IsMatch(CurrentData) then begin
Result := LoadRegion;
end
else
Assert(False, 'TMifStorage.LoadNext: Unknown feature type!');
Assert(Assigned(Result));
LoadAttributes(Result);
end;
end;
procedure TMifStorage.MoveToNextAttribute;
begin
FAttrLine := FAttrLine + 1;
end;
end.
|
{This unit contains implementation of entites interfaces from
ModelDataModel}
unit ModelEntitiesImplementation;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ModelDataModel, Graphics;
type
{ TCommunity
is an implementation of ICommunityInterface}
TCommunity = class(TInterfacedObject, ICommunity)
private
FAccessKey: string;
FChatBot: IChatBot;
FCommunityType: TCommunityType;
FDeactivated: boolean;
FDialogs: TDialogsList;
FHasPhoto: boolean;
FID: string;
FIsClosed: boolean;
FName: string;
FScreenName: string;
FPhoto: TPicture;
public
constructor Create(AAccessKey: string; AChatBot: IChatBot;
ACommunityType: TCommunityType; ADeactivated: boolean;
ADialogs: TDialogsList; AHasPhoto: boolean; AId: string;
AIsClosed: boolean; AName: string; AScreenName: string; APhoto: TPicture);
function GetAccessKey: string;
function GetChatbot: IChatBot;
function GetCommunityType: TCommunityType;
function GetDeactivated: boolean;
function GetDialogs: TDialogsList;
function GetHasPhoto: boolean;
function GetId: string;
function GetIsClosed: boolean;
function GetName: string;
function GetPhoto: TPicture;
function GetScreenName: string;
{SetDialogs frees old dialog list}
procedure SetDialogs(AValue: TDialogsList);
property Name: string read GetName;
property Id: string read GetId;
property ScreenName: string read GetScreenName;
property IsClosed: boolean read GetIsClosed;
property Deactivated: boolean read GetDeactivated;
property CommunityType: TCommunityType read GetCommunityType;
property HasPhoto: boolean read GetHasPhoto;
property Photo: TPicture read GetPhoto;
property AccessKey: string read GetAccessKey;
property Chatbot: IChatBot read GetChatbot;
property Dialogs: TDialogsList read GetDialogs write SetDialogs;
destructor Destroy; override;
end;
{ TChatBot }
TChatBot = class(TInterfacedObject, IChatBot)
private
FCommands: TChatBotCommandsList;
public
constructor Create(ACommands: TChatBotCommandsList);
function GetCommands: TChatBotCommandsList;
property Commands: TChatBotCommandsList read GetCommands;
{Frees commands}
destructor Destroy; override;
end;
{ TChatBotCommand }
TChatBotCommand = class(TInterfacedObject, IChatBotCommand)
private
FCommand: string;
FResponse: string;
public
constructor Create(ACommand: string; AResponse: string);
function GetCommand: string;
function GetResponse: string;
property Command: string read GetCommand;
property Response: string read GetResponse;
end;
{ TDialog }
TDialog = class(TInterfacedObject, IDialog)
private
FMessages: TMessageList;
FPerson: IUser;
public
constructor Create(APerson: IUser; AMessages: TMessageList);
function GetMessages: TMessageList;
function GetPerson: IUser;
property Person: IUser read GetPerson;
property Messages: TMessageList read GetMessages;
{Frees messages}
destructor Destroy; override;
end;
{ TMessage }
TMessage = class(TInterfacedObject, IMessage)
private
FDate: TDateTime;
FDeleted: boolean;
FEmoji: boolean;
FFromId: string;
FId: string;
FMessage: string;
FOut: TOutType;
FReadState: TReadState;
FTitle: string;
public
constructor Create(ADate: TDateTime; ADeleted: boolean; AEmoji: boolean;
AFromId: string; AId: string; AMessage: string; AOut: TOutType;
AReadState: TReadState; ATitle: string);
function GetDate: TDateTime;
function GetDeleted: boolean;
function GetEmoji: boolean;
function GetFromId: string;
function GetId: string;
function GetMessage: string;
function GetOut: TOutType;
function GetReadState: TReadState;
function GetTitle: string;
property Id: string read GetId;
property Message: string read GetMessage;
property Date: TDateTime read GetDate;
property ReadState: TReadState read GetReadState;
property Out: TOutType read GetOut;
property Title: string read GetTitle;
property Deleted: boolean read GetDeleted;
property Emoji: boolean read GetEmoji;
end;
{ TUser }
TUser = class(TInterfacedObject, IUser)
FFirstName: string;
Fid: string;
FLastName: string;
FPicture200: TPicture;
FPicture50: TPicture;
public
constructor Create(AFirstName: string; AId: string; ALastName: string;
APicture200: TPicture; APicture50: TPicture);
function GetFirstName: string;
function GetId: string;
function GetLastName: string;
function GetPicture200: TPicture;
function GetPicture50: TPicture;
property Id: string read GetId;
property FirstName: string read GetFirstName;
property LastName: string read GetLastName;
property Picture50: TPicture read GetPicture50;
property Picture200: TPicture read GetPicture200;
{Frees Picture200 and Picture50}
destructor Destroy; overload;
end;
implementation
{ TUser }
constructor TUser.Create(AFirstName: string; AId: string; ALastName: string;
APicture200: TPicture; APicture50: TPicture);
begin
FFirstName := AFirstName;
Fid := AId;
FPicture50 := APicture50;
FPicture200 := APicture200;
end;
function TUser.GetFirstName: string;
begin
Result := FFirstName;
end;
function TUser.GetId: string;
begin
Result := Fid;
end;
function TUser.GetLastName: string;
begin
Result := FLastName;
end;
function TUser.GetPicture200: TPicture;
begin
Result := FPicture200;
end;
function TUser.GetPicture50: TPicture;
begin
Result := FPicture50;
end;
destructor TUser.Destroy;
begin
if Assigned(FPicture50) then
FreeAndNil(FPicture50);
if Assigned(FPicture200) then
FreeAndNil(FPicture200);
end;
{ TMessage }
constructor TMessage.Create(ADate: TDateTime; ADeleted: boolean;
AEmoji: boolean; AFromId: string; AId: string; AMessage: string;
AOut: TOutType; AReadState: TReadState; ATitle: string);
begin
FDate := ADate;
FDeleted := ADeleted;
FEmoji := AEmoji;
FFromId := AFromId;
FId := AId;
FMessage := AMessage;
FOut := AOut;
FReadState := AReadState;
FTitle := ATitle;
end;
function TMessage.GetDate: TDateTime;
begin
Result := FDate;
end;
function TMessage.GetDeleted: boolean;
begin
Result := FDeleted;
end;
function TMessage.GetEmoji: boolean;
begin
Result := FEmoji;
end;
function TMessage.GetFromId: string;
begin
Result := FFromId;
end;
function TMessage.GetId: string;
begin
Result := FId;
end;
function TMessage.GetMessage: string;
begin
Result := FMessage;
end;
function TMessage.GetOut: TOutType;
begin
Result := FOut;
end;
function TMessage.GetReadState: TReadState;
begin
Result := FReadState;
end;
function TMessage.GetTitle: string;
begin
Result := FTitle;
end;
{ TDialog }
constructor TDialog.Create(APerson: IUser; AMessages: TMessageList);
begin
FPerson := APerson;
AMessages := AMessages;
end;
function TDialog.GetMessages: TMessageList;
begin
Result := FMessages;
end;
function TDialog.GetPerson: IUser;
begin
Result := FPerson;
end;
destructor TDialog.Destroy;
begin
FPerson := nil;
FreeAndNil(FMessages);
inherited Destroy;
end;
{ TChatBotCommand }
constructor TChatBotCommand.Create(ACommand: string; AResponse: string);
begin
FCommand := ACommand;
FResponse := AResponse;
end;
function TChatBotCommand.GetCommand: string;
begin
Result := FCommand;
end;
function TChatBotCommand.GetResponse: string;
begin
Result := FResponse;
end;
{ TChatBot }
constructor TChatBot.Create(ACommands: TChatBotCommandsList);
begin
FCommands := ACommands;
end;
function TChatBot.GetCommands: TChatBotCommandsList;
begin
Result := FCommands;
end;
destructor TChatBot.Destroy;
begin
FreeAndNil(FCommands);
end;
{ TCommunity }
constructor TCommunity.Create(AAccessKey: string; AChatBot: IChatBot;
ACommunityType: TCommunityType; ADeactivated: boolean; ADialogs: TDialogsList;
AHasPhoto: boolean; AId: string; AIsClosed: boolean; AName: string;
AScreenName: string; APhoto: TPicture);
begin
FAccessKey := AAccessKey;
FChatBot := AChatBot;
FCommunityType := ACommunityType;
FDeactivated := ADeactivated;
FDialogs := ADialogs;
FHasPhoto := AHasPhoto;
FID := AId;
FIsClosed := AIsClosed;
FName := AName;
FScreenName := AScreenName;
FPhoto := APhoto;
end;
function TCommunity.GetAccessKey: string;
begin
Result := FAccessKey;
end;
function TCommunity.GetChatbot: IChatBot;
begin
Result := FChatBot;
end;
function TCommunity.GetCommunityType: TCommunityType;
begin
Result := FCommunityType;
end;
function TCommunity.GetDeactivated: boolean;
begin
Result := FDeactivated;
end;
function TCommunity.GetDialogs: TDialogsList;
begin
Result := FDialogs;
end;
function TCommunity.GetHasPhoto: boolean;
begin
Result := FHasPhoto;
end;
function TCommunity.GetId: string;
begin
Result := FID;
end;
function TCommunity.GetIsClosed: boolean;
begin
Result := FIsClosed;
end;
function TCommunity.GetName: string;
begin
Result := FName;
end;
function TCommunity.GetPhoto: TPicture;
begin
Result := FPhoto;
end;
function TCommunity.GetScreenName: string;
begin
Result := FScreenName;
end;
procedure TCommunity.SetDialogs(AValue: TDialogsList);
begin
FreeAndNil(FDialogs);
FDialogs := AValue;
end;
destructor TCommunity.Destroy;
begin
FChatBot := nil;
FDialogs := nil;
inherited Destroy;
end;
end.
|
{
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* HproseHttpClient.pas *
* *
* hprose synapse http client unit for delphi. *
* *
* LastModified: Dec 9, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
}
unit HproseHttpClient;
interface
uses Classes, HproseCommon, HproseClient, SysUtils{$IFDEF FPC}, LResources{$ENDIF};
type
{ THproseHttpClient }
THproseHttpClient = class(THproseClient)
private
FHttpPool: IList;
FProtocol: string;
FUser: string;
FPassword: string;
FHost: string;
FPort: string;
FPath: string;
FPara: string;
FHeaders: IMap;
FKeepAlive: Boolean;
FKeepAliveTimeout: Integer;
FProxyHost: string;
FProxyPort: Integer;
FProxyUser: string;
FProxyPass: string;
FUserAgent: string;
FConnectionTimeout: Integer;
protected
function SendAndReceive(const Data: TBytes;
const Context: TClientContext): TBytes; override;
procedure InitURI(const AValue: string); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{:Before HTTP operation you may define any non-standard headers for HTTP
request, except of: 'Expect: 100-continue', 'Content-Length', 'Content-Type',
'Connection', 'Authorization', 'Proxy-Authorization' and 'Host' headers.}
property Headers: IMap read FHeaders;
{:If @true (default value is @true), keepalives in HTTP protocol 1.1 is enabled.}
property KeepAlive: Boolean read FKeepAlive write FKeepAlive;
{:Define timeout for keepalives in seconds! Default value is 300.}
property KeepAliveTimeout: Integer read FKeepAliveTimeout write FKeepAliveTimeout;
{:Address of proxy server (IP address or domain name).}
property ProxyHost: string read FProxyHost write FProxyHost;
{:Port number for proxy connection. Default value is 8080.}
property ProxyPort: Integer read FProxyPort write FProxyPort;
{:Username for connect to proxy server.}
property ProxyUser: string read FProxyUser write FProxyUser;
{:Password for connect to proxy server.}
property ProxyPass: string read FProxyPass write FProxyPass;
{:Here you can specify custom User-Agent indentification. By default is
used: 'Hprose Http Client for Delphi (Synapse)'}
property UserAgent: string read FUserAgent write FUserAgent;
{:UserName for user authorization.}
property UserName: string read FUser write FUser;
{:Password for user authorization.}
property Password: string read FPassword write FPassword;
{:Define timeout for ConnectionTimeout in milliseconds! Default value is 10000.}
property ConnectionTimeout: Integer read FConnectionTimeout write FConnectionTimeout;
end;
procedure Register;
implementation
uses httpsend, synautil, Variants;
var
cookieManager: IMap;
procedure SetCookie(Header: IMap; const Host: string);
var
I, Pos: Integer;
Name, Value, CookieString, Path: string;
Cookie: IMap;
begin
for I := 0 to Header.Count - 1 do begin
Name := LowerCase(Header.Keys[I]);
if (Name = 'set-cookie') or (Name = 'set-cookie2') then begin
Value := Header.Values[I];
Pos := AnsiPos(';', Value);
CookieString := Copy(Value, 1, Pos - 1);
Value := Copy(Value, Pos + 1, MaxInt);
Cookie := TCaseInsensitiveHashMap.Split(Value, ';', '=', 0, True, False, True);
Pos := AnsiPos('=', CookieString);
Cookie['name'] := Copy(CookieString, 1, Pos - 1);
Cookie['value'] := Copy(CookieString, Pos + 1, MaxInt);
if Cookie.ContainsKey('path') then begin
Path := Cookie['path'];
if (Length(Path) > 0) then begin
if (Path[1] = '"') then Delete(Path, 1, 1);
if (Path[Length(Path)] = '"') then SetLength(Path, Length(Path) - 1);
end;
if (Length(Path) > 0) then
Cookie['path'] := Path
else
Cookie['path'] := '/';
end
else
Cookie['path'] := '/';
if Cookie.ContainsKey('expires') then begin
Cookie['expires'] := DecodeRfcDateTime(Cookie['expires']);
end;
if Cookie.ContainsKey('domain') then
Cookie['domain'] := LowerCase(Cookie['domain'])
else
Cookie['domain'] := Host;
Cookie['secure'] := Cookie.ContainsKey('secure');
CookieManager.BeginWrite;
try
if not CookieManager.ContainsKey(Cookie['domain']) then
CookieManager[Cookie['domain']] := THashMap.Create(False, True) as IMap;
VarToMap(CookieManager[Cookie['domain']])[Cookie['name']] := Cookie;
finally
CookieManager.EndWrite;
end;
end;
end;
end;
function GetCookie(const Host, Path: string; Secure: Boolean): string;
var
Cookies, CookieMap, Cookie: IMap;
Names: IList;
Domain: string;
I, J: Integer;
begin
Cookies := THashMap.Create(False);
CookieManager.BeginRead;
try
for I := 0 to CookieManager.Count - 1 do begin
Domain := VarToStr(CookieManager.Keys[I]);
if AnsiPos(Domain, Host) <> 0 then begin
CookieMap := VarToMap(CookieManager.Values[I]);
CookieMap.BeginRead;
try
Names := TArrayList.Create(False);
for J := 0 to CookieMap.Count - 1 do begin
Cookie := VarToMap(CookieMap.Values[J]);
if Cookie.ContainsKey('expires') and (Cookie['expires'] < Now) then
Names.Add(Cookie['name'])
else if AnsiPos(Cookie['path'], Path) = 1 then begin
if ((Secure and Cookie['secure']) or not Cookie['secure']) and
(Cookie['value'] <> '') then
Cookies[Cookie['name']] := Cookie['value'];
end;
end;
finally
CookieMap.EndRead;
end;
if Names.Count > 0 then begin
CookieMap.BeginWrite;
try
for J := 0 to Names.Count - 1 do CookieMap.Delete(Names[J]);
finally
CookieMap.EndWrite;
end;
end;
end;
end;
Result := Cookies.Join('; ');
finally
CookieManager.EndRead;
end;
end;
{ THproseHttpClient }
function THproseHttpClient.SendAndReceive(const Data: TBytes;
const Context: TClientContext): TBytes;
var
HttpSend: THttpSend;
Cookie: string;
Error: string;
Header, HttpHeader: IMap;
I: Integer;
K, V: string;
begin
FHttpPool.Lock;
try
if FHttpPool.Count > 0 then
HttpSend := THttpSend(VarToObj(FHttpPool.Delete(FHttpPool.Count - 1)))
else
HttpSend := THttpSend.Create;
finally
FHttpPool.Unlock;
end;
Header := TCaseInsensitiveHashMap.Create;
Header.PutAll(FHeaders);
HttpHeader := VarToMap(Context['httpHeader']);
if (Assigned(HttpHeader)) then
Header.PutAll(HttpHeader)
else
HttpHeader := TCaseInsensitiveHashMap.Create;
for I := 0 to Header.Count - 1 do
HttpSend.Headers.Values[Header.Keys[I]] := Header.Values[I];
HttpSend.KeepAlive := FKeepAlive;
HttpSend.KeepAliveTimeout := FKeepAliveTimeout;
HttpSend.UserName := FUser;
HttpSend.Password := FPassword;
HttpSend.ProxyHost := FProxyHost;
if FProxyPort = 0 then
HttpSend.ProxyPort := ''
else
HttpSend.ProxyPort := IntToStr(FProxyPort);
HttpSend.ProxyUser := FProxyUser;
HttpSend.ProxyPass := FProxyPass;
HttpSend.UserAgent := FUserAgent;
HttpSend.Sock.ConnectionTimeout := FConnectionTimeout;
HttpSend.Timeout := Context.Settings.Timeout;
HttpSend.Protocol := '1.1';
HttpSend.MimeType := 'application/hprose';
Cookie := GetCookie(FHost,
FPath,
LowerCase(FProtocol) = 'https');
if Cookie <> '' then HttpSend.Headers.Add('Cookie: ' + Cookie);
HttpSend.Document.WriteBuffer(Data[0], Length(Data));
if (HttpSend.HTTPMethod('POST', URI)) then begin
HttpHeader.Clear();
for I := 0 to HttpSend.Headers.Count - 1 do begin
K := HttpSend.Headers.Names[I];
V := HttpSend.Headers.Values[K];
HttpHeader.Put(K, V);
end;
Context['httpHeader'] := HttpHeader;
SetCookie(HttpHeader, FHost);
SetLength(Result, HttpSend.Document.Size);
Move(HttpSend.Document.Memory^, Result[0], Length(Result));
HttpSend.Clear;
HttpSend.Cookies.Clear;
FHttpPool.Lock;
try
FHttpPool.Add(ObjToVar(HttpSend));
finally
FHttpPool.Unlock;
end;
end
else begin
Error := IntToStr(HttpSend.Sock.LastError) + ':' + HttpSend.Sock.LastErrorDesc;
FreeAndNil(HttpSend);
raise Exception.Create(Error);
end;
end;
constructor THproseHttpClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHttpPool := TArrayList.Create(10);
FHeaders := TCaseInsensitiveHashMap.Create;
FUser := '';
FPassword := '';
FKeepAlive := True;
FKeepAliveTimeout := 300;
FProxyHost := '';
FProxyPort := 8080;
FProxyUser := '';
FProxyPass := '';
FUserAgent := 'Hprose Http Client for Delphi (Synapse)';
FConnectionTimeout := 10000;
end;
destructor THproseHttpClient.Destroy;
var
I: Integer;
begin
FHttpPool.Lock;
try
for I := FHttpPool.Count - 1 downto 0 do
THTTPSend(VarToObj(FHttpPool.Delete(I))).Free;
finally
FHttpPool.Unlock;
end;
inherited;
end;
procedure THproseHttpClient.InitURI(const AValue: string);
begin
inherited InitURI(AValue);
ParseURL(URI, FProtocol, FUser, FPassword, FHost, FPort, FPath, FPara);
end;
procedure Register;
begin
RegisterComponents('Hprose',[THproseHttpClient]);
end;
initialization
CookieManager := TCaseInsensitiveHashMap.Create(False, True);
{$IFDEF FPC}
{$I Hprose.lrs}
{$ENDIF}
end.
|
unit TransfersList;
interface
uses
Windows, Messages, CommCtrl, AvL, avlUtils, avlListViewEx, avlEventBus,
avlMasks, Aria2, Utils;
type
TTransfersList = class(TListViewEx)
private
FUpdateState: record
Item: Integer;
Selected, RestoreSelected: TAria2GID;
end;
FColumns: TListColumns;
FUpdateKeys: TStringArray;
FSearchString: string;
procedure Cleanup(Sender: TObject);
procedure AddTransferKey(const Column: TListColumn);
function GetGID(Index: Integer): TAria2GID;
procedure LoadSettings(Sender: TObject; const Args: array of const);
procedure SaveSettings(Sender: TObject; const Args: array of const);
procedure ServerChanged(Sender: TObject; const Args: array of const);
public
constructor Create(Parent: TWinControl);
destructor Destroy; override;
procedure Clear;
procedure Find(const S: string);
procedure BeginUpdate;
procedure EndUpdate;
procedure Update(List: TAria2Struct; Names: TStringList);
property GID[Index: Integer]: TAria2GID read GetGID;
property UpdateKeys: TStringArray read FUpdateKeys;
end;
const
STransferColumns = 'TransferListColumns';
implementation
const
SListState = 'TransfersList.State';
DefTransferColumns: array[0..10] of TListColumn = (
(Caption: 'Name'; Width: 200; FType: ftName; Field: ''),
(Caption: 'Size'; Width: 80; FType: ftSize; Field: sfTotalLength),
(Caption: 'Progress'; Width: 60; FType: ftPercent; Field: sfCompletedLength + ':' + sfTotalLength),
(Caption: 'ETA'; Width: 60; FType: ftETA; Field: sfDownloadSpeed + ':' + sfTotalLength + ':' + sfCompletedLength),
(Caption: 'Status'; Width: 100; FType: ftStatus; Field: ''),
(Caption: 'Uploaded'; Width: 80; FType: ftSize; Field: sfUploadLength),
(Caption: 'DL speed'; Width: 80; FType: ftSpeed; Field: sfDownloadSpeed),
(Caption: 'UL speed'; Width: 80; FType: ftSpeed; Field: sfUploadSpeed),
(Caption: 'Ratio'; Width: 50; FType: ftPercent; Field: sfUploadLength + ':' + sfCompletedLength),
(Caption: 'Conns.'; Width: 50; FType: ftString; Field: sfConnections),
(Caption: 'Seeds'; Width: 50; FType: ftString; Field: sfNumSeeders));
type
TListState = class
public
Selected: string;
constructor Create(const S: string);
end;
{ TTransfersList }
constructor TTransfersList.Create(Parent: TWinControl);
begin
inherited;
Style := Style and not LVS_SINGLESEL or LVS_SHOWSELALWAYS {or LVS_EDITLABELS} or LVS_NOSORTHEADER; //TODO: switches for sorting & etc
ViewStyle := LVS_REPORT;
OptionsEx := OptionsEx or LVS_EX_FULLROWSELECT or LVS_EX_GRIDLINES or LVS_EX_INFOTIP;
SmallImages := LoadImageList('TLICONS');
EventBus.AddListener(EvLoadSettings, LoadSettings);
EventBus.AddListener(EvSaveSettings, SaveSettings);
EventBus.AddListener(EvServerChanged, ServerChanged);
OnDestroy := Cleanup;
end;
destructor TTransfersList.Destroy;
begin
EventBus.RemoveListeners([LoadSettings, SaveSettings, ServerChanged]);
Finalize(FColumns);
Finalize(FUpdateKeys);
SmallImages.Free;
inherited;
end;
procedure TTransfersList.Clear;
var
i: Integer;
begin
for i := 0 to ItemCount - 1 do
FreeMem(PChar(ItemObject[i]));
inherited Clear;
end;
procedure TTransfersList.Find(const S: string);
var
i, From: Integer;
Mask: TMask;
begin
if S <> '' then
begin
FSearchString := S;
if (Pos('*', FSearchString) = 0) and (Pos('?', FSearchString) = 0) then
FSearchString := '*' + FSearchString + '*';
From := -1;
end
else From := SelectedIndex;
Mask := TMask.Create(FSearchString);
try
for i := Max(0, From + 1) to ItemCount - 1 do
if Mask.Matches(Items[i, 0]) then
begin
ClearSelection;
SelectedIndex := i;
Perform(LVM_ENSUREVISIBLE, i, 0);
SetFocus;
Exit;
end;
MessageDlg('Not found', (Application as TForm).Caption, MB_ICONINFORMATION);
finally
Mask.Free;
end;
end;
procedure TTransfersList.BeginUpdate;
begin
inherited;
with FUpdateState do
begin
Item := 0;
Selected := GID[SelectedIndex];
end;
end;
procedure TTransfersList.EndUpdate;
var
i: Integer;
begin
while ItemCount > FUpdateState.Item do
begin
FreeMem(PChar(ItemObject[ItemCount - 1]));
ItemDelete(ItemCount - 1);
end;
with FUpdateState do
if RestoreSelected <> '' then
Selected := RestoreSelected;
if (FUpdateState.Selected <> '') and (SelCount <= 1) and (GID[SelectedIndex] <> FUpdateState.Selected) then
begin
ClearSelection;
for i := 0 to ItemCount - 1 do
if GID[i] = FUpdateState.Selected then
begin
SelectedIndex := i;
Break;
end;
end;
with FUpdateState do
if RestoreSelected <> '' then
begin
RestoreSelected := '';
Perform(LVM_ENSUREVISIBLE, SelectedIndex, 0);
end;
if SelCount = 0 then
begin
SelectedIndex := ItemCount - 1; //TODO: Setting 'where to scroll'
Perform(LVM_ENSUREVISIBLE, SelectedIndex, 0);
end;
inherited;
end;
procedure TTransfersList.Update(List: TAria2Struct; Names: TStringList);
var
i, j, Image, TopItem, BottomItem: Integer;
P: PChar;
S: string;
//Pt: TPoint;
begin
TopItem := Perform(LVM_GETTOPINDEX, 0, 0);
BottomItem := TopItem + Perform(LVM_GETCOUNTPERPAGE, 0, 0);
for i := 0 to List.Length[''] - 1 do
begin
List.Index := i;
if FUpdateState.Item >= ItemCount then
begin
FUpdateState.Item := ItemAdd('');
GetMem(P, 32);
ZeroMemory(P, 32);
ItemObject[FUpdateState.Item] := TObject(P);
end;
//Perform(LVM_GETORIGIN, 0, Integer(@Pt));
if GID[FUpdateState.Item] <> List[sfGID] then
LStrCpy(PChar(ItemObject[FUpdateState.Item]), PChar(List[sfGID]))
else if (FUpdateState.Item < TopItem) or (FUpdateState.Item > BottomItem) then
begin
Inc(FUpdateState.Item); //TODO: refresh items on scrolling
Continue;
end;
for j := Low(FColumns) to High(FColumns) do
begin
S := GetFieldValue(List, Names, FColumns[j].FType, FColumns[j].Field);
if Items[FUpdateState.Item, j] <> S then
Items[FUpdateState.Item, j] := S;
end;
Image := StrToEnum(List[sfStatus], sfStatusValues);
if (TAria2Status(Image) in [asActive, asWaiting]) and Boolean(StrToEnum(List[sfSeeder], sfBoolValues)) then
Inc(Image, 6);
if Boolean(StrToEnum(List[sfVerifyPending], sfBoolValues)) or List.Has[sfVerifiedLength] then
Image := 8;
if ItemImageIndex[FUpdateState.Item] <> Image then
ItemImageIndex[FUpdateState.Item] := Image;
Inc(FUpdateState.Item);
end;
end;
procedure TTransfersList.Cleanup(Sender: TObject);
begin
Clear;
end;
procedure TTransfersList.AddTransferKey(const Column: TListColumn);
begin
AddStatusKey(FUpdateKeys, Column.Field);
end;
function TTransfersList.GetGID(Index: Integer): TAria2GID;
begin
if (Index < 0) or (Index >= ItemCount) then
Result := ''
else
Result := PChar(ItemObject[Index]);
end;
procedure TTransfersList.LoadSettings(Sender: TObject; const Args: array of const);
begin
SetArray(FUpdateKeys, BasicTransferKeys);
LoadListColumns(Self, STransferColumns, FColumns, DefTransferColumns, AddTransferKey);
end;
procedure TTransfersList.SaveSettings(Sender: TObject; const Args: array of const);
begin
SaveListColumns(Self, STransferColumns, FColumns, DefTransferColumns);
end;
procedure TTransfersList.ServerChanged(Sender: TObject; const Args: array of const);
var
State: TListState;
begin
(Args[0].VObject as TServerInfo)[SListState] := TListState.Create(GID[SelectedIndex]);
Clear;
State := (Args[1].VObject as TServerInfo)[SListState] as TListState;
if Assigned(State) then
FUpdateState.RestoreSelected := State.Selected;
(Args[1].VObject as TServerInfo)[SListState] := nil;
end;
{ TListState }
constructor TListState.Create(const S: string);
begin
Selected := S;
end;
end.
|
unit RRManagerEditCommands;
interface
uses Classes, RRManagerBaseObjects, RRManagerObjects, ClientCommon, ComCtrls,
RRmanagerPersistentObjects, RRManagerDataPosters, SysUtils, RRManagerBaseGUI,
Controls, Windows;
type
TVersionBaseSaveAction = class(TBaseAction)
public
function Execute(ABaseObject: TBaseObject): boolean; overload; override;
constructor Create(AOwner: TComponent); override;
end;
TStructureBaseSaveAction = class(TBaseAction)
public
function Execute(ABaseObject: TBaseObject): boolean; overload; override;
constructor Create(AOwner: TComponent); override;
end;
THorizonBaseSaveAction = class(TBaseAction)
public
function Execute(ABaseObject: TBaseObject): boolean; overload; override;
constructor Create(AOwner: TComponent); override;
end;
TSubstructureBaseSaveAction = class(TBaseAction)
public
function Execute(ABaseObject: TBaseObject): boolean; overload; override;
constructor Create(AOwner: TComponent); override;
end;
TLayerBaseSaveAction = class(TBaseAction)
public
function Execute(ABaseObject: TBaseObject): boolean; overload; override;
constructor Create(AOwner: TComponent); override;
end;
TBedBaseSaveAction = class(TBaseAction)
public
function Execute(ABaseObject: TBaseObject): boolean; overload; override;
constructor Create(AOwner: TComponent); override;
end;
TLicenseZoneBaseSaveAction = class(TBaseAction)
public
function Execute(ABaseObject: TBaseObject): boolean; overload; override;
constructor Create(AOwner: TComponent); override;
end;
TStructureBaseEditAction = class(TBaseAction)
public
function Execute(ABaseObject: TBaseObject): boolean; overload; override;
constructor Create(AOwner: TComponent); override;
end;
TStructureBaseDeleteAction = class(TBaseAction)
public
function Execute(ABaseObject: TBaseObject): boolean; overload; override;
constructor Create(AOwner: TComponent); override;
end;
implementation
uses RRManagerStructureInfoForm, ClientProgressBarForm, Forms, BaseDicts, Facade, LicenseZonePoster, BaseObjects;
{ TStructureBaseEditAction }
constructor TStructureBaseEditAction.Create(AOwner: TComponent);
begin
inherited;
Caption := 'Редактировать структуру';
CanUndo := false;
end;
function TStructureBaseEditAction.Execute(
ABaseObject: TBaseObject): boolean;
var actn: TStructureBaseSaveAction;
begin
Result := true;
if not Assigned(frmStructureInfo) then frmStructureInfo := TfrmStructureInfo.Create(Self);
frmStructureInfo.Prepare;
frmStructureInfo.EditingObject := ABaseObject;
if frmStructureInfo.ShowModal = mrOK then
begin
frmStructureInfo.Save;
ABaseObject := (frmStructureInfo.Dlg.Frames[0] as TbaseFrame).EditingObject;
actn := TStructureBaseSaveAction.Create(nil);
actn.Execute(ABaseObject);
actn.Free;
end;
end;
{ TStructureBaseDeleteAction }
constructor TStructureBaseDeleteAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Caption := 'Удалить структуру';
Visible := false;
end;
function TStructureBaseDeleteAction.Execute(
ABaseObject: TBaseObject): boolean;
var dp: RRManagerPersistentObjects.TDataPoster;
begin
Result := false;
if MessageBox(0, PChar('Вы действительно хотите удалить структуру ' + #13#10 +
ABaseObject.List(AllOpts.Current.ListOption, false, false) + '?'), 'Вопрос',
MB_YESNO+MB_APPLMODAL+MB_DEFBUTTON2+MB_ICONQUESTION) = ID_YES then
begin
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TStructureDataPoster];
dp.DeleteFromDB(ABaseObject);
Result := true;
end;
end;
{ TStructureBaseSaveAction }
constructor TStructureBaseSaveAction.Create(AOwner: TComponent);
begin
inherited;
Caption := 'Сохранить структуру';
CanUndo := false;
end;
function TStructureBaseSaveAction.Execute(
ABaseObject: TBaseObject): boolean;
var s: TOldStructure;
iSecondStructureTypeID: integer;
dp: RRManagerPersistentObjects.TDataPoster;
cls: RRManagerPersistentObjects.TDataPosterClass;
d: TDict;
i: integer;
begin
// показываем форму
FreeAndNil(frmProgressBar);
frmProgressBar := TfrmProgressBar.Create(Application.MainForm);
frmProgressBar.FormStyle := fsStayOnTop;
frmProgressBar.InitProgressBar('сохраняем объект в базу данных', aviCopyFile);
s := ABaseObject as TOldStructure;
iSecondStructureTypeID := s.StructureTypeID;
// берем постер
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TStructureDataPoster];
// инициализируем коллекцию
dp.PostToDB(ABaseObject);
s.PetrolRegions.Update(s.PetrolRegions);
s.Districts.Update(s.Districts);
s.TectonicStructs.Update(s.TectonicStructs);
// берем постер истории
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TStructureHistoryDataPoster];
// записываем элемент(элементы) истории
dp.PostToDB(s.History);
cls := nil;
case iSecondStructureTypeID of
// Выявленные
1: cls := TDiscoveredStructureDataPoster;
// подгтовленные
2: cls := TPreparedStructureDataPoster;
// в бурении
3: cls := TDrilledStructureDataPoster;
// месторождения
4: cls := TFieldDataPoster;
end;
if Assigned(cls) then
begin
// берем постер
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[cls];
// инициализируем коллекцию
dp.PostToDB(ABaseObject);
end;
d := (TMainFacade.GetInstance as TMainFacade).AllDicts.DictByName[UpperCase('spd_get_report_authors')];
d.Update(false, true);
d := (TMainFacade.GetInstance as TMainFacade).AllDicts.DictByName[UpperCase('spd_get_seismogroup_number')];
d.Update(false, true);
// записываем скважины - для структур в бурении
if iSecondStructureTypeID = 3 then
begin
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TDrilledStructureWellDataPoster];
dp.PostToDB((ABaseObject as TOldDrilledStructure).Wells);
end
else if iSecondStructureTypeID = 4 then
s.LicenseZones.Update(s.LicenseZones);
// берем постер и сохраняем документы
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TAccountVersionDataPoster];
// затираем версии и добавляем заново
dp.PostToDB(s.Versions);
// записываем параметры
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TParameterDataPoster];
for i := 0 to s.Versions.Count - 1 do
dp.PostToDB(s.Versions.Items[i].Parameters);
Result := true;
FreeAndNil(frmProgressBar);
end;
{ TLayerBaseBaseSaveAction }
constructor TLayerBaseSaveAction.Create(AOwner: TComponent);
begin
inherited;
Caption := 'Сохранить продуктивный пласт';
CanUndo := false;
end;
function TLayerBaseSaveAction.Execute(
ABaseObject: TBaseObject): boolean;
var dp, dpParam: RRManagerPersistentObjects.TDataPoster;
lr: TOldLayer;
i: integer;
begin
// показываем форму
FreeAndNil(frmProgressBar);
frmProgressBar := TfrmProgressBar.Create(Application.MainForm);
frmProgressBar.FormStyle := fsStayOnTop;
frmProgressBar.InitProgressBar('сохраняем объект в базу данных', aviCopyFile);
// берем постер
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TLayerDataPoster];
// сохраняем подструктуру
dp.PostToDB(ABaseObject);
lr := ABaseObject as TOldLayer;
// берем постер и сохраняем документы
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TAccountVersionDataPoster];
// добавляем новые версии, но не затираем старые
dp.PostToDB(lr.Versions, false);
if assigned(lr.Substructure) then
begin
// затираем все
// ресурсы, запасы и параметры
// и добавляем заново
// берем еще один постер и сохраняем ресурсы
// по каждому из документов
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TResourceDataPoster];
dpParam := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TParameterDataPoster];
for i := 0 to lr.Versions.Count - 1 do
begin
dp.PostToDB(lr.Versions.Items[i].Resources);
dpParam.PostToDB(lr.Versions.Items[i].Parameters);
end;
end
else
if Assigned(lr.Bed) then
begin
// затираем все
// ресурсы, запасы и параметры
// и добавляем заново
// берем еще один постер и сохраняем ресурсы
// по каждому из документов
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TReserveDataPoster];
dpParam := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TParameterDataPoster];
for i := 0 to lr.Versions.Count - 1 do
begin
dp.PostToDB(lr.Versions.Items[i].Reserves);
dpParam.PostToDB(lr.Versions.Items[i].Parameters);
end;
end;
Result := true;
FreeAndNil(frmProgressBar);
end;
{ TSubstructureBaseSaveAction }
constructor TSubstructureBaseSaveAction.Create(AOwner: TComponent);
begin
inherited;
Caption := 'Сохранить подструктуру';
CanUndo := false;
end;
function TSubstructureBaseSaveAction.Execute(
ABaseObject: TBaseObject): boolean;
var dp: RRManagerPersistentObjects.TDataPoster;
s: TOldSubstructure;
i: integer;
begin
// показываем форму
FreeAndNil(frmProgressBar);
frmProgressBar := TfrmProgressBar.Create(Application.MainForm);
frmProgressBar.FormStyle := fsStayOnTop;
frmProgressBar.InitProgressBar('сохраняем объект в базу данных', aviCopyFile);
// берем постер
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TSubstructureDataPoster];
// сохраняем подструктуру
dp.PostToDB(ABaseObject);
s := ABaseObject as TOldSubstructure;
// берем постер и сохраняем документы
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TAccountVersionDataPoster];
// затираем версии и добавляем заново
dp.PostToDB(s.Versions);
// записываем параметры
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TParameterDataPoster];
for i := 0 to s.Versions.Count - 1 do
dp.PostToDB(s.Versions.Items[i].Parameters);
Result := true;
FreeAndNil(frmProgressBar);
end;
{ THorizonBaseSaveAction }
constructor THorizonBaseSaveAction.Create(AOwner: TComponent);
begin
inherited;
Caption := 'Сохранить горизонт';
CanUndo := false;
end;
function THorizonBaseSaveAction.Execute(ABaseObject: TBaseObject): boolean;
var dp: RRManagerPersistentObjects.TDataPoster;
h: TOldHorizon;
i: integer;
begin
// показываем форму
FreeAndNil(frmProgressBar);
frmProgressBar := TfrmProgressBar.Create(Application.MainForm);
frmProgressBar.FormStyle := fsStayOnTop;
frmProgressBar.InitProgressBar('сохраняем объект в базу данных', aviCopyFile);
// берем постер
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[THorizonDataPoster];
// инициализируем коллекцию
dp.PostToDB(ABaseObject);
h := ABaseObject as TOldHorizon;
// записываем коллекцию фондов
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[THorizonFundTypeDataPoster];
dp.PostToDB(h.FundTypes, true);
// берем постер и сохраняем документы
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TAccountVersionDataPoster];
// затираем версии и добавляем заново
dp.PostToDB(h.Versions);
// записываем параметры
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TParameterDataPoster];
for i := 0 to h.Versions.Count - 1 do
dp.PostToDB(h.Versions.Items[i].Parameters);
Result := true;
FreeAndNil(frmProgressBar);
end;
{ TBedBaseSaveAction }
constructor TBedBaseSaveAction.Create(AOwner: TComponent);
begin
inherited;
Caption := 'Сохранить залежь';
CanUndo := false;
end;
function TBedBaseSaveAction.Execute(ABaseObject: TBaseObject): boolean;
var dp, dpd: RRManagerPersistentObjects.TDataPoster;
b: TOldBed;
i: integer;
begin
// показываем форму
FreeAndNil(frmProgressBar);
frmProgressBar := TfrmProgressBar.Create(Application.MainForm);
frmProgressBar.FormStyle := fsStayOnTop;
frmProgressBar.InitProgressBar('сохраняем объект в базу данных', aviCopyFile);
// берем постер
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TBedDataPoster];
// сохраняем подструктуру
dp.PostToDB(ABaseObject);
b := ABaseObject as TOldBed;
// сохраняем слои
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TLayerDataPoster];
dp.PostToDB(b.Layers);
// берем постер и сохраняем документы
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TAccountVersionDataPoster];
// затираем версии и добавляем заново
dp.PostToDB(b.Versions);
// записываем параметры
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TParameterDataPoster];
dpd := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TReserveDataPoster];
for i := 0 to b.Versions.Count - 1 do
begin
dpd.PostToDB(b.Versions.Items[i].Reserves);
dp.PostToDB(b.Versions.Items[i].Parameters);
end;
Result := true;
FreeAndNil(frmProgressBar);
end;
{ TVersionBaseSaveAction }
constructor TVersionBaseSaveAction.Create(AOwner: TComponent);
begin
inherited;
Caption := 'Сохранить версию';
CanUndo := false;
end;
function TVersionBaseSaveAction.Execute(ABaseObject: TBaseObject): boolean;
var dp: RRManagerPersistentObjects.TDataPoster;
begin
Result := true;
// берем постер
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TVersionDataPoster];
// инициализируем коллекцию
dp.PostToDB(ABaseObject);
end;
{ TLicenseZoneBaseSaveAction }
constructor TLicenseZoneBaseSaveAction.Create(AOwner: TComponent);
begin
inherited;
Caption := 'Сохранить лицензионный участок';
CanUndo := false;
end;
function TLicenseZoneBaseSaveAction.Execute(
ABaseObject: TBaseObject): boolean;
var dp: RRManagerPersistentObjects.TDataPoster;
ndp: TDataPoster;
lz: TOldLicenseZone;
i: integer;
begin
// показываем форму
FreeAndNil(frmProgressBar);
frmProgressBar := TfrmProgressBar.Create(Application.MainForm);
frmProgressBar.FormStyle := fsStayOnTop;
frmProgressBar.InitProgressBar('сохраняем объект в базу данных', aviCopyFile);
// берем постер
dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TLicenseZoneDataPoster];
// сохраняем подструктуру
dp.PostToDB(ABaseObject);
lz := ABaseObject as TOldLicenseZone;
{ lz := ABaseObject as TOldLicenseZone;
dp := AllPosters.Posters[TAccountVersionDataPoster];
// затираем версии и добавляем заново
dp.PostToDB(lz.Versions);
// записываем параметры
dp := AllPosters.Posters[TParameterDataPoster];
for i := 0 to lz.Versions.Count - 1 do
dp.PostToDB(lz.Versions.Items[i].Parameters);}
ndp := TMainFacade.GetInstance.DataPosterByClassType[TLicenseConditionValuePoster];
for i := 0 to lz.LicenseConditionValues.DeletedObjects.Count - 1 do
ndp.DeleteFromDB(lz.LicenseConditionValues.DeletedObjects.Items[i], lz.LicenseConditionValues);
ndp.PostToDB(lz.LicenseConditionValues, nil);
Result := true;
FreeAndNil(frmProgressBar);
end;
end.
|
{$include kode.inc}
unit kode_surface_cairo;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
{$ifdef KODE_LINUX} X, Xlib, CairoXlib, {$endif}
{$ifdef KODE_WIN32} Windows, CairoWin32, {$endif}
Cairo,
kode_surface_base;
type
KSurface_Cairo = class(KSurface_Base)
private
FSurface : Pcairo_surface_t;
FWidth : longint;
FHeight : longint;
FDepth : longint;
public
property _surface : Pcairo_surface_t read FSurface;
property _width : longint read FWidth;
property _height : longint read FHeight;
public
constructor create(AWidth,AHeight,ADepth:LongInt);
constructor create(ASurface:KSurface_Base{_Cairo}; AWidth,AHeight:LongInt);
//constructor create(AFilename:PChar);
destructor destroy; override;
{$ifdef KODE_LINUX}
//constructor create;
constructor create(ADisplay:PDisplay; ADrawable:TDrawable; AVisual:PVisual; AWidth,AHeight:longint);
//constructor create(ADisplay:PDisplay; APixmap:TPixmap; AScreen:PScreen; AWidth,AHeight:longint);
procedure setSize(AWidth,AHeight:longint);
{$endif}
{$ifdef KODE_WIN32}
constructor create(hdc:HDC);
constructor create(hdc:HDC; AWidth,AHeight,ADepth:LongInt);
constructor create(AWidth,AHeight,ADepth:LongInt);
procedure setSize(AWidth,AHeight:longint);
{$endif}
end;
//----------
KSurface_Implementation = KSurface_Cairo;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
constructor KSurface_Cairo.create(AWidth,AHeight,ADepth:LongInt);
var
fmt : cairo_format_t;
begin
inherited create;
FWidth := AWidth;
FHeight := AHeight;
FDepth := ADepth;
//fmt := CAIRO_FORMAT_ARGB32;
case ADepth of
1 : fmt := CAIRO_FORMAT_A1;
8 : fmt := CAIRO_FORMAT_A8;
24 : fmt := CAIRO_FORMAT_RGB24;
32 : fmt := CAIRO_FORMAT_ARGB32;
end;
cairo_image_surface_create(fmt,AWidth,AHeight);
end;
//----------
constructor KSurface_Cairo.create(ASurface:KSurface_Base{_Cairo}; AWidth,AHeight:LongInt);
var
sc : KSurface_Cairo;
begin
inherited create;
sc := ASurface as KSurface_Cairo;;
FSurface := cairo_surface_create_similar(sc._surface,CAIRO_CONTENT_COLOR_ALPHA,AWidth,AHeight);
FWidth := AWidth;
FHeight := AHeight;
//FDepth := 0;
end;
//----------
{constructor ZCairoSurface.create(AFilename:PChar);
begin
inherited create;
FSurface := cairo_image_surface_create_from_png(AFilename);
end;}
//----------------------------------------
destructor KSurface_Cairo.destroy;
begin
cairo_surface_destroy(FSurface);
inherited;
end;
//----------------------------------------------------------------------
// linux
//----------------------------------------------------------------------
{$ifdef KODE_LINUX}
{
Creates an Xlib surface that draws to the given drawable. The way that colors
are represented in the drawable is specified by the provided visual.
Note: If drawable is a Window, then the function
cairo_xlib_surface_set_size() must be called whenever the size of the
window changes.
drawable: an X Drawable, (a Pixmap or a Window)
visual: the visual to use for drawing to drawable. The depth of the visual
must match the depth of the drawable. Currently, only TrueColor visuals are
fully supported.
}
constructor KSurface_Cairo.create(ADisplay:PDisplay; ADrawable:TDrawable; AVisual:PVisual; AWidth,AHeight:longint);
begin
inherited create;
FSurface := cairo_xlib_surface_create(ADisplay,ADrawable,AVisual,AWidth,AHeight);
FWidth := AWidth;
FHeight := AHeight;
//FDepth := 0;
end;
//----------
{
Creates an Xlib surface that draws to the given bitmap. This will be drawn to
as a CAIRO_FORMAT_A1 object.
pixmap : an X Drawable, (a depth-1 Pixmap)
}
//constructor KSurface_Cairo.create(ADisplay:PDisplay; APixmap:TPixmap; AScreen:PScreen; AWidth,AHeight:longint);
//begin
// inherited create;
// cairo_xlib_surface_create_for_bitmap(ADisplay,APixmap,AScreen,AWidth,AHeight);
//end;
//----------
{
Informs cairo of the new size of the X Drawable underlying the surface. For
a surface created for a Window (rather than a Pixmap), this function must be
called each time the size of the window changes. (For a subwindow, you are
normally resizing the window yourself, but for a toplevel window, it is
necessary to listen for ConfigureNotify events.)
A Pixmap can never change size, so it is never necessary to call this
function on a surface created for a Pixmap.
}
procedure KSurface_Cairo.setSize(AWidth,AHeight:longint);
begin
cairo_xlib_surface_set_size(FSurface,AWidth,AHeight);
FWidth := AWidth;
FHeight := AHeight;
end;
//----------
{
Informs cairo of a new X Drawable underlying the surface. The drawable must
match the display, screen and format of the existing drawable or the
application will get X protocol errors and will probably terminate. No
checks are done by this function to ensure this compatibility.
}
// void cairo_xlib_surface_set_drawable(cairo_surface_t *surface, Drawable drawable, int width, int height);
//----------
{
Get the underlying X Drawable used for the surface.
}
// Drawable cairo_xlib_surface_get_drawable(cairo_surface_t *surface);
//----------
{
Get the X Display for the underlying X Drawable.
}
// Display* cairo_xlib_surface_get_display(cairo_surface_t *surface);
//----------
{
Get the X Screen for the underlying X Drawable.
}
// Screen* cairo_xlib_surface_get_screen(cairo_surface_t *surface);
//----------
{
Gets the X Visual associated with surface, suitable for use with the
underlying X Drawable. If surface was created by cairo_xlib_surface_create(),
the return value is the Visual passed to that constructor.
Returns: the Visual or NULL if there is no appropriate Visual for surface.
}
// Visual* cairo_xlib_surface_get_visual(cairo_surface_t *surface);
//----------
{
Get the width of the X Drawable underlying the surface in pixels.
}
// int cairo_xlib_surface_get_width(cairo_surface_t *surface);
//----------
{
Get the height of the X Drawable underlying the surface in pixels.
}
// int cairo_xlib_surface_get_height(cairo_surface_t *surface);
//----------
{
Get the number of bits used to represent each pixel value.
}
// int cairo_xlib_surface_get_depth(cairo_surface_t *surface);
//----------
{$endif} // KODE_LINUX
//----------------------------------------------------------------------
// win32
//----------------------------------------------------------------------
{$ifdef KODE_WIN32}
{
Creates a cairo surface that targets the given DC. The DC will be queried for
its initial clip extents, and this will be used as the size of the cairo
surface. The resulting surface will always be of format CAIRO_FORMAT_RGB24
}
constructor KSurface_Cairo.create(hdc:HDC);
begin
inherited create;
FSurface := cairo_win32_surface_create(hdc);
//FWidth := 0;
//FHeight := 0;
//FDepth := 0; // 24
end;
//----------
{
Creates a device-independent-bitmap surface not associated with any particular
existing surface or device context. The created bitmap will be uninitialized.
}
constructor KSurface_Cairo.create(hdc:HDC; AWidth,AHeight,ADepth:LongInt);
var
fmt : cairo_format_t;
begin
inherited create;
case ADepth of
1: fmt := CAIRO_FORMAT_A1;
8: fmt := CAIRO_FORMAT_A8;
24: fmt := CAIRO_FORMAT_RGB24;
32: fmt := CAIRO_FORMAT_ARGB32;
end;
FSurface := cairo_win32_surface_create_with_ddb(hdc,fmt,AWidth,AHeight);
FWidth := AWidth;
FHeight := AHeight;
FDepth := ADepth;
end;
//----------
{
Creates a device-independent-bitmap surface not associated with any particular
existing surface or device context. The created bitmap will be uninitialized.
}
constructor KSurface_Cairo.create(AWidth,AHeight,ADepth:LongInt);
var
fmt : cairo_format_t;
begin
inherited create;
case ADepth of
1: fmt := CAIRO_FORMAT_A1;
8: fmt := CAIRO_FORMAT_A8;
24: fmt := CAIRO_FORMAT_RGB24;
32: fmt := CAIRO_FORMAT_ARGB32;
end;
FSurface := cairo_win32_surface_create_with_dib(fmt,AWidth,AHeight);
FWidth := AWidth;
FHeight := AHeight;
FDepth := ADepth;
end;
//------------------------------
destructor KSurface_Cairo.destroy;
begin
cairo_surface_destroy(FSurface);
inherited;
end;
//------------------------------
procedure KSurface_Cairo.setSize(AWidth,AHeight:longint);
begin
FWidth := AWidth;
FHeight := AHeight;
end;
{$endif} // KODE_WIN32
//----------------------------------------------------------------------
end.
|
unit VSECore;
//TODO: edit all log messages
interface
uses
Windows, Messages, MMSystem, AvL, avlMath, avlUtils, OpenGL, oglExtensions,
VSEOpenGLExt, VSEImageCodec {$IFDEF VSE_LOG}, VSELog{$ENDIF};
type
//Events
TCoreEvent = class // Base event class
protected
FSender: TObject;
{$IFDEF VSE_LOG}function GetDump: string; virtual;{$ENDIF}
public
constructor Create(Sender: TObject = nil);
property Sender: TObject read FSender; //Event sender
{$IFDEF VSE_LOG}property Dump: string read GetDump;{$ENDIF}
end;
TMouseEvents=(meDown, meUp, meMove, meWheel); //Mouse events: button pressed, button release, mouse moving, mouse wheel
TMouseEvent = class(TCoreEvent) //Mouse event
protected
FButton: Integer;
FEvType: TMouseEvents;
FCursor: TPoint;
{$IFDEF VSE_LOG}function GetDump: string; override;{$ENDIF}
public
constructor Create(Sender: TObject; Button: Integer; EvType: TMouseEvents; Cursor: TPoint);
property Button: Integer read FButton; //Mouse button number or wheel click if Event=meWheel
property EvType: TMouseEvents read FEvType; //Event type
property Cursor: TPoint read FCursor; //Mouse cursor coordinates or cursor coordinates delta if Core.MouseCapture=true
end;
TKeyEvents=(keDown, keUp); //Keyboard events: key pressed, key released
TKeyEvent = class(TCoreEvent) //Keyboard event
protected
FKey: Integer;
FEvType: TKeyEvents;
{$IFDEF VSE_LOG}function GetDump: string; override;{$ENDIF}
public
constructor Create(Sender: TObject; Key: Integer; EvType: TKeyEvents);
property Key: Integer read FKey; //Virtual key code
property EvType: TKeyEvents read FEvType; //Event type
end;
TCharEvent = class(TCoreEvent) //Keyboard character event
protected
FChr: Char;
{$IFDEF VSE_LOG}function GetDump: string; override;{$ENDIF}
public
constructor Create(Sender: TObject; Chr: Char);
property Chr: Char read FChr;
end;
TSysNotifies=( //System notifies:
snMinimized, //Application minimized
snMaximized, //Application maximized
snUpdateOverload, //Update Overload Detection triggered
snPause, //Engine paused
snResume, //Engine resumed
snResolutionChanged, //Resolution changed
snStateChanged, //State changed
snLogSysInfo //Write system info to log
);
TSysNotify = class(TCoreEvent) //System notify
protected
FNotify: TSysNotifies;
{$IFDEF VSE_LOG}function GetDump: string; override;{$ENDIF}
public
constructor Create(Sender: TObject; Notify: TSysNotifies);
property Notify: TSysNotifies read FNotify; //Notification code
end;
PStream = ^TStream;
TGetFileEvent = class(TCoreEvent)
protected
FFileName: string;
FResult: PStream;
procedure SetResult(Result: TStream);
{$IFDEF VSE_LOG}function GetDump: string; override;{$ENDIF}
public
constructor Create(Sender: TObject; const FileName: string; Result: PStream);
property FileName: string read FFileName;
property Result: TStream write SetResult;
end;
TCoreModule=class
public
procedure Draw; virtual; //Draw handler
procedure Update; virtual; //Update handler
procedure OnEvent(var Event: TCoreEvent); virtual; //Events handler; FreeAndNil event to stop furhter dispatching
end;
TGameState = class(TCoreModule) //Base state class
protected
function GetName: string; virtual; abstract; //Must return state name
public
procedure OnEvent(var Event: TCoreEvent); override;
function Activate: Cardinal; virtual; //Activate handler (triggered on switching to state), must return updates interval
procedure Deactivate; virtual; //Deactiovate handler (triggered on switching from state)
property Name: string read GetName; //State name
end;
TModule = class(TCoreModule) //Base engine module class
public
constructor Create; virtual;
class function Name: string; virtual; abstract; //Must return module name
end;
CModule=class of TModule;
TStopState=( //Engine stop codes
StopNormal, //Engine stopped normally
StopDefault, //Engine stopped by something other than StopEngine
StopNeedRestart, //Engine needs restart
//Critical errors
StopInitError, //Cannot initialize engine
StopInternalError, //Internal engine error
StopUserException, //Engine stopped due to unhandled exception in user code
StopDisplayModeError, //Engine stopped due to error when setting display mode
StopUserError //Engine stopped by user code due to error
);
TEventReceiver=(erModule, erState);
TEventReceivers=set of TEventReceiver;
TCore=class
private
FHandle: THandle;
FDC: HDC;
FRC: HGLRC;
FResolutionX: Cardinal;
FResolutionY: Cardinal;
FRefreshRate: Cardinal;
FColorDepth: Cardinal;
FFramesCount, FFPS, FFPSTimer, FPreviousUpdate, FUpdInt, FUpdOverloadCount, FUpdOverloadThreshold: Cardinal;
FHPETFreq: Int64;
FStates: array of TGameState;
FModules: array of TModule;
FState, FSwitchTo: Cardinal;
FCurState: TGameState;
FPrevStateName: string;
FFullscreen, FNeedSwitch, FMinimized, FPaused, FMouseCapture, FInhibitUpdate: Boolean;
FKeyState: TKeyboardState;
FSavedMousePos: TPoint;
procedure SetFullscreen(Value: Boolean);
function GetCaption: string;
procedure SetCaption(const Value: string);
function GetVSync: Boolean;
procedure SetVSync(Value: Boolean);
procedure SetState(Value: Cardinal);
function GetKeyPressed(Index: Byte): Boolean;
procedure SetMouseCapture(Value: Boolean);
function GetMouseCursor: TPoint;
function GetTime: Cardinal;
procedure ResetMouse;
{$IFDEF VSE_CONSOLE}
function QuitHandler(Sender: TObject; Args: array of const): Boolean;
function StateHandler(Sender: TObject; Args: array of const): Boolean;
function ResolutionHandler(Sender: TObject; Args: array of const): Boolean;
function FullscreenHandler(Sender: TObject; Args: array of const): Boolean;
function VSyncHandler(Sender: TObject; Args: array of const): Boolean;
function ScreenshotHandler(Sender: TObject; Args: array of const): Boolean;
{$ENDIF}
protected
procedure StartEngine;
procedure SaveSettings;
procedure Update;
procedure Resume;
procedure MouseEvent(Button: Integer; Event: TMouseEvents; X, Y: Integer);
procedure KeyEvent(Key: Integer; Event: TKeyEvents);
procedure CharEvent(C: Char);
public
constructor Create(WndHandle: THandle); //internally used
destructor Destroy; override; //internally used
procedure StopEngine(StopState: TStopState = StopNormal); //Stop engine with stop code StopState and quit
procedure SendEvent(Event: TCoreEvent; Receivers: TEventReceivers = [erModule, erState]); //Send event
{State manager}
function AddState(State: TGameState): Cardinal; //Add state object, returns state index
function ReplaceState(OrigState: Cardinal; NewState: TGameState): Boolean; //Replace state at index OrigState with state object NewState; returns true if success
procedure DeleteState(State: Cardinal); //Delete state, may change indices of other states
procedure SwitchState(NewState: Cardinal); overload; //Switch to state by state index
procedure SwitchState(const NewStateName: string); overload; //Switch to state by state name
function StateExists(State: Cardinal): Boolean; //Returns true if exists state with supplied index
function GetState(State: Cardinal): TGameState; //Returns state object by index
function FindState(const Name: string): Cardinal; //Returns state index by state name or InvalidState if state not found
{Misc.}
function KeyRepeat(Key: Byte; Rate: Integer; var KeyVar: Cardinal): Boolean; //Returns true if Key pressed, but no more often then Rate; KeyVar - counter for rate limiting
procedure SetResolution(ResolutionX, ResolutionY, RefreshRate: Cardinal; Fullscreen: Boolean; CanReset: Boolean = true); //Set resolution ResX*ResY@Refresh; CanReset: return to previous resolution if fail
procedure MakeScreenshot(Name: string; Format: TImageFormat; Numerate: Boolean = true); //Makes screenshot in exe folder; Name: screentshot file name; Format: screenshot file format; Numerate: append counter to name
procedure ResetUpdateTimer; //Reset update timer and clear pending updates
function GetFile(const FileName: string): TStream; //Get file as stream
function GetFileText(const FileName: string): TStringList; //Get text file as TStringList
///
property Caption: string read GetCaption write SetCaption;
property Handle: THandle read FHandle; //Engine window handle
property DC: HDC read FDC; //Engine window GDI device context
property RC: HGLRC read FRC; //Engine window OpenGL rendering context
property ResolutionX: Cardinal read FResolutionX; //Horizontal resolution of viewport
property ResolutionY: Cardinal read FResolutionY; //Vertical resolution of viewport
property RefreshRate: Cardinal read FRefreshRate; //Screen refresh rate, fullscreen only
property ColorDepth: Cardinal read FColorDepth write FColorDepth; //Color depth, applied after engine restart
property Fullscreen: Boolean read FFullscreen write SetFullscreen; //Fullscreen mode
property VSync: Boolean read GetVSync write SetVSync; //Vertical synchronization
property Minimized: Boolean read FMinimized; //Engine window minimized
property Paused: Boolean read FPaused write FPaused; //Engine paused; do not write
property KeyPressed[Index: Byte]: Boolean read GetKeyPressed; //True if Key pressed
property MouseCapture: Boolean read FMouseCapture write SetMouseCapture; //Mouse capture mode
property MouseCursor: TPoint read GetMouseCursor; //Mouse cursor coordinates relative to engine window
property Time: Cardinal read GetTime; //Current time in ms
property State: Cardinal read FState write SetState; //Current state index
property CurState: TGameState read FCurState; //Current state object
property PrevStateName: string read FPrevStateName; //Name of previous state
property InhibitUpdate: Boolean read FInhibitUpdate write FInhibitUpdate; //Inhibit next State.Update
property FPS: Cardinal read FFPS; //Current FPS
property UpdateInterval: Cardinal read FUpdInt write FUpdInt; //Current state updates interval
property UpdateOverloadThreshold: Cardinal read FUpdOverloadThreshold write FUpdOverloadThreshold; //Update Overload Detection threshold, overloaded update cycles before triggering
end;
TSettings=class
private
FFirstRun: Boolean;
FIni: TIniFile;
function GetBool(const Section, Name: string): Boolean;
function GetInt(const Section, Name: string): Integer;
function GetStr(const Section, Name: string): string;
procedure SetBool(const Section, Name: string; const Value: Boolean);
procedure SetInt(const Section, Name: string; const Value: Integer);
procedure SetStr(const Section, Name: string; const Value: string);
public
constructor Create;
destructor Destroy; override;
procedure ReloadInitSettings; //Reload InitSettings from ini
function ReadSection(const Section: string): TStringList; //Read section contents to TStringList
procedure EraseSection(const Section: string); //Erase section
property FirstRun: Boolean read FFirstRun; //True if ini file wasn't exist at time of engine's start
property Bool[const Section, Name: string]: Boolean read GetBool write SetBool; //Read/write Boolean value
property Int[const Section, Name: string]: Integer read GetInt write SetInt; //Read/write Integer value
property Str[const Section, Name: string]: string read GetStr write SetStr; //Read/write String value
end;
TInitStates=procedure;
TInitSettings=record
InitStates: TInitStates; //Init states procedure pointer
Caption: string; //Engine window caption
Version: string; //Application version
DataDir: string; //Data directory (absolute path with trailing backslash)
ResolutionX: Integer; //Horizontal resolution
ResolutionY: Integer; //Vertical resolution
RefreshRate: Integer; //Screen refresh rate, fullscreen only
ColorDepth: Integer; //Color depth
Fullscreen: Boolean; //Fullscreen mode
VSync: Boolean; //Vertical synchronization
end;
function VSEStart: TStopState; //Start engine, returns engine stop code
procedure LogException(Comment: string); //Writes current exception info to log, followed by Comment. Call only in except block
procedure RegisterModule(Module: CModule); //Register engine module
var
Core: TCore; //Global variable for accessing to Engine Core
Settings: TSettings; //Interface to engine's ini file
InitSettings: TInitSettings = ( //Engine pre-init settings
InitStates: nil;
Caption: '';
Version: '';
DataDir: '';
ResolutionX: 640;
ResolutionY: 480;
RefreshRate: 0;
ColorDepth: 32;
Fullscreen: false;
VSync: true;
);
const
UM_STOPENGINE = WM_USER;
InvalidState = $FFFFFFFF; //Non-existing state index
StopCodeNames: array[TStopState] of string =
('Normal', 'Default', 'Need Restart', 'Init Error', 'Internal Error', 'User Exception', 'Display Mode Error', 'User Error');
SysNotifyNames: array[TSysNotifies] of string =
('snMinimized', 'snMaximized', 'snUpdateOverload', 'snPause', 'snResume', 'snResolutionChanged', 'snStateChanged', 'snLogSysInfo');
MouseEventNames: array[TMouseEvents] of string =
('meDown', 'meUp', 'meMove', 'meWheel');
KeyEventNames: array[TKeyEvents] of string =
('keDown', 'keUp');
VSECaptVer = 'reduced VS Engine 1.0';
SSectionSettings = 'Settings';
mbLeft = 1; //Left mouse button
mbRight = 2; //Right mouse button
mbMiddle = 3; //Middle mouse button
mbX1 = 4; //Fourth mouse button
mbX2 = 5; //Fifth mouse button
implementation
{$IFDEF VSE_CONSOLE}
uses
VSEConsole;
{$ENDIF}
const
WindowedWindowStyle = WS_OVERLAPPED or WS_CAPTION or WS_SYSMENU or WS_CLIPCHILDREN or WS_CLIPSIBLINGS;
MinResolutionX = 640;
MinResolutionY = 480;
DefaultOverloadThreshold = 8;
WndClassName: PChar = 'VSENGINE';
WM_XBUTTONDOWN=$20B;
WM_XBUTTONUP=$20C;
SNameColorDepth = 'ColorDepth';
SNameFullscreen = 'Fullscreen';
SNameRefreshRate = 'RefreshRate';
SNameResolutionY = 'ResolutionY';
SNameResolutionX = 'ResolutionX';
SNameVSync = 'VSync';
var
Mutex: Integer=0;
VSEStopState: TStopState=StopNormal;
Modules: array of CModule;
{$IFNDEF VSE_NOSYSINFO}SysInfoLogged: Boolean = false;{$ENDIF}
procedure LogErrorAndShowMessage(Msg: string);
begin
{$IFDEF VSE_LOG}Log(llError, Msg);{$ENDIF}
MessageBox(0, PChar(Msg), PChar(InitSettings.Caption), MB_ICONERROR);
end;
procedure LogException(Comment: string);
begin
Comment:=Format('Exception "%s" at $%s with message "%s" %s', [string(ExceptObject.ClassName), IntToHex(Cardinal(ExceptAddr), 8), Exception(ExceptObject).Message, Comment]);
{$IFDEF VSE_LOG}Log(llError, Comment);{$ENDIF}
{$IFNDEF VSE_DEBUG}MessageBox(0, PChar(Comment), PChar(InitSettings.Caption), MB_ICONERROR);{$ENDIF}
end;
procedure UpdateFPS(uID, uMsg, dwUser, dw1, dw2: Cardinal); stdcall;
begin
Core.FFPS:=Core.FFramesCount;
Core.FFramesCount:=0;
end;
{ TCoreEvent }
constructor TCoreEvent.Create(Sender: TObject);
begin
inherited Create;
FSender := Sender;
end;
{$IFDEF VSE_LOG}
function TCoreEvent.GetDump: string;
begin
Result := ClassName;
end;
{$ENDIF}
{ TMouseEvent }
constructor TMouseEvent.Create(Sender: TObject; Button: Integer; EvType: TMouseEvents; Cursor: TPoint);
begin
inherited Create(Sender);
FButton := Button;
FEvType := EvType;
FCursor := Cursor;
end;
{$IFDEF VSE_LOG}
function TMouseEvent.GetDump: string;
begin
Result := Format('%s(Btn=%d Ev=%s X=%d Y=%d)', [string(ClassName), FButton, MouseEventNames[FEvType], Cursor.X, Cursor.Y]);
end;
{$ENDIF}
{ TKeyEvent }
constructor TKeyEvent.Create(Sender: TObject; Key: Integer; EvType: TKeyEvents);
begin
inherited Create(Sender);
FKey := Key;
FEvType := EvType;
end;
{$IFDEF VSE_LOG}
function TKeyEvent.GetDump: string;
begin
Result := Format('%s(Key=%d Ev=%s)', [string(ClassName), FKey, KeyEventNames[FEvType]]);
end;
{$ENDIF}
{ TCharEvent }
constructor TCharEvent.Create(Sender: TObject; Chr: Char);
begin
inherited Create(Sender);
FChr := Chr;
end;
{$IFDEF VSE_LOG}
function TCharEvent.GetDump: string;
begin
Result := Format('%s(Chr=0x%02x)', [string(ClassName), Ord(FChr)]);
end;
{$ENDIF}
{ TSysNotify }
constructor TSysNotify.Create(Sender: TObject; Notify: TSysNotifies);
begin
inherited Create(Sender);
FNotify := Notify;
end;
{$IFDEF VSE_LOG}
function TSysNotify.GetDump: string;
begin
Result := Format('%s(Notify=%s)', [string(ClassName), SysNotifyNames[FNotify]]);
end;
{$ENDIF}
{ TGetFileEvent }
constructor TGetFileEvent.Create(Sender: TObject; const FileName: string; Result: PStream);
begin
inherited Create(Sender);
FFileName := FileName;
FResult := Result;
end;
procedure TGetFileEvent.SetResult(Result: TStream);
begin
if not Assigned(FResult) or not Assigned(Result) then Exit;
if Assigned(FResult^) then
FreeAndNil(FResult^);
FResult^ := Result;
end;
{$IFDEF VSE_LOG}
function TGetFileEvent.GetDump: string;
begin
Result := Format('%s(File="%s")', [string(ClassName), FFileName]);
end;
{$ENDIF}
{ TCoreModule }
procedure TCoreModule.Draw;
begin
end;
procedure TCoreModule.Update;
begin
end;
procedure TCoreModule.OnEvent(var Event: TCoreEvent);
begin
end;
{ TGameState }
procedure TGameState.OnEvent(var Event: TCoreEvent);
begin
inherited;
if (Event is TSysNotify) then
case (Event as TSysNotify).Notify of
snUpdateOverload: Core.ResetUpdateTimer; //Override to implement your own UpdateOverload handler
snMinimized: Core.Paused := true; //Override to disable core pausing on minimizing window
end;
end;
function TGameState.Activate: Cardinal;
begin
Result := 50;
end;
procedure TGameState.Deactivate;
begin
end;
{ TModule }
constructor TModule.Create;
begin
inherited;
end;
{ TCore }
constructor TCore.Create(WndHandle: THandle);
begin
inherited Create;
FPaused:=true;
FMinimized:=false;
FNeedSwitch:=false;
FState:=InvalidState;
FStates:=nil;
FModules:=nil;
FCurState:=nil;
FHandle:=WndHandle;
FFullscreen:=false;
FFPS:=0;
FFramesCount:=0;
{$IFDEF VSE_LOG}if not{$ENDIF}
QueryPerformanceFrequency(FHPETFreq)
{$IFDEF VSE_LOG}then Log(llWarning, 'HPET not available, using GTC'){$ENDIF};
FPreviousUpdate:=0;
FUpdOverloadCount:=0;
FUpdOverloadThreshold:=DefaultOverloadThreshold;
end;
destructor TCore.Destroy;
var
i: Integer;
Name: string;
begin
SaveSettings;
for i:=0 to High(FStates) do
try
Name:=FStates[i].Name;
FAN(FStates[i]);
except
LogException('in state '+Name+'.Free');
end;
Finalize(FStates);
for i:=High(FModules) downto 0 do
try
if not Assigned(FModules[i]) then Continue;
Name:=FModules[i].Name;
{$IFDEF VSE_LOG}Log(llInfo, 'Finalizing module '+Name);{$ENDIF}
FAN(FModules[i]);
except
LogException('in module '+Name+'.Free');
end;
Finalize(FModules);
{$IFDEF VSE_CONSOLE}FAN(Console);{$ENDIF}
if FFullscreen then gleGoBack;
wglMakeCurrent(FDC, 0);
wglDeleteContext(FRC);
if FDC>0 then ReleaseDC(FHandle, FDC);
timeKillEvent(FFPSTimer);
inherited Destroy;
end;
//Protected - interacting with WndProc
procedure TCore.StartEngine;
var
i: Integer;
begin
//FFullscreen:=InitSettings.Fullscreen;
if InitSettings.ResolutionX<MinResolutionX then InitSettings.ResolutionX:=MinResolutionX;
if InitSettings.ResolutionY<MinResolutionY then InitSettings.ResolutionY:=MinResolutionY;
if InitSettings.RefreshRate=0 then InitSettings.RefreshRate:=gleGetCurrentResolution.RefreshRate;
FColorDepth:=InitSettings.ColorDepth;
FDC:=GetDC(FHandle);
FRC:=gleSetPix(FDC, FColorDepth);
if FRC=0 then raise Exception.Create('Unable to set rendering context');
{$IFDEF VSE_CONSOLE}
Console:=TConsole.Create;
Console['quit']:=QuitHandler;
Console['state ?state=s']:=StateHandler;
Console['resolution ?resx=i640:65536 ?resy=i480:65536 ?refr=i0']:=ResolutionHandler;
Console['fullscreen ?val=eoff:on']:=FullscreenHandler;
Console['vsync ?val=eoff:on']:=VSyncHandler;
Console['screenshot ?name=s ?fmt=ebmp:jpg:gif:png:tif']:=ScreenshotHandler;
{$ENDIF}
SetLength(FModules, Length(Modules));
for i:=0 to High(Modules) do
try
{$IFDEF VSE_LOG}Log(llInfo, 'Initializing module '+Modules[i].Name);{$ENDIF}
FModules[i]:=Modules[i].Create;
if not Assigned(FModules[i]) then raise Exception.Create('Can''t initialize module '+Modules[i].Name);
except
LogException('in module '+Modules[i].Name+'.Create');
Core.StopEngine(StopInitError);
end;
{$IF Defined(VSE_LOG) and not Defined(VSE_NOSYSINFO)}
if not SysInfoLogged then
begin
SendEvent(TSysNotify.Create(Self, snLogSysInfo), [erModule]);
SysInfoLogged := true;
end;
{$IFEND}
SetResolution(InitSettings.ResolutionX, InitSettings.ResolutionY, InitSettings.RefreshRate, InitSettings.Fullscreen, false);
VSync:=InitSettings.VSync;
{$IFDEF VSE_LOG}Log(llInfo, 'States initialization');{$ENDIF}
if not Assigned(InitSettings.InitStates) then raise Exception.Create('InitStates() are NULL');
try
InitSettings.InitStates;
{$IFDEF VSE_LOG}Log(llInfo, 'States initialized');{$ENDIF}
except
LogException('in InitStates');
Core.StopEngine(StopUserException);
end;
glShadeModel(GL_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA);
glHint(GL_POLYGON_SMOOTH, GL_NICEST);
glHint(GL_SHADE_MODEL, GL_NICEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_NORMALIZE);
FFPSTimer:=timeSetEvent(1000, 0, @UpdateFPS, 0, TIME_PERIODIC);
{$IFDEF VSE_CONSOLE}
{$IFDEF VSE_LOG}Log(llInfo, 'Executing autoexec.cfg');{$ENDIF}
Console.Execute('if "exist autoexec.cfg" exec autoexec.cfg');
{$ENDIF}
FPaused:=false;
end;
procedure TCore.SaveSettings;
begin
Settings.Int[SSectionSettings, SNameResolutionX]:=FResolutionX;
Settings.Int[SSectionSettings, SNameResolutionY]:=FResolutionY;
Settings.Int[SSectionSettings, SNameRefreshRate]:=FRefreshRate;
Settings.Int[SSectionSettings, SNameColorDepth]:=FColorDepth;
Settings.Bool[SSectionSettings, SNameFullscreen]:=Fullscreen;
Settings.Bool[SSectionSettings, SNameVSync]:=VSync;
end;
procedure TCore.Update;
var
T, UpdTime: Cardinal;
i: Integer;
Cursor: TPoint;
begin
try
GetKeyboardState(FKeyState);
{$IFDEF VSE_CONSOLE}Console.Update;{$ENDIF}
for i:=0 to High(FModules) do
try
FModules[i].Update;
except
LogException(Format('in module %s.Update', [FModules[i].Name]));
{$IFNDEF VSE_DEBUG}StopEngine(StopInternalError);{$ENDIF}
end;
if FPaused then Exit;
if GetForegroundWindow<>FHandle then
begin
{$IFDEF VSE_LOG}if not FMinimized then Log(llInfo, 'Window minimized');{$ENDIF}
FMinimized:=True;
if FFullscreen then
begin
gleGoBack;
SendMessage(FHandle, WM_SYSCOMMAND, SC_MINIMIZE, 0);
end;
SendEvent(TSysNotify.Create(Self, snMinimized));
if FPaused then
begin
if FNeedSwitch
then State:=FSwitchTo;
SendEvent(TSysNotify.Create(Self, snPause));
if not FFullscreen
then SendMessage(FHandle, WM_SYSCOMMAND, SC_MINIMIZE, 0);
Exit;
end;
end;
if FNeedSwitch
then State:=FSwitchTo;
if FPreviousUpdate=0 then FPreviousUpdate:=Time;
T:=Time-FPreviousUpdate; //TODO: one update per draw if FUpdInt=0
FPreviousUpdate:=FPreviousUpdate+T-(T mod FUpdInt);
if FCurState<>nil then
begin
if FMouseCapture and not FMinimized then
begin
Cursor:=MouseCursor;
Cursor.X:=Cursor.X-FResolutionX div 2;
Cursor.Y:=Cursor.Y-FResolutionY div 2;
ResetMouse;
if not FInhibitUpdate then
SendEvent(TMouseEvent.Create(Self, 0, meMove, Cursor), [erState]);
end;
if not FInhibitUpdate then
for i:=1 to T div FUpdInt do
begin
UpdTime:=Time;
try
FCurState.Update;
except
LogException('in state '+FCurState.Name+'.Update');
{$IFNDEF VSE_DEBUG}StopEngine(StopUserException);{$ENDIF}
end;
if Time-UpdTime>FUpdInt then
begin
Inc(FUpdOverloadCount);
if FUpdOverloadCount>FUpdOverloadThreshold then
begin
SendEvent(TSysNotify.Create(Self, snUpdateOverload), [erState]);
{$IFDEF VSE_LOG}Log(llWarning, 'Update overload in state "'+FCurState.Name+'"');{$ENDIF}
end;
end
else if FUpdOverloadCount>0 then Dec(FUpdOverloadCount);
end;
FInhibitUpdate:=false;
try
FCurState.Draw;
except
LogException('in state '+FCurState.Name+'.Draw');
{$IFNDEF VSE_DEBUG}StopEngine(StopUserException);{$ENDIF}
end;
end;
for i:=High(FModules) downto 0 do
try
FModules[i].Draw;
except
LogException(Format('in module %s.Draw', [FModules[i].Name]));
{$IFNDEF VSE_DEBUG}StopEngine(StopInternalError);{$ENDIF}
end;
SwapBuffers(FDC);
Inc(FFramesCount);
except
LogException('in TCore.Update');
StopEngine(StopInternalError);
end;
end;
procedure TCore.Resume;
begin
{$IFDEF VSE_LOG}Log(llInfo, 'Window maximized');{$ENDIF}
try
if FFullscreen then gleGoFullscreen(ResolutionX, ResolutionY, RefreshRate, FColorDepth);
FMinimized:=false;
if FPaused then ResetUpdateTimer;
FPaused:=false;
SendEvent(TSysNotify.Create(Self, snResume));
SendEvent(TSysNotify.Create(Self, snMaximized));
except
LogException('in TCore.Resume');
StopEngine(StopInternalError);
end;
end;
procedure TCore.MouseEvent(Button: Integer; Event: TMouseEvents; X, Y: Integer);
var
Pos: TPoint;
begin
try
Pos:=Point(X, Y);
if (Event=meWheel) and not Fullscreen then
ScreenToClient(Handle, Pos);
if Event=meDown
then SetCapture(FHandle)
else if Event=meUp
then ReleaseCapture;
if (FMouseCapture and (Event=meMove)) or FPaused then Exit;
SendEvent(TMouseEvent.Create(Self, Button, Event, Pos));
except
LogException(Format('in TCore.MouseEvent(%d, %s, %d, %d)', [Button, MouseEventNames[Event], X, Y]));
StopEngine(StopInternalError);
end;
end;
procedure TCore.KeyEvent(Key: Integer; Event: TKeyEvents);
begin
try
if FPaused then Exit;
{$IFDEF VSE_ESC_EXIT}
if (Key=VK_ESCAPE) and (Event=keUp) then
begin
StopEngine;
Exit;
end;
{$ENDIF}
{$IFDEF VSE_USE_SNAPSHOT_KEY}
if (Key=VK_SNAPSHOT) and (Event=keUp) then
begin
MakeScreenshot(ChangeFileExt(ExtractFileName(ExeName), '')+'_screenshot', ifPNG);
Exit;
end;
{$ENDIF}
SendEvent(TKeyEvent.Create(Self, Key, Event));
except
LogException(Format('in TCore.KeyEvent(%d, %s)', [Key, KeyEventNames[Event]]));
StopEngine(StopInternalError);
end;
end;
procedure TCore.CharEvent(C: Char);
begin
try
if FPaused then Exit;
SendEvent(TCharEvent.Create(Self, C));
except
LogException('in TCore.CharEvent(#'+IntToStr(Ord(C))+')');
StopEngine(StopInternalError);
end;
end;
//Public
procedure TCore.StopEngine(StopState: TStopState);
begin
{$IFDEF VSE_LOG}LogF(llInfo, 'Stopping engine with code %d (%s)', [Ord(StopState), StopCodeNames[StopState]]);{$ENDIF}
VSEStopState:=StopState;
PostMessage(Handle, UM_STOPENGINE, 0, 0);
end;
procedure TCore.SendEvent(Event: TCoreEvent; Receivers: TEventReceivers);
var
i: Integer;
EventDump: string;
begin
if not Assigned(Event) then Exit;
try
{$IFDEF VSE_LOG}EventDump := Event.Dump;{$ENDIF}
if erModule in Receivers then
for i:=0 to High(FModules) do
try
if Assigned(Event) then
FModules[i].OnEvent(Event)
else Break;
except
LogException(Format('in module %s.Event(%s)', [FModules[i].Name, EventDump]));
{$IFNDEF VSE_DEBUG}StopEngine(StopInternalError);{$ENDIF}
end;
if (erState in Receivers) and Assigned(Event) and Assigned(FCurState) then
try
FCurState.OnEvent(Event);
except
LogException(Format('in state %s.Event(%s)', [FCurState.Name, EventDump]));
{$IFNDEF VSE_DEBUG}StopEngine(StopUserException);{$ENDIF}
end;
finally
FreeAndNil(Event);
end;
end;
function TCore.AddState(State: TGameState): Cardinal;
begin
Result:=Length(FStates);
SetLength(FStates, Result+1);
FStates[Result]:=State;
{$IFDEF VSE_LOG}LogF(llInfo, 'Added state #%d %s', [Result, State.Name]);{$ENDIF}
end;
function TCore.ReplaceState(OrigState: Cardinal; NewState: TGameState): Boolean;
begin
Result:=true;
{$IFDEF VSE_LOG}LogF(llInfo, 'Replacing state #%d with %s', [OrigState, NewState.Name]);{$ENDIF}
if OrigState<Length(FStates)
then FStates[OrigState]:=NewState
else Result:=false;
end;
procedure TCore.DeleteState(State: Cardinal);
begin
{$IFDEF VSE_LOG}Log(llInfo, 'Deleting state #'+IntToStr(State));{$ENDIF}
if State<Length(FStates) then
begin
if State<High(FStates)
then Move(FStates[State+1], FStates[State], (Length(FStates)-State-1)*SizeOf(TGameState));
SetLength(FStates, Length(FStates)-1);
end;
end;
procedure TCore.SwitchState(NewState: Cardinal);
begin
if NewState = InvalidState then Exit;
FSwitchTo:=NewState;
FNeedSwitch:=true;
end;
procedure TCore.SwitchState(const NewStateName: string);
begin
SwitchState(FindState(NewStateName));
end;
function TCore.StateExists(State: Cardinal): Boolean;
begin
Result:=(State<Length(FStates)) and Assigned(FStates[State]);
end;
function TCore.GetState(State: Cardinal): TGameState;
begin
if State<Length(FStates)
then Result:=FStates[State]
else Result:=nil;
end;
function TCore.FindState(const Name: string): Cardinal;
var
i: Cardinal;
begin
Result:=InvalidState;
for i:=0 to High(FStates) do
if Assigned(FStates[i]) and (FStates[i].Name=Name) then
begin
Result:=i;
Exit;
end;
end;
function TCore.KeyRepeat(Key: Byte; Rate: Integer; var KeyVar: Cardinal): Boolean;
var
T: Cardinal;
begin
Result:=false;
if KeyPressed[Key] then
begin
T:=Time;
if (T>KeyVar+Rate) or (KeyVar=0) then
begin
Result:=true;
KeyVar:=T;
end;
end
else KeyVar:=0;
end;
procedure TCore.SetResolution(ResolutionX, ResolutionY, RefreshRate: Cardinal; Fullscreen: Boolean; CanReset: Boolean = true);
var
OldResX, OldResY, OldRefresh: Cardinal;
R: TRect;
begin
//TODO: Переделать нахуй
OldResX:=FResolutionX;
OldResY:=FResolutionY;
OldRefresh:=FRefreshRate;
FResolutionX:=ResolutionX;
FResolutionY:=ResolutionY;
FRefreshRate:=RefreshRate;
{$IFDEF VSE_LOG}LogF(llInfo, 'Set resolution %dx%d@%d', [ResolutionX, ResolutionY, RefreshRate]);{$ENDIF}
Self.Fullscreen:=Fullscreen;
SendMessage(FHandle, WM_SIZE, 0, ResolutionY shl 16 + ResolutionX);
if FFullscreen then
begin
if not gleGoFullscreen(ResolutionX, ResolutionY, RefreshRate, FColorDepth) then
begin
{$IFDEF VSE_LOG}LogF(llError, 'Unable to set resolution %dx%d@%d', [ResolutionX, ResolutionY, RefreshRate]);{$ENDIF}
if CanReset
then SetResolution(OldResX, OldResY, OldRefresh, false)
else begin
MessageBox(FHandle, 'Unable to set resolution! Choose lower resolution or refresh rate', PChar(InitSettings.Caption), MB_ICONERROR);
StopEngine(StopDisplayModeError);
end;
end;
end
else begin
GetWindowRect(FHandle, R);
SetWindowPos(FHandle, 0, (Screen.Width-R.Right+R.Left) div 2, (Screen.Height-R.Bottom+R.Top) div 2, 0, 0, SWP_NOSIZE or SWP_NOZORDER or SWP_NOACTIVATE);
end;
SendEvent(TSysNotify.Create(Self, snResolutionChanged));
end;
procedure TCore.MakeScreenshot(Name: string; Format: TImageFormat; Numerate: Boolean = true);
var
Image: TImage;
i, Quality: Integer;
begin
if Numerate then
begin
for i:=0 to 99 do
if (i=99) or not FileExists(ExePath+Name+IntToStrLZ(i, 2)+ImageFormatExtension[Format]) then
begin
Name:=ExePath+Name+IntToStrLZ(i, 2)+ImageFormatExtension[Format];
Break;
end;
end
else Name:=ExePath+Name+ImageFormatExtension[Format];
Image:=TImage.Create(FResolutionX, FResolutionY, pfBGR24bit, Ceil(FResolutionX*3/4)*4);
try
glPixelStore(GL_PACK_ALIGNMENT, 4);
glReadPixels(0, 0, FResolutionX, FResolutionY, GL_BGR, GL_UNSIGNED_BYTE, Image.Pixels);
if Format = ifJPEG
then Quality := 95
else Quality := 0;
Image.Save(Name, Format, Quality);
{$IFDEF VSE_LOG}Log(llInfo, 'Screenshot saved to "'+Name+'"'){$ENDIF};
finally
Image.Free;
end;
end;
procedure TCore.ResetUpdateTimer;
begin
FPreviousUpdate:=Time;
end;
function TCore.GetFile(const FileName: string): TStream;
begin
Result:=nil;
if FileExists(InitSettings.DataDir+FileName) then
Result:=TFileStream.Create(InitSettings.DataDir+FileName, fmOpenRead or fmShareDenyWrite)
else SendEvent(TGetFileEvent.Create(Self, FileName, @Result), [erModule]);
end;
function TCore.GetFileText(const FileName: string): TStringList;
var
F: TStream;
begin
Result:=nil;
F:=GetFile(FileName);
if Assigned(F) then
try
Result:=TStringList.Create;
Result.LoadFromStream(F);
finally
FAN(F);
end;
end;
//Private
procedure TCore.SetFullscreen(Value: Boolean);
begin
//TODO: Переделать нахуй
if FFullscreen=Value then Exit;
FFullscreen:=Value;
if Value
then FFullscreen:=gleGoFullscreen(FResolutionX, FResolutionY, FRefreshRate, FColorDepth)
else gleGoBack;
{$IFDEF VSE_LOG}if FFullscreen<>Value then Log(llError, 'Unable to enter fullscreen! Choose lower resolution or refresh rate');{$ENDIF}
if FFullscreen then
begin
SetWindowLong(FHandle, GWL_EXSTYLE, WS_EX_APPWINDOW);
SetWindowLong(FHandle, GWL_STYLE, Integer(WS_POPUP) or WS_CLIPCHILDREN or WS_CLIPSIBLINGS);
SetWindowPos(FHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_FRAMECHANGED or SWP_SHOWWINDOW);
end
else begin
SetWindowLong(FHandle, GWL_EXSTYLE, WS_EX_APPWINDOW or WS_EX_WINDOWEDGE);
SetWindowLong(FHandle, GWL_STYLE, WindowedWindowStyle);
SetWindowPos(FHandle, HWND_NOTOPMOST, (Screen.Width-FResolutionX) div 2, (Screen.Height-FResolutionY) div 2, 0, 0, SWP_NOSIZE or SWP_FRAMECHANGED or SWP_SHOWWINDOW);
end;
end;
function TCore.GetCaption: string;
begin
SetLength(Result, GetWindowTextLength(FHandle));
SetLength(Result, GetWindowText(FHandle, PChar(Result), Length(Result)));
end;
procedure TCore.SetCaption(const Value: string);
begin
SetWindowText(FHandle, PChar(Value));
end;
function TCore.GetVSync: Boolean;
begin
Result:=false;
if WGL_EXT_swap_control then Result:=wglGetSwapIntervalEXT<>0;
end;
procedure TCore.SetVSync(Value: Boolean);
const
VSync: array[Boolean] of Integer=(0, 1);
begin
if WGL_EXT_swap_control then wglSwapIntervalEXT(VSync[Value]);
end;
procedure TCore.SetState(Value: Cardinal);
begin
{$IFDEF VSE_LOG}if StateExists(FState) and StateExists(Value)
then LogF(llInfo, 'Switch state from %s to %s', [FStates[FState].Name, FStates[Value].Name])
else if StateExists(Value)
then Log(llInfo, 'Switch state to '+FStates[Value].Name);{$ENDIF}
FNeedSwitch:=false;
if (FState=Value) or (Value>High(FStates)) then Exit;
if FCurState<>nil then
begin
try
FCurState.Deactivate;
except
LogException('in state '+FCurState.Name+'.Deactivate');
{$IFNDEF VSE_DEBUG}StopEngine(StopUserException);{$ENDIF}
end;
FPrevStateName:=FCurState.Name;
end;
SendEvent(TSysNotify.Create(Self, snStateChanged), [erModule]);
FState:=Value;
FCurState:=FStates[Value];
try
FUpdInt:=FCurState.Activate;
except
if FUpdInt<=1 then FUpdInt:=50;
LogException('in state '+FCurState.Name+'.Activate');
{$IFNDEF VSE_DEBUG}StopEngine(StopUserException);{$ENDIF}
end;
end;
function TCore.GetKeyPressed(Index: Byte): Boolean;
begin
Result:=(FKeyState[Index]>127) and not FMinimized;
end;
procedure TCore.SetMouseCapture(Value: Boolean);
begin
if Value=FMouseCapture then Exit;
FMouseCapture:=Value;
if Value then
begin
GetCursorPos(FSavedMousePos);
ResetMouse;
SetCapture(FHandle);
ShowCursor(false);
end
else begin
ReleaseCapture;
with FSavedMousePos do
SetCursorPos(X, Y);
ShowCursor(true);
end;
end;
function TCore.GetMouseCursor: TPoint;
begin
GetCursorPos(Result);
ScreenToClient(FHandle, Result);
end;
function TCore.GetTime: Cardinal;
var
T: Int64;
begin
if QueryPerformanceCounter(T) then
Result := 1000 * (T div FHPETFreq) + (1000 * (T mod FHPETFreq)) div FHPETFreq
else
Result := GetTickCount;
end;
procedure TCore.ResetMouse;
var
Cur: TPoint;
begin
Cur := Point(FResolutionX div 2, FResolutionY div 2);
ClientToScreen(FHandle, Cur);
SetCursorPos(Cur.X, Cur.Y);
end;
{$IFDEF VSE_CONSOLE}
const
BoolState: array[Boolean] of string = ('off', 'on');
function TCore.FullscreenHandler(Sender: TObject; Args: array of const): Boolean;
begin
if Length(Args)>1
then Fullscreen:=Boolean(Args[1].VInteger)
else Console.WriteLn('Fullscreen: '+BoolState[Fullscreen]);
Result:=true;
end;
function TCore.QuitHandler(Sender: TObject; Args: array of const): Boolean;
begin
StopEngine;
Result:=true;
end;
function TCore.ResolutionHandler(Sender: TObject; Args: array of const): Boolean;
begin
Result:=true;
case Length(Args) of
1: Console.WriteLn(Format('Resolution: %dx%d@%d', [ResolutionX, ResolutionY, RefreshRate]));
3: SetResolution(Args[1].VInteger, Args[2].VInteger, RefreshRate, Fullscreen);
4: SetResolution(Args[1].VInteger, Args[2].VInteger, Args[3].VInteger, Fullscreen);
else begin
Console.WriteLn('Invalid arguments' + PostfixError);
Result:=false;
end;
end;
end;
function TCore.ScreenshotHandler(Sender: TObject; Args: array of const): Boolean;
begin
case Length(Args) of
1: MakeScreenshot(ChangeFileExt(ExtractFileName(ExeName), '')+'_screenshot', ifPNG);
2: MakeScreenshot(string(Args[1].VAnsiString), ifPNG, false);
else MakeScreenshot(string(Args[1].VAnsiString), TImageFormat(Args[2].VInteger), false);
end;
Result:=true;
end;
function TCore.StateHandler(Sender: TObject; Args: array of const): Boolean;
begin
if Length(Args)>1
then SwitchState(string(Args[1].VAnsiString))
else Console.WriteLn('Current state: '+CurState.Name);
Result:=true;
end;
function TCore.VSyncHandler(Sender: TObject; Args: array of const): Boolean;
begin
if Length(Args)>1
then VSync:=Boolean(Args[1].VInteger)
else Console.WriteLn('VSync: '+BoolState[VSync]);
Result:=true;
end;
{$ENDIF}
{TSettings}
constructor TSettings.Create;
var
IniName: string;
begin
inherited;
IniName:=ChangeFileExt(FullExeName, '.ini');
FFirstRun:=not FileExists(IniName);
InitSettings.DataDir:=ExePath+'data\';
{$IFNDEF VSE_NO_INI}
FIni:=TIniFile.Create(IniName);
if not FFirstRun then
ReloadInitSettings;
{$ENDIF}
end;
destructor TSettings.Destroy;
begin
FAN(FIni);
inherited;
end;
procedure TSettings.ReloadInitSettings;
begin
{$IFNDEF VSE_NO_INI}
with InitSettings do
begin
{$IFDEF VSE_LOG}Log(llInfo, 'Loading settings from ini file');{$ENDIF}
ResolutionX:=FIni.ReadInteger(SSectionSettings, SNameResolutionX, ResolutionX);
ResolutionY:=FIni.ReadInteger(SSectionSettings, SNameResolutionY, ResolutionY);
RefreshRate:=FIni.ReadInteger(SSectionSettings, SNameRefreshRate, RefreshRate);
ColorDepth:=FIni.ReadInteger(SSectionSettings, SNameColorDepth, ColorDepth);
Fullscreen:=FIni.ReadBool(SSectionSettings, SNameFullscreen, Fullscreen);
VSync:=FIni.ReadBool(SSectionSettings, SNameVSync, VSync);
end;
{$ENDIF}
end;
procedure TSettings.EraseSection(const Section: string);
begin
if Assigned(FIni) then FIni.EraseSection(Section);
end;
function TSettings.GetBool(const Section, Name: string): Boolean;
begin
if Assigned(FIni) then
Result:=FIni.ReadBool(Section, Name, false)
else
Result:=false;
end;
function TSettings.GetInt(const Section, Name: string): Integer;
begin
if Assigned(FIni) then
Result:=FIni.ReadInteger(Section, Name, 0)
else
Result:=0;
end;
function TSettings.GetStr(const Section, Name: string): string;
begin
if Assigned(FIni) then
Result:=FIni.ReadString(Section, Name, '')
else
Result:='';
end;
function TSettings.ReadSection(const Section: string): TStringList;
begin
Result:=TStringList.Create;
if Assigned(FIni) then FIni.ReadSectionValues(Section, Result);
end;
procedure TSettings.SetBool(const Section, Name: string; const Value: Boolean);
begin
if Assigned(FIni) then FIni.WriteBool(Section, Name, Value);
end;
procedure TSettings.SetInt(const Section, Name: string; const Value: Integer);
begin
if Assigned(FIni) then FIni.WriteInteger(Section, Name, Value);
end;
procedure TSettings.SetStr(const Section, Name: string; const Value: string);
begin
if Assigned(FIni) then FIni.WriteString(Section, Name, Value);
end;
{Procedures}
function WndProc(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
WndWidth, WndHeight: Word;
begin
Result:=0;
case (Msg) of
WM_ACTIVATE:
begin
if not Assigned(Core) then
begin
{$IFDEF VSE_LOG}Log(llInfo, 'Creating engine');
{$IFDEF VSE_DEBUG}Log(llInfo, 'Debug mode');{$ENDIF}{$ENDIF}
try
Core:=TCore.Create(hWnd);
Core.StartEngine;
{$IFDEF VSE_LOG}Log(llInfo, 'Engine created');{$ENDIF}
except
LogException('while initializing engine');
VSEStopState:=StopInitError;
SendMessage(hWnd, UM_STOPENGINE, 0, 0);
end;
end;
end;
WM_KEYUP: Core.KeyEvent(wParam, keUp);
WM_KEYDOWN: Core.KeyEvent(wParam, keDown);
WM_CHAR: Core.CharEvent(Chr(wParam));
WM_MOUSEMOVE: Core.MouseEvent(0, meMove, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
WM_LBUTTONDOWN: Core.MouseEvent(mbLeft, meDown, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
WM_LBUTTONUP: Core.MouseEvent(mbLeft, meUp, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
WM_RBUTTONDOWN: Core.MouseEvent(mbRight, meDown, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
WM_RBUTTONUP: Core.MouseEvent(mbRight, meUp, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
WM_MBUTTONDOWN: Core.MouseEvent(mbMiddle, meDown, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
WM_MBUTTONUP: Core.MouseEvent(mbMiddle, meUp, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
WM_XBUTTONDOWN: Core.MouseEvent(3+HiWord(wParam), meDown, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
WM_XBUTTONUP: Core.MouseEvent(3+HiWord(wParam), meUp, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
WM_MOUSEWHEEL: Core.MouseEvent(SmallInt(HiWord(wParam)) div 120, meWheel, SmallInt(LoWord(lParam)), SmallInt(HiWord(lParam)));
{$IFDEF VSE_USE_ALT_ENTER}
WM_SYSKEYUP: if Assigned(Core) and (wParam=VK_RETURN) and (lParam and (1 shl 29) <> 0) then
Core.Fullscreen:=not Core.Fullscreen;
{$ENDIF}
WM_DESTROY:
begin
{$IFDEF VSE_LOG}Log(llInfo, 'Destroying engine');{$ENDIF}
try
FAN(Core);
{$IFDEF VSE_LOG}Log(llInfo, 'Engine destroyed');{$ENDIF}
except
LogException('while destroying engine');
VSEStopState:=StopInternalError;
end;
PostQuitMessage(Integer(VSEStopState));
Result:=0;
end;
WM_QUERYENDSESSION:
begin
{$IFDEF VSE_LOG}Log(llInfo, 'Received WM_QUERYENDSESSION');{$ENDIF}
Core.StopEngine;
Result:=1;
end;
WM_SIZE:
try
if Assigned(Core) then begin
if Core.Fullscreen then
begin
WndWidth:=Core.ResolutionX;
WndHeight:=Core.ResolutionY;
end
else begin
WndWidth:=Core.ResolutionX+GetSystemMetrics(SM_CXDLGFRAME)*2;
WndHeight:=Core.ResolutionY+GetSystemMetrics(SM_CYCAPTION)+GetSystemMetrics(SM_CYDLGFRAME)*2;
end;
gleResizeWnd(Core.ResolutionX, Core.ResolutionY);
if Core.Fullscreen
then SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, WndWidth, WndHeight, 0)
else SetWindowPos(hWnd, HWND_TOP, 0, 0, WndWidth, WndHeight, SWP_NOMOVE or SWP_FRAMECHANGED);
end;
Result:=0;
except
LogException('while resizing window');
{$IFNDEF VSE_DEBUG}Core.StopEngine(StopInternalError);{$ENDIF}
end;
UM_STOPENGINE: DestroyWindow(hWnd);
else
Result:=DefWindowProc(hWnd, Msg, wParam, lParam);
end;
end;
function IsRunning(const ID: string): Boolean;
begin
Result:=false;
if Mutex<>0 then Exit;
Mutex:=CreateMutex(nil, true, PChar(ID));
if GetLastError=ERROR_ALREADY_EXISTS then Result:=true;
end;
function VSEStart: TStopState;
var
WndClass: TWndClass;
Handle: THandle;
Msg: TMsg;
Fin: Boolean;
begin
Result:=StopInitError;
if IsRunning(InitSettings.Caption) then Exit;
VSEStopState:=StopDefault;
{$IFDEF VSE_LOG}
LogRaw(llInfo, '');
Log(llInfo, InitSettings.Caption+' '+InitSettings.Version+' started');
Log(llInfo, VSECaptVer);
{$ENDIF}
Set8087CW($133F);
Fin:=false;
ZeroMemory(@WndClass, SizeOf(WndClass));
with WndClass do
begin
style:=CS_HREDRAW or CS_VREDRAW or CS_OWNDC;
lpfnWndProc:=@WndProc;
hInstance:=SysInit.hInstance;
hCursor:=LoadCursor(0, IDC_ARROW);
hIcon:=LoadIcon(hInstance, 'MAINICON');
lpszClassName:=WndClassName;
hbrBackground:=0;
end;
if Windows.RegisterClass(WndClass)=0 then
begin
LogErrorAndShowMessage('Failed to register the window class');
Exit;
end;
Handle:=CreateWindowEx(WS_EX_APPWINDOW or WS_EX_WINDOWEDGE, WndClassName, PChar(InitSettings.Caption),
WindowedWindowStyle, 0, 0, 800, 600, 0, 0, hInstance, nil);
if Handle=0 then
begin
LogErrorAndShowMessage('Unable to create window');
Exit;
end;
SendMessage(Handle, WM_SETICON, ICON_SMALL, LoadIcon(hInstance, IDI_APPLICATION));
SendMessage(Handle, WM_SETICON, ICON_BIG, LoadIcon(hInstance, IDI_APPLICATION));
ShowWindow(Handle, SW_SHOW);
try
while not Fin do
begin
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
if (Msg.message=WM_QUIT)
then Fin:=true
else begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end
else
if Core<>nil then
begin
if Core.Minimized and (GetForegroundWindow=Handle)
then Core.Resume;
if Core.Paused
then Sleep(50)
else Core.Update;
end;
end;
Result:=TStopState(Msg.wParam);
except
LogException('in main loop');
Result:=StopInternalError;
end;
{$IFDEF VSE_LOG}
if Result<>StopNormal then
begin
LogF(llInfo, 'Engine stopped with error code %d (%s)', [Ord(Result), StopCodeNames[Result]]);
end;
{$ENDIF}
UnregisterClass(WndClassName, hInstance);
end;
procedure RegisterModule(Module: CModule);
begin
SetLength(Modules, Length(Modules)+1);
Modules[High(Modules)]:=Module;
end;
initialization
Settings:=TSettings.Create;
finalization
Finalize(Modules);
FAN(Settings);
ReleaseMutex(Mutex);
end.
|
unit FastStringBuilder;
interface
uses SysUtils;
type
TStringBuilder = class
private const
MALLOC_SIZE = 10 * 1024; // 10KB
private
procedure ExpandCapacity(const AdditionalSize: Integer);
procedure SetCapacity(Value: NativeUInt);
function GetChars(Index: NativeUInt): Char;
procedure SetChars(Index: NativeUInt; Value: Char);
procedure SetLength(Value: NativeUint); inline;
procedure ReduceCapacity; inline;
procedure CheckBounds(Index: NativeUint); inline;
function _Replace(Index: NativeUint; const Old, New: string): Boolean;
//prevent ref count and exception frame for local strings.
function _Append(const Value: PChar; Length: cardinal): TStringBuilder; overload;
function _Append(const Value: TCharArray; StartIndex,
CharCount: NativeUInt): TStringBuilder; overload;
protected
FData: TCharArray;
//FInsertPoint: PChar;
FLength: NativeUInt;
FCapacity: NativeUint; //Avoid the need for nil testing the underlying storage.
FMaxCapacity: NativeUInt;
public
constructor Create; overload;
constructor Create(aCapacity: NativeUInt); overload;
constructor Create(const Value: string); overload;
constructor Create(aCapacity, aMaxCapacity: NativeUInt); overload;
constructor Create(const Value: string; aCapacity: NativeUInt); overload;
constructor Create(const Value: string; StartIndex, Length, aCapacity: NativeUInt); overload;
function Append(const Value: string): TStringBuilder; overload; //put first, so the inlines work.
function Append(const Value: Boolean): TStringBuilder; overload; inline;
function Append(const Value: Byte): TStringBuilder; overload; {$ifndef cpux64} inline; {$endif}
function Append(const Value: Char): TStringBuilder; overload; {$ifndef cpux64} inline; {$endif}
function Append(const Value: Currency): TStringBuilder; overload; inline;
function Append(const Value: Double): TStringBuilder; overload; inline;
function Append(const Value: Smallint): TStringBuilder; overload; {$ifndef cpux64} inline; {$endif}
function Append(const Value: Integer): TStringBuilder; overload; {$ifndef cpux64} inline; {$endif}
function Append(const Value: Int64): TStringBuilder; overload; {$ifndef cpux64} inline; {$endif}
function Append(const Value: TObject): TStringBuilder; overload; inline;
function Append(const Value: Shortint): TStringBuilder; overload; {$ifndef cpux64} inline; {$endif}
function Append(const Value: Single): TStringBuilder; overload; inline;
function Append(const Value: UInt64): TStringBuilder; overload; {$ifndef cpux64} inline; {$endif}
function Append(const Value: TCharArray): TStringBuilder; overload; inline;
function Append(const Value: Word): TStringBuilder; overload; {$ifndef cpux64} inline; {$endif}
function Append(const Value: Cardinal): TStringBuilder; overload; {$ifndef cpux64} inline; {$endif}
{$IFNDEF NEXTGEN}
function Append(const Value: PAnsiChar): TStringBuilder; overload; inline;
function Append(const Value: RawByteString): TStringBuilder; overload; inline;
{$ENDIF !NEXTGEN}
function Append(const Value: Char; RepeatCount: NativeUInt): TStringBuilder; overload;
function Append(const Value: TCharArray; StartIndex, CharCount: NativeUInt): TStringBuilder; overload; inline;
function Append(const Value: string; StartIndex, Count: NativeUInt): TStringBuilder; overload;
function AppendFormat(const Format: string; const Args: array of const): TStringBuilder; overload;
function AppendLine: TStringBuilder; overload;
function AppendLine(const Value: string): TStringBuilder; overload; inline;
procedure Clear; inline;
procedure CopyTo(SourceIndex: NativeUInt; const Destination: TCharArray; DestinationIndex, Count: NativeUInt);
function EnsureCapacity(aCapacity: NativeUInt): NativeUInt;
function Equals(StringBuilder: TStringBuilder): Boolean; reintroduce;
function Insert(Index: NativeUInt; const Value: Boolean): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: Byte): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: Char): TStringBuilder; overload;
function Insert(Index: NativeUInt; const Value: Currency): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: Double): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: Smallint): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: Integer): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: TCharArray): TStringBuilder; overload;
function Insert(Index: NativeUInt; const Value: Int64): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: TObject): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: Shortint): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: Single): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: string): TStringBuilder; overload;
function Insert(Index: NativeUInt; const Value: Word): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: Cardinal): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: UInt64): TStringBuilder; overload; inline;
function Insert(Index: NativeUInt; const Value: string; count: NativeUInt): TStringBuilder; overload;
function Insert(Index: NativeUInt; const Value: TCharArray; startIndex: NativeUInt; charCount: NativeUInt): TStringBuilder; overload;
function Remove(StartIndex: Integer; RemLength: Integer): TStringBuilder;
function Replace(const OldChar: Char; const NewChar: Char): TStringBuilder; overload;
function Replace(const OldValue: string; const NewValue: string): TStringBuilder; overload;
function Replace(const OldChar: Char; const NewChar: Char; StartIndex, Count: NativeUInt): TStringBuilder; overload;
function Replace(const OldValue: string; const NewValue: string; StartIndex, Count: NativeUInt): TStringBuilder; overload;
function ToString: string; overload; override;
function ToString(StartIndex: NativeUInt; StrLength: Cardinal): string; reintroduce; overload;
property Capacity: NativeUInt read FCapacity write SetCapacity;
property Chars[index: NativeUInt]: Char read GetChars write SetChars; default;
property Length: NativeUInt read FLength write SetLength;
property MaxCapacity: NativeUInt read FMaxCapacity;
end;
implementation
uses
System.SysConst, System.RTLConsts, WinAPI.Windows, System.classes, System.Diagnostics;
const
/// fast lookup table for converting any decimal number from
// 0 to 99 into their ASCII equivalence
// - our enhanced SysUtils.pas (normal and LVCL) contains the same array
TwoDigitLookup: packed array[0..99] of array[1..2] of Char =
('00','01','02','03','04','05','06','07','08','09',
'10','11','12','13','14','15','16','17','18','19',
'20','21','22','23','24','25','26','27','28','29',
'30','31','32','33','34','35','36','37','38','39',
'40','41','42','43','44','45','46','47','48','49',
'50','51','52','53','54','55','56','57','58','59',
'60','61','62','63','64','65','66','67','68','69',
'70','71','72','73','74','75','76','77','78','79',
'80','81','82','83','84','85','86','87','88','89',
'90','91','92','93','94','95','96','97','98','99');
TwoDigitLookupAnsi: packed array[0..99] of array[1..2] of AnsiChar =
('00','01','02','03','04','05','06','07','08','09',
'10','11','12','13','14','15','16','17','18','19',
'20','21','22','23','24','25','26','27','28','29',
'30','31','32','33','34','35','36','37','38','39',
'40','41','42','43','44','45','46','47','48','49',
'50','51','52','53','54','55','56','57','58','59',
'60','61','62','63','64','65','66','67','68','69',
'70','71','72','73','74','75','76','77','78','79',
'80','81','82','83','84','85','86','87','88','89',
'90','91','92','93','94','95','96','97','98','99');
{ TStringBuilder }
type
TCharStorage = array [1..28] of char;
TAnsiCharStorage = array [1..28] of AnsiChar;
{$ifdef cpux64}
/// <summary>
/// Convert value into a string.
/// Negative values will have a '-' in front.
/// Returns the first char of the string.
/// At Result -4 a length encoding will be stored.
/// </summary>
function _IntToStrAnsi(const Value: Int64; var Dump: TAnsiCharStorage): PAnsiChar; overload;
//rcx = value
//rdx = dump
//rax = length
asm
.noframe
push rcx
mov r8,rcx
neg rcx
cmovs rcx,r8
lea r11, [rdx+24]
push r11 //save the end of the data
lea r10, [rip+TwoDigitLookupAnsi]
//mov byte ptr [rdx+60], 0
cmp rcx, 100
jb @tail
mov r8, $47ae147ae147ae15
@loop:
mov rax, rcx
mov r9d, ecx
mul r8
sub rcx, rdx
shr rcx, 1
add rdx, rcx
mov rcx, rdx
shr rcx, 6
imul rax, rcx, -100
add r9, rax
movzx edx, word ptr [r10+r9*2]
mov [r11], dx
sub r11, 2
cmp rcx, 100
jae @loop
@tail:
movzx eax, word ptr [r10+rcx*2]
mov edx,$2d //'-'
mov [r11], ax
xor eax, eax
cmp ecx, 10
pop r10
pop rcx
setb al
add r10, 4
shl rcx, 1 //sign flag to carry flag
mov [r11+rax-1],dl //put the '-', just in case
sbb rax,0 //include the '-' if applicable
lea rax, [r11+rax]
sub r10,rax
mov [rax-4],r10d
ret
end;
{$endif}
{$ifdef cpux64}
/// <summary>
/// Convert value into a string.
/// Negative values will have a '-' in front.
/// Returns the first char of the string.
/// At Result -4 a length encoding will be stored.
/// </summary>
function _IntToStr(const Value: Int64; var Dump: TCharStorage): PChar; overload;
//rcx = value
//rdx = dump
//rax = length
asm
.noframe
push rcx //1
mov r8,rcx //3+1=4
neg rcx //4+3=7
cmovs rcx,r8 //7+4=11 //Value = abs(value)
@@IntToStrNoSign:
lea r11, [rdx+26*2]
push r11 //save the end of the data for length calculations later
lea r10, [rip+TwoDigitLookup]
cmp rcx, 100 //process two digits at a time
jb @tail //only two digits, goto tail.
mov r8, $47ae147ae147ae15 //division using multiplication by reciprocal
db $0F, $1F, $84, $00, $00, $00, $00, $00 //nop 8
@loop:
mov rax, rcx
mov r9d, ecx
mul r8
sub rcx, rdx
shr rcx, 1
add rdx, rcx
mov rcx, rdx
shr rcx, 6
imul rax, rcx, -100 //i = remainder mod 100
add r9d, eax
mov eax, [r10+r9*4] //digits = lookup[i]
mov [r11], eax //add to digits to the string
sub r11, 4
cmp rcx, 100 //repeat ...
jae @loop //... until remainder < 100
@tail:
mov eax,[r10+rcx*4] //lookup 2 digits
pop r10
mov edx,$2d //sign = '-'
mov [r11], eax //write 2 digits
xor eax, eax
cmp ecx, 10 //do we have a leading zero?
pop rcx
setb al //yes, add one
add r10, 4 //correct starting pos
shl rcx, 1 //rcx = 1 if number was negative
mov [r11+rax*2-2],dx//put the '-', just in case
sbb rax,0 //correct the start pos, if we have a '-' in front
lea rax, [r11+rax*2]//return the start of the string
sub r10,rax //r10 = length
shr r10,1 //pass length in chars
mov [rax-4],r10d //write the length before the string
ret
end;
function _UIntToStr(const Value: UInt64; var Dump: TCharStorage): PChar; overload;
asm
.noframe
//push 0 //Save positive sign
@@IntToStrNoSign:
lea r11, [rdx+26*2]
push r11 //save the end of the data for length calculations later
lea r10, [rip+TwoDigitLookup]
cmp rcx, 100 //process two digits at a time
jb @tail //only two digits, goto tail.
mov r8, $47ae147ae147ae15 //division using multiplication by reciprocal
db $0F, $1F, $00 //nop 3
@loop:
mov rax, rcx
mov r9d, ecx
mul r8
sub rcx, rdx
shr rcx, 1
add rdx, rcx
mov rcx, rdx
shr rcx, 6
imul rax, rcx, -100 //i = remainder mod 100
add r9d, eax
mov eax, [r10+r9*4] //digits = lookup[i]
mov [r11], eax //add to digits to the string
sub r11, 4
cmp rcx, 100 //repeat ...
jae @loop //... until remainder < 100
@tail:
mov eax,[r10+rcx*4] //lookup 2 digits
pop r10
//mov edx,$2d //sign = '-'
mov [r11], eax //write 2 digits
xor eax, eax
cmp ecx, 10 //do we have a leading zero?
//pop rcx
setb al //yes, add one
add r10, 4 //correct starting pos
//shl rcx, 1 //rcx = 1 if number was negative
//mov [r11+rax*2-2],dx//put the '-', just in case
//sbb rax,0 //correct the start pos, if we have a '-' in front
lea rax, [r11+rax*2]//return the start of the string
sub r10,rax //r10 = length
shr r10,1 //pass length in chars
mov [rax-4],r10d //write the length before the string
ret
end;
{$endif}
{$pointermath on}
function Min(a,b: NativeUInt): NativeUInt; overload; inline;
begin
Result:= a xor ((a xor b) and -integer(a > b));
end;
procedure TStringBuilder.ExpandCapacity(const AdditionalSize: Integer);
begin
FCapacity:= Min(FCapacity, MALLOC_SIZE);
FCapacity := ((FLength + AdditionalSize) * 4) div 2;
System.SetLength(FData, FCapacity);
end;
procedure TStringBuilder.SetLength(Value: NativeUInt);
begin
if Value > Capacity then ExpandCapacity(Value - Capacity);
FLength:= Value;
end;
function TStringBuilder.Append(const Value: string): TStringBuilder;
var
L: NativeUInt;
P: PInteger;
begin
Result:= Self;
//L:= System.Length(Value);
P:= PInteger(Value);
if P = nil then exit;
Dec(P);
L:= P^;
if (Length + L) > Capacity then ExpandCapacity(L); //ExpandCapacity(Length + L);
Move(pointer(Value)^, FData[FLength], L * SizeOf(Char));
FLength := FLength + L;
end;
function TStringBuilder.Append(const Value: UInt64): TStringBuilder;
{$ifdef CPUx64}
var
P: PChar;
L: integer;
Storage: TCharStorage;
begin
P:= _UIntToStr(Value, Storage);
L:= PInteger(P)[-1];
Result:= _Append(P, L);
end;
{$else}
begin
Result:= Append(UIntToStr(Value));
end;
{$endif}
function TStringBuilder.Append(const Value: TCharArray): TStringBuilder;
begin
Result:= _Append(Value, 0, System.Length(Value));
end;
function TStringBuilder.Append(const Value: Single): TStringBuilder;
begin
Result:= Append(FloatToStr(Value));
end;
function TStringBuilder.Append(const Value: Word): TStringBuilder;
{$ifdef cpux64}
var
P: PChar;
L: integer;
Storage: TCharStorage;
begin
P:= _UIntToStr(Value, Storage);
L:= PInteger(P)[-1];
Result:= _Append(P, L);
end;
{$else}
begin
Result:= Append(UIntToStr(Value));
end;
{$endif}
function TStringBuilder._Append(const Value: TCharArray; StartIndex,
CharCount: NativeUInt): TStringBuilder;
begin
Length := Length + CharCount;
Move(Value[StartIndex], FData[Length - CharCount], CharCount * SizeOf(Char));
Result := self;
end;
function TStringBuilder.Append(const Value: TCharArray; StartIndex,
CharCount: NativeUInt): TStringBuilder;
begin
if StartIndex + CharCount > System.Length(Value) then
raise ERangeError.CreateResFmt(@SListIndexError, [StartIndex]);
Result:= _Append(Value, StartIndex, CharCount);
end;
function TStringBuilder.Append(const Value: string; StartIndex,
Count: NativeUInt): TStringBuilder;
var
i: integer;
L: integer;
begin
if StartIndex + Count > System.Length(Value) then
raise ERangeError.CreateResFmt(@SListIndexError, [StartIndex]);
L:= System.Length(Value) - StartIndex + Low(string);
Length := Length + (L * Count);
for i:= Count -1 downto 0 do begin
Move(Value[StartIndex + Low(string)], FData[Length - i * L], Count * SizeOf(Char));
end;
Result := Self;
end;
function TStringBuilder._Append(const Value: PChar; Length: cardinal): TStringBuilder;
var
L: NativeUint;
begin
L:= FLength;
Self.Length:= L + Length;
Move(Value^, FData[L], Length * SizeOf(Char));
Result:= self;
end;
{$IFNDEF NEXTGEN}
function TStringBuilder.Append(const Value: PAnsiChar): TStringBuilder;
begin
Result:= Append(string(Value));
end;
function TStringBuilder.Append(const Value: RawByteString): TStringBuilder;
begin
Result:= Append(string(Value));
end;
{$ENDIF !NEXTGEN}
function TStringBuilder.Append(const Value: Cardinal): TStringBuilder;
{$ifdef cpux64}
var
P: PChar;
L: integer;
Storage: TCharStorage;
begin
P:= _UIntToStr(Value, Storage);
L:= PInteger(P)[-1];
Result:= _Append(P, L);
end;
{$else}
begin
Result:= Append(UIntToStr(Value));
end;
{$endif}
function TStringBuilder.Append(const Value: Char; RepeatCount: NativeUInt): TStringBuilder;
{$ifdef CPUX64}
asm
//RCX = self
//DX = Value
//r8 = Repeatcount
and edx,$FFFF
mov r9,[RCX+TStringBuilder.FLength]
mov rax,$0001000100010001 //stamp with 4 copies
imul rdx,rax
push r9
push r8
push rdx
push rcx
lea rdx,[r9+r8] //L = FLength + RepeatCount
call TStringBuilder.SetLength
pop rcx
pop rdx
pop r8
lea rax,[rcx+TStringBuilder.FData]
mov rax,[rax] //rax = FData[0]
pop r9
lea r9,[rax+r9*type(char)] //rax = FData[Length]
mov eax,3
and eax,r8d
shr r8,2 //divide by four
jz @tail
@loop:
sub r8,1
mov [r9],rdx
lea r9,[r9+8]
jnz @loop
@tail:
cmp eax,1
js @done
je @one
@two_three:
mov [r9],edx
lea r9,[r9+4]
cmp eax,2
jz @done
@one:
mov [r9],dx
@done:
mov rax,rcx
ret
end;
{$ELSE}
var
S: string;
begin
S:= StringOfChar(Value, RepeatCount);
Result:= Append(S);
end;
{$ENDIF}
function TStringBuilder.Append(const Value: Shortint): TStringBuilder;
{$ifdef cpux64}
var
P: PChar;
L: integer;
Storage: TCharStorage;
begin
P:= _IntToStr(Value, Storage);
L:= PInteger(P)[-1];
Result:= _Append(P, L);
end;
{$else}
begin
Result:= Append(IntToStr(Value));
end;
{$endif}
function TStringBuilder.Append(const Value: Char): TStringBuilder;
{$ifdef cpux64}
asm
//rcx = self
//dx = value
.noframe
mov rax,[rcx+TStringBuilder.FLength]
mov r8,[rcx+TStringBuilder.FCapacity]
mov r9,[rcx+TStringBuilder.FData]
cmp rax,r8
jne @AfterExpand
push rax
push rdx
push rcx
mov edx,1
call TStringBuilder.ExpandCapacity
pop rcx
pop rdx
pop rax
mov r9,[rcx+TStringBuilder.FData] //may have moved
@AfterExpand:
lea r8,[rax+1]
mov [r9+rax*2],dx
mov [rcx+TStringBuilder.FLength],r8
end;
{$endif}
{$ifndef cpux64}
//{$ifdef CPUx86}
//asm
// //eax = self
// //dx = value
// push edi
// push esi
// mov ecx,[eax+TStringBuilder.FLength]
// mov edi,[eax+TStringBuilder.FCapacity]
// mov esi,[eax+TStringBuilder.FData]
// cmp ecx,edi
// jne @AfterExpand
// push edx
// push eax
// mov edi,ecx
// mov edx,1
// call TStringBuilder.ExpandCapacity;
// pop eax
// pop edx
// mov ecx,edi
// mov esi,[eax+TStringBuilder.FData] //may have moved
//@AfterExpand:
// mov [esi+ecx*2],dx
// inc ecx
// mov [eax+TStringBuilder.FLength],ecx
// pop esi
// pop edi
//end;
//{$else}
var
LLength: NativeUInt;
begin
LLength := FLength;
if (LLength >= FCapacity) then ExpandCapacity(1);
FData[LLength] := Value;
FLength:= LLength + 1;
Result := Self;
end;
//{$endif}
{$endif}
function TStringBuilder.Append(const Value: Currency): TStringBuilder;
begin
Result:= Append(CurrToStr(Value));
end;
function TStringBuilder.Append(const Value: Boolean): TStringBuilder;
begin
case Value of
true: Result:= Append('True');
else Result:= Append('False');
end;
end;
function TStringBuilder.Append(const Value: Byte): TStringBuilder;
{$ifdef cpux64}
var
P: PChar;
L: integer;
Storage: TCharStorage;
begin
P:= _UIntToStr(Value, Storage);
L:= PInteger(P)[-1];
Result:= _Append(P, L);
end;
{$else}
begin
Result:= Append(UIntToStr(Value));
end;
{$endif}
function TStringBuilder.Append(const Value: Double): TStringBuilder;
begin
Result:= Append(FloatToStr(Value));
end;
function TStringBuilder.Append(const Value: Int64): TStringBuilder;
{$ifdef cpux64}
var
P: PChar;
L: integer;
Storage: TCharStorage;
begin
P:= _IntToStr(Value, Storage);
L:= PInteger(P)[-1];
Result:= _Append(P, L);
end;
{$else}
begin
Result:= Append(IntToStr(Value));
end;
{$endif}
function TStringBuilder.Append(const Value: TObject): TStringBuilder;
begin
{$if CompilerVersion >= 19}
Result:= Append(Value.ToString());
{$else}
Result:= Append(IntToStr(Integer(Value)));
{$ENDIF}
end;
function TStringBuilder.Append(const Value: Smallint): TStringBuilder;
{$ifdef cpux64}
var
P: PChar;
L: integer;
Storage: TCharStorage;
begin
P:= _IntToStr(Value, Storage);
L:= PInteger(P)[-1];
Result:= _Append(P, L);
end;
{$else}
begin
Result:= Append(IntToStr(Value));
end;
{$endif}
function TStringBuilder.Append(const Value: Integer): TStringBuilder;
{$ifdef cpux64}
var
Storage: TCharStorage;
P: PChar;
L: integer;
begin
P:= _IntToStr(Value, Storage);
L:= PInteger(P)[-1];
Result:= _Append(P, L);
end;
{$else}
begin
Result:= Append(IntToStr(Value));
end;
{$endif}
function TStringBuilder.AppendFormat(const Format: string; const Args: array of const): TStringBuilder;
begin
Result:= Append(System.SysUtils.Format(Format, Args));
end;
function TStringBuilder.AppendLine: TStringBuilder;
const
LineBreak = $0D000A;
var
L: NativeUInt;
begin
L:= FLength;
Length:= L + 2;
PInteger(@FData[L])^:= LineBreak;
Result:= Self;
end;
function TStringBuilder.AppendLine(const Value: string): TStringBuilder;
begin
Append(Value);
Result:= AppendLine;
end;
procedure TStringBuilder.Clear ;
begin
Length := 0;
FCapacity:= 0;
ExpandCapacity(0);
//Capacity := MALLOC_SIZE; //DefaultCapacity;
end;
procedure TStringBuilder.CheckBounds(Index: NativeUInt);
begin
if Index >= Length then
raise ERangeError.CreateResFmt(@SListIndexError, [Index]);
end;
procedure TStringBuilder.CopyTo(SourceIndex: NativeUInt;
const Destination: TCharArray; DestinationIndex, Count: NativeUInt);
begin
if DestinationIndex + Count > System.Length(Destination) then
raise ERangeError.CreateResFmt(@SInputBufferExceed,
['DestinationIndex', DestinationIndex, 'Count', Count]);
if Count > 0 then
begin
CheckBounds(SourceIndex);
CheckBounds(SourceIndex + Count - 1);
Move(FData[SourceIndex], Destination[DestinationIndex], Count * SizeOf(Char));
end;
end;
constructor TStringBuilder.Create;
begin
inherited Create;
FMaxCapacity := MaxInt;
FCapacity:= 0;
ExpandCapacity(0);
//Capacity := MALLOC_SIZE; // DefaultCapacity;
//FInsertPoint:= @FData[0];
//FLength := 0; //fields are zero initialized
end;
constructor TStringBuilder.Create(const Value: string; aCapacity: NativeUInt);
begin
inherited Create;
FMaxCapacity := MaxInt;
FCapacity:= 0;
ExpandCapacity(aCapacity);
//Capacity := aCapacity;
//FLength := 0;
Append(Value);
end;
constructor TStringBuilder.Create(const Value: string; StartIndex, Length,
aCapacity: NativeUInt);
begin
//Create(Copy(Value, StartIndex + 1, length), aCapacity);
Create(Value.Substring( StartIndex, length), aCapacity);
end;
constructor TStringBuilder.Create(aCapacity, aMaxCapacity: NativeUInt);
begin
Create(aCapacity);
FMaxCapacity := aMaxCapacity;
end;
constructor TStringBuilder.Create(aCapacity: NativeUInt);
begin
inherited Create;
FMaxCapacity := MaxInt;
FCapacity:= 0;
ExpandCapacity(ACapacity);
//Capacity := aCapacity;
FLength := 0;
end;
constructor TStringBuilder.Create(const Value: string);
begin
Create;
Append(Value);
end;
function TStringBuilder.EnsureCapacity(aCapacity: NativeUInt): NativeUInt;
begin
if aCapacity > MaxCapacity then
raise ERangeError.CreateResFmt(@SListIndexError, [aCapacity]);
if FCapacity < aCapacity then
Capacity := aCapacity;
Result := Capacity;
end;
function TStringBuilder.Equals(StringBuilder: TStringBuilder): Boolean;
begin
Result := (StringBuilder <> nil) and (Length = StringBuilder.Length) and
(MaxCapacity = StringBuilder.MaxCapacity) and
CompareMem(@FData[0], @StringBuilder.FData[0], Length * SizeOf(Char));
end;
//function Max(a,b: NativeUInt): NativeUInt; overload; inline;
//begin
// //jumpless max.
// Result:= a xor ((a xor b) and -integer(a < b));
// //Result = a.
// //if (a >= b) then x:= 0; Result:= a xor 0;
// //if (a < b) then x:= -1; Result:= a xor (a xor b) and -1
// // ^^^^^^ nop
// // ^^^^^^^^^^^^^^^swap a and b
// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Result:= b;
//end;
//
//function Min(a,b: NativeUInt): NativeUInt; overload; inline;
//begin
// Result:= a xor ((a xor b) and -integer(a > b));
//end;
//procedure TStringBuilder.ExpandCapacity(NewLength: NativeUInt);
//var
// NewCapacity: NativeUint; //do not worry about overflow.
//begin
// NewCapacity := Max(Capacity * 2, (NewLength * 3 div 2));
// Capacity:= Min(NewCapacity, MaxCapacity);
//end;
function TStringBuilder.GetChars(Index: NativeUInt): Char;
begin
CheckBounds(Index);
Result := FData[Index];
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: TObject): TStringBuilder;
begin
{$if CompilerVersion >= 19}
Result:= Insert(Index, Value.ToString());
{$else}
Result:= Insert(Index, IntToStr(Integer(Value)));
{$ENDIF}
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Int64): TStringBuilder;
begin
Result:= Insert(Index, IntToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Single): TStringBuilder;
begin
Result:= Insert(Index, FloatToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: string): TStringBuilder;
var
L: integer;
begin
if Index > Length then
raise ERangeError.CreateResFmt(@SListIndexError, [Index]);
L:= System.Length(Value);
Length := Length + L;
Move(FData[Index], FData[Index + L], (Length - L - Index) * SizeOf(Char));
Move(pointer(Value)^, FData[Index], L * SizeOf(Char));
Result := Self;
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Word): TStringBuilder;
begin
Result:= Insert(Index, IntToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Shortint): TStringBuilder;
begin
Result:= Insert(Index, IntToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: TCharArray): TStringBuilder;
var
L: NativeUint;
begin
if Index > Length then
raise ERangeError.CreateResFmt(@SListIndexError, [Index]);
L:= System.Length(Value);
Length := Length + L;
Move(FData[Index], FData[Index + L], L * SizeOf(Char));
Move(pointer(Value)^, FData[Index], L * SizeOf(Char));
Result := Self;
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Currency): TStringBuilder;
begin
Result:= Insert(Index, CurrToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Char): TStringBuilder;
begin
if Index > Length then
raise ERangeError.CreateResFmt(@SListIndexError, [Index]);
Length := Length + 1;
Move(FData[Index], FData[Index + 1], (Length - Index - 1) * SizeOf(Char));
FData[Index] := Value;
Result := Self;
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Byte): TStringBuilder;
begin
Result:= Insert(Index, IntToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Double): TStringBuilder;
begin
Result:= Insert(Index, FloatToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Integer): TStringBuilder;
begin
Result:= Insert(Index, IntToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Smallint): TStringBuilder;
begin
Result:= Insert(Index, IntToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Boolean): TStringBuilder;
begin
Result:= Insert(Index, BoolToStr(Value, True));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: string; Count: NativeUInt): TStringBuilder;
var
I: Integer;
S: string;
L: integer;
P: PChar;
begin
L:= System.Length(Value);
System.SetLength(S, L);
P:= PChar(S);
for I := 0 to Count - 1 do begin
Move(pointer(Value)^, P^, L * SizeOf(Char));
Inc(P,L);
end;
Result:= Insert(Index, S);
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: TCharArray; StartIndex,
CharCount: NativeUInt): TStringBuilder;
begin
if Index - 1 >= Length then
raise ERangeError.CreateResFmt(@SListIndexError, [Index]);
if StartIndex + CharCount > System.Length(Value) then
raise ERangeError.CreateResFmt(@SInputBufferExceed,
['StartIndex', StartIndex, 'CharCount', CharCount]);
Length := Length + CharCount;
if Length - Index > 0 then
Move(FData[Index], FData[Index + CharCount], (Length - Index) * SizeOf(Char));
Move(Value[StartIndex], FData[Index], CharCount * SizeOf(Char));
Result := Self;
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: Cardinal): TStringBuilder;
begin
Result:= Insert(Index, IntToStr(Value));
end;
function TStringBuilder.Insert(Index: NativeUInt; const Value: UInt64): TStringBuilder;
begin
Result:= Insert(Index, UIntToStr(Value));
end;
procedure TStringBuilder.ReduceCapacity;
begin
if Length >= (Capacity div 4) then ExpandCapacity(0);
end;
function TStringBuilder.Remove(StartIndex, RemLength: Integer): TStringBuilder;
begin
if RemLength <> 0 then
begin
CheckBounds(StartIndex);
CheckBounds(StartIndex + RemLength - 1);
if (Length - (StartIndex + RemLength)) > 0 then
Move(FData[StartIndex + RemLength], FData[StartIndex], (Length - (StartIndex + RemLength)) * SizeOf(Char));
Length := Length - RemLength;
ReduceCapacity;
end;
Result := Self;
end;
function TStringBuilder.Replace(const OldValue, NewValue: string; StartIndex,
Count: NativeUInt): TStringBuilder;
var
CurPtr: PChar;
EndPtr: PChar;
Index: Integer;
EndIndex: Integer;
OldLen, NewLen: Integer;
begin
Result := Self;
if Count <> 0 then
begin
if StartIndex + Count > Length then
raise ERangeError.CreateResFmt(@SInputBufferExceed,
['StartIndex', StartIndex, 'Count', Count]);
OldLen := System.Length(OldValue);
NewLen := System.Length(NewValue);
Index := StartIndex;
CurPtr := @FData[StartIndex];
EndIndex := StartIndex + Count - OldLen;
EndPtr := @FData[EndIndex];
while CurPtr <= EndPtr do
begin
if CurPtr^ = OldValue[Low(string)] then
begin
if StrLComp(CurPtr, PChar(OldValue), OldLen) = 0 then
begin
if _Replace(Index, OldValue, NewValue) then
begin
CurPtr := @FData[Index];
EndPtr := @FData[EndIndex];
end;
Inc(CurPtr, NewLen - 1);
Inc(Index, NewLen - 1);
Inc(EndPtr, NewLen - OldLen);
Inc(EndIndex, NewLen - OldLen);
end;
end;
Inc(CurPtr);
Inc(Index);
end;
end;
end;
function TStringBuilder.Replace(const OldChar, NewChar: Char; StartIndex,
Count: NativeUInt): TStringBuilder;
var
Ptr: PChar;
EndPtr: PChar;
begin
if Count <> 0 then
begin
CheckBounds(StartIndex);
CheckBounds(StartIndex + Count - 1);
EndPtr := @FData[StartIndex + Count - 1];
Ptr := @FData[StartIndex];
while Ptr <= EndPtr do
begin
if Ptr^ = OldChar then
Ptr^ := NewChar;
Inc(Ptr);
end;
end;
Result := Self;
end;
function TStringBuilder.Replace(const OldChar, NewChar: Char): TStringBuilder;
var
Ptr: PChar;
EndPtr: PChar;
begin
EndPtr := @FData[Length - 1];
Ptr := @FData[0];
while Ptr <= EndPtr do
begin
if Ptr^ = OldChar then
Ptr^ := NewChar;
Inc(Ptr);
end;
Result := Self;
end;
function TStringBuilder.Replace(const OldValue, NewValue: string): TStringBuilder;
begin
Result := self;
Replace(OldValue, NewValue, 0, Length);
end;
procedure TStringBuilder.SetCapacity(Value: NativeUInt);
begin
if Value < Length then
raise ERangeError.CreateResFmt(@SListCapacityError, [Value]);
if Value > FMaxCapacity then
raise ERangeError.CreateResFmt(@SListCapacityError, [Value]);
System.SetLength(FData, Value);
FCapacity:= Value;
end;
procedure TStringBuilder.SetChars(Index: NativeUInt; Value: Char);
begin
CheckBounds(Index);
FData[Index] := Value;
end;
function TStringBuilder.ToString: string;
begin
SetString(Result, MarshaledString(FData), Length);
end;
function TStringBuilder.ToString(StartIndex: NativeUInt; StrLength: Cardinal): string;
begin
if StrLength <> 0 then
begin
CheckBounds(StartIndex);
CheckBounds(StartIndex + StrLength - 1);
Result := string.Create(FData, StartIndex, StrLength);
end else
Result := '';
end;
function TStringBuilder._Replace(Index: NativeUInt; const Old, New: string): Boolean;
var
OldLength: Integer;
OldCapacity: Integer;
SizeChange: Integer;
begin
Result := False;
SizeChange := System.Length(New) - System.Length(Old);
if SizeChange = 0 then
begin
Move(New[Low(string)], FData[Index], System.Length(New) * SizeOf(Char));
end
else
begin
OldLength := Length;
if SizeChange > 0 then
begin
OldCapacity := Capacity;
Length := Length + SizeChange;
if OldCapacity <> Capacity then
Result := True;
end;
Move(FData[Index + System.Length(Old)], FData[Index + System.Length(New)],
(OldLength - (System.Length(Old) + Index)) * SizeOf(Char));
Move(New[Low(String)], FData[Index], System.Length(New) * SizeOf(Char));
if SizeChange < 0 then
Length := Length + SizeChange;
end;
end;
//var
// SSB: SysUtils.TStringBuilder;
// FSB: TStringBuilder;
// S: string;
// LTick: cardinal;
//
//const
// TestCount = 100 * 1000 * 100;
//
//
//procedure Timings;
//var
// Test: string;
// C: Char;
// i,j: integer;
//
//begin
// j:= 1457454;
// Test:= 'appleappleapple';
// SSB:= SysUtils.TStringBuilder.Create;
// FSB:= TStringBuilder.Create;
//
// LTick:= TThread.GetTickCount;
// for i:= 0 to TestCount do begin
// SSB.Append(Test);
// end;
//
// WriteLn('Standard SB: ',TThread.GetTickCount- LTick, 'ms');
//
// LTick:= TThread.GetTickCount;
// for i:= 0 to TestCount do begin
// FSB.Append(Test);
// end;
// Writeln('Fast SB: ',TThread.GetTickCount- LTick, 'ms');
//
// LTick:= TThread.GetTickCount;
// for i:= 0 to TestCount do begin
// S:= S + Test;
// end;
// Assert(S <> '');
// Writeln('string: ',TThread.GetTickCount- LTick, 'ms');
//
// WriteLn('Char');
// LTick:= TThread.GetTickCount;
// for i:= 0 to TestCount do begin
// SSB.Append(C);
// end;
// Writeln('Standard SB: ',TThread.GetTickCount- LTick, 'ms');
//
// LTick:= TThread.GetTickCount;
// for i:= 0 to TestCount do begin
// FSB.Append(C);
// end;
// Writeln('Fast SB: ',TThread.GetTickCount- LTick, 'ms');
//
// LTick:= TThread.GetTickCount;
// for i:= 0 to TestCount do begin
// S:= S + C;
// end;
// Assert(S <> '');
// Writeln('String: ',TThread.GetTickCount- LTick, 'ms');
//
// WriteLn('Integer');
// LTick:= TThread.GetTickCount;
// for i:= 0 to TestCount do begin
// SSB.Append(i);
// end;
// Writeln('Standard SB: ',TThread.GetTickCount- LTick, 'ms');
//
// LTick:= TThread.GetTickCount;
// for i:= 0 to TestCount do begin
// FSB.Append(i);
// end;
// Writeln('Fast SB: ',TThread.GetTickCount- LTick, 'ms');
//
// LTick:= TThread.GetTickCount;
// for i:= 0 to TestCount do begin
// S:= S + i.ToString;
// end;
// Assert(S <> '');
// Writeln('String: ',TThread.GetTickCount- LTick, 'ms');
// SSB.Free;
// FSB.Free;
// ReadLn;
//end;
initialization
// Timings;
//for j:= TestCount to TestCount + 10 do begin
// LTick:= TThread.GetTickCount;
// for I:= 1 to TestCount do begin
// _IntToStrInt64(-j, cs); //takes longer because it produces a much longer string.
// end;
// Writeln('IntToStr64: ', TThread.GetTickCount - LTick, 'ms');
//
// LTick:= TThread.GetTickCount;
// for I:= 1 to TestCount do begin
// _IntToStr(j, cs);
// end;
// Writeln('IntToStr fast: ', TThread.GetTickCount - LTick, 'ms');
//
// LTick:= TThread.GetTickCount;
// for I:= 1 to TestCount do begin
// UIntToStr(uint64(-j));
// end;
// Writeln('IntToStr system: ', TThread.GetTickCount - LTick, 'ms');
//end;
end.
|
unit uPrincipal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, StrUtils, xmldom, XMLIntf, msxmldom, XMLDoc;
const
SenhaPadrao = 'top2015';
type
TForm2 = class(TForm)
OpenDialog1: TOpenDialog;
ButtonLerUsuarios: TButton;
ListBox1: TListBox;
LabelNomeArquivo: TLabel;
XMLDocument1: TXMLDocument;
procedure ButtonLerUsuariosClick(Sender: TObject);
private
ArquivoShadow, ArquivoPasswd, ScriptCria, ScriptApaga: TStringList;
UsuariosFilezilla: TStringList;
Usuario, Senha, Descricao, Comando: String;
procedure LerNodos(XMLNode: IXMLNode);
procedure LerNodoServer(XMLNode: IXMLNode);
function TratarCaracteres(aTexto: String): String;
public
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
function TForm2.TratarCaracteres(aTexto: String): String;
var
I: Integer;
Str: String;
const
COM_ACENTO = 'àâêôûãõáéíóúçüîäëïöèìòùÀÂÊÔÛÃÕÁÉÍÓÚÇÜÎÄËÏÖÈÌÒÙ';
SEM_ACENTO = 'aaeouaoaeioucuiaeioeiouAAEOUAOAEIOUCUIAEIOEIOU';
COM_ESPECIAIS = '¹²³ªº°';
SEM_ESPECIAIS = '123aoo';
begin
Result := '';
Str := aTexto;
for I := 1 to Length(Str) do
begin
if (Pos(Str[I], COM_ACENTO) > 0) then
Str[I] := SEM_ACENTO[Pos(Str[I], COM_ACENTO)];
if (Pos(Str[I], COM_ESPECIAIS) > 0) then
Str[I] := SEM_ESPECIAIS[Pos(Str[I], COM_ESPECIAIS)];
end;
for I := 1 to Length(Str) do
if (Str[I] in [' ' .. '~']) then
Result := Result + Str[I];
Result := Trim(Result);
end;
procedure TForm2.LerNodoServer(XMLNode: IXMLNode);
begin
if (UpperCase(XMLNode.NodeName) = UpperCase('Server')) then
begin
if (XMLNode.HasChildNodes) then
begin
Usuario := XMLNode.ChildNodes['User'].Text;
Senha := XMLNode.ChildNodes['Pass'].Text;
Descricao := XMLNode.ChildNodes['Name'].Text;
Descricao := TratarCaracteres(Descricao);
if (Senha = '') then
Senha := SenhaPadrao;
if (Descricao = '') then
Descricao := Usuario;
Comando := Format('echo "criando usuario %S"', [Usuario]);
ScriptCria.Add(Comando);
Comando := Format('adduser %s -g 100 -s /sbin/nologin -p $(openssl passwd -1 %s) -c "%s"', [Usuario, Senha, Descricao]);
ScriptCria.Add(Comando);
ListBox1.Items.Add(Usuario + ' -> ' + Senha);
UsuariosFilezilla.Add(Usuario);
Comando := Format('echo "apagando usuario %S"', [Usuario]);
ScriptApaga.Add(Comando);
Comando := Format('userdel -r %s ', [Usuario]);
ScriptApaga.Add(Comando);
end;
end;
end;
procedure TForm2.LerNodos(XMLNode: IXMLNode);
var
INivel2: Integer;
XMLNodeN2: IXMLNode;
begin
if (UpperCase(XMLNode.NodeName) = 'SERVER') then
begin
LerNodoServer(XMLNode);
end;
if (UpperCase(XMLNode.NodeName) <> 'SERVER') then
begin
if (XMLNode.HasChildNodes) then
begin
for INivel2 := 0 to pred(XMLNode.ChildNodes.Count) do
begin
XMLNodeN2 := XMLNode.ChildNodes[INivel2];
if (XMLNodeN2.HasChildNodes) then
LerNodos(XMLNodeN2);
end;
end;
end;
end;
procedure TForm2.ButtonLerUsuariosClick(Sender: TObject);
var
IShadow, IPasswd: Integer;
PosicaoDelimitador1, PosicaoDelimitador2, PosicaoDelimitador3, PosicaoDelimitador4, PosicaoDelimitador5: Integer;
INivel1: Integer;
XMLNodeN1: IXMLNode;
begin
try
ListBox1.Clear;
UsuariosFilezilla := TStringList.Create;
ArquivoShadow := TStringList.Create;
ArquivoPasswd := TStringList.Create;
ScriptCria := TStringList.Create;
ScriptCria.Add('#!/bin/bash');
ScriptApaga := TStringList.Create;
ScriptApaga.Add('#!/bin/bash');
TButton(Sender).Enabled := False;
if (OpenDialog1.Execute) then
begin
if (UpperCase(ExtractFileName(OpenDialog1.FileName)) <> UpperCase('Shadow')) then
raise Exception.Create('selecionar o arquivo Shadow');
ArquivoShadow.LoadFromFile(OpenDialog1.FileName);
end;
if OpenDialog1.Execute then
begin
if (UpperCase(ExtractFileName(OpenDialog1.FileName)) <> UpperCase('Passwd')) then
raise Exception.Create('selecionar o arquivo Passwd');
ArquivoPasswd.LoadFromFile(OpenDialog1.FileName);
end;
if OpenDialog1.Execute then
if (UpperCase(ExtractFileExt(OpenDialog1.FileName)) <> UpperCase('.xml')) then
raise Exception.Create('selecionar o arquivo Passwd');
{ *********************************************************** }
XMLDocument1.FileName := '';
XMLDocument1.XML.Text := '';
XMLDocument1.Active := False;
XMLDocument1.Active := True;
XMLDocument1.Version := '1.0';
XMLDocument1.Encoding := 'UTF-8';
XMLDocument1.LoadFromFile(OpenDialog1.FileName);
ListBox1.Clear;
for INivel1 := 0 to pred(XMLDocument1.ChildNodes.Count) do
begin
XMLNodeN1 := XMLDocument1.ChildNodes[INivel1];
if (XMLNodeN1.NodeType = ntElement) then
begin
LerNodos(XMLNodeN1);
end;
end;
{ *********************************************************** }
Comando := 'echo "usuarios nao existentes no xml"';
ScriptCria.Add(Comando);
for IShadow := 0 to (ArquivoShadow.Count - 1) do
begin
PosicaoDelimitador1 := Pos(':', ArquivoShadow[IShadow]);
PosicaoDelimitador2 := PosEx(':', ArquivoShadow[IShadow], PosicaoDelimitador1 + 1);
Usuario := Copy(ArquivoShadow[IShadow], 1, PosicaoDelimitador1 - 1);
Senha := Copy(ArquivoShadow[IShadow], PosicaoDelimitador1 + 1, (PosicaoDelimitador2) - (PosicaoDelimitador1 + 1));
for IPasswd := 0 to (ArquivoPasswd.Count - 1) do
begin
PosicaoDelimitador1 := Pos(':', ArquivoPasswd[IPasswd]);
PosicaoDelimitador2 := PosEx(':', ArquivoPasswd[IPasswd], PosicaoDelimitador1 + 1);
PosicaoDelimitador3 := PosEx(':', ArquivoPasswd[IPasswd], PosicaoDelimitador2 + 1);
PosicaoDelimitador4 := PosEx(':', ArquivoPasswd[IPasswd], PosicaoDelimitador3 + 1);
PosicaoDelimitador5 := PosEx(':', ArquivoPasswd[IPasswd], PosicaoDelimitador4 + 1);
if (UpperCase(Copy(ArquivoPasswd[IPasswd], 1, PosicaoDelimitador1 - 1)) = UpperCase(Usuario)) then
Descricao := Copy(ArquivoPasswd[IPasswd], PosicaoDelimitador4 + 1, (PosicaoDelimitador5) - (PosicaoDelimitador4 + 1));
end;
if (UpperCase(Usuario) <> UpperCase('root')) then
if (UsuariosFilezilla.IndexOf(Usuario) = -1) then
begin
if (Trim(Usuario) = '') then
raise Exception.Create('erro ao ler usuario');
if (Trim(Senha) = '') then
Senha := SenhaPadrao;
if (Trim(Descricao) = '') then
Descricao := Usuario;
Descricao := TratarCaracteres(Descricao);
Comando := Format('echo "criando usuario %S"', [Usuario]);
ScriptCria.Add(Comando);
Comando := Format('adduser %s -g 100 -s /sbin/nologin -p $(openssl passwd -1 %s) -c "%s"', [Usuario, Usuario, Descricao]);
ScriptCria.Add(Comando);
ListBox1.Items.Add(Comando);
Comando := Format('echo "apagando usuario %S"', [Usuario]);
ScriptApaga.Add(Comando);
Comando := Format('userdel -r %s ', [Usuario]);
ScriptApaga.Add(Comando);
end;
end;
if (FileExists('criar.sh')) then
DeleteFile('criar.sh');
ScriptCria.SaveToFile('criar.sh');
if (FileExists('apagar.sh')) then
DeleteFile('apagar.sh');
ScriptApaga.SaveToFile('apagar.sh');
finally
FreeAndNil(UsuariosFilezilla);
FreeAndNil(ArquivoShadow);
FreeAndNil(ArquivoPasswd);
FreeAndNil(ScriptCria);
FreeAndNil(ScriptApaga);
TButton(Sender).Enabled := True;
end;
end;
end.
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
program preprocessor;
uses
unicode, json, fileutils;
type
PEntityTreeNode = ^TEntityTreeNode;
TSubNodeEntry = record
Prefix: Cardinal;
SubNode: PEntityTreeNode;
end;
TEntityTreeNode = record
StateID: Cardinal;
Children: array of TSubNodeEntry;
Value: TUnicodeCodepointArray;
end;
var
LastStateID: Cardinal = 0;
procedure Add(const Entity: AnsiString; const Index: Cardinal; const Value: TJSONArray; const Node: PEntityTreeNode);
var
SearchIndex: Cardinal;
CurrentCharacter: Cardinal;
CurrentValue: Double;
begin
Assert(Assigned(Node));
Assert(Index > 1);
if (Index > Length(Entity)) then
begin
Assert(Length(Node^.Value) = 0);
Assert(Value.Length >= 1);
Assert(Value.Length <= 2);
SetLength(Node^.Value, Value.Length);
for SearchIndex := 0 to Value.Length-1 do // $R-
begin
CurrentValue := Value[SearchIndex];
Assert(Frac(CurrentValue) = 0.0);
Assert(CurrentValue >= $0000);
Assert(CurrentValue <= $10FFFF);
Node^.Value[SearchIndex] := Trunc(CurrentValue); // $R-
end;
end
else
begin
// walk the tree
Assert(Index <= Length(Entity));
CurrentCharacter := Ord(Entity[Index]);
SearchIndex := Low(Node^.Children);
while (SearchIndex <= High(Node^.Children)) do
begin
if (Node^.Children[SearchIndex].Prefix = CurrentCharacter) then
Break;
Inc(SearchIndex);
end;
if (SearchIndex > High(Node^.Children)) then
begin
// we don't have a node for this yet
SetLength(Node^.Children, Length(Node^.Children)+1);
Assert(SearchIndex = High(Node^.Children));
Node^.Children[SearchIndex].Prefix := Ord(Entity[Index]);
New(Node^.Children[SearchIndex].SubNode);
Inc(LastStateID);
Node^.Children[SearchIndex].SubNode^.StateID := LastStateID;
end;
Assert(Index < High(Index)); // we'd presumably crash long before we reach this...
Add(Entity, Index+1, Value, Node^.Children[SearchIndex].SubNode); // $R-
end;
end;
procedure PrintStates(const Root: PEntityTreeNode; const LastDefault: PEntityTreeNode = nil);
var
Index: Cardinal;
NewDefault: PEntityTreeNode;
begin
if (Length(Root^.Children) > 0) then
begin
Writeln(' ', Root^.StateID, ': case (Character.Value) of');
for Index := Low(Root^.Children) to High(Root^.Children) do // $R-
begin
Write(' ', Root^.Children[Index].Prefix, ': ');
if (Length(Root^.Children[Index].SubNode^.Children) = 0) then
begin
Assert(Root^.Children[Index].Prefix = Ord(';'));
Assert(Length(Root^.Children[Index].SubNode^.Value) > 0);
Assert(Length(Root^.Children[Index].SubNode^.Value) <= 2);
Write('FinishedWithSemicolon(', Root^.Children[Index].SubNode^.Value[0].Value);
if (Length(Root^.Children[Index].SubNode^.Value) = 2) then
Write(', ', Root^.Children[Index].SubNode^.Value[1].Value);
Writeln(');');
end
else
if (Length(Root^.Children[Index].SubNode^.Value) > 0) then
begin
Writeln('IncompleteButBookmark(', Root^.Children[Index].SubNode^.StateID, ');');
end
else
begin
Writeln('Incomplete(', Root^.Children[Index].SubNode^.StateID, ');');
end;
end;
if (Length(Root^.Value) > 0) then
begin
Assert(Length(Root^.Value) = 1);
Writeln(' else FailButBacktrack(', Root^.Value[0].Value, ');')
end
else
if (Assigned(LastDefault)) then
begin
Assert(Length(LastDefault^.Value) = 1);
Writeln(' else FailButBacktrack(', LastDefault^.Value[0].Value, ');')
end
else
begin
Writeln(' else Fail();');
end;
Writeln(' end;');
end;
if (Length(Root^.Value) > 0) then
NewDefault := Root
else
NewDefault := LastDefault;
if (Length(Root^.Children) > 0) then
for Index := Low(Root^.Children) to High(Root^.Children) do
PrintStates(Root^.Children[Index].SubNode, NewDefault);
end;
procedure DisposeTree(const Node: PEntityTreeNode);
var
Index: Cardinal;
begin
if (Length(Node^.Children) > 0) then
for Index := Low(Node^.Children) to High(Node^.Children) do
DisposeTree(Node^.Children[Index].SubNode);
Dispose(Node);
end;
var
Data: TJSON;
Tree: PEntityTreeNode;
EntityName: AnsiString;
begin
Tree := New(PEntityTreeNode);
Tree^.StateID := 0;
Data := ParseJSON(ReadTextFile('src/entities/entities.json'));
Assert(Data is TJSONObject);
try
for EntityName in (Data as TJSONObject).Keys do
Add(EntityName, 2, Data[EntityName]['codepoints'], Tree);
PrintStates(Tree);
finally
Data.Free();
DisposeTree(Tree);
end;
end.
|
unit Modelo.ConfigBd;
interface
uses
Winapi.Windows;
type
TConfigBd = class
private
FServidor : string;
FBanco : string;
public
property Servidor : string read FServidor write FServidor;
property Banco : string read FBanco write FBanco;
procedure GravaRegistroBd(AServidor, ABanco: string);
procedure RetornaRegistroBd(var AServidor: string; var ABanco: string);
end;
const
lLocal = HKEY_CURRENT_USER;
lChave = 'Software\\SoftPosto\\';
implementation
uses
Classes.Funcoes;
{ TConfigBd }
procedure TConfigBd.GravaRegistroBd(AServidor, ABanco: string);
begin
TFuncao.SalvarRegistroWindows(lLocal, lChave, 'ServidorBd', AServidor);
TFuncao.SalvarRegistroWindows(lLocal, lChave, 'Banco', ABanco);
end;
procedure TConfigBd.RetornaRegistroBd(var AServidor, ABanco: string);
begin
AServidor := TFuncao.LerRegistroWindows(lLocal, lChave, 'ServidorBd');
ABanco := TFuncao.LerRegistroWindows(lLocal, lChave, 'Banco');
end;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2012-2-24
描述: 运行参数
*******************************************************************************}
unit UFrameParam;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrameBase, StdCtrls, ExtCtrls, ComCtrls, ImgList, Menus,
CheckLst, Buttons;
type
TfFrameParam = class(TfFrameBase)
ImageList1: TImageList;
wPage: TPageControl;
TabSheet1: TTabSheet;
Group1: TGroupBox;
Label1: TLabel;
CheckAutoMin: TCheckBox;
CheckAutoRun: TCheckBox;
TabSheet3: TTabSheet;
Label2: TLabel;
GroupPack: TGroupBox;
ListPack: TCheckListBox;
Label3: TLabel;
TabSheet4: TTabSheet;
Bevel1: TBevel;
Label4: TLabel;
Label6: TLabel;
NamesDB: TComboBox;
Label7: TLabel;
NamesPerform: TComboBox;
EditPack: TLabeledEdit;
BtnAddPack: TSpeedButton;
BtnDelPack: TSpeedButton;
GroupDB: TGroupBox;
Label10: TLabel;
Bevel3: TBevel;
Label11: TLabel;
BtnAddDB: TSpeedButton;
BtnDelDB: TSpeedButton;
ListDB: TCheckListBox;
EditDB: TLabeledEdit;
LabeledEdit12: TLabeledEdit;
LabeledEdit13: TLabeledEdit;
LabeledEdit14: TLabeledEdit;
LabeledEdit15: TLabeledEdit;
LabeledEdit16: TLabeledEdit;
LabeledEdit17: TLabeledEdit;
MemoConn: TMemo;
Label12: TLabel;
GroupPerform: TGroupBox;
Label13: TLabel;
Bevel4: TBevel;
Label14: TLabel;
BtnAddPerform: TSpeedButton;
BtnDelPerform: TSpeedButton;
ListPerform: TCheckListBox;
EditPerform: TLabeledEdit;
LabeledEdit18: TLabeledEdit;
LabeledEdit19: TLabeledEdit;
LabeledEdit20: TLabeledEdit;
LabeledEdit21: TLabeledEdit;
LabeledEdit22: TLabeledEdit;
Label15: TLabel;
EditBehConn: TComboBox;
Label16: TLabel;
EditBehBus: TComboBox;
LabeledEdit11: TLabeledEdit;
LabeledEdit23: TLabeledEdit;
procedure CheckAutoRunClick(Sender: TObject);
procedure BtnAddDBClick(Sender: TObject);
procedure BtnDelDBClick(Sender: TObject);
procedure ListDBClick(Sender: TObject);
procedure EditDBChange(Sender: TObject);
procedure BtnAddPerformClick(Sender: TObject);
procedure BtnDelPerformClick(Sender: TObject);
procedure ListPerformClick(Sender: TObject);
procedure EditPerformChange(Sender: TObject);
procedure wPageChange(Sender: TObject);
procedure BtnAddPackClick(Sender: TObject);
procedure BtnDelPackClick(Sender: TObject);
procedure ListPackClick(Sender: TObject);
procedure EditPackChange(Sender: TObject);
procedure ListPackClickCheck(Sender: TObject);
private
{ Private declarations }
function GetEditText(const nFlag: string): string;
procedure SetEditText(const nFlag,nText: string);
//读写内容
procedure CheckItem(const nID: string; const nList: TCheckListBox);
//选中指定项
public
{ Public declarations }
procedure OnCreateFrame; override;
procedure OnDestroyFrame; override;
class function FrameID: integer; override;
end;
implementation
{$R *.dfm}
uses
ULibFun, UMgrControl, UMgrDBConn, USysShareMem, UParamManager,
USysLoger, USmallFunc, UMITConst, uROClassFactories;
class function TfFrameParam.FrameID: integer;
begin
Result := cFI_FrameParam;
end;
procedure TfFrameParam.OnCreateFrame;
begin
inherited;
Name := MakeFrameName(FrameID);
wPage.ActivePage := TabSheet1;
CheckAutoMin.Checked := gSysParam.FAutoMin;
CheckAutoRun.Checked := gSysParam.FAutoStart;
with gParamManager do
begin
LoadParam(NamesDB.Items, ptDB);
LoadParam(NamesPerform.Items, ptPerform);
LoadParam(ListPack.Items, ptPack);
ListPackClickCheck(ListPack);
LoadParam(ListDB.Items, ptDB);
ListPackClickCheck(ListDB);
LoadParam(ListPerform.Items, ptPerform);
ListPackClickCheck(ListPerform);
end;
end;
procedure TfFrameParam.OnDestroyFrame;
begin
inherited;
end;
//------------------------------------------------------------------------------
procedure TfFrameParam.CheckAutoRunClick(Sender: TObject);
begin
if Sender = CheckAutoMin then
gSysParam.FAutoMin := CheckAutoMin.Checked;
if Sender = CheckAutoRun then
gSysParam.FAutoStart := CheckAutoRun.Checked;
end;
//Desc: 更新列表
procedure TfFrameParam.wPageChange(Sender: TObject);
begin
if (wPage.ActivePage = TabSheet1) and gParamManager.Modified then
begin
gParamManager.LoadParam(NamesDB.Items, ptDB);
gParamManager.LoadParam(NamesPerform.Items, ptPerform);
gParamManager.ParamAction(False);
end;
end;
//Desc: 屏蔽选择
procedure TfFrameParam.ListPackClickCheck(Sender: TObject);
var nStr: string;
begin
with gParamManager do
begin
nStr := '';
if Sender = ListPack then
begin
if Assigned(ActiveParam) then
nStr := ActiveParam.FItemID;
CheckItem(nStr, ListPack);
end;
if Sender = ListDB then
begin
if Assigned(ActiveParam) and Assigned(ActiveParam.FDB) then
nStr := ActiveParam.FDB.FID;
CheckItem(nStr, ListDB);
end;
if Sender = ListPerform then
begin
if Assigned(ActiveParam) and Assigned(ActiveParam.FPerform) then
nStr := ActiveParam.FPerform.FID;
CheckItem(nStr, ListPerform);
end;
end;
end;
//Date: 2012-2-24
//Parm: 标识;标题
//Desc: 设置标识为nFlag的文本为nText
procedure TfFrameParam.SetEditText(const nFlag, nText: string);
var nIdx: Integer;
nCtrl: TWinControl;
begin
if nFlag[1] = 'D' then nCtrl := GroupDB else
if nFlag[1] = 'P' then nCtrl := GroupPerform else Exit;
for nIdx:=nCtrl.ControlCount - 1 downto 0 do
if nCtrl.Controls[nIdx].Hint = nFlag then
begin
if nCtrl.Controls[nIdx] is TEdit then
TEdit(nCtrl.Controls[nIdx]).Text := nText else
if nCtrl.Controls[nIdx] is TLabeledEdit then
TLabeledEdit(nCtrl.Controls[nIdx]).Text := nText;
Break;
end;
end;
//Date: 2012-3-4
//Parm: 标识
//Desc: 获取nFlag的文本内容
function TfFrameParam.GetEditText(const nFlag: string): string;
var nIdx: Integer;
nCtrl: TWinControl;
begin
Result := '';
if nFlag[1] = 'D' then nCtrl := GroupDB else
if nFlag[1] = 'P' then nCtrl := GroupPerform else Exit;
for nIdx:=nCtrl.ControlCount - 1 downto 0 do
if nCtrl.Controls[nIdx].Hint = nFlag then
begin
if nCtrl.Controls[nIdx] is TEdit then
Result := TEdit(nCtrl.Controls[nIdx]).Text else
if nCtrl.Controls[nIdx] is TLabeledEdit then
Result := TLabeledEdit(nCtrl.Controls[nIdx]).Text;
Break;
end;
end;
//Date: 2012-3-4
//Parm: 标识;列表
//Desc: 在nList中选中标识为nID的项
procedure TfFrameParam.CheckItem(const nID: string; const nList: TCheckListBox);
var nIdx: Integer;
begin
for nIdx:=nList.Count - 1 downto 0 do
nList.Checked[nIdx] := CompareText(nID, nList.Items[nIdx]) = 0;
//xxxxx
end;
//------------------------------------------------------------------------------
//Desc: 添加DB参数
procedure TfFrameParam.BtnAddDBClick(Sender: TObject);
var nP: PDBParam;
nDB: TDBParam;
begin
nDB.FID := '新建参数';
nP := gParamManager.GetDB(nDB.FID);
if not Assigned(nP) then
with gParamManager do
begin
InitDB(nDB);
AddDB(nDB);
LoadParam(ListDB.Items, ptDB);
if Assigned(ActiveParam) and Assigned(ActiveParam.FDB) then
CheckItem(ActiveParam.FDB.FID, ListDB);
//xxxxx
end;
end;
//Desc: 删除DB参数
procedure TfFrameParam.BtnDelDBClick(Sender: TObject);
var nIdx: Integer;
begin
nIdx := ListDB.ItemIndex;
if nIdx < 0 then Exit;
with gParamManager do
begin
DelDB(ListDB.Items[ListDB.ItemIndex]);
LoadParam(ListDB.Items, ptDB);
if Assigned(ActiveParam) and Assigned(ActiveParam.FDB) then
CheckItem(ActiveParam.FDB.FID, ListDB);
//xxxxx
if nIdx >= ListDB.Count then Dec(nIdx);
if nIdx > -1 then
begin
ListDB.ItemIndex := nIdx;
ListDBClick(nil);
end;
end;
end;
//Desc: 显示DB参数
procedure TfFrameParam.ListDBClick(Sender: TObject);
var nP: PDBParam;
begin
if ListDB.ItemIndex > -1 then
begin
nP := gParamManager.GetDB(ListDB.Items[ListDB.ItemIndex]);
if not Assigned(nP) then Exit;
with nP^ do
begin
SetEditText('D.1', FID);
SetEditText('D.2', FHost);
SetEditText('D.3', IntToStr(FPort));
SetEditText('D.4', FDB);
SetEditText('D.5', FUser);
SetEditText('D.6', FPwd);
SetEditText('D.7', IntToStr(FNumWorker));
MemoConn.Text := FConn;
end;
end;
end;
//Desc: 数据生效
procedure TfFrameParam.EditDBChange(Sender: TObject);
var nP: PDBParam;
nCtrl: TWinControl;
begin
if ListDB.ItemIndex > -1 then
begin
nCtrl := TWinControl(Sender);
if not nCtrl.Focused then Exit;
nP := gParamManager.GetDB(ListDB.Items[ListDB.ItemIndex]);
if not Assigned(nP) then Exit;
with nP^ do
begin
FID := GetEditText('D.1');
FHost := GetEditText('D.2');
if (nCtrl.Hint = 'D.3') and IsNumber(TLabeledEdit(nCtrl).Text, False) then
FPort := StrToInt(GetEditText('D.3'));
//xxxxx
FDB := GetEditText('D.4');
FUser := GetEditText('D.5');
FPwd := GetEditText('D.6');
if (nCtrl.Hint = 'D.7') and IsNumber(TLabeledEdit(nCtrl).Text, False) then
FNumWorker := StrToInt(GetEditText('D.7'));
FConn := MemoConn.Text;
gParamManager.Modified := True;
if nCtrl.Hint = 'D.1' then
ListDB.Items[ListDB.ItemIndex] := FID;
//xxxxx
end;
end;
end;
//------------------------------------------------------------------------------
//Desc: 添加Perform参数
procedure TfFrameParam.BtnAddPerformClick(Sender: TObject);
var nP: PPerformParam;
nPerform: TPerformParam;
begin
nPerform.FID := '新建参数';
nP := gParamManager.GetPerform(nPerform.FID);
if not Assigned(nP) then
with gParamManager do
begin
InitPerform(nPerform);
AddPerform(nPerform);
LoadParam(ListPerform.Items, ptPerform);
if Assigned(ActiveParam) and Assigned(ActiveParam.FPerform) then
CheckItem(ActiveParam.FPerform.FID, ListPerform);
//xxxxx
end;
end;
//Desc: 删除Perform参数
procedure TfFrameParam.BtnDelPerformClick(Sender: TObject);
var nIdx: Integer;
begin
nIdx := ListPerform.ItemIndex;
if nIdx < 0 then Exit;
with gParamManager do
begin
DelPerform(ListPerform.Items[ListPerform.ItemIndex]);
LoadParam(ListPerform.Items, ptPerform);
if Assigned(ActiveParam) and Assigned(ActiveParam.FPerform) then
CheckItem(ActiveParam.FPerform.FID, ListPerform);
//xxxxx
if nIdx >= ListDB.Count then Dec(nIdx);
if nIdx > -1 then
begin
ListPerform.ItemIndex := nIdx;
ListPerformClick(nil);
end;
end;
end;
procedure TfFrameParam.ListPerformClick(Sender: TObject);
var nP: PPerformParam;
begin
if ListPerform.ItemIndex > -1 then
begin
nP := gParamManager.GetPerform(ListPerform.Items[ListPerform.ItemIndex]);
if not Assigned(nP) then Exit;
with nP^ do
begin
SetEditText('P.1', FID);
SetEditText('P.2', IntToStr(FMonInterval));
SetEditText('P.3', IntToStr(FPortTCP));
SetEditText('P.4', IntToStr(FPortHttp));
SetEditText('P.5', IntToStr(FPoolSizeConn));
SetEditText('P.6', IntToStr(FPoolSizeBusiness));
SetEditText('P.7', IntToStr(FPoolSizeSAP));
SetEditText('P.8', IntToStr(FMaxRecordCount));
EditBehConn.ItemIndex := Ord(FPoolBehaviorConn);
EditBehBus.ItemIndex := Ord(FPoolBehaviorBusiness);
end;
end;
end;
//Desc: 参数生效
procedure TfFrameParam.EditPerformChange(Sender: TObject);
var nP: PPerformParam;
nCtrl: TWinControl;
begin
if ListPerform.ItemIndex > -1 then
begin
nCtrl := TWinControl(Sender);
if not nCtrl.Focused then Exit;
nP := gParamManager.GetPerform(ListPerform.Items[ListPerform.ItemIndex]);
if not Assigned(nP) then Exit;
with nP^ do
begin
FID := GetEditText('P.1');
if (nCtrl.Hint = 'P.2') and IsNumber(TLabeledEdit(nCtrl).Text, False) then
FMonInterval := StrToInt(GetEditText('P.2'));
//xxxxx
if (nCtrl.Hint = 'P.3') and IsNumber(TLabeledEdit(nCtrl).Text, False) then
FPortTCP := StrToInt(GetEditText('P.3'));
if (nCtrl.Hint = 'P.4') and IsNumber(TLabeledEdit(nCtrl).Text, False) then
FPortHttp := StrToInt(GetEditText('P.4'));
if (nCtrl.Hint = 'P.5') and IsNumber(TLabeledEdit(nCtrl).Text, False) then
FPoolSizeConn := StrToInt(GetEditText('P.5'));
if (nCtrl.Hint = 'P.6') and IsNumber(TLabeledEdit(nCtrl).Text, False) then
FPoolSizeBusiness := StrToInt(GetEditText('P.6'));
if (nCtrl.Hint = 'P.7') and IsNumber(TLabeledEdit(nCtrl).Text, False) then
FPoolSizeSAP := StrToInt(GetEditText('P.7'));
if (nCtrl.Hint = 'P.8') and IsNumber(TLabeledEdit(nCtrl).Text, False) then
FMaxRecordCount := StrToInt(GetEditText('P.8'));
FPoolBehaviorConn := TROPoolBehavior(EditBehConn.ItemIndex);
FPoolBehaviorBusiness := TROPoolBehavior(EditBehBus.ItemIndex);
gParamManager.Modified := True;
if nCtrl.Hint = 'P.1' then
ListPerform.Items[ListPerform.ItemIndex] := FID;
//xxxxx
end;
end;
end;
//------------------------------------------------------------------------------
//Desc: 添加Pack参数
procedure TfFrameParam.BtnAddPackClick(Sender: TObject);
var nP: PParamItemPack;
nPack: TParamItemPack;
begin
nPack.FItemID := '新建参数';
nP := gParamManager.GetParamPack(nPack.FItemID);
if not Assigned(nP) then
with gParamManager do
begin
InitPack(nPack);
AddPack(nPack);
LoadParam(ListPack.Items, ptPack);
if Assigned(ActiveParam) then
CheckItem(ActiveParam.FItemID, ListPack);
//xxxxx
end;
end;
//Desc: 删除Pack参数
procedure TfFrameParam.BtnDelPackClick(Sender: TObject);
var nIdx: Integer;
begin
nIdx := ListPack.ItemIndex;
if nIdx < 0 then Exit;
with gParamManager do
begin
DelPack(ListPack.Items[ListPack.ItemIndex]);
LoadParam(ListPack.Items, ptPack);
if Assigned(ActiveParam) then
CheckItem(ActiveParam.FItemID, ListPack);
//xxxxx
if nIdx >= ListPack.Count then Dec(nIdx);
if nIdx > -1 then
begin
ListPack.ItemIndex := nIdx;
ListPackClick(nil);
end;
end;
end;
//Desc: 显示内容
procedure TfFrameParam.ListPackClick(Sender: TObject);
var nP: PParamItemPack;
begin
if ListPack.ItemIndex > -1 then
begin
nP := gParamManager.GetParamPack(ListPack.Items[ListPack.ItemIndex]);
if not Assigned(nP) then Exit;
with nP^ do
begin
EditPack.Text := FItemID;
NamesDB.ItemIndex := NamesDB.Items.IndexOf(FNameDB);
NamesPerform.ItemIndex := NamesPerform.Items.IndexOf(FNamePerform);
end;
end;
end;
//Desc: 内容生效
procedure TfFrameParam.EditPackChange(Sender: TObject);
var nP: PParamItemPack;
nCtrl: TWinControl;
begin
if ListPack.ItemIndex > -1 then
begin
nCtrl := TWinControl(Sender);
if not nCtrl.Focused then Exit;
nP := gParamManager.GetParamPack(ListPack.Items[ListPack.ItemIndex]);
if not Assigned(nP) then Exit;
with nP^ do
begin
FItemID := EditPack.Text;
FNameDB := NamesDB.Text;
FDB := gParamManager.GetDB(FNameDB);
FNamePerform := NamesPerform.Text;
FPerform := gParamManager.GetPerform(FNamePerform);
gParamManager.Modified := True;
if nCtrl = EditPack then
ListPack.Items[ListPack.ItemIndex] := FItemID;
//xxxxx
end;
end;
end;
initialization
gControlManager.RegCtrl(TfFrameParam, TfFrameParam.FrameID);
end.
|
/// classe transiente que controla o filtro
/// tomar como base o seguinte esquema para criar as condições de filtro (filter conditions)
/// https://github.com/nestjsx/crud/wiki/Requests
/// Syntax:
/// ?filter=field||$condition||value
unit Filtro;
interface
uses
Classes, System.StrUtils, System.SysUtils;
type
TFiltro = class
private
FCampo: string;
FValor: string;
FDataInicial: string;
FDataFinal: string;
FCondicao: string;
FWhere: string;
public
constructor Create(Filter: string);
property Campo: string read FCampo write FCampo;
property Valor: string read FValor write FValor;
property DataInicial: string read FDataInicial write FDataInicial;
property DataFinal: string read FDataFinal write FDataFinal;
property Condicao: string read FCondicao write FCondicao;
property Where: string read FWhere write FWhere;
end;
implementation
{ TFiltro }
constructor TFiltro.Create(Filter: string);
var
Condicoes: TStrings;
Datas: TStrings;
PartesDoFiltro: TStrings;
I: Integer;
begin
PartesDoFiltro := TStringList.Create;
Condicoes := TStringList.Create;
Datas := TStringList.Create;
try
Filter := StringReplace(Filter, '||', '*', [rfReplaceAll, rfIgnoreCase]);
// separa as partes do filtro, caso existam
ExtractStrings(['?'], [], PChar(Filter), PartesDoFiltro);
for I := 0 to PartesDoFiltro.Count - 1 do
begin
Condicoes.Clear;
ExtractStrings(['*'], [], PChar(PartesDoFiltro[I]), Condicoes);
Condicao := Condicoes[1];
if I > 0 then
Where := Where + ' AND ';
// $cont (LIKE %val%, contains)
if Condicao = '$cont' then
begin
Campo := Condicoes[0];
Valor := Condicoes[2];
Where := Where + Campo + ' like "%' + Valor + '%"';
end;
// $eq (=, equal)
if Condicao = '$eq' then
begin
Campo := Condicoes[0];
Valor := Condicoes[2];
Where := Where + Campo + ' = "' + Valor + '"';
end;
// $between (BETWEEN, between, accepts two values)
if Condicao = '$between' then
begin
Campo := Condicoes[0];
ExtractStrings([','], [], PChar(Condicoes[2]), Datas);
DataInicial := Datas[0];
DataFinal := Datas[1];
Where := Where + Campo + ' between ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal);
end;
end;
finally
Condicoes.Free;
Datas.Free;
PartesDoFiltro.Free;
end;
end;
end.
|
// ----------------------------------------------------------------------------
// Unit : PxSplash.pas - a part of PxLib
// Author : Matthias Hryniszak
// Date :
// Version : 1.0
// Description :
// Changes log : 2005-06-01 - initial version
// 2005-06-22 - changed the way the message loop is driven.
// Now it is a separate thread.
// ToDo : Testing.
// ----------------------------------------------------------------------------
unit PxSplash;
interface
uses
{$IFDEF USEVCL}
Forms,
{$ENDIF}
Windows, Messages;
//
// This unit requires that in the splash bitmap is included in the exe resources, ie:
//
// splash.rc:
// SPLASH BITMAP "appsplash.bmp"
//
// and the resulting resource file is linked to the executable with
//
// project.dpr:
// {$R Splash.res}
//
// Show the splash for Timeout miliseconds.
// If Timeout = 0 equals then no timeout. In that case use HideSplash to manualy remove the splash from screen
//
procedure ShowSplash(Timeout: Integer);
//
// Call this to hide the splash manually (see ShowSplash without timeout)
//
procedure HideSplash;
implementation
const
SPLASH_WIDTH = 440;
SPLASH_HEIGHT = 221;
SPLASH_CLASS = 'SPLASH';
var
SplashClass: WNDCLASS;
hSplashWnd: THandle;
hSplashLogo: THandle;
hSplashThread: THandle;
function SplashWndProc(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): Integer; stdcall;
var
PS: PAINTSTRUCT;
DC, BDC: HDC;
begin
case Msg of
WM_CREATE:
begin
hSplashLogo := LoadBitmap(hInstance, 'SPLASH');
Result := 0;
end;
WM_DESTROY:
begin
DeleteObject(hSplashLogo);
PostQuitMessage(0);
Result := 0;
end;
WM_PAINT:
begin
DC := BeginPaint(hWnd, PS);
BDC := CreateCompatibleDC(DC);
SelectObject(BDC, hSplashLogo);
BitBlt(DC, 0, 0, SPLASH_WIDTH, SPLASH_HEIGHT, BDC, 0, 0, SRCCOPY);
DeleteDC(BDC);
EndPaint(hWnd, PS);
Result := 0;
end;
WM_CLOSE:
begin
Result := DefWindowProc(hWnd, Msg, wParam, lParam);
end;
WM_TIMER:
begin
KillTimer(hWnd, 1);
DestroyWindow(hWnd);
Result := 0;
end;
else Result := DefWindowProc(hWnd, Msg, wParam, lParam);
end;
end;
procedure SplashThread(Data: Pointer); stdcall;
var
M: MSG;
R: TRect;
Timeout: Integer;
begin
Timeout := Integer(Data);
SplashClass.style := CS_VREDRAW or CS_HREDRAW;
SplashClass.lpfnWndProc := @SplashWndProc;
SplashClass.cbClsExtra := 0;
SplashClass.cbWndExtra := 0;
SplashClass.hInstance := hInstance;
SplashClass.hIcon := 0;
SplashClass.hCursor := LoadCursor(hInstance, IDC_WAIT);
SplashClass.hbrBackground := 0;
SplashClass.lpszMenuName := '';
SplashClass.lpszClassName := SPLASH_CLASS;
RegisterClass(SplashClass);
GetClientRect(GetDesktopWindow, R);
R.Left := (R.Right - SPLASH_WIDTH) div 2;
R.Top := (R.Bottom - SPLASH_Height) div 2;
hSplashWnd := CreateWindowEx(WS_EX_TOPMOST or WS_EX_TOOLWINDOW, SPLASH_CLASS, '', WS_CHILD or WS_POPUP, R.Left, R.Top, SPLASH_WIDTH, SPLASH_HEIGHT, GetDesktopWindow, 0, HInstance, nil);
ShowWindow(hSplashWnd, SW_SHOWNORMAL);
UpdateWindow(hSplashWnd);
if Timeout > 0 then
SetTimer(hSplashWnd, 1, Timeout, nil);
while GetMessage(M, 0, 0, 0) do
begin
TranslateMessage(M);
DispatchMessage(M);
end;
UnregisterClass(SPLASH_CLASS, hInstance);
// ExitThread(0);
end;
procedure ShowSplash;
var
TID: Cardinal;
begin
// create the splash thread so that messages are
hSplashThread := CreateThread(nil, 4096, @SplashThread, Pointer(Timeout), 0, TID);
end;
procedure HideSplash;
begin
if hSplashWnd <> 0 then
begin
// Close the splash window and wait 'till the splash thread terminates
SendMessage(hSplashWnd, WM_TIMER, 1, 0);
WaitForSingleObject(hSplashThread, INFINITE);
{$IFDEF USEVCL}
// Make the top-most window active
//
// Warning: If a additional form is created before the main application form it becomes the active window
//
if Screen.FormCount > 0 then
SetForegroundWindow(Screen.Forms[0].Handle);
{$ENDIF}
end;
end;
end.
|
unit MetropolisDark;
interface
uses
Classes, dxCore, dxCoreGraphics, dxGDIPlusApi, cxLookAndFeelPainters, dxSkinsCore, dxSkinsLookAndFeelPainter;
type
{ TdxSkinMetropolisDarkPainter }
TdxSkinMetropolisDarkPainter = class(TdxSkinLookAndFeelPainter)
public
function LookAndFeelName: string; override;
end;
implementation
{$R MetropolisDark.res}
const
SkinsCount = 1;
SkinNames: array[0..SkinsCount - 1] of string = (
'MetropolisDark'
);
SkinPainters: array[0..SkinsCount - 1] of TdxSkinLookAndFeelPainterClass = (
TdxSkinMetropolisDarkPainter
);
{ TdxSkinMetropolisDarkPainter }
function TdxSkinMetropolisDarkPainter.LookAndFeelName: string;
begin
Result := 'MetropolisDark';
end;
//
procedure RegisterPainters;
var
I: Integer;
begin
if CheckGdiPlus then
begin
for I := 0 to SkinsCount - 1 do
cxLookAndFeelPaintersManager.Register(SkinPainters[I].Create(SkinNames[I], HInstance));
end;
end;
procedure UnregisterPainters;
var
I: Integer;
begin
if cxLookAndFeelPaintersManager <> nil then
begin
for I := 0 to SkinsCount - 1 do
cxLookAndFeelPaintersManager.Unregister(SkinNames[I]);
end;
end;
{$IFNDEF DXSKINDYNAMICLOADING}
initialization
dxUnitsLoader.AddUnit(@RegisterPainters, @UnregisterPainters);
finalization
dxUnitsLoader.RemoveUnit(@UnregisterPainters);
{$ENDIF}
end.
|
{********************************************************}
{ }
{ Zeos Database Objects }
{ Oracle8 Query and Table components }
{ }
{ Copyright (c) 1999-2001 Sergey Seroukhov }
{ Copyright (c) 1999-2002 Zeos Development Group }
{ }
{********************************************************}
unit ZOraSqlQuery;
interface
{$R *.dcr}
uses
{$IFNDEF LINUX}
Windows, Db,
{$ELSE}
DB,
{$ENDIF}
SysUtils, Classes, ZDirSql, ZDirOraSql, DbCommon,
ZOraSqlCon, ZOraSqlTr, ZToken, ZLibOraSql, ZSqlExtra, ZQuery,
ZSqlTypes, ZSqlItems, ZSqlBuffer;
{$IFNDEF LINUX}
{$INCLUDE ..\Zeos.inc}
{$ELSE}
{$INCLUDE ../Zeos.inc}
{$ENDIF}
type
TZOraSqlOption = (ooAutoIncKey);
TZOraSqlOptions = set of TZOraSqlOption;
{ Direct Oracle8 dataset with descendant of TZDataSet }
TZCustomOraSqlDataset = class(TZDataSet)
private
FExtraOptions: TZOraSqlOptions;
procedure SetDatabase(Value: TZOraSqlDatabase);
procedure SetTransact(Value: TZOraSqlTransact);
function GetDatabase: TZOraSqlDatabase;
function GetTransact: TZOraSqlTransact;
protected
{ Overriding ZDataset methods }
procedure QueryRecord; override;
procedure UpdateAfterInit(RecordData: PRecordData); override;
procedure UpdateAfterPost(OldData, NewData: PRecordData); override;
{$IFDEF WITH_IPROVIDER}
{ IProvider support }
function PSInTransaction: Boolean; override;
function PSExecuteStatement(const ASql: string; AParams: TParams;
ResultSet: Pointer): Integer; override;
procedure PSSetCommandText(const CommandText: string); override;
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
procedure AddTableFields(Table: string; SqlFields: TSqlFields); override;
procedure AddTableIndices(Table: string; SqlFields: TSqlFields;
SqlIndices: TSqlIndices); override;
function FieldValueToSql(Value: string; FieldDesc: PFieldDesc): string; override;
{ Buffer support methods }
procedure CopyRecord(SqlBuffer: TSqlBuffer; Source, Dest: PRecordData); override;
procedure FreeRecord(SqlBuffer: TSqlBuffer; Value: PRecordData); override;
published
property ExtraOptions: TZOraSqlOptions read FExtraOptions write FExtraOptions;
property Database: TZOraSqlDatabase read GetDatabase write SetDatabase;
property Transaction: TZOraSqlTransact read GetTransact write SetTransact;
end;
{ Direct OraSql query with descendant of TDataSet }
TZOraSqlQuery = class(TZCustomOraSqlDataset)
public
property MacroCount;
property ParamCount;
published
property MacroChar;
property Macros;
property MacroCheck;
property Params;
property ParamCheck;
property DataSource;
property Sql;
property RequestLive;
property Database;
property Transaction;
property Active;
end;
{ Direct OraSql query with descendant of TDataSet }
TZOraSqlTable = class(TZCustomOraSqlDataset)
public
constructor Create(AOwner: TComponent); override;
published
property TableName;
property ReadOnly default False;
property DefaultIndex default True;
property Database;
property Transaction;
property Active;
end;
implementation
uses ZExtra, ZDBaseConst, ZBlobStream, Math;
{********** TZCustomOraSqlDataset implementation **********}
{ Class constructor }
constructor TZCustomOraSqlDataset.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Query := TDirOraSqlQuery.Create(nil, nil);
DatabaseType := dtOracle;
FExtraOptions := [];
end;
{ Set connect to database component }
procedure TZCustomOraSqlDataset.SetDatabase(Value: TZOraSqlDatabase);
begin
inherited SetDatabase(Value);
end;
{ Set connect to transact-server component }
procedure TZCustomOraSqlDataset.SetTransact(Value: TZOraSqlTransact);
begin
inherited SetTransact(Value);
end;
{ Get connect to database component }
function TZCustomOraSqlDataset.GetDatabase: TZOraSqlDatabase;
begin
Result := TZOraSqlDatabase(DatabaseObj);
end;
{ Get connect to transact-server component }
function TZCustomOraSqlDataset.GetTransact: TZOraSqlTransact;
begin
Result := TZOraSqlTransact(TransactObj);
end;
{ Read query from server to internal buffer }
procedure TZCustomOraSqlDataset.QueryRecord;
var
I, Count: Integer;
RecordData: PRecordData;
FieldDesc: PFieldDesc;
Temp: string;
TempTime: TDateTime;
TimeStamp: TTimeStamp;
BlobPtr: PRecordBlob;
Status: Integer;
Cancel: Boolean;
begin
Count := SqlBuffer.Count;
while not Query.EOF and (Count = SqlBuffer.Count) do
begin
{ Go to the record }
if SqlBuffer.FillCount > 0 then
Query.Next;
{ Invoke OnProgress event }
if Assigned(OnProgress) then
begin
Cancel := False;
OnProgress(Self, psRunning, ppFetching, Query.RecNo+1,
MaxIntValue([Query.RecNo+1, Query.RecordCount]), Cancel);
if Cancel then Query.Close;
end;
if Query.EOF then Break;
{ Getting record }
RecordData := SqlBuffer.Add;
for I := 0 to SqlBuffer.SqlFields.Count - 1 do
begin
FieldDesc := SqlBuffer.SqlFields[I];
if FieldDesc.FieldNo < 0 then Continue;
if Query.FieldIsNull(FieldDesc.FieldNo) and
not (FieldDesc.FieldType in [ftBlob, ftMemo]) then
Continue;
case FieldDesc.FieldType of
ftString:
begin
Temp := ConvertFromSqlEnc(Query.Field(FieldDesc.FieldNo));
SqlBuffer.SetFieldDataLen(FieldDesc,
PChar(Temp), RecordData, Length(Temp));
end;
ftInteger, ftFloat:
SqlBuffer.SetFieldData(FieldDesc,
Query.FieldBuffer(FieldDesc.FieldNo), RecordData);
ftDateTime:
begin
TimeStamp := DateTimeToTimeStamp(
OraDateToDateTime(Query.FieldBuffer(FieldDesc.FieldNo)));
TempTime := TimeStampToMSecs(TimeStamp);
SqlBuffer.SetFieldData(FieldDesc, @TempTime, RecordData);
end;
ftMemo, ftBlob:
begin
{ Process blob and memo fields }
BlobPtr := PRecordBlob(@RecordData.Bytes[FieldDesc.Offset+1]);
BlobPtr.Handle.Ptr := 0;
BlobPtr.Handle.PtrEx := 0;
BlobPtr.Size := 0;
BlobPtr.Data := nil;
BlobPtr.BlobType := FieldDesc.BlobType;
if not Query.FieldIsNull(FieldDesc.FieldNo) then
begin
RecordData.Bytes[FieldDesc.Offset] := 0;
{ Fill internal blobs }
if FieldDesc.BlobType = btInternal then
begin
if FieldDesc.FieldType = ftMemo then
begin
Temp := ConvertFromSqlEnc(Query.Field(FieldDesc.FieldNo));
BlobPtr.Size := Length(Temp);
BlobPtr.Data := AllocMem(BlobPtr.Size);
System.Move(PChar(Temp)^, BlobPtr.Data^, BlobPtr.Size);
end
else
begin
BlobPtr.Size := PInteger(Query.FieldBuffer(FieldDesc.FieldNo))^;
BlobPtr.Data := AllocMem(BlobPtr.Size);
System.Move((Query.FieldBuffer(FieldDesc.FieldNo)+SizeOf(Integer))^,
BlobPtr.Data^, BlobPtr.Size);
end;
end
{ Fill external blobs }
else if not Query.FieldIsNull(FieldDesc.FieldNo) then begin
Status := OCIDescriptorAlloc(TDirOraSqlConnect(Query.Connect).Handle,
POCIDescriptor(BlobPtr.Handle.Ptr), OCI_DTYPE_LOB, 0, nil);
if Status <> OCI_SUCCESS then
DatabaseError('Lob allocation error in field "' + FieldDesc.Alias + '"');
Status := OCILobAssign(TDirOraSqlConnect(Query.Connect).Handle,
TDirOraSqlTransact(Query.Transact).ErrorHandle,
PPOCIDescriptor(Query.FieldBuffer(FieldDesc.FieldNo))^,
POCIDescriptor(BlobPtr.Handle.Ptr));
if Status <> OCI_SUCCESS then
DatabaseError('Lob assign error in field "' + FieldDesc.Alias + '"');
end;
end;
end;
else
DatabaseError(SUnknownType + FieldDesc.Alias);
end;
end;
{ Filter received record }
SqlBuffer.FilterItem(SqlBuffer.Count-1);
end;
end;
{************** Sql-queries processing ******************}
{ Fill collection with fields }
procedure TZCustomOraSqlDataset.AddTableFields(Table: string;
SqlFields: TSqlFields);
var
Size: Integer;
Decimals: Integer;
FieldType: TFieldType;
Query: TDirOraSqlQuery;
Default: string;
BlobType: TBlobType;
begin
Query := TDirOraSqlQuery(Transaction.QueryHandle);
Query.ShowColumns(Table, '');
while not Query.EOF do
begin
{ Evalute field parameters }
Size := StrToIntDef(Query.Field(3), 0);
Decimals := StrToIntDef(Query.Field(6), 0);
FieldType := OraSqlToDelphiType(Query.Field(2), Size, Decimals, BlobType);
if FieldType <> ftString then Size := 0;
Default := Query.Field(5);
{ Put new field description }
SqlFields.Add(Table, Query.Field(1), '', Query.Field(2), FieldType,
Size, Decimals, atNone, Query.Field(4) = 'Y', False, Default, BlobType);
Query.Next;
end;
Query.Close;
end;
{ Fill collection with indices }
procedure TZCustomOraSqlDataset.AddTableIndices(Table: string;
SqlFields: TSqlFields; SqlIndices: TSqlIndices);
var
KeyType: TKeyType;
SortType: TSortType;
Query: TDirOraSqlQuery;
begin
Query := TDirOraSqlQuery(TransactObj.QueryHandle);
Query.ShowIndexes(Table);
while not Query.EOF do
begin
{ Define a key type }
if Query.Field(2) = 'UNIQUE' then
begin
if Query.Field(3) = 'Y' then
KeyType := ktPrimary
else KeyType := ktUnique;
end else KeyType := ktIndex;
{ Define a sorting mode }
SortType := stAscending;
{ Put new index description }
SqlIndices.AddIndex(Query.Field(0), Table, Query.Field(4),
KeyType, SortType);
Query.Next;
end;
Query.Close;
end;
{ Convert field value to sql value }
function TZCustomOraSqlDataset.FieldValueToSql(Value: string;
FieldDesc: PFieldDesc): string;
function BytesToSql(Value: string): string;
var
I: Integer;
begin
if Value = '' then
begin
Result := 'NULL';
Exit;
end
else
begin
Result := '';
for I := 1 to Length(Value) do
Result := Result + IntToHex(Ord(Value[I]),2);
Result := '''' + Result + '''';
end;
end;
begin
if FieldDesc.FieldType = ftBlob then
Result := BytesToSql(Value)
else begin
Result := inherited FieldValueToSql(Value, FieldDesc);
if FieldDesc.FieldType = ftDateTime then
begin
// Result := 'TO_DATE(' + Result + ',''YYYY-MM-DD HH24-MI-SS'')'
if Pos(' ', Result) > 0 then
Result := 'TO_DATE(' + Result + ',''' + UpperCase(ShortDateFormat) + ' HH24' + TimeSeparator + 'MI' + TimeSeparator + 'SS'')'
else
Result := 'TO_DATE(' + Result + ',''' + UpperCase(ShortDateFormat) + ''')';
end
else
if (FieldDesc.FieldType = ftString)
and (StrCaseCmp(FieldDesc.TypeName, 'NCHAR')
or StrCaseCmp(FieldDesc.TypeName, 'NVARCHAR2')) then
Result := 'N' + Result;
end;
end;
{ Update record after initialization }
procedure TZCustomOraSqlDataset.UpdateAfterInit(RecordData: PRecordData);
function FindPrimaryKey: PFieldDesc;
var
I: Integer;
IndexDesc: PIndexDesc;
begin
Result := nil;
if SqlParser.Tables.Count = 0 then Exit;
{ Find primary key }
IndexDesc := nil;
for I := 0 to SqlBuffer.SqlIndices.Count-1 do
if StrCaseCmp(SqlBuffer.SqlIndices[I].Table, SqlParser.Tables[0])
and (SqlBuffer.SqlIndices[I].KeyType = ktPrimary) then
begin
IndexDesc := SqlBuffer.SqlIndices[I];
Break;
end;
{ Check primary key }
if (IndexDesc = nil) or (IndexDesc.FieldCount <> 1) then Exit;
Result := SqlBuffer.SqlFields.FindByName(SqlParser.Tables[0],
IndexDesc.Fields[0]);
if Result = nil then Exit;
if Result.FieldType <> ftInteger then
Result := nil;
end;
var
FieldDesc: PFieldDesc;
begin
inherited UpdateAfterInit(RecordData);
if ooAutoIncKey in FExtraOptions then
begin
FieldDesc := FindPrimaryKey;
if FieldDesc <> nil then
SqlBuffer.SetField(FieldDesc, EvaluteDef(Format('%s_%s_seq.NextVal',
[SqlParser.Tables[0], FieldDesc.Field])), RecordData);
end;
end;
{ Update Lobs after update or insert }
procedure TZCustomOraSqlDataset.UpdateAfterPost(OldData,
NewData: PRecordData);
var
I: Integer;
Sql: string;
BlobDescs: array[0..MAX_FIELD_COUNT-1] of PFieldDesc;
BlobCount: Integer;
FieldDesc: PFieldDesc;
FieldValue: string;
OraConnect: TDirOraSqlConnect;
OraTransact: TDirOraSqlTransact;
UpdateQuery: TDirOraSqlQuery;
LobHandle: POCILobLocator;
Affected: ub4;
begin
inherited UpdateAfterPost(OldData, NewData);
if SqlParser.Tables.Count = 0 then Exit;
if NewData.RecordType in [ztUnmodified, ztDeleted] then Exit;
Sql := '';
BlobCount := 0;
for I := 0 to SqlBuffer.SqlFields.Count-1 do
begin
FieldDesc := SqlBuffer.SqlFields[I];
if not StrCaseCmp(FieldDesc.Table, SqlParser.Tables[0]) then
Continue;
if not (FieldDesc.FieldType in [ftBlob, ftMemo])
or (FieldDesc.BlobType <> btExternal) then Continue;
if SqlBuffer.GetFieldNull(FieldDesc, NewData) then Continue;
FieldValue := SqlBuffer.GetField(FieldDesc, NewData);
if (NewData.RecordType = ztModified)
and (FieldValue = SqlBuffer.GetField(FieldDesc, OldData)) then
Continue;
if Sql <> '' then Sql := Sql + ',';
Sql := Sql + FieldDesc.Field;
BlobDescs[BlobCount] := FieldDesc;
Inc(BlobCount);
end;
if Sql = '' then Exit;
Sql := 'SELECT ' + Sql + ' FROM ' + SqlParser.Tables[0]
+ FormSqlWhere(SqlParser.Tables[0], OldData) + ' FOR UPDATE';
OraConnect := TDirOraSqlConnect(Query.Connect);
OraTransact := TDirOraSqlTransact(Query.Transact);
UpdateQuery := TDirOraSqlQuery.Create(OraConnect, OraTransact);
UpdateQuery.Sql := Sql;
UpdateQuery.Open;
for I := 0 to MinIntValue([BlobCount, UpdateQuery.FieldCount]) do
begin
if not (UpdateQuery.FieldType(I) in [SQLT_BLOB, SQLT_CLOB]) or
UpdateQuery.FieldIsNull(I) then
Continue;
FieldValue := SqlBuffer.GetField(BlobDescs[I], NewData);
LobHandle := PPOCIDescriptor(UpdateQuery.FieldBuffer(I))^;
Affected := Length(FieldValue);
OCILobWrite(OraTransact.Handle, OraTransact.ErrorHandle,
LobHandle, Affected, 1, PChar(FieldValue), Affected,
OCI_ONE_PIECE, nil, nil, 0, SQLCS_IMPLICIT);
end;
UpdateQuery.Close;
end;
{ Assign Lob handlers }
procedure TZCustomOraSqlDataset.CopyRecord(SqlBuffer: TSqlBuffer; Source,
Dest: PRecordData);
var
I, Status: Integer;
NewPtr: POCILobLocator;
DestBlob: PRecordBlob;
begin
for I := 0 to SqlBuffer.SqlFields.Count-1 do
if (SqlBuffer.SqlFields[I].FieldType in [ftBlob, ftMemo])
and (Dest.Bytes[SqlBuffer.SqlFields[I].Offset] = 0) then
begin
DestBlob := PRecordBlob(@Dest.Bytes[SqlBuffer.SqlFields[I].Offset+1]);
if (DestBlob.BlobType = btExternal) and (DestBlob.Handle.Ptr <> 0) then
begin
Status := OCIDescriptorAlloc(TDirOraSqlConnect(Query.Connect).Handle,
POCIDescriptor(NewPtr), OCI_DTYPE_LOB, 0, nil);
if Status = OCI_SUCCESS then
Status := OCILobAssign(TDirOraSqlConnect(Query.Connect).Handle,
TDirOraSqlTransact(Query.Transact).ErrorHandle,
POCIDescriptor(DestBlob.Handle.Ptr),
POCIDescriptor(NewPtr));
if Status = OCI_SUCCESS then
DestBlob.Handle.Ptr := Integer(NewPtr)
else
DestBlob.Handle.Ptr := 0;
end;
end;
end;
{ Free Lob handlers }
procedure TZCustomOraSqlDataset.FreeRecord(SqlBuffer: TSqlBuffer;
Value: PRecordData);
var
I: Integer;
BlobPtr: PRecordBlob;
begin
for I := 0 to SqlBuffer.SqlFields.Count-1 do
if (SqlBuffer.SqlFields[I].FieldType in [ftBlob, ftMemo])
and (Value.Bytes[SqlBuffer.SqlFields[I].Offset] = 0) then
begin
BlobPtr := PRecordBlob(@Value.Bytes[SqlBuffer.SqlFields[I].Offset+1]);
if (BlobPtr.BlobType = btExternal) and (BlobPtr.Handle.Ptr <> 0) then
begin
OCIDescriptorFree(POCIDescriptor(BlobPtr.Handle.Ptr), OCI_DTYPE_LOB);
BlobPtr.Handle.Ptr := 0;
end;
end;
end;
{$IFDEF WITH_IPROVIDER}
{ IProvider support }
{ Is in transaction }
function TZCustomOraSqlDataset.PSInTransaction: Boolean;
begin
Result := True;
end;
{ Execute an sql statement }
function TZCustomOraSqlDataset.PSExecuteStatement(const ASql: string; AParams: TParams;
ResultSet: Pointer): Integer;
begin
if Assigned(ResultSet) then
begin
TDataSet(ResultSet^) := TZOraSqlQuery.Create(nil);
with TZOraSqlQuery(ResultSet^) do
begin
Sql.Text := ASql;
Params.Assign(AParams);
Open;
Result := RowsAffected;
end;
end else
Result := TransactObj.ExecSql(ASql);
end;
{ Set command query }
procedure TZCustomOraSqlDataset.PSSetCommandText(const CommandText: string);
begin
Close;
if Self is TZOraSqlQuery then
TZOraSqlQuery(Self).Sql.Text := CommandText
else
if Self is TZOraSqlTable then
TZOraSqlQuery(Self).TableName := CommandText;
end;
{$ENDIF}
{ TZOraSqlTable }
constructor TZOraSqlTable.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DefaultIndex := True;
ReadOnly := False;
end;
end.
|
{ Subroutine RAY_TRACE (RAY, COLOR)
*
* Trace a ray and resolve its "color".
*
* The data type for the ray used here, RAY_DESC_T, is not intended to be used
* directly. It is a template for holding only the minimum necessary
* information required at this level. The TYPEn client routines define the
* details of the ray, as assumed by their objects and shaders.
*
* COLOR is returned the final resolved color of the ray. The format of color
* is set by the TYPEn client routines, and is unknown here.
}
module ray_trace;
define ray_trace;
%include 'ray2.ins.pas';
procedure ray_trace (
in out ray: univ ray_base_t; {the ray to trace}
out color: univ sys_int_machine_t); {returned color, format defined by TYPEn}
val_param;
var
hit_info: ray_hit_info_t; {handle to all results from INTERSECT_CHECK}
shader: ray_shader_t; {pointer to shader that resolves hit color}
begin
{
* Find whether the ray hits something. If so, then HIT_INFO and SHADER are
* also returned.
}
if ray.context_p^.top_level_obj_p^.class_p^.intersect_check^ ( {hit something ?}
ray, {all the information about this ray}
ray.context_p^.top_level_obj_p^, {object to intersect ray with}
ray.context_p^.object_parms_p, {parameters for top level object}
hit_info, {specific data returned about this hit}
shader) {routine to call to get hit color}
{
* The ray hit something. Call the shader returned by the INTERSECT_CHECK routine
* to resolve the object's color at the intersect point.
}
then begin {yes, the ray hit something}
shader^ ( {call the supplied shader to resolve the color}
ray, {everything you need to know about the ray}
hit_info, {specific info about this intersection}
color); {retured color at intersect point}
end {done with ray hit object case}
{
* The ray didn't hit any objects. Call the background shader pointed to
* by the static ray descriptor to get the background color.
}
else begin {the ray hit nothing at all}
ray.context_p^.backg_shader^ ( {call the default "background" shader}
ray, {the ray information}
ray.context_p^.backg_hit_info, {default hit info when ray hit nothing}
color); {retured background color for this ray}
end
;
end;
|
unit SlottingPoster;
interface
uses PersistentObjects, DBGate, BaseObjects, DB, Straton;
type
// для долблений
TSlottingDataPoster = class(TImplementedDataPoster)
private
FStratons: TSimpleStratons;
procedure SetStratons(const Value: TSimpleStratons);
public
property AllStratons: TSimpleStratons read FStratons write SetStratons;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
implementation
uses Facade, Slotting, SysUtils, Math, DateUtils;
{ TSlottingdDataPoster }
constructor TSlottingDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'VW_SLOTTING_DESCRIPTION';
DataDeletionString := 'TBL_SLOTTING';
DataPostString := 'TBL_SLOTTING';
KeyFieldNames := 'SLOTTING_UIN';
FieldNames := 'SLOTTING_UIN, WELL_UIN, VCH_SLOTTING_NUMBER, ' +
'NUM_SLOTTING_TOP, NUM_SLOTTING_BOTTOM, ' +
'NUM_CORE_YIELD, NUM_CORE_FINAL_YIELD, TRUE_DESCRIPTION, ' +
'DTM_KERN_TAKE_DATE, NUM_DNR_SAMPLE_COUNT, NUM_SLOTTING_CHECKED, NUM_DIAMETER, VCH_COMMENT, STRATON_ID, VCH_SUBS_STRATON_INDEX';
AccessoryFieldNames := 'SLOTTING_UIN, WELL_UIN, VCH_SLOTTING_NUMBER, NUM_SLOTTING_TOP, NUM_SLOTTING_BOTTOM, ' +
'NUM_CORE_YIELD, NUM_DIAMETER, VCH_BOX_NUMBER, NUM_CORE_FINAL_YIELD, NUM_DNR_SAMPLE_COUNT, ' +
'VCH_CORE_STATE, NUM_COLLECTION_MEMBER, VCH_COMMENT, DTM_KERN_TAKE_DATE, ' +
'NUM_SLOTTING_CHECKED, STRATON_ID';
AutoFillDates := false;
Sort := 'NUM_SLOTTING_TOP';
end;
function TSlottingDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TSlottingDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TSlotting;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TSlotting;
o.ID := ds.FieldByName('SLOTTING_UIN').AsInteger;
o.Name := trim(ds.FieldByName('VCH_SLOTTING_NUMBER').AsString);
o.Top := ds.FieldByName('NUM_SLOTTING_TOP').AsFloat;
o.Bottom := ds.FieldByName('NUM_SLOTTING_BOTTOM').AsFloat;
o.CoreYield := ds.FieldByName('NUM_CORE_YIELD').AsFloat;
o.CoreFinalYield := ds.FieldByName('NUM_CORE_FINAL_YIELD').AsFloat;
o.Diameter := ds.FieldByName('NUM_DIAMETER').Value;
o.Comment := trim(ds.FieldByName('VCH_COMMENT').AsString);
o.Straton := AllStratons.ItemsByID[ds.FieldByName('STRATON_ID').AsInteger] as TSimpleStraton;
o.SubDivisionStratonName := ds.FieldByName('VCH_SUBS_STRATON_INDEX').AsString;
if ds.FieldByName('TRUE_DESCRIPTION').AsInteger > 0 then o.TrueDescription := true
else o.TrueDescription := False;
o.CoreTakeDate := ds.FieldByName('DTM_KERN_TAKE_DATE').AsDateTime;
ds.Next;
end;
ds.First;
end;
end;
function TSlottingDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TSlotting;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TSlotting;
ds.FieldByName('SLOTTING_UIN').Value := o.ID;
ds.FieldByName('WELL_UIN').Value := o.Collection.Owner.ID;
ds.FieldByName('VCH_SLOTTING_NUMBER').Value := o.Name;
ds.FieldByName('NUM_SLOTTING_TOP').Value := o.Top;
ds.FieldByName('NUM_SLOTTING_BOTTOM').Value := o.Bottom;
ds.FieldByName('NUM_CORE_YIELD').Value := o.CoreYield;
ds.FieldByName('NUM_CORE_FINAl_YIELD').Value := o.CoreFinalYield;
if Assigned(o.Straton) then
ds.FieldByName('STRATON_ID').Value := o.Straton.ID;
ds.FieldByName('NUM_SLOTTING_CHECKED').Value := 1;
ds.FieldByName('NUM_DIAMETER').Value := o.Diameter;
ds.FieldByName('DTM_KERN_TAKE_DATE').Value := DateOf(o.CoreTakeDate);
ds.FieldByName('VCH_COMMENT').Value := trim(o.Comment);
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('SLOTTING_UIN').Value;
end;
procedure TSlottingDataPoster.SetStratons(const Value: TSimpleStratons);
begin
if FStratons <> Value then
FStratons := Value;
end;
end.
|
unit Aurelius.Drivers.dbGo;
{$I Aurelius.inc}
interface
uses
Classes, DB, Variants, Generics.Collections, ADODB,
Aurelius.Drivers.Base,
Aurelius.Drivers.Interfaces;
type
TDbGoResultSetAdapter = class(TDriverResultSetAdapter<TADOQuery>)
end;
TDbGoStatementAdapter = class(TInterfacedObject, IDBStatement, IDBDatasetStatement)
private
FADOQuery: TADOQuery;
function GetDataset: TDataset;
public
constructor Create(AADOQuery: TADOQuery);
destructor Destroy; override;
procedure SetSQLCommand(SQLCommand: string);
procedure SetParams(Params: TEnumerable<TDBParam>);
procedure Execute;
function ExecuteQuery: IDBResultSet;
end;
TDbGoConnectionAdapter = class(TDriverConnectionAdapter<TADOConnection>, IDBConnection)
public
procedure Connect;
procedure Disconnect;
function IsConnected: Boolean;
function CreateStatement: IDBStatement;
function BeginTransaction: IDBTransaction;
function RetrieveSqlDialect: string; override;
end;
TDbGoTransactionAdapter = class(TInterfacedObject, IDBTransaction)
private
//FDBXTransaction: TDBXTransaction;
FADOConnection: TADOConnection;
public
constructor Create(ADOConnection: TADOConnection);
procedure Commit;
procedure Rollback;
end;
implementation
{ TDbGoStatementAdapter }
uses
SysUtils,
Aurelius.Drivers.Exceptions,
Aurelius.Global.Utils;
constructor TDbGoStatementAdapter.Create(AADOQuery: TADOQuery);
begin
FADOQuery := AADOQuery;
end;
destructor TDbGoStatementAdapter.Destroy;
begin
FADOQuery.Free;
inherited;
end;
procedure TDbGoStatementAdapter.Execute;
begin
FADOQuery.ExecSQL;
end;
function TDbGoStatementAdapter.ExecuteQuery: IDBResultSet;
var
ResultSet: TADOQuery;
begin
ResultSet := TADOQuery.Create(nil);
try
ResultSet.Connection := FADOQuery.Connection;
ResultSet.SQL := FADOQuery.SQL;
ResultSet.Parameters.ParseSQL(ResultSet.SQL.Text, True);
ResultSet.Parameters.AssignValues(FADOQuery.Parameters);
ResultSet.Open;
except
ResultSet.Free;
raise;
end;
Result := TDbGoResultSetAdapter.Create(ResultSet);
end;
function TDbGoStatementAdapter.GetDataset: TDataset;
begin
Result := FADOQuery;
end;
procedure TDbGoStatementAdapter.SetParams(Params: TEnumerable<TDBParam>);
var
P: TDBParam;
Parameter: TParameter;
BytesStream: TBytesStream;
begin
FADOQuery.Parameters.ParseSQL(FADOQuery.SQL.Text, True);
for P in Params do
begin
Parameter := FADOQuery.Parameters.FindParam(P.ParamName);
if P.ParamType in [ftBlob, ftOraBlob, ftOraClob] then
begin
Parameter.DataType := P.ParamType;
Parameter.Direction := pdInput;
if VarIsNull(P.ParamValue) or (Length(TUtils.VariantToBytes(P.ParamValue)) = 0) then
Parameter.Value := Null
else
begin
BytesStream := TBytesStream.Create(TUtils.VariantToBytes(P.ParamValue));
try
Parameter.LoadFromStream(BytesStream, P.ParamType);
finally
BytesStream.Free;
end;
end;
end else
begin
Parameter.DataType := P.ParamType;
Parameter.Value := P.ParamValue;
Parameter.Direction := pdInput;
if (Parameter.DataType in [ftString, ftFixedChar, ftWideString, ftFixedWideChar]) and (Parameter.Size <= 0) then
Parameter.Size := 1;
end;
end;
end;
procedure TDbGoStatementAdapter.SetSQLCommand(SQLCommand: string);
begin
FADOQuery.SQL.Text := SQLCommand;
end;
{ TDbGoConnectionAdapter }
procedure TDbGoConnectionAdapter.Disconnect;
begin
if Connection <> nil then
Connection.Connected := False;
end;
function TDbGoConnectionAdapter.RetrieveSqlDialect: string;
begin
if Connection = nil then
Exit('');
if Pos('DB2', Uppercase(Connection.Provider)) > 0 then
Result := 'DB2'
else
if Pos('IFX', Uppercase(Connection.Provider)) > 0 then
Result := 'Informix'
else
Result := 'MSSQL';
end;
function TDbGoConnectionAdapter.IsConnected: Boolean;
begin
if Connection <> nil then
Result := Connection.Connected
else
Result := false;
end;
function TDbGoConnectionAdapter.CreateStatement: IDBStatement;
var
Statement: TADOQuery;
begin
if Connection = nil then
Exit(nil);
Statement := TADOQuery.Create(nil);
try
Statement.Connection := Connection;
except
Statement.Free;
raise;
end;
Result := TDbGoStatementAdapter.Create(Statement);
end;
procedure TDbGoConnectionAdapter.Connect;
begin
if Connection <> nil then
Connection.Connected := True;
end;
function TDbGoConnectionAdapter.BeginTransaction: IDBTransaction;
begin
if Connection = nil then
Exit(nil);
Connection.Connected := true;
if not Connection.InTransaction then
begin
Connection.BeginTrans;
Result := TDbGoTransactionAdapter.Create(Connection);
end else
Result := TDbGoTransactionAdapter.Create(nil);
end;
{ TDbGoTransactionAdapter }
procedure TDbGoTransactionAdapter.Commit;
begin
if (FADOConnection = nil) then
Exit;
FADOConnection.CommitTrans;
end;
constructor TDbGoTransactionAdapter.Create(ADOConnection: TADOConnection);
begin
FADOConnection := ADOConnection;
end;
procedure TDbGoTransactionAdapter.Rollback;
begin
if (FADOConnection = nil) then
Exit;
FADOConnection.RollbackTrans;
end;
end.
|
unit unit_csv;
{Unit untuk mengolah data tipe CSV}
{DEFINISI TIPE, FUNGSI, DAN PROSEDUR}
interface
uses sysutils;
type
baris_dan_kolom = array [1..2] of integer;
tabel_data = array of array of string;
// Prosedur untuk load data
procedure load_data(var data : textfile; const nama_file : string);
// Fungsi untuk mencari ada berapa kolom dan baris pada data.csv
function cari_baris_kolom(var data : textfile): baris_dan_kolom;
// Fungsi untuk membuat tabel dengan size baris x kolom dari data.csv
function buat_tabel(var data : textfile) : tabel_data;
// Prosedur untuk menambahkan barisan baru pada tabel sekaligus mengupdate jumlah baris;
procedure tambah_baris(var tabel : tabel_data; var baris: integer; kolom : integer);
// Fungsi untuk mencari ada berapa baris pada tabel
function cari_baris(var tabel : tabel_data) : integer;
// Fungsi untuk mencari ada berapa kolom pada tabel
function cari_kolom(var tabel : tabel_data) : integer;
// Fungsi untuk membackup file jika ternyata file tidak ingin disave
Function backup_file(var data : textfile) : tabel_data;
// Procedure untuk menyimpan data yang telah diubah tabel ke data.csv
procedure save_data(var data : textfile; var tabel : tabel_data);
// Prosedur untuk mengulangi file menjadi keadaan awal
procedure reset_file(var data_sesudah : textfile; data_sebelum : tabel_data);
{IMPLEMENTASI FUNGSI DAN PROSEDUR}
implementation
procedure load_data(var data : textfile; const nama_file : string);
{ALGORITMA}
begin
assign(data, nama_file);
reset(data);
end;
function cari_baris_kolom(var data : textfile): baris_dan_kolom;
{KAMUS LOKAL}
var
kolom, baris, i, count, count2 : integer;
s : string;
hasil : baris_dan_kolom;
{ALGORITMA}
begin
// set ulang semua
reset(data);
kolom := 0;
baris := 0;
count2 := 0;
while not eof(data) do begin
readln(data,s); // membaca data dan mengassign hasil bacaan tersebut ke string s
count := 1; // variabel count untuk menghitung banyaknya koma (,) ditambah 1 atau kolom di csv
for i := 0 to length(s) - 1 do begin // Mencari banyaknya koma (,) di string s
if (s[i] = '"') then begin
inc(count2);
end;
if (s[i] = ',') and (count2 mod 2 = 0) then begin
inc(count);
end;
end;
if count > kolom then kolom := count; // kolom kita jadikan maksimum dari count yang ada pada tiap baris
inc(baris); // variabel baris ditambahkan 1 setiap membaca baris baru
end;
hasil[1] := baris; // masukkan baris ke indeks pertama array hasil
hasil[2] := kolom; // masukkan kolom ke indeks kedua array hasil
cari_baris_kolom := hasil; // assign fungsi ke array hasil
end;
function buat_tabel(var data : textfile) : tabel_data;
{KAMUS LOKAL}
var
caribariskolom : array [1..2] of integer;
hasil_array : tabel_data;
baris, kolom : integer;
i, baris_s, kolom_s : integer;
s, temp : string;
count : integer;
{ALGORITMA}
begin
// Mencari terlebih dahulu baris dan kolom menggunakan prosedur yang sudah dibuat sebelumnya
caribariskolom := cari_baris_kolom(data);
baris := caribariskolom[1];
kolom := caribariskolom[2];
// Set dynamic array 'hasil_array' menjadi size baris + 1 dan kolom + 1 (indeks dimulai dari 1)
setLength(hasil_array,baris + 1,kolom + 1);
reset(data);
count := 0;
baris_s := 1; // baris_s = baris sekarang
while not eof(data) do begin
readln(data,s); // masukkan data pada baris sekarang ke variabel string s
s := s + ','; // menambahkan string s dengan ',' agar berpola <kalimat> + ',' semua
temp := ''; // string untuk menyimpan hasil sementara
kolom_s := 1; // kolom_s = kolom sekarang
for i := 1 to length(s) do begin // iterasi string s
if (s[i] = '"') then begin // menghitung banyaknya petik
inc(count)
end;
if (s[i] <> ',') or (count mod 2 = 1) then begin // jika bukan ',' atau jumlah count ganjil maka tambahkan ke string temp
temp := temp + s[i];
end else if (s[i] = ',') and (count mod 2 = 0) then begin
hasil_array[baris_s, kolom_s] := temp;
// set ulang string temp
temp := '';
inc(kolom_s); // increment kolom sekarang
end;
end;
inc(baris_s); // increment baris sekarang
end;
// assign buat_tabel ke hasil yang telah didapatkan
buat_tabel := hasil_array;
end;
function cari_baris(var tabel : tabel_data) : integer;
begin
cari_baris := length(tabel) - 1;
end;
function cari_kolom(var tabel : tabel_data) : integer;
begin
cari_kolom := length(tabel[0]) - 1;
end;
procedure tambah_baris(var tabel : tabel_data; var baris : integer; kolom : integer);
{ALGORITMA}
begin
baris := baris + 1;
kolom := kolom + 1;
SetLength(tabel, baris+1, kolom);
end;
function backup_file(var data : textfile) : tabel_data;
{KAMUS LOKAL}
{ALGORITMA}
begin
// buat array backup sebelum array tersebut diubah
backup_file := buat_tabel(data);
end;
procedure save_data(var data : textfile; var tabel : tabel_data);
{KAMUS LOKAL}
var
temp : string;
baris, kolom, i , j: integer;
{ALGORITMA}
begin
baris := cari_baris(tabel);
kolom := cari_kolom(tabel);
rewrite(data); // Kosongkan data
// mencari baris dan kolom tabel
for i:= 1 to baris do begin
temp := ''; // buat string sementara untuk menyimpan hasil
for j:=1 to kolom do begin
temp := temp + tabel[i, j];
if j < kolom then temp := temp + ',';
// string sementara merupakan penjumlahan cell pada baris ke-i
// yang ditambahkan ',' pada akhir semua cell kecuali cell terakhir
end;
// tuliskan hasil string tadi ke data yang sudah terubah
writeln(data,temp);
end;
reset(data);
end;
procedure reset_file(var data_sesudah : textfile; data_sebelum : tabel_data);
{ALGORITMA}
begin
save_data(data_sesudah, data_sebelum);
end;
end.
|
unit modsimplejson_lib;
{$mode objfpc}{$H+}
interface
uses
Dialogs, Controls, LazarusPackageIntf, ProjectIntf, NewItemIntf, IDEMsgIntf,
Classes, SysUtils;
resourcestring
rs_Mod_JSON_Name = 'JSON module';
rs_Mod_JSON_Description = 'create fastplaz simple json module';
type
{ TFileDescJSONModule }
TFileDescJSONModule = class(TFileDescPascalUnit)
private
public
constructor Create; override;
function GetInterfaceUsesSection: string; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function GetInterfaceSource(const Filename, SourceName,
ResourceName: string): string;
override;
function GetImplementationSource(const Filename, SourceName,
ResourceName: string): string; override;
function GetResourceSource(const ResourceName: string): string; override;
function CreateSource(const Filename, SourceName, ResourceName: string): string;
override;
procedure UpdateDefaultPascalFileExtension(const DefPasExt: string); override;
end;
implementation
uses fastplaz_tools_register, modsimple_wzd;
{ TFileDescJSONModule }
constructor TFileDescJSONModule.Create;
begin
inherited Create;
//Name:=rs_Mod_JSON_Name;
DefaultFileExt := '.pas';
VisibleInNewDialog := True;
end;
function TFileDescJSONModule.GetInterfaceUsesSection: string;
begin
Result := inherited GetInterfaceUsesSection;
Result := Result + ', fpcgi, fpjson, HTTPDefs, fastplaz_handler, database_lib';
end;
function TFileDescJSONModule.GetLocalizedName: string;
begin
Result := inherited GetLocalizedName;
Result := rs_Mod_JSON_Name;
end;
function TFileDescJSONModule.GetLocalizedDescription: string;
begin
Result := inherited GetLocalizedDescription;
Result := rs_Mod_JSON_Description;
end;
function TFileDescJSONModule.GetInterfaceSource(
const Filename, SourceName, ResourceName: string): string;
var
str: TStringList;
begin
//Result:=inherited GetInterfaceSource(Filename, SourceName, ResourceName);
str := TStringList.Create;
with str do
begin
Add('type');
Add(' ' + ModulTypeName + ' = class(TMyCustomWebModule)');
Add(' procedure RequestHandler(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: boolean);');
Add(' private');
Add(' public');
Add(' constructor CreateNew(AOwner: TComponent; CreateMode: integer); override;');
Add(' destructor Destroy; override;');
Add(' end;');
Add('');
end;
Result := str.Text;
FreeAndNil(str);
end;
function TFileDescJSONModule.GetImplementationSource(
const Filename, SourceName, ResourceName: string): string;
var
str: TStringList;
begin
Result := inherited GetImplementationSource(FileName, SourceName, ResourceName);
str := TStringList.Create;
with str do
begin
Add('uses common;');
Add('');
Add('constructor ' + ModulTypeName +
'.CreateNew(AOwner: TComponent; CreateMode: integer);');
Add('Begin');
Add(' inherited CreateNew(AOwner, CreateMode);');
Add(' OnRequest := @RequestHandler;');
Add('End;');
Add('');
Add('destructor ' + ModulTypeName + '.Destroy;');
Add('Begin');
Add(' inherited Destroy;');
Add('End;');
Add('');
Add('procedure ' + ModulTypeName +
'.RequestHandler(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: boolean);');
Add('var');
Add(' o, response_json : TJSONObject;');
Add('Begin');
Add(' response_json := TJSONObject.Create;');
Add(' o := TJSONObject.Create;');
Add('');
Add(' // example');
Add(' o.Add( ''msg'', ''OK'');');
Add(' o.Add( ''variable'', ''value'');');
Add('');
Add(' response_json.Add( ''code'', 0);');
Add(' response_json.Add( ''response'', o);');
Add(' // example - end');
Add('');
Add(' Response.Content := response_json.AsJSON;');
Add(' FreeAndNil( response_json);');
Add(' Handled := True;');
Add('End;');
Add('');
Add('');
Add('');
end;
Result := Result + str.Text;
FreeAndNil(str);
if not bCreateProject then
begin
Result := Result + LineEnding + 'initialization' + LineEnding +
' // -> http://yourdomainname/' + ResourceName + LineEnding +
' // The following line should be moved to a file "routes.pas"' +
LineEnding + ' Route.Add(''' + Permalink + ''',' + ModulTypeName +
');' + LineEnding + LineEnding;
end;
end;
function TFileDescJSONModule.GetResourceSource(const ResourceName: string): string;
begin
Result := inherited GetResourceSource(ResourceName);
end;
function TFileDescJSONModule.CreateSource(
const Filename, SourceName, ResourceName: string): string;
begin
if not bExpert then
begin;
Permalink := 'json';
ModulTypeName := 'TJsonModule';
if not bCreateProject then
begin
with TfModuleSimpleWizard.Create(nil) do
begin
if ShowModal = mrOk then
begin
if edt_ModuleName.Text <> '' then
ModulTypeName := 'T' + StringReplace(UcWords(edt_ModuleName.Text),
' ', '', [rfReplaceAll]) + 'Module';
Permalink := edt_Permalink.Text;
if Permalink = '' then
begin
Permalink := StringReplace(UcWords(edt_ModuleName.Text),
' ', '', [rfReplaceAll]);
end;
end;
Free;
end;
end
else
begin
ModulTypeName := 'TMainModule';
Permalink := 'main';
end;
end;
Result := inherited CreateSource(Filename, SourceName, Permalink);
log('module "' + ModulTypeName + '" created');
end;
procedure TFileDescJSONModule.UpdateDefaultPascalFileExtension(
const DefPasExt: string);
begin
inherited UpdateDefaultPascalFileExtension(DefPasExt);
end;
end.
|
unit sFrameBar;
{$I sDefs.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, sSpeedButton, sScrollBox, ImgList, Menus, sConst;
type
{$IFNDEF NOTFORHELP}
TsTitleItem = class;
TsTitles = class;
TsTitleState = (stClosed, stOpened, stClosing, stOpening);
{$ENDIF} // NOTFORHELP
TsFrameBar = class(TsScrollBox)
{$IFNDEF NOTFORHELP}
private
FItems: TsTitles;
FTitleHeight: integer;
FAnimation: boolean;
FImages: TCustomImageList;
FSpacing: integer;
FAllowAllClose: boolean;
FAllowAllOpen: boolean;
FAutoFrameSize: boolean;
FBorderWidth: integer;
procedure SetItems(const Value: TsTitles);
procedure SetTitleHeight(const Value: integer);
procedure SetImages(const Value: TCustomImageList);
function Offset : integer;
procedure UpdateWidths;
procedure SetSpacing(const Value: integer);
function CalcClientRect : TRect;
function CreateDefaultFrame : TFrame;
function UpdateFrame(i, y, h, w : integer) : boolean;
procedure SetAutoFrameSize(const Value: boolean);
procedure SetAllowAllOpen(const Value: boolean);
procedure SetBorderWidth(const Value: integer);
public
Arranging : boolean;
Sizing : boolean;
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
procedure WndProc (var Message: TMessage); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{$ENDIF} // NOTFORHELP
procedure ArrangeTitles; virtual;
procedure ChangeSize(Index : integer; AllowAnimation : boolean; Height:integer);
procedure OpenItem(Index : integer; AllowAnimation : boolean);
procedure CloseItem(Index : integer; AllowAnimation : boolean);
procedure ExpandAll(AllowAnimation : boolean);
procedure CollapseAll(AllowAnimation : boolean);
procedure Rearrange;
published
{$IFNDEF NOTFORHELP}
property Align default alLeft;
property BorderStyle;
property BorderWidth : integer read FBorderWidth write SetBorderWidth default 2;
{$ENDIF} // NOTFORHELP
property AllowAllClose : boolean read FAllowAllClose write FAllowAllClose default False;
property AllowAllOpen : boolean read FAllowAllOpen write SetAllowAllOpen default False;
property Animation : boolean read FAnimation write FAnimation default True;
property AutoFrameSize : boolean read FAutoFrameSize write SetAutoFrameSize;
property Images : TCustomImageList read FImages write SetImages;
property Items : TsTitles read FItems write SetItems;
property TitleHeight : integer read FTitleHeight write SetTitleHeight default 28;
property Spacing : integer read FSpacing write SetSpacing default 2;
end;
{$IFNDEF NOTFORHELP}
TsTitles = class(TCollection)
private
FOwner: TsFrameBar;
protected
function GetItem(Index: Integer): TsTitleItem;
procedure SetItem(Index: Integer; Value: TsTitleItem);
function GetOwner: TPersistent; override;
public
constructor Create(AOwner : TsFrameBar);
destructor Destroy; override;
property Items[Index: Integer]: TsTitleItem read GetItem write SetItem; default;
end;
TsTitleButton = class(TsSpeedButton)
protected
Active : boolean;
constructor InternalCreate(AOwner : TsFrameBar; Index : integer);
public
TitleItem : TsTitleItem;
function CurrentState : integer; override;
property OnClick;
end;
{$ENDIF} // NOTFORHELP
TCreateFrameEvent = procedure (Sender: TObject; var Frame: TCustomFrame) of object;
TFrameDestroyEvent = procedure (Sender: TObject; var Frame: TCustomFrame; var CanDestroy: boolean) of object;
TsTitleItem = class(TCollectionItem)
{$IFNDEF NOTFORHELP}
private
FOwner: TsTitles;
FCaption: acString;
FVisible: boolean;
FOnCreateFrame: TCreateFrameEvent;
FImageIndex: integer;
FOnFrameDestroy: TFrameDestroyEvent;
FOnClick: TNotifyEvent;
FTag: Longint;
FCursor: TCursor;
procedure SetCaption(const Value: acString);
procedure SetVisible(const Value: boolean);
procedure TitleButtonClick(Sender: TObject);
function GetSkinSection: string;
procedure SetSkinSection(const Value: string);
procedure SetImageIndex(const Value: integer);
function GetMargin: integer;
function GetSpacing: integer;
procedure SetMargin(const Value: integer);
procedure SetSpacing(const Value: integer);
function GetPopupMenu: TPopupMenu;
procedure SetPopupMenu(const Value: TPopupMenu);
procedure SetCursor(const Value: TCursor);
public
{$ENDIF} // NOTFORHELP
TitleButton : TsTitleButton;
Frame : TCustomFrame;
State : TsTitleState;
{$IFNDEF NOTFORHELP}
FrameSize : integer;
Closing : boolean;
procedure Assign(Source: TPersistent); override;
destructor Destroy; override;
constructor Create(Collection: TCollection); override;
{$ENDIF} // NOTFORHELP
published
property Caption : acString read FCaption write SetCaption;
property Cursor : TCursor read FCursor write SetCursor;
property ImageIndex : integer read FImageIndex write SetImageIndex default -1;
property SkinSection : string read GetSkinSection write SetSkinSection;
property Margin : integer read GetMargin write SetMargin default 5;
property Spacing : integer read GetSpacing write SetSpacing default 8;
property Tag : Longint read FTag write FTag default 0;
property Visible : boolean read FVisible write SetVisible default True;
property PopupMenu : TPopupMenu read GetPopupMenu write SetPopupMenu;
property OnCreateFrame: TCreateFrameEvent read FOnCreateFrame write FOnCreateFrame;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property OnFrameDestroy: TFrameDestroyEvent read FOnFrameDestroy write FOnFrameDestroy;
end;
implementation
uses sMessages, sSkinProps, sVCLUtils, sFrameAdapter, sLabel, stdctrls, acntUtils, acSBUtils;
{ TsTitles }
var
DontAnim : boolean;
constructor TsTitles.Create(AOwner: TsFrameBar);
begin
inherited Create(TsTitleItem);
FOwner := AOwner;
end;
destructor TsTitles.Destroy;
begin
inherited Destroy;
FOwner := nil;
end;
function TsTitles.GetItem(Index: Integer): TsTitleItem;
begin
Result := TsTitleItem(inherited GetItem(Index));
end;
function TsTitles.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TsTitles.SetItem(Index: Integer; Value: TsTitleItem);
begin
inherited SetItem(Index, Value);
end;
{ TsFrameBar }
procedure TsFrameBar.ArrangeTitles;
const
StepsCount = 3;
DelayValue = 10;
var
i, ii, sHeight, cWidth, AutoHeight : integer;
cRect : TRect;
Steps, sDiv : integer;
CanDestroy : boolean;
procedure SetActive(Index : integer; Active : boolean);
begin
if (Items[Index].TitleButton.Active <> Active) and (Items[Index].State in [stClosed, stOpened]) then begin
Items[Index].TitleButton.Active := Active;
Items[Index].TitleButton.SkinData.Invalidate;
end;
end;
begin
if not visible or Arranging or (csReading in ComponentState) or (Items.Count = 0) then Exit;
if not DontAnim and not (csDesigning in ComponentState) and FAnimation and Visible and not (csLoading in ComponentState) then Steps := StepsCount else Steps := 0;
cRect := CalcClientRect;
Arranging := True;
sHeight := 0;
AutoHeight := -1;
if not ShowHintStored then begin
AppShowHint := Application.ShowHint;
Application.ShowHint := False;
ShowHintStored := True;
end;
FadingForbidden := True;
MouseForbidden := True;
if AutoFrameSize then begin
AutoScroll := False;
sHeight := cRect.Top;
for i := 0 to Items.Count - 1 do if Items[i].TitleButton.Visible and Items[i].Visible then begin
inc(sHeight, FTitleHeight);
if (Items[i].State in [stOpened, stOpening]) then inc(sHeight, BorderWidth);
inc(sHeight, BorderWidth);
end;
AutoHeight := HeightOf(cRect) - sHeight;
end;
for ii := 0 to Steps do begin
SkinData.BeginUpdate;
Perform(WM_SETREDRAW, 0, 0);
sHeight := cRect.Top;
cWidth := WidthOf(cRect);
for i := 0 to Items.Count - 1 do if Items[i].TitleButton.Visible and Items[i].Visible then begin
Items[i].TitleButton.SetBounds(cRect.Left, sHeight - Offset, cWidth, FTitleHeight);
if Items[i].TitleButton.Parent <> Self then Items[i].TitleButton.Parent := Self;
inc(sHeight, FTitleHeight);
sDiv := Items[i].FrameSize;
if (sDiv = 0) and (Items[i].State = stOpening) and not Animation then Items[i].State := stOpened;
case Items[i].State of
stOpening : begin
inc(sHeight, FSpacing);
if (ii = Steps) and (AutoHeight <> -1) then begin
sDiv := AutoHeight;
Items[i].FrameSize := AutoHeight;
if Items[i].Frame <> nil then Items[i].Frame.Height := AutoHeight
end;
if Steps <> 0 then sDiv := Round((sDiv / Steps) * ii);
if UpdateFrame(i, sHeight - Offset, sDiv, cWidth) then begin
if (ii = Steps) then begin
Items[i].State := stOpened;
end;
if Steps > 0 then Sleep(DelayValue);
end;
end;
stClosing : begin
if Steps = 0 then sDiv := 0 else sDiv := Round((sDiv / Steps) * (Steps - ii));
if (ii = Steps) then begin
Items[i].Closing := False;
CanDestroy := True;
if Assigned(Items[i].FOnFrameDestroy) then Items[i].FOnFrameDestroy(Self, Items[i].Frame, CanDestroy);
if CanDestroy then FreeAndNil(Items[i].Frame);
Items[i].FrameSize := 0;
sDiv := 0;
inc(sHeight, BorderWidth);
Items[i].State := stClosed;
SetActive(i, False);
if Items[i].Frame <> nil then UpdateFrame(i, sHeight - Offset, sDiv, cWidth);
Continue;
end;
UpdateFrame(i, sHeight - Offset, sDiv, cWidth);
if Steps > 0 then Sleep(DelayValue);
end;
stOpened : begin
if AutoHeight <> -1 then begin
sDiv := AutoHeight;
Items[i].FrameSize := AutoHeight;
if Items[i].Frame <> nil then Items[i].Frame.Height := AutoHeight
end;
UpdateFrame(i, sHeight - Offset, -1, cWidth);
if (sDiv = 0) and (Items[i].Frame <> nil) then begin
sDiv := Items[i].Frame.Height
end;
end;
stClosed : begin
if Items[i].Frame <> nil then begin
CanDestroy := True;
if Assigned(Items[i].FOnFrameDestroy) then Items[i].FOnFrameDestroy(Self, Items[i].Frame, CanDestroy);
if CanDestroy then FreeAndNil(Items[i].Frame);
Items[i].FrameSize := 0;
sDiv := 0;
if Items[i].Frame <> nil then UpdateFrame(i, sHeight - Offset, sDiv, cWidth);
Items[i].FrameSize := 0;
end
end;
end;
if (Items[i].Frame <> nil) and (Items[i].State in [stOpened, stOpening, stClosing]) then begin
if Items[i].Frame.Parent = nil then Items[i].Frame.Parent := Self;
inc(sHeight, sDiv + BorderWidth);
end;
if (Items[i].Frame <> nil) and (Items[i].State = stOpened) then begin
SetWindowRgn(Items[i].Frame.Handle, 0, False);
end;
inc(sHeight, BorderWidth);
SetActive(i, Items[i].State in [stOpened, stOpening]);
end;
Perform(WM_SETREDRAW, 1, 0);
SkinData.EndUpdate;
if Showing then begin
RedrawWindow(Handle, nil, 0, RDW_ALLCHILDREN or RDW_INVALIDATE or RDW_ERASE or RDW_FRAME or RDW_UPDATENOW);
SetParentUpdated(Self);
end;
if Assigned(acMagnForm) then SendMessage(acMagnForm.Handle, SM_ALPHACMD, MakeWParam(0, AC_REFRESH), 0);
// if Steps > 0 then Application.ProcessMessages;
end;
FadingForbidden := False;
inc(sHeight, BorderWidth + 2 * integer(BorderStyle = bsSingle));
if VertScrollBar.Range <> sHeight then VertScrollBar.Range := sHeight;
Arranging := False;
UpdateWidths;
if Showing then
RedrawWindow(Handle, nil, 0, RDW_ALLCHILDREN or RDW_INVALIDATE or RDW_ERASE or RDW_FRAME);
if Assigned(acMagnForm) then SendMessage(acMagnForm.Handle, SM_ALPHACMD, MakeWParam(0, AC_REFRESH), 0);
MouseForbidden := False;
Application.ShowHint := AppShowHint;
ShowHintStored := False;
end;
function TsFrameBar.CalcClientRect: TRect;
begin
Result := Rect(0, 0, Width - 4 * integer(BorderStyle = bsSingle), Height);
InflateRect(Result, - BorderWidth - 2 * integer(BorderStyle = bsSingle), - BorderWidth - 2 * integer(BorderStyle = bsSingle));
if Parent = nil then Exit;
if GetWindowLong(Handle, GWL_STYLE) and WS_VSCROLL = WS_VSCROLL then dec(Result.Right, GetSystemMetrics(SM_CXVSCROLL));
end;
procedure TsFrameBar.ChangeSize(Index: integer; AllowAnimation: boolean; Height: integer);
begin
if Assigned(Items[Index].Frame) then begin
Items[Index].FrameSize := Height;
Items[Index].Frame.Height := Height;
end;
Items[Index].FrameSize := Height;
if AllowAnimation then Items[Index].State := stOpening else Items[Index].State := stOpened;
DontAnim := not AllowAnimation;
ArrangeTitles;
DontAnim := False;
end;
procedure TsFrameBar.CloseItem(Index: integer; AllowAnimation: boolean);
begin
if AllowAnimation then Items[Index].State := stClosing else Items[Index].State := stClosed;
DontAnim := not AllowAnimation;
ArrangeTitles;
DontAnim := False;
end;
procedure TsFrameBar.CollapseAll(AllowAnimation : boolean);
var
i : integer;
begin
for i := 0 to Items.Count - 1 do if AllowAnimation then Items[i].State := stClosing else Items[i].State := stClosed;
ArrangeTitles;
end;
constructor TsFrameBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SkinData.COC := COC_TsFrameBar;
FItems := TsTitles.Create(Self);
Caption := ' ';
Align := alLeft;
BevelOuter := bvLowered;
FTitleHeight := 28;
VertScrollBar.Tracking := True;
HorzScrollBar.Visible := False;
FBorderWidth := 2;
FAnimation := True;
FAllowAllClose := False;
FAllowAllOpen := False;
end;
function TsFrameBar.CreateDefaultFrame: TFrame;
begin
Result := TFrame.Create(Self);
Result.Height := 150;
with TsFrameAdapter.Create(Result) do begin
SkinData.SkinManager := Self.SkinData.FSkinManager;
SkinData.SkinSection := s_BarPanel;
end;
with TsLabel.Create(Result) do begin
Align := alClient;
Caption := 'Frame creation'#13#10'event has not been defined.';
Alignment := taCenter;
Layout := tlCenter;
WordWrap := True;
Font.color := clRed;
Parent := Result;
end;
end;
destructor TsFrameBar.Destroy;
begin
FreeAndNil(FItems);
inherited Destroy;
end;
procedure TsFrameBar.ExpandAll(AllowAnimation : boolean);
var
i : integer;
begin
for i := 0 to Items.Count - 1 do if AllowAnimation then Items[i].State := stOpening else Items[i].State := stOpened;
ArrangeTitles;
end;
procedure TsFrameBar.Loaded;
var
i : integer;
begin
inherited;
for i := 0 to Items.Count - 1 do begin
Items[i].TitleButton.SkinData.SkinManager := SkinData.FSkinManager;
Items[i].TitleButton.Cursor := Items[i].Cursor;
end;
if Visible then Rearrange
end;
procedure TsFrameBar.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = Images) then Images := nil;
end;
function TsFrameBar.Offset: integer;
var
sbi : TScrollInfo;
begin
if SkinData.Skinned then begin
if Assigned(ListSW) and (ListSW.sBarVert <> nil) and ListSW.sBarVert.fScrollVisible then Result := ListSW.sBarVert.ScrollInfo.nPos else Result := 0;
end
else begin
sbi.cbSize := SizeOf(TScrollInfo);
sbi.fMask := SIF_POS;
GetScrollInfo(Handle, SB_VERT, sbi);
Result := sbi.nPos
end;
end;
procedure TsFrameBar.OpenItem(Index: integer; AllowAnimation: boolean);
var
i : integer;
begin
if AllowAnimation then Items[Index].State := stOpening else Items[Index].State := stOpened;
if not AllowAllOpen then begin
for i := 0 to Items.Count - 1 do if Items[i].State = stOpened then Items[i].State := stClosing;
Items[Index].State := stOpened;
end;
DontAnim := not AllowAnimation;
ArrangeTitles;
DontAnim := False;
end;
procedure TsFrameBar.Rearrange;
begin
DontAnim := True;
ArrangeTitles;
DontAnim := False;
end;
procedure TsFrameBar.SetAllowAllOpen(const Value: boolean);
begin
if FAllowAllOpen <> Value then begin
if Value and FAutoFrameSize then FAutoFrameSize := False;
FAllowAllOpen := Value;
if not (csLoading in ComponentState) then Rearrange;
end;
end;
procedure TsFrameBar.SetAutoFrameSize(const Value: boolean);
begin
if FAutoFrameSize <> Value then begin
if Value then begin
if AllowAllOpen then AllowAllOpen := False;
AutoScroll := False;
end;
FAutoFrameSize := Value;
if not (csLoading in ComponentState) then Rearrange;
end;
end;
procedure TsFrameBar.SetBorderWidth(const Value: integer);
begin
if FBorderWidth <> Value then begin
FBorderWidth := Value;
RecreateWnd;
if not (csLoading in ComponentState) then Rearrange;
end;
end;
procedure TsFrameBar.SetImages(const Value: TCustomImageList);
var
i : integer;
begin
if FImages <> Value then begin
FImages := Value;
for i := 0 to Items.Count - 1 do if Items[i].TitleButton.Visible then Items[i].TitleButton.Images := Images;
end;
end;
procedure TsFrameBar.SetItems(const Value: TsTitles);
begin
FItems.Assign(Value);
end;
procedure TsFrameBar.SetSpacing(const Value: integer);
begin
if FSpacing <> Value then begin
FSpacing := Value;
if not (csLoading in ComponentState) then Rearrange;
end;
end;
procedure TsFrameBar.SetTitleHeight(const Value: integer);
begin
if FTitleHeight <> Value then begin
FTitleHeight := Value;
if not (csLoading in ComponentState) then Rearrange;
end;
end;
function TsFrameBar.UpdateFrame(i, y, h, w : integer) : boolean;
var
rgn : hrgn;
begin
Result := False;
if Items.Count <= i then Exit;
if (Items[i].Frame = nil) and not (csDesigning in ComponentState) then begin
if Assigned(Items[i].OnCreateFrame)
then Items[i].OnCreateFrame(Items[i], Items[i].Frame)
else Items[i].Frame := CreateDefaultFrame;
end;
if (Items[i].Frame <> nil) then begin
if (Items[i].FrameSize = 0) then Items[i].FrameSize := Items[i].Frame.Height;
if h = -1 then begin
h := Items[i].FrameSize; // if frame has not been created
Items[i].Frame.Height := Items[i].FrameSize;
end;
if h = 0 then begin
rgn := CreateRectRgn(-1, -1, -1, -1);
SetWindowRgn(Items[i].Frame.Handle, rgn, False);
Items[i].Frame.Visible := False;
end
else if h = Items[i].Frame.Height then begin
rgn := CreateRectRgn(0, 0, Items[i].Frame.Width, Items[i].Frame.Height);
SetWindowRgn(Items[i].Frame.Handle, rgn, False);
Items[i].Frame.Visible := True;
end
else begin
rgn := CreateRectRgn(0, Items[i].Frame.Height - h, w, Items[i].Frame.Height);
SetWindowRgn(Items[i].Frame.Handle, rgn, False);
Items[i].Frame.Visible := True;
end;
Items[i].Frame.SetBounds(Items[i].TitleButton.Left, y - (Items[i].Frame.Height - h), w, Items[i].Frame.Height);
Result := True
end
else Result := False;
end;
procedure TsFrameBar.UpdateWidths;
var
i, cWidth : integer;
begin
Arranging := True;
cWidth := WidthOf(CalcClientRect);
for i := 0 to Items.Count - 1 do if Items[i].TitleButton.Visible and Items[i].Visible then begin
if Items[i].TitleButton.Width <> cWidth then begin
Items[i].TitleButton.SkinData.BGChanged := True;
Items[i].TitleButton.Width := cWidth;
end;
if (Items[i].Frame <> nil) and (Items[i].Frame.Width <> cWidth) then begin
Items[i].Frame.Width := cWidth;
end;
end;
Arranging := False;
if AutoScroll then UpdateScrolls(ListSW);
end;
procedure TsFrameBar.WndProc(var Message: TMessage);
var
i : integer;
begin
inherited;
case Message.Msg of
WM_SIZE : if Showing then begin
if AutoFrameSize then Rearrange else begin
UpdateWidths;
RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE);
// SendMessage(Handle, WM_NCPAINT, 0, 0);
end;
end;
CM_VISIBLECHANGED : if Showing then begin
Rearrange;
end;
CM_ENABLEDCHANGED: begin
for i := 0 to Items.Count - 1 do begin
Items[i].TitleButton.Enabled := Enabled;
if Items[i].Frame <> nil then Items[i].Frame.Enabled := Enabled;
end;
Repaint
end;
end;
if Message.Msg = cardinal(SM_ALPHACMD) then case Message.WParamHi of
AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) and SkinData.Skinned then UpdateWidths
end;
end;
{ TsTitleItem }
procedure TsTitleItem.Assign(Source: TPersistent);
var
Src : TsTitleItem;
begin
if Source <> nil then begin
Src := TsTitleItem(Source);
Caption := Src.Caption;
Cursor := Src.Cursor;
ImageIndex := Src.ImageIndex;
SkinSection := Src.SkinSection;
Margin := Src.Margin;
Spacing := Src.Spacing;
Tag := Src.Tag;
Visible := Src.Visible;
PopupMenu := Src.PopupMenu;
end
else inherited;
end;
constructor TsTitleItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FTag := 0;
FOwner := TsTitles(Collection);
TitleButton := TsTitleButton.InternalCreate(FOwner.FOwner, Index);
TitleButton.TitleItem := Self;
TitleButton.OnClick := TitleButtonClick;
FVisible := True;
DontAnim := True;
FOwner.FOwner.ArrangeTitles;
DontAnim := False;
FImageIndex := -1;
State := stClosed;
end;
destructor TsTitleItem.Destroy;
begin
if not (csDestroying in FOwner.FOwner.ComponentState) and (TitleButton <> nil) then begin
TitleButton.Visible := False;
TitleButton.Free;
TitleButton := nil;
if Frame <> nil then FreeAndNil(Frame);
end;
inherited Destroy;
if not (csDestroying in FOwner.FOwner.ComponentState) then FOwner.FOwner.ArrangeTitles;
end;
function TsTitleItem.GetMargin: integer;
begin
Result := TitleButton.Margin;
end;
function TsTitleItem.GetPopupMenu: TPopupMenu;
begin
if TitleButton <> nil then Result := TitleButton.PopupMenu else Result := nil
end;
function TsTitleItem.GetSkinSection: string;
begin
Result := TitleButton.SkinData.SkinSection;
end;
function TsTitleItem.GetSpacing: integer;
begin
Result := 0;
if Result <> TitleButton.Spacing then begin
Result := TitleButton.Spacing;
if csDesigning in TitleButton.ComponentState then TitleButton.SkinData.Invalidate;
end;
end;
procedure TsTitleItem.SetCaption(const Value: acString);
begin
TitleButton.Caption := Value;
FCaption := Value;
end;
procedure TsTitleItem.SetCursor(const Value: TCursor);
begin
if FCursor <> Value then begin
FCursor := Value;
if TitleButton <> nil then TitleButton.Cursor := Value;
end;
end;
procedure TsTitleItem.SetImageIndex(const Value: integer);
begin
if FImageIndex <> Value then begin
FImageIndex := Value;
TitleButton.ImageIndex := Value;
if TitleButton.Images <> FOwner.FOwner.Images then TitleButton.Images := FOwner.FOwner.Images
end;
end;
procedure TsTitleItem.SetMargin(const Value: integer);
begin
if TitleButton.Margin <> Value then begin
TitleButton.Margin := Value;
if csDesigning in TitleButton.ComponentState then TitleButton.SkinData.Invalidate;
end;
end;
procedure TsTitleItem.SetPopupMenu(const Value: TPopupMenu);
begin
if TitleButton <> nil then TitleButton.PopupMenu := Value;
end;
procedure TsTitleItem.SetSkinSection(const Value: string);
begin
TitleButton.SkinData.SkinSection := Value
end;
procedure TsTitleItem.SetSpacing(const Value: integer);
begin
TitleButton.Spacing := Value;
end;
procedure TsTitleItem.SetVisible(const Value: boolean);
begin
if FVisible <> Value then begin
FVisible := Value;
if Value then begin
TitleButton.SkinData.UpdateIndexes;
TitleButton.Parent := FOwner.FOwner;
end
else TitleButton.Parent := nil;
FOwner.FOwner.ArrangeTitles;
end;
end;
procedure TsTitleItem.TitleButtonClick;
var
i : integer;
begin
if (csDesigning in FOwner.FOwner.ComponentState) then Exit;
if Assigned(TitleButton) and Assigned(FOnClick) then FOnClick(TitleButton);
case State of
stClosed : begin
State := stOpening;
if not FOwner.FOwner.AllowAllOpen
then for i := 0 to FOwner.Count - 1 do if FOwner[i].State = stOpened then FOwner[i].State := stClosing;
end;
stOpened : if FOwner.FOwner.AllowAllClose then FOwner[Index].State := stClosing;
end;
FOwner.FOwner.ArrangeTitles;
end;
{ TsTitleButton }
function TsTitleButton.CurrentState: integer;
begin
Result := inherited CurrentState;
if Active and SkinData.Skinned and SkinData.SkinManager.IsValidImgIndex(SkinData.BorderIndex) then begin
case Result of
0 : if SkinData.SkinManager.ma[SkinData.BorderIndex].ImageCount > 3 then Result := 3 else Result := 1
else if SkinData.SkinManager.ma[SkinData.BorderIndex].ImageCount > 3 then Result := 3;
end;
end;
end;
constructor TsTitleButton.InternalCreate(AOwner: TsFrameBar; Index: integer);
var
i : Integer;
begin
inherited Create(AOwner);
SkinData.COC := COC_TsBarTitle;
i := 0;
repeat
inc(i);
if AOwner.FindComponent('sTitleButton' + IntToStr(i)) = nil then begin
Name := 'sTitleButton' + IntToStr(i);
break;
end;
until False;
Alignment := taLeftJustify;
Spacing := 8;
Margin := 5;
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Janela de Fluxo de Caixa
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</p>
@author Albert Eije
@version 2.0
******************************************************************************* }
unit UFinFluxoCaixa;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Atributos,
Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids,
DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, ViewFinFluxoCaixaVO,
ViewFinFluxoCaixaController, Tipos, Constantes, LabeledCtrls,
ActnList, RibbonSilverStyleActnCtrls, ActnMan, Mask, JvExMask, JvToolEdit,
JvExStdCtrls, JvEdit, JvValidateEdit, ToolWin, ActnCtrls, JvBaseEdits,
Generics.Collections, Biblioteca, RTTI, Controller;
type
[TFormDescription(TConstantes.MODULO_FINANCEIRO, 'Fluxo de Caixa')]
TFFinFluxoCaixa = class(TFTelaCadastro)
BevelEdits: TBevel;
PanelEditsInterno: TPanel;
DSFluxoCaixa: TDataSource;
CDSFluxoCaixa: TClientDataSet;
EditIdContaCaixa: TLabeledCalcEdit;
EditContaCaixa: TLabeledEdit;
GroupBox1: TGroupBox;
Label1: TLabel;
EditDataInicio: TLabeledDateEdit;
EditDataFim: TLabeledDateEdit;
PanelGridInterna: TPanel;
GridPagamentos: TJvDBUltimGrid;
PanelTotais: TPanel;
PanelTotaisGeral: TPanel;
CDSFluxoCaixaID_CONTA_CAIXA: TIntegerField;
CDSFluxoCaixaNOME_CONTA_CAIXA: TStringField;
CDSFluxoCaixaNOME_PESSOA: TStringField;
CDSFluxoCaixaDATA_LANCAMENTO: TDateField;
CDSFluxoCaixaDATA_VENCIMENTO: TDateField;
CDSFluxoCaixaVALOR: TFMTBCDField;
CDSFluxoCaixaCODIGO_SITUACAO: TStringField;
CDSFluxoCaixaDESCRICAO_SITUACAO: TStringField;
CDSFluxoCaixaOPERACAO: TStringField;
procedure FormCreate(Sender: TObject);
procedure BotaoConsultarClick(Sender: TObject);
procedure BotaoSalvarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CalcularTotais;
procedure CalcularTotaisGeral;
private
{ Private declarations }
public
{ Public declarations }
procedure GridParaEdits; override;
procedure ControlaBotoes; override;
procedure ControlaPopupMenu; override;
procedure LimparCampos; override;
function MontaFiltro: string; override;
// Controles CRUD
function DoEditar: Boolean; override;
end;
var
FFinFluxoCaixa: TFFinFluxoCaixa;
implementation
uses
UTela;
{$R *.dfm}
{$REGION 'Infra'}
procedure TFFinFluxoCaixa.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TViewFinFluxoCaixaVO;
ObjetoController := TViewFinFluxoCaixaController.Create;
inherited;
end;
procedure TFFinFluxoCaixa.FormShow(Sender: TObject);
begin
inherited;
EditDataInicio.Date := Now;
EditDataFim.Date := Now;
end;
procedure TFFinFluxoCaixa.ControlaBotoes;
begin
inherited;
BotaoImprimir.Visible := False;
BotaoInserir.Visible := False;
BotaoExcluir.Visible := False;
BotaoCancelar.Visible := False;
BotaoAlterar.Caption := 'Filtrar Conta [F3]';
BotaoAlterar.Hint := 'Filtrar Conta [F3]';
BotaoAlterar.Width := 120;
BotaoSalvar.Caption := 'Retornar [F12]';
BotaoSalvar.Hint := 'Retornar [F12]';
end;
procedure TFFinFluxoCaixa.ControlaPopupMenu;
begin
inherited;
MenuImprimir.Visible := False;
MenuInserir.Visible := False;
MenuExcluir.Visible := False;
MenuCancelar.Visible := False;
MenuAlterar.Caption := 'Filtrar Conta [F3]';
menuSalvar.Caption := 'Retornar [F12]';
end;
procedure TFFinFluxoCaixa.LimparCampos;
var
DataInicioInformada, DataFimInformada: TDateTime;
begin
DataInicioInformada := EditDataInicio.Date;
DataFimInformada := EditDataFim.Date;
inherited;
CDSFluxoCaixa.EmptyDataSet;
EditDataInicio.Date := DataInicioInformada;
EditDataFim.Date := DataFimInformada;
end;
{$ENDREGION}
{$REGION 'Controles CRUD'}
function TFFinFluxoCaixa.DoEditar: Boolean;
begin
Result := inherited DoEditar;
if Result then
begin
EditIdContaCaixa.SetFocus;
end;
end;
{$ENDREGION}
{$REGION 'Controle de Grid'}
procedure TFFinFluxoCaixa.GridParaEdits;
begin
inherited;
EditIdContaCaixa.AsInteger := CDSGrid.FieldByName('ID_CONTA_CAIXA').AsInteger;
EditContaCaixa.Text := CDSGrid.FieldByName('NOME_CONTA_CAIXA').AsString;
TViewFinFluxoCaixaController.SetDataSet(CDSFluxoCaixa);
Filtro := '(DATA_VENCIMENTO between ' + QuotedStr(DataParaTexto(EditDataInicio.Date)) + ' and ' + QuotedStr(DataParaTexto(EditDataFim.Date)) + ') and ID_CONTA_CAIXA=' + QuotedStr(EditIdContaCaixa.Text);
TController.ExecutarMetodo('ViewFinFluxoCaixaController.TViewFinFluxoCaixaController', 'Consulta', [Filtro, '0', False], 'GET', 'Lista');
CalcularTotais;
end;
{$ENDREGION}
{$REGION 'Actions'}
procedure TFFinFluxoCaixa.BotaoConsultarClick(Sender: TObject);
var
Contexto: TRttiContext;
Tipo: TRttiType;
NomeClasseController: String;
begin
Filtro := MontaFiltro;
if Filtro <> 'ERRO' then
begin
Pagina := 0;
Contexto := TRttiContext.Create;
try
Tipo := Contexto.GetType(ObjetoController.ClassType);
ObjetoController.SetDataSet(CDSGrid);
NomeClasseController := ObjetoController.UnitName + '.' + ObjetoController.ClassName;
TController.ExecutarMetodo(NomeClasseController, 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista');
ControlaBotoesNavegacaoPagina;
finally
Contexto.Free;
end;
if not CDSGrid.IsEmpty then
Grid.SetFocus;
CalcularTotaisGeral;
end
else
EditCriterioRapido.SetFocus;
end;
procedure TFFinFluxoCaixa.BotaoSalvarClick(Sender: TObject);
begin
inherited;
//BotaoConsultar.Click;
end;
function TFFinFluxoCaixa.MontaFiltro: string;
var
Item: TItemComboBox;
Idx: Integer;
DataSetField: TField;
DataSet: TClientDataSet;
begin
DataSet := CDSGrid;
if ComboBoxCampos.ItemIndex <> -1 then
begin
if Trim(EditCriterioRapido.Text) = '' then
EditCriterioRapido.Text := '*';
Idx := ComboBoxCampos.ItemIndex;
Item := TItemComboBox(ComboBoxCampos.Items.Objects[Idx]);
DataSetField := DataSet.FindField(Item.Campo);
if DataSetField.DataType = ftDateTime then
begin
try
Result := '[' + Item.Campo + '] IN ' + '(' + QuotedStr(FormatDateTime('yyyy-mm-dd', StrToDate(EditCriterioRapido.Text))) + ')';
except
Application.MessageBox('Data informada inválida.', 'Erro', MB_OK + MB_ICONERROR);
Result := 'ERRO';
end;
end
else
Result := '([DATA_VENCIMENTO] between ' + QuotedStr(DataParaTexto(EditDataInicio.Date)) + ' and ' + QuotedStr(DataParaTexto(EditDataFim.Date)) + ') and [' + Item.Campo + '] LIKE ' + QuotedStr('%' + EditCriterioRapido.Text + '%');
end
else
begin
Result := ' 1=1 ';
end;
end;
procedure TFFinFluxoCaixa.CalcularTotais;
var
Recebimentos, Pagamentos, Saldo: Extended;
begin
Recebimentos := 0;
Pagamentos := 0;
Saldo := 0;
//
CDSFluxoCaixa.DisableControls;
CDSFluxoCaixa.First;
while not CDSFluxoCaixa.Eof do
begin
if CDSFluxoCaixa.FieldByName('OPERACAO').AsString = 'S' then
Pagamentos := Pagamentos + CDSFluxoCaixa.FieldByName('VALOR').AsExtended
else if CDSFluxoCaixa.FieldByName('OPERACAO').AsString = 'E' then
Recebimentos := Recebimentos + CDSFluxoCaixa.FieldByName('VALOR').AsExtended;
CDSFluxoCaixa.Next;
end;
CDSFluxoCaixa.First;
CDSFluxoCaixa.EnableControls;
//
PanelTotais.Caption := '| A Receber: ' + FloatToStrF(Recebimentos, ffCurrency, 15, 2) +
' | A Pagar: ' + FloatToStrF(Pagamentos, ffCurrency, 15, 2) +
' | Saldo: ' + FloatToStrF(Recebimentos - Pagamentos, ffCurrency, 15, 2) + ' |';
end;
procedure TFFinFluxoCaixa.CalcularTotaisGeral;
var
Recebimentos, Pagamentos, Saldo: Extended;
begin
Recebimentos := 0;
Pagamentos := 0;
Saldo := 0;
//
CDSGrid.DisableControls;
CDSGrid.First;
while not CDSGrid.Eof do
begin
if CDSGrid.FieldByName('OPERACAO').AsString = 'S' then
Pagamentos := Pagamentos + CDSGrid.FieldByName('VALOR').AsExtended
else if CDSGrid.FieldByName('OPERACAO').AsString = 'E' then
Recebimentos := Recebimentos + CDSGrid.FieldByName('VALOR').AsExtended;
CDSGrid.Next;
end;
CDSGrid.First;
CDSGrid.EnableControls;
//
PanelTotaisGeral.Caption := '| A Receber: ' + FloatToStrF(Recebimentos, ffCurrency, 15, 2) +
' | A Pagar: ' + FloatToStrF(Pagamentos, ffCurrency, 15, 2) +
' | Saldo: ' + FloatToStrF(Recebimentos - Pagamentos, ffCurrency, 15, 2) + ' |';
end;
{$ENDREGION}
end.
/// EXERCICIO: FAÇA O COMPARATIVO ENTRE O ORÇADO E REALIZADO.
/// PARA ISSO CRIE UMA NOVA VIEW PEGUE OS DADOS DAS TABELAS DE LANCAMENTO E DO QUE FOI EFETIVAMENTE RECEBIDO
/// OU FAÇA USO DAS VIEWS EXISTENTES - ANALISE OS DADOS COM ATENCAO
|
unit uMain;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, System.RegularExpressions,
Vcl.ExtCtrls;
type
TfMain = class(TForm)
cInput: TMemo;
FormatBtn: TButton;
cOutput: TMemo;
cEnableForeword: TCheckBox;
cForeword: TMemo;
cEnableAfterword: TCheckBox;
cAfterword: TMemo;
cCode: TLabel;
cComment: TCheckBox;
cApplyAntiFreebie: TCheckBox;
cAntiFreebie: TMemo;
cApplyAntiAntiSpam: TCheckBox;
cAntiAntiSpam: TComboBox;
CopyBtn: TButton;
PasteBtn: TButton;
Splitter4: TSplitter;
Splitter1: TSplitter;
Splitter2: TSplitter;
Splitter3: TSplitter;
procedure FormatBtnClick(Sender: TObject);
procedure cEnableForewordClick(Sender: TObject);
procedure cEnableAfterwordClick(Sender: TObject);
procedure cApplyAntiFreebieClick(Sender: TObject);
procedure cApplyAntiAntiSpamClick(Sender: TObject);
procedure CopyBtnClick(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure PasteBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
function FormatCode(Text: string; Space: string; AntiFreebie: Boolean;
AntiAntiSpam: Boolean; AntiAntiSpamUrl: string): string;
end;
var
fMain: TfMain;
implementation
{$R *.dfm}
uses
Winapi.Windows;
function TfMain.FormatCode(Text: string; Space: string; AntiFreebie: Boolean;
AntiAntiSpam: Boolean; AntiAntiSpamUrl: string): string;
const
_OLD: string = 'aceopxyABCEHKMOPTXасеорхуАВСЕНКМОРТХ';
_NEW: string = 'асеорхуАВСЕНКМОРТХaceopxyABCEHKMOPTX';
var
i: Integer;
mc: TMatchCollection;
function DontReplace(n: Integer): Boolean;
var
i: Integer;
begin
Result := False;
for i := 0 to Pred(mc.Count) do
if (mc.Item[i].Index <= n) and (Pred(mc.Item[i].Index + mc.Item[i].Length)
>= n) then
begin
Result := True;
Exit;
end;
end;
begin
Result := Text;
mc := TRegEx.Matches(Result,
'(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\:\%\?\=\+\-\&\w\.-]*)*\/?');
i := 1;
while i <= Length(Result) do
begin
case Result[i] of
'&':
if (not DontReplace(i)) then
begin
Insert('amp;', Result, Succ(i));
Inc(i, 5);
end
else
Inc(i);
else
if AntiFreebie then
if Pos(Result[i], _OLD) <> 0 then
if (not DontReplace(i)) then
Result[i] := _NEW[Pos(Result[i], _OLD)];
Inc(i);
end;
end;
Result := StringReplace(Result, #32#32, Space, [rfReplaceAll]);
Result := StringReplace(Result, #09, Space, [rfReplaceAll]);
Result := StringReplace(Result, '<', '<', [rfReplaceAll]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
if AntiAntiSpam then
Result := TRegEx.Replace(Result,
'(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\:\%\?\=\+\-\&\w\.-]*)*\/?',
'<a rel="nofollow" href="' + AntiAntiSpamUrl + '$0" target="_blank">$0</a>')
else
Result := TRegEx.Replace(Result,
'(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\:\%\?\=\+\-\&\w\.-]*)*\/?',
'<a rel="nofollow" href="$0" target="_blank">$0</a>')
end;
procedure TfMain.FormCreate(Sender: TObject);
begin
with Constraints do
begin
MinWidth := Width;
MinHeight := Height;
end;
end;
procedure TfMain.FormPaint(Sender: TObject);
begin
cAntiAntiSpam.SelStart := Length(cAntiAntiSpam.Text);
cAntiAntiSpam.SelLength := 0;
end;
procedure TfMain.PasteBtnClick(Sender: TObject);
begin
cInput.SelectAll;
cInput.PasteFromClipboard;
end;
procedure TfMain.cApplyAntiAntiSpamClick(Sender: TObject);
begin
cAntiAntiSpam.Enabled := cApplyAntiAntiSpam.Checked;
end;
procedure TfMain.cApplyAntiFreebieClick(Sender: TObject);
begin
cAntiFreebie.Enabled := cApplyAntiFreebie.Checked;
end;
procedure TfMain.cEnableAfterwordClick(Sender: TObject);
begin
cAfterword.Enabled := cEnableAfterword.Checked;
end;
procedure TfMain.cEnableForewordClick(Sender: TObject);
begin
cForeword.Enabled := cEnableForeword.Checked;
end;
procedure TfMain.CopyBtnClick(Sender: TObject);
begin
cOutput.SelectAll;
cOutput.CopyToClipboard;
end;
procedure TfMain.FormatBtnClick(Sender: TObject);
var
i: Integer;
begin
for i := 0 to Pred(cInput.Lines.Count) do
cInput.Lines[i] := TrimRight(cInput.Lines[i]);
if (cComment.Checked) and (Trim(cInput.Text) <> '') then
cOutput.Text := FormatCode(TrimRight(cInput.Text), ' ', cApplyAntiFreebie.Checked,
cApplyAntiAntiSpam.Checked, cAntiAntiSpam.Text)
else
cOutput.Text := FormatCode(TrimRight(cInput.Text), ' ',
cApplyAntiFreebie.Checked, cApplyAntiAntiSpam.Checked, cAntiAntiSpam.Text);
if (cEnableForeword.Checked) and (Trim(cForeword.Text) <> '') then
cOutput.Text := Trim(cForeword.Text) + #13#10#13#10 + cOutput.Text;
if (cApplyAntiFreebie.Checked) and (Trim(cAntiFreebie.Text) <> '') then
cOutput.Text := cOutput.Text + #13#10#13#10 + Trim(cAntiFreebie.Text);
if (cEnableAfterword.Checked) and (Trim(cAfterword.Text) <> '') then
cOutput.Text := cOutput.Text + #13#10#13#10 + Trim(cAfterword.Text);
cOutput.SelectAll;
end;
end.
|
{ Este exemplo foi baixado no site www.andrecelestino.com
Passe por lá a qualquer momento para conferir os novos artigos! :)
contato@andrecelestino.com }
unit untBalloonHint;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList;
type
TForm1 = class(TForm)
BalloonHint1: TBalloonHint;
Edit1: TEdit;
Button1: TButton;
ImageList1: TImageList;
Label1: TLabel;
Label2: TLabel;
Edit2: TEdit;
Label3: TLabel;
procedure Button1Click(Sender: TObject);
procedure Edit1Enter(Sender: TObject);
private
// procedure para exibir o BalloonHint
procedure ExibirBalloonHint(const Mensagem: string; Campo: TEdit);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
// se o Edit1 estiver vazio, o BalloonHint é exibido
if Trim(Edit1.Text) = '' then
begin
ExibirBalloonHint('Informe o nome do cliente', Edit1);
Exit;
end;
// se o Edit2 estiver vazio, o BalloonHint é exibido
if Trim(Edit2.Text) = '' then
begin
ExibirBalloonHint('Informe a cidade do cliente', Edit2);
Exit;
end;
// se os dois campos estiverem exibidos, a validação está OK!
MessageDlg('Validação OK!', mtInformation, [mbOK], 0);
end;
procedure TForm1.Edit1Enter(Sender: TObject);
begin
// esconde o BalloonHint quando o campo é focado
BalloonHint1.HideHint;
end;
procedure TForm1.ExibirBalloonHint(const Mensagem: string; Campo: TEdit);
var
Pt: TPoint;
begin
BalloonHint1.Description := Mensagem; // define a mensagem do BalloonHint
Pt.X := Campo.Width Div 2; // define a posição X
Pt.Y := 0; // define a posição Y
BalloonHint1.ShowHint(Campo.ClientToScreen(Pt)); // Exibe o BalloonHint
end;
end.
|
unit DSE_defs;
interface
uses Windows, Messages, Classes, SysUtils, vcl.Graphics;
type
SE_Direction = ( dirForward, dirBackward );
TFlipDirection = (FlipH, FlipV);
SE_BlendMode = (
SE_BlendNormal,
SE_BlendAlpha,
SE_BlendOR,
SE_BlendAND,
SE_BlendXOR,
SE_BlendMAX,
SE_BlendMIN,
SE_BlendAverage,
SE_BlendHardLight,
SE_BlendSoftLight,
SE_BlendReflect,
SE_BlendStamp,
SE_BlendLuminosity,
SE_BlendLuminosity2
);
PRGB = ^TRGB;
PRGBROW = ^RGBROW;
PBitmapInfoHeader256 = ^TBitmapInfoHeader256;
TBitmapInfoHeader256 = packed record
biSize: DWORD;
biWidth: Longint;
biHeight: Longint;
biPlanes: Word;
biBitCount: Word;
biCompression: DWORD;
biSizeImage: DWORD;
biXPelsPerMeter: Longint;
biYPelsPerMeter: Longint;
biClrUsed: DWORD;
biClrImportant: DWORD;
Palette: array[0..1] of TRGBQUAD;
end;
TRGB = packed record
b: byte;
g: byte;
r: byte;
end;
RGBROW = array[0..Maxint div 16] of TRGB;
type TPointArray7 = array[0..6] of TPoint;
type THexCellSize = record
Width : Integer;
Height : Integer;
SmallWidth : Integer;
end;
implementation
end.
|
unit UVoicePlayerThread;
interface
uses MPlayer, classes, Windows, dialogs, forms, SysUtils;
type
TVoicePlayerThread = class(TThread)
private
{ Private declarations }
filesStrList:TStrings;//play list: each entry is separated by * mark.
//For example, 100_v.wav*1.wav is 101.
mPlayer:TMediaPlayer;
mutex:Cardinal;
procedure playVoices();
protected
procedure Execute; override;
public constructor create(filesStrList:TStrings;mPlayer:TMediaPlayer;mutex:Cardinal);reintroduce;
end;
implementation
uses uspeech;
{ TVoicePlayerThread }
constructor TVoicePlayerThread.create(filesStrList: TStrings;
mPlayer: TMediaPlayer;mutex:Cardinal);
begin
inherited create(true);
FreeOnTerminate:=true;
self.mutex:=mutex;
self.filesStrList:=filesStrList;
self.mPlayer:=mPlayer;
end;
procedure TVoicePlayerThread.Execute;
begin
while WaitForSingleObject(mutex, 3000) = WAIT_TIMEOUT do ;
playVoices;
ReleaseMutex(mutex);
end;
procedure TVoicePlayerThread.playVoices;
var voicesDir, filesStr:string;
voiceFiles:TStrings;
i:integer;
begin
voicesDir:=IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName))+'numVoices\';
filesStr:=filesStrList.Strings[0];
filesStrList.Delete(0);
filesStr:='number.wav*'+filesStr;
voiceFiles := TStringList.Create;
try
ExtractStrings(['*'], [], PChar(filesStr), voiceFiles);
for i:=0 to voiceFiles.Count-1 do
begin
mPlayer.Close;
mPlayer.FileName:=voicesDir+voiceFiles[i];
mPlayer.Open;
mPlayer.Wait:=true;
mPlayer.Play;
end;
finally
voiceFiles.Free;
end;
end;
end.
|
(******************************************************************************
* *
* Project: Usermanager, Benutzerverwaltung für Windows NT, 2000, XP, Vista *
* File : ChooseComputerDlg, Dialog-Funktion für Computer im Netzwerk *
* *
* Copyright (c) Michael Puff http://www.michael-puff.de *
* *
******************************************************************************)
{$I ..\..\CompilerSwitches.inc}
unit ChooseComputerDlg;
interface
uses
Windows,
Messages,
Consts,
GUIHelpers,
MpuTools,
MpuRegistry,
Network,
HTMLHlp;
type
TSelCmpData = packed record
Computer: string[255];
Success: Boolean;
end;
PSelCmpData = ^TSelCmpData;
TCurCompData = packed record
Computer: string[255];
ParentHandle: THandle;
end;
PCurCompData = ^TCurCompData;
var
CurComputer : WideString;
{$I .\units\includes\resStrings.inc}
function ChooseCompDlgFunc(hDlg: HWND; umsg: Cardinal; wparam: WPARAM; lparam: LPARAM): BOOL; stdcall;
implementation
procedure SetDlgBtnCheck(Handle: THandle; ID: Integer; bCheck: Boolean);
const
Check : array[Boolean] of Integer = (BST_UNCHECKED, BST_CHECKED);
begin
CheckDlgButton(Handle, ID, Check[bCheck]);
end;
function GetDlgBtnCheck(hParent: THandle; ID: Integer): Boolean;
begin
result := IsDlgButtonChecked(hParent, ID) = BST_CHECKED;
end;
function ChooseCompDlgFunc(hDlg: HWND; umsg: Cardinal; wparam: WPARAM; lparam: LPARAM): BOOL; stdcall;
var
rect, rect1 : TRect;
x, y : Cardinal;
s : string;
ws : WideString;
len : Integer;
SelCmpData : PSelCmpData;
Computer : WideString;
User : WideString;
PW : WideString;
ret : DWORD;
reg : TMpuRegistry;
bSaveNetUserName : Boolean;
HelpFilename : string;
Url : string;
resourcestring
rsLinkTimeStamp = '%s - %s';
begin
Result := TRUE;
case umsg of
WM_INITDIALOG:
begin
// Window-Icons
if SendMessage(hDlg, WM_SETICON, ICON_SMALL, Integer(LoadIcon(hInstance, MAKEINTRESOURCE(5)))) = 0 then
SendMessage(hDlg, WM_SETICON, ICON_BIG, Integer(LoadIcon(hInstance, MAKEINTRESOURCE(5))));
// center dialog
GetWindowRect(PCurCompData(lparam)^.ParentHandle, rect);
GetWindowRect(hDlg, rect1);
x := rect.Left - ((rect.Left - rect.Right) div 2) - ((rect1.Right - rect1.Left) div 2);
y := rect.Top - ((rect.Top - rect.Bottom) div 2) - ((rect1.Bottom - rect1.Top) div 2);
SetWindowPos(hDlg, 0, x, y, 0, 0, SWP_NOSIZE);
SetWindowPos(GetDlgItem(hDlg, 299), 0, 0, 0, 305, 2, SWP_NOMOVE or SWP_SHOWWINDOW);
CurComputer := string(PCurCompData(lparam)^.Computer);
FreeMemory(PCurCompData(lparam));
EnableControl(hDlg, ID_BTN_OK_X, False);
EnableControl(hDlg, ID_BTN_HELP, FileExists(ExtractFilepath(ParamStr(0)) + HELPFILE));
// read registry settings
reg := TMpuRegistry.CreateW('', HKEY_CURRENT_USER);
try
if reg.Connect = 0 then
begin
if reg.OpenKeyW(XPUM_REG_KEY, KEY_READ) = 0 then
begin
if reg.ReadBoolW(REG_SAVENETUSERNAME, bSaveNetUserName) = 0 then
begin
SetDlgBtnCheck(hDlg, ID_CHK_SAVEUSERNAME, bSaveNetUserName);
if bSaveNetUserName then
begin
reg.ReadStringW(REG_NETUSERNAME, ws);
SetItemTextW(hDlg, ID_EDT_ACCOUNT_X, ws);
reg.ReadStringW(REG_REMOTECOMPUTER, ws);
SetItemTextW(hDlg, ID_EDT_COMP_X, ws);
end;
end;
//else if GetLastError <> 0 then
//DisplayErrorMsg(hDlg, GetLastError, SysErrorMessage(GetLastError), APPNAME);
end;
//else if GetLastError <> 0 then
//DisplayErrorMsg(hDlg, GetLastError, SysErrorMessage(GetLastError), APPNAME);
end;
//else
//DisplayErrorMsg(hDlg, GetLastError, SysErrorMessage(GetLastError), APPNAME);
finally
reg.Free;
end;
end;
WM_HELP:
begin
if PHelpInfo(lParam)^.dwContextId > 0 then
ShowHelpHandle(PHelpInfo(lParam)^.hItemHandle, PHelpInfo(lParam)^.dwContextId)
else
//DefDlgProc(hDlg, uMsg, wParam, lParam);
Exit;
end;
WM_LBUTTONDOWN:
Sendmessage(hDlg, WM_NCLBUTTONDOWN, HTCAPTION, lParam);
WM_CLOSE:
begin
SelCmpData := GetMemory(SizeOf(TSelCmpData));
SelCmpData.Success := False;
EndDialog(hDlg, Integer(SelCmpData));
end;
WM_DESTROY:
begin
// Save user name to registry
reg := TMpuRegistry.CreateW('', HKEY_CURRENT_USER);
try
if reg.Connect = 0 then
begin
if reg.OpenKeyW(XPUM_REG_KEY, KEY_WRITE) = 0 then
begin
// save
if GetDlgBtnCheck(hDlg, ID_CHK_SAVEUSERNAME) then
begin
Computer := GetItemTextW(hDlg, ID_EDT_COMP_X);
User := GetItemTextW(hDlg, ID_EDT_ACCOUNT_X);
reg.WriteBoolW(REG_SAVENETUSERNAME, True);
reg.WriteStringW(REG_NETUSERNAME, User);
reg.WriteStringW(REG_REMOTECOMPUTER, Computer);
end
else // don't save / delete
begin
reg.WriteBoolW(REG_SAVENETUSERNAME, False);
reg.DeleteValueName(REG_NETUSERNAME);
reg.DeleteValueName(REG_REMOTECOMPUTER);
end;
end
else if GetLastError <> 0 then
MessageBoxW(hDlg, PWideChar(WideString(SysErrorMessage(GetLastError))),
PWideChar(WideString(APPNAME)), MB_ICONERROR);
end;
finally
reg.Free;
end;
end;
WM_COMMAND:
begin
if wParam = ID_CANCEL then
SendMessage(hDlg, WM_CLOSE, 0, 0);
if HiWord(wParam) = EN_CHANGE then
begin
case LoWord(wParam) of
ID_EDT_COMP_X:
begin
len := SendDlgItemMessage(hDlg, ID_EDT_COMP_X, WM_GETTEXTLENGTH, 0, 0);
EnableControl(hDlg, ID_BTN_OK_X, len > 0);
end;
end;
end;
if HiWord(wParam) = BN_CLICKED then
case LoWord(wParam) of
ID_BTN_HELP:
begin
HelpFilename := ExtractFilepath(ParamStr(0)) + HELPFILE;
Url := string(HelpFilename + '::/hilfe.html#3');
HtmlHelp(hDlg, PChar(Url), HH_DISPLAY_TOPIC, 0);
end;
ID_BTN_SEARCH_X:
begin
if FindComputer(hDlg, rsSelComputer, s) then
begin
SetDlgItemText(hDlg, ID_EDT_COMP_X, PChar(s));
end;
end;
ID_BTN_CLOSE_X:
begin
//SelCmpData := GetMemory(SizeOf(TSelCmpData));
//SelCmpData.Success := False;
SendMessage(hDlg, WM_CLOSE, 0, 0);
//EndDialog(hDlg, Integer(SelCmpData));
end;
ID_BTN_OK_X:
begin
Computer := GetItemTextW(hDlg, ID_EDT_COMP_X);
User := GetItemTextW(hDlg, ID_EDT_ACCOUNT_X);
PW := GetItemTextW(hDlg, ID_EDT_PW_X);
DisconnectNetworkDrivew(CurComputer);
ret := ConnectToNetworkDriveW('', Computer + '\IPC$', User, PW, False);
if ret = 0 then
begin
SelCmpData := GetMemory(sizeof(TSelCmpData));
SelCmpData.Computer := AnsiString(Computer);
SelCmpData.Success := True;
EndDialog(hDlg, Integer(SelCmpData));
end
else
begin
DisplayErrorMsg(hDlg, ret, SysErrorMessage(ret), rsErrorConnectNetWork);
case ret of
53:
begin
SetItemTextW(hDlg, ID_EDT_COMP_X, '');
SetFocus(GetDlgItem(hDlg, ID_EDT_COMP_X));
end;
1385:
begin
SetItemTextW(hDlg, ID_EDT_ACCOUNT_X, '');
SetItemTextW(hDlg, ID_EDT_PW_X, '');
SetFocus(GetDlgItem(hDlg, ID_EDT_ACCOUNT_X));
end;
end;
end;
end;
end;
end;
else
result := false;
end;
end;
end.
|
Unit ZDialogs;
{################################}
{# ZiLEM Z80 Emulator #}
{# Dialogs #}
{# Copyright (c) 1994 James Ots #}
{# All rights reserved #}
{################################}
Interface
Uses
Objects, Views, Dialogs, Drivers, Validate, ZStdDlg, ZConsts, MsgBox,
ZValid, ZGlobals, ZInputs;
Type
PPrintDialog = ^TPrintDialog;
TPrintDialog = Object(TDialog)
Constructor Init;
End;
PGotoDialog = ^TGotoDialog;
TGotoDialog = Object(TDialog)
Constructor Init;
End;
PFillDialog = ^TFillDialog;
TFillDialog = Object(TDialog)
Constructor Init;
End;
PLoadDialog = ^TLoadDialog;
TLoadDialog = Object(TFileDialog)
PLoadInputLine : PInputLine;
Constructor Init(AWildCard : String);
End;
PSaveDialog = ^TSaveDialog;
TSaveDialog = Object(TFileDialog)
PSaveFromInputLine : PAddressInputLine;
PSaveToInputLine : PAddressInputLine;
Constructor Init(AWildCard : String);
End;
PPreferencesDialog = ^TPreferencesDialog;
TPreferencesDialog = Object(TDialog)
Constructor Init;
End;
PCopyDialog = ^TCopyDialog;
TCopyDialog = Object(TDialog)
PCopyFromInputLine : PAddressInputLine;
PCopyToInputLine : PAddressInputLine;
Constructor Init;
End;
PPasteDialog = ^TPasteDialog;
TPasteDialog = Object(TDialog)
Constructor Init;
End;
PFindDialog = ^TFindDialog;
TFindDialog = Object(TDialog)
PFindStringInputLine : PStringInputLine;
Constructor Init;
End;
PReplaceDialog = ^TReplaceDialog;
TReplaceDialog = Object(TDialog)
PFindStringInputLine,
PReplaceStringInputLine : PStringInputLine;
Constructor Init;
Function Valid(Command : Word) : Boolean; virtual;
End;
PInterruptModeDialog = ^TInterruptModeDialog;
TInterruptModeDialog = Object(TDialog)
Constructor Init;
End;
PInterruptDialog = ^TInterruptDialog;
TInterruptDialog = Object(TDialog)
PInterruptInput : PByteInputLine;
Constructor Init;
End;
Implementation
Constructor TPrintDialog.Init;
Var
R : TRect;
PPrintFromInputLine,
PPrintToInputLine : PAddressInputLine;
PPrintRadio : PRadioButtons;
PPrintButton : PButton;
Begin
R.Assign(0,0,26,14);
Inherited Init(R,'Print');
Options := Options or ofCentered;
R.Assign(3,3,13,4);
PPrintFromInputLine := New(PAddressInputLine,Init(R,
hcPrintFromInputLine));
Insert(PPrintFromInputLine);
R.Assign(2,2,14,3);
Insert(New(PLabel,Init(R,'Print ~f~rom',PPrintFromInputLine)));
R.Assign(3,6,13,7);
PPrintToInputLine := New(PAddressInputLine,Init(R,hcPrintToInputLine));
Insert(PPrintToInputLine);
R.Assign(2,5,11,6);
Insert(New(PLabel,Init(R,'Print ~t~o',PPrintToInputLine)));
R.Assign(3,9,13,12);
PPrintRadio := New(PRadioButtons, Init(R,
NewSItem('He~x~',
NewSItem('~A~SCII',
NewSItem('~C~ode',
nil)))
));
PPrintRadio^.HelpCtx := hcPrintRadio;
Insert(PPrintRadio);
R.Assign(2,8,13,9);
Insert(New(PLabel,Init(R,'~P~rint in',PPrintRadio)));
R.Assign(14,3,24,5);
PPrintButton := New(PButton,Init(R,'O~k~',cmOk,bfDefault));
PPrintButton^.HelpCtx := hcOkButton;
Insert(PPrintButton);
R.Assign(14,6,24,8);
PPrintButton := New(PButton,Init(R,'~C~ancel',cmCancel,bfNormal));
PPrintButton^.HelpCtx := hcCancelButton;
Insert(PPrintButton);
SelectNext(False);
End;
Function TReplaceDialog.Valid(Command : Word) : Boolean;
Var
TempValid,
TempValid2 : Boolean;
AnError : Boolean;
Begin
If Inherited Valid(Command) and (Command <> cmCancel) then
If UnformatStr(PFindStringInputLine^.Data^,AnError) =
UnformatStr(PReplaceStringInputLine^.Data^,AnError) then
Valid := True else
Begin
Valid := False;
MessageBox(#3'Strings are not the'#13#13#3'same length',
nil,mfError or mfOkButton);
End else
If Command = cmCancel then
Valid := True else
Valid := False;
End; {of TReplaceDialog.Valid}
Constructor TReplaceDialog.Init;
Var
R : TRect;
PReplaceButton : PButton;
Begin
R.Assign(0,0,40,11);
Inherited Init(R,'Replace');
Options := Options or ofCentered;
R.Assign(3,3,34,4);
PFindStringInputLine := New(PStringInputLine,Init(R,255,
hcFindInputLine));
Insert(PFindStringInputLine);
R.Assign(34,3,37,4);
Insert(New(PHistory,Init(R,PFindStringInputLine,
hsReplaceFindInputLine)));
R.Assign(2,2,17,3);
Insert(New(PLabel,Init(R,'~S~tring to find',PFindStringInputLine)));
R.Assign(3,6,34,7);
PReplaceStringInputLine := New(PStringInputLine,Init(R,255,
hcReplaceInputLine));
Insert(PReplaceStringInputLine);
R.Assign(34,6,37,7);
Insert(New(PHistory,Init(R,PReplaceStringInputLine,
hsReplaceInputLine)));
R.Assign(2,5,17,6);
Insert(New(PLabel,Init(R,'~N~ew String',PReplaceStringInputLine)));
R.Assign(15,8,25,10);
PReplaceButton := New(PButton,Init(R,'O~k~',cmOk,bfDefault));
PReplaceButton^.HelpCtx := hcOkButton;
Insert(PReplaceButton);
R.Assign(27,8,37,10);
PReplaceButton := New(PButton,Init(R,'~C~ancel',cmCancel,bfNormal));
PReplaceButton^.HelpCtx := hcCancelButton;
Insert(PReplaceButton);
SelectNext(False);
End; {of TReplaceDialog.Init}
Constructor TFindDialog.Init;
Var
R : TRect;
PFindButton : PButton;
Begin
R.Assign(0,0,39,8);
Inherited Init(R,'Find');
Options := Options or ofCentered;
R.Assign(3,3,33,4);
PFindStringInputLine := New(PStringInputLine,Init(R,255,
hcFindInputLine));
Insert(PFindStringInputLine);
R.Assign(33,3,36,4);
Insert(New(PHistory,Init(R,PFindStringInputLine,hsFindInputLine)));
R.Assign(2,2,17,3);
Insert(New(PLabel,Init(R,'~S~tring to find',PFindStringInputLine)));
R.Assign(14,5,24,7);
PFindButton := New(PButton,Init(R,'O~k~',cmOk,bfDefault));
PFindButton^.HelpCtx := hcOkButton;
Insert(PFindButton);
R.Assign(26,5,36,7);
PFindButton := New(PButton,Init(R,'~C~ancel',cmCancel,bfNormal));
PFindButton^.HelpCtx := hcCancelButton;
Insert(PFindButton);
SelectNext(False);
End; {of TFindDialog.Init}
Constructor TPasteDialog.Init;
Var
R : TRect;
PPasteInputLine : PAddressInputLine;
PCopyButton : PButton;
Begin
R.Assign(0,0,27,8);
Inherited Init(R,'Paste');
Options := Options or ofCentered;
R.Assign(3,3,13,4);
PPasteInputLine := New(PAddressInputLine,Init(R,hcPasteInputLine));
Insert(PPasteInputLine);
R.Assign(2,2,11,3);
Insert(New(PLabel,Init(R,'~P~aste to',PPasteInputLine)));
R.Assign(2,5,12,7);
PCopyButton := New(PButton,Init(R,'O~k~',cmOk,bfDefault));
PCopyButton^.HelpCtx := hcOkButton;
Insert(PCopyButton);
R.Assign(14,5,24,7);
PCopyButton := New(PButton,Init(R,'~C~ancel',cmCancel,bfNormal));
PCopyButton^.HelpCtx := hcCancelButton;
Insert(PCopyButton);
SelectNext(False);
End; {of TPasteDialog.Init}
Constructor TCopyDialog.Init;
Var
R : TRect;
PCopyButton : PButton;
Begin
R.Assign(0,0,27,11);
Inherited Init(R,'Copy');
Options := Options or ofCentered;
R.Assign(3,3,13,4);
PCopyFromInputLine := New(PAddressInputLine,Init(R,
hcCopyFromInputLine));
Insert(PCopyFromInputLine);
R.Assign(2,2,12,3);
Insert(New(PLabel,Init(R,'Copy ~f~rom',PCopyFromInputLine)));
R.Assign(3,6,13,7);
PCopyToInputLine := New(PAddressInputLine,Init(R,hcCopyToInputLine));
Insert(PCopyToInputLine);
R.Assign(2,5,10,6);
Insert(New(PLabel,Init(R,'Copy ~t~o',PCopyToInputLine)));
R.Assign(2,8,12,10);
PCopyButton := New(PButton,Init(R,'O~k~',cmOk,bfDefault));
PCopyButton^.HelpCtx := hcOkButton;
Insert(PCopyButton);
R.Assign(14,8,24,10);
PCopyButton := New(PButton,Init(R,'~C~ancel',cmCancel,bfNormal));
PCopyButton^.HelpCtx := hcCancelButton;
Insert(PCopyButton);
SelectNext(False);
End; {of TCopyDialog.Init}
Constructor TInterruptDialog.Init;
Var
R : TRect;
PInterruptButton : PButton;
Begin
R.Assign(0,0,20,8);
Inherited Init(R,'Interrupt');
Options := Options or ofCentered;
R.Assign(3,3,9,4);
PInterruptInput := New(PByteInputLine,Init(R,hcInterruptInput));
Insert(PInterruptInput);
R.Assign(2,2,19,3);
Insert(New(PLabel,Init(R,'~I~nterrupt data',PInterruptInput)));
R.Assign(7,5,17,7);
PInterruptButton := New(PButton, Init(R,'O~k~',cmOk,bfDefault));
PInterruptButton^.HelpCtx := hcOkButton;
Insert(PInterruptButton);
SelectNext(False);
End; {of TInterruptDialog.Init}
Constructor TInterruptModeDialog.Init;
Var
R : TRect;
PModeRadio : PRadioButtons;
PInterruptButton : PButton;
Begin
R.Assign(0,0,28,8);
Inherited Init(R,'Interrupt Mode');
Options := Options or ofCentered;
R.Assign(3,3,25,4);
PModeRadio := New(PRadioButtons, Init(R,
NewSItem('~0~',
NewSItem('~1~',
NewSItem('~2~',
nil)))
));
PModeRadio^.HelpCtx := hcInterruptModeRadio;
Insert(PModeRadio);
R.Assign(2,2,13,3);
Insert(New(PLabel,Init(R,'Interrupt Mode',PModeRadio)));
R.Assign(3,5,13,7);
PInterruptButton := New(PButton, Init(R,'O~k~',cmOk,bfDefault));
PInterruptButton^.HelpCtx := hcOkButton;
Insert(PInterruptButton);
R.Assign(15,5,25,7);
PInterruptButton := New(PButton, Init(R,'~C~ancel',cmCancel,bfNormal));
PInterruptButton^.HelpCtx := hcCancelButton;
Insert(PInterruptButton);
SelectNext(False);
End; {of TInterruptModeDialog.Init}
Constructor TPreferencesDialog.Init;
Var
R : TRect;
PPrefScreenRadio : PRadioButtons;
PPrefBaseRadio : PRadioButtons;
PPrefChecks : PCheckBoxes;
PPrefButton : PButton;
Begin
R.Assign(0,0,37,16);
Inherited Init(R,'Preferences');
Options := Options or ofCentered;
R.Assign(3,3,34,4);
PPrefScreenRadio := New(PRadioButtons, Init(R,
NewSItem('~2~5 lines',
NewSItem('~4~3/50 lines',
nil))
));
PPrefScreenRadio^.HelpCtx := hcScreenRadio;
Insert(PPrefScreenRadio);
R.Assign(2,2,15,3);
Insert(New(PLabel,Init(R,'Screen sizes',PPrefScreenRadio)));
R.Assign(3,6,34,7);
PPrefBaseRadio := New(PRadioButtons, Init(R,
NewSItem('~H~exadecimal',
NewSItem('~D~ecimal',
nil))
));
PPrefBaseRadio^.HelpCtx := hcDefaultBaseRadio;
Insert(PPrefBaseRadio);
R.Assign(2,5,15,6);
Insert(New(PLabel,Init(R,'Default base',PPrefBaseRadio)));
R.Assign(3,8,34,12);
PPrefChecks := New(PCheckBoxes, Init(R,
NewSItem('D~i~splay #00-#1F',
NewSItem('~P~rint #00-#1F',
NewSItem('~U~pper case opcodes',
NewSItem('~F~ollow PC in code window',
nil))))
));
PPrefChecks^.HelpCtx := hcPrefChecks;
Insert(PPrefChecks);
R.Assign(12,13,22,15);
PPrefButton := New(PButton, Init(R,'O~k~',cmOk,bfDefault));
PPrefButton^.HelpCtx := hcOkButton;
Insert(PPrefButton);
R.Assign(24,13,34,15);
PPrefButton := New(PButton, Init(R,'~C~ancel',cmCancel,bfNormal));
PPrefButton^.HelpCtx := hcCancelButton;
Insert(PPrefButton);
SelectNext(False);
End; {of TPreferencesDialog.Init}
Constructor TSaveDialog.Init(AWildCard : String);
Var
R : TRect;
Begin
Inherited Init(AWildCard,'Save File As','~S~ave file as',fdOkButton,
hsSave);
R.Assign(36,9,45,10);
PSaveFromInputLine := New(PAddressInputLine,Init(R,
hcSaveFromInputLine));
Insert(PSaveFromInputLine);
R.Assign(35,8,45,9);
Insert(New(PLabel,Init(R,'Save ~f~rom',PSaveFromInputLine)));
R.Assign(36,12,45,13);
PSaveToInputLine := New(PAddressInputLine,Init(R,hcSaveToInputLine));
Insert(PSaveToInputLine);
R.Assign(35,11,43,12);
Insert(New(PLabel,Init(R,'Save ~t~o',PSaveToInputLine)));
End; {of TSaveDialog.Init}
Constructor TLoadDialog.Init(AWildCard : String);
Var
R : TRect;
Begin
Inherited Init(AWildCard,'Load a File','~N~ame',fdOkButton,hsLoad);
R.Assign(36,9,45,10);
PLoadInputLine := New(PAddressInputLine,Init(R,hcLoadInputLine));
Insert(PLoadInputLine);
R.Assign(35,8,43,9);
Insert(New(PLabel,Init(R,'~L~oad at',PLoadInputLine)));
End; {of TLoadDialog.Init}
Constructor TGotoDialog.Init;
Var
R : TRect;
PGotoInputLine : PAddressInputLine;
PGotoButton : PButton;
Begin
R.Assign(0,0,27,7);
Inherited Init(R,'Go to');
Options := Options or ofCentered;
R.Assign(11,2,19,3);
PGotoInputLine := New(PAddressInputLine,Init(R,hcGotoInputLine));
Insert(PGotoInputLine);
R.Assign(2,2,10,3);
Insert(New(PLabel,Init(R,'~G~o to',PGotoInputLine)));
R.Assign(2,4,12,6);
PGotoButton := New(PButton,Init(R,'O~k~',cmOk,bfDefault));
PGotoButton^.HelpCtx := hcOkButton;
Insert(PGotoButton);
R.Assign(14,4,24,6);
PGotoButton := New(PButton,Init(R,'~C~ancel',cmCancel,bfNormal));
PGotoButton^.HelpCtx := hcCancelButton;
Insert(PGotoButton);
SelectNext(False);
End; {of TGotoDialog.Init}
Constructor TFillDialog.Init;
var
R : TRect;
PFillInputLine : PInputLine;
PFillButton : PButton;
Begin
R.Assign(0,0,27,11);
Inherited Init(R,'Fill');
Options := Options or ofCentered;
R.Assign(14,2,22,3);
PFillInputLine := New(PAddressInputLine,Init(R,hcFillFromInputLine));
Insert(PFillInputLine);
R.Assign(2,2,12,3);
Insert(New(PLabel,Init(R,'Fill ~f~rom',PFillInputLine)));
R.Assign(14,4,22,5);
PFillInputLine := New(PAddressInputLine,Init(R,hcFillToInputLine));
Insert(PFillInputLine);
R.Assign(2,4,12,5);
Insert(New(PLabel,Init(R,' ~t~o',PFillInputLine)));
R.Assign(14,6,22,7);
PFillInputLine := New(PInputLine,Init(R,6));
PFillInputLine^.SetValidator(New(PZRangeValidator,Init(0,255,
Pref.Base=0)));
PFillInputLine^.HelpCtx := hcFillWithInputLine;
Insert(PFillInputLine);
R.Assign(2,6,12,7);
Insert(New(PLabel,Init(R,' ~w~ith',PFillInputLine)));
R.Assign(2,8,12,10);
PFillButton := New(PButton,Init(R,'O~k~',cmOk,bfDefault));
PFillButton^.HelpCtx := hcOkButton;
Insert(PFillButton);
R.Assign(14,8,24,10);
PFillButton := New(PButton,Init(R,'~C~ancel',cmCancel,bfNormal));
PFillButton^.HelpCtx := hcCancelButton;
Insert(PFillButton);
SelectNext(False);
End; {of TFillDialog.Init}
End. {of Unit ZDialogs}
|
unit NovusSimpleXML;
interface
Uses NovusUtilities, JvSimpleXML, SysUtils, classes;
Type
TNovusSimpleXML = Class(TNovusUtilities)
private
protected
public
class function FindNodeByValue(aNodeList: TJvSimpleXmlElem; NodeName: String; NodeValueName, NodeValue: String): TJvSimpleXmlElem;
class function FindNode(aNodeList: TJvSimpleXmlElem; NodeName: String; Var Index: Integer): TJvSimpleXmlElem;
class procedure ListNodeNames(aNodeList: TJvSimpleXmlElem; Var aStringList: tStringList);
end;
implementation
class function TNovusSimpleXML.FindNodeByValue(aNodeList: TJvSimpleXmlElem; NodeName: String; NodeValueName, NodeValue: String): TJvSimpleXmlElem;
Var
fJvSimpleXmlElem: TJvSimpleXmlElem;
I, Index: Integer;
begin
Result := NIL;
Index := 0;
fJvSimpleXmlElem := FindNode(aNodeList, NodeName,Index);
While(fJvSimpleXmlElem <> NIL) do
begin
For I := 0 to fJvSimpleXmlElem.Properties.Count-1 do
begin
If Uppercase(fJvSimpleXmlElem.Properties[I].Name) = uppercase(NodeValueName) then
begin
If Uppercase(fJvSimpleXmlElem.Properties[I].Value) = Uppercase(NodeValue) then
begin
Result := fJvSimpleXmlElem;
Exit;
end;
end;
end;
fJvSimpleXmlElem := FindNode(aNodeList, NodeName,Index);
end;
end;
class procedure TNovusSimpleXML.ListNodeNames(aNodeList: TJvSimpleXmlElem; Var aStringList: tStringList);
Var
I: integer;
begin
aStringList.Clear;
For I := 0 to aNodeList.Items.count -1 do
astringList.Add(aNodeList.Items[i].Name);
end;
class function TNovusSimpleXML.FindNode(aNodeList: TJvSimpleXmlElem; NodeName: String; Var Index: Integer): TJvSimpleXmlElem;
Var
I: integer;
begin
Result := NIL;
For I := Index to aNodeList.Items.count -1 do
begin
If Uppercase(aNodeList.Items[i].Name) = Uppercase(NodeName) then
begin
Result := aNodeLIst.Items[I];
Index := i + 1;
Break;
end;
end;
end;
end.
|
unit DAO.Entregadores;
interface
uses DAO.Base, Model.Entregadores, Generics.Collections, System.Classes;
type
TEntregadoresDAO = class (TDAO)
public
function Insert(aEntregadores: Model.Entregadores.TEntregadores): Boolean;
function Update(aEntregadores: Model.Entregadores.TEntregadores): Boolean;
function Delete(iCadastro: Integer): Boolean;
function FindEntregador(sFiltro: String; aParam: array of Variant): TObjectList<Model.Entregadores.TEntregadores>;
end;
const
TABLENAME = 'tbcodigosentregadores';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
{ TEntregadoresDAO }
function TEntregadoresDAO.Delete(iCadastro: Integer): Boolean;
var
sSQL : String;
begin
Result := False;
if iCadastro = 0 then
begin
Exit;
end;
sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE COD_CADASTRO = :CADASTRO';
Connection.ExecSQL(sSQL,[iCadastro],[ftInteger]);
Result := True;
end;
function TEntregadoresDAO.FindEntregador(sFiltro: String; aParam: array of Variant): TObjectList<Model.Entregadores.TEntregadores>;
var
FDQuery: TFDQuery;
entregadores: TObjectList<TEntregadores>;
begin
try
FDQuery := TFDQuery.Create(nil);
if Length(aParam) = 0 then
begin
Exit;
end;
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if sFiltro = 'CADASTRO' then
begin
FDQuery.SQL.Add('WHERE COD_CADASTRO = :CADASTRO');
FDQuery.ParamByName('CADASTRO').AsInteger := aParam[0];
end;
if sFiltro = 'ENTREGADOR' then
begin
FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR');
FDQuery.ParamByName('ENTREGADOR').AsInteger := aParam[0];
end;
if sFiltro = 'FANTASIA' then
begin
FDQuery.SQL.Add('WHERE NOM_FANTASIA = :FANTASIA');
FDQuery.ParamByName('FANTASIA').AsString := aParam[0];
end;
if sFiltro = 'AGENTE' then
begin
FDQuery.SQL.Add('WHERE COD_AGENTE = :AGENTE ORDER BY COD_ENTREGADOR');
FDQuery.ParamByName('AGENTE').AsInteger := aParam[0];
end;
if sFiltro = 'CHAVE' then
begin
FDQuery.SQL.Add('WHERE DES_CHAVE = :CHAVE');
FDQuery.ParamByName('CHAVE').AsString := aParam[0];
end;
if sFiltro = 'GRUPO' then
begin
FDQuery.SQL.Add('WHERE COD_GRUPO = :GRUPO');
FDQuery.ParamByName('GRUPO').AsInteger := aParam[0];
end;
if sFiltro = 'FILTRO' then
begin
FDQuery.SQL.Add(aParam[0]);
end;
FDQuery.Open();
entregadores := TObjectList<TEntregadores>.Create;
while not FDQuery.Eof do
begin
entregadores.Add(TEntregadores.Create(FDQuery.FieldByName('COD_CADASTRO').AsInteger,
FDQuery.FieldByName('COD_ENTREGADOR').AsInteger,
FDQuery.FieldByName('NOM_FANTASIA').AsString,
FDQuery.FieldByName('COD_AGENTE').AsInteger,
FDQuery.FieldByName('DAT_CODIGO').AsDateTime,
FDQuery.FieldByName('DES_CHAVE').AsString,
FDQuery.FieldByName('COD_GRUPO').AsInteger,
FDQuery.FieldByName('VAL_VERBA').AsFloat,
FDQuery.FieldByName('NOM_EXECUTANTE').AsString,
FDQuery.FieldByName('DAT_MANUTENCAO').AsDateTime));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := entregadores;
end;
function TEntregadoresDAO.Insert(aEntregadores: Model.Entregadores.TEntregadores): Boolean;
var
sSQL : System.string;
begin
Result := False;
sSQL := 'INSERT INTO ' + TABLENAME + ' (COD_CADASTRO, COD_ENTREGADOR, NOM_FANTASIA, COD_AGENTE, DAT_CODIGO, ' +
'DES_CHAVE, COD_GRUPO, VAL_VERBA, NOM_EXECUTANTE, DAT_MANUTENCAO) ' +
'VALUES ' +
'(:COD_CADASTRO, :COD_ENTREGADOR, :NOM_FANTASIA, :COD_AGENTE, :DAT_CODIGO, ' +
':DES_CHAVE, :COD_GRUPO, :VAL_VERBA, :NOM_EXECUTANTE, :DAT_MANUTENCAO) ';
Connection.ExecSQL(sSQL,[aEntregadores.Cadastro, aEntregadores.Entregador, aEntregadores.Fantasia, aEntregadores.Agente,
aEntregadores.Data, aEntregadores.Chave, aEntregadores.Grupo, aEntregadores.Verba,
aEntregadores.Executor, aEntregadores.Manutencao],
[ftInteger, ftInteger, ftString, ftInteger, ftDate, ftString, ftInteger, ftFloat,
ftString, ftDateTime]);
Result := True;
end;
function TEntregadoresDAO.Update(aEntregadores: Model.Entregadores.TEntregadores): Boolean;
var
sSQL : System.string;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' SET ' +
'NOM_FANTASIA = :NOM_FANTASIA, COD_AGENTE = :COD_AGENTE, DAT_CODIGO = :DAT_CODIGO, DES_CHAVE = :DES_CHAVE, ' +
'COD_GRUPO = :COD_GRUPO, VAL_VERBA = :VAL_VERBA, NOM_EXECUTANTE = :NOM_EXECUTANTE, ' +
'DAT_MANUTENCAO = :DAT_MANUTENCAO ' +
'WHERE COD_CADASTRO = :COD_CADASTRO AND COD_ENTREGADOR = :COD_ENTREGADOR;';
Connection.ExecSQL(sSQL,[aEntregadores.Fantasia, aEntregadores.Agente,
aEntregadores.Data, aEntregadores.Chave, aEntregadores.Grupo, aEntregadores.Verba,
aEntregadores.Executor, aEntregadores.Manutencao, aEntregadores.Cadastro, aEntregadores.Entregador],
[ftString, ftInteger, ftDate, ftString, ftInteger, ftFloat,
ftString, ftDateTime, ftInteger, ftInteger]);
Result := True;
end;
end.
|
unit SRWave;
{ TSRWavePlayer - Komponente (C)opyright 2000 Version 1.02
Autor : Simon Reinhardt
eMail : reinhardt@picsoft.de
Internet : http://www.picsoft.de
Die Komponente TSRWavePlayer kapselt die Methoden PlaySound (32Bit)
bzw. sndPlaySound (16Bit) der Windows-API zur Wiedergabe von Wave-Sounds.
Diese Komponente ist Public Domain, das Urheberrecht liegt aber beim Autor.
Fragen und Verbesserungsvorschläge sind immer willkommen. }
interface
{$I SRDefine.inc}
uses
{$IFDEF SR_Win32} Windows, {$ELSE} WinTypes, WinProcs, SysUtils, {$ENDIF}
Classes, Graphics, Controls, Forms, MMSystem;
type
TWaveLocation = (wlFile, wlResource, wlRAM);
TSRWavePlayer = class(TComponent)
private
FAsync,
FLoop : boolean;
FWaveName : string;
FWavePointer : pointer;
FWaveLocation : TWaveLocation;
FBeforePlay,
FAfterPlay : TNotifyEvent;
procedure SetAfterPlay(Value: TNotifyEvent);
procedure SetAsync(Value: boolean);
procedure SetBeforePlay(Value: TNotifyEvent);
procedure SetLoop(Value: boolean);
public
property WavePointer: pointer read fWavePointer write fWavePointer;
function Play: boolean;
procedure Stop;
published
property Async: boolean read FAsync write SetAsync;
property Loop: boolean read FLoop write SetLoop;
{$IFDEF SR_Delphi2_Up}
property WaveLocation: TWaveLocation read FWaveLocation write fWaveLocation default wlFile;
{$ENDIF}
property WaveName: string read FWaveName write FWaveName;
property BeforePlay: TNotifyEvent read FBeforePlay write SetBeforePlay;
property AfterPlay: TNotifyEvent read FAfterPlay write SetAfterPlay;
end;
procedure Register;
implementation
{$IFDEF SR_Delphi2_Up}
{$R *.D32}
{$ELSE}
{$R *.D16}
{$ENDIF}
procedure TSRWavePlayer.SetAfterPlay(Value: TNotifyEvent);
begin
FAfterPlay:=Value;
end;
procedure TSRWavePlayer.SetAsync(Value: boolean);
begin
FAsync:=Value;
if not FAsync then
FLoop:=false;
end;
procedure TSRWavePlayer.SetBeforePlay(Value: TNotifyEvent);
begin
FBeforePlay:=Value;
end;
procedure TSRWavePlayer.SetLoop(Value: boolean);
begin
if (FLoop<>Value) and FAsync then
FLoop:=Value;
end;
function TSRWavePlayer.Play;
{$IFDEF SR_Delphi2_Up}
var Flags : DWORD;
{$ELSE}
var Flags : WORD;
PWaveName : PChar;
{$ENDIF}
begin
if Assigned(FBeforePlay) then
FBeforePlay(Self);
{$IFDEF SR_Delphi2_Up}
case FWaveLocation of
wlFile : Flags:=SND_FILENAME;
wlResource : Flags:=SND_RESOURCE;
else Flags:=SND_MEMORY;
end;
{$ELSE}
Flags := 0;
{$ENDIF}
if FLoop then
Flags:=Flags or SND_LOOP;
if FAsync then
Flags:=Flags or SND_ASYNC
else
Flags:=Flags or SND_SYNC;
{$IFDEF SR_Delphi2_Up}
if FWaveLocation = wlRAM then
Result:=PlaySound(FWavePointer, 0, Flags)
else
Result:=PlaySound(PChar(FWaveName), HInstance, Flags);
{$ELSE}
PWaveName:=StrAlloc(255);
StrPCopy(PWaveName, FWaveName);
Result:=sndPlaySound(PWaveName, Flags);
StrDispose(PWaveName);
{$ENDIF}
if Assigned(FAfterPlay) then
FAfterPlay(Self);
end;
procedure TSRWavePlayer.Stop;
{$IFDEF SR_Delphi2_Up}
var Flags : DWORD;
{$ELSE}
var Flags : WORD;
{$ENDIF}
begin
{$IFDEF SR_Delphi2_Up}
case FWaveLocation of
wlFile : Flags:=SND_FILENAME;
wlResource : Flags:=SND_RESOURCE;
else Flags:=SND_MEMORY;
end;
PlaySound(nil, 0, Flags);
{$ELSE}
sndPlaySound(nil, 0);
{$ENDIF}
end;
procedure Register;
begin
RegisterComponents('Simon', [TSRWavePlayer]);
end;
end.
|
unit NovusWindows;
interface
uses Windows, sysutils, Classes, NovusUtilities, Registry, Messages;
Type
TNovusWindows = class(TNovusUtilities)
protected
public
class function IsWin64: Boolean;
class function CommonFilesDir: string;
class function WindowsSystemDir: String;
class function WindowsDir: string;
class function WindowsTempPath: String;
class function WindowsExceptMess: String;
class function GetLocalComputerName: String;
class function SetEnvironmentVariableEx(const aVariableName: String; const aValue: string; aIsSystemVariable: Boolean): Integer;
class function SetSysEnvironmentVariable(const aVariableName: String; aValue: string): boolean;
end;
function CreateEnvironmentBlock(var lpEnvironment: Pointer; hToken: THandle; bInherit: BOOL): BOOL; stdcall; external 'userenv';
function DestroyEnvironmentBlock(pEnvironment: Pointer): BOOL; stdcall; external 'userenv';
implementation
class function TNovusWindows.WindowsDir: string;
begin
SetLength( result, 255 );
Windows.GetWindowsDirectory( pChar(result), 255 );
SetLength(result, StrLen(pChar(result)));
end;
class function TNovusWindows.WindowsSystemDir: String;
begin
SetLength( result, 255 );
Windows.GetSystemDirectory( pChar(result), 255 );
SetLength( result, StrLen(pChar(result)) );
end;
class function TNovusWindows.CommonFilesDir: string;
begin
with TRegistry.Create do try
RootKey:= HKey_Local_Machine;
if OpenKey( 'Software\Microsoft\Windows\CurrentVersion', True ) then begin
if ValueExists( 'CommonFilesDir' ) then begin
result:= ReadString( 'CommonFilesDir' );
end else begin
result:= Copy(WindowsDir{},1,2) + '\Program Files\Common Files';
WriteString( 'CommonFilesDir', result );
end;
end;
finally Free end;
end;
class function TNovusWindows.WindowsTempPath: String;
begin
SetLength(Result,Max_path);
SetLength(result,GetTempPath(Max_Path,Pchar(Result)));
end;
class function TNovusWindows.WindowsExceptMess;
Var
ValSize: Integer;
P: Pointer;
S: String;
begin
Result := '';
If ExceptObject = NIL then Exit;
ValSize := 255;
P := AllocMem(ValSize);
ExceptionErrorMessage(ExceptObject, ExceptAddr, P, ValSize);
{$IFDEF VER180}
S := StrPas(P);
{$ELSE}
S := StrPas(PWideChar(P));
{$ENDIF}
FreeMem(P);
S := Copy(S, (Pos('.', S) + 1), Length(S) - Pos('.', S));
Result := Copy(S, (Pos('.', S) + 1), Length(S) - Pos('.', S));
end;
class function TNovusWindows.GetLocalComputerName;
var
P: Pointer;
Size : DWORD;
begin
Result := '';
Size := MAX_COMPUTERNAME_LENGTH + 1;
P := AllocMem(Size);
if GetComputerName(P, Size) then
{$IFDEF VER180}
Result := StrPas(P);
{$ELSE}
Result := StrPas(PWideChar(P));
{$ENDIF}
FreeMem(P);
end;
class function TNovusWindows.SetSysEnvironmentVariable(const aVariableName: String; aValue: string): Boolean;
var
fok: Boolean;
reg: TRegistry;
resourcestring
key = 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment';
begin
Try
Result := False;
reg := TRegistry.Create;
reg.Access := KEY_ALL_ACCESS or KEY_WOW64_64KEY;
reg.RootKey := HKEY_LOCAL_MACHINE;
fok := reg.KeyExists(key);
if fok then
begin
if reg.OpenKey(key, true) then
begin
Result := True;
reg.WriteString(aVariableName, aValue);
//SetEnvironmentVariable(PChar(aVariableName), PChar(aValue));
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, Integer(PChar('Environment')));
end;
end;
Finally
reg.free;
End;
(*
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
fok := OpenKey('SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', true);
if fok then
begin
WriteString(aVariableName, aValue);
SetEnvironmentVariable(PChar(aVariableName), PChar(aValue));
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, Integer(PChar('Environment')));
end
else
Result := GetLastError;
finally
Free;
end;
*)
end;
class function TNovusWindows.SetEnvironmentVariableEx(const aVariableName: String; const aValue: string; aIsSystemVariable: Boolean): Integer;
begin
if aIsSystemVariable = false then
begin
if Windows.SetEnvironmentVariable(PChar(aVariableName),
PChar(aValue)) then
Result := 0
else
begin
Result := GetLastError;
if Result = 0 then Result := -1;
end;
end
else
begin
Result := 0;
if Not SetSysEnvironmentVariable(aVariableName, aValue) then
begin
Result := GetLastError;
if Result = 0 then Result := -1;
end;
end;
end;
class function TNovusWindows.IsWin64: Boolean;
var
IsWow64Process : function(hProcess : THandle; var Wow64Process : BOOL): BOOL; stdcall;
Wow64Process : BOOL;
begin
Result := False;
IsWow64Process := GetProcAddress(GetModuleHandle(Kernel32), 'IsWow64Process');
if Assigned(IsWow64Process) then begin
if IsWow64Process(GetCurrentProcess, Wow64Process) then begin
Result := Wow64Process;
end;
end;
end;
end.
|
program testrelop06(output);
{relational operators with character types}
var c,d:char;
begin
c := 'A';
d := 'C';
if c < d then
writeln('A is less than C');
if c = d then
writeln('oops')
else
writeln('A is not equal to C');
d := pred(pred(pred(d)));
writeln ('d now equals ',d);
if d < c then
writeln(d, ' is now less than ', c);
end.
|
unit Atm.Tests.Mocks.Communicator;
interface
uses
Atm.Services.Communicator;
type
IAtmCommunicatorMock = interface (IAtmCommunicator)
['{C0E34E85-44A3-4B56-961A-E09231512E7B}']
function GetWarningSent: Boolean;
function GetWarningText: string;
property WarningSent: Boolean read GetWarningSent;
property WarningText: string read GetWarningText;
end;
TAtmCommunicatorMock = class(TInterfacedObject, IAtmCommunicator,
IAtmCommunicatorMock)
private
FWarningSent: Boolean;
FWarningText: string;
public
procedure SendMessage(const AText: string);
function GetWarningSent: Boolean;
function GetWarningText: string;
end;
function CreateCommunicatorMock: IAtmCommunicatorMock;
implementation
function TAtmCommunicatorMock.GetWarningSent: Boolean;
begin
Result := FWarningSent;
end;
function TAtmCommunicatorMock.GetWarningText: string;
begin
Result := FWarningText;
end;
procedure TAtmCommunicatorMock.SendMessage(const AText: string);
begin
FWarningSent := True;
FWarningText := AText;
end;
function CreateCommunicatorMock: IAtmCommunicatorMock;
begin
Result := TAtmCommunicatorMock.Create;
end;
end.
|
unit AsyncIO.Test.Copy;
interface
procedure RunCopyTest;
implementation
uses
System.SysUtils, System.DateUtils, AsyncIO, AsyncIO.ErrorCodes, System.Math,
AsyncIO.Filesystem;
type
FileCopier = class
private
FBuffer: TBytes;
FInputStream: AsyncFileStream;
FOutputStream: AsyncFileStream;
FTotalBytesRead: UInt64;
FTotalBytesWritten: UInt64;
FReadTimestamp: TDateTime;
FWriteTimestamp: TDateTime;
FReadTimeMSec: Int64;
FWriteTimeMSec: Int64;
FPrintTimestamp: TDateTime;
FDoneReading: boolean;
procedure ReadHandler(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64);
procedure WriteHandler(const ErrorCode: IOErrorCode; const BytesTransferred: UInt64);
procedure PrintProgress;
public
constructor Create(const Service: IOService; const InputFilename, OutputFilename: string);
end;
procedure RunCopyTest;
var
inputFilename, outputFilename: string;
ios: IOService;
copier: FileCopier;
r: Int64;
begin
ios := nil;
copier := nil;
try
ios := NewIOService();
inputFilename := ParamStr(1);
outputFilename := ParamStr(2);
if (inputFilename = '') or (outputFilename = '') then
raise Exception.Create('Missing command line parameters');
copier := FileCopier.Create(ios, inputFilename, outputFilename);
r := ios.Poll;
WriteLn;
WriteLn(Format('%d handlers executed', [r]));
finally
copier.Free;
end;
end;
{ FileCopier }
constructor FileCopier.Create(const Service: IOService; const InputFilename,
OutputFilename: string);
begin
inherited Create;
SetLength(FBuffer, 1024*1024);
FInputStream := NewAsyncFileStream(Service, InputFilename, fcOpenExisting, faRead, fsRead);
FOutputStream := NewAsyncFileStream(Service, OutputFilename, fcCreateAlways, faWrite, fsNone);
FDoneReading := False;
Service.Post(
procedure
begin
// queue read to start things
FReadTimestamp := Now;
AsyncRead(FInputStream, FBuffer, TransferAll(), ReadHandler);
end
);
end;
procedure FileCopier.PrintProgress;
begin
if (MilliSecondsBetween(Now, FPrintTimestamp) < 500) then
exit;
Write(Format(#13'Read: %3d MB (%.2f MB/s) | Written: %3d MB (%.2f MB/s) ',
[FTotalBytesRead shr 20, FTotalBytesRead / (1e3 * Max(1, FReadTimeMSec)),
FTotalBytesWritten shr 20, FTotalBytesWritten / (1e3 * Max(1, FWriteTimeMSec))]));
FPrintTimestamp := Now;
end;
procedure FileCopier.ReadHandler(const ErrorCode: IOErrorCode;
const BytesTransferred: UInt64);
begin
if (ErrorCode) and (ErrorCode <> IOErrorCode.EndOfFile) then
begin
RaiseLastOSError(ErrorCode.Value, 'While reading file');
end;
if (ErrorCode = IOErrorCode.EndOfFile) then
FDoneReading := True;
FTotalBytesRead := FTotalBytesRead + BytesTransferred;
FReadTimeMSec := FReadTimeMSec + MilliSecondsBetween(Now, FReadTimestamp);
PrintProgress;
if (BytesTransferred = 0) then
exit;
// reading done, queue write
FWriteTimestamp := Now;
AsyncWrite(FOutputStream, FBuffer, TransferExactly(BytesTransferred), WriteHandler);
end;
procedure FileCopier.WriteHandler(const ErrorCode: IOErrorCode;
const BytesTransferred: UInt64);
begin
if (ErrorCode) then
begin
RaiseLastOSError(ErrorCode.Value, 'While writing file');
end;
if (FDoneReading) then
FPrintTimestamp := 0;
FTotalBytesWritten := FTotalBytesWritten + BytesTransferred;
FWriteTimeMSec := FWriteTimeMSec + MilliSecondsBetween(Now, FWriteTimestamp);
PrintProgress;
if (FDoneReading) then
exit;
// writing done and we got more to read, so queue read
FReadTimestamp := Now;
AsyncRead(FInputStream, FBuffer, TransferAll(), ReadHandler);
end;
end.
|
unit UNiceDelphi;
interface
uses
System.SysUtils;
function int(num: string): integer; overload;
function int(num: char): integer; overload;
function str(str: integer): string;
function len(str: string): integer;
implementation
function int(num: string): integer;
begin
result := strtoint(num);
end;
function int(num: char): integer; overload;
begin
result := strtoint(num + ' ');
end;
function str(str: integer): string;
begin
result := inttostr(str);
end;
function len(str: string): integer;
begin
result := length(str);
end;
end.
|
unit HotelsEditForm;
interface
uses
Forms, cxLookAndFeelPainters, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxEdit, DB, cxDBData, Classes, ActnList, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxMemo, cxDBEdit, cxTextEdit,
cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, Controls, StdCtrls,
CheckLst, cxContainer, cxMaskEdit, cxDropDownEdit, cxButtons, ExtCtrls,
Messages, TB2Item, TB2Dock, TB2Toolbar, cxDBLookupComboBox, cxCheckBox,
Dialogs, ExtDlgs;
type
TServicesItem = class(TCollectionItem)
private
FGroupID: Integer;
FServiceID: Integer;
public
property ServiceID: Integer read FServiceID write FServiceID;
property GroupID: Integer read FGroupID write FGroupID;
end;
TServices = class(TCollection)
private
function GetItem(Index: Integer): TServicesItem;
procedure SetItem(Index: Integer; const Value: TServicesItem);
public
constructor Create;
function Add: TServicesItem;
function Locate(ID, GroupID: Integer): Boolean;
property Items[Index: Integer]: TServicesItem read GetItem write SetItem; default;
end;
THotelsForm = class(TForm)
Panel2: TPanel;
Cancel: TcxButton;
Panel1: TPanel;
btnOK: TcxButton;
Groups: TcxComboBox;
Panel3: TPanel;
ServicesList: TCheckListBox;
Label1: TLabel;
Panel4: TPanel;
Label2: TLabel;
name: TcxDBTextEdit;
description: TcxDBMemo;
Label5: TLabel;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
ActionList: TActionList;
ActionOK: TAction;
TBToolbar1: TTBToolbar;
Ins: TAction;
Edit: TAction;
Del: TAction;
DescEdit: TAction;
TBItem1: TTBItem;
TBSeparatorItem1: TTBSeparatorItem;
TBItem2: TTBItem;
TBItem3: TTBItem;
TBItem4: TTBItem;
Types: TcxComboBox;
Label7: TLabel;
TBToolbar2: TTBToolbar;
TypeEdit: TAction;
TBItem5: TTBItem;
ImageUp: TAction;
ImageDown: TAction;
TBSeparatorItem2: TTBSeparatorItem;
TBItem6: TTBItem;
TBItem7: TTBItem;
place_id: TcxDBLookupComboBox;
starts: TcxDBComboBox;
super: TcxDBCheckBox;
Label6: TLabel;
Label3: TLabel;
country_id: TcxDBLookupComboBox;
cxGrid1DBTableView1id: TcxGridDBColumn;
cxGrid1DBTableView1hotel_id: TcxGridDBColumn;
cxGrid1DBTableView1image: TcxGridDBColumn;
cxGrid1DBTableView1description: TcxGridDBColumn;
cxGrid1DBTableView1sort_order: TcxGridDBColumn;
cxGrid1DBTableView1name: TcxGridDBColumn;
procedure ActionOKExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure GroupsPropertiesChange(Sender: TObject);
procedure TypesPropertiesChange(Sender: TObject);
procedure TypeEditExecute(Sender: TObject);
procedure InsExecute(Sender: TObject);
procedure EditExecute(Sender: TObject);
procedure DelExecute(Sender: TObject);
procedure DescEditExecute(Sender: TObject);
private
FServices: TServices;
FGroupID: Integer;
procedure CMDialogKey(var Msg: TWMKey); message CM_DIALOGKEY;
procedure FillServicesList(TypeID: Integer = 0);
procedure FillServicesCollection;
procedure SetCheckedServices(GroupID: Integer);
procedure FillGroups;
procedure FillTypes;
procedure SaveServices;
public
procedure Save;
end;
function GetHotelsForm(): Integer;
implementation
uses Windows, HotelsDataModule, HotelsMainForm,
HotelsTypesForm, Variants, SysUtils, HotelsImageForm, DBClient,
HTMLEditorIntf;
{$R *.dfm}
function GetHotelsForm;
var
Form: THotelsForm;
begin
Form := THotelsForm.Create(Application);
try
Result := Form.ShowModal;
if Result = mrOK then
begin
Form.Save;
end;
finally
Form.Free;
end;
end;
{ THotelsForm }
procedure THotelsForm.CMDialogKey(var Msg: TWMKey);
begin
if not (ActiveControl is TButton) then
if Msg.Charcode = VK_RETURN then
Msg.Charcode := VK_TAB;
inherited;
end;
procedure THotelsForm.ActionOKExecute(Sender: TObject);
begin
btnOK.SetFocus;
SaveServices();
ModalResult := mrOK;
end;
procedure THotelsForm.FillServicesList(TypeID: Integer = 0);
begin
with DM.Services do
begin
DisableControls;
ServicesList.Clear;
ServicesList.Items.BeginUpdate;
First;
while not EOF do
begin
if (TypeID = 0) or (TypeID = FieldValues['type_id']) then
ServicesList.Items.AddObject(FieldValues['name'],
TObject(FieldByName('id').AsInteger));
Next;
end;
ServicesList.Items.EndUpdate;
EnableControls;
end;
// расновление галочек
end;
procedure THotelsForm.FormCreate(Sender: TObject);
var
GroupID: Integer;
begin
FServices := TServices.Create;
FillServicesCollection; // заполнение коллекции данными
FillServicesList; // заполнение списка сервисов
FillGroups; // -//- для групп
FillTypes; // -//- для типов
///
GroupID := Integer(Groups.Properties.Items.Objects[Groups.ItemIndex]);
SetCheckedServices(GroupID); // растановка галок
end;
procedure THotelsForm.FillGroups;
begin
with DM.ServicesGroups, Groups.Properties do
begin
Items.Clear;
BeginUpdate;
First;
while not EOF do
begin
Items.AddObject(FieldValues['name'],
TObject(FieldByName('id').AsInteger));
Next;
end;
EndUpdate;
end;
Groups.ItemIndex := 0;
end;
procedure THotelsForm.FillTypes;
begin
with DM.ServicesTypes, Types.Properties do
begin
DisableControls;
Items.Clear;
BeginUpdate;
Items.Add('< Все типы >');
First;
while not EOF do
begin
Items.AddObject(FieldValues['name'],
TObject(FieldByName('id').AsInteger));
Next;
end;
EndUpdate;
EnableControls;
end;
Types.ItemIndex := 0;
end;
procedure THotelsForm.SaveServices;
var
i: Integer;
id: Integer;
Item: TServicesItem;
begin
id := Integer(Groups.Properties.Items.Objects[Groups.ItemIndex]);
if FGroupID > 0 then
begin
// чистим данные
i := 0;
while FServices.Count > i do
begin
if FServices[i].GroupID = FGroupID then
FServices.Delete(i)
else
Inc(i);
end;
// добаялем
for i := 0 to ServicesList.Count - 1 do
begin
if ServicesList.Checked[i] then
begin
Item := FServices.Add;
Item.GroupID := FGroupID;
Item.ServiceID := Integer(ServicesList.Items.Objects[i]);
end;
end;
end;
FGroupID := ID;
end;
procedure THotelsForm.FillServicesCollection;
var
Item: TServicesItem;
begin
with DM.HotelsServices do
begin
DisableControls;
FServices.Clear;
First;
while not EOF do
begin
if FieldValues['hotel_id'] = DM.Hotels['id'] then
begin
Item := FServices.Add;
Item.ServiceID := FieldValues['service_id'];
Item.GroupID := FieldValues['group_id'];
end;
Next;
end;
EnableControls;
end;
end;
procedure THotelsForm.SetCheckedServices(GroupID: Integer);
var
i: Integer;
LID: Integer;
begin
for i := 0 to ServicesList.Count - 1 do
begin
LID := Integer(ServicesList.Items.Objects[i]);
ServicesList.Checked[i] := FServices.Locate(LID, GroupID);
end;
end;
procedure THotelsForm.Save;
var
i: Integer;
HotelID: Integer;
begin
with DM.HotelsServices do
begin
DisableControls;
HotelID := DM.Hotels['id'];
// удаление удаленных записей
First;
while not EOF do
begin
if not FServices.Locate(FieldValues['service_id'], FieldValues['group_id']) then
Delete
else
Next;
end;
// добавление записей
for i := 0 to FServices.Count - 1 do
begin
if not Locate('hotel_id;service_id;group_id',
VarArrayOf([HotelID, FServices[i].ServiceID, FServices[i].GroupID]),
[loPartialKey]) then
begin
Append;
FieldValues['hotel_id'] := HotelID;
FieldValues['service_id'] := FServices[i].ServiceID;
FieldValues['group_id'] := FServices[i].GroupID;
Post;
end;
end;
EnableControls;
end;
end;
{ TServices }
function TServices.Add: TServicesItem;
begin
Result := TServicesItem(inherited Add);
end;
constructor TServices.Create;
begin
inherited Create(TServicesItem);
end;
function TServices.GetItem(Index: Integer): TServicesItem;
begin
Result := TServicesItem(inherited GetItem(Index));
end;
function TServices.Locate(ID, GroupID: Integer): Boolean;
var
i: Integer;
begin
Result := False;
for i := 0 to Count - 1 do
if (Items[i].ServiceID = ID) and (Items[i].GroupID = GroupID) then
begin
Result := True;
Exit;
end;
end;
procedure TServices.SetItem(Index: Integer; const Value: TServicesItem);
begin
inherited SetItem(Index, Value);
end;
procedure THotelsForm.FormDestroy(Sender: TObject);
begin
FServices.Free;
end;
procedure THotelsForm.GroupsPropertiesChange(Sender: TObject);
begin
SaveServices();
SetCheckedServices(FGroupID);
end;
procedure THotelsForm.TypesPropertiesChange(Sender: TObject);
var
TypeID: Integer;
begin
TypeID := Integer(Types.Properties.Items.Objects[Types.ItemIndex]);
FillServicesList(TypeID);
SetCheckedServices(FGroupID); // растановка галок
end;
procedure THotelsForm.TypeEditExecute(Sender: TObject);
begin
GetTypesForm;
TypesPropertiesChange(nil);
end;
procedure THotelsForm.InsExecute(Sender: TObject);
var
SortOrder: Integer;
ImageName: String;
begin
with DM.HotelsImages do
begin
SortOrder := DM.GetNextHotelsImagesSort;
Append;
FieldValues['sort_order'] := SortOrder;
FieldValues['name'] := Format('Фото № %d', [(SortOrder div 10)]);
if GetImageForm(ImageName) = mrOK then
begin
if Length(ImageName) > 0 then
FieldValues['image'] := ExtractFileName(ImageName);
Post;
if Length(ImageName) > 0 then
DM.AddImage2(ImageName, Name, 'id', FieldValues['id']);
end
else
Cancel;
end;
end;
procedure THotelsForm.EditExecute(Sender: TObject);
var
ImageNameOld, ImageNameNew: String;
begin
with DM.HotelsImages do
begin
ImageNameOld := DM.GetImagesPathL + FieldByName('image').AsString;
ImageNameNew := ImageNameOld;
Edit;
if GetImageForm(ImageNameNew) = mrOK then
begin
if AnsiCompareText(ImageNameNew, ImageNameOld) <> 0 then
begin
Dm.RemoveImage(ImageNameOld, Name, 'id', FieldValues['id']);
FieldValues['image'] := ExtractFileName(ImageNameNew);
DM.AddImage(ImageNameNew, Name, 'id', FieldValues['id']);
end;
Post;
end
else
Cancel;
end;
end;
procedure THotelsForm.DelExecute(Sender: TObject);
begin
if MessageBox(Handle,
'Вы тоействительно хотите удалить картинку ?',
PChar(Caption),
MB_OKCANCEL + MB_ICONQUESTION + MB_DEFBUTTON2) = IDOK
then
DM.HotelsImages.Delete;
end;
procedure THotelsForm.DescEditExecute(Sender: TObject);
var
Editor: IHTMLEditor;
FilesList: TStringList;
s: String;
begin
if DM.PluginManager.GetPlugin(IHTMLEditor, Editor) then
begin
FilesList := TStringList.Create;
try
s := description.DataBinding.Field.AsString;
Editor.FilesList := FilesList;
Editor.LocalPath := DM.GetImagesPathL;
Editor.RemotePath := DM.GetImagesPathR;
if Editor.Execute(s) then
begin
description.DataBinding.Field.Value := s;
end;
finally
FilesList.Free;
end;
end;
end;
end.
|
unit aOPCStateLine;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics,
Controls, Forms, StdCtrls, //Gauges,
aCustomOPCSource, aOPCSource, aOPCDataObject,
uOPCInterval,
uDCObjects;
type
TXY = record
X: TDateTime;
Y: string;
S: integer;
end;
PXY = ^TXY;
TaCustomOPCStateLine = class(TaCustomOPCDataObject)
private
FXYValues: TList;
FBorderStyle: TBorderStyle;
FStateColors: TStrings;
FErrorColor: TColor;
FDataLoaded: boolean;
FInterval: TOPCInterval;
function Get(Index: Integer): TXY;
procedure Put(Index: Integer; const Value: TXY);
procedure SetInterval(const Value: TOPCInterval);
procedure SetBorderStyle(Value: TBorderStyle);
procedure SetStateColors(const Value: TStrings);
procedure SetErrorColor(const Value: TColor);
procedure PaintBackground(AnImage: TBitmap);
procedure PaintStateLine(AnImage: TBitmap; PaintRect: TRect);
function GetCount: Integer;
protected
procedure SetPhysID(const Value: TPhysID);override;
procedure SetOPCSource(const Value: TaCustomOPCSource);override;
procedure Paint; override;
procedure ChangeData(Sender:TObject);override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy;override;
procedure AddXY(X: TDateTime; Y: string; S: integer);
procedure Delete(i: Integer);
procedure ClearNotUsedRecs;
procedure Clear;
function CorrectStringToColor(aStr: string): TColor;
function GetStateColor(aState: string): TColor;
procedure LoadData;
property Items[Index: Integer]: TXY read Get write Put;
property Count: Integer read GetCount;
published
property Align;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property Color;
property Constraints;
property ParentShowHint;
property StateColors: TStrings read FStateColors write SetStateColors;
property ErrorColor: TColor read FErrorColor write SetErrorColor default clGray;
property Interval: TOPCInterval read FInterval write SetInterval;
end;
TaOPCStateLine = class(TaCustomOPCStateLine)
end;
implementation
uses
StrUtils, math,
Consts;
type
TBltBitmap = class(TBitmap)
procedure MakeLike(ATemplate: TBitmap);
end;
{ TBltBitmap }
procedure TBltBitmap.MakeLike(ATemplate: TBitmap);
begin
Width := ATemplate.Width;
Height := ATemplate.Height;
Canvas.Brush.Color := clWindowFrame;
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(Rect(0, 0, Width, Height));
end;
{ TaCustomOPCStateLine }
procedure TaCustomOPCStateLine.AddXY(X: TDateTime; Y: string; S: integer);
var
XY: PXY;
begin
// если последние две записи содержат такое же значние, то обновляем последнюю запись новым временем
if (Count > 1) then
begin
if (Items[Count - 1].Y = Y) and (Items[Count - 2].Y = Y)
and (Items[Count - 1].S = S) and (Items[Count - 2].S = S) then
begin
PXY(FXYValues[Count-1])^.X := X;
Exit;
end;
end;
// добавляем новую запись
New(XY);
XY^.X := X;
XY^.Y := Y;
XY^.S := S;
FXYValues.Add(XY);
// удаляем записи, которые не входят в период
ClearNotUsedRecs;
end;
procedure TaCustomOPCStateLine.ChangeData(Sender: TObject);
begin
// Progress := Round(StrToFloatDef(Value,Progress,OpcFS));
if not FDataLoaded then
LoadData;
AddXY(DataLink.Moment, DataLink.Value, DataLink.ErrorCode);
UpdateDataLinks;
if Assigned(OnChange) and (not (csLoading in ComponentState))
and (not (csDestroying in ComponentState)) then
OnChange(Self);
RepaintRequest(self);
//inherited;
end;
procedure TaCustomOPCStateLine.Clear;
var
i: Integer;
begin
for i := 0 to FXYValues.Count - 1 do
Dispose(PXY(FXYValues[i]));
FXYValues.Clear;
FDataLoaded := false;
end;
procedure TaCustomOPCStateLine.ClearNotUsedRecs;
var
p, p1, p2: Integer;
i: Integer;
begin
// ищем левую границу
p1 := -1;
for i := 0 to Count - 1 do
if Items[i].X > Interval.Date1 then
begin
p1 := i;
Break;
end;
if p1 < 0 then
Exit;
// p - позиция элемента, левее которого все удаляем
p := p1 - 1;
// удаляем левые элементы (кроме одного)
while p > 0 do
begin
Delete(0);
Dec(p);
end;
// ищем правую границу
p2 := -1;
for i := Count - 1 downto 0 do
if Items[i].X < Interval.Date2 then
begin
p2 := i;
Break;
end;
// p - позиция элемента, правее которого все удаляем
p := p2 + 1;
while p < Count - 1 do
Delete(Count-1);
end;
function TaCustomOPCStateLine.CorrectStringToColor(aStr: string): TColor;
var
aColor: Integer;
begin
// пытаемся получить число из строки: $FFAAB0, 255, 65535 и пр.
if TryStrToInt(aStr, aColor) then
Result := TColor(aColor)
else
// иначе ищем в таблице соответствий: название - цвет: clYellow, clGreen ...
Result := StringToColor(aStr);
end;
constructor TaCustomOPCStateLine.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FInterval := TOPCInterval.Create;
FDataLoaded := false;
FXYValues := TList.Create;
FStateColors := TStringList.Create;
ControlStyle := ControlStyle + [csFramed, csOpaque];
BorderStyle := bsSingle;
{ default values }
Width := 100;
Height := 16;
StairsOptions := [];
DataLink.UpdateOnChangeMoment := true;
ErrorColor := clGray;
FStateColors.Add('0=clWhite');
FStateColors.Add('1=clGreen');
end;
procedure TaCustomOPCStateLine.Delete(i: Integer);
begin
Dispose(PXY(FXYValues[i]));
FXYValues.Delete(i);
end;
destructor TaCustomOPCStateLine.Destroy;
begin
Clear;
FStateColors.Free;
FXYValues.Free;
FInterval.Free;
inherited;
end;
function TaCustomOPCStateLine.Get(Index: Integer): TXY;
begin
Result := PXY(FXYValues[Index])^;
end;
function TaCustomOPCStateLine.GetCount: Integer;
begin
Result := FXYValues.Count;
end;
function TaCustomOPCStateLine.GetStateColor(aState: string): TColor;
var
aLeftIndex: Integer;
colorIndex: Integer;
// aColor: Integer;
begin
Result := ErrorColor;
try
// точное соответствие ?
colorIndex := StateColors.IndexOfName(aState);
if colorIndex >= 0 then
Result := CorrectStringToColor(StateColors.ValueFromIndex[colorIndex])
else
// не нашли, тогда в зависимости от StairsOptions ищем левое, правое и т.д.
begin
aLeftIndex := -1;
for colorIndex := 0 to StateColors.Count - 1 do
begin
aLeftIndex := colorIndex;
if StrToFloat(StateColors.Names[colorIndex]) > StrToFloat(aState) then
Break;
end;
// пока берем левое
{ TODO : сделать расчет промежуточного цвета }
if aLeftIndex >= 0 then
Result := CorrectStringToColor(StateColors.ValueFromIndex[aLeftIndex]);
end;
except
Result := ErrorColor;
end;
end;
procedure TaCustomOPCStateLine.LoadData;
var
aOPCSource: TaOPCSource;
Stream:TMemoryStream;
aDate1, aDate2: TDateTime;
aMoment: TDatetime;
aValue1, aValue2: extended;
aStateValue: extended;
saveScreenCursor: TCursor;
begin
if Assigned(OPCSource) and (OPCSource is TaOPCSource) then
begin
aOPCSource := TaOPCSource(OPCSource);
aOPCSource.Connected := True;
if aOPCSource.Connected and (PhysID <> '') then
begin
saveScreenCursor := Screen.Cursor;
Stream := TMemoryStream.Create;
try
aDate2 := Interval.Date2;
aDate1 := Interval.Date1;
aOPCSource.FillHistory(Stream, PhysID, aDate1, aDate2, [dkValue,dkState]);
if Stream.Size > 0 then
begin
Clear;
Stream.Read(aMoment, SizeOf(aMoment)); // момент времени
Stream.Read(aValue2, SizeOf(aValue2)); // значение
Stream.Read(aStateValue, SizeOf(aStateValue));// состояние
AddXY(aMoment, FloatToStr(aValue2), trunc(aStateValue));
if Stream.Position = Stream.Size then
begin
// если у нас всего одно значение, добавим еще парочку точек
AddXY(aDate1, FloatToStr(aValue2), trunc(aStateValue));
AddXY(IfThen(aDate2=0, Now, aDate2), FloatToStr(aValue2), trunc(aStateValue));
end
else
begin
while Stream.Position < Stream.Size do
begin
//aValue1 := aValue2;
Stream.Read(aMoment, SizeOf(aMoment)); // момент времени
Stream.Read(aValue2, SizeOf(aValue2)); // значение
Stream.Read(aStateValue, SizeOf(aStateValue));// состояние
AddXY(aMoment, FloatToStr(aValue2), trunc(aStateValue));
end;
end;
end;
FDataLoaded := true;
Repaint;
finally
Stream.Free;
Screen.Cursor := saveScreenCursor;
end;
end;
end;
end;
procedure TaCustomOPCStateLine.Paint;
var
TheImage: TBitmap;
OverlayImage: TBltBitmap;
PaintRect: TRect;
begin
with Canvas do
begin
TheImage := TBitmap.Create;
try
TheImage.Height := Height;
TheImage.Width := Width;
PaintBackground(TheImage);
PaintRect := ClientRect;
if FBorderStyle = bsSingle then
InflateRect(PaintRect, -1, -1);
OverlayImage := TBltBitmap.Create;
try
OverlayImage.MakeLike(TheImage);
PaintBackground(OverlayImage);
PaintStateLine(OverlayImage,PaintRect);
TheImage.Canvas.CopyMode := cmSrcInvert;
TheImage.Canvas.Draw(0, 0, OverlayImage);
TheImage.Canvas.CopyMode := cmSrcCopy;
finally
OverlayImage.Free;
end;
Canvas.CopyMode := cmSrcCopy;
Canvas.Draw(0, 0, TheImage);
finally
TheImage.Destroy;
end;
end;
end;
procedure TaCustomOPCStateLine.PaintBackground(AnImage: TBitmap);
var
ARect: TRect;
begin
with AnImage.Canvas do
begin
CopyMode := cmBlackness;
ARect := Rect(0, 0, Width, Height);
CopyRect(ARect, Animage.Canvas, ARect);
CopyMode := cmSrcCopy;
end;
end;
procedure TaCustomOPCStateLine.PaintStateLine(AnImage: TBitmap;
PaintRect: TRect);
var
xy1,xy2: TXY;
x1,x2: integer;
XCoef: extended;
XShift: TDateTime;
aColor: TColor;
i: integer;
// colorIndex: integer;
begin
with AnImage.Canvas do
begin
Brush.Color := clWhite;
FillRect(PaintRect);
if (FXYValues.Count = 0) then
exit;
if SameValue(Interval.Date1, 0, 1) or SameValue(Interval.Date2, 0, 1) then
Exit;
XCoef := (PaintRect.Right-PaintRect.Left)/(Interval.Date2 - Interval.Date1);
XShift := Interval.Date1;
xy1 := PXY(FXYValues[0])^;
x1 := Round((xy1.X - XShift)*XCoef);
for i := 1 to FXYValues.Count - 1 do
begin
xy2 := PXY(FXYValues[i])^;
//Assert(xy1.X < xy2.X,'xy1.X < xy2.X');
x2 := Trunc((xy2.X - XShift)*XCoef)+1;
if xy1.S <> 0 then
aColor := ErrorColor
else
begin
aColor := GetStateColor(xy1.Y);
// try
// colorIndex := StateColors.IndexOfName(xy1.Y);
// if colorIndex >= 0 then
// aColor := StringToColor(StateColors.ValueFromIndex[colorIndex])
// else
// begin
// aColor := ErrorColor;
// for colorIndex := 0 to StateColors.Count - 1 do
// begin
// if StrToFloat(StateColors.Names[colorIndex]) > StrToFloat(xy1.Y) then
// Break;
//
// aColor := StringToColor(StateColors.ValueFromIndex[colorIndex]);
// end;
// end;
// except
// aColor := ErrorColor;
// end;
end;
Brush.Color := aColor;
if x1 < 0 then
x1 := 0;
if x2 > (PaintRect.Right - PaintRect.Left) then
x2 := PaintRect.Right - PaintRect.Left;
if (x2 < x1) then
begin
if (x2 > 0) then
x1 := x2
else
x2 := x1;
end;
FillRect(Rect(PaintRect.Left+x1,PaintRect.Top,PaintRect.Left+x2,PaintRect.Bottom));
xy1 := xy2;
x1 := x2;
end;
end;
end;
procedure TaCustomOPCStateLine.Put(Index: Integer; const Value: TXY);
begin
PXY(FXYValues[Index])^.X := Value.X;
PXY(FXYValues[Index])^.Y := Value.Y;
PXY(FXYValues[Index])^.S := Value.S;
end;
procedure TaCustomOPCStateLine.SetBorderStyle(Value: TBorderStyle);
begin
if Value <> FBorderStyle then
begin
FBorderStyle := Value;
Refresh;
end;
end;
procedure TaCustomOPCStateLine.SetErrorColor(const Value: TColor);
begin
FErrorColor := Value;
end;
procedure TaCustomOPCStateLine.SetInterval(const Value: TOPCInterval);
begin
FInterval.Assign(Value);
end;
//procedure TaCustomOPCStateLine.SetInterval(const Value: double);
//begin
// if FInterval <> Value then
// begin
// FInterval := Value;
// FDataLoaded := false;
// end;
//end;
procedure TaCustomOPCStateLine.SetOPCSource(const Value: TaCustomOPCSource);
begin
if Value <> OPCSource then
begin
Clear;
inherited;
end;
end;
procedure TaCustomOPCStateLine.SetPhysID(const Value: TPhysID);
begin
if Value <> PhysID then
begin
Clear;
inherited;
end;
end;
procedure TaCustomOPCStateLine.SetStateColors(const Value: TStrings);
begin
FStateColors.Assign(Value);
FStateColors.Text := ReplaceStr(FStateColors.Text,' ','');
end;
end.
|
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved.
//
// 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 Casbin.Adapter.Types;
interface
uses
Casbin.Core.Base.Types, Casbin.Core.Logger.Types, System.Generics.Collections;
type
IAdapter = interface (IBaseInterface)
['{474D7E69-1015-4DB8-92CF-AA19A448A4B6}']
function getAssertions: TList<string>;
function getLogger: ILogger;
procedure setLogger(const aValue: ILogger);
procedure load (const aFilter: TFilterArray = []);
procedure save;
procedure setAssertions(const aValue: TList<string>);
function toOutputString: string;
procedure clear;
function getFilter: TFilterArray;
function getFiltered: boolean;
property Assertions: TList<string> read getAssertions write setAssertions; //PALOFF
property Filter: TFilterArray read getFilter;
property Filtered: boolean read getFiltered;
property Logger: ILogger read getLogger write setLogger;
end;
implementation
end.
|
unit UfrmBrowseBook;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
USourceInfo, Vcl.AppEvnts;
type
TfrmBrowseBook = class(TForm)
tvBooks: TTreeView;
Panel1: TPanel;
btnOK: TButton;
btnCancel: TButton;
Splitter1: TSplitter;
mmoVerse: TMemo;
ApplicationEvents1: TApplicationEvents;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
procedure tvBooksClick(Sender: TObject);
private
FSelectionValid: boolean;
FSelection: TSourceInfo;
FBook: string;
function GetSelection: TSourceInfo;
function GetSelectionMulti: TSourceInfos;
procedure SetSelection(const Value: TSourceInfo);
procedure SetSelectionMulti(const Value: TSourceInfos);
function GetDoMultiSelection: boolean;
procedure SetDoMultiSelection(const Value: boolean);
{ Private declarations }
public
property DoMultiSelection: boolean read GetDoMultiSelection write SetDoMultiSelection;
property Selection: TSourceInfo read GetSelection write SetSelection;
property SelectionMulti: TSourceInfos read GetSelectionMulti write SetSelectionMulti;
property SelectionValid: boolean read FSelectionValid;
procedure ClearSelection;
procedure ClearTree;
procedure ValidateSelection;
procedure OpenBook(strBook: string);
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
GNUGetText, USourceBook;
{ TfrmBrowseBook }
procedure TfrmBrowseBook.ApplicationEvents1Idle(Sender: TObject;
var Done: Boolean);
begin
btnOK.Enabled := SelectionValid;
end;
procedure TfrmBrowseBook.ClearSelection;
begin
mmoVerse.Lines.Clear;
FreeAndNil(FSelection);
FSelection := TSourceInfo.CreateAsBook('' ,'', '');
FSelectionValid := false;
end;
procedure TfrmBrowseBook.ClearTree;
begin
tvBooks.Items.Clear;
end;
procedure TfrmBrowseBook.FormCreate(Sender: TObject);
begin
TranslateComponent(self);
FSelection := nil;
ClearSelection;
end;
procedure TfrmBrowseBook.FormDestroy(Sender: TObject);
begin
FSelection.Free;
end;
function TfrmBrowseBook.GetDoMultiSelection: boolean;
begin
Result := tvBooks.MultiSelect;
end;
function TfrmBrowseBook.GetSelection: TSourceInfo;
begin
Result := FSelection.DeepCopy;
end;
function TfrmBrowseBook.GetSelectionMulti: TSourceInfos;
var
node, nodeChild: TTreeNode;
iShape: integer;
source: TSourceInfo;
begin
Result := TSourceInfos.Create;
node := tvBooks.Items.GetFirstNode;
while Assigned(node) do begin
if node.Selected then begin
if (node.Level = 1) then begin
source := TSourceInfo.Create;
Result.Add(source);
source.SourceType := sitBook;
source.FileName := FBook;
source.SlideName := node.Parent.Text;
source.ShapeName := node.Text;
end else if (node.Level = 0) then begin
nodeChild := node.getFirstChild;
while Assigned(nodeChild) do begin
source := TSourceInfo.Create;
Result.Add(source);
source.SourceType := sitBook;
source.FileName := FBook;
source.SlideName := nodeChild.Parent.Text;
source.ShapeName := nodeChild.Text;
nodeChild := nodeChild.getNextSibling;
end;
end;
end;
node := node.GetNext;
end;
end;
procedure TfrmBrowseBook.OpenBook(strBook: string);
var
cachedPPT: TCachedBook;
i,j: integer;
slideNode: TTreeNode;
tree: TStringTree;
begin
ClearSelection;
ClearTree;
Caption := _('Browse') + ' ' + strBook;
cachedPPT := GetCachedBooks.Get(strBook);
if Assigned(cachedPPT) then begin
FBook := strBook;
FSelection.FileName := strBook;
tree := cachedPPT.ChaptersAndVerses;
for i := 0 to tree.Count -1 do begin
slideNode := tvBooks.Items.AddChild(nil, tree.Item[i].Data);
for j := 0 to tree.Item[i].Count -1 do begin
tvBooks.Items.AddChild(slideNode, tree.Item[i].Item[j].Data );
end;
end;
end;
end;
procedure TfrmBrowseBook.SetDoMultiSelection(const Value: boolean);
begin
tvBooks.MultiSelect := Value;
end;
procedure TfrmBrowseBook.SetSelection(const Value: TSourceInfo);
var
node: TTreeNode;
begin
if Value.FileName = '' then Exit;
OpenBook(Value.FileName);
if tvBooks.Items.Count = 0 then Exit;
if Value.SlideName <> '' then begin
node := tvBooks.Items.GetFirstNode;
while Assigned(node) do begin
if (node.Level = 0) and (node.Text = Value.SlideName) then begin
node.MakeVisible;
tvBooks.Selected := node;
if Value.ShapeName <> '' then begin
node := node.getFirstChild;
while Assigned(node) do begin
if (node.Level = 1) and (node.Text = Value.ShapeName) then begin
node.MakeVisible;
tvBooks.Selected := node;
node := nil;
end else begin
node := node.getNextSibling;
end;
end;
end;
node := nil;
end else begin
node := node.getNextSibling;
end;
end;
end;
ValidateSelection;
end;
procedure TfrmBrowseBook.SetSelectionMulti(const Value: TSourceInfos);
begin
if Value.Count > 0 then begin
if Value[0].FileName <> FSelection.FileName then begin
OpenBook(Value[0].FileName);
end;
end;
end;
procedure TfrmBrowseBook.tvBooksClick(Sender: TObject);
begin
ValidateSelection;
end;
procedure TfrmBrowseBook.ValidateSelection;
var
iShape: integer;
source: TSourceInfo;
nodeChild: TTreeNode;
begin
FSelectionValid := false;
if Assigned(tvBooks.Selected) then begin
if (tvBooks.Selected.Level = 0) then begin
FSelection.FileName := FBook;
FSelection.ShapeName := tvBooks.Selected.Text;
FSelectionValid := true;
source := TSourceInfo.Create;
try
source.SourceType := sitBook;
source.FileName := FBook;
mmoVerse.Lines.Text := '';
nodeChild := tvBooks.Selected.getFirstChild;
while Assigned(nodeChild) do begin
source.SlideName := nodeChild.Parent.Text;
source.ShapeName := nodeChild.Text;
mmoVerse.Lines.Text := mmoVerse.Lines.Text + #13 + GetCachedBooks.GetVerse(source);
nodeChild := nodeChild.getNextSibling;
end;
finally
source.Free;
end;
end;
if (tvBooks.Selected.Level = 1) then begin
FSelection.FileName := FBook;
FSelection.SlideName := tvBooks.Selected.Parent.Text;
FSelection.ShapeName := tvBooks.Selected.Text;
FSelectionValid := true;
mmoVerse.Lines.Text := GetCachedBooks.GetVerse(FSelection);
end;
end;
if not FSelectionValid then
ClearSelection;
end;
end.
|
{
Clean triangle Edge Links in navmeshes after Finalize,
before Apply Filter to Clean.
(apply to plugin, not master)
}
unit NavMeshCleanEdgeLinks;
var
arEdge: array [0..2] of string;
//===========================================================================
function Initialize: integer;
begin
if wbSimpleRecords then begin
MessageDlg('Simple records must be unchecked in xEdit options', mtInformation, [mbOk], 0);
Result := 1;
Exit;
end;
arEdge[0] := 'Edge 0-1';
arEdge[1] := 'Edge 1-2';
arEdge[2] := 'Edge 2-0';
end;
//===========================================================================
// search EdgeLinks table for equivalent Mesh and Triangle
function FindEdgeLink(EdgeLinks: IInterface; elM: string; elT: integer): integer;
var
EdgeLink: IInterface;
k: integer;
begin
for k := Pred(ElementCount(EdgeLinks)) downto 0 do begin
EdgeLink := ElementByIndex(EdgeLinks, k);
if elT = GetElementNativeValues(EdgeLink, 'Triangle') then begin
//AddMessage(Format('%d = %d', [elT, GetElementNativeValues(EdgeLink, 'Triangle')]));
//AddMessage(elM);
//AddMessage(GetElementEditValues(EdgeLink, 'Mesh'));
if CompareStr(elM, GetElementEditValues(EdgeLink, 'Mesh')) = 0 then begin
//AddMessage(Format('found %d', [k]));
Result := k;
Exit;
end;
end;
end;
Result := -1;
end;
//===========================================================================
// search Triangle for EdgeLink
function FindEdgeLinkIndex(Triangle: IInterface; elN: integer): integer;
var
flags, j: integer;
begin
flags := GetElementNativeValues(Triangle, 'Flags');
for j := 0 to 2 do begin
// triangle has EdgeLinks?
if flags and (1 shl j) > 0 then begin
if elN = GetElementNativeValues(Triangle, arEdge[j]) then begin
Result := j;
Exit;
end;
end;
end;
Result := -1;
end;
//===========================================================================
// search Triangles table for EdgeLink
function FindTriangleByEdgeLinkIndex(Triangles: IInterface; elN: integer): integer;
var
i: integer;
begin
// iterate through triangles in reverse
for i := Pred(ElementCount(Triangles)) downto 0 do begin
if FindEdgeLinkIndex(ElementByIndex(Triangles, i), elN) >= 0 then begin
Result := i;
Exit;
end;
end;
Result := -1;
end;
//===========================================================================
// swap equivalent Mesh and Triangle
procedure SwapEdgeLink(swapLink, haveLink: IInterface);
var
swapPath, havePath: IInterface;
saveValue: integer;
saveString: String;
begin
havePath := ElementByPath(haveLink, 'Triangle');
saveValue := GetNativeValue(havePath);
swapPath := ElementByPath(swapLink, 'Triangle');
SetNativeValue(havePath, GetNativeValue(swapPath));
SetNativeValue(swapPath, saveValue);
havePath := ElementByPath(haveLink, 'Mesh');
saveString := GetEditValue(havePath);
swapPath := ElementByPath(swapLink, 'Mesh');
SetEditValue(havePath, GetEditValue(swapPath));
SetEditValue(swapPath, saveString);
havePath := ElementByPath(haveLink, 'Unknown');
saveString := GetEditValue(havePath);
swapPath := ElementByPath(swapLink, 'Unknown');
SetEditValue(havePath, GetEditValue(swapPath));
SetEditValue(swapPath, saveString);
end;
//===========================================================================
// find old edge link in triangles and swap with new
// Result: True on failure!
//
function SwapEdgeLinkValues(newTs, newLinks: IInterface; oldLinkIndex, newLimit, newLinkIndex, edgeIndex, newT: integer): integer;
var
haveT, haveLink: IInterface;
flags, j, i: integer;
begin
haveLink := ElementByIndex(newLinks, newLinkIndex);
// iterate through triangles in reverse
for i := newLimit downto 0 do begin
haveT := ElementByIndex(newTs, i);
flags := GetElementNativeValues(haveT, 'Flags');
for j := 0 to 2 do begin
// triangle has EdgeLinks?
if flags and (1 shl j) > 0 then begin
if oldLinkIndex = GetElementNativeValues(haveT, arEdge[j]) then begin
//AddMessage(Format('Swap %s %s value %d with %d', [Name(haveT), arEdge[j], oldLinkIndex, newLinkIndex]));
SetElementNativeValues(ElementByIndex(newTs, newT), arEdge[edgeIndex], oldLinkIndex);
SetElementNativeValues(haveT, arEdge[j], newLinkIndex);
SwapEdgeLink(ElementByIndex(newLinks, oldLinkIndex), haveLink);
Result := i;
Exit;
end;
end;
end;
end;
AddMessage(Format('ERROR: swap %s link %d not found!', [arEdge[edgeIndex], oldLinkIndex]));
Result := -1;
end;
//===========================================================================
function Process(e: IInterface): integer;
var
saveString: String;
ore, mos, haveLink: IInterface;
oldTs, oldT, oldLinks: IInterface;
newTs, newT, newLinks: IInterface;
oldLinkLimit, oldLinkIndex, oldLinkCount, oldLimit, oldFlags, oldFails: integer;
newLinkLimit, newLinkIndex, newLinkCount, newLimit, newFlags, newFails: integer;
saveValue, orc, j, i, hadTriangle, hadEdge, failures, b: integer;
begin
if Signature(e) <> 'NAVM' then begin
//AddMessage(Format('Not NAVM %s', [Name(e)]));
Exit;
end;
{
for i := 0 to Pred(OverrideCount(MasterOrSelf(e))) do
AddMessage(GetFileName(OverrideByIndex(MasterOrSelf(e), i)));
Exit;
}
mos := MasterOrSelf(e);
orc := OverrideCount(mos);
if orc < 1 then begin
//AddMessage(Format('Override Count %d for %s', [orc, Name(e)]));
Exit;
end
else if orc < 2 then
ore := mos
else
ore := OverrideByIndex(mos, Pred(Pred(orc)));
//AddMessage('Master/Override ' + GetFileName(ore) + ' for ' + Name(e));
if Signature(ore) <> 'NAVM' then begin
AddMessage(Format('Not NAVM: %s', [Name(ore)]));
Exit;
end;
oldTs := ElementByPath(ore, 'NVNM\Triangles');
oldLimit := Pred(ElementCount(oldTs));
oldLinks := ElementByPath(ore, 'NVNM\Edge Links');
oldLinkCount := ElementCount(oldLinks);
oldLinkLimit := Pred(oldLinkCount);
newTs := ElementByPath(e, 'NVNM\Triangles');
newLimit := Pred(ElementCount(newTs));
newLinks := ElementByPath(e, 'NVNM\Edge Links');
newLinkCount := ElementCount(newLinks);
newLinkLimit := Pred(newLinkCount);
// iterate through triangles
for i := 0 to newLimit do begin
failures := 0;
if i <= oldLimit then begin
oldT := ElementByIndex(oldTs, i);
oldFlags := GetElementNativeValues(oldT, 'Flags');
end;
newT := ElementByIndex(newTs, i);
newFlags := GetElementNativeValues(newT, 'Flags');
for j := 0 to 2 do begin
b := 1 shl j;
oldFails := 0;
if i > oldLimit then
oldLinkIndex := -1
else if oldFlags and b = 0 then
oldLinkIndex := -1
else begin
oldLinkIndex := GetElementNativeValues(oldT, arEdge[j]);
//AddMessage(Format('%s %s value %d:', [Name(oldT), arEdge[j], oldLinkIndex]));
if oldLinkIndex < 0 then begin
AddMessage(Format('ERROR: old %s link (%d < 0)!', [arEdge[j], oldLinkIndex]));
Inc(oldFails);
end
else if oldLinkIndex > oldLinkLimit then begin
AddMessage(Format('ERROR: old %s link (%d > %d)!', [arEdge[j], oldLinkIndex, oldLinkLimit]));
oldLinkIndex := -1;
Inc(oldFails);
end
else if oldLinkIndex > newLinkLimit then begin
// new table has fewer links (unusual condition)
AddMessage(Format('Had old %s link %d > new limit %d', [arEdge[j], oldLinkIndex, newLinkLimit]));
oldLinkIndex := -1;
Inc(oldFails);
end;
end;
failures := failures + oldFails;
newFails := 0;
if newFlags and b > 0 then begin
newLinkIndex := GetElementNativeValues(newT, arEdge[j]);
//AddMessage(Format('%s %s value %d:', [Name(newT), arEdge[j], newLinkIndex]));
if newLinkIndex < 0 then begin
AddMessage(Format('ERROR: new %s link (%d < 0)!', [arEdge[j], newLinkIndex]));
Inc(newFails);
end
else if newLinkIndex > newLinkLimit then begin
AddMessage(Format('ERROR: new %s link (%d > %d)!', [arEdge[j], newLinkIndex, newLinkLimit]));
Inc(newFails);
end
else if oldLinkIndex = newLinkIndex then
// nothing to do! (very common)
else if oldLinkIndex >= 0 then begin
// try to swap! (less common)
if SwapEdgeLinkValues(newTs, newLinks, oldLinkIndex, newLimit, newLinkIndex, j, i) < 0 then
Inc(newFails);
end
else begin
// search old Edge Links for possible match...
haveLink := ElementByIndex(newLinks, newLinkIndex);
saveString := GetElementEditValues(haveLink, 'Mesh');
saveValue := GetElementNativeValues(haveLink, 'Triangle');
oldLinkIndex := FindEdgeLink(oldLinks, saveString, saveValue);
if oldLinkIndex < 0 then begin
// new link added (debugging, nothing to be done)
//AddMessage(Format('No match for triangle %d in %s', [saveValue, saveString]));
//Inc(newFails);
end
else if oldLinkIndex > newLinkLimit then begin
// new table has fewer links (unusual condition)
hadTriangle := FindTriangleByEdgeLinkIndex(oldTs, oldLinkIndex);
if (hadTriangle <> i) and (hadTriangle >= 0) and (hadTriangle <= newLimit) then begin
AddMessage(Format('%s needs repair?', [Name(newT)]));
hadEdge := FindEdgeLinkIndex(ElementByIndex(oldTs, hadTriangle), oldLinkIndex);
AddMessage(Format('Triangle #%d %s was found!', [hadTriangle, arEdge[hadEdge]]));
end;
AddMessage(Format('Was old matching link %d > new limit %d', [oldLinkIndex, newLinkLimit]));
AddMessage(Format('Have match (%d) for triangle %d in %s', [oldLinkIndex, saveValue, saveString]));
Inc(newFails);
end
else if (newFlags and (7 - b)) > 0 then begin
// multiple edges (requires repair)
AddMessage(Format('%s needs repaired edges!', [Name(newT)]));
AddMessage(Format('Have match (%d) for triangle %d in %s', [oldLinkIndex, saveValue, saveString]));
// cannot swap, unknown edge to use!
Inc(newFails);
end
else begin
// singular changes (can swap awaiting repair)
hadTriangle := FindTriangleByEdgeLinkIndex(oldTs, oldLinkIndex);
if (hadTriangle <> i) and (hadTriangle >= 0) and (hadTriangle <= newLimit) then begin
AddMessage(Format('%s needs repair?', [Name(newT)]));
hadEdge := FindEdgeLinkIndex(ElementByIndex(oldTs, hadTriangle), oldLinkIndex);
AddMessage(Format('Triangle #%d %s was found!', [hadTriangle, arEdge[hadEdge]]));
end;
AddMessage(Format('Have match (%d) for triangle %d in %s', [oldLinkIndex, saveValue, saveString]));
if oldLinkIndex <> newLinkIndex then
SwapEdgeLinkValues(newTs, newLinks, oldLinkIndex, newLimit, newLinkIndex, j, i);
Inc(newFails);
end;
end;
if newFails > 0 then begin
AddMessage(Format('via new %s link %d', [arEdge[j], newLinkIndex]));
failures := failures + newFails;
end;
end
else if oldLinkIndex >= 0 then begin
haveLink := ElementByIndex(oldLinks, oldLinkIndex);
saveString := GetElementEditValues(haveLink, 'Mesh');
saveValue := GetElementNativeValues(haveLink, 'Triangle');
AddMessage(Format('Want match for triangle %d in %s', [saveValue, saveString]));
AddMessage(Format('via old %s link %d', [arEdge[j], oldLinkIndex]));
Inc(failures);
end;
end;
if failures > 0 then begin
AddMessage(Format('^^^ Check triangle %d in %s', [i, Name(e)]));
AddMessage('');
//Exit;
end;
end;
end;
end. |
unit Operations;
interface
uses
Classes, Types, Operation, DataType;
type
IOperations = Interface(IInterface)
['{4BAAA81A-08BB-47C3-8BC4-FC6EE57F2B58}']
function GetOperation(AOperation: string; ALeftType, ARightType: TDataType): TOperation;
end;
implementation
end.
|
unit U_ConfigSISVISA;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
U_CADASTROPADRAO, FMX.TabControl, System.Actions, FMX.ActnList, FMX.Edit,
FMX.SearchBox, FMX.ListBox, FMX.Layouts, FMX.Controls.Presentation,
FMX.EditBox, FMX.NumberBox, FMX.ComboEdit, FMX.Objects;
type
TfrmConfiguracoesSISVISA = class(TfrmCadastroPadrao)
changeTabConfigBanco: TChangeTabAction;
tabArtigos1059: TTabItem;
changeTabArtigos: TChangeTabAction;
tabCadCaminhoBanco: TTabItem;
tabCadArtigos: TTabItem;
changeTabCadBanco: TChangeTabAction;
changeTabCadArtigo: TChangeTabAction;
layoutArtigos: TLayout;
layoutCadCaminhoBanco: TLayout;
tabConfigBanco: TTabItem;
layoutConfigBanco: TLayout;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
ListBoxItem5: TListBoxItem;
lbxConfigBanco: TListBox;
SearchBox2: TSearchBox;
Layout9: TLayout;
lbxArtigos: TListBox;
SearchBox3: TSearchBox;
Panel3: TPanel;
btnInserirArtigo: TButton;
btnAlterarArtigo: TButton;
btnExcluirArtigo: TButton;
btnImprimirArtigo: TButton;
btnSalvarArtigo: TButton;
btnVoltarMenuConfig: TButton;
Button16: TButton;
Edit2: TEdit;
ListBoxItem7: TListBoxItem;
ListBoxItem6: TListBoxItem;
ListBoxItem8: TListBoxItem;
actInserirArtigo: TAction;
Panel1: TPanel;
btnInserirBanco: TButton;
btnAlterarBanco: TButton;
btnExcluirBanco: TButton;
btnImprimirBanco: TButton;
btnSalvarBanco: TButton;
btnVoltarMenu: TButton;
btnConectarBanco: TButton;
edtCaminhoConexao: TEdit;
Panel4: TPanel;
btnInsereBD: TButton;
btnAlteraBD: TButton;
btnExcluiBD: TButton;
btnImprimeBD: TButton;
btnSalvaBD: TButton;
btnVolta: TButton;
btnConectaBD: TButton;
Edit1: TEdit;
actInserirBD: TAction;
actSalvaBD: TAction;
layoutConteiner: TLayout;
procedure ListBoxItem1Click(Sender: TObject);
procedure actAlterarExecute(Sender: TObject);
procedure ListBoxItem2Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure lbxConfigBancoItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
procedure actInserirArtigoExecute(Sender: TObject);
procedure actInserirBDExecute(Sender: TObject);
procedure actSalvaBDExecute(Sender: TObject);
private
{ Private declarations }
procedure fnc_ExecutarCadBanco;
public
{ Public declarations }
end;
var
frmConfiguracoesSISVISA: TfrmConfiguracoesSISVISA;
implementation
{$R *.fmx}
uses U_SISVISA, U_CadastroArtigos;
procedure TfrmConfiguracoesSISVISA.actAlterarExecute(Sender: TObject);
begin
inherited;
changeTabCadBanco.ExecuteTarget(Self);
btnVoltar.Enabled := False;
lblTitulo.Text := lblTitulo.Text + CADALTERA;
end;
procedure TfrmConfiguracoesSISVISA.actInserirArtigoExecute(Sender: TObject);
begin
changeTabCadArtigo.ExecuteTarget(Self);
lblTitulo.Text := lblTitulo.Text + CADNOVO;
end;
procedure TfrmConfiguracoesSISVISA.actInserirBDExecute(Sender: TObject);
begin
changeTabCadBanco.ExecuteTarget(Self);
end;
procedure TfrmConfiguracoesSISVISA.actSalvaBDExecute(Sender: TObject);
begin
changeTabConfigBanco.ExecuteTarget(Self);
end;
procedure TfrmConfiguracoesSISVISA.Button1Click(Sender: TObject);
begin
inherited;
changeTabDados.ExecuteTarget(Self);
end;
procedure TfrmConfiguracoesSISVISA.Button2Click(Sender: TObject);
begin
inherited;
changeTabDados.ExecuteTarget(Self);
end;
procedure TfrmConfiguracoesSISVISA.Button3Click(Sender: TObject);
begin
inherited;
changeTabDados.ExecuteTarget(Self);
end;
procedure TfrmConfiguracoesSISVISA.Button4Click(Sender: TObject);
begin
inherited;
changeTabDados.ExecuteTarget(Self);
end;
procedure TfrmConfiguracoesSISVISA.fnc_ExecutarCadBanco;
begin
changeTabCadBanco.ExecuteTarget(Self);
Panel3.Visible := True;
btnVoltar.Enabled := False;
end;
procedure TfrmConfiguracoesSISVISA.lbxConfigBancoItemClick
(const Sender: TCustomListBox; const Item: TListBoxItem);
begin
edtCaminhoConexao.Text := '';
edtCaminhoConexao.Text := lbxConfigBanco.Items[lbxConfigBanco.ItemIndex];
end;
procedure TfrmConfiguracoesSISVISA.ListBoxItem1Click(Sender: TObject);
begin
changeTabConfigBanco.ExecuteTarget(Self);
end;
procedure TfrmConfiguracoesSISVISA.ListBoxItem2Click(Sender: TObject);
var
FormArtigo: TfrmCadastroArtigos;
begin
if not Assigned(FormArtigo) then
FormArtigo := TfrmCadastroArtigos.Create(Self);
layoutConteiner.RemoveObject(0);
layoutConteiner.AddObject(FormArtigo.Layout1);
end;
end.
|
unit SLBtns;
interface
uses
Windows, Messages, Classes, SysUtils, Graphics, Controls, Buttons, ExtCtrls, Menus;
type
TSkinDrawEvent = function(Sender: TObject; Rect: TRect): Boolean of object;
TSLButton = class(TGraphicControl)
private
FDragging: Boolean;
FRepeatTimer: TTimer;
FDragPos: TPoint;
FFocusColor: TColor;
FHighlightColor: TColor;
FShadowColor: TColor;
FDarkColor: TColor;
FFocusEnter: Boolean;
FActive: Boolean;
FSelected: Boolean;
FMouseEntered: Boolean;
FSelTransparent: Boolean;
FTransparent: Boolean;
FRepeating: Boolean;
FRepeatDelay: Integer;
FRepeatInterval: Integer;
FDragSrouce: Boolean;
FOnMouseEnter: TNotifyEvent;
FOnMouseLeave: TNotifyEvent;
FOnStartDrag: TNotifyEvent;
FOnSkinDrawFace: TSkinDrawEvent;
FOnSkinDrawFrame: TSkinDrawEvent;
FOnSkinDrawIcon: TSkinDrawEvent;
FOnSkinDrawCaption: TSkinDrawEvent;
FOnSkinDrawMask: TSkinDrawEvent;
procedure SetRepeatTimer(Value: Boolean);
procedure RepeatTimerTimer(Sender: TObject);
procedure MouseTimerTimer(Sender: TObject);
procedure SetActive(Value: Boolean);
procedure SetSelected(Value: Boolean);
procedure SetMouseEntered(Value: Boolean);
procedure FocusCheck;
procedure SetFocusColor(Value: TColor);
procedure SetSelTransparent(Value: Boolean);
procedure SetTransparent(Value: Boolean);
protected
FState: TButtonState;
procedure Paint; override;
procedure CMTextChanged(var Msg: TMessage); message CM_TEXTCHANGED;
procedure CMWinIniChange(var Msg: TMessage); message CM_WININICHANGE;
procedure CMColorChanged(var Msg: TMessage); message CM_COLORCHANGED;
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 DrawFrame(Canvas: TCanvas; ARect: TRect; Down: Boolean);
// property Canvas: TCanvas read FCanvas write FCanvas;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Click; override;
property Active: Boolean read FActive write SetActive;
property Selected: Boolean read FSelected write SetSelected;
property MouseEntered: Boolean read FMouseEntered write SetMouseEntered;
property HighlightColor: TColor read FHighlightColor;
property ShadowColor: TColor read FShadowColor;
property DarkColor: TColor read FDarkColor;
published
property Enabled;
property Color;
property FocusColor: TColor read FFocusColor write SetFocusColor;
property SelTransparent: Boolean read FSelTransparent write SetSelTransparent;
property Transparent: Boolean read FTransparent write SetTransparent;
property Repeating: Boolean read FRepeating write FRepeating default False;
property RepeatDelay: Integer read FRepeatDelay write FRepeatDelay default 400;
property RepeatInterval: Integer read FRepeatInterval write FRepeatInterval default 100;
property DragSource: Boolean read FDragSrouce write FDragSrouce;
property OnClick;
property OnMouseDown;
property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
property OnStartDrag: TNotifyEvent read FOnStartDrag write FOnStartDrag;
property OnSkinDrawFace: TSkinDrawEvent read FOnSkinDrawFace write FOnSkinDrawFace;
property OnSkinDrawFrame: TSkinDrawEvent read FOnSkinDrawFrame write FOnSkinDrawFrame;
property OnSkinDrawIcon: TSkinDrawEvent read FOnSkinDrawIcon write FOnSkinDrawIcon;
property OnSkinDrawCaption: TSkinDrawEvent read FOnSkinDrawCaption write FOnSkinDrawCaption;
property OnSkinDrawMask: TSkinDrawEvent read FOnSkinDrawMask write FOnSkinDrawMask;
end;
TSLScrollButtonKind = (skGUp, skUp, skDown, skGDown);
TSLScrollButton = class(TSLButton)
private
FKind: TSLScrollButtonKind;
FVertical: Boolean;
protected
procedure Paint; override;
procedure SetKind(Value: TSLScrollButtonKind);
procedure SetVertical(Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Kind: TSLScrollButtonKind read FKind write SetKind;
property Vertical: Boolean read FVertical write SetVertical;
end;
TSLBtnCaptionPosition = (cpNone, cpBottom, cpRight);
TSLNormalButton = class(TSLButton)
private
FOwnerDraw: Boolean;
FIconHandle: HIcon;
FNarrowText:Boolean;
FSpacing: Integer;
FCaptionPosition: TSLBtnCaptionPosition;
FSmallIcon: Boolean;
procedure SetIconHandle(Value: HIcon);
function GetIconSize: Integer;
function GetSpacing: Integer;
procedure SetSpacing(Value: Integer);
procedure SetCaptionPosition(Value: TSLBtnCaptionPosition);
procedure SetSmallIcon(Value: Boolean);
protected
procedure Paint; override;
public
property Canvas;
property IconHandle: HIcon read FIconHandle write SetIconHandle;
property IconSize: Integer read GetIconSize;
property NarrowText: Boolean read FNarrowText;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Caption;
property OwnerDraw: Boolean read FOwnerDraw write FOwnerDraw;
property Spacing: Integer read GetSpacing write SetSpacing;
property CaptionPosition: TSLBtnCaptionPosition read FCaptionPosition write SetCaptionPosition;
property SmallIcon: Boolean read FSmallIcon write SetSmallIcon;
end;
TDrawButtonEvent = procedure (Sender: TObject; Rect: TRect; State: TButtonState) of object;
TSLPluginButton = class(TSLNormalButton)
private
FOnDrawButton: TDrawButtonEvent;
FOnCreate: TNotifyEvent;
FOnDestroy: TNotifyEvent;
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property OnDrawButton: TDrawButtonEvent read FOnDrawButton write FOnDrawButton;
property OnCreate: TNotifyEvent read FOnCreate write FOnCreate;
property OnDestroy: TNotifyEvent read FOnDestroy write FOnDestroy;
end;
const
BUTTON_MARGIN = 4;
const
COLOR_GRADIENTACTIVECAPTION = 27;
COLOR_GRADIENTINACTIVECAPTION = 28;
clGradientActiveCaption = $80000000 + COLOR_GRADIENTACTIVECAPTION;
clGradientInactiveCaption = $80000000 + COLOR_GRADIENTINACTIVECAPTION;
type
TDirection = (drLeftRight, drRightLeft, drBottomUp, drTopDown);
function DrawNarrowText(Canvas: TCanvas; ARect: TRect; const Text: string): Boolean;
procedure RotateTextOut(Canvas: TCanvas; ARect: TRect; Direction: TDirection; const Text: String);
procedure GradationRect(Canvas: TCanvas; ARect: TRect; Direction: TDirection; ColorA, ColorB: TColor);
procedure ColorBetween(Canvas: TCanvas; ARect: TRect; Color: TColor);
function GetFontColorFromFaceColor(FaceColor: TColor): TColor;
function GetShadowColor(FaceColor: TColor): TColor;
implementation
var
MouseLastPos: TPoint;
MouseInButton: TSLButton = nil;
MouseTimer: TTimer = nil;
// 狭いテキストを描画
function DrawNarrowText(Canvas: TCanvas; ARect: TRect; const Text: string): Boolean;
var
ComS, S: string;
LastChar: string;
MaxWidth: Integer;
begin
Result := False;
ComS := Text;
S := Text;
MaxWidth := ARect.Right - ARect.Left;
while Canvas.TextWidth(ComS) > MaxWidth do
begin
Result := True;
LastChar := StrPas(AnsiLastChar(S));
if LastChar = S then
Break;
S := Copy(S, 1, Length(S) - Length(LastChar));
ComS := S + '...';
end;
Canvas.TextOut(ARect.Left, ARect.Top, ComS);
end;
// 狭いテキストを指定の方向に描画
procedure RotateTextOut(Canvas: TCanvas; ARect: TRect; Direction: TDirection; const Text: String);
var
ComS, S: string;
LastChar: string;
MaxWidth: Integer;
LogFont: TLogFont;
NewFont, OldFont: HFont;
X, Y: Integer;
begin
GetObject(Canvas.Font.Handle, SizeOf(LogFont), @LogFont);
case Direction of
drLeftRight:
begin
LogFont.lfEscapement := 0;
MaxWidth := ARect.Right - ARect.Left;
X := ARect.Left;
Y := ARect.Top;
end;
drRightLeft:
begin
LogFont.lfEscapement := 1800;
MaxWidth := ARect.Right - ARect.Left;
X := ARect.Right - 1;
Y := ARect.Bottom - 1;
end;
drBottomUp:
begin
LogFont.lfEscapement := 900;
MaxWidth := ARect.Bottom - ARect.Top;
X := ARect.Left;
Y := ARect.Bottom - 1;
end;
else
begin
LogFont.lfEscapement := 2700;
MaxWidth := ARect.Bottom - ARect.Top;
X := ARect.Right;
Y := ARect.Top;
end;
end;
ComS := Text;
S := Text;
while Canvas.TextWidth(ComS) > MaxWidth do
begin
LastChar := StrPas(AnsiLastChar(S));
if LastChar = S then
Break;
S := Copy(S, 1, Length(S) - Length(LastChar));
ComS := S + '...';
end;
NewFont := CreateFontIndirect(LogFont);
try
OldFont := SelectObject(Canvas.Handle, NewFont);
TextOut(Canvas.Handle, x, y, PChar(ComS), Length(ComS));
NewFont := SelectObject(Canvas.Handle, OldFont);
finally
DeleteObject(NewFont);
end;
end;
// グラデーション描画
procedure GradationRect(Canvas: TCanvas; ARect: TRect; Direction: TDirection; ColorA, ColorB: TColor);
var
C1, C2: LongInt;
dr, dg, db: Double;
nr, ng, nb: Double;
dx, dy: Integer;
R: TRect;
DrawWidth: Integer;
i: Integer;
begin
C1 := ColorToRGB(ColorA);
C2 := ColorToRGB(ColorB);
R := ARect;
case Direction of
drLeftRight:
begin
dx := +1;
dy := 0;
R.Right := R.Left + 1;
DrawWidth := ARect.Right - ARect.Left;
end;
drRightLeft:
begin
dx := -1;
dy := 0;
R.Left := R.Right - 1;
DrawWidth := ARect.Right - ARect.Left;
end;
drTopDown:
begin
dx := 0;
dy := +1;
R.Bottom := R.Top + 1;
DrawWidth := ARect.Bottom - ARect.Top;
end;
drBottomUp:
begin
dx := 0;
dy := -1;
R.Top := R.Bottom - 1;
DrawWidth := ARect.Bottom - ARect.Top;
end;
else
dx := +1;
dy := 0;
R.Right := R.Left + 1;
DrawWidth := ARect.Right - ARect.Left;
end;
nr := GetRValue(C1);
ng := GetGValue(C1);
nb := GetBValue(C1);
dr := (GetRValue(C2) - nr) / DrawWidth;
dg := (GetGValue(C2) - ng) / DrawWidth;
db := (GetBValue(C2) - nb) / DrawWidth;
for i := 0 to DrawWidth - 1 do
begin
Canvas.Brush.Color := RGB(Trunc(nr), Trunc(ng), Trunc(nb));
Canvas.FillRect(R);
Inc(R.Left, dx);
Inc(R.Right, dx);
Inc(R.Top, dy);
Inc(R.Bottom, dy);
nr := nr + dr;
ng := ng + dg;
nb := nb + db;
end;
end;
// 中間色に変更
procedure ColorBetween(Canvas: TCanvas; ARect: TRect; Color: TColor);
var
x,y : integer;
Bitmap : TBitmap;
P : PByteArray;
C: LongInt;
R, G, B: Word;
begin
Bitmap := TBitmap.Create;
try
C := ColorToRGB(Color);
R := GetRValue(C);
G := GetGValue(C);
B := GetBValue(C);
Bitmap.Width := ARect.Right - ARect.Left;
Bitmap.Height := ARect.Bottom - ARect.Top;
Bitmap.Canvas.CopyMode := cmSrcCopy;
Bitmap.Canvas.CopyRect(Rect(0, 0, Bitmap.Width, Bitmap.Height), Canvas, ARect);
Bitmap.PixelFormat := pf24bit;
for y := 0 to Bitmap.Height -1 do
begin
P := Bitmap.ScanLine[y];
for x := 0 to Bitmap.Width * 3 -1 do
begin
case x mod 3 of
{ 0: P[x] := (P[x] + B) div 2;
1: P[x] := (P[x] + G) div 2;
2: P[x] := (P[x] + R) div 2;}
0: P[x] := (P[x] * 2 + B) div 3;
1: P[x] := (P[x] * 2 + G) div 3;
2: P[x] := (P[x] * 2 + R) div 3;
end;
end;
end;
Canvas.Draw(ARect.Left, ARect.Top ,Bitmap);
finally
Bitmap.Free;
end;
end;
function GetFontColorFromFaceColor(FaceColor: TColor): TColor;
var
C: LongInt;
R, G, B: Word;
// Y, MaxY: Integer;
Y: Double;
begin
case FaceColor of
clActiveCaption:
Result := clCaptionText;
clInactiveCaption:
Result := clInactiveCaptionText;
clMenu:
Result := clMenuText;
clWindow:
Result := clWindowText;
clBtnFace:
Result := clBtnText;
clHighlight:
Result := clHighlightText;
clInfoBk:
Result := clInfoText;
else
C := ColorToRGB(FaceColor);
R := GetRValue(C);
G := GetGValue(C);
B := GetBValue(C);
{ Y := R * 299 + G * 587 + B * 114;
MaxY := $FF * 299 + $FF * 587 + $FF * 114;
if Y <= (MaxY / 2) then
Result := clWhite
else
Result := clBlack;}
Y := (0.24 * R + 0.67 * G + 0.08 * B) / 255;
if Y >= 0.5 then
Result := clBlack
else
Result := clWhite;
end;
end;
function GetShadowColor(FaceColor: TColor): TColor;
var
C: LongInt;
R, G, B: Word;
begin
C := ColorToRGB(FaceColor);
R := GetRValue(C);
G := GetGValue(C);
B := GetBValue(C);
Result := RGB(R * 2 div 3, G * 2 div 3, B * 2 div 3);
end;
/////////////////////
// TSLButton
constructor TSLButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SetBounds(0, 0, 32, 32);
ControlStyle := [csCaptureMouse, csDoubleClicks];
Color := clBtnFace;
FocusColor := clBlue;
FRepeatDelay := 400;
FRepeatInterval := 100;
end;
destructor TSLButton.Destroy;
begin
if MouseEntered then // マウスが入ってるとタイマー等が動いたままになる
MouseEntered := False;
inherited Destroy;
end;
procedure TSLButton.CMTextChanged(var Msg: TMessage);
begin
Refresh;
end;
procedure TSLButton.Paint;
begin
end;
procedure TSLButton.CMWinIniChange(var Msg: TMessage);
var
LogFont: TLogFont;
begin
SystemParametersInfo(SPI_GETICONTITLELOGFONT, SizeOf(LogFont), @LogFont, 0);
Font.Handle := CreateFontIndirect(LogFont);
end;
procedure TSLButton.CMColorChanged(var Msg: TMessage);
var
C: LongInt;
R, G, B: Word;
begin
C := ColorToRGB(Color);
R := GetRValue(C);
G := GetGValue(C);
B := GetBValue(C);
if Color = clBtnFace then
begin
FHighlightColor := clBtnHighlight;
FShadowColor := clBtnShadow;
FDarkColor := clBlack;
end
else
begin
FHighlightColor := RGB((R + $FF) div 2, (G + $FF) div 2, (B + $FF) div 2);
FShadowColor := RGB(R div 2, G div 2, B div 2);
FDarkColor := RGB(R div 4, G div 4, B div 4);
end;
Refresh;
end;
procedure TSLButton.SetActive(Value: Boolean);
begin
if FActive = Value then
Exit;
FActive := Value;
FocusCheck;
end;
procedure TSLButton.SetSelected(Value: Boolean);
begin
if FSelected = Value then
Exit;
FSelected := Value;
FocusCheck;
end;
procedure TSLButton.SetMouseEntered(Value: Boolean);
var
P: TPoint;
begin
if FMouseEntered = Value then
Exit;
if Value then
begin
if (MouseInButton <> Self) and (MouseInButton <> nil) then
MouseInButton.MouseEntered := False;
// 本当にマウスポインタが入ってるか?
GetCursorPos(P);
P := ScreenToClient(P);
if PtInRect(ClientRect, P) then
begin
FMouseEntered := Value;
MouseInButton := Self;
if Assigned(FOnMouseEnter) then
FOnMouseEnter(Self);
if MouseTimer = nil then
MouseTimer := TTimer.Create(Self)
else
MouseTimer.Enabled := False;
MouseTimer.Interval := 125;
MouseTimer.OnTimer := MouseTimerTimer;
MouseTimer.Enabled := True;
end;
end
else
begin
if MouseTimer <> nil then
MouseTimer.Free;
MouseTimer := nil;
MouseInButton := nil;
FMouseEntered := Value;
if Assigned(FOnMouseLeave) then
begin
FOnMouseLeave(Self);
end;
end;
FocusCheck;
end;
procedure TSLButton.FocusCheck;
var
NewFocusEnter: Boolean;
begin
NewFocusEnter := (FSelected and FActive) or FMouseEntered;
if FFocusEnter <> NewFocusEnter then
begin
FFocusEnter := NewFocusEnter;
Refresh;
end;
end;
procedure TSLButton.SetFocusColor(Value: TColor);
begin
if FFocusColor = Value then
Exit;
FFocusColor := Value;
Refresh;
end;
procedure TSLButton.SetSelTransparent(Value: Boolean);
begin
if FSelTransparent = Value then
Exit;
FSelTransparent := Value;
Refresh;
end;
procedure TSLButton.SetTransparent(Value: Boolean);
begin
if FTransparent = Value then
Exit;
FTransparent := Value;
Refresh;
end;
procedure TSLButton.SetRepeatTimer(Value: Boolean);
begin
if Value = (FRepeatTimer <> nil) then
Exit;
FRepeatTimer.Free;
FRepeatTimer := nil;
if Value then
begin
FRepeatTimer := TTimer.Create(Self);
FRepeatTimer.Interval := FRepeatDelay;
FRepeatTimer.OnTimer := RepeatTimerTimer;
FRepeatTimer.Enabled := True;
end;
end;
procedure TSLButton.RepeatTimerTimer(Sender: TObject);
var
P: TPoint;
begin
FRepeatTimer.Interval := FRepeatInterval;
GetCursorPos(P);
P := ScreenToClient(P);
if Enabled and Repeating and FDragging and MouseCapture and PtInRect(ClientRect, P) then
Click;
end;
procedure TSLButton.MouseTimerTimer(Sender: TObject);
var
P: TPoint;
begin
GetCursorPos(P);
P := ScreenToClient(P);
MouseEntered := PtInRect(ClientRect, P);
end;
procedure TSLButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
MouseEntered := True;
if (Button = mbLeft) and Enabled then
begin
FDragging := True;
FDragPos.X := X;
FDragPos.Y := Y;
FState := bsDown;
Repaint;
if FRepeating then
begin
Click;
SetRepeatTimer(True);
end;
end
else
begin
FDragging := False;
if FState <> bsUp then
begin
FState := bsUp;
Refresh;
end;
end;
end;
procedure TSLButton.MouseMove(Shift: TShiftState; X, Y: Integer);
var
MousePos: TPoint;
NewState: TButtonState;
begin
inherited;
// マウスポインタが動いてなければMouseEnteredは変更しない
MousePos := ClientToScreen(Point(X, Y));
if (MouseLastPos.x <> MousePos.x) or (MouseLastPos.y <> MousePos.y) then
begin
MouseLastPos := MousePos;
MouseEntered := PtInRect(ClientRect, Point(X, Y));
end;
if FDragging and FDragSrouce and Assigned(FOnStartDrag) then
begin
if (Abs(FDragPos.X - X) > 10) or (Abs(FDragPos.Y - Y) > 10) then
begin
FDragging := False;
if FState <> bsUp then
begin
FState := bsUp;
Refresh;
end;
FOnStartDrag(Self);
Exit;
end;
end;
if FDragging then
begin
if FMouseEntered then
NewState := bsDown
else
NewState := bsUp;
SetRepeatTimer(FRepeating and (NewState = bsDown));
if NewState <> FState then
begin
FState := NewState;
Refresh;
end;
end;
end;
procedure TSLButton.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
SetRepeatTimer(False);
inherited;
if FDragging then
begin
FDragging := False;
if FState <> bsUp then
begin
FState := bsUp;
Refresh;
end;
if PtInRect(ClientRect, Point(X, Y)) and not FRepeating then
Click;
end;
end;
procedure TSLButton.Click;
begin
inherited Click;
end;
procedure TSLButton.DrawFrame(Canvas: TCanvas; ARect: TRect; Down: Boolean);
begin
with ARect do
begin
if Down then
begin
Canvas.Pen.Color := FHighlightColor;
Canvas.Polyline([Point(Right - 1, Top), Point(Right - 1, Bottom - 1), Point(Left, Bottom - 1)]);
Canvas.Pen.Color := FDarkColor;
Canvas.Polyline([Point(Left, Bottom - 1), Point(Left, Top), Point(Right - 1, Top)]);
Canvas.Pen.Color := FShadowColor;
Canvas.Polyline([Point(Left + 1, Bottom - 2), Point(Left + 1, Top + 1), Point(Right - 2, Top + 1)]);
end
else
begin
Canvas.Pen.Color := FHighlightColor;
Canvas.Polyline([Point(Left, Bottom - 1), Point(Left, Top), Point(Right - 1, Top)]);
Canvas.Pen.Color := FShadowColor;
Canvas.Polyline([Point(Right - 1, Top), Point(Right - 1, Bottom - 1), Point(Left, Bottom - 1)]);
end;
end;
end;
/////////////////////
// TSLScrollButton
constructor TSLScrollButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TSLScrollButton.Destroy;
begin
inherited Destroy;
end;
procedure TSLScrollButton.Paint;
var
i, x, y: Integer;
P, PD: array[0..2] of TPoint;
Bmp: TBitmap;
ACanvas: TCanvas;
BackColor: TColor;
begin
inherited;
if FTransparent then
begin
Bmp := nil;
ACanvas := Canvas;
end
else
begin
Bmp := TBitmap.Create;
Bmp.Width := ClientWidth;
Bmp.Height := ClientHeight;
ACanvas := Bmp.Canvas;
end;
try
// 選択状態を透明でなく表示
if Enabled and FFocusEnter and not FSelTransparent then
begin
BackColor := FFocusColor;
ACanvas.Brush.Color := FFocusColor;
ACanvas.FillRect(ClientRect);
end
else
begin
BackColor := Color;
ACanvas.Brush.Color := Color;
if not FTransparent then
ACanvas.FillRect(ClientRect);
end;
DrawFrame(ACanvas, ClientRect, FState = bsDown);
if (FState = bsDown)
and (Width >= 10) and (Height >= 10)
or ((Width >= 12) and (Height >= 12)) then
begin
x := Width div 2;
y := Height div 2;
if FVertical then
begin
if FKind in [skGUp, skUp] then
begin
P[0] := Point(x, y - 2);
P[1] := Point(x - 3, y + 1);
P[2] := Point(x + 3, y + 1);
end
else
begin
P[0] := Point(x, y + 2);
P[1] := Point(x - 3, y - 1);
P[2] := Point(x + 3, y - 1);
end;
end
else
begin
if FKind in [skGUp, skUp] then
begin
P[0] := Point(x - 2, y);
P[1] := Point(x + 1, y - 3);
P[2] := Point(x + 1, y + 3);
end
else
begin
P[0] := Point(x + 2, y);
P[1] := Point(x - 1, y - 3);
P[2] := Point(x - 1, y + 3);
end;
end;
if FState = bsDown then
for i := 0 to 2 do
begin
Inc(P[i].x);
Inc(P[i].y);
end;
if Enabled then
ACanvas.Pen.Color := GetFontColorFromFaceColor(BackColor)
else
begin
for i := 0 to 2 do
begin
PD[i].x := P[i].x + 1;
PD[i].y := P[i].y + 1;
end;
ACanvas.Pen.Color := HighlightColor;
ACanvas.Brush.Color := ACanvas.Pen.Color;
ACanvas.Polygon(PD);
ACanvas.Pen.Color := ShadowColor;
end;
ACanvas.Brush.Color := ACanvas.Pen.Color;
ACanvas.Polygon(P);
end;
if FSelTransparent then
begin
if Enabled and FFocusEnter then
ColorBetween(ACanvas, ClientRect, FFocusColor);
if FState = bsDown then
ColorBetween(ACanvas, ClientRect, clBlack);
end;
if not FTransparent then
begin
Canvas.Draw(0, 0, Bmp);
end;
finally
Bmp.Free;
end;
end;
procedure TSLScrollButton.SetKind(Value: TSLScrollButtonKind);
begin
if FKind = Value then
Exit;
FKind := Value;
Refresh;
end;
procedure TSLScrollButton.SetVertical(Value: Boolean);
begin
if FVertical = Value then
Exit;
FVertical := Value;
Refresh;
end;
/////////////////////
// TSLNormalButton
constructor TSLNormalButton.Create(AOwner: TComponent);
var
LogFont: TLogFont;
begin
inherited Create(AOwner);
SystemParametersInfo(SPI_GETICONTITLELOGFONT, SizeOf(LogFont), @LogFont, 0);
Font.Handle := CreateFontIndirect(LogFont);
FSpacing := 4;
FNarrowText := False;
end;
destructor TSLNormalButton.Destroy;
begin
IconHandle := 0;
inherited Destroy;
end;
procedure TSLNormalButton.SetIconHandle(Value: HIcon);
begin
if FIconHandle = Value then
Exit;
if FIconHandle <> 0 then
DestroyIcon(FIconHandle);
FIconHandle := Value;
Refresh;
end;
function TSLNormalButton.GetIconSize: Integer;
var
H: Integer;
begin
if FIconHandle = 0 then
Result := 0
else if FSmallIcon then
Result := 16
else
begin
Result := GetSystemMetrics(SM_CXICON);
H := GetSystemMetrics(SM_CYICON);
if Result > H then
Result := H;
end;
end;
function TSLNormalButton.GetSpacing: Integer;
begin
if FIconHandle <> 0 then
Result := FSpacing
else
Result := 0;
end;
procedure TSLNormalButton.SetSpacing(Value: Integer);
begin
if FSpacing = Value then
Exit;
FSpacing := Value;
Refresh;
end;
procedure TSLNormalButton.SetCaptionPosition(Value: TSLBtnCaptionPosition);
begin
if FCaptionPosition = Value then
Exit;
FCaptionPosition := Value;
Refresh;
end;
procedure TSLNormalButton.SetSmallIcon(Value: Boolean);
begin
if FSmallIcon = Value then
Exit;
FSmallIcon := Value;
Refresh;
end;
procedure TSLNormalButton.Paint;
var
BrushStyleBack: TBrushStyle;
IconX, IconY, IconS: Integer;
TextX, TextY, TextW, TextH: Integer;
Bmp: TBitmap;
ACanvas: TCanvas;
BackColor: TColor;
begin
inherited;
if FTransparent or Assigned(FOnSkinDrawFace) then
begin
Bmp := nil;
ACanvas := Canvas;
end
else
begin
Bmp := TBitmap.Create;
Bmp.Width := ClientWidth;
Bmp.Height := ClientHeight;
ACanvas := Bmp.Canvas;
end;
try
// スキンによる表面の描画
if Assigned(FOnSkinDrawFace) and FOnSkinDrawFace(Self, ClientRect) then
begin
// 選択状態を透明でなく表示
if Enabled and FFocusEnter and not FSelTransparent then
BackColor := FFocusColor
else
BackColor := Color;
end
else
begin
// 選択状態を透明でなく表示
if Enabled and FFocusEnter and not FSelTransparent then
begin
BackColor := FFocusColor;
ACanvas.Brush.Color := FFocusColor;
ACanvas.FillRect(ClientRect);
end
else
begin
BackColor := Color;
ACanvas.Brush.Color := Color;
if not FTransparent then
ACanvas.FillRect(ClientRect);
end;
end;
// DrawFrame(ACanvas, ClientRect, FState = bsDown);
ACanvas.Font.Assign(Font);
case FCaptionPosition of
cpBottom:
begin
IconS := IconSize;
if IconS > Width - BUTTON_MARGIN then
IconS := Width - BUTTON_MARGIN;
if IconS > Height - BUTTON_MARGIN then
IconS := Height - BUTTON_MARGIN;
TextW := ACanvas.TextWidth(Caption);
TextH := ACanvas.TextHeight(Caption);
if TextW > Width - BUTTON_MARGIN then
TextW := Width - BUTTON_MARGIN;
IconX := (Width - IconS) div 2;
IconY := (Height - IconS - TextH - Spacing) div 2;
if IconY < BUTTON_MARGIN div 2 then
IconY := BUTTON_MARGIN div 2;
TextX := (Width - TextW) div 2;
TextY := IconY + IconS + Spacing;
if (TextY + TextH) > Height - BUTTON_MARGIN then
TextY := Height - BUTTON_MARGIN - TextH;
end;
cpRight:
begin
IconS := IconSize;
if IconS > Width - BUTTON_MARGIN then
IconS := Width - BUTTON_MARGIN;
if IconS > Height - BUTTON_MARGIN then
IconS := Height - BUTTON_MARGIN;
TextW := ACanvas.TextWidth(Caption);
TextH := ACanvas.TextHeight(Caption);
if TextW > Width - IconS - Spacing - BUTTON_MARGIN then
TextW := Width - IconS - Spacing - BUTTON_MARGIN;
IconX := BUTTON_MARGIN div 2;
IconY := (Height - IconS) div 2;
TextX := IconX + IconS + Spacing;
TextY := (Height - TextH) div 2;
end;
else
begin
if Width < Height then
IconS := Width - BUTTON_MARGIN
else
IconS := Height - BUTTON_MARGIN;
TextW := 0;
TextH := 0;
IconX := (Width - IconS) div 2;
IconY := (Height - IconS) div 2;
TextX := 0;
TextY := 0;
end;
end;
if FState = bsDown then
begin
Inc(IconX);
Inc(IconY);
Inc(TextX);
Inc(TextY);
end;
if IconHandle <> 0 then
begin
if not Assigned(FOnSkinDrawIcon) or not FOnSkinDrawIcon(Self, ClientRect) then
DrawIconEx(ACanvas.Handle, IconX, IconY, IconHandle, IconS, IconS, 0, 0, DI_NORMAL);
end;
if not Assigned(FOnSkinDrawCaption) or not FOnSkinDrawCaption(Self, ClientRect) then
begin
if (Caption <> '') and (FCaptionPosition <> cpNone) then
begin
BrushStyleBack := ACanvas.Brush.Style;
ACanvas.Font.Color := GetFontColorFromFaceColor(BackColor);
ACanvas.Brush.Style := bsClear;
try
FNarrowText := DrawNarrowText(ACanvas, Bounds(TextX, TextY, TextW, TextH), Caption);
finally
ACanvas.Brush.Style := BrushStyleBack;
end;
end;
end;
if not Assigned(FOnSkinDrawFrame) or not FOnSkinDrawFrame(Self, ClientRect) then
DrawFrame(ACanvas, ClientRect, FState = bsDown);
if not Assigned(FOnSkinDrawMask) or not FOnSkinDrawMask(Self, ClientRect) then
begin
if FSelTransparent then
begin
if Enabled and FFocusEnter then
ColorBetween(ACanvas, ClientRect, FFocusColor);
if FState = bsDown then
ColorBetween(ACanvas, ClientRect, clBlack);
end;
end;
if ACanvas <> Canvas then
begin
Canvas.Draw(0, 0, Bmp);
end;
finally
Bmp.Free;
end;
end;
/////////////////////
// TSLPluginButton
constructor TSLPluginButton.Create(AOwner: TComponent);
begin
inherited;
if Assigned(FOnCreate) then
FOnCreate(Self);
end;
destructor TSLPluginButton.Destroy;
begin
if Assigned(FOnDestroy) then
FOnDestroy(Self);
inherited;
end;
procedure TSLPluginButton.Paint;
var
DrawRect: TRect;
begin
if FOwnerDraw and Assigned(FOnDrawButton) then
begin
// スキンによる表面の描画
if not Assigned(FOnSkinDrawFace) or not FOnSkinDrawFace(Self, ClientRect) then
begin
// 選択状態を透明でなく表示
if Enabled and FFocusEnter and not FSelTransparent then
begin
Canvas.Brush.Color := FFocusColor;
Canvas.FillRect(ClientRect);
end
else
begin
Canvas.Brush.Color := Color;
if not FTransparent then
Canvas.FillRect(ClientRect);
end;
end;
DrawRect.Left := ClientRect.Left + 2;
DrawRect.Top := ClientRect.Top + 2;
DrawRect.Right := ClientRect.Right - 2;
DrawRect.Bottom := ClientRect.Bottom - 2;
if FState = bsDown then
begin
Inc(DrawRect.Left);
Inc(DrawRect.Top);
Inc(DrawRect.Right);
Inc(DrawRect.Bottom);
end;
FOnDrawButton(Self, DrawRect, FState);
if not Assigned(FOnSkinDrawFrame) or not FOnSkinDrawFrame(Self, ClientRect) then
DrawFrame(Canvas, ClientRect, FState = bsDown);
if not Assigned(FOnSkinDrawMask) or not FOnSkinDrawMask(Self, ClientRect) then
begin
if FSelTransparent then
begin
if Enabled and FFocusEnter then
ColorBetween(Canvas, ClientRect, FFocusColor);
if FState = bsDown then
ColorBetween(Canvas, ClientRect, clBlack);
end;
end;
end
else
inherited
end;
end.
|
program review_record;
uses crt;
const max=10;
type toefl=record
no_pst,nama:string;
listening,reading,structure:word;
total:Real;
end;//syntax deklasrasi record
larik_toefl=array[1..max] of toefl;//syntax deklarasi larik record
var peserta:larik_toefl;//deklarasi variabel
i,n,pil:Byte;
procedure tambah_pst(var X:larik_toefl);
var baru:string;
label ulang;
begin
WriteLn('menambah data peserta baru');
ulang:
Write('masukkan nomor peserta :');ReadLn(baru);
for i:=1 to n do //validasi no peserta
begin
if (X[i].no_pst=baru) then begin
WriteLn('nomor sudah digunakan , ulangi');
goto ulang;
end;
end;
// valid
inc(n);
X[n].no_pst:=baru;
Write('masukkan nama peserta :');ReadLn(X[n].nama);
// inisialisasi nilai awal
X[n].listening:=0;
X[n].reading:=0;
X[n].structure:=0;
X[n].total:=0;
WriteLn('selamat, pendaftaran peserta berhasil');
end;
procedure cetak_pst(X:larik_toefl);
begin
WriteLn('DAFTAR PESERTA TES TOEFL');
WriteLn('Pusat Bahasa IST AKPRIND');
WriteLn('----------------------------------------------------------------');
WriteLn('No No_Peserta Nama Listening Reading Structure Total');
WriteLn('----------------------------------------------------------------');
for i:=1 to n do WriteLn(i:2,' ',X[i].no_pst:4,' ',X[i].nama:6,' ',X[i].listening:3,' ',X[i].reading:3,' ',X[i].structure:3,' ',X[i].total:5:2);
WriteLn('----------------------------------------------------------------');
end;
procedure test_toefl(var X:larik_toefl);
var nomtes:String;
pos:byte;ada:Boolean;
begin
ada:=false;
WriteLn('tes toefl');
write('masukkan nomer tes anda : ');readln(nomtes);
// validasi apakah si nomer sudah pernah tes atau belum
// cek no tes ada atau tidak , jika ada dicek lagi apakah dia sdh pernah tes atau belum ?
for i:=1 to n do
begin
if(X[i].no_pst=nomtes) then
begin
ada:=true;
pos:=i;
end;
end;//end for
if not ada then WriteLn('anda tidak terdaftar sebagai peserta tes')
else
begin
// cek dia sudah pernah tes atau belum
if (X[pos].total=0) then
begin
Write('masukkan nilai listening :');ReadLn(X[pos].listening);
Write('masukkan nilai reading :');ReadLn(X[pos].reading);
Write('masukkan nilai structure :');ReadLn(X[pos].structure);
X[pos].total:=0.4*X[pos].listening+0.3*X[pos].reading+0.3*X[pos].structure;
end else WriteLn('mohon maaf anda sudah pernah tes');
end;
end;
begin
n:=0;
repeat
clrscr;
WriteLn('Menu pengelolaan data peserta toefl test');
WriteLn('1. Pendaftaran peserta');
WriteLn('2. Cetak peserta');
WriteLn('3. Input dan Hitung Data Tes');
WriteLn('0. Selesai');
Write('pilih menu 0-3 :');ReadLn(pil);
case pil of
1: if n=max then WriteLn('kelas sudah penuh ') else tambah_pst(peserta);
2: if n=0 then WriteLn('kelas masih kosong') else cetak_pst(peserta);
3: if n=0 then WriteLn('kelas masih kosong ') else test_toefl(peserta);
0:WriteLn('terimkasih') else WriteLn('anda salah pilih menu');
end;//end case
ReadLn;
until pil=0;
end.
|
(*******************************************************)
(* *)
(* Engine Paulovich DirectX *)
(* Win32-DirectX API Unit *)
(* *)
(* Copyright (c) 2003-2004, Ivan Paulovich *)
(* *)
(* iskatrek@hotmail.com uin#89160524 *)
(* *)
(* Unit: glCanvas *)
(* *)
(*******************************************************)
unit glCanvas;
interface
uses
Windows, SysUtils, Classes, glError, glConst, gl3DGraphics,
D3DX8, {$IFDEF DXG_COMPAT}DirectXGraphics{$ELSE}Direct3D8{$ENDIF};
type
(* Pre-Declaration *)
TPictureItem = class;
TPictureCollection = class;
(* TReferer *)
PCanvasReferer = ^TCanvasReferer;
TCanvasReferer = class of TCanvas;
(* T3DBrush *)
P3DBrush = ^T3DBrush;
T3DBrush = class
Alpha: Byte;
Color: TD3DColor;
end;
(* T3DFont *)
P3DFont = ^T3DFont;
T3DFont = class
Name: string;
Size: Integer;
Color: TD3DColor;
Font: HFONT;
end;
(* TCanvas *)
PCanvas = ^TCanvas;
TCanvas = class
private
F3DBrush: T3DBrush;
F3DFont: T3DFont;
FDXSprite: ID3DXSprite;
FDXFont: ID3DXFont;
FOldFont: T3DFont;
public
constructor Create(Graphics: TGraphics);
procedure TextOut(X, Y: Integer; Text: string);
procedure CreateTextureFromSurface(Surface: IDirect3DSurface8; SrcRect: TRect;
ColorKey: TD3DColor; var Texture: IDirect3DTexture8);
procedure Draw(X, Y: Integer; Source: TRect; Scale: TD3DXVector2; AxisRot: TD3DXVector2;
Rotation: Single; Alpha: Byte; Color: TD3DColor; const Texture: IDirect3DTexture8); overload;
procedure Draw(X, Y: Integer; Width, Height: Integer; const Texture: IDirect3DTexture8); overload;
procedure SpriteBegin;
procedure Draw(X, Y: Integer; Picture: TPictureItem; Index: Integer; Alpha: Byte); overload;
procedure Draw(X, Y: Integer; Picture: TPictureItem; Index: Integer; Alpha: Byte; Color: TD3DColor); overload;
procedure Draw(X, Y: Integer; Picture: TPictureItem; Index: Integer; Scale: TD3DXVector2; AxisRot: TD3DXVector2;
Rotation: Single; Alpha: Byte; Color: TD3DColor); overload;
procedure SpriteEnd;
property Brush: T3DBrush read F3DBrush write F3DBrush;
property Font: T3DFont read F3DFont write F3DFont;
property Sprite: ID3DXSprite read FDXSprite write FDXSprite;
end;
(* TImage *)
TImage = class
public
Image: IDirect3DTexture8;
end;
(* TPictureItem *)
TPictureItem = class
private
FInfo: TD3DXImageInfo;
FName: string;
FPatternWidth: Integer;
FPatternHeight: Integer;
FSkipWidth: Integer;
FSkipHeight: Integer;
FTransparent: Boolean;
FTransparentColor: LongInt;
FTextureList: TList;
function GetWidth: Integer;
function GetHeight: Integer;
function GetItem(Index: Integer): TImage;
function GetCount: Integer;
public
constructor Create;
destructor Destroy;
function Add(const FileName: string): Boolean;
property Name: string read FName write FName;
property PatternWidth: Integer read FPatternWidth write FPatternWidth;
property PatternHeight: Integer read FPatternHeight write FPatternHeight;
property SkipWidth: Integer read FSkipWidth write FSkipWidth default 0;
property SkipHeight: Integer read FSkipHeight write FSkipHeight default 0;
property Transparent: Boolean read FTransparent write FTransparent;
property TransparentColor: LongInt read FTransparentColor write FTransparentColor;
property PatternTextures[Index: Integer]: TImage read GetItem;
property Width: Integer read GetWidth;
property Height: Integer read GetHeight;
property PatternCount: Integer read GetCount;
end;
(* TPictureCollection *)
TPictureCollection = class
private
FListPictures: TList;
function IndexOf(Name: string): Integer;
function GetItem(Index: Integer): TPictureItem;
public
constructor Create;
function Add(FileName: string; Name: string; PatternWidth, PatternHeight: Integer; ColorKey: Longint;
SkipWidth: Integer = 0; SkipHeight: Integer = 0): Boolean;
function Find(const Name: string): TPictureItem;
property Items[Index: Integer]: TPictureItem read GetItem;
end;
var
Canvas: TCanvas = nil;
implementation
uses
glApplication;
(* TCanvas *)
constructor TCanvas.Create;
begin
F3DFont := T3DFont.Create;
F3DFont.Name := 'Arial';
F3DFont.Size := 20;
F3DFont.Font := 0;
F3DFont.Font := CreateFont(F3DFont.Size, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
PROOF_QUALITY, 0, PChar(F3DFont.Name));
F3DFont.Color := clWhite;
FOldFont := T3DFont.Create;
F3DBrush := T3DBrush.Create;
F3DBrush.Alpha := 255;
F3DBrush.Color := clBlack;
D3DXCreateSprite(Graphics.Device, FDXSprite);
D3DXCreateFont(Graphics.Device, F3DFont.Font, FDXFont);
end;
procedure TCanvas.TextOut(X, Y: Integer; Text: string);
var
I: Integer;
Rect: TRect;
begin
I := Length(Text);
SetRect(Rect, X, Y, X + (F3DFont.Size * I), Y + F3DFont.Size);
if (F3DFont.Name <> FOldFont.Name) or
(F3DFont.Size <> FOldFont.Size) or
(F3DFont.Color <> FOldFont.Color) then
begin
F3DFont.Font := CreateFont(F3DFont.Size, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
PROOF_QUALITY, 0, PChar(F3DFont.Name));
D3DXCreateFont(Graphics.Device, F3DFont.Font, FDXFont);
FOldFont := Font;
end;
FDXFont._Begin;
FDXFont.DrawTextA(PChar(Text), Length(Text), Rect, DT_LEFT, (255 shl 24) + F3DFont.Color);
FDXFont._End;
end;
procedure TCanvas.CreateTextureFromSurface(Surface: IDirect3DSurface8; SrcRect: TRect;
ColorKey: TD3DColor; var Texture: IDirect3DTexture8);
var
SurfDesc: TD3DSurface_Desc;
TexSurface: IDirect3DSurface8;
begin
Surface.GetDesc(SurfDesc);
D3DXCreateTexture(Graphics.Device, SrcRect.Right - SrcRect.Left,
SrcRect.Bottom - SrcRect.Top, 1, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, Texture);
Texture.GetLevelDesc(0, SurfDesc);
Texture.GetSurfaceLevel(0, TexSurface);
D3DXLoadSurfaceFromSurface(TexSurface, nil, nil, Surface, nil, @SrcRect, D3DX_FILTER_NONE, Colorkey);
end;
procedure TCanvas.Draw(X, Y: Integer; Width, Height: Integer; const Texture: IDirect3DTexture8);
var
MatWorld, MatRotation, MatTranslation, MatScale: TD3DXMatrix;
FX, FY: Single;
begin
D3DXMatrixIdentity(MatTranslation);
D3DXMatrixScaling(MatScale, Width, Height, 1.0);
D3DXMatrixMultiply(MatTranslation, MatTranslation, MatScale);
D3DXMatrixRotationZ(MatRotation, 0.0);
D3DXMatrixMultiply(MatWorld, MatTranslation, MatRotation);
FX := -(Graphics.Width div 2) + X;
FY := (Graphics.Height div 2) - Height - Y;
MatWorld._41 := FX;
MatWorld._42 := FY;
Graphics.Device.SetTransform(D3DTS_WORLD, MatWorld);
Graphics.Device.SetTexture(0, Texture);
Graphics.Device.SetStreamSource(0, Graphics.VertexBuffer, SizeOf(TVertex));
Graphics.Device.SetVertexShader(D3DFVFVERTEX);
Graphics.Device.DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
Graphics.Device.SetTexture(0, nil);
end;
procedure TCanvas.Draw(X, Y: Integer; Source: TRect; Scale: TD3DXVector2; AxisRot: TD3DXVector2;
Rotation: Single; Alpha: Byte; Color: TD3DColor; const Texture: IDirect3DTexture8);
var
Pos: TD3DXVector2;
begin
Pos := D3DXVector2(X, Y);
FDXSprite.Draw(Texture, @Source, @Scale, @AxisRot, Rotation, @Pos, (Alpha shl 24) + Color);
end;
procedure TCanvas.Draw(X, Y: Integer; Picture: TPictureItem; Index: Integer; Alpha: Byte);
var
Pos: TD3DXVector2;
S: TD3DXVector2;
begin
Pos := D3DXVector2(X, Y);
S := D3DXVector2(1.0, 1.0);
if Picture.Transparent then
FDXSprite.Draw(TImage(Picture.PatternTextures[Index]).Image, nil, @S, nil, 0, @Pos, (Alpha shl 24) + $FFFFFF)
else
FDXSprite.Draw(TImage(Picture.PatternTextures[Index]).Image, nil, @S, nil, 0, @Pos, 0);
end;
procedure TCanvas.Draw(X, Y: Integer; Picture: TPictureItem; Index: Integer; Alpha: Byte; Color: TD3DColor);
var
Pos: TD3DXVector2;
S: TD3DXVector2;
begin
Pos := D3DXVector2(X, Y);
S := D3DXVector2(1.0, 1.0);
if Picture.Transparent then
FDXSprite.Draw(TImage(Picture.PatternTextures[Index]).Image, nil, @S, nil, 0, @Pos, (Alpha shl 24) + Color)
else
FDXSprite.Draw(TImage(Picture.PatternTextures[Index]).Image, nil, @S, nil, 0, @Pos, 0);
end;
procedure TCanvas.Draw(X, Y: Integer; Picture: TPictureItem; Index: Integer; Scale: TD3DXVector2; AxisRot: TD3DXVector2;
Rotation: Single; Alpha: Byte; Color: TD3DColor);
var
Pos: TD3DXVector2;
begin
Pos := D3DXVector2(X, Y);
if Picture.Transparent then
FDXSprite.Draw(TImage(Picture.PatternTextures[Index]).Image, nil, @Scale, @AxisRot, Rotation, @Pos, (Alpha shl 24) + $FFFFFF)
else
FDXSprite.Draw(TImage(Picture.PatternTextures[Index]).Image, nil, @Scale, @AxisRot, Rotation, @Pos, 0);
end;
procedure TCanvas.SpriteBegin;
begin
FDXSprite._Begin;
end;
procedure TCanvas.SpriteEnd;
begin
FDXSprite._End;
end;
(* TPictureItem *)
constructor TPictureItem.Create;
begin
FTextureList := TList.Create;
FPatternWidth := 0;
FPatternHeight := 0;
FSkipWidth := 0;
FSkipHeight := 0;
FTransparent := True;
FTransparentColor := clFuchsia;
end;
destructor TPictureItem.Destroy;
begin
FTextureList.Free;
end;
function TPictureItem.GetItem(Index: Integer): TImage;
begin
Result := TImage(FTextureList.Items[Index]);
end;
function TPictureItem.GetCount: Integer;
begin
Result := FTextureList.Count - 1;
end;
function TPictureItem.Add(const FileName: string): Boolean;
var
Texture: IDirect3DTexture8;
Surface: IDirect3DSurface8;
FRect: TRect;
I, J: Integer;
L, M: Integer;
function AddTexture(const SrcRect: TRect): IDirect3DTexture8;
begin
Canvas.CreateTextureFromSurface(Surface, SrcRect, FTransparentColor, Result);
FTextureList.Add(TImage.Create);
TImage(FTextureList[FTextureList.Count - 1]).Image := Result;
end;
begin
Result := False;
if Failed(D3DXGetImageInfoFromFile(PChar(FileName), FInfo)) then
raise EError.Create(Format(ERROR_NOTFOUND,[FileName]))
else
SaveLog(Format(EVENT_FOUND,[FileName]));
Graphics.Device.CreateImageSurface(FInfo.Width, FInfo.Height,
Graphics.Parameters.BackBufferFormat, Surface);
D3DXLoadSurfaceFromFile(Surface, nil, nil, PChar(FileName), nil, D3DX_FILTER_NONE, FTransparentColor, nil);
if (GetWidth = FInfo.Width) and (GetHeight = FInfo.Height) then
begin
SetRect(FRect, 0, 0, FInfo.Width, FInfo.Height);
if AddTexture(FRect) = nil then
Exit;
end
else
begin
L := 0;
if FPatternWidth <> 0 then
L := (FInfo.Width + FSkipWidth) div (FPatternWidth + FSkipWidth);
M := 0;
if FPatternHeight <> 0 then
M := (FInfo.Height + FSkipHeight) div (FPatternHeight + FSkipHeight);
for J := 0 to M - 1 do
for I := 0 to L - 1 do
begin
SetRect(FRect, I * (FPatternWidth + FSkipWidth), J * (FPatternHeight + FSkipHeight),
(I * (FPatternWidth + FSkipWidth)) + FPatternWidth, (J * (FPatternHeight + FSkipHeight)) + FPatternHeight);
if AddTexture(FRect) = nil then
Exit;
end;
end;
Result := True;
end;
function TPictureItem.GetWidth: Integer;
begin
Result := FPatternWidth;
if (Result <= 0) then
Result := FInfo.Width;
end;
function TPictureItem.GetHeight: Integer;
begin
Result := FPatternHeight;
if (Result <= 0) then
Result := FInfo.Height;
end;
(* TPictureCollection *)
constructor TPictureCollection.Create;
begin
FListPictures := TList.Create;
end;
function TPictureCollection.Add(FileName: string; Name: string; PatternWidth, PatternHeight: Integer;
ColorKey: Longint; SkipWidth: Integer = 0; SkipHeight: Integer = 0): Boolean;
begin
Result := False;
FListPictures.Add(TPictureItem.Create);
TPictureItem(FListPictures.Items[FListPictures.Count - 1]).Name := Name;
TPictureItem(FListPictures.Items[FListPictures.Count - 1]).PatternWidth := PatternWidth;
TPictureItem(FListPictures.Items[FListPictures.Count - 1]).PatternHeight := PatternHeight;
TPictureItem(FListPictures.Items[FListPictures.Count - 1]).SkipWidth := SkipWidth;
TPictureItem(FListPictures.Items[FListPictures.Count - 1]).SkipHeight := SkipHeight;
TPictureItem(FListPictures.Items[FListPictures.Count - 1]).TransparentColor := ColorKey;
if not TPictureItem(FListPictures.Items[FListPictures.Count - 1]).Add(FileName) then
Result := True;
end;
function TPictureCollection.IndexOf(Name: string): Integer;
var
I: Integer;
begin
for I := 0 to FListPictures.Count - 1 do
begin
if TPictureItem(FListPictures[I]).Name = Name then
begin
Result := I;
Exit;
end;
end;
I := -1;
end;
function TPictureCollection.GetItem(Index: Integer): TPictureItem;
begin
Result := TPictureItem(FListPictures.Items[Index]);
end;
function TPictureCollection.Find(const Name: string): TPictureItem;
var
I: Integer;
begin
I := IndexOf(Name);
if I = -1 then
raise EError.Create(Format(ERROR_NOTFOUND, [Name]));
Result := TPictureItem(FListPictures.Items[I]);
end;
end.
|
{$include kode.inc}
unit syn_s2_osc_waveshape;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_control,
kode_editor,
kode_plugin,
kode_voice,
kode_widget;
type
s2_osc_waveshape_proc = class
private
FVoice : KVoice;
private
FType : LongInt;
FSrc : LongInt;
FAmt : Single;
FModSrc : LongInt;
FModAmt : Single;
public
constructor create(AVoice:KVoice; AUser:LongInt=0);
procedure noteOn(ANote,AVel:Single);
procedure noteOff(ANote,AVel:Single);
procedure pitchBend(ABend:Single);
function process(wav:single) : single;
procedure control(AIndex:LongInt; AValue:Single);
end;
//----------
s2_osc_waveshape_ctrl = class(KControlGroup)
private
WType : KWidget;
WSrc : KWidget;
WAmt : KWidget;
WModSrc : KWidget;
WModAmt : KWidget;
public
constructor create(AName:PChar; APlugin:KPlugin; AUser:LongInt=0);
destructor destroy; override;
function appendParameters(APlugin:KPlugin; AOffset:LongInt=0) : LongInt; override;
procedure appendWidgets(AOwner:KWidget; AXpos,AYpos:LongInt); override;
procedure connectWidgets(AEditor:KEditor; APlugin:KPlugin); override;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_color,
kode_math,
kode_parameter,
kode_rect,
kode_widget_slider,
kode_widget_text,
syn_s2_const,
syn_s2_voicemanager,
syn_s2_widgets;
constructor s2_osc_waveshape_proc.create(AVoice:KVoice; AUser:LongInt=0);
begin
FVoice := AVoice;
FType := s2s_off;
FSrc := s2m_off;
FAmt := 0;
FModSrc := s2m_off;
FModAmt := 0;
end;
//----------
procedure s2_osc_waveshape_proc.noteOn(ANote,AVel:Single);
begin
end;
//----------
procedure s2_osc_waveshape_proc.noteOff(ANote,AVel:Single);
begin
end;
//----------
procedure s2_osc_waveshape_proc.pitchBend(ABend:Single);
begin
end;
//----------
function s2_osc_waveshape_proc.process(wav:single) : Single;
var
vm : s2_voicemanager;
amt : single;
m : Single;
begin
vm := s2_voicemanager(FVoice.voicemanager);
amt := FAmt;
amt += vm.getModValue(FModSrc) * FModAmt;
m := vm.getModValue(FSrc) * amt;
case FType of
s2s_off: result := wav;
s2s_add: result := wav + m;
s2s_mul: result := wav * m;
s2s_curve:
begin
m := (m*0.5)+0.5;
m := KClamp(m,0.02,0.96);
result := KCurve(abs(wav),m);
if wav < 0 then result := -result;
end;
end;
end;
//----------
procedure s2_osc_waveshape_proc.control(AIndex:LongInt; AValue:Single);
begin
case AIndex of
0 : FType := trunc(AValue);
1 : FSrc := trunc(AValue);
2 : FAmt := AValue;
3 : FModSrc := trunc(AValue);
4 : FModAmt := AValue;
end;
end;
//----------------------------------------------------------------------
// control
//----------------------------------------------------------------------
constructor s2_osc_waveshape_ctrl.create(AName:PChar; APlugin:KPlugin; AUser:LongInt=0);
begin
inherited;
FCount := 5;
end;
//----------
destructor s2_osc_waveshape_ctrl.destroy;
begin
inherited;
end;
//----------
function s2_osc_waveshape_ctrl.appendParameters(APlugin:KPlugin; AOffset:LongInt=0) : LongInt;
begin
FOffset := AOffset;
APlugin.appendParameter(KParamText.create( 'Type', s2s_off, s2s_count, txt_shape ));
APlugin.appendParameter(KParamText.create( 'Src', s2m_off, s2m_count, txt_src ));
APlugin.appendParameter(KParamFloat.create( 'Amt', 0, -1, 1 ));
APlugin.appendParameter(KParamText.create( 'ModSrc', s2m_off, s2m_count, txt_src ));
APlugin.appendParameter(KParamFloat.create( 'ModAmt', 0, -1, 1 ));
result := 5;
end;
//----------
procedure s2_osc_waveshape_ctrl.appendWidgets(AOwner:KWidget; AXpos,AYpos:LongInt);
begin
AOwner.appendWidgetW( KWidget_Text.create( rect( AXpos, AYpos+(0*18), 128,16 ), FName, KLightGrey, KDarkGrey ));
WType := AOwner.appendWidgetW( s2_slider_cyan.create( rect( AXpos, AYpos+(1*18), 128,16 ), 'type', 0 ));
WSrc := AOwner.appendWidgetW( s2_slider_yellow.create( rect( AXpos, AYpos+(2*18), 128,16 ), 'src', 0 ));
WAmt := AOwner.appendWidgetW( s2_slider_orange.create( rect( AXpos, AYpos+(3*18), 128,16 ), 'amt', 0 ));
WModSrc := AOwner.appendWidgetW( s2_slider_magenta.create( rect( AXpos, AYpos+(4*18), 128,16 ), 'modsrc', 0 ));
WModAmt := AOwner.appendWidgetW( s2_slider_red.create( rect( AXpos, AYpos+(5*18), 128,16 ), 'modamt', 0 ));
end;
//----------
procedure s2_osc_waveshape_ctrl.connectWidgets(AEditor:KEditor; APlugin:KPlugin);
begin
AEditor.connect( WType, APlugin.getParameter(FOffset+0) );
AEditor.connect( WSrc, APlugin.getParameter(FOffset+1) );
AEditor.connect( WAmt, APlugin.getParameter(FOffset+2) );
AEditor.connect( WModSrc, APlugin.getParameter(FOffset+3) );
AEditor.connect( WModAmt, APlugin.getParameter(FOffset+4) );
end;
//----------------------------------------------------------------------
end.
|
unit Kinect2Dll;
interface
uses
Windows, SysUtils, Dialogs;
type
TDepthFrameData = Word;
PDepthFrameData = PWord;
TIRFrameData = Word;
PIRFrameData = PWord;
TColorFrameData = Byte;
PColorFrameData = PByte;
function KinectVersionString:String;
function AbleToLoadKinectLibrary:Boolean;
procedure UnloadKinectLibrary;
function AbleToStartUpKinect2:Boolean;
procedure ShutDownKinect2;
const
KINECT2_DLL_NAME = 'Kinect2DLL.dll';
DEPTH_W = 512;
DEPTH_H = 424;
IR_W = 512;
IR_H = 424;
COLOR_W = 1920;
COLOR_H = 1080;
COLOR_BPP = 4;
// hand state
HandState_Unknown = 0;
HandState_NotTracked = 1;
HandState_Open = 2;
HandState_Closed = 3;
HandState_Lasso = 4;
// tracking confidence
TrackingConfidence_Low = 0;
TrackingConfidence_High = 1;
JOINT_TYPE_COUNT = 25;
BODY_COUNT = 6;
type
TJointType = (JointType_SpineBase, JointType_SpineMid, JointType_Neck,
JointType_Head, JointType_ShoulderLeft, JointType_ElbowLeft,
JointType_WristLeft, JointType_HandLeft, JointType_ShoulderRight,
JointType_ElbowRight, JointType_WristRight, JointType_HandRight,
JointType_HipLeft, JointType_KneeLeft, JointType_AnkleLeft,
JointType_FootLeft, JointType_HipRight, JointType_KneeRight,
JointType_AnkleRight, JointType_FootRight, JointType_SpineShoulder,
JointType_HandTipLeft, JointType_ThumbLeft, JointType_HandTipRight,
JointType_ThumbRight, JointType_Count);
TTrackingState = (TrackingState_NotTracked, TrackingState_Inferred,
TrackingState_Tracked);
TCameraSpacePoint = record
X, Y, Z : Single;
end;
PCameraSpacePoint = ^TCameraSpacePoint;
TJoint = record
JointType : TJointType;
Position : TCameraSpacePoint;
TrackingState : TTrackingState;
end;
PJoint = ^TJoint;
TJointArray = array[1..JOINT_TYPE_COUNT] of TJoint;
THandState = Integer;
TColorSpacePoint = record
X,Y : Single;
end;
TJointColorPtArray = array[1..JOINT_TYPE_COUNT] of TColorSpacePoint;
TBodyData = record
TrackingID : Int64;
Tracked : Boolean;
Confidence : Integer;
LeftHandState : THandState;
RightHandState : THandState;
Joint : TJointArray;
JointColorPt : TJointColorPtArray;
end;
PBodyData = ^TBodyData;
TBodyDataArray = array[1..BODY_COUNT] of TBodyData;
PBodyDataArray = ^TBodyDataArray;
TGetVersion = function:Integer; stdcall; // yes it's just an integer :)
TAbleToInitialize = function:Boolean; stdcall;
TAbleToStartStream = function:Boolean; stdcall;
TGetDepthFrame = function:PDepthFrameData; stdcall;
TGetIRFrame = function:PIRFrameData; stdcall;
TGetColorFrame = function:PColorFrameData; stdcall;
TDoneFrame = procedure; stdcall;
TAbleToUpdateBodyFrame = function:Boolean; stdcall;
TShutDown = procedure; stdcall;
TGetColorData = function:PColorFrameData; stdcall;
TGetBodyData = function:PBodyData; stdcall;
TAbleToUpdateMultiFrame = function:Boolean; stdcall;
var
HLibrary : HModule = 0;
GetVersion : TGetVersion = nil;
AbleToStartUp : TAbleToInitialize = nil;
ShutDown : TShutDown = nil;
// depth
AbleToStartDepth : TAbleToStartStream = nil;
GetDepthFrame : TGetDepthFrame = nil;
DoneDepthFrame : TDoneFrame = nil;
// IR
AbleToStartIR : TAbleToStartStream = nil;
GetIRFrame : TGetIRFrame = nil;
DoneIRFrame : TDoneFrame = nil;
// color
AbleToStartColor : TAbleToStartStream = nil;
GetColorFrame : TGetColorFrame = nil;
DoneColorFrame : TDoneFrame = nil;
GetColorData : TGetColorData = nil;
// multiframe
AbleToStartMultiFrame : TAbleToStartStream = nil;
AbleToUpdateMultiFrame : TAbleToUpdateMultiFrame = nil;
DoneMultiFrame : TDoneFrame = nil;
// body
AbleToStartBody : TAbleToStartStream = nil;
AbleToUpdateBodyFrame : TAbleToUpdateBodyFrame = nil;
DoneBodyFrame : TDoneFrame = nil;
GetBodyData : TGetBodyData = nil;
function FullDLLName:String;
implementation
function KinectVersionString:String;
var
V : Integer;
begin
if HLibrary=0 then Result:='???'
else begin
V:=getVersion;
Result:=IntToStr(V);
end;
end;
function FullDLLName:String;
begin
Result:=KINECT2_DLL_NAME;
end;
function AbleToLoadKinectLibrary:Boolean;
var
FileName : String;
RC : Integer;
begin
Result:=False;
if HLibrary<>0 then Exit;
FileName:=FullDLLName;
if not FileExists(FileName) then begin
ShowMessage(FileName+' not found');
end;
HLibrary:=LoadLibrary(PChar(FileName));
if HLibrary=0 then begin
RC:=GetLastError;
Exit;
end;
// version
GetVersion:=GetProcAddress(HLibrary,'getVersion');
if not Assigned(GetVersion) then Exit;
// startup / shutdown
AbleToStartUp:=GetProcAddress(HLibrary,'ableToStartUp');
if not Assigned(AbleToStartUp) then Exit;
ShutDown:=GetProcAddress(HLibrary,'shutDown');
if not Assigned(ShutDown) then Exit;
// depth
AbleToStartDepth:=GetProcAddress(HLibrary,'ableToStartDepth');
if not Assigned(AbleToStartDepth) then Exit;
GetDepthFrame:=GetProcAddress(HLibrary,'getDepthFrame');
if not Assigned(GetDepthFrame) then Exit;
DoneDepthFrame:=GetProcAddress(HLibrary,'doneDepthFrame');
if not Assigned(DoneDepthFrame) then Exit;
// IR
AbleToStartIR:=GetProcAddress(HLibrary,'ableToStartIR');
if not Assigned(AbleToStartIR) then Exit;
GetIRFrame:=GetProcAddress(HLibrary,'getIRFrame');
if not Assigned(GetIRFrame) then Exit;
DoneIRFrame:=GetProcAddress(HLibrary,'doneIRFrame');
if not Assigned(DoneIRFrame) then Exit;
// color
AbleToStartColor:=GetProcAddress(HLibrary,'ableToStartColor');
if not Assigned(AbleToStartColor) then Exit;
GetColorFrame:=GetProcAddress(HLibrary,'getColorFrame');
if not Assigned(GetColorFrame) then Exit;
DoneColorFrame:=GetProcAddress(HLibrary,'doneColorFrame');
if not Assigned(DoneColorFrame) then Exit;
GetColorData:=GetProcAddress(HLibrary,'getColorData');
if not Assigned(GetColorData) then Exit;
// multiframe
AbleToStartMultiFrame:=GetProcAddress(HLibrary,'ableToStartMultiFrame');
if not Assigned(AbleToStartMultiFrame) then Exit;
AbleToUpdateMultiFrame:=GetProcAddress(HLibrary,'ableToUpdateMultiFrame');
if not Assigned(AbleToUpdateMultiFrame) then Exit;
DoneMultiFrame:=GetProcAddress(HLibrary,'doneMultiFrame');
if not Assigned(DoneMultiFrame) then Exit;
// body
AbleToStartBody:=GetProcAddress(HLibrary,'ableToStartBody');
if not Assigned(AbleToStartBody) then Exit;
AbleToUpdateBodyFrame:=GetProcAddress(HLibrary,'ableToUpdateBodyFrame');
if not Assigned(AbleToUpdateBodyFrame) then Exit;
GetBodyData:=GetProcAddress(HLibrary,'getBodyData');
if not Assigned(GetBodyData) then Exit;
DoneBodyFrame:=GetProcAddress(HLibrary,'doneBodyFrame');
if not Assigned(DoneBodyFrame) then Exit;
Result:=True;
end;
procedure UnloadKinectLibrary;
begin
if HLibrary=0 then Exit;
GetVersion:=nil;
AbleToStartUp:=nil;
ShutDown:=nil;
// depth
AbleToStartDepth:=nil;
GetDepthFrame:=nil;
DoneDepthFrame:= nil;
// IR
AbleToStartIR:=nil;
GetIRFrame:=nil;
DoneIRFrame:=nil;
// color
AbleToStartColor:=nil;
GetColorFrame:=nil;
DoneColorFrame:=nil;
GetColorData:=nil;
// multiframe
AbleToStartMultiFrame:=nil;
AbleToUpdateMultiFrame:=nil;
DoneMultiFrame:=nil;
// body
AbleToStartBody:=nil;
AbleToUpdateBodyFrame:=nil;
DoneBodyFrame:=nil;
if not Assigned(DoneBodyFrame) then Exit;
GetBodyData:=nil;
FreeLibrary(HLibrary);
HLibrary:=0;
end;
function AbleToStartUpKinect2:Boolean;
begin
Result:=AbleToStartUp;
end;
procedure ShutDownKinect2;
begin
ShutDown;
end;
end.
|
Unit ListUtil;
INTERFACE
TYPE
ItemPtr = ^Item;
Item = OBJECT
Next : ItemPtr;
Constructor Init;
Procedure print; Virtual;
Destructor Done; Virtual;
End;
List = OBJECT
Root : ItemPtr;
Constructor Init;
procedure InsertItem(P : ItemPtr);
Procedure DisposeList;
Procedure PrintList;
End;
IMPLEMENTATION
Var
Last : ItemPtr;
{------------------------------}
Constructor Item.Init;
Begin
Next := Nil;
End;
{------------------------------}
Destructor Item.Done;
Begin
End;
{------------------------------}
Procedure Item.Print;
Begin
Writeln;
End;
{------------------------------}
Constructor List.Init;
Begin
Root := Nil;
End;
{------------------------------}
Procedure List.InsertItem;
Begin
If Root = Nil Then
Root := P
Else
Last^.Next := P;
Last := P;
Last^.Next := Nil
End;
{------------------------------}
Procedure List.PrintList;
Var
Ip : ItemPtr;
Begin
Ip := Root;
While ( Ip <> Nil ) Do
Begin
Ip^.print;
Ip := Ip^.Next
End;
End;
{------------------------------}
Procedure List.DisposeList;
Var
Ip : ItemPtr;
Begin
While (Root <> Nil) Do
Begin
Ip := Root;
Root := Ip^.Next;
Dispose(Ip,Done);
End;
End;
END.
|
unit AsyncHttpServer.RequestHandler;
interface
uses
AsyncIO, AsyncHttpServer.Mime, AsyncHttpServer.Request, AsyncHttpServer.Response;
type
HttpRequestHandler = interface
['{AC26AF7B-589F-41D1-8449-995ECDADB2B4}']
{$REGION 'Property accessors'}
function GetService: IOService;
{$ENDREGION}
function HandleRequest(const Request: HttpRequest): HttpResponse;
property Service: IOService read GetService;
end;
function NewHttpRequestHandler(const Service: IOService; const DocRoot: string; const Mime: MimeRegistry): HttpRequestHandler;
implementation
uses
WinAPI.Windows, System.SysUtils, System.Math, System.IOUtils, EncodingHelper,
AsyncIO.Filesystem, AsyncHttpServer.Headers, HttpDateTime;
const
HTTP_GET_METHOD = 'GET';
HTTP_HEAD_METHOD = 'HEAD';
// I shouldn't complain, it's not even a decade since Vista was released...
function GetFileSizeEx(hFile: THandle; out lpFileSize: int64): BOOL; stdcall; external kernel32;
type
URLParts = record
Path: string;
Query: string;
end;
function DecodeURLSegment(const Input: string; out Output: string; const PlusToSpace: boolean): boolean;
var
i, v: integer;
c: char;
hs: string;
validHex: boolean;
encc: string;
begin
result := False;
Output := '';
i := 0;
while (i < Input.Length) do
begin
c := Input.Chars[i];
if (c = '%') then
begin
hs := '$' + Input.Substring(i+1, 2);
if (hs.Length <> 3) then
exit;
validHex := TryStrToInt(hs, v);
if (not validHex) then
exit;
// assume encoded character is in default encoding
encc := TEncoding.Default.GetString(PByte(@v), 0, 1);
Output := Output + encc;
i := i + 3;
end
else if (PlusToSpace and (c = '+')) then
begin
Output := Output + ' ';
i := i + 1;
end
else
begin
Output := Output + c;
i := i + 1;
end;
end;
result := True;
end;
function DecodeURL(const URL: string; out Decoded: URLParts): boolean;
var
path: string;
query: string;
paramIndex, queryIndex, pathEndIndex: integer;
begin
// here we assume the URL represents an absolute path
paramIndex := URL.IndexOf(';');
queryIndex := URL.IndexOf('?');
path := '';
query := '';
if ((paramIndex < 0) and (queryIndex < 0)) then
begin
// no path parameters nor query segment
path := URL;
end
else
begin
if ((paramIndex < 0) or ((queryIndex >= 0) and (queryIndex < paramIndex))) then
begin
pathEndIndex := queryIndex; // no path parameter separator in path segment
end
else
begin
pathEndIndex := paramIndex; // path stops at path parameter separator
end;
path := URL.Substring(0, pathEndIndex);
if (queryIndex > 0) then
begin
query := URL.Substring(queryIndex + 1, URL.Length);
end;
end;
// now to decode the segments
result := DecodeURLSegment(path, Decoded.Path, False);
if (not result) then
exit;
result := DecodeURLSegment(query, Decoded.Query, True);
if (not result) then
exit;
end;
type
HttpRequestHandlerImpl = class(TInterfacedObject, HttpRequestHandler)
strict private
FService: IOService;
FDocRoot: string;
FMime: MimeRegistry;
function GetFullPath(const Filename: string): string;
function GetFileModifiedTime(const FileStream: AsyncFileStream): TSystemTime;
function GetFileSize(const FileStream: AsyncFileStream): Int64;
procedure Log(const Msg: string);
public
constructor Create(const Service: IOService; const DocRoot: string; const Mime: MimeRegistry);
function GetService: IOService;
function HandleRequest(const Request: HttpRequest): HttpResponse;
property Service: IOService read FService;
property DocRoot: string read FDocRoot;
property Mime: MimeRegistry read FMime;
end;
function NewHttpRequestHandler(const Service: IOService; const DocRoot: string; const Mime: MimeRegistry): HttpRequestHandler;
begin
result := HttpRequestHandlerImpl.Create(Service, DocRoot, Mime);
end;
{ HttpRequestHandlerImpl }
constructor HttpRequestHandlerImpl.Create(const Service: IOService; const DocRoot: string; const Mime: MimeRegistry);
begin
inherited Create;
FService := Service;
FDocRoot := IncludeTrailingPathDelimiter(DocRoot);
FMime := Mime;
end;
function HttpRequestHandlerImpl.GetFileSize(
const FileStream: AsyncFileStream): Int64;
var
res: boolean;
begin
res := GetFileSizeEx(FileStream.Handle, result);
if (not res) then
RaiseLastOSError();
end;
function HttpRequestHandlerImpl.GetFileModifiedTime(
const FileStream: AsyncFileStream): TSystemTime;
var
res: boolean;
mt: TFileTime;
begin
res := WinAPI.Windows.GetFileTime(FileStream.Handle, nil, nil, @mt);
if (not res) then
RaiseLastOSError();
res := WinAPI.Windows.FileTimeToSystemTime(mt, result);
if (not res) then
RaiseLastOSError();
end;
function HttpRequestHandlerImpl.GetFullPath(const Filename: string): string;
var
p: TArray<string>;
i: integer;
begin
result := '';
p := Filename.Split(['/']);
// we know start of Filename starts with / and ends with a filename
Delete(p, 0, 1);
i := 0;
while (i < Length(p)) do
begin
if (p[i] = '..') then
begin
// check if we're attempting to escape root
if (i < 1) then
exit;
i := i - 1;
Delete(p, i, 2);
end
else
begin
i := i + 1;
end;
end;
result := DocRoot + string.Join(PathDelim, p);
end;
function HttpRequestHandlerImpl.GetService: IOService;
begin
result := FService;
end;
function HttpRequestHandlerImpl.HandleRequest(const Request: HttpRequest): HttpResponse;
var
url: URLParts;
urlValid: boolean;
filename: string;
fileExists: boolean;
contentStream: AsyncFileStream;
fileSize: Int64;
modifiedTime: TSystemTime;
hasIfModifiedSinceTime: boolean;
ifModifiedSinceTime: TSystemTime;
contentModified: boolean;
contentType: string;
begin
try
if (Request.HttpVersionMajor <> 1) then
begin
result := StandardResponse(StatusNotImplemented);
exit;
end;
if ((Request.Method <> HTTP_GET_METHOD) and (Request.Method <> HTTP_HEAD_METHOD)) then
begin
result := StandardResponse(StatusNotImplemented);
exit;
end;
urlValid := DecodeURL(Request.URI, url);
// require absolute path
urlValid := urlValid
and (url.Path.Length > 0)
and (url.Path.Chars[0] = '/')
and (url.Path.IndexOf('//') < 0);
if (not urlValid) then
begin
result := StandardResponse(StatusBadRequest);
exit;
end;
filename := url.Path;
if (filename.EndsWith('/')) then
filename := filename + 'index.html';
filename := GetFullPath(filename);
// check if all went well with resolving the full path
// and that file actually exists
fileExists := (filename <> '') and TFile.Exists(filename);
if (not fileExists) then
begin
result := StandardResponse(StatusNotFound);
exit;
end;
// all looking good
// now to open the file and get the details for the headers
contentStream := NewAsyncFileStream(Service, filename, fcOpenExisting, faRead, fsRead);
fileSize := GetFileSize(contentStream);
modifiedTime := GetFileModifiedTime(contentStream);
// TESTING
//DateTimeToSystemTime(Now(), modifiedTime);
contentType := Mime.FileExtensionToMimeType(ExtractFileExt(filename));
hasIfModifiedSinceTime := TryHttpDateToSystemTime(Request.Headers.Value['If-Modified-Since'], ifModifiedSinceTime);
if (hasIfModifiedSinceTime) then
begin
contentModified := CompareSystemTime(modifiedTime, ifModifiedSinceTime) > 0;
if (not contentModified) then
begin
// content not modified, so we just send a standard 304 response
result := StandardResponse(StatusNotModified);
exit;
end;
end;
result.Status := StatusOK;
result.Headers.Value['Content-Length'] := IntToStr(fileSize);
result.Headers.Value['Content-Type'] := contentType;
result.Headers.Value['Last-Modified'] := SystemTimeToHttpDate(modifiedTime);
// only send content if we've been asked to
if (Request.Method = HTTP_GET_METHOD) then
begin
result.Content := nil;
result.ContentStream := contentStream;
end;
except
on E: Exception do
begin
Log('Error processing request');
Log(Format('Exception: [%s] %s', [E.ClassName, E.Message]));
Log(Format('Request: %s %s HTTP/%d.%d', [Request.Method, Request.URI, Request.HttpVersionMajor, '.', Request.HttpVersionMinor]));
result := StandardResponse(StatusInternalServerError);
end;
end;
end;
procedure HttpRequestHandlerImpl.Log(const Msg: string);
begin
WriteLn(Msg);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.