text stringlengths 14 6.51M |
|---|
unit ACBrCEPDll;
interface
uses
Classes, SysUtils,
ACBrCEP;
type TNoArgumentsCallback = procedure(); cdecl;
type TAntesAbrirHTTPCallback = function(const AURL : pChar) : pChar; cdecl;
type TEventHandlersCEP = class
OnBuscaEfetuadaCallback : TNoArgumentsCallback;
OnAntesAbrirHTTPCallback : TAntesAbrirHTTPCallback;
procedure OnBuscaEfetuada(Sender: TObject);
procedure OnAntesAbrirHTTP(var AURL : String);
end;
{Handle para o componente TACBrCEP }
type TCEPHandle = record
UltimoErro : String;
CEP : TACBrCEP;
EventHandlers : TEventHandlersCEP;
end;
{Ponteiro para o Handle }
type PCEPHandle = ^TCEPHandle;
implementation
{%region Constructor/Destructor }
{
PADRONIZAÇÃO DAS FUNÇÕES:
PARÂMETROS:
Todas as funções recebem o parâmetro "handle" que é o ponteiro
para o componente instanciado; Este ponteiro deve ser armazenado
pela aplicação que utiliza a DLL;
RETORNO:
Todas as funções da biblioteca retornam um Integer com as possíveis Respostas:
MAIOR OU IGUAL A ZERO: SUCESSO
Outos retornos maior que zero indicam sucesso, com valor específico de cada função.
MENOR QUE ZERO: ERROS
-1 : Erro ao executar;
Vide UltimoErro
-2 : ACBr não inicializado.
Outros retornos negativos indicam erro específico de cada função;
A função "UltimoErro" retornará a mensagem da última exception disparada pelo componente.
}
{
CRIA um novo componente TACBrCEP retornando o ponteiro para o objeto criado.
Este ponteiro deve ser armazenado pela aplicação que utiliza a DLL e informado
em todas as chamadas de função relativas ao TACBrCEP
}
Function CEP_Create(var cepHandle: PCEPHandle): Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
try
New(cepHandle);
cepHandle^.CEP := TACBrCEP.Create(nil);
cepHandle^.EventHandlers := TEventHandlersCEP.Create();
cepHandle^.UltimoErro := '';
Result := 0;
except
on exception : Exception do
begin
Result := -1;
cepHandle^.UltimoErro := exception.Message;
end
end;
end;
{
DESTRÓI o objeto TACBrCEP e libera a memória utilizada.
Esta função deve SEMPRE ser chamada pela aplicação que utiliza a DLL
quando o componente não mais for utilizado.
}
Function CEP_Destroy(cepHandle: PCEPHandle): Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.Destroy();
cepHandle^.CEP := nil;
Dispose(cepHandle);
cepHandle := nil;
Result := 0;
except
on exception : Exception do
begin
Result := -1;
cepHandle^.UltimoErro := exception.Message;
end
end;
end;
Function CEP_GetUltimoErro(const cepHandle: PCEPHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
try
StrPLCopy(Buffer, cepHandle^.UltimoErro, BufferLen);
Result := length(cepHandle^.UltimoErro);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
{%endregion}
{%region Funções mapeando as propriedades do componente }
Function CEP_GetChaveAcesso(const cepHandle: PCEPHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, cepHandle^.CEP.ChaveAcesso, BufferLen);
Result := length(cepHandle^.CEP.ChaveAcesso);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetChaveAcesso(const cepHandle: PCEPHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.ChaveAcesso := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_GetUsuario(const cepHandle: PCEPHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, cepHandle^.CEP.Usuario, BufferLen);
Result := length(cepHandle^.CEP.Usuario);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetUsuario(const cepHandle: PCEPHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.Usuario := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_GetSenha(const cepHandle: PCEPHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, cepHandle^.CEP.Senha, BufferLen);
Result := length(cepHandle^.CEP.Senha);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetSenha(const cepHandle: PCEPHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.Senha := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_GetURL(const cepHandle: PCEPHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, cepHandle^.CEP.URL, BufferLen);
Result := length(cepHandle^.CEP.ChaveAcesso);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_GetParseText(const cepHandle: PCEPHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
if cepHandle^.CEP.ParseText then
Result := 1
else
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetParseText(const cepHandle: PCEPHandle; const value : Boolean) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.ParseText := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_GetProxyHost(const cepHandle: PCEPHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, cepHandle^.CEP.ProxyHost, BufferLen);
Result := length(cepHandle^.CEP.ChaveAcesso);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetProxyHost(const cepHandle: PCEPHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.ProxyHost := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_GetProxyPort(const cepHandle: PCEPHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, cepHandle^.CEP.ProxyPort, BufferLen);
Result := length(cepHandle^.CEP.ChaveAcesso);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetProxyPort(const cepHandle: PCEPHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.ProxyPort := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_GetProxyUser(const cepHandle: PCEPHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, cepHandle^.CEP.ProxyUser, BufferLen);
Result := length(cepHandle^.CEP.ChaveAcesso);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetProxyUser(const cepHandle: PCEPHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.ProxyUser := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_GetProxyPass(const cepHandle: PCEPHandle; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, cepHandle^.CEP.ProxyPass, BufferLen);
Result := length(cepHandle^.CEP.ChaveAcesso);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetProxyPass(const cepHandle: PCEPHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.ProxyPass := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_GetWebService(const cepHandle: PCEPHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
Result := Integer(cepHandle^.CEP.WebService);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetWebService(const cepHandle: PCEPHandle; const value : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.WebService := TACBrCEPWebService(value);
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
{%endregion}
{%region Endereços }
Function CEP_GetEnderecos(const cepHandle: PCEPHandle; var endsHandle : TACBrCEPEnderecos) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endsHandle := cepHandle^.CEP.Enderecos;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Enderecos_GetCount(const cepHandle: PCEPHandle; const endsHandle : TACBrCEPEnderecos) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
Result := endsHandle.Count;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Enderecos_GetItem(const cepHandle: PCEPHandle; const endsHandle : TACBrCEPEnderecos; const index : Integer; var endHandle : TACBrCEPEndereco) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endHandle := endsHandle[index];
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
{%endregion}
{%region Endereço }
Function CEP_Endereco_GetCEP(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, endHandle.CEP, BufferLen);
Result := length(endHandle.CEP);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_SetCEP(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endHandle.CEP := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_GetBairro(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, endHandle.Bairro, BufferLen);
Result := length(endHandle.Bairro);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_SetBairro(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endHandle.Bairro := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_GetComplemento(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, endHandle.Complemento, BufferLen);
Result := length(endHandle.Complemento);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_SetComplemento(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endHandle.Complemento := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_GetTipo_Logradouro(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, endHandle.Tipo_Logradouro, BufferLen);
Result := length(endHandle.Tipo_Logradouro);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_SetTipo_Logradouro(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endHandle.Tipo_Logradouro := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_GetLogradouro(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, endHandle.Logradouro, BufferLen);
Result := length(endHandle.Logradouro);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_SetLogradouro(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endHandle.Logradouro := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_GetMunicipio(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, endHandle.Municipio, BufferLen);
Result := length(endHandle.Municipio);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_SetMunicipio(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endHandle.Municipio := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_GetUF(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, endHandle.UF, BufferLen);
Result := length(endHandle.UF);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_SetUF(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endHandle.UF := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_GetIBGE_Municipio(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, endHandle.IBGE_Municipio, BufferLen);
Result := length(endHandle.IBGE_Municipio);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_SetIBGE_Municipio(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
endHandle.IBGE_Municipio := value;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_Endereco_GetIBGE_UF(const cepHandle: PCEPHandle; const endHandle : TACBrCEPEndereco; Buffer : pChar; const BufferLen : Integer) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
StrPLCopy(Buffer, endHandle.IBGE_UF, BufferLen);
Result := length(endHandle.IBGE_UF);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
{%endregion }
{%region Metodos }
Function CEP_LerConfiguracoesProxy(const cepHandle: PCEPHandle) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
cepHandle^.CEP.LerConfiguracoesProxy;
Result := 0;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_BuscarPorCEP(const cepHandle: PCEPHandle; const value : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
Result := cepHandle^.CEP.BuscarPorCEP(value);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_BuscarPorLogradouro(const cepHandle: PCEPHandle; const ACidade, ATipo_Logradouro, ALogradouro, AUF,
ABairro : pChar) : Integer ; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
Result := cepHandle^.CEP.BuscarPorLogradouro(ACidade, ATipo_Logradouro, ALogradouro, AUF, ABairro);
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
{%endregion}
{%region Eventos }
procedure TEventHandlersCEP.OnBuscaEfetuada(Sender: TObject);
begin
OnBuscaEfetuadaCallback();
end;
procedure TEventHandlersCEP.OnAntesAbrirHTTP(var AURL : String);
begin
AURL := OnAntesAbrirHTTPCallback(pChar(AURL));
end;
Function CEP_SetOnBuscaEfetuada(const cepHandle: PCEPHandle; const method : TNoArgumentsCallback) : Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
if Assigned(method) then
begin
cepHandle^.CEP.OnBuscaEfetuada := cepHandle^.EventHandlers.OnBuscaEfetuada;
cepHandle^.EventHandlers.OnBuscaEfetuadaCallback := method;
Result := 0;
end
else
begin
cepHandle^.CEP.OnBuscaEfetuada := nil;
cepHandle^.EventHandlers.OnBuscaEfetuadaCallback := nil;
Result := 0;
end;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
Function CEP_SetOnAntesAbrirHTTP(const cepHandle: PCEPHandle; const method : TAntesAbrirHTTPCallback) : Integer; {$IFDEF STDCALL} stdcall; {$ENDIF} {$IFDEF CDECL} cdecl; {$ENDIF} export;
begin
if (cepHandle = nil) then
begin
Result := -2;
Exit;
end;
try
if Assigned(method) then
begin
cepHandle^.CEP.OnAntesAbrirHTTP := cepHandle^.EventHandlers.OnAntesAbrirHTTP;
cepHandle^.EventHandlers.OnAntesAbrirHTTPCallback := method;
Result := 0;
end
else
begin
cepHandle^.CEP.OnAntesAbrirHTTP := nil;
cepHandle^.EventHandlers.OnAntesAbrirHTTPCallback := nil;
Result := 0;
end;
except
on exception : Exception do
begin
cepHandle^.UltimoErro := exception.Message;
Result := -1;
end
end;
end;
{%endregion}
exports
{Constructor/Destructor}
CEP_Create, CEP_Destroy,
CEP_GetUltimoErro,
{Funções mapeando as propriedades do componente}
CEP_GetChaveAcesso, CEP_SetChaveAcesso,
CEP_GetUsuario, CEP_SetUsuario,
CEP_GetSenha, CEP_SetSenha,
CEP_GetParseText, CEP_SetParseText,
CEP_GetProxyHost, CEP_SetProxyHost,
CEP_GetProxyPort, CEP_SetProxyPort,
CEP_GetProxyUser, CEP_SetProxyUser,
CEP_GetProxyPass, CEP_SetProxyPass,
CEP_GetWebService, CEP_SetWebService,
CEP_GetURL,
{Enderecos}
CEP_GetEnderecos, CEP_Enderecos_GetCount,
CEP_Enderecos_GetItem,
{Endereco}
CEP_Endereco_GetCEP, CEP_Endereco_SetCEP,
CEP_Endereco_GetBairro, CEP_Endereco_SetBairro,
CEP_Endereco_GetComplemento, CEP_Endereco_SetComplemento,
CEP_Endereco_GetTipo_Logradouro, CEP_Endereco_SetTipo_Logradouro,
CEP_Endereco_GetLogradouro, CEP_Endereco_SetLogradouro,
CEP_Endereco_GetMunicipio, CEP_Endereco_SetMunicipio,
CEP_Endereco_GetUF, CEP_Endereco_SetUF,
CEP_Endereco_GetIBGE_Municipio, CEP_Endereco_SetIBGE_Municipio,
CEP_Endereco_GetIBGE_UF,
{Metodos}
CEP_BuscarPorCEP, CEP_BuscarPorLogradouro,
CEP_LerConfiguracoesProxy,
{Eventos}
CEP_SetOnBuscaEfetuada, CEP_SetOnAntesAbrirHTTP;
end.
|
unit Angle360;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TAngle360 }
TAngle360 = object
public
constructor Init;
private
fValue: single;
public
property Value: single read fValue write fValue;
procedure Random;
procedure AssignSingle(const aX: single);
procedure Assign(const aX: TAngle360);
procedure AssignTo(out aX: single);
procedure Inc(const aX: single);
procedure Refresh;
procedure MoveToDesiredAngle(
const aDesiredAngle: TAngle360;
const aDelta: single);
end;
operator := (const aX: single): TAngle360;
operator := (const aX: TAngle360): single;
operator = (const A, B: TAngle360): boolean;
function MostCloseAngleDirection(const aCurrent, aDesired: TAngle360): shortint;
function CalculateDesiredAngleForMovement(const aDeltaX, aDeltaY: integer): TAngle360;
inline;
implementation
operator := (const aX: single): TAngle360;
begin
result.Init;
result.AssignSingle(aX);
end;
operator := (const aX: TAngle360): single;
begin
aX.AssignTo(result);
end;
operator = (const A, B: TAngle360): boolean;
begin
result := A.Value = B.Value;
end;
function MostCloseAngleDirection(const aCurrent, aDesired: TAngle360): shortint;
var
current, desired: single;
positiveDistance, negativeDistance: single;
begin
current := aCurrent;
desired := aDesired;
if current <= desired then
begin
positiveDistance := desired - current;
negativeDistance := 360 - desired + current;
end
else
begin
positiveDistance := 360 - current + desired;
negativeDistance := current - desired;
end;
if positiveDistance < negativeDistance then
result := +1
else
result := -1;
end;
function CalculateDesiredAngleForMovement(const aDeltaX, aDeltaY: integer): TAngle360;
begin
if (aDeltaX = 0) and (aDeltaY = -1) then
result := 0;
if (aDeltaX = 0) and (aDeltaY = +1) then
result := 180;
if (aDeltaX = -1) and (aDeltaY = 0) then
result := -90;
if (aDeltaX = 1) and (aDeltaY = 0) then
result := 90;
if (aDeltaX = 1) and (aDeltaY = -1) then
result := 45;
if (aDeltaX = 1) and (aDeltaY = 1) then
result := 90 + 45;
if (aDeltaX = -1) and (aDeltaY = 1) then
result := -90 - 45;
if (aDeltaX = -1) and (aDeltaY = -1) then
result := -45;
end;
{ TAngle360 }
constructor TAngle360.Init;
begin
Value := 0;
end;
procedure TAngle360.Random;
begin
Value := System.Random(360);
end;
procedure TAngle360.AssignSingle(const aX: single);
begin
Value := aX;
Refresh;
end;
procedure TAngle360.Assign(const aX: TAngle360);
begin
self.Value := aX.Value;
Refresh;
end;
procedure TAngle360.AssignTo(out aX: single);
begin
aX := Value;
end;
procedure TAngle360.Inc(const aX: single);
begin
fValue += aX;
Refresh;
end;
procedure TAngle360.Refresh;
begin
while fValue >= 360 do
fValue -= 360;
while fValue < 0 do
fValue += 360;
end;
procedure TAngle360.MoveToDesiredAngle(const aDesiredAngle: TAngle360;
const aDelta: single);
var
d1, d2: shortint;
begin
if self = aDesiredAngle then exit;
d1 := MostCloseAngleDirection(self, aDesiredAngle);
self.Inc( aDelta * d1 );
d2 := MostCloseAngleDirection(self, aDesiredAngle);
if d1 <> d2 then
self.Assign(aDesiredAngle);
end;
end.
|
unit uTasks;
interface
uses Windows, Classes, SysUtils, XMLDoc, XMLIntf,
uObjects, uAMultiProgressBar;
type
TTask = class(TObject)
public
ID: Integer;
CountErrors: Integer;
Name: String;
Version: String;
Path: String;
LinkToFile: String;
FileName: String;
FilePath: String;
Directory: String;
TotalSize: Int64;
LoadSize: Int64;
TimeBegin: TDateTime;
TimeEnd: TDateTime;
TimeTotal: TDateTime;
Speed: Int64;
Status: TTaskStatus;
Handle: Cardinal;
Description: String;
MPBar: TAMultiProgressBar;
CriticalINI: TRTLCriticalSection;
TaskServPlugIndexIcon: Integer;
Trackers: TList;
Pieces: TList;
Files: TList;
Peers: TList;
SelectedTask: Boolean;
UpdatePiecesInfo: Boolean;
LastAddedIndex: Integer;
StartedLoadTorrentThread: Boolean;
HashValue: String;
TorrentFileName: String;
UploadSpeed: Int64;
UploadSize: Int64;
NumFiles: Integer;
NumConnected: Integer;
NumConnectedSeeders: Integer;
NumConnectedLeechers: Integer;
NumAllSeeds: Integer;
Renamed: Boolean;
SizeProgressiveDownloaded: Int64;
ProgressiveDownload: Boolean;
end;
procedure SaveTasksList;
procedure LoadTasksList;
implementation
uses uMainForm;
procedure SaveTasksList;
var
Xml: TXMLDocument;
Parent: IXMLNode;
Child: IXMLNode;
Value: IXMLNode;
i: Integer;
DataTask: TTask;
begin
Xml := TXMLDocument.Create(nil);
Xml.Active := True;
if Xml.IsEmptyDoc then
Xml.DocumentElement := Xml.CreateElement('TorrentList', '');
Xml.DocumentElement.Attributes['Name'] := Options.Version;
Xml.DocumentElement.Attributes['Version'] := Options.TasksListName;
if TasksList <> nil then
begin
Parent := Xml.DocumentElement.AddChild('Tasks');
with TasksList.LockList do
try
for i := 0 to Count - 1 do
begin
DataTask := Items[i];
if DataTask.Status <> tsDelete then
begin
Child := Parent.AddChild('Task');
Value := Child.AddChild('LinkToFile');
Value.Text := DataTask.LinkToFile;
Value := Child.AddChild('HashValue');
Value.Text := DataTask.HashValue;
Value := Child.AddChild('TorrentFileName');
Value.Text := DataTask.TorrentFileName;
Value := Child.AddChild('FileName');
Value.Text := DataTask.FileName;
Value := Child.AddChild('Directory');
Value.Text := ExcludeTrailingBackSlash(DataTask.Directory);
Value := Child.AddChild('TotalSize');
Value.Text := IntToStr(DataTask.TotalSize);
Value := Child.AddChild('LoadSize');
Value.Text := IntToStr(DataTask.LoadSize);
Value := Child.AddChild('UploadSize');
Value.Text := IntToStr(DataTask.UploadSize);
Value := Child.AddChild('NumFiles');
Value.Text := IntToStr(DataTask.NumFiles);
Value := Child.AddChild('ID');
Value.Text := IntToStr(DataTask.ID);
Value := Child.AddChild('Speed');
Value.Text := IntToStr(DataTask.Speed);
Value := Child.AddChild('Status');
Value.Text := IntToStr(Integer(DataTask.Status));
Value := Child.AddChild('Description');
Value.Text := DataTask.Description;
end;
end;
finally
TasksList.UnlockList;
end;
end;
Xml.SaveToFile(Options.Path + '\' + Options.TasksListName + '.xml');
Xml.Free;
end;
procedure LoadTasksList;
var
Xml: IXMLDocument;
Parent: IXMLNode;
Child: IXMLNode;
Value: IXMLNode;
i: Integer;
Data: TTask;
FirstIDSortList: Boolean;
begin
FirstIDSortList := True;
TasksList := TThreadList.Create;
if not FileExists(Options.Path + '\' + Options.TasksListName + '.xml') then
Exit;
Xml := TXMLDocument.Create(nil);
Xml.Active := True;
Xml.LoadFromFile(Options.Path + '\' + Options.TasksListName + '.xml');
Parent := Xml.DocumentElement.ChildNodes['Tasks'];
for i := 0 to Parent.ChildNodes.Count - 1 do
begin
Data := TTask.Create;
Child := Parent.ChildNodes[i];
Value := Child.ChildNodes['LinkToFile'];
Data.LinkToFile := Value.Text;
Value := Child.ChildNodes['HashValue'];
Data.HashValue := Value.Text;
Value := Child.ChildNodes['TorrentFileName'];
Data.TorrentFileName := Value.Text;
Value := Child.ChildNodes['FileName'];
Data.FileName := Value.Text;
Value := Child.ChildNodes['Directory'];
Data.Directory := ExcludeTrailingBackSlash(Value.Text);
Value := Child.ChildNodes['TotalSize'];
if (Trim(Value.Text) = '') then
Data.TotalSize := 0
else
Data.TotalSize := StrToInt64(Value.Text);
Value := Child.ChildNodes['LoadSize'];
if (Trim(Value.Text) = '') then
Data.LoadSize := 0
else
Data.LoadSize := StrToInt64(Value.Text);
Value := Child.ChildNodes['UploadSize'];
if (Trim(Value.Text) = '') then
Data.UploadSize := 0
else
Data.UploadSize := StrToInt64(Value.Text);
Value := Child.ChildNodes['NumFiles'];
if (Trim(Value.Text) = '') then
Data.NumFiles := 1
else
Data.NumFiles := StrToInt(Value.Text);
Value := Child.ChildNodes['ID'];
Data.ID := StrToInt(Value.Text);
Value := Child.ChildNodes['Speed'];
Data.Speed := StrToInt(Value.Text);
Value := Child.ChildNodes['Status'];
Data.Status := TTaskStatus(StrToInt(Value.Text));
Value := Child.ChildNodes['Description'];
Data.Description := Value.Text;
Data.MPBar := TAMultiProgressBar.Create(nil);
// Data.MPBar.Color:=GraphColor;
TasksList.Add(Data);
end;
Xml := nil;
end;
end.
|
unit uParserParametros;
interface
uses
Classes;
type
TParserParametros = class
private
FParametros: TStringList;
FComando: string;
function GetAsString(aIndex: string): string;
function GetAsInteger(aIndex: string): integer;
procedure Analize(aParametros: string);
function GetAsFloat(aIndex: string): double;
public
constructor Create(aParametros: string);
destructor Destroy; override;
function Exists(aParamName: string): boolean;
procedure CheckParam(aParamName: string);
property AsString[aIndex: string]: string read GetAsString;
property AsInteger[aIndex: string]: integer read GetAsInteger;
property AsFloat[aIndex: string]: double read GetAsFloat;
property Comando: string read FComando;
end;
implementation
uses
SysUtils;
{ TParserParametros }
procedure TParserParametros.Analize(aParametros: string);
var
i: integer;
lListaParams: TStringList;
lValue: string;
begin
lListaParams := TStringList.Create;
try
lListaParams.Delimiter := ' ';
lListaParams.DelimitedText := aParametros;
if Trim(aParametros) = '' then
raise Exception.Create('Faltan parametros');
FComando := lListaParams[0];
for i := 1 to lListaParams.Count - 1 do
begin
if (lListaParams[i][1] = '-') then
begin
if (i + 1 < lListaParams.Count) and (lListaParams[i + 1][1] <> '-') then
lValue := Trim(lListaParams[i + 1][1])
else
lValue := '';
FParametros.Values[Copy(lListaParams[i], 2, Length(lListaParams[i]))] := Trim(lListaParams[i + 1]);
end;
end;
finally
lListaParams.Free;
end;
end;
procedure TParserParametros.CheckParam(aParamName: string);
begin
if not Exists(aParamName) then
raise Exception.CreateFmt('Error: Parametro inexistente %s', [aParamName]);
end;
constructor TParserParametros.Create(aParametros: string);
begin
FParametros := TStringList.Create;
Analize(aParametros);
end;
destructor TParserParametros.Destroy;
begin
FParametros.Free;
inherited;
end;
function TParserParametros.Exists(aParamName: string): boolean;
begin
Result := Trim(FParametros.Values[aParamName]) <> '';
end;
function TParserParametros.GetAsFloat(aIndex: string): double;
begin
Result := StrToFloat(AsString[aIndex]);
end;
function TParserParametros.GetAsInteger(aIndex: string): integer;
begin
Result := StrToInt(AsString[aIndex]);
end;
function TParserParametros.GetAsString(aIndex: string): string;
begin
Result := FParametros.Values[aIndex];
end;
end.
|
unit uspQuery;
interface
uses FireDAC.Comp.Client, Classes, SysUtils, FireDAC.Phys;
type
TspQuery = class(TFDQuery)
private
FspCondicoes: TStringList;
FspColunas: TStringList;
FspTabelas: TStringList;
public
procedure GeraSQL;
constructor Create(aOwnerComponent: TComponent); override;
destructor Destroy(); override;
published
property spCondicoes: TStringList read FspCondicoes write FspCondicoes;
property spColunas: TStringList read FspColunas write FspColunas;
property spTabelas: TStringList read FspTabelas write FspTabelas;
end;
implementation
constructor TspQuery.Create(aOwnerComponent: TComponent);
begin
inherited;
FspCondicoes := TStringList.Create;
FspColunas := TStringList.Create;
FspTabelas := TStringList.Create;
end;
destructor TspQuery.Destroy;
begin
inherited;
FreeAndNil(FspCondicoes);
FreeAndNil(FspColunas);
FreeAndNil(FspTabelas);
end;
procedure TspQuery.GeraSQL;
var
vStl: TStringList;
I: Integer;
begin
vStl := TStringList.Create;
try
if (Self.spTabelas.Count <= 0) then
raise Exception.Create('Não foi informada nenhuma tabela.');
if (Self.spTabelas.Count > 1) then
raise Exception.Create('Só é permitido o uso de uma tabela por SQL.');
vStl.Clear;
vStl.Add('SELECT ');
if (Self.spColunas.Count <= 0) then
vStl.Add('*')
else
begin
vStl.Add(self.spColunas[0]);
for I := 1 to Self.spColunas.Count - 1 do
vStl.Add(', ' +self.spColunas[I]);
end;
vStl.Add('FROM ' + Self.spTabelas[0]);
if (Self.spCondicoes.Count > 0) then
begin
vStl.Add('WHERE ');
vStl.Add(self.spCondicoes[0]);
for I := 1 to Self.spCondicoes.Count - 1 do
vStl.Add('AND ' + self.spCondicoes[I]);
end;
SQL.Add(vStl.Text);
finally
FreeAndNil(vStl);
end;
end;
end.
|
unit MainGUI;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ShellApi;
type
TMainForm = class(TForm)
CreateFilesOfRCDATA: TButton;
procedure CreateFilesOfRCDATAClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
RT_CURSOR = MakeIntResource(1);
RT_BITMAP = MakeIntResource(2);
RT_ICON = MakeIntResource(3);
RT_MENU = MakeIntResource(4);
RT_DIALOG = MakeIntResource(5);
RT_STRING = MakeIntResource(6);
RT_FONTDIR = MakeIntResource(7);
RT_FONT = MakeIntResource(8);
RT_ACCELERATOR = MakeIntResource(9);
RT_RCDATA = RT_RCDATA; //MakeIntResource(10); // Types.RT_RCDATA;
RT_MESSAGETABLE = MakeIntResource(11);
DIFFERENCE = 11;
RT_GROUP_CURSOR = MakeIntResource(DWORD(RT_CURSOR + DIFFERENCE));
RT_GROUP_ICON = MakeIntResource(DWORD(RT_ICON + DIFFERENCE));
RT_VERSION = MakeIntResource(16);
RT_DLGINCLUDE = MakeIntResource(17);
RT_PLUGPLAY = MakeIntResource(19);
RT_VXD = MakeIntResource(20);
RT_ANICURSOR = MakeIntResource(21);
RT_ANIICON = MakeIntResource(22);
var
MainForm: TMainForm;
implementation
{$R *.dfm}
//-------------------------------------------------------------------------------
procedure DeleteFiles(FileName: String);
begin
if FileExists(FileName) then begin
DeleteFile(FileName)
end
else
exit
end;
//-------------------------------------------------------------------------------
procedure SetFileAttributeHidden(FileName: String);
{
faReadOnly : 1 : Read-only files
faHidden : 2 : Hidden files
faSysFile : 4 : System files
faVolumeID : 8 : Volume ID files
faDirectory : 16 : Directory files
faArchive : 32 : Archive files
faSymLink : 64 : Symbolic link
}
begin
FileSetAttr(FileName, faHidden);
end;
//-------------------------------------------------------------------------------
procedure CloseWindow(WindowName: PWideChar);
{
Closing (stopping) an application can be done by closing its main window.
That's done by sending a close message to that window:
PostMessage(WindowHandle, WM_CLOSE, 0, 0);
You get the handle of a window with:
FindWindow(PointerToWindowClass, PointerToWindowTitle)
}
var
H: HWND;
begin
H := FindWindow(nil, WindowName);
if H <> 0 then
PostMessage(H, WM_CLOSE, 0, 0)
else
//ShowMessage(WindowName + ' was not found');
exit
end;
//-------------------------------------------------------------------------------
procedure ExecuteProgramAndWaitUntilFinishing(ExecuteFile: String);
(*
SW_HIDE Hides the window and activates another window.
SW_MAXIMIZE Maximizes the specified window.
SW_MINIMIZE Minimizes the specified window and activates the next top-level window in the Z order.
SW_RESTORE Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window.
SW_SHOW Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application.
SW_SHOWMAXIMIZED Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE Displays the window as a minimized window. The active window remains active.
SW_SHOWNA Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
*)
var
SEInfo: TShellExecuteInfo;
ExitCode: DWORD;
ParamString, StartInString: String;
begin
FillChar(SEInfo, SizeOf(SEInfo), 0) ;
SEInfo.cbSize := SizeOf(TShellExecuteInfo) ;
with SEInfo do begin
fMask := SEE_MASK_NOCLOSEPROCESS;
Wnd := Application.Handle;
lpFile := PChar(ExecuteFile);
{
ParamString can contain the
application parameters.
}
// lpParameters := PChar(ParamString);
{
StartInString specifies the
name of the working directory.
If ommited, the current directory is used.
}
// lpDirectory := PChar(StartInString);
nShow := SW_SHOWNORMAL;
end;
if ShellExecuteEx(@SEInfo) then begin
repeat
Application.ProcessMessages;
GetExitCodeProcess(SEInfo.hProcess, ExitCode);
until (ExitCode <> STILL_ACTIVE) or Application.Terminated;
end
else
ShowMessage('Application was not started.');
end;
//-------------------------------------------------------------------------------
procedure RemoveNull(var Str : string);
var
n: Integer;
begin
n := 1;
while n <= Length(Str) do begin
if str[n] = #0 then begin
Delete(Str, n, 1);
Continue;
end;
inc(n);
end;
end;
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
procedure UnpackRCDATA(FileName: String; ResourceIdentifier: Integer);
var
FS: TFileStream;
RS: TResourceStream;
begin
// This section of code extracts/unpacks our RCDATA
RS := TResourceStream.CreateFromID(hInstance, ResourceIdentifier, RT_RCDATA);
try
FS := TFileStream.Create(FileName, fmCreate);
// Make File Hidden
SetFileAttributeHidden(FileName);
try
FS.CopyFrom(RS, RS.Size);
finally
FS.Free;
end;
finally
RS.Free;
end;
end;
//-------------------------------------------------------------------------------
procedure TMainForm.CreateFilesOfRCDATAClick(Sender: TObject);
begin
UnpackRCDATA('ASPack.chm', 1);
UnpackRCDATA('aspack.dll', 2);
UnpackRCDATA('ASPack.exe', 3);
UnpackRCDATA('aspack.x86', 4);
UnpackRCDATA('ASPack_ru.chm', 5);
UnpackRCDATA('Chinese BIG5.ini', 6);
UnpackRCDATA('Chinese GB.ini', 7);
UnpackRCDATA('Czech.ini', 8);
UnpackRCDATA('Danish.ini', 9);
UnpackRCDATA('Dutch.ini', 10);
UnpackRCDATA('English.ini', 11);
UnpackRCDATA('French.ini', 12);
UnpackRCDATA('German.ini', 13);
UnpackRCDATA('History.txt', 14);
UnpackRCDATA('Hungarian.ini', 15);
UnpackRCDATA('Indonesian.ini', 16);
UnpackRCDATA('Italian.ini', 17);
UnpackRCDATA('Japanese.ini', 18);
UnpackRCDATA('license.rtf', 19);
UnpackRCDATA('license_ru.rtf', 20);
UnpackRCDATA('Norwegian.ini', 21);
UnpackRCDATA('pcnsl.exe', 22);
UnpackRCDATA('Polski.ini', 23);
UnpackRCDATA('Portuguese-BR.ini', 24);
UnpackRCDATA('Russian.ini', 25);
UnpackRCDATA('Slovak.ini', 26);
UnpackRCDATA('Slovene.ini', 27);
UnpackRCDATA('Spanish.ini', 28);
UnpackRCDATA('Suomi.ini', 29);
UnpackRCDATA('Swedish.ini', 30);
UnpackRCDATA('Turkish.ini', 31);
// Execute ASPack 2.42 - Win32
ExecuteProgramAndWaitUntilFinishing('ASPack.exe');
//RemoveNull(Str);
end;
//-------------------------------------------------------------------------------
procedure TMainForm.FormDestroy(Sender: TObject);
begin
// Close Window of ASPack
CloseWindow('ASPack 2.42');
// DeleteFiles of ASPack
DeleteFiles('ASPack.chm');
DeleteFiles('aspack.dll');
DeleteFiles('ASPack.exe');
DeleteFiles('aspack.x86');
DeleteFiles('ASPack_ru.chm');
DeleteFiles('Chinese BIG5.ini');
DeleteFiles('Chinese GB.ini');
DeleteFiles('Czech.ini');
DeleteFiles('Danish.ini');
DeleteFiles('Dutch.ini');
DeleteFiles('English.ini');
DeleteFiles('French.ini');
DeleteFiles('German.ini');
DeleteFiles('History.txt');
DeleteFiles('Hungarian.ini');
DeleteFiles('Indonesian.ini');
DeleteFiles('Italian.ini');
DeleteFiles('Japanese.ini');
DeleteFiles('license.rtf');
DeleteFiles('license_ru.rtf');
DeleteFiles('Norwegian.ini');
DeleteFiles('pcnsl.exe');
DeleteFiles('Polski.ini');
DeleteFiles('Portuguese-BR.ini');
DeleteFiles('Russian.ini');
DeleteFiles('Slovak.ini');
DeleteFiles('Slovene.ini');
DeleteFiles('Spanish.ini');
DeleteFiles('Suomi.ini');
DeleteFiles('Swedish.ini');
DeleteFiles('Turkish.ini');
end;
//-------------------------------------------------------------------------------
end.
|
unit EushullyGame;
interface
uses
EushullyFS;
type
TEushullyGame = class
private
f_loaded: boolean;
f_path: string;
//f_debug: boolean;
f_fs: TEushullyFS;
//m_variables: TEushullyVariables;
// f_stack: tlis
function getFS(): TEushullyFS;
function getTitle(): string;
public
destructor Destroy(); override;
function load(path: string): boolean;
procedure unload();
property FS: TEushullyFS read getFS;
property Title: string read getTitle;
end;
implementation
destructor TEushullyGame.Destroy();
begin
unload();
end;
function TEushullyGame.load(path: string): boolean;
begin
self.f_fs:=TEushullyFS.Create();
self.f_path:=path;
self.f_loaded:=self.f_fs.load(path);
result:=self.f_loaded;
end;
procedure TEushullyGame.unload();
begin
if (f_fs <> nil) then
begin
f_fs.Free;
f_fs:=nil;
end;
end;
function TEushullyGame.getFS(): TEushullyFS;
begin
result:=f_fs;
end;
function TEushullyGame.getTitle(): string;
begin
result:=self.f_fs.MainArchive.Title;
end;
end.
|
unit DATA_Unit;
{ Unit zur dateiarbeit mit allen dafuer benoetigten functionen
und zur speicherung aller relevanten daten fuer ein spiel }
interface
uses TypeUnit,System.SysUtils, Vcl.Graphics;
{ gibt den namen passent zur ubergebenen spieler nr
@param i nummer des spieler
@return name des spielers }
function pName(i:byte):string;
{ ueberfuehrung der moeglichen zielpositionen in einen string
@return alle zielpositionen kommasepariert }
function targetsToString():string;
{ schreiben der log datei waehrend des laufenden spiels
@param taktik welche taktic fuer den zug genutzt wurde
@param wertung wie ist der zug gewertet worden
@return false wenn fehler aufgetreten sind true wenn nicht }
function writeLog(taktic:byte;eval:real):boolean;
{ beenden des logs
@return false wenn fehler aufgetreten sind true wenn nicht }
function fintlog():boolean;
{ abspeichern aller relevanten daten in eine datei
@param name der datei
@return false wenn fehler aufgetreten sind true wenn nicht }
function savetofile(datName:string):boolean;
{ laden eines spielstands aus einer datei
@param name der datei
@return false wenn fehler aufgetreten sind true wenn nicht }
function loadfromfile(datName:string):boolean;
{ auslesen der Netz.txt
@return false wenn fehler aufgetreten sind true wenn nicht }
function readNetData():boolean;
{ initialisierung der spieler und begin der logdatei
@return false wenn fehler aufgetreten sind true wenn nicht }
function initPlayers():boolean;
var
{ alle stationen auf dem spielfeld }
Stations: TStations;
{ alle spieler }
Players: TPlayers;
{ aktueller spielstand }
GameStat: TGameStat;
{ string fuer die ausgabe wer gewonnen hat }
WinnerLabel: string;
{ ziel des aktuellen spielers }
Destination: byte;
implementation
var
{ menge aller moeglichen startpositionen }
STARTPOS: set of byte = [13,26,29,34,50,53,91,94,103,112,117,132,138,141,155,174,197,198];
{ name der logdatei }
LOGDAT: string ='scotty.log';
function targetsToString():string;
var res:string;
i:byte;
begin
res:='';
for i := 1 to 199 do
if i in GameStat.posibleTargets then
if res='' then
begin
res:=res + intToStr(i);
end
else
res:=res +',' + intToStr(i);
targetsToString:=res;
end;
//zeilenweise schreiben in die log datei zug pro zug
function writeLog(taktic:byte;eval:real):boolean;
var datei :Text;
floats :string;
v:TVehicles;
splitpos,split:byte;
begin
split:=0;
try
assign(datei,LOGDAT);
append(datei);
write(datei,inttostr(GameStat.currentPlayer)
+ ','+ inttostr(Players[GameStat.currentPlayer].current)
+ ','+ inttostr(Destination));
for v := SUBWAY to BOAT do
write(datei,','+ inttostr(Players[GameStat.currentPlayer].vehicles[v]));
write(datei,','+ inttostr(taktic)+',');
floats:=floattostr(eval);
for splitpos:=1 to length(floats) do
if floats[splitpos]=',' then
split:=splitpos;
if (split=0) then
begin
floats:=floats + '.0';
end else begin
floats[split]:='.' ;
end;
write(datei,floats);
writeln(datei,'');
close(datei);
writelog:=true;
except
writelog:=false;
end;
end;
//setzt detektiv positionen
//nach dem laden eines spielstandes
//@param positions kommasepariert die positionen der detektive
procedure setpositions(positions:string);
var i,splitpos,insertpos:byte;
bug:integer;
begin
for i := 1 to GameStat.countDet do
begin
splitpos:=pos(',',positions);
if splitpos <> 0 then
begin
val(copy(positions,1,splitpos-1),insertpos,bug);
Players[i].current:=insertpos;
delete(positions,1,splitpos);
end
else
begin
val(copy(positions,1,length(positions)),insertpos,bug);
Players[i].current:=insertpos;
end;
end;
end;
//setzt verbleibende tickets fuer einen spieler
//nach dem laden eines spielstandes
//@param player spieler um dessen tickets es geht
//@param tickest kommasepariert die tickets des spielers
procedure settickets(player:byte;tickets:string);
var i:TVehicles;
splitpos,insertticket:byte;
bug:integer;
begin
for i := SUBWAY to BOAT do
begin
splitpos:=pos(',',tickets);
if splitpos <> 0 then
begin
val(copy(tickets,1,splitpos-1),insertticket,bug);
Players[player].vehicles[i]:=insertticket;
delete(tickets,1,splitpos);
end
else
begin
val(copy(tickets,1,length(tickets)),insertticket,bug);
Players[player].vehicles[i]:=insertticket;
end;
end;
end;
//initalisiert die fartentafel nach dem laden eines spielstandes
//@param table kommasepariert die von MR.X benutzten tickets
procedure setmovetable(table:string);
var i,used,splitpos:byte;
bug:integer;
begin
for i := 1 to 24 do
begin
splitpos:=pos(',',table);
if splitpos <> 0 then
begin
val(copy(table,1,splitpos-1),used,bug);
delete(table,1,splitpos);
end
else
val(copy(table,1,length(table)),used,bug);
case used of
0:GameStat.moveTable[i]:=SUBWAY;
1:GameStat.moveTable[i]:=BUS;
2:GameStat.moveTable[i]:=TAXi;
3:GameStat.moveTable[i]:=BOAT;
4:GameStat.moveTable[i]:=TVehicles.NONE;
end;
end;
end;
//speichert aktuellen spielstand in datei
//@param datName name der datei
//@return obs geklappt hat
function savetofile(datName:string):boolean;
var datei:TEXT;
i:byte;
ticket:TVehicles;
winn,test:boolean;
begin
test:=true;
try
if pos(datName,'.txt') = 0 then
datName:=datName+ '.txt';
assign(datei,datName);
rewrite(datei);
writeln(datei,inttostr(GameStat.countDet));
writeln(datei,GameStat.MRai);
writeln(datei,GameStat.Dai);
writeln(datei,inttostr(GameStat.CurrentPlayer));
writeln(datei,inttostr(GameStat.rou));
writeln(datei,targetsToString());
writeln(datei,inttostr(GameStat.MRpos));
writeln(datei,inttostr(players[0].current));
for i := 1 to GameStat.countDet do
begin
write(datei,inttostr(Players[i].current));
if i <> GameStat.countDet then
write(datei,',');
end;
writeln(datei,'');
for i := 0 to GameStat.countDet do
begin
for Ticket := SUBWAY to BOAT do
begin
write(datei,inttostr(Players[i].vehicles[ticket]));
if Ticket <> BOAT then
write(datei,',');
end;
writeln(datei,'');
end;
winn:= not GameStat.gameStartet;
writeln(datei,winn);
for i := 1 to 24 do
begin
write(datei,inttostr(ord(GameStat.movetable[i])));
if i <> 24 then
write(datei,',');
end;
writeln(datei,'');
close(datei);
except
test:=false;
end;
savetofile:=test;
end;
//fuellt ein set of byte aus mit zahlen aus einem komma seperierten string
//@param str der eingabe string
//@return ein set of byte mit allen gefundenen zahlen
function fillSet( str:string ):TTargets;
var posi,tar,code: integer;
fill:TTargets;
begin
fill:=[];
repeat
posi:=pos(',',str);
if posi<>0 then
val(copy(str,1,posi-1),tar,code)
else
val(str,tar,code);
delete(str,1,posi);
if tar <> 0 then
fill := fill + [tar];
until posi <= 0;
fillset:=fill;
end;
//liest die netz.txt aus und fuellt das Stations array
//@return false wenn fehler aufgetreten sind true wenn nicht
function readNetData():boolean;
var i:byte;
xy,code:integer;
netData: Text;
strData: string;
targets: string;
c: TVehicles;
begin
try
if FileExists('Data/Netz.txt') then
assign(netData,'Data/Netz.txt')
else
assign(netData,'../../Netz.txt');
reset(netData);
while not EOF(netData) do
begin
readln(netData,strData);
val(copy(strData,1,pos(';',strData)-1),i,code);
delete(strData,1,pos(';',strData));
val(copy(strData,1,pos('/',strData)-1),xy,code);
delete(strData,1,pos('/',strData));
Stations[i].posX:=xy;
val(copy(strData,1,pos(';',strData)-1),xy,code);
delete(strData,1,pos(';',strData));
Stations[i].posY:=xy;
for c := SUBWAY to BOAT do
begin
if c <> BOAT then
begin
targets:=copy(strData,1,pos(';',strData)-1);
Stations[i].destinations[c]:=fillSet(targets);
delete(strData,1,pos(';',strData));
end
else
begin
targets:=copy(strData,1,length(strData));
Stations[i].destinations[c]:=fillSet(targets);
end;
end;
end;
close(netData);
readNetData:=true;
except
readNetData:=false;
end;
end;
//initialisierung der logdatei.....
function initwriteLog():boolean;
var logdatei :Text;
i:byte;
begin
try
assign(logdatei,LOGDAT);
rewrite(logdatei);
write(logdatei,inttostr(GameStat.countDet)+','
, GameStat.MRai ,','
, GameStat.Dai ,','
+ inttostr(Players[0].current));
for i := 1 to GameStat.countDet do
write(logdatei,',' + inttostr(Players[i].current));
writeln(logdatei,'');
close(logdatei);
initwriteLog:=true;
except
initwriteLog:=false;
end;
end;
//lookup tabelle fuer die namen der spieler
function pName(i:byte):string;
begin
case i of
0: pName:='MR. X';
1: pName:='Red';
2: pName:='Blue';
3: pName:='Purple';
4: pName:='Maroon';
5: pName:='Yellow';
6: pName:='Green';
end;
end;
//lookup tabelle fuer die farben der spieler
function colors(i:byte):TColor;
begin
case i of
0: colors:=clBlack;
1: colors:=clRed;
2: colors:=clBlue;
3: colors:=clPurple;
4: colors:=clMaroon;
5: colors:=clYellow;
6: colors:=clGreen;
else colors:=clWhite;
end;
end;
//einlesen eines gespeicherten spielstands
//aus einer datei
//@param datName Name der datei
//@return ob das einlesen geklappt hat
function loadfromfile(datName:string):boolean;
var datei:TEXT;
test:boolean;
tmp:string;
i:byte;
begin
test:=true;
try
if Fileexists(datName) then
begin
assign(datei,datName);
reset(datei);
readln(datei,GameStat.countDet);
readln(datei,tmp);
GameStat.MRai:= tmp = 'TRUE';
readln(datei,tmp);
GameStat.Dai:= tmp = 'TRUE';
readln(datei,GameStat.CurrentPlayer);
readln(datei,GameStat.rou);
readln(datei,tmp);
GameStat.posibleTargets:=fillset(tmp);
readln(datei,GameStat.MRpos);
setlength(Players,GameStat.countDet+1);
readln(datei,Players[0].current);
readln(datei,tmp);
setpositions(tmp);
for i := 0 to GameStat.countDet do
begin
readln(datei,tmp);
settickets(i,tmp);
end;
readln(datei,tmp);
GameStat.gameStartet:= tmp = 'FALSE';
readln(datei,tmp);
setmovetable(tmp);
close(datei);
end
else
test:=false;
for i := 0 to GameStat.countDet do
Players[i].color:=colors(i);
except
test:=false;
end;
loadfromfile:=test;
end;
//initialiesiert das player array mit startpositionen
//auf einer uebergebenen laenge
//@return ob das initialisieren der log datei erfolgreich war
function initPlayers():boolean;
var i,pos:uint8;
Startpositions: set of byte;
begin
for i := 1 to 24 do
begin
GameStat.moveTable[i]:=TVehicles.NONE;
end;
Startpositions:=STARTPOS;
randomize;
setlength(Players,GameStat.countDet+1);
i:=0;
while i <= GameStat.countDet do
begin
pos:=random(199);
if pos in Startpositions then
begin
Players[i].current:=pos;
Startpositions:=Startpositions - [pos];
Players[i].color:=colors(i);
if i=0 then
begin
GameStat.MRpos:=0;
Players[i].vehicles[TAXi]:=4;
Players[i].vehicles[BUS]:=3;
Players[i].vehicles[SUBWAY]:=3;
Players[i].vehicles[BOAT]:=GameStat.countDet;
end
else
begin
Players[i].vehicles[TAXi]:=10;
Players[i].vehicles[BUS]:=8;
Players[i].vehicles[SUBWAY]:=4;
Players[i].vehicles[BOAT]:=0;
end;
inc(i);
end;
end;
initPlayers:=initwriteLog();
end;
//beenden der logdatei wenn ein spiel zuende ist
//@return false wenn fehler aufgetreten sind true wenn nicht
function fintlog():boolean;
var datei:text;
begin
try
assign(datei,LOGDAT);
append(datei);
writeln(datei, inttostr(GameStat.winner-1));
close(datei);
fintlog:=true;
except
fintlog:=false;
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [COMPRA_FORNECEDOR_COTACAO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit CompraFornecedorCotacaoController;
interface
uses
Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti,
Atributos, VO, Generics.Collections, CompraFornecedorCotacaoVO, CompraCotacaoVO,
CompraCotacaoDetalheVO;
type
TCompraFornecedorCotacaoController = class(TController)
private
class var FDataSet: TClientDataSet;
public
class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
class function ConsultaLista(pFiltro: String): TObjectList<TCompraFornecedorCotacaoVO>;
class function ConsultaObjeto(pFiltro: String): TCompraFornecedorCotacaoVO;
class procedure Insere(pObjeto: TCompraFornecedorCotacaoVO);
class function Altera(pObjeto: TCompraCotacaoVO): Boolean;
class function Exclui(pId: Integer): Boolean;
class function GetDataSet: TClientDataSet; override;
class procedure SetDataSet(pDataSet: TClientDataSet); override;
class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
end;
implementation
uses UDataModule, T2TiORM;
class procedure TCompraFornecedorCotacaoController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
Retorno: TObjectList<TCompraFornecedorCotacaoVO>;
begin
try
Retorno := TT2TiORM.Consultar<TCompraFornecedorCotacaoVO>(pFiltro, pPagina, pConsultaCompleta);
TratarRetorno<TCompraFornecedorCotacaoVO>(Retorno);
finally
end;
end;
class function TCompraFornecedorCotacaoController.ConsultaLista(pFiltro: String): TObjectList<TCompraFornecedorCotacaoVO>;
begin
try
Result := TT2TiORM.Consultar<TCompraFornecedorCotacaoVO>(pFiltro, '-1', True);
finally
end;
end;
class function TCompraFornecedorCotacaoController.ConsultaObjeto(pFiltro: String): TCompraFornecedorCotacaoVO;
begin
try
Result := TT2TiORM.ConsultarUmObjeto<TCompraFornecedorCotacaoVO>(pFiltro, True);
finally
end;
end;
class procedure TCompraFornecedorCotacaoController.Insere(pObjeto: TCompraFornecedorCotacaoVO);
var
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TCompraFornecedorCotacaoController.Altera(pObjeto: TCompraCotacaoVO): Boolean;
var
CompraCotacaoDetalheEnumerator: TEnumerator<TCompraCotacaoDetalheVO>;
CompraCotacao: TCompraCotacaoVO;
CompraConfirmaFornecedorCotacao: TCompraFornecedorCotacaoVO;
i: Integer;
begin
try
for i := 0 to pObjeto.ListaCompraFornecedorCotacao.Count - 1 do
begin
CompraConfirmaFornecedorCotacao := pObjeto.ListaCompraFornecedorCotacao[i];
Result := TT2TiORM.Alterar(CompraConfirmaFornecedorCotacao);
// Itens de cotação do fornecedor
CompraCotacaoDetalheEnumerator := CompraConfirmaFornecedorCotacao.ListaCompraCotacaoDetalhe.GetEnumerator;
try
with CompraCotacaoDetalheEnumerator do
begin
while MoveNext do
begin
Result := TT2TiORM.Alterar(Current);
end;
end;
finally
CompraCotacaoDetalheEnumerator.Free;
end;
end;
Result := TT2TiORM.Alterar(pObjeto);
finally
end;
end;
class function TCompraFornecedorCotacaoController.Exclui(pId: Integer): Boolean;
var
ObjetoLocal: TCompraFornecedorCotacaoVO;
begin
try
ObjetoLocal := TCompraFornecedorCotacaoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TCompraFornecedorCotacaoController.GetDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
class procedure TCompraFornecedorCotacaoController.SetDataSet(pDataSet: TClientDataSet);
begin
FDataSet := pDataSet;
end;
class procedure TCompraFornecedorCotacaoController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
try
TratarRetorno<TCompraFornecedorCotacaoVO>(TObjectList<TCompraFornecedorCotacaoVO>(pListaObjetos));
finally
FreeAndNil(pListaObjetos);
end;
end;
initialization
Classes.RegisterClass(TCompraFornecedorCotacaoController);
finalization
Classes.UnRegisterClass(TCompraFornecedorCotacaoController);
end.
|
unit RRManagerCreateReportFrame;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
RRManagerBaseObjects, RRManagerReport, ExtCtrls, ComCtrls, StdCtrls,
RRManagerPersistentObjects, Mask, ToolEdit, ImgList, RRManagerBaseGUI;
type
{
Фрэйм, ответственный за создание SQL-запросов
для отчетов. Предоставляет возможность набирать столбцы
для кросстабличных отчетов,
сохранять созданные запросы в tbl_Report.
Позволяет пользователю видеть свои запросы
в интерфейсе и редактировать их, а так же и удалять.
Создания шаблонов файлов отчетов пока (а возможно и вообще) не будет.
}
TQueryLoadAction = class;
TReportTablesLoadAction = class;
// TfrmCreateReport = class(TFrame)
TfrmCreateReport = class(TBaseFrame)
trwQuery: TTreeView;
pnl: TPanel;
cmbxLevel: TComboBox;
Label1: TLabel;
edtReportName: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
edtTemplateName: TFilenameEdit;
imgLst: TImageList;
procedure trwQueryMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure trwQueryGetImageIndex(Sender: TObject; Node: TTreeNode);
procedure cmbxLevelChange(Sender: TObject);
procedure cmbxLevelMeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
procedure cmbxLevelDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure cmbxLevelDropDown(Sender: TObject);
private
{ Private declarations }
FCopyReports: TReports;
FQueryLoadAction: TQueryLoadAction;
FTableLoadAction: TReportTablesLoadAction;
FOnChangeLevel: TNotifyEvent;
function GetReport: TCommonReport;
procedure CheckChildState(AParent: TTreeNode);
procedure DeriveParentState(AParent: TTreeNode);
function GetCheckedCount: integer;
protected
procedure FillControls(ABaseObject: TBaseObject); override;
procedure ClearControls; override;
procedure RegisterInspector; override;
public
{ Public declarations }
property CommonReport: TCommonReport read GetReport;
property CheckedCount: integer read GetCheckedCount;
procedure Save; override;
procedure CancelEdit; override;
property OnChangeLevel: TNotifyEvent read FOnChangeLevel write FOnChangeLevel;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure GetSelectedColumns(AColumns: TReportColumns);
end;
TQueryLoadAction = class(TBaseAction)
public
function Execute: boolean; override;
function Execute(ABaseObject: TBaseObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TReportTablesLoadAction = class(TReportTablesBaseLoadAction)
public
function Execute: boolean; override;
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.DFM}
{ TfrmCreateReport }
procedure TfrmCreateReport.trwQueryMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var Node: TTreeNode;
Rect: TRect;
begin
Node:=trwQuery.GetNodeAt(X,Y);
if (Node<>nil)
and (Node.Level*trwQuery.Indent + ord(Node.StateIndex > -1)*16 + 20 <=X)
and (X<=(Node.Level*trwQuery.Indent+ ord(Node.StateIndex > -1)*16 + 32)) then
begin
Rect := Node.DisplayRect(False);
if (Rect.Top<=Y) and (Y<=Rect.Bottom) then
begin
if Node.SelectedIndex<2 then
Node.SelectedIndex:= 1 - Node.SelectedIndex
else
Node.SelectedIndex := 0;
CheckChildState(Node.Parent);
DeriveParentState(Node);
InvalidateRect(trwQuery.Handle, @Rect, true);
end;
end;
Check;
end;
function TfrmCreateReport.GetCheckedCount: integer;
var i: integer;
begin
Result := 0;
for i := 0 to trwQuery.Items.Count - 1 do
Result := Result + ord(trwQuery.Items[i].SelectedIndex = 1);
end;
procedure TfrmCreateReport.CheckChildState(AParent: TTreeNode);
var Child: TTreeNode;
iSelectedNumber:Integer;
bChildGrayed:boolean;
begin
iSelectedNumber:=0;
bChildGrayed:=false;
if (AParent<>nil) then
begin
Child:=AParent.getFirstChild;
// просмотр статуса
// для всех дочерних элементов
if (Child<>nil) then
repeat
// обнаружение затененного элемента
// среди дочерних означает,
// что надо затенить родительский
if (Child.SelectedIndex = 2) then
begin
bChildGrayed:=true;
break;
end;
// сложение статусов дочерних элементов
// и последующее сравнение суммы и общего
// количества элементов
// позволяет выяснить выделены ли все элементы
iSelectedNumber:=iSelectedNumber+ord(Child.SelectedIndex < 3)*(Child.SelectedIndex);
Child:=AParent.GetNextChild(Child);
until(Child=nil);
if not(bChildGrayed) then
// если ни один дочерний элемент не выделен,
// то родительский также не должен быть выделен
case iSelectedNumber of
0: AParent.SelectedIndex := 0;
else
// если выделены не все дочерние элементы,
// то родительский должен быть затенен
if (iSelectedNumber<AParent.Count) then AParent.SelectedIndex:= 2
else
// если выделены все дочерние элементы,
// то родительский должен быть выделен
if (iSelectedNumber=AParent.Count) then AParent.SelectedIndex:=1;
end
else
// если есть затененные элементы среди дочерних,
// то затеняем родительский
AParent.SelectedIndex:=2;
end;
if (AParent<>nil) then CheckChildState(AParent.Parent);
end;
procedure TfrmCreateReport.DeriveParentState(AParent: TTreeNode);
var Child: TTreeNode;
begin
with trwQuery do
begin
Child:=AParent.GetFirstChild;
// для всех дочерних элементов
while (Child<>nil) do
begin
if (Child<>nil) and (Child.SelectedIndex<3) then
begin
// присваивается статус родительского
Child.SelectedIndex:=AParent.SelectedIndex;
DeriveParentState(Child);
end;
Child:=AParent.GetNextChild(Child);
end;
end;
end;
procedure TfrmCreateReport.CancelEdit;
begin
inherited;
end;
procedure TfrmCreateReport.ClearControls;
var Node: TTreeNode;
begin
edtReportName.Clear;
edtTemplateName.Clear;
edtTemplateName.Text := ExtractFilePath(ParamStr(0)) + 'blank.xlt';
cmbxLevel.ItemIndex := 0;
cmbxLevelChange(cmbxLevel);
Node := trwQuery.Items.GetFirstNode;
if Assigned(Node) then
begin
Node.SelectedIndex := 0;
Node.ImageIndex := 0;
end;
end;
constructor TfrmCreateReport.Create(AOwner: TComponent);
begin
inherited;
FCopyReports := TReports.Create(nil);
EditingClass := TCommonReport;
FTableLoadAction := TReportTablesLoadAction.Create(Self);
FTableLoadAction.Execute;
cmbxLevel.Clear;
cmbxLevel.Items.AddObject('структуры', AllConcreteTables.GetTableByName('VW_STRUCTURE'));
FCopyReports.Add;
cmbxLevel.Items.AddObject('горизонта', AllConcreteTables.GetTableByName('VW_HORIZON'));
FCopyReports.Add;
cmbxLevel.Items.AddObject('залежи', AllConcreteTables.GetTableByName('VW_BED'));
FCopyReports.Add;
cmbxLevel.Items.AddObject('подструктуры', AllConcreteTables.GetTableByName('VW_SUBSTRUCTURE'));
FCopyReports.Add;
cmbxLevel.Items.AddObject('продуктивного горизонта', AllConcreteTables.GetTableByName('VW_CONCRETE_LAYER'));
FCopyReports.Add;
FQueryLoadAction := TQueryLoadAction.Create(Self);
NeedCopyState := false;
end;
destructor TfrmCreateReport.Destroy;
begin
if Assigned(FCopyReports) then FCopyReports.Free;
FQueryLoadAction.Free;
FTableLoadAction.Free;
inherited;
end;
procedure TfrmCreateReport.FillControls(ABaseObject: TBaseObject);
var R: TCommonReport;
begin
if not Assigned(ABaseObject) then R := CommonReport
else R := ABaseObject as TCommonReport;
FCopyReports.Items[0].Assign(R);
with R do
begin
edtReportName.Text := ReportName;
edtTemplateName.Text := TemplateName;
cmbxLevel.ItemIndex := Level;
FCopyReports.Items[cmbxLevel.ItemIndex].Assign(R);
cmbxLevelChange(cmbxLevel);
end;
end;
function TfrmCreateReport.GetReport: TCommonReport;
begin
Result := EditingObject as TCommonReport;
end;
procedure TfrmCreateReport.Save;
begin
inherited;
if not Assigned(EditingObject) then
FEditingObject := AllReports.Add;
FCopyReports.Items[cmbxLevel.ItemIndex].ReportName := edtReportName.Text;
FCopyReports.Items[cmbxLevel.ItemIndex].TemplateName := edtTemplateName.Text;
FCopyReports.Items[cmbxLevel.ItemIndex].Level := cmbxLevel.ItemIndex;
CommonReport.Assign(FCopyReports.Items[cmbxLevel.ItemIndex]);
end;
procedure TfrmCreateReport.RegisterInspector;
begin
inherited;
Inspector.Add(edtReportName, nil, ptString, 'наименование отчёта', false);
Inspector.Add(edtTemplateName, nil, ptString, 'путь к шаблону', false);
Inspector.Add(trwQuery, nil, ptTreeMultiSelect, 'состав отчёта', false);
end;
procedure TfrmCreateReport.GetSelectedColumns(AColumns: TReportColumns);
var Node, tmp: TTreeNode;
cl: TReportColumn;
j, iOrder: integer;
R: TCommonReport;
begin
Node := trwQuery.Items.GetFirstNode;
repeat
if (Node.SelectedIndex > 0) and Node.HasChildren then
Node := Node.getFirstChild
else if Node.HasChildren then
begin
tmp := Node.getNextSibling;
if Assigned(tmp) then
Node := tmp
else Node := Node.GetNext;
end
else if not Node.HasChildren then
begin
if (TObject(Node.Data) is TReportColumn) and (Node.SelectedIndex = 1) then
begin
cl := TReportColumn.Create;
cl.Assign(TReportColumn(Node.Data));
cl.Order := 1000;
AColumns.Add(cl);
end;
Node := Node.GetNext;
end;
until not Assigned(Node);
// пересортировываем по порядку
R := FCopyReports.Items[cmbxLevel.ItemIndex];
iOrder := 0;
for j := 0 to R.ArrangedColumns.Count - 1 do
begin
cl := AColumns.ColByName(R.ArrangedColumns.Items[j].ColName);
if Assigned(cl) then
begin
cl.Order := iOrder;
inc(iOrder);
end;
end;
AColumns.SortByOrder;
end;
{ TQueryLoadAction }
constructor TQueryLoadAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Visible := false;
Caption := 'Загрузить запрос в дерево';
end;
function TQueryLoadAction.Execute: boolean;
begin
with (Owner as TfrmCreateReport) do
Result := Execute(FCopyReports.Items[cmbxLevel.ItemIndex]);
end;
function TQueryLoadAction.Execute(ABaseObject: TBaseObject): boolean;
var sp: TStringPoster;
r: TCommonReport;
pnm, nm: string;
ParentNode, Node: TTreeNode;
pt, t: TReportTable;
AllIncluded: boolean;
i, j, iIndex: integer;
cl: TReportColumn;
rts: TReportTables;
begin
Result := false;
r := ABaseObject as TCommonReport;
rts := TReportTables.Create(nil);
LastCollection := r.ReportTables;
if LastCollection.NeedsUpdate then
begin
LastCollection.NeedsUpdate := false;
Result := inherited Execute;
// берем постер
sp := TQueryTablesDataPoster.Create;
// инициализируем коллекцию
sp.LastGotCollection := LastCollection;
LastCollection := sp.GetFromString(r.Query);
// делаем чтобы столбцы шли в правильном порядке
r.ArrangedColumns.Clear;
for i := 0 to r.ReportTables.Count - 1 do
for j := 0 to r.ReportTables.Items[i].ColumnCount - 1 do
begin
cl := TReportColumn.Create;
cl.Assign(r.ReportTables.Items[i].Items[j]);
r.ArrangedColumns.Add(cl);
end;
r.ArrangedColumns.SortByOrder;
rts.Assign(r.ReportTables);
for i := 0 to rts.Count - 1 do
rts.Items[i].CopyColumns(r.ReportTables.Items[i]);
// загружаем в интерфейс
with (Owner as TfrmCreateReport) do
begin
trwQuery.Items.BeginUpdate;
// проходим по готовому дереву
Node := trwQuery.Items.GetFirstNode;
t := nil;
// сличаем его ветви с тем, что выбрано для запроса
while Assigned(Node) do
begin
// если находим таблицу - отмечаем
// узел с подчиненными узлами - соответствует таблице со столбцами
if TObject(Node.Data) is TReportTable then
begin
nm := TReportTable(Node.Data).TableName;
t := rts.GetTableByName(nm);
if Assigned(t) then
begin
Node.SelectedIndex := 1;
Node.ImageIndex := 1;
end;
end
else
begin
// если находим колонки - тоже отмечаем;
// в принципе нужно, чтобы все приходило в согласованное состояние,
// то есть узел соответствующий таблице показывался в
// grayed состоянии
nm := TReportColumn(Node.Data).ColName;
// чтобы не отмечались два раза одни и те же таблицы
// провераем еще верхний уровень
AllIncluded := true;
ParentNode := Node.Parent.Parent;
if Assigned(ParentNode) then
while Assigned(ParentNode) do
begin
pnm := TReportTable(ParentNode.Data).TableName;
pt := r.ReportTables.GetTableByName(pnm);
if not Assigned(pt) then
begin
AllIncluded := false;
break;
end;
ParentNode := ParentNode.Parent;
end;
if Assigned(t) and AllIncluded then
begin
cl := t.Columns[nm];
if Assigned(cl) then
begin
Node.SelectedIndex := 1;
Node.ImageIndex := 1;
iIndex := t.IndexOfName(nm);
while iIndex > -1 do
begin
t.Delete(iIndex);
iIndex := t.IndexOfName(nm);
end;
end;
end;
end;
// согласовываем состояние предыдущего родителя со всеми потомками
if Assigned(t) and Assigned(Node.Parent) then CheckChildState(Node.Parent);
Node := Node.GetNext;
end;
trwQuery.Items.EndUpdate;
end;
sp.Free;
end;
end;
{ TReportTablesLoadAction }
constructor TReportTablesLoadAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Visible := false;
Caption := 'Загрузить досутпные таблицы в дерево';
end;
function TReportTablesLoadAction.Execute: boolean;
var Node: TTreeNode;
rts: TReportTables;
tbl: TReportTable;
procedure RecourseTable(ATree: TTreeView; ANode: TTreeNode; ATable: TReportTable);
var j: integer;
Child: TTreeNode;
begin
if Assigned(ANode) then ANode.SelectedIndex := 0;
ANode := ATree.Items.AddChildObject(ANode, ATable.RusTableName, ATable);
ANode.SelectedIndex := 0;
// сортируем столбца по алфавиту
ATable.SortColumnsByRusName;
// добавляем столбцы
for j := 0 to ATable.ColumnCount - 1 do
if ATable.Items[j].RusColName <> '' then
begin
Child := ATree.Items.AddChildObject(ANode, ATable.Items[j].List, ATable.Items[j]);
Child.SelectedIndex := 0;
end;
// ANode := Child;
for j := 0 to ATable.Joins.Count - 1 do
if Assigned(ATable.Joins.Items[j].RightTable) then
RecourseTable(ATree, ANode, ATable.Joins.Items[j].RightTable);
end;
begin
Result := inherited Execute;
LastCollection := AllConcreteTables;
rts := LastCollection as TReportTables;
with (Owner as TfrmCreateReport) do
begin
trwQuery.Items.BeginUpdate;
trwQuery.Items.Clear;
Node := nil;
if cmbxLevel.ItemIndex > -1 then
begin
tbl := TReportTable(cmbxLevel.Items.Objects[cmbxLevel.ItemIndex]);
RecourseTable(trwQuery, Node, tbl);
end;
trwQuery.Items.EndUpdate;
end;
end;
procedure TfrmCreateReport.trwQueryGetImageIndex(Sender: TObject;
Node: TTreeNode);
begin
with Node do ImageIndex:=SelectedIndex;
end;
procedure TfrmCreateReport.cmbxLevelChange(Sender: TObject);
begin
FTableLoadAction.Execute;
trwQuery.Items.GetFirstNode.StateIndex := cmbxLevel.ItemIndex + 3;
FCopyReports.Items[cmbxLevel.ItemIndex].ReportTables.NeedsUpdate := true;
FQueryLoadAction.Execute;
Check;
end;
procedure TfrmCreateReport.cmbxLevelMeasureItem(Control: TWinControl;
Index: Integer; var Height: Integer);
begin
Height := 18;
end;
procedure TfrmCreateReport.cmbxLevelDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
imgLst.Draw(cmbxLevel.Canvas, Rect.Left + 1, Rect.Top + 1, Index + 3);
cmbxLevel.Canvas.TextOut(Rect.Left + 22, Rect.Top + 2, cmbxLevel.Items[Index]);
end;
procedure TfrmCreateReport.cmbxLevelDropDown(Sender: TObject);
begin
if Assigned(FCopyReports.Items[cmbxLevel.ItemIndex]) and Assigned(FOnChangeLevel) then FOnChangeLevel(Sender);
end;
end.
|
unit SavedQuestionClass;
interface
uses QuestionClass;
type TSavedQuestion = Class (TQuestion)
private
SaveTime : TDateTime;
User : String[15];
public
//constructor Create;
function GetSaveTime : TDateTime;
function GetUser : String;
procedure SetSaveTime (NewSaveTime : TDateTime);
procedure SetUser (NewUser : String);
end;
implementation
function TSavedQuestion.GetSaveTime : TDateTime;
begin
GetSaveTime := SaveTime;
end;
function TSavedQuestion.GetUser : String;
begin
GetUser := String(User);
end;
procedure TSavedQuestion.SetSaveTime (NewSaveTime : TDateTime);
begin
SaveTime := NewSaveTime;
end;
procedure TSavedQuestion.SetUser (NewUser : String);
begin
User := AnsiString(NewUser);
end;
end.
|
{ MIT License
Copyright (c) 2022 Viacheslav Komenda
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. }
{$M 32768,131072,131072}
USES System2, WinCB;
CONST
ERR_NO_MEMORY = 'ERROR: No memory.';
ERR_NO_FILE = 'ERROR: Could not read ';
ERROR = 1;
OK = 0;
PROCEDURE Help;
BEGIN
System.WriteLn('usage: DWCLIP [C fname] [P]');
System.WriteLn;
System.WriteLn('C fname - copy text file to clipboard');
System.WriteLn('P - paste from clipboard to STDOUT');
System.WriteLn;
System.WriteLn('NOTE: 64kb restiction. DOS LFN - supported, use name with quotes.');
System.WriteLn;
System.Write('Check Windows Clipboard status: ');
IF WCB_Detect THEN System.Write('OK')
ELSE System.Write('NONE');
System.WriteLn;
END;
PROCEDURE Copy(fname : STRING);
VAR p : PCHAR;
f : BFile;
w : WORD;
BEGIN
IF NOT WCB_Detect THEN EXIT;
GetMem(p, 65000);
IF p = NIL THEN BEGIN
Help;
System.WriteLn;
WriteLnErr(ERR_NO_MEMORY);
Halt(ERROR);
END;
Assign(f, fname);
Reset(f);
IF NOT IsOpen(f) THEN BEGIN
FreeMem(p, 65000);
Help;
System.WriteLn;
WriteLnErr(ERR_NO_FILE + fname);
Halt(ERROR);
END;
w := BlockRead(f, p^, 65000 - 1);
Close(f);
p[w] := #0;
WCB_Copy(p, w + 1);
FreeMem(p, 65000);
Halt(OK);
END;
PROCEDURE Paste;
VAR p : PCHAR;
BEGIN
IF NOT WCB_Detect THEN EXIT;
GetMem(p, 65000);
IF p = NIL THEN BEGIN
Help;
System.WriteLn;
WriteLnErr(ERR_NO_MEMORY);
Halt(ERROR);
END;
IF WCB_Paste(p^, 65000) THEN System.WriteLn(p);
FreeMem(p, 65000);
Halt(OK);
END;
VAR pc : INTEGER;
cmd : STRING;
BEGIN
pc := ParamCount;
IF pc > 0 THEN BEGIN
cmd := ParamStr(1);
CASE UPCASE(cmd[1]) OF
'C': IF pc = 2 THEN Copy(ParamStr(2));
'P': Paste;
END;
END;
Help;
Halt(ERROR);
END.
|
unit FHIRContext;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.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
AdvObjects, AdvGenerics,
FHIRTypes, FHIRResources;
type
TValidationResult = class (TAdvObject)
private
FSeverity : TFhirIssueSeverityEnum;
FMessage : String;
FDisplay: String;
public
constructor Create; overload; override;
constructor Create(Severity : TFhirIssueSeverityEnum; Message : String); overload; virtual;
constructor Create(display : String); overload; virtual;
Property Severity : TFhirIssueSeverityEnum read FSeverity write FSeverity;
Property Message : String read FMessage write FMessage;
Property Display : String read FDisplay write FDisplay;
function isOk : boolean;
end;
TFHIRCustomResourceInformation = class (TAdvObject)
private
FName: String;
FSearchParameters: TAdvList<TFHIRSearchParameter>;
FDefinition: TFHIRStructureDefinition;
public
Constructor Create(definition : TFHIRStructureDefinition);
Destructor Destroy; override;
function Link : TFHIRCustomResourceInformation; overload;
property Name : String read FName;
property Definition : TFHIRStructureDefinition read FDefinition;
property SearchParameters : TAdvList<TFHIRSearchParameter> read FSearchParameters;
end;
TFHIRWorkerContext = class abstract (TAdvObject)
public
function link : TFHIRWorkerContext; overload;
function allStructures : TAdvMap<TFHIRStructureDefinition>.TValueCollection; virtual; abstract;
function getResourceNames : TAdvStringSet; virtual; abstract;
function fetchResource(t : TFhirResourceType; url : String) : TFhirResource; virtual; abstract;
function expand(vs : TFhirValueSet) : TFHIRValueSet; virtual; abstract;
function supportsSystem(system, version : string) : boolean; virtual; abstract;
function validateCode(system, version, code, display : String) : TValidationResult; overload; virtual; abstract;
function validateCode(system, version, code : String; vs : TFhirValueSet) : TValidationResult; overload; virtual; abstract;
function validateCode(code : TFHIRCoding; vs : TFhirValueSet) : TValidationResult; overload; virtual; abstract;
function validateCode(code : TFHIRCodeableConcept; vs : TFhirValueSet) : TValidationResult; overload; virtual; abstract;
function getChildMap(profile : TFHIRStructureDefinition; element : TFhirElementDefinition) : TFHIRElementDefinitionList; virtual; abstract;
function getStructure(url : String) : TFHIRStructureDefinition; overload; virtual; abstract;
function getStructure(ns, name : String) : TFHIRStructureDefinition; overload; virtual; abstract;
function getCustomResource(name : String) : TFHIRCustomResourceInformation; virtual; abstract;
function hasCustomResource(name : String) : boolean; virtual; abstract;
function allResourceNames : TArray<String>; virtual; abstract;
function nonSecureResourceNames : TArray<String>; virtual; abstract;
end;
implementation
{ TValidationResult }
constructor TValidationResult.Create(Severity: TFhirIssueSeverityEnum; Message: String);
begin
inherited create;
FSeverity := Severity;
FMessage := Message;
end;
constructor TValidationResult.Create;
begin
Inherited Create;
end;
constructor TValidationResult.Create(display: String);
begin
inherited Create;
FDisplay := display;
end;
function TValidationResult.isOk: boolean;
begin
result := not (Severity in [IssueSeverityError, IssueSeverityFatal]);
end;
{ TFHIRWorkerContext }
function TFHIRWorkerContext.link: TFHIRWorkerContext;
begin
result := TFHIRWorkerContext(inherited link);
end;
{ TFHIRCustomResourceInformation }
constructor TFHIRCustomResourceInformation.Create(definition: TFHIRStructureDefinition);
begin
inherited Create;
FDefinition := definition;
FName := definition.snapshot.elementList[0].path;
FSearchParameters := TAdvList<TFHIRSearchParameter>.create;
end;
destructor TFHIRCustomResourceInformation.Destroy;
begin
FSearchParameters.Free;
FDefinition.Free;
inherited;
end;
function TFHIRCustomResourceInformation.Link: TFHIRCustomResourceInformation;
begin
result := TFHIRCustomResourceInformation(inherited Link);
end;
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.Scene3D.Renderer.Passes.HUDMipMapCustomPass;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Framework,
PasVulkan.Application,
PasVulkan.FrameGraph,
PasVulkan.Scene3D,
PasVulkan.Scene3D.Renderer.Globals,
PasVulkan.Scene3D.Renderer,
PasVulkan.Scene3D.Renderer.Instance;
type { TpvScene3DRendererPassesHUDMipMapCustomPass }
TpvScene3DRendererPassesHUDMipMapCustomPass=class(TpvFrameGraph.TCustomPass)
private
fInstance:TpvScene3DRendererInstance;
fResourceInput:TpvFrameGraph.TPass.TUsedImageResource;
fVulkanSampler:TpvVulkanSampler;
fVulkanImageViews:array[0..MaxInFlightFrames-1] of TpvVulkanImageView;
public
constructor Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance); reintroduce;
destructor Destroy; override;
procedure AcquirePersistentResources; override;
procedure ReleasePersistentResources; override;
procedure AcquireVolatileResources; override;
procedure ReleaseVolatileResources; override;
procedure Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt); override;
procedure Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt); override;
end;
implementation
{ TpvScene3DRendererPassesHUDMipMapCustomPass }
constructor TpvScene3DRendererPassesHUDMipMapCustomPass.Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance);
begin
inherited Create(aFrameGraph);
fInstance:=aInstance;
Name:='HUDMipMapCustomPass';
fResourceInput:=AddImageInput('resourcetype_hud_color',
'resource_hud_color',
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
[]
);
end;
destructor TpvScene3DRendererPassesHUDMipMapCustomPass.Destroy;
begin
inherited Destroy;
end;
procedure TpvScene3DRendererPassesHUDMipMapCustomPass.AcquirePersistentResources;
begin
inherited AcquirePersistentResources;
end;
procedure TpvScene3DRendererPassesHUDMipMapCustomPass.ReleasePersistentResources;
begin
inherited ReleasePersistentResources;
end;
procedure TpvScene3DRendererPassesHUDMipMapCustomPass.AcquireVolatileResources;
var InFlightFrameIndex,MipMapLevelIndex:TpvInt32;
ImageViewType:TVkImageViewType;
begin
inherited AcquireVolatileResources;
fVulkanSampler:=TpvVulkanSampler.Create(fInstance.Renderer.VulkanDevice,
TVkFilter.VK_FILTER_NEAREST,
TVkFilter.VK_FILTER_NEAREST,
TVkSamplerMipmapMode.VK_SAMPLER_MIPMAP_MODE_NEAREST,
VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
0.0,
false,
0.0,
false,
VK_COMPARE_OP_ALWAYS,
0.0,
0.0,
VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
false);
ImageViewType:=TVkImageViewType(VK_IMAGE_VIEW_TYPE_2D);
for InFlightFrameIndex:=0 to FrameGraph.CountInFlightFrames-1 do begin
fVulkanImageViews[InFlightFrameIndex]:=TpvVulkanImageView.Create(fInstance.Renderer.VulkanDevice,
fResourceInput.VulkanImages[InFlightFrameIndex],
ImageViewType,
TpvFrameGraph.TImageResourceType(fResourceInput.ResourceType).Format,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT),
0,
1,
0,
1
);
end;
end;
procedure TpvScene3DRendererPassesHUDMipMapCustomPass.ReleaseVolatileResources;
var InFlightFrameIndex,MipMapLevelIndex:TpvInt32;
begin
for InFlightFrameIndex:=0 to fInstance.Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fVulkanImageViews[InFlightFrameIndex]);
end;
FreeAndNil(fVulkanSampler);
inherited ReleaseVolatileResources;
end;
procedure TpvScene3DRendererPassesHUDMipMapCustomPass.Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt);
begin
inherited Update(aUpdateInFlightFrameIndex,aUpdateFrameIndex);
end;
procedure TpvScene3DRendererPassesHUDMipMapCustomPass.Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt);
var InFlightFrameIndex,MipMapLevelIndex:TpvInt32;
ImageMemoryBarrier:TVkImageMemoryBarrier;
ImageBlit:TVkImageBlit;
begin
inherited Execute(aCommandBuffer,aInFlightFrameIndex,aFrameIndex);
InFlightFrameIndex:=aInFlightFrameIndex;
FillChar(ImageMemoryBarrier,SizeOf(TVkImageMemoryBarrier),#0);
ImageMemoryBarrier.sType:=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
ImageMemoryBarrier.pNext:=nil;
ImageMemoryBarrier.srcAccessMask:=TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT);
ImageMemoryBarrier.dstAccessMask:=TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT);
ImageMemoryBarrier.oldLayout:=VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
ImageMemoryBarrier.newLayout:=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
ImageMemoryBarrier.srcQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED;
ImageMemoryBarrier.dstQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED;
ImageMemoryBarrier.image:=fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].VulkanImage.Handle;
ImageMemoryBarrier.subresourceRange.aspectMask:=TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT);
ImageMemoryBarrier.subresourceRange.baseMipLevel:=0;
ImageMemoryBarrier.subresourceRange.levelCount:=fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].MipMapLevels;
ImageMemoryBarrier.subresourceRange.baseArrayLayer:=0;
ImageMemoryBarrier.subresourceRange.layerCount:=1;
aCommandBuffer.CmdPipelineBarrier(FrameGraph.VulkanDevice.PhysicalDevice.PipelineStageAllShaderBits or TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
FrameGraph.VulkanDevice.PhysicalDevice.PipelineStageAllShaderBits or TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
0,
0,nil,
0,nil,
1,@ImageMemoryBarrier);
begin
FillChar(ImageMemoryBarrier,SizeOf(TVkImageMemoryBarrier),#0);
ImageMemoryBarrier.sType:=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
ImageMemoryBarrier.pNext:=nil;
ImageMemoryBarrier.srcAccessMask:=TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT);
ImageMemoryBarrier.dstAccessMask:=TVkAccessFlags(VK_ACCESS_TRANSFER_READ_BIT);
ImageMemoryBarrier.oldLayout:=VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
ImageMemoryBarrier.newLayout:=VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
ImageMemoryBarrier.srcQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED;
ImageMemoryBarrier.dstQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED;
ImageMemoryBarrier.image:=fResourceInput.VulkanImages[InFlightFrameIndex].Handle;
ImageMemoryBarrier.subresourceRange.aspectMask:=TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT);
ImageMemoryBarrier.subresourceRange.baseMipLevel:=0;
ImageMemoryBarrier.subresourceRange.levelCount:=1;
ImageMemoryBarrier.subresourceRange.baseArrayLayer:=0;
ImageMemoryBarrier.subresourceRange.layerCount:=1;
aCommandBuffer.CmdPipelineBarrier(FrameGraph.VulkanDevice.PhysicalDevice.PipelineStageAllShaderBits or TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
FrameGraph.VulkanDevice.PhysicalDevice.PipelineStageAllShaderBits or TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
0,
0,nil,
0,nil,
1,@ImageMemoryBarrier);
ImageBlit:=TVkImageBlit.Create(TVkImageSubresourceLayers.Create(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT),
0,
0,
1),
[TVkOffset3D.Create(0,
0,
0),
TVkOffset3D.Create(fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].Width,
fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].Height,
1)],
TVkImageSubresourceLayers.Create(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT),
0,
0,
1),
[TVkOffset3D.Create(0,
0,
0),
TVkOffset3D.Create(fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].Width,
fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].Height,
1)]
);
aCommandBuffer.CmdBlitImage(fResourceInput.VulkanImages[InFlightFrameIndex].Handle,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].VulkanImage.Handle,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
@ImageBlit,
TVkFilter(VK_FILTER_LINEAR));
FillChar(ImageMemoryBarrier,SizeOf(TVkImageMemoryBarrier),#0);
ImageMemoryBarrier.sType:=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
ImageMemoryBarrier.pNext:=nil;
ImageMemoryBarrier.srcAccessMask:=TVkAccessFlags(VK_ACCESS_TRANSFER_READ_BIT);
ImageMemoryBarrier.dstAccessMask:=TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT);
ImageMemoryBarrier.oldLayout:=VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
ImageMemoryBarrier.newLayout:=VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
ImageMemoryBarrier.srcQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED;
ImageMemoryBarrier.dstQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED;
ImageMemoryBarrier.image:=fResourceInput.VulkanImages[InFlightFrameIndex].Handle;
ImageMemoryBarrier.subresourceRange.aspectMask:=TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT);
ImageMemoryBarrier.subresourceRange.baseMipLevel:=0;
ImageMemoryBarrier.subresourceRange.levelCount:=1;
ImageMemoryBarrier.subresourceRange.baseArrayLayer:=0;
ImageMemoryBarrier.subresourceRange.layerCount:=1;
aCommandBuffer.CmdPipelineBarrier(FrameGraph.VulkanDevice.PhysicalDevice.PipelineStageAllShaderBits or TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
FrameGraph.VulkanDevice.PhysicalDevice.PipelineStageAllShaderBits or TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
0,
0,nil,
0,nil,
1,@ImageMemoryBarrier);
end;
FillChar(ImageMemoryBarrier,SizeOf(TVkImageMemoryBarrier),#0);
ImageMemoryBarrier.sType:=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
ImageMemoryBarrier.pNext:=nil;
ImageMemoryBarrier.srcAccessMask:=TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT);
ImageMemoryBarrier.dstAccessMask:=TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT);
ImageMemoryBarrier.oldLayout:=VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
ImageMemoryBarrier.newLayout:=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
ImageMemoryBarrier.srcQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED;
ImageMemoryBarrier.dstQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED;
ImageMemoryBarrier.image:=fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].VulkanImage.Handle;
ImageMemoryBarrier.subresourceRange.aspectMask:=TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT);
ImageMemoryBarrier.subresourceRange.baseMipLevel:=0;
ImageMemoryBarrier.subresourceRange.levelCount:=fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].MipMapLevels;
ImageMemoryBarrier.subresourceRange.baseArrayLayer:=0;
ImageMemoryBarrier.subresourceRange.layerCount:=1;
for MipMapLevelIndex:=1 to fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].MipMapLevels-1 do begin
ImageMemoryBarrier.subresourceRange.levelCount:=1;
ImageMemoryBarrier.subresourceRange.baseMipLevel:=MipMapLevelIndex-1;
ImageMemoryBarrier.oldLayout:=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
ImageMemoryBarrier.newLayout:=VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
ImageMemoryBarrier.srcAccessMask:=TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT);
ImageMemoryBarrier.dstAccessMask:=TVkAccessFlags(VK_ACCESS_TRANSFER_READ_BIT);
aCommandBuffer.CmdPipelineBarrier(TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
0,
0,
nil,
0,
nil,
1,
@ImageMemoryBarrier);
ImageBlit:=TVkImageBlit.Create(TVkImageSubresourceLayers.Create(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT),
MipMapLevelIndex-1,
0,
1),
[TVkOffset3D.Create(0,
0,
0),
TVkOffset3D.Create(fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].Width shr (MipMapLevelIndex-1),
fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].Height shr (MipMapLevelIndex-1),
1)],
TVkImageSubresourceLayers.Create(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT),
MipMapLevelIndex,
0,
1),
[TVkOffset3D.Create(0,
0,
0),
TVkOffset3D.Create(fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].Width shr MipMapLevelIndex,
fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].Height shr MipMapLevelIndex,
1)]
);
aCommandBuffer.CmdBlitImage(fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].VulkanImage.Handle,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].VulkanImage.Handle,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
@ImageBlit,
TVkFilter(VK_FILTER_LINEAR));
ImageMemoryBarrier.oldLayout:=VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
ImageMemoryBarrier.newLayout:=VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
ImageMemoryBarrier.srcAccessMask:=TVkAccessFlags(VK_ACCESS_TRANSFER_READ_BIT);
ImageMemoryBarrier.dstAccessMask:=TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT);
aCommandBuffer.CmdPipelineBarrier(TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
TVkPipelineStageFlags(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT),
0,
0,
nil,
0,
nil,
1,
@ImageMemoryBarrier);
end;
ImageMemoryBarrier.subresourceRange.levelCount:=1;
ImageMemoryBarrier.subresourceRange.baseMipLevel:=fInstance.HUDMipmappedArray2DImages[InFlightFrameIndex].MipMapLevels-1;
ImageMemoryBarrier.oldLayout:=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
ImageMemoryBarrier.newLayout:=VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
ImageMemoryBarrier.srcAccessMask:=TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT);
ImageMemoryBarrier.dstAccessMask:=TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT);
aCommandBuffer.CmdPipelineBarrier(TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
TVkPipelineStageFlags(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT),
0,
0,
nil,
0,
nil,
1,
@ImageMemoryBarrier);
end;
end.
|
unit VSEGUI;
interface
uses
Windows, AvL, avlUtils, OpenGL, VSEOpenGLExt, oglExtensions, VSECore, VSERender2D;
type
TGUIForm = class;
TBtnType = (btPush, btCheck, btRadio); //Button type: push button, check box, radio button
PBtn = ^TBtn;
TGUIOnClick = procedure(Btn: PBtn) of object; //OnClick handler; Btn: pressed button info
TOnForm = procedure(Form: TGUIForm) of object;
TBtn = record //Button
Caption: string; //Button caption
Type_: TBtnType; //Button type
X, Y, Width, Height, Group, Tag: Integer; //X, Y, Width, Height: button bounds; Group: radio button group; Tag: custom information
OnClick: TGUIOnClick; //Button click event handler, don't override if Type_=btCheck or Type_=btRadio
Checked, Enabled: Boolean; //Checked: true if check box or radio button checked; Enabled: enable button
end;
TLabelAlign = (laLeft, laCenter, laRight); //Label aligning
PLbl = ^TLbl;
TLbl = record //Label
Caption: string; //Label text
X, Y, Width: Integer; //Label bounds (height depends from form font)
Align: TLabelAlign; //Text aligning
Color: TColor; //Text color, 0 for default
end;
TBtnStates = (bsHighlighted, bsPushed, bsTabStop, fsLocked = bsTabStop); //Button state - highlighted (mouse over), pushed, selected from keyboard
TBtnState = set of TBtnStates;
TColorSet = record
Default, Highlighted, Activated, Disabled: TColor;
end;
TMenuItem = record //Menu item
Caption: string; //Item button caption
Tag: Integer; //Item button tag
OnClick: TGUIOnClick; //Item button click event handler
end;
PFormRec = ^TFormRec;
TFormRec = record
Name, Parent: string;
Form: TGUIForm;
Visible, Locked: Boolean;
Prev, Next: PFormRec;
end;
TMenuItems = array of Integer;
TGUIFormsSet = class
private
FForms: PFormRec;
function GetForm(const Name: string): TGUIForm;
function GetVisible(const Name: string): Boolean;
procedure SetVisible(const Name: string; const Value: Boolean);
public
destructor Destroy; override;
function AddForm(const Name: string; Form: TGUIForm; const Parent: string = ''): TGUIForm; //Add form; Parent: name of parent form; Parentless forms visible by default
procedure RemoveForm(Form: TGUIForm); //Remove form
procedure IterateForms(Handler: TOnForm); //Call Handler for every form
function FindForm(const Name: string): PFormRec; overload; //internally used
function FindForm(Form: TGUIForm): PFormRec; overload; //internally used
function FormAt(X, Y: Integer): PFormRec; //internally used
procedure Pop(Form: PFormRec); //internally used
function LastForm: PFormRec; //internally used
property FirstForm: PFormRec read FForms; //internally used
function FormName(Form: TGUIForm): string; //Name of form
property Forms[const Name: string]: TGUIForm read GetForm; default; //Forms
property Visible[const Name: string]: Boolean read GetVisible write SetVisible; //Form visibility
end;
TGUIForm = class //GUI Form
private
FActive, FLast, FTabStop: Integer; //internally used
FCustomFont: Cardinal; //internally used
FMovable, FClose: Boolean; //internally used
FDragPoint: TPoint; //internally used
FButtons: array of TBtn; //internally used
FRects: array of TRect; //internally used
FLabels: array of TLbl; //internally used
function BtnState(Highlighted, Pushed, TabStop: Boolean): TBtnState;
function IsMoving: Boolean;
function GetName: string;
protected
FCaption: string; //Form caption
FCaptHeight: Integer; //Form caption height
FX, FY, FWidth, FHeight: Integer; //Form position and size
FParentSet: TGUIFormsSet; //Form set
function Font: Cardinal;
function GetButton(Index: Integer): PBtn; //Get button by index
function GetLabel(Index: Integer): PLbl; //Get label by index
procedure CheckClick(Btn: PBtn); //CheckBox click handler
procedure RadioClick(Btn: PBtn); //RadioButton click handler
procedure MapCursor(var Cursor: TPoint); //Map cursor to form coordinates
function BtnAt(Point: TPoint): Integer; //Get button at specified coordinates
procedure SetColor(State: TBtnState; const ColorSet: TColorSet; Enabled: Boolean = true); //Set color from color set
procedure DrawForm(State: TBtnState); dynamic; //Override for custom form drawing
procedure DrawButton(const Btn: TBtn; State: TBtnState); dynamic; //Override for custom buttons drawing
procedure DrawRect(const Rect: TRect); dynamic; //Override for custom rectangles drawing
procedure DrawLabel(const Lbl: TLbl); dynamic; //Override for custom labels drawing
public
constructor Create(X, Y, Width, Height: Integer); //Creates form; X, Y, Width, Height: form bounds
destructor Destroy; override;
function AddButton(Btn: TBtn): Integer; //Add button, returns button index
function AddLabel(const Lbl: TLbl): Integer; //Add label, returns label index
procedure AddRect(const Rect: TRect); //Add rectangle (visual frame)
procedure Draw; //Draw form
procedure Update; dynamic; //Update form
procedure Close; //Free form safely
function Event(Event: TCoreEvent): Boolean; //Process event
function MouseEvent(Button: Integer; Event: TMouseEvents; Cursor: TPoint): Boolean; dynamic; //Process mouse event
function KeyEvent(Key: Integer; Event: TKeyEvents): Boolean; dynamic; //Process key event
function CharEvent(C: Char): Boolean; dynamic; //Process char event
property Button[Index: Integer]: PBtn read GetButton; //Buttons array
property Lbl[Index: Integer]: PLbl read GetLabel; //Labels array
property Caption: string read FCaption write FCaption; //Form caption
property Left: Integer read FX write FX; //Horisontal position
property Top: Integer read FY write FY; //Vertical position
property Width: Integer read FWidth write FWidth; //Form width
property Height: Integer read FHeight write FHeight; //Form height
property Name: string read GetName; //Form name
property CustomFont: Cardinal read FCustomFont write FCustomFont; //Custom form font; InvalidFont: don't use
property Movable: Boolean read FMovable write FMovable; //Form can be dragged by caption
end;
procedure SetGUIFont(const Name: string = 'Tahoma'; Size: Integer = 12; Bold: Boolean = true);
function CreateSelect(Form: TGUIForm; X, Y, Width, Height: Integer; OnChange: TGUIOnClick; const PrevCaption, NextCaption: string): Integer; //Creates select control, returns select state label index; distinguish prev & next buttons in handler by Btn^.Tag (-1 for prev, 1 for next)
function CreateMenu(Form: TGUIForm; X, Y, BtnWidth, BtnHeight, BtnSpacing: Integer; Items: array of TMenuItem): TMenuItems; //Creates menu from buttons, returns butttons' indexes
var
{$IF not (Defined(CLRSCM_DEFAULT) or Defined(CLRSCM_WINMO) or Defined(CLRSCM_WIN95))}
{$DEFINE CLRSCM_DEFAULT}
{$IFEND}
{$IF Defined(CLRSCM_DEFAULT)}
BtnBackground: TColorSet = (Default: $FF80FF80; Highlighted: $FF8080FF; Activated: $FF7070E0; Disabled: $FF80FF80);
BtnBorder: TColorSet = (Default: $FF00D000; Highlighted: $FF0000FF; Activated: $FF0000FF; Disabled: $FF20FF20);
BtnText: TColorSet = (Default: $FF00B200; Highlighted: $FF00C000; Activated: $FF00A000; Disabled: $FF00F000);
FormCapt: TColorSet = (Default: $FF80E600; Highlighted: $FF80DC00; Activated: $FF73CF00; Disabled: $FF80FF80);
clFormBackground: TColor = $FF80FF80;
clFormBorder: TColor = $FF00FF00;
clFormCaptText: TColor = $FF00FFFF;
clText: TColor = $FF00B200;
clTabStop: TColor = $FF000080;
{$ELSEIF Defined(CLRSCM_WINMO) or Defined(CLRSCM_WIN95)}
BtnBackground: TColorSet = (Default: $FFC0C0C0; Highlighted: $FFC8C8C8; Activated: $FFA0A0A0; Disabled: $FFC0C0C0);
BtnBorder: TColorSet = (Default: $FF404040; Highlighted: $FF404040; Activated: $FF404040; Disabled: $FF808080);
BtnText: TColorSet = (Default: $FF000000; Highlighted: $FF000000; Activated: $FF000000; Disabled: $FF808080);
FormCapt: TColorSet = (Default: $FF800000; Highlighted: $FF8A0000; Activated: $FF880000; Disabled: $FF808080);
clFormBackground: TColor = {$IFDEF CLRSCM_WINMO}$FFFFFFFF{$ELSE}$FFC0C0C0{$ENDIF};
clFormBorder: TColor = $FF404040;
clFormCaptText: TColor = $FFFFFFFF;
clText: TColor = $FF000000;
clTabStop: TColor = $FF000000;
{$IFEND}
GUIFont: Cardinal;
implementation
uses
VSECollisionCheck;
{ TGUIFormsSet }
destructor TGUIFormsSet.Destroy;
var
Cur: PFormRec;
begin
while Assigned(FForms) do
begin
Cur := FForms;
FForms := Cur.Next;
Cur.Form.Free;
Dispose(Cur);
end;
inherited;
end;
function TGUIFormsSet.AddForm(const Name: string; Form: TGUIForm; const Parent: string): TGUIForm;
var
Rec, Last: PFormRec;
begin
Result := Form;
if Assigned(FindForm(Name)) then
raise Exception.Create('FormsSet: duplicate form name "' + Name + '"');
New(Rec);
Rec.Name := Name;
Rec.Form := Form;
Rec.Parent := Parent;
Rec.Visible := Parent = '';
Rec.Locked := false;
if Rec.Visible or not Assigned(FForms) then
begin
Rec.Prev := nil;
Rec.Next := FForms;
if Assigned(FForms) then FForms.Prev := Rec;
FForms := Rec;
end
else begin
Last := LastForm;
Rec.Prev := Last;
Rec.Next := nil;
if Assigned(Last) then
Last.Next := Rec
else
FForms := Rec;
end;
Form.FParentSet := Self;
end;
procedure TGUIFormsSet.RemoveForm(Form: TGUIForm);
var
Rec: PFormRec;
begin
Rec := FindForm(Form);
if not Assigned(Rec) then Exit;
Visible[Rec.Name] := false;
Rec.Form.FParentSet := nil;
if Assigned(Rec.Prev) then
Rec.Prev.Next := Rec.Next;
if Assigned(Rec.Next) then
Rec.Next.Prev := Rec.Prev;
if Rec = FForms then
FForms := Rec.Next;
Dispose(Rec);
end;
procedure TGUIFormsSet.IterateForms(Handler: TOnForm);
var
Cur: PFormRec;
begin
Cur := FForms;
while Assigned(Cur) do
begin
Handler(Cur.Form);
Cur := Cur.Next;
end;
end;
function TGUIFormsSet.FindForm(const Name: string): PFormRec;
begin
Result := FForms;
while Assigned(Result) do
if Result.Name = Name then
Break
else
Result := Result.Next;
end;
function TGUIFormsSet.FindForm(Form: TGUIForm): PFormRec;
begin
Result := FForms;
while Assigned(Result) do
if Result.Form = Form then
Break
else
Result := Result.Next;
end;
function TGUIFormsSet.FormAt(X, Y: Integer): PFormRec;
begin
Result := FForms;
while Assigned(Result) do
with Result.Form do
if Result.Visible and PointInRect(Render2D.MapCursor(Point(X, Y)), Rect(Left, Top, Left + Width, Top + Height)) then
Break
else
Result := Result.Next;
end;
function TGUIFormsSet.LastForm: PFormRec;
begin
Result := FForms;
while Assigned(Result) and Assigned(Result.Next) do
Result := Result.Next;
end;
function TGUIFormsSet.FormName(Form: TGUIForm): string;
var
Rec: PFormRec;
begin
Result := '';
Rec := FindForm(Form);
if Assigned(Rec) then
Result := Rec.Name;
end;
procedure TGUIFormsSet.Pop(Form: PFormRec);
begin
if not Assigned(Form) or not Assigned(Form.Prev) then Exit;
Form.Prev.Next := Form.Next;
if Assigned(Form.Next) then
Form.Next.Prev := Form.Prev;
FForms.Prev := Form;
Form.Prev := nil;
Form.Next := FForms;
FForms := Form;
end;
function TGUIFormsSet.GetForm(const Name: string): TGUIForm;
var
Form: PFormRec;
begin
Result := nil;
Form := nil;
if Assigned(Self) then
Form := FindForm(Name);
if Assigned(Form) then
Result := Form.Form;
end;
function TGUIFormsSet.GetVisible(const Name: string): Boolean;
var
Form: PFormRec;
begin
Result := false;
Form := FindForm(Name);
if Assigned(Form) then
Result := Form.Visible;
end;
procedure TGUIFormsSet.SetVisible(const Name: string; const Value: Boolean);
var
Form, Parent: PFormRec;
begin
Form := FindForm(Name);
if not Assigned(Form) then Exit;
Form.Visible := Value;
if Form.Parent <> '' then
begin
Parent := FindForm(Form.Parent);
if not Assigned(Parent) then Exit;
Parent.Locked := Value;
if not Value then
Pop(Parent);
end;
end;
{ TGUIForm }
constructor TGUIForm.Create(X, Y, Width, Height: Integer);
begin
inherited Create;
FX := X;
FY := Y;
FWidth := Width;
FHeight := Height;
FCustomFont := InvalidFont;
FCaptHeight := Render2D.TextHeight(Font) + 6; //TODO: Recalc on font change
FActive := -1;
FLast := -1;
FTabStop := -1;
FMovable := false;
end;
destructor TGUIForm.Destroy;
begin
if Assigned(FParentSet) then
FParentSet.RemoveForm(Self);
Finalize(FButtons);
Finalize(FRects);
end;
function TGUIForm.AddButton(Btn: TBtn): Integer;
begin
Result := Length(FButtons);
SetLength(FButtons, Result + 1);
if Btn.Type_ = btCheck then
Btn.OnClick := CheckClick;
if Btn.Type_ = btRadio then
Btn.OnClick := RadioClick;
FButtons[Result] := Btn;
end;
function TGUIForm.AddLabel(const Lbl: TLbl): Integer;
begin
Result := Length(FLabels);
SetLength(FLabels, Result + 1);
FLabels[Result] := Lbl;
end;
procedure TGUIForm.AddRect(const Rect: TRect);
begin
SetLength(FRects, Length(FRects) + 1);
FRects[High(FRects)] := Rect;
end;
procedure TGUIForm.Draw;
var
i: Integer;
FormRec: PFormRec;
begin
Render2D.Enter;
Render2D.Move(FX, FY, false);
if Assigned(FParentSet) then
FormRec := FParentSet.FindForm(Self)
else
FormRec := nil;
DrawForm(BtnState(Assigned(FParentSet) and (FParentSet.FirstForm = FormRec), IsMoving, Assigned(FormRec) and FormRec.Locked));
for i := 0 to High(FRects) do
DrawRect(FRects[i]);
for i := 0 to High(FLabels) do
DrawLabel(FLabels[i]);
for i := 0 to High(FButtons) do
DrawButton(FButtons[i], BtnState(i = FActive, i = FLast, i = FTabStop));
Render2D.Leave;
end;
procedure TGUIForm.Update;
var
FormRec: PFormRec;
begin
if FClose then
begin
Self.Free;
Exit;
end;
if Assigned(FParentSet) then
begin
with Core.MouseCursor do
FormRec := FParentSet.FormAt(X, Y);
if Assigned(FormRec) and ((FormRec.Form <> Self) or ((FormRec.Form = Self) and FormRec.Locked)) then
FActive := -1;
end;
end;
procedure TGUIForm.Close;
begin
FClose := true;
end;
function TGUIForm.Event(Event: TCoreEvent): Boolean;
begin
if Event is TKeyEvent then
with Event as TKeyEvent do
Result := KeyEvent(Key, EvType)
else if Event is TMouseEvent then
with Event as TMouseEvent do
Result := MouseEvent(Button, EvType, Cursor)
else if Event is TCharEvent then
Result := CharEvent((Event as TCharEvent).Chr)
else
Result := false;
end;
function TGUIForm.MouseEvent(Button: Integer; Event: TMouseEvents; Cursor: TPoint): Boolean;
begin
MapCursor(Cursor);
Result := PointInRect(Cursor, Rect(0, 0, FWidth, FHeight));
FActive := BtnAt(Cursor);
case Event of
meMove: if IsMoving then
begin
FX := FX + Cursor.X - FDragPoint.X;
FY := FY + Cursor.Y - FDragPoint.Y;
end;
meDown:
begin
if Button = mbLeft then
FLast := FActive;
FTabStop := -1;
if PointInRect(Cursor, Rect(0, 0, FWidth, FCaptHeight)) then
FDragPoint := Cursor;
end;
meUp:
begin
if Button = mbLeft then
begin
if (FActive >= 0) and (FLast = FActive) and FButtons[FActive].Enabled and Assigned(FButtons[FActive].OnClick) then
begin
FLast := -1;
FButtons[FActive].OnClick(@FButtons[FActive]);
end
else FLast := -1;
end;
FTabStop := -1;
FDragPoint := Point(0, 0);
end;
end;
end;
function TGUIForm.KeyEvent(Key: Integer; Event: TKeyEvents): Boolean;
begin
Result := false;
if (Event = keDown) then
begin
case Key of
VK_TAB: if Core.KeyPressed[VK_SHIFT]
then Dec(FTabStop)
else Inc(FTabStop);
VK_UP: Dec(FTabStop);
VK_DOWN: Inc(FTabStop);
VK_SHIFT, VK_SPACE: ;
else begin
FTabStop := -1;
Exit;
end;
end;
if FTabStop < 0 then
FTabStop := High(FButtons);
if FTabStop > High(FButtons) then
FTabStop := 0;
Result := true;
end
else if (Key = VK_SPACE) and FButtons[FTabStop].Enabled and Assigned(FButtons[FTabStop].OnClick) then
begin
FButtons[FTabStop].OnClick(@FButtons[FTabStop]);
Result := true;
Exit;
end;
end;
function TGUIForm.CharEvent(C: Char): Boolean;
begin
Result := false;
end;
procedure TGUIForm.SetColor(State: TBtnState; const ColorSet: TColorSet; Enabled: Boolean = true);
var
Color: TColor;
begin
if Enabled then
begin
Color := ColorSet.Default;
if bsHighlighted in State then
Color := ColorSet.Highlighted;
if bsPushed in State then
Color := ColorSet.Activated;
end
else Color := ColorSet.Disabled;
gleColor(Color);
end;
procedure TGUIForm.DrawForm(State: TBtnState);
begin
Render2D.LineWidth(1);
gleColor(clFormBackground);
Render2D.DrawRect(0, 0, FWidth, FHeight);
SetColor(State, FormCapt, not (fsLocked in State));
Render2D.DrawRect(0, 0, FWidth, FCaptHeight);
gleColor(clFormBorder);
Render2D.DrawRectBorder(0, 0, FWidth, FHeight);
gleColor(clFormCaptText);
Render2D.TextOut(Font, (FWidth - Render2D.TextWidth(Font, FCaption)) div 2, (FCaptHeight - Render2D.TextHeight(Font)) div 2, FCaption);
end;
procedure TGUIForm.DrawButton(const Btn: TBtn; State: TBtnState);
var
TextX, TextY: Integer;
Text: string;
begin
Render2D.LineWidth(2);
case Btn.Type_ of
btPush:
begin
SetColor(State, BtnBackground, Btn.Enabled);
Render2D.DrawRect(Btn.X, Btn.Y, Btn.Width, Btn.Height);
SetColor(State, BtnBorder, Btn.Enabled);
Render2D.DrawRectBorder(Btn.X, Btn.Y, Btn.Width, Btn.Height);
TextX := Max((Btn.Width - Render2D.TextWidth(Font, Btn.Caption)) div 2, 0);
end;
btCheck, btRadio:
begin
SetColor(State, BtnBorder, Btn.Enabled);
if Btn.Checked then
Render2D.DrawRect(Btn.X + 3, Btn.Y + 3, Btn.Height - 6, Btn.Height - 6);
Render2D.DrawRectBorder(Btn.X, Btn.Y, Btn.Height, Btn.Height);
TextX := Min(Btn.Height + 5, Btn.Width);
end;
end;
Text := Btn.Caption;
TextY := (Btn.Height - Render2D.TextHeight(Font)) div 2;
while (Text <> '') and (Render2D.TextWidth(Font, Text) + TextX > Btn.Width) do
Delete(Text, Length(Text), 1);
SetColor(State, BtnText, Btn.Enabled);
Render2D.TextOut(Font, Btn.X + TextX, Btn.Y + TextY, Text);
if bsTabStop in State then
begin
glLineStipple(1, $F0F0);
glEnable(GL_LINE_STIPPLE);
gleColor(clTabStop);
Render2D.DrawRectBorder(Btn.X, Btn.Y, Btn.Width, Btn.Height);
glDisable(GL_LINE_STIPPLE);
end;
end;
procedure TGUIForm.DrawRect(const Rect: TRect);
begin
Render2D.LineWidth(2);
gleColor(BtnBorder.Default);
Render2D.DrawRectBorder(Rect);
end;
procedure TGUIForm.DrawLabel(const Lbl: TLbl);
var
Text: string;
TextX: Integer;
begin
with Lbl do
begin
if Color <> 0
then gleColor(Color)
else gleColor(clText);
Text := Caption;
while (Text <> '') and (Render2D.TextWidth(Font, Text) > Width) do
Delete(Text, Length(Text), 1);
case Align of
laLeft: TextX := X;
laCenter: TextX := X + (Width - Render2D.TextWidth(Font, Text)) div 2;
laRight: TextX := X + Width - Render2D.TextWidth(Font, Text);
end;
Render2D.TextOut(Font, TextX, Y, Text);
end;
end;
function TGUIForm.BtnState(Highlighted, Pushed, TabStop: Boolean): TBtnState;
begin
Result := [];
if Highlighted then
Result := Result + [bsHighlighted];
if Pushed then
Result := Result + [bsPushed];
if TabStop then
Result := Result + [bsTabStop];
end;
function TGUIForm.IsMoving: Boolean;
begin
Result := FMovable and Core.KeyPressed[VK_LBUTTON] and (FDragPoint.X <> 0) and (FDragPoint.Y <> 0);
end;
function TGUIForm.GetName: string;
begin
if Assigned(FParentSet) then
Result := FParentSet.FormName(Self)
else
Result := ClassName;
end;
function TGUIForm.Font: Cardinal;
begin
if FCustomFont <> InvalidFont then
Result := FCustomFont
else
Result := GUIFont;
end;
function TGUIForm.GetButton(Index: Integer): PBtn;
begin
Result := nil;
if (Index < 0) or (Index > High(FButtons)) then Exit;
Result := @FButtons[Index];
end;
function TGUIForm.GetLabel(Index: Integer): PLbl;
begin
Result := nil;
if (Index < 0) or (Index > High(FLabels)) then Exit;
Result := @FLabels[Index];
end;
procedure TGUIForm.CheckClick(Btn: PBtn);
begin
//Due to optimizer bug in Delphi 7.1
if Btn^.Checked
then Btn^.Checked := false
else Btn^.Checked := true;
end;
procedure TGUIForm.RadioClick(Btn: PBtn);
var
i: Integer;
begin
for i := 0 to High(FButtons) do
if (FButtons[i].Type_ = btRadio) and (FButtons[i].Group = Btn^.Group) then
FButtons[i].Checked := false;
Btn^.Checked := true;
end;
procedure TGUIForm.MapCursor(var Cursor: TPoint);
begin
Cursor := Render2D.MapCursor(Cursor);
Dec(Cursor.X, FX);
Dec(Cursor.Y, FY);
end;
function TGUIForm.BtnAt(Point: TPoint): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to High(FButtons) do
with FButtons[i] do
if PointInRect(Point, Rect(X, Y, X + Width, Y + Height)) then
begin
Result := i;
Exit;
end;
end;
{ Functions }
procedure SetGUIFont(const Name: string; Size: Integer; Bold: Boolean);
begin
GUIFont := Render2D.CreateFont(Name, Size, Bold);
end;
function CreateSelect(Form: TGUIForm; X, Y, Width, Height: Integer; OnChange: TGUIOnClick; const PrevCaption, NextCaption: string): Integer;
var
Lbl: TLbl;
Btn: TBtn;
begin
Btn.Type_ := btPush;
Btn.X := X;
Btn.Y := Y;
Btn.Width := Height;
Btn.Height := Height;
Btn.OnClick := OnChange;
Btn.Enabled := true;
Btn.Caption := PrevCaption;
Btn.Tag := -1;
Form.AddButton(Btn);
Btn.X := X + Width - Height;
Btn.Caption := NextCaption;
Btn.Tag := 1;
Form.AddButton(Btn);
Lbl.X := X + Height;
Lbl.Y := Y + (Height - Render2D.TextHeight(Form.Font)) div 2;
Lbl.Width := Width - 2 * Height;
Lbl.Align := laCenter;
Lbl.Color := 0;
Result := Form.AddLabel(Lbl);
Form.AddRect(Rect(X + Height, Y, X + Width - Height, Y + Height));
end;
function CreateMenu(Form: TGUIForm; X, Y, BtnWidth, BtnHeight, BtnSpacing: Integer; Items: array of TMenuItem): TMenuItems;
var
Btn: TBtn;
i: Integer;
begin
SetLength(Result, Length(Items));
Btn.Type_ := btPush;
Btn.X := X;
Btn.Width := BtnWidth;
Btn.Height := BtnHeight;
Btn.Enabled := true;
for i := 0 to High(Items) do
begin
Btn.Y := Y + i * (BtnHeight + BtnSpacing);
Btn.Caption := Items[i].Caption;
Btn.Tag := Items[i].Tag;
Btn.OnClick := Items[i].OnClick;
Result[i] := Form.AddButton(Btn);
end;
end;
end.
|
unit
DibImage;
interface
{$MINENUMSIZE 4}
uses
Windows;
type
HDIBIMAGE = Pointer; // 设备无关位图句柄定义
TDibImage = class
constructor Create();
destructor Destroy();
function Width() : Integer;
function Height() : Integer;
function Pitch() : Integer;
function BitCount() : Integer;
function ImageSize() : Integer;
function GetBitmapInfo() : PBITMAPINFO;
function GetBits() : PBYTE;
function Load(const lpszPathName : PWideChar) : BOOL;
function Save(const lpszPathName : PWideChar) : BOOL;
function HeaderSize(lpbi : PBITMAPINFO = nil) : Integer;
function SetContent(cx, cy, nBitCount : Integer) : BOOL;
procedure Clear();
function Blt(hDC: HDC; x, y: Integer; cx: Integer = -1; cy : Integer = -1; xSrc : Integer = 0; ySrc :Integer = 0): BOOL;
private
m_nPitch : Integer;
m_lpBits : PBYTE;
m_lpBmpInfo : PBITMAPINFO;
end;
//var
implementation
{ TDibImage }
constructor TDibImage.Create;
begin
end;
destructor TDibImage.Destroy;
begin
Clear;
end;
function TDibImage.BitCount: Integer;
begin
if nil <> m_lpBmpInfo then
Result := m_lpBmpInfo.bmiHeader.biBitCount;
end;
function TDibImage.GetBitmapInfo: PBITMAPINFO;
begin
Result := m_lpBmpInfo;
end;
function TDibImage.GetBits: PBYTE;
begin
Result := m_lpBits;
end;
function TDibImage.Width: Integer;
begin
if nil <> m_lpBmpInfo then
Result := m_lpBmpInfo.bmiHeader.biWidth;
end;
function TDibImage.Height: Integer;
begin
if nil <> m_lpBmpInfo then
Result := m_lpBmpInfo.bmiHeader.biHeight;
end;
function TDibImage.ImageSize: Integer;
begin
if nil <> m_lpBmpInfo then
Result := m_lpBmpInfo.bmiHeader.biSizeImage;
end;
function TDibImage.HeaderSize(lpbi: PBITMAPINFO): Integer;
var
nSize : Integer;
nColor : Integer;
begin
nSize := 0;
if lpbi = nil then
lpbi := m_lpBmpInfo;
if lpbi <> nil then
begin
nSize := sizeof(BITMAPINFOHEADER);
if(lpbi.bmiHeader.biBitCount <= 8) then
begin
nColor := lpbi.bmiHeader.biClrUsed;
if (nColor = 0) then
nColor := 1 shl lpbi.bmiHeader.biBitCount;
nSize := nSize + sizeof(RGBQUAD) * nColor;
end;
end;
Result := nSize;
end;
//#define DIBPITCH(cx, bit) (((bit * cx + 31) & ~31) >> 3)
function DIBPITCH(cx, bit : Integer) : Integer;
begin
Result := ((bit * cx + 31) and (not 31)) shr 3;
end;
function TDibImage.Save(const lpszPathName: PWideChar): BOOL;
var
bRet : Boolean;
hFile : THandle;
fd : BITMAPFILEHEADER;
dwWrited : DWORD;
begin
bRet := FALSE;
ZeroMemory(@fd, SizeOf(fd));
dwWrited := 0;
if m_lpBits <> nil then
begin
hFile := CreateFileW( lpszPathName,
GENERIC_WRITE,
FILE_SHARE_READ,
nil,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
0);
if(hFile <> INVALID_HANDLE_VALUE) then
begin
fd.bfType := $4d42;
fd.bfSize := sizeof(BITMAPFILEHEADER) + HeaderSize() + ImageSize();
fd.bfReserved1 := 0;
fd.bfReserved2 := 0;
fd.bfOffBits := sizeof(BITMAPFILEHEADER) + HeaderSize();
dwWrited := 0;
WriteFile(hFile, fd, sizeof(BITMAPFILEHEADER), dwWrited, nil);
WriteFile(hFile, m_lpBmpInfo^, HeaderSize(), dwWrited, nil);
WriteFile(hFile, GetBits()^, ImageSize(), dwWrited, nil);
CloseHandle(hFile);
bRet := TRUE;
end;
end;
Result := bRet;
end;
function TDibImage.Load(const lpszPathName: PWideChar): BOOL;
var
bRet : BOOL;
hFile : THandle;
fd : BITMAPFILEHEADER;
id : BITMAPINFOHEADER;
dwRead : DWORD;
nColor : Integer;
begin
bRet := FALSE;
ZeroMemory(@fd, SizeOf(fd));
ZeroMemory(@id, SizeOf(id));
dwRead := 0;
nColor := 0;
hFile := CreateFileW( lpszPathName,
GENERIC_READ,
FILE_SHARE_READ,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN,
0);
if(hFile <> INVALID_HANDLE_VALUE) then
begin
dwRead := 0;
ReadFile(hFile, fd, sizeof(BITMAPFILEHEADER), dwRead, nil);
if(fd.bfType = $4d42) then
begin
ReadFile(hFile, id, sizeof(BITMAPINFOHEADER), dwRead, nil);
if(id.biSizeImage = 0) then
id.biSizeImage := DIBPITCH(id.biWidth, id.biBitCount) * id.biHeight;
if(SetContent(id.biWidth, id.biHeight, id.biBitCount)) then
begin
CopyMemory(Pointer(m_lpBmpInfo), Pointer(@id), sizeof(BITMAPINFOHEADER));
if(id.biBitCount <= 8) then
begin
nColor := id.biClrUsed;
if(nColor = 0) then
nColor := 1 shl id.biBitCount;
ReadFile(hFile, m_lpBmpInfo.bmiColors, sizeof(RGBQUAD) * nColor, dwRead, nil);
end;
ReadFile(hFile, GetBits()^, ImageSize(), dwRead, nil);
bRet := TRUE;
end;
end;
CloseHandle(hFile);
end;
Result := bRet;
end;
function TDibImage.Pitch: Integer;
begin
if 0 <> m_nPitch then
begin
if nil <> m_lpBmpInfo then
m_nPitch := DIBPITCH(m_lpBmpInfo.bmiHeader.biWidth, m_lpBmpInfo.bmiHeader.biBitCount);
end;
Result := m_nPitch;
end;
procedure TDibImage.Clear;
begin
FreeMem(Pointer(m_lpBits));
FreeMem(Pointer(m_lpBmpInfo));
m_nPitch := 0;
m_lpBits := 0;
m_lpBmpInfo := 0;
end;
function TDibImage.SetContent(cx, cy, nBitCount: Integer): BOOL;
var
nHeaderSize : Integer;
dwMemSize : Integer;
begin
Result := TRUE;
if (cx = Width()) and (cy = Height()) and (nBitCount = BitCount()) then
Exit;
Clear();
nHeaderSize := sizeof(BITMAPINFOHEADER);
if(nBitCount <= 8) then
nHeaderSize := nHeaderSize + (1 shl nBitCount) * sizeof(RGBQUAD);
m_nPitch := DIBPITCH(cx, nBitCount);
dwMemSize := m_nPitch * cy;
GetMem(m_lpBmpInfo, nHeaderSize); // Dispose(m_lpBmpInfo);
ZeroMemory(m_lpBmpInfo, nHeaderSize);
m_lpBmpInfo.bmiHeader.biSize := sizeof(BITMAPINFOHEADER);
m_lpBmpInfo.bmiHeader.biWidth := cx;
m_lpBmpInfo.bmiHeader.biHeight := cy;
m_lpBmpInfo.bmiHeader.biPlanes := 1;
m_lpBmpInfo.bmiHeader.biBitCount := nBitCount;
m_lpBmpInfo.bmiHeader.biSizeImage := dwMemSize;
GetMem(m_lpBits, dwMemSize + 1024);
ZeroMemory(m_lpBits, dwMemSize + 1024);
end;
function TDibImage.Blt(hDC: HDC; x, y, cx, cy, xSrc, ySrc: Integer): BOOL;
var
iRet: Integer;
nHeight: Integer;
BitsInfo: TBitmapInfo;
lpbi: PBITMAPINFO;
pBits: PBYTE;
begin
lpbi := m_lpBmpInfo;
pBits := m_lpBits;
if (lpbi = nil) then
begin
result := FALSE;
Exit;
end;
if (pBits = nil) then
pBits := pbyte(pchar(lpbi) + 40);
iRet := 0;
if(pBits <> nil) then
begin
if(cx < 0) then cx := lpbi.bmiHeader.biWidth;
if(cy < 0) then cy := lpbi.bmiHeader.biHeight;
{
hOldPal := 0;
hPalette1 := 0;
if(lpbi.bmiHeader.biBitCount <= 8) then
begin
hPalette1 := MakePalette(lpbi);
hOldPal := SelectPalette(hDC, hPalette1, TRUE);
RealizePalette(hDC);
end;
}
nHeight := lpbi.bmiHeader.biHeight;
iRet := SetDIBitsToDevice(hDC,
x, y, cx, cy, xSrc, nHeight - ySrc - cy,
0, nHeight, pBits,
lpbi^, DIB_RGB_COLORS);
{
if (hOldPal <> 0) then
SelectPalette(hDC, hOldPal, FALSE);
if (hPalette1 <> 0) then
DeleteObject(hPalette1);
}
end;
result := iRet <> 0;
end;
end.
|
(* Е) Вращение строки влево. Напишите процедуру для перемещения 2-го
символа на место 1-го, 3-го - на место 2-го и т.д. Первый символ должен
стать последним. *)
procedure RotateLeft(var s : string);
var
lChar : char;
begin
lChar := s[1];
Delete(s, 1, 1);
Insert(lChar, s, Length(s)+1);
end;
var
str : string;
begin
str := 'pascal';
Writeln(str);
RotateLeft(str);
Writeln(str);
end. |
unit working;
(*
Permission is hereby granted, on 24-Mar-2003, free of charge, to any person
obtaining a copy of this file (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.
Author of original version of this file: Michael Ax
*)
interface
uses
SysUtils, Messages, Classes, Graphics, Controls, Windows, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls,
OkCore, utForm;
type
{------------------------------------------------------------------------------}
{TOkBoxForm defines the look the generic OkBox. Change this form or modify the
look at runtime via TOk.OnActivate; Take care to keep the default events!
attached to FormClose and ButtonClick; The Defaults are implemented at the end.}
TWorkingMsgFormStop = procedure(Sender: TObject;Var CanStop:Boolean) of object;
TWorkingForm = class(ttpFitForm)
Panel1: TPanel;
StopLabel: TLabel;
StopButton: TBitBtn;
procedure StopButtonClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanStop: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
protected
{ Protected declarations }
fOkClose: Boolean;
fOnOkStop: TWorkingMsgFormStop;
public
{ Public declarations }
property OkClose:Boolean read fOkClose write fOkClose;
property OnOkStop: TWorkingMsgFormStop read fOnOkStop write fOnOkStop;
published
{ Published declarations }
end;
{------------------------------------------------------------------------------}
TOkFormActivate = procedure(StopForm:TForm;StopLabel:TLabel;StopButton:TButton) of object;
TWorkingMsg = class(TOk)
Form: TWorkingForm;
private
{ Private declarations }
fVisible: Boolean;
fOnFormActivate: TOkFormActivate; {used to setup form.}
protected
{ Protected declarations }
function BusyCount(Add:ShortInt):Integer;
procedure SetVisible(Flag:Boolean); Virtual;
procedure SetActive(Flag:Boolean); override;
procedure DoOkStart(Var CanStart:Boolean); override;
function FreezeFormHandle:HWND; override;
procedure SetCritical(Flag:Boolean); override;
public
{ Public declarations }
constructor Create(AOwner:TComponent); override;
procedure Reset; override;
procedure OkStopHandler(Sender:TObject;Var CanStop:Boolean);
function IsNotBusy:Boolean;
procedure BusyReset;
procedure BusyOn;
procedure BusyMsg(const Text:String);
procedure BusyOff;
published
{ Published declarations }
property Visible: Boolean read fVisible write SetVisible default true;
property OnFormActivate: TOkFormActivate read fOnFormActivate write fOnFormActivate;
end;
{------------------------------------------------------------------------------}
//procedure Register;
procedure waitNSeconds(nSeconds:DWORD; msg:TWorkingMsg);
implementation
{------------------------------------------------------------------------------}
{$R *.DFM}
procedure waitNSeconds(nSeconds:DWORD; msg:TWorkingMsg);
var
dt,i:DWORD;
begin
dt:= GetTickCount + nseconds*1000;
//
while (nSeconds>0) do begin
if (msg<>nil) and NOT msg.ok then break;
if (GetTickCount>dt) then
break;
//
i:=GetTickCount+1000;
while (GetTickCount<i) do begin
if (msg<>nil) and NOT msg.ok then break;
application.processMessages;
sleep(50);
end;
dec(nSeconds);
end;
end;
{------------------------------------------------------------------------------}
{TOkBoxUForm. *Here* is the OkBox Form code which defines ESSENTIAL events.
You can completely redefine the Form via Ok.OnActivate; Below are the
things that have to happen on the Form and CancelButton}
procedure TWorkingForm.StopButtonClick(Sender: TObject);
begin
If Assigned(fOnOkStop) then {if a OnOkStop proc is defined, allow closing.}
fOnOkStop(Sender,fOkClose);
end;
procedure TWorkingForm.FormCloseQuery(Sender: TObject; var CanStop: Boolean);
begin
StopButtonClick(Sender);
CanStop:=fOkClose; {Form Property can be reset via fOnOkStop proc}
end;
procedure TWorkingForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ Action:=caFree;} {can't free all the time; keep one instance up to reset.}
end;
{------------------------------------------------------------------------------}
constructor TWorkingMsg.Create(AOwner:TComponent);
begin
inherited create(AOwner);
fVisible:=true;
end;
procedure TWorkingMsg.SetVisible(Flag:Boolean);
{must be much stronger on memory issues?
just not call activate if not visible!}
begin
if flag<>fVisible then begin
fVisible:=Flag;
if assigned(Form) then
Form.Visible:=Flag;
end;
end;
procedure TWorkingMsg.SetActive(Flag:Boolean);
begin
if Enabled and Flag<>Active then begin
inherited SetActive(Flag);
if not Active and assigned(Form) then {do we have one?}
Form.hide{Close};
end;
end;
procedure TWorkingMsg.SetCritical(Flag:Boolean);
{OkTry can not be stopped when in a critical section}
begin
if flag<>Critical then begin
inherited SetCritical(Flag);
if assigned(Form) then
Form.StopButton.Enabled:=not Critical;
end;
end;
procedure TWorkingMsg.DoOkStart(Var CanStart:Boolean);
begin
Inherited DoOkStart(CanStart);
if CanStart then begin
Application.CreateForm(TWorkingForm,Form);
Form.OnOkStop:=OkStopHandler;
Form.OkClose:=True;
if assigned(fOnFormActivate) then
fOnFormActivate(tForm(Form),Form.StopLabel,Form.StopButton);
if fVisible then begin
Form.Show;
Form.Update;
end;
end;
end;
function TWorkingMsg.FreezeFormHandle:HWND;
begin
result:=Form.Handle;
end;
procedure TWorkingMsg.OkStopHandler(Sender:TObject;Var CanStop:Boolean);
begin
if Critical then {can not exit in a critical section!}
CanStop:=False {let the user beware!}
else begin
Active:=False; {try to turn off.. ancestor will now call user's CanCanel proc}
CanStop:=Stop; {if that proc concurs, we allow the OkBoxform to close}
{That's all. The Active Flag has already been set to false when we return}
end;
end;
procedure TWorkingMsg.Reset;
{unconditional deactivate. very useful while setting up OkTryes. put a call
on a button somewhere to allow you to break out of things regardless of what you
coded! very helpful during development (to me anyway) it is not used inside here}
begin
inherited Reset;
if assigned(Form) then {do we have one?}
with Form do begin {begin manual override <g>}
OnOkStop:=nil; {no denying the exit this time}
OkClose:=True; {manually allow Close-- that'll set the vars.}
end;
Active:=False;
if assigned(Form) then begin
Form.Free;
Form:=nil;
end;
end;
{------------------------------------------------------------------------------}
{ BUSY.. }
{------------------------------------------------------------------------------}
{the following is a set of procs to manage telling the user that we're busy.}
{in order to implement this well, we're tracking how often the box has been turned
on and off, placing it and removing it as needed.}
var
Count:Integer;
c:TCursor;
function TWorkingMsg.BusyCount(Add:ShortInt):Integer;
{keep track of how often we've been turned on.}
{parameters used to combine get/set}
begin
Count:=Count+Add;
if Count<=0 then begin
Count:=0;
Screen.Cursor:=c;
end
else
if Count=Add then begin {just turned on}
c:=Screen.Cursor;
Screen.Cursor:=crHourGlass;
end;
Result:=Count;
end;
function TWorkingMsg.IsNotBusy:Boolean;
{inquire about the box status and syncronize the counter if it's off}
begin
Result:=Stop;
if Result then
if BusyCount(0)>0 then
BusyCount(-BusyCount(0));
end;
procedure TWorkingMsg.BusyOn;
{Turn it on anyway!! (resetting the box) and up the counter}
begin
OkOn;
BusyCount(1);
end;
procedure TWorkingMsg.BusyMsg(const Text:String);
{could stall! this is why this functionality belongs into StopBox! and TOK!}
begin
Form.StopLabel.Caption:=Text;
end;
procedure TWorkingMsg.BusyOff;
{turn off only when we're counting back to 0 and it's on in the second place}
begin
if BusyCount(0)=1 then
if not IsNotBusy then
OkOff;
BusyCount(-1);
end;
procedure TWorkingMsg.BusyReset;
begin
if BusyCount(0)>0 then
BusyCount(-BusyCount(0));
BusyOff;
end;
//----------------------------------------------------------------------
//procedure Register;
//begin
// RegisterComponents('TPACK', [TWorkingMsg]);
//end;
//----------------------------------------------------------------------
initialization
Count:=0;
c:=crDefault;
end.
|
unit MyStack;
interface
type PStack = ^TStack;
TStack = record
Bracket: char;
Previous: PStack;
end;
procedure Push(br: char);
function Pop: char;
var Stack: PStack = nil;
IsEmpty: boolean = true;
implementation
procedure Push(br: char);
var NewRecord: PStack;
begin
if Stack = nil then begin
New(Stack);
Stack.Bracket:=br;
Stack.Previous:=nil;
IsEmpty:=false;
end
else begin
New(NewRecord);
NewRecord.Bracket:=br;
NewRecord.Previous:=Stack;
Stack:=NewRecord;
end;
end;
function Pop: char;
var Temp: PStack;
begin
if Stack <> nil then begin
Result:=Stack.Bracket;
Temp:=Stack;
Stack:=Temp.Previous;
Dispose(Temp);
if Stack <> nil then IsEmpty:=false
else IsEmpty:=true;
end
else begin
IsEmpty:=true;
Result:=#0;
end;
end;
end.
|
unit unt3_3;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
Tfrm3_3 = class(TForm)
edtKMPH: TEdit;
edtMPS: TEdit;
lblMPS: TLabel;
lblKMPH: TLabel;
procedure edtMPSKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edtKMPHKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
function MPSToKMPH(dMps : double) : double;
function KMPHToMPS(dKmph : double) : double;
end;
var
frm3_3: Tfrm3_3;
implementation
{$R *.dfm}
function Tfrm3_3.MPSToKMPH(dMps: Double) : double;
begin
result := dMps * 3.6;
end;
procedure Tfrm3_3.edtKMPHKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
dMps, dKmph : double;
begin
dKmph := StrToFloat(self.edtKMPH.Text);
dMps := self.KMPHToMPS(dKmph);
self.edtMPS.Text := FloatToStr(dMps);
end;
procedure Tfrm3_3.edtMPSKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
dMps, dKmph : double;
begin
dMps := StrToFloat(self.edtMPS.Text);
dKmph := self.MPSToKMPH(dMps);
self.edtKMPH.Text := FloatToStr(dKmph);
end;
function Tfrm3_3.KMPHToMPS(dKmph: Double) : double;
begin
result := dKmph / 3.6;
end;
end.
|
unit VkApi.Authenticator;
interface
uses
REST.Authenticator.OAuth, REST.Utils, VkApi.Types, VkApi.Utils;
type
TVkAuthenticator = class(TOAuth2Authenticator)
private
FDisplay: TVkDisplayType;
FApiVersion: TVkApiVersion;
procedure SetDisplay(const Value: TVkDisplayType);
procedure SetApiVersion(const Value: TVkApiVersion);
public
property Display: TVkDisplayType read FDisplay write SetDisplay;
property ApiVersion: TVkApiVersion read FApiVersion write SetApiVersion;
function AuthorizationRequestURI: string;
end;
implementation
{ TVkAuthenticator }
function TVkAuthenticator.AuthorizationRequestURI: string;
begin
Result := inherited AuthorizationRequestURI;
Result := Result + '&display=' + URIEncode(VkDisplayTypeToString(
FDisplay));
Result := Result + '&v=' + URIEncode(VkApiVersionToString(FApiVersion));
end;
procedure TVkAuthenticator.SetApiVersion(const Value: TVkApiVersion);
begin
if (Value <> FApiVersion) then
begin
FApiVersion := Value;
PropertyValueChanged;
end;
end;
procedure TVkAuthenticator.SetDisplay(const Value: TVkDisplayType);
begin
if (Value <> FDisplay) then
begin
FDisplay := Value;
PropertyValueChanged;
end;
end;
end.
|
{----------------------------------------------------------------------
DEVIUM Content Management System
Copyright (C) 2004 by DEIV Development Team.
http://www.deiv.com/
$Header: /devium/Devium\040CMS\0402/Source/Common/DataBase.pas,v 1.7 2004/05/14 09:38:10 paladin Exp $
------------------------------------------------------------------------}
unit DataBase;
interface
uses
SysUtils, Classes, PluginManagerIntf, DB, DBClient, SOAPConn, xmldom,
XMLIntf, msxmldom, XMLDoc, DataBaseIntf, SettingsIntf;
type
TDB = class(TDataModule, IDataBase)
SoapConnection: TSoapConnection;
XMLDocument: TXMLDocument;
RemoteTasks: TClientDataSet;
procedure DataModuleDestroy(Sender: TObject);
procedure SoapConnectionAfterExecute(const MethodName: String;
SOAPResponse: TStream);
procedure DataModuleCreate(Sender: TObject);
private
FPluginManager: IPluginManager;
FDataPath: String;
FSettings: ISettings;
FOldName: Variant;
procedure SetDataPath(const Value: String);
procedure SetPluginManager(const Value: IPluginManager);
protected
procedure OpenDataFile(const DataBasePrefix, DataPath: String); virtual;
procedure DeleteDataFiles; virtual;
procedure OpenDataSet(DataSet: TClientDataSet; const Prefix,
Path: String); virtual;
procedure OpenRemoteTasks;
procedure SplitPath(const AFileName: String; var LocalPath,
RemotePath, FileName: String); virtual;
procedure DataSetBeforePost(DataSet: TDataSet); virtual;
procedure DataSetBeforeDelete(DataSet: TDataSet); virtual;
procedure DataSetAfterPost(DataSet: TDataSet); virtual;
public
{ работа с путем для файлов }
function GetFilesPath(DataSet: TDataSet): String; virtual;
function GetRemotePath(const LocalPath: String): String; overload; virtual;
function GetRemotePath(DataSet: TDataSet): String; overload; virtual;
function GetLocalPath(DataSet: TDataSet): String; virtual;
{ методы для данных}
procedure Open; virtual;
procedure Close; virtual;
procedure ApplyUpdates; virtual;
procedure Refresh; virtual;
function CanApplyUpdates: Boolean; virtual;
function GetStatsuBarString: String; virtual;
{ работа с очередью }
procedure AddFile(DataSet: TDataSet; const AFileName: String);
procedure DelFile(const AFileName: String);
procedure DelDir(ADirName: String);
procedure RenFile(AOldName, NewName: String);
procedure RenDir(AOldName, NewName: String);
procedure GetFile(AFileName: String);
procedure GetDir(ADirName: String);
{ прочие методы для данных }
function GetNextSortOrder(DataSet: TDataSet; const AFieldName: String;
const AFilter: String = ''): Integer; virtual;
procedure ReSort(DataSet: TDataSet; const AFieldName: String; ADelta: Integer;
const AFilter: String = ''); virtual;
{ properties }
property PluginManager: IPluginManager read FPluginManager write SetPluginManager;
property DataPath: String read FDataPath write SetDataPath;
property Settings: ISettings read FSettings;
end;
const
REMOTE_SERVER_DATASET_TAG = 100;
NAME_FIELD = 'name';
implementation
uses ZLIBEX, EncdDecd, FilesLib,
ProgressCopyFrm, Controls, DeviumLib, Variants, Math;
{$R *.dfm}
{ TDB }
procedure TDB.ApplyUpdates;
var
F: TFiles;
fi: TFile;
i: Integer;
DataSet: TClientDataSet;
AFilter: String;
begin
F := TFiles.Create;
try
F.URL := Settings.HttpRoot + 'upload_server.php';
AFilter := '';
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TClientDataSet) then
begin
DataSet := TClientDataSet(Components[i]);
if Assigned(DataSet.RemoteServer) then
begin
AFilter := AFilter + Format('dataset=''%s'' or ', [DataSet.Name]);
end;
end;
end;
AFilter := Copy(AFilter, 1, Length(AFilter) - 4); // remode ' or '
with RemoteTasks do
begin
DisableControls;
Filter := AFilter;
Filtered := True;
First;
while not EOF do
begin
fi := F.Add;
fi.LocalPath := FieldByName('filename').AsString;
fi.RemotePath := GetRemotePath(fi.LocalPath);
fi.Action := FieldByName('action').AsInteger;
Next;
end;
if F.Count > 0 then
begin
GetProgressCopyForm(F);
while not EOF do Delete;
end;
Filtered := False;
EnableControls;
end;
finally
f.Free;
end;
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TClientDataSet) then
begin
DataSet := TClientDataSet(Components[i]);
if Assigned(DataSet.RemoteServer) then
DataSet.ApplyUpdates(-1);
end;
end;
end;
function TDB.CanApplyUpdates: Boolean;
var
DataSet: TClientDataSet;
i: Integer;
begin
Result := False;
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TClientDataSet) then
begin
DataSet := TClientDataSet(Components[i]);
if Assigned(DataSet.RemoteServer) then
Result := Result or (DataSet.ChangeCount > 0);
end;
end;
end;
procedure TDB.Close;
var
i: Integer;
begin
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TClientDataSet) then
TClientDataSet(Components[i]).Close;
end;
end;
procedure TDB.Open;
begin
Settings.SetupSoapConnection(SoapConnection);
OpenDataFile(Settings.DataBasePrefix, FDataPath);
OpenRemoteTasks;
end;
procedure TDB.Refresh;
begin
Close;
DeleteDataFiles;
Open;
end;
procedure TDB.SetDataPath(const Value: String);
begin
FDataPath := IncludeTrailingPathDelimiter(Value);
end;
procedure TDB.SetPluginManager(const Value: IPluginManager);
begin
FPluginManager := Value;
FPluginManager.GetPlugin(ISettings, FSettings);
end;
procedure TDB.DataModuleDestroy(Sender: TObject);
begin
Close;
end;
procedure TDB.OpenDataFile(const DataBasePrefix, DataPath: String);
var
DataSet: TClientDataSet;
i: Integer;
begin
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TClientDataSet) then
begin
DataSet := TClientDataSet(Components[i]);
if Assigned(DataSet.RemoteServer) then
OpenDataSet(DataSet, DataBasePrefix, DataPath)
end;
end;
end;
procedure TDB.DeleteDataFiles;
var
DataSet: TClientDataSet;
i: Integer;
begin
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TClientDataSet) then
begin
DataSet := TClientDataSet(Components[i]);
if Assigned(DataSet.RemoteServer) then
DeleteFile(DataSet.FileName);
end;
end;
end;
procedure TDB.OpenDataSet(DataSet: TClientDataSet; const Prefix,
Path: String);
begin
DataSet.ProviderName := Prefix + DataSet.ProviderName;
DataSet.FileName := Path + DataSet.ProviderName + '.xml';
DataSet.BeforePost := DataSetBeforePost;
DataSet.BeforeDelete := DataSetBeforeDelete;
DataSet.AfterPost := DataSetAfterPost;
DataSet.Open;
DataSet.SaveToFile();
end;
procedure TDB.SoapConnectionAfterExecute(const MethodName: String;
SOAPResponse: TStream);
var
s: String;
begin
if MethodName = 'AS_ApplyUpdates' then Exit;
SOAPResponse.Position := 0;
XMLDocument.LoadFromStream(SOAPResponse);
s := XMLDocument.DocumentElement.ChildNodes[0].ChildNodes[0].ChildNodes[0].Text;
s := DecodeString(s);
s := ZDecompressStr(s);
s := EncodeString(s);
XMLDocument.DocumentElement.ChildNodes[0].ChildNodes[0].ChildNodes[0].Text := s;
SOAPResponse.Size := 0;
XMLDocument.SaveToStream(SOAPResponse);
end;
procedure TDB.DataModuleCreate(Sender: TObject);
var
DataSet: TClientDataSet;
i: Integer;
begin
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TClientDataSet) then
begin
DataSet := TClientDataSet(Components[i]);
if DataSet.Tag = REMOTE_SERVER_DATASET_TAG then
DataSet.RemoteServer := SoapConnection;
end;
end;
end;
procedure TDB.OpenRemoteTasks;
begin
RemoteTasks.FileName := DataPath + RemoteTasks.Name + '.xml';
try
RemoteTasks.Open;
except
RemoteTasks.CreateDataSet;
end;
RemoteTasks.LogChanges := False;
RemoteTasks.SaveToFile();
end;
procedure TDB.AddFile(DataSet: TDataSet; const AFileName: String);
begin
with RemoteTasks do
begin
// если файл уже есть с писке ?
if Locate('filename;action', VarArrayOf([AFileName, POST_FILE]),
[loPartialKey]) then Exit;
// если с писке на удаление
if Locate('filename;action', VarArrayOf([AFileName, DELETE_FILE]),
[loPartialKey]) then Delete;
Append;
FieldValues['filename'] := AFileName;
FieldValues['action'] := POST_FILE;
FieldValues['dataset'] := DataSet.Name;
FieldValues['key'] := DataSet.Fields[0].Value;
Post;
end;
end;
procedure TDB.DelDir(ADirName: String);
begin
with RemoteTasks do
begin
// если файл уже есть с писке ?
while Locate('filename', ADirName, [loPartialKey]) do
Delete;
Append;
FieldValues['filename'] := ADirName;
FieldValues['action'] := DELETE_DIR;
Post;
end;
end;
procedure TDB.DelFile(const AFileName: String);
begin
with RemoteTasks do
begin
// если файл уже есть с писке ?
if Locate('filename;action', VarArrayOf([AFileName, DELETE_FILE]),
[loPartialKey]) then Exit;
// если с писке на удаление
if Locate('filename;action', VarArrayOf([AFileName, POST_FILE]),
[loPartialKey]) then
begin
Delete;
Exit;
end;
Append;
FieldValues['filename'] := AFileName;
FieldValues['action'] := DELETE_FILE;
Post;
end;
end;
procedure TDB.RenDir(AOldName, NewName: String);
begin
with RemoteTasks do
begin
Append;
FieldValues['filename'] := AOldName;
FieldValues['new_filename'] := NewName;
FieldValues['action'] := RENAME_DIR;
Post;
end;
end;
procedure TDB.RenFile(AOldName, NewName: String);
begin
with RemoteTasks do
begin
Append;
FieldValues['filename'] := AOldName;
FieldValues['new_filename'] := NewName;
FieldValues['action'] := RENAME_FILE;
Post;
end;
end;
procedure TDB.GetDir(ADirName: String);
begin
end;
procedure TDB.GetFile(AFileName: String);
begin
end;
procedure TDB.SplitPath(const AFileName: String; var LocalPath, RemotePath,
FileName: String);
begin
LocalPath := ExtractFilePath(AFileName);
FileName := ExtractFileName(AFileName);
RemotePath := Copy(LocalPath, Length(FDataPath), Length(RemotePath));
RemotePath := DosPathToUnixPath(RemotePath);
end;
// больба с блобавми, нулевае блобы
procedure TDB.DataSetBeforePost(DataSet: TDataSet);
var
I: Integer;
begin
FOldName := NULL;
for I := 0 to DataSet.FieldCount - 1 do
begin
if (DataSet.Fields[i] is TBlobField) and (DataSet.Fields[i].IsNull) then
DataSet.Fields[i].Value := #32;
if (DataSet.Fields[i].FieldName = NAME_FIELD) then
FOldName := DataSet.Fields[i].Value;
end;
end;
function TDB.GetFilesPath(DataSet: TDataSet): String;
begin
Result := '';
end;
// попвтка удалить все файла которые пренадлежат данной записи
procedure TDB.DataSetBeforeDelete(DataSet: TDataSet);
var
sl: TStringList;
i: Integer;
begin
sl := TStringList.Create;
try
sl.Text := GetFilesPath(DataSet);
for i := 0 to sl.Count - 1 do
begin
if FileExists(sl[i]) then
begin
DeleteFile(sl[i]);
DelFile(sl[i]);
end
else
begin
ForceDeleteDir(sl[i]);
DelDir(sl[i]);
end;
end;
finally
sl.Free;
end;
end;
// получение статцсной информации
function TDB.GetStatsuBarString: String;
var
DataSet: TClientDataSet;
i: Integer;
begin
Result := '';
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TClientDataSet) then
begin
DataSet := TClientDataSet(Components[i]);
if DataSet.Tag = REMOTE_SERVER_DATASET_TAG then
Result := Result + Format('%s: %d; ', [DataSet.Name, DataSet.ChangeCount]);
end;
end;
end;
function TDB.GetRemotePath(const LocalPath: String): String;
begin
Result := Copy(LocalPath, Length(DataPath), Length(LocalPath));
Result := {Settings.HttpRoot + }DosPathToUnixPath(Result);
end;
function TDB.GetRemotePath(DataSet: TDataSet): String;
begin
Result := GetFilesPath(DataSet);
Result := GetRemotePath(Result);
end;
procedure TDB.DataSetAfterPost(DataSet: TDataSet);
var
FileList: String;
sl: TStringList;
i: Integer;
NewValue: Variant;
begin
FileList := GetFilesPath(DataSet);
if FileList <> '' then
begin
sl := TStringList.Create;
try
sl.Text := FileList;
for i := 0 to sl.Count - 1 do
if ExtractFileName(sl[i]) <> '' then // не папка
AddFile(DataSet, sl[i]);
finally
sl.Free;
end;
end;
if not VarIsNull(FOldName) then
begin
NewValue := DataSet.FieldByName(NAME_FIELD).Value;
if NewValue <> FOldName then ;
{ TODO : Rename }
end;
end;
function TDB.GetLocalPath(DataSet: TDataSet): String;
begin
Result := '';
end;
function TDB.GetNextSortOrder(DataSet: TDataSet; const AFieldName: String;
const AFilter: String = ''): Integer;
var
SavePlace: TBookmark;
OldFilter: String;
OldFiltered: Boolean;
begin
OldFilter := '';
OldFiltered := False;
Result := 0;
with DataSet do
begin
DisableControls;
SavePlace := GetBookmark;
if Length(AFilter) > 0 then
begin
OldFilter := Filter;
OldFiltered := Filtered;
Filter := AFilter;
Filtered := True;
end;
try
First;
while not EOF do
begin
Result := Max(Result, FieldByName(AFieldName).AsInteger);
Next;
end;
if Length(AFilter) > 0 then
begin
Filter := OldFilter;
Filtered := OldFiltered;
end;
GotoBookmark(SavePlace);
finally
FreeBookmark(SavePlace);
end;
EnableControls;
end;
Result := Result + 10;
end;
procedure TDB.ReSort(DataSet: TDataSet; const AFieldName: String;
ADelta: Integer; const AFilter: String);
var
Sort: Integer;
Key: Variant;
OldFilter: String;
OldIndexFieldNames: String;
OldFiltere: Boolean;
begin
{ TODO -oPaladin : Filter }
with TClientDataSet(DataSet) do
begin
DisableControls;
Key := Fields[0].Value;
// save filter
OldFilter := Filter;
OldFiltere := Filtered;
// set filter
OldIndexFieldNames := IndexFieldNames;
IndexFieldNames := AFieldName;
Filter := AFilter;
if Length(AFilter) > 0 then
Filtered := True;
// go
IndexFieldNames := AFieldName;
Edit;
FieldValues[AFieldName] := ADelta + FieldValues[AFieldName];
Post;
Sort := RecordCount;
Last;
while not BOF do
begin
Edit;
FieldValues[AFieldName] := Sort * 10;
Post;
Prior;
Dec(Sort);
end;
//restore filter
Filter := OldFilter;
Filtered := OldFiltere;
IndexFieldNames := OldIndexFieldNames;
// return
EnableControls;
Locate(Fields[0].FieldName, Key, [loPartialKey]);
end;
end;
end.
|
unit UFolioCaptura;
interface
uses
Classes;
type
TFolioCaptura = class
private
FIdFolio : int64; {ID DEL FOLIO QUE SE ASIGNA}
FCodigoFolio : string; {CODIGO DEL FOLIO}
FCodigoFolioSigu : string; {CODIGO DEL FOLIO SIGUIENTE}
FSecuenciaFolio : int32; {CONSECUTIVO DEL FOLIO}
FIdDatoPlanilla : string; {ID DE LA INFORMACION DE LA PLANILLA SI LA TIENE}
FNombreImagen : string; {NOMBRE DEL ARCHIVO CON EXTENSION}
FIdCarpeta : Int32; {ID DE LA CARPETA A LA QUE PERTENECE EL FOLIO}
FCodigoCarpeta : string; {CODIGO DE LA CARPETA A LA QUE PERTENECE EL FOLIO}
FClaseCarpeta : Char; {INDICA SI LA CARPETA ES DE CREACION O INSERCION}
FIdTarea : Int32; {ID DE LA TAREA DE LA CARPETADEL FOLIO}
FCodigoCaja : string; {NOMBRE DE LA CAJA A LA QUE PERTENECE LA IMAGEN}
FDescSerieDocum : string; {DESCRIPCION SERIE DOCUMENTAL}
FDescTipoSerieDocum : string; {DESCRIPCION TIPO DE SERIE DOCUMENTAL}
FDescSubSerieDocum : string; {DESCRIPCION SUB SERIE DOCUMENTAL}
FDiasBloqueo : Int32; {DIAS QUE LLEVA EL BLOQUEO DEL FOLIO SI YA SE ASIGNÓ}
FHorasBloqueo : TTime; {HORAS,MINUTOS Y SEGUNDOS QUE LLEVA EL BLOQUEO DEL FOLIO SI YA SE ASIGNÓ}
FServidorFtp : string; {DIRECCION IP DEL FTP}
FRutaFtp : string; {RUTA DE LA CARPETA EN EL FTP}
FImagenLocal : string; {ARCHIVO DE IMAGEN CON RUTA COMPLETA EN ELEQUIPO LOCAL}
FFechaNomina : string; {FECHA DE NOMINA REGISTRADA EN TABLA DATOS PLAINILLA}
FIdFondo : Int32; {ID DE LA ENTIDAD FONDO}
FPeriodoCotizacion : string; {PERIODO DE COTIZACIÓN PARA PLANILLAS DE APORTES}
FFechaPagoBanco : string; {FECHA DE PAGO AL BANCO PARA PLANILLAS DE APORTES}
FTipoPlanilla : char; {TIPO DE PLANILLA N:NOMINA A:APORTES}
FNovedadesFolio : TStringList; {NOVEDADES (OBSERVACIONES) AL FOLIO SIN CAPTURA}
public
property IdFolio : int64 read FIdFolio write FIdFolio;
property CodigoFolio : string read FCodigoFolio write FCodigoFolio;
property CodigoFolioSigu : string read FCodigoFolioSigu write FCodigoFolioSigu;
property SecuenciaFolio : int32 read FSecuenciaFolio write FSecuenciaFolio;
property IdDatoPlanilla : string read FIdDatoPlanilla write FIdDatoPlanilla;
property NombreImagen : string read FNombreImagen write FNombreImagen;
property IdCarpeta : int32 read FIdCarpeta write FIdCarpeta;
property CodigoCarpeta : string read FCodigoCarpeta write FCodigoCarpeta;
property ClaseCarpeta : char read FClaseCarpeta write FClaseCarpeta;
property IdTarea : int32 read FIdTarea write FIdTarea;
property CodigoCaja : string read FCodigoCaja write FCodigoCaja;
property DescSerieDocum : string read FDescSerieDocum write FDescSerieDocum;
property DescTipoSerieDocum : string read FDescTipoSerieDocum write FDescTipoSerieDocum;
property DescSubSerieDocum : string read FDescSubSerieDocum write FDescSubSerieDocum;
property DiasBloqueo : int32 read FDiasBloqueo write FDiasBloqueo;
property HorasBloqueo : TTime read FHorasBloqueo write FHorasBloqueo;
property ServidorFtp : string read FServidorFtp write FServidorFtp;
property RutaFtp : string read FRutaFtp write FRutaFtp;
property ImagenLocal : string read FImagenLocal write FImagenLocal;
property FechaNomina : string read FFechaNomina write FFechaNomina;
property IdFondo : Int32 read FIdFondo write FIdFondo;
property PeriodoCotizacion : string read FPeriodoCotizacion write FPeriodoCotizacion;
property FechaPagoBanco : string read FFechaPagoBanco write FFechaPagoBanco;
property TipoPlanilla : Char read FTipoPlanilla write FTipoPlanilla;
property NovedadesFolio : TStringList read FNovedadesFolio write FNovedadesFolio;
{CONSTRUCTOR - DESTRUCTOR}
constructor Create;
destructor Destroy;
end;
implementation
{$REGION 'CONSTRUTOR AND DESTRUCTOR'}
constructor TFolioCaptura.Create;
begin
FFechaNomina := '';
FIdFondo := 0;
FPeriodoCotizacion := '';
FFechaPagoBanco := '';
FNovedadesFolio:= TStringList.Create;
end;
destructor TFolioCaptura.Destroy;
begin
FNovedadesFolio.free;
end;
{$ENDREGION}
end.
|
unit OError;
{Обработка ошибок}
interface
procedure Error(Msg : string);
procedure Expected(Msg : string);
procedure Warning(Msg : string);
{=======================================================}
implementation
uses
OText, OScan;
procedure Error(Msg : string);
var
ELine : integer;
begin
ELine := Line;
while (Ch <> chEOL) and (Ch <> chEOT) do NextCh;
if Ch = chEOT then WriteLn;
WriteLn('^': LexPos);
Writeln('(Строка ', ELine, ') Ошибка: ', Msg);
WriteLn;
WriteLn('Нажмите ВВОД');
Readln;
Halt(1);
end;
procedure Expected(Msg: string);
begin
Error('Ожидается ' + Msg);
end;
procedure Warning(Msg : string);
begin
WriteLn;
Writeln('Предупреждение: ', Msg);
WriteLn;
end;
end.
|
{ MIT License
Copyright (c) 2020 Viacheslav Komenda
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. }
{$F+}
unit scr;
interface
var
screen : pchar;
cursor : word;
procedure cls(clr : byte);
procedure cln(x, y : integer; clr : byte);
procedure print(x, y : integer; clr : byte; s : string);
procedure printhl(x, y : integer; clr, hlclr : byte; s : string);
procedure hprint(x, y:integer; clr : byte; c : char; len : integer);
procedure vprint(x, y:integer; clr : byte; c : char; len : integer);
procedure chcolor(x, y:integer; clr : byte; len: integer);
procedure push;
procedure pop;
procedure pick;
procedure show;
procedure locate(x, y:integer);
procedure cursor_off;
procedure cursor_on;
procedure cursor_big;
function get_cursor:word;
procedure set_cursor(w : word);
procedure set_blink(on : boolean);
function getwidth:integer;
function getheight:integer;
function getx:integer;
function gety:integer;
procedure scroll_up(stx, sty, w, h, lines : integer);
procedure scroll_down(stx, sty, w, h, lines : integer);
procedure spinner_start;
procedure spinner_stop;
procedure Fade0;
procedure FadeIn;
procedure FadeOut;
procedure reset_palette;
procedure gray_palette;
procedure WaitRetrace;
implementation
uses kminput, dos, detect;
const vseg : word = 0;
SPINNER : string[8] = '|/-\|/-\';
type
PScr=^TScr;
TScr=record
prev : PScr;
size : word;
x, y : integer;
buf : byte;
end;
const
last_scr_buf : PScr = nil;
FADE_STEP = 8;
FADE_DELAY = 15;
var
screen_size, line_size : word;
spinnerValue : word;
spinnerOldInt : pointer;
spinnerOn : boolean;
palette : array[0..(256 * 3)] of byte;
vga : boolean;
function getheight : integer;assembler;
asm
push ds
mov ax, seg0040
mov ds, ax
mov al, byte ptr[$0084]
xor ah, ah
inc ax
pop ds
end;
function getwidth : integer;assembler;
asm
push ds
mov ax, seg0040
mov ds, ax
mov ax, word ptr[$004a]
pop ds
end;
{ in: ax = x, cx = y }
{ out: es:di }
procedure buf_es_di;assembler;
asm
mov bx, ax
mov ax, line_size
mul cx
xchg bx, ax
shl ax, 1
add ax, bx
les di, screen
add di, ax
end;
procedure cls(clr : byte);assembler;
asm
push es
mov ax, screen_size
shr ax, 1
xchg ax, cx
mov ah, clr
mov al, ' '
les di, screen
cld
repz stosw
pop es
end;
procedure cln(x, y : integer; clr : byte);assembler;
asm
push es
call getwidth
push ax
mov ax, x
mov cx, y
call buf_es_di
pop cx
sub cx, x
mov ah, clr
mov al, ' '
cld
repz stosw
pop es
end;
procedure hprint(x, y : integer; clr : byte; c : char; len : integer);assembler;
asm
push es
mov ax, x
mov cx, y
call buf_es_di
xor ch, ch
mov cx, len
xor ch, ch
mov ah, clr
mov al, c
cld
repz stosw
pop es
end;
procedure chcolor(x, y : integer; clr : byte; len : integer);assembler;
asm
push es
mov ax, x
mov cx, y
call buf_es_di
inc di
mov cx, len
mov al, clr
cld
or cl, cl
jz @end
@cont:
stosb
inc di
dec cl
jnz @cont
@end:
pop es
end;
procedure vprint(x, y : integer; clr : byte; c : char; len : integer);assembler;
asm
push es
mov ax, x
mov cx, y
call buf_es_di
mov bx, line_size
sub bx, 2
mov cx, len
mov ah, clr
mov al, c
cld
or cl, cl
jz @end
@cont:
stosw
add di, bx
dec cl
jnz @cont
@end:
pop es
end;
procedure print(x, y:integer; clr : byte; s : string);assembler;
asm
push es
push ds
mov ax, x
mov cx, y
call buf_es_di
mov ah, clr
lds si, s
lodsb
or al, al
jz @end
mov cl, al
cld
@cont:
lodsb
stosw
dec cl
jnz @cont
@end:
pop ds
pop es
end;
procedure printhl(x, y : integer; clr, hlclr : byte; s : string);assembler;
asm
push es
push ds
mov ax, x
mov cx, y
call buf_es_di
mov ah, clr
mov bh, hlclr
lds si, s
lodsb
or al, al
jz @end
mov cl, al
cld
@cont:
lodsb
cmp al, '~'
jnz @print
xchg ah, bh
jmp @cont2
@print:
stosw
@cont2:
dec cl
jnz @cont
@end:
pop ds
pop es
end;
procedure show;assembler;
asm
call mouse_hide
call WaitRetrace
push es
push ds
mov ax, screen_size
shr ax, 1
mov cx, ax
mov ax, vseg
mov es, ax
lds si, screen
xor di, di
cld
repz movsw
pop ds
pop es
call mouse_show
end;
procedure locate(x, y : integer);assembler;
asm
push ds
mov ax, word ptr [seg0040]
mov ds, ax
mov bh, byte ptr [$0062]
pop ds
mov dl, byte ptr [x]
mov dh, byte ptr [y]
mov ah, 2
int $10
end;
function getx : integer;assembler;
asm
push ds
mov ax, word ptr [seg0040]
mov ds, ax
mov bh, byte ptr [$0062]
pop ds
mov ah, 3
int $10
mov al,dl
xor ah,ah
end;
function gety : integer;assembler;
asm
push ds
mov ax, word ptr [seg0040]
mov ds, ax
mov bh, byte ptr [$0062]
pop ds
mov ah, 3
int $10
mov al,dh
xor ah,ah
end;
procedure push;
var p : PScr;
begin
getmem(p, screen_size + sizeof(TScr) - 1);
p^.size := screen_size;
p^.prev := last_scr_buf;
p^.x := getx;
p^.y := gety;
move(screen^, p^.buf, p^.size);
last_scr_buf := p;
end;
procedure pop;
var p : PScr;
begin
if last_scr_buf = nil then exit;
WaitRetrace;
move(last_scr_buf^.buf, screen^, last_scr_buf^.size);
p := last_scr_buf;
last_scr_buf := last_scr_buf^.prev;
scr.locate(p^.x, p^.y);
freemem(p, p^.size + sizeof(TScr) - 1);
end;
procedure pick;
begin
if last_scr_buf = nil then exit;
WaitRetrace;
move(last_scr_buf^.buf, screen^, last_scr_buf^.size);
scr.locate(last_scr_buf^.x, last_scr_buf^.y);
end;
procedure set_cursor(w : word);assembler;
asm
mov cx, w
mov ah, 1
int $10
end;
function get_cursor : word;assembler;
asm
mov ah, $0f
int $10
mov ah, 3
int $10
mov ax, cx
end;
procedure cursor_off;
begin
set_cursor($2020);
end;
procedure cursor_on;
begin
set_cursor(cursor);
end;
procedure cursor_big;
begin
set_cursor(cursor and $FF);
end;
procedure set_blink(on : boolean);assembler;
asm
mov bl, byte ptr [on]
mov ax, $1003
int $10
end;
procedure scroll_up(stx, sty, w, h, lines : integer);
var i : integer;
scrw : integer;
slines : integer;
cur : integer;
begin
i := 0; w := w shl 1; scrw := getwidth;
slines := (lines * scrw) shl 1;
cur := (stx + (sty * scrw)) shl 1;
scrw := scrw shl 1;
WaitRetrace;
while i < (h - lines) do begin
move(screen[slines + cur], screen[cur], w);
inc(cur, scrw);
inc(i);
end;
end;
procedure scroll_down(stx, sty, w, h, lines : integer);
var i : integer;
scrw : integer;
slines : integer;
cur : integer;
begin
i := h - lines; w := w shl 1; scrw := getwidth;
slines := (lines * scrw) shl 1;
cur := (stx + i * scrw) shl 1;
scrw := scrw shl 1;
WaitRetrace;
while i >= 0 do begin
move(screen[cur], screen[slines + cur], w);
dec(cur, scrw);
dec(i);
end;
end;
procedure spinner1c;interrupt;
var spin : char;
begin
spin := SPINNER[((spinnerValue shr 3) mod length(SPINNER)) + 1];
mem[vseg:0] := Ord(spin);
mem[vseg:1] := $20;
screen^ := spin;
screen[1] := #$20;
Inc(spinnerValue);
if spinnerValue = 90 then gray_palette;
end;
procedure spinner_start;
begin
if spinnerOn then exit;
spinnerValue := 0;
SetIntVec($1c, @spinner1c);
spinnerOn := true;
end;
procedure spinner_stop;
begin
SetIntVec($1c, spinnerOldInt);
reset_palette;
spinnerOn := false;
end;
procedure delay(ms : word); assembler;
asm
mov ax, 1000
mul ms
mov cx, dx
mov dx, ax
mov ah, $86
int $15
end;
procedure save_palette;
var i : integer;
begin
if not vga then exit;
for i := 0 to 255 do begin
Port[$3C7] := i;
Palette[i * 3] := Port[$3C9];
Palette[i * 3 + 1] := Port[$3C9];
Palette[i * 3 + 2] := Port[$3C9];
end;
end;
procedure set_color(num, r, g, b : byte);
begin
Port[$3C8] := num;
Port[$3C9] := r;
Port[$3C9] := g;
Port[$3C9] := b;
end;
procedure reset_palette;
var i : integer;
begin
if not vga then exit;
for i := 0 to 255 do begin
set_color(i, palette[i * 3], palette[i * 3 + 1], palette[i * 3 + 2]);
end;
end;
procedure gray_palette;
var i, n : integer;
begin
if not vga then exit;
for i := 0 to 255 do begin
n := palette[i * 3] + palette[i * 3 + 1] + palette[i * 3 + 2];
n := n div 6;
set_color(i, n, n, n);
end;
end;
procedure Fade0;
var i : integer;
begin
if not vga then exit;
WaitRetrace;
for i := 0 to 255 do begin
set_color(i, 0, 0, 0);
end;
end;
procedure FadeIn;
var op1, op2, op3 : byte;
p1, p2, p3 : byte;
i, j : integer;
begin
if not vga then exit;
Fade0;
for j := 0 to 7 do begin
WaitRetrace;
for i := 0 to 255 do begin
Port[$3C7] := i;
op1 := Port[$3C9];
op2 := Port[$3C9];
op3 := Port[$3C9];
p1 := palette[i * 3];
p2 := palette[i * 3 + 1];
p3 := palette[i * 3 + 2];
if op1 + FADE_STEP <= p1 then Inc(op1, FADE_STEP) else op1 := p1;
if op2 + FADE_STEP <= p2 then Inc(op2, FADE_STEP) else op2 := p2;
if op3 + FADE_STEP <= p3 then Inc(op3, FADE_STEP) else op3 := p3;
set_color(i, op1, op2, op3);
end;
delay(FADE_DELAY);
end;
end;
procedure FadeOut;
var op1, op2, op3 : byte;
i, j : integer;
begin
if not vga then exit;
for j := 0 to 7 do begin
WaitRetrace;
for i := 0 to 255 do begin
Port[$3C7] := i;
op1 := Port[$3C9];
op2 := Port[$3C9];
op3 := Port[$3C9];
if op1 >= FADE_STEP then Dec(op1, FADE_STEP) else op1 := 0;
if op2 >= FADE_STEP then Dec(op2, FADE_STEP) else op2 := 0;
if op3 >= FADE_STEP then Dec(op3, FADE_STEP) else op3 := 0;
set_color(i, op1, op2, op3);
end;
delay(FADE_DELAY);
end;
reset_palette;
end;
procedure WaitRetrace; assembler;
asm
mov dx, $3da
@l1: in al, dx
test al, 8
jnz @l1
@l2: in al, dx
test al, 8
jz @l2
end;
begin
GetIntVec($1c, spinnerOldInt);
spinnerOn := false;
vga := Detect.IsVga;
save_palette;
cursor := scr.get_cursor;
if (not vga) and IsMonochrome then vseg := segb000 else vseg := segb800;
scr.set_blink(false);
screen_size := (scr.getwidth * scr.getheight) shl 1;
line_size := scr.getwidth shl 1;
getmem(screen, screen_size);
move(mem[vseg:0], screen^, screen_size);
mouse_show;
end.
|
unit
TClip;
{$MINENUMSIZE 4}
interface
uses
Windows;
type
HCLIP = Pointer; // BaseClip对象句柄定义。
HIMAGECLIP = Pointer; // ImageClip对象句柄定义。
HTITLECLIP = Pointer; // TitleClip对象句柄定义。
HVIDEOCLIP = Pointer; // VideoClip对象句柄定义。
HAUDIOCLIP = Pointer; // AudioClip对象句柄定义。
HTRANSCLIP = Pointer; // TransClip对象句柄定义。
{$IFNDEF CLIP_PARAM_DEF}
{$DEFINE CLIP_PARAM_DEF}
// Clip类型定义
type
ClipType =
(
CT_NONE,
CT_VIDEO, // 视频
CT_IMAGE, // 图像
CT_TITLE, // 字幕
CT_AUDIO, // 音频
CT_TRANSITION // 转场
);
// 操作状态
type
ClipWorkState =
(
CWS_NORMAL = $0001, // 正常
CWS_SELECTED = $0002, // 选中状态
CWS_FOCUS = $0004 // 拥有焦点
);
// 属性状态
type
ClipAttributeState =
(
CAS_NORMAL = $0001, // 正常
CAS_LOCKED = $0002, // 锁定状态
CAS_FROZEN = $0004 // 冻结状态
);
{$ENDIF} // CLIP_PARAM_DEF
{$IFNDEF IMAGE_RESIZE_METHOD_DEFINE}
{$DEFINE IMAGE_RESIZE_METHOD_DEFINE}
IMAGE_RESIZE_METHOD =
(
IRM_FULLSCREEN, // stretch to full screen
IRM_ORIGINAL_SCALE, // keep scale, fit to size of output
IRM_16_9, // resize to 16:9, fit to size of output
IRM_4_3, // resize to 4:3, fit to size of output
IRM_LETTERBOX,
IRM_PAN_SCAN
);
{$ENDIF} // IMAGE_RESIZE_METHOD_DEFINE
//HCLIP __stdcall TCClone(HCLIP hClip); // 复制Clip
function TCClone(hClip: HCLIP) : HCLIP; stdcall;
//HCLIP __stdcall TCCreate(ClipType nType); // 创建Clip
function TCCreate(nType: ClipType) : HCLIP; stdcall;
//int __stdcall TCRelease(HCLIP hClip); // 释放Clip
function TCRelease(hClip: HCLIP) : Integer; stdcall;
//int __stdcall TCAddRef(HCLIP hClip); // 添加引用记数
function TCAddRef(hClip: HCLIP) : Integer; stdcall;
//ClipType __stdcall TCGetType(HCLIP hClip);
function TCGetType(hClip: HCLIP) : ClipType; stdcall;
//void __stdcall TCSetBeginTime(HCLIP hClip, double dBeginTime, double dLength = -1);
procedure TCSetBeginTime(hClip: HCLIP; dBeginTime : double; dLength : double = -1); stdcall;
//double __stdcall TCGetBeginTime(HCLIP hClip);
function TCGetBeginTime(hClip: HCLIP) : double; stdcall;
//double __stdcall TCGetEndTime(HCLIP hClip);
function TCGetEndTime(hClip: HCLIP) : double; stdcall;
//double __stdcall TCGetLength(HCLIP hClip);// 获取当前长度
function TCGetLength(hClip: HCLIP) : double; stdcall;
//void __stdcall TCSetLength(HCLIP hClip, double dLength);
procedure TCSetLength(hClip: HCLIP; dLength : double); stdcall;
//DWORD __stdcall TCGetUserData(HCLIP hClip);
function TCGetUserData(hClip: HCLIP) : DWORD; stdcall;
//DWORD __stdcall TCSetUserData(HCLIP hClip, DWORD dwUserData); // 返回先前的UserData
function TCSetUserData(hClip: HCLIP; dwUserData : DWORD) : DWORD; stdcall;
//double __stdcall TCGetPhysicalLength(HCLIP hClip); // 返回Clip物理长度,仅对视频、音频Clip有效
function TCGetPhysicalLength(hClip: HCLIP) : double; stdcall;
//double __stdcall TCGetPhysicalBegin(HCLIP hClip); // 返回Clip的物理起始位置
function TCGetPhysicalBegin(hClip: HCLIP) : double; stdcall;
//void __stdcall TCSetPhysicalBegin(HCLIP hClip, double dBegin); // 设置Clip的物理起始位置
procedure TCSetPhysicalBegin(hClip: HCLIP; dBegin : double); stdcall;
//void __stdcall TCSetPhysicalLength(HCLIP hClip, double dLength); // 设置Clip的物理长度
procedure TCSetPhysicalLength(hClip: HCLIP; dLength : double); stdcall;
//extern "C" void __stdcall TCSetLabel(HCLIP hClip, const wchar_t* lpLabel); // 默认情况下:Video、Audio、Image Clip将以文件名Title作为Label,转场则用ID
procedure TCSetLabel(hClip: HCLIP; const lpLabel : PWideChar); stdcall;
//extern "C" const wchar_t* __stdcall TCGetLabel(HCLIP hClip);
function TCGetLabel(hClip: HCLIP) : PWideChar; stdcall;
//extern "C" void __stdcall TCSetFileName(HCLIP hClip, const wchar_t* lpFileName); // 仅对Video、Audio、Image Clip有效
procedure TCSetFileName(hClip: HCLIP; const lpFileName : PWideChar); stdcall;
//extern "C" const wchar_t* __stdcall TCGetFileName(HCLIP hClip);
function TCGetFileName(hClip: HCLIP) : PWideChar; stdcall;
//BOOL __stdcall TCSetBitmap(HCLIP hClip, UINT nID, HINSTANCE hInstance); // 缩略图
function TCSetBitmap(hClip: HCLIP; nID : UINT; hModule : HMODULE) : BOOL; stdcall;
//BOOL __stdcall TCSetDib(HCLIP hClip, LPBITMAPINFO lpbi, void* pBits); // 缩略图 Clip会拷贝hBitmap数据,应用程序应该自动释放位图数据
function TCSetDib(hClip: HCLIP; lpbi : PBITMAPINFO; pBits : pointer) : BOOL; stdcall;
//BOOL __stdcall TCSetHBitmap(HCLIP hClip, HBITMAP hBitmap); // 缩略图 Clip会拷贝hBitmap数据,应用程序应该自动释放hBitmap
function TCSetHBitmap(hClip: HCLIP; hBitmap : HBITMAP) : BOOL; stdcall;
//BOOL __stdcall TCAutoLoadThumbnail(HCLIP hClip); // 自动加载缩略图 调用TIMELINE_QUERY_API回调函数 回调函数应该调用以上三个函数之一来设置,如果回调失败 Timeline将自行加载缩略图 适用于CT_IMAGE的clip
function TCAutoLoadThumbnail(hClip: HCLIP) : BOOL; stdcall;
//DWORD __stdcall TCGetAttribState(HCLIP hClip);
function TCGetAttribState(hClip: HCLIP) : DWORD; stdcall;
//DWORD __stdcall TCGetWorkState(HCLIP hClip);
function TCGetWorkState(hClip: HCLIP) : DWORD; stdcall;
//int __stdcall TCGetIndex(HCLIP hClip); // 返回在Track中的索引值
function TCGetIndex(hClip: HCLIP) : Integer; stdcall;
//HCLIP __stdcall TCGetNext(HCLIP hClip);
function TCGetNext(hClip: HCLIP) : HCLIP; stdcall;
//HCLIP __stdcall TCGetPrev(HCLIP hClip);
function TCGetPrev(hClip: HCLIP) : HCLIP; stdcall;
// Title Clip
//extern "C" void __stdcall TTSetText(HTITLECLIP hClip, const wchar_t* lpText);
procedure TTSetText(hClip: HTITLECLIP; const lpText : PWideChar); stdcall;
//extern "C" const wchar_t* __stdcall TTGetText(HTITLECLIP hClip);
function TTGetText(hClip: HTITLECLIP) : PWideChar; stdcall;
// Transition Clip
//extern "C" void __stdcall TRSetTransID(HTRANSCLIP hClip, const wchar_t* lpTransID);
procedure TRSetTransID(hClip: HTRANSCLIP; const lpTransID : PWideChar); stdcall;
//extern "C" const wchar_t* __stdcall TRGetTransID(HTRANSCLIP hClip);
function TRGetTransID(hClip: HTRANSCLIP) : PWideChar; stdcall;
//HTRANSCLIP __stdcall TCGetClipTailTrans(HCLIP hClip); // 取得尾部转场
function TCGetClipTailTrans(hClip: HCLIP) : HTRANSCLIP; stdcall;
//HCLIP __stdcall TCGetTransBeginClip(HTRANSCLIP hTrClip); // 取得转场hTrClip前面的clip
function TCGetTransBeginClip(hTrClip: HTRANSCLIP) : HCLIP; stdcall;
//HTRANSCLIP __stdcall TCGetClipHeadTrans(HCLIP hClip); // 取得头部转场
function TCGetClipHeadTrans(hClip: HCLIP) : HTRANSCLIP; stdcall;
//HCLIP __stdcall TCGetTransEndClip(HTRANSCLIP hTrClip); // 取得转场hTrClip后面的clip
function TCGetTransEndClip(hTrClip: HTRANSCLIP) : HCLIP; stdcall;
//BOOL __stdcall TCSetDubbingFlag(HCLIP hClip, BOOL bHasDubbing);
function TCSetDubbingFlag(hClip: HCLIP; bHasDubbing : BOOL) : BOOL; stdcall;
//BOOL __stdcall TCHasDubbing(HCLIP hClip);
function TCHasDubbing(hClip: HCLIP) : BOOL; stdcall;
//void __stdcall TCSetMinLength(HCLIP hClip, double dMinLen);
procedure TCSetMinLength(hClip: HCLIP; dMinLen : double); stdcall;
//double __stdcall TCGetMinLength(HCLIP hClip);
function TCGetMinLength(hClip: HCLIP) : double; stdcall;
//void __stdcall TCSetAudioFadeIn(HCLIP hClip, double dFadeIn);
procedure TCSetAudioFadeIn(hClip: HCLIP; dFadeIn : double); stdcall;
//double __stdcall TCGetAudioFadeIn(HCLIP hClip);
function TCGetAudioFadeIn(hClip: HCLIP) : double; stdcall;
//void __stdcall TCSetAudioFadeOut(HCLIP hClip, double dFadeOut);
procedure TCSetAudioFadeOut(hClip: HCLIP; dFadeOut : double); stdcall;
//double __stdcall TCGetAudioFadeOut(HCLIP hClip);
function TCGetAudioFadeOut(hClip: HCLIP) : double; stdcall;
//void __stdcall TCSetVolume(HCLIP hClip, int nVolume);
procedure TCSetVolume(hClip: HCLIP; nVolume : Integer); stdcall;
//int __stdcall TCGetVolume(HCLIP hClip);
function TCGetVolume(hClip: HCLIP) : Integer; stdcall;
//void __stdcall TCSetVideoOnly(HCLIP hClip, BOOL bVideoOnly = TRUE);
procedure TCSetVideoOnly(hClip: HCLIP; bVideoOnly : BOOL = TRUE); stdcall;
//BOOL __stdcall TCIsVideoOnly(HCLIP hClip)
function TCIsVideoOnly(hClip: HCLIP) : BOOL; stdcall;
//void __stdcall TCSetAudioMute(HCLIP hClip, BOOL bAudioMute = TRUE);
procedure TCSetAudioMute(hClip: HCLIP; bAudioMute : BOOL = TRUE); stdcall;
//BOOL __stdcall TCIsAudioMute(HCLIP hClip)
function TCIsAudioMute(hClip: HCLIP) : BOOL; stdcall;
//void __stdcall TCSetResizeStyle(HCLIP hClip, IMAGE_RESIZE_METHOD uResizeStyle);
procedure TCSetResizeStyle(hClip: HCLIP; uResizeStyle : IMAGE_RESIZE_METHOD); stdcall;
//设置剪裁区域, pCropRect——剪裁区域, 0 为取消剪裁操作
//void __stdcall TCSetCropRect(HCLIP hClip, RECT* pCropRect);
procedure TCSetCropRect(hClip: HCLIP; pCropRect : PRECT); stdcall;
//设置亮度,-100~100,0保持原亮度
//void __stdcall TCSetBrightness(HCLIP hClip, int nValue);
procedure TCSetBrightness(hClip: HCLIP; nValue : Integer); stdcall;
//设置对比度,-100~100,0保持原对比度
//void __stdcall TCSetContrast(HCLIP hClip, int nValue);
procedure TCSetContrast(hClip: HCLIP; nValue : Integer); stdcall;
//设置饱和度,-100~100,0保持原饱和度
//void __stdcall TCSetSaturation(HCLIP hClip, int nValue);
procedure TCSetSaturation(hClip: HCLIP; nValue : Integer); stdcall;
//IMAGE_RESIZE_METHOD __stdcall TCGetResizeStyle(HCLIP hClip);
function TCGetResizeStyle(hClip: HCLIP) : IMAGE_RESIZE_METHOD; stdcall;
//返回剪裁区域, 0 为不使用剪裁
//const RECT* __stdcall TCGetCropRect(HCLIP hClip);
function TCGetCropRect(hClip: HCLIP) : PRECT; stdcall;
//int __stdcall TCGetBrightness(HCLIP hClip);
function TCGetBrightness(hClip: HCLIP) : Integer; stdcall;
//int __stdcall TCGetContrast(HCLIP hClip);
function TCGetContrast(hClip: HCLIP) : Integer; stdcall;
//int __stdcall TCGetSaturation(HCLIP hClip);
function TCGetSaturation(hClip: HCLIP) : Integer; stdcall;
implementation
const
DLLNAME = 'WS_Timeline.dll';
function TCClone; external DLLNAME Name 'TCClone';
function TCCreate; external DLLNAME Name 'TCCreate';
function TCRelease; external DLLNAME Name 'TCRelease';
function TCAddRef; external DLLNAME Name 'TCAddRef';
function TCGetType; external DLLNAME Name 'TCGetType';
procedure TCSetBeginTime; external DLLNAME Name 'TCSetBeginTime';
function TCGetBeginTime; external DLLNAME Name 'TCGetBeginTime';
function TCGetEndTime; external DLLNAME Name 'TCGetEndTime';
function TCGetLength; external DLLNAME Name 'TCGetLength';
procedure TCSetLength; external DLLNAME Name 'TCSetLength';
function TCGetUserData; external DLLNAME Name 'TCGetUserData';
function TCSetUserData; external DLLNAME Name 'TCSetUserData';
function TCGetPhysicalLength; external DLLNAME Name 'TCGetPhysicalLength';
function TCGetPhysicalBegin; external DLLNAME Name 'TCGetPhysicalBegin';
procedure TCSetPhysicalBegin; external DLLNAME Name 'TCSetPhysicalBegin';
procedure TCSetPhysicalLength; external DLLNAME Name 'TCSetPhysicalLength';
procedure TCSetLabel; external DLLNAME Name 'TCSetLabel';
function TCGetLabel; external DLLNAME Name 'TCGetLabel';
procedure TCSetFileName; external DLLNAME Name 'TCSetFileName';
function TCGetFileName; external DLLNAME Name 'TCGetFileName';
function TCSetBitmap; external DLLNAME Name 'TCSetBitmap';
function TCSetDib; external DLLNAME Name 'TCSetDib';
function TCSetHBitmap; external DLLNAME Name 'TCSetHBitmap';
function TCAutoLoadThumbnail; external DLLNAME Name 'TCAutoLoadThumbnail';
function TCGetAttribState; external DLLNAME Name 'TCGetAttribState';
function TCGetWorkState; external DLLNAME Name 'TCGetWorkState';
function TCGetIndex; external DLLNAME Name 'TCGetIndex';
function TCGetNext; external DLLNAME Name 'TCGetNext';
function TCGetPrev; external DLLNAME Name 'TCGetPrev';
procedure TTSetText; external DLLNAME Name 'TTSetText';
function TTGetText; external DLLNAME Name 'TTGetText';
procedure TRSetTransID; external DLLNAME Name 'TRSetTransID';
function TRGetTransID; external DLLNAME Name 'TRGetTransID';
function TCGetClipTailTrans; external DLLNAME Name 'TCGetClipTailTrans';
function TCGetTransBeginClip; external DLLNAME Name 'TCGetTransBeginClip';
function TCGetClipHeadTrans; external DLLNAME Name 'TCGetClipHeadTrans';
function TCGetTransEndClip; external DLLNAME Name 'TCGetTransEndClip';
function TCSetDubbingFlag; external DLLNAME Name 'TCSetDubbingFlag';
function TCHasDubbing; external DLLNAME Name 'TCHasDubbing';
procedure TCSetMinLength; external DLLNAME Name 'TCSetMinLength';
function TCGetMinLength; external DLLNAME Name 'TCGetMinLength';
procedure TCSetAudioFadeIn; external DLLNAME Name 'TCSetAudioFadeIn';
function TCGetAudioFadeIn; external DLLNAME Name 'TCGetAudioFadeIn';
procedure TCSetAudioFadeOut; external DLLNAME Name 'TCSetAudioFadeOut';
function TCGetAudioFadeOut; external DLLNAME Name 'TCGetAudioFadeOut';
procedure TCSetVolume; external DLLNAME Name 'TCSetVolume';
function TCGetVolume; external DLLNAME Name 'TCGetVolume';
procedure TCSetVideoOnly; external DLLNAME Name 'TCSetVideoOnly';
function TCIsVideoOnly; external DLLNAME Name 'TCIsVideoOnly';
procedure TCSetAudioMute; external DLLNAME Name 'TCSetAudioMute';
function TCIsAudioMute; external DLLNAME Name 'TCIsAudioMute';
function TCGetResizeStyle; external DLLNAME Name 'TCGetResizeStyle';
function TCGetCropRect; external DLLNAME Name 'TCGetCropRect';
function TCGetBrightness; external DLLNAME Name 'TCGetBrightness';
function TCGetContrast; external DLLNAME Name 'TCGetContrast';
function TCGetSaturation; external DLLNAME Name 'TCGetSaturation';
procedure TCSetResizeStyle; external DLLNAME Name 'TCSetResizeStyle';
procedure TCSetCropRect; external DLLNAME Name 'TCSetCropRect';
procedure TCSetBrightness; external DLLNAME Name 'TCSetBrightness';
procedure TCSetContrast; external DLLNAME Name 'TCSetContrast';
procedure TCSetSaturation; external DLLNAME Name 'TCSetSaturation';
end.
|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
}
{
Description:
some lame filtering (used by thread_client to filter some listing)
TODO: add an importable file to allow custom filtering
}
unit helper_filtering;
interface
uses
sysutils,classes2,classes,windows;
function is_copyrighted_content(const key:String):boolean;
function is_teen_content(const key:string):boolean;
function str_isWebSpam(const strin:String):boolean;
function strip_spamcomments(comments:string):string;
procedure init_keywfilter(const filterbranch:string; list:tmystringlist);
function is_filtered_text(const lostr:string; filtered_strings:tmystringlist):boolean;
implementation
uses
helper_diskio,vars_global,const_ares;
function is_filtered_text(const lostr:string; filtered_strings:tmystringlist):boolean;
var
i:integer;
lofiltered:string;
begin
result:=true;
for i:=0 to filtered_strings.count-1 do begin
lofiltered:=filtered_strings[i];
if pos(lofiltered,lostr)<>0 then begin
exit;
end;
end;
result:=False;
end;
procedure init_keywfilter(const filterbranch:string; list:tmystringlist);
var
stream:thandlestream;
str,keywordstr:string;
buffer:array[0..1023] of char;
previous_len,red:integer;
begin
if filterbranch='ChanListFilter' then begin
with list do begin
add('sex');
add('racis');
add('porn');
add('shemale');
add('fetish');
add('incest');
add('gangbang');
add('masochist');
add('razors');
end;
end;
stream:=MyFileOpen(vars_global.app_path+'\Data\'+filterbranch+'.txt',ARES_READONLY_BUT_SEQUENTIAL);
if stream=nil then exit;
with stream do begin
str:='';
while (position<size) do begin
red:=read(buffer,sizeof(buffer));
if red<1 then break;
previous_len:=length(str);
setlength(str,previous_len+red);
move(buffer,str[previous_len+1],red);
end;
end;
FreeHandleStream(stream);
if length(str)>0 then begin
if copy(str,1,3)=chr($ef)+chr($bb)+chr($bf) then delete(str,1,3); //strip utf-8 header
while (pos('#',str)=1) do delete(str,1,pos(CRLF,str)+1);
while (length(str)>0) do begin
if pos(',',str)>0 then begin
keywordstr:=copy(str,1,pos(',',str)-1);
delete(str,1,pos(',',str));
end else begin
keywordstr:=str;
str:='';
end;
list.add(keywordstr);
end;
end;
end;
function strip_spamcomments(comments:string):string;
var
locom:string;
begin
result:='';
locom:=lowercase(comments);
if pos('quickmusic',locom)=0 then
if pos('supermusic',locom)=0 then
if pos('elitemusic',locom)=0 then
if pos('musictiger',locom)=0 then
if pos('mp3finder',locom)=0 then
if pos('mp3advance',locom)=0 then
if pos('simplemp3',locom)=0 then
if pos('popgal',locom)=0 then
if pos('mp3',locom)=0 then
if pos('.com',locom)=0 then
if pos('www.',locom)=0 then
result:=comments;
end;
function str_isWebSpam(const strin:String):boolean;
begin
result:=False;
if pos('.com',strin)<>0 then result:=true else
if pos('www.',strin)<>0 then result:=true else
if pos('http',strin)<>0 then result:=true;
end;
function is_copyrighted_content(const key:String):boolean;
begin
if length(key)<12 then begin
result:=false;
exit;
end;
result:=true;
if pos('nathan stone',key)<>0 then exit;
result:=False;
end;
function is_teen_content(const key:string):boolean;
var
lokey:string;
begin
if length(key)<=2 then begin
result:=false;
exit;
end;
result:=true;
lokey:=lowercase(key);
if pos('teen',lokey)<>0 then exit else
if pos('deflor',lokey)<>0 then exit else
if pos('pedo',lokey)<>0 then exit else
if pos('bambi',lokey)<>0 then exit else
if pos('tiny',lokey)<>0 then exit else
//if pos('r@ygold',lokey)<>0 then exit else
//if pos('roygold',lokey)<>0 then exit else
if pos('ygold',lokey)<>0 then exit else
if pos('child',lokey)<>0 then exit else
if pos('underage',lokey)<>0 then exit else
if pos('kiddy',lokey)<>0 then exit else
if pos('kiddie',lokey)<>0 then exit else
if pos('lolita',lokey)<>0 then exit else
if pos('incest',lokey)<>0 then exit else
if pos('rape',lokey)<>0 then exit else
if pos('legal',lokey)<>0 then exit else
if pos('babysitter',lokey)<>0 then exit else
if pos('1yo',lokey)<>0 then exit else
if pos('2yo',lokey)<>0 then exit else
if pos('3yo',lokey)<>0 then exit else
if pos('4yo',lokey)<>0 then exit else
if pos('5yo',lokey)<>0 then exit else
if pos('6yo',lokey)<>0 then exit else
if pos('7yo',lokey)<>0 then exit else
if pos('8yo',lokey)<>0 then exit else
if pos('9yo',lokey)<>0 then exit else
if pos('0yo',lokey)<>0 then exit else
if pos('petit',lokey)<>0 then exit;
result:=false;
end;
end. |
{$include kode.inc}
unit kode_imagestrip;
// TODO
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_bitmap,
kode_canvas,
kode_math,
kode_surface;
const
// bitmapstrip orientation
kbo_vertical = 0;
kbo_horizontal = 1;
type
KImageStrip = class
private
FBitmap : KBitmap;
FSurface : KSurface;
FCount : LongInt;
FOrientation : LongInt;
FWidth : LongInt;
FHeight : LongInt;
public
constructor create(ABitmap:KBitmap; ACount:LongInt; AOrientation:LongInt=kbo_vertical);
//constructor create(ASurface:KSurface; ACount:LongInt; AOrientation:LongInt=kbo_vertical);
//constructor create(AFile:PChar; ACount:LongInt; AOrientation:LongInt=kbo_vertical);
destructor destroy; override;
procedure draw(ACanvas:KCanvas; AXpos,AYpos:LongInt; AValue:Single);
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_const,
kode_debug;
constructor KImageStrip.create(ABitmap:KBitmap; ACount:LongInt; AOrientation:LongInt=kbo_vertical);
begin
inherited create;
FBitmap := ABitmap;
FSurface := KSurface.create(ABitmap);
FCount := ACount;
FOrientation := AOrientation;
case AOrientation of
kbo_vertical:
begin
FWidth := ABitmap._width;
FHeight := ABitmap._height div ACount;
end;
kbo_horizontal:
begin
FWidth := ABitmap._width div ACount;
FHeight := ABitmap._height;
end;
end;
end;
//----------
{constructor KImageStrip.create(ASurface:KSurface; ACount:LongInt; AOrientation:LongInt=kbo_vertical);
begin
inherited create;
FBitmap := nil;
FSurface := ASurface;
FCount := ACount;
FOrientation := AOrientation;
case AOrientation of
kbo_vertical:
begin
FWidth := ASurface._width;
FHeight := ASurface._height div ACount;
end;
kbo_horizontal:
begin
FWidth := ASurface._width div ACount;
FHeight := ASurface._height;
end;
end;
end;}
//----------
{constructor KImageStrip.create(AFile:PChar; ACount:LongInt; AOrientation:LongInt=kbo_vertical);
begin
end;}
//----------
destructor KImageStrip.destroy;
begin
if Assigned(FBitmap) then FSurface.destroy;
inherited;
end;
//----------
procedure KImageStrip.draw(ACanvas:KCanvas; AXpos,AYpos:LongInt; AValue:Single);
var
s : single;
num{,ofs} : longint;
x,y{,w,h}: longint;
begin
s := Single(FCount) * AValue;
num := KMinI( FCount-1, trunc(s) );
//KTrace([ 'FCount=',FCount,', AValue=',AValue,' :: s=',s,', trunc(s)=',trunc(s),', num=',num,KODE_CR]);
case FOrientation of
kbo_vertical:
begin
//ACanvas.drawSurface(AXpos,AYpos,FSurface,0,ofs,FWidth,ofs+FHeight);
x := 0;
y := FHeight*num;
end;
kbo_horizontal:
begin
//ofs := FWidth*num;
//ACanvas.drawSurface(AXpos,AYpos,FSurface,ofs,0,ofs+FWidth,FHeight);
x := FWidth*num;
y := 0;
end;
end;
//ACanvas.drawSurface(AXpos,AYpos,FSurface,x,y,FWidth,FHeight);
ACanvas.blendSurface(AXpos,AYpos,FSurface,x,y,FWidth,FHeight);
end;
//----------------------------------------------------------------------
end.
|
(*======================================================================*
| unitResourceRCData |
| |
| Encapsulates RC Data resources in resources |
| |
| Copyright (c) Colin Wilson 2001,2008 |
| |
| All rights reserved |
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 1.0 06/02/2001 CPWW Original |
| 16/5/2008 CPWW Tiburon version |
*======================================================================*)
unit unitResourceRCData;
interface
uses Windows, Classes, SysUtils, Contnrs, unitResourceDetails, ZLib, unitResourceGraphics;
type
TRCDataResourceDetails = class (TResourceDetails)
private
fDelegate : TResourceDetails;
public
class function GetBaseType : UnicodeString; override;
procedure ChangeData (newData : TMemoryStream); override;
function GetData: TMemoryStream; override;
property Delegate : TResourceDetails read fDelegate;
end;
TRCDataDescriptionResourceDetails = class (TRCDataResourceDetails)
private
function GetDescription: UnicodeString;
procedure SetDescription(const Value: UnicodeString);
protected
class function SupportsRCData (const AName : UnicodeString; Size : Integer; data : Pointer) : Boolean; override;
public
property Description : UnicodeString read GetDescription write SetDescription;
end;
TRCDataFormResourceDetails = class (TRCDataResourceDetails)
private
function GetText: UnicodeString;
procedure SetText(const Value: UnicodeString);
protected
class function SupportsRCData (const AName : UnicodeString; Size : Integer; data : Pointer) : Boolean; override;
public
property Text : UnicodeString read GetText write SetText;
end;
TRCDataCompressedBitmapResourceDetails = class (TRCDataResourceDetails)
protected
class function SupportsRCData (const AName : UnicodeString; Size : Integer; data : Pointer) : Boolean; override;
public
constructor Create (AParent : TResourceModule; ALanguage : Integer; const AName, AType : UnicodeString; ASize : Integer; AData : pointer); override;
end;
TCompressedBitmapResourceDetails = class (TBitmapResourceDetails)
private
fCompressedData : TMemoryStream;
protected
function GetData : TMemoryStream; override;
constructor Create (AParent : TResourceModule; ALanguage : Integer; const AName, AType : UnicodeString; ASize : Integer; AData : pointer); override;
public
constructor CreateNew (AParent : TResourceModule; ALanguage : Integer; const AName : UnicodeString); override;
destructor Destroy; override;
procedure ChangeData (data : TMemoryStream); override;
end;
TPackageEnvironment = (pePreV4, peUndefine, peBCB, peDelphi);
TModuleType = (mtEXE, mtPackageDLL, mtLibraryDLL, mtUndefine);
TRCDataPackagesResourceDetails = class (TRCDataResourceDetails)
private
fRequiresList : TStrings;
fContainsList : TStrings;
fFlags : DWORD;
function GetRequiresCount: Integer;
function GetRequires(idx : Integer): string;
function GetContainsCount: Integer;
function GetContains(idx: Integer): string;
function GetContainsFlag(idx: Integer): Byte;
procedure DecodeData;
function GetCheckForDuplicates: Boolean;
function GetDesignTimeOnly: Boolean;
function GetEnvironment: TPackageEnvironment;
function GetModuleType: TModuleType;
function GetNeverBuild: Boolean;
function GetRunTimeOnly: Boolean;
protected
class function SupportsRCData (const AName : UnicodeString; Size : Integer; data : Pointer) : Boolean; override;
public
destructor Destroy; override;
procedure ChangeData (newData : TMemoryStream); override;
property RequiresCount : Integer read GetRequiresCount;
property Requires [idx : Integer] : string read GetRequires;
property ContainsCount : Integer read GetContainsCount;
property Contains [idx : Integer] : string read GetContains;
property ContainsFlag [idx : Integer] : Byte read GetContainsFlag;
property NeverBuild : Boolean read GetNeverBuild;
property DesignTimeOnly : Boolean read GetDesignTimeOnly;
property RunTimeOnly : Boolean read GetRunTimeOnly;
property CheckForDuplicates : Boolean read GetCheckForDuplicates;
property Environment : TPackageEnvironment read GetEnvironment;
property ModuleType : TModuleType read GetModuleType;
end;
implementation
type
TPkgName = packed record
HashCode : Byte;
Name : array [0..255] of AnsiChar;
end;
PPkgName = ^TPkgName;
{ PackageUnitFlags:
bit meaning
-----------------------------------------------------------------------------------------
0 | main unit
1 | package unit (dpk source)
2 | $WEAKPACKAGEUNIT unit
3 | original containment of $WEAKPACKAGEUNIT (package into which it was compiled)
4 | implicitly imported
5..7 | reserved
}
PUnitName = ^TUnitName;
TUnitName = packed record
Flags : Byte;
HashCode: Byte;
Name: array[0..255] of AnsiChar;
end;
{ TRCDataResourceDetails }
procedure TRCDataResourceDetails.ChangeData(newData: TMemoryStream);
begin
if Delegate <> Nil then
Delegate.ChangeData(newData)
else
inherited;
end;
class function TRCDataResourceDetails.GetBaseType: UnicodeString;
begin
result := IntToStr (Integer (RT_RCDATA));
end;
function TRCDataResourceDetails.GetData: TMemoryStream;
begin
if Delegate <> Nil then
result := Delegate.Data
else
result := inherited;
end;
{ TRCDataDescriptionResourceDetails }
function TRCDataDescriptionResourceDetails.GetDescription: UnicodeString;
begin
Result := PWideChar (data.Memory);
end;
procedure TRCDataDescriptionResourceDetails.SetDescription(
const Value: UnicodeString);
begin
data.Size := (Length (Value) + 1) * SizeOf (WideChar);
Move (Value [1], data.memory^, (Length (Value) + 1) * SizeOf (WideChar))
end;
class function TRCDataDescriptionResourceDetails.SupportsRCData(
const AName: UnicodeString; Size: Integer; data: Pointer): Boolean;
begin
Result := CompareText (AName, 'DESCRIPTION') = 0;
end;
{ TRCDataPackagesResourceDetails }
procedure TRCDataPackagesResourceDetails.ChangeData(
newData: TMemoryStream);
begin
inherited;
FreeAndNil (fRequiresList);
FreeAndNil (fContainsList);
end;
procedure TRCDataPackagesResourceDetails.DecodeData;
var
p : PAnsiChar;
i, Count : Integer;
pkg : PPkgName;
unt : PUnitName;
begin
if not Assigned (fRequiresList) then
begin
fRequiresList := TStringList.Create;
fContainsList := TStringList.Create;
p := Data.Memory;
fFlags := PDWORD (p)^;
Inc (p, SizeOf (DWORD)); // Flags
Count := PInteger (p)^;
Inc (p, SizeOf (Integer));
for i := 0 to Count - 1 do
begin
pkg := PPkgName (p);
fRequiresList.Add (String (pkg^.Name));
Inc (p, 2 + lstrlena (pkg^.Name));
end;
Count := PInteger (p)^;
Inc (p, SizeOf (Integer));
for i := 0 to Count - 1 do
begin
unt := PUnitName (p);
fContainsList.AddObject (String (unt^.Name), TObject (Integer (unt.Flags)));
Inc (p, 3 + lstrlena (unt^.Name));
end
end
end;
destructor TRCDataPackagesResourceDetails.Destroy;
begin
fRequiresList.Free;
fContainsList.Free;
inherited;
end;
function TRCDataPackagesResourceDetails.GetCheckForDuplicates: Boolean;
begin
DecodeData;
Result := (fFlags and 8) = 0
end;
function TRCDataPackagesResourceDetails.GetContains(idx: Integer): string;
begin
DecodeData;
Result := fContainsList [idx]
end;
function TRCDataPackagesResourceDetails.GetContainsCount: Integer;
begin
DecodeData;
Result := fContainsList.Count
end;
function TRCDataPackagesResourceDetails.GetContainsFlag(
idx: Integer): Byte;
begin
DecodeData;
Result := Integer (fContainsList.Objects [idx])
end;
function TRCDataPackagesResourceDetails.GetDesignTimeOnly: Boolean;
begin
DecodeData;
Result := (fFlags and 2) <> 0
end;
function TRCDataPackagesResourceDetails.GetEnvironment: TPackageEnvironment;
begin
DecodeData;
Result := TPackageEnvironment ((fFlags shr 26) and 3);
end;
function TRCDataPackagesResourceDetails.GetModuleType: TModuleType;
begin
DecodeData;
Result := TModuleType (fFlags shr 30);
end;
function TRCDataPackagesResourceDetails.GetNeverBuild: Boolean;
begin
DecodeData;
Result := (fFlags and 1) <> 0
end;
function TRCDataPackagesResourceDetails.GetRequires(idx : Integer): string;
begin
DecodeData;
Result := fRequiresList [idx]
end;
function TRCDataPackagesResourceDetails.GetRequiresCount: Integer;
begin
DecodeData;
Result := fRequiresList.Count
end;
function TRCDataPackagesResourceDetails.GetRunTimeOnly: Boolean;
begin
DecodeData;
Result := (fFlags and 4) <> 0
end;
class function TRCDataPackagesResourceDetails.SupportsRCData(
const AName: UnicodeString; Size: Integer; data: Pointer): Boolean;
begin
Result := CompareText (AName, 'PACKAGEINFO') = 0;
end;
{ TRCDataFormResourceDetails }
function ObjectTextToUTF8 (src : TStream) : UTF8String;
var
ach : AnsiChar;
outp : Integer;
token : AnsiString;
i : Integer;
begin
SetLength (result, src.Size - src.Position);
outp := 1;
while src.Read (ach, 1) = 1 do
begin
while ach = '#' do
begin
token := '';
repeat
if src.Read (ach, 1) <> 1 then
break;
if not (ach in ['0'..'9']) then
break;
token := token + ach
until false;
if token = '' then
break;
token := UTF8Encode (WideChar (StrToInt (String (token))));
for i := 1 to Length (token) do
begin
result [outp] := token [i];
Inc (outp)
end
end;
result [outp] := ach;
Inc (outp)
end;
SetLength (result, outp-1)
end;
function TRCDataFormResourceDetails.GetText: UnicodeString;
var
m : TMemoryStream;
off : TStreamOriginalFormat;
s : TStrings;
st : string;
begin
s := Nil;
m := TMemoryStream.Create;
try
data.Seek (0, soFromBeginning);
off := sofUnknown;
ObjectBinaryToText (data, m, off);
s := TStringList.Create;
m.Seek(0, soFromBeginning);
s.LoadFromStream(m);
st := s.Text;
result := UTF8ToUnicodeString (AnsiString (st))
finally
m.Free;
s.Free
end
end;
procedure TRCDataFormResourceDetails.SetText(const Value: UnicodeString);
var
m, m1 : TMemoryStream;
us : UTF8String;
begin
m := Nil;
us := Utf8Encode (Value);
m1 := TMemoryStream.Create;
m1.Write(us [1], Length (us));
try
m := TMemoryStream.Create;
m1.Seek(0, soFromBeginning);
ObjectTextToBinary (m1, m);
ChangeData (m);
finally
m.Free;
m1.Free;
end
end;
class function TRCDataFormResourceDetails.SupportsRCData(
const AName: UnicodeString; Size: Integer; data: Pointer): Boolean;
begin
Result := (Size > 0) and (strlcomp (PAnsiChar (data), 'TPF0', 4) = 0);
end;
{ TRCDataCompressedBitmapResourceDetails }
constructor TRCDataCompressedBitmapResourceDetails.Create(
AParent: TResourceModule; ALanguage: Integer; const AName,
AType: UnicodeString; ASize: Integer; AData: pointer);
var
delBitmap : TBitmapResourceDetails;
ms : TMemoryStream;
begin
inherited;
delBitmap := TCompressedBitmapResourceDetails.CreateNew (Nil, ALanguage, AName);
fDelegate := delBitmap;
ms := TMemoryStream.Create;
try
ms.Write(AData^, ASize);
delBitmap.ChangeData(ms);
finally
ms.Free
end
end;
class function TRCDataCompressedBitmapResourceDetails.SupportsRCData(
const AName: UnicodeString; Size: Integer; data: Pointer): Boolean;
var
outBuffer : pointer;
inSize, outSize : Integer;
procedure ZDecompressPartial(const inBuffer: Pointer; inSize: Integer;
out outBuffer: Pointer; out outSize: Integer);
var
zstream: TZStreamRec;
delta: Integer;
begin
FillChar(zstream, SizeOf(TZStreamRec), 0);
delta := (inSize + 255) and not 255;
outSize := delta;
GetMem(outBuffer, outSize);
try
zstream.next_in := inBuffer;
zstream.avail_in := inSize;
zstream.next_out := outBuffer;
zstream.avail_out := outSize;
if InflateInit_(zstream, ZLIB_VERSION, SizeOf(TZStreamRec)) < 0 then
raise EZDecompressionError.Create ('ZLib error');
if inflate (zstream, Z_NO_FLUSH) >= 0 then
Inc (outSize, delta)
else
raise EZDecompressionError.Create ('ZLib error');
inflateEnd (zstream);
except
outSize := 0;
ReallocMem (outBuffer, 0);
raise
end
end;
begin
inSize := Size;
if inSize > 1024 then
inSize := 1024;
result := False;
try
try
outSize := 0;
ZDecompressPartial (data, inSize, outBuffer, outSize);
try
result := (PAnsiChar (outBuffer)^ = AnsiChar ('B')) and
((PAnsiChar (outBuffer) + 1)^ = AnsiChar ('M'));
finally
ReallocMem (outBuffer, 0)
end
except
MessageBeep ($ffff);
end;
finally
end;
end;
{ TCompressedBitmapResourceDetails }
procedure TCompressedBitmapResourceDetails.ChangeData(data: TMemoryStream);
var
outb : Pointer;
outs : Integer;
ms : TMemoryStream;
begin
data.Seek(0, soFromBeginning);
ms := Nil;
ZDecompress (data.Memory, data.Size, outb, outs);
try
ms := TMemoryStream.Create;
ms.Write((PAnsiChar (outb) + sizeof (TBitmapFileHeader))^, outs - sizeof (TBitmapFileHeader));
inherited ChangeData (ms);
finally
ms.Free;
ReallocMem (outb, 0)
end;
end;
constructor TCompressedBitmapResourceDetails.Create(AParent: TResourceModule;
ALanguage: Integer; const AName, AType: UnicodeString; ASize: Integer;
AData: pointer);
begin
fCompressedData := TMemoryStream.Create;
inherited;
end;
constructor TCompressedBitmapResourceDetails.CreateNew(AParent: TResourceModule;
ALanguage: Integer; const AName: UnicodeString);
begin
fCompressedData := TMemoryStream.Create;
inherited;
end;
destructor TCompressedBitmapResourceDetails.Destroy;
begin
fCompressedData.Free;
inherited;
end;
function TCompressedBitmapResourceDetails.GetData: TMemoryStream;
var
ms, m : TMemoryStream;
hdr :TBitmapFileHeader;
outb : Pointer;
outs : Integer;
begin
ms := inherited GetData;
fCompressedData.Clear;
hdr.bfType :=$4D42; // TBitmap.LoadFromStream requires a bitmapfileheader
hdr.bfSize := ms.size; // before the data...
hdr.bfReserved1 := 0;
hdr.bfReserved2 := 0;
hdr.bfOffBits := sizeof (hdr);
outb := Nil;
m := TMemoryStream.Create;
try
m.Write(hdr, sizeof (hdr));
m.Write(ms.Memory^, ms.Size);
ZCompress (m.Memory, m.Size, outb, outs);
fCompressedData.Write(outb^, outs)
finally
m.Free;
ReallocMem (outb, 0);
end;
result := fCompressedData
end;
initialization
RegisterResourceDetails (TRCDataDescriptionResourceDetails);
RegisterResourceDetails (TRCDataPackagesResourceDetails);
RegisterResourceDetails (TRCDataFormResourceDetails);
RegisterResourceDetails (TRCDataCompressedBitmapResourceDetails);
finalization
UnregisterResourceDetails (TRCDataDescriptionResourceDetails);
UnregisterResourceDetails (TRCDataPackagesResourceDetails);
UnregisterResourceDetails (TRCDataFormResourceDetails);
UnregisterResourceDetails (TRCDataCompressedBitmapResourceDetails);
end.
|
unit EushullyBIN;
interface
uses
Classes, SysUtils, EushullyFile;
const
BIN_SIGN = 'SYS';
type
TBINHeader = record
sign: array[0..2] of AnsiChar; // always "SYS"
version: array[0..3] of AnsiChar;
space: char;
type_,
d1,
d2,
d3,
d4,
d5,
offsets_size, // always 0x1C (include here value)
size_71,
offset_71,
size_03,
offset_03,
size_8f,
offset_8f: UInt32;
end;
TEushullyBIN = class
private
fName: string;
fHeader: TBINHeader;
fScriptRAW: array of UInt32;
fOffsets: array[0..2] of array of UInt32;
function getName(): string;
function getScriptRAW(): PInteger;
function getScriptSize(): UInt32;
public
destructor Destroy(); override;
function load(from: TEushullyFile): boolean;
procedure close();
property Name: string read getName;
class function isFormat(tstFile: TEushullyFile): boolean;
property ScriptRAW: PInteger read getScriptRAW;
property ScriptSize: UInt32 read getScriptSize;
end;
implementation
destructor TEushullyBIN.Destroy();
begin
close();
inherited;
end;
function TEushullyBIN.getName(): string;
begin
result:=fName;
end;
function TEushullyBIN.getScriptRAW(): PInteger;
begin
result:=@fScriptRAW[0];
end;
function TEushullyBIN.getScriptSize(): UInt32;
begin
result:=Length(fScriptRAW);
end;
function TEushullyBIN.load(from: TEushullyFile): boolean;
begin
from.seek(0);
from.read(fHeader, sizeof(TBINHeader));
if (fHeader.sign <> BIN_SIGN) then
begin
result:=false;
Exit;
end;
fName:=from.Name;
SetLength(fScriptRAW, fHeader.offset_71);
from.read(fScriptRAW[0], fHeader.offset_71*4);
if (fHeader.size_71>0) then
begin
from.seek(fHeader.offset_71);
SetLength(fOffsets[0], fHeader.size_71);
from.read(fOffsets[0][0], fHeader.size_71*4);
end;
if (fHeader.size_03>0) then
begin
from.seek(fHeader.offset_03);
SetLength(fOffsets[1], fHeader.size_03);
from.read(fOffsets[1][0], fHeader.size_03*4);
end;
if (fHeader.size_8f>0) then
begin
from.seek(fHeader.offset_8f);
SetLength(fOffsets[2], fHeader.size_8f);
from.read(fOffsets[2][0], fHeader.size_8f*4);
end;
result:=true;
end;
procedure TEushullyBIN.close();
begin
SetLength(fScriptRAW, 0);
SetLength(fOffsets[0], 0);
SetLength(fOffsets[1], 0);
SetLength(fOffsets[2], 0);
end;
class function TEushullyBIN.isFormat(tstFile: TEushullyFile): boolean;
var
header: TBINHeader;
begin
tstFile.seek(0);
tstFile.read(header, sizeof(TBINHeader));
result:=(header.sign = BIN_SIGN);
end;
end.
|
unit ThroughputSocket;
interface
uses
IdTCPClient, BasisFunction, Windows, SysUtils, Classes, SyncObjs, DefineUnit,
Types, BaseClientSocket, IdIOHandlerSocket, Messages;
type
TThroughputScoket = class(TBaseClientSocket)
private
{* 数据缓冲区 *}
FBuffer: array of Byte;
{* 数据缓冲区大小 *}
FBufferSize: Integer;
{* 循环发包次数 *}
FCount: Integer;
public
constructor Create; override;
destructor Destroy; override;
{* 连接服务器 *}
function Connect(const ASvr: string; APort: Integer): Boolean;
{* 断开连接 *}
procedure Disconnect;
{* 循环发包检测 *}
function CyclePacket: Boolean;
property BufferSize: Integer read FBufferSize write FBufferSize;
property Count: Integer read FCount;
end;
implementation
{ TThroughputScoket }
constructor TThroughputScoket.Create;
begin
inherited;
FBufferSize := 1024;
end;
destructor TThroughputScoket.Destroy;
begin
inherited;
end;
function TThroughputScoket.Connect(const ASvr: string;
APort: Integer): Boolean;
begin
FHost := ASvr;
FPort := APort;
Result := inherited Connect(Char(sfThroughput));
end;
procedure TThroughputScoket.Disconnect;
begin
inherited Disconnect;
end;
function TThroughputScoket.CyclePacket: Boolean;
var
i: Integer;
slRequest, slResponse: TStringList;
begin
if FBufferSize > Length(FBuffer) then
begin
SetLength(FBuffer, FBufferSize);
for i := Low(FBuffer) to High(FBuffer) do
begin
FBuffer[i] := 1;
end;
end;
slRequest := TStringList.Create;
slResponse := TStringList.Create;
try
FCount := FCount + 1;
slRequest.Add(Format(CSFmtInt, [CSCount, FCount]));
Result := ControlCommand(CSThroughputCommand[tcCyclePacket], slRequest, slResponse, FBuffer);
if Result then
FCount := StrToInt(slResponse.Values[CSCount]);
finally
slResponse.Free;
slRequest.Free;
end;
end;
end.
|
(*
功能概述:封装简单的线程,线程执行的方法由创建时传入
调用方式:
THJYThread.Create(
procedure()
begin
//线程执行代码
end,
procedure()
begin
//线程执行完成后处理代码
end
);
*)
unit HJYThreads;
interface
uses Classes;
type
THJYThread = class(TThread)
private
FPrc: TThreadProcedure;
FOnTerminate: TThreadProcedure;
FSynchronize: Boolean;
protected
procedure Execute; override;
procedure DoTerminate; override;
public
constructor Create(APrc: TThreadProcedure; ASynchronize: Boolean = False); overload;
constructor Create(APrc, AOnTerminate: TThreadProcedure); overload;
constructor Create(APrc, AOnTerminate: TThreadProcedure; ASynchronize: Boolean); overload;
end;
implementation
{ THJYThread }
constructor THJYThread.Create(APrc: TThreadProcedure; ASynchronize: Boolean);
begin
Self.FreeOnTerminate := True;
Self.FPrc := APrc;
FSynchronize := ASynchronize;
inherited Create(False);
end;
constructor THJYThread.Create(APrc: TThreadProcedure; AOnTerminate: TThreadProcedure);
begin
Self.FreeOnTerminate := True;
Self.FPrc := APrc;
FSynchronize := False;
FOnTerminate := AOnTerminate;
inherited Create(False);
end;
constructor THJYThread.Create(APrc, AOnTerminate: TThreadProcedure; ASynchronize: Boolean);
begin
Self.FreeOnTerminate := True;
Self.FPrc := APrc;
FSynchronize := ASynchronize;
FOnTerminate := AOnTerminate;
inherited Create(False);
end;
procedure THJYThread.Execute;
begin
Self.FreeOnTerminate := True;
try
if FSynchronize then
Synchronize(FPrc)
else
FPrc;
except
end;
end;
procedure THJYThread.DoTerminate;
begin
if Assigned(FOnTerminate) then
FOnTerminate;
end;
end. |
program cheatengine;
{$mode DELPHI}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes,
windows,
LazUTF8,
sysutils,
ShellApi
{ you can add units after this };
{$ifdef cpu64}
{$ERROR You MUST compile this code as 32-bit!}
{$endif}
{$R *.res}
type TIsWow64Process=function (processhandle: THandle; var isWow: BOOL): BOOL; stdcall;
var IsWow64Process :TIsWow64Process;
WindowsKernel: THandle;
launch32bit: boolean;
isWow: BOOL;
self: thandle;
selfname: pwidechar;
selfpath: widestring;
param: string;
i: integer;
cpuid7ebx: dword;
basename: widestring;
exename: widestring;
s: string;
begin
{$ifdef cpu64}
MessageBox(0,'A fucking retard thought that removing an earlier $ERROR line would be enough to run this','',0);
exit;
{$endif}
{$ifndef altname}
basename:='cheatengine';
{$else}
basename:='rt-mod';
{$endif}
WindowsKernel:=LoadLibrary('Kernel32.dll'); //there is no kernel33.dll
IsWow64Process:= GetProcAddress(WindowsKernel, 'IsWow64Process');
launch32bit:=true;
if assigned(IsWow64Process) then
begin
isWow:=true;
if IsWow64Process(GetCurrentProcess(), isWow) then
launch32bit:=not isWow;
end;
self:=GetModuleHandle(nil);
getmem(selfname,512);
if GetModuleFileNameW(self, selfname, 512)>0 then
selfpath:=ExtractFilePath(selfname)
else
selfpath:=''; //fuck it if it fails
param:='';
for i:=1 to paramcount do
param:=param+'"'+ParamStrUTF8(i)+'" ';
//MessageBox(0, pchar(param),'bla',0);
if launch32bit then
exename:=basename+'-i386.exe'
else
begin
asm
push ecx
mov ecx,0
mov eax,7
cpuid
mov cpuid7ebx,ebx
pop ecx
end;
if (cpuid7ebx and (1 shl 5))>0 then
exename:=basename+'-x86_64-SSE4-AVX2.exe'
else
exename:=basename+'-x86_64.exe';
end;
if FileExists(selfpath+exename) then
ShellExecuteW(0, 'open', pwidechar(selfpath+exename), pwidechar(widestring(param)), pwidechar(selfpath), sw_show)
else
begin
s:=exename;
MessageBoxW(0, pwidechar(exename+' could not be found. Please disable/uninstall your anti virus and reinstall Cheat Engine to fix this'),'Cheat Engine launch error',MB_OK or MB_ICONERROR);
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
LinhaTop: TPanel;
LinhaBotton: TPanel;
LinhaLeft: TPanel;
LinhaRigth: TPanel;
Panel1: TPanel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
EditNome: TEdit;
EditTop: TEdit;
EditLeft: TEdit;
EditHeight: TEdit;
EditWidth: TEdit;
Label8: TLabel;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure ClickDefault(Sender: TObject);
procedure MouseDownDefault(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure MouseMoveDefault(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure MouseUpDefault(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure Button1Click(Sender: TObject);
private
MouseDownSpot: TPoint;
Capturing: BOOL;
procedure AlinhamentoDefault(Sender: TObject);
procedure CriarLinhaTop(ALeft, ATop, AWidth: Integer);
procedure GetComponent(Sender: TObject);
procedure SetComponent;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.GetComponent(Sender: TObject);
begin
EditNome.Text := TGraphicControl(Sender).Name;
EditTop.Text := IntToStr(TGraphicControl(Sender).top);
EditLeft.Text := IntToStr(TGraphicControl(Sender).Left);
EditHeight.Text := IntToStr(TGraphicControl(Sender).Height);
EditWidth.Text := IntToStr(TGraphicControl(Sender).Width);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
begin
CriarLinhaTop(-1, -1, -1);
for I := 0 to ComponentCount - 1 do
if (Components[I].ClassType = TLabel) then
begin
TLabel(Components[I]).onMouseDown := MouseDownDefault;
TLabel(Components[I]).OnMouseMove := MouseMoveDefault;
TLabel(Components[I]).OnMouseUp := MouseUpDefault;
TLabel(Components[I]).OnClick := ClickDefault;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
SetComponent();
end;
procedure TForm1.SetComponent();
var
I: Integer;
begin
for I := 0 to ComponentCount - 1 do
if (AnsiUpperCase(Components[I].Name) = AnsiUpperCase(EditNome.Text)) then
begin
TGraphicControl(Components[I]).top := StrToIntDef(EditTop.Text, 0);
TGraphicControl(Components[I]).Left := StrToIntDef(EditLeft.Text, 0);
TGraphicControl(Components[I]).Height := StrToIntDef(EditHeight.Text, 0);
TGraphicControl(Components[I]).Width := StrToIntDef(EditWidth.Text, 0);
AlinhamentoDefault(Components[I]);
end;
end;
procedure TForm1.ClickDefault(Sender: TObject);
var
I: Integer;
begin
for I := 0 to ComponentCount - 1 do
if (Components[I].ClassType = TLabel) then
TLabel(Components[I]).Font.Color := clBlack;
TLabel(Sender).Font.Color := clRed;
AlinhamentoDefault(Sender);
GetComponent(Sender);
end;
procedure TForm1.MouseDownDefault(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
Capturing := True;
MouseDownSpot.X := X;
MouseDownSpot.Y := Y;
end;
procedure TForm1.MouseMoveDefault(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if (Capturing) then
begin
TGraphicControl(Sender).Left := TGraphicControl(Sender).Left - (MouseDownSpot.X - X);
TGraphicControl(Sender).top := TGraphicControl(Sender).top - (MouseDownSpot.Y - Y);
AlinhamentoDefault(Sender);
end;
end;
procedure TForm1.MouseUpDefault(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if (Capturing) then
begin
Capturing := False;
TGraphicControl(Sender).Left := TGraphicControl(Sender).Left - (MouseDownSpot.X - X);
TGraphicControl(Sender).top := TGraphicControl(Sender).top - (MouseDownSpot.Y - Y);
end;
end;
procedure TForm1.CriarLinhaTop(ALeft, ATop, AWidth: Integer);
begin
TGraphicControl(LinhaTop).Visible := False;
TGraphicControl(LinhaBotton).Visible := False;
TGraphicControl(LinhaLeft).Visible := False;
TGraphicControl(LinhaRigth).Visible := False;
if (ATop > 0) then
begin
TGraphicControl(LinhaTop).Visible := True;
TGraphicControl(LinhaTop).Left := ALeft;
TGraphicControl(LinhaTop).top := ATop;
TGraphicControl(LinhaTop).Width := AWidth;
end;
end;
procedure TForm1.AlinhamentoDefault(Sender: TObject);
var
I: Integer;
begin
CriarLinhaTop(-1, -1, -1);
for I := 0 to ComponentCount - 1 do
begin
if (TGraphicControl(Sender).Name <> TGraphicControl(Components[I]).Name) then
if (TGraphicControl(Sender).top = TGraphicControl(Components[I]).top) then
CriarLinhaTop(TGraphicControl(Sender).Left, TGraphicControl(Sender).top, 100);
end;
end;
end.
|
unit VistaProgressBar;
// © 2011 by Roy Magne Klever. All rights reserved
// WEB: www.rmklever.com
// Mail: roymagne@rmklever.com
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls;
type
TVistaProgressBar = class(TGraphicControl)
private
FAltMode: boolean;
FShowPosition: boolean;
FShowPercent: boolean;
FPosition: integer;
FMax: integer;
FMin: integer;
procedure SetMax(const Value: integer);
procedure SetMin(const Value: integer);
procedure SetShowPercent(const Value: boolean);
procedure SetPosition(const Value: integer);
procedure SetShowPosition(const Value: boolean);
procedure CMFontChanged(var Message: TMessage); message CM_FontChanged;
procedure SetAltMode(const Value: boolean);
protected
procedure Paint; override;
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddPosition(APos: integer);
procedure Draw(Canvas: TCanvas; Pos, Max: integer);
published
property Anchors;
property Max: integer read FMax write SetMax default 100;
property Min: integer read FMin write SetMin default 0;
property AltMode: boolean read FAltMode write SetAltMode;
property ShowPercent: boolean read FShowPercent write SetShowPercent;
property Position: integer read FPosition write SetPosition;
property ShowPosition: boolean read FShowPosition write SetShowPosition;
property Color;
property Align;
property Font;
property ParentShowHint;
property ShowHint;
property Visible;
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
implementation
function Blend(Color1, Color2: TColor; Value: Byte): TColor;
var
i: LongInt;
r1, g1, b1, r2, g2, b2: byte;
begin
Value := Round(2.56 * Value);
i := ColorToRGB(Color2);
R1 := Byte(i);
G1 := Byte(i shr 8);
B1 := Byte(i shr 16);
i := ColorToRGB(Color1);
R2 := Byte(i);
G2 := Byte(i shr 8);
B2 := Byte(i shr 16);
R1 := (Value * (R2 - R1)) shr 8 + R1;
G1 := (Value * (G2 - G1)) shr 8 + G1;
B1 := (Value * (B2 - B1)) shr 8 + B1;
Result := (B1 shl 16) + (G1 shl 8) + R1;
end;
procedure SmoothGradient(Canvas: TCanvas; const ARect: TRect; const c1: TColor; const Gray: Boolean);
type
PRGB = ^TRGB;
TRGB = record
b, g, r: Byte;
end;
PRGBArray = ^TRGBArray;
TRGBARRAY = array[0..0] of TRGB;
var
rc1, gc1, bc1, rc2, gc2, bc2, rc3, gc3, bc3, rc4, gc4, bc4: Integer;
x, y, w, h: Integer;
i, w1, w2, h1, sp, sm: Integer;
Row: PRGBArray;
C: TRGB;
slMain, slSize, slPtr: Integer;
Color, tc: Integer;
Profil: array of TRGB;
r, g, b: Byte;
bmp: TBitmap;
begin
if ((ARect.Right - ARect.Left) - 1 <= 0) or ((ARect.Bottom - ARect.Top) - 1 <= 1) then
exit;
bmp := TBitmap.Create;
bmp.PixelFormat := pf24Bit;
bmp.Width := (ARect.Right - ARect.Left) - 1;
bmp.Height := (ARect.Bottom - ARect.Top) - 1;
h := bmp.Height;
w := bmp.Width;
SetLength(Profil, h);
// Get colors for first gradient
Color := ColorToRGB(c1);
if Gray then
begin
rc1 := 253;
gc1 := 253;
bc1 := 253;
rc2 := 218;
gc2 := 218;
bc2 := 218;
rc3 := 160;
gc3 := 160;
bc3 := 160;
rc4 := 213;
gc4 := 213;
bc4 := 213;
end
else
begin
tc := Blend(Color, clWhite, 5);
rc1 := Byte(tc);
gc1 := Byte(tc shr 8);
bc1 := Byte(tc shr 16);
tc := Blend(Color, clWhite, 50);
rc2 := Byte(tc);
gc2 := Byte(tc shr 8);
bc2 := Byte(tc shr 16);
tc := Blend(Color, clBlack, 60);
rc3 := Byte(tc);
gc3 := Byte(tc shr 8);
bc3 := Byte(tc shr 16);
tc := Blend(Color, clBlack, 80);
rc4 := Byte(tc);
gc4 := Byte(tc shr 8);
bc4 := Byte(tc shr 16);
end;
// Calc first gradient
sp := Trunc(h / 2.5);
y := sp;
for i := 0 to y - 1 do
begin
C.r := Byte(rc1 + (((rc2 - rc1) * (i)) div y));
C.g := Byte(gc1 + (((gc2 - gc1) * (i)) div y));
C.b := Byte(bc1 + (((bc2 - bc1) * (i)) div y));
Profil[i] := C;
end;
for i := y to h - 1 do
begin
C.r := Byte(rc3 + (((rc4 - rc3) * (i)) div h));
C.g := Byte(gc3 + (((gc4 - gc3) * (i)) div h));
C.b := Byte(bc3 + (((bc4 - bc3) * (i)) div h));
Profil[i] := C;
end;
// First gradient done
if Gray then
begin
rc1 := 200;
gc1 := 200;
bc1 := 200;
rc2 := 253;
gc2 := 253;
bc2 := 253;
end
else
begin
tc := Blend(Color, clBlack, 50);
rc1 := Byte(tc);
gc1 := Byte(tc shr 8);
bc1 := Byte(tc shr 16);
tc := Blend(Color, clWhite, 50);
rc2 := Byte(tc);
gc2 := Byte(tc shr 8);
bc2 := Byte(tc shr 16);
end;
w1 := w - 1;
w := (w shr 1) + (w and 1);
// Init scanline accsess
slMain := Integer(bmp.ScanLine[0]);
slSize := Integer(bmp.ScanLine[1]) - slMain;
// Paint gradient
h1 := h shr 1;
w2 := 25;
for x := 0 to w - 1 do
begin
if x < w2 then
begin
C.b := Byte(bc1 + (((bc2 - bc1) * x) div w2));
C.g := Byte(gc1 + (((gc2 - gc1) * x) div w2));
C.r := Byte(rc1 + (((rc2 - rc1) * x) div w2));
end
else
begin
C.b := bc2;
C.g := gc2;
C.r := rc2;
end;
slPtr := slMain;
for y := 0 to h - 1 do
begin
Row := PRGBArray(slPtr);
r := Profil[y].r;
g := Profil[y].g;
b := Profil[y].b;
if x = 0 then
sm := 3
else
sm := 2;
if (x = 0) or ((y < sp) or (y = h - 1)) then
begin
Row[x].r := (C.r - r) shr sm + r;
Row[x].g := (C.g - g) shr sm + g;
Row[x].b := (C.b - b) shr sm + b;
end
else
begin
Row[x].r := (C.r - r) shr 1 + r;
Row[x].g := (C.g - g) shr 1 + g;
Row[x].b := (C.b - b) shr 1 + b;
end;
if (x < (w1 - x)) then
begin
Row[w1 - x].r := Row[x].r;
Row[w1 - x].g := Row[x].g;
Row[w1 - x].b := Row[x].b;
end;
slPtr := slPtr + slSize;
end;
end;
Profil := nil;
Canvas.Draw(ARect.Left, Arect.Top, bmp);
FreeAndNil(bmp);
end;
procedure TVistaProgressBar.AddPosition(APos: integer);
begin
Position := Position + APos;
end;
procedure TVistaProgressBar.CMFontChanged(var Message: TMessage);
begin
Invalidate;
end;
constructor TVistaProgressBar.Create(AOwner: TComponent);
begin
inherited;
Width:= 150;
Height:= 17;
Color:= clLime;
fPosition := 0;
fMin := 0;
fMax := 100;
fShowPercent := False;
end;
destructor TVistaProgressBar.Destroy;
begin
inherited;
end;
procedure TVistaProgressBar.Draw(Canvas: TCanvas; Pos, Max: integer);
var
R: TRect;
Len: integer;
Percent: Extended;
ACap: string;
TempBmp: TBitmap;
c: TColor;
ts: TSize;
begin
if (Width <= 0) or (Height <= 0) then
Exit;
TempBmp := TBitmap.Create;
TempBmp.PixelFormat := pf24bit;
if TempBmp.Width <> Width then
TempBmp.Width := Width;
if TempBmp.Height <> Height then
TempBmp.Height := Height;
c := Blend(clWhite, clSilver, 50);
TempBmp.Canvas.Brush.Style := bsSolid;
TempBmp.Canvas.Pen.Color := $00A0A0A0;
R:= Rect(0, 0, TempBmp.Width, TempBmp.Height);
TempBmp.Canvas.Rectangle(R);
TempBmp.Canvas.Pen.Color := clSilver;
TempBmp.Canvas.MoveTo(1, 0);
TempBmp.Canvas.LineTo(R.Right - 1, R.Top);
TempBmp.Canvas.Pixels[R.Left, R.Top] := c;
TempBmp.Canvas.Pixels[R.Left, R.Bottom - 1] := c;
TempBmp.Canvas.Pixels[R.Right - 1, R.Top] := c;
TempBmp.Canvas.Pixels[R.Right - 1, R.Bottom - 1] := c;
R.Left := 1;
R.Top := 1;
if not FAltMode then
SmoothGradient(TempBmp.Canvas, R, Color, True);
Len := FMax - FMin;
if FMax = FMin then
Percent := 0
else
Percent := (fPosition - FMin) / Len;
R.Right := Round(Width * Percent);
if R.Right > 0 then
SmoothGradient(TempBmp.Canvas, r, Color, False);
if FShowPercent then
ACap := IntToStr(Round(Percent * 100)) + '%'
else
ACap := IntToStr(FPosition);
TempBmp.Canvas.Font := Font;
if FShowPosition then
begin
TempBmp.Canvas.Brush.Style := bsClear;
ts:= TempBmp.Canvas.TextExtent(ACap);
TempBmp.Canvas.TextOut((Width - ts.cx) div 2, (Height - ts.cy) div 2, ACap);
end;
TempBmp.Canvas.Brush.Style := bsSolid;
Canvas.CopyMode := cmSrcCopy;
Canvas.Draw(0, 0, TempBmp);
FreeAndNil(TempBmp);
end;
procedure TVistaProgressBar.Paint;
begin
Draw(Canvas, FPosition, FMax);
end;
procedure TVistaProgressBar.Resize;
begin
inherited;
end;
procedure TVistaProgressBar.SetAltMode(const Value: boolean);
begin
FAltMode := Value;
Invalidate;
end;
procedure TVistaProgressBar.SetMax(const Value: integer);
begin
if FMax = Value then
Exit;
FMax := Value;
Paint;
end;
procedure TVistaProgressBar.SetMin(const Value: integer);
begin
if FMin = Value then
Exit;
FMin := Value;
Paint;
end;
procedure TVistaProgressBar.SetShowPercent(const Value: boolean);
begin
if FShowPercent = Value then
Exit;
FShowPercent := Value;
Paint;
end;
procedure TVistaProgressBar.SetPosition(const Value: integer);
begin
if FPosition = Value then
Exit;
if Value > FMax then
FPosition := FMax
else
if Value < FMin then
FPosition := FMin
else
FPosition := Value;
Paint;
end;
procedure TVistaProgressBar.SetShowPosition(const Value: boolean);
begin
if FShowPosition = Value then
Exit;
FShowPosition := Value;
Paint;
end;
end.
|
unit uSmartPhoneFactory;
interface
uses
uSmartPhone
;
type
TBaseSmartPhoneFactory = class abstract
public
function GetSmartPhone: TBaseSmartPhone; virtual; abstract;
end;
TCheapCrappyPhoneFactory = class(TBaseSmartPhoneFactory)
public
function GetSmartPhone: TBaseSmartPhone; override;
end;
TBasicSmartPhoneFactory = class(TBaseSmartPhoneFactory)
public
function GetSmartPhone: TBaseSmartPhone; override;
end;
TDeluxeSmartPhoneFactory = class(TBaseSmartPhoneFactory)
public
function GetSmartPhone: TBaseSmartPhone; override;
end;
TSuperDuperSmartPhoneFactory = class(TBaseSmartPhoneFactory)
public
function GetSmartPhone: TBaseSmartPhone; override;
end;
TSmartPhoneFactory = class(TBaseSmartPhoneFactory)
private
FSmartPhoneType: TSmartPhoneType;
public
function GetSmartPhone: TBaseSmartPhone; override;
constructor CreateByType(aType: TSmartPhoneType);
end;
implementation
uses
System.SysUtils
;
{ TBasicSmartPhoneFactory }
function TBasicSmartPhoneFactory.GetSmartPhone: TBaseSmartPhone;
begin
Result := TBasicSmartPhone.Create;
end;
{ TDeluxeSmartPhoneFactory }
function TDeluxeSmartPhoneFactory.GetSmartPhone: TBaseSmartPhone;
begin
Result := TDeluxeSmartPhone.Create;
end;
{ TSmartPhoneFactory }
constructor TSmartPhoneFactory.CreateByType(aType: TSmartPhoneType);
begin
inherited Create;
FSmartPhoneType := aType;
end;
function TSmartPhoneFactory.GetSmartPhone: TBaseSmartPhone;
begin
case FSmartPhoneType of
Basic: Result := TBasicSmartPhone.Create;
CheapCrappy: Result := TCheapCrappySmartPhone.Create;
Deluxe: Result := TDeluxeSmartPhone.Create;
SuperDuper: Result := TSuperDuperSmartPhone.Create;
else
raise Exception.Create('An impossiblility occurred -- a value for TSmartPhoneType was passed that doesn''t exist');
end;
end;
{ TSuperDuperSmartPhoneFactory }
function TSuperDuperSmartPhoneFactory.GetSmartPhone: TBaseSmartPhone;
begin
Result := TSuperDuperSmartPhone.Create;
end;
{ TCheapCrappyPhoneFactory }
function TCheapCrappyPhoneFactory.GetSmartPhone: TBaseSmartPhone;
begin
Result := TCheapCrappySmartPhone.Create;
end;
end.
|
{@unit RLSaveDialog - Implementação do diálogo de salvamento e sua classe de setup. }
unit RLSaveDialog;
interface
uses
Classes, SysUtils, Windows, Messages, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, RLFilters, RLConsts, RLTypes, RLUtils;
type
{@type TRLSaveDialogOptions - Opções de configuração do diálogo de salvamento.
Pode ser um conjunto dos seguintes valores:
rsoDisableSaveInBackground - Desabilitar a opção de salvamento em segundo plano.
:}
TRLSaveDialogOption =(rsoDisableSaveInBackground);
TRLSaveDialogOptions=set of TRLSaveDialogOption;
{/@type}
{@type TRLSaveRange - Opções para o modo seleção de páginas.
Pode ser um dos seguintes valores:
rsrAllPages - Salvar todas as páginas;
rsrSelection - Salvar as páginas de números indicados;
rsrPageNums - Salvar o intervalo de páginas indicado.
:/}
TRLSaveRange=(rsrAllPages,rsrSelection,rsrPageNums);
const
DefaultSaveOptions=[];
type
TRLSaveDialog = class(TForm)
GroupBoxPages: TGroupBox;
ButtonSave: TButton;
ButtonCancel: TButton;
RadioButtonPagesAll: TRadioButton;
RadioButtonPagesInterval: TRadioButton;
RadioButtonPagesSelect: TRadioButton;
LabelFromPage: TLabel;
EditFromPage: TEdit;
LabelToPage: TLabel;
EditToPage: TEdit;
LabelFileName: TLabel;
EditFileName: TEdit;
LabelUseFilter: TLabel;
ComboBoxFilters: TComboBox;
SpeedButtonLookup: TSpeedButton;
SaveDialog: TSaveDialog;
CheckBoxSaveInBackground: TCheckBox;
procedure EditFromPageChange(Sender: TObject);
procedure SpeedButtonLookupClick(Sender: TObject);
private
{ Private declarations }
procedure LoadEditors;
procedure SaveEditors;
procedure LoadFilterList;
procedure Init;
public
{ Public declarations }
constructor Create(aOwner:TComponent); override;
function Execute:boolean;
end;
{@class TRLSaveDialogSetup - Opções do diálogo de salvamento.
O diálogo de salvamento obedecerá as configurações da instância deste componente. Com ele, é
possível configurar alguns itens de comportamento do diálogo de salvamento.
@pub}
TRLSaveDialogSetup=class(TComponent)
private
{ Private declarations }
function GetOptions: TRLSaveDialogOptions;
procedure SetOptions(const Value: TRLSaveDialogOptions);
function GetSaveInBackground: boolean;
procedure SetSaveInBackground(const Value: boolean);
function GetFilter: TRLCustomSaveFilter;
procedure SetFilter(const Value: TRLCustomSaveFilter);
public
{ Public declarations }
published
{@prop Options - Opções diversas do diálogo de salvamento. @links TRLSaveDialogOptions. :/}
property Options:TRLSaveDialogOptions read GetOptions write SetOptions default DefaultSaveOptions;
{@prop SaveInBackground - Indica o valor inicial para a opção de salvar em segundo plano. :/}
property SaveInBackground:boolean read GetSaveInBackground write SetSaveInBackground;
{@prop Filter - Filtro atualmente selecionado. @links TRLCustomSaveFilter:/}
property Filter:TRLCustomSaveFilter read GetFilter write SetFilter;
end;
{/@class}
{@class TRLSaveParams - Parâmetros de salvamento.}
TRLSaveParams=class(TComponent)
private
{ Private declarations }
fFileName :string;
fMaxPage :integer;
fToPage :integer;
fMinPage :integer;
fFromPage :integer;
fOptions :TRLSaveDialogOptions;
fSaveRange :TRLSaveRange;
fSaveInBackground:boolean;
fFilter :TRLCustomSaveFilter;
fHelpContext :integer;
//
procedure SetMaxPage(const Value: integer);
procedure SetFilter(const Value: TRLCustomSaveFilter);
protected
{ Protected declarations }
procedure Notification(Component:TComponent; Operation:TOperation); override;
public
{ Public declarations }
constructor Create(aOwner:TComponent); override;
destructor Destroy; override;
{@method Clear - Preenche todas as props com valores default.:/}
procedure Clear;
published
{@prop Options - Opções diversas do diálogo de salvamento. @links TRLSaveDialogOptions.:/}
property Options :TRLSaveDialogOptions read fOptions write fOptions default DefaultSaveOptions;
{@prop FileName - Nome do arquivo a gerar.:/}
property FileName :string read fFileName write fFileName;
{@prop MaxPage - Limite superior para o intervalo de páginas a imprimir.:/}
property MaxPage :integer read fMaxPage write SetMaxPage;
{@prop MinPage - Limite inferior para o intervalo de páginas a imprimir.:/}
property MinPage :integer read fMinPage write fMinPage;
{@prop FromPage - Valor escolhido para a primeira página a imprimir.:/}
property FromPage :integer read fFromPage write fFromPage;
{@prop ToPage - Valor escolhido para a última página a imprimir.:/}
property ToPage :integer read fToPage write fToPage;
{@prop SaveRange - Valor inicial para o modo de seleção de páginas. @links TRLSaveRange.:/}
property SaveRange :TRLSaveRange read fSaveRange write fSaveRange;
{@prop SaveInBackground - Indica o valor inicial para o salvamento em segundo plano.:/}
property SaveInBackground:boolean read fSaveInBackground write fSaveInBackground;
{@prop Filter - Filtro atualmente selecionado. @links TRLCustomSaveFilter:/}
property Filter :TRLCustomSaveFilter read fFilter write SetFilter;
{@prop HelpContext - Código do tópico de ajuda associado.:/}
property HelpContext :integer read fHelpContext write fHelpContext;
end;
{/@class}
{@var SaveParams - Parâmetros de salvamento atuais. @links TRLSaveParams:/}
var SaveParams:TRLSaveParams=nil;
{/@unit}
implementation
//{$R *.DFM}
// UTILS
function IntToEmptyStr(aInt:integer):string;
begin
if aInt=0 then
Result:=''
else
Result:=IntToStr(aInt);
end;
function EmptyStrToInt(const aStr:string):integer;
begin
Result:=StrToIntDef(aStr,0);
end;
{ TRLSaveDialog }
// OVERRIDE
constructor TRLSaveDialog.Create(aOwner:TComponent);
begin
inherited CreateNew(aOwner);
//
Init;
end;
// PUBLIC
function TRLSaveDialog.Execute:boolean;
begin
LoadFilterList;
LoadEditors;
ActiveControl:=EditFileName;
Result:=(ShowModal=mrOk);
if Result then
SaveEditors;
end;
// PRIVATE
procedure TRLSaveDialog.Init;
begin
Left := 211;
Top := 407;
ActiveControl := EditFileName;
BorderStyle := bsDialog;
Caption := 'Salvar como';
ClientHeight := 244;
ClientWidth := 391;
Color := clBtnFace;
Font.Charset := DEFAULT_CHARSET;
Font.Color := clWindowText;
Font.Height := 11;
Font.Name := 'MS Sans Serif';
Font.Pitch := fpVariable;
Font.Style := [];
Position := poScreenCenter;
//
LabelFileName:=TLabel.Create(Self);
with LabelFileName do
begin
Name := 'LabelFileName';
Parent := Self;
Left := 12;
Top := 16;
Width := 84;
Height := 13;
Caption := 'Nome do arquivo:';
end;
LabelUseFilter:=TLabel.Create(Self);
with LabelUseFilter do
begin
Name := 'LabelUseFilter';
Parent := Self;
Left := 12;
Top := 44;
Width := 86;
Height := 13;
Caption := 'Salvar no formato:';
end;
SpeedButtonLookup:=TSpeedButton.Create(Self);
with SpeedButtonLookup do
begin
Name := 'SpeedButtonLookup';
Parent := Self;
Left := 356;
Top := 12;
Width := 21;
Height := 21;
Caption := '...';
OnClick := SpeedButtonLookupClick;
end;
GroupBoxPages:=TGroupBox.Create(Self);
with GroupBoxPages do
begin
Name := 'GroupBoxPages';
Parent := Self;
Left := 12;
Top := 68;
Width := 365;
Height := 101;
Caption := ' Páginas no intervalo';
TabOrder := 2;
LabelFromPage:=TLabel.Create(Self);
with LabelFromPage do
begin
Name := 'LabelFromPage';
Parent := GroupBoxPages;
Left := 68;
Top := 45;
Width := 15;
Height := 13;
Caption := '&de:';
FocusControl := EditFromPage;
end;
LabelToPage:=TLabel.Create(Self);
with LabelToPage do
begin
Name := 'LabelToPage';
Parent := GroupBoxPages;
Left := 136;
Top := 45;
Width := 18;
Height := 13;
Caption := '&até:';
FocusControl := EditToPage;
end;
RadioButtonPagesAll:=TRadioButton.Create(Self);
with RadioButtonPagesAll do
begin
Name := 'RadioButtonPagesAll';
Parent := GroupBoxPages;
Left := 8;
Top := 20;
Width := 113;
Height := 17;
Caption := 'Salvar &tudo';
Checked := True;
TabOrder := 0;
TabStop := True;
end;
RadioButtonPagesInterval:=TRadioButton.Create(Self);
with RadioButtonPagesInterval do
begin
Name := 'RadioButtonPagesInterval';
Parent := GroupBoxPages;
Left := 8;
Top := 44;
Width := 61;
Height := 17;
Caption := 'Páginas';
TabOrder := 1;
end;
RadioButtonPagesSelect:=TRadioButton.Create(Self);
with RadioButtonPagesSelect do
begin
Name := 'RadioButtonPagesSelect';
Parent := GroupBoxPages;
Left := 8;
Top := 68;
Width := 73;
Height := 17;
Caption := '&Seleção';
TabOrder := 2;
end;
EditFromPage:=TEdit.Create(Self);
with EditFromPage do
begin
Name := 'EditFromPage';
Parent := GroupBoxPages;
Left := 88;
Top := 44;
Width := 41;
Height := 21;
TabStop := False;
TabOrder := 3;
Text := '1';
OnChange := EditFromPageChange;
end;
EditToPage:=TEdit.Create(Self);
with EditToPage do
begin
Name := 'EditToPage';
Parent := GroupBoxPages;
Left := 160;
Top := 44;
Width := 41;
Height := 21;
TabStop := False;
TabOrder := 4;
OnChange := EditFromPageChange;
end;
end;
CheckBoxSaveInBackground:=TCheckBox.Create(Self);
with CheckBoxSaveInBackground do
begin
Name := 'CheckBoxSaveInBackground';
Parent := Self;
Left := 12;
Top := 172;
Width := 365;
Height := 17;
Caption := 'Salvar em segundo plano';
TabOrder := 3;
end;
ButtonSave:=TButton.Create(Self);
with ButtonSave do
begin
Name := 'ButtonSave';
Parent := Self;
Left := 220;
Top := 204;
Width := 75;
Height := 25;
Caption := 'Salvar';
Default := True;
ModalResult := 1;
TabOrder := 3;
end;
ButtonCancel:=TButton.Create(Self);
with ButtonCancel do
begin
Name := 'ButtonCancel';
Parent := Self;
Left := 304;
Top := 204;
Width := 75;
Height := 25;
Cancel := True;
Caption := 'Cancelar';
ModalResult := 2;
TabOrder := 4;
end;
EditFileName:=TEdit.Create(Self);
with EditFileName do
begin
Name := 'EditFileName';
Parent := Self;
Left := 108;
Top := 12;
Width := 249;
Height := 21;
TabOrder := 0;
end;
ComboBoxFilters:=TComboBox.Create(Self);
with ComboBoxFilters do
begin
Name := 'ComboBoxFilters';
Parent := Self;
Left := 108;
Top := 40;
Width := 177;
Height := 21;
Style := csDropDownList;
ItemHeight := 13;
TabOrder := 1;
end;
SaveDialog:=TSaveDialog.Create(Self);
with SaveDialog do
begin
Name := 'SaveDialog';
Left := 340;
Top := 80;
end;
//
Caption :=LS_SaveStr;
LabelFileName.Caption :=LS_FileNameStr+':';
LabelUseFilter.Caption :=LS_UseFilterStr+':';
GroupBoxPages.Caption :=' '+LS_PageRangeStr+' ';
CheckBoxSaveInBackground.Caption:=LS_SaveInBackground;
LabelFromPage.Caption :=LS_RangeFromStr+':';
LabelToPage.Caption :=LS_RangeToStr;
RadioButtonPagesAll.Caption :=LS_AllStr;
RadioButtonPagesInterval.Caption:=LS_PagesStr;
RadioButtonPagesSelect.Caption :=LS_SelectionStr;
ButtonSave.Caption :=LS_SaveStr;
ButtonCancel.Caption :=LS_CancelStr;
end;
procedure TRLSaveDialog.LoadFilterList;
var
i,j,p:integer;
f:TRLCustomSaveFilter;
begin
ComboBoxFilters.Items.Clear;
ComboBoxFilters.Items.AddObject(LS_DefaultStr,nil);
j:=0;
for i:=0 to ActiveFilters.Count-1 do
if TObject(ActiveFilters[i]) is TRLCustomSaveFilter then
begin
f:=TRLCustomSaveFilter(ActiveFilters[i]);
p:=ComboBoxFilters.Items.AddObject(f.GetDisplayLabel,f);
if Assigned(SaveParams.Filter) and (f=SaveParams.Filter) then
j:=p;
end;
ComboBoxFilters.ItemIndex:=j;
end;
procedure TRLSaveDialog.LoadEditors;
const
StateColors:array[boolean] of TColor=(clBtnFace,clWindow);
begin
case SaveParams.SaveRange of
rsrAllPages : RadioButtonPagesAll.Checked :=true;
rsrSelection: RadioButtonPagesSelect.Checked :=true;
rsrPageNums : RadioButtonPagesInterval.Checked:=true;
end;
EditFileName.Text :=SaveParams.FileName;
EditFromPage.Text :=IntToEmptyStr(SaveParams.FromPage);
EditToPage.Text :=IntToEmptyStr(SaveParams.ToPage);
CheckBoxSaveInBackground.Checked:=SaveParams.SaveInBackground;
CheckBoxSaveInBackground.Enabled:=not (rsoDisableSaveInBackground in SaveParams.Options);
RadioButtonPagesInterval.Enabled:=True;
EditFromPage.Enabled :=True;
EditToPage.Enabled :=True;
EditFromPage.Color :=StateColors[EditFromPage.Enabled];
EditToPage.Color :=StateColors[EditToPage.Enabled];
RadioButtonPagesSelect.Enabled :=False;
end;
procedure TRLSaveDialog.SaveEditors;
begin
SaveParams.FileName:=EditFileName.Text;
if RadioButtonPagesAll.Checked then
SaveParams.SaveRange:=rsrAllPages
else if RadioButtonPagesSelect.Checked then
SaveParams.SaveRange:=rsrSelection
else if RadioButtonPagesInterval.Checked then
SaveParams.SaveRange:=rsrPageNums;
case SaveParams.SaveRange of
rsrAllPages : begin
SaveParams.FromPage:=SaveParams.MinPage;
SaveParams.ToPage :=SaveParams.MaxPage;
end;
rsrSelection: begin
SaveParams.FromPage:=EmptyStrToInt(EditFromPage.Text);
SaveParams.ToPage :=SaveParams.FromPage;
end;
rsrPageNums : begin
SaveParams.FromPage:=EmptyStrToInt(EditFromPage.Text);
SaveParams.ToPage :=EmptyStrToInt(EditToPage.Text);
end;
end;
SaveParams.SaveInBackground:=CheckBoxSaveInBackground.Checked;
if ComboBoxFilters.ItemIndex<>-1 then
SaveParams.Filter:=TRLCustomSaveFilter(ComboBoxFilters.Items.Objects[ComboBoxFilters.ItemIndex])
else
SaveParams.Filter:=nil;
// se não foi especificada uma extensão, pega-la-emos do filtro selecionado
if ExtractFileExt(SaveParams.FileName)='' then
if Assigned(SaveParams.Filter) then
SaveParams.FileName:=ChangeFileExt(SaveParams.FileName,SaveParams.Filter.DefaultExt)
else
SaveParams.FileName:=ChangeFileExt(SaveParams.FileName,RLFILEEXT)
else
SaveParams.Filter:=SaveFilterByFileName(SaveParams.FileName);
end;
// EVENTS
procedure TRLSaveDialog.EditFromPageChange(Sender: TObject);
begin
if not RadioButtonPagesInterval.Checked then
RadioButtonPagesInterval.Checked:=true;
end;
function FilterStr(const aDescription,aExt:string):string;
begin
Result:=aDescription+' (*'+FormatFileExt(aExt)+')|*'+FormatFileExt(aExt);
end;
procedure TRLSaveDialog.SpeedButtonLookupClick(Sender: TObject);
var
s:TRLCustomSaveFilter;
begin
if ComboBoxFilters.ItemIndex<>-1 then
s:=TRLCustomSaveFilter(ComboBoxFilters.Items.Objects[ComboBoxFilters.ItemIndex])
else
s:=nil;
if Assigned(s) then
begin
SaveDialog.Filter :=FilterStr(s.GetDisplayLabel,s.DefaultExt);
SaveDialog.DefaultExt:=s.DefaultExt;
end
else
begin
SaveDialog.Filter :=FilterStr(CS_ProductTitleStr,RLFILEEXT);
SaveDialog.DefaultExt:=RLFILEEXT;
end;
SaveDialog.FileName:=EditFileName.Text;
if SaveDialog.Execute then
EditFileName.Text:=SaveDialog.FileName;
end;
{ TRLSaveDialogSetup }
function TRLSaveDialogSetup.GetFilter: TRLCustomSaveFilter;
begin
Result:=SaveParams.Filter;
end;
function TRLSaveDialogSetup.GetOptions: TRLSaveDialogOptions;
begin
Result:=SaveParams.Options;
end;
function TRLSaveDialogSetup.GetSaveInBackground: boolean;
begin
Result:=SaveParams.SaveInBackground;
end;
procedure TRLSaveDialogSetup.SetFilter(const Value: TRLCustomSaveFilter);
begin
SaveParams.Filter:=Value;
end;
procedure TRLSaveDialogSetup.SetOptions(const Value: TRLSaveDialogOptions);
begin
SaveParams.Options:=Value;
end;
procedure TRLSaveDialogSetup.SetSaveInBackground(const Value: boolean);
begin
SaveParams.SaveInBackground:=Value;
end;
{ TRLSaveParams }
constructor TRLSaveParams.Create(aOwner: TComponent);
begin
fSaveInBackground:=False;
fOptions :=DefaultSaveOptions;
fFilter :=nil;
//
inherited;
end;
destructor TRLSaveParams.Destroy;
begin
inherited;
end;
procedure TRLSaveParams.Notification(Component: TComponent;
Operation: TOperation);
begin
inherited;
//
if Operation=opRemove then
if Component=fFilter then
fFilter:=nil;
end;
procedure TRLSaveParams.Clear;
begin
fFileName :='';
fMinPage :=1;
fMaxPage :=9999;
fFromPage :=fMinPage;
fToPage :=fMaxPage;
fSaveRange :=rsrAllPages;
fHelpContext:=0;
end;
procedure TRLSaveParams.SetFilter(const Value: TRLCustomSaveFilter);
begin
if Assigned(fFilter) then
fFilter.RemoveFreeNotification(Self);
fFilter:=Value;
if Assigned(fFilter) then
fFilter.FreeNotification(Self);
end;
procedure TRLSaveParams.SetMaxPage(const Value: integer);
begin
if fToPage=fMaxPage then
fToPage:=Value;
fMaxPage:=Value;
end;
initialization
SaveParams:=TRLSaveParams.Create(nil);
finalization
SaveParams.Free;
end.
|
unit EPSG2binTools;
interface
uses
ShareTools,
Contnrs, Classes, SysUtils;
type
TProjParam = class
Title : string;
Id : string;
Params : string;
procedure WriteToStream(s : TStream);
procedure ReadFromStream(s : TStream);
end;
TProjParams = class(TObjectList)
private
function GetItem(i : integer) : TProjParam;
public
property Item[i : integer] : TProjParam read GetItem; default;
function Add : TProjParam;
procedure SaveToBinFile(FileName : string);
procedure LoadFromBinFile(FileName : string);
function FindByID(aID : string) : TProjParam;
end;
const
EPSG_FILENAME = 'epsg';
function ConvertEPSGtoBin(EPSGFileName : string = EPSG_FILENAME) : boolean;
function GetBinFileName(EPSGFileName : string = EPSG_FILENAME) : string;
procedure SetupProjDir(aPath : string);
const
Params : TProjParams = nil;
implementation
procedure SetupProjDir(aPath : string);
begin
Params.Free;
Params := TProjParams.Create;
Params.LoadFromBinFile(GetBinFileName(PathWithLAstSlash(aPath) + EPSG_FILENAME));
end;
function CompareProjParamByID(Item1, Item2 : Pointer): Integer;
begin
Result := CompareText(TProjParam(Item1).ID, TProjParam(Item2).ID);
end;
function ConvertEPSGtoBin(EPSGFileName : string = 'epsg') : boolean;
{
jeden zaznam:
# Anguilla 1957 / British West Indies Grid
<2000> +proj=tmerc +lat_0=0 +lon_0=-62 +k=0.999500 +x_0=400000 +y_0=0 +ellps=clrk80 +units=m +no_defs no_defs <>
}
var
InF : TextFile;
sTitle, s, sID, sParams : string;
Params : TProjParams;
begin
Params := TProjParams.Create;
AssignFile(InF, EPSGFileName);
try
Reset(InF);
while not Eof(InF) do begin
ReadLn(InF, sTitle);
if (sTitle <> '') and (sTitle[1] = '#') and not Eof(InF) then begin
ReadLn(InF, s);
if (s <> '') and (s[1] = '<') then begin
s := Copy(s, 2, Length(s));
sID := GetAndDeleteStrItem(s, '>');
sParams := s;
with Params.Add do begin
Title := Copy(sTitle, 2, Length(sTitle));
ID := sID;
Params := sParams;
end;
end;
end;
end;
Params.Sort(CompareProjParamByID);
Params.SaveToBinFile(GetBinFileName(EPSGFileName));
finally
CloseFile(InF);
Params.Free;
end;
Result := true;
end;
function GetBinFileName(EPSGFileName : string = 'epsg') : string;
begin
Result := EPSGFileName + '.bin';
end;
// **************************************************************
// TProjParam
// **************************************************************
procedure TProjParam.WriteToStream(s : TStream);
procedure SaveStr(v : string);
var
i : Word;
begin
i := Length(v);
s.Write(i, SizeOf(i));
if i > 0 then s.Write(v[1], i);
end;
begin
SaveStr(Title);
SaveStr(Id);
SaveStr(Params);
end;
procedure TProjParam.ReadFromStream(s : TStream);
function ReadStr: string;
var
i : Word;
begin
s.Read(i, SizeOf(i));
if i = 0
then Result := ''
else begin
SetLength(Result, i);
s.Read(Result[1], i);
end;
end;
begin
Title := ReadStr;
Id := ReadStr;
Params := ReadStr;
end;
// **************************************************************
// TProjParams
// **************************************************************
function TProjParams.FindByID(aID : string) : TProjParam;
var
i : integer;
begin
Result := nil;
for i := 0 to Count - 1 do
with Item[i] do begin
case CompareText(ID, aID) of
0:begin
Result := Item[i];
Exit;
end;
1:Exit;
end;
end;
end;
function TProjParams.GetItem(i : integer) : TProjParam;
begin
Result := pointer(Items[i]);
end;
function TProjParams.Add : TProjParam;
begin
inherited Add(TProjParam.Create);
Result := Pointer(Items[Count - 1]);
end;
procedure TProjParams.SaveToBinFile(FileName : string);
var
s : TMemoryStream;
fs : TFileStream;
i : integer;
c : integer;
begin
s := TMemoryStream.Create;
try
c := Count;
s.Write(c, SizeOf(c));
for i := 0 to Count - 1 do
Item[i].WriteToStream(s);
fs := TFileStream.Create(FileName, fmCreate);
try
s.Position := 0;
fs.CopyFrom(s, s.Size);
finally
fs.Free;
end;
finally
s.Free;
end;
end;
procedure TProjParams.LoadFromBinFile(FileName : string);
var
s : TMemoryStream;
fs : TFileStream;
i, c : integer;
begin
Clear;
if not FileExists(FileName) then Exit;
s := TMemoryStream.Create;
try
fs := TFileStream.Create(FileName, fmOpenRead);
try
s.CopyFrom(fs, fs.Size);
finally
fs.Free;
end;
s.Position := 0;
s.Read(c, SizeOf(c));
for i := 1 to c do
with Add do ReadFromStream(s);
finally
s.Free;
end;
end;
initialization
SetupProjDir('C:\Tera\Source\Libraries\lib.proj.-4.4.7.r\nad');
finalization
Params.Free;
end.
|
unit mav_defs; {MAVlink definitions and variables}
{$mode objfpc}{$H+}
interface
uses
sysutils, q5_common;
const
MAVurl='https://github.com/mavlink/c_library_v2/tree/master/common';
{Extract data from following messages}
MAVmsgX=[0, 1, 22, 24, 30, 32, 33, 65, 74, 87, 105, 141, 147, 245, 253];
{Public functions and procedures}
function MsgIDtoStr(id: integer): string;
function CoordFrameToStr(f: integer): string; {for POSITION_TARGET_GLOBAL_INT}
function MAVseverity(sv: byte): string;
function MAVcompID(cid: byte): string; {MAV_Component_ID}
function MSenStat(m: longword): string; {uint32 MAV_SYS_STATUS_SENSOR}
function GPSfixType(const s:string): string; {MAVlink GPS fix type to string}
function MLStoStr(const m: byte): string; {MAV_LANDED_STATE}
function MSTtoStr(const m: byte): string; {Bitleiste MAV_STATE auswerten}
function MMFtoStr(const m: byte): string; {Bitleiste MAV_Mode_FLAG auswerten}
{$I language.inc}
implementation
{Message Struktur:
https://github.com/mavlink/c_library_v2/tree/master/common
inconsistent !
https://github.com/YUNEEC/MavlinkLib/blob/master/message_definitions/common.xml
https://github.com/YUNEEC/MavlinkLib}
function MsgIDtoStr(id: integer): string;
begin
result:=rsUnknown+' MAV_CMD'+' $'+IntToHex(id, 2)+
' ('+IntToStr(id)+')'; {default}
case id of
0: result:='heartbeat'; {Supported Msg Länge 9}
1: result:='sys_status'; {Supported Msg Länge 1F}
2: result:='system_time'; {Länge 0B}
4: result:='ping';
5: result:='change_operator_control';
6: result:='change_operator_control_ack';
7: result:='auth_key';
8: result:='link_node_status';
11: result:='set_mode';
19: result:='param_ack_transaction';
20: result:='param_request_read';
21: result:='param_request_list';
22: result:='param_value';
23: result:='param_set';
24: result:='gps_raw_int'; {Supported Msg Länge 31/32}
25: result:='gps_status'; {Länge 1}
26: result:='scaled_imu';
$1B: result:='raw_imu';
$1C: result:='raw_pressure';
$1D: result:='scaled_pressure';
$1E: result:='attitude'; {Länge 1C}
$1F: result:='attitude_quaternion'; {Supported Msg Länge 20}
$20: result:='local_position_ned'; {Länge 1C}
$21: result:='global_position_int'; {Supported Msg Länge 1C}
$22: result:='rc_channels_scaled';
$23: result:='rc_channels_raw';
$24: result:='servo_output_raw'; {Länge 10 oder 15}
$25: result:='mission_request_partial_list';
$26: result:='mission_write_partial_list';
$27: result:='mission_item';
$28: result:='mission_request';
$29: result:='mission_set_current';
$2A: result:='mission_current';
43: result:='mission_request_list';
$2C: result:='mission_count'; {Länge 3 oder 5}
$2D: result:='mission_clear_all';
$2E: result:='mission_item_reached';
$2F: result:='mission_ack';
$30: result:='set_gps_global_origin';
$31: result:='gps_global_origin';
$32: result:='param_map_rc';
51: result:='mission_request_int';
52: result:='mission_changed';
54: result:='safety_set_allowed_area';
55: result:='safety_allowed_area';
$3D: result:='attitude_quaternion_cov';
$3E: result:='nav_controller_output';
$3F: result:='global_position_int_cov';
$40: result:='local_position_ned_cov';
$41: result:='rc_channels'; {Supported Msg Länge 2A}
$42: result:='request_data_stream';
$43: result:='data_stream';
$45: result:='manual_control'; {Länge 0B}
$46: result:='rc_channels_override'; {Länge 11}
$49: result:='mission_item_int';
$4A: result:='vfr_hud'; {Länge 11}
$4B: result:='command_int';
$4C: result:='command_long'; {Länge 20}
$4D: result:='command_ack';
$4E: result:='command_cancel'; {78: UTC time stamp, Boot time}
$4F: result:='command_long_stamped'; {79: not supported anymore}
$51: result:='manual_setpoint';
$52: result:='set_attitude_target';
$53: result:='attitude_target'; {Länge 24}
$54: result:='set_position_target_local_ned';
$55: result:='position_target_local_ned'; {Länge 33}
$56: result:='set_position_target_global_int';
$57: result:='position_target_global_int'; {Länge 3}
$59: result:='local_position_ned_system_global_offset';
$5A: result:='hil_state';
$5B: result:='hil_controls';
$5C: result:='hil_rc_inputs_raw';
$5D: result:='hil_actuator_controls';
$64: result:='optical_flow';
$65: result:='global_vision_position_estimate';
$66: result:='vision_position_estimate';
$67: result:='vision_speed_estimate';
$68: result:='vicon_position_estimate';
$69: result:='highres_imu'; {Länge 3E}
$6A: result:='optical_flow_rad';
$6B: result:='hil_sensor';
$6C: result:='sim_state';
$6D: result:='radio_status';
$6E: result:='file_transfer_protocol';
$6F: result:='timesync'; {Länge 0D}
$70: result:='camera_trigger';
$71: result:='hil_gps';
$72: result:='hil_optical_flow';
$73: result:='hil_state_quaternion';
116: result:='scaled_imu2';
$75: result:='log_request_list';
$76: result:='log_entry';
$77: result:='log_request_data';
$78: result:='log_data';
$79: result:='log_erase';
$7A: result:='log_request_end';
$7B: result:='gps_inject_data';
$7C: result:='gps2_raw';
$7D: result:='power_status';
$7E: result:='serial_control';
$7F: result:='gps_rtk';
$80: result:='gps2_rtk';
$81: result:='scaled_imu3';
$82: result:='data_transmission_handshake';
$83: result:='encapsulated_data';
$84: result:='distance_sensor';
$85: result:='terrain_request';
$86: result:='terrain_data';
$87: result:='terrain_check';
$88: result:='terrain_report';
$89: result:='scaled_pressure2';
$8A: result:='att_pos_mocap';
$8B: result:='set_actuator_control_target';
$8C: result:='actuator_control_target'; {Länge 14}
$8D: result:='altitude'; {Länge 20}
$8E: result:='resource_request';
$8F: result:='scaled_pressure3';
$90: result:='follow_target';
$92: result:='control_system_state';
$93: result:='battery_status';
$94: result:='autopilot_version'; {Länge 34, 48, 4C}
149: result:='landing_target';
162: result:='fence_status';
192: result:='mag_cal_report';
225: result:='efi_status';
{MESSAGE IDs 180 - 229: Space for custom messages in
individual projectname_messages.xml files -->}
(* 201: result:='sens_power'; {not know if used}
202: result:='sens_MPTT';
203: result:='aslctrl_data';
204: result:='aslctrl_debug';
205: result:='asluav_status';
206: result:='ekf_ext'; {Wind speed and such stuff}
207: result:='asl_obctrl';
208: result:='sens_atmos'; {Atmospheric sensors}
209: result:='sens_batmon'; {Battery monitor}
210: result:='fw_soaring_data'; {fixed wing...}
211: result:='sensorpod_status';
212: result:='sens_power_board';
213: result:='gsm_link_status'; {LTE too} *)
230: result:='estimator_status'; {Länge 2A}
$E7: result:='wind_cov'; {Länge 20}
$E8: result:='gps_input';
$E9: result:='gps_rtcm_data';
$EA: result:='high_latency';
$EB: result:='high_latency2';
241: result:='vibration'; {Länge 14}
$F2: result:='home_position'; {Supported Msg Länge 28 oder 3C}
$F3: result:='set_home_position';
$F4: result:='message_interval';
$F5: result:='extended_sys_state'; {Länge 02}
$F6: result:='adsb_vehicle';
$F7: result:='collision';
$F8: result:='v2_extension';
$F9: result:='memory_vect';
$FA: result:='debug_vect';
$FB: result:='named_value_float';
$FC: result:='named_value_int';
$FD: result:='statustext'; {Länge variabel}
$FE: result:='debug';
256: result:='setup_signing';
$101: result:='button_change';
$102: result:='play_tune';
$103: result:='camera_information';
$104: result:='camera_settings';
$105: result:='storage_information';
$106: result:='camera_capture_status';
$107: result:='camera_image_captured'; {Länge FC}
$108: result:='flight_information'; {Supported Msg Länge 1B}
$109: result:='mount_orientation'; {Länge 20}
$10A: result:='logging_data';
$10B: result:='logging_data_acked';
$10C: result:='logging_ack';
$10D: result:='video_stream_information';
$10E: result:='video_stream_status'; {270 len 19}
$10F: result:='camera_fov_status'; {271 len 52}
275: result:='camera_tracking_image_status'; {275 len 31}
276: result:='camera_tracking_geo_status'; {276 len 49}
280: result:='gimbal_manager_information';
281: result:='gimbal_manager_status';
282: result:='gimbal_manager_set_attitude';
283: result:='gimbal_device_information';
284: result:='gimbal_device_set_attitude';
285: result:='gimbal_device_attitude_status';
286: result:='autopilot_state_for_gimbal_device';
287: result:='gimbal_manager_set_pitchyaw';
288: result:='gimbal_manager_set_manual_control';
290: result:='esc_info';
291: result:='esc_status';
299: result:='wifi_config_ap';
300: result:='protocol_version'; {12C'h not supported anymore}
301: result:='ais_vessel';
310: result:='uavcan_node_status';
$137: result:='uavcan_node_info';
$140: result:='param_ext_request_read';
$141: result:='param_ext_request_list';
$142: result:='param_ext_value'; {Länge 95}
$143: result:='param_ext_set';
$144: result:='param_ext_ack'; {Länge 91}
$14A: result:='obstacle_distance'; {Länge 9E}
$14B: result:='odometry';
$14C: result:='trajectory_representation_waypoints';
$14D: result:='trajectory_representation_bezier';
336: result:='cellular_config';
339: result:='raw_rpm';
340: result:='UTM_global_position'; {154'h}
350: result:='debug_float_array';
360: result:='orbit_execution_status';
370: result:='smart_battery_info';
373: result:='generator_status';
375: result:='actuator_output_status';
380: result:='time_estimate_to_target';
385: result:='tunnel';
390: result:='onboard_computer_status';
395: result:='component_information';
400: result:='play_tune v2';
401: result:='supported_tunes';
9000: result:='wheel_distance'; {2328'h}
9005: result:='winch_status';
12900: result:='open_drone_id_basic_id'; {3264'h}
12901: result:='open_drone_id_location';
12902: result:='open_drone_id_authentication';
12903: result:='open_drone_id_self_id';
12904: result:='open_drone_id_system';
12905: result:='open_drone_id_operator_id';
12915: result:='open_drone_id_message_pack';
12918: result:='open_drone_id_arm_status';
12919: result:='open_drone_id_system_update';
19920: result:='hygrometer_sensor';
end;
end;
{https://github.com/mavlink/c_library_v2/blob/master/common/mavlink_msg_position_target_global_int.h}
function CoordFrameToStr(f: integer): string; {for POSITION_TARGET_GLOBAL_INT}
begin
result:='';
case f of
5: result:='GLOBAL';
6: result:='GLOBAL_RELATIVE_ALT';
11: result:='GLOBAL_TERRAIN_ALT';
end;
end;
(* unused until now
{https://github.com/YUNEEC/MavlinkLib/blob/master/message_definitions/ASLUAV.xml}
function GSMlinkType(sv: byte): string;
begin
result:='Link type unknown';
case sv of
0: result:='No service';
2: result:='2G (GSM/GRPS/EDGE) link';
3: result:='3G link (WCDMA/HSDPA/HSPA)';
4: result:='4G link (LTE)';
end;
end; *)
{ENUMs see: https://github.com/mavlink/c_library_v2/blob/master/common/common.h}
function MAVseverity(sv: byte): string;
begin
result:='';
case sv of
0: result:=emcyID; {System is unusable. This is a "panic" condition}
1: result:='ALERT'; {Action should be taken immediately. Indicates error
in non-critical systems}
2: result:='CRITICAL'; {Action must be taken immediately. Indicates failure
in a primary system}
3: result:='ERROR'; {Indicates an error in secondary/redundant systems}
4: result:='WARNING'; {Indicates about a possible future error if this
is not resolved within a given timeframe. Example
would be a low battery warning}
5: result:='NOTICE'; {An unusual event has occurred, though not an error
condition. This should be investigated for the
root cause.}
6: result:='INFO'; {Normal operational messages. Useful for logging.
No action is required for these messages.}
7: result:='DEBUG'; {Useful non-operational messages that can assist in
debugging. These should not occur during normal
operation}
end;
end;
{https://developer.yuneec.com/documentation/125/Supported-mavlink-messages
https://github.com/YUNEEC/MavlinkLib/blob/master/message_definitions/common.xml}
function MAVcompID(cid: byte): string; {MAV_Component_ID}
begin
result:='';
case cid of
0: result:='ALL';
1: result:='AUTOPILOT 1';
25..86, 88..99: result:='USER '+IntToStr(cid-24);
87: result:='USER 63 (H520 - CGO-ET?)';
100..105: result:='CAMERA '+IntToStr(cid-99);
140..153: result:='SERVO '+IntToStr(cid-139);
154: result:='GIMBAL 1';
155: result:='LOG';
156: result:='ADSB';
157: result:='OSD';
158: result:='PERIPHERAL';
159: result:='QX1_GIMBAL';
160: result:='FLARM';
171..175: result:='GIMBAL '+IntToStr(cid-169);
180: result:='MAPPER';
190: result:='MISSIONPLANNER';
195: result:='PATHPLANNER';
200: result:='IMU';
201: result:='IMU 2';
202: result:='IMU 3';
220: result:='GPS';
221: result:='GPS 2';
240: result:='UDP BRIDGE';
241: result:='UART BRIDGE';
250: result:='SYSTEM CONTROL';
end;
end;
{https://github.com/mavlink/c_library_v2/blob/master/common/common.h
1 MAV_SYS_STATUS_SENSOR_3D_GYRO 0x01 3D gyro
2 MAV_SYS_STATUS_SENSOR_3D_ACCEL 0x02 3D accelerometer
4 MAV_SYS_STATUS_SENSOR_3D_MAG 0x04 3D magnetometer
8 MAV_SYS_STATUS_SENSOR_ABSOLUTE_PRESSURE 0x08 absolute pressure
16 MAV_SYS_STATUS_SENSOR_DIFFERENTIAL_PRESSURE 0x10 differential pressure
32 MAV_SYS_STATUS_SENSOR_GPS 0x20 GPS
64 MAV_SYS_STATUS_SENSOR_OPTICAL_FLOW 0x40 optical flow
128 MAV_SYS_STATUS_SENSOR_VISION_POSITION 0x80 computer vision position
256 MAV_SYS_STATUS_SENSOR_LASER_POSITION 0x100 laser based position
512 MAV_SYS_STATUS_SENSOR_EXTERNAL_GROUND_TRUTH 0x200 external ground truth (Vicon or Leica)
1024 MAV_SYS_STATUS_SENSOR_ANGULAR_RATE_CONTROL 0x400 3D angular rate control
2048 MAV_SYS_STATUS_SENSOR_ATTITUDE_STABILIZATION 0x800 attitude stabilization
4096 MAV_SYS_STATUS_SENSOR_YAW_POSITION 0x1000 yaw position
8192 MAV_SYS_STATUS_SENSOR_Z_ALTITUDE_CONTROL 0x2000 z/altitude control
16384 MAV_SYS_STATUS_SENSOR_XY_POSITION_CONTROL 0x4000 x/y position control
32768 MAV_SYS_STATUS_SENSOR_MOTOR_OUTPUTS 0x8000 motor outputs / control
65536 MAV_SYS_STATUS_SENSOR_RC_RECEIVER 0x10000 rc receiver
131072 MAV_SYS_STATUS_SENSOR_3D_GYRO2 0x20000 2nd 3D gyro
262144 MAV_SYS_STATUS_SENSOR_3D_ACCEL2 0x40000 2nd 3D accelerometer
524288 MAV_SYS_STATUS_SENSOR_3D_MAG2 0x80000 2nd 3D magnetometer
1048576 MAV_SYS_STATUS_GEOFENCE 0x100000 geofence
2097152 MAV_SYS_STATUS_AHRS 0x200000 AHRS subsystem health
4194304 MAV_SYS_STATUS_TERRAIN 0x400000 Terrain subsystem health
8388608 MAV_SYS_STATUS_REVERSE_MOTOR 0x800000 Motors are reversed
16777216 MAV_SYS_STATUS_LOGGING 0x1000000 Logging
33554432 MAV_SYS_STATUS_SENSOR_BATTERY 0x2000000 Battery
67108864 MAV_SYS_STATUS_SENSOR_PROXIMITY 0x4000000 Proximity
134217728 MAV_SYS_STATUS_SENSOR_SATCOM 0x8000000 Satellite Communication}
function MSenStat(m: longword): string; {uint32 MAV_SYS_STATUS_SENSOR}
begin
result:='';
if m>0 then begin
if (m and 1)>0 then result:=result+'3D_GYRO ';
if (m and 2)>0 then result:=result+'3D_ACCEL ';
if (m and 4)>0 then result:=result+'3D_MAG ';
if (m and 8)>0 then result:=result+'ABSOLUTE_PRESSURE ';
if (m and 16)>0 then result:=result+'DIFFERENTIAL_PRESSURE ';
if (m and 32)>0 then result:=result+'GPS ';
if (m and 64)>0 then result:=result+'OPTICAL_FLOW ';
if (m and 128)>0 then result:=result+'VISION_POSITION ';
if (m and 256)>0 then result:=result+'LASER_POSITION ';
if (m and 512)>0 then result:=result+'EXTERNAL_GROUND_TRUTH ';
if (m and 1024)>0 then result:=result+'ANGULAR_RATE_CONTROL ';
if (m and 2048)>0 then result:=result+'ATTITUDE_STABILIZATION ';
if (m and 4096)>0 then result:=result+'YAW_POSITION ';
if (m and 8192)>0 then result:=result+'Z_ALTITUDE_CONTROL ';
if (m and 16384)>0 then result:=result+'XY_POSITION_CONTROL ';
if (m and 32768)>0 then result:=result+'MOTOR_OUTPUTS ';
if (m and 65536)>0 then result:=result+'RC_RECEIVER ';
if (m and 131072)>0 then result:=result+'3D_GYRO2 ';
if (m and 262144)>0 then result:=result+'3D_ACCEL2 ';
if (m and 524288)>0 then result:=result+'3D_MAG2 ';
if (m and 1048576)>0 then result:=result+'GEOFENCE ';
if (m and 2097152)>0 then result:=result+'AHRS ';
if (m and 4194304)>0 then result:=result+'TERRAIN ';
if (m and 8388608)>0 then result:=result+'REVERSE_MOTOR ';
if (m and 16777216)>0 then result:=result+'LOGGING ';
if (m and 33554432)>0 then result:=result+'BATTERY ';
if (m and 67108864)>0 then result:=result+'PROXIMITY ';
if (m and 134217728)>0 then result:=result+'SATCOM ';
end else result:='0';
end;
{https://mavlink.io/en/messages/common.html#GPS_FIX_TYPE (nicht aktuell!)
besser hier: https://github.com/mavlink/c_library_v2/tree/master/common
siehe heartbeat "Verdrehung"
0 GPS_FIX_TYPE_NO_GPS No GPS connected
1 GPS_FIX_TYPE_NO_FIX No position information, GPS is connected
2 GPS_FIX_TYPE_2D_FIX 2D position
3 GPS_FIX_TYPE_3D_FIX 3D position
4 GPS_FIX_TYPE_DGPS DGPS/SBAS aided 3D position
5 GPS_FIX_TYPE_RTK_FLOAT RTK float, 3D position
6 GPS_FIX_TYPE_RTK_FIXED RTK Fixed, 3D position
7 GPS_FIX_TYPE_STATIC Static fixed, typically used for base stations
8 GPS_FIX_TYPE_PPP PPP, 3D position.}
function GPSfixType(const s:string): string; {MAVlink GPS fix type to string}
var w: integer;
begin
result:=rsUnknown;
w:=StrToIntDef(s, 0);
case w of
0: Result:='No GPS connected';
1: Result:='No position information, GPS is connected';
2: Result:='2D position';
3: Result:='3D position';
4: Result:='DGPS/SBAS aided 3D position';
5: Result:='RTK float, 3D position';
6: Result:='RTK fixed, 3D position';
7: Result:='Static fixed, typically used for base stations';
8: Result:='PPP, 3D position';
end;
end;
{https://mavlink.io/en/messages/common.html#MAV_LANDED_STATE
(nicht aktuell!) besser hier: https://github.com/mavlink/c_library_v2/tree/master/common
siehe heartbeat "Verdrehung"
0 MAV_LANDED_STATE_UNDEFINED MAV landed state is unknown
1 MAV_LANDED_STATE_ON_GROUND MAV is landed (on ground)
2 MAV_LANDED_STATE_IN_AIR MAV is in air
3 MAV_LANDED_STATE_TAKEOFF MAV currently taking off
4 MAV_LANDED_STATE_LANDING MAV currently landing }
function MLStoStr(const m: byte): string; {MAV_LANDED_STATE}
begin
case m of
1: result:='Landed (on ground)';
2: result:='In air';
3: result:='Currently taking off';
4: result:='Currently landing';
else
result:='MAV landed state undef';
end;
end;
{https://mavlink.io/en/messages/common.html#MAV_STATE
(nicht aktuell!) besser hier: https://github.com/mavlink/c_library_v2/tree/master/common
siehe heartbeat "Verdrehung"
0 MAV_STATE_UNINIT Uninitialized system, state is unknown.
bit 0 MAV_STATE_BOOT System is booting up.
bit 1 MAV_STATE_CALIBRATING System is calibrating and not flight-ready.
bit 2 MAV_STATE_STANDBY System is grounded and on standby. It can be launched any time.
bit 3 MAV_STATE_ACTIVE System is active and might be already airborne. Motors are engaged.
bit 4 MAV_STATE_CRITICAL System is in a non-normal flight mode. It can however still navigate.
bit 5 MAV_STATE_EMERGENCY System is in a non-normal flight mode. It lost control over parts or over the whole airframe. It is in mayday and going down.
bit 6 MAV_STATE_POWEROFF System just initialized its power-down sequence, will shut down now.
bit 7 MAV_STATE_FLIGHT_TERMINATION System is terminating itself.
H Plus: MAVstate = 0 wird während Compass Calibration ausgegeben, sollte 2 sein}
function MSTtoStr(const m: byte): string; {Bitleiste MAV_STATE auswerten}
begin
result:='MAV_STATE'+suff;
case m of
0: result:=result+'UNINIT';
1: result:=result+'BOOT';
2: result:=result+'CALIBRATING';
3: result:=result+'STANDBY';
4: result:=result+'ACTIVE';
5: result:=result+'CRITICAL';
6: result:=result+emcyID;
7: result:=result+'POWEROFF';
8: result:=result+'FLIGHT_TERMINATION';
else
result:=result+rsUnknown;
end;
end;
{https://mavlink.io/en/messages/common.html MAV_MODE_FLAG
(nicht aktuell!) besser hier: https://github.com/mavlink/c_library_v2/tree/master/common
siehe heartbeat "Verdrehung"
Flags:
https://github.com/mavlink/c_library_v2/blob/master/common/common.h
These flags encode the MAV mode. In Heartbeat base-mode +6
Value Field Name Description
128 MAV_MODE_FLAG_SAFETY_ARMED 0b10000000 MAV safety set to armed. Motors are enabled / running / can start. Ready to fly. Additional note: this flag is to be ignore when sent in the command MAV_CMD_DO_SET_MODE and MAV_CMD_COMPONENT_ARM_DISARM shall be used instead. The flag can still be used to report the armed state.
64 MAV_MODE_FLAG_MANUAL_INPUT_ENABLED 0b01000000 remote control input is enabled.
32 MAV_MODE_FLAG_HIL_ENABLED 0b00100000 hardware in the loop simulation. All motors / actuators are blocked, but internal software is full operational.
16 MAV_MODE_FLAG_STABILIZE_ENABLED 0b00010000 system stabilizes electronically its attitude (and optionally position). It needs however further control inputs to move around.
8 MAV_MODE_FLAG_GUIDED_ENABLED 0b00001000 guided mode enabled, system flies waypoints / mission items.
4 MAV_MODE_FLAG_AUTO_ENABLED 0b00000100 autonomous mode enabled, system finds its own goal positions. Guided flag can be set or not, depends on the actual implementation.
2 MAV_MODE_FLAG_TEST_ENABLED 0b00000010 system has a test mode enabled. This flag is intended for temporary system tests and should not be used for stable implementations.
1 MAV_MODE_FLAG_CUSTOM_MODE_ENABLED 0b00000001 Reserved for future use.}
function MMFtoStr(const m: byte): string; {Bitleiste MAV_Mode_FLAG auswerten}
begin
result:='MAV_MODE_FLAG'+suff;
if m>0 then begin
if (m and 1)>0 then result:=result+'CUSTOM_MODE_ENABLED ';
if (m and 2)>0 then result:=result+'TEST_ENABLED ';
if (m and 4)>0 then result:=result+'AUTO_ENABLED ';
if (m and 8)>0 then result:=result+'GUIDED_ENABLED ';
if (m and 16)>0 then result:=result+'STABILIZE_ENABLED ';
if (m and 32)>0 then result:=result+'HIL_ENABLED ';
if (m and 64)>0 then result:=result+'MANUAL_INPUT_ENABLED ';
if (m and 128)>0 then result:=result+'SAFETY_ARMED';
end else Result:=result+rsUnknown;
end;
end.
|
unit Configuracoes;
interface
uses
IniFiles, SysUtils, Funcoes, Forms;
type
TConfiguracoes = Class(TObject)
Private
// Descritores Predefinidos - Planilhas
fPastaOrigem: String;
fPastaDestino: String;
fPastaLogs: String;
fMoverArquivos: Boolean;
// Banco de dados
fServidor: String;
fBanco: String;
fUsuario: String;
fSenha: String;
// Carga Bematech
fArquivoAccess: String;
Public
Property PastaOrigem : String read fPastaOrigem write fPastaOrigem;
Property PastaDestino: String read fPastaDestino write fPastaDestino;
Property PastaLogs: String read fPastaLogs write fPastaLogs;
Property MoverArquivos: Boolean read fMoverArquivos write fMoverArquivos;
Property Servidor: String read fServidor write fServidor;
Property Banco: String read fBanco write fBanco;
Property Usuario: String read fUsuario write fUsuario;
property Senha: String read fSenha write fSenha;
property ArquivoAccess: String read fArquivoAccess write fArquivoAccess;
Function CarregarConfiguracoes: Boolean;
Function SalvarConfiguracoes: Boolean;
End;
var
Configuracao: TConfiguracoes;
implementation
{ TConfiguracoes }
function TConfiguracoes.CarregarConfiguracoes: Boolean;
var ini: TIniFile;
begin
try
try
ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + '\ap.ini');
Self.fPastaOrigem := ini.ReadString('planilhas','pasta_origem','');
Self.fPastaDestino := ini.ReadString('planilhas','pasta_destino','');
Self.fPastaLogs := ini.ReadString('planilhas','pasta_logs','');
Self.fMoverArquivos := ini.ReadString('planilhas','mover_apos_processar','') = 'S';
Self.fServidor := ini.ReadString('banco','servidor','');
Self.fBanco := ini.ReadString('banco','banco','');
Self.fUsuario := ini.ReadString('banco','usuario','');
Self.fSenha := ini.ReadString('banco','senha','');
Self.fArquivoAccess := ini.ReadString('carga_bematech','arquivo_access','');
result := True;
finally
FreeAndNil(ini);
end;
Except
result := False;
end;
end;
function TConfiguracoes.SalvarConfiguracoes: Boolean;
var ini: TIniFile;
barra: String;
begin
try
try
ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + '\ap.ini');
if Copy(Self.PastaOrigem, Length(Self.PastaOrigem), 1) <> '\' then
barra := '\'
else
barra := '';
ini.WriteString('planilhas', 'pasta_origem', Self.fPastaOrigem + barra);
ini.WriteString('planilhas', 'pasta_destino', Self.fPastaDestino + barra);
ini.WriteString('planilhas', 'pasta_logs', Self.fPastaLogs + barra);
if fMoverArquivos then
ini.WriteString('planilhas','mover_apos_processar', 'S')
else
ini.WriteString('planilhas','mover_apos_processar', 'N');
ini.WriteString('banco','servidor', Self.fServidor);
ini.WriteString('banco','banco', Self.fBanco);
ini.WriteString('banco','usuario', Self.fUsuario);
ini.WriteString('banco','senha', Self.fSenha);
ini.WriteString('carga_bematech', 'arquivo_access', Self.fArquivoAccess);
result := True;
finally
FreeAndNil(ini);
end;
Except
result := False;
end;
end;
end.
|
unit Form.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Mask,
// -----
Action.DataSet,
Vcl.AppEvnts;
type
TForm1 = class(TForm)
FDConnection1: TFDConnection;
fdqCustomers: TFDQuery;
DBNavigator1: TDBNavigator;
DBEdit1: TDBEdit;
DBGrid1: TDBGrid;
tmrReady: TTimer;
Button1: TButton;
GroupBox1: TGroupBox;
btnDataSourceRemove: TButton;
btnDataSourceCreate: TButton;
btnBindAction: TButton;
procedure btnBindActionClick(Sender: TObject);
procedure btnDataSourceCreateClick(Sender: TObject);
procedure btnDataSourceRemoveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure tmrReadyTimer(Sender: TObject);
private
actDataSetFirst: TDataSetFirstAction;
procedure BindDBControlsToDataSet (DataSet: TDataSet);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
actDataSetFirst := TDataSetFirstAction.Create(Button1);
actDataSetFirst.Caption := '⏪ First';
Button1.Action := actDataSetFirst;
end;
procedure TForm1.tmrReadyTimer(Sender: TObject);
begin
tmrReady.Enabled := False;
FDConnection1.Open();
fdqCustomers.Open();
BindDBControlsToDataSet(fdqCustomers);
actDataSetFirst.DataSource := DBNavigator1.DataSource;
end;
procedure TForm1.BindDBControlsToDataSet (DataSet: TDataSet);
begin
DBGrid1.DataSource := TDataSource.Create(Self);
DBEdit1.DataSource := DBGrid1.DataSource;
DBEdit1.DataField := 'CompanyName';
DBNavigator1.DataSource := DBGrid1.DataSource;
DBGrid1.DataSource.DataSet := DataSet;
end;
procedure TForm1.btnBindActionClick(Sender: TObject);
begin
if DBGrid1.DataSource <> nil then
actDataSetFirst.DataSource := DBGrid1.DataSource;
end;
procedure TForm1.btnDataSourceCreateClick(Sender: TObject);
begin
if DBGrid1.DataSource = nil then
BindDBControlsToDataSet(fdqCustomers);
end;
procedure TForm1.btnDataSourceRemoveClick(Sender: TObject);
var
aDataSource: TDataSource;
begin
if DBGrid1.DataSource <> nil then
begin
aDataSource := DBGrid1.DataSource;
aDataSource.Free;
end;
end;
end.
|
unit CRBaseActions;
interface
uses BaseActions, BaseObjects,
TestInterval, Controls,
Classes, Windows, CoreInterfaces, LoggerImpl;
type
TSlottingBaseLoadAction = class(TBaseAction)
end;
TSlottingBaseEditAction = class(TBaseAction, ILogger)
private
function GetLogger: TMemoLogger;
public
property Logger: TMemoLogger read GetLogger implements ILogger;
function Execute(ABaseObject: TIDObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TSlottingBaseAddAction = class(TSlottingBaseEditAction)
public
function Execute: boolean; override;
function Execute(ABaseObject: TIDObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TSlottingPlacementBaseAddAction = class(TBaseAction)
public
function Execute: boolean; override;
function Execute(ABaseObject: TIDObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TSlottingDeleteAction = class(TBaseAction)
public
function Execute(ABaseObject: TIDObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TRockSampleSizeTypeEditAction = class(TBaseAction)
public
function Execute(ABaseObject: TIDObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TRockSampleSizeTypeAddAction = class(TRockSampleSizeTypeEditAction)
public
function Execute: boolean; override;
function Execute(ABaseObject: TIDObject): boolean; override;
function Execute(ABaseCollection: TIDObjects): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TCollectionEditAction = class(TBaseAction)
public
function Execute(ABaseObject: TIDObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TCollectionAddAction = class(TCollectionEditAction)
public
function Execute(ABaseObject: TIDObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TCollectionSampleEditAction = class(TBaseAction)
public
function Execute(ABaseObject: TIDObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
TCollectionSampleAddAction = class(TCollectionSampleEditAction)
public
function Execute(ABaseObject: TIDObject): boolean; override;
constructor Create(AOwner: TComponent); override;
end;
implementation
uses CRSlottingEditForm, CommonFrame, SysUtils, CRSlottingPlacementEdit,
Slotting, CRRockSampleSizeTypeEditFrame,
CRSampleSizeTypeEditForm, CRCollectionEditForm, CRSampleEditForm, Well;
{ TSlottingBaseEditAction }
constructor TSlottingBaseEditAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Caption := 'Редактировать интервал отбора керна';
end;
function TSlottingBaseEditAction.Execute(ABaseObject: TIDObject): boolean;
begin
Result := true;
if not Assigned(frmSlottingEdit) then frmSlottingEdit := TfrmSlottingEdit.Create(Self);
frmSlottingEdit.ToolBarVisible := false;
frmSlottingEdit.Clear;
frmSlottingEdit.EditingObject := ABaseObject;
frmSlottingEdit.dlg.ActiveFrameIndex := 0;
if frmSlottingEdit.ShowModal = mrOK then
begin
frmSlottingEdit.Save;
// это у нас такая транзакционность - самый простой случай
try
ABaseObject := (frmSlottingEdit.dlg.Frames[0] as TfrmCommonFrame).EditingObject;
if ((ABaseObject as TSlotting).Owner is TWell) then ((ABaseObject as TSlotting).Owner as TWell).SlottingPlacement.Update();
ABaseObject.Update;
(ABaseObject as TSlotting).Boxes.Update(nil);
(ABaseObject as TSlotting).RockSampleSizeTypePresences.Update(nil);
except
on E: Exception do
begin
if Assigned(LastObjectCopy) then ABaseObject.Assign(LastObjectCopy)
else FreeAndNil(ABaseObject);
raise EObjectAddingException.Create(ABaseObject, E);
end;
end;
end;
end;
function TSlottingBaseEditAction.GetLogger: TMemoLogger;
begin
Result := TMemoLogger.GetInstance;
end;
{ TSlottingBaseAddAction }
constructor TSlottingBaseAddAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Caption := 'Добавить интервал отбора керна';
end;
function TSlottingBaseAddAction.Execute: boolean;
begin
Result := Execute(nil);
end;
function TSlottingBaseAddAction.Execute(ABaseObject: TIDObject): boolean;
begin
Result := inherited Execute(ABaseObject);
end;
{ TCoreMechanicalStateBaseEditAction }
{ TSlottingDeleteAction }
constructor TSlottingDeleteAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Caption := 'Удалить интервал отбора керна';
end;
function TSlottingDeleteAction.Execute(ABaseObject: TIDObject): boolean;
begin
Result := true;
if MessageBox(0, PChar('Вы действительно хотите удалить интервал отбора керна ' + #13#10 +
ABaseObject.List + '?'), 'Вопрос',
MB_YESNO+MB_TASKMODAL+MB_DEFBUTTON2+MB_ICONQUESTION) = ID_YES then
begin
try
ABaseObject.Collection.Remove(ABaseObject);
except
on E: Exception do
begin
if Assigned(LastObjectCopy) then ABaseObject.Assign(LastObjectCopy)
else FreeAndNil(ABaseObject);
raise EObjectDeletingException.Create(ABaseObject);
end;
end;
end;
end;
{ TSlottingPlacementBaseAddAction }
constructor TSlottingPlacementBaseAddAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
CanUndo := false;
Caption := 'Редактировать местоположение керна';
end;
function TSlottingPlacementBaseAddAction.Execute: boolean;
begin
Result := Execute(nil);
end;
function TSlottingPlacementBaseAddAction.Execute(
ABaseObject: TIDObject): boolean;
begin
Result := true;
if not Assigned(frmSlottingPlacementEditForm) then frmSlottingPlacementEditForm := TfrmSlottingPlacementEditForm.Create(Self);
frmSlottingPlacementEditForm.Clear;
frmSlottingPlacementEditForm.EditingObject := ABaseObject;
frmSlottingPlacementEditForm.dlg.ActiveFrameIndex := 0;
if frmSlottingPlacementEditForm.ShowModal = mrOK then
begin
frmSlottingPlacementEditForm.Save;
// это у нас такая транзакционность - самый простой случай
try
ABaseObject := (frmSlottingPlacementEditForm.dlg.Frames[0] as TfrmCommonFrame).EditingObject;
ABaseObject.Update;
except
on E: Exception do
begin
if Assigned(LastObjectCopy) then ABaseObject.Assign(LastObjectCopy)
else FreeAndNil(ABaseObject);
raise EObjectAddingException.Create(ABaseObject, E);
end;
end;
end;
end;
{ TRockSampleSizeTypeEditAction }
constructor TRockSampleSizeTypeEditAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Caption := 'Редактировать типоразмер образца';
end;
function TRockSampleSizeTypeEditAction.Execute(
ABaseObject: TIDObject): boolean;
begin
if not Assigned(frmSampleSizeTypeEditor) then frmSampleSizeTypeEditor := TfrmSampleSizeTypeEditor.Create(Self);
Result := true;
frmSampleSizeTypeEditor.Clear;
frmSampleSizeTypeEditor.EditingObject := ABaseObject;
frmSampleSizeTypeEditor.dlg.ActiveFrameIndex := 0;
(frmSampleSizeTypeEditor.dlg.Frames[0] as TfrmRockSampleSizeTypeEditFrame).ShowShortName := true;
if frmSampleSizeTypeEditor.ShowModal = mrOK then
begin
frmSampleSizeTypeEditor.Save;
// это у нас такая транзакционность - самый простой случай
try
ABaseObject := (frmSampleSizeTypeEditor.dlg.Frames[0] as TfrmCommonFrame).EditingObject;
ABaseObject.Update;
except
on E: Exception do
begin
if Assigned(LastObjectCopy) then ABaseObject.Assign(LastObjectCopy)
else FreeAndNil(ABaseObject);
raise EObjectAddingException.Create(ABaseObject, E);
end;
end;
end;
end;
{ TRockSampleSizeTypeAddAction }
{constructor TRockSampleSizeTypeAddAction.Create(AOwner: TComponent);
begin
inherited;
end;
function TRockSampleSizeTypeAddAction.Execute: boolean;
begin
Result := Execute(TIDObject(nil));
end;
function TRockSampleSizeTypeAddAction.Execute(
ABaseObject: TIDObject): boolean;
begin
Result := inherited Execute(ABaseObject);
end;
function TRockSampleSizeTypeAddAction.Execute(
ABaseCollection: TIDObjects): boolean;
begin
end;}
{ TRockSampleSizeTypeAddAction }
constructor TRockSampleSizeTypeAddAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Caption := 'Добавить типоразмер образца';
end;
function TRockSampleSizeTypeAddAction.Execute: boolean;
begin
Result := Execute(TIDObject(nil));
end;
function TRockSampleSizeTypeAddAction.Execute(
ABaseObject: TIDObject): boolean;
begin
Result := inherited Execute(ABaseObject);
end;
function TRockSampleSizeTypeAddAction.Execute(
ABaseCollection: TIDObjects): boolean;
begin
if not Assigned(frmSampleSizeTypeEditor) then frmSampleSizeTypeEditor := TfrmSampleSizeTypeEditor.Create(Self);
frmSampleSizeTypeEditor.Clear;
frmSampleSizeTypeEditor.IDObjects := ABaseCollection;
Result := Execute;
end;
{ TCollectionEditAction }
constructor TCollectionEditAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Caption := 'Редактировать коллекцию';
end;
function TCollectionEditAction.Execute(ABaseObject: TIDObject): boolean;
begin
if not Assigned(frmCollectionEditForm) then frmCollectionEditForm := TfrmCollectionEditForm.Create(Self);
Result := true;
frmCollectionEditForm.Clear;
frmCollectionEditForm.EditingObject := ABaseObject;
if frmCollectionEditForm.ShowModal = mrOK then
begin
frmCollectionEditForm.Save;
// это у нас такая транзакционность - самый простой случай
try
ABaseObject := (frmCollectionEditForm.dlg.Frames[0] as TfrmCommonFrame).EditingObject;
ABaseObject.Update;
except
on E: Exception do
begin
if Assigned(LastObjectCopy) then ABaseObject.Assign(LastObjectCopy)
else FreeAndNil(ABaseObject);
raise EObjectAddingException.Create(ABaseObject, E);
end;
end;
end;
end;
{ TCollectionAddAction }
constructor TCollectionAddAction.Create(AOwner: TComponent);
begin
inherited;
Caption := 'Добавить коллекцию';
end;
function TCollectionAddAction.Execute(ABaseObject: TIDObject): boolean;
begin
Result := inherited Execute(nil);
end;
{ TCollectionSampleAddAction }
constructor TCollectionSampleAddAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Caption := 'Добавить образец коллекции';
end;
function TCollectionSampleAddAction.Execute(
ABaseObject: TIDObject): boolean;
begin
Result := inherited Execute(nil);
end;
{ TCollectionSampleEditAction }
constructor TCollectionSampleEditAction.Create(AOwner: TComponent);
begin
inherited;
CanUndo := false;
Caption := 'Редактировать образец коллекции';
end;
function TCollectionSampleEditAction.Execute(
ABaseObject: TIDObject): boolean;
begin
if not Assigned(frmSampleEditForm) then frmSampleEditForm := TfrmSampleEditForm.Create(Self);
Result := true;
frmSampleEditForm.Clear;
frmSampleEditForm.EditingObject := ABaseObject;
if frmSampleEditForm.ShowModal = mrOK then
begin
frmSampleEditForm.Save;
// это у нас такая транзакционность - самый простой случай
try
ABaseObject := (frmCollectionEditForm.dlg.Frames[0] as TfrmCommonFrame).EditingObject;
ABaseObject.Update;
except
on E: Exception do
begin
if Assigned(LastObjectCopy) then ABaseObject.Assign(LastObjectCopy)
else FreeAndNil(ABaseObject);
raise EObjectAddingException.Create(ABaseObject, E);
end;
end;
end;
end;
end.
|
unit ShBrowseU;
{wrapper for ShBrowseForFolder}
{*D 22/01/2004}
interface
uses
Windows, Messages, SysUtils
{,Classes, Graphics, Controls, Forms}, Dialogs{, StdCtrls}, ShlObj ;
type
TFolderCheck = function(Sender : TObject; Folder : string) : boolean of object;
TShBrowseOption = (sboBrowseForComputer, sboBrowseForPrinter,
sboBrowseIncludeFiles, sboBrowseIncludeURLs,
sboDontGoBelowDomain, sboEditBox, sboNewDialogStyle,
sboNoNewFolderButton, sboReturnFSAncestors,
sboReturnOnlyFSDirs, sboShareable, sboStatusText,
sboUAHint, sboUseNewUI, sboValidate);
TShBrowseOptions = set of TShBrowseOption;
TShBrowse = class(TObject)
private
FBrowseWinHnd : THandle;
FCaption : string;
FFolder : string;
FFolderCheck : TFolderCheck;
FInitFolder : string;
FLeft : integer;
FOptions : TShBrowseOptions;
FSelIconIndex : integer;
FTop : integer;
FUserMessage : string;
WinFlags : DWord;
procedure Callback(Handle : THandle; MsgId : integer; lParam : DWord);
function GetUNCFolder : string;
function IdFromPIdL(PtrIdL : PItemIdList; FreeMem : boolean) : string;
procedure SetOptions(AValue : TShBrowseOptions);
protected
property BrowseWinHnd : THandle read FBrowseWinHnd write FBrowseWinHnd;
public
constructor Create;
function Execute : boolean;
property Caption : string write FCaption;
property Folder : string read FFolder;
property FolderCheck : TFolderCheck write FFolderCheck;
property InitFolder : string write FInitFolder;
property Left : integer write FLeft; // both Left & Top must be > 0 to position widow
property Options : TShBrowseOptions read FOptions write SetOptions;
property SelIconIndex : integer read FSelIconIndex;
property Top : integer write FTop;
property UNCFolder : string read GetUNCFolder;
property UserMessage : string write FUserMessage;
end;
implementation
uses
ActiveX;
const
BIF_RETURNONLYFSDIRS = $00000001;
BIF_DONTGOBELOWDOMAIN = $00000002;
BIF_STATUSTEXT = $00000004;
BIF_RETURNFSANCESTORS = $00000008;
BIF_EDITBOX = $00000010;
BIF_VALIDATE = $00000020;
BIF_NEWDIALOGSTYLE = $00000040;
BIF_USENEWUI = $00000040;
BIF_BROWSEINCLUDEURLS = $00000080;
BIF_NONEWFOLDERBUTTON = 0;
BIF_UAHINT = 0;
BIF_BROWSEFORCOMPUTER = $00001000;
BIF_BROWSEFORPRINTER = $00002000;
BIF_BROWSEINCLUDEFILES = $00004000;
BIF_SHAREABLE = $00008000;
BFFM_VALIDATEFAILED = 3;
ShBrowseOptionArray : array[TShBrowseOption] of DWord =
(BIF_BROWSEFORCOMPUTER, BIF_BROWSEFORPRINTER,
BIF_BROWSEINCLUDEFILES, BIF_BROWSEINCLUDEURLS,
BIF_DONTGOBELOWDOMAIN, BIF_EDITBOX, BIF_NEWDIALOGSTYLE,
BIF_NONEWFOLDERBUTTON, BIF_RETURNFSANCESTORS,
BIF_RETURNONLYFSDIRS, BIF_SHAREABLE, BIF_STATUSTEXT,
BIF_UAHINT, BIF_USENEWUI, BIF_VALIDATE);
function ShBFFCallback(hWnd : THandle; uMsg : integer;
lParam, lpData : DWord) : integer; stdcall;
{connects the ShBFF callback general function to the
Delphi method which handles it}
begin
TShBrowse(lpData).Callback(hWnd, uMsg, lParam); // calls object's method
Result := 0;
end;
constructor TShBrowse.Create;
begin
inherited Create;
Caption := 'Browse for Folder'; // default
UserMessage := 'Select folder'; // default
end;
procedure TShBrowse.Callback(Handle : THandle; MsgId : integer; lParam : DWord);
{Delphi method which handles the ShBFF callback}
var
WorkArea, WindowSize : TRect;
BFFWidth, BFFHeight : integer;
SelOK : boolean;
begin
FBrowseWinHnd := Handle;
case MsgId of
BFFM_INITIALIZED :
begin
if (FLeft = 0) or (FTop = 0) then begin
{centre the browse window on screen}
GetWindowRect(FBrowseWinHnd, WindowSize); // get ShBFF window size
with WindowSize do begin
BFFWidth := Right - Left;
BFFHeight := Bottom - Top;
end;
SystemParametersInfo(SPI_GETWORKAREA, 0, @WorkArea, 0); // get screen size
with WorkArea do begin // calculate ShBFF window position
FLeft := (Right - Left - BFFWidth) div 2;
FTop := (Bottom - Top - BFFHeight) div 2;
end;
end;
{set browse window position}
SetWindowPos(FBrowseWinHnd, HWND_TOP, FLeft, FTop, 0, 0, SWP_NOSIZE);
if (FCaption <> '') then
{set Caption}
SendMessage(FBrowseWinHnd, WM_SETTEXT, 0, integer(PChar(FCaption)));
if (FInitFolder <> '') then
{set initial folder}
SendMessage(FBrowseWinHnd, BFFM_SETSELECTION, integer(LongBool(true)),
integer(PChar(FInitFolder)));
end;
BFFM_SELCHANGED :
begin
if Assigned(FFolderCheck) then
{get folder and check for validity}
if (lParam <> 0) then begin
FFolder := IdFromPIdL(PItemIdList(lParam), false);
{check folder ....}
SelOK := FFolderCheck(Self, FFolder);
{... en/disable OK button}
SendMessage(Handle, BFFM_ENABLEOK, 0, integer(SelOK));
end; {if (lParam <> nil)}
{end; if Assigned(FFolderCheck)}
end;
{ BFFM_IUNKNOWN :;
BFFM_VALIDATEFAILED :; }
end;
end;
procedure TShBrowse.SetOptions(AValue : TShBrowseOptions);
var
I : TShBrowseOption;
begin
if (AValue <> FOptions) then begin
FOptions := AValue;
WinFlags := 0;
for I := Low(TShBrowseOption) to High(TShBrowseOption) do
if I in AValue then
WinFlags := WinFlags or ShBrowseOptionArray[I];
{end; for I := Low(TBrowseOption) to High(TBrowseOption)}
end; {if (AValue <> FOptions)}
end;
function TShBrowse.Execute : boolean;
{called to display the ShBFF window and return the selected folder}
var
BrowseInfo : TBrowseInfo;
IconIndex : integer;
PtrIDL : PItemIdList;
begin
FillChar(BrowseInfo, SizeOf(TBrowseInfo), #0);
IconIndex := 0;
with BrowseInfo do begin
hwndOwner := Self.FBrowseWinHnd;
PIDLRoot := nil;
pszDisplayName := nil;
lpszTitle := PChar(FUserMessage);
ulFlags := WinFlags;
lpfn := @ShBFFCallback;
lParam := integer(Self); // this object's reference
iImage := IconIndex;
end;
CoInitialize(nil);
PtrIDL := ShBrowseForFolder(BrowseInfo);
if PtrIDL = nil then
Result := false
else begin
FSelIconIndex := BrowseInfo.iImage;
FFolder := IdFromPIdL(PtrIDL, true);
Result := true;
end; {if PtrIDL = nil else}
end;
function TShBrowse.IdFromPIdL(PtrIdL : PItemIdList; FreeMem : boolean) : string;
var
AMalloc : IMalloc;
begin
Result := '';
SetLength(Result, MAX_PATH);
SHGetPathFromIDList(PtrIDL, PChar(Result));
Result := trim(Result);
Result := string(PChar(Result));
// When a PIDL is passed via BFFM_SELCHANGED and that selection is OK'ed
// then the PIDL memory is the same as that returned by ShBrowseForFolder.
// This leads to the assumption that ShBFF frees the memory for the PIDL
// passed by BFFM_SELCHANGED if that selection is NOT OK'ed. Hence one
// should free memory ONLY when ShBFF returns, NOT for BFF_SELCHANGED
if FreeMem then begin
{free PIDL memory ...}
ShGetMalloc(AMalloc);
AMalloc.Free(PtrIDL);
end;
end;
function TShBrowse.GetUNCFolder : string;
// sub-proc start = = = = = = = = = = = = = = = =
function GetErrorStr(Error : integer) : string;
begin
Result := 'Unknown Error : ' + IntToStr(Error); // default
case Error of
ERROR_BAD_DEVICE : Result := 'Invalid path';
ERROR_CONNECTION_UNAVAIL : Result := 'No connection';
ERROR_EXTENDED_ERROR : Result := 'Network error';
ERROR_MORE_DATA : Result := 'Buffer too small';
ERROR_NOT_SUPPORTED : Result := 'UNC name not supported';
ERROR_NO_NET_OR_BAD_PATH : Result := 'Unrecognised path';
ERROR_NO_NETWORK : Result := 'Network unavailable';
ERROR_NOT_CONNECTED : Result := 'Not connected';
end;
end;
// sub-proc end = = = = = = = = = = = = = = = = =
var
LenResult, Error : integer;
PtrUNCInfo : PUniversalNameInfo;
begin
{note that both the PChar _and_ the characters it
points to are placed in UNCInfo by WNetGetUniversalName
on return, hence the extra allocation for PtrUNCInfo}
LenResult := 4 + MAX_PATH; // "4 +" for storage for lpUniversalName == @path
SetLength(Result, LenResult);
PtrUNCInfo := AllocMem(LenResult);
Error := WNetGetUniversalName(PChar(FFolder), UNIVERSAL_NAME_INFO_LEVEL,
PtrUNCInfo, LenResult);
if Error = NO_ERROR then begin
Result := string(PtrUNCInfo^.lpUniversalName);
SetLength(Result, Length(Result));
end
else
Result := GetErrorStr(Error);
end;
end.
|
unit NewsgroupsForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
RootProp, ComCtrls, StdCtrls, ExtCtrls, Mask;
type
TformNewsgroups = class(TformRootProp)
tshtGeneral: TTabSheet;
Label1: TLabel;
Bevel1: TBevel;
Label2: TLabel;
editNewsgroupDesc: TEdit;
Label3: TLabel;
Bevel2: TBevel;
Label4: TLabel;
medtHiMsg: TMaskEdit;
cboxSubscribed: TCheckBox;
Image1: TImage;
procedure DetermineProtection(Sender: TObject); override;
procedure SetPropertyCaption(Sender: TObject);
private
protected
procedure WorkDataToComponents; override;
procedure ComponentsToWorkData; override;
function ValidDefinition : Boolean; override;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
uses
FolderList;
{$R *.DFM}
constructor TformNewsgroups.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataClass := TNewsgroupData;
end;
procedure TformNewsgroups.DetermineProtection(Sender: TObject);
begin
{}
end;
procedure TformNewsgroups.SetPropertyCaption(Sender: TObject);
begin
Caption := editNewsgroupDesc.Text + ' Properties';
end;
procedure TformNewsgroups.WorkDataToComponents;
begin
with TNewsgroupData(FWorkData) do begin
editNewsgroupDesc.Text := NewsgroupDesc;
cboxSubscribed.Checked := Subscribed;
medtHiMsg.Text := IntToStr(HiMsg);
end;
SetPropertyCaption(nil);
end;
procedure TformNewsgroups.ComponentsToWorkData;
begin
with TNewsgroupData(FWorkData) do begin
NewsgroupDesc := editNewsgroupDesc.Text;
Subscribed := cboxSubscribed.Checked;
HiMsg := StrToInt(medtHiMsg.Text);
end;
end;
function TformNewsgroups.ValidDefinition : Boolean;
begin
Result := False;
if medtHiMsg.Text = '' then begin
FocusRequiredMsg('Last article retrieved', medtHiMsg);
Exit;
end;
{-Perform clean up}
if editNewsgroupDesc.Text = '' then
editNewsgroupDesc.Text := TNewsgroupData(FWorkData).NewsgroupName;
Result := True;
end;
end.
|
unit uTUsuariosLog;
interface
uses Classes, contnrs, uUsuarioLog;
type
TUsuariosLog = class(TObject)
private
FListaUsuarios: TObjectList;
procedure agregarUsuario(IdUsuario, Nombre, Evento: string);
function existeUsuario(IdUsuario: string): boolean;
function getCantidad: integer;
public
constructor create;
destructor destroy; override;
procedure AgregarEvento(IdUsuario, Nombre, Evento: string);
function Usuario(IdUsuario: string): TUsuarioLog;
function obtenerUsuario(id: integer): TUsuarioLog;
published
property Cantidad: integer read getCantidad;
end;
implementation
{ TUsuariosLog }
procedure TUsuariosLog.AgregarEvento(IdUsuario, Nombre, Evento: string);
begin
if existeUsuario(IdUsuario) then
Usuario(IdUsuario).AgregarEvento(Evento)
else
agregarUsuario(IdUsuario, Nombre, Evento);
end;
procedure TUsuariosLog.agregarUsuario(IdUsuario, Nombre, Evento: string);
var
id: integer;
begin
id := FListaUsuarios.Add(TUsuarioLog.create);
obtenerUsuario(id).IdUsuario := IdUsuario;
obtenerUsuario(id).Nombre := Nombre;
obtenerUsuario(id).AgregarEvento(Evento);
end;
constructor TUsuariosLog.create;
begin
FListaUsuarios := TObjectList.create;
end;
destructor TUsuariosLog.destroy;
begin
FListaUsuarios.Free;
inherited destroy;
end;
function TUsuariosLog.existeUsuario(IdUsuario: string): boolean;
var
i: integer;
begin
Result := false;
for i := 1 to Cantidad do
begin
if obtenerUsuario(i - 1).IdUsuario = IdUsuario then
begin
Result := true;
exit;
end;
end;
end;
function TUsuariosLog.getCantidad: integer;
begin
Result := FListaUsuarios.Count;
end;
function TUsuariosLog.obtenerUsuario(id: integer): TUsuarioLog;
begin
Result := FListaUsuarios.Items[id] as TUsuarioLog;
end;
function TUsuariosLog.Usuario(IdUsuario: string): TUsuarioLog;
var
i: integer;
begin
Result := nil;
for i := 1 to Cantidad do
begin
if obtenerUsuario(i - 1).IdUsuario = IdUsuario then
begin
Result := obtenerUsuario(i - 1);
exit;
end;
end;
end;
end.
|
{$include kode.inc}
unit syn_s2;
{
todo: move most of the controlgroup stuff to kode_plugin?
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
//kode_array,
kode_control,
//kode_filter_decimator,
kode_filter_downsample,
//kode_filter_hiir,
kode_plugin,
kode_types,
syn_s2_const,
syn_s2_editor,
syn_s2_voice,
syn_s2_voicemanager,
syn_s2_env,
syn_s2_lfo,
syn_s2_osc,
syn_s2_osc_phase,
syn_s2_osc_phaseshape,
syn_s2_osc_wave,
syn_s2_osc_waveshape,
syn_s2_osc_filter,
syn_s2_osc_volume,
syn_s2_mix,
syn_s2_master,
syn_s2_master_filter,
syn_s2_master_fx,
syn_s2_master_volume,
syn_s2_config;
//----------------------------------------------------------------------
type
s2_plugin = class(KPlugin)
private
FVoiceManager : s2_voicemanager;
FTextBuf : array[0..31] of PChar;
FTextBuf2 : array[0..31] of PChar;
FControlGroups : KControlGroups;
private
FOSType : LongInt;
FOSAmt : LongInt;
FBendRange : Single;
FDownsampler : KFilter_Downsample;
public
property voicemanager : s2_voicemanager read FVoiceManager;
property controls : KControlGroups read FControlGroups;
public
procedure appendControlGroups;
procedure deleteControlGroups;
public
procedure on_create; override;
procedure on_destroy; override;
procedure on_stateChange(AState:LongWord); override;
procedure on_midiEvent(AOffset:LongWord; AData1,AData2,AData3:Byte); override;
procedure on_parameterChange(AIndex:LongWord; AValue:Single); override;
procedure on_processBlock(AInputs,AOutputs:PPSingle; ASize:LongWord); override;
procedure on_processSample(AInputs,AOutputs:PPSingle); override;
procedure on_postProcess; override;
{$ifdef KODE_GUI}
function on_openEditor(AParent:Pointer) : Pointer; override;
procedure on_closeEditor; override;
procedure on_idleEditor; override;
{$endif}
end;
KPluginClass = s2_plugin;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
_plugin_id,
math,
{$ifdef KODE_GUI}
kode_editor,
kode_widget,
kode_widget_panel,
{$endif}
kode_color,
kode_const,
kode_debug,
kode_flags,
kode_memory,
kode_rect,
kode_string,
kode_utils;
//----------------------------------------------------------------------
//
//----------------------------------------------------------------------
procedure s2_plugin.on_create;
var
i : longint;
begin
// test
//KTrace(['power( 0.5, 3 ) = ',power( 0.5, 3 ),KODE_CR]);
//KTrace(['power( 0.125, 1/3 ) = ',power( 0.125, 1/3 ),KODE_CR]);
//
FName := 'syn_s2';
FAuthor := 'skei.audio';
FProduct := FName;
FVersion := 0;
FUniqueId := KODE_MAGIC + syn_s2_id;
FNumInputs := 2;
FNumOutputs := 2;
KSetFlag(FFlags,kpf_perSample);
KSetFlag(FFlags,kpf_receiveMidi);
KSetFlag(FFlags,kpf_isSynth);
{$ifdef KODE_GUI}
KSetFlag(FFlags,kpf_hasEditor);
FEditor := nil;
FEditorRect.setup(656,583);
{$endif}
FVoiceManager := s2_voicemanager.create(self);
FControlGroups := KControlGroups.create;
FControlGroups.append( s2_osc_ctrl.create('osc 1',self,0) );
FControlGroups.append( s2_osc_ctrl.create('osc 2',self,1) );
FControlGroups.append( s2_osc_ctrl.create('osc 3',self,2) );
FControlGroups.append( s2_mix_ctrl.create('mix', self) );
FControlGroups.append( s2_env_ctrl.create('env 1',self,0) );
FControlGroups.append( s2_env_ctrl.create('env 2',self,1) );
FControlGroups.append( s2_env_ctrl.create('env 3',self,2) );
FControlGroups.append( s2_lfo_ctrl.create('lfo 1',self,0) );
FControlGroups.append( s2_lfo_ctrl.create('lfo 2',self,1) );
FControlGroups.append( s2_lfo_ctrl.create('lfo 3',self,2) );
FControlGroups.append( s2_master_ctrl.create('master',self) );
FControlGroups.append( s2_config_ctrl.create('config',self) );
appendControlGroups;
for i := 0 to S2_NUM_PROGRAMS-1 do appendProgram( createDefaultProgram );
FDownsampler := KFilter_Downsample.create;
FOSType := s2o_none;
FOSAmt := 0;
FBendRange := 2;
FVoiceManager.on_setPitchBendRange(FBendRange);
end;
//----------
procedure s2_plugin.on_destroy;
begin
{$ifndef KODE_NO_AUTODELETE}
deleteControlGroups;
{$endif}
FVoiceManager.destroy;
FControlGroups.destroy;
FDownsampler.destroy;
end;
//----------------------------------------------------------------------
// controls
//----------------------------------------------------------------------
procedure s2_plugin.appendControlGroups;
var
i : longint;
offset : longint;
begin
if FControlGroups._size > 0 then
begin
offset := 0;
for i := 0 to FControlGroups._size-1 do
begin
offset += FControlGroups[i].appendParameters(self,offset);
end;
end;
end;
//----------
procedure s2_plugin.deleteControlGroups;
var
i : LongInt;
cg : KControlGroup;
begin
if FControlGroups._size > 0 then
begin
for i := 0 to FControlGroups._size-1 do FControlGroups[i].destroy;
//begin
// cg := FControlGroups[i];
// cg.destroy;
//end;
end;
end;
//----------------------------------------------------------------------
// events
//----------------------------------------------------------------------
//kps_suspend, kps_resume, kps_bypass, kps_bypassOff;
procedure s2_plugin.on_stateChange(AState:LongWord);
var
os : longint;
begin
case AState of
kps_resume,
kps_sampleRate:
begin
if FOSType = s2o_none then os := 1
else
begin
case FOSAmt of
0: os := 1;
1: os := 2;
2: os := 4;
3: os := 8;
4: os := 16;
end;
end;
FVoiceManager.on_setSampleRate(FSampleRate{*os});
end;
end;
end;
//----------
procedure s2_plugin.on_midiEvent(AOffset:LongWord; AData1,AData2,AData3:Byte);
begin
FVoiceManager.on_midi(AOffset,AData1,AData2,AData3);
end;
//----------
procedure s2_plugin.on_parameterChange(AIndex:LongWord; AValue:Single);
var
group_index : longint;
sub_index : longint;
param_index : longint;
os : single;
begin
param_index := FControlGroups.find(AIndex,group_index,sub_index);
if param_index >= 0 then
begin
if group_index = s2g_config then
begin
case param_index of
0: FOSType := trunc(AValue);
1:
begin
FOSAmt := trunc(AValue);
//if FOSType = s2o_none then os := 1
//else
//begin
//KTrace(['FOSAmt ',FOSAmt,KODE_CR]);
case FOSAmt of
0: os := 1;
1: os := 2;
2: os := 4;
3: os := 8;
4: os := 16;
end;
//end;
//KTrace(['os ',os,KODE_CR]);
FVoiceManager.on_setSampleRate(FSampleRate*os);
end;
2:
begin
FBendRange := AValue;
FVoiceManager.on_setPitchBendRange(FBendRange);
end;
end;
end
else FVoiceManager.on_control(param_index,AValue,group_index,sub_index);
end
end;
//----------------------------------------------------------------------
// process
//----------------------------------------------------------------------
procedure s2_plugin.on_processBlock(AInputs,AOutputs:PPSingle; ASize:LongWord);
begin
FVoiceManager.on_preProcess;
//KTrace(['env1: ',FVoiceManager.getModValue(s2m_env1),KODE_CR]);
end;
//----------
{
hmmmm...
interesting fact..
downsampling..
c[0] := dec5_1.process(d[0],d[1]);
c[1] := dec5_1.process(d[2],d[3]);
c[2] := dec5_1.process(d[4],d[5]);
c[3] := dec5_1.process(d[6],d[7]);
they are separate.. multi-threads, simd?
}
procedure s2_plugin.on_processSample(AInputs,AOutputs:PPSingle);
var
i : longint;
outs : array[0..1] of single;
//mix : single;
a : single;
//b : array[0..1] of single;
//c : array[0..3] of single;
//d : array[0..7] of single;
v : array[0..15] of single;
begin
FVoiceManager.setModValue(s2m_inl,AInputs[0]^);
FVoiceManager.setModValue(s2m_inr,AInputs[1]^);
FVoiceManager.on_process(outs); v[0] := outs[0];
if FOSAmt >= 1 then
begin
FVoiceManager.on_process(outs); v[1] := outs[0];
end;
if FOSAmt >= 2 then
begin
FVoiceManager.on_process(outs); v[2] := outs[0];
FVoiceManager.on_process(outs); v[3] := outs[0];
end;
if FOSAmt >= 3 then
begin
FVoiceManager.on_process(outs); v[4] := outs[0];
FVoiceManager.on_process(outs); v[5] := outs[0];
FVoiceManager.on_process(outs); v[6] := outs[0];
FVoiceManager.on_process(outs); v[7] := outs[0];
end;
if FOSAmt >= 4 then
begin
FVoiceManager.on_process(outs); v[8] := outs[0];
FVoiceManager.on_process(outs); v[9] := outs[0];
FVoiceManager.on_process(outs); v[10] := outs[0];
FVoiceManager.on_process(outs); v[11] := outs[0];
FVoiceManager.on_process(outs); v[12] := outs[0];
FVoiceManager.on_process(outs); v[13] := outs[0];
FVoiceManager.on_process(outs); v[14] := outs[0];
FVoiceManager.on_process(outs); v[15] := outs[0];
end;
FDownsampler.process(FOSAmt,v);
AOutputs[0]^ := v[0];
AOutputs[1]^ := v[0];
(*
s2o_hiir12s:
begin
case FOSAmt of
4:
begin
FVoiceManager.on_process(outs); c[0] := outs[0];
FVoiceManager.on_process(outs); c[1] := outs[0];
FVoiceManager.on_process(outs); c[2] := outs[0];
FVoiceManager.on_process(outs); c[3] := outs[0];
b[0] := hiir12s_1.process(c[0]);
hiir12s_1.process(c[1]);
b[1] := hiir12s_1.process(c[2]);
hiir12s_1.process(c[3]);
a := hiir12s_2.process(b[0]);
hiir12s_2.process(b[1]);
AOutputs[0]^ := a;
AOutputs[1]^ := a;
end;
*)
//------------------------------
// test: up/down-sample 4
//------------------------------
(*
FVoiceManager.on_process(outs);
a := outs[0];
// upsample
// upsample 1 -> 2
b[0] := hiir1.process(a);
b[1] := hiir1.process0;
// upsample 2 -> 4
c[0] := hiir2.process(b[0]);
c[1] := hiir2.process0;
c[2] := hiir2.process(b[1]);
c[3] := hiir2.process0;
// downsample
// downsample 4 -> 2
b[0] := hiir3.process(c[0]);
hiir3.process(c[1]);
b[1] := hiir3.process(c[2]);
hiir3.process(c[3]);
// downsample 2 -> 1
a := hiir4.process(b[0]);
hiir4.process(b[1]);
AOutputs[0]^ := a;
AOutputs[1]^ := a;
*)
end;
//----------
procedure s2_plugin.on_postProcess;
begin
FVoiceManager.on_postProcess;
end;
//----------------------------------------------------------------------
// editor
//----------------------------------------------------------------------
{$ifdef KODE_GUI}
function s2_plugin.on_openEditor(AParent:Pointer) : Pointer;
begin
result := s2_editor.create(self,FEditorRect,AParent);
end;
{$endif}
//----------
{$ifdef KODE_GUI}
procedure s2_plugin.on_closeEditor;
begin
FEditor.hide; // need this?
FEditor.destroy;
FEditor := nil;
end;
{$endif}
//----------
{$ifdef KODE_GUI}
procedure s2_plugin.on_idleEditor;
var
editor : s2_editor;
voice : s2_voice;
num : longint;
begin
editor := FEditor as s2_editor;
voice := FVoiceManager.getCurrentVoice as s2_voice;
if Assigned(voice) then
begin
// update & draw waveforms
editor.waveform1.setBufferSize( voice.getOsc(0).getBufferLength );
editor.waveform2.setBufferSize( voice.getOsc(1).getBufferLength );
editor.waveform3.setBufferSize( voice.getOsc(2).getBufferLength );
editor.waveform1.setBuffer( voice.getOsc(0).getBufferPtr );
editor.waveform2.setBuffer( voice.getOsc(1).getBufferPtr );
editor.waveform3.setBuffer( voice.getOsc(2).getBufferPtr );
editor.do_redraw( editor.waveform1, editor.waveform1._rect );
editor.do_redraw( editor.waveform2, editor.waveform2._rect );
editor.do_redraw( editor.waveform3, editor.waveform3._rect );
end
else
begin
// don't draw waveforms
editor.waveform1.setBuffer( nil );
editor.waveform2.setBuffer( nil );
editor.waveform3.setBuffer( nil );
editor.waveform1.setBufferSize( 0 );
editor.waveform2.setBufferSize( 0 );
editor.waveform3.setBufferSize( 0 );
//editor.do_redraw( editor.waveform1, editor.waveform1._rect );
//editor.do_redraw( editor.waveform2, editor.waveform2._rect );
//editor.do_redraw( editor.waveform3, editor.waveform3._rect );
end;
num := FVoiceManager.getNumProcessed;
KStrcpy(@FTextBuf,'voices: ');
KIntToString(@FTextBuf2,num);
KStrcat(@FTextBuf,@FTextBuf2);
editor.numvoices._text := @FTextBuf;
editor.do_redraw( editor.numvoices, editor.numvoices._rect );
end;
{$endif}
//----------------------------------------------------------------------
end.
|
unit StrConv;
interface
uses SysUtils, Windows;
const
CP_INVALID = DWord(-1);
CP_ANSI = CP_ACP;
CP_OEM = CP_OEMCP;
CP_SHIFTJIS = 932;
function MinStrConvBufSize(SrcCodepage: DWord; Str: String): DWord; overload;
function MinStrConvBufSize(DestCodepage: DWord; Wide: WideString): DWord; overload;
function ToWideString(SrcCodepage: DWord; Str: String; BufSIze: Integer = -1): WideString;
function FromWideString(DestCodepage: DWord; Str: WideString; BufSIze: Integer = -1): String;
function CharsetToID(Str: String): DWord;
function IdToCharset(ID: DWord; GetDescription: Boolean = False): String;
implementation
function MinStrConvBufSize(SrcCodepage: DWord; Str: String): DWord;
begin
Result := MultiByteToWideChar(SrcCodepage, 0, PAnsiChar(Str), -1, NIL, 0)
end;
function MinStrConvBufSize(DestCodepage: DWord; Wide: WideString): DWord;
begin
Result := WideCharToMultiByte(DestCodepage, 0, PWideChar(Wide), -1, NIL, 0, NIL, NIL)
end;
function ToWideString(SrcCodepage: DWord; Str: String; BufSIze: Integer = -1): WideString;
begin
if BufSize = -1 then
BufSize := MinStrConvBufSize(SrcCodepage, Str);
SetLength(Result, BufSIze * 2);
MultiByteToWideChar(SrcCodepage, 0, PAnsiChar(Str), -1, PWideChar(Result), BufSIze);
SetLength(Result, BufSize - 1)
end;
function FromWideString(DestCodepage: DWord; Str: WideString; BufSIze: Integer = -1): String;
begin
if BufSize = -1 then
BufSize := MinStrConvBufSize(DestCodepage, Str);
SetLength(Result, BufSIze);
WideCharToMultiByte(DestCodepage, 0, PWideChar(Str), -1, PAnsiChar(Result), BufSize, NIL, NIL);
SetLength(Result, BufSize - 1)
end;
function CharsetToID(Str: String): DWord;
var
Key: HKEY;
ValueType, BufSize: DWord;
Alias: String[255];
begin
Result := CP_INVALID;
if RegOpenKeyEx(HKEY_CLASSES_ROOT, PChar('MIME\Database\Charset\' + LowerCase(Str)), 0, KEY_QUERY_VALUE, Key) = ERROR_SUCCESS then
try
BufSize := SizeOf(Result);
ValueType := REG_DWORD;
if (RegQueryValueEx(Key, 'InternetEncoding', NIL, @ValueType, @Result, @BufSize) <> ERROR_SUCCESS) or
(BufSize <> SizeOf(Result)) then
begin
BufSize := SizeOf(Alias);
ValueType := REG_SZ;
if RegQueryValueEx(Key, 'AliasForCharset', NIL, @ValueType, @Alias[1], @BufSize) = ERROR_SUCCESS then
Result := CharsetToID(Copy(Alias, 1, BufSIze - 1 {= last #0}));
end;
finally
RegCloseKey(Key);
end;
end;
function IdToCharset(ID: DWord; GetDescription: Boolean = False): String;
var
Key: HKEY;
ValueType, BufSize: DWord;
Field: pchar;
begin
Result := '';
if RegOpenKeyEx(HKEY_CLASSES_ROOT, pchar('MIME\Database\Codepage\' + IntToStr(ID)), 0, KEY_QUERY_VALUE, Key) = ERROR_SUCCESS then
try
SetLength(Result, 4096);
BufSize := SizeOf(Result);
if GetDescription then
Field := 'Description'
else
Field := 'BodyCharset';
ValueType := REG_SZ;
if RegQueryValueEx(Key, Field, NIL, @ValueType, @Result[1], @BufSize) = ERROR_SUCCESS then
SetLength(Result, BufSize - 1)
else
Result := '';
finally
RegCloseKey(Key);
end;
end;
end.
|
{*********************************************************}
{* ALLORDB.PAS 4.06 *}
{*********************************************************}
{* ***** BEGIN LICENSE BLOCK ***** *}
{* Version: MPL 1.1 *}
{* *}
{* The contents of this file are subject to the Mozilla Public License *}
{* Version 1.1 (the "License"); you may not use this file except in *}
{* compliance with the License. You may obtain a copy of the License at *}
{* http://www.mozilla.org/MPL/ *}
{* *}
{* Software distributed under the License is distributed on an "AS IS" basis, *}
{* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *}
{* for the specific language governing rights and limitations under the *}
{* License. *}
{* *}
{* The Original Code is TurboPower Orpheus *}
{* *}
{* The Initial Developer of the Original Code is TurboPower Software *}
{* *}
{* Portions created by TurboPower Software Inc. are Copyright (C)1995-2002 *}
{* TurboPower Software Inc. All Rights Reserved. *}
{* *}
{* Contributor(s): *}
{* *}
{* ***** END LICENSE BLOCK ***** *}
unit AllOrDb;
interface
uses
OvcDbCal,
OvcDbDLb,
OvcDbEd,
OvcDbIdx,
OvcDbIsE,
OvcDbNF,
OvcDbPF,
OvcDbPLb,
OvcDbSF,
OvcDbDat,
OvcDbNum,
OvcDbMDg,
OvcDbFCb,
OvcDbAE,
OvcDbCL,
OvcDbTbl,
OvcDbTim,
OvcDbRpV,
OvcDbClk,
Ovcdbadg,
OvcDbACb,
OvcDbTCb,
OvcDbSEd,
OvcDbSld,
Ovcdbccb,
Ovcdbhll,
O32dbfe;
implementation
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
OpenDialog1: TOpenDialog;
Button2: TButton;
Label1: TLabel;
Label2: TLabel;
procedure Button2Click(Sender: TObject);
private
fNomeArquivo: String;
property NomeArquivo: String read fNomeArquivo write fNomeArquivo;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button2Click(Sender: TObject);
var
ArquivoTexto: TextFile;
Text: String;
TempoInicial, TempoFinal, TempoTotal: TTime;
Linhas: Double;
begin
Label2.Caption := '';
NomeArquivo := '';
if OpenDialog1.Execute then
NomeArquivo := OpenDialog1.FileName;
if not FileExists(NomeArquivo) then
raise Exception.Create('arquivo nao encontrado');
Linhas := 0;
TempoInicial := Now;
AssignFile(ArquivoTexto, NomeArquivo);
try
Reset(ArquivoTexto);
while not Eof(ArquivoTexto) do
begin
ReadLn(ArquivoTexto, Text);
Linhas := Linhas + 1;
end;
TempoFinal := Now;
TempoTotal := TempoFinal - TempoInicial;
ShowMessage(TimeToStr(TempoTotal));
Label2.Caption := FormatFloat('#,###', Linhas);
finally
CloseFile(ArquivoTexto);
end;
end;
end.
|
unit Simnoise;
{ ============================================================
WinCDR - SimNoise.pas -Ion channel noise simulation
(c) J. Dempster, University of Strathclyde 1998
============================================================
29/6/98 Close button disabled during simulation run to avoid
GPF due to closing form while Start button method running
30/1/99 ... Now uses TScopeDisplay and TValidatedEdit custom controls
25/8/99 ... Revised
}
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls,
global, shared, maths, fileio, ValEdit, ScopeDisplay, math, ComCtrls ;
type
TSimNoiseFrm = class(TForm)
GroupBox1: TGroupBox;
bStart: TButton;
bAbort: TButton;
GroupBox4: TGroupBox;
Label2: TLabel;
Label11: TLabel;
IonCurrentGrp: TGroupBox;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
RecCondGrp: TGroupBox;
Label9: TLabel;
Label6: TLabel;
scDisplay: TScopeDisplay;
edBackGroundTime: TValidatedEdit;
edTransientTime: TValidatedEdit;
edSteadyStateTime: TValidatedEdit;
edUnitCurrent: TValidatedEdit;
edNumChannels: TValidatedEdit;
edPOpen: TValidatedEdit;
edTauOPen: TValidatedEdit;
edNoiseRMS: TValidatedEdit;
edLPFilter: TValidatedEdit;
ProgressGrp: TGroupBox;
prProgress: TProgressBar;
procedure bStartClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure bAbortClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormResize(Sender: TObject);
procedure scDisplayCursorChange(Sender: TObject);
private
{ Private declarations }
procedure HeapBuffers( Operation : THeapBufferOp ) ;
public
{ Public declarations }
procedure ChangeDisplayGrid ;
procedure ZoomOut ;
end;
var
SimNoiseFrm: TSimNoiseFrm;
implementation
{$R *.DFM}
uses mdiform ;
const
NumSamplesPerBuffer = 512 ;
ChSim = 0 ;
MaxChannels = 100 ;
type
TChannelState = (Open,Closed) ;
TChannelRecord = record
Time : Single ;
State : TChannelState ;
end ;
TSim = record
BackgroundTime : single ;
TransientTime : single ;
SteadyStateTime : single ;
UnitCurrent : single ;
NumChannels : Integer ;
POpen : single ;
TauOpen : single ;
TauClosed : single ;
NoiseRMS : Single ;
LPFilter : single ;
LPFilterFirstCall : Boolean ;
t : double ;
EndTime : double ;
Channel : Array[0..MaxChannels-1] of TChannelRecord ;
end ;
var
ADC : ^TSmallIntArray ; { Digitised signal buffer }
Sim : TSim ;
BuffersAllocated : boolean ;{ Indicates if memory buffers have been allocated }
procedure TSimNoiseFrm.HeapBuffers( Operation : THeapBufferOp ) ;
{ -----------------------------------------------
Allocate/deallocation dynamic buffers from heap
-----------------------------------------------}
begin
case Operation of
Allocate : begin
if not BuffersAllocated then begin
New(ADC) ;
BuffersAllocated := True ;
end ;
end ;
Deallocate : begin
if BuffersAllocated then begin
Dispose(ADC) ;
BuffersAllocated := False ;
end ;
end ;
end ;
end ;
procedure TSimNoiseFrm.FormShow(Sender: TObject);
{ --------------------------------------
Initialisations when form is displayed
--------------------------------------}
var
ch,i : Integer ;
begin
{ Disable menu option to prevent user starting another instance }
Main.mnSimNoise.Enabled := False ;
{ Create buffers }
HeapBuffers( Allocate ) ;
bStart.Enabled := True ;
bAbort.Enabled := False ;
Channel[ChSim].ADCUnits := 'pA' ;
Channel[ChSim].ADCName := 'Im' ;
Channel[ChSim].ADCZero := 0 ;
Channel[ChSim].InUse := True ;
{ Set up Display }
scDisplay.MaxADCValue := MaxADCValue ;
scDisplay.MinADCValue := MinADCValue ;
scDisplay.DisplayGrid := Settings.DisplayGrid ;
scDisplay.MaxPoints := NumSamplesPerBuffer ;
scDisplay.NumPoints := NumSamplesPerBuffer ;
scDisplay.NumChannels := CdrFH.NumChannels ;
{ Set channel information }
for ch := 0 to CdrFH.NumChannels-1 do begin
scDisplay.ChanUnits[ch] := Channel[Ch].ADCUnits ;
scDisplay.ChanName[ch] := Channel[Ch].ADCName ;
scDisplay.yMin[ch] := Channel[Ch].yMin ;
scDisplay.yMax[ch] := Channel[Ch].yMax ;
if ch = ChSim then scDisplay.ChanVisible[ch] := True
else scDisplay.ChanVisible[ch] := False ;
end ;
scDisplay.xMin := 0 ;
scDisplay.xMax := NumSamplesPerBuffer-1 ;
scDisplay.HorizontalCursors[0] := Channel[ChSim].ADCZero ;
scDisplay.TScale := CdrFH.dt ;
scDisplay.TFormat := ' %.2f s ' ;
{ Clear all channels }
for i := 0 to CdrFH.NumChannels*NumSamplesPerBuffer-1 do ADC^[i] := 0 ;
scDisplay.SetDataBuf( ADC^ ) ;
scDisplay.AddHorizontalCursor(0,clGray) ;
end ;
procedure TSimNoiseFrm.bStartClick(Sender: TObject);
{ -------------------------
Create simulated currents
-------------------------}
var
TBuffer : single ;
Alpha, Beta, p : single ;
NumOpenChannels,iZeroLevel,i,j,iCh : Integer ;
NumBytesToWrite : LongInt ;
Done,FirstTime : Boolean ;
begin
{ Set buttons to be active during simulation run }
bStart.Enabled := False ;
bAbort.Enabled := True ;
{ Get parameters from edit boxes }
Sim.BackgroundTime := edBackgroundTime.Value ;
Sim.TransientTime := edTransientTime.Value ;
Sim.SteadyStateTime := edSteadyStateTime.Value ;
Sim.UnitCurrent := edUnitCurrent.Value ;
Sim.NumChannels := Round(edNumChannels.Value) ;
Sim.POpen := edPOpen.Value ;
Sim.TauOpen := edTauOpen.Value ;
Sim.NoiseRMS := edNoiseRMS.Value ;
Sim.LPFilter := edLPFilter.Value ;
{ Total simulation time }
Sim.EndTime := Sim.BackgroundTime + Sim.TransientTime + Sim.SteadyStateTime ;
{ Set scaling factor if this is an empty file }
if CdrFH.NumSamplesInFile = 0 then begin
cdrFH.NumChannels := 1 ;
Channel[ChSim].ADCCalibrationFactor := 1. ;
Channel[ChSim].ADCScale := Abs(Sim.UnitCurrent*Sim.NumChannels*1.25) / MaxADCValue ;
CdrFH.ADCVoltageRange := Channel[ChSim].ADCCalibrationFactor
* ( Channel[ChSim].ADCScale * (MaxADCValue+1) ) ;
if Sim.UnitCurrent > 0.0 then Channel[ChSim].ADCZero := -1024
else Channel[ChSim].ADCZero := 1024 ;
end ;
Channel[ChSim].ChannelOffset := 0 ;
{ Position data file pointer at end of data in file }
CdrFH.FilePointer := (CdrFH.NumSamplesInFile*2*CdrFH.NumChannels)
+ CdrFH.NumBytesInHeader ;
CdrFH.FilePointer := FileSeek(CdrFH.FileHandle,0,2) ;
{ *** Ion channel simulation loop *** }
Done := False ;
FirstTime := True ;
TBuffer := NumSamplesPerBuffer*CdrFH.dt ;
iZeroLevel := Channel[ChSim].ADCZero ;
prProgress.Position := 0 ;
prProgress.Min := 0 ;
prProgress.Max := Round(Sim.EndTime/TBuffer);
Sim.t := 0.0 ;
while (not Done) do begin
{ Background noise }
j := Channel[ChSim].ChannelOffset ;
for i := 0 to NumSamplesPerBuffer do begin
ADC^[j] := Round( RandG(0.0,Sim.NoiseRMS)
/Channel[ChSim].ADCScale ) + iZeroLevel ;
j := j + CdrFH.NumChannels ;
end ;
{ Ion channel noise }
if Sim.t >= Sim.BackgroundTime then begin
{ Open channel probability for this time point }
p := (1.0 - exp( -(Sim.t - Sim.BackgroundTime)/(Sim.TransientTime*0.25)))
* Sim.POPen ;
{ Calculate channel mean open and closed dwell times }
Alpha := 1.0 / Sim.TauOpen ;
if p > 0.0 then begin
Beta :=(Alpha*p)/(1.0 - p) ;
Sim.TauClosed := 1.0 / Beta ;
end
else Sim.TauClosed := 1E10 ;
if FirstTime then begin
{ Set all channels to closed }
for iCh := 0 to Sim.NumChannels-1 do begin
Sim.Channel[iCh].State := Closed ;
Sim.Channel[iCh].Time := 0.0 ;
Sim.Channel[iCh].Time := -Sim.TauClosed*ln(Random) ;
end ;
FirstTime := False ;
end ;
{ Calculate ionic current for each sample point in buffer }
j := Channel[ChSim].ChannelOffset ;
for i := 0 to NumSamplesPerBuffer do begin
NumOPenChannels := 0 ;
for iCh := 0 to Sim.NumChannels-1 do begin
{ If at end dwell time in current channel state,
flip to other state and obtain a new dwell time }
if Sim.Channel[iCh].Time <= 0.0 then begin
if Sim.Channel[iCh].State = Open then begin
{ Change to closed state }
Sim.Channel[iCh].Time := -Sim.TauClosed*ln(Random) ;
Sim.Channel[iCh].State := Closed ;
end
else begin
{ Change to open state }
Sim.Channel[iCh].Time := -Sim.TauOpen*ln(Random) ;
Sim.Channel[iCh].State := Open ;
end ;
end
else begin
{ Decrement time in this state }
Sim.Channel[iCh].Time := Sim.Channel[iCh].Time - CdrFH.dt ;
end ;
{ If channel is open add it to open count }
if Sim.Channel[iCh].State = Open then Inc(NumOpenChannels) ;
end ;
ADC^[j] := ADC^[j] + Round( (NumOpenChannels*Sim.UnitCurrent) /
Channel[ChSim].ADCScale ) ;
j := j + CdrFH.NumChannels ;
end ;
end ;
{ Save data to file }
NumBytesToWrite := NumSamplesPerBuffer*CdrFH.NumChannels*2 ;
if FileWrite(CdrFH.FileHandle,ADC^,NumBytesToWrite)
<> NumBytesToWrite then
MessageDlg( ' File write file failed',mtWarning, [mbOK], 0 ) ;
CdrFH.NumSamplesInFile := CdrFH.NumSamplesInFile
+ NumSamplesPerBuffer*CdrFH.NumChannels ;
scDisplay.xOffset := Round( Sim.t /CdrFH.dt ) ;
scDisplay.Invalidate ;
Sim.t := Sim.t + TBuffer ;
if Sim.t > Sim.EndTime then Done := True ;
if bStart.Enabled = True then Done := True ;
prProgress.Position := prProgress.Position + 1 ;
Application.ProcessMessages ;
end ;
{ Close form if simulation has not been aborted }
bStart.Enabled := True ;
bAbort.Enabled := False ;
end;
procedure TSimNoiseFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
{ ------------------------
Tidy up when form closed
------------------------}
begin
HeapBuffers( Deallocate ) ;
{ Re-enable item in "Simulation" menu }
Main.mnSimNoise.enabled := true ;
SaveCDRHeader( CdrFH ) ;
Main.UpdateMDIWindows ;
Action := caFree ;
end;
procedure TSimNoiseFrm.bAbortClick(Sender: TObject);
{ ------------------------------------
ABORT button - Aborts simulation run
------------------------------------}
begin
bStart.Enabled := True ;
bAbort.Enabled := False ;
end;
procedure TSimNoiseFrm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
{ Prevent form being closed if a simulation is running (Start button disabled) }
if bStart.Enabled then CanClose := True
else CanClose := False ;
end;
procedure TSimNoiseFrm.FormResize(Sender: TObject);
{ ------------------------------------------------------
Adjust size/position of controls when form is re-sized
------------------------------------------------------ }
begin
IonCurrentGrp.Top := ClientHeight - IonCurrentGrp.Height - 5 ;
RecCondGrp.Top := ClientHeight - RecCondGrp.Height - 5 ;
RecCondGrp.Width := ClientWidth - RecCondGrp.Left - 5 ;
scDisplay.Height := RecCondGrp.Top - scDisplay.Top - 10 ;
scDisplay.Width := ClientWidth - scDisplay.Left - 5 ;
end;
procedure TSimNoiseFrm.scDisplayCursorChange(Sender: TObject);
begin
Channel[ChSim].yMin := scDisplay.YMin[ChSim] ;
Channel[ChSim].yMax := scDisplay.YMax[ChSim] ;
end;
procedure TSimNoiseFrm.ChangeDisplayGrid ;
{ --------------------------------------------
Update grid pattern on oscilloscope display
-------------------------------------------- }
begin
scDisplay.MaxADCValue := MaxADCValue ;
scDisplay.MinADCValue := MinADCValue ;
scDisplay.DisplayGrid := Settings.DisplayGrid ;
scDisplay.Invalidate ;
end ;
procedure TSimNoiseFrm.ZoomOut ;
{ ---------------------------------
Set minimum display magnification
--------------------------------- }
begin
scDisplay.MaxADCValue := MaxADCValue ;
scDisplay.MinADCValue := MinADCValue ;
scDisplay.ZoomOut ;
end ;
initialization
BuffersAllocated := False ;
end.
|
{$include kode.inc}
unit kode_widget_image_slider;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_bitmap,
kode_canvas,
kode_color,
//kode_const,
kode_flags,
//kode_math,
kode_rect,
kode_surface,
kode_widget_value;
type
KWidget_ImageSlider = class(KWidget_Value)
private
FFlexBarLeft : longint;
FFlexBarTop : longint;
FFlexBarRight : longint;
FFlexBarBottom : longint;
FFlexBackLeft : longint;
FFlexBackTop : longint;
FFlexBackRight : longint;
FFlexBackBottom : longint;
protected
FBackBitmap : KBitmap;
FBarBitmap : KBitmap;
FBackSurface : KSurface;
FBarSurface : KSurface;
public
constructor create(ARect:KRect; AValue:Single; ABack:KSurface; ABar:KSurface; AAlignment:LongWord);
constructor create(ARect:KRect; AValue:Single; ABack:KBitmap; ABar:KBitmap; AAlignment:LongWord);
destructor destroy; override;
procedure on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); override;
procedure setBarFlex(l,t,r,b:longint);
procedure setBackFlex(l,t,r,b:longint);
procedure init;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
//kode_const,
//kode_debug,
kode_math,
kode_utils;
//----------
constructor KWidget_ImageSlider.create(ARect:KRect; AValue:Single; ABack:KSurface; ABar:KSurface; AAlignment:LongWord);
begin
inherited create(ARect,AValue,AAlignment);
FName := 'KWidget_ImageSlider';
FBackBitmap := nil;
FBarBitmap := nil;
FBackSurface := ABack;
FBarSurface := ABar;
init;
end;
//----------
constructor KWidget_ImageSlider.create(ARect:KRect; AValue:Single; ABack:KBitmap; ABar:KBitmap; AAlignment:LongWord);
begin
inherited create(ARect,AValue,AAlignment);
FName := 'KWidget_ImageSlider';
FBackBitmap := ABack;
FBarBitmap := ABar;
FBackSurface := KSurface.create(ABack);
FBarSurface := KSurface.create(ABar);
init;
end;
//----------
destructor KWidget_ImageSlider.destroy;
begin
if Assigned(FBackBitmap) then FBackSurface.destroy;
if Assigned(FBarBitmap) then FBarSurface.destroy;
inherited;
end;
//----------
procedure KWidget_ImageSlider.init;
begin
FCursor := kmc_ArrowUpDown;
FFlexBarLeft := 0;
FFlexBarTop := 0;
FFlexBarRight := 0;
FFlexBarBottom := 0;
FFlexBackLeft := 0;
FFlexBackTop := 0;
FFlexBackRight := 0;
FFlexBackBottom := 0;
end;
//----------
procedure KWidget_ImageSlider.on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0);
var
//v : single;
w : longint;
r : KRect;
//nt : PChar; // name
//vt : PChar; // value
begin
//if Assigned(FParameter) then
//begin
// //nt := FParameter.getName;
// //vt := FParameter.getDisplay( FValue )
//end
//else
//begin
// //nt := FName;
// //KFloatToString(FTextBuf,FValue);
// //vt := FTextBuf;
//end;
ACanvas.flexSurface( FRect, FBackSurface, kfm_stretch, FFlexBackLeft,FFlexBackTop,FFlexBackRight,FFlexBackBottom );
w := trunc( FValue * Single(FRect.w) );
if w > 0 then
begin
r := rect( FRect.x, FRect.y, w, FRect.h );
ACanvas.flexSurface( r, FBarSurface, kfm_stretch, FFlexBarLeft,FFlexBarTop,FFlexBarRight,FFlexBarBottom );
end;
end;
//
procedure KWidget_ImageSlider.setBarFlex(l,t,r,b:longint);
begin
FFlexBarLeft := l;
FFlexBarTop := t;
FFlexBarRight := r;
FFlexBarBottom := b;
end;
procedure KWidget_ImageSlider.setBackFlex(l,t,r,b:longint);
begin
FFlexBackLeft := l;
FFlexBackTop := t;
FFlexBackRight := r;
FFlexBackBottom := b;
end;
//----------------------------------------------------------------------
end.
|
unit uInqu;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBase, StdCtrls, Buttons, ComCtrls, ExtCtrls, CtrlsEx, DB, DBGridEh;
type
TfrmInqu = class(TfrmBase)
gbBasic: TGroupBox;
Label2: TLabel;
cbBF: TComboBox;
Label3: TLabel;
edtBV: TEdit;
gbDate: TGroupBox;
Label1: TLabel;
Label4: TLabel;
cbDF: TComboBox;
cbDC: TComboBox;
dpStart: TDateTimePicker;
dpEnd: TDateTimePicker;
Label5: TLabel;
rbOr: TRadioButton;
rbAnd: TRadioButton;
cbBC: TComboBox;
btnReset: TButton;
lblSpace: TLabel;
cbBV: TComboBox;
procedure cbBFChange(Sender: TObject);
procedure cbDFChange(Sender: TObject);
procedure cbDCChange(Sender: TObject);
procedure btnResetClick(Sender: TObject);
private
{ Private declarations }
FDBGrid: TDBGridEh;
function GetWhrStr: string;
function GetFieldNameByCaption(const ACaption: string): string;
protected
//数据操作过程...
procedure InitData; override;
procedure ResetData; override;
public
{ Public declarations }
end;
var
frmInqu: TfrmInqu;
function ShowInqu(ADBGrid: TDBGridEh; out AWhr: string): Boolean;
implementation
uses uGlobal, uData;
{$R *.dfm}
function ShowInqu(ADBGrid: TDBGridEh; out AWhr: string): Boolean;
begin
if not Assigned(frmInqu) then
begin
frmInqu := TfrmInqu.Create(Application.MainForm);
with frmInqu do
begin
HelpHtml := 'inqu.html';
FDBGrid := ADBGrid;
InitData();
end;
end;
//显示
with frmInqu do
begin
Result := ShowModal() = mrOk;
if Result then
begin
AWhr := GetWhrStr();
Log.Write(App.UserID + '进行员工查询操作:' + AWhr);
end;
end;
end;
{ TfrmInqu }
procedure TfrmInqu.InitData;
var
i: Integer;
begin
cbBV.Visible := False;
cbBV.Top := edtBV.Top;
cbBF.Items.Clear;
cbDF.Items.Clear;
cbDF.Items.Append('留空……');
for i := 1 to FDBGrid.Columns.Count - 1 do
if FDBGrid.Columns[i].Field.FieldName <> 'workState' then
begin
//基本备件字段
if FDBGrid.Columns[i].Field.DataType <> ftDateTime then
cbBF.Items.Append(FDBGrid.Columns[i].Title.Caption)
//时间条件字段
else cbDF.Items.Append(FDBGrid.Columns[i].Title.Caption);
end;
cbBF.ItemIndex := 1;
cbBC.ItemIndex := 5;
cbDF.ItemIndex := 0;
cbDF.OnChange(cbDF);
cbDC.ItemIndex := 0;
cbDC.OnChange(cbDC);
//日期初始值
dpStart.Date := Date();
dpEnd.Date := Date();
end;
procedure TfrmInqu.ResetData;
begin
cbBF.ItemIndex := 1;
cbBF.OnChange(cbBF);
cbBC.ItemIndex := 5;
edtBV.Text := '';
rbOr.Checked := True;
cbDF.ItemIndex := 0;
cbDF.OnChange(cbDF);
cbDC.ItemIndex := 0;
cbDC.OnChange(cbDC);
//日期初始值
dpStart.Date := Date();
dpEnd.Date := Date();
edtBV.SetFocus;
end;
function TfrmInqu.GetWhrStr: string;
function GetSign(ACbx: TComboBox): string;
begin
case ACbx.ItemIndex of
0: Result := '>';
1: Result := '>=';
2: Result := '=';
3: Result := '<=';
4: Result := '<';
5:
begin
if ACbx = cbBC then
Result := 'LIKE'
else Result := 'BETWEEN #%s# AND #%s#';
end
end;
end;
var
sFieldName, sValue, sWhr: string;
begin
//基本条件
if (edtBV.Visible and (Trim(edtBV.Text) <> '')) or (cbBV.Visible and (Trim(cbBV.Text) <> '')) then
begin
sFieldName := GetFieldNameByCaption(cbBF.Text);
if edtBV.Visible then
sValue := edtBV.Text
else sValue := cbBV.Text;
if sFieldName = 'age' then
begin
if cbBC.ItemIndex <> cbBC.Items.Count - 1 then
sWhr := sFieldName + ' ' + GetSign(cbBC) + ' ' + sValue
else sWhr := ' (' + sFieldName + ' - ' + sValue + ') <= 2';
end
else
begin
if cbBC.ItemIndex <> cbBC.Items.Count - 1 then
sWhr := sFieldName + ' ' + GetSign(cbBC) + ' ''' + sValue + ''''
else sWhr := sFieldName + ' ' + GetSign(cbBC) + ' ''%' + sValue + '%''';
end;
end;
//逻辑关系
if cbDF.ItemIndex <> 0 then
begin
if sWhr <> '' then
begin
if rbOr.Checked then
sWhr := sWhr + ' OR '
else sWHr := sWhr + ' AND ';
end;
//日期条件
if sWhr <> '' then
begin
if cbDC.ItemIndex <> cbDC.Items.Count - 1 then
sWhr := sWhr + GetFieldNameByCaption(cbDF.Text) + ' ' + GetSign(cbDC) + ' #' + DateToStr(dpStart.Date) + '#'
else sWhr := sWhr + GetFieldNameByCaption(cbDF.Text) + ' ' + Format(GetSign(cbDC), [DateToStr(dpStart.Date), DateToStr(dpEnd.Date)]);
end
else
begin
if cbDC.ItemIndex <> cbDC.Items.Count - 1 then
sWhr := GetFieldNameByCaption(cbDF.Text) + ' ' + GetSign(cbDC) + ' #' + DateToStr(dpStart.Date) + '#'
else sWhr := GetFieldNameByCaption(cbDF.Text) + ' ' + Format(GetSign(cbDC), [DateToStr(dpStart.Date), DateToStr(dpEnd.Date)]);
end;
end;
if sWhr = '' then sWhr := '0 = 0';
Result := sWhr;
end;
function TfrmInqu.GetFieldNameByCaption(const ACaption: string): string;
var
i: Integer;
begin
for i := 0 to FDBGrid.Columns.Count - 1 do
if FDBGrid.Columns[i].Title.Caption = ACaption then
begin
Result := FDBGrid.Columns[i].FieldName;
Break;
end;
end;
procedure TfrmInqu.cbDFChange(Sender: TObject);
begin
cbDC.Enabled := cbDF.ItemIndex <> 0;
dpStart.Enabled := cbDC.Enabled;
dpEnd.Enabled := cbDc.Enabled;
end;
procedure TfrmInqu.cbBFChange(Sender: TObject);
var
sFieldName, sMaxValue: string;
begin
sFieldName := GetFieldNameByCaption(cbBF.Text);
cbBV.Visible := Pos(sFieldName, 'sex,folk,marriage,politics,culture,special,deptName,duty,workKind,technic,bankName') <> 0;
edtBV.Visible := not cbBV.Visible;
if cbBV.Visible then
begin
cbBV.Clear;
if sFieldName = 'deptName' then
FillDept(cbBV)
else if sFieldName = 'sex' then
begin
cbBV.Items.Append('男');
cbBV.Items.Append('女');
end
else FillKind(cbBV, GetKindTypeByFieldName(sFieldName));
//置最多使用的为默认值
//sMaxValue := dmPer.GetFieldValue('SELECT TOP 1 ' + sFieldName + ' FROM [staffs] GROUP BY ' + sFieldName + ' HAVING Count(id)=(SELECT Max(vCount) FROM (SELECT Count(id) AS vCount, ' + sFieldName + ' FROM [staffs] GROUP BY ' + sFieldName + '))', sFieldName);
//两种方法都可以得到想要的结果
if cbBV.Items.Count <> 0 then
begin
sMaxValue := dmPer.GetFieldValue('SELECT TOP 1 ' + sFieldName + ' FROM (SELECT Count(id) AS vCount, ' + sFieldName + ' FROM [staffs] WHERE NOT ' + sFieldName + ' IS NULL GROUP BY ' + sFieldName + ') ORDER BY vCount DESC, ' + sFieldName, sFieldName);
cbBV.ItemIndex := cbBV.Items.IndexOf(sMaxValue);
end;
end;
end;
procedure TfrmInqu.cbDCChange(Sender: TObject);
begin
dpEnd.Visible := cbDC.ItemIndex = cbDC.Items.Count - 1;
lblSpace.Visible := dpEnd.Visible;
if dpEnd.Visible then
dpStart.Width := 105
else dpStart.Width := 219;
end;
procedure TfrmInqu.btnResetClick(Sender: TObject);
begin
ResetData();
end;
end.
|
unit Sqllist;
interface
Uses Outline,SysUtils,StdCtrls,Classes,Buttons,Controls,ExtCtrls,
DB,DBTables,Messages,Graphics,Forms,Grids,Menus,TSQLCls;
Type TSQLListBox=class(TListBox)
private
FDSN:TFileName;
FTable:string;
FID:string;
FInfo:string;
FWhere:string;
fSortFlag:boolean;
fOnItemChange:TNotifyEvent;
protected
procedure WriteDSN(FN:TFileName);
procedure WriteTable(FN:string);
procedure WriteID(FN:string);
procedure WriteInfo(FN:string);
procedure WriteWhere(FN:string);
function ReadItemIndex:integer;
procedure WriteItemIndex(ind:integer);
procedure EvOnClick(Sender:TObject);
public
function GetData:longint;
procedure SetActive(l:longint);
procedure Recalc;
constructor Create(AC:TComponent); override;
published
property DatabaseName:TFileName read FDSN write WriteDSN;
property Table:string read FTable write WriteTable;
property IDField:string read FID write WriteID;
property InfoField:string read FInfo write WriteInfo;
property Where:string read FWhere write WriteWhere;
property ItemIndex:integer read ReadItemIndex write WriteItemIndex;
property NoSort:boolean read fSortFlag write fSortFlag default FALSE;
property OnItemChange:TNotifyEvent read fOnItemChange write fOnItemChange;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('MyOwn',[TSQLListBox])
end;
function TSQLListBox.GetData:longint;
begin
if ItemIndex=-1 then GetData:=0
else
GetData:=Longint(Items.Objects[ItemIndex])
end;
constructor TSQLListBox.Create(AC:TComponent);
begin
inherited Create(AC);
OnClick:=EvOnClick;
Recalc
end;
procedure TSQLListBox.WriteDSN(FN:TFileName);
begin
FDSN:=FN;
Recalc
end;
procedure TSQLListBox.WriteTable(FN:string);
begin
FTable:=FN;
Recalc
end;
procedure TSQLListBox.WriteID(FN:string);
begin
FID:=FN;
Recalc
end;
procedure TSQLListBox.WriteInfo(FN:string);
begin
FInfo:=FN;
Recalc
end;
procedure TSQLListBox.WriteWhere(FN:string);
begin
FWhere:=FN;
Recalc
end;
procedure TSQLListBox.SetActive(l:longint);
var i:longint;
BEGIN
for i:=0 to Items.Count-1 do
if Longint(Items.Objects[i])=l then
begin
ItemIndex:=i;
break
end
end;
procedure TSQLListBox.Recalc;
var q :TQuery;
l,i:longint;
OrderBy:string;
f1,f2:TField;
begin
if (DatabaseName<>'') and (Table<>'') and (IDField<>'') and (InfoField<>'') and
(sql<>NIL) then
begin
Items.Clear;
if not NoSort then
OrderBy:=sql.Keyword(InfoField)
else
OrderBy:='';
q:=sql.Select(Table,sql.Keyword(IDField)+','+sql.Keyword(InfoField),Where,OrderBy);
f1:=q.FieldByName(IDField);
f2:=q.FieldByName(InfoField);
while not q.eof do
begin
i:=f1.AsInteger;
l:=Items.AddObject(f2.AsString,Pointer(i));
q.Next
end;
q.Free
end
end;
procedure TSQLListBox.WriteItemIndex(ind:integer);
var l:integer;
begin
l:=inherited ItemIndex;
inherited ItemIndex:=ind;
if (l<>ind) and Assigned(fOnItemChange) then
OnItemChange(self);
end;
function TSQLListBox.ReadItemIndex:integer;
begin
ReadItemIndex:=inherited ItemIndex;
end;
procedure TSQLListBox.EvOnClick(Sender:TObject);
begin
if Assigned(fOnItemChange) then
OnItemChange(self);
end;
end.
|
unit Views.Interfaces.Observers;
interface
type
IObserverCategoriaEdicao = interface
['{E49ECA91-7D31-4683-ADE6-2C613D861FD1}']
procedure AtualizarCategoria;
end;
ISubjectCategoriaEdicao = interface
['{086DAA9A-75CE-4E1E-85B8-2D831C11069D}']
procedure AdicionarObservador(Observer : IObserverCategoriaEdicao);
procedure RemoverObservador(Observer : IObserverCategoriaEdicao);
procedure RemoverTodosObservadores;
procedure Notificar;
end;
IObserverLancamentoEdicao = interface
['{4D15F73F-8AF9-4476-9F98-DCFC1CC38EAC}']
procedure AtualizarItemLancamento;
end;
ISubjectLancamentoEdicao = interface
['{BA3C15C1-A37E-4449-8C44-809E630A42B8}']
procedure AdicionarObservador(Observer : IObserverLancamentoEdicao);
procedure RemoverObservador(Observer : IObserverLancamentoEdicao);
procedure RemoverTodosObservadores;
procedure Notificar;
end;
IObserverCompromissoEdicao = interface
['{CF5D9749-D3ED-4455-883E-ED39E9FEADA0}']
procedure AtualizarItemCompromisso;
end;
ISubjectCompromissoEdicao = interface
['{9AF5A0DB-3AD5-4E7F-A697-2FCE0AB9C2AD}']
procedure AdicionarObservador(Observer : IObserverCompromissoEdicao);
procedure RemoverObservador(Observer : IObserverCompromissoEdicao);
procedure RemoverTodosObservadores;
procedure Notificar;
end;
implementation
end.
|
unit FluidPoster;
interface
uses PersistentObjects, DBGate, BaseObjects, DB, Fluid;
type
TFluidCharacteristicDataPoster = class(TImplementedDataPoster)
public
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;
TFluidTypeDataPoster = class(TImplementedDataPoster)
public
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, SysUtils;
{ TFluidTypeDataPoster }
constructor TFluidTypeDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_FLUID_TYPE_DICT';
KeyFieldNames := 'FLUID_TYPE_ID';
FieldNames := 'FLUID_TYPE_ID, VCH_FLUID_TYPE_NAME, VCH_FLUID_SHORT_NAME, NUM_BALANCE_FLUID';
AccessoryFieldNames := '';
AutoFillDates := false;
Sort := 'VCH_FLUID_TYPE_NAME';
end;
function TFluidTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TFluidTypeDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TFluidType;
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 TFluidType;
o.ID := ds.FieldByName('FLUID_TYPE_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_FLUID_TYPE_NAME').AsString);
o.ShortName := trim(ds.FieldByName('VCH_FLUID_SHORT_NAME').AsString);
o.BalanceFluid := ds.FieldByName('NUM_BALANCE_FLUID').AsInteger;
ds.Next;
end;
ds.First;
end;
end;
function TFluidTypeDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TFluidType;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TFluidType;
ds.FieldByName('FLUID_TYPE_ID').Value := o.ID;
ds.FieldByName('VCH_FLUID_TYPE_NAME').Value := o.Name;
ds.FieldByName('VCH_FLUID_SHORT_NAME').Value := o.ShortName;
if o.BalanceFluid <> 0 then
ds.FieldByName('NUM_BALANCE_FLUID').AsInteger := o.BalanceFluid;
ds.Post;
o.ID := ds.FieldByName('FLUID_TYPE_ID').Value;
end;
{ TTestIntervalFluidCharacteristicDataPoster }
constructor TFluidCharacteristicDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource, soGetKeyValue];
DataSourceString := 'TBL_FLUID_TYPE_CHARACTERISTICS';
KeyFieldNames := 'FLUID_TYPE_CHARACTERISTICS_ID';
FieldNames := 'FLUID_TYPE_CHARACTERISTICS_ID, VCH_FLUID_TYPE_CHARACT_NAME';
AccessoryFieldNames := '';
AutoFillDates := false;
Sort := 'VCH_FLUID_TYPE_CHARACT_NAME';
end;
function TFluidCharacteristicDataPoster.DeleteFromDB(
AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject,ACollection);
end;
function TFluidCharacteristicDataPoster.GetFromDB(
AFilter: string; AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TIDObject;
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;
o.ID := ds.FieldByName('FLUID_TYPE_CHARACTERISTICS_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_FLUID_TYPE_CHARACT_NAME').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TFluidCharacteristicDataPoster.PostToDB(
AObject: TIDObject; ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TIDObject;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TIDObject;
ds.FieldByName('FLUID_TYPE_CHARACTERISTICS_ID').Value := o.ID;
ds.FieldByName('VCH_FLUID_TYPE_CHARACT_NAME').Value := o.Name;
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('FLUID_TYPE_CHARACTERISTICS_ID').Value;
end;
end.
|
unit Controle.CadastroProduto;
interface
uses
Modelo.Produto, Dao.Produto, Bd.Gerenciador, Controle.Padrao, uTipos;
type
TControleProduto = class(TControlePadrao)
public
Produto: TProduto;
Constructor Create;
Destructor Destroy; override;
function CarregaProduto(ACodigoProduto: string): Boolean;
function ObtemNumeroVago: Integer; override;
function ObtemValorImposto(APrecoCusto, AAliquotaImposto: string): string;
function ObtemSugestaoPrecoDeVenda(APrecoCusto, AMargem, AValorImposto: string): string;
procedure SalvarProduto(AEvento: TEvento);
end;
var
Bd : TBdGerenciador;
ProdutoDao : TProdutoDao;
implementation
uses
System.SysUtils, Classes.Calculos;
{ TControleProduto }
function TControleProduto.CarregaProduto(ACodigoProduto: string): Boolean;
begin
Result := ProdutoDao.RetornaProduto(StrToIntDef(ACodigoProduto, 0), Produto);
end;
constructor TControleProduto.Create;
begin
if not Assigned(Produto) then
Produto := TProduto.Create;
if not Assigned(ProdutoDao) then
ProdutoDao := TProdutoDao.Create;
Bd := TBdGerenciador.ObterInstancia;
end;
destructor TControleProduto.Destroy;
begin
if Assigned(Produto) then
FreeAndNil(Produto);
if Assigned(ProdutoDao) then
FreeAndNil(ProdutoDao);
inherited Destroy;
end;
function TControleProduto.ObtemNumeroVago: Integer;
begin
Result := Bd.RetornaMaxCodigo('Produto', 'Codigo');
end;
function TControleProduto.ObtemSugestaoPrecoDeVenda(APrecoCusto, AMargem,
AValorImposto: string): string;
begin
Result := FormatFloat('0.00',
TCalculo.CalculaSugestaoPrecoDeVenda(
StrToFloatDef(APrecoCusto,0 ),
StrToFloatDef(AValorImposto, 0),
StrToFloatDef(AMargem, 0)
)
);
end;
function TControleProduto.ObtemValorImposto(APrecoCusto,
AAliquotaImposto: string): string;
begin
Result := FormatFloat('0.00',
TCalculo.ObtemValorImposto(StrToFloatDef(APrecoCusto, 0),
StrToFloatDef(AAliquotaImposto, 0))
);
end;
procedure TControleProduto.SalvarProduto(AEvento: TEvento);
begin
case AEvento of
teInclusao: ProdutoDao.Inserir(Produto);
teEdicao: ProdutoDao.Atualizar(Produto);
end;
end;
end.
|
unit usbasp45;
{$mode objfpc}
interface
uses
Classes, Forms, SysUtils, libusb, usbhid, utilfunc;
const
// ISP SCK speed identifiers
USBASP_ISP_SCK_AUTO = 0;
USBASP_ISP_SCK_0_5 = 1; // 500 Hz
USBASP_ISP_SCK_1 = 2; // 1 kHz
USBASP_ISP_SCK_2 = 3; // 2 kHz
USBASP_ISP_SCK_4 = 4; // 4 kHz
USBASP_ISP_SCK_8 = 5; // 8 kHz
USBASP_ISP_SCK_16 = 6; // 16 kHz
USBASP_ISP_SCK_32 = 7; // 32 kHz
USBASP_ISP_SCK_93_75 = 8; // 93.75 kHz
USBASP_ISP_SCK_187_5 = 9; // 187.5 kHz
USBASP_ISP_SCK_375 = 10; // 375 kHz
USBASP_ISP_SCK_750 = 11; // 750 kHz
USBASP_ISP_SCK_1500 = 12; // 1.5 MHz
USBASP_ISP_SCK_3000 = 13; // 3 Mhz
USBASP_ISP_SCK_6000 = 14; // 6 Mhz
USBASP_FUNC_GETCAPABILITIES = 127;
USBASP_FUNC_DISCONNECT = 2;
USBASP_FUNC_TRANSMIT = 3;
USBASP_FUNC_SETISPSCK = 10;
USBASP_FUNC_GPIO_CONFIG = 40;
USBASP_FUNC_GPIO_READ = 41;
USBASP_FUNC_GPIO_WRITE = 42;
USBASP_FUNC_25_CONNECT = 50;
USBASP_FUNC_25_READ = 51;
USBASP_FUNC_25_WRITE = 52;
function UsbAsp45_Busy(devHandle: Pusb_dev_handle): boolean;
function UsbAsp45_isPagePowerOfTwo(devHandle: Pusb_dev_handle): boolean;
function UsbAsp45_Write(devHandle: Pusb_dev_handle; PageAddr: word; buffer: array of byte; bufflen: integer): integer;
function UsbAsp45_Read(devHandle: Pusb_dev_handle; PageAddr: word; var buffer: array of byte; bufflen: integer): integer;
//
function UsbAsp45_ChipErase(devHandle: Pusb_dev_handle): integer;
//Disable Sector protect
function UsbAsp45_DisableSP(devHandle: Pusb_dev_handle): integer;
//
function UsbAsp45_ReadSR(devHandle: Pusb_dev_handle; var sreg: byte): integer;
//read sector lockdown
function UsbAsp45_ReadSectorLockdown(devHandle: Pusb_dev_handle; var buffOut: array of byte): integer;
implementation
uses Main;
//Пока отлипнет ромка
function UsbAsp45_Busy(devHandle: Pusb_dev_handle): boolean;
var
sreg: byte;
begin
Result := True;
sreg := 0;
UsbAsp45_ReadSR(devHandle, sreg);
if IsBitSet(Sreg, 7) then Result := False;
end;
function UsbAsp45_isPagePowerOfTwo(devHandle: Pusb_dev_handle): boolean;
var
sreg: byte;
begin
sreg := 0;
UsbAsp45_ReadSR(devHandle, sreg);
if (sreg and 1) = 1 then Result := True else Result := false;
end;
function UsbAsp45_ChipErase(devHandle: Pusb_dev_handle): integer;
var
buff: array[0..3] of byte;
begin
buff[0]:= $C7;
buff[1]:= $94;
buff[2]:= $80;
buff[3]:= $9A;
result := USBSendControlMessage(devHandle, PC2USB, USBASP_FUNC_25_WRITE, 1, 0, 4, buff);
end;
function UsbAsp45_DisableSP(devHandle: Pusb_dev_handle): integer;
var
buff: array[0..3] of byte;
begin
Buff[0] := $3D;
Buff[1] := $2A;
Buff[2] := $7F;
Buff[2] := $9A;
result := USBSendControlMessage(devHandle, PC2USB, USBASP_FUNC_25_WRITE, 1, 0, 4, buff);
end;
function UsbAsp45_ReadSectorLockdown(devHandle: Pusb_dev_handle; var buffOut: array of byte): integer;
var
buff: array[0..3] of byte;
begin
Buff[0] := $35;
Buff[1] := $00;
Buff[2] := $00;
Buff[3] := $00;
USBSendControlMessage(devHandle, PC2USB, USBASP_FUNC_25_WRITE, 0, 0, 4, buff);
result := USBSendControlMessage(devHandle, USB2PC, USBASP_FUNC_25_READ, 1, 0, 32, buffOut);
end;
function UsbAsp45_ReadSR(devHandle: Pusb_dev_handle; var sreg: byte): integer;
begin
sreg := $D7; //57H Legacy
USBSendControlMessage(devHandle, PC2USB, USBASP_FUNC_25_WRITE, 0, 0, 1, sreg);
result := USBSendControlMessage(devHandle, USB2PC, USBASP_FUNC_25_READ, 1, 0, 1, sreg);
end;
//Возвращает сколько байт записали
function UsbAsp45_Write(devHandle: Pusb_dev_handle; PageAddr: word; buffer: array of byte; bufflen: integer): integer;
var
buff: array[0..3] of byte;
begin
// rrrraaaa aaaaaaap pppppppp
//r - reserved
//a - page address
//p - buffer address
//Опкод
buff[0] := $82;
//В зависимости от размера страницы(не меньше 8 бит), адрес страницы будет занимать
//столько-то старших бит
PageAddr := ( PageAddr shl (BitNum(bufflen)-8) );
buff[1] := hi(PageAddr);
buff[2] := lo(PageAddr);
buff[3] := 0;
USBSendControlMessage(devHandle, PC2USB, USBASP_FUNC_25_WRITE, 0, 0, 4, buff);
result := USBSendControlMessage(devHandle, PC2USB, USBASP_FUNC_25_WRITE, 1, 0, bufflen, buffer);
end;
function UsbAsp45_Read(devHandle: Pusb_dev_handle; PageAddr: word; var buffer: array of byte; bufflen: integer): integer;
begin
//Опкод
buffer[0] := $E8;
//В зависимости от размера страницы(не меньше 8 бит), адрес страницы будет занимать
//столько-то старших бит
PageAddr := ( PageAddr shl (BitNum(bufflen)-8) );
buffer[1] := hi(PageAddr);
buffer[2] := lo(PageAddr);
buffer[3] := 0;
USBSendControlMessage(devHandle, PC2USB, USBASP_FUNC_25_WRITE, 0, 0, 8, buffer);
result := USBSendControlMessage(devHandle, USB2PC, USBASP_FUNC_25_READ, 1, 0, bufflen, buffer);
end;
end.
|
{
ID: ndchiph1
PROG: humble
LANG: PASCAL
}
uses math;
const
maxN = 100010;
maxK = 110;
//type
var
fi,fo: text;
n,k: longint;
cur,p: array[0..maxK] of longint;
h: array[0..maxN] of longint;
procedure input;
var i,j,t: longint;
begin
readln(fi,k,n);
for i:= 1 to k do read(fi,p[i]);
for i:= 1 to k-1 do
for j:= i+1 to k do
if (p[i] > p[j]) then
begin
t:= p[i];
p[i]:= p[j];
p[j]:= t;
end;
end;
procedure process;
var i,j,t,tmp,min: longint;
begin
h[0]:= 1;
for i:= 1 to k do cur[i]:= 0;
t:= 1;
while (t <= n) do
begin
min:= maxlongint;
for i:= 1 to k do
begin
tmp:= h[cur[i]] * p[i];
if (tmp < min) then min:= tmp;
end;
for i:= 1 to k do
if (h[cur[i]] * p[i] = min) then inc(cur[i]);
h[t]:= min;
inc(t);
end;
writeln(fo,h[n]);
end;
begin
assign(fi,'humble.in'); reset(fi);
assign(fo,'humble.out'); rewrite(fo);
//
input;
process;
//
close(fi);
close(fo);
end.
|
unit uClassCalculadora;
interface
uses
System.SysUtils;
type
//Nome da classe
TCalculadora = class
private
//Variáveis que irão armazenar os valores das propriedades
FNumero1: Currency;
FNumero2: Currency;
//Procedimentos e funções responsáveis por armazenar e
//buscar os dados para a propriedade
function GetNumero1: String;
procedure SetNumero1(ANumero1: String);
function GetNumero2: String;
procedure SetNumero2(ANumero2: String);
//Procedimento que verifica se foi enviado um numero válido
procedure EhNumero(AValor: String);
public
property Numero1: String read GetNumero1 write SetNumero1;
property Numero2: String read GetNumero2 write SetNumero2;
//Função que retorna o valor para a calculadora
function Resultado(sOperacao: String): String;
end;
implementation
{ TCalculadora }
procedure TCalculadora.EhNumero(AValor: String);
begin
try
StrToCurr(AValor);
except
//Cria uma excessão que irá retornar para a aplicação principal
raise Exception.Create('Valor informado não é um número válido.');
end;
end;
function TCalculadora.GetNumero1: String;
begin
Result := CurrToStr(FNumero1);
end;
function TCalculadora.GetNumero2: String;
begin
Result := CurrToStr(FNumero2);
end;
function TCalculadora.Resultado(sOperacao: String): String;
begin
if sOperacao = 'Adicao' then
Result := CurrToStr(FNumero1 + FNumero2)
else
if sOperacao = 'Subtracao' then
Result := CurrToStr(FNumero1 - FNumero2)
else
if sOperacao = 'Multiplicacao' then
Result := CurrToStr(FNumero1 * FNumero2)
else
if sOperacao = 'Divisao' then
Result := CurrToStr(FNumero1 / FNumero2);
end;
procedure TCalculadora.SetNumero1(ANumero1: String);
begin
EhNumero(ANumero1);
FNumero1 := StrToCurr(ANumero1);
end;
procedure TCalculadora.SetNumero2(ANumero2: String);
begin
EhNumero(ANumero2);
FNumero2 := StrToCurr(ANumero2);
end;
end.
|
// GLCollision
{: Egg<p>
Collision-detection management for GLScene<p>
<b>Historique : </b><font size=-1><ul>
<li>22/02/01 - Egg - Included new collision code by Uwe Raabe
<li>08/08/00 - Egg - Fixed TGLBCollision.Assign
<li>16/07/00 - Egg - Added support for all bounding modes (most are un-tested)
<li>23/05/00 - Egg - Creation
</ul></font>
}
unit GLCollision;
interface
uses Classes, GLScene, XCollection, Geometry;
type
TGLBCollision = class;
TObjectCollisionEvent = procedure (Sender : TObject; object1, object2 : TGLBaseSceneObject) of object;
// TCollisionBoundingMode
//
{: Defines how fine collision bounding is for a particular object.<p>
Possible values are :<ul>
<li>cbmPoint : the object is punctual and may only collide with volumes
<li>cbmSphere : the object is defined by its bounding sphere (sphere radius
is the max of axis-aligned dimensions)
<li>cbmEllipsoid the object is defined by its bounding axis-aligned ellipsoid
<li>cbmCube : the object is defined by a bounding axis-aligned "cube"
<li>cbmFaces : the object is defined by its faces (needs object-level support,
if unavalaible, uses cbmCube code)
</ul> }
TCollisionBoundingMode = (cbmPoint, cbmSphere, cbmEllipsoid, cbmCube, cbmFaces);
TFastCollisionChecker = function (obj1, obj2 : TGLBaseSceneObject) : Boolean;
PFastCollisionChecker = ^TFastCollisionChecker;
// TCollisionManager
//
TCollisionManager = class (TComponent)
private
{ Private Declarations }
FClients : TList;
FOnCollision : TObjectCollisionEvent;
protected
{ Protected Declarations }
procedure RegisterClient(aClient : TGLBCollision);
procedure DeRegisterClient(aClient : TGLBCollision);
procedure DeRegisterAllClients;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CheckCollisions;
published
{ Published Declarations }
property OnCollision : TObjectCollisionEvent read FOnCollision write FOnCollision;
end;
// TGLBCollision
//
{: Collision detection behaviour.<p>
Allows an object to register to a TCollisionManager and be accounted for
in collision-detection and distance calculation mechanisms.<p>
An object may have multiple TGLBCollision, registered to multiple collision
managers, however if multiple behaviours share the same manager, only one
of them will be accounted for, others will be ignored. }
TGLBCollision = class (TGLBehaviour)
private
{ Private Declarations }
FBoundingMode : TCollisionBoundingMode;
FManager : TCollisionManager;
FManagerName : String; // NOT persistent, temporarily used for persistence
FGroupIndex : Integer;
protected
{ Protected Declarations }
procedure SetGroupIndex(const value : Integer);
procedure SetManager(const val : TCollisionManager);
procedure WriteToFiler(writer : TWriter); override;
procedure ReadFromFiler(reader : TReader); override;
procedure Loaded; override;
public
{ Public Declarations }
constructor Create(aOwner : TXCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function FriendlyName : String; override;
class function FriendlyDescription : String; override;
published
{ Published Declarations }
{: Refers the collision manager. }
property Manager : TCollisionManager read FManager write SetManager;
property BoundingMode : TCollisionBoundingMode read FBoundingMode write FBoundingMode;
property GroupIndex : Integer read FGroupIndex write SetGroupIndex;
end;
function FastCheckPointVsPoint(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckPointVsSphere(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckPointVsEllipsoid(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckPointVsCube(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckSphereVsPoint(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckSphereVsSphere(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckSphereVsEllipsoid(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckSphereVsCube(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckEllipsoidVsPoint(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckEllipsoidVsSphere(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckEllipsoidVsEllipsoid(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckEllipsoidVsCube(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckCubeVsPoint(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckCubeVsSphere(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckCubeVsEllipsoid(obj1, obj2 : TGLBaseSceneObject) : Boolean;
function FastCheckCubeVsCube(obj1, obj2 : TGLBaseSceneObject) : Boolean;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils, GLMisc;
const
cEpsilon : Single = 1e-6;
const
cFastCollisionChecker : array [cbmPoint..cbmFaces, cbmPoint..cbmFaces] of TFastCollisionChecker = (
(FastCheckPointVsPoint, FastCheckPointVsSphere, FastCheckPointVsEllipsoid, FastCheckPointVsCube, FastCheckPointVsCube),
(FastCheckSphereVsPoint, FastCheckSphereVsSphere, FastCheckSphereVsEllipsoid, FastCheckSphereVsCube, FastCheckSphereVsCube),
(FastCheckEllipsoidVsPoint, FastCheckEllipsoidVsSphere, FastCheckEllipsoidVsEllipsoid, FastCheckEllipsoidVsCube, FastCheckEllipsoidVsCube),
(FastCheckCubeVsPoint, FastCheckCubeVsSphere, FastCheckCubeVsEllipsoid, FastCheckCubeVsCube, FastCheckCubeVsCube),
(FastCheckCubeVsPoint, FastCheckCubeVsSphere, FastCheckCubeVsEllipsoid, FastCheckCubeVsCube, FastCheckCubeVsCube)
);
// Collision utility routines
// Fast Collision detection routines
// by "fast" I mean they are heavily specialized and just return a boolean
function FastCheckPointVsPoint(obj1, obj2 : TGLBaseSceneObject) : Boolean;
begin
Result:=(obj2.SqrDistanceTo(obj1.AbsolutePosition)<=cEpsilon);
end;
function FastCheckPointVsSphere(obj1, obj2 : TGLBaseSceneObject) : Boolean;
begin
Result:=(obj2.SqrDistanceTo(obj1.AbsolutePosition)<=Sqr(obj2.BoundingSphereRadius));
end;
function FastCheckPointVsEllipsoid(obj1, obj2 : TGLBaseSceneObject) : Boolean;
var
v : TVector;
begin
// calc vector expressed in local coordinates (for obj2)
v:=VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// rescale to unit dimensions
DivideVector(v, obj2.AxisAlignedDimensions);
v[3]:=0;
// if norm is below 1, collision
Result:=(VectorNorm(v)<=1);
end;
function FastCheckPointVsCube(obj1, obj2 : TGLBaseSceneObject) : Boolean;
var
v : TVector;
begin
// calc vector expressed in local coordinates (for obj2)
v:=VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// rescale to unit dimensions
DivideVector(v, obj2.AxisAlignedDimensions);
// if abs() of all components are below 1, collision
Result:=(MaxAbsXYZComponent(v)<=1);
end;
function FastCheckSphereVsPoint(obj1, obj2 : TGLBaseSceneObject) : Boolean;
begin
Result:=(obj1.SqrDistanceTo(obj2.AbsolutePosition)<=Sqr(obj1.BoundingSphereRadius));
end;
function FastCheckSphereVsSphere(obj1, obj2 : TGLBaseSceneObject) : Boolean;
begin
Result:=(obj1.SqrDistanceTo(obj2.AbsolutePosition)
<= Sqr(obj1.BoundingSphereRadius+obj2.BoundingSphereRadius));
end;
function FastCheckSphereVsEllipsoid(obj1, obj2 : TGLBaseSceneObject) : Boolean;
var
v : TVector;
aad : TVector;
begin
// express in local coordinates (for obj2)
v:=VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// calc local vector, and rescale to unit dimensions
//VectorSubstract(pt1, obj2.AbsolutePosition, v);
aad:=VectorAdd(obj2.AxisAlignedDimensions, obj1.BoundingSphereRadius);
DivideVector(v, aad);
v[3]:=0;
// if norm is below 1, collision
Result:=(VectorNorm(v)<=1);
end;
function FastCheckSphereVsCube(obj1, obj2 : TGLBaseSceneObject) : Boolean;
var
v : TVector;
aad : TVector;
r,r2 : Single;
begin
// express in local coordinates (for cube "obj2")
// v gives the vector from obj2 to obj1 expressed in obj2's local system
v := VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// because of symmetry we can make abs(v)
v[0] := abs(v[0]);
v[1] := abs(v[1]);
v[2] := abs(v[2]);
aad := obj2.AxisAlignedDimensions; // should be abs at all!
VectorSubtract(v, aad, v); // v holds the distance in each axis
v[3] := 0;
r := obj1.BoundingSphereRadius;
r2 := Sqr(r);
if (v[0]>0) then begin
if (v[1]>0) then begin
if (v[2]>0) then begin
// v is outside axis parallel projection, so use distance to edge point
result := (VectorNorm(v)<=r2);
end else begin
// v is inside z axis projection, but outside x-y projection
result := (VectorNorm(v[0],v[1])<=r2);
end
end else begin
if (v[2]>0) then begin
// v is inside y axis projection, but outside x-z projection
result := (VectorNorm(v[0],v[2])<=r2);
end else begin
// v is inside y-z axis projection, but outside x projection
result := (v[0]<=r);
end
end
end else begin
if (v[1]>0) then begin
if (v[2]>0) then begin
// v is inside x axis projection, but outside y-z projection
result := (VectorNorm(v[1],v[2])<=r2);
end else begin
// v is inside x-z projection, but outside y projection
result := (v[1]<=r);
end
end else begin
if (v[2]>0) then begin
// v is inside x-y axis projection, but outside z projection
result := (v[2]<=r);
end else begin
// v is inside all axes parallel projection, so it is inside cube
result := true;
end;
end
end;
end;
function FastCheckEllipsoidVsPoint(obj1, obj2 : TGLBaseSceneObject) : Boolean;
begin
Result:=FastCheckPointVsEllipsoid(obj2, obj1);
end;
function FastCheckEllipsoidVsSphere(obj1, obj2 : TGLBaseSceneObject) : Boolean;
begin
Result:=FastCheckSphereVsEllipsoid(obj2, obj1);
end;
function FastCheckEllipsoidVsEllipsoid(obj1, obj2 : TGLBaseSceneObject) : Boolean;
var
v1, v2 : TVector;
begin
// express in local coordinates (for obj2)
v1:=VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// calc local vector, and rescale to unit dimensions
//VectorSubstract(pt, obj2.AbsolutePosition, v1);
DivideVector(v1, obj2.AxisAlignedDimensions);
v1[3]:=0;
// express in local coordinates (for obj1)
v2:=VectorTransform(obj2.AbsolutePosition, obj1.InvAbsoluteMatrix);
// calc local vector, and rescale to unit dimensions
//VectorSubstract(pt, obj1.AbsolutePosition, v2);
DivideVector(v2, obj1.AxisAlignedDimensions);
v2[3]:=0;
// if sum of norms is below 2, collision
Result:=(VectorNorm(v1)+VectorNorm(v2)<=2);
end;
function FastCheckEllipsoidVsCube(obj1, obj2 : TGLBaseSceneObject) : Boolean;
{ current implementation assumes Ellipsoid as Sphere }
var
v : TVector;
aad : TVector;
begin
// express in local coordinates (for obj2)
v:=VectorTransform(obj1.AbsolutePosition, obj2.InvAbsoluteMatrix);
// calc local vector, and rescale to unit dimensions
aad:=VectorAdd(obj2.AxisAlignedDimensions, obj1.BoundingSphereRadius);
DivideVector(v, aad);
v[3]:=0;
// if norm is below 1, collision
Result:=(VectorNorm(v)<=1);
end;
function FastCheckCubeVsPoint(obj1, obj2 : TGLBaseSceneObject) : Boolean;
begin
Result:=FastCheckPointVsCube(obj2, obj1);
end;
function FastCheckCubeVsSphere(obj1, obj2 : TGLBaseSceneObject) : Boolean;
begin
Result:=FastCheckSphereVsCube(obj2, obj1);
end;
function FastCheckCubeVsEllipsoid(obj1, obj2 : TGLBaseSceneObject) : Boolean;
begin
Result:=FastCheckEllipsoidVsCube(obj2, obj1);
end;
procedure InitArray(v:TVector; var pt:array of TVector);
// calculate the cube edge points from the axis aligned dimension
begin
pt[0] := VectorMake(-v[0],-v[1],-v[2],1);
pt[1] := VectorMake( v[0],-v[1],-v[2],1);
pt[2] := VectorMake( v[0], v[1],-v[2],1);
pt[3] := VectorMake(-v[0], v[1],-v[2],1);
pt[4] := VectorMake(-v[0],-v[1], v[2],1);
pt[5] := VectorMake( v[0],-v[1], v[2],1);
pt[6] := VectorMake( v[0], v[1], v[2],1);
pt[7] := VectorMake(-v[0], v[1], v[2],1);
end;
function DoCubesIntersectPrim(obj1, obj2 : TGLBaseSceneObject) : Boolean;
// first check if any edge point of "cube" obj1 lies within "cube" obj2
// else, for each "wire" in then wireframe of the "cube" obj1, check if it
// intersects with one of the "planes" of "cube" obj2
function CheckWire(p0,p1,pl:TVector):Boolean;
// check "wire" line (p0,p1) for intersection with each plane, given from
// axis aligned dimensions pl
// - calculate "direction" d: p0 -> p1
// - for each axis (0..2) do
// - calculate line parameter t of intersection with plane pl[I]
// - if not in range [0..1] (= not within p0->p1), no intersection
// - else
// - calculate intersection point s = p0 + t*d
// - for both other axes check if coordinates are within range
// - do the same for opposite plane -pl[I]
var
t : Single;
d,s : TVector;
i,j,k : Integer;
begin
result := true;
VectorSubtract(p1, p0, d); // d: direction p0 -> p1
for i:=0 to 2 do begin
if d[i]=0 then begin // wire is parallel to plane
// this case will be handled by the other planes
end else begin
j := (i+1) mod 3;
k := (j+1) mod 3;
t := (pl[i]-p0[i])/d[i]; // t: line parameter of intersection
if IsInRange(t, 0, 1) then begin
s := p0;
CombineVector(s,d,t); // calculate intersection
// if the other two coordinates lie within the ranges, collision
if IsInRange(s[j],-pl[j],pl[j]) and IsInRange(s[k],-pl[k],pl[k]) then Exit;
end;
t := (-pl[i]-p0[i])/d[i]; // t: parameter of intersection
if IsInRange(t,0,1) then begin
s := p0;
CombineVector(s,d,t); // calculate intersection
// if the other two coordinates lie within the ranges, collision
if IsInRange(s[j],-pl[j],pl[j]) and IsInRange(s[k],-pl[k],pl[k]) then Exit;
end;
end;
end;
result := false;
end;
const
cWires : array[0..11,0..1] of Integer
= ((0,1),(1,2),(2,3),(3,0),
(4,5),(5,6),(6,7),(7,4),
(0,4),(1,5),(2,6),(3,7));
var
pt1 : array[0..7] of TVector;
M : TMatrix;
I : Integer;
aad : TVector;
begin
result := true;
aad := obj2.AxisAlignedDimensions;
InitArray(obj1.AxisAlignedDimensions,pt1);
// calculate the matrix to transform obj1 into obj2
MatrixMultiply(obj1.AbsoluteMatrix,obj2.InvAbsoluteMatrix,M);
for I:=0 to 7 do begin // transform points of obj1
pt1[I] := VectorTransform(pt1[I],M);
// check if point lies inside "cube" obj2, collision
if IsInCube(pt1[I],aad) then Exit;
end;
for I:=0 to 11 do begin
if CheckWire(pt1[cWires[I,0]],pt1[cWires[I,1]],aad) then Exit;
end;
result := false;
end;
function FastCheckCubeVsCube(obj1, obj2 : TGLBaseSceneObject) : Boolean;
var
aad1,aad2 : TVector;
D1,D2,D : Double;
begin
aad1 := obj1.AxisAlignedDimensions;
aad2 := obj2.AxisAlignedDimensions;
D1 := VectorLength(aad1);
D2 := VectorLength(aad2);
D := Sqrt(obj1.SqrDistanceTo(obj2.AbsolutePosition));
if D>(D1+D2) then result := false
else begin
D1 := MinAbsXYZComponent(aad1);
D2 := MinAbsXYZComponent(aad2);
if D<(D1+D2) then result := true
else begin
result := DoCubesIntersectPrim(obj1,obj2) or
DoCubesIntersectPrim(obj2,obj1);
end;
end;
end;
// ------------------
// ------------------ TCollisionManager ------------------
// ------------------
// Create
//
constructor TCollisionManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClients:=TList.Create;
RegisterManager(Self);
end;
// Destroy
//
destructor TCollisionManager.Destroy;
begin
DeRegisterAllClients;
DeRegisterManager(Self);
FClients.Free;
inherited Destroy;
end;
// RegisterClient
//
procedure TCollisionManager.RegisterClient(aClient : TGLBCollision);
begin
if Assigned(aClient) then
if FClients.IndexOf(aClient)<0 then begin
FClients.Add(aClient);
aClient.FManager:=Self;
end;
end;
// DeRegisterClient
//
procedure TCollisionManager.DeRegisterClient(aClient : TGLBCollision);
begin
if Assigned(aClient) then begin
aClient.FManager:=nil;
FClients.Remove(aClient);
end;
end;
// DeRegisterAllClients
//
procedure TCollisionManager.DeRegisterAllClients;
var
i : Integer;
begin
// Fast deregistration
for i:=0 to FClients.Count-1 do
TGLBCollision(FClients[i]).FManager:=nil;
FClients.Clear;
end;
// CheckCollisions
//
procedure TCollisionManager.CheckCollisions;
var
obj1, obj2 : TGLBaseSceneObject;
cli1, cli2 : TGLBCollision;
grp1, grp2 : Integer; // GroupIndex of collisions
i, j : Integer;
begin
if not Assigned(FOnCollision) then Exit;
// if you know a code slower than current one, call me ;)
{ TODO : speed improvements & distance cacheing }
for i:=0 to FClients.Count-2 do begin
cli1:=TGLBCollision(FClients[i]);
obj1:=cli1.OwnerBaseSceneObject;
grp1:=cli1.GroupIndex;
for j:=i+1 to FClients.Count-1 do begin
cli2:=TGLBCollision(FClients[j]);
obj2:=cli2.OwnerBaseSceneObject;
grp2:=cli2.GroupIndex;
// if either one GroupIndex=0 or both are different, check for collision
if (grp1=0) or (grp2=0) or (grp1<>grp2) then begin
if cFastCollisionChecker[cli1.BoundingMode, cli2.BoundingMode](obj1, obj2) then
FOnCollision(Self, obj1, obj2);
end;
end;
end;
end;
// ------------------
// ------------------ TGLBCollision ------------------
// ------------------
// Create
//
constructor TGLBCollision.Create(aOwner : TXCollection);
begin
inherited Create(aOwner);
end;
// Destroy
//
destructor TGLBCollision.Destroy;
begin
Manager:=nil;
inherited Destroy;
end;
// FriendlyName
//
class function TGLBCollision.FriendlyName : String;
begin
Result:='Collision';
end;
// FriendlyDescription
//
class function TGLBCollision.FriendlyDescription : String;
begin
Result:='Collision-detection registration';
end;
// WriteToFiler
//
procedure TGLBCollision.WriteToFiler(writer : TWriter);
begin
with writer do begin
WriteInteger(1); // ArchiveVersion 1, added FGroupIndex
if Assigned(FManager) then
WriteString(FManager.GetNamePath)
else WriteString('');
WriteInteger(Integer(BoundingMode));
WriteInteger(FGroupIndex);
end;
end;
// ReadFromFiler
//
procedure TGLBCollision.ReadFromFiler(reader : TReader);
var
archiveVersion : Integer;
begin
with reader do begin
archiveVersion:=ReadInteger;
Assert(archiveVersion in [0..1]);
FManagerName:=ReadString;
BoundingMode:=TCollisionBoundingMode(ReadInteger);
Manager:=nil;
if archiveVersion>=1 then
FGroupIndex:=ReadInteger
else FGroupIndex:=0;
end;
end;
// Loaded
//
procedure TGLBCollision.Loaded;
var
mng : TComponent;
begin
inherited;
if FManagerName<>'' then begin
mng:=FindManager(TCollisionManager, FManagerName);
if Assigned(mng) then
Manager:=TCollisionManager(mng);
FManagerName:='';
end;
end;
// Assign
//
procedure TGLBCollision.Assign(Source: TPersistent);
begin
if Source is TGLBCollision then begin
Manager:=TGLBCollision(Source).Manager;
BoundingMode:=TGLBCollision(Source).BoundingMode;
end;
inherited Assign(Source);
end;
// SetManager
//
procedure TGLBCollision.SetManager(const val : TCollisionManager);
begin
if val<>FManager then begin
if Assigned(FManager) then
FManager.DeRegisterClient(Self);
if Assigned(val) then
val.RegisterClient(Self);
end;
end;
// SetGroupIndex
//
procedure TGLBCollision.SetGroupIndex(const value : Integer);
begin
FGroupIndex:=value;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterXCollectionItemClass(TGLBCollision);
end.
|
(**
* $Id: dco.rpc.Identifier.pas 840 2014-05-24 06:04:58Z QXu $
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the License for the specific language governing rights and limitations under the License.
*)
unit dco.rpc.Identifier;
interface
uses
superobject { An universal object serialization framework with Json support };
type
/// <summary>This immutable record represents a RPC request identifier.</summary>
TIdentifier = record
private
FValue: ISuperObject;
public
property Value: ISuperObject read FValue;
public
class function NullIdentifier: TIdentifier; static;
class function StringIdentifier(const Value: string): TIdentifier; static;
class function NumberIdentifier(Value: Integer): TIdentifier; static;
/// <exception cref="EArgumentException">Invalid identifier type</exception>
class function FromValue(const Value: ISuperObject): TIdentifier; static;
function ToString: string;
function Valid: Boolean;
function Equals(const Other: TIdentifier): Boolean;
end;
implementation
uses
System.SysUtils;
class function TIdentifier.NullIdentifier: TIdentifier;
begin
Result.FValue := nil;
end;
class function TIdentifier.StringIdentifier(const Value: string): TIdentifier;
begin
Result.FValue := SO(Value);
end;
class function TIdentifier.NumberIdentifier(Value: Integer): TIdentifier;
begin
Result.FValue := SO(Value);
end;
class function TIdentifier.FromValue(const Value: ISuperObject): TIdentifier;
begin
Result.FValue := Value;
if not Result.Valid then
raise EArgumentException.Create('Invalid identifier type');
end;
function TIdentifier.ToString: string;
begin
if FValue = nil then
Result := ''
else
Result := FValue.AsJson;
end;
function TIdentifier.Valid: Boolean;
begin
Result := (FValue = nil) or (FValue.DataType in [TSuperType.stNull, TSuperType.stString, TSuperType.stInt]);
end;
function TIdentifier.Equals(const Other: TIdentifier): Boolean;
begin
Result := Other.ToString = ToString;
end;
end.
|
{Practica de vectores }
{A continuación se desarrolla un programa que utilizando funciones y procedimientos para
cada ítem:
a. Lee un arreglo de enteros
b. Calcula la suma de sus elementos
c. Cuenta la cantidad de componentes pares
d. Imprime las componentes que se encuentran en ubicaciones pares
e. Imprime el mínimo
f. Genera un segundo arreglo con los múltiplos de K (dato entero) y l}
program Vectores_Menu;
uses
crt;
Type
TV = array[1..100] of integer;
var
N, M, K: integer;
A, B: TV;
op: char;
Procedure LeeVector(var A: TV; var N: integer); // lee el arreglo de enteros
var
i: integer; //Variable local
begin
writeln('Ingrese la cantidad de elementos del vector <= 100'); readln(N);
for i:=1 to N do
begin
writeln('Ingrese el elemento'); readln(A[i]);
clrscr();
end;
end;
Function Suma (A: TV; N: integer) : integer; // calcula la suma de sus elementos
var
i, sum : integer;
begin
sum:= 0;
for i:= 1 to N do
sum:= sum + A[i];
Suma:= sum;
end;
Function CuentaPares(A: TV; N: integer) : integer; // cuenta los pares
var
i, cont: integer;
begin
cont:= 0;
for i:= 1 to N do
if not odd(A[i]) then // Si no es impar entonces...
cont:= cont + 1;
CuentaPares:= cont;
end;
Procedure EscPosPares( A: TV; N: integer ); // Imprime las componentes que se encuentran en ubicaciones pares
var
i: integer;
begin
i:= 2;
while i <= N do
begin
writeln(A[i] : 5);
i:= i + 2;
end;
end;
//Imprime el minimo
Function Minimo (A: TV; N: integer) : integer;
var
i, min: integer;
begin
min:= A[1]; // ubico el minimo en la posicion 1
for i:= 2 to N do
if A[i] < min then // si es menor al minimo entonces...
min:= A[i]; // sobreescribo la variable min con el menor encontrado
Minimo:= min;
end;
// genera un segundo arreglo con los multiplos de K (dato entero) y lo escribe
Procedure GeneraOtro (A: TV; N, K: integer; var B: TV; var M: integer);
var
i: integer;
begin
M:= 0;
for i:= 1 to N do
if A[i] mod K = 0 then // si el resto es 0 entonces k es multiplo de i
begin
M:= M + 1;
B[M]:= A[i];
end;
end;
Procedure EscVector (V: TV; L: integer);
var
i: integer;
begin
for i:= 1 to L do
writeln(V[i] : 5 );
end;
// Permite elegir por medio de un menú el/los proceso/s descriptos
Procedure Menu (var op: char);
begin
Writeln('Menu de opciones');
Writeln('b - Suma los elementos del arreglo');
Writeln('c - Cuenta los elementos pares');
Writeln('d - Imprime los elementos de las posiciones pares');
Writeln('e - Calcula el mínimo');
Writeln('f - Genera un arreglo con los elementos múltiplos de K');
Writeln('g - Salir');
Repeat
Writeln(' Ingrese su opcion'); Readln(op);
clrscr();
Until ( 'b' <= Op) and ( Op <= 'g');
end;
// las variables globales estan declaradas al principio
begin
LeeVector(A, N);
writeln(A[1]);
repeat
Menu(op);
case op of
'b': writeln('La suma de los elementos del arreglo es:', Suma(A, N));
'c': writeln('La cantidad de elementos pares del arreglo es:', CuentaPares(A, N));
'd': begin
writeln('Elementos de las posiciones pares del arreglo'); EscPosPares ( A , N );
end;
'e': writeln('El mínimo del arreglo es:', Minimo(A, N));
'f': begin
Write ('Ingrese un valor de K para seleccionar los múltiplos de K'); Readln(K);
GeneraOtro (A , N, K, B, M );
writeln('Elementos de múltiplos de ' , K ); EscVector(B, M);
end;
end; {case}
until op = 'g';
end.
|
{ Module of routines that perform simple pathname manipulation.
}
module string_pathname;
define string_generic_fnam;
define string_pathname_join;
define string_pathname_split;
%include 'string2.ins.pas';
%include 'string_sys.ins.pas';
{
*******************************************************************
*
* Subroutine STRING_GENERIC_FNAM (INNAM, EXTENSIONS, FNAM)
*
* Create the generic file name of a file given its pathname and a list
* of possible extensions. INNAM is the pathname of the file. It can be
* just a leaf name or an arbitrary tree name. EXTENSIONS is a PASCAL
* STRING data type containing a list of possible file name extensions,
* one of which may be on the end of the pathname in INNAM. FNAM is
* returned as the file name from INNAM without the previous directory
* names (if any) and the without the file name extension (if any).
* The first file name extension that matches the end of INNAM is used,
* even if subsequent extensions would also have matched.
}
procedure string_generic_fnam ( {generic leaf name from file name and extensions}
in innam: univ string_var_arg_t; {input file name (may be tree name)}
in extensions: string; {list of extensions separated by blanks}
in out fnam: univ string_var_arg_t); {output file name without extension}
var
lnam: string_leafname_t; {leaf name before extension removed}
unused: string_var4_t; {unused var string call argument}
begin
lnam.max := sizeof(lnam.str); {init local var strings}
unused.max := sizeof(unused.str);
string_pathname_split (innam, unused, lnam); {extract leaf name}
string_fnam_unextend (lnam, extensions, fnam); {remove extension, if present}
end;
{
*******************************************************************
*
* Subroutine STRING_PATHNAME_JOIN (DNAM, LNAM, TNAM)
*
* Make treename from an arbitrary directory name and leaf name.
* DNAM is arbitrary directory name. LNAM is the leaf name.
* TNAM is the output combined tree name.
}
procedure string_pathname_join ( {join directory and leaf name together}
in dnam: univ string_treename_t; {arbitrary directory name}
in lnam: univ string_leafname_t; {leaf name}
out tnam: univ string_treename_t); {joined treename}
var
i: sys_int_machine_t;
begin
string_copy (dnam, tnam); {copy directory name into path name}
string_unpad (tnam); {remove any trailing spaces}
for i := 1 to tnam.len do begin {translate all "/" to "\"}
if tnam.str[i] = '/' then tnam.str[i] := '\';
end;
if not (tnam.str[tnam.len] = '\')
then string_append1 (tnam, '\'); {append slash delimiter}
string_append (tnam, lnam); {append leafname}
end;
{
*******************************************************************
*
* Subroutine STRING_PATHNAME_SPLIT (TNAM, DNAM, LNAM)
*
* Split arbitrary pathname into its directory name and leaf name.
* TNAM is the arbitrary path name. DNAM is the output directory name.
* LNAM is the output leaf name.
*
* When TNAM specifies a directory with no parent, then DNAM will be the
* same directory as TNAM, and LNAM will be "." to indicate the same directory.
}
procedure string_pathname_split ( {make dir. and leaf name from arbitrary path name}
in tnam: univ string_treename_t; {arbitrary path name to split}
out dnam: univ string_treename_t; {directory name}
out lnam: univ string_leafname_t); {leaf name}
var
i: sys_int_machine_t; {loop index}
tl: string_index_t; {virtual TNAM length}
label
next_char;
begin
if tnam.len <= 0 then begin {input pathname is empty ?}
string_vstring (dnam, '..', 2); {pass back directory name}
string_vstring (lnam, '.', 1); {pass back leaf name}
return;
end;
tl := tnam.len; {init to use full TNAM string}
for i := tnam.len downto 1 do begin {look for last separator character}
case tnam.str[i] of {what character is here ?}
{
* Found path down character.
}
'\', '/': begin
if
(i = 1) or {at node root ?}
((i = 2) and ((tnam.str[1] = '\') or (tnam.str[1] = '/'))) {at network root ?}
then begin
string_substr (tnam, 1, i, dnam); {directory is the root directory}
if tl > i
then begin {we were given a directory below the root}
string_substr (tnam, i + 1, tl, lnam); {extract leaf name}
end
else begin {we were given only the root directory}
string_vstring (lnam, '.', 1);
end
;
return;
end;
if i = tl then begin {this is trailing character}
tl := tl - 1; {pretend character isn't there}
goto next_char; {back for next loop character}
end;
string_substr (tnam, 1, i - 1, dnam); {extract directory before separator}
string_substr (tnam, i + 1, tl, lnam); {extract leaf name after separator}
if (i > 1) and then (tnam.str[i - 1] = ':') then begin {actually at drive root ?}
string_append1 (dnam, '\'); {indicate drive root directory}
end;
return;
end;
{
* Found end of drive name.
}
':': begin
string_substr (tnam, 1, i, dnam); {drive name becomes directory name}
string_append1 (dnam, '\'); {indicate drive root directory}
if i = tl
then begin {no path follows drive name}
string_vstring (lnam, '.', 1); {indicate in same directory}
end
else begin {a path follows drive name}
string_substr (tnam, i + 1, tl, lnam); {get path after drive name}
end
;
return;
end;
end; {end of special character cases}
next_char: {jump here to advance to next char in loop}
end; {back to examine previous input string char}
{
* No separator character was found in input pathname. TNAM must be the leafname
* of an object in the current directory.
}
string_substr (tnam, 1, tl, lnam); {leafname is just input pathname}
if (tl = 1) and (tnam.str[1] = '.')
then begin {TNAM is really current directory}
string_vstring (dnam, '..', 2);
end
else begin {TNAM is object within current directory}
string_vstring (dnam, '.', 1);
end
;
end;
|
program TesteSortiereListe(input, output);
type
tNatZahl = 0..maxint;
tRefListe = ^tListe;
tListe = record
info : tNatZahl;
next : tRefListe;
end;
var
RefListe : tRefListe;
procedure SortiereListe (var ioRefListe : tRefListe);
{ sortiert eine lineare Liste aufsteigend }
var
tmp, { Hilfsvariable zum umhängen}
iterZeiger, { zum iterieren durch die Liste}
Zeiger : tRefListe; { das letzte sortierte Element }
Eingefuegt : boolean;
{ Im folgenden heißt "Element" immer das erste Element aus dem unsortieren Listen Teil. }
begin
{ base case - die Leere Liste }
if (ioRefListe <> nil) then
begin
{ init }
Zeiger := ioRefListe;
{ new(tmp); }
while (Zeiger^.next <> nil) do
begin
{ kleinstes Element? -> hänge an den Anfang der Liste}
if(ioRefListe^.info >= Zeiger^.next^.info) then
begin
{ Verweis auf Folgeelement wird zwischengespeichert }
tmp := Zeiger^.next^.next;
{ Element wird an Anfang der Liste gehangen }
Zeiger^.next^.next := ioRefListe;
{ Element wird zum neuen Anfang der Liste }
ioRefListe := Zeiger^.next;
{ Letztes sortiertes Element zeigt nun auf den Nachfolger des Elements bevor es
umgehangenen wurde, d.h. das nächste unsortierte Element. }
Zeiger^.next := tmp;
end
else { nicht kleinstes Element}
begin
{ Element ist das größte? -> hänge ans ende der sortierten Liste}
if (Zeiger^.info <= Zeiger^.next^.info) then
begin
{ easy, Element einfach Vorne belassen und es zum neuen vordersten Zeiger machen. }
Zeiger := Zeiger^.next;
end
else
begin
{ Element ist weder das kleinste noch das größte, jetzt suchen wir nach einer Stelle,
in der sortierten Liste, um es einzuhängen. }
Eingefuegt := false;
iterZeiger := ioRefListe;
while (not Eingefuegt) do
begin
if (iterZeiger^.next^.info >= Zeiger^.next^.info) then
begin
tmp := Zeiger^.next^.next; {Folgeelement zwischenspeichern}
{ Element wird umgehangen }
Zeiger^.next^.next := iterZeiger^.next; {sortierte liste *klick* vorne}
iterZeiger^.next := Zeiger^.next; {sortierte liste *klick* hinten}
{ letztes sortiertes Element zeigt nun auf das nächste unsortierte, das
wir vorher in tmp zwischengespeichert haben. }
Zeiger^.next := tmp;
Eingefuegt := true;
end;
iterZeiger := iterZeiger^.next;
end; {while (not Eingefuegt) }
end;
end;
end; { while (Zeiger^.next <> nil) }
end; { base case - die leere Liste}
end; { SortiereListe }
procedure Anhaengen(var ioListe : tRefListe;
inZahl : tNatZahl);
{ Haengt inZahl an ioListe an }
var Zeiger : tRefListe;
begin
Zeiger := ioListe;
if Zeiger = nil then
begin
new(ioListe);
ioListe^.info := inZahl;
ioListe^.next := nil;
end
else
begin
while Zeiger^.next <> nil do
Zeiger := Zeiger^.next;
{ Jetzt zeigt Zeiger auf das letzte Element }
new(Zeiger^.next);
Zeiger := Zeiger^.next;
Zeiger^.info := inZahl;
Zeiger^.next := nil;
end;
end;
procedure ListeEinlesen(var outListe:tRefListe);
{ liest eine durch Leerzeile abgeschlossene Folge von Integer-
Zahlen ein und speichert diese in der linearen Liste RefListe. }
var
Liste : tRefListe;
Zeile : string;
Zahl, Code : integer;
begin
writeln('Bitte geben Sie die zu sortierenden Zahlen ein.');
writeln('Beenden Sie Ihre Eingabe mit einer Leerzeile.');
Liste := nil;
readln(Zeile);
val(Zeile, Zahl, Code); { val konvertiert String nach Integer }
while Code=0 do
begin
Anhaengen(Liste, Zahl);
readln(Zeile);
val(Zeile, Zahl, Code);
end; { while }
outListe := Liste;
end; { ListeEinlesen }
procedure GibListeAus(inListe : tRefListe);
{ Gibt die Elemente von inListe aus }
var Zeiger : tRefListe;
begin
Zeiger := inListe;
while Zeiger <> nil do
begin
writeln(Zeiger^.info);
Zeiger := Zeiger^.next;
end; { while }
end; { GibListeAus }
begin
ListeEinlesen(RefListe);
SortiereListe(RefListe);
GibListeAus(RefListe)
end. { TesteSortiereListe }
|
unit Casbin.Functions.KeyMatch;
interface
/// <summary>
/// Determines whether key1 matches the pattern of key2
/// (as in REST paths)
/// key2 can contain '*'
/// eg. '/foo/bar' matches '/foo/*'
/// </summary>
function KeyMatch (const aArgs: array of string): Boolean;
implementation
uses
System.SysUtils;
function KeyMatch (const aArgs: array of string): Boolean;
var
key1: string;
key2: string;
index: Integer;
begin
if Length(aArgs)<>2 then
raise Exception.Create('Wrong number of arguments in KeyMatch');
key1:=aArgs[0];
key2:=aArgs[1];
index:=Pos('*', key2);
if index=0 then
Exit(key1 = key2);
if Length(key1) >= index then
Exit(Copy(key1, low(string), index-1) = Copy(key2, low(string), index-1));
Exit(key1 = Copy(key2, low(string), index-1));
end;
end.
|
program testbugfix01(output);
begin
{Tests two bugs:
1) Known Bug reported in README on 2019.07.31
Floating point literals with a large number of digits will fail to compile,
as the compiler currently stores the symbol as a number, and Python loses precision.
For example:
```writeln(19832792187987.66);```
results in the following display at program execution:
```198327921879872.656250000000```
however:
```writeln(1983279218798723.66);```
results in a compilation error:
```symboltable.SymbolException: Literal not found: 1983279218798723.8```
2) Bug discovered during this fix, where the following code would not compile properly:
```
writeln(1.23);
writeln('1.23');
```
As the literal table was a single dictionary that stored, as its key, the string value
of the literal.
}
writeln(19832792187987.66);
writeln(1983279218798723.66);
writeln(1.23);
writeln('1.23');
end.
|
unit jniAddressList;
{
AddressList replacement to be used by the java version. It only contains data and not responsible for gui updates
}
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils, jni;
procedure InitializeJniAddressList(env: PJNIEnv);
implementation
uses MemoryRecordUnit, unixporthelper, commonTypeDefs, syncobjs, math;
type
TAddressListFreezer=class(TThread)
private
public
procedure execute; override;
end;
var
addresslist: TList=nil; //list of MemoryRecord's
addresslistcs: TCriticalsection; //used to protect the list from the freezer thread. Changing memory records is not part of this.
AddressListEntry_class: jclass; //global ref
AddressListEntry_init_method: jmethodID;
description_fieldid: JFieldID;
vartype_fieldid: JFieldID;
addressString_fieldid: JFieldID;
address_fieldid: JFieldID;
offsets_fieldid: JFieldID;
index_fieldid: JFieldID;
active_fieldid: jfieldID;
isUnicode_fieldid: jfieldID;
size_fieldid: jFieldid;
freezeInterval: integer;
freezerthread: TAddressListFreezer;
procedure TAddressListFreezer.execute;
{
'timer' that freezes the addresslist
}
var
i: integer;
r: TMemoryrecord;
begin
while not terminated do
begin
addresslistcs.enter;
try
for i:=0 to addresslist.count-1 do
begin
r:=TMemoryrecord(addresslist[i]);
if (r.Active) then
r.ApplyFreeze;
end;
finally
addresslistcs.Leave;
end;
sleep(freezeInterval);
end;
end;
function addresslist_getCount(PEnv: PJNIEnv; Obj: JObject): jint; cdecl;
begin
// log('addresslist_getCount');
if (addresslist<>nil) then
result:=addresslist.Count
else
begin
result:=0;
log('addresslist=nil');
end;
end;
function addresslist_setActive(PEnv: PJNIEnv; Obj: JObject; index: jint; state: jboolean): jboolean; cdecl;
var r: TMemoryRecord;
begin
log('addresslist_setActive');
if (index>=0) and (index<addresslist.count) then
begin
r:=TMemoryRecord(addresslist[index]);
r.Active:=state=1;
result:=ifthen(r.Active,1,0);
if r.Active and (freezerthread=nil) then //start the freezer thread
freezerthread:=TAddressListFreezer.Create(false);
end;
end;
function addresslist_setFreezeTimer(PEnv: PJNIEnv; Obj: JObject; interval: jint): jobject; cdecl;
begin
log('Setting freeze interval to '+inttostr(interval));
freezeInterval:=interval;
end;
procedure addresslist_setEntryValue(PEnv: PJNIEnv; Obj: JObject; index: jint; value: jstring); cdecl;
var r: TMemoryRecord;
begin
if (index>=0) and (index<addresslist.count) then
begin
r:=TMemoryRecord(addresslist[index]);
try
r.Value:=jniGetString(penv, value);
except
log('addresslist_setEntryValue: Error trying to set value');
end;
end;
end;
function addresslist_getEntryValue(PEnv: PJNIEnv; Obj: JObject; index: jint): jstring; cdecl;
var
r: TMemoryRecord;
v: string;
begin
if (index>=0) and (index<addresslist.count) then
begin
r:=TMemoryRecord(addresslist[index]);
v:=r.value;
result:=penv^.NewStringUTF(penv, pchar(v));
end;
end;
function addresslist_getEntry(PEnv: PJNIEnv; Obj: JObject; index: jint): jobject; cdecl;
var
i: integer;
r: TMemoryRecord;
descriptionstring, addressString: jstring;
offsetsarr: jintArray;
offsets: Pjint;
iscopy: jboolean;
begin
result:=nil;
//log('addresslist_getEntry');
if (index>=0) and (index<addresslist.count) then
begin
r:=TMemoryRecord(addresslist[index]);
result:=penv^.NewObject(penv, AddressListEntry_class, AddressListEntry_init_method);
//log('Created result. Creating description string ('+r.description+')');
descriptionstring:=penv^.NewStringUTF(penv, pchar(r.Description));
// log('Created descriptionstring, assigning it to the description field');
penv^.SetObjectField(penv, result, description_fieldid, descriptionstring);
//log('Assigned the string to the description field');
//log('Creating addressString ('+r.AddressString+')');
addressString:=penv^.NewStringUTF(penv, pchar(r.interpretableaddress));
//log('Created addressString ('+r.AddressString+')');
// log('Assigning addressString');
penv^.SetObjectField(penv, result, addressString_fieldid, addressString);
penv^.SetLongField(penv, result, address_fieldid, r.GetRealAddress);
penv^.SetIntField(penv, result, vartype_fieldid, integer(r.VarType));
penv^.SetIntField(penv, result, index_fieldid, index);
penv^.SetBooleanField(penv, result, active_fieldid, ifthen(r.active,1,0));
//assign the offsets (if there are any)
offsetsarr:=penv^.NewIntArray(penv, r.offsetCount);
offsets:=penv^.GetIntArrayElements(penv, offsetsarr, iscopy);
for i:=0 to r.offsetCount-1 do
PIntegerArray(offsets)[i]:=r.offsets[i].offset;
penv^.ReleaseIntArrayElements(penv, offsetsarr, offsets, 0);
penv^.SetObjectField(penv, result, offsets_fieldid, offsetsarr);
if r.vartype=vtString then
begin
penv^.SetIntField(penv, result, size_fieldid, r.Extra.stringData.length);
penv^.SetBooleanField(penv, result, isUnicode_fieldid, ifthen(r.extra.stringData.unicode,1,0));
end;
if r.vartype=vtByteArray then
penv^.SetIntField(penv, result, size_fieldid, r.Extra.byteData.bytelength);
end;
end;
procedure addresslist_setEntry(PEnv: PJNIEnv; Obj: JObject; index: jint; entry: JObject) cdecl;
type TJintArray=Array[0..1000] of jint;
type PJintArray=^TJintArray;
var
r: TMemoryRecord;
descriptionstring,addressString: jstring;
l: jint;
offsetlist: PJintArray;
offsets: jintArray;
iscopy: jboolean;
i: integer;
begin
// log('setting memory record');
if (index<0) or (index>=addresslist.count) then
begin
log('index ('+inttostr(index)+') is outside bounds');
exit;
end;
r:=TMemoryRecord(addresslist[index]);
// log('accessing provided entry');
descriptionstring:=penv^.GetObjectField(penv, entry, description_fieldid);
if (descriptionstring<>nil) then
begin
// log('got the description');
r.Description:=jniGetString(penv, descriptionstring);
// log('description='+r.Description);
end
else
log('description=null');
// log('getting vartype');
i:=penv^.GetIntField(penv, entry, vartype_fieldid);
// log('vartype='+inttostr(i));
r.VarType:=TVariableType(i);
// log('Getting addressString');
addressString:=penv^.GetObjectField(penv, entry, addressString_fieldid);
if (addressString<>nil) then
begin
// log('got the addressString');
r.interpretableaddress:=jniGetString(penv, addressString);
end
else
log('addressString=null');
offsets:=penv^.GetObjectField(penv, entry, offsets_fieldid);
if (offsets<>nil) then
begin
// log('offsets is not null');
l:=penv^.GetArrayLength(penv, offsets);
// log('the offsets array length='+inttostr(l));
iscopy:=0;
offsetlist:=PJintArray(penv^.GetIntArrayElements(penv,offsets, iscopy));
if offsetlist<>nil then
begin
r.offsetCount:=l;
for i:=0 to l-1 do
r.offsets[i].offset:=offsetlist[i];
penv^.ReleaseIntArrayElements(penv, offsets, PJint(offsetlist),JNI_ABORT);
end
else
log('offsetlist=nil');
end;
if r.vartype=vtString then
begin
Log('set address: string');
r.extra.stringData.length:=penv^.GetIntField(penv, entry, size_fieldid);
r.Extra.stringData.unicode:=penv^.GetBooleanField(penv, entry, isUnicode_fieldid)<>0;
Log('Length='+inttostr(r.extra.stringData.length));
Log('isUnicode='+BoolToStr(r.extra.stringData.unicode));
end;
if r.vartype=vtByteArray then
r.Extra.byteData.bytelength:=penv^.GetIntField(penv, entry, size_fieldid);
r.ReinterpretAddress;
end;
function addresslist_addEntry(PEnv: PJNIEnv; Obj: JObject; entry: JObject): jint; cdecl;
var
r: TMemoryrecord;
begin
//log('creating memory record');
r:=TMemoryrecord.Create(nil);
addresslistcs.enter;
try
addresslist.Add(r);
result:=addresslist.count;
// log('Initializing memory record. (result='+inttostr(result)+')');
addresslist_setEntry(penv, obj, result-1, entry);
finally
addresslistcs.leave;
end;
end;
procedure addresslist_deleteEntry(PEnv: PJNIEnv; Obj: JObject; index: jint); cdecl;
begin
log('Delete entry');
if (index>=0) and (index<addresslist.count) then
begin
addresslistcs.enter;
try
TMemoryRecord(addresslist[index]).free;
addresslist.Delete(index);
finally
addresslistcs.leave;
end;
end;
end;
procedure addresslist_clear(PEnv: PJNIEnv; Obj: JObject); cdecl;
var i: integer;
begin
log('addresslist.Clear');
addresslistcs.enter;
try
for i:=0 to addresslist.count-1 do
TMemoryrecord(addresslist[i]).Free;
addresslist.Clear;
finally
addresslistcs.leave;
end;
end;
const methodcount=10;
var jnimethods: array [0..methodcount-1] of JNINativeMethod =(
(name: 'GetCount'; signature: '()I'; fnPtr: @addresslist_getCount),
(name: 'GetEntry'; signature: '(I)Lorg/cheatengine/AddressListEntry;'; fnPtr: @addresslist_getEntry),
(name: 'SetEntry'; signature: '(ILorg/cheatengine/AddressListEntry;)V'; fnPtr: @addresslist_setEntry),
(name: 'AddEntry'; signature: '(Lorg/cheatengine/AddressListEntry;)I'; fnPtr: @addresslist_addEntry),
(name: 'SetEntryActive'; signature: '(IZ)Z'; fnPtr: @addresslist_setActive),
(name: 'SetFreezeTimer'; signature: '(I)V'; fnPtr: @addresslist_setFreezeTimer),
(name: 'DeleteEntry'; signature: '(I)V'; fnPtr: @addresslist_deleteEntry),
(name: 'Clear'; signature: '()V'; fnPtr: @addresslist_clear) ,
(name: 'SetEntryValue'; signature: '(ILjava/lang/String;)V'; fnPtr: @addresslist_setEntryValue),
(name: 'GetEntryValue'; signature: '(I)Ljava/lang/String;'; fnPtr: @addresslist_getEntryValue)
);
procedure InitializeJniAddressList(env: PJNIEnv);
var c: jclass;
begin
if addresslist=nil then
begin
addresslist:=Tlist.create;
addresslistcs:=TCriticalSection.Create;
end;
c:=env^.FindClass(env, 'org/cheatengine/AddressList');
env^.RegisterNatives(env, c, @jnimethods[0], methodcount);
c:=env^.FindClass(env, 'org/cheatengine/AddressListEntry');
AddressListEntry_class:=env^.NewGlobalRef(env, c); //I'll need this later
AddressListEntry_init_method:=env^.GetMethodID(env, c, '<init>', '()V');
description_fieldid:=env^.GetFieldID(env, AddressListEntry_class, 'description','Ljava/lang/String;');
vartype_fieldid:=env^.GetFieldID(env, AddressListEntry_class, 'vartype','I');
addressString_fieldid:=env^.GetFieldID(env, AddressListEntry_class, 'addressString','Ljava/lang/String;');
address_fieldid:=env^.GetFieldID(env, AddressListEntry_class, 'address','J');
offsets_fieldid:=env^.GetFieldID(env, AddressListEntry_class, 'offsets','[I');
active_fieldid:=env^.GetFieldID(env, AddressListEntry_class, 'active','Z');
index_fieldid:=env^.GetFieldID(env, AddressListEntry_class, 'index','I');
isUnicode_fieldid:=env^.GetFieldID(env, AddressListEntry_class, 'isUnicode','Z');
size_fieldid:=env^.GetFieldID(env, AddressListEntry_class, 'size','I');
log('description_fieldid='+inttohex(ptruint(description_fieldid),8));
log('vartype_fieldid='+inttohex(ptruint(vartype_fieldid),8));
end;
end.
|
{
@author(Patrick Michael Kolla-ten Venne [pk] <patrick@kolla-tenvenne.de>)
@abstract(Demonstrates icon loading and caching in a background thread.)
@preformatted(
// *****************************************************************************
// Copyright: © 2018 Patrick Michael Kolla-ten Venne. All rights reserved.
// *****************************************************************************
// Changelog (new entries first):
// ---------------------------------------
// 2018-11-14 pk --- [CCD] Updated unit header.
// *****************************************************************************
)
}
unit TListViewIconsCacheDemoForm;
{$IFDEF FPC}
{$mode Delphi}{$H+}
{$ENDIF FPC}
interface
uses
Classes,
SysUtils,
Forms,
Controls,
Graphics,
Dialogs,
ComCtrls,
StdCtrls,
FileIconCache;
type
TDemoListItem = class(TFileIconListItem);
{ TListViewIconsCacheDemoFormMain }
TListViewIconsCacheDemoFormMain = class(TForm)
bnRefresh: TButton;
ilIcons: TImageList;
lvFiles: TListView;
procedure bnRefreshClick({%H-}Sender: TObject);
procedure FormCreate({%H-}Sender: TObject);
procedure FormDestroy({%H-}Sender: TObject);
procedure FormShow({%H-}Sender: TObject);
procedure lvFilesCreateItemClass({%H-}Sender: TCustomListView; var ItemClass: TListItemClass);
private
FPath: string;
FFileIconCache: TFileIconCache;
public
procedure ShowFolderContents(AFolder: string);
end;
var
ListViewIconsCacheDemoFormMain: TListViewIconsCacheDemoFormMain;
implementation
{$R *.lfm}
{ TListViewIconsCacheDemoFormMain }
procedure TListViewIconsCacheDemoFormMain.FormShow(Sender: TObject);
begin
bnRefresh.Click;
end;
procedure TListViewIconsCacheDemoFormMain.lvFilesCreateItemClass(Sender: TCustomListView; var ItemClass: TListItemClass);
begin
ItemClass := TDemoListItem;
end;
procedure TListViewIconsCacheDemoFormMain.FormCreate(Sender: TObject);
begin
FFileIconCache := TFileIconCache.Create;
FFileIconCache.ListView := lvFiles;
end;
procedure TListViewIconsCacheDemoFormMain.bnRefreshClick(Sender: TObject);
begin
// TODO : pick own path; network folders work best to demonstrate since icons load slow
ShowFolderContents('t:\people\patrick\');
end;
procedure TListViewIconsCacheDemoFormMain.FormDestroy(Sender: TObject);
begin
FFileIconCache.Free;
end;
procedure TListViewIconsCacheDemoFormMain.ShowFolderContents(AFolder: string);
var
sr: TSearchRec;
i: integer;
li: TFileIconListItem;
begin
FPath := AFolder;
AFolder := IncludeTrailingPathDelimiter(AFolder);
lvFiles.Items.BeginUpdate;
try
lvFiles.Items.Clear;
i := FindFirst(AFolder + '*.*', faAnyFile, sr);
try
while i = 0 do begin
if (sr.Name <> '.') and (sr.Name <> '..') then begin
li := TFileIconListItem(lvFiles.Items.Add);
li.Filename := AFolder + sr.Name;
li.Caption := sr.Name;
li.ImageIndex := FFileIconCache.GetFileIcon(AFolder + sr.Name);
end;
i := FindNext(sr);
end;
finally
SysUtils.FindClose(sr);
end;
finally
lvFiles.Items.EndUpdate;
FFileIconCache.TriggerNewIcons;
end;
end;
end.
|
unit NovusLog;
interface
Uses Classes, NovusStringUtils, NovusList, NovusUtilities, SysUtils,
NovusBO, NovusWinEventLog;
Type
TLogType = (ltFile, ltWinEventType);
TNovusLogDetails = class(TNovusBO)
private
fiLogID:Integer;
fdtLogDateTime: tDateTime;
fsLogDesc: String;
fsDateTimeMask: String;
protected
public
constructor Create; virtual;
destructor Destroy; override;
Property LogID: Integer
read fiLogID
write fiLogID;
property LogDateTime: tdateTime
read fdtLogDateTime
write fdtLogDateTime;
property LogDesc: String
read fsLogDesc
write fsLogDesc;
property DateTimeMask: String
read fsDateTimeMask
write fsDateTimeMask;
end;
TNovusLog = Class(TNovusBO)
private
fiLastLogID: Integer;
foLogDetailsList: TNovusList;
foEventLog: tNovusWinEventLog;
fsDateTimeMask: String;
protected
public
constructor Create(ALogType: TLogType);
destructor Destroy; override;
function FormatedNow(const aDate: tDateTime = 0): String;
procedure AddLogDetails(ALogDesc: string; ALogDateTime: tDateTime);
function WriteLog(AMsg: string; AEventType: TEventType = etNone): string; virtual;
function WriteExceptLog:String; virtual;
Property oLogDetailsList: TNovusList
read foLogDetailsList
write foLogDetailsList;
property DateTimeMask: String
read fsDateTimeMask
write fsDateTimeMask;
property oEventLog: tNovusWinEventLog
read foEventLog
write foEventLog;
property LastLogID: Integer
read fiLastLogID
write fiLastLogID;
end;
TNovusLogFile = Class(TNovusLog)
private
protected
fboutputConsole: Boolean;
fcSeparator: char;
fiFileSize: integer;
fbIsFileOpen: Boolean;
fsFilename: string;
FFilePonter : text;
fsPathName: String;
public
constructor Create(AFilename: String); virtual;
destructor Destroy; override;
function WriteLine(ATimeStr, ALogDesc: string; ALogDateTime: tDateTime): String;
function ReadLine: String;
function OpenLog(AOveride: Boolean = false): Boolean; virtual;
procedure CloseLog; virtual;
procedure ReadAll;
function WriteLog(AMsg: string; AEventType: TEventType = etNone): string; override;
function WriteExceptLog: String; override;
property Filename: String
read FsFilename
write FsFilename;
property Separator: char
read fcSeparator
write fcSeparator;
property IsFileOpen: Boolean
read fbIsFileOpen
write fbIsFileOpen;
property FileSize: Integer
read fiFileSize
write fiFileSize;
property FilePonter : text
read FFilePonter
write FFilePonter;
property OutputConsole: Boolean
read fbOutputConsole
write fbOutputConsole;
end;
implementation
constructor TNovusLog.Create(ALogType: TLogType);
begin
inherited Create;
DateTimeMask := FormatSettings.ShortDateFormat + ' hh:mm';
foLogDetailsList := TNovusList.Create(TNovusLogDetails);
foEventLog := tNovusWinEventLog.Create;
end;
destructor TNovusLog.Destroy;
begin
foEventLog.Free;
foLogDetailsList.Free;
inherited;
end;
constructor TNovusLogDetails.Create;
begin
inherited Create;
end;
destructor TNovusLogDetails.Destroy;
begin
inherited;
end;
function TNovusLog.FormatedNow(const aDate: tDateTime = 0): String;
var
fDate: tDatetime;
begin
fDate := aDate;
if aDate = 0 then fDate := Now;
Result := FormatDateTime(DateTimeMask, fDate)
end;
procedure TNovusLog.AddLogDetails;
Var
loLogDetails : TNovusLogDetails;
begin
Inc(fiLastLogId);
loLogDetails := TNovusLogDetails.Create;
loLogDetails.LogId := fiLastLogId;
loLogDetails.LogDateTime := ALogDateTime;
loLogDetails.LogDesc := ALogDesc;
loLogDetails.DateTimeMask := DateTimeMask;
foLogDetailsList.Add(loLogDetails);
end;
function TNovusLog.WriteLog(AMsg: string; AEventType: TEventType = etNone): String;
Var
ldDataTime: tDateTime;
begin
ldDataTime := Now;
AddLogDetails(AMsg, ldDataTime);
If AEventType = etNone then
begin
Self.oEventLog.EventType := AEventType;
Self.oEventLog.LogEvent(AMsg);
end;
end;
function TNovusLog.WriteExceptLog: String;
begin
Result := WriteLog(TNovusUtilities.GetExceptMess);
end;
constructor TNovusLogFile.Create;
begin
inherited Create(ltFile);
FsFilename := AFilename;
fbIsFileOpen := False;
FsPathname := '';
fiFileSize := 0;
fcSeparator := '-';
end;
destructor TNovusLogFile.Destroy;
begin
inherited;
end;
function TNovusLogFile.OpenLog(AOveride: Boolean = false): Boolean;
begin
inherited;
Result := False;
If fbIsFileOpen then Exit;
if Not DirectoryExists(TNovusUtilities.JustPathname(Filename)) then Exit;
if FileExists(Filename) then
begin
If (FileSize > 0) and (tNovusUtilities.FindFileSize(Filename) > FileSize) then
RenameFile(Filename, TNovusUtilities.JustPathname(Filename) + tNovusUtilities.JustFilename(Filename) + '.bak');
end;
AssignFile(FFilePonter, Filename);
if AOveride = False then
begin
if FileExists(Filename) then
Append(FFilePonter)
else Rewrite(FFilePonter);
end
else
begin
Rewrite(FFilePonter);
end;
fbIsFileOpen:= True;
Result := fbIsFileOpen;
WriteLog('Logging started');
end;
function TNovusLogFile.WriteLine(ATimeStr, ALogDesc: string; ALogDateTime: tDateTime): String;
Var
lsLine: String;
begin
If Separator = #0 then
lsLine := ATimeStr + ALogDesc
else
lsLine := ATimeStr + Separator + ALogDesc;
Writeln(FFilePonter, lsline);
Result := lsLine;
end;
function TNovusLogFile.ReadLine: string;
begin
Readln(FFilePonter, Result)
end;
procedure TNovusLogFile.CloseLog;
begin
fbIsFileOpen := False;
WriteLog('Logging finished');
CloseFile(FFilePonter);
end;
function TNovusLogFile.WriteExceptLog: String;
begin
Result := inherited WriteExceptLog;
WriteLine(FormatDateTime(fsDateTimeMask, Now), Result, now);
Flush(FFilePonter);
end;
function TNovusLogFile.WriteLog(AMsg: string; AEventType: TEventType = etNone): string;
begin
if AMsg = '' then Exit;
if OutputConsole then WriteLn(AMsg);
inherited WriteLog(AMsg, AEventType);
Result := WriteLine(FormatedNow, AMsg, now);
Flush(FFilePonter);
end;
procedure TNovusLogFile.ReadAll;
Var
lsLine: String;
liPos: Integer;
ldLogDateTime: tDateTime;
lsLogDesc: String;
begin
If Not FileExists(Filename) then Exit;
AssignFile(FFilePonter, Filename);
Reset(FFilePonter);
while not System.Eof(FilePonter) do
begin
lsLine := ReadLine;
If Trim(lsLine) <> '' then
begin
liPos := 1;
ldLogDateTime := TNovusStringUtils.Str2DateTime(tNovusStringUtils.GetStrTokenA(lsLine, '-', liPos));
lsLogDesc := tNovusStringUtils.GetStrTokenA(lsLine, '-', liPos);
AddLogDetails(lsLogDesc, ldLogDateTime);
end;
end;
CloseFile(FFilePonter)
end;
end.
|
{ Type 1 OCTREE aggregate object. The octree is rectangular and axis aligned.
}
module type1_octree;
define type1_octree_class_make;
define type1_octree_geom;
%include 'ray_type1_2.ins.pas';
%include 'type1_octree.ins.pas';
const
max_coor_level = 15; {how many subdivision levels to keep data for}
int_scale = 268435456.0; {octree floating point to integer coordinates}
box_radius_scale = 1.0/int_scale; {pick mask to voxel radius scale factor}
iter_below_minvox = 3; {coor iterations to do beyond min voxel size}
{
* Static storage. This storage is allocated at load time and therefore should
* not be altered.
}
var
coor_masks: {mask in address bits for each voxel size}
array[0..max_coor_level] of integer32 := [
16#F0000000,
16#F8000000,
16#FC000000,
16#FE000000,
16#FF000000,
16#FF800000,
16#FFC00000,
16#FFE00000,
16#FFF00000,
16#FFF80000,
16#FFFC0000,
16#FFFE0000,
16#FFFF0000,
16#FFFF8000,
16#FFFFC000,
16#FFFFE000];
pick_masks: {mask in bit for selecting next voxel down}
array[0..max_coor_level] of integer32 := [
16#08000000,
16#04000000,
16#02000000,
16#01000000,
16#00800000,
16#00400000,
16#00200000,
16#00100000,
16#00080000,
16#00040000,
16#00020000,
16#00010000,
16#00008000,
16#00004000,
16#00002000,
16#00001000];
{
********************************************************************************
*
* Local subroutine TYPE1_OCTREE_CREATE (OBJECT, CREA, STAT)
*
* Fill in the new object in OBJECT. CREA is the user data parameters for
* this object. STAT is the standard system error return code.
}
procedure type1_octree_create ( {create new primitive with custom data}
in out object: ray_object_t; {newly filled in object block}
in gcrea_p: univ_ptr; {data for creating this object instance}
out stat: sys_err_t); {completion status code}
val_param;
var
crea_p: type1_octree_crea_data_p_t; {pointer to our specific creation data}
data_p: oct_data_p_t; {pointer to internal object data}
step_level: sys_int_machine_t; {voxel level of iteration step size}
box_err: real; {size of voxel intersect box size grow}
sz: sys_int_adr_t; {memory size}
begin
sys_error_none (stat); {init to no error}
crea_p := gcrea_p; {pointer to our specific creation data}
sz := sizeof(data_p^); {amount of memory to allocate}
util_mem_grab ( {allocate data block for new object}
sz, ray_mem_p^, false, data_p);
stats_oct.mem := stats_oct.mem + sz;
object.data_p := data_p; {set pointer to object data block}
data_p^.shader := crea_p^.shader; {copy pointer to shader to use}
data_p^.liparm_p := crea_p^.liparm_p; {copy pointer to light source block}
data_p^.visprop_p := crea_p^.visprop_p; {copy pointer to visual properties block}
data_p^.min_gen := crea_p^.min_gen; {copy other data specific to this object}
data_p^.max_gen := crea_p^.max_gen;
data_p^.min_miss := crea_p^.min_miss;
data_p^.origin := crea_p^.origin;
data_p^.size := crea_p^.size;
{
* All the user's data has been copied. Now init the rest of the local data for this
* object.
}
data_p^.recip_size.x := 1.0/data_p^.size.x; {make reciprocal sizes}
data_p^.recip_size.y := 1.0/data_p^.size.y;
data_p^.recip_size.z := 1.0/data_p^.size.z;
sz := sizeof(data_p^.ar_p^); {amount of memory to allocate}
util_mem_grab ( {allocate an initial block of nodes}
sz, ray_mem_p^, false, data_p^.ar_p);
stats_oct.mem := stats_oct.mem + sz;
data_p^.top_node_p := addr(data_p^.ar_p^[1]); {set pointer to top level node}
data_p^.n_ar := 1; {init to one node allocated in current array}
data_p^.top_node_p^.n_obj := 0; {init node to empty leaf node}
data_p^.top_node_p^.hits := 0; {init to no rays passed thru here}
data_p^.top_node_p^.misses := 0;
data_p^.top_node_p^.next_p := nil; {init to no data nodes chained on}
data_p^.free_p := nil; {init to no nodes on free chain}
data_p^.next_p := addr(data_p^.top_node_p^.obj_p[1]); {init adr of next obj pointer}
data_p^.last_left := obj_per_leaf_node; {init num object pointers left this node}
step_level := {voxel level of iteration steps}
min(max_coor_level, data_p^.max_gen + iter_below_minvox);
box_err := {intersect box size increment in octree space}
1.0 / lshft(1, step_level);
data_p^.box_err.x := box_err * data_p^.size.x;
data_p^.box_err.y := box_err * data_p^.size.y;
data_p^.box_err.z := box_err * data_p^.size.z;
data_p^.box_err_half.x := data_p^.box_err.x / 2.0;
data_p^.box_err_half.y := data_p^.box_err.y / 2.0;
data_p^.box_err_half.z := data_p^.box_err.z / 2.0;
stats_oct.n_leaf := stats_oct.n_leaf + 1; {one more leaf node voxel}
end;
{
********************************************************************************
*
* Local function TYPE1_OCTREE_INTERSECT_CHECK (
* GRAY, OBJECT, GPARMS, HIT_INFO, SHADER)
*
* Check ray and object for an intersection. If so, return TRUE, and save any
* partial results in HIT_INFO. These partial results may be used later to get
* detailed information about the intersection geometry.
}
function type1_octree_intersect_check ( {check for ray/object intersection}
in out gray: univ ray_base_t; {input ray descriptor}
in var object: ray_object_t; {input object to intersect ray with}
in gparms_p: univ_ptr; {pointer to run time TYPEn-specific params}
out hit_info: ray_hit_info_t; {handle to routines and data to get hit color}
out shader: ray_shader_t) {pointer to shader to resolve color here}
:boolean; {TRUE if ray does hit object}
val_param;
const
mic = 4.76837E-7; {min representable coor in 0.0 to 1.0 space}
mac = 1.0 - mic; {max representable coor in 0.0 to 1.0 space}
cached_checks = 8; {previously checked objects list max size}
type
icoor_t = record case integer of {integer XYZ coordinate with array overlay}
1:( {individually named fields}
x, y, z: sys_int_machine_t);
2:( {overlay array of algorithmic indexing}
coor: array[1..3] of sys_int_machine_t);
end;
vstack_entry_t = record {data about current voxel at one level}
icoor: icoor_t; {voxel coordinate with unused bits set to zero}
p: node_p_t; {pointer to voxel data}
parent_p: node_pp_t; {adr of pointer to the node at this level}
end;
var
ray_p: type1_ray_p_t; {pointer to the ray in our format}
uparms_p: type1_object_parms_p_t; {pointer to object parameters in our format}
r: real; {scratch floating point number}
data_p: oct_data_p_t; {pointer to object's specific data area}
p: vect_3d_t; {octree ray start point}
orayp: vect_3d_t; {ray point in octree 0,0,0 to 1,1,1 space}
v: vect_3d_t; {non-unit ray vector in 0 to 1 space}
vsq: vect_3d_t; {V with each component squared}
maj, min1, min2: sys_int_machine_t; {1-3 subscripts for major and minor axies}
slope: vect_3d_t; {slope of each axis with respect to major axis}
dmaj: real; {major axis delta}
p1, p2: vect_3d_t; {scratch points}
level: sys_int_machine_t; {nesting level of current node, top = 0}
coor_mask: integer32; {masks in relevant adr bits for this level}
icoor: icoor_t; {32 bit integer XYZ coordinate}
icoor2: icoor_t; {scratch integer coordinate}
max_iter_level: sys_int_machine_t; {max level for iterating new coordinate}
vox_icoor: icoor_t; {voxel coordinate with unused bits set to zero}
coor_step: {delta ICOOR when major axis steps one voxel}
array[0..max_coor_level] of icoor_t;
vstack: {data about each nested voxel level}
array[0..max_coor_level] of vstack_entry_t;
vp: node_p_t; {pointer to current voxel}
i, j: sys_int_machine_t; {loop counters and scratch integers}
box: ray_box_t; {paralellpiped for voxel intersection checks}
box_coor: array[0..1] of vect_3d_t; {possible box corner points}
newp: node_p_t; {pointer to new subdivided voxel}
obj_pp: ^ray_object_p_t; {adr of next obj pnt in scanning voxel list}
vlnp: node_p_t; {pointer to curr node in scanning voxel list}
nleft: sys_int_machine_t; {obj pointers left this node in scanning list}
new_left: sys_int_machine_t; {num obj pointers left in node being built}
n_new: sys_int_machine_t; {total number of objects in voxel being built}
new_pp: ^ray_object_p_t; {adr of next obj pointer in node being built}
nnewp: node_p_t; {pointer to node being built}
parms: type1_object_parms_t; {parameters to pass to subordinate objects}
old_mem: sys_int_adr_t; {MEM index before any object hits}
new_mem: sys_int_adr_t; {MEM index after last object hit}
last_checks: {cached object pointers of recent misses}
array[1..cached_checks] of ray_object_p_t;
n_cached: sys_int_machine_t; {number of object pointers in LAST_CHECKS array}
next_cache: sys_int_machine_t; {LAST_checks index of where to put next obj pnt}
old_max_dist: real; {saved copy of RAY.MAX_DIST}
parent_p: node_pp_t; {address of pointer to current voxel}
sz: sys_int_adr_t; {memory size}
ray_ends: boolean; {TRUE if ray ends withing octree}
here: boolean; {flag indicating ray can hit object in box}
enclosed: boolean; {flag indicating object completely encloses box}
hit: boolean; {the ray hit an object}
label
got_p, new_coor, got_start_level, new_voxel, leaf_node, subdivide_voxel,
trace_voxel, next_obj, next_coor, no_hit, leave;
begin
data_p := oct_data_p_t(object.data_p); {make pointer to object's data area}
ray_p := univ_ptr(addr(gray)); {pointer to ray descriptor}
uparms_p := gparms_p; {pointer to runtime parameters for this object}
with {set up abbreviations}
data_p^:d,
ray_p^:ray
do begin
{
* Abbreviations:
* D - Specific data block for OCTREE object
*
* Now transform the ray into the (0,0,0) to (1,1,1) octree space.
}
orayp.x := (ray.point.x - d.origin.x)*d.recip_size.x; {octree space ray point}
orayp.y := (ray.point.y - d.origin.y)*d.recip_size.y;
orayp.z := (ray.point.z - d.origin.z)*d.recip_size.z;
v.x := ray.vect.x*d.recip_size.x; {transform ray vector to our space (not unity)}
v.y := ray.vect.y*d.recip_size.y;
v.z := ray.vect.z*d.recip_size.z;
p.x := orayp.x + v.x*ray.min_dist; {first valid ray point in octree space}
p.y := orayp.y + v.y*ray.min_dist;
p.z := orayp.z + v.z*ray.min_dist;
ray_ends := ray.max_dist < 1.0E20; {set flag if ray effectively has ending point}
vsq.x := sqr(v.x); {square each component of unscaled vector}
vsq.y := sqr(v.y);
vsq.z := sqr(v.z);
{
* The ray point and ray vector have been transformed into a space in which the
* octree occupies (0,0,0) to (1,1,1). The transformed ray start point is in P,
* and the transformed ray vector is in V. V is a unit vector. This transformed
* space is only used to decide which voxels the ray hits. The original ray is
* passed directly to the subordinate object intersection routines.
*
* Start by determining which is the major axis and the two minor axies.
}
if vsq.x > vsq.y {sort based on X and Y alone}
then begin
maj := 1;
min2 := 2;
end
else begin
maj := 2;
min2 := 1;
end
;
if vsq.z > vsq.coor[maj] {sort biggest against Z}
then maj := 3;
if vsq.z < vsq.coor[min2] {sort smallest against Z}
then min2 := 3;
min1 := 6 - maj - min2; {middle size must be the one left over}
{
* MAJ, MIN1, MIN2 are indicies for the most major to the most minor axies.
}
slope.coor[maj] := 1.0; {find slopes with respect to major axis}
slope.coor[min1] := v.coor[min1]/v.coor[maj];
slope.coor[min2] := v.coor[min2]/v.coor[maj];
if (p.x >= mic) and (p.x <= mac) {is ray point inside octree ?}
and (p.y >= mic) and (p.y <= mac)
and (p.z >= mic) and (p.z <= mac)
then begin {start point is just the ray point}
goto got_p; {point P is all set}
end;
{
* The ray start point is not inside the octree. Make points P1 and P2 which are
* the intersection points between the ray and the front and back planes perpendicular
* to the major axis. P1 and P2 are clipped to the ray starting point.
}
if (p.coor[maj] < mic) and (v.coor[maj] < 0.0) {start behind and heading away ?}
then goto no_hit;
if (p.coor[maj] > mac) and (v.coor[maj] > 0.0) {start in front and heading more so ?}
then goto no_hit;
if ((p.coor[maj] < mic) and (v.coor[maj] > 0.0)) {intersecting MAJ=MIC plane ?}
or ((p.coor[maj] > mic) and (v.coor[maj] < 0.0))
then begin {the ray hits the MAJ=MIC plane}
dmaj := mic - p.coor[maj]; {major axis distance to plane}
p1.coor[maj] := mic; {find intersect point with MAJ=MIC plane}
p1.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1];
p1.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2];
end
else begin {ray does not hit the MAJ=MIC plane}
p1 := p; {ray start is the MAJ minimum point}
end
; {P1 set to major axis minimum point}
if ((p.coor[maj] > mac) and (v.coor[maj] < 0.0)) {intersecting MAJ=MAC plane ?}
or ((p.coor[maj] < mac) and (v.coor[maj] > 0.0))
then begin {ray hits the MAJ=MAC plane}
dmaj := mac - p.coor[maj]; {major axis distance to plane}
p2.coor[maj] := mac; {find intersect point with MAJ=MAC plane}
p2.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1];
p2.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2];
end
else begin {ray does not hit the MAJ=MAC plane}
p2 := p; {ray start is the MAJ maximum point}
end
; {P2 set to major axis maximum point}
{
* The line segment P1 to P2 is the segment of the ray passing thru the major axis
* MIC to MAC slice. P1 to P2 are in order of increasing major axis. Now clip the
* line segment against the MIN1 and MIN2 MIC to MAC slices. The resulting line
* segment is the intersection of the ray and the outside of the octree.
}
if slope.coor[min1] >= 0.0 {check P1-->P2 direction relative to MIN1 axis}
then begin {P1 --> P2 goes along increasing MIN1}
if p1.coor[min1] > mac then goto no_hit; {ray starts past MIN1 slice ?}
if p2.coor[min1] < mic then goto no_hit; {ray ends before MIN1 slice ?}
if p1.coor[min1] < mic then begin {ray starts before hitting MIN1 slice ?}
dmaj := {major axis delta from P1 to MIN1=MIC}
(mic - p.coor[min1])/slope.coor[min1];
p1.coor[maj] := p.coor[maj] + dmaj; {P1-->P2 intersect point with MIN1=MIC}
p1.coor[min1] := mic;
p1.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2];
end; {done adjusting P1 to MIN1 slice}
if p2.coor[min1] > mac then begin {need to adjust P2 coordinate ?}
dmaj := {major axis delta from P1 to MIN1=MAC}
(mac - p.coor[min1])/slope.coor[min1];
p2.coor[maj] := p.coor[maj] + dmaj; {P1-->P2 intersect point with MIN1=MAC}
p2.coor[min1] := mac;
p2.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2];
end; {done adjusting P2 to MIN1 slice}
end
else begin {P2 --> P1 goes along decreasing MIN1}
if p2.coor[min1] > mac then goto no_hit; {ray starts past MIN1 slice ?}
if p1.coor[min1] < mic then goto no_hit; {ray ends before MIN1 slice ?}
if p2.coor[min1] < mic then begin {ray starts before hitting MIN1 slice ?}
dmaj := {major axis delta from P2 to MIN1=MIC}
(mic - p.coor[min1])/slope.coor[min1];
p2.coor[maj] := p.coor[maj] + dmaj; {P2-->P1 intersect point with MIN1=MIC}
p2.coor[min1] := mic;
p2.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2];
end; {done adjusting P2 to MIN1 slice}
if p1.coor[min1] > mac then begin {need to adjust P1 coordinate ?}
dmaj := {major axis delta from P2 to MIN1=MAC}
(mac - p.coor[min1])/slope.coor[min1];
p1.coor[maj] := p.coor[maj] + dmaj; {P2-->P1 intersect point with MIN1=MAC}
p1.coor[min1] := mac;
p1.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2];
end; {done adjusting P1 to MIN1 slice}
end
; {done clipping segment to MIN1 slice}
if slope.coor[min2] >= 0.0 {check P1-->P2 direction relative to MIN2 axis}
then begin {P1 --> P2 goes along increasing MIN2}
if p1.coor[min2] > mac then goto no_hit; {ray starts past MIN2 slice ?}
if p2.coor[min2] < mic then goto no_hit; {ray ends before MIN2 slice ?}
if p1.coor[min2] < mic then begin {ray starts before hitting MIN2 slice ?}
dmaj := {major axis delta from P1 to MIN2=MIC}
(mic - p.coor[min2])/slope.coor[min2];
p1.coor[maj] := p.coor[maj] + dmaj; {P1-->P2 intersect point with MIN2=MIC}
p1.coor[min2] := mic;
p1.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1];
end; {done adjusting P1 to MIN2 slice}
if p2.coor[min2] > mac then begin {need to adjust P2 coordinate ?}
dmaj := {major axis delta from P1 to MIN2=MAC}
(mac - p.coor[min2])/slope.coor[min2];
p2.coor[maj] := p.coor[maj] + dmaj; {P1-->P2 intersect point with MIN2=MAC}
p2.coor[min2] := mac;
p2.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1];
end; {done adjusting P2 to MIN2 slice}
end
else begin {P2 --> P1 goes along decreasing MIN2}
if p2.coor[min2] > mac then goto no_hit; {ray starts past MIN2 slice ?}
if p1.coor[min2] < mic then goto no_hit; {ray ends before MIN2 slice ?}
if p2.coor[min2] < mic then begin {ray starts before hitting MIN2 slice ?}
dmaj := {major axis delta from P2 to MIN2=MIC}
(mic - p.coor[min2])/slope.coor[min2];
p2.coor[maj] := p.coor[maj] + dmaj; {P2-->P1 intersect point with MIN2=MIC}
p2.coor[min2] := mic;
p2.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1];
end; {done adjusting P2 to MIN2 slice}
if p1.coor[min2] > mac then begin {need to adjust P1 coordinate ?}
dmaj := {major axis delta from P2 to MIN2=MAC}
(mac - p.coor[min2])/slope.coor[min2];
p1.coor[maj] := p.coor[maj] + dmaj; {P2-->P1 intersect point with MIN2=MAC}
p1.coor[min2] := mac;
p1.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1];
end; {done adjusting P1 to MIN2 slice}
end
; {done clipping segment to MIN2 slice}
{
* The line segment P1 to P2 is the part of the ray that intersects the outer box
* of the octree. P1 to P2 is in order of increasing major axis. Now set P to the
* ray start point inside the octree.
}
if v.coor[maj] >= 0.0 {check MAJ direction with respect to ray dir}
then begin {ray is in increasing MAJ direction}
p := p1;
end
else begin {ray is in decreasing MAJ direction}
p := p2;
end
;
{
* P is the first point along the ray where we are allowed to look for hits that
* is also inside the octree. P is in the octree (0,0,0) to (1,1,1) space.
* Now do remaining initialization before entering main voxel stepping loop.
}
got_p: {jump here if P started out inside octree}
old_max_dist := ray.max_dist; {save field we will corrupt later}
if d.shader = nil {resolve shader pointer inheritance}
then parms.shader := uparms_p^.shader
else parms.shader := d.shader;
if d.liparm_p = nil {resolve LIPARM pointer inheritance}
then parms.liparm_p := uparms_p^.liparm_p
else parms.liparm_p := d.liparm_p;
if d.visprop_p = nil {resolve VISPROP pointer inheritance}
then parms.visprop_p := uparms_p^.visprop_p
else parms.visprop_p := d.visprop_p;
n_cached := 0; {init checked objects cache to empty}
next_cache := 1; {init where to cache next checked obj pointer}
hit := false; {init to ray not hit anything in octree}
old_mem := next_mem; {save MEM index before any obj save blocks}
max_iter_level := d.max_gen + iter_below_minvox; {set max coordinate level to use}
if max_iter_level > max_coor_level {clip to max coordinate level allocated}
then max_iter_level := max_coor_level;
if v.coor[maj] >= 0 {check sign of major axis}
then begin {major axis is positive}
icoor2.x := round(slope.x*int_scale);
icoor2.y := round(slope.y*int_scale);
icoor2.z := round(slope.z*int_scale);
end
else begin {major axis is negative}
icoor2.x := -round(slope.x*int_scale);
icoor2.y := -round(slope.y*int_scale);
icoor2.z := -round(slope.z*int_scale);
end
;
for i := 0 to max_iter_level do begin {once for each used coordinate level}
coor_step[i] := icoor2; {set step sizes for this level}
icoor2.x := icoor2.x div 2; {make step size for next level down}
icoor2.y := icoor2.y div 2;
icoor2.z := icoor2.z div 2;
end; {back and fill in next COOR_STEP entry}
icoor.x := trunc(p.x*int_scale); {init current ray point integer coordinate}
icoor.y := trunc(p.y*int_scale);
icoor.z := trunc(p.z*int_scale);
vstack[0].icoor.x := 0; {set coordinate of top level voxel}
vstack[0].icoor.y := 0;
vstack[0].icoor.z := 0;
vstack[0].p := d.top_node_p; {set pointer to top level voxel}
vstack[0].parent_p := addr(d.top_node_p); {init parent pointer of top level voxel}
level := 0; {init to we are at top level voxel}
{
* Voxel loop. Come back here for each new voxel to check. ICOOR is set to
* an integer coordinate inside the next voxel. LEVEL is set to the level of
* the previous voxel, and is also the index for the current voxel into VSTACK,
* COOR_MASKS, PICK_MASKS, and COOR_STEP.
*
}
new_coor: {jump back here to check voxel at each new coor}
for i := level-1 downto 1 do begin {scan back up the stack for new parent voxel}
if (icoor.x & coor_masks[i] = vstack[i].icoor.x) and
(icoor.y & coor_masks[i] = vstack[i].icoor.y) and
(icoor.z & coor_masks[i] = vstack[i].icoor.z)
then begin {new coordinate is within this voxel}
level := i; {indicate new current level}
goto got_start_level; {try scanning down from here}
end;
end; {try next parent voxel up the stack}
level := 0; {nothing matched, re-start at top voxel}
got_start_level:
{
* LEVEL indicates the lowest valid level in the voxel stack for the new
* coordinate. Now scan down to find the leaf node voxel for this coordinate.
}
vp := vstack[level].p; {init pointer to voxel at current level}
new_voxel: {jump back here after subdividing curr voxel}
while vp^.n_obj < 0 do begin {keep looping while not leaf node voxel}
j := pick_masks[level]; {get mask for picking child voxel index}
if j & icoor.x <> 0 {set I to index for proper child voxel}
then i := 1
else i := 0;
if j & icoor.y <> 0
then i := i+2;
if j & icoor.z <> 0
then i := i+4;
parent_p := addr(vp^.node_p[i]); {adr of pointer to new child voxel}
level := level + 1; {now one level further down in voxels}
vp := parent_p^; {make pointer to new current voxel}
coor_mask := coor_masks[level]; {set coordinate mask for current level}
vstack[level].icoor.x := icoor.x & coor_mask; {make coordinate of new voxel}
vstack[level].icoor.y := icoor.y & coor_mask;
vstack[level].icoor.z := icoor.z & coor_mask;
vstack[level].p := vp; {set pointer to new voxel}
vstack[level].parent_p := parent_p; {save adr of pointer to this voxel}
if vp = nil then begin {this child node does not exist or is empty ?}
vox_icoor := vstack[level].icoor; {set coordinate of current voxel}
goto next_coor; {find coordinate in next voxel along ray}
end;
end; {back and find next child voxel down}
vox_icoor := vstack[level].icoor; {set coordinate of current voxel}
{
* VP is pointing to the leaf node containing the coordinate in ICOOR. Check whether
* the voxel needs to be subdivided. If so, subdivide it and then jump back to
* NEW_VOXEL to find the voxel at the next level down.
}
leaf_node:
if level >= d.max_gen then goto trace_voxel; {already divided max allowed levels ?}
if level < d.min_gen then goto subdivide_voxel; {not deeper than min level ?}
if vp^.n_obj > (d.min_miss * 8) then goto subdivide_voxel; {too many obj in voxel ?}
if vp^.misses < d.min_miss then goto trace_voxel; {not enough rays missed here ?}
if vp^.hits >= (vp^.misses-d.min_miss)*3 {hit ratio is good enough ?}
then goto trace_voxel;
{
* This voxel needs to be subdivided.
}
subdivide_voxel:
if d.free_p = nil {check for available nodes on free list}
then begin {no nodes currently on free list}
if d.n_ar >= node_array_size then begin {this node array filled up ?}
sz := sizeof(d.ar_p^); {amount of memory to allocate}
util_mem_grab ( {allocate a new node array}
sz, ray_mem_p^, false, d.ar_p);
stats_oct.mem := stats_oct.mem + sz;
d.n_ar := 0; {new array starts out empty}
end;
d.n_ar := d.n_ar+1; {make index for new node}
newp := addr(d.ar_p^[d.n_ar]); {get address of new node}
end
else begin {there are nodes currently on the free list}
newp := d.free_p; {get pointer to a free node}
d.free_p := newp^.free_p; {remove this node from free chain}
end
; {NEWP points to new subdivided voxel node}
newp^.n_obj := -1; {indicate this is a subdivided node}
stats_oct.n_leaf := stats_oct.n_leaf - 1; {this leaf node becomes parent voxel}
stats_oct.n_parent := stats_oct.n_parent + 1;
{
* NEWP points to what will be the new node for this voxel. It has already been
* flagged as a subdivided node. The 8 child pointers need to be filled in.
* The box checks need to be performed before this can be done. Since the boxes
* share common coordinate values, these will be precomputed into array BOX_COOR.
* The box descriptor BOX will be all set up except for the box corner point.
* This will be put into the BOX_COOR array separately for each box.
}
r := {size of raw bounds box in octree space}
pick_masks[level]*box_radius_scale;
box.edge[1].width := r*d.size.x + d.box_err.x;
box.edge[2].width := r*d.size.y + d.box_err.y;
box.edge[3].width := r*d.size.z + d.box_err.z;
box.edge[1].edge.x := box.edge[1].width; {fill in box edge vectors}
box.edge[1].edge.y := 0.0;
box.edge[1].edge.z := 0.0;
box.edge[2].edge.x := 0.0;
box.edge[2].edge.y := box.edge[2].width;
box.edge[2].edge.z := 0.0;
box.edge[3].edge.x := 0.0;
box.edge[3].edge.y := 0.0;
box.edge[3].edge.z := box.edge[3].width;
box.edge[1].unorm.x := 1.0; {fill in box unit normal vectors}
box.edge[1].unorm.y := 0.0;
box.edge[1].unorm.z := 0.0;
box.edge[2].unorm.x := 0.0;
box.edge[2].unorm.y := 1.0;
box.edge[2].unorm.z := 0.0;
box.edge[3].unorm.x := 0.0;
box.edge[3].unorm.y := 0.0;
box.edge[3].unorm.z := 1.0;
box_coor[0].x :=
(vox_icoor.x * box_radius_scale * d.size.x) - d.box_err_half.x + d.origin.x;
box_coor[0].y :=
(vox_icoor.y * box_radius_scale * d.size.y) - d.box_err_half.y + d.origin.y;
box_coor[0].z :=
(vox_icoor.z * box_radius_scale * d.size.z) - d.box_err_half.z + d.origin.z;
box_coor[1].x := box_coor[0].x + box.edge[1].width - d.box_err.x;
box_coor[1].y := box_coor[0].y + box.edge[2].width - d.box_err.y;
box_coor[1].z := box_coor[0].z + box.edge[3].width - d.box_err.z;
for i := 0 to 7 do begin {once for each subordinate voxel to create}
box.point.x := box_coor[i&1].x; {fill in coordinate of box corner point}
box.point.y := box_coor[rshft(i, 1)&1].y;
box.point.z := box_coor[rshft(i, 2)&1].z;
vlnp := vp; {init pointer to current node in voxel list}
obj_pp := addr(vp^.obj_p[1]); {get pointer to first object pointer}
nleft := obj_per_leaf_node; {init number of pointers left for this node}
if d.free_p = nil {check for available nodes on free list}
then begin {no nodes currently on free list}
if d.n_ar >= node_array_size then begin {this node array filled up ?}
sz := sizeof(d.ar_p^); {amount of memory to allocate}
util_mem_grab ( {allocate a new node array}
sz, ray_mem_p^, false, d.ar_p);
stats_oct.mem := stats_oct.mem + sz;
d.n_ar := 0; {new array starts out empty}
end;
d.n_ar := d.n_ar+1; {make index for new node}
nnewp := addr(d.ar_p^[d.n_ar]); {get address of new node}
end
else begin {there are nodes currently on the free list}
nnewp := d.free_p; {get pointer to a free node}
d.free_p := nnewp^.free_p; {remove this node from free chain}
end
; {NNEWP points to new subdivided voxel node}
nnewp^.next_p := nil; {init to no data nodes chained on}
newp^.node_p[i] := nnewp; {set pointer to this child voxel}
n_new := 0; {init number of objects in child voxel}
new_pp := addr(nnewp^.obj_p[1]); {address of next object pointer to fill in}
new_left := obj_per_leaf_node; {obj pointers left to fill in this node}
for j := 1 to vp^.n_obj do begin {once for each object in this voxel}
if nleft <= 0 then begin {no more object pointers left this voxel ?}
vlnp := vlnp^.next_p; {point to next node in voxel data chain}
obj_pp := addr(vlnp^.ch_p[1]); {get address of first object pointer this node}
nleft := obj_per_data_node; {reset number of object pointers available}
end; {done switching to next data node}
obj_pp^^.class_p^.intersect_box^ ( {check object intersect with this voxel}
box, {box descriptor for this voxel}
obj_pp^^, {object to intersect box with}
here, {true if ray can bump into object here}
enclosed); {true if object completely encloses box}
if here then begin {object needs to be added to new voxel ?}
if new_left <= 0 then begin {no more object pointers left in this node ?}
if d.free_p = nil {check for available nodes on free list}
then begin {no nodes currently on free list}
if d.n_ar >= node_array_size then begin {this node array filled up ?}
sz := sizeof(d.ar_p^); {amount of memory to allocate}
util_mem_grab ( {allocate a new node array}
sz, ray_mem_p^, false, d.ar_p);
stats_oct.mem := stats_oct.mem + sz;
d.n_ar := 0; {new array starts out empty}
end;
d.n_ar := d.n_ar+1; {make index for new node}
nnewp^.next_p := addr(d.ar_p^[d.n_ar]); {get address of new node}
end
else begin {there are nodes currently on the free list}
nnewp^.next_p := d.free_p; {get pointer to a free node}
d.free_p := nnewp^.next_p^.free_p; {remove this node from free chain}
end
; {new node has been linked onto end of chain}
nnewp := nnewp^.next_p; {point NNEWP to newly allocated node}
nnewp^.next_p := nil; {indicate that this node is end of data chain}
new_pp := addr(nnewp^.ch_p[1]); {make address of next obj pointer to fill in}
new_left := obj_per_data_node; {init to all obj pointers available this node}
end; {done allocating a new node on chain}
new_pp^ := obj_pp^; {copy obj pointer into new voxel}
new_left := new_left-1; {one less obj pointer left this node}
new_pp := univ_ptr(integer32(new_pp)+sizeof(new_pp^)); {point to next slot}
n_new := n_new+1; {one more object in this child voxel}
end; {done handling object found in child voxel}
obj_pp := {make address of next object pointer this node}
univ_ptr(integer32(obj_pp)+sizeof(obj_pp^));
nleft := nleft-1; {one less obj left to read from this node}
end; {back and check next object in old parent voxel}
if n_new > 0 {check for object found in this child voxel}
then begin {the child voxel is not empty}
newp^.node_p[i]^.n_obj := n_new; {set number of objects in child voxel}
newp^.node_p[i]^.hits := 0; {init to no rays hit anything here}
newp^.node_p[i]^.misses := 0; {init to no rays missed anything here}
stats_oct.n_leaf := stats_oct.n_leaf + 1; {one more leaf node created}
end
else begin {the newly created child voxel is empty}
newp^.node_p[i]^.free_p := d.free_p; {put this node onto free chain}
d.free_p := newp^.node_p[i];
newp^.node_p[i] := nil; {indicate this child voxel is empty}
end
;
end; {back and do next child voxel}
{
* The voxel at VP has been subdivided. The subdivided voxel is at NEWP. Now put
* all the nodes of the voxel at VP on the free list, and link the new voxel into
* the structure in place of the old voxel.
}
vstack[level].parent_p^ := newp; {link new voxel into octree data structure}
vstack[level].p := newp;
while vp <> nil do begin {keep looping until end of data chain}
vlnp := vp^.next_p; {save pointer to next node in data chain}
vp^.free_p := d.free_p; {put node at VP onto free chain}
d.free_p := vp;
vp := vlnp; {point VP to next node in voxel}
end; {back do deallocate this new node}
vp := newp; {set the resulting subdivided voxel as current}
goto new_voxel; {back and process this new subdivided voxel}
{
* VP is pointing at a leaf node voxel that the ray is supposed to be traced
* thru.
}
trace_voxel: {jump here to trace ray thru voxel at VP}
obj_pp := addr(vp^.obj_p[1]); {init address of next object pointer}
vlnp := vp; {init current node pointer}
nleft := obj_per_leaf_node; {init number of obj pointers left this node}
for i := 1 to vp^.n_obj do begin {once for each object in this voxel}
if nleft <= 0 then begin {no more object pointers in this node ?}
vlnp := vlnp^.next_p; {make pointer to next node in chain}
obj_pp := addr(vlnp^.ch_p[1]); {make adr of first object pointer in new node}
nleft := obj_per_data_node; {init number of object pointers left this node}
end;
for j := 1 to n_cached do begin {check the cache of previous object checks}
if obj_pp^ = last_checks[j] then goto next_obj; {already checked this object ?}
end; {back and check next cached miss}
if obj_pp^^.class_p^.intersect_check^ ( {run object's intersect check routine}
ray, {the ray to intersect object with}
obj_pp^^, {the object to intersect ray with}
addr(parms), {run time specific parameters}
hit_info, {partial results returned}
shader) {returned shader}
then begin {the ray did hit the object}
ray.max_dist := hit_info.distance; {future hits must be closer than this one}
hit := true; {remember that the ray hit something}
new_mem := next_mem; {save MEM index after this hit data}
next_mem := old_mem; {restore mem index to before hit data}
vp^.hits := vp^.hits + 1; {one more ray/object hit in this voxel}
end
else begin {the ray did not hit the object}
vp^.misses := vp^.misses + 1; {one more ray/object miss in this voxel}
end
;
last_checks[next_cache] := obj_pp^; {save pointer to object we just checked}
next_cache := next_cache+1; {advance where to put next checked obj pointer}
if next_cache > cached_checks {wrap NEXT_CACHE back to 1}
then next_cache := 1;
if n_cached < cached_checks {LAST_CHECKS not full yet ?}
then n_cached := n_cached+1; {one more object in checked objects cache}
next_obj: {skip to here to test next object in voxel}
obj_pp := {make adr of next obj pointer in this node}
univ_ptr(integer32(obj_pp)+sizeof(obj_pp^));
nleft := nleft-1; {one less object pointer left in this node}
end; {back and process next object in this voxel}
{
* We are done with the current voxel pointed to by VP. Update point ICOOR to a
* coordinate inside the next voxel, and then jump back to NEW_COOR. COOR_MASK
* is set to the coordinate mask for the level of the current voxel. END_COOR
* is the ending coordinate of the ray within this octree. It is only valid
* if RAY_END is TRUE.
}
next_coor: {jump here to step to the next voxel}
if ray_ends or hit then begin {ray may end in this current voxel ?}
p1.x := orayp.x + v.x*ray.max_dist; {make ray end point in octree space}
p1.y := orayp.y + v.y*ray.max_dist;
p1.z := orayp.z + v.z*ray.max_dist;
if (p1.x >= mic) and (p1.x <= mac) and {ray ends within the octree ?}
(p1.y >= mic) and (p1.y <= mac) and
(p1.z >= mic) and (p1.z <= mac) then begin
icoor2.x := trunc(p1.x*int_scale); {integer octree ray end coordinate}
icoor2.y := trunc(p1.y*int_scale);
icoor2.z := trunc(p1.z*int_scale);
if (vox_icoor.x = icoor2.x & coor_mask) and {ray ends in the current voxel ?}
(vox_icoor.y = icoor2.y & coor_mask) and
(vox_icoor.z = icoor2.z & coor_mask) then begin
goto leave;
end; {done with ray ends in this voxel}
end; {done with ray ends within octree}
end; {done with checking ray end for termination}
icoor.x := icoor.x + coor_step[level].x; {advance by one current voxel size}
icoor.y := icoor.y + coor_step[level].y;
icoor.z := icoor.z + coor_step[level].z;
for i := level+1 to max_iter_level do begin {one iteration at each coordinate level}
icoor2.x := icoor.x - coor_step[i].x; {make small step backwards}
icoor2.y := icoor.y - coor_step[i].y;
icoor2.z := icoor.z - coor_step[i].z;
if (icoor2.x & coor_mask <> vox_icoor.x) or
(icoor2.y & coor_mask <> vox_icoor.y) or
(icoor2.z & coor_mask <> vox_icoor.z)
then begin {did not step back into source voxel ?}
icoor := icoor2; {update current coordinate}
end;
end; {back and try a step half as large}
if (icoor.x ! icoor.y ! icoor.z) & 16#F0000000 <> 0 then begin {outside octree ?}
goto leave; {no more voxels left to do}
end;
goto new_coor; {point P is new coordinate to find voxel at}
{
* The ray has ended, or we checked all the voxels in its path. Now return to the
* caller.
}
leave:
ray.max_dist := old_max_dist; {restore field we corrupted}
if hit {all done with ray, did we hit anything ?}
then begin {the ray hit something}
next_mem := new_mem; {set next mem after hit data for this hit}
type1_octree_intersect_check := true; {indicate we hit something}
return; {return with hit}
end
else begin {the ray hit nothing}
type1_octree_intersect_check := false; {indicate no hit for this ray}
return; {return with no hit}
end
;
{
* Jump here if the ray never intersected the outside box of the octree in the first
* place.
}
no_hit:
type1_octree_intersect_check := false; {indicate no hit}
end; {done with abbreviations}
end;
{
********************************************************************************
*
* Local subroutine TYPE1_OCTREE_INTERSECT_GEOM (HIT_INFO, FLAGS, GEOM_INFO)
*
* Return specific geometric information about a ray/object intersection
* in GEOM_INFO. In HIT_INFO are any useful results left by the ray/object
* intersection check calculation. FLAGS identifies what specific geometric
* information is being requested.
}
procedure type1_octree_intersect_geom ( {return detailed geometry of intersection}
in hit_info: ray_hit_info_t; {data saved by INTERSECT_CHECK}
in flags: ray_geom_flags_t; {bit mask list of what is being requested}
out geom_info: ray_geom_info_t); {filled in geometric info}
val_param;
begin
writeln ('Intersect geom entry point to OCTREE object called.');
sys_bomb;
end;
{
********************************************************************************
*
* Local subroutine TYPE1_OCTREE_INTERSECT_BOX (BOX, OBJECT, HERE, ENCLOSED)
*
* Find the intersection status between this object and a paralellpiped.
* HERE is returned as TRUE if the intersect check routine for this object could
* ever return TRUE for ray within the box volume. ENCLOSED is returned as true
* if the object completely encloses the box.
}
procedure type1_octree_intersect_box ( {find object/box intersection status}
in box: ray_box_t; {descriptor for a paralellpiped volume}
in object: ray_object_t; {object to intersect with the box}
out here: boolean; {TRUE if ISECT_CHECK could be true in box}
out enclosed: boolean); {TRUE if solid obj, and completely encloses box}
val_param;
begin
here := true;
enclosed := false;
end;
{
********************************************************************************
*
* Local subroutine TYPE1_OCTREE_ADD_CHILD (AGGR_OBJ, OBJECT)
*
* This call is illegal after we have already started subdividing the top node.
}
procedure type1_octree_add_child ( {Add child to this object}
in aggr_obj: ray_object_t; {the object to add child to}
var object: ray_object_t); {the object to add}
val_param;
var
data_p: oct_data_p_t; {pointer to internal object data}
ln_p: node_p_t; {pointer to initial last node in chain}
sz: sys_int_adr_t; {memory size}
begin
data_p := oct_data_p_t(aggr_obj.data_p); {make local pointer to our data}
with {set up abbreviations}
data_p^:d
do begin
{
* Abbreviations:
* D - Object data block
}
if d.last_left <= 0 then begin {no more room in current last node on chain ?}
ln_p := addr(d.ar_p^[d.n_ar]); {save adr of current last node in chain}
if d.n_ar >= node_array_size then begin {no more room in current nodes array ?}
sz := sizeof(d.ar_p^); {amount of memory to allocate}
util_mem_grab ( {allocate a new nodes array}
sz, ray_mem_p^, false, d.ar_p);
stats_oct.mem := stats_oct.mem + sz;
d.n_ar := 0; {init to no nodes allocated from new array}
end; {done handling nodes array overflow}
d.n_ar := d.n_ar+1; {allocate one more entry in nodes array}
ln_p^.next_p := addr(d.ar_p^[d.n_ar]); {link new entry onto end of chain}
ln_p^.next_p^.next_p := nil; {indicate new node is end of data chain}
d.next_p := addr(d.ar_p^[d.n_ar].ch_p[1]); {get adr of next obj pointer to fill in}
d.last_left := obj_per_data_node; {init num object pointers left in new node}
end;
d.next_p^ := addr(object); {put pointer to new object into data base}
d.next_p := univ_ptr(integer32(d.next_p)+sizeof(d.next_p^)); {point to next slot}
d.last_left := d.last_left-1; {one less object pointer left in curr node}
d.top_node_p^.n_obj := d.top_node_p^.n_obj+1; {one more object in the data base}
end; {done with D abbreviation}
end;
{
********************************************************************************
*
* Subroutine TYPE1_OCTREE_GEOM (ORIGIN, SIZE, OBJECT)
*
* This subroutine is an externally visible kluge to reset the octree outer
* geometry. It is used by RENDlib because it doesn't know the bounding box
* around the data until after all the ADD_CHILD operations.
}
procedure type1_octree_geom ( {back door to stomp on octree geometry}
in origin: vect_3d_t; {most negative corner for all 3 axies}
in size: vect_3d_t; {outer octree dimension for each axis}
in object: ray_object_t); {handle to specific octree object}
val_param;
var
data_p: oct_data_p_t; {pointer to data for this octree}
step_level: sys_int_machine_t; {voxel level of iteration step size}
box_err: real; {size of voxel intersect box size grow}
begin
data_p := oct_data_p_t(object.data_p); {get pointer to data for this octree}
data_p^.origin := origin; {save new octree geometry info}
data_p^.size := size;
{
* The caller's data has been saved. Some internal fields need to be
* re-computed based on the octree geometry.
}
data_p^.recip_size.x := 1.0/data_p^.size.x; {make reciprocal sizes}
data_p^.recip_size.y := 1.0/data_p^.size.y;
data_p^.recip_size.z := 1.0/data_p^.size.z;
step_level := {voxel level of iteration steps}
min(max_coor_level, data_p^.max_gen + iter_below_minvox);
box_err := {intersect box size increment in octree space}
1.0 / lshft(1, step_level);
data_p^.box_err.x := box_err * data_p^.size.x;
data_p^.box_err.y := box_err * data_p^.size.y;
data_p^.box_err.z := box_err * data_p^.size.z;
data_p^.box_err_half.x := data_p^.box_err.x / 2.0;
data_p^.box_err_half.y := data_p^.box_err.y / 2.0;
data_p^.box_err_half.z := data_p^.box_err.z / 2.0;
end;
{
********************************************************************************
*
* Subroutine TYPE1_OCTREE_CLASS_MAKE (CLASS)
*
* Fill in the routines block for this class of objects.
}
procedure type1_octree_class_make ( {fill in object class descriptor}
out class: ray_object_class_t); {block to fill in}
val_param;
begin
class.create := addr(type1_octree_create);
class.intersect_check := addr(type1_octree_intersect_check);
class.hit_geom := addr(type1_octree_intersect_geom);
class.intersect_box := addr(type1_octree_intersect_box);
class.add_child := addr(type1_octree_add_child);
end;
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.types.lazy;
interface
uses
SysUtils,
TypInfo;
const
ObjCastGUID: TGUID = '{CEDF24DE-80A4-447D-8C75-EB871DC121FD}';
type
ILazy<T: class> = interface(TFunc<T>)
['{D2646FB7-724B-44E4-AFCB-1FDD991DACB3}']
function IsValueCreated: Boolean;
property Value: T read Invoke;
end;
TLazy<T: class> = class(TInterfacedObject, ILazy<T>, IInterface)
private
FIsValueCreated: Boolean;
FValue: T;
FValueFactory: TFunc<T>;
procedure Initialize;
function Invoke: T;
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
public
constructor Create(ValueFactory: TFunc<T>);
destructor Destroy; override;
function IsValueCreated: Boolean;
property Value: T read Invoke;
end;
Lazy<T: class> = record
strict private
FLazy: ILazy<T>;
function GetValue: T;
public
class constructor Create;
property Value: T read GetValue;
class operator Implicit(const Value: Lazy<T>): ILazy<T>; overload;
class operator Implicit(const Value: Lazy<T>): T; overload;
class operator Implicit(const Value: TFunc<T>): Lazy<T>; overload;
end;
implementation
uses
ormbr.mapping.rttiutils;
{ TLazy<T> }
constructor TLazy<T>.Create(ValueFactory: TFunc<T>);
begin
FValueFactory := ValueFactory;
end;
destructor TLazy<T>.Destroy;
begin
if FIsValueCreated then
begin
if Assigned(FValue) then
FValue.Free;
end;
inherited;
end;
procedure TLazy<T>.Initialize;
begin
if not FIsValueCreated then
begin
FValue := FValueFactory();
FIsValueCreated := True;
end;
end;
function TLazy<T>.Invoke: T;
begin
Initialize();
Result := FValue;
end;
function TLazy<T>.IsValueCreated: Boolean;
begin
Result := FIsValueCreated;
end;
function TLazy<T>.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if IsEqualGUID(IID, ObjCastGUID) then
begin
Initialize;
end;
Result := inherited;
end;
{ Lazy<T> }
class constructor Lazy<T>.Create;
begin
TRttiSingleton.GetInstance.GetRttiType(TypeInfo(T));
end;
function Lazy<T>.GetValue: T;
begin
Result := FLazy();
end;
class operator Lazy<T>.Implicit(const Value: Lazy<T>): ILazy<T>;
begin
Result := Value.FLazy;
end;
class operator Lazy<T>.Implicit(const Value: Lazy<T>): T;
begin
Result := Value.Value;
end;
class operator Lazy<T>.Implicit(const Value: TFunc<T>): Lazy<T>;
begin
Result.FLazy := TLazy<T>.Create(Value);
end;
end.
|
unit PreferencesDlg;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TPreferences = class(TForm)
Ok: TButton;
Cancel: TButton;
EditorOptions: TGroupBox;
InsertMode: TCheckBox;
AutoIndentMode: TCheckBox;
SmartTab: TCheckBox;
BackspaceUnindent: TCheckBox;
BRIEFCursor: TCheckBox;
PersistentsBlocks: TCheckBox;
FindTextAtCursor: TCheckBox;
UseSyntaxHighLight: TCheckBox;
procedure OkClick(Sender: TObject);
procedure CancelClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Preferences: TPreferences;
implementation
{$R *.DFM}
procedure TPreferences.OkClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TPreferences.CancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TPreferences.FormActivate(Sender: TObject);
begin
Ok.SetFocus;
end;
end.
|
unit LocalizationUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.MPlayer, Vcl.StdCtrls, Vcl.ComCtrls,
Vcl.Menus, Vcl.ExtCtrls, Vcl.Imaging.jpeg, Vcl.Buttons, Vcl.FileCtrl,
Vcl.WinXCtrls, mmsystem, ShellAPI, Vcl.Imaging.pngimage, Vcl.JumpList,
Vcl.WinXPickers, Vcl.TabNotBk, Vcl.ExtDlgs;
type
TLanguages = (ENG, RUS);
TLocalization = class(TObject)
procedure SetLanguage(Language: TLanguages);
procedure SelectLanguageForMessage(var Cap, Msg: string; RUS_CAP, RUS_MSG, ENG_CAP, ENG_MSG: string);
procedure SelectLanguageForCaption(var Msg: string; RUS_MSG, ENG_MSG: string);
end;
const
RUS_LNG = 'RUS';
ENG_LNG = 'ENG';
DAMAGED_FILE_RUS = 'Файл повреждён. Выберите другой файл!';
DAMAGED_FILE_ENG = 'The file is damaged. Please select another file!';
ERROR_CAP_RUS = 'Ошибка';
ERROR_CAP_ENG = 'Error';
TRACK_NOT_FOUND_RUS = 'Трек не найден в плейлисте';
TRACK_NOT_FOUND_ENG = 'Track not found in playlist';
SELECT_TRACK_ENG = 'Select track';
SELECT_TRACK_RUS = 'Выберите трек';
DEL_TRACK_QUEST_RUS = 'Вы действительно хотите удалить трек: ';
DEL_TRACK_QUEST_ENG = 'Do you really want to delete the track: ';
DEL_TRACK_CAP_RUS = 'Удалить трек';
DEL_TRACK_CAP_ENG = 'Delete track';
DEL_PLAYLIST_CAP_RUS = 'Удалить плейлист';
DEL_PLAYLIST_CAP_ENG = 'Delete playlist';
DEL_PLAYLIST_QUEST_RUS = 'Вы действительно хотите удалить плейлист: ';
DEL_PLAYLIST_QUEST_ENG = 'Are you sure you want to delete the playlist: ';
PLST_NOT_FOUND_RUS = 'Плейлист не найден';
PLST_NOT_FOUND_ENG = 'Playlist not found';
SELECT_FOLDER_TITLE_ENG = 'Select a playlist (folder)';
SELECT_FOLDER_TITLE_RUS = 'Выберите плейлист (папку)';
SELECT_PLAYLIST_ENG = 'Select a playlist';
SELECT_PLAYLIST_RUS = 'Выберите плейлист';
TRACKS_LBL_ENG = 'TRACKS: ';
TRACKS_LBL_RUS = 'ТРЕКОВ: ';
CHNG_SUCC_MSG_RUS = 'Изменения успешно сохранены';
CHNG_SUCC_MSG_ENG = 'Changes saved successfully';
SETTINGS_CAP_RUS = 'Настройки';
SETTINGS_CAP_ENG = 'Settings';
ERR_MSG_RUS = 'Ошибка доступа к файлу конфигураций, изменения сохранены не будут';
ERR_MSG_ENG = 'Configuration file access error, changes will not be saved';
ENT_PLST_NAME_RUS = 'Введите название плейлиста';
ENT_PLST_NAME_ENG = 'Enter playlist title';
var
Localization: TLocalization;
Language: TLanguages;
implementation
uses
MainUnit, CreatePlaylistUnit, RenamePlaylistUnit, AboutUnit, SettingsUnit;
procedure TLocalization.SetLanguage(Language: TLanguages);
begin
if Language = ENG then
begin
with SettingsForm do
begin
Caption := 'Settings';
SettingsLabel.Caption := 'SETTINGS';
LngLabel.Caption := 'Language';
AboutButton.Caption := 'About program';
SaveSettingsButton.Caption := 'Save settings';
end;
with MainForm do
begin
PlaylistLabel.Caption := 'PLAYLISTS';
NowPlayLabel.Caption := 'Now play:';
RepeatButton.Hint := 'Loop track';
MuteButton.Hint := 'Mute sound';
ShowPlaylistsButton.Hint := 'Show playlists';
SettingsButton.Hint := 'Settings';
CreatePlaylistButton.Hint := 'Create playlist';
AddPlaylistButton.Hint := 'Add playlist';
DeletePlaylistButton.Hint := 'Delete playlist';
UpdatePlaylistsButton.Hint := 'Update playlists';
ShowPlstsInExpButton.Hint := 'Open playlists in explorer';
BackButton.Hint := 'Back';
AddMusicButton.Hint := 'Add track';
DeleteMusicButton.Hint := 'Delete track';
UpdateTracksButton.Hint := 'Update tracks';
ShowCurrPlstInExpButton.Hint := 'Open playlist in explorer';
RenamePlaylistButton.Hint := 'Rename';
ChangeCoverButton.Hint := 'Change cover';
AddMusicDialog.Title := 'Add track';
AddPlaylistDialog.Title := 'Add playlist';
OpenPictureDialog.Title := 'Change cover';
end;
with CreatePlaylistForm do
begin
OpenPictureDialog.Title := 'Select cover';
AddMusicDialog.Title := 'Add track';
Caption := 'Create playlist';
NameLabel.Caption := 'Name';
CoverLabel.Caption := 'Cover';
TracksLabel.Caption := 'Tracks';
AddMusicButton.Hint := 'Add track';
DeleteButton.Hint := 'Delete track';
LoadButton.Caption := 'Load';
CreateButton.Caption := 'Create';
CancelButton.Caption := 'Cancel';
end;
with RenamePlaylistForm do
begin
Caption := 'Rename';
NameLabel.Caption := 'Enter the name';
SaveButton.Caption := 'Save';
CancelButton.Caption := 'Cancel';
end;
end
else
begin
with SettingsForm do
begin
Caption := 'Настройки';
SettingsLabel.Caption := 'НАСТРОЙКИ';
LngLabel.Caption := 'Язык';
AboutButton.Caption := 'О программе';
SaveSettingsButton.Caption := 'Сохранить настройки';
end;
with MainForm do
begin
PlaylistLabel.Caption := 'ПЛЕЙЛИСТЫ';
NowPlayLabel.Caption := 'Сейчас играет:';
RepeatButton.Hint := 'Зациклить трек';
MuteButton.Hint := 'Без звука';
ShowPlaylistsButton.Hint := 'Показать плейлисты';
SettingsButton.Hint := 'Настройки';
CreatePlaylistButton.Hint := 'Создать плейлист';
AddPlaylistButton.Hint := 'Добавить плейлист';
DeletePlaylistButton.Hint := 'Удалить плейлист';
UpdatePlaylistsButton.Hint := 'Обновить плейлисты';
ShowPlstsInExpButton.Hint := 'Открыть плейлисты в проводнике';
BackButton.Hint := 'Назад';
AddMusicButton.Hint := 'Добавить трек';
DeleteMusicButton.Hint := 'Удалить трек';
UpdateTracksButton.Hint := 'Обновить треки';
ShowCurrPlstInExpButton.Hint := 'Открыть плейлист в проводнике';
RenamePlaylistButton.Hint := 'Переименовать';
ChangeCoverButton.Hint := 'Сменить обложку';
AddMusicDialog.Title := 'Добавить трек';
AddPlaylistDialog.Title := 'Добавить плейлист';
OpenPictureDialog.Title := 'Сменить обложку';
end;
with CreatePlaylistForm do
begin
OpenPictureDialog.Title := 'Выбрать обложку';
AddMusicDialog.Title := 'Добавить трек';
Caption := 'Создать плейлист';
NameLabel.Caption := 'Название плейлиста';
CoverLabel.Caption := 'Обложка';
TracksLabel.Caption := 'Треки';
AddMusicButton.Hint := 'Добавить трек';
DeleteButton.Hint := 'Удалить трек';
LoadButton.Caption := 'Загрузить';
CreateButton.Caption := 'Создать';
CancelButton.Caption := 'Отмена';
end;
with RenamePlaylistForm do
begin
Caption := 'Переименовать';
NameLabel.Caption := 'Введите название';
SaveButton.Caption := 'Сохранить';
CancelButton.Caption := 'Отмена';
end;
end;
end;
procedure TLocalization.SelectLanguageForMessage(var Cap, Msg: string; RUS_CAP, RUS_MSG, ENG_CAP, ENG_MSG: string);
begin
if Language = ENG then
begin
Cap := ENG_CAP;
Msg := ENG_MSG;
end
else
begin
Cap := RUS_CAP;
Msg := RUS_MSG;
end;
end;
procedure TLocalization.SelectLanguageForCaption(var Msg: string; RUS_MSG, ENG_MSG: string);
begin
if Language = ENG then
begin
Msg := ENG_MSG;
end
else
begin
Msg := RUS_MSG;
end;
end;
end.
|
unit StrViewForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TfrmStringView = class(TForm)
mmoStr: TMemo;
private
procedure SetText(const Value: string);
function GetText: string;
{ Private declarations }
public
{ Public declarations }
property Text: string read GetText write SetText;
end;
var
frmStringView: TfrmStringView;
implementation
{$R *.dfm}
{ TfrmStringView }
function TfrmStringView.GetText: string;
begin
Result := mmoStr.Text;
end;
procedure TfrmStringView.SetText(const Value: string);
begin
mmoStr.text := Value;
end;
end.
|
{$include kode.inc}
unit kode_widget_image_knob;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_canvas,
kode_color,
//kode_const,
kode_flags,
kode_imagestrip,
//kode_math,
kode_rect,
kode_widget_value;
type
KWidget_ImageKnob = class(KWidget_Value)
protected
FImageStrip : KImageStrip;
public
constructor create(ARect:KRect; AValue:Single; AImageStrip:KImageStrip; AAlignment:LongWord=kwa_none);
procedure on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); override;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
//kode_debug,
kode_math,
kode_utils;
//----------
constructor KWidget_ImageKnob.create(ARect:KRect; AValue:Single; AImageStrip:KImageStrip; AAlignment:LongWord);
begin
inherited create(ARect,AValue,AAlignment);
FName := 'KWidget_ImageKnob';
//FValue := AValue;
FCursor := kmc_ArrowUpDown;
FImageStrip := AImageStrip;
end;
//----------
procedure KWidget_ImageKnob.on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0);
//var s : LongInt;
begin
//s := FRect.h div (3*2);
{ background }
//ACanvas.setFillColor(FBackColor);
//ACanvas.fillRect(FRect.x,FRect.y,FRect.x2,FRect.y2);
{ background arc }
FImageStrip.draw(ACanvas,FRect.x,FRect.y,FValue);
//inherited;
end;
//----------------------------------------------------------------------
end.
|
{
DBE Brasil é um Engine de Conexão simples e descomplicado for Delphi/Lazarus
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(DBEBr Framework)
@created(20 Jul 2016)
@author(Isaque Pinheiro <https://www.isaquepinheiro.com.br>)
}
unit dbebr.driver.ibexpress;
interface
uses
Classes,
DB,
Variants,
SysUtils,
IBScript,
IBCustomDataSet,
IBQuery,
IBDatabase,
// DBEBr
dbebr.driver.connection,
dbebr.factory.interfaces;
type
// Classe de conexão concreta com dbExpress
TDriverIBExpress = class(TDriverConnection)
protected
FConnection: TIBDatabase;
FSQLScript: TIBScript;
public
constructor Create(const AConnection: TComponent;
const ADriverName: TDriverName); override;
destructor Destroy; override;
procedure Connect; override;
procedure Disconnect; override;
procedure ExecuteDirect(const ASQL: string); overload; override;
procedure ExecuteDirect(const ASQL: string;
const AParams: TParams); overload; override;
procedure ExecuteScript(const ASQL: string); override;
procedure AddScript(const ASQL: string); override;
procedure ExecuteScripts; override;
function IsConnected: Boolean; override;
function InTransaction: Boolean; override;
function CreateQuery: IDBQuery; override;
function CreateResultSet(const ASQL: String): IDBResultSet; override;
function ExecuteSQL(const ASQL: string): IDBResultSet; override;
end;
TDriverQueryIBExpress = class(TDriverQuery)
private
FSQLQuery: TIBQuery;
protected
procedure SetCommandText(ACommandText: string); override;
function GetCommandText: string; override;
public
constructor Create(AConnection: TIBDatabase);
destructor Destroy; override;
procedure ExecuteDirect; override;
function ExecuteQuery: IDBResultSet; override;
end;
TDriverResultSetIBExpress = class(TDriverResultSet<TIBQuery>)
public
constructor Create(ADataSet: TIBQuery); override;
destructor Destroy; override;
function NotEof: Boolean; override;
function GetFieldValue(const AFieldName: string): Variant; overload; override;
function GetFieldValue(const AFieldIndex: Integer): Variant; overload; override;
function GetFieldType(const AFieldName: string): TFieldType; overload; override;
function GetField(const AFieldName: string): TField; override;
end;
implementation
{ TDriverIBExpress }
constructor TDriverIBExpress.Create(const AConnection: TComponent;
const ADriverName: TDriverName);
begin
inherited;
FConnection := AConnection as TIBDatabase;
FDriverName := ADriverName;
FSQLScript := TIBScript.Create(nil);
try
FSQLScript.Database := FConnection;
FSQLScript.Transaction := FConnection.DefaultTransaction;
except
on E: Exception do
begin
FSQLScript.Free;
raise Exception.Create(E.Message);
end;
end;
end;
destructor TDriverIBExpress.Destroy;
begin
FConnection := nil;
FSQLScript.Free;
inherited;
end;
procedure TDriverIBExpress.Disconnect;
begin
inherited;
FConnection.Connected := False;
end;
procedure TDriverIBExpress.ExecuteDirect(const ASQL: string);
begin
inherited;
ExecuteDirect(ASQL, nil);
end;
procedure TDriverIBExpress.ExecuteDirect(const ASQL: string; const AParams: TParams);
var
LExeSQL: TIBQuery;
LFor: Integer;
begin
inherited;
LExeSQL := TIBQuery.Create(nil);
try
LExeSQL.Database := FConnection;
LExeSQL.Transaction := FConnection.DefaultTransaction;
LExeSQL.SQL.Text := ASQL;
if AParams <> nil then
begin
for LFor := 0 to AParams.Count - 1 do
begin
LExeSQL.ParamByName(AParams[LFor].Name).DataType := AParams[LFor].DataType;
LExeSQL.ParamByName(AParams[LFor].Name).Value := AParams[LFor].Value;
end;
end;
LExeSQL.ExecSQL;
finally
LExeSQL.Free;
end;
end;
procedure TDriverIBExpress.ExecuteScript(const ASQL: string);
begin
inherited;
FSQLScript.Script.Text := ASQL;
FSQLScript.ExecuteScript;
end;
procedure TDriverIBExpress.ExecuteScripts;
begin
inherited;
try
FSQLScript.ExecuteScript;
finally
FSQLScript.Script.Clear;
end;
end;
function TDriverIBExpress.ExecuteSQL(const ASQL: string): IDBResultSet;
var
LDBQuery: IDBQuery;
begin
inherited;
LDBQuery := TDriverQueryIBExpress.Create(FConnection);
LDBQuery.CommandText := ASQL;
Result := LDBQuery.ExecuteQuery;
end;
procedure TDriverIBExpress.AddScript(const ASQL: string);
begin
inherited;
FSQLScript.Script.Add(ASQL);
end;
procedure TDriverIBExpress.Connect;
begin
inherited;
FConnection.Connected := True;
end;
function TDriverIBExpress.InTransaction: Boolean;
begin
inherited;
Result := FConnection.DefaultTransaction.InTransaction;
end;
function TDriverIBExpress.IsConnected: Boolean;
begin
inherited;
Result := FConnection.Connected;
end;
function TDriverIBExpress.CreateQuery: IDBQuery;
begin
Result := TDriverQueryIBExpress.Create(FConnection);
end;
function TDriverIBExpress.CreateResultSet(const ASQL: String): IDBResultSet;
var
LDBQuery: IDBQuery;
begin
LDBQuery := TDriverQueryIBExpress.Create(FConnection);
LDBQuery.CommandText := ASQL;
Result := LDBQuery.ExecuteQuery;
end;
{ TDriverDBExpressQuery }
constructor TDriverQueryIBExpress.Create(AConnection: TIBDatabase);
begin
if AConnection = nil then
Exit;
FSQLQuery := TIBQuery.Create(nil);
try
FSQLQuery.Database := AConnection;
FSQLQuery.Transaction := AConnection.DefaultTransaction;
FSQLQuery.UniDirectional := True;
except
on E: Exception do
begin
FSQLQuery.Free;
raise Exception.Create(E.Message);
end;
end;
end;
destructor TDriverQueryIBExpress.Destroy;
begin
FSQLQuery.Free;
inherited;
end;
function TDriverQueryIBExpress.ExecuteQuery: IDBResultSet;
var
LResultSet: TIBQuery;
LFor: Integer;
begin
LResultSet := TIBQuery.Create(nil);
try
LResultSet.Database := FSQLQuery.Database;
LResultSet.Transaction := FSQLQuery.Transaction;
LResultSet.UniDirectional := True;
LResultSet.SQL.Text := FSQLQuery.SQL.Text;
for LFor := 0 to FSQLQuery.Params.Count - 1 do
begin
LResultSet.Params[LFor].DataType := FSQLQuery.Params[LFor].DataType;
LResultSet.Params[LFor].Value := FSQLQuery.Params[LFor].Value;
end;
LResultSet.Open;
except
on E: Exception do
begin
LResultSet.Free;
raise Exception.Create(E.Message);
end;
end;
Result := TDriverResultSetIBExpress.Create(LResultSet);
if LResultSet.RecordCount = 0 then
Result.FetchingAll := True;
end;
function TDriverQueryIBExpress.GetCommandText: string;
begin
Result := FSQLQuery.SQL.Text;
end;
procedure TDriverQueryIBExpress.SetCommandText(ACommandText: string);
begin
inherited;
FSQLQuery.SQL.Text := ACommandText;
end;
procedure TDriverQueryIBExpress.ExecuteDirect;
begin
FSQLQuery.ExecSQL;
end;
{ TDriverResultSetIBExpress }
constructor TDriverResultSetIBExpress.Create(ADataSet: TIBQuery);
begin
FDataSet := ADataSet;
inherited;
end;
destructor TDriverResultSetIBExpress.Destroy;
begin
FDataSet.Free;
inherited;
end;
function TDriverResultSetIBExpress.GetFieldValue(const AFieldName: string): Variant;
var
LField: TField;
begin
LField := FDataSet.FieldByName(AFieldName);
Result := GetFieldValue(LField.Index);
end;
function TDriverResultSetIBExpress.GetField(const AFieldName: string): TField;
begin
inherited;
Result := FDataSet.FieldByName(AFieldName);
end;
function TDriverResultSetIBExpress.GetFieldType(const AFieldName: string): TFieldType;
begin
Result := FDataSet.FieldByName(AFieldName).DataType;
end;
function TDriverResultSetIBExpress.GetFieldValue(const AFieldIndex: Integer): Variant;
begin
if AFieldIndex > FDataSet.FieldCount -1 then
Exit(Variants.Null);
if FDataSet.Fields[AFieldIndex].IsNull then
Result := Variants.Null
else
Result := FDataSet.Fields[AFieldIndex].Value;
end;
function TDriverResultSetIBExpress.NotEof: Boolean;
begin
if not FFirstNext then
FFirstNext := True
else
FDataSet.Next;
Result := not FDataSet.Eof;
end;
end. |
unit My_SelectDir;
interface
uses ShlObj, ActiveX, Windows, Forms;
function SelectDir(
Owner : THandle; //父窗口的句柄
const Title : string; //搜索标题
const RemText : string; //树形框上面的说明,支持#10
Root : string; //根目录,''为我的电脑,可以指定例如C:\之类的
var DefaultDir : string) //默认路径,也是接受路径
: boolean; //[OK]->True 否则false
implementation
uses Controls, Dialogs;
var OpenTitle : string;
procedure CenterWindow(phWnd:HWND);
var
hParentOrOwner : HWND;
rc, rc2 : Windows.TRect;
x,y : integer;
begin
hParentOrOwner:=GetParent(phWnd);
if (hParentOrOwner=HWND(nil)) then
SystemParametersInfo(SPI_GETWORKAREA, 0, @rc, 0)
else
Windows.GetClientRect(hParentOrOwner, rc);
GetWindowRect(phWnd, rc2);
x:=((rc.Right-rc.Left) - (rc2.Right-rc2.Left)) div 2 + rc.Left;
y:=((rc.Bottom-rc.Top) - (rc2.Bottom-rc2.Top)) div 2 + rc.Top;
SetWindowPos(phWnd, HWND_TOP, x, y , 0, 0, SWP_NOSIZE);
end;
function BrowseProc(
hWin : THandle;
uMsg : Cardinal;
lParam : LPARAM;
lpData : LPARAM) : LRESULT; stdcall;
begin
if (uMsg = BFFM_INITIALIZED) then
begin
SendMessage(hWin, BFFM_SETSELECTION, 1, lpData); //用传过来的参数作默认路径
SetWindowText(hWin, PChar(OpenTitle));
CenterWindow(hWin);
end;
Result := 0;
end;
function SelectPath(
Owner : THandle;
const Title : string;
const RemText : string;
Root : string;
DefaultDir : PChar) : string;
var
bi : TBrowseInfo; //uses ShlObj
IdList,RootItemIDList : PItemIDList;
IDesktopFolder : IShellFolder;
Eaten,Flags : LongWord;
begin
result := '';
FillChar(bi, SizeOf(bi), 0);
bi.hwndOwner := Owner;
OpenTitle := Title;
bi.lpszTitle := PChar(RemText);
bi.ulFlags := BIF_RETURNONLYFSDIRS OR BIF_NEWDIALOGSTYLE;//BIF_NEWDIALOGSTYLE,显示"新建文件夹"按钮
bi.lpfn := @BrowseProc;
bi.lParam := longint(defaultDir); //重点是增加了这个
//设置起始路径
if Root<>'' then
begin
SHGetDesktopFolder(IDesktopFolder);
IDesktopFolder.ParseDisplayName(Application.Handle, nil,
POleStr(WideString(Root)), Eaten, RootItemIDList, Flags);//uses ActiveX
bi.pidlRoot:=RootItemIDList;
end;
IdList := SHBrowseForFolder(bi);
if IdList<>nil then
begin
SetLength(result, 255);
SHGetPathFromIDList(IdList, PChar(result));
result := string(pchar(result));
// if result<>'' then
// if result[Length(result)] <>'\' then
// result := result + '\';
end;
end;
function SelectDir(
Owner : THandle;
const Title : string;
const RemText : string;
Root : string;
var DefaultDir : string) : boolean;
var
s : string;
begin
s:=DefaultDir;
s:=SelectPath(Owner, Title, RemText, Root, PChar(s));
if (s<>'') then
begin
if (s=DefaultDir) then
Result:=false
else
begin
DefaultDir:=s;
Result:=true;
end;
end
else
Result:=false;
end;
end.
|
unit Options;
interface
uses
Classes, SysUtils, PxCommandLine, PxSettings;
type
TOptions = class (TPxCommandLineParser)
private
function GetHelp: Boolean;
function GetQuiet: Boolean;
function GetDatabase: String;
function GetIdForUpperCase: Integer;
function GetIdForLowerCase: Integer;
protected
class procedure Initialize;
class procedure Shutdown;
procedure CreateOptions; override;
procedure AfterParseOptions; override;
public
class function Instance: TOptions;
property Help: Boolean read GetHelp;
property Quiet: Boolean read GetQuiet;
property Database: String read GetDatabase;
property IdForUpperCase: Integer read GetIdForUpperCase;
property IdForLowerCase: Integer read GetIdForLowerCase;
end;
implementation
{ TOptions }
var
_Instance: TOptions = nil;
{ Private declarations }
function TOptions.GetHelp: Boolean;
begin
Result := ByName['help'].Value;
end;
function TOptions.GetQuiet: Boolean;
begin
Result := ByName['quiet'].Value;
end;
function TOptions.GetDatabase: String;
begin
Result := ByName['database'].Value;
end;
function TOptions.GetIdForUpperCase: Integer;
begin
Result := ByName['uppercase-id'].Value;
end;
function TOptions.GetIdForLowerCase: Integer;
begin
Result := ByName['lowercase-id'].Value;
end;
{ Protected declarations }
class procedure TOptions.Initialize;
begin
_Instance := TOptions.Create;
_Instance.ParseOptions;
end;
class procedure TOptions.Shutdown;
begin
FreeAndNil(_Instance);
end;
procedure TOptions.CreateOptions;
begin
with AddOption(TPxBoolOption.Create('h', 'help')) do
Explanation := 'Show help';
with AddOption(TPxBoolOption.Create('q', 'quiet')) do
Explanation := 'Be quiet';
with AddOption(TPxStringOption.Create('d', 'database')) do
begin
Value := IniFile.ReadString('settings', LongForm, '127.0.0.1:RTMGR');
Explanation := Format('Database to connect to (default: %s)', [Value]);
end;
with AddOption(TPxIntegerOption.Create('l', 'lowercase-id')) do
begin
Value := IniFile.ReadInteger('settings', LongForm, 10001);
Explanation := Format('Area id for lowercase street names (default: %s)', [Value]);
end;
with AddOption(TPxIntegerOption.Create('u', 'uppercase-id')) do
begin
Value := IniFile.ReadInteger('settings', LongForm, 10002);
Explanation := Format('Area id for uppercase street names (default: %s)', [Value]);
end;
end;
procedure TOptions.AfterParseOptions;
begin
if not Quiet then
begin
Writeln(Format('%s - assign street names according to name character case', [ExtractFileName(ParamStr(0))]));
Writeln;
end;
if Help then
begin
WriteExplanations;
Halt(0);
end;
end;
{ Public declarations }
class function TOptions.Instance: TOptions;
begin
Result := _Instance;
end;
initialization
TOptions.Initialize;
end.
|
unit CommonStepForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ExtCtrls, CalculationLoggerFrame, Registrator,
ToolWin, ActnList, CalculationLogger;
type
TOnCheckOwnerState = procedure (var IsThreadFinished: boolean; var FinishingState: string) of object;
TfrmStep = class(TForm)
frmCalculationLogger: TfrmCalculationLogger;
actnStepForm: TActionList;
actnHide: TAction;
pnlStep: TPanel;
tlbr: TToolBar;
sbtnHide: TToolButton;
prg: TProgressBar;
prgSub: TProgressBar;
lblStep: TStaticText;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure actnHideUpdate(Sender: TObject);
procedure actnHideExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
FRegistrator: TRegistrator;
FShowLog: boolean;
FOnCheckOwnerState: TOnCheckOwnerState;
FShowSubPrg: boolean;
procedure SetRegistrator(const Value: TRegistrator);
procedure StepAdded(Sender: TObject; StepCount: integer; ItemState: TItemState);
procedure SetShowLog(const Value: boolean);
procedure SetShowSubPrg(const Value: boolean);
public
{ Public declarations }
property OnCheckOwnerState: TOnCheckOwnerState read FOnCheckOwnerState write FOnCheckOwnerState;
function CheckOwnerState: boolean;
property Registrator: TRegistrator read FRegistrator write SetRegistrator;
procedure InitProgress(AMin, AMax, AStep: integer);
procedure MakeStep(AStepName: string);
procedure MakeSubStep(AStepName: string = '');
procedure InitSubProgress(AMin, AMax, AStep: integer);
procedure Clear;
property ShowLog: boolean read FShowLog write SetShowLog;
property ShowSubPrg: boolean read FShowSubPrg write SetShowSubPrg;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var frmStep: TfrmStep;
implementation
{$R *.dfm}
{ TfrmStep }
constructor TfrmStep.Create(AOwner: TComponent);
begin
inherited;
ShowLog := true;
frmCalculationLogger.OnAddItem := StepAdded;
end;
procedure TfrmStep.InitProgress(AMin, AMax, AStep: integer);
begin
prg.Min := AMin;
prg.Max := AMax;
prg.Step := AStep;
prg.Position := 0;
lblStep.Caption := '';
Update;
end;
procedure TfrmStep.MakeStep(AStepName: string);
begin
prg.StepIt;
lblStep.Caption := AStepName;
prg.Refresh;
lblStep.Refresh;
if ShowLog then
frmCalculationLogger.lwLog.AddItem(AStepName, nil);
Refresh;
end;
procedure TfrmStep.SetRegistrator(const Value: TRegistrator);
begin
if FRegistrator <> Value then
begin
FRegistrator := Value;
end;
end;
procedure TfrmStep.StepAdded(Sender: TObject; StepCount: integer; ItemState: TItemState);
begin
if ItemState = isError then prg.Max := prg.Max + 1;
if prg.Position < prg.Max then prg.StepIt;
Visible := true;
end;
procedure TfrmStep.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TfrmStep.Clear;
begin
prg.Position := 0;
frmCalculationLogger.Clear;
end;
procedure TfrmStep.SetShowLog(const Value: boolean);
begin
FShowLog := Value;
frmCalculationLogger.Visible := FShowLog;
tlbr.Visible := FShowLog;
Height := pnlStep.Height + 300 * ord(frmCalculationLogger.Visible) + 50;
end;
function TfrmStep.CheckOwnerState: boolean;
var s: string;
begin
Result := true;
if Assigned(FOnCheckOwnerState) then
begin
FOnCheckOwnerState(Result, s);
lblStep.Caption := s;
end;
end;
procedure TfrmStep.actnHideUpdate(Sender: TObject);
begin
actnHide.Enabled := CheckOwnerState;
end;
procedure TfrmStep.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := CheckOwnerState;
end;
destructor TfrmStep.Destroy;
begin
inherited;
end;
procedure TfrmStep.actnHideExecute(Sender: TObject);
begin
Hide;
end;
procedure TfrmStep.SetShowSubPrg(const Value: boolean);
begin
FShowSubPrg := Value;
prgSub.Visible := FShowSubPrg;
end;
procedure TfrmStep.InitSubProgress(AMin, AMax, AStep: integer);
begin
prgSub.Max := AMax;
prgSub.Min := AMin;
prgSub.Position := prgSub.Min;
prgSub.Step := AStep;
prgSub.Update;
prgSub.Visible := true;
end;
procedure TfrmStep.MakeSubStep(AStepName: string = '');
begin
prgSub.StepIt;
if AStepName <> '' then
lblStep.Caption := AStepName;
prgSub.Refresh;
Refresh;
end;
end.
|
unit AccessedMemory;
{$mode objfpc}{$H+}
interface
uses
windows, Classes, SysUtils, FileUtil, laz.VirtualTrees, Forms, Controls, Graphics,
Dialogs, StdCtrls, ExtCtrls, Menus, ComCtrls, genericHotkey, DBK32functions,
commonTypeDefs, newkernelhandler, betterControls,AvgLvlTree, Laz_AVL_Tree;
resourcestring
rsAMError = 'Error';
rsAMYouCantSaveAnEmptyList = 'You can''t save an empty list';
type
{ TfrmAccessedMemory }
TfrmAccessedMemory = class(TForm)
btnClearSmallSnapshot: TButton;
btnClearSmallSnapshot1: TButton;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Edit1: TEdit;
Edit2: TEdit;
famrImageList: TImageList;
Label1: TLabel;
lblLost: TLabel;
Label3: TLabel;
tReader: TTimer;
vsResults: TLazVirtualStringTree;
MenuItem4: TMenuItem;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
PopupMenu1: TPopupMenu;
SaveDialog1: TSaveDialog;
procedure btnClearSmallSnapshot1Click(Sender: TObject);
procedure btnClearSmallSnapshotClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Edit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Edit2KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ListView1Data(Sender: TObject; Item: TListItem);
procedure MenuItem2Click(Sender: TObject);
procedure MenuItem3Click(Sender: TObject);
procedure MenuItem4Click(Sender: TObject);
procedure startMonitor(sender: TObject);
procedure stopMonitor(sender: TObject);
procedure tReaderTimer(Sender: TObject);
procedure vsResultsDblClick(Sender: TObject);
procedure vsResultsExpanding(Sender: TBaseVirtualTree; Node: PVirtualNode;
var Allowed: Boolean);
procedure vsResultsGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: String);
private
{ private declarations }
startk, stopk: TKeyCombo;
hkStart: TGenericHotkey;
hkStop: TGenericHotkey;
results: TIndexedAVLTree;
watchinfo: PPSAPI_WS_WATCH_INFORMATION;
watchinfosize: dword;
flost: integer;
procedure setLost(count: integer);
property lost: integer read flost write setLost;
public
{ public declarations }
end;
var
frmAccessedMemory: TfrmAccessedMemory;
implementation
{$R *.lfm}
uses ProcessHandlerUnit, CEFuncProc, math, symbolhandler, MemoryBrowserFormUnit;
{ TfrmAccessedMemory }
type
TPListDescriptor=record
address: ptruint;
count: dword;
list: PUintPtr;
end;
PPListDescriptor=^TPListDescriptor;
procedure TfrmAccessedMemory.setLost(count: integer);
begin
flost:=count;
lbllost.caption:='Lost: '+inttostr(count);
if (flost<>0) and (lbllost.visible=false) then lbllost.visible:=true;
end;
function ResultCompare(Item1, Item2: Pointer): Integer;
begin
result:=CompareValue(PPListDescriptor(Item1)^.address, PPListDescriptor(Item2)^.address);
end;
procedure TfrmAccessedMemory.startMonitor(sender: TObject);
begin
{$ifdef windows}
if results=nil then
results:=TIndexedAVLTree.Create(@ResultCompare);
if InitializeProcessForWsWatch(processhandle) then
begin
EmptyWorkingSet(processhandle);
button3.enabled:=true;
tReader.enabled:=true;
end;
{$endif}
end;
procedure TfrmAccessedMemory.stopMonitor(sender: TObject);
begin
{$ifdef windows}
treader.enabled:=false;
tReaderTimer(treader);
{$endif}
end;
procedure TfrmAccessedMemory.tReaderTimer(Sender: TObject);
var
i,j: integer;
listcount: integer;
plist: PPListDescriptor;
found: boolean;
search: TPListDescriptor;
n: TAVLTreeNode;
begin
if watchinfo=nil then
begin
watchinfosize:=64*1024*1024;
getmem(watchinfo, watchinfosize);
end;
while GetWsChanges(processhandle, watchinfo, watchinfosize)=false do
begin
if getlasterror=ERROR_INSUFFICIENT_BUFFER then
begin
watchinfosize:=watchinfosize*2;
ReAllocMem(watchinfo, watchinfosize);
end
else
break;
end;
listcount:=watchinfosize div sizeof(PSAPI_WS_WATCH_INFORMATION);
for i:=0 to listcount-1 do
begin
if watchinfo[i].FaultingPc=0 then
begin
lost:=lost+watchinfo[i].FaultingVa;
break;
end;
watchinfo[i].FaultingVa:=watchinfo[i].FaultingVa and qword($fffffffffffff000);
search.address:=watchinfo[i].FaultingVa;
n:=results.Find(@search);
if n=nil then
begin
getmem(plist, sizeof(TPListDescriptor));
plist^.address:=watchinfo[i].FaultingVa and qword($fffffffffffff000);
plist^.Count:=1;
plist^.list:=getmem(sizeof(pointer));
plist^.list[0]:=watchinfo[i].FaultingPC;
results.Add(plist);
vsResults.AddChild(nil);
end
else
begin
found:=false;
plist:=n.Data;
for j:=0 to plist^.count-1 do
begin
if plist^.list[j]=watchinfo[i].FaultingPc then
begin
found:=true;
break;
end;
end;
if not found then
begin
inc(plist^.count);
ReAllocMem(plist^.list, plist^.count*sizeof(pointer));
plist^.list[plist^.count-1]:=watchinfo[i].FaultingPc;
end;
end;
end;
end;
procedure TfrmAccessedMemory.vsResultsDblClick(Sender: TObject);
begin
if vsResults.FocusedNode<>nil then
MemoryBrowser.disassemblerview.SelectedAddress:=symhandler.getAddressFromName(vsResults.Text[vsResults.FocusedNode,1]);
end;
procedure TfrmAccessedMemory.vsResultsExpanding(Sender: TBaseVirtualTree;
Node: PVirtualNode; var Allowed: Boolean);
var d: PPListDescriptor;
begin
if vsResults.GetNodeLevel(node)=0 then
begin
d:=results[Node^.index];
allowed:=d^.count>1;
vsResults.AddChild(node, nil);
end;
end;
procedure TfrmAccessedMemory.vsResultsGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: String);
var d: PPListDescriptor;
begin
if vsResults.GetNodeLevel(node)=0 then
begin
d:=results[Node^.index];
if column=0 then
celltext:=d^.address.ToHexString(8)
else
celltext:=symhandler.getNameFromAddress(d^.list[0]);
vsResults.HasChildren[node]:=d^.count>1;
end
else
begin
d:=results[vsResults.NodeParent[node]^.Index];
if column=0 then
celltext:=''
else
celltext:=symhandler.getNameFromAddress(d^.list[node^.Index+1]);
end;
end;
procedure TfrmAccessedMemory.FormCreate(Sender: TObject);
begin
LoadFormPosition(self);
end;
procedure TfrmAccessedMemory.FormDestroy(Sender: TObject);
begin
SaveFormPosition(self);
end;
procedure TfrmAccessedMemory.FormShow(Sender: TObject);
begin
btnClearSmallSnapshot.autosize:=true;
btnClearSmallSnapshot1.autosize:=true;
btnClearSmallSnapshot.autosize:=false;
btnClearSmallSnapshot1.autosize:=false;
btnClearSmallSnapshot.ClientHeight:=canvas.TextHeight(btnClearSmallSnapshot.caption)+3;
btnClearSmallSnapshot1.ClientHeight:=canvas.TextHeight(btnClearSmallSnapshot.caption)+3;
button2.autosize:=true;
button3.autosize:=true;
button2.autosize:=false;
button3.autosize:=false;
if button2.width>button3.width then button3.width:=button2.width else button2.width:=button3.width;
end;
procedure TfrmAccessedMemory.ListView1Data(Sender: TObject; Item: TListItem);
begin
end;
procedure TfrmAccessedMemory.MenuItem2Click(Sender: TObject);
begin
end;
procedure TfrmAccessedMemory.MenuItem3Click(Sender: TObject);
begin
end;
procedure TfrmAccessedMemory.MenuItem4Click(Sender: TObject);
begin
end;
procedure TfrmAccessedMemory.Button2Click(Sender: TObject);
begin
end;
procedure TfrmAccessedMemory.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var i: integer;
begin
if startk[4]=0 then
begin
for i:=0 to 4 do
if startk[i]=0 then
begin
startk[i]:=key;
break;
end else
if startk[i]=key then break;
end;
edit1.Text:=ConvertKeyComboToString(startk);
button1.visible:=true;
end;
procedure TfrmAccessedMemory.Edit2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var i: integer;
begin
if stopk[4]=0 then
begin
for i:=0 to 4 do
if stopk[i]=0 then
begin
stopk[i]:=key;
break;
end else
if startk[i]=key then break;
end;
edit2.Text:=ConvertKeyComboToString(stopk);
button2.visible:=true;
end;
procedure TfrmAccessedMemory.Button1Click(Sender: TObject);
begin
if hkstart<>nil then
freeandnil(hkstart);
if hkstop<>nil then
freeandnil(hkstop);
if startk[0]<>0 then
hkStart:=TGenericHotkey.create(@startMonitor, startk);
if stopk[0]<>0 then
hkStop:=TGenericHotkey.create(@stopMonitor, stopk);
end;
procedure TfrmAccessedMemory.btnClearSmallSnapshotClick(Sender: TObject);
begin
FillWord(startk, 5,0);
edit1.text:='';
edit1.SetFocus;
end;
procedure TfrmAccessedMemory.btnClearSmallSnapshot1Click(Sender: TObject);
begin
FillWord(stopk, 5,0);
edit2.text:='';
edit2.SetFocus;
end;
end.
|
{ Модуль, хранящий глобальные переменные, которые требуют доступа из всех модулей программы. }
Unit GlobalVars;
Interface
Uses
Types;
Const
GridSize = 240; //Константа, хранящая размер (в пикселях) стороны сетки.
Var
size: integer; //Размер игрового поля (size x size клеток).
MainState: GameState; //Основная переменная, хранящая все основные сведения о игровом процессе.
GrCrds: pnt; //Координаты левого верхнего края системы игровых полей.
ShipsMenuCrds: pnt; //Координаты меню выбора кораблей. */(Используется
curShip: integer; //Текущий выбранный корабль. */ при расстановке кораблей пользователем).
lastState: integer; //Предыдушее игровое состояние.
pause: boolean; //Флаг для выхода в главное меню из партии (True - пауза => отрисовка кнопок для подтверждения).
Implementation
end. |
namespace Sugar.Test;
interface
uses
Sugar,
Sugar.TestFramework;
type
UserSettingsTest = public class (Testcase)
var
Data: UserSettings := UserSettings.Default;
public
method TearDown; override;
method ReadString;
method ReadInteger;
method ReadBoolean;
method ReadDouble;
method WriteString;
method WriteInteger;
method WriteBoolean;
method WriteDouble;
method Clear;
method &Remove;
method Keys;
method &Default;
end;
implementation
method UserSettingsTest.TearDown;
begin
Data.Clear;
Data.Save;
end;
method UserSettingsTest.ReadString;
begin
Data.Write("String", "One");
var Actual := Data.Read("String", nil);
Assert.IsNotNull(Actual);
Assert.CheckString("One", Actual);
Assert.CheckString("Default", Data.Read("StringX", "Default"));
Data.Clear;
Assert.CheckString("Default", Data.Read("String", "Default"));
Assert.IsException(->Data.Read(nil, "Default"));
end;
method UserSettingsTest.ReadInteger;
begin
Data.Write("Integer", 42);
var Actual := Data.Read("Integer", -1);
Assert.CheckInt(42, Actual);
Assert.CheckInt(-1, Data.Read("IntegerX", -1));
Data.Clear;
Assert.CheckInt(-1, Data.Read("Integer", -1));
Assert.IsException(->Data.Read(nil, 1));
end;
method UserSettingsTest.ReadBoolean;
begin
Data.Write("Boolean", true);
Assert.CheckBool(true, Data.Read("Boolean", false));
Assert.CheckBool(true, Data.Read("BooleanX", true));
Data.Clear;
Assert.CheckBool(false, Data.Read("Boolean", false));
Assert.IsException(->Data.Read(nil, true));
end;
method UserSettingsTest.ReadDouble;
begin
Data.Write("Double", 4.2);
var Actual := Data.Read("Double", -1.0);
Assert.CheckDouble(4.2, Actual);
Assert.CheckDouble(-1, Data.Read("DoubleX", -1));
Data.Clear;
Assert.CheckDouble(-1, Data.Read("Double", -1));
Assert.IsException(->Data.Read(nil, 1.1));
end;
method UserSettingsTest.WriteString;
begin
Assert.CheckInt(0, length(Data.Keys));
Data.Write("String", "One");
Assert.CheckInt(1, length(Data.Keys));
Assert.CheckString("One", Data.Read("String", nil));
Data.Write("String", "Two"); //override
Assert.CheckInt(1, length(Data.Keys));
Assert.CheckString("Two", Data.Read("String", nil));
Assert.IsException(->Data.Write(nil, "One"));
end;
method UserSettingsTest.WriteInteger;
begin
Assert.CheckInt(0, length(Data.Keys));
Data.Write("Integer", 42);
Assert.CheckInt(1, length(Data.Keys));
Assert.CheckInt(42, Data.Read("Integer", -1));
Data.Write("Integer", 5);
Assert.CheckInt(1, length(Data.Keys));
Assert.CheckInt(5, Data.Read("Integer", -1));
Assert.IsException(->Data.Write(nil, 1));
end;
method UserSettingsTest.WriteBoolean;
begin
Assert.CheckInt(0, length(Data.Keys));
Data.Write("Boolean", true);
Assert.CheckInt(1, length(Data.Keys));
Assert.CheckBool(true, Data.Read("Boolean", false));
Data.Write("Boolean", false);
Assert.CheckInt(1, length(Data.Keys));
Assert.CheckBool(false, Data.Read("Boolean", true));
Assert.IsException(->Data.Write(nil, true));
end;
method UserSettingsTest.WriteDouble;
begin
Assert.CheckInt(0, length(Data.Keys));
Data.Write("Double", 4.2);
Assert.CheckInt(1, length(Data.Keys));
Assert.CheckDouble(4.2, Data.Read("Double", -1.0));
Data.Write("Double", 5.5);
Assert.CheckInt(1, length(Data.Keys));
Assert.CheckDouble(5.5, Data.Read("Double", -1.0));
Assert.IsException(->Data.Write(nil, 1.0));
end;
method UserSettingsTest.Clear;
begin
Assert.CheckInt(0, length(Data.Keys));
Data.Write("Boolean", true);
Assert.CheckInt(1, length(Data.Keys));
Data.Clear;
Assert.CheckInt(0, length(Data.Keys));
end;
method UserSettingsTest.&Remove;
begin
Assert.CheckInt(0, length(Data.Keys));
Data.Write("String", "One");
Assert.CheckInt(1, length(Data.Keys));
Data.Remove("String");
Assert.CheckInt(0, length(Data.Keys));
Data.Remove("A");
Assert.IsException(->Data.Remove(nil));
end;
method UserSettingsTest.Keys;
begin
var Expected := new Sugar.Collections.List<String>;
Expected.Add("String");
Expected.Add("Integer");
Expected.Add("Double");
Data.Write("String", "");
Data.Write("Integer", 0);
Data.Write("Double", 2.2);
var Actual := Data.Keys;
Assert.CheckInt(3, length(Actual));
for i: Integer := 0 to length(Actual) - 1 do
Assert.CheckBool(true, Expected.Contains(Actual[i]));
end;
method UserSettingsTest.&Default;
begin
Assert.IsNotNull(UserSettings.Default);
Assert.CheckInt(0, length(UserSettings.Default.Keys));
Assert.CheckInt(0, length(Data.Keys));
UserSettings.Default.Write("Boolean", true);
Assert.CheckInt(1, length(UserSettings.Default.Keys));
Assert.CheckInt(1, length(Data.Keys));
end;
end. |
/*
Código realizado por Pablo Bermejo
https://github.com/PabloAsekas/
*/
UNIT uGrafos;
INTERFACE
USES uElemTAD;
TYPE
tNodo: ^tNodo;
tipoNodo = RECORD
info: tElemento;
sig: tNodo;
peso: integer;
END;
tGrafo: ^tGrafo;
tipoGrafo = RECORD
info: tElemento;
adyacente: ^tNodo;
sig: tGrafo;
END;
PROCEDURE CrearGrafoVacio (VAR grafo: tGrafo);
PROCEDURE InsertarNodo (VAR grafo: tGrafo; e: tElemento);
PROCEDURE InsertarAdyacente (VAR grafo: tGrafo; e1, e2: tElemento; peso: integer);
FUNCTION BuscarNodo (grafo: tGrafo, e2: tElemento):boolean;
PROCEDURE ImprimirGrafo (grafo: tGrafo);
IMPLEMENTATION
PROCEDURE CrearGrafoVacio (VAR grafo: tGrafo);
BEGIN
grafo:=NIL;
END;
PROCEDURE InsertarNodo (VAR grafo: tGrafo; e: tElemento);
VAR
aux: tGrafo;
BEGIN
new (aux);
AsignarElemento (aux^.info, e);
aux^.adyacente:=NIL;
aux^.sig:=grafo;
grafo:=aux;
END;
PROCEDURE InsertarAdyacente (VAR grafo: tGrafo; e1, e2: tElemento; peso: integer);
VAR
aux: tGrafo;
aux2: tNodo;
BEGIN
IF NOT EsVacio (grafo) THEN
BEGIN
IF (BuscarNodo (grafo, e2)) THEN
BEGIN
aux:=grafo;
WHILE ((aux^.info <> e1) AND (aux^.sig <> NIL)) DO
aux:=aux^.sig;
IF (aux^.info = e) THEN
BEGIN
new (aux2);
AsignarElemento (aux2^.info, e2);
AsignarElemento (aux2^.peso, peso);
aux2^.sig:=aux^.adyacente;
aux^.adyacente:=aux2;
END;
END;
END;
END;
FUNCTION BuscarNodo (grafo: tGrafo, e2: tElemento):boolean;
BEGIN
WHILE ((grafo^.info <> e2) AND (grafo^.sig <> NIL)) DO
grafo:=grafo^.sig;
IF (grafo^.info = e2) THEN
BuscarNodo:=TRUE
ELSE
BuscarNodo:=FALSE;
END;
{tNodo: ^tNodo;
tipoNodo = RECORD
info: tElemento;
nodo: tNodo;
peso: integer;
END;
tGrafo: ^tGrafo;
tipoGrafo = RECORD
info: tElemento;
adyacente: ^tNodo;
sig: tGrafo;
END;}
PROCEDURE ImprimirGrafo (grafo: tGrafo);
BEGIN
IF EsVacio (grafo) THEN
WRITELN ('El grafo es vacio')
ELSE
BEGIN
WHILE (grafo <> NIL) DO
BEGIN
WRITELN ('Nodo ', grafo^.info);
WRITELN ('Adyacente');
WHILE (grafo^.adyacente <> NIL) DO
BEGIN
WRITELN ('-'. grafo^.adyacente^.info);
grafo^.adyacente:=grafo^.adyacente^.sig;
END;
grafo:=grafo^.sig;
END;
END;
END;
END.
|
{*******************************************************************************
作者: dmzn@163.com 2023-04-08
描述: 监控图片按规则存放
*******************************************************************************}
unit UFormMain;
interface
uses
System.SysUtils, System.Variants, System.Classes, Vcl.Forms, Winapi.Messages,
Winapi.Windows, UThreadPool, Vcl.Imaging.GIFImg, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore,
Vcl.ExtCtrls, System.ImageList, Vcl.ImgList, Vcl.Controls, cxImageList,
Vcl.Menus, Vcl.StdCtrls, cxLabel, Vcl.ComCtrls;
type
TfFormMain = class(TForm)
SBar1: TStatusBar;
wPage1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TrayIcon1: TTrayIcon;
PMenu1: TPopupMenu;
N1: TMenuItem;
Group1: TGroupBox;
Label3: TLabel;
Label4: TLabel;
EditFilter: TEdit;
cxImageList1: TcxImageList;
Image1: TImage;
LabelHint: TcxLabel;
GroupBox1: TGroupBox;
CheckAutoStart: TCheckBox;
CheckAutoMin: TCheckBox;
TimerDelay: TTimer;
EditDir: TButtonedEdit;
GroupBox2: TGroupBox;
Label2: TLabel;
EditDest: TButtonedEdit;
CheckAddID: TCheckBox;
N2: TMenuItem;
MenuStart: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TrayIcon1DblClick(Sender: TObject);
procedure TimerDelayTimer(Sender: TObject);
procedure EditDestRightButtonClick(Sender: TObject);
procedure EditDirRightButtonClick(Sender: TObject);
procedure MenuStartClick(Sender: TObject);
private
{ Private declarations }
FCanExit: Boolean;
{*关闭标记*}
FMonDir: string;
FMonFilter: string;
FMonDest: string;
FMonAddID: Boolean;
FMonDate: string;
{*监控参数*}
FMonitorID: Cardinal;
FMonitor: TThreadWorkerConfig;
procedure DoMonitInit(const nConfig: PThreadWorkerConfig;
const nThread: TThread);
procedure DoMonit(const nConfig: PThreadWorkerConfig;
const nThread: TThread);
procedure DoMonitFree(const nConfig: PThreadWorkerConfig;
const nThread: TThread);
{*目录监控*}
procedure WMSysCommand(var nMsg: TMessage);message WM_SYSCOMMAND;
{*消息处理*}
procedure DoFormConfig(const nLoad: Boolean);
{*界面配置*}
procedure ShowHint(const nHint: string);
{*提示信息*}
procedure CopyFiles(const nFiles: TStrings; const nDest: string);
{*复制文件*}
public
{ Public declarations }
end;
var
fFormMain: TfFormMain;
implementation
{$R *.dfm}
uses
System.IniFiles, System.Win.Registry, FileCtrl, ShlObj, ActiveX, ShellApi,
IdTCPClient, ULibFun, UManagerGroup;
resourcestring
sStart = '服务已启动';
sStop = '服务已停止';
procedure WriteLog(const nEvent: string);
begin
gMG.FLogManager.AddLog(TfFormMain, 'DirMonitor', nEvent);
end;
procedure TfFormMain.FormCreate(Sender: TObject);
var nStr: string;
nGif: TGIFImage;
begin
FCanExit := False;
wPage1.ActivePageIndex := 0;
gMG.FLogManager.StartService();
FMonitorID := 0;
gMG.FThreadPool.WorkerInit(FMonitor);
with FMonitor do
begin
FWorkerName := '目录状态监控';
FCallInterval := 0;
FCallMaxTake := 0;
FAutoDelete := False;
FOnInit.WorkEvent := DoMonitInit;
FOnWork.WorkEvent := DoMonit;
FOnFree.WorkEvent := DoMonitFree;
end;
ShowHint(sStop);
DoFormConfig(True);
//load config
nGif := nil;
nStr := TApplicationHelper.gPath + 'animate.gif';
if FileExists(nStr) then
try
nGif := TGIFImage.Create;
nGif.LoadFromFile(nStr);
nGif.Animate := True;
Image1.Picture.Assign(nGif);
finally
nGif.Free;
end;
end;
procedure TfFormMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if not FCanExit then
begin
Action := caNone;
Visible := False;
Exit;
end;
FCanExit := True;
//for debug
gMG.FThreadPool.WorkerDelete(Self);
gMG.FThreadPool.WorkerDelete(FMonitorID);
//clear threads
Action := caFree;
DoFormConfig(False);
end;
procedure TfFormMain.MenuStartClick(Sender: TObject);
begin
if FMonitorID < 1 then
begin
if not System.SysUtils.DirectoryExists(EditDir.Text) then
begin
TApplicationHelper.ShowDlg('监控目录不存在', '提示', Handle);
Exit;
end;
if not System.SysUtils.DirectoryExists(EditDest.Text) then
begin
TApplicationHelper.ShowDlg('存储目录不存在', '提示', Handle);
Exit;
end;
FMonDir := TApplicationHelper.RegularPath(EditDir.Text);
FMonDest := TApplicationHelper.RegularPath(EditDest.Text);
FMonFilter := EditFilter.Text;
FMonAddID := CheckAddID.Checked;
FMonitor.FDataInt[0] := 0;
FMonitorID := gMG.FThreadPool.WorkerAdd(@FMonitor);
//投递监控
ShowHint('');
MenuStart.Caption := '停止服务';
MenuStart.ImageIndex := 3;
end else
begin
FMonitor.FDataInt[0] := 10;
//set stop flag
gMG.FThreadPool.WorkerDelete(FMonitorID);
//停止监控
FMonitorID := 0;
ShowHint(sStop);
MenuStart.ImageIndex := 2;
MenuStart.Caption := '启动服务';
end;
end;
procedure TfFormMain.N1Click(Sender: TObject);
begin
FCanExit := True;
Close();
end;
procedure TfFormMain.WMSysCommand(var nMsg: TMessage);
begin
if nMsg.WParam = SC_ICON then
Visible := False
else DefWindowProc(Handle, nMsg.Msg, nMsg.WParam, nMsg.LParam);
end;
procedure TfFormMain.TimerDelayTimer(Sender: TObject);
begin
TimerDelay.Enabled := False;
Hide();
MenuStartClick(nil);
end;
procedure TfFormMain.TrayIcon1DblClick(Sender: TObject);
begin
if not Visible then
Visible := True;
//xxxxx
end;
procedure TfFormMain.DoFormConfig(const nLoad: Boolean);
const
cConfig = 'Config';
cAutoKey = 'Software\Microsoft\Windows\CurrentVersion\Run';
cAutoVal = 'Fihe_DirMonitor';
var nIni: TIniFile;
nReg: TRegistry;
begin
nIni := TIniFile.Create(TApplicationHelper.gFormConfig);
with nIni do
try
if nLoad then
begin
CheckAutoMin.Checked := ReadBool(cConfig, 'AutoMin', False);
if CheckAutoMin.Checked then
TimerDelay.Enabled := True;
//xxxxx
EditDir.Text := ReadString(cConfig, 'MonDir', '');
EditFilter.Text := ReadString(cConfig, 'MonFilter', 'Image*.jpg');
EditDest.Text := ReadString(cConfig, 'MonDest', '');
CheckAddID.Checked := ReadBool(cConfig, 'FileAddID', True);
end else
begin
if EditDir.Modified then
WriteString(cConfig, 'MonDir', EditDir.Text);
//xxxxx
if EditFilter.Modified then
WriteString(cConfig, 'MonFilter', EditFilter.Text);
//xxxxx
if EditDest.Modified then
WriteString(cConfig, 'MonDest', EditDest.Text);
//xxxxx
WriteBool(cConfig, 'FileAddID', CheckAddID.Checked);
WriteBool(cConfig, 'AutoMin', CheckAutoMin.Checked);
//other config
end;
finally
nIni.Free;
end;
nReg := TRegistry.Create;
try
nReg.RootKey := HKEY_CURRENT_USER;
if nLoad then
begin
if nReg.OpenKey(cAutoKey, False) then
CheckAutoStart.Checked := nReg.ValueExists(cAutoVal);
//xxxxx
end else
begin
if nReg.OpenKey(cAutoKey, True) then
if CheckAutoStart.Checked then
begin
if not nReg.ValueExists(cAutoVal) then
nReg.WriteString(cAutoVal, Application.ExeName);
//xxxxx
end else
begin
if nReg.ValueExists(cAutoVal) then
nReg.DeleteValue(cAutoVal);
//xxxxx
end;
end;
finally
nReg.Free;
end;
end;
//------------------------------------------------------------------------------
function SelectDirCB(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer stdcall;
begin
if (uMsg = BFFM_INITIALIZED) and (lpData <> 0) then
SendMessage(Wnd, BFFM_SETSELECTION, Integer(True), lpdata);
result := 0;
end;
function SelectDirectoryB(const ACaption: string; var ADirectory: string): Boolean;
var
BrowseInfo: TBrowseInfo;
Buffer: PChar;
ItemIDList: PItemIDList;
ShellMalloc: IMalloc;
begin
Result := False;
if not System.SysUtils.DirectoryExists(ADirectory) then
ADirectory := '';
//判断默认选择目录是否存在,不存在时置为空
FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
//填充BrowseInfo结构体
if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then
begin
//分配IMalloc大小为路径最大大小
Buffer := ShellMalloc.Alloc(MAX_PATH);
try
with BrowseInfo do
begin
hwndOwner := Application.Handle;
pidlRoot := nil;
pszDisplayName := Buffer;
//设置标题
lpszTitle := PChar(ACaption);
//设置标识
ulFlags := BIF_RETURNONLYFSDIRS or BIF_NEWDIALOGSTYLE;
//设置默认选择目录(通过回调函数SelectDirCB处理)
if ADirectory <> '' then
begin
lpfn := SelectDirCB;
lParam := Integer(PChar(ADirectory));
end;
end;
ItemIDList := ShBrowseForFolder(BrowseInfo);
//获取选择的路径
Result := ItemIDList <> nil;
if Result then
begin
ShGetPathFromIDList(ItemIDList, Buffer);
ShellMalloc.Free(ItemIDList);
ADirectory := Buffer;
end;
finally
ShellMalloc.Free(Buffer);
end;
end;
end;
procedure TfFormMain.EditDestRightButtonClick(Sender: TObject);
var nStr: string;
begin
nStr := EditDest.Text;
if SelectDirectoryB('存储到', nStr) then
begin
EditDest.Text := nStr;
EditDest.Modified := True;
end;
end;
procedure TfFormMain.EditDirRightButtonClick(Sender: TObject);
var nStr: string;
begin
nStr := EditDir.Text;
if SelectDirectoryB('监控目标', nStr) then
begin
EditDir.Text := nStr;
EditDir.Modified := True;
end;
end;
//------------------------------------------------------------------------------
procedure TfFormMain.ShowHint(const nHint: string);
begin
if nHint = '' then
begin
LabelHint.Visible := False;
Exit;
end;
with LabelHint do
begin
Visible := True;
Caption := nHint;
Left := Trunc((TabSheet1.Width - Width) / 2);
Top := Trunc((TabSheet1.Height - Height) / 2);
end;
end;
procedure TfFormMain.DoMonitInit(const nConfig: PThreadWorkerConfig;
const nThread: TThread);
begin
end;
procedure TfFormMain.DoMonitFree(const nConfig: PThreadWorkerConfig;
const nThread: TThread);
begin
end;
function FileTimeToStr(const nFT: TFileTime): string;
var nLocal: TFileTime;
nSys: TSystemTime;
begin
FileTimeToLocalFileTime(nFT, nLocal);
FileTimeToSystemTime(nLocal, nSys);
Result := TDateTimeHelper.DateTime2Str(SystemTimeToDateTime(nSys));
Result := StringReplace(Result, ':', '', [rfReplaceAll]);
Result := StringReplace(Result, ' ', '_', [rfReplaceAll]);
//date _ time
end;
function FileInUse(const nFile: TFileName): Boolean;
var nHwnd: HFILE;
nInt: Integer;
begin
Result := False;
if not FileExists(nFile) then Exit;
Sleep(100); //wait for completly
nInt := 1;
while nInt <= 3 do
begin
nHwnd := CreateFile(PChar(nFile), GENERIC_READ or GENERIC_WRITE, 0, nil,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
//try to open file
Result := (nHwnd = INVALID_HANDLE_VALUE);
if not Result then //file normal
begin
CloseHandle(nHwnd);
Break;
end;
Sleep(nInt * 200);
Inc(nInt);
end;
end;
procedure TfFormMain.DoMonit(const nConfig: PThreadWorkerConfig;
const nThread: TThread);
var nStr: string;
nHwnd: THandle;
nWait: DWORD;
nSr: TSearchRec;
nRes: Integer;
nFiles: TStrings;
begin
if FMonitor.FDataInt[0] = 10 then Exit;
//has stop flag
nHwnd := FindFirstChangeNotification(PChar(FMonDir), LongBool(1),
FILE_NOTIFY_CHANGE_FILE_NAME or FILE_NOTIFY_CHANGE_DIR_NAME);
//FILE_NOTIFY_CHANGE_LAST_WRITE or FILE_NOTIFY_CHANGE_CREATION);
//start monit
while True do
try
if FCanExit or TThreadRunner(nThread).Terminated or
(FMonitor.FDataInt[0] = 10) then Break;
//程序退出,线程结束,服务停止
nWait := WaitForSingleObject(nHwnd, 500);
if nWait <> WAIT_OBJECT_0 then Continue;
FindNextChangeNotification(nHwnd);
nFiles := nil;
try
nRes := FindFirst(FMonDir + FMonFilter, faAnyFile, nSr);
while nRes = 0 do
begin
if FileInUse(FMonDir + nSr.Name) then //invalid File
begin
nRes := FindNext(nSr);
Continue;
end;
if not Assigned(nFiles) then
nFiles := TStringList.Create;
//xxxxx
nFiles.AddPair(FMonDir + nSr.Name,
FileTimeToStr(nSr.FindData.ftCreationTime));
//file, create_time
nRes := FindNext(nSr);
end;
System.SysUtils.FindClose(nSr);
//close handle
if Assigned(nFiles) then
begin
FMonDate := TDateTimeHelper.Date2Str(Now());
nStr := FMonDest + FMonDate + '\';
if not System.SysUtils.DirectoryExists(nStr) then
System.SysUtils.ForceDirectories(nStr);
//new dir
if System.SysUtils.DirectoryExists(nStr) then
CopyFiles(nFiles, nStr) //do copy
else WriteLog('无法创建目录: ' + nStr);
end;
finally
nFiles.Free;
end;
except
on nErr: Exception do
begin
WriteLog(nErr.Message);
end;
end;
FindCloseChangeNotification(nHwnd);
//close handle
end;
procedure MakeFileID(const nDate: string; var nID: Integer);
const
cConfig = 'FileID';
var nIni: TIniFile;
begin
nIni := TIniFile.Create(TApplicationHelper.gFormConfig);
try
if nID < 1 then //read
begin
nID := nIni.ReadInteger(cConfig, nDate, 1);
if nID < 1 then
nID := 1;
//limit value
end else //write
begin
nIni.WriteInteger(cConfig, nDate, nID);
end;
finally
nIni.Free;
end;
end;
procedure TfFormMain.CopyFiles(const nFiles: TStrings; const nDest: string);
var nStr: string;
nIdx,nID: Integer;
nAction: TShFileOpStruct;
begin
nID := 0;
if FMonAddID then
MakeFileID(FMonDate, nID);
//xxxxx
for nIdx := nFiles.Count -1 downto 0 do
begin
if nID > 0 then
begin
nStr := IntToStr(nID);
nStr := StringOfChar('0', 3 - Length(nStr)) + nStr;
nStr := nDest + nFiles.ValueFromIndex[nIdx] + '_' + nStr;
Inc(nID);
end else
begin
nStr := nDest + nFiles.ValueFromIndex[nIdx];
end;
nStr := nStr + ExtractFileExt(nFiles.Names[nIdx]);
//full filename
FillChar(nAction, SizeOf(nAction), #0);
with nAction do
begin
Wnd := Handle;
wFunc := FO_MOVE;
pFrom := PChar(nFiles.Names[nIdx] + #0);
pTo := PChar(nStr + #0);
fFlags := FOF_NOCONFIRMATION or FOF_RENAMEONCOLLISION or
FOF_NOERRORUI or FOF_SILENT;
//不出现确认文件替换对话框
//有重复文件时自动重命名
//不出现错误对话框
//产生正在复制的对话框
end;
ShFileOperation(nAction);
//执行移动
end;
if nID > 0 then
MakeFileID(FMonDate, nID);
//write last
end;
end.
|
unit setbit_2;
interface
implementation
var
V: Int64;
procedure Test;
begin
setbit(V, 63, True);
end;
initialization
Test();
finalization
Assert(V = Low(Int64));
end. |
unit uLocationFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TLocationFrame = class(TFrame)
lblName: TLabel;
mmoDesc: TMemo;
btnDelete: TButton;
procedure btnDeleteClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
uses uDataModule;
procedure TLocationFrame.btnDeleteClick(Sender: TObject);
begin
if Application.MessageBox('Are you sure you want to delete this location?'
,'Warning!',mb_yesno + mb_iconquestion) = id_yes then
begin
DM.FDQuery.SQL.Clear;
DM.FDQuery.SQL.Add('DELETE FROM locations WHERE name = ' + QuotedStr(lblName.Caption));
DM.FDQuery.ExecSQL;
showmessage('Note deleted!');
FreeAndNil(Self);
end
else
showmessage('Process cancelled!');
end;
end.
|
unit xDataDictionary;
interface
uses xDBActionBase, System.Classes, System.SysUtils, FireDAC.Stan.Param, xFunction;
type
/// <summary>
/// 数据字典类
/// </summary>
TDataDictionary = class(TDBActionBase)
private
FDictionaries: TStringList;
function GetDictionary(sName: string): TStringList;
procedure SetDictionary(sName: string; const Value: TStringList);
public
constructor Create; override;
destructor Destroy; override;
/// <summary>
/// 数据字典列表
/// </summary>
property Dictionaries : TStringList read FDictionaries ;
/// <summary>
/// 数据字典的数据项
/// </summary>
/// <param name=" sName "> 数据项名称 </param>
property Dictionary[ sName : string ] : TStringList read GetDictionary write SetDictionary;
/// <summary>
/// 获取数据字典列表
/// </summary>
/// <returns>字典名称列表</returns>
procedure LoadFromDB;
/// <summary>
/// 保存数据字典列表
/// </summary>
procedure SaveToDB;
end;
var
DataDict : TDataDictionary;
implementation
{ TDataDictionary }
constructor TDataDictionary.Create;
begin
inherited;
FDictionaries := TStringList.Create;
try
LoadFromDB;
except
end;
end;
destructor TDataDictionary.Destroy;
begin
ClearStringList( FDictionaries );
FDictionaries.Free;
inherited;
end;
function TDataDictionary.GetDictionary(sName: string): TStringList;
var
nIndex : Integer;
begin
nIndex := FDictionaries.IndexOf( sName );
if nIndex < 0 then
begin
Result := TStringList.Create;
Dictionaries.AddObject( sName, Result );
end
else
Result := TStringList( FDictionaries.Objects[ nIndex ] );
end;
procedure TDataDictionary.LoadFromDB;
const
C_SEL = ' select * from UserDictionary order by DicSN ';
var
Items : TStringList;
begin
FQuery.SQL.Text := C_SEL;
try
FQuery.Open;
while not FQuery.Eof do
begin
Items := TStringList.Create;
Items.Text := FQuery.FieldByName( 'DicValue' ).AsString;
FDictionaries.AddObject( FQuery.FieldByName( 'DicName' ).AsString, Items );
FQuery.Next;
end;
FQuery.Close;
finally
end;
end;
procedure TDataDictionary.SaveToDB;
const
C_DEL = ' delete from UserDictionary ' ;
C_INS = ' insert into UserDictionary ( DicSN, DicName, DicValue )' +
' values ( :DicSN, :DicName, :DicValue ) ';
var
i : Integer;
begin
try
//清空表中记录
FQuery.SQL.Text := C_DEL;
ExecSQL;
// 插入新的数据
for i := 0 to FDictionaries.Count - 1 do
begin
FQuery.SQL.Text := C_INS;
with FQuery.Params, FDictionaries do
begin
ParamByName( 'DicSN' ).Value := i;
ParamByName( 'DicName' ).Value := Strings[ i ] ;
ParamByName( 'DicValue' ).Value := TStringList(
FDictionaries.Objects[ i ] ).Text;
end;
ExecSQL;
end;
finally
end;
end;
procedure TDataDictionary.SetDictionary(sName: string;
const Value: TStringList);
var
nIndex : Integer;
begin
// 数据项在字典中的位置
nIndex := FDictionaries.IndexOf( sName );
// 如果没有对应的数据,退出
if nIndex < 0 then
Exit;
// 给字典数据项赋值
TStringList( FDictionaries.Objects[ nIndex ] ).Text := Value.Text ;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{
GLFileNMF - NormalMapper loading into GLScene FreeForms/Actors
Notes:
NormalMapper can be found at http://www.ati.com/developer/tools.html
History:
20/05/2003 - SG - Fixed SaveToStream to use ExtractTriangles
16/05/2003 - SG - Creation
}
unit GLFileNMF;
interface
uses
System.Classes,
GLVectorFileObjects, GLVectorGeometry, GLVectorLists, GLApplicationFileIO,
FileNMF;
type
TGLNMFVectorFile = class (TVectorFile)
public
class function Capabilities : TDataFileCapabilities; override;
procedure LoadFromStream(aStream : TStream); override;
procedure SaveToStream(aStream : TStream); override;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLNMFVectorFile ------------------
// ------------------
// Capabilities
//
class function TGLNMFVectorFile.Capabilities : TDataFileCapabilities;
begin
Result:=[dfcRead, dfcWrite];
end;
// LoadFromStream
//
procedure TGLNMFVectorFile.LoadFromStream(aStream : TStream);
var
i,j : Integer;
mesh : TMeshObject;
nmf : TFileNMF;
begin
nmf:=TFileNMF.Create;
try
nmf.LoadFromStream(aStream);
mesh:=TMeshObject.CreateOwned(Owner.MeshObjects);
mesh.Mode:=momTriangles;
for i:=0 to nmf.NumTris-1 do begin
for j:=0 to 2 do begin
mesh.Vertices.Add(nmf.RawTriangles[i].vert[j]);
mesh.Normals.Add(nmf.RawTriangles[i].norm[j]);
mesh.TexCoords.Add(nmf.RawTriangles[i].texCoord[j]);
end;
end;
finally
nmf.Free;
end;
end;
// SaveToStream
//
procedure TGLNMFVectorFile.SaveToStream(aStream : TStream);
var
i,j : Integer;
nmf : TFileNMF;
Vertices,
TempVertices,
Normals,
TexCoords : TAffineVectorList;
begin
nmf:=TFileNMF.Create;
Vertices:=TAffineVectorList.Create;
Normals:=TAffineVectorList.Create;
TexCoords:=TAffineVectorList.Create;
try
for i:=0 to Owner.MeshObjects.Count-1 do begin
TempVertices:=Owner.MeshObjects[i].ExtractTriangles(TexCoords,Normals);
Vertices.Add(TempVertices);
TempVertices.Free;
end;
nmf.NumTris:=(Vertices.count div 3);
SetLength(nmf.RawTriangles,nmf.NumTris);
for i:=0 to nmf.NumTris-1 do begin
for j:=0 to 2 do begin
nmf.RawTriangles[i].vert[j]:=Vertices[3*i+j];
nmf.RawTriangles[i].norm[j]:=Normals[3*i+j];
nmf.RawTriangles[i].texCoord[j].S:=TexCoords[3*i+j].V[0];
nmf.RawTriangles[i].texCoord[j].T:=TexCoords[3*i+j].V[1];
end;
end;
nmf.SaveToStream(aStream);
finally
Vertices.Free;
Normals.Free;
TexCoords.Free;
nmf.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterVectorFileFormat('nmf', 'NormalMapper files', TGLNMFVectorFile);
end. |
unit Unit1;
interface
uses
System.SysUtils, System.Math,
Vcl.Forms, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.StdCtrls,
//GLS
GLScene, GLObjects, System.Classes, Vcl.Controls, Vcl.Dialogs, GLCadencer,
GLWin32Viewer, GLCrossPlatform, GLCoordinates, GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
TrackBar: TTrackBar;
Cube1: TGLCube;
Cube3: TGLCube;
Cube2: TGLCube;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
CBPlay: TCheckBox;
StaticText1: TStaticText;
GLCadencer1: TGLCadencer;
procedure TrackBarChange(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.TrackBarChange(Sender: TObject);
var
t : Integer;
begin
t:=TrackBar.Position;
// the "sun" turns slowly around Y axis
Cube1.TurnAngle:=t/4;
// "earth" rotates around the sun on the Y axis
with Cube2.Position do begin
X:=3*cos(DegToRad(t));
Z:=3*sin(DegToRad(t));
end;
// "moon" rotates around earth on the X axis
with Cube3.Position do begin
X:=Cube2.Position.X;
Y:=Cube2.Position.Y+1*cos(DegToRad(3*t));
Z:=Cube2.Position.Z+1*sin(DegToRad(3*t));
end;
// update FPS count
StaticText1.Caption:=IntToStr(Trunc(GLSceneViewer1.FramesPerSecond))+' FPS';
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
if CBPlay.Checked and Visible then begin
// simulate a user action on the trackbar...
TrackBar.Position:=((TrackBar.Position+1) mod 360);
end;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
GLSceneViewer1.ResetPerformanceMonitor;
end;
end.
|
unit TestBufferInterpreter.NVMe.Intel;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, Device.SMART.List, SysUtils,
BufferInterpreter, BufferInterpreter.NVMe.Intel;
type
// Test methods for class TIntelBufferInterpreter
TestTIntelBufferInterpreter = class(TTestCase)
strict private
FIntelBufferInterpreter: TIntelBufferInterpreter;
private
procedure CompareWithOriginalIdentify(
const ReturnValue: TIdentifyDeviceResult);
procedure CompareWithOriginalSMART(const ReturnValue: TSMARTValueList);
procedure CheckIDEquals(const Expected, Actual: TSMARTValueEntry;
const Msg: String);
procedure CompareWithOriginalIntelSMART(const ReturnValue: TSMARTValueList);
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestBufferToIdentifyDeviceResult;
procedure TestBufferToSMARTValueList;
procedure TestLargeBufferToIdentifyDeviceResult;
procedure TestLargeBufferToSMARTValueList;
procedure TestBufferToCapacityAndLBA;
procedure TestVendorSpecificSMARTValueList;
end;
const
Intel750IdentifyDevice: TSmallBuffer =
($86,$80,$86,$80,$43,$56,$43,$51,$35,$33,$30,$34,$30,$30,$41,$50,$34,$30,$30,$41
,$47,$4E,$20,$20,$49,$4E,$54,$45,$4C,$20,$53,$53,$44,$50,$45,$44,$4D,$57,$34,$30
,$30,$47,$34,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20
,$20,$20,$20,$20,$38,$45,$56,$31,$30,$31,$37,$34,$00,$E4,$D2,$5C,$00,$05,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$06,$00,$03,$03
,$02,$02,$3F,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00);
Intel750SMART: TSmallBuffer =
($00,$31,$01,$64,$0A,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$98,$04,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$8B,$1C,$02,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$E1,$88,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$75,$8A,$10,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$81,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$F8,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$2A,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00);
Intel750Capacity: TSmallBuffer =
($00,$00,$00,$00,$2E,$93,$90,$AF,$00,$00,$02,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00);
Intel750AdditionalSMART: TSmallBuffer =
($AB,$00,$00,$64,$00,$00,$00,$00,$00,$00,$00,$00
,$AC,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$AD,$00,$00,$00,$00,$01,$00,$05,$00,$03,$00,$00
,$B8,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$C7,$00,$00,$00,$00,$63,$00,$00,$00,$00,$00,$00
,$E2,$00,$00,$00,$00,$FF,$FF,$00,$00,$00,$00,$00
,$E3,$00,$00,$00,$00,$FF,$FF,$00,$00,$00,$00,$00
,$E4,$00,$00,$00,$00,$FF,$FF,$00,$00,$00,$00,$00
,$EA,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$F0,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$F3,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00
,$F4,$00,$00,$00,$00,$CA,$5B,$00,$00,$00,$00,$00
,$F5,$00,$00,$00,$00,$76,$08,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00);
implementation
procedure TestTIntelBufferInterpreter.SetUp;
begin
FIntelBufferInterpreter := TIntelBufferInterpreter.Create;
end;
procedure TestTIntelBufferInterpreter.TearDown;
begin
FIntelBufferInterpreter.Free;
FIntelBufferInterpreter := nil;
end;
procedure TestTIntelBufferInterpreter.TestBufferToIdentifyDeviceResult;
var
ReturnValue: TIdentifyDeviceResult;
Buffer: TSmallBuffer;
begin
StartExpectingException(ESmallBufferException);
ReturnValue := FIntelBufferInterpreter.BufferToIdentifyDeviceResult(Buffer);
StopExpectingException;
end;
procedure TestTIntelBufferInterpreter.TestBufferToSMARTValueList;
var
Buffer: TSmallBuffer;
begin
StartExpectingException(ESmallBufferException);
FIntelBufferInterpreter.BufferToSMARTValueList(Buffer);
StopExpectingException;
end;
procedure TestTIntelBufferInterpreter.TestLargeBufferToIdentifyDeviceResult;
var
ReturnValue: TIdentifyDeviceResult;
Buffer: TLargeBuffer;
begin
FillChar(Buffer, SizeOf(Buffer), #0);
Move(Intel750IdentifyDevice, Buffer, SizeOf(Intel750IdentifyDevice));
ReturnValue :=
FIntelBufferInterpreter.LargeBufferToIdentifyDeviceResult(Buffer);
CompareWithOriginalIdentify(ReturnValue);
end;
procedure TestTIntelBufferInterpreter.CompareWithOriginalIdentify(
const ReturnValue: TIdentifyDeviceResult);
begin
CheckEquals('INTEL SSDPEDMW400G4', ReturnValue.Model);
CheckEquals('8EV10174', ReturnValue.Firmware);
CheckEquals('CVCQ530400AP400AGN', ReturnValue.Serial);
CheckTrue(TSATASpeed.NotSATA = ReturnValue.SATASpeed,
'TSATASpeed.NotSATA = ReturnValue.SATASpeed');
CheckEquals(512, ReturnValue.LBASize);
end;
procedure TestTIntelBufferInterpreter.TestLargeBufferToSMARTValueList;
var
ReturnValue: TSMARTValueList;
Buffer: TLargeBuffer;
begin
FillChar(Buffer, SizeOf(Buffer), #0);
Move(Intel750SMART, Buffer, SizeOf(Intel750SMART));
ReturnValue := FIntelBufferInterpreter.LargeBufferToSMARTValueList(Buffer);
CompareWithOriginalSMART(ReturnValue);
end;
procedure TestTIntelBufferInterpreter.CheckIDEquals(
const Expected, Actual: TSMARTValueEntry;
const Msg: String);
begin
CheckEquals(Expected.ID, Actual.ID, Msg);
CheckEquals(Expected.Current, Actual.Current, Msg);
CheckEquals(Expected.Worst, Actual.Worst, Msg);
CheckEquals(Expected.Threshold, Actual.Threshold, Msg);
CheckEquals(Expected.RAW, Actual.RAW, Msg);
end;
procedure TestTIntelBufferInterpreter.CompareWithOriginalSMART(
const ReturnValue: TSMARTValueList);
const
ID0: TSMARTValueEntry = (ID: 1; Current: 0; Worst: 0; Threshold: 0; RAW: 0);
ID1: TSMARTValueEntry = (ID: 2; Current: 0; Worst: 0; Threshold: 0; RAW: 305);
ID2: TSMARTValueEntry = (ID: 3; Current: 0; Worst: 0; Threshold: 10; RAW: 100);
ID3: TSMARTValueEntry = (ID: 4; Current: 0; Worst: 0; Threshold: 0; RAW: 0);
ID4: TSMARTValueEntry = (ID: 5; Current: 0; Worst: 0; Threshold: 0; RAW: 1176);
ID5: TSMARTValueEntry = (ID: 6; Current: 0; Worst: 0; Threshold: 0; RAW: 138379);
ID6: TSMARTValueEntry = (ID: 7; Current: 0; Worst: 0; Threshold: 0; RAW: 35041);
ID7: TSMARTValueEntry = (ID: 8; Current: 0; Worst: 0; Threshold: 0; RAW: 1084021);
ID8: TSMARTValueEntry = (ID: 9; Current: 0; Worst: 0; Threshold: 0; RAW: 0);
ID9: TSMARTValueEntry = (ID: 10; Current: 0; Worst: 0; Threshold: 0; RAW: 129);
ID10: TSMARTValueEntry = (ID: 11; Current: 0; Worst: 0; Threshold: 0; RAW: 248);
ID11: TSMARTValueEntry = (ID: 12; Current: 0; Worst: 0; Threshold: 0; RAW: 42);
ID12: TSMARTValueEntry = (ID: 13; Current: 0; Worst: 0; Threshold: 0; RAW: 0);
ID13: TSMARTValueEntry = (ID: 14; Current: 0; Worst: 0; Threshold: 0; RAW: 0);
begin
CheckEquals(14, ReturnValue.Count, 'ReturnValue.Count');
CheckIDEquals(ID0, ReturnValue[0], 'ReturnValue[0]');
CheckIDEquals(ID1, ReturnValue[1], 'ReturnValue[1]');
CheckIDEquals(ID2, ReturnValue[2], 'ReturnValue[2]');
CheckIDEquals(ID3, ReturnValue[3], 'ReturnValue[3]');
CheckIDEquals(ID4, ReturnValue[4], 'ReturnValue[4]');
CheckIDEquals(ID5, ReturnValue[5], 'ReturnValue[5]');
CheckIDEquals(ID6, ReturnValue[6], 'ReturnValue[6]');
CheckIDEquals(ID7, ReturnValue[7], 'ReturnValue[7]');
CheckIDEquals(ID8, ReturnValue[8], 'ReturnValue[8]');
CheckIDEquals(ID9, ReturnValue[9], 'ReturnValue[9]');
CheckIDEquals(ID10, ReturnValue[10], 'ReturnValue[10]');
CheckIDEquals(ID11, ReturnValue[11], 'ReturnValue[11]');
CheckIDEquals(ID12, ReturnValue[12], 'ReturnValue[12]');
CheckIDEquals(ID13, ReturnValue[13], 'ReturnValue[13]');
end;
procedure TestTIntelBufferInterpreter.TestBufferToCapacityAndLBA;
var
ReturnValue: TIdentifyDeviceResult;
Buffer: TSmallBuffer;
LargeBuffer: TLargeBuffer;
begin
Buffer := Intel750Capacity;
FillChar(LargeBuffer, SizeOf(LargeBuffer), 0);
Move(Buffer, LargeBuffer, SizeOf(Buffer));
ReturnValue := FIntelBufferInterpreter.BufferToCapacityAndLBA(LargeBuffer);
CheckEquals(ReturnValue.UserSizeInKB, 400088457);
CheckEquals(ReturnValue.LBASize, 512);
end;
procedure TestTIntelBufferInterpreter.TestVendorSpecificSMARTValueList;
var
ReturnValue: TSMARTValueList;
Buffer: TLargeBuffer;
begin
FillChar(Buffer, SizeOf(Buffer), #0);
Move(Intel750AdditionalSMART, Buffer, SizeOf(Intel750AdditionalSMART));
ReturnValue := FIntelBufferInterpreter.VendorSpecificSMARTValueList(Buffer);
CompareWithOriginalIntelSMART(ReturnValue);
end;
procedure TestTIntelBufferInterpreter.CompareWithOriginalIntelSMART(
const ReturnValue: TSMARTValueList);
const
ID0: TSMARTValueEntry = (ID: 171; Current: 100; Worst: 0; Threshold: 0; RAW: 0);
ID1: TSMARTValueEntry = (ID: 172; Current: 0; Worst: 0; Threshold: 0; RAW: 0);
ID2: TSMARTValueEntry = (ID: 173; Current: 0; Worst: 0; Threshold: 0; RAW: 12885229569);
ID3: TSMARTValueEntry = (ID: 184; Current: 0; Worst: 0; Threshold: 0; RAW: 0);
ID4: TSMARTValueEntry = (ID: 199; Current: 0; Worst: 0; Threshold: 0; RAW: 99);
ID5: TSMARTValueEntry = (ID: 226; Current: 0; Worst: 0; Threshold: 0; RAW: 65535);
ID6: TSMARTValueEntry = (ID: 227; Current: 0; Worst: 0; Threshold: 0; RAW: 65535);
ID7: TSMARTValueEntry = (ID: 228; Current: 0; Worst: 0; Threshold: 0; RAW: 65535);
ID8: TSMARTValueEntry = (ID: 234; Current: 0; Worst: 0; Threshold: 0; RAW: 0);
ID9: TSMARTValueEntry = (ID: 240; Current: 0; Worst: 0; Threshold: 0; RAW: 0);
ID10: TSMARTValueEntry = (ID: 243; Current: 0; Worst: 0; Threshold: 0; RAW: 1);
ID11: TSMARTValueEntry = (ID: 244; Current: 0; Worst: 0; Threshold: 0; RAW: 23498);
ID12: TSMARTValueEntry = (ID: 245; Current: 0; Worst: 0; Threshold: 0; RAW: 2166);
begin
CheckEquals(13, ReturnValue.Count, 'ReturnValue.Count');
CheckIDEquals(ID0, ReturnValue[0], 'ReturnValue[0]');
CheckIDEquals(ID1, ReturnValue[1], 'ReturnValue[1]');
CheckIDEquals(ID2, ReturnValue[2], 'ReturnValue[2]');
CheckIDEquals(ID3, ReturnValue[3], 'ReturnValue[3]');
CheckIDEquals(ID4, ReturnValue[4], 'ReturnValue[4]');
CheckIDEquals(ID5, ReturnValue[5], 'ReturnValue[5]');
CheckIDEquals(ID6, ReturnValue[6], 'ReturnValue[6]');
CheckIDEquals(ID7, ReturnValue[7], 'ReturnValue[7]');
CheckIDEquals(ID8, ReturnValue[8], 'ReturnValue[8]');
CheckIDEquals(ID9, ReturnValue[9], 'ReturnValue[9]');
CheckIDEquals(ID10, ReturnValue[10], 'ReturnValue[10]');
CheckIDEquals(ID11, ReturnValue[11], 'ReturnValue[11]');
CheckIDEquals(ID12, ReturnValue[12], 'ReturnValue[12]');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTIntelBufferInterpreter.Suite);
end.
|
unit CommonTypes;
interface
uses
System.UITypes, System.Classes, DB, System.SysUtils, Winapi.Messages,
Vcl.Forms, Winapi.Windows, Vcl.ExtCtrls;
const
WM_STARTCALL = WM_USER + 200;
WM_FINISHCALL = WM_USER + 201;
WM_ACCEPTCALL = WM_USER + 202;
type TClientType = (clFiz, clUr);
type TTrayView =(trayNormal, trayMissed);
type TActionStr = (asCreate,asEdit,asShow);
type
TCallInfo = class
public
CallFlow: string;
CallId: string;
CallApiId: string;
Phone: string;
ClientId: Integer;
ClientType: string;
ClientSubType: string;
CallResult: string;
procedure Clear;
procedure Assign(ASource: TCallInfo);
end;
type
TCallProto = class
private
fCallInfo: TCallInfo;
fOnStartCall: TNotifyEvent;
fOnFinishCall: TNotifyEvent;
fOnAcceptCall: TNotifyEvent;
fOnCheckTimer: TNotifyEvent;
fActive: Boolean; //идет звонок
fReady: Boolean; // готов к звонку
fAccepted: Boolean; //принят звонок
fTimer: TTimer;
procedure SetActive(AValue: boolean);
procedure SetReady(AValue: boolean);
function GetAccepted: Boolean;
procedure SetAccepted(AValue: boolean);
function GetCanceled: Boolean;
procedure OnTimerProc(Sender: TObject);
procedure DoCheckCall;
protected
public
property Active: Boolean read fActive write SetActive;
property Ready: Boolean read fReady write SetReady;
property Accepted: Boolean read GetAccepted write SetAccepted;
property Cancelled: Boolean read GetCanceled;
property CallInfo: TCallInfo read fCallInfo;
property OnStartCall: TNotifyEvent read fOnStartCall write fOnStartCall;
property OnFinishCall: TNotifyEvent read fOnFinishCall write fOnFinishCall;
property OnAcceptCall: TNotifyEvent read fOnAcceptCall write fOnAcceptCall;
property OnCheckTimer: TNotifyEvent read fOnCheckTimer write fOnCheckTimer;
constructor Create; overload;
destructor Destroy; overload;
procedure StartCall(ACallFlow, ACallId, ACallApiId, APhone, AClientId, AClientType: string);overload;
procedure StartCall(ACallInfo: TCallInfo); overload;
procedure FinishCall(ACallResult: string);
procedure AcceptCall(ACallId: string);
end;
type
CurrentUserRec = record
ID: Integer;
UserName :string;
UserType :smallint;
userTypeName :string;
ATS_Phone_Num :string;
session_id: integer;
DebugMode : Boolean;
HideOnClose :Boolean;
end;
type
FtpProps = record //настройки фтп
Host: string;
Login: string;
Psw: string;
Passive: boolean;
Dir: string;
end;
type
ClientInfoParams = record
clType : TClientType;
ClientName: string;
ClientInfo :string;
ClientComms :string;
end;
type
PClientCallParams = ^ClientCallParams;
ClientCallParams = record
id_call: integer;
Client_Type :string;
Client_id :Integer;
TelNum :string;
ClientName :string;
Format_Id: Integer;
Status_Id: Integer;
PERSON_ID: Integer;
FORMA_ID: Integer;
INN :string;
clientContact :string;
Author :string;
ClientInfoParams :ClientInfoParams;
public
procedure Assign(ASource: ClientCallParams);
procedure Setup;
end;
type
FormResult = record
New_Id: Integer;
ModalRes: TModalResult;
Comments: string;
end;
type
PClientParam = ^TClientParam;
TClientParam = record
Status: Integer;
ClientType: Integer;
CallParam: PClientCallParams;
public
constructor Init(Astatus: integer; AClientType: Integer; ACallParam: PClientCallParams);
procedure Setup;
end;
type
PFrmCreateParam = ^TFrmCreateParam;
TFrmCreateParam = record
action: TActionstr;
Dataset: TDataset;
ExtParam: PClientParam;
public
constructor Init(Aaction: TActionstr; ADataset: TDataset; AExtParam: PClientParam);
end;
function NewFrmCreateParam(AAction: TActionstr; ADataSet: TDataSet=nil; AExtParam: PClientParam=nil): TFrmCreateParam;
procedure PostMessageToAll(AMsg: CArdinal);
implementation
function NewFrmCreateParam(AAction: TActionstr; ADataSet: TDataSet=nil; AExtParam: PClientParam=nil): TFrmCreateParam;
begin
Result.action := AAction;
Result.Dataset := ADataSet;
Result.ExtParam := AExtParam;
end;
procedure PostMessageToAll(AMsg: Cardinal);
var
i: Integer;
begin
for I := 0 to Screen.FormCount - 1 do
PostMessage(Screen.Forms[i].Handle, AMsg, 0, 0);
end;
{ ClientCallParams }
procedure ClientCallParams.Assign(ASource: ClientCallParams);
begin
self.id_call := ASource.id_call;
self.Client_Type := ASource.Client_Type;
self.Client_id := ASource.Client_id;
self.TelNum := ASource.TelNum;
self.ClientName := ASource.ClientName;
self.Format_Id := ASource.Format_Id;
self.Status_Id := ASource.Status_Id;
self.PERSON_ID := ASource.PERSON_ID;
self.FORMA_ID := ASource.FORMA_ID;
self.Author := ASource.Author;
self.INN := ASource.INN;
self.clientContact := ASource.clientContact;
self.ClientInfoParams.ClientInfo := ASource.ClientInfoParams.ClientInfo;
self.ClientInfoParams.ClientComms := ASource.ClientInfoParams.ClientComms;
end;
procedure ClientCallParams.Setup;
begin
id_call := 0;
Client_Type := '';
Client_id := 0;
TelNum := '';
ClientName := '';
Format_Id := 1;
Status_Id := 1;
PERSON_ID := 0;
FORMA_ID := 1;
INN := '';
clientContact := '';
Author := '';
end;
{ TClientParam }
constructor TClientParam.Init(AStatus: integer; AClientType: Integer; ACallParam: PClientCallParams);
begin
Self.Status := AStatus;
Self.ClientType := AClientType;
CallParam := ACallParam;
end;
procedure TClientParam.Setup;
begin
Status := 1;
ClientType := 0;
CallParam := nil;
end;
{ TFrmCreateParam }
constructor TFrmCreateParam.Init(Aaction: TActionstr; ADataset: TDataset;
AExtParam: PClientParam);
begin
Self.action := Aaction;
Self.Dataset := ADataset;
Self.ExtParam := AExtParam;
end;
{ TCallPcroto }
procedure TCallProto.AcceptCall(ACallId: string);
begin
if ACallId <> Self.CallInfo.CallId then
Exit;
end;
constructor TCallProto.Create;
begin
inherited Create;
fCallInfo := TCallInfo.Create;
//fTimer := TTimer.Create;
//fTimer.Enabled := False;
//fTimer.Interval := 1000;
//fTimer.OnTimer := onTimerProc;
fReady := True;
end;
destructor TCallProto.Destroy;
begin
fCallInfo.Free;
//fTimer.Free;
inherited;
end;
procedure TCallProto.DoCheckCall;
begin
end;
procedure TCallProto.FinishCall(ACallResult: string);
begin
CallInfo.CallResult := ACallResult;
fActive := false;
if Assigned(fOnFinishCall) then
fOnFinishCall(Self);
PostMessageToAll(WM_FINISHCALL);
end;
function TCallProto.GetAccepted: Boolean;
begin
Result := (CallInfo.CallFlow = 'in') and fAccepted;
//(CallInfo.CallResult = 'ANSWER');
end;
function TCallProto.GetCanceled: Boolean;
begin
Result := (CallInfo.CallResult = 'CANCEL');
end;
procedure TCallProto.OnTimerProc(Sender: TObject);
begin
if Assigned(fOnCheckTimer) then
fOnCheckTimer(self);
end;
procedure TCallProto.SetAccepted(AValue: boolean);
begin
if AValue <> fAccepted then
fAccepted := AValue;
if AValue then
begin
if Assigned(fOnAcceptCall) then
fOnAcceptCall(self);
PostMessageToAll(WM_ACCEPTCALL);
end;
end;
procedure TCallProto.SetActive(AValue: boolean);
begin
if AValue <> fActive then
begin
fActive := AValue;
if not AValue then
fCallInfo.Clear;
end;
end;
procedure TCallProto.SetReady(AValue: boolean);
begin
if AValue <> fReady then
begin
fReady := AValue;
end;
end;
procedure TCallProto.StartCall(ACallInfo: TCallInfo);
begin
StartCall(ACallInfo.CallFlow, ACallInfo.CallId, ACallInfo.CallApiId,
ACallInfo.Phone, IntToStr(ACallInfo.ClientId), ACallInfo.ClientType);
end;
procedure TCallProto.StartCall(ACallFlow, ACallId, ACallApiId, APhone, AClientId, AClientType: string);
begin
if CallInfo <> nil then
with fCallInfo do
begin
CallId := ACallId;
CallApiId := ACallApiId;
CallFlow := ACallFlow;
Phone := APhone;
ClientId := StrToInt(AClientId);
ClientType := AClientType;
CallResult :='';
Accepted := false;
end;
fActive := True;
fReady := False;
//PostMessage()
//ftimer.Enabled := true;
if Assigned(fOnStartCall) then
fOnStartCall(Self);
PostMessageToAll(WM_STARTCALL);
end;
{ TCallInfo }
procedure TCallInfo.Assign(ASource: TCallInfo);
begin
CallId := ASource.CallId;
CallApiId := ASource.CallApiId;
CallFlow := ASource.CallFlow;
ClientId := ASource.ClientId;
ClientType := ASource.ClientType;
ClientSubType := ASource.ClientSubType;
end;
procedure TCallInfo.Clear;
begin
CallId := '';
CallApiId := '';
CallFlow := '';
ClientId := -1;
ClientType := '';
ClientSubType := '';
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC PostgreSQL driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.PGMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator;
type
TFDPhysPgMetadata = class(TFDPhysConnectionMetadata)
private
FColumnOriginProvided: Boolean;
FUseMonthsBetween: Boolean;
FBackslashEscSupported: Boolean;
protected
function GetKind: TFDRDBMSKind; override;
function GetTxSavepoints: Boolean; override;
function GetTxAtomic: Boolean; override;
function GetEventSupported: Boolean; override;
function GetEventKinds: String; override;
function GetGeneratorSupported: Boolean; override;
function GetIdentityInsertSupported: Boolean; override;
function GetParamNameMaxLength: Integer; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameQuotedSupportedParts: TFDPhysNameParts; override;
function GetNameQuotedCaseSensParts: TFDPhysNameParts; override;
function GetNameCaseSensParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetInlineRefresh: Boolean; override;
function GetLockNoWait: Boolean; override;
function GetNamedParamMark: TFDPhysParamMark; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetAsyncAbortSupported: Boolean; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetArrayExecMode: TFDPhysArrayExecMode; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function GetNullLocations: TFDPhysNullLocations; override;
function GetColumnOriginProvided: Boolean; override;
function GetBackslashEscSupported: Boolean; override;
procedure DefineMetadataStructure(ATable: TFDDatSTable; AKind: TFDPhysMetaInfoKind); override;
function GetResultSetFields(const ASQLKey: String): TFDDatSView; override;
function InternalEscapeBoolean(const AStr: String): String; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeFloat(const AStr: String): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalEscapeEscape(AEscape: Char; const AStr: String): String; override;
function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
public
constructor Create(const AConnection: TFDPhysConnection;
AServerVersion, AClientVersion: TFDVersion; AIsUnicode: Boolean;
AColumnOriginProvided, AUseMonthsBetween, ABackslashEscSupported: Boolean);
end;
TFDPhysPgCommandGenerator = class(TFDPhysCommandGenerator)
protected
function GetSubColumn(const AParentField, ASubField: String): String; override;
function GetRowConstructor(const AValues: String; ARowCol: TFDDatSColumn): String; override;
function GetCastColumn(const AValue: String; ACol: TFDDatSColumn): String; override;
function GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String; override;
function GetReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String; override;
function GetPessimisticLock: String; override;
function GetCommitSavepoint(const AName: String): String; override;
function GetRollbackToSavepoint(const AName: String): String; override;
function GetSavepoint(const AName: String): String; override;
function GetCall(const AName: String): String; override;
function GetStoredProcCall(const ACatalog, ASchema, APackage, AProc: String;
AOverload: Word; ASPUsage: TFDPhysCommandKind): String; override;
function GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String; override;
function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer;
var AOptions: TFDPhysLimitOptions): String; override;
function GetColumnType(AColumn: TFDDatSColumn): String; override;
function GetColumnDef(AColumn: TFDDatSColumn): String; override;
function GetMerge(AAction: TFDPhysMergeAction): String; override;
end;
implementation
uses
System.SysUtils, Data.DB,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Param, FireDAC.Stan.Error;
const
// copied here from FireDAC.Phys.PGCli to remove dependency
NAMEMAXLEN = 64;
SQL_CHAR = 18; // Internal
SQL_NAME = 19; // Internal
SQL_UNKNOWN = 705; // Internal
SQL_INET = 869; // Internal
SQL_BPCHAR = 1042;
SQL_VARCHAR = 1043;
SQL_NUMERIC = 1700;
{-------------------------------------------------------------------------------}
{ TFDPhysPgMetadata }
{-------------------------------------------------------------------------------}
constructor TFDPhysPgMetadata.Create(const AConnection: TFDPhysConnection;
AServerVersion, AClientVersion: TFDVersion; AIsUnicode: Boolean;
AColumnOriginProvided, AUseMonthsBetween, ABackslashEscSupported: Boolean);
begin
inherited Create(AConnection, AServerVersion, AClientVersion, AIsUnicode);
FColumnOriginProvided := AColumnOriginProvided;
FUseMonthsBetween := AUseMonthsBetween;
FBackslashEscSupported := ABackslashEscSupported;
FKeywords.CommaText :=
'ABORT,ABSOLUTE,ACCESS,ACTION,ADD,ADMIN,AFTER,' +
'AGGREGATE,ALL,ALSO,ALTER,ALWAYS,ANALYSE,ANALYZE,' +
'AND,ANY,ARRAY,AS,ASC,ASSERTION,ASSIGNMENT,ASYMMETRIC,' +
'AT,AUTHORIZATION,BACKWARD,BEFORE,BEGIN,BETWEEN,BIGINT,' +
'BINARY,BIT,BOOLEAN,BOTH,BY,CACHE,CALLED,CASCADE,' +
'CASCADED,CASE,CAST,CHAIN,CHAR,CHARACTER,CHARACTERISTICS,' +
'CHECK,CHECKPOINT,CLASS,CLOSE,CLUSTER,COALESCE,COLLATE,' +
'COLUMN,COMMENT,COMMIT,COMMITTED,CONCURRENTLY,CONFIGURATION,' +
'CONNECTION,CONSTRAINT,CONSTRAINTS,CONTENT,CONVERSION,COPY,' +
'COST,CREATE,CREATEDB,CREATEROLE,CREATEUSER,CROSS,CSV,' +
'CURRENT,CURRENT_DATE,CURRENT_ROLE,CURRENT_TIME,CURRENT_TIMESTAMP,' +
'CURRENT_USER,CURSOR,CYCLE,DATABASE,DAY,DEALLOCATE,DEC,' +
'DECIMAL,DECLARE,DEFAULT,DEFAULTS,DEFERRABLE,DEFERRED,DEFINER,' +
'DELETE,DELIMITER,DELIMITERS,DESC,DICTIONARY,DISABLE,DISCARD,' +
'DISTINCT,DO,DOCUMENT,DOMAIN,DOUBLE,DROP,EACH,ELSE,' +
'ENABLE,ENCODING,ENCRYPTED,END,ENUM,ESCAPE,EXCEPT,' +
'EXCLUDING,EXCLUSIVE,EXECUTE,EXISTS,EXPLAIN,EXTERNAL,' +
'EXTRACT,FALSE,FAMILY,FETCH,FIRST,FLOAT,FOR,FORCE,' +
'FOREIGN,FORWARD,FREEZE,FROM,FULL,FUNCTION,GLOBAL,' +
'GRANT,GRANTED,GREATEST,GROUP,HANDLER,HAVING,HEADER,' +
'HOLD,HOUR,IF,ILIKE,IMMEDIATE,IMMUTABLE,IMPLICIT,' +
'IN,INCLUDING,INCREMENT,INDEX,INDEXES,INHERIT,INHERITS,' +
'INITIALLY,INNER,INOUT,INPUT,INSENSITIVE,INSERT,INSTEAD,' +
'INT,INTEGER,INTERSECT,INTERVAL,INTO,INVOKER,IS,ISNULL,' +
'ISOLATION,JOIN,KEY,LANCOMPILER,LANGUAGE,LARGE,LAST,' +
'LEADING,LEAST,LEFT,LEVEL,LIKE,LIMIT,LISTEN,LOAD,' +
'LOCAL,LOCALTIME,LOCALTIMESTAMP,LOCATION,LOCK,LOGIN,' +
'MAPPING,MATCH,MAXVALUE,MINUTE,MINVALUE,MODE,MONTH,' +
'MOVE,NATIONAL,NATURAL,NCHAR,NEW,NEXT,NO,' +
'NOCREATEDB,NOCREATEROLE,NOCREATEUSER,NOINHERIT,NOLOGIN,' +
'NONE,NOSUPERUSER,NOT,NOTHING,NOTIFY,NOTNULL,NOWAIT,' +
'NULL,NULLIF,NULLS,NUMERIC,OBJECT,OF,OFF,OFFSET,OIDS,' +
'OLD,ON,ONLY,OPERATOR,OPTION,OR,ORDER,OUT,OUTER,' +
'OVERLAPS,OVERLAY,OWNED,OWNER,PARSER,PARTIAL,PASSWORD,' +
'PLACING,PLANS,POSITION,PRECISION,PREPARE,PREPARED,PRESERVE,' +
'PRIMARY,PRIOR,PRIVILEGES,PROCEDURAL,PROCEDURE,QUOTE,READ,' +
'REAL,REASSIGN,RECHECK,REFERENCES,REINDEX,RELATIVE,RELEASE,' +
'RENAME,REPEATABLE,REPLACE,REPLICA,RESET,RESTART,RESTRICT,' +
'RETURNING,RETURNS,REVOKE,RIGHT,ROLE,ROLLBACK,ROW,ROWS,' +
'RULE,SAVEPOINT,SCHEMA,SCROLL,SEARCH,SECOND,SECURITY,' +
'SELECT,SEQUENCE,SERIALIZABLE,SESSION,SESSION_USER,SET,' +
'SETOF,SHARE,SHOW,SIMILAR,SIMPLE,SMALLINT,SOME,STABLE,' +
'STANDALONE,START,STATEMENT,STATISTICS,STDIN,STDOUT,' +
'STORAGE,STRICT,STRIP,SUBSTRING,SUPERUSER,SYMMETRIC,SYSID,' +
'SYSTEM,TABLE,TABLESPACE,TEMP,TEMPLATE,TEMPORARY,TEXT,' +
'THEN,TIME,TIMESTAMP,TO,TRAILING,TRANSACTION,TREAT,' +
'TRIGGER,TRIM,TRUE,TRUNCATE,TRUSTED,TYPE,UNCOMMITTED,' +
'UNENCRYPTED,UNION,UNIQUE,UNKNOWN,UNLISTEN,UNTIL,UPDATE,' +
'USER,USING,VACUUM,VALID,VALIDATOR,VALUE,VALUES,' +
'VARCHAR,VARYING,VERBOSE,VERSION,VIEW,VOLATILE,WHEN,' +
'WHERE,WHITESPACE,WITH,WITHOUT,WORK,WRITE,XML,' +
'XMLATTRIBUTES,XMLCONCAT,XMLELEMENT,XMLFOREST,XMLPARSE,' +
'XMLPI,XMLROOT,XMLSERIALIZE,YEAR,YES,ZONE';
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.PostgreSQL;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetTxSavepoints: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetTxAtomic: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetEventSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetEventKinds: String;
begin
Result := S_FD_EventKind_PG_Events;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetGeneratorSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetIdentityInsertSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetParamNameMaxLength: Integer;
begin
Result := NAMEMAXLEN;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npSchema, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetNameQuotedSupportedParts: TFDPhysNameParts;
begin
Result := [npCatalog, npSchema, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
Result := [npCatalog, npSchema, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
Result := [npCatalog, npSchema, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetNamedParamMark: TFDPhysParamMark;
begin
Result := prDollar;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetInlineRefresh: Boolean;
begin
Result := GetServerVersion >= svPGSQL080200;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetLockNoWait: Boolean;
begin
Result := GetServerVersion >= svPGSQL080100;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
Result := [soWithoutFrom, soInlineView];
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
Result := dvDefVals;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetArrayExecMode: TFDPhysArrayExecMode;
begin
if GetServerVersion >= svPGSQL080100 then
Result := aeOnErrorUndoAll
else
Result := aeUpToFirstError;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
Result := [loSkip, loRows];
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetNullLocations: TFDPhysNullLocations;
begin
Result := [nlAscLast, nlDescFirst];
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetColumnOriginProvided: Boolean;
begin
Result := FColumnOriginProvided;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysPgMetadata.DefineMetadataStructure(ATable: TFDDatSTable;
AKind: TFDPhysMetaInfoKind);
begin
inherited DefineMetadataStructure(ATable, AKind);
case AKind of
mkResultSetFields:
begin
AddMetadataCol(ATable, 'ATTRELID', dtUInt32);
AddMetadataCol(ATable, 'ATTNUM', dtInt16);
AddMetadataCol(ATable, 'ATTNAME', dtWideString);
AddMetadataCol(ATable, 'ATTRS', dtInt32);
AddMetadataCol(ATable, 'INDISPRIMARY', dtBoolean);
AddMetadataCol(ATable, 'TYPNAME', dtWideString);
AddMetadataCol(ATable, 'NSPNAME', dtWideString);
AddMetadataCol(ATable, 'RELNAME', dtWideString);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetResultSetFields(const ASQLKey: String): TFDDatSView;
begin
Result := inherited GetResultSetFields(ASQLKey);
Result.Mechanisms.AddSort('ATTRELID;ATTNUM');
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.GetBackslashEscSupported: Boolean;
begin
Result := FBackslashEscSupported;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.InternalEscapeBoolean(const AStr: String): String;
begin
Result := AnsiQuotedStr(AStr, '''') + '::BOOLEAN';
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := 'TO_DATE(' + AnsiQuotedStr(AStr, '''') + ', ''YYYY-MM-DD'')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := AnsiQuotedStr(AStr, '''') + '::TIME'
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
Result := 'TO_TIMESTAMP(' + AnsiQuotedStr(AStr, '''') + ', ''YYYY-MM-DD HH24:MI:SS'')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := AnsiQuotedStr(AStr, '''') + '::FLOAT';
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.InternalEscapeEscape(AEscape: Char; const AStr: String): String;
var
i: Integer;
begin
if (AEscape = '\') and (GetServerVersion < svPGSQL090100) then begin
Result := AStr;
i := 1;
while i <= Length(Result) do begin
if Result[i] = '\' then begin
Result := Copy(Result, 1, i) + '\' + Copy(Result, i + 1, Length(Result));
Inc(i);
end;
Inc(i);
end;
Result := Result + ' ESCAPE ''\\''';
end
else
Result := inherited InternalEscapeEscape(AEscape, AStr);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
var
sName: String;
A1, A2, A3, A4: String;
i: Integer;
function AddArgs: string;
begin
Result := '(' + AddEscapeSequenceArgs(Aseq) + ')';
end;
begin
sName := ASeq.FName;
if Length(ASeq.FArgs) >= 1 then begin
A1 := ASeq.FArgs[0];
if Length(ASeq.FArgs) >= 2 then begin
A2 := ASeq.FArgs[1];
if Length(ASeq.FArgs) >= 3 then begin
A3 := ASeq.FArgs[2];
if Length(ASeq.FArgs) >= 4 then
A4 := ASeq.FArgs[3];
end;
end;
end;
case ASeq.FFunc of
efDECODE:
begin
Result := 'CASE ' + ASeq.FArgs[0];
i := 1;
while i < Length(ASeq.FArgs) - 1 do begin
Result := Result + ' WHEN ' + ASeq.FArgs[i] + ' THEN ' + ASeq.FArgs[i + 1];
Inc(i, 2);
end;
if i = Length(ASeq.FArgs) - 1 then
Result := Result + ' ELSE ' + ASeq.FArgs[i];
Result := Result + ' END';
end;
efASCII,
efBIT_LENGTH,
efCHAR_LENGTH,
efOCTET_LENGTH,
efREPEAT,
efREPLACE: Result := sName + AddArgs;
efCHAR: Result := 'CHR' + AddArgs;
efLENGTH: Result := 'CHAR_LENGTH' + AddArgs;
efCONCAT: Result := '(' + A1 + ' || ' + A2 + ')';
efINSERT: Result := '(SUBSTR(' + A1 + ', 1, (' + A2 + ') - 1) || ' + A4 +
' || SUBSTR(' + A1 + ', (' + A2 + ' + ' + A3 + ')))';
efLCASE: Result := 'LOWER' + AddArgs;
efLEFT: Result := 'SUBSTR(' + A1 + ', 1, ' + A2 + ')';
efLTRIM: Result := 'TRIM(LEADING FROM ' + A1 + ')';
efLOCATE,
efPOSITION:
begin
if Length(ASeq.FArgs) >= 3 then
UnsupportedEscape(ASeq);
Result := 'STRPOS(' + A2 + ',' + A1 + ')';
end;
efRIGHT: Result := 'SUBSTR(' + A1+ ', CHAR_LENGTH(' + A1 + ') + 1 - ' + A2 + ', CHAR_LENGTH(' + A1 + '))';
efRTRIM: Result := 'TRIM(TRAILING FROM ' + A1 + ')';
efSPACE: Result := 'RPAD('' '', ' + A1 + ')';
efSUBSTRING: Result := 'SUBSTR' + AddArgs;
efUCASE: Result := 'UPPER' + AddArgs;
efABS,
efACOS,
efASIN,
efATAN,
efATAN2,
efCOS,
efCOT,
efCEILING,
efDEGREES,
efEXP,
efFLOOR,
efMOD,
efPI,
efPOWER,
efRADIANS,
efRANDOM,
efROUND,
efSIGN,
efSIN,
efSQRT,
efTAN: Result := sName + AddArgs;
efLOG: Result := 'LN' + AddArgs;
efLOG10: Result := 'LOG(' + A1 + ')';
efTRUNCATE: Result := 'TRUNC' + AddArgs;
efCURDATE : Result := 'CURRENT_DATE';
efCURTIME: Result := 'CURRENT_TIME';
efNOW: Result := 'CURRENT_TIMESTAMP';
efDAYNAME: Result := 'RTRIM(TO_CHAR(' + A1 + ', ''DAY''))';
efDAYOFMONTH: Result := 'CAST(TO_CHAR(' + A1 + ', ''DD'') AS INTEGER)';
efDAYOFWEEK: Result := 'CAST(TO_CHAR(' + A1 + ', ''D'') AS INTEGER)';
efDAYOFYEAR: Result := 'CAST(TO_CHAR(' + A1 + ', ''DDD'') AS INTEGER)';
efEXTRACT:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
Result := sName + '(' + A1 + ' FROM ' + A2 + ')';
end;
efHOUR: Result := 'CAST(TO_CHAR(' + A1 + ', ''HH24'') AS INTEGER)';
efMINUTE: Result := 'CAST(TO_CHAR(' + A1 + ', ''MI'') AS INTEGER)';
efMONTH: Result := 'CAST(TO_CHAR(' + A1 + ', ''MM'') AS INTEGER)';
efMONTHNAME: Result := 'RTRIM(TO_CHAR(' + A1 + ', ''MONTH''))';
efQUARTER: Result := 'CAST(TO_CHAR(' + A1 + ', ''MM'') AS INTEGER)';
efSECOND: Result := 'CAST(TO_CHAR(' + A1 + ', ''SS'') AS INTEGER)';
efTIMESTAMPADD:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'FRAC_SECOND' then
A1 := 'MICROSECONDS';
Result := '(' + A3 + ' + CAST(CAST(' + A2 + ' AS VARCHAR) || ''' + A1 + ''' AS INTERVAL))';
end;
efTIMESTAMPDIFF:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if (A1 = 'MONTH') and FUseMonthsBetween then
Result := 'MONTHS_BETWEEN(' + A3 + ', ' + A2 + ')'
else if A1 = 'WEEK' then
Result := 'TRUNC((DATE_PART(''DAY'', CAST(' + A3 + ' AS TIMESTAMP)) - ' +
'DATE_PART(''DAY'', CAST(' + A2 + ' AS TIMESTAMP))) / 7)'
else begin
if A1 = 'FRAC_SECOND' then
A1 := 'MICROSECONDS';
Result := '(DATE_PART(''' + A1 + ''', CAST(' + A3 + ' AS TIMESTAMP)) - ' +
'DATE_PART(''' + A1 + ''', CAST(' + A2 + ' AS TIMESTAMP)))';
end;
end;
efWEEK: Result := 'CAST(TO_CHAR(' + A1 + ', ''WW'') AS INTEGER)';
efYEAR: Result := 'CAST(TO_CHAR(' + A1 + ', ''YYYY'') AS INTEGER)';
// system
efCATALOG: Result := 'CURRENT_DATABASE()';
efSCHEMA: Result := 'CURRENT_SCHEMA()';
efIFNULL: Result := 'COALESCE' + AddArgs;
efIF: Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END';
efCONVERT:
begin
A2 := UpperCase(FDUnquote(Trim(A2), ''''));
if A2 = 'DATETIME' then
A2 := 'TIMESTAMP';
Result := 'CAST(' + A1 + ' AS ' + A2 + ')';
end;
else
UnsupportedEscape(ASeq);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgMetadata.InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind;
var
sToken: String;
begin
sToken := ATokens[0];
if sToken = 'FETCH' then
Result := skSelect
else if sToken = 'SET' then
if ATokens.Count = 1 then
Result := skNotResolved
else if ATokens[1] = 'SEARCH_PATH' then
Result := skSetSchema
else
Result := skSet
else if sToken = 'SHOW' then
Result := skSelect
else if sToken = 'EXPLAIN' then
Result := skSelect
else if sToken = 'START' then
if ATokens.Count = 1 then
Result := skNotResolved
else if ATokens[1] = 'TRANSACTION' then
Result := skStartTransaction
else
Result := inherited InternalGetSQLCommandKind(ATokens)
else if sToken = 'BEGIN' then
Result := skStartTransaction
else if sToken = 'END' then
Result := skCommit
else if sToken = 'ABORT' then
Result := skRollback
else if sToken = 'DO' then
Result := skExecute
else
Result := inherited InternalGetSQLCommandKind(ATokens);
if (Result in [skInsert, skMerge, skUpdate, skDelete]) and (ATokens.Count = 2) and
(ATokens[1] = 'RETURNING') then
Result := skSelectForLock;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysPgMetadata }
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetSubColumn(const AParentField,
ASubField: String): String;
begin
if FCommandPart = cpWHERE then
Result := '(' + AParentField + ').' + ASubField
else
Result := inherited GetSubColumn(AParentField, ASubField);
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetRowConstructor(const AValues: String;
ARowCol: TFDDatSColumn): String;
begin
Result := 'ROW(' + AValues + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetCastColumn(const AValue: String;
ACol: TFDDatSColumn): String;
begin
Result := AValue;
if ACol.SourceDataTypeName <> '' then
Result := Result + '::' + ACol.SourceDataTypeName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String;
var
sRet: String;
begin
Result := AStmt;
sRet := GetReturning(ARequest, False);
if sRet <> '' then begin
Result := Result + sRet;
FCommandKind := skSelectForLock;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetPessimisticLock: String;
var
lNeedFrom: Boolean;
begin
lNeedFrom := False;
Result := 'SELECT ' + GetSelectList(True, False, lNeedFrom) + BRK +
'FROM ' + GetFrom + BRK + 'WHERE ' + GetWhere(False, True, False) + BRK +
'FOR UPDATE';
ASSERT(lNeedFrom);
if not FOptions.UpdateOptions.LockWait then
Result := Result + ' NOWAIT';
FCommandKind := skSelectForLock;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String;
begin
if ANextValue then
Result := 'NEXTVAL(''' + AName + ''')'
else
Result := 'CURRVAL(''' + AName + ''')';
if AAlias <> '' then
Result := Result + ' AS ' + AAlias;
if AFullSelect then
Result := 'SELECT ' + Result;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetSavepoint(const AName: String): String;
begin
Result := 'SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetCommitSavepoint(const AName: String): String;
begin
Result := 'RELEASE SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetRollbackToSavepoint(const AName: String): String;
begin
Result := 'ROLLBACK TO SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetCall(const AName: String): String;
begin
Result := 'SELECT NULL FROM ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetStoredProcCall(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
var
i: Integer;
oParam: TFDParam;
sInPar: String;
iInParNo: Integer;
rName: TFDPhysParsedName;
lHasCrs, lFunc, lHasOut: Boolean;
begin
iInParNo := 1;
sInPar := '';
lHasCrs := False;
lFunc := False;
lHasOut := False;
for i := 0 to FParams.Count - 1 do begin
case FParams.BindMode of
pbByName: oParam := FParams[i];
pbByNumber: oParam := FParams.FindParam(i + 1);
else oParam := nil;
end;
if oParam.DataType = ftCursor then
lHasCrs := True
else if oParam.ParamType = ptResult then
lFunc := True;
if oParam.ParamType in [ptResult, ptInputOutput, ptOutput] then
lHasOut := True;
if oParam.ParamType in [ptUnknown, ptInput, ptInputOutput] then begin
if sInPar <> '' then
sInPar := sInPar + ', ';
if (FParams.BindMode = pbByName) and (oParam.Name <> '') and
(FConnMeta.ServerVersion >= svPGSQL090000) then
sInPar := sInPar + oParam.Name + ' := ';
sInPar := sInPar + '$' + IntToStr(iInParNo);
Inc(iInParNo);
end;
end;
// function returns void
if not lHasOut then begin
if FCommandKind = skStoredProc then
FCommandKind := skStoredProcNoCrs;
// NULL to avoid problem with execution of a
// void function in binary result format
Result := 'SELECT NULL FROM ';
end
else begin
if lHasCrs and (FCommandKind = skStoredProc) then
FCommandKind := skStoredProcWithCrs
else if lFunc then
lFunc := FCommandKind in [skStoredProc, skStoredProcNoCrs];
if lFunc then
Result := 'SELECT '
else
Result := 'SELECT * FROM ';
end;
rName.FCatalog := ACatalog;
rName.FSchema := ASchema;
rName.FBaseObject := APackage;
rName.FObject := AProc;
Result := Result + FConnMeta.EncodeObjName(rName, FCommand, [eoQuote, eoNormalize]) +
'(' + sInPar + ')';
if lFunc then
Result := Result + ' AS RESULT';
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String;
var
lWasWhere: Boolean;
sSchemaName: String;
sKinds: String;
oPar: TFDParam;
function Par: String;
begin
Result := '$' + IntToStr(GetParams.Count + 1);
end;
procedure AddWhere(const ACond: String; const AParam: String = '');
var
oPar: TFDParam;
begin
if lWasWhere then
Result := Result + ' AND ' + ACond
else begin
Result := Result + ' WHERE ' + ACond;
lWasWhere := True;
end;
if AParam <> '' then begin
oPar := GetParams.Add;
oPar.Name := AParam;
oPar.DataType := ftString;
oPar.Size := 70;
end;
end;
function EscapeArrayToString(const AStr: String): String;
var
iPos: Integer;
sAlias: String;
begin
iPos := Pos('.', AStr);
if iPos > 0 then
sAlias := Copy(AStr, iPos + 1, Length(AStr))
else
sAlias := AStr;
Result := 'ARRAY_TO_STRING(' + AStr + ', '';'') AS ' + sAlias;
end;
procedure AddTopScope(const AOwnerName, AObjName: String);
var
sScope: String;
begin
if ASchema <> '' then
AddWhere(AOwnerName + ' = ' + sSchemaName)
else if AObjectScopes <> [osMy, osSystem, osOther] then begin
sScope := '';
if osMy in AObjectScopes then
sScope := sScope + '(A.USENAME = USER) OR ';
if osOther in AObjectScopes then
sScope := sScope + '(A.USENAME <> USER) AND ' +
'NOT ((N.NSPNAME = ''information_schema'') OR (N.NSPNAME = ''pg_catalog'') OR ' +
'(N.NSPNAME = ''dbo'') OR (N.NSPNAME = ''sys'') OR ' +
'(substr(' + AObjName + ', 1, 3) = ''pg_'')) OR ';
if osSystem in AObjectScopes then
sScope := sScope + '(N.NSPNAME = ''information_schema'') OR (N.NSPNAME = ''pg_catalog'') OR ' +
'(substr(' + AObjName + ', 1, 3) = ''pg_'') OR ';
if sScope <> '' then
AddWhere('(' + Copy(sScope, 1, Length(sScope) - 4) + ')');
end;
end;
function EncodeScope(const AObjName: String): String;
begin
Result :=
'CASE' +
' WHEN (N.NSPNAME = ''information_schema'') OR (N.NSPNAME = ''pg_catalog'') OR ' +
'(N.NSPNAME = ''dbo'') OR (N.NSPNAME = ''sys'') OR ' +
'(SUBSTR(' + AObjName + ', 1, 3) = ''pg_'') THEN ' + IntToStr(Integer(osSystem)) +
' WHEN A.USENAME = USER THEN ' + IntToStr(Integer(osMy)) +
' ELSE ' + IntToStr(Integer(osOther)) + ' ' +
'END::SMALLINT';
end;
function EncodeLength: String;
begin
Result := Format(
'CASE' +
' WHEN A.ATTTYPID IN (%d, %d, %d, %d, %d) THEN A.ATTTYPMOD - 4' +
' WHEN A.ATTTYPID = %d THEN %d' +
' ELSE 0 ' +
'END::INTEGER', [SQL_CHAR, SQL_BPCHAR, SQL_VARCHAR, SQL_NAME, SQL_INET,
SQL_UNKNOWN, GetOptions.FormatOptions.MaxStringSize]);
end;
function EncodePrecision(const ATypeName: String): String;
begin
Result := Format(
'CASE' +
' WHEN (A.ATTTYPID IN (%d)) AND ' +
'(UPPER(SUBSTRING(' + ATypeName + ' FROM 1 FOR 3)) <> ''INT'') AND ' +
'(UPPER(SUBSTRING(' + ATypeName + ' FROM 1 FOR 5)) <> ''FLOAT'') AND ' +
'(UPPER(SUBSTRING(' + ATypeName + ' FROM 1 FOR 4)) <> ''REAL'') THEN (A.ATTTYPMOD - 4) / 65536' +
' ELSE 0 ' +
'END::SMALLINT', [SQL_NUMERIC]);
end;
function EncodeScale: String;
begin
Result := Format(
'CASE' +
' WHEN A.ATTTYPID IN (%d) THEN MOD(A.ATTTYPMOD - 4, 65536)' +
' ELSE 0 ' +
'END::SMALLINT', [SQL_NUMERIC]);
end;
function EncodeAttrs(ABase: Boolean): String;
function Attrs(AAttrs: TFDDataAttributes): String;
begin
Result := IntToStr(PWord(@AAttrs)^);
end;
begin
Result := '(';
if ABase then
Result := Result + Attrs([caBase]) + ' + ';
Result := Result +
'CASE WHEN A.ATTNOTNULL THEN 0 ELSE ' + Attrs([caAllowNull]) + ' END + ' +
'CASE WHEN A.ATTNUM > 0 THEN 0 ELSE ' + Attrs([caReadOnly]) + ' END + ' +
'CASE WHEN UPPER(A.ATTNAME) = ''OID'' AND A.ATTNUM < 0 THEN ' + Attrs([caROWID]) + ' ELSE 0 END + ' +
'CASE WHEN UPPER(SUBSTR(D.ADSRC, 1, 8)) = ''NEXTVAL('' THEN ' + Attrs([caAutoInc]) +
' WHEN D.ADBIN IS NOT NULL THEN ' + Attrs([caDefault]) + ' ELSE 0 END';
if FConnMeta.ServerVersion >= svPGSQL100000 then
Result := Result +
' + CASE WHEN A.ATTIDENTITY = ''a'' OR A.ATTIDENTITY = ''d'' THEN ' + Attrs([caAutoInc]) + ' ELSE 0 END';
Result := Result +
')::INTEGER';
end;
begin
if ASchema = '' then
sSchemaName := 'CURRENT_SCHEMA()'
else
sSchemaName := QuotedStr(ASchema);
Result := '';
sKinds := '';
lWasWhere := False;
case AKind of
mkCatalogs:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, DATNAME AS CATALOG_NAME ' +
'FROM PG_DATABASE WHERE DATISTEMPLATE = false';
lWasWhere := True;
if AWildcard <> '' then
AddWhere('DATNAME LIKE ' + Par(), 'WIL');
Result := Result + ' ORDER BY 2';
end;
mkSchemas:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, CURRENT_DATABASE() AS CATALOG_NAME, ' +
'NSPNAME AS SCHEMA_NAME FROM PG_CATALOG.PG_NAMESPACE';
if AWildcard <> '' then
AddWhere('NSPNAME LIKE ' + Par(), 'WIL');
Result := Result + ' ORDER BY 3';
end;
mkTables:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, CURRENT_DATABASE() AS CATALOG_NAME, ' +
'N.NSPNAME AS SCHEMA_NAME, C.RELNAME AS TABLE_NAME, ' +
'CASE' +
' WHEN N.OID = pg_my_temp_schema() THEN ' + IntToStr(Integer(tkTempTable)) +
' WHEN C.RELKIND = ''r'' THEN ' + IntToStr(Integer(tkTable)) +
' WHEN C.RELKIND = ''v'' THEN ' + IntToStr(Integer(tkView)) +
' ELSE 0 ' +
'END::INTEGER AS TABLE_TYPE, ' +
EncodeScope('C.RELNAME') + ' AS TABLE_SCOPE ' +
'FROM PG_CATALOG.PG_CLASS C ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE N ON N.OID = C.RELNAMESPACE '+
'INNER JOIN PG_CATALOG.PG_USER A ON C.RELOWNER = A.USESYSID ';
sKinds := '';
if (tkTable in ATableKinds) or (tkTempTable in ATableKinds) then
sKinds := sKinds + '''r''';
if tkView in ATableKinds then begin
if sKinds <> '' then
sKinds := sKinds + ',';
sKinds := sKinds + '''v''';
end;
if sKinds <> '' then
AddWhere('C.RELKIND IN (' + sKinds + ')')
else
AddWhere('0 = 1');
if AWildcard <> '' then
AddWhere('C.RELNAME LIKE ' + Par(), 'WIL');
AddTopScope('N.NSPNAME', 'C.RELNAME');
if not (tkTempTable in ATableKinds) then
AddWhere('N.OID <> pg_my_temp_schema()')
else if ATableKinds = [tkTempTable] then
AddWhere('N.OID = pg_my_temp_schema()');
Result := Result + ' ORDER BY 3, 4';
end;
mkTableFields:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, CURRENT_DATABASE() AS CATALOG_NAME, ' +
'N.NSPNAME AS SCHEMA_NAME, C.RELNAME AS TABLE_NAME, A.ATTNAME AS COLUMN_NAME, ' +
'A.ATTNUM AS COLUMN_POSITION, A.ATTTYPID AS COLUMN_DATATYPE, T.TYPNAME AS COLUMN_TYPENAME, ' +
EncodeAttrs(True) + ' AS COLUMN_ATTRIBUTES, ' +
EncodePrecision('T.TYPNAME') + ' AS COLUMN_PRECISION, ' +
EncodeScale + ' AS COLUMN_SCALE, ' +
EncodeLength + ' AS COLUMN_LENGTH ' +
'FROM PG_CATALOG.PG_CLASS C ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE N ON N.OID = C.RELNAMESPACE ' +
'INNER JOIN PG_CATALOG.PG_ATTRIBUTE A ON A.ATTRELID = C.OID ' +
'INNER JOIN PG_CATALOG.PG_TYPE T ON A.ATTTYPID = T.OID ' +
'LEFT JOIN PG_CATALOG.PG_ATTRDEF D ON D.ADNUM = A.ATTNUM AND D.ADRELID = C.OID ';
AddWhere('A.ATTNUM > 0 AND NOT A.ATTISDROPPED');
AddWhere('N.NSPNAME = ' + sSchemaName);
AddWhere('C.RELNAME = ' + Par(), 'OBJ');
if AWildcard <> '' then
AddWhere('A.ATTNAME LIKE ' + Par(), 'WIL');
Result := Result + ' ORDER BY 6';
end;
mkIndexes,
mkPrimaryKey:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, CURRENT_DATABASE() AS CATALOG_NAME,' +
'N.NSPNAME AS SCHEMA_NAME, TC.RELNAME AS TABLE_NAME, IC.RELNAME AS INDEX_NAME,' +
'CASE' +
' WHEN I.INDISPRIMARY OR I.INDISUNIQUE THEN IC.RELNAME' +
' ELSE NULL ' +
'END::NAME AS PKEY_NAME, ' +
'CASE ' +
' WHEN I.INDISPRIMARY THEN ' + IntToStr(Integer(ikPrimaryKey)) +
' WHEN I.INDISUNIQUE THEN ' + IntToStr(Integer(ikUnique)) +
' ELSE ' + IntToStr(Integer(ikNonUnique)) + ' ' +
'END::INTEGER AS INDEX_TYPE ' +
'FROM PG_CATALOG.PG_INDEX I ' +
'INNER JOIN PG_CATALOG.PG_CLASS TC ON TC.OID = I.INDRELID ' +
'INNER JOIN PG_CATALOG.PG_CLASS IC ON IC.OID = I.INDEXRELID ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE N ON N.OID = TC.RELNAMESPACE ';
AddWhere('NOT EXISTS(SELECT 1 FROM PG_CATALOG.PG_ATTRIBUTE A WHERE A.ATTRELID = I.INDRELID AND 0 = ANY(I.INDKEY))');
AddWhere('N.NSPNAME = ' + sSchemaName);
AddWhere('TC.RELNAME = ' + Par(), 'OBJ');
if AWildcard <> '' then
AddWhere('IC.RELNAME LIKE ' + Par(), 'WIL');
if AKind = mkPrimaryKey then
AddWhere('I.INDISPRIMARY');
Result := Result + ' ORDER BY 7 DESC, 5 ASC';
end;
mkIndexFields,
mkPrimaryKeyFields:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, CURRENT_DATABASE() AS CATALOG_NAME, ' +
'N.NSPNAME AS SCHEMA_NAME, TC.RELNAME AS TABLE_NAME, IC.RELNAME AS INDEX_NAME, ' +
'A.ATTNAME AS COLUMN_NAME, A.ATTNUM AS COLUMN_POSITION, ''A''::VARCHAR(1) AS SORT_ORDER, ' +
'NULL::VARCHAR(67) AS FILTER ' +
'FROM PG_CATALOG.PG_INDEX I ' +
'INNER JOIN PG_CATALOG.PG_CLASS TC ON TC.OID = I.INDRELID ' +
'INNER JOIN PG_CATALOG.PG_CLASS IC ON IC.OID = I.INDEXRELID ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE N ON N.OID = TC.RELNAMESPACE ' +
'INNER JOIN PG_CATALOG.PG_ATTRIBUTE A ON A.ATTRELID = I.INDRELID AND A.ATTNUM = ANY(I.INDKEY) ';
AddWhere('N.NSPNAME = ' + sSchemaName);
AddWhere('TC.RELNAME = ' + Par(), 'BAS');
if AKind = mkPrimaryKeyFields then
AddWhere('I.INDISPRIMARY')
else
AddWhere('IC.RELNAME = ' + Par(), 'OBJ');
if AWildcard <> '' then
AddWhere('A.ATTNAME LIKE ' + Par(), 'WIL');
Result := Result + ' ORDER BY position(trim(both from to_char(A.ATTNUM, ''99999'')) in ' +
' ''~'' || array_to_string(I.INDKEY, ''~'') || ''~'')';
end;
mkForeignKeys:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, CURRENT_DATABASE() AS CATALOG_NAME, ' +
'TN.NSPNAME AS SCHEMA_NAME, TT.RELNAME AS TABLE_NAME, C.CONNAME AS FKEY_NAME, ' +
'CURRENT_DATABASE() AS PKEY_CATALOG_NAME, RN.NSPNAME AS PKEY_SCHEMA_NAME, ' +
'RT.RELNAME AS PKEY_TABLE_NAME,' +
'CASE' +
' WHEN C.CONFDELTYPE = ''r'' THEN ' + IntToStr(Integer(ckRestrict)) +
' WHEN C.CONFDELTYPE = ''a'' THEN ' + IntToStr(Integer(ckRestrict)) +
' WHEN C.CONFDELTYPE = ''c'' THEN ' + IntToStr(Integer(ckCascade)) +
' WHEN C.CONFDELTYPE = ''n'' THEN ' + IntToStr(Integer(ckSetNull)) +
' WHEN C.CONFDELTYPE = ''d'' THEN ' + IntToStr(Integer(ckSetDefault)) + ' ' +
'END::INTEGER AS DELETE_RULE, ' +
'CASE' +
' WHEN C.CONFUPDTYPE = ''r'' THEN ' + IntToStr(Integer(ckRestrict)) +
' WHEN C.CONFUPDTYPE = ''a'' THEN ' + IntToStr(Integer(ckRestrict)) +
' WHEN C.CONFUPDTYPE = ''c'' THEN ' + IntToStr(Integer(ckCascade)) +
' WHEN C.CONFUPDTYPE = ''n'' THEN ' + IntToStr(Integer(ckSetNull)) +
' WHEN C.CONFUPDTYPE = ''d'' THEN ' + IntToStr(Integer(ckSetDefault)) + ' ' +
'END::INTEGER AS UPDATE_RULE ' +
'FROM PG_CATALOG.PG_CONSTRAINT C ' +
'INNER JOIN PG_CATALOG.PG_CLASS TT ON TT.OID = C.CONRELID ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE TN ON TN.OID = TT.RELNAMESPACE ' +
'INNER JOIN PG_CATALOG.PG_CLASS RT ON RT.OID = C.CONFRELID ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE RN ON RN.OID = RT.RELNAMESPACE';
AddWhere('C.CONTYPE = ''f''');
AddWhere('TN.NSPNAME = ' + sSchemaName);
AddWhere('TT.RELNAME = ' + Par(), 'OBJ');
if AWildcard <> '' then
AddWhere('C.CONNAME LIKE ' + Par(), 'WIL');
Result := Result + ' ORDER BY 3, 5';
end;
mkForeignKeyFields:
Result := inherited GetSelectMetaInfo(AKind, ACatalog, ASchema, ABaseObject,
AObject, AWildcard, AObjectScopes, ATableKinds, AOverload);
mkPackages:
;
mkProcs:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, CURRENT_DATABASE() AS CATALOG_NAME, ' +
'N.NSPNAME AS SCHEMA_NAME, NULL::NAME AS PACK_NAME, P.PRONAME AS PROC_NAME, ' +
'0 AS OVERLOAD, ' +
IntToStr(Integer(pkFunction)) + ' AS PROC_TYPE, '+
EncodeScope('P.PRONAME') + ' AS PROC_SCOPE, ' +
'P.PRONARGS AS IN_PARAMS, ' +
'CASE' +
' WHEN PROALLARGTYPES IS NULL THEN 0 ' +
'ELSE ' +
' ARRAY_UPPER(P.PROALLARGTYPES, 1) - P.PRONARGS ' +
'END AS OUT_PARAMS ' +
'FROM PG_CATALOG.PG_PROC P ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE N ON N.OID = P.PRONAMESPACE ' +
'INNER JOIN PG_CATALOG.PG_USER A ON P.PROOWNER = A.USESYSID ';
if AWildcard <> '' then
AddWhere('P.PRONAME LIKE ' + Par(), 'WIL');
AddTopScope('N.NSPNAME', 'P.PRONAME');
Result := Result + ' ORDER BY 3, 5';
end;
mkProcArgs:
begin
Result := 'SELECT PRORETSET, PRORETTYPE,' +
EscapeArrayToString('PROARGTYPES') + ',' +
EscapeArrayToString('PROALLARGTYPES') + ',' +
EscapeArrayToString('PROARGMODES') + ',' +
EscapeArrayToString('PROARGNAMES') + ' ' +
'FROM PG_CATALOG.PG_PROC P ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE N ON N.OID = P.PRONAMESPACE ';
AddWhere('N.NSPNAME = ' + sSchemaName);
// TFDPhysPgSPDescriber.ReadProcArgs expects two parameters
AddWhere('P.PRONAME = $1');
Result := Result + ' OFFSET $2 LIMIT 1';
end;
mkGenerators:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, CURRENT_DATABASE() AS TABLE_CATALOG, ' +
'N.NSPNAME AS SEQUENCE_SCHEMA, C.RELNAME AS GENERATOR_NAME, ' +
EncodeScope('C.RELNAME') + ' AS GENERATOR_SCOPE ' +
'FROM PG_CATALOG.PG_CLASS C ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE N ON N.OID = C.RELNAMESPACE ' +
'INNER JOIN PG_CATALOG.PG_USER A ON C.RELOWNER = A.USESYSID ';
AddWhere('C.RELKIND = ''S''');
if AWildcard <> '' then
AddWhere('C.RELNAME LIKE ' + Par(), 'WIL');
AddTopScope('N.NSPNAME', 'C.RELNAME');
Result := Result + ' ORDER BY 3, 4';
end;
mkResultSetFields:
begin
Result := 'SELECT NULL::INTEGER AS RECNO, ' + QuotedStr(AObject) + '::VARCHAR(1024) AS RESULTSET_KEY, ' +
'A.ATTRELID, A.ATTNUM, A.ATTNAME, ' + EncodeAttrs(False) + ' AS ATTRS, I.INDISPRIMARY, T.TYPNAME, N.NSPNAME, C.RELNAME ' +
'FROM PG_CATALOG.PG_ATTRIBUTE A ' +
'INNER JOIN PG_CATALOG.PG_CLASS C ON C.OID = A.ATTRELID ' +
'INNER JOIN PG_CATALOG.PG_NAMESPACE N ON N.OID = C.RELNAMESPACE ' +
'INNER JOIN PG_CATALOG.PG_TYPE T ON T.OID = A.ATTTYPID ' +
'LEFT JOIN PG_CATALOG.PG_INDEX I ON (I.INDRELID = A.ATTRELID) AND ' +
'(A.ATTNUM = ANY(I.INDKEY)) AND I.INDISPRIMARY ' +
'LEFT JOIN PG_CATALOG.PG_ATTRDEF D ON (D.ADNUM = A.ATTNUM) AND ' +
'(D.ADRELID = A.ATTRELID) ';
if Pos(',', AObject) = 0 then begin
AddWhere('A.ATTRELID = ' + Par(), 'OBJ');
oPar := GetParams[GetParams.Count - 1];
oPar.DataType := ftInteger;
oPar.Size := 0;
end
else
AddWhere('A.ATTRELID IN (' + AObject + ')');
AddWhere('(A.ATTNUM > 0)');
end;
mkTableTypeFields:
;
else
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetLimitSelect(const ASQL: String;
ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String;
begin
if (ASkip > 0) and (ARows + ASkip <> MAXINT) then
Result := ASQL + BRK + 'LIMIT ' + IntToStr(ARows) + ' OFFSET ' + IntToStr(ASkip)
else if ASkip > 0 then
Result := ASQL + BRK + 'LIMIT ALL OFFSET ' + IntToStr(ASkip)
else if ARows >= 0 then
Result := ASQL + BRK + 'LIMIT ' + IntToStr(ARows)
else begin
Result := ASQL;
AOptions := [];
end;
end;
{-------------------------------------------------------------------------------}
// http://www.postgresql.org/docs/9.1/static/datatype.html
function TFDPhysPgCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String;
begin
if (FConnMeta.ServerVersion < svPGSQL100000) and (caAutoInc in AColumn.ActualAttributes) then begin
if AColumn.DataType in [dtSByte, dtInt16, dtInt32, dtByte, dtUInt16] then
Result := 'SERIAL'
else
Result := 'BIGSERIAL';
Exit;
end;
case AColumn.DataType of
dtBoolean:
Result := 'BOOLEAN';
dtSByte,
dtInt16,
dtByte:
Result := 'SMALLINT';
dtInt32,
dtUInt16:
Result := 'INTEGER';
dtInt64,
dtUInt32,
dtUInt64:
Result := 'BIGINT';
dtSingle:
Result := 'REAL';
dtDouble,
dtExtended:
Result := 'DOUBLE PRECISION';
dtCurrency:
Result := 'MONEY';
dtBCD,
dtFmtBCD:
Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1,
FOptions.FormatOptions.MaxBcdPrecision, 0);
dtDateTime,
dtDateTimeStamp:
Result := 'TIMESTAMP';
dtTime:
Result := 'TIME';
dtDate:
Result := 'DATE';
dtTimeIntervalYM:
Result := 'INTERVAL YEAR TO MONTH';
dtTimeIntervalFull,
dtTimeIntervalDS:
Result := 'INTERVAL DAY TO SECOND';
dtAnsiString,
dtWideString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'CHAR'
else
Result := 'VARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtByteString,
dtBlob:
Result := 'BYTEA';
dtMemo,
dtWideMemo:
Result := 'TEXT';
dtXML:
Result := 'XML';
dtHBlob,
dtHMemo,
dtWideHMemo,
dtHBFile:
Result := 'BLOB';
dtGUID:
Result := '';
dtUnknown,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef,
dtParentRowRef,
dtObject:
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetColumnDef(AColumn: TFDDatSColumn): String;
begin
Result := inherited GetColumnDef(AColumn);
if (Result <> '') and
(FConnMeta.ServerVersion >= svPGSQL100000) and (caAutoInc in AColumn.ActualAttributes) then
Result := Result + ' GENERATED BY DEFAULT AS IDENTITY';
end;
{-------------------------------------------------------------------------------}
function TFDPhysPgCommandGenerator.GetMerge(AAction: TFDPhysMergeAction): String;
var
sKeys: String;
i: Integer;
oCol: TFDDatSColumn;
begin
if FConnMeta.ServerVersion < svPGSQL090500 then
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
sKeys := '';
for i := 0 to FTable.Columns.Count - 1 do begin
oCol := FTable.Columns[i];
if ColumnStorable(oCol) and ColumnInKey(oCol) then begin
if sKeys <> '' then
sKeys := sKeys + ', ';
sKeys := sKeys + GetColumn('', -1, oCol);
end;
end;
if sKeys <> '' then
sKeys := '(' + sKeys + ') ';
Result := '';
case AAction of
maInsertUpdate: Result := GenerateInsert() + BRK + 'ON CONFLICT ' + sKeys + 'DO UPDATE SET ' + GetUpdate();
maInsertIgnore: Result := GenerateInsert() + BRK + 'ON CONFLICT ' + sKeys + 'DO NOTHING';
end;
FCommandKind := skMerge;
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.PostgreSQL, S_FD_PG_RDBMS);
end.
|
unit SJ_ECB;
(*************************************************************************
DESCRIPTION : SkipJack ECB functions
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : B.Schneier, Applied Cryptography, 2nd ed., ch. 9.1
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 03.06.09 W.Ehrhardt Initial version a la XT_ECB
0.11 06.08.10 we Longint ILen
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2009-2010 Wolfgang Ehrhardt
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 acknowledgment 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.
----------------------------------------------------------------------------*)
{$i STD.INC}
interface
uses
BTypes, SJ_Base;
function SJ_ECB_Init({$ifdef CONST} const {$else} var {$endif} Key; KeyBytes: word; var ctx: TSJContext): integer;
{-SkipJack key expansion, error if invalid key size}
{$ifdef DLL} stdcall; {$endif}
procedure SJ_ECB_Reset(var ctx: TSJContext);
{-Clears ctx fields bLen and Flag}
{$ifdef DLL} stdcall; {$endif}
function SJ_ECB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in ECB mode}
{$ifdef DLL} stdcall; {$endif}
function SJ_ECB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in ECB mode}
{$ifdef DLL} stdcall; {$endif}
implementation
{---------------------------------------------------------------------------}
procedure SJ_ECB_Reset(var ctx: TSJContext);
{-Clears ctx fields bLen and Flag}
begin
SJ_Reset(ctx);
end;
{---------------------------------------------------------------------------}
function SJ_ECB_Init({$ifdef CONST} const {$else} var {$endif} Key; KeyBytes: word; var ctx: TSJContext): integer;
{-SkipJack key expansion, error if invalid key size}
begin
SJ_ECB_Init := SJ_Init(Key, KeyBytes, ctx);
end;
{---------------------------------------------------------------------------}
function SJ_ECB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in ECB mode}
var
i,n: longint;
m: word;
tmp: TSJBlock;
begin
SJ_ECB_Encrypt := 0;
if ILen<0 then ILen := 0;
if (ptp=nil) or (ctp=nil) then begin
if ILen>0 then begin
SJ_ECB_Encrypt := SJ_Err_NIL_Pointer;
exit;
end;
end;
{$ifdef BIT16}
if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin
SJ_ECB_Encrypt := SJ_Err_Invalid_16Bit_Length;
exit;
end;
{$endif}
n := ILen div SJBLKSIZE; {Full blocks}
m := ILen mod SJBLKSIZE; {Remaining bytes in short block}
if m<>0 then begin
if n=0 then begin
SJ_ECB_Encrypt := SJ_Err_Invalid_Length;
exit;
end;
dec(n); {CTS: special treatment of last TWO blocks}
end;
{Short block must be last, no more processing allowed}
if ctx.Flag and 1 <> 0 then begin
SJ_ECB_Encrypt := SJ_Err_Data_After_Short_Block;
exit;
end;
with ctx do begin
for i:=1 to n do begin
SJ_Encrypt(ctx, PSJBlock(ptp)^, PSJBlock(ctp)^);
inc(Ptr2Inc(ptp),SJBLKSIZE);
inc(Ptr2Inc(ctp),SJBLKSIZE);
end;
if m<>0 then begin
{Cipher text stealing}
SJ_Encrypt(ctx, PSJBlock(ptp)^, buf);
inc(Ptr2Inc(ptp),SJBLKSIZE);
tmp := buf;
move(PSJBlock(ptp)^, tmp, m);
SJ_Encrypt(ctx, tmp, PSJBlock(ctp)^);
inc(Ptr2Inc(ctp),SJBLKSIZE);
move(buf,PSJBlock(ctp)^,m);
{Set short block flag}
Flag := Flag or 1;
end;
end;
end;
{---------------------------------------------------------------------------}
function SJ_ECB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in ECB mode}
var
i,n: longint;
m: word;
tmp: TSJBlock;
begin
SJ_ECB_Decrypt := 0;
if ILen<0 then ILen := 0;
if (ptp=nil) or (ctp=nil) then begin
if ILen>0 then begin
SJ_ECB_Decrypt := SJ_Err_NIL_Pointer;
exit;
end;
end;
{$ifdef BIT16}
if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin
SJ_ECB_Decrypt := SJ_Err_Invalid_16Bit_Length;
exit;
end;
{$endif}
n := ILen div SJBLKSIZE; {Full blocks}
m := ILen mod SJBLKSIZE; {Remaining bytes in short block}
if m<>0 then begin
if n=0 then begin
SJ_ECB_Decrypt := SJ_Err_Invalid_Length;
exit;
end;
dec(n); {CTS: special treatment of last TWO blocks}
end;
{Short block must be last, no more processing allowed}
if ctx.Flag and 1 <> 0 then begin
SJ_ECB_Decrypt := SJ_Err_Data_After_Short_Block;
exit;
end;
with ctx do begin
for i:=1 to n do begin
SJ_Decrypt(ctx, PSJBlock(ctp)^, PSJBlock(ptp)^);
inc(Ptr2Inc(ptp),SJBLKSIZE);
inc(Ptr2Inc(ctp),SJBLKSIZE);
end;
if m<>0 then begin
{Cipher text stealing}
SJ_Decrypt(ctx, PSJBlock(ctp)^, buf);
inc(Ptr2Inc(ctp),SJBLKSIZE);
tmp := buf;
move(PSJBlock(ctp)^, tmp, m);
SJ_Decrypt(ctx, tmp, PSJBlock(ptp)^);
inc(Ptr2Inc(ptp),SJBLKSIZE);
move(buf,PSJBlock(ptp)^,m);
{Set short block flag}
Flag := Flag or 1;
end;
end;
end;
end.
|
unit Player.AudioOutput.ACM;
interface
uses Windows, SysUtils, Classes, Graphics, Messages, MSACM,Player.AudioOutput.Base,MediaProcessing.Definitions;
type
TAudioOutputDecoder_ACM = class (TAudioOutputDecoder)
private
FAudioDecoder: THandle;
FInBuffer: TBytes;
FOutBuffer: TBytes;
FLastFailedDecompressorFCC: cardinal;
FInStreamHead: TACMSTREAMHEADER;
FLastUnspportedStreamType: TStreamType;
FInFormat: TMediaStreamDataHeader;
FOutFormat: TPCMFormat;
//FDecompressorDescription: string;
//FDecompressorName: string;
//FDecompressorDriver: string;
//FDecompressorFCC: string;
procedure InitDecompressor(const aInInfo: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal);
procedure CloseDecompressor;
public
function DecodeToPCM(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal;
out aPcmFormat: TPCMFormat;
out aPcmData: pointer; out aPcmDataSize: cardinal):boolean; override;
// function StatusInfo: string; override;
//property DecompressorFCC: string read FDecompressorFCC;
// property DecompressorName: string read FDecompressorName;
// property DecompressorDescription: string read FDecompressorDescription;
// property DecompressorDriver: string read FDecompressorDriver;
constructor Create; override;
destructor Destroy; override;
end;
TPlayerAudioOutput_ACM = class (TPlayerAudioOutputWaveOut)
public
constructor Create; override;
end;
implementation
uses MMSystem, MMReg, Math;
{ TAudioOutputDecoder_ACM }
constructor TAudioOutputDecoder_ACM.Create;
begin
inherited Create;
end;
destructor TAudioOutputDecoder_ACM.Destroy;
begin
inherited;
CloseDecompressor;
end;
procedure TAudioOutputDecoder_ACM.InitDecompressor(const aInInfo: TMediaStreamDataHeader;aInfo: pointer; aInfoSize: cardinal);
var
aOutFormatSize: cardinal;
aDecompressorFourCCString: string;
aOutFormat : TWAVEFORMATEX;
aErrorCode: integer;
aInFormatMp3: TMpegLayer3WaveFormat;
pInFormat: PWaveFormatEx;
begin
ZeroMemory(@aOutFormat,sizeof(aOutFormat));
aOutFormat.wFormatTag:=WAVE_FORMAT_PCM;
aOutFormat.cbSize:=sizeof(aOutFormat);
aOutFormat.nChannels:=aInInfo.AudioChannels;
aOutFormat.nSamplesPerSec:=aInInfo.AudioSamplesPerSec;
aOutFormat.wBitsPerSample:=16;
aOutFormat.nBlockAlign:=(aOutFormat.wBitsPerSample div 8) * aOutFormat.nChannels;
aOutFormat.nAvgBytesPerSec:=aOutFormat.nBlockAlign * aOutFormat.nSamplesPerSec;
aDecompressorFourCCString:=StreamTypeToFourccString(aInInfo.biStreamType);
Assert(FAudioDecoder=0);
if aInInfo.biStreamType=stPCM then
begin
FAudioDecoder:=INVALID_HANDLE_VALUE;
FInFormat:=aInInfo;
FOutFormat.Channels:=aOutFormat.nChannels;
FOutFormat.BitsPerSample:=aOutFormat.wBitsPerSample;
FOutFormat.SamplesPerSec:=aOutFormat.nSamplesPerSec;
exit;
end;
pInFormat:=nil;
if aInInfo.biStreamType=WAVE_FORMAT_MPEGLAYER3 then
begin
aDecompressorFourCCString:='MP3';
if (aInfo<>nil) and (aInfoSize=sizeof(aInFormatMp3)) then
begin
aInFormatMp3:=PMpegLayer3WaveFormat(aInfo)^;
Assert(aInFormatMp3.wfx.wFormatTag=WAVE_FORMAT_MPEGLAYER3);
end
else begin
aInFormatMp3.wfx:=aInInfo.ToWaveFormatEx();
//TODO!!!!
aInFormatMp3.wfx.cbSize:=MPEGLAYER3_WFX_EXTRA_BYTES;
aInFormatMp3.fdwFlags:=MPEGLAYER3_FLAG_PADDING_OFF;
//aInFormatMp3.nBlockSize:=???;
aInFormatMp3.nFramesPerBlock := 1; // MUST BE ONE
aInFormatMp3.nCodecDelay := 0; // 0 for LAME or 1393 for fraunh..
aInFormatMp3.wID := MPEGLAYER3_ID_MPEG;
end;
pInFormat:=pointer(@aInFormatMp3);
end;
if (pInFormat<>nil) then
begin
aErrorCode:=acmStreamOpen(
@FAudioDecoder, // Open an ACM conversion stream
0, // Query all ACM drivers
pInFormat^, // input format : mp3
aOutFormat, // output format : pcm
nil, // No filters
0, // No async callback
0, // No data for callback
0 // No flags
);
Win32Check(aErrorCode=MMSYSERR_NOERROR);
end;
if FAudioDecoder=0 then
begin
FLastFailedDecompressorFCC:=aInInfo.biStreamType;
raise Exception.CreateFmt('Ошибка открытия декодера для аудио потока %s: не найден соответствующий декодер',[aDecompressorFourCCString]);
end
else begin
{ if ICGetInfo(FAudioDecoder,@aDecoderInfo,sizeof(aDecoderInfo))<>0 then
begin
FDecompressorFCC:=FOURCCTOSTR(aDecoderInfo.fccHandler);
FDecompressorName:=aDecoderInfo.szName;
FDecompressorDescription:=aDecoderInfo.szDescription;
FDecompressorDriver:=aDecoderInfo.szDriver;
end
}
end;
if pInFormat.wFormatTag=WAVE_FORMAT_MPEGLAYER3 then
begin
SetLength(FInBuffer,aInFormatMp3.nBlockSize);
acmStreamSize(FAudioDecoder, aInFormatMp3.nBlockSize, aOutFormatSize, ACM_STREAMSIZEF_SOURCE);
end
else //TODO????
begin
SetLength(FInBuffer,0);
acmStreamSize(FAudioDecoder, pInFormat.nAvgBytesPerSec, aOutFormatSize, ACM_STREAMSIZEF_SOURCE);
end;
if integer(aOutFormatSize)<=0 then
RaiseLastOSError;
SetLength(FOutBuffer,aOutFormatSize);
// prepare the decoder
// memset( &mp3streamHead, 0, sizeof(ACMSTREAMHEADER ) );
FInStreamHead.cbStruct := sizeof(FInStreamHead);
FInStreamHead.pbSrc := @FInBuffer[0];
FInStreamHead.cbSrcLength := Length(FInBuffer);
FInStreamHead.pbDst := @FOutBuffer[0];
FInStreamHead.cbDstLength := Length(FOutBuffer);
Win32Check(acmStreamPrepareHeader(FAudioDecoder, FInStreamHead, 0 )=MMSYSERR_NOERROR);
FInFormat:=aInInfo;
FOutFormat.Channels:=aOutFormat.nChannels;
FOutFormat.BitsPerSample:=aOutFormat.wBitsPerSample;
FOutFormat.SamplesPerSec:=aOutFormat.nSamplesPerSec;
end;
{
function TAudioOutputDecoder_ACM.StatusInfo: string;
begin
result:=inherited StatusInfo;
result:=result+'ACM:'#13#10;
result:=result+ Format(' Input Type:%s, %dx%d'#13#10,[FOURCCTOSTR(FInFormat.bmiHeader.biCompression),FInFormat.bmiHeader.biWidth,FInFormat.bmiHeader.biHeight]);
result:=result+ Format(' Decoder created:%s'#13#10,[BoolToStr(FAudioDecoder<>0,true)]);
if FAudioDecoder<>0 then
begin
result:=result+ Format(' Decoder FCC:%s'#13#10,[DecompressorFCC]);
result:=result+ Format(' Decoder Name:%s'#13#10,[DecompressorName]);
result:=result+ Format(' Decoder Desc:%s'#13#10,[DecompressorDescription]);
result:=result+ Format(' Decoder Driver:%s'#13#10,[DecompressorDriver]);
end;
end;
}
function TAudioOutputDecoder_ACM.DecodeToPCM(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal;
out aPcmFormat: TPCMFormat;
out aPcmData: pointer; out aPcmDataSize: cardinal):boolean;
begin
Assert(aData<>nil);
Assert(aFormat.biMediaType=mtAudio);
result:=false;
if (FInFormat.biStreamType<>aFormat.biStreamType) or
(FInFormat.AudioChannels<>aFormat.AudioChannels) or
(FInFormat.AudioBitsPerSample<>aFormat.AudioBitsPerSample) or
(FInFormat.AudioSamplesPerSec<>aFormat.AudioSamplesPerSec) then
CloseDecompressor;
if FAudioDecoder=0 then
try
if FLastUnspportedStreamType=aFormat.biStreamType then
exit; //Не поддерживам такой формат
InitDecompressor(aFormat,aInfo,aInfoSize);
except
FLastUnspportedStreamType:=aFormat.biStreamType;
exit;
end;
if (aFormat.biStreamType=stPCM) then
begin
aPcmData:=aData;
aPcmDataSize:=aDataSize;
aPcmFormat.Channels:=aFormat.AudioChannels;
aPcmFormat.BitsPerSample:=aFormat.AudioBitsPerSample;
aPcmFormat.SamplesPerSec:=aFormat.AudioSamplesPerSec;
result:=true;
end
else begin
begin
CopyMemory(@FInBuffer[0],aData,Min(aDataSize,Length(FInBuffer)));
if acmStreamConvert(FAudioDecoder, FInStreamHead, ACM_STREAMCONVERTF_BLOCKALIGN )=MMSYSERR_NOERROR then
begin
aPcmData:=@FOutBuffer[0];
aPcmDataSize:=FInStreamHead.cbDstLengthUsed;
aPcmFormat:=FOutFormat;
result:=true;
end;
end;
end;
end;
procedure TAudioOutputDecoder_ACM.CloseDecompressor;
begin
if (FAudioDecoder<>0) and (FAudioDecoder<>INVALID_HANDLE_VALUE) then
begin
acmStreamUnprepareHeader(FAudioDecoder, FInStreamHead, 0 );
acmStreamClose(FAudioDecoder,0);
end;
FAudioDecoder:=0;
FInBuffer:=nil;
FOutBuffer:=nil;
ZeroMemory(@FInFormat,sizeof(FInFormat));
(*
FDecompressorFCC:='';
FDecompressorName:='';
FDecompressorDescription:='';
FDecompressorDriver:='';
*)
end;
{ TPlayerAudioOutput_ACM }
constructor TPlayerAudioOutput_ACM.Create;
begin
inherited Create;
RegisterDecoderClass(stUNIV,TAudioOutputDecoder_ACM);
SetStreamType(stUNIV);
end;
end.
|
unit GC.LaserCutBoxes.Box;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TMeasureUnits }
TMeasureUnits = (muMillimetres, muInches);
{ TLaserCutBox }
TLaserCutBox = class(TObject)
private
FDimensionsInside: Boolean;
FMeasureUnits: TMeasureUnits;
FWidth: Double;
FHeight: Double;
FDepth: Double;
FTabWidth: Double;
FTabsProportional: Boolean;
FMaterialThickness: Double;
FKerf: Double;
FJointClearance: Double;
FSpaceBetweenParts: Double;
FDividersLength: Integer;
FDividersWidth: Integer;
procedure ReCalculate;
procedure SetDepth(Value: Double);
procedure SetDimensionsInside(Value: Boolean);
procedure SetDividersLength(Value: Integer);
procedure SetDividersWidth(Value: Integer);
procedure SetHeight(Value: Double);
procedure SetJointClearance(Value: Double);
procedure SetKerf(Value: Double);
procedure SetMaterialThickness(Value: Double);
procedure SetMeasureUnits(Value: TMeasureUnits);
procedure SetSpaceBetweenParts(Value: Double);
procedure SetTabsProportional(Value: Boolean);
procedure SetTabWidth(Value: Double);
procedure SetWidth(Value: Double);
protected
public
constructor Create;
destructor Destroy; override;
property DimensionsInside: Boolean
read FDimensionsInside
write SetDimensionsInside;
property MeasureUnits: TMeasureUnits
read FMeasureUnits
write SetMeasureUnits;
property Width: Double read FWidth write SetWidth;
property Height: Double read FHeight write SetHeight;
property Depth: Double read FDepth write SetDepth;
property TabWidth: Double read FTabWidth write SetTabWidth;
property TabsProportional: Boolean
read FTabsProportional
write SetTabsProportional;
property MaterialThickness: Double
read FMaterialThickness
write SetMaterialThickness;
property Kerf: Double read FKerf write SetKerf;
property JointClearance: Double
read FJointClearance
write SetJointClearance;
property SpaceBetweenParts: Double
read FSpaceBetweenParts
write SetSpaceBetweenParts;
property DividersLength: Integer
read FDividersLength
write SetDividersLength;
property DividersWidth: Integer
read FDividersWidth
write SetDividersWidth;
end;
implementation
{ TLaserCutBox }
constructor TLaserCutBox.Create;
begin
FDimensionsInside := True;
FMeasureUnits := muMillimetres;
FWidth := 100.0;
FHeight := 100.0;
FDepth := 100.0;
FTabWidth := 6.0;
FTabsProportional := False;
FMaterialThickness := 3.0;
FKerf := 0.5;
FJointClearance := 0.1;
FSpaceBetweenParts := 1.0;
FDividersLength := 0;
FDividersWidth := 0;
ReCalculate;
end;
destructor TLaserCutBox.Destroy;
begin
inherited Destroy;
end;
procedure TLaserCutBox.ReCalculate;
begin
//
end;
procedure TLaserCutBox.SetDepth(Value: Double);
begin
if FDepth = Value then Exit;
FDepth := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetDimensionsInside(Value: Boolean);
begin
if FDimensionsInside = Value then Exit;
FDimensionsInside := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetDividersLength(Value: Integer);
begin
if FDividersLength = Value then Exit;
FDividersLength := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetDividersWidth(Value: Integer);
begin
if FDividersWidth = Value then Exit;
FDividersWidth := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetHeight(Value: Double);
begin
if FHeight = Value then Exit;
FHeight := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetJointClearance(Value: Double);
begin
if FJointClearance = Value then Exit;
FJointClearance := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetKerf(Value: Double);
begin
if FKerf = Value then Exit;
FKerf := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetMaterialThickness(Value: Double);
begin
if FMaterialThickness = Value then Exit;
FMaterialThickness := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetMeasureUnits(Value: TMeasureUnits);
begin
if FMeasureUnits = Value then Exit;
FMeasureUnits := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetSpaceBetweenParts(Value: Double);
begin
if FSpaceBetweenParts = Value then Exit;
FSpaceBetweenParts := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetTabsProportional(Value: Boolean);
begin
if FTabsProportional = Value then Exit;
FTabsProportional := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetTabWidth(Value: Double);
begin
if FTabWidth = Value then Exit;
FTabWidth := Value;
ReCalculate;
end;
procedure TLaserCutBox.SetWidth(Value: Double);
begin
if FWidth = Value then Exit;
FWidth := Value;
ReCalculate;
end;
end.
|
unit slimtimer;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Dialogs, Forms, configuration, httpsend, synacode, synautil, sqlite3ds, DOM, XMLRead, otlog;
type
TTimeEntry = record
idwp: integer;
idw: integer;
seconds: integer;
timestart: string;
windowtitle: string;
processname: string;
end;
TSlimTimer = class(TThread)
private
CFG: TOTConfig;
DB: TSqlite3Dataset;
cacheIdw: TStringList;
cacheST: TStringList;
cachecalled: boolean;
AccessToken: string;
UserID: string;
Log: TOTLog;
procedure CreateCache;
procedure GetAccessTokenUserId;
function CreateTask(Name:string): integer;
function CreateTimeEntry(TaskId,StartTime,Duration,Tags: String):boolean;
public
constructor Create(CreateSuspended: boolean; mCFG: TOTConfig; mDB: TSqlite3Dataset; mLog: TOTLog);
procedure Execute; override;
end;
implementation
const
MAXTask: integer = 30;
constructor TSlimTimer.Create(CreateSuspended: boolean; mCFG: TOTConfig; mDB: TSqlite3Dataset; mLog: TOTLog);
begin
self.CFG := mCFG;
self.DB := mDB;
self.log := mLog;
cacheIdw := TStringList.create;
cacheST := TStringList.create;
cachecalled := false;
AccessToken := '';
FreeOnTerminate := True;
inherited Create(CreateSuspended);
end;
procedure TSlimTimer.CreateCache;
begin
cachecalled := true;
try
DB.SQL := 'SELECT idw,idslimtimer FROM storedata_stcache';
try
DB.Open;
IF DB.RecordCount > 0 THEN BEGIN
cacheIdw.Capacity := DB.RecordCount + 100;
cacheST.Capacity := cacheIdw.Capacity;
DB.First;
WHILE NOT DB.EOF DO BEGIN
cacheIdw.Add(DB.FieldByName('idw').asString);
cacheST.Add(DB.FieldByName('idslimtimer').asString);
DB.next;
END;
END;
finally
DB.close;
end;
except
on E: Exception do
Log.add('Exception: '+E.ClassName+' '+E.Message);
end;
end;
procedure TSlimTimer.GetAccessTokenUserId;
var
HTTP: THTTPSend;
xmldata: string;
S : TStringStream;
XML : TXMLDocument;
Passnode: TDOMNode;
begin
Log.Add('SlimTimer: Trying to get a valid Acces Token and User Id');
HTTP := THTTPSend.Create;
try
WriteStrToStream(HTTP.Document, 'api_key='+CFG.Get('SlimTimerAPIKey')+'&user[password]='+CFG.Get('SlimTimerPassword')+'&user[email]='+cfg.Get('SlimTimerUsername'));
HTTP.MimeType := 'application/x-www-form-urlencoded';
http.headers.Add('Accept: application/xml');
if HTTP.HTTPMethod('POST', 'http://slimtimer.com/users/token') then
begin
xmldata := ReadStrFromStream(HTTP.Document,HTTP.Document.Size);
IF(Pos('access-token',xmldata) > 0) THEN BEGIN
try
S:= TStringStream.Create(xmldata);
//Log.add(xmldata);
Try
S.Position:=0;
XML:=Nil;
ReadXMLFile(XML,S);
PassNode := XML.DocumentElement.FindNode('access-token');
AccessToken := PassNode.TextContent;
PassNode := XML.DocumentElement.FindNode('user-id');
UserID := PassNode.TextContent;
Finally
S.Free;
Log.Add('SlimTimer: Success Valid Access token and User id');
end;
except
on E: Exception do
Log.add('Exception: '+E.ClassName+' '+E.Message);
end;
END
ELSE
Log.Add('SlimTimer: Unable to obtain Valid Access token and User id');
end;
finally
HTTP.Free;
end;
end;
function TSlimTimer.CreateTask(Name: string): integer;
var
HTTP: THTTPSend;
xmldata: string;
S : TStringStream;
XML : TXMLDocument;
Passnode: TDOMNode;
rtmp: integer;
begin
rtmp := 0;
IF AccessToken = '' THEN
GetAccessTokenUserId;
IF (AccessToken <> '') AND (UserID <> '') THEN BEGIN
Log.Add('SlimTimer: Trying to create a new task');
try
HTTP := THTTPSend.Create;
try
WriteStrToStream(HTTP.Document, 'api_key='+CFG.Get('SlimTimerAPIKey')+'&access_token='+AccessToken+'&task[name]='+EncodeURLElement(Name));
HTTP.MimeType := 'application/x-www-form-urlencoded';
http.headers.Add('Accept: application/xml');
if HTTP.HTTPMethod('POST', 'http://slimtimer.com/users/'+UserID+'/tasks') then
begin
xmldata := ReadStrFromStream(HTTP.Document,HTTP.Document.size);
IF(Pos('<task>',xmldata) > 0) AND (Pos('</id>',xmldata) > 0) THEN BEGIN
S:= TStringStream.Create(xmldata);
//Log.add(xmldata);
Try
S.Position:=0;
XML:=Nil;
ReadXMLFile(XML,S);
PassNode := XML.DocumentElement.FindNode('id');
rtmp := strtoint(PassNode.TextContent);
Finally
S.Free;
Log.Add('SlimTimer: New Task Created');
end;
end;
end;
finally
HTTP.Free;
end;
except
on E: Exception do
Log.add('Exception: '+E.ClassName+' '+E.Message);
end;
END;
result := rtmp;
end;
function TSlimTimer.CreateTimeEntry(TaskId,StartTime,Duration,Tags: String):boolean;
var
HTTP: THTTPSend;
xmldata: string;
rtmp: boolean;
begin
rtmp := FALSE;
IF AccessToken = '' THEN
GetAccessTokenUserId;
IF (AccessToken <> '') AND (UserID <> '') THEN BEGIN
Log.Add('SlimTimer: Trying to create a new time entry');
try
HTTP := THTTPSend.Create;
try
log.add('api_key='+CFG.Get('SlimTimerAPIKey')+'&access_token='+AccessToken+'&time-entry[task_id]='+EncodeURLElement(TaskId)+'&time-entry[start_time]='+EncodeURLElement(StartTime)+'&time-entry[duration_in_seconds]='+EncodeURLElement(Duration)+'&time-entry[tags]='+EncodeURLElement(Tags));
WriteStrToStream(HTTP.Document, 'api_key='+CFG.Get('SlimTimerAPIKey')+'&access_token='+AccessToken+'&time-entry[task_id]='+EncodeURLElement(TaskId)+'&time-entry[start_time]='+EncodeURLElement(StartTime)+'&time-entry[duration_in_seconds]='+EncodeURLElement(Duration)+'&time-entry[tags]='+EncodeURLElement(Tags));
HTTP.MimeType := 'application/x-www-form-urlencoded';
http.headers.Add('Accept: application/xml');
if HTTP.HTTPMethod('POST', 'http://slimtimer.com/users/'+UserID+'/time_entries') then
begin
xmldata := ReadStrFromStream(HTTP.Document,HTTP.Document.size);
Log.add(xmldata);
IF(Pos('<time-entry>',xmldata) > 0) AND (Pos('</id>',xmldata) > 0) THEN BEGIN
rtmp := TRUE;
Log.Add('SlimTimer: New Time Entry Created');
end;
end;
finally
HTTP.Free;
end;
except
on E: Exception do
Log.add('Exception: '+E.ClassName+' '+E.Message);
end;
END;
result := rtmp;
end;
procedure TSlimTimer.Execute;
var
i,tid, NewTask, currentSTTask, counTask: integer;
tasks: array of TTimeEntry;
begin
counTask := 0;
SetLength(tasks,MAXTask);
Log.Add('Starting Slim Timer Task and Time Entries Commit');
IF NOT cachecalled THEN
self.CreateCache;
try
DB.SQL := 'SELECT t.id, t.idw, t.seconds, strftime("%Y-%m-%d %H:%M:%S",dtimestart) as ts, w.title, p.name FROM storedata_wpt wpt, wp_track t, windows w, processes p WHERE wpt.idwp = t.id AND wpt.saveslimtimer = 0 AND t.idw = w.id AND t.idp = p.id LIMIT '+inttostr(MAXTask);
try
DB.Open;
IF DB.RecordCount > 0 THEN BEGIN
DB.first;
WHILE NOT DB.EOF DO BEGIN
tasks[counTask].idwp := DB.FieldByName('id').AsInteger;
tasks[counTask].idw := DB.FieldByName('idw').AsInteger;
tasks[counTask].seconds := DB.FieldByName('seconds').AsInteger;
tasks[counTask].timestart := DB.FieldByName('ts').AsString;
tasks[counTask].windowtitle := DB.FieldByName('title').AsString;
tasks[counTask].processname := DB.FieldByName('name').AsString;
Inc(counTask);
DB.Next;
END;
END;
finally
DB.close;
end;
except
on E: Exception do
Log.add('Exception: '+E.ClassName+' '+E.Message);
end;
Log.Add(' SlimTimer: '+inttostr(counTask)+' new time entries found.');
FOR i:= 0 TO counTask - 1 DO BEGIN
currentSTTask := 0;
// Check if task exists
tid := tasks[i].idw;
IF cacheIdw.IndexOf(inttostr(tid)) = -1 THEN BEGIN
NewTask := CreateTask(tasks[i].windowtitle);
IF NewTask > 0 THEN
begin
currentSTTask := NewTask;
try
DB.ExecSQL('INSERT INTO storedata_stcache(idw,idslimtimer) VALUES ("'+inttostr(tid)+'","'+inttostr(NewTask)+'")');
except
on E: Exception do
Log.add('Exception: '+E.ClassName+' '+E.Message);
end;
cacheIdw.Add(inttostr(tid));
cacheST.Add(inttostr(NewTask));
end;
END
ELSE BEGIN
currentSTTask := strtoint(cacheST.Strings[cacheIdw.IndexOf(inttostr(tid))]);
END;
IF currentSTTASk > 0 THEN BEGIN
IF CreateTimeEntry(inttostr(currentSTTask),tasks[i].timestart,inttostr(tasks[i].seconds),tasks[i].processname) THEN BEGIN
try
DB.ExecSQL('UPDATE storedata_wpt SET saveslimtimer = 1 WHERE idwp = '+inttostr(tasks[i].idwp));
except
on E: Exception do
Log.add('Exception: '+E.ClassName+' '+E.Message);
end;
END;
END;
END;
end;
end.
|
unit IdResourceStrings;
interface
resourcestring
{General}
RSAlreadyConnected = 'Already connected.';
RSByteIndexOutOfBounds = 'Byte index out of range.';
RSCannotAllocateSocket = 'Cannot allocate socket.';
RSConnectionClosedGracefully = 'Connection Closed Gracefully.';
RSCouldNotBindSocket =
'Could not bind socket. Address and port are already in use.';
RSFailedTimeZoneInfo = 'Failed attempting to retrieve time zone information.';
RSNoBindingsSpecified = 'No bindings specified.';
RSOnExecuteNotAssigned = 'OnExecute not assigned.';
RSNotAllBytesSent = 'Not all bytes sent.';
RSNotEnoughDataInBuffer = 'Not enough data in buffer.';
RSPackageSizeTooBig = 'Package Size Too Big.';
RSUDPReceiveError0 = 'UDP Receive Error = 0.';
RSRawReceiveError0 = 'Raw Receive Error = 0.';
RSICMPReceiveError0 = 'ICMP Receive Error = 0.';
RSWinsockInitializationError = 'Winsock Initialization Error.';
RSCouldNotLoad = '%s could not be loaded.';
RSSetSizeExceeded = 'Set Size Exceeded.';
RSThreadClassNotSpecified = 'Thread Class Not Specified.';
RSCannotChangeDebugTargetAtWhileActive = 'Cannot change target while active.';
RSOnlyOneAntiFreeze = 'Only one TIdAntiFreeze can exist per application.';
RSInterceptPropIsNil =
'InterceptEnabled cannot be set to true when Intercept is nil.';
RSInterceptPropInvalid = 'Intercept value is not valid';
RSObjectTypeNotSupported = 'Object type not supported.';
RSAcceptWaitCannotBeModifiedWhileServerIsActive
= 'AcceptWait property cannot be modified while server is active.';
RSNoExecuteSpecified = 'No execute handler found.';
RSIdNoDataToRead = 'No data to read.';
// Status Strings
RSStatusResolving = 'Resolving hostname %s.';
RSStatusConnecting = 'Connecting to %s.';
RSStatusConnected = 'Connected.';
RSStatusDisconnecting = 'Disconnecting from %s.';
RSStatusDisconnected = 'Not connected.';
RSStatusText = '%s';
//IdRegister
RSRegIndyClients = 'Indy Clients';
RSRegIndyServers = 'Indy Servers';
RSRegIndyMisc = 'Indy Misc';
//IdCoder3To4
RSCoderNoTableEntryNotFound = 'Coding table entry not found.';
// MessageClient Strings
RSMsgClientEncodingText = 'Encoding text';
RSMsgClientEncodingAttachment = 'Encoding attachment';
// NNTP Exceptions
RSNNTPConnectionRefused = 'Connection explicitly refused by NNTP server.';
RSNNTPStringListNotInitialized = 'Stringlist not initialized!';
RSNNTPNoOnNewsgroupList = 'No OnNewsgroupList event has been defined.';
RSNNTPNoOnNewGroupsList = 'No OnNewGroupsList event has been defined.';
RSNNTPNoOnNewNewsList = 'No OnNewNewsList event has been defined.';
// HTTP Status
RSHTTPChunkStarted = 'Chunk Started';
RSHTTPContinue = 'Continue';
RSHTTPSwitchingProtocols = 'Switching protocols';
RSHTTPOK = 'OK';
RSHTTPCreated = 'Created';
RSHTTPAccepted = 'Accepted';
RSHTTPNonAuthoritativeInformation = 'Non-authoritative Information';
RSHTTPNoContent = 'No Content';
RSHTTPResetContent = 'Reset Content';
RSHTTPPartialContent = 'Partial Content';
RSHTTPMovedPermanently = 'Moved Permanently';
RSHTTPMovedTemporarily = 'Moved Temporarily';
RSHTTPSeeOther = 'See Other';
RSHTTPNotModified = 'Not Modified';
RSHTTPUseProxy = 'Use Proxy';
RSHTTPBadRequest = 'Bad Request';
RSHTTPUnauthorized = 'Unauthorized';
RSHTTPForbidden = 'Forbidden';
RSHTTPNotFound = 'Not Found';
RSHTTPMethodeNotallowed = 'Method not allowed';
RSHTTPNotAcceptable = 'Not Acceptable';
RSHTTPProxyAuthenticationRequired = 'Proxy Authentication Required';
RSHTTPRequestTimeout = 'Request Timeout';
RSHTTPConflict = 'Conflict';
RSHTTPGone = 'Gone';
RSHTTPLengthRequired = 'Length Required';
RSHTTPPreconditionFailed = 'Precondition Failed';
RSHTTPRequestEntityToLong = 'Request Entity To Long';
RSHTTPRequestURITooLong = 'Request-URI Too Long. 256 Chars max';
RSHTTPUnsupportedMediaType = 'Unsupported Media Type';
RSHTTPInternalServerError = 'Internal Server Error';
RSHTTPNotImplemented = 'Not Implemented';
RSHTTPBadGateway = 'Bad Gateway';
RSHTTPServiceUnavailable = 'Service Unavailable';
RSHTTPGatewayTimeout = 'Gateway timeout';
RSHTTPHTTPVersionNotSupported = 'HTTP version not supported';
RSHTTPUnknownResponseCode = 'Unknown Response Code';
// HTTP Other
RSHTTPHeaderAlreadyWritten = 'Header has already been written.';
RSHTTPErrorParsingCommand = 'Error in parsing command.';
RSHTTPUnsupportedAuthorisationScheme = 'Unsupported authorization scheme.';
RSHTTPCannotSwitchSessionStateWhenActive =
'Cannot change session state when the server is active.';
// FTP
RSFTPUnknownHost = 'Unknown';
// Property editor exceptions
RSCorruptServicesFile = '%s is corrupt.';
RSInvalidServiceName = '%s is not a valid service.';
// Stack Error Messages
RSStackError = 'Socket Error # %d' + #13#10 + '%s';
RSStackEINTR = 'Interrupted system call.';
RSStackEBADF = 'Bad file number.';
RSStackEACCES = 'Access denied.';
RSStackEFAULT = 'Bad address.';
RSStackEINVAL = 'Invalid argument.';
RSStackEMFILE = 'Too many open files.';
RSStackEWOULDBLOCK = 'Operation would block. ';
RSStackEINPROGRESS = 'Operation now in progress.';
RSStackEALREADY = 'Operation already in progress.';
RSStackENOTSOCK = 'Socket operation on non-socket.';
RSStackEDESTADDRREQ = 'Destination address required.';
RSStackEMSGSIZE = 'Message too long.';
RSStackEPROTOTYPE = 'Protocol wrong type for socket.';
RSStackENOPROTOOPT = 'Bad protocol option.';
RSStackEPROTONOSUPPORT = 'Protocol not supported.';
RSStackESOCKTNOSUPPORT = 'Socket type not supported.';
RSStackEOPNOTSUPP = 'Operation not supported on socket.';
RSStackEPFNOSUPPORT = 'Protocol family not supported.';
RSStackEAFNOSUPPORT = 'Address family not supported by protocol family.';
RSStackEADDRINUSE = 'Address already in use.';
RSStackEADDRNOTAVAIL = 'Cannot assign requested address.';
RSStackENETDOWN = 'Network is down.';
RSStackENETUNREACH = 'Network is unreachable.';
RSStackENETRESET = 'Net dropped connection or reset.';
RSStackECONNABORTED = 'Software caused connection abort.';
RSStackECONNRESET = 'Connection reset by peer.';
RSStackENOBUFS = 'No buffer space available.';
RSStackEISCONN = 'Socket is already connected.';
RSStackENOTCONN = 'Socket is not connected.';
RSStackESHUTDOWN = 'Cannot send or receive after socket is closed.';
RSStackETOOMANYREFS = 'Too many references, cannot splice.';
RSStackETIMEDOUT = 'Connection timed out.';
RSStackECONNREFUSED = 'Connection refused.';
RSStackELOOP = 'Too many levels of symbolic links.';
RSStackENAMETOOLONG = 'File name too long.';
RSStackEHOSTDOWN = 'Host is down.';
RSStackEHOSTUNREACH = 'No route to host.';
RSStackENOTEMPTY = 'Directory not empty';
RSStackEPROCLIM = 'Too many processes.';
RSStackEUSERS = 'Too many users.';
RSStackEDQUOT = 'Disk Quota Exceeded.';
RSStackESTALE = 'Stale NFS file handle.';
RSStackEREMOTE = 'Too many levels of remote in path.';
RSStackSYSNOTREADY = 'Network subsystem is unavailable.';
RSStackVERNOTSUPPORTED = 'WINSOCK DLL Version out of range.';
RSStackNOTINITIALISED = 'Winsock not loaded yet.';
RSStackHOST_NOT_FOUND = 'Host not found.';
RSStackTRY_AGAIN =
'Non-authoritative response (try again or check DNS setup).';
RSStackNO_RECOVERY = 'Non-recoverable errors: FORMERR, REFUSED, NOTIMP.';
RSStackNO_DATA = 'Valid name, no data record (check DNS setup).';
RSCMDNotRecognized = 'command not recognized';
RSGopherNotGopherPlus = '%s is not a Gopher+ server';
RSCodeNoError = 'RCode NO Error';
RSCodeQueryFormat = 'DNS Server Reports Query Format Error';
RSCodeQueryServer = 'DNS Server Reports Query Server Error';
RSCodeQueryName = 'DNS Server Reports Query Name Error';
RSCodeQueryNotImplemented = 'DNS Server Reports Query Not Implemented Error';
RSCodeQueryQueryRefused = 'DNS Server Reports Query Refused Error';
RSCodeQueryUnknownError = 'Server Returned Unknown Error';
RSDNSMFIsObsolete = 'MF is an Obsolete Command. USE MX.';
RSDNSMDISObsolete = 'MD is an Obsolete Command. Use MX.';
RSDNSMailAObsolete = 'MailA is an Obsolete Command. USE MX.';
RSDNSMailBNotImplemented = '-Err 501 MailB is not implemented';
RSQueryInvalidQueryCount = 'Invaild Query Count %d';
RSQueryInvalidPacketSize = 'Invalid Packet Size %d';
RSQueryLessThanFour = 'Received Packet is too small. Less than 4 bytes %d';
RSQueryInvalidHeaderID = 'Invalid Header Id %d';
RSQueryLessThanTwelve = 'Received Packet is too small. Less than 12 bytes %d';
RSQueryPackReceivedTooSmall = 'Received Packet is too small. %d';
{ LPD Client Logging event strings }
RSLPDDataFileSaved = 'Data file saved to %s';
RSLPDControlFileSaved = 'Control file save to %s';
RSLPDDirectoryDoesNotExist = 'Directory %s does not exist';
RSLPDServerStartTitle = 'Winshoes LPD Server %s ';
RSLPDServerActive = 'Server status: active';
RSLPDQueueStatus = 'Queue %s status: %s';
RSLPDClosingConnection = 'closing connection';
RSLPDUnknownQueue = 'Unknown queue %s';
RSLPDConnectTo = 'connected with %s';
RSLPDAbortJob = 'abort job';
RSLPDReceiveControlFile = 'Receive control file';
RSLPDReceiveDataFile = 'Receive data file';
{ LPD Exception Messages }
RSLPDNoQueuesDefined = 'Error: no queues defined';
{ Trivial FTP Exception Messages }
RSTimeOut = 'Timeout';
RSTFTPUnexpectedOp = 'Unexpected operation from %s:%d';
RSTFTPUnsupportedTrxMode = 'Unsupported transfer mode: "%s"';
RSTFTPDiskFull =
'Unable to complete write request, progress halted at %d bytes';
RSTFTPFileNotFound = 'Unable to open %s';
RSTFTPAccessDenied = 'Access to %s denied';
{ MESSAGE Exception messages }
RSTIdTextInvalidCount = 'Invalid Text count. TIdText must be greater than 1';
RSTIdMessagePartCreate =
'TIdMessagePart can not be created. Use descendant classes. ';
{ POP Exception Messages }
RSPOP3FieldNotSpecified = ' not specified';
{ Telnet Server }
RSTELNETSRVUsernamePrompt = 'Username: ';
RSTELNETSRVPasswordPrompt = 'Password: ';
RSTELNETSRVInvalidLogin = 'Invalid Login.';
RSTELNETSRVMaxloginAttempt = 'Allowed login attempts exceeded, good bye.';
RSTELNETSRVNoAuthHandler = 'No authentication handler has been specified.';
RSTELNETSRVWelcomeString = 'Indy Telnet Server';
RSTELNETSRVOnDataAvailableIsNil = 'OnDataAvailable event is nil.';
{ Telnet Client }
RSTELNETCLIConnectError = 'server not responding';
RSTELNETCLIReadError = 'Server did not respond.';
{ Network Calculator }
RSNETCALInvalidIPString = 'The string %s does not translate into a valid IP.';
RSNETCALCInvalidNetworkMask = 'Invalid network mask.';
RSNETCALCInvalidValueLength = 'Invalid value length: Should be 32.';
RSNETCALConfirmLongIPList =
'There is too many IP addresses in the specified range (%d) to be displayed at design time.';
{ About Box stuff }
RSAAboutFormCaption = 'About';
RSAAboutBoxCompName = 'Internet Direct (Indy)';
RSAAboutMenuItemName = 'About Internet &Direct (Indy) %s...';
RSAAboutBoxVersion = 'Version %s';
RSAAboutBoxCopyright = 'Copyright © 1993 - 2001'#13#10
+ 'Kudzu (Chad Z. Hower)'#13#10
+ 'and the'#13#10
+ 'Indy Pit Crew';
RSAAboutBoxPleaseVisit =
'For the latest updates and information please visit:';
RSAAboutBoxIndyWebsite = 'http://www.nevrona.com/indy/';
RSAAboutCreditsCoordinator = 'Project Coordinator';
RSAAboutCreditsCoCordinator = 'Project Co-Coordinator';
{ Tunnel messages }
RSTunnelGetByteRange =
'Call to %s.GetByte [property Bytes] with index <> [0..%d]';
RSTunnelTransformErrorBS = 'Error in transformation before send';
RSTunnelTransformError = 'Transform failed';
RSTunnelCRCFailed = 'CRC Failed';
RSTunnelConnectMsg = 'Connecting';
RSTunnelDisconnectMsg = 'Disconnect';
RSTunnelConnectToMasterFailed = 'Cannt connect to the Master server';
RSTunnelDontAllowConnections = 'Do not allow connctions now';
RSTunnelMessageTypeError = 'Message type recognition error';
RSTunnelMessageHandlingError = 'Message handling failed';
RSTunnelMessageInterpretError = 'Interpretation of message failed';
RSTunnelMessageCustomInterpretError = 'Custom message interpretation failed';
{ Socks messages }
RSSocksRequestFailed = 'Request rejected or failed.';
RSSocksRequestServerFailed =
'Request rejected because SOCKS server cannot connect.';
RSSocksRequestIdentFailed =
'Request rejected because the client program and identd report different user-ids.';
RSSocksUnknownError = 'Unknown socks error.';
RSSocksServerRespondError = 'Socks server did not respond.';
RSSocksAuthMethodError = 'Invalid socks authentication method.';
RSSocksAuthError = 'Authentication error to socks server.';
RSSocksServerGeneralError = 'General SOCKS server failure.';
RSSocksServerPermissionError = 'Connection not allowed by ruleset.';
RSSocksServerNetUnreachableError = 'Network unreachable.';
RSSocksServerHostUnreachableError = 'Host unreachable.';
RSSocksServerConnectionRefusedError = 'Connection refused.';
RSSocksServerTTLExpiredError = 'TTL expired.';
RSSocksServerCommandError = 'Command not supported.';
RSSocksServerAddressError = 'Address type not supported.';
{ FTP }
RSDestinationFileAlreadyExists = 'Destination file already exists.';
{ SSL messages }
RSSSLAcceptError = 'Error accepting connection with SSL.';
RSSSLConnectError = 'Error connecting with SSL.';
RSSSLSettingChiperError = 'SetCipher failed.';
RSSSLCreatingContextError = 'Error creating SSL context.';
RSSSLLoadingRootCertError = 'Could not load root certificate.';
RSSSLLoadingCertError = 'Could not load certificate.';
RSSSLLoadingKeyError = 'Could not load key, check password.';
RSSSLGetMethodError = 'Error geting SSL method.';
RSSSLDataBindingError = 'Error binding data to SSL socket.';
{IdMessage Component Editor}
RSMsgCmpEdtrNew = '&New Message Part...';
RSMsgCmpEdtrExtraHead = 'Extra Headers Text Editor';
RSMsgCmpEdtrBodyText = 'Body Text Editor';
{IdICMPClient}
RSICMPNotEnoughtBytes = 'Not enough bytes received';
RSICMPNonEchoResponse = 'Non-echo type response received';
RSICMPWrongDestination = 'Received someone else''s packet';
{IdNNTPServer}
RSNNTPServerNotRecognized = 'command not recognized (%s)';
RSNNTPServerGoodBye = 'Goodbye';
{IdGopherServer}
RSGopherServerNoProgramCode = 'Error: No program code to return request!';
{IdOpenSSL}
RSOSSLModeNotSet = 'Mode has not been set.';
RSOSSLCouldNotLoadSSLLibrary = 'Could not load SSL library.';
RSOSSLStatusString = 'SSL status: "%s"';
RSOSSLConnectionDropped = 'SSL connection has dropped.';
RSOSSLCertificateLookup = 'SSL certificate request error.';
RSOSSLInternal = 'SSL library internal error.';
{IdWinsockStack}
RSWSockStack = 'Winsock stack';
{IdLogBase}
RSLogConnected = 'Connected.';
RSLogRecV = 'Recv: ';
RSLogSent = 'Sent: ';
RSLogDisconnected = 'Disconnected.';
RSLogEOL = '<EOL>';
implementation
end.
|
unit NsLibSSH2Channel;
interface
uses
Windows, SysUtils, Classes, WinSock, libssh2, NsLibSSH2Session,
NsLibSSH2Const;
type
TExchangerThd = class(TThread)
private
FPoolIndex: Integer;
FExchangeSocket: TSocket;
FChannel: PLIBSSH2_CHANNEL;
// Property getters/setters
function GetPoolIndex: Integer;
procedure SetPoolIndex(Value: Integer);
function GetExchangeSocket: TSocket;
procedure SetExchangeSocket(Value: TSocket);
function GetChannel: PLIBSSH2_CHANNEL;
procedure SetChannel(Value: PLIBSSH2_CHANNEL);
function GetTerminated: Boolean;
public
destructor Destroy; override;
procedure Execute; override;
property PoolIndex: Integer read GetPoolIndex write SetPoolIndex;
property ExchangeSocket: TSocket read GetExchangeSocket write
SetExchangeSocket;
property Channel: PLIBSSH2_CHANNEL read GetChannel write SetChannel;
property Terminated: Boolean read GetTerminated;
end;
type
TExchangerPool = class(TObject)
private
FCount: Integer;
FPool: array[0..MAX_POOL_SIZE - 1] of TExchangerThd;
procedure Clear;
function GetFreePoolItem: Integer;
procedure RemovePoolThread(Sender: TObject);
// Property getters/setters
function GetPoolItem(Index: Integer): TExchangerThd;
procedure SetPoolItem(Index: Integer; Value: TExchangerThd);
public
constructor Create;
destructor Destroy; override;
function Add(const ExchangerThd: TExchangerThd): Integer;
procedure Remove(const Index: Integer);
property PoolItem[Index: Integer]: TExchangerThd read GetPoolItem write
SetPoolItem; default;
end;
type
TListenerThd = class(TThread)
private
FListenSocket: TSocket;
FSockAddr: sockaddr_in;
FSockAddrLen: Integer;
FExchangerPool: TExchangerPool;
FExchangeChannel: PLIBSSH2_CHANNEL;
FExchangeSocket: TSocket;
FSession: PLIBSSH2_SESSION;
FRemoteHost: PAnsiChar;
FRemotePort: Integer;
procedure StartExchangerThread;
procedure StopExchangerThreads;
// Property getters/setters
function GetListenSocket: TSocket;
procedure SetListenSocket(Value: TSocket);
function GetSockAddr: sockaddr_in;
procedure SetSockAddr(Value: sockaddr_in);
function GetSockAddrLen: Integer;
procedure SetSockAddrLen(Value: Integer);
function GetSession: PLIBSSH2_SESSION;
procedure SetSession(Value: PLIBSSH2_SESSION);
function GetRemoteHost: PAnsiChar;
procedure SetRemoteHost(Value: PAnsiChar);
function GetRemotePort: Integer;
procedure SetRemotePort(Value: Integer);
public
constructor Create(CreateSuspended: Boolean);
destructor Destroy; override;
procedure Execute; override;
property ListenSocket: TSocket read GetListenSocket write SetListenSocket;
property SockAddr: sockaddr_in read GetSockAddr write SetSockAddr;
property SockAddrLen: Integer read GetSockAddrLen write SetSockAddrLen;
property Session: PLIBSSH2_SESSION read GetSession write SetSession;
property RemoteHost: PAnsiChar read GetRemoteHost write SetRemoteHost;
property RemotePort: Integer read GetRemotePort write SetRemotePort;
end;
type
TNsLibSSH2Channel = class(TComponent)
private
FSession: TNsLibSSH2Session;
FListenerThd: TListenerThd;
FListenSocket: TSocket;
FLocalHost: string;
FLocalPort: Integer;
FRemoteHost: string;
FRemotePort: Integer;
FChannel: PLIBSSH2_CHANNEL;
FOpened: Boolean;
FStatus: string;
SockAddr: sockaddr_in;
SockAddrLen: Integer;
//Events
FAfterCreate: TNotifyEvent;
FBeforeDestroy: TNotifyEvent;
FBeforeOpen: TNotifyEvent;
FAfterOpen: TNotifyEvent;
FBeforeClose: TNotifyEvent;
FAfterClose: TNotifyEvent;
protected
procedure InitProperties;
procedure SetListenerProperties;
function CreateListenSocket: Boolean;
procedure CloseListenSocket;
function CreateListenerThread: Boolean;
procedure DestroyListenerThread;
function StartListenerThread: Boolean;
procedure StopListenerThread;
// Property getters/setters
function GetSession: TNsLibSSH2Session;
procedure SetSession(Value: TNsLibSSH2Session);
function GetLocalHost: string;
procedure SetLocalHost(Value: string);
function GetLocalPort: Integer;
procedure SetLocalPort(Value: Integer);
function GetRemoteHost: string;
procedure SetRemoteHost(Value: string);
function GetRemotePort: Integer;
procedure SetRemotePort(Value: Integer);
function GetOpened: Boolean;
function GetStatus: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Open: Boolean;
function OpenEx(const ALocalHost, ARemoteHost: string;
const ALocalPort, ARemotePort: Integer): Boolean;
procedure Close;
published
property AfterCreate: TNotifyEvent read FAfterCreate write FAfterCreate;
property BeforeDestroy: TNotifyEvent read FBeforeDestroy write
FBeforeDestroy;
property BeforeOpen: TNotifyEvent read FBeforeOpen write FBeforeOpen;
property AfterOpen: TNotifyEvent read FAfterOpen write FAfterOpen;
property BeforeClose: TNotifyEvent read FBeforeClose write FBeforeClose;
property AfterClose: TNotifyEvent read FAfterClose write FAfterClose;
property Session: TNsLibSSH2Session read GetSession write SetSession;
property LocalHost: string read GetLocalHost write SetLocalHost;
property LocalPort: Integer read GetLocalPort write SetLocalPort;
property RemoteHost: string read GetRemoteHost write SetRemoteHost;
property RemotePort: Integer read GetRemotePort write SetRemotePort;
property Opened: Boolean read GetOpened;
property Status: string read GetStatus;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NeferSky', [TNsLibSSH2Channel]);
end;
//---------------------------------------------------------------------------
{ TNsLibSSH2Channel }
// Public
constructor TNsLibSSH2Channel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
InitProperties;
if Assigned(AfterCreate) then
AfterCreate(Self);
end;
//---------------------------------------------------------------------------
destructor TNsLibSSH2Channel.Destroy;
begin
if Assigned(BeforeDestroy) then
BeforeDestroy(Self);
if Opened then
Close;
DestroyListenerThread;
inherited Destroy;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.Open: Boolean;
begin
if Assigned(BeforeOpen) then
BeforeOpen(Self);
Result := False;
if FSession = nil then
begin
FStatus := ER_SESSION_UNAVAILABLE;
Exit;
end;
if Opened then
Close;
if not CreateListenSocket then
Exit;
if not CreateListenerThread then
begin
CloseListenSocket;
Exit;
end;
SetListenerProperties;
if not StartListenerThread then
begin
DestroyListenerThread;
CloseListenSocket;
Exit;
end;
FStatus := ST_CONNECTED;
FOpened := True;
Result := Opened;
if Assigned(AfterOpen) then
AfterOpen(Self);
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.OpenEx(const ALocalHost, ARemoteHost: string;
const ALocalPort, ARemotePort: Integer): Boolean;
begin
LocalHost := ALocalHost;
RemoteHost := ARemoteHost;
LocalPort := ALocalPort;
RemotePort := ARemotePort;
Result := Open;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.Close;
begin
if Assigned(BeforeClose) then
BeforeClose(Self);
if Opened then
begin
StopListenerThread;
DestroyListenerThread;
CloseListenSocket;
FStatus := ST_DISCONNECTED;
FOpened := False;
end;
if Assigned(AfterClose) then
AfterClose(Self);
end;
//---------------------------------------------------------------------------
// Protected
procedure TNsLibSSH2Channel.InitProperties;
begin
FLocalHost := DEFAULT_LOCAL_HOST;
FLocalPort := DEFAULT_LOCAL_PORT;
FRemoteHost := DEFAULT_REMOTE_HOST;
FRemotePort := DEFAULT_REMOTE_PORT;
FSession := nil;
FChannel := nil;
FListenerThd := nil;
FOpened := False;
FStatus := ST_DISCONNECTED;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.SetListenerProperties;
begin
FListenerThd.ListenSocket := FListenSocket;
FListenerThd.SockAddr := SockAddr;
FListenerThd.SockAddrLen := SockAddrLen;
FListenerThd.Session := FSession.Session;
FListenerThd.RemoteHost := PAnsiChar(FRemoteHost);
FListenerThd.RemotePort := RemotePort;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.CreateListenSocket: Boolean;
var
SockOpt: PAnsiChar;
rc: Integer;
begin
Result := False;
FListenSocket := Socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (FListenSocket = INVALID_SOCKET) then
begin
FListenSocket := INVALID_SOCKET;
FStatus := ER_OPEN_SOCKET;
Exit;
end;
SockAddr.sin_family := AF_INET;
SockAddr.sin_port := htons(FLocalPort);
SockAddr.sin_addr.s_addr := inet_addr(PAnsiChar(FLocalHost));
if (SockAddr.sin_addr.s_addr = INADDR_NONE) then
begin
CloseSocket(FListenSocket);
FListenSocket := INVALID_SOCKET;
FStatus := ER_IP_INCORRECT;
Exit;
end;
SockOpt := #1;
SetSockOpt(FListenSocket, SOL_SOCKET, SO_REUSEADDR, SockOpt, SizeOf(SockOpt));
SockAddrLen := SizeOf(SockAddr);
rc := Bind(FListenSocket, SockAddr, SockAddrLen);
if (rc = -1) then
begin
CloseSocket(FListenSocket);
FListenSocket := INVALID_SOCKET;
FStatus := Format(ER_BINDING, [WSAGetLastError]);
Exit;
end;
rc := Listen(FListenSocket, 2);
if (rc = -1) then
begin
CloseSocket(FListenSocket);
FListenSocket := INVALID_SOCKET;
FStatus := ER_SOCKET_LISTEN;
Exit;
end;
Result := True;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.CloseListenSocket;
begin
if FListenSocket <> INVALID_SOCKET then
begin
CloseSocket(FListenSocket);
FListenSocket := INVALID_SOCKET;
end;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.CreateListenerThread: Boolean;
begin
Result := False;
try
FListenerThd := TListenerThd.Create(True);
Result := True;
except
FListenerThd := nil;
end;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.DestroyListenerThread;
begin
FreeAndNil(FListenerThd);
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.StartListenerThread: Boolean;
begin
Result := False;
try
FListenerThd.Resume;
WaitForSingleObject(FListenerThd.Handle, 1000);
Result := True;
except
;
end;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.StopListenerThread;
begin
if FListenerThd <> nil then
begin
CloseListenSocket;
FListenerThd.Terminate;
FListenerThd.WaitFor;
FreeAndNil(FListenerThd);
end;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.GetLocalHost: string;
begin
Result := FLocalHost;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.GetLocalPort: Integer;
begin
Result := FLocalPort;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.GetOpened: Boolean;
begin
Result := FOpened;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.GetRemoteHost: string;
begin
Result := FRemoteHost;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.GetRemotePort: Integer;
begin
Result := FRemotePort;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.GetSession: TNsLibSSH2Session;
begin
Result := FSession;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2Channel.GetStatus: string;
begin
Result := FStatus;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.SetLocalHost(Value: string);
begin
if FLocalHost <> Value then
FLocalHost := Value;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.SetLocalPort(Value: Integer);
begin
if FLocalPort <> Value then
FLocalPort := Value;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.SetRemoteHost(Value: string);
begin
if FRemoteHost <> Value then
FRemoteHost := Value;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.SetRemotePort(Value: Integer);
begin
if FRemotePort <> Value then
FRemotePort := Value;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2Channel.SetSession(Value: TNsLibSSH2Session);
begin
if FSession <> Value then
FSession := Value;
end;
//---------------------------------------------------------------------------
{ TListenerThd }
// Public
constructor TListenerThd.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
FExchangerPool := TExchangerPool.Create;
end;
//---------------------------------------------------------------------------
destructor TListenerThd.Destroy;
begin
StopExchangerThreads;
FExchangerPool.Destroy;
end;
//---------------------------------------------------------------------------
procedure TListenerThd.Execute;
var
SHost: PAnsiChar;
SPort: Integer;
SafeCounter: Integer;
function ExchangeSocketInvalid: Boolean;
begin
Result := FExchangeSocket = INVALID_SOCKET;
end;
begin
while not Terminated do
begin
FExchangeSocket := Accept(FListenSocket, @FSockAddr, @FSockAddrLen);
if ExchangeSocketInvalid then
Continue;
SHost := inet_ntoa(SockAddr.sin_addr);
SPort := ntohs(SockAddr.sin_port);
// Unclear why the channel is not created by the first time,
// that's why i have to make several attempts.
// I use the SafeCounter to prevent an infinite loop.
SafeCounter := 0;
repeat
Inc(SafeCounter);
FExchangeChannel := libssh2_channel_direct_tcpip_ex(FSession,
FRemoteHost, FRemotePort, SHost, SPort);
// Just waiting. It's a kind of magic.
Sleep(1000);
until (FExchangeChannel <> nil) or (SafeCounter > MAX_CONNECTION_ATTEMPTS);
// if exceeded MAX_CONNECTION_ATTEMPTS, but channel is still not created.
if FExchangeChannel = nil then
Continue;
StartExchangerThread;
end;
end;
//---------------------------------------------------------------------------
// Private
procedure TListenerThd.StartExchangerThread;
var
ExchangerThd: TExchangerThd;
begin
ExchangerThd := TExchangerThd.Create(True);
ExchangerThd.FreeOnTerminate := True;
ExchangerThd.ExchangeSocket := FExchangeSocket;
ExchangerThd.Channel := FExchangeChannel;
FExchangerPool.Add(ExchangerThd);
end;
//---------------------------------------------------------------------------
procedure TListenerThd.StopExchangerThreads;
begin
FExchangerPool.Clear;
end;
//---------------------------------------------------------------------------
function TListenerThd.GetListenSocket: TSocket;
begin
Result := FListenSocket;
end;
//---------------------------------------------------------------------------
function TListenerThd.GetRemoteHost: PAnsiChar;
begin
Result := FRemoteHost;
end;
//---------------------------------------------------------------------------
function TListenerThd.GetRemotePort: Integer;
begin
Result := FRemotePort;
end;
//---------------------------------------------------------------------------
function TListenerThd.GetSession: PLIBSSH2_SESSION;
begin
Result := FSession;
end;
//---------------------------------------------------------------------------
function TListenerThd.GetSockAddr: sockaddr_in;
begin
Result := FSockAddr;
end;
//---------------------------------------------------------------------------
function TListenerThd.GetSockAddrLen: Integer;
begin
Result := FSockAddrLen;
end;
//---------------------------------------------------------------------------
procedure TListenerThd.SetListenSocket(Value: TSocket);
begin
if FListenSocket <> Value then
FListenSocket := Value;
end;
//---------------------------------------------------------------------------
procedure TListenerThd.SetRemoteHost(Value: PAnsiChar);
begin
if FRemoteHost <> Value then
FRemoteHost := Value;
end;
//---------------------------------------------------------------------------
procedure TListenerThd.SetRemotePort(Value: Integer);
begin
if FRemotePort <> Value then
FRemotePort := Value;
end;
//---------------------------------------------------------------------------
procedure TListenerThd.SetSession(Value: PLIBSSH2_SESSION);
begin
if FSession <> Value then
FSession := Value;
end;
//---------------------------------------------------------------------------
procedure TListenerThd.SetSockAddr(Value: sockaddr_in);
begin
// if FSockAddr <> Value then
FSockAddr := Value;
end;
//---------------------------------------------------------------------------
procedure TListenerThd.SetSockAddrLen(Value: Integer);
begin
if FSockAddrLen <> Value then
FSockAddrLen := Value;
end;
//---------------------------------------------------------------------------
{ TExchangerThd }
procedure TExchangerThd.Execute;
var
i: Integer;
wr: ssize_t;
rc: Integer;
tv: timeval;
fds: tfdset;
Len: ssize_t;
Buffer: array[0..16384] of Char;
begin
while not Terminated do
begin
FD_ZERO(fds);
FD_SET(FExchangeSocket, fds);
tv.tv_sec := 0;
tv.tv_usec := 100000;
rc := Select(0, @fds, nil, nil, @tv);
if (rc = -1) then
Terminate;
if ((rc <> 0) and FD_ISSET(FExchangeSocket, fds)) then
begin
FillChar(Buffer, 16385, 0);
Len := Recv(FExchangeSocket, Buffer[0], SizeOf(Buffer), 0);
if (Len <= 0) then
Terminate;
wr := 0;
while (wr < Len) do
begin
i := libssh2_channel_write(Channel, @Buffer[wr], Len - wr);
if (LIBSSH2_ERROR_EAGAIN = i) then
Continue;
if (i < 0) then
Terminate;
wr := wr + i;
end;
end;
while True do
begin
FillChar(Buffer, 16385, 0);
Len := libssh2_channel_read(Channel, @Buffer[0], SizeOf(Buffer));
if (LIBSSH2_ERROR_EAGAIN = Len) then
Break
else if (Len < 0) then
Terminate;
wr := 0;
while (wr < Len) do
begin
i := Send(FExchangeSocket, Buffer[wr], Len - wr, 0);
if (i <= 0) then
Terminate;
wr := wr + i;
end;
if (libssh2_channel_eof(Channel) = 1) then
Terminate;
end;
end;
end;
//---------------------------------------------------------------------------
destructor TExchangerThd.Destroy;
begin
if (Channel <> nil) then
begin
libssh2_channel_close(Channel);
libssh2_channel_wait_closed(Channel);
libssh2_channel_free(Channel);
end;
if FExchangeSocket <> INVALID_SOCKET then
begin
CloseSocket(FExchangeSocket);
FExchangeSocket := INVALID_SOCKET;
end;
end;
//---------------------------------------------------------------------------
function TExchangerThd.GetChannel: PLIBSSH2_CHANNEL;
begin
Result := FChannel;
end;
//---------------------------------------------------------------------------
function TExchangerThd.GetExchangeSocket: TSocket;
begin
Result := FExchangeSocket;
end;
//---------------------------------------------------------------------------
function TExchangerThd.GetPoolIndex: Integer;
begin
Result := FPoolIndex;
end;
//---------------------------------------------------------------------------
function TExchangerThd.GetTerminated: Boolean;
begin
Result := Self.Terminated;
end;
//---------------------------------------------------------------------------
procedure TExchangerThd.SetChannel(Value: PLIBSSH2_CHANNEL);
begin
if FChannel <> Value then
FChannel := Value;
end;
//---------------------------------------------------------------------------
procedure TExchangerThd.SetExchangeSocket(Value: TSocket);
begin
if FExchangeSocket <> Value then
FExchangeSocket := Value;
end;
//---------------------------------------------------------------------------
procedure TExchangerThd.SetPoolIndex(Value: Integer);
begin
if FPoolIndex <> Value then
FPoolIndex := Value;
end;
//---------------------------------------------------------------------------
{ TExchangerPool }
// Public
constructor TExchangerPool.Create;
var
I: Integer;
begin
inherited Create;
FCount := 0;
for I := 0 to MAX_POOL_SIZE - 1 do
PoolItem[I] := nil;
end;
//---------------------------------------------------------------------------
destructor TExchangerPool.Destroy;
begin
Clear;
inherited Destroy;
end;
//---------------------------------------------------------------------------
procedure TExchangerPool.Clear;
var
I: Integer;
begin
for I := 0 to MAX_POOL_SIZE - 1 do
begin
if PoolItem[I] <> nil then
begin
PoolItem[I].Terminate;
PoolItem[I].WaitFor;
PoolItem[I].Free;
PoolItem[I] := nil;
end;
end;
FCount := 0;
end;
//---------------------------------------------------------------------------
function TExchangerPool.Add(const ExchangerThd: TExchangerThd): Integer;
var
NewPoolItemIndex: Integer;
begin
NewPoolItemIndex := GetFreePoolItem;
if NewPoolItemIndex = INVALID_POOL_ITEM_INDEX then
begin
Result := INVALID_POOL_ITEM_INDEX;
Exit;
end;
PoolItem[NewPoolItemIndex] := ExchangerThd;
PoolItem[NewPoolItemIndex].OnTerminate := RemovePoolThread;
PoolItem[NewPoolItemIndex].PoolIndex := NewPoolItemIndex;
PoolItem[NewPoolItemIndex].Resume;
Inc(FCount);
Result := 0;
end;
//---------------------------------------------------------------------------
procedure TExchangerPool.Remove(const Index: Integer);
begin
if PoolItem[Index] <> nil then
begin
if not (PoolItem[Index].Terminated) then
begin
PoolItem[Index].Terminate;
PoolItem[Index].WaitFor;
end;
PoolItem[Index].Free;
PoolItem[Index] := nil;
Dec(FCount);
end;
end;
//---------------------------------------------------------------------------
// Private
function TExchangerPool.GetFreePoolItem: Integer;
var
I: Integer;
begin
Result := INVALID_POOL_ITEM_INDEX;
for I := 0 to MAX_POOL_SIZE - 1 do
begin
if PoolItem[I] = nil then
begin
Result := I;
Break;
end;
end;
end;
//---------------------------------------------------------------------------
procedure TExchangerPool.RemovePoolThread(Sender: TObject);
begin
Remove((Sender as TExchangerThd).PoolIndex);
end;
//---------------------------------------------------------------------------
function TExchangerPool.GetPoolItem(Index: Integer): TExchangerThd;
begin
Result := FPool[Index];
end;
//---------------------------------------------------------------------------
procedure TExchangerPool.SetPoolItem(Index: Integer; Value: TExchangerThd);
begin
if FPool[Index] <> Value then
FPool[Index] := Value;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
//GLS
GLCadencer, GLTexture, GLUserShader, GLWin32Viewer,
GLScene, GLObjects, GLAsyncTimer, GLScriptBase, GLScriptDWS2,
dws2OpenGL1x, dws2VectorGeometry, dws2Comp, GLMaterial, GLCoordinates,
GLCrossPlatform, GLBaseClasses, GLRenderContextInfo;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
Panel1: TPanel;
dws2OpenGL1xUnit1: Tdws2OpenGL1xUnit;
GLUserShader1: TGLUserShader;
ShaderScript: TMemo;
Recompile: TButton;
Enabled: TCheckBox;
Label1: TLabel;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLDummyCube1: TGLDummyCube;
GLLightSource1: TGLLightSource;
GLCube1: TGLCube;
GLMaterialLibrary1: TGLMaterialLibrary;
dws2VectorGeometryUnit1: Tdws2VectorGeometryUnit;
AsyncTimer1: TGLAsyncTimer;
GLDelphiWebScriptII1: TGLDelphiWebScriptII;
GLScriptLibrary1: TGLScriptLibrary;
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure RecompileClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure GLUserShader1DoApply(Sender: TObject;
var rci: TRenderContextInfo);
procedure GLUserShader1DoUnApply(Sender: TObject; Pass: Integer;
var rci: TRenderContextInfo; var Continue: Boolean);
procedure EnabledClick(Sender: TObject);
procedure AsyncTimer1Timer(Sender: TObject);
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
mx, my : Integer;
Compiled : Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
ShaderScript.Lines.AddStrings(GLScriptLibrary1.Scripts[0].Text);
// Compile the program when the form is created
RecompileClick(nil);
end;
procedure TForm1.RecompileClick(Sender: TObject);
begin
with GLScriptLibrary1.Scripts[0] do begin;
// Assign the script text from the memo
Text.Clear;
Text.AddStrings(ShaderScript.Lines);
// Compile/Recompiler and then start the script
Compile;
Start;
end;
end;
procedure TForm1.GLUserShader1DoApply(Sender: TObject;
var rci: TRenderContextInfo);
begin
// Call the scripted DoApply procedure to handle the shader application
GLScriptLibrary1.Scripts[0].Call('DoApply',[]);
end;
procedure TForm1.GLUserShader1DoUnApply(Sender: TObject; Pass: Integer;
var rci: TRenderContextInfo; var Continue: Boolean);
begin
// Call the scripted DoUnApply function to handle the shader unapplication
// pass the result of the scripted function to the Continue variable
Continue:=GLScriptLibrary1.Scripts[0].Call('DoUnApply',[Pass]);
end;
procedure TForm1.EnabledClick(Sender: TObject);
begin
GLUserShader1.Enabled:=Enabled.Checked;
end;
procedure TForm1.AsyncTimer1Timer(Sender: TObject);
begin
Form1.Caption:=GLSceneViewer1.FramesPerSecondText;
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x;
my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x;
my:=y;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
GLSceneViewer1.Invalidate;
end;
end.
|
unit TestOSFile.IoControl;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, Classes, SysUtils, OSFile.IoControl, OSFile.Handle, Windows,
OS.Handle;
type
// Test methods for class TIoControlFile
TConcreteIoControlFile = class(TIoControlFile)
protected
function GetMinimumPrivilege: TCreateFileDesiredAccess; override;
end;
TestTIoControlFile = class(TTestCase)
strict private
FIoControlFile: TConcreteIoControlFile;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestBuildOSBufferBy;
procedure TestBuildOSBufferByOutput;
procedure TestNormalOSControlCode;
procedure TestUnknownIoControlCode;
procedure TestIntMax;
end;
implementation
procedure TestTIoControlFile.SetUp;
begin
FIoControlFile := TConcreteIoControlFile.Create('');
end;
procedure TestTIoControlFile.TearDown;
begin
FIoControlFile.Free;
FIoControlFile := nil;
end;
procedure TestTIoControlFile.TestBuildOSBufferBy;
var
ReturnValue: TIoControlIOBuffer;
OutputBuffer: Integer;
InputBuffer: Integer;
begin
ReturnValue :=
FIoControlFile.BuildOSBufferBy<Integer, Integer>(InputBuffer, OutputBuffer);
CheckEquals(NativeUInt(@InputBuffer),
NativeUInt(ReturnValue.InputBuffer.Buffer), 'InputBuffer Pointer');
CheckEquals(NativeUInt(@OutputBuffer),
NativeUInt(ReturnValue.OutputBuffer.Buffer), 'OutputBuffer Pointer');
end;
procedure TestTIoControlFile.TestBuildOSBufferByOutput;
var
ReturnValue: TIoControlIOBuffer;
OutputBuffer: Integer;
begin
ReturnValue :=
FIoControlFile.BuildOSBufferByOutput<Integer>(OutputBuffer);
CheckEquals(NativeUInt(nil),
NativeUInt(ReturnValue.InputBuffer.Buffer), 'InputBuffer Pointer');
CheckEquals(NativeUInt(@OutputBuffer),
NativeUInt(ReturnValue.OutputBuffer.Buffer), 'OutputBuffer Pointer');
end;
procedure TestTIoControlFile.TestNormalOSControlCode;
const
IOCTL_SCSI_BASE = FILE_DEVICE_CONTROLLER;
IOCTL_STORAGE_BASE = $2D;
IOCTL_ATA_PASS_THROUGH =
(IOCTL_SCSI_BASE shl 16) or
((FILE_READ_ACCESS or FILE_WRITE_ACCESS) shl 14) or ($040B shl 2) or
(METHOD_BUFFERED);
IOCTL_ATA_PASS_THROUGH_DIRECT = $4D030;
IOCTL_SCSI_PASS_THROUGH =
(IOCTL_SCSI_BASE shl 16) or
((FILE_READ_ACCESS or FILE_WRITE_ACCESS) shl 14) or ($0401 shl 2) or
(METHOD_BUFFERED);
IOCTL_SCSI_MINIPORT =
(IOCTL_SCSI_BASE shl 16) or
((FILE_READ_ACCESS or FILE_WRITE_ACCESS) shl 14) or ($0402 shl 2) or
(METHOD_BUFFERED);
IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES =
(IOCTL_STORAGE_BASE shl 16) or
(FILE_WRITE_ACCESS shl 14) or ($0501 shl 2) or
(METHOD_BUFFERED);
IOCTL_SCSI_GET_ADDRESS =
(IOCTL_SCSI_BASE shl 16) or
(FILE_ANY_ACCESS shl 14) or ($0406 shl 2) or
(METHOD_BUFFERED);
begin
CheckEquals(
IOCTL_ATA_PASS_THROUGH,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.ATAPassThrough),
'ATAPassThrough');
CheckEquals(
IOCTL_ATA_PASS_THROUGH_DIRECT,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.ATAPassThroughDirect),
'ATAPassThroughDirect');
CheckEquals(
IOCTL_SCSI_PASS_THROUGH,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.SCSIPassThrough),
'SCSIPassThrough');
CheckEquals(
IOCTL_STORAGE_QUERY_PROPERTY,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.StorageQueryProperty),
'StorageQueryProperty');
CheckEquals(
IOCTL_STORAGE_CHECK_VERIFY,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.StorageCheckVerify),
'StorageCheckVerify');
CheckEquals(
FSCTL_GET_VOLUME_BITMAP,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.GetVolumeBitmap),
'GetVolumeBitmap');
CheckEquals(
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.GetVolumeDiskExtents),
'GetVolumeDiskExtents');
CheckEquals(
FSCTL_GET_NTFS_VOLUME_DATA,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.GetNTFSVolumeData),
'GetNTFSVolumeData');
CheckEquals(
IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.GetDriveGeometryEX),
'GetDriveGeometryEX');
CheckEquals(
IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.OSLevelTrim),
'OSLevelTrim');
CheckEquals(
IOCTL_SCSI_MINIPORT,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.ScsiMiniport),
'ScsiMiniport');
CheckEquals(
IOCTL_SCSI_GET_ADDRESS,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.GetScsiAddress),
'GetScsiAddress');
end;
procedure TestTIoControlFile.TestIntMax;
begin
StartExpectingException(EInvalidIoControlCode);
CheckEquals(
0,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode(Integer.MaxValue)),
'Out of range');
StopExpectingException('ControlCode: Integer.MaxValue');
end;
procedure TestTIoControlFile.TestUnknownIoControlCode;
begin
StartExpectingException(EInvalidIoControlCode);
CheckEquals(
0,
FIoControlFile.TDeviceIoControlCodeToOSControlCode(
TIoControlCode.Unknown),
'Unknown');
StopExpectingException('ControlCode: TIoControlCode.Unknown');
end;
{ TConcreteIoControlFile }
function TConcreteIoControlFile.GetMinimumPrivilege: TCreateFileDesiredAccess;
begin
result := TCreateFileDesiredAccess.DesiredNone;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTIoControlFile.Suite);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.