text stringlengths 14 6.51M |
|---|
unit Gatecash.Integration;
interface
type
{$SCOPEDENUMS ON}
TResponse = (COMMANDFAILURE, SUCCESS, COMMANDNOTINITIALIZED, INVALIDPARAMS);
{$SCOPEDENUMS OFF}
TResponseHelper = record helper for TResponse
/// <summary>
/// Retorna o valor que representa o tipo selecionado do enum.
/// </summary>
function ToInteger: Integer;
/// <summary>
/// Converte o enum para uma string de fácil entendimento para o usuário.
/// </summary>
function ToString: string;
/// <summary>
/// Converte o enum para um Texto de fácil entendimento para o usuário.
/// </summary>
function ToText: string;
end;
function IntToResponse(Value: Integer): TResponse;
/// Inicialização da comunicação com o GATECASH.
/// A aplicação deve inicializar a comunicação com o GATECASH antes que qualquer
/// evento de comunicação seja enviado. A inicialização da comunicação é
/// realizada apenas uma vez, quando o programa de frente de caixa é
/// inicializado.
/// Um arquivo de configuração (gcecho.config) é utilizado para carregar parâmetros.
/// Se não existir, um arquivo gcecho.config é gerado com valores padrão.
/// Para finalizar a comunicação com o GATECASH veja GATECASH_Finaliza().
/// @param CaminhoBase Caminho (path) básico onde GCPlug manipula arquivos auxiliares.
/// Normalmente é o caminho da aplicação. Usar "." para pasta local,
/// ou string vazia ("") para pasta do sistema operacional.
/// @param Servidor Sugestão de endereço IP do servidor GATECASH. Ex.: "127.0.0.1".
/// Essa informação é desconsiderada se o arquivo de configuração "gcecho.config"
/// tiver o parâmetro "Address". A configuração do arquivo é prioritária.
/// @param Pdv Sugestão de número do PDV que envia as mensagens.
/// Essa informação é desconsiderada se o arquivo de configuração "gcecho.config"
/// tiver o parâmetro "IdPdv". A configuração do arquivo é prioritária.
/// @remark Serão gravados registros de log em arquivos gcecho#.log, onde # indica
/// o dia da semana.
/// @return 0: Sucesso ao inicializar comunicação.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_Finaliza.
function GATECASH_InicializaEx(const CaminhoBase: string; Servidor: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Inicialização da comunicação com o GATECASH.
/// A aplicação deve inicializar a comunicação com o GATECASH antes que qualquer
/// evento de comunicação seja enviado. A inicialização da comunicação é
/// realizada apenas uma vez, quando o programa de frente de caixa é
/// inicializado.
/// Um arquivo de configuração (gcecho.config) é utilizado para carregar parâmetros.
/// Se não existir, um arquivo gcecho.config é gerado com valores padrão.
/// Para finalizar a comunicação com o GATECASH veja GATECASH_Finaliza().
/// @param CaminhoBase Caminho (path) básico onde GCPlug manipula arquivos auxiliares.
/// Normalmente é o caminho da aplicação. Usar "." para pasta local,
/// ou string vazia ("") para pasta do sistema operacional.
/// @param Servidor Sugestão de endereço IP do servidor GATECASH. Ex.: "127.0.0.1".
/// Essa informação é desconsiderada se o arquivo de configuração "gcecho.config"
/// tiver o parâmetro "Address". A configuração do arquivo é prioritária.
/// @param Pdv Sugestão de número do PDV que envia as mensagens.
/// Essa informação é desconsiderada se o arquivo de configuração "gcecho.config"
/// tiver o parâmetro "IdPdv". A configuração do arquivo é prioritária.
/// @param CaminhoLog Caminho onde será salvo o arquivo de log. Se esse caminho for
/// String vazia ou NULL, o caminho utilizado será o CaminhoBase.
/// @remark Serão gravados registros de log em arquivos gcecho#.log, onde # indica
/// o dia da semana.
/// @return 0: Sucesso ao inicializar comunicação.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_Finaliza.
function GATECASH_InicializaEx2(const CaminhoBase: string; const Servidor: string; Pdv: Integer; const CaminhoLog: string)
: Integer; stdcall; external 'GCPlug.dll';
/// Finalização da comunicação com o GATECASH.
/// A finalização da comunicação é realizada apenas uma vez, quando o programa
/// de frente de caixa é encerrado. Esta função força o término de qualquer
/// conexão com outros módulos do GATECASH. Nenhum evento de comunicação será
/// enviado após a finalização. Para habilitar o envio de eventos de
/// comunicação, veja GATECASH_Inicializa().
/// @return 0: Sucesso finalizar comunicação.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_Inicializa.
function GATECASH_Finaliza(): Integer; stdcall; external 'GCPlug.dll';
/// Evento de abertura do PDV.
/// A ser executado quando um operador inicia o acesso ao PDV (quando o PDV é aberto para vendas).
/// Também deve ser executado quando ocorrer troca o operador do PDV.
/// Geralmente associado ao login do operador no sistema de frente de caixa.
/// @param Funcionario Nome do funcionário que abriu o caixa.
/// Se não disponível, informar string vazia ("").
/// @param Codigo Codigo do funcionário que abriu o caixa.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_AbrePdvEx(const Funcionario: string; const Codigo: string): Integer; stdcall; external 'GCPlug.dll';
/// Evento de fechamento do PDV.
/// A ser executado quando o operador finaliza o acesso ao PDV
/// (quando o PDV é fechado ou colocado em pausa). Este NÃO é o evento de
/// REDUÇÃO Z, e o caixa pode ser aberto novamente (ver GATECASH_AbrePdv).
/// Geralmente associado ao logout do operador do sistema de frente de caixa.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_AbrePdv.
function GATECASH_FechaPdv(): Integer; stdcall; external 'GCPlug.dll';
/// Informação de operador.
/// Adicionada em 201710 para manter mais consistente as informações de operador no sistema.
/// @param Funcionario Nome do funcionário que abriu o caixa.
/// @param Codigo Codigo do funcionário que abriu o caixa. Se não disponível, informar string vazia.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_InformaOperador(const Funcionario: string; const Codigo: string): Integer; stdcall; external 'GCPlug.dll';
/// Registro de suprimento de caixa.
/// A ser executado quando o processo de suprimento de caixa é iniciado.
/// @param FormaPagamento String com nome da forma do suprimento de caixa.
/// @param Complemento Descrição complementar da operação realizada.
/// Se não utilizado, informar string vazia ("").
/// @param Valor Valor do suprimento (adicionado ao caixa).
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_Suprimento(const FormaPagamento: string; const Complemento: string; Valor: Double): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de sangria do caixa.
/// A ser executado quando o processo de sangria do caixa é iniciado.
/// @param Complemento Descrição complementar da operação realizada.
/// Se não utilizado, informar string vazia ("").
/// @param Valor Valor da sangria (retirado do caixa).
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_Sangria(const Complemento: string; Valor: Double): Integer; stdcall; external 'GCPlug.dll';
/// Registro de operação genérica no PDV.
/// A ser executado quando forem realizadas operações genéricas no PDV não associadas
/// a um cupom. Por exemplo, operações não-fiscais, leitura x, redução z, etc.
/// @param Operacao Nome da operação realizada.
/// @param Complemento Descrição complementar da operação realizada.
/// Se não utilizado, informar string vazia ("").
/// @param Valor Valor associado à operação. Se não aplicável, utilizar zero.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_Operacao(const Operacao: string; const Complemento: string; Valor: Double): Integer; stdcall;
external 'GCPlug.dll';
/// Informa que gaveta foi aberta ou fechada.
/// A ser executado no instante em que a gaveta é acionada para abertura.
/// A execução deste comando é opcional quando for detectado o fechamento da gaveta.
/// @param Aberta Indica se é um evento de abertura da gaveta (1) ou fechamento da gaveta (0).
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_Gaveta(Aberta: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de abertura de cupom.
/// A ser executado quando o comando de abertura de cupom é registrado.
/// Cupom é finalizado pelo comando GATECASH_FechaDocumento().
/// @param Codigo Identificador numérico do cupom. Em geral, COO ou CNF.
/// Se não disponível, informar -1.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_FechaDocumento.
function GATECASH_AbreCupom(Codigo: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de abertura de documento genérico.
/// A ser executado quando for registrada a abertura de um documento (exceto cupom fiscal).
/// Alguns documentos genéricos são: cupom não fiscal, relatório gerencial, etc.
/// Um documento genérico é finalizado pelo comando GATECASH_FechaDocumento().
/// Em caso de documento instantâneo (sem duração variável), recomenda-se utilizar o comando
/// GATECASH_Operacao().
/// @param Nome String com nome do documento genérico aberto.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_Operacao()
/// @sa GATECASH_FechaDocumento.
function GATECASH_AbreDocumento(const Nome: string): Integer; stdcall; external 'GCPlug.dll';
/// Fechamento de cupom ou documento.
/// A ser executado quando o cupom fiscal ou um documento genérico for finalizado.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_AbreCupom, GATECASH_AbreDocumento.
function GATECASH_FechaDocumento(): Integer; stdcall; external 'GCPlug.dll';
/// Fechamento de cupom ou documento.
/// A ser executado quando o cupom fiscal ou um documento genérico for finalizado.
/// @param Codigo - o código do documento que está sendo fechado.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_AbreCupom, GATECASH_AbreDocumento.
function GATECASH_FechaDocumentoCod(Codigo: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro do cancelamento de um cupom arbitrário.
/// A ser executado quando o cancelamento do cupom é efetivado.
/// @param Codigo Identificador numérico do cupom. Em geral, COO ou CNF.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_CancelandoCupom.
function GATECASH_CancelaCupomEx(Codigo: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro da anulação de uma venda já fechada.
/// @param Pdv Identificador do PDV no qual foi realizada a venda anteriormente.
/// @param Codigo Identificador numérico do cupom. Em geral, COO ou CNF.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_AnulaCupom(Pdv: Integer; Codigo: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Associa informação de cliente ao cupom.
/// Deve ser executado enquanto o cupom está aberto e informa o cliente que realiza a compra.
/// Geralmente executado logo após a abertura do cupom ou pouco antes do seu fechamento.
/// @param Cliente String com nome do cliente ou string com número que o identifica (RG, CPF, etc).
/// @param Codigo String com o código do cliente.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_InformaClienteEx(const Cliente: string; const Codigo: string): Integer; stdcall; external 'GCPlug.dll';
/// Associa informação de Supervisor ao cupom (quem aprovou alguma operação que necessitava aprovação).
/// @param Supervisor é o identificador do supervisor que aprovou a operação.
/// @param Codigo é o código do supervisor que aprovou a operação.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_InformaSupervisor(const Supervisor: string; const Codigo: string): Integer; stdcall; external 'GCPlug.dll';
/// Registro de acréscimo ou desconto ao valor total do cupom.
/// A ser executado quando algum acréscimo ou desconto ao valor total do cupom é
/// impresso. Este registro normalmente é associado ao início do fechamento do
/// cupom, ou seja, depois do último item vendido e antes do registro da
/// primeira forma de pagamento. O registro de diferença no cupom não é
/// necessário caso não haja acréscimo ou desconto ao valor total do cupom.
/// A especificação de diferença do cupom NÃO é acumulativa.
/// Será considerada apenas a última chamada de GATECASH_DiferencaCupom() para cada cupom.
/// @param Diferenca Acréscimo (positivo) ou desconto (negativo) no valor total do cupom.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_DiferencaCupom(Diferenca: Double): Integer; stdcall; external 'GCPlug.dll';
/// Registro de venda de item diferenciação se é unitário e se foi digitado...
/// A ser executado quando a venda de item (com ou sem desconto) é registrada.
/// Se o item tiver acréscimo ou desconto, esta diferença de valor deve ser informada chamando
/// GATECASH_DiferencaItem() logo após o registro do item, informando o valor de acréscimo/desconto.
/// @param Sequencia Índice da seqüência do item vendido no cupom. É o mesmo índice que será
/// utilizado como referência para registro de diferença de item, cancelamento de item, etc.
/// @param Codigo String com código do produto vendido (código de barras).
/// @param Descricao String com descrição do produto vendido.
/// @param Quantidade Quantidade da venda do produto.
/// @param ValorUnitario Valor unitário do produto.
/// Valor da venda é calculado por Quantidade X ValorUnitário.
/// @param Unitario flag que indica se o item é unitário ou é um item que possui venda por peso.
/// @param Scaneado flag que indica se o item foi escaneado ou digitado.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_DiferencaItem.
function GATECASH_VendeItemEx(Sequencia: Integer; const Codigo: string; const Descricao: string;
Quantidade: Double; ValorUnitario: Double; Unitario: Boolean; Escaneado: Boolean): Integer; stdcall; external 'GCPlug.dll';
/// Registro de venda de item com diferenciação se é unitário e se foi digitado..
/// Esse registro de venda de item deve ser utilizado apenas para itens fora do padrão (como, por exemplo, itens que são
/// escaneados com scanner de mão. Itens registrados com scanners de mesa ou digitados devem ser registrados com os métodos
/// VendeItem e VendeItemEx.
/// Se o item tiver acréscimo ou desconto, esta diferença de valor deve ser informada chamando
/// GATECASH_DiferencaItem() logo após o registro do item, informando o valor de acréscimo/desconto.
/// @param Sequencia Índice da seqüência do item vendido no cupom. É o mesmo índice que será
/// utilizado como referência para registro de diferença de item, cancelamento de item, etc.
/// @param Codigo String com código do produto vendido (código de barras).
/// @param Descricao String com descrição do produto vendido.
/// @param Quantidade Quantidade da venda do produto.
/// @param ValorUnitario Valor unitário do produto.
/// Valor da venda é calculado por Quantidade X ValorUnitário.
/// @param Unitario flag que indica se o item é unitário ou é um item que possui venda por peso.
/// @param Scaneado flag que indica se o item foi escaneado ou digitado.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_DiferencaItem.
function GATECASH_VendeItemFp(Sequencia: Integer; const Codigo: string; const Descricao: string;
Quantidade: Double; ValorUnitario: Double; Unitario: Boolean; Escaneado: Boolean; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Consulta de preço de produto.
/// A ser executado quando for feita a consulta de preço de um produto,
/// independente de haver um cupom aberto ou não.
/// @param Codigo String com código do produto consultado.
/// @param Descricao String com descrição do produto consultado.
/// @param ValorUnitario Valor unitário do produto.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_ConsultaProduto(const Codigo: string; const Descricao: string; Valor: Double; Unitario: Boolean): Integer;
stdcall; external 'GCPlug.dll';
/// Registro do cancelamento de item.
/// A ser executado quando o cancelamento de item é registrado (quando é efetivado).
/// @param Sequencia Índice do item que foi cancelado.
/// Ex.: 1 indica o primeiro item do cupom. Se -1, indica último item vendido.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_CancelaItem(Sequencia: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de acréscimo ou desconto a uma venda de item.
/// A ser executado ao registrar acréscimo ou desconto à venda de um item.
/// Em geral é executado imediatamente após GATECASH_VendeItem,
/// registrando a diferença lançada no item vendido. A diferença lançada por
/// GATECASH_DiferencaItem() NÃO é acumulativa. O registro de diferença no item não é
/// necessário caso não haja acréscimo ou desconto ao valor do item vendido.
/// @param Sequencia Índice do item referente ao acréscimo/desconto.
/// Ex.: 1 indica o primeiro item do cupom. Se -1, indica o último item vendido.
/// @param Diferenca Valor absoludo de acréscimo (positivo) ou desconto (negativo)
/// no valor da venda do item.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_VendeItem.
function GATECASH_DiferencaItem(Sequencia: Integer; Diferenca: Double): Integer; stdcall; external 'GCPlug.dll';
/// Registro de acréscimo ou desconto a uma venda de item.
/// A ser executado ao registrar acréscimo ou desconto à venda de um item.
/// Em geral é executado imediatamente após GATECASH_VendeItem,
/// registrando a diferença lançada no item vendido. A diferença lançada por
/// GATECASH_DiferencaItem() NÃO é acumulativa. O registro de diferença no item não é
/// necessário caso não haja acréscimo ou desconto ao valor do item vendido.
/// @param Sequencia Índice do item referente ao acréscimo/desconto.
/// Ex.: 1 indica o primeiro item do cupom. Se -1, indica o último item vendido.
/// @param Diferenca Valor absoludo de acréscimo (positivo) ou desconto (negativo)
/// no valor da venda do item.
/// @param Motivo é a razão do desconto.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_VendeItem.
function GATECASH_DiferencaItemEx(Sequencia: Integer; Diferenca: Double; const Motivo: string): Integer; stdcall;
external 'GCPlug.dll';
/// Informa desmagnetização de etiqueta magnética durante um cupom ou documento.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_Desmagnetizacao(): Integer; stdcall; external 'GCPlug.dll';
/// Registro de forma de pagamento.
/// A ser executado quando uma forma de pagamento for registrada.
/// @param FormaPagamento String com nome da forma de pagamento.
/// @param Valor Valor pago através da forma de pagamento.
/// @param Complemento Informação adicional associada ao pagamento. Ex.: Número do cartão.
/// Se não disponível, informar string vazia ("").
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_FormaPagamento(const FormaPagamento: string; const Complemento: string; Valor: Double): Integer; stdcall;
external 'GCPlug.dll';
/// Cancelamento de registro de forma de pagamento.
/// A ser executado quando for registrado o estorno de uma forma de pagamento.
/// Em geral, o valor estornado de uma forma de pagamento é movido para ser registrado em outra
/// forma de pagamento. Neste caso, um cancelamento de pagamento deve ser seguido de um novo
/// comando de forma de pagamento GATECASH_FormaPamento() com o mesmo valor estornado.
/// @param FormaPagamento String com nome da forma de pagamento cancelada.
/// @param Valor Valor cancelado da forma de pagamento.
/// Não negativar o valor cancelado. Ex.: se estornado R$10, informar 10.
/// @param Complemento Informação adicional associada ao cancelamento.
/// Se não disponível, informar string vazia ("").
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_CancelaPagamento(const FormaPagamento: string; const Complemento: string; Valor: Double): Integer; stdcall;
external 'GCPlug.dll';
/// Informacao de erro genérico do sistema.
/// Informações como o Erro de comunicação com impressora, fim de papel, enfim, qualquer erro.
/// @param CodigoErro string que define o código do erro
/// @param NomeErro string que define o nome do erro
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando
function GATECASH_ErroGenerico(const CodigoErro: string; const NomeErro: string): Integer; stdcall; external 'GCPlug.dll';
/// Informacao de Alerta genérico do sistema
/// Alertas como pouco papel em impressora, inatividade, etc podem ser registrados por esse alerta.
/// @param CodigoAlerta string que define o código do Alerta
/// @param NomeAlerta string que define o nome do Alerta
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando
function GATECASH_AlertaGenerico(const CodigoAlerta: string; const NomeAlerta: string): Integer; stdcall; external 'GCPlug.dll';
/// Informacao de Ocorrência genérica.
/// Ocorrências como pedido de ajuda de cliente, Terminal inativo, etc podem ser registrados por esta mensagem.
/// @param CodigoOcorrencia string que define o código da Ocorrencia
/// @param NomeOcorrencia string que define o nome da Ocorrencia
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando
function GATECASH_OcorrenciaGenerico(const CodigoOcorrencia: string; const NomeOcorrencia: string): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de abertura de transferência de mercadoria
/// Deve ser executada quando uma operação de transferência de mercadoria tem início
/// Uma abertura de transferência é finalizada pelo comando GATECASH_FechaTransferência().
/// @param Identificador String identificando o processo de transferência
/// @param NomeLocal String identificando o local da transferência
/// @param DataEmissao Data de emissão da nota fiscal ou pedido
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_SuspendeTransferencia
/// @sa GATECASH_FechaTransferencia
function GATECASH_AbreTransferencia(const Identificador: string; const NomeLocal: string; DataEmissao: TDate): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de nota fiscal.
/// Alguns casos de sistema de recebimento podem ter mais de uma nota fiscal vinculada, por isso a criação dessa função.
/// @param Identificador String identificando o processo de transferência
/// @param Serie String identificando Série no processo de transferência
/// @param DataEmissao data emissão da nota
/// @param Entrada booleano que indica se é entrada (true) ou saída (false)
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_AbreTransferencia
function GATECASH_InformaNF(const Identificador: string; const Serie: string; DataEmissao: TDate; Entrada: Boolean): Integer;
stdcall; external 'GCPlug.dll';
/// Registro de suspensão de transferência de mercadoria
/// Deve ser executada quando uma operação de transferência de mercadoria é interrompida por algum motivo
/// Uma transferência pode ser retomada pelo comando GATECASH_RetomaTransferencia().
/// @param Identificador String identificando o processo de transferência
/// @param Motivo String identificando o motivo da suspensão da transferência
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_RetomaTransferencia
function GATECASH_SuspendeTransferencia(const Identificador: string; const Motivo: string): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de retomada de transferência de mercadoria
/// Deve ser executada quando uma operação de transferência de mercadoria estava interrompida e foi retomada
/// Uma transferência pode ser suspendida pelo comando GATECASH_SuspendeTransferencia().
/// @param Identificador String identificando o processo de transferência
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_SuspendeTransferencia
function GATECASH_RetomaTransferencia(const Identificador: string): Integer; stdcall; external 'GCPlug.dll';
/// Registro de cancelamento de transferência de mercadoria
/// Deve ser executada quando uma operação de transferência de mercadoria é cancelada antes de ser concluída
/// Impossibilita qualquer ação posterior vinculada a essa transferência
/// @param Identificador String identificando o processo de transferência
/// @param Motivo String identificando o motivo do cancelamento da transferência
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_AbreTransferencia
/// @sa GATECASH_FechaTransferencia
function GATECASH_CancelaTransferencia(const Identificador: string; const Motivo: string): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de fechamento de transferência de mercadoria
/// Deve ser executada quando uma operação de transferência de mercadoria é concluída com sucesso
/// Impossibilita qualquer ação posterior vinculada a essa transferência
/// @param Identificador String identificando o processo de transferência
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_AbreTransferencia
/// @sa GATECASH_CancelaTransferencia
function GATECASH_FechaTransferencia(const Identificador: string): Integer; stdcall; external 'GCPlug.dll';
/// Registro do tipo de transferência que está sendo realizada
/// Deve ser executada após a abertura de uma transferência
/// É vinculada à transferência atualmente ativa
/// @param Tipo inteiro que informa a natureza da transferência: 1 - Recebimento; 2 - Devolução; 3 - Saída; 4 - Outros
/// @param Descricao usado para informar o nome caso seja a transferência seja do tipo outros
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_InformaConferente
/// @sa GATECASH_InformaFornecedor
function GATECASH_InformaTipoTransferencia(Tipo: Integer; const Descricao: string): Integer; stdcall; external 'GCPlug.dll';
/// Registro do funcionário que está conferindo a transferência
/// Deve ser executada após a abertura de uma transferência
/// É vinculada à transferência atualmente ativa
/// @param Identificador Código do conferente que está realizando a transferência
/// @param Nome Nome do conferente que está realizando a transferência
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_InformaTipoTransferencia
/// @sa GATECASH_InformaFornecedor
function GATECASH_InformaConferente(const Identificador: string; const Nome: string): Integer; stdcall; external 'GCPlug.dll';
/// Registro do fornecedor da transferência
/// Deve ser executada após a abertura de uma transferência
/// É vinculada à transferência atualmente ativa
/// @param Identificador Código do fornecedor atribuído à transferência
/// @param Nome Nome do fornecedor atribuído à transferência
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_InformaTipoTransferencia
/// @sa GATECASH_InformaConferente
function GATECASH_InformaFornecedor(const Identificador: string; const Nome: string): Integer; stdcall; external 'GCPlug.dll';
/// Registro de saída de veículo
/// Deve ser executado apenas em uma transferência do tipo saída
/// @param Placa Placa associada ao veículo de transporte
/// @param TipoVeiculo Nome associado ao veículo de transporte
/// @param CodigoMotorista Identificador que pode ser CPF, RG ou CNH
/// @param NomeMotorista Nome do Condutor
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_InformaFornecedor
/// @sa GATECASH_InformaTipoTransferencia
function GATECASH_InformaSaidaVeiculo(const Placa: string; const TipoVeiculo: string;
const CodigoMotorista: string; const NomeMotorista: string): Integer; stdcall; external 'GCPlug.dll';
/// Sinaliza o início de uma contagem ou recontagem
/// Deve ser executada após a abertura de uma transferência e antes de iniciar a transferência de itens
/// É vinculada à transferência atualmente ativa
/// @param Tipo Usado para identificar se os itens que serão transferidos pertencem a uma contagem (1) ou recontagem (2)
/// @return 0: Sucesso ao enviar evento
/// @return -1: Comunicação não inicializada
/// @return -999: Falha ao executar comando
/// @sa GATECASH_InformaTipoTransferencia
/// @sa GATECASH_InformaConferente
function GATECASH_RegistraContagem(Tipo: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de transferência de item.
/// Deve ser executada após um registro de contagem e antes do fechamento de transferência de itens
/// @param Sequencia Índice da sequência do item transferido. É o mesmo índice que será
/// utilizado como referência para cancelamento de item
/// @param Codigo String com código do produto transferido (normalmente código de barras).
/// @param Descricao String com descrição do produto transferido.
/// @param NomeTipoEmbalagem String com nome associado ao tipo de embalagem, i.e. pallet, caixa, fardo, ...
/// @param QuantidadeEmbalagem Quantidade de embalagem na transferência
/// @param QuantidadeItem Quantidade total de itens na transferência
/// @param Validade Validade do lote de itens transferidos
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_RegistraContagem
/// @sa GATECASH_CancelaItemTransferencia
function GATECASH_TransfereItem(Sequencia: Integer; const Codigo: string; const Descricao: string;
const Nome: string; TipoEmbalagem, QuantidadeEmbalagem: Integer;
QuantidadeItem: Double; Validade: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de cancelamento de um item da transferência.
/// Deve ser executada após um registro de contagem e antes do fechamento de transferência de itens
/// @param Sequencia Índice da sequência do item transferido a ser cancelado
/// @param QuantidadeItem Quantidade de itens que foram cancelados
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_RegistraContagem
/// @sa GATECASH_TransfereItem
function GATECASH_CancelaItemTransferencia(Sequencia: Integer; QuantidadeItem: Double): Integer; stdcall; external 'GCPlug.dll';
//* *********** METHODS THAT INFORM MULTIPLES PDVS IN ONE INSTANCE OF GATECASH ******* *//
//* ******************** OPERATION EQUALS THE ABOVE FUNCTIONS **************** ******* *//
/// Evento de abertura de um determinado pdv.
function GATECASH_AbrePdvEx_InformPDV(const Funcionario: string; const Codigo: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Evento de fechamento de um determinado PDV.
function GATECASH_FechaPdv_InformPDV(Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Informação de operador de um determinado pdv.
function GATECASH_InformaOperador_InformPDV(const Funcionario: string; const Codigo: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de suprimento de caixa de um determinado pdv.
function GATECASH_Suprimento_InformPDV(const FormaPagamento: string; const Complemento: string; Valor: Double; Pdv: Integer)
: Integer; stdcall; external 'GCPlug.dll';
/// Registro de sangria do caixa de um determinado pdv.
function GATECASH_Sangria_InformPDV(const Complemento: string; Valor: Double; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de operação genérica de um determinado pdv.
function GATECASH_Operacao_InformPDV(const Operacao: string; const Complemento: string; Valor: Double; Pdv: Integer): Integer;
stdcall; external 'GCPlug.dll';
/// Informa que gaveta foi aberta ou fechada de um determinado pdv.
function GATECASH_Gaveta_InformPDV(Aberta: Integer; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de abertura de cupom de um determinado pdv.
function GATECASH_AbreCupom_InformPDV(Codigo: Integer; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de abertura de documento genérico de um determinado pdv.
function GATECASH_AbreDocumento_InformPDV(const Nome: string; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Fechamento de cupom ou documento de um determinado pdv.
function GATECASH_FechaDocumento_InformPDV(Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Fechamento de cupom ou documento de um determinado pdv.
function GATECASH_FechaDocumentoCod_InformPDV(Codigo: Integer; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro do cancelamento de um cupom arbitrário de um determinado pdv.
function GATECASH_CancelaCupomEx_InformPDV(Codigo: Integer; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro da anulação de uma venda já fechada de um determinado pdv.
function GATECASH_AnulaCupom_InformPDV(Pdv: Integer; Codigo: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Associa informação de cliente ao cupom de um determinado pdv.
function GATECASH_InformaClienteEx_InformPDV(const Cliente: string; const Codigo: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Associa informação de Supervisor ao cupom (quem aprovou alguma operação que necessitava aprovação) de um determinado pdv.
function GATECASH_InformaSupervisor_InformPDV(const Supervisor: string; const Codigo: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de acréscimo ou desconto ao valor total do cupom de um determinado pdv.
function GATECASH_DiferencaCupom_InformPDV(Diferenca: Double; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de venda de item diferenciação se é unitário e se foi digitado...de um determinado pdv
function GATECASH_VendeItemEx_InformPDV(Sequencia: Integer; const Codigo: string; const Descricao: string;
Quantidade: Double; ValorUnitario: Double; Unitario: Boolean; Escaneado: Boolean; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de venda de item com diferenciação se é unitário e se foi digitado.. de um determinado pdv
function GATECASH_VendeItemFp_InformPDV(Sequencia: Integer; const Codigo: string; const Descricao: string;
Quantidade: Double; ValorUnitario: Double; Unitario: Boolean; Escaneado: Boolean; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Consulta de preço de produto de um determinado pdv.
function GATECASH_ConsultaProduto_InformPDV(const Codigo: string; const Descricao: string; ValorUnitario: Double; Pdv: Integer)
: Integer; stdcall; external 'GCPlug.dll';
/// Registro do cancelamento de item de um determinado pdv.
function GATECASH_CancelaItem_InformPDV(Sequencia: Integer; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de acréscimo ou desconto a uma venda de item de um determinado pdv.
function GATECASH_DiferencaItem_InformPDV(Sequencia: Integer; Diferenca: Double; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de acréscimo ou desconto a uma venda de item de um determinado pdv.
function GATECASH_DiferencaItemEx_InformPDV(Sequencia: Integer; Diferenca: Double; const Motivo: string; Pdv: Integer): Integer;
stdcall; external 'GCPlug.dll';
/// Informa desmagnetização de etiqueta magnética durante um cupom ou documento de um determinado pdv.
function GATECASH_Desmagnetizacao_InformPDV(Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de forma de pagamento de um determinado pdv.
function GATECASH_FormaPagamento_InformPDV(const FormaPagamento: string; const Complemento: string; Valor: Double; Pdv: Integer)
: Integer; stdcall; external 'GCPlug.dll';
/// Cancelamento de registro de forma de pagamento de um determinado pdv.
function GATECASH_CancelaPagamento_InformPDV(const FormaPagamento: string; const Complemento: string; Valor: Double; Pdv: Integer)
: Integer; stdcall; external 'GCPlug.dll';
/// Informacao de erro genérico do sistema de um determinado pdv.
function GATECASH_ErroGenerico_InformPDV(const CodigoErro: string; const NomeErro: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Informacao de Alerta genérico do sistema de um determinado pdv
function GATECASH_AlertaGenerico_InformPDV(const CodigoAlerta: string; const NomeAlerta: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Informacao de Ocorrência genérica de um determinado pdv.
function GATECASH_OcorrenciaGenerico_InformPDV(const CodigoOcorrencia: string; const NomeOcorrencia: string; Pdv: Integer)
: Integer; stdcall; external 'GCPlug.dll';
/// Registro de abertura de transferência de mercadoria de um determinado pdv
function GATECASH_AbreTransferencia_InformPDV(const Identificador: string; const NomeLocal: string; DataEmissao: TDate;
Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de suspensão de transferência de mercadoria de um determinado pdv
function GATECASH_SuspendeTransferencia_InformPDV(const Identificador: string; const Motivo: string; Pdv: Integer): Integer;
stdcall; external 'GCPlug.dll';
/// Registro de retomada de transferência de mercadoria de um determinado pdv
function GATECASH_RetomaTransferencia_InformPDV(const Identificador: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de cancelamento de transferência de mercadoria de um determinado pdv
function GATECASH_CancelaTransferencia_InformPDV(const Identificador: string; const Motivo: string; Pdv: Integer): Integer;
stdcall; external 'GCPlug.dll';
/// Registro de fechamento de transferência de mercadoria de um determinado pdv
function GATECASH_FechaTransferencia_InformPDV(const Identificador: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro do tipo de transferência que está sendo realizada de um determinado pdv
function GATECASH_InformaTipoTransferencia_InformPDV(Tipo: Integer; const Descricao: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro do funcionário que está conferindo a transferência de um determinado pdv
function GATECASH_InformaConferente_InformPDV(const Identificador: string; const Nome: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro do fornecedor da transferência de um determinado pdv
function GATECASH_InformaFornecedor_InformPDV(const Identificador: string; const Nome: string; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de saída de veículo de um determinado pdv
function GATECASH_InformaSaidaVeiculo_InformPDV(const Placa: string; const TipoVeiculo: string;
const CodigoMotorista: string; const NomeMotorista: string; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Sinaliza o início de uma contagem ou recontagem de um determinado pdv
function GATECASH_RegistraContagem_InformPDV(Tipo: Integer; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de transferência de item de um determinado pdv.
function GATECASH_TransfereItem_InformPDV(Sequencia: Integer; const Codigo: string; const Descricao: string;
const NomeTipoEmbalagem: string; QuantidadeEmbalagem: Integer;
QuantidadeItem: Double; Validade: Integer; Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Registro de cancelamento de um item da transferência de um determinado pdv.
function GATECASH_CancelaItemTransferencia_InformPDV(Sequencia: Integer; QuantidadeItem: Double; Pdv: Integer): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de informação de nota fiscal.
function GATECASH_InformaNF_InformPDV(const Identificador: string; const Serie: string; DataEmissao: TDate; Entrada: Boolean;
Pdv: Integer): Integer; stdcall; external 'GCPlug.dll';
//* ****************************** DEPRECATED METHODS ******************************** *//
/// Inicialização da comunicação com o GATECASH (simplificado).
/// Equivale a executar GATECASH_InicializaEx() sem informar Servidor e Pdv.
/// Veja documentação de GATECASH_InicializaEx() para mais informações.
/// @param CaminhoBase Caminho (path) básico onde GCPlug manipula arquivos auxiliares.
/// @return 0: Sucesso ao inicializar comunicação.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_InicializaEx.
/// @sa GATECASH_Finaliza.
/// @remark Servidor e Pdv devem estar especificados no arquivo de configuração.
function GATECASH_Inicializa(const CaminhoBase: string): Integer; stdcall; external 'GCPlug.dll';
/// Evento de abertura do PDV.
/// A ser executado quando um operador inicia o acesso ao PDV (quando o PDV é aberto para vendas).
/// Também deve ser executado quando ocorrer troca o operador do PDV.
/// Geralmente associado ao login do operador no sistema de frente de caixa.
/// @param Funcionario Nome do funcionário que abriu o caixa.
/// Se não disponível, informar string vazia ("").
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_AbrePdv(const Funcionario: string): Integer; stdcall; external 'GCPlug.dll';
/// Associa informação de cliente ao cupom.
/// Deve ser executado enquanto o cupom está aberto e informa o cliente que realiza a compra.
/// Geralmente executado logo após a abertura do cupom ou pouco antes do seu fechamento.
/// @param Cliente String com nome do cliente ou string com número que o identifica (RG, CPF, etc).
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_InformaCliente(const Cliente: string): Integer; stdcall; external 'GCPlug.dll';
/// Início do cancelamento do último cupom.
/// A ser executado quando o processo de cancelamento de cupom é iniciado.
/// Em geral, quando o operador de caixa solicita a presença do supervisor para cancelar o cupom.
/// O cancelamento refere-se ao último cupom registrado, que pode já ter sido concluído ou não.
/// Este comando é opcional, pois em muitos sistemas de frente de caixa o "início de cancelamento"
/// não passa pelo sistema.
/// Independente de executar GATECASH_CancelandoCupom(), o comando GATECASH_CancelaCupom()
/// deverá ser executado quando o cancelamento do cupom for efetivado (enviado à impressora).
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_CancelaCupom.
function GATECASH_CancelandoCupom(): Integer; stdcall; external 'GCPlug.dll';
/// Registro do cancelamento do último cupom.
/// A ser executado quando o cancelamento do cupom é registrado (quando é efetivado).
/// O cancelamento refere-se ao último cupom registrado, que pode já ter sido concluído ou não.
/// Caso o cancelamento tenha sido iniciado (ver GATECASH_CancelandoCupom()) e não efetivado,
/// basta não executar este comando.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_CancelandoCupom.
function GATECASH_CancelaCupom(): Integer; stdcall; external 'GCPlug.dll';
/// Adiciona detalhe a um cupom ou documento genérico.
/// Deve ser executado enquando houver um cupom ou documento genérico aberto.
/// A execução deste comando depende da regra de negócio da aplicação.
/// Detalhes são listados ao visualizar um cupom ou documento genérico, mas não são computados
/// como vendas e não são totalizados no cupom ou documento genérico.
/// @param Nome String com nome do tipo de detalhe adicionado.
/// @param Complemento Descrição complementar do detalhe adicionado.
/// Se não utilizado, informar string vazia ("").
/// @param Valor Valor associado ao detalhe. Se não aplicável, informar 0.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_InformaDetalhe(const Nome: string; const Complemento: string; Valor: Double): Integer; stdcall;
external 'GCPlug.dll';
/// Registro de venda de item.
/// A ser executado quando a venda de item (com ou sem desconto) é registrada.
/// Se o item tiver acréscimo ou desconto, esta diferença de valor deve ser informada chamando
/// GATECASH_DiferencaItem() logo após o registro do item, informando o valor de acréscimo/desconto.
/// @param Sequencia Índice da seqüência do item vendido no cupom. É o mesmo índice que será
/// utilizado como referência para registro de diferença de item, cancelamento de item, etc.
/// @param Codigo String com código do produto vendido (código de barras).
/// @param Descricao String com descrição do produto vendido.
/// @param Quantidade Quantidade da venda do produto.
/// @param ValorUnitario Valor unitário do produto.
/// Valor da venda é calculado por Quantidade X ValorUnitário.
/// @param Indice Número adicional associado à venda do item. A ser definido
/// pela regra de negócio. Se não disponível, informar -1.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_DiferencaItem.
function GATECASH_VendeItem(Sequencia: Integer; const Codigo: string; const Descricao: string;
Quantidade: Double; ValorUnitario: Double; Indice: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Início do cancelamento de item.
/// A ser executado quando o processo de cancelamento de item é iniciado.
/// Em geral, quando o operador de caixa solicita a presença do supervisor para cancelar o item.
/// Este comando é opcional, pois em muitos sistemas de frente de caixa o "início de cancelamento"
/// não passa pelo sistema.
/// Independente de executar GATECASH_CancelandoItem(), o comando GATECASH_CancelaItem()
/// deverá ser executado quando o cancelamento do item for efetivado (enviado à impressora).
/// @param Sequencia Índice do item a ser cancelado.
/// Ex.: 1 indica o primeiro item do cupom. Se -1, indica último item vendido.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_CancelaItem.
function GATECASH_CancelandoItem(Sequencia: Integer): Integer; stdcall; external 'GCPlug.dll';
//* ****************************** UNDOCUMENTED METHODS ******************************** *//
/// Envia mensagem de evento com protocolo público.
/// @param Mensagem String que retornará com mensagem montada.
/// @param Tamanho Tamanho da string de retorno (em bytes).
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
function GATECASH_EventoPublico(const Mensagem: string; Tamanho: Integer): Integer; stdcall; external 'GCPlug.dll';
/// Monta mensagem de evento com protocolo público.
/// A execução deste comando não depende da inicialização da comunicação.
/// Este comando expoe os principais campos disponíveis no protocolo público,
/// mas apenas alguns campos são utilizados em cada tipo de evento.
/// Utilize valor ZERO ou strings NULAS como valores default dos campos.
/// @param Mensagem String que retornará com mensagem montada.
/// @param Tamanho Tamanho da string de retorno (em bytes). Normalmente 140.
/// @param Pdv Identificador do PDV.
/// @param Evento Código indicando o tipo do evento.
/// @param Codigo Código do produto, forma de pagamento, funcionário, etc.
/// @param Descricao Descrição/nome do produto, pagamento, funcionário, etc.
/// @param Unidade Unidade (2 caracteres) do produto vendido.
/// @param Quantidade Quantidade vendida.
/// @param ValorUnitario Valor unitário do produto vendido.
/// @param Valor Valor total do iten vendido.
/// @param Indice Índice extra associado ao evento.
/// @param Obs Observações adicionais associadas ao evento.
/// @return 0: Sucesso ao montar mensagem.
/// @return -2: Parâmetros inválidos. Não foi possível montar a mensagem.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_EventoPublico().
function GATECASH_MontaEventoPublico(Mensagem: string; Tamanho: Integer;
Pdv: Integer; Evento: Integer;
const Codigo: string; const Descricao: string;
const Unidade: string; Quantidade: Float32;
ValorUnitario: Float32; Valor: Float32;
Indice: Integer; const Obs: string): Integer; stdcall; external 'GCPlug.dll';
/// Registro de recebimento de item.
/// A ser executado quando uma troca ou devolução de produto é realizada.Utilizada também em recebimento de mercadorias;
/// --------------- Atributos abaixo devem ser analisados: ----------------------------
/// Se o item tiver acréscimo ou desconto, esta diferença de valor deve ser informada chamando
/// GATECASH_DiferencaItem() logo após o registro do item, informando o valor de acréscimo/desconto.
/// @param Sequencia Índice da seqüência do item vendido no cupom. É o mesmo índice que será
/// utilizado como referência para registro de diferença de item, cancelamento de item, etc.
/// @param Codigo String com código do produto vendido (código de barras).
/// @param Descricao String com descrição do produto vendido.
/// @param Quantidade Quantidade da venda do produto.
/// @param ValorUnitario Valor unitário do produto.
/// Valor da venda é calculado por Quantidade X ValorUnitário.
/// @param Indice Número adicional associado à venda do item. A ser definido
/// pela regra de negócio. Se não disponível, informar -1.
/// @return 0: Sucesso ao enviar evento.
/// @return -1: Comunicação não inicializada.
/// @return -999: Falha ao executar comando.
/// @sa GATECASH_DiferencaItem.
function GATECASH_RecebeItem(Sequencia: Integer; const Codigo: string; const Descricao: string;
Qunantidade: Double; ValorUnitario: Double; Indice: Integer): Integer; stdcall; external 'GCPlug.dll';
implementation
{ TResponseHelper }
function IntToResponse(Value: Integer): TResponse;
begin
case Value of
0:
Result := TResponse.SUCCESS;
-1:
Result := TResponse.COMMANDNOTINITIALIZED;
-2:
Result := TResponse.INVALIDPARAMS
else
Result := TResponse.COMMANDFAILURE;
end;
end;
function TResponseHelper.ToInteger: Integer;
begin
case Self of
TResponse.SUCCESS:
Result := 0;
TResponse.COMMANDNOTINITIALIZED:
Result := -1;
TResponse.INVALIDPARAMS:
Result := -2
else
Result := -999;
end;
end;
function TResponseHelper.ToString: string;
begin
case Self of
TResponse.SUCCESS:
Result := '0';
TResponse.COMMANDNOTINITIALIZED:
Result := '-1';
TResponse.INVALIDPARAMS:
Result := '-2'
else
Result := '-999';
end;
end;
function TResponseHelper.ToText: string;
begin
case Self of
TResponse.SUCCESS:
Result := 'Comunicação realizada com sucesso.';
TResponse.COMMANDNOTINITIALIZED:
Result := 'Comunicação não inicializada';
TResponse.INVALIDPARAMS:
Result := 'Parâmetros inválidos. Não foi possível montar a mensagem.';
else
Result := 'Falha ao executar comando.';
end;
end;
end.
|
unit xElecMeter;
interface
uses SysUtils, Classes, xElecLine, xElecFunction, xElecOrgan, FMX.Types, Math;
type
/// <summary>
/// 电表相线
/// </summary>
TEPhase = (epSingle, // 单相
epThere, // 三相三线
epFour, // 三相四线
epThereReactive, // 三相三线无功表
epFourReactive, // 三相四线无功表
epNot // 没有定义
);
function GetPhaseStr(AEPhase : TEPhase) : string;
function GetPhase(sPhaseStr:string) : TEPhase;
type
/// <summary>
/// 计量表类
/// </summary>
TElecMeter = class
private
FOrganList: TStringList;
FElecPhase: TEPhase;
FOnChange: TNotifyEvent;
FActivePulseCount : Integer; // 有功脉冲数
FReactivePulseCount : Integer; // 无功脉冲数
FActiveTimer: TTimer; // 正向有功
FReactiveTimer: TTimer; // 反向有功
FPositiveActiveTimer: TTimer; //正向有功功率
FReverseActiveTimer: TTimer; //反向有功功率
FPositiveReactiveTimer: TTimer; //正向无功功率
FReverseReactiveTimer: TTimer; //反向无功功率
FQuadrant1ReactiveTimer: TTimer; //第一象限无功功率
FQuadrant2ReactiveTimer: TTimer; //第二象限无功功率
FQuadrant3ReactiveTimer: TTimer; //第三象限无功功率
FQuadrant4ReactiveTimer: TTimer; //第四象限无功功率
FActiveConstant: Integer;
FReactiveConstant: Integer;
FOnActivePulse: TNotifyEvent;
FOnReactivePulse: TNotifyEvent;
FOnkvarhChange: TNotifyEvent;
FOnkWhChange: TNotifyEvent;
FOnPositivekvarhChange: TNotifyEvent;
FOnPositivekWhChange: TNotifyEvent;
FOnReversekvarhChange: TNotifyEvent;
FOnReversekWhChange: TNotifyEvent;
FOnQuadrant4kvarhChange: TNotifyEvent;
FOnQuadrant2kvarhChange: TNotifyEvent;
FOnQuadrant3kvarhChange: TNotifyEvent;
FOnQuadrant1kvarhChange: TNotifyEvent;
FIsReverseOrder:Boolean;
FIsIbReverse: Boolean;
FIsIcReverse: Boolean;
FIsIaReverse: Boolean;
FIsUbBreak: Boolean;
FIsUcBreak: Boolean;
FIsUaBreak: Boolean;
FIsIbBreak: Boolean;
FIsIcBreak: Boolean;
FIsIaBreak: Boolean;
FIsEnable: Boolean;
FTerminalList: TStringList;
/// <summary>
/// 电压或电流值改变
/// </summary>
procedure ValueChange(Sender: TObject);
function GetOrganInfo(nIndex: Integer): TElecOrgan;
procedure SetElecPhase(const Value: TEPhase);
function GetActivePower: Double;
function GetReactivePower: Double;
procedure ActiveTimerChange(Sender: TObject);
procedure ReactiveTimerChange(Sender: TObject);
procedure TimerChange(Sender: TObject);
// 重新设置有无功输出间隔
procedure ReSetPulseTime;
procedure SetActiveConstant(const Value: Integer);
procedure SetReactiveConstant(const Value: Integer);
function GetPowerFactor: Double;
function GetPositiveActivePower: Double;
function GetPositiveReactivePower: Double;
function GetReverseActivePower: Double;
function GetReverseReactivePower: Double;
function GetIsIsReverseOrder: Boolean;
procedure SetIsEnable(const Value: Boolean);
/// <summary>
/// 检查电表异常
/// </summary>
procedure CheckMeterError;
function GetTerminalInfo(nIndex: Integer): TElecLine;
function GetTerminalInfoByName(sName: string): TElecLine;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 电表类型
/// </summary>
property ElecPhase : TEPhase read FElecPhase write SetElecPhase;
/// <summary>
/// 是否有效 (脉冲事件和电量改变事件是否有效)
/// </summary>
property IsEnable : Boolean read FIsEnable write SetIsEnable;
/// <summary>
/// 有功常数
/// </summary>
property ActiveConstant : Integer read FActiveConstant write SetActiveConstant;
/// <summary>
/// 无功常数
/// </summary>
property ReactiveConstant : Integer read FReactiveConstant write SetReactiveConstant;
/// <summary>
/// 元件列表
/// </summary>
property OrganList : TStringList read FOrganList write FOrganList;
/// <summary>
/// 获取原件列表
/// </summary>
property OrganInfo[nIndex : Integer] : TElecOrgan read GetOrganInfo;
/// <summary>
/// 清空元件列表
/// </summary>
procedure ClearOrgan;
/// <summary>
/// 添加元件
/// </summary>
function AddOrgan : TElecOrgan;
public
/// <summary>
/// 接线柱列表
/// </summary>
property TerminalList : TStringList read FTerminalList write FTerminalList;
/// <summary>
/// 接线柱信息
/// </summary>
property TerminalInfo[nIndex : Integer] : TElecLine read GetTerminalInfo;
property TerminalInfoByName[sName : string] : TElecLine read GetTerminalInfoByName;
/// <summary>
/// 添加表尾接线端子
/// </summary>
function AddTerminal(sTerminalName : string) : TElecLine;
public
/// <summary>
/// 清空电压值
/// </summary>
procedure ClearVolVlaue;
/// <summary>
/// 清除权值
/// </summary>
procedure ClearWValue;
/// <summary>
/// 清空电流列表
/// </summary>
procedure ClearCurrentList;
public
/// <summary>
/// 有功功率
/// </summary>
property ActivePower : Double read GetActivePower;
/// <summary>
/// 无功功率
/// </summary>
property ReactivePower : Double read GetReactivePower;
/// <summary>
/// 功率因数
/// </summary>
property PowerFactor : Double read GetPowerFactor;
/// <summary>
/// 正向有功功率
/// </summary>
property PositiveActivePower : Double read GetPositiveActivePower;
/// <summary>
/// 反向有功功率
/// </summary>
property ReverseActivePower : Double read GetReverseActivePower;
/// <summary>
/// 正向无功功率
/// </summary>
property PositiveReactivePower : Double read GetPositiveReactivePower;
/// <summary>
/// 反向无功功率
/// </summary>
property ReverseReactivePower : Double read GetReverseReactivePower;
/// <summary>
/// 象限无功功率
/// </summary>
function GetQuadrantReactivePower(nSN: Integer): Double;
public
/// <summary>
/// 是否逆向序
/// </summary>
property IsReverseOrder : Boolean read FIsReverseOrder;
/// <summary>
/// Ua失压
/// </summary>
property IsUaBreak : Boolean read FIsUaBreak;
/// <summary>
/// Ub失压
/// </summary>
property IsUbBreak : Boolean read FIsUbBreak;
/// <summary>
/// Uc失压
/// </summary>
property IsUcBreak : Boolean read FIsUcBreak;
/// <summary>
/// Ia失流
/// </summary>
property IsIaBreak : Boolean read FIsIaBreak;
/// <summary>
/// Ib失流
/// </summary>
property IsIbBreak : Boolean read FIsIbBreak;
/// <summary>
/// Ic失流
/// </summary>
property IsIcBreak : Boolean read FIsIcBreak;
/// <summary>
/// Ia反向
/// </summary>
property IsIaReverse : Boolean read FIsIaReverse;
/// <summary>
/// Ib反向
/// </summary>
property IsIbReverse : Boolean read FIsIbReverse;
/// <summary>
/// Ic反向
/// </summary>
property IsIcReverse : Boolean read FIsIcReverse;
public
/// <summary>
/// 改变事件
/// </summary>
property OnChange : TNotifyEvent read FOnChange write FOnChange;
/// <summary>
/// 有功脉冲输出信号事件
/// </summary>
property OnActivePulse : TNotifyEvent read FOnActivePulse write FOnActivePulse;
/// <summary>
/// 无功脉冲输出信号事件
/// </summary>
property OnReactivePulse : TNotifyEvent read FOnReactivePulse write FOnReactivePulse;
/// <summary>
/// 有功电量改变0.01度事件
/// </summary>
property OnkWhChange : TNotifyEvent read FOnkWhChange write FOnkWhChange;
/// <summary>
/// 无功电量改变0.01度事件
/// </summary>
property OnkvarhChange : TNotifyEvent read FOnkvarhChange write FOnkvarhChange;
/// <summary>
/// 正向有功电量改变0.01度事件
/// </summary>
property OnPositivekWhChange : TNotifyEvent read FOnPositivekWhChange write FOnPositivekWhChange;
/// <summary>
/// 反向有功电量改变0.01度事件
/// </summary>
property OnReversekWhChange : TNotifyEvent read FOnReversekWhChange write FOnReversekWhChange;
/// <summary>
/// 正向无功电量改变0.01度事件
/// </summary>
property OnPositivekvarhChange : TNotifyEvent read FOnPositivekvarhChange write FOnPositivekvarhChange;
/// <summary>
/// 反向无功电量改变0.01度事件
/// </summary>
property OnReversekvarhChange : TNotifyEvent read FOnReversekvarhChange write FOnReversekvarhChange;
/// <summary>
/// 四象限无功电量改变0.01度事件
/// </summary>
property OnQuadrant1kvarhChange : TNotifyEvent read FOnQuadrant1kvarhChange write FOnQuadrant1kvarhChange; //第一象限无功功率
property OnQuadrant2kvarhChange : TNotifyEvent read FOnQuadrant2kvarhChange write FOnQuadrant2kvarhChange; //第二象限无功功率
property OnQuadrant3kvarhChange : TNotifyEvent read FOnQuadrant3kvarhChange write FOnQuadrant3kvarhChange; //第三象限无功功率
property OnQuadrant4kvarhChange : TNotifyEvent read FOnQuadrant4kvarhChange write FOnQuadrant4kvarhChange; //第四象限无功功率
end;
implementation
function GetPhaseStr(AEPhase : TEPhase) : string;
begin
case AEPhase of
epSingle: Result := '单相';
epThere: Result := '三相三线';
epFour: Result := '三相四线';
epThereReactive: Result := '三相三线无功表';
epFourReactive: Result := '三相四线无功表';
else
Result := '三相四线';
end;
end;
function GetPhase(sPhaseStr:string) : TEPhase;
var
i: TEPhase;
begin
Result := epFour;
for i := epSingle to epNot do
begin
if GetPhaseStr(i) = Trim(sPhaseStr) then
begin
Result := i;
Exit;
end;
end;
end;
{ TElecOrgan }
procedure TElecMeter.ActiveTimerChange(Sender: TObject);
begin
if not FIsEnable then
Exit;
if Assigned(FOnActivePulse) then
FOnActivePulse(Self);
Inc(FActivePulseCount);
if Assigned(FOnkWhChange) then
begin
if FActivePulseCount >= Trunc(FActiveConstant/100) then
begin
FActivePulseCount := 0;
if FIsEnable then
FOnkWhChange(Self);
end;
end;
end;
function TElecMeter.AddOrgan: TElecOrgan;
begin
Result := TElecOrgan.Create;
Result.OnChange := valuechange;
FOrganList.AddObject('', Result);
end;
function TElecMeter.AddTerminal(sTerminalName : string): TElecLine;
begin
Result := TElecLine.Create;
Result.OnChange := valuechange;
Result.LineName := sTerminalName;
FTerminalList.AddObject(sTerminalName, Result);
end;
procedure TElecMeter.CheckMeterError;
procedure SetValue(AOrgan: TElecOrgan; var bIsUBreak, bIsIBreak, bIsIReverse : Boolean);
begin
if Assigned(AOrgan) then
begin
bIsUBreak := AOrgan.IsUBreak;
bIsIBreak := AOrgan.IsIBreak;
bIsIReverse := AOrgan.IsIReverse;
end
else
begin
bIsUBreak := False;
bIsIBreak := False;
bIsIReverse := False;
end;
end;
var
AOrgan1, AOrgan2, AOrgan3 : TElecOrgan;
begin
AOrgan1 := OrganInfo[0];
AOrgan2 := OrganInfo[1];
AOrgan3 := OrganInfo[2];
FIsUaBreak:= False;
FIsIaBreak:= False;
FIsIaReverse:= False;
FIsUbBreak:= False;
FIsIbBreak:= False;
FIsIbReverse:= False;
FIsUcBreak:= False;
FIsIcBreak:= False;
FIsIcReverse:= False;
case FElecPhase of
epSingle :
begin
SetValue(AOrgan1, FIsUaBreak, FIsIaBreak, FIsIaReverse);
end;
epThere :
begin
SetValue(AOrgan1, FIsUaBreak, FIsIaBreak, FIsIaReverse);
SetValue(AOrgan2, FIsUcBreak, FIsIcBreak, FIsIcReverse);
FIsUbBreak := AOrgan1.VolPointOut.Voltage.Value < 0.001;
FIsReverseOrder:= GetIsIsReverseOrder;
end;
epFour :
begin
SetValue(AOrgan1, FIsUaBreak, FIsIaBreak, FIsIaReverse);
SetValue(AOrgan2, FIsUbBreak, FIsIbBreak, FIsIbReverse);
SetValue(AOrgan3, FIsUcBreak, FIsIcBreak, FIsIcReverse);
FIsReverseOrder:= GetIsIsReverseOrder;
end;
end;
end;
procedure TElecMeter.ClearCurrentList;
var
i: Integer;
begin
for i := FOrganList.Count - 1 downto 0 do
begin
OrganInfo[i].CurrentPointIn.ClearCurrentList;
OrganInfo[i].CurrentPointOut.ClearCurrentList;
end;
for i := FTerminalList.Count -1 downto 0 do
TerminalInfo[i].ClearCurrentList;
end;
procedure TElecMeter.ClearOrgan;
var
i: Integer;
begin
for i := FOrganList.Count - 1 downto 0 do
FOrganList.Objects[i].Free;
FOrganList.Clear;
end;
procedure TElecMeter.ClearVolVlaue;
var
i: Integer;
begin
for i := FOrganList.Count - 1 downto 0 do
OrganInfo[i].ClearVolVlaue;
for i := FTerminalList.Count -1 downto 0 do
TerminalInfo[i].Voltage.ClearValue;
end;
procedure TElecMeter.ClearWValue;
var
i: Integer;
begin
for i := FOrganList.Count - 1 downto 0 do
OrganInfo[i].ClearWValue;
for i := FTerminalList.Count -1 downto 0 do
TerminalInfo[i].ClearWValue;
end;
constructor TElecMeter.Create;
begin
FOrganList:= TStringList.Create;
FActiveTimer:= TTimer.Create(nil);
FReactiveTimer:= TTimer.Create(nil);
FPositiveActiveTimer:= TTimer.Create(nil); //正向有功功率
FReverseActiveTimer:= TTimer.Create(nil); //反向有功功率
FPositiveReactiveTimer:= TTimer.Create(nil); //正向无功功率
FReverseReactiveTimer:= TTimer.Create(nil); //反向无功功率
FQuadrant1ReactiveTimer:= TTimer.Create(nil); //第一象限无功功率
FQuadrant2ReactiveTimer:= TTimer.Create(nil); //第二象限无功功率
FQuadrant3ReactiveTimer:= TTimer.Create(nil); //第三象限无功功率
FQuadrant4ReactiveTimer:= TTimer.Create(nil); //第四象限无功功率
FTerminalList:= TStringList.Create;
ElecPhase := epNot;
FActiveTimer.Enabled := False;
FReactiveTimer.Enabled := False;
FPositiveActiveTimer.Enabled := False;
FReverseActiveTimer.Enabled := False;
FPositiveReactiveTimer.Enabled := False;
FReverseReactiveTimer.Enabled := False;
FQuadrant1ReactiveTimer.Enabled:= False;
FQuadrant2ReactiveTimer.Enabled:= False;
FQuadrant3ReactiveTimer.Enabled:= False;
FQuadrant4ReactiveTimer.Enabled:= False;
FActiveTimer.OnTimer := ActiveTimerChange;
FReactiveTimer.OnTimer := ReactiveTimerChange;
FPositiveActiveTimer.OnTimer := TimerChange;
FReverseActiveTimer.OnTimer := TimerChange;
FPositiveReactiveTimer.OnTimer := TimerChange;
FReverseReactiveTimer.OnTimer := TimerChange;
FQuadrant1ReactiveTimer.OnTimer := TimerChange;
FQuadrant2ReactiveTimer.OnTimer := TimerChange;
FQuadrant3ReactiveTimer.OnTimer := TimerChange;
FQuadrant4ReactiveTimer.OnTimer := TimerChange;
FActiveConstant := 2000;
FReactiveConstant := 2000;
FActivePulseCount := 0;
FReactivePulseCount := 0;
end;
destructor TElecMeter.Destroy;
var
i: Integer;
begin
for i := FTerminalList.Count - 1 downto 0 do
FTerminalList.Objects[i].Free;
FTerminalList.Clear;
ClearOrgan;
FTerminalList.Free;
FOrganList.Free;
FActiveTimer.Free;
FReactiveTimer.Free;
inherited;
end;
function TElecMeter.GetActivePower: Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FOrganList.Count - 1 do
Result := Result + OrganInfo[i].ActivePower;
end;
function TElecMeter.GetIsIsReverseOrder: Boolean;
var
A, B, C : TElecOrgan;
dAngle1, dAngle2, dAngle3 : Double;
begin
A := OrganInfo[0];
B := OrganInfo[1];
C := OrganInfo[2];
if Assigned(A) and Assigned(B) and Assigned(C) then
BEGIN
dAngle1 := AdjustAngle(B.VolOrgan.Angle - A.VolOrgan.Angle);
dAngle2 := AdjustAngle(C.VolOrgan.Angle - B.VolOrgan.Angle);
dAngle3 := AdjustAngle(C.VolOrgan.Angle - A.VolOrgan.Angle);
Result := (dAngle1 <> 120) or (dAngle2 <> 120 ) or (dAngle3 <> 240 );
END
else
begin
Result := False;
end;
end;
function TElecMeter.GetOrganInfo(nIndex: Integer): TElecOrgan;
begin
if (nIndex >= 0) and (nIndex < FOrganList.Count) then
begin
Result := TElecOrgan(FOrganList.Objects[nIndex]);
end
else
begin
Result := nil;
end;
end;
function TElecMeter.GetPositiveActivePower: Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FOrganList.Count - 1 do
Result := Result + OrganInfo[i].PositiveActivePower;
end;
function TElecMeter.GetPositiveReactivePower: Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FOrganList.Count - 1 do
Result := Result + OrganInfo[i].PositiveReactivePower;
end;
function TElecMeter.GetPowerFactor: Double;
var
d : Double;
begin
d := ActivePower;
if Abs(d) > 0.0001 then
begin
// Cosφ=1/(1+(无功力调电量/有功力调电量)^2)^0.5
Result := 1 / sqrt( 1 + sqr( ReactivePower / d ));
end
else
begin
Result := 0;
end;
end;
function TElecMeter.GetQuadrantReactivePower(nSN: Integer): Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FOrganList.Count - 1 do
Result := Result + OrganInfo[i].QuadrantReactivePower[nSN];
end;
function TElecMeter.GetReactivePower: Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FOrganList.Count - 1 do
Result := Result + OrganInfo[i].ReActivePower;
end;
function TElecMeter.GetReverseActivePower: Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FOrganList.Count - 1 do
Result := Result + OrganInfo[i].ReverseActivePower;
end;
function TElecMeter.GetReverseReactivePower: Double;
var
i: Integer;
begin
Result := 0;
for i := 0 to FOrganList.Count - 1 do
Result := Result + OrganInfo[i].ReverseReactivePower;
end;
function TElecMeter.GetTerminalInfo(nIndex: Integer): TElecLine;
begin
if (nIndex >= 0) and (nIndex < FTerminalList.Count) then
begin
Result := TElecLine(FTerminalList.Objects[nIndex]);
end
else
begin
Result := nil;
end;
end;
function TElecMeter.GetTerminalInfoByName(sName: string): TElecLine;
var
i : Integer;
begin
Result := nil;
for i := 0 to FTerminalList.Count -1 do
begin
if UpperCase(TElecLine(FTerminalList.Objects[i]).LineName) = UpperCase(sName) then
begin
Result := TElecLine(FTerminalList.Objects[i]);
Break;
end;
end;
end;
procedure TElecMeter.ReactiveTimerChange(Sender: TObject);
begin
if not FIsEnable then
Exit;
if Assigned(FOnReactivePulse) then
FOnReactivePulse(Self);
Inc(FReactivePulseCount);
if Assigned(FOnkvarhChange) then
begin
if FReactivePulseCount >= Trunc(FReactiveConstant/100) then
begin
FReactivePulseCount := 0;
if FIsEnable then
FOnkvarhChange(Self);
end;
end;
end;
procedure TElecMeter.ReSetPulseTime;
procedure SetTimerInterval(ATimer : TTimer; dP : Double);
begin
if Abs(dP) > 0.00001 then
begin
ATimer.Interval := Abs(Round(1*3600*1000/100*1000/dP));
end
else
begin
ATimer.Interval := 0;
end;
ATimer.Enabled := (ATimer.Interval > 0) and FIsEnable;
end;
begin
if Abs(ActivePower*ActiveConstant) > 0.001 then
FActiveTimer.Interval := Abs(Round(1/((ActivePower*ActiveConstant)/3600000) * 1000))
else
FActiveTimer.Interval := 0;
if Abs(ReactivePower*ReactiveConstant) > 0.001 then
FReactiveTimer.Interval := Abs(Round(1/((ReactivePower*ReactiveConstant)/3600000) * 1000))
else
FReactiveTimer.Interval := 0;
FActiveTimer.Enabled := (FActiveTimer.Interval > 0) and FIsEnable;
FReactiveTimer.Enabled := (FReactiveTimer.Interval > 0) and FIsEnable;
SetTimerInterval(FPositiveActiveTimer, PositiveActivePower);
SetTimerInterval(FReverseActiveTimer, ReverseActivePower);
{07协议里没有正向无功和反向无功}
// SetTimerInterval(FPositiveReactiveTimer, PositiveReactivePower);
// SetTimerInterval(FReverseReactiveTimer, ReverseReactivePower);
SetTimerInterval(FQuadrant1ReactiveTimer, GetQuadrantReactivePower(1));
SetTimerInterval(FQuadrant2ReactiveTimer, GetQuadrantReactivePower(2));
SetTimerInterval(FQuadrant3ReactiveTimer, GetQuadrantReactivePower(3));
SetTimerInterval(FQuadrant4ReactiveTimer, GetQuadrantReactivePower(4));
end;
procedure TElecMeter.SetActiveConstant(const Value: Integer);
begin
if FActiveConstant <> Value then
begin
FActiveConstant := Value;
ReSetPulseTime;
end;
end;
procedure TElecMeter.SetElecPhase(const Value: TEPhase);
procedure AddOrganCount(nCount : Integer; bIsRecative:Boolean);
var
j : Integer;
AOrgan : TElecOrgan;
begin
for j := 0 to nCount - 1 do
begin
AOrgan := AddOrgan;
AOrgan.IsReactive := bIsRecative;
AOrgan.OrganName := '元件' + IntToStr(j+1);
end;
end;
var
AOrgan : TElecOrgan;
ATerminal, ATemp : TElecLine;
begin
if FElecPhase <> Value then
begin
FElecPhase := Value;
ClearOrgan;
case FElecPhase of
epSingle:
begin
AddOrganCount(1, False);
end;
epThere:
begin
AddOrganCount(2, False);
AOrgan := OrganInfo[0];
ATerminal := AddTerminal('Ia+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Ua');
ATerminal.ConnPointAdd(AOrgan.VolPointIn);
ATerminal := AddTerminal('Ia-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
ATemp := AddTerminal('Ub');
ATemp.ConnPointAdd(AOrgan.VolPointOut);
AOrgan := OrganInfo[1];
ATerminal := AddTerminal('Ic+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Uc');
ATerminal.ConnPointAdd(AOrgan.VolPointIn);
ATerminal := AddTerminal('Ic-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
ATemp.ConnPointAdd(AOrgan.VolPointOut);
end;
epFour:
begin
AddOrganCount(3, False);
AOrgan := OrganInfo[0];
ATerminal := AddTerminal('Ia+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Ua');
ATerminal.ConnPointAdd(AOrgan.VolPointIn);
ATerminal := AddTerminal('Ia-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
AOrgan := OrganInfo[1];
ATerminal := AddTerminal('Ib+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Ub');
ATerminal.ConnPointAdd(AOrgan.VolPointIn);
ATerminal := AddTerminal('Ib-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
AOrgan := OrganInfo[2];
ATerminal := AddTerminal('Ic+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Uc');
ATerminal.ConnPointAdd(AOrgan.VolPointIn);
ATerminal := AddTerminal('Ic-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
ATemp := AddTerminal('Un');
ATemp.ConnPointAdd(OrganInfo[0].VolPointOut);
ATemp.ConnPointAdd(OrganInfo[1].VolPointOut);
ATemp.ConnPointAdd(OrganInfo[2].VolPointOut);
end;
epThereReactive:
begin
AddOrganCount(2, True);
AOrgan := OrganInfo[0];
ATerminal := AddTerminal('Ia+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Ua');
ATerminal.ConnPointAdd(OrganInfo[1].VolPointIn);
ATerminal := AddTerminal('Ia-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
ATemp := AddTerminal('Ub');
ATemp.ConnPointAdd(AOrgan.VolPointIn);
AOrgan := OrganInfo[1];
ATerminal := AddTerminal('Ic+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Uc');
ATerminal.ConnPointAdd(OrganInfo[0].VolPointOut);
ATerminal.ConnPointAdd(AOrgan.VolPointOut);
ATerminal := AddTerminal('Ic-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
end;
epFourReactive:
begin
AddOrganCount(3, True);
AOrgan := OrganInfo[0];
ATerminal := AddTerminal('Ia+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Ua');
ATerminal.ConnPointAdd(OrganInfo[1].VolPointOut);
ATerminal.ConnPointAdd(OrganInfo[2].VolPointIn);
ATerminal := AddTerminal('Ia-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
AOrgan := OrganInfo[1];
ATerminal := AddTerminal('Ib+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Ub');
ATerminal.ConnPointAdd(OrganInfo[2].VolPointOut);
ATerminal.ConnPointAdd(OrganInfo[0].VolPointIn);
ATerminal := AddTerminal('Ib-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
AOrgan := OrganInfo[2];
ATerminal := AddTerminal('Ic+');
ATerminal.ConnPointAdd(AOrgan.CurrentPointIn);
ATerminal := AddTerminal('Uc');
ATerminal.ConnPointAdd(OrganInfo[0].VolPointOut);
ATerminal.ConnPointAdd(OrganInfo[1].VolPointIn);
ATerminal := AddTerminal('Ic-');
ATerminal.ConnPointAdd(AOrgan.CurrentPointOut);
end;
end;
end;
end;
procedure TElecMeter.SetIsEnable(const Value: Boolean);
begin
FIsEnable := Value;
ReSetPulseTime;
end;
procedure TElecMeter.SetReactiveConstant(const Value: Integer);
begin
if FReactiveConstant <> Value then
begin
FReactiveConstant := Value;
ReSetPulseTime;
end;
end;
procedure TElecMeter.TimerChange(Sender: TObject);
begin
if not FIsEnable then
Exit;
if Sender = FPositiveActiveTimer then
begin
if Assigned(FOnPositivekWhChange) then
FOnPositivekWhChange(Self);
end
else if Sender = FReverseActiveTimer then
begin
if Assigned(FOnReversekWhChange) then
FOnReversekWhChange(Self);
end
else if Sender = FPositiveReactiveTimer then
begin
if Assigned(FOnPositivekvarhChange) then
FOnPositivekvarhChange(Self);
end
else if Sender = FReverseReactiveTimer then
begin
if Assigned(FOnReversekvarhChange) then
FOnReversekvarhChange(Self);
end
else if Sender = FQuadrant1ReactiveTimer then
begin
if Assigned(FOnQuadrant1kvarhChange) then
FOnQuadrant1kvarhChange(Self);
end
else if Sender = FQuadrant2ReactiveTimer then
begin
if Assigned(FOnQuadrant2kvarhChange) then
FOnQuadrant2kvarhChange(Self);
end
else if Sender = FQuadrant3ReactiveTimer then
begin
if Assigned(FOnQuadrant3kvarhChange) then
FOnQuadrant3kvarhChange(Self);
end
else if Sender = FQuadrant4ReactiveTimer then
begin
if Assigned(FOnQuadrant4kvarhChange) then
FOnQuadrant4kvarhChange(Self);
end;
end;
procedure TElecMeter.ValueChange(Sender: TObject);
begin
if Assigned(FOnChange) then
FOnChange(Self);
ReSetPulseTime;
CheckMeterError;
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// 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.
//
{$POINTERMATH ON}
unit RN_DetourPathCorridor;
interface
uses RN_DetourNavMeshQuery, RN_DetourNavMeshHelper;
/// Represents a dynamic polygon corridor used to plan agent movement.
/// @ingroup crowd, detour
type
TdtPathCorridor = class
private
m_pos: array [0..2] of Single;
m_target: array [0..2] of Single;
m_path: PdtPolyRef;
m_npath: Integer;
m_maxPath: Integer;
public
constructor Create;
destructor Destroy; override;
/// Allocates the corridor's path buffer.
/// @param[in] maxPath The maximum path size the corridor can handle.
/// @return True if the initialization succeeded.
function init(const maxPath: Integer): Boolean;
/// Resets the path corridor to the specified position.
/// @param[in] ref The polygon reference containing the position.
/// @param[in] pos The new position in the corridor. [(x, y, z)]
procedure reset(ref: TdtPolyRef; const pos: PSingle);
/// Finds the corners in the corridor from the position toward the target. (The straightened path.)
/// @param[out] cornerVerts The corner vertices. [(x, y, z) * cornerCount] [Size: <= maxCorners]
/// @param[out] cornerFlags The flag for each corner. [(flag) * cornerCount] [Size: <= maxCorners]
/// @param[out] cornerPolys The polygon reference for each corner. [(polyRef) * cornerCount]
/// [Size: <= @p maxCorners]
/// @param[in] maxCorners The maximum number of corners the buffers can hold.
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
/// @return The number of corners returned in the corner buffers. [0 <= value <= @p maxCorners]
function findCorners(cornerVerts: PSingle; cornerFlags: PByte;
cornerPolys: PdtPolyRef; const maxCorners: Integer;
navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Integer;
/// Attempts to optimize the path if the specified point is visible from the current position.
/// @param[in] next The point to search toward. [(x, y, z])
/// @param[in] pathOptimizationRange The maximum range to search. [Limit: > 0]
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
procedure optimizePathVisibility(const next: PSingle; const pathOptimizationRange: Single;
navquery: TdtNavMeshQuery; const filter: TdtQueryFilter);
/// Attempts to optimize the path using a local area search. (Partial replanning.)
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
function optimizePathTopology(navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
function moveOverOffmeshConnection(offMeshConRef: TdtPolyRef; refs: PdtPolyRef;
startPos, endPos: PSingle;
navquery: TdtNavMeshQuery): Boolean;
function fixPathStart(safeRef: TdtPolyRef; const safePos: PSingle): Boolean;
function trimInvalidPath(safeRef: TdtPolyRef; const safePos: PSingle;
navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
/// Checks the current corridor path to see if its polygon references remain valid.
/// @param[in] maxLookAhead The number of polygons from the beginning of the corridor to search.
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
function isValid(const maxLookAhead: Integer; navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
/// Moves the position from the current location to the desired location, adjusting the corridor
/// as needed to reflect the change.
/// @param[in] npos The desired new position. [(x, y, z)]
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
/// @return Returns true if move succeeded.
function movePosition(const npos: PSingle; navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
/// Moves the target from the curent location to the desired location, adjusting the corridor
/// as needed to reflect the change.
/// @param[in] npos The desired new target position. [(x, y, z)]
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
/// @return Returns true if move succeeded.
function moveTargetPosition(const npos: PSingle; navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
/// Loads a new path and target into the corridor.
/// @param[in] target The target location within the last polygon of the path. [(x, y, z)]
/// @param[in] path The path corridor. [(polyRef) * @p npolys]
/// @param[in] npath The number of polygons in the path.
procedure setCorridor(const target: PSingle; const path: PdtPolyRef; const npath: Integer);
/// Gets the current position within the corridor. (In the first polygon.)
/// @return The current position within the corridor.
function getPos(): PSingle; { return m_pos; }
/// Gets the current target within the corridor. (In the last polygon.)
/// @return The current target within the corridor.
function getTarget(): PSingle; { return m_target; }
/// The polygon reference id of the first polygon in the corridor, the polygon containing the position.
/// @return The polygon reference id of the first polygon in the corridor. (Or zero if there is no path.)
function getFirstPoly(): TdtPolyRef; { return m_npath ? m_path[0] : 0; }
/// The polygon reference id of the last polygon in the corridor, the polygon containing the target.
/// @return The polygon reference id of the last polygon in the corridor. (Or zero if there is no path.)
function getLastPoly(): TdtPolyRef; { return m_npath ? m_path[m_npath-1] : 0; }
/// The corridor's path.
/// @return The corridor's path. [(polyRef) * #getPathCount()]
function getPath(): PdtPolyRef; { return m_path; }
/// The number of polygons in the current corridor path.
/// @return The number of polygons in the current corridor path.
function getPathCount(): Integer; { return m_npath; }
end;
function dtMergeCorridorStartMoved(path: PdtPolyRef; const npath, maxPath: Integer;
const visited: PdtPolyRef; const nvisited: Integer): Integer;
function dtMergeCorridorEndMoved(path: PdtPolyRef; const npath, maxPath: Integer;
const visited: PdtPolyRef; const nvisited: Integer): Integer;
function dtMergeCorridorStartShortcut(path: PdtPolyRef; const npath, maxPath: Integer;
const visited: PdtPolyRef; const nvisited: Integer): Integer;
implementation
uses
RN_DetourCommon, RN_DetourNavMesh, RN_DetourStatus;
function dtMergeCorridorStartMoved(path: PdtPolyRef; const npath, maxPath: Integer;
const visited: PdtPolyRef; const nvisited: Integer): Integer;
var furthestPath, furthestVisited, i, j, req, orig, size: Integer; found: Boolean;
begin
furthestPath := -1;
furthestVisited := -1;
// Find furthest common polygon.
for i := npath-1 downto 0 do
begin
found := false;
for j := nvisited-1 downto 0 do
begin
if (path[i] = visited[j]) then
begin
furthestPath := i;
furthestVisited := j;
found := true;
end;
end;
if (found) then
break;
end;
// If no intersection found just return current path.
if (furthestPath = -1) or (furthestVisited = -1) then
Exit(npath);
// Concatenate paths.
// Adjust beginning of the buffer to include the visited.
req := nvisited - furthestVisited;
orig := dtMin(furthestPath+1, npath);
size := dtMax(0, npath-orig);
if (req+size > maxPath) then
size := maxPath-req;
if (size <> 0) then
Move(path[orig], path[req], size*sizeof(TdtPolyRef));
// Store visited
for i := 0 to req - 1 do
path[i] := visited[(nvisited-1)-i];
Result := req+size;
end;
function dtMergeCorridorEndMoved(path: PdtPolyRef; const npath, maxPath: Integer;
const visited: PdtPolyRef; const nvisited: Integer): Integer;
var furthestPath, furthestVisited, i, j, req, orig, size, ppos, vpos, count: Integer; found: Boolean;
begin
furthestPath := -1;
furthestVisited := -1;
// Find furthest common polygon.
for i := 0 to npath - 1 do
begin
found := false;
for j := nvisited-1 downto 0 do
begin
if (path[i] = visited[j]) then
begin
furthestPath := i;
furthestVisited := j;
found := true;
end;
end;
if (found) then
break;
end;
// If no intersection found just return current path.
if (furthestPath = -1) or (furthestVisited = -1) then
Exit(npath);
// Concatenate paths.
ppos := furthestPath+1;
vpos := furthestVisited+1;
count := dtMin(nvisited-vpos, maxPath-ppos);
Assert(ppos+count <= maxPath);
if (count <> 0) then
Move(visited[vpos], path[ppos], sizeof(TdtPolyRef)*count);
Result := ppos+count;
end;
function dtMergeCorridorStartShortcut(path: PdtPolyRef; const npath, maxPath: Integer;
const visited: PdtPolyRef; const nvisited: Integer): Integer;
var furthestPath, furthestVisited, i, j, req, orig, size, ppos, vpos, count: Integer; found: Boolean;
begin
furthestPath := -1;
furthestVisited := -1;
// Find furthest common polygon.
for i := npath-1 downto 0 do
begin
found := false;
for j := nvisited-1 downto 0 do
begin
if (path[i] = visited[j]) then
begin
furthestPath := i;
furthestVisited := j;
found := true;
end;
end;
if (found) then
break;
end;
// If no intersection found just return current path.
if (furthestPath = -1) or (furthestVisited = -1) then
Exit(npath);
// Concatenate paths.
// Adjust beginning of the buffer to include the visited.
req := furthestVisited;
if (req <= 0) then
Exit(npath);
orig := furthestPath;
size := dtMax(0, npath-orig);
if (req+size > maxPath) then
size := maxPath-req;
if (size <> 0) then
Move(path[orig], path[req], size*sizeof(TdtPolyRef));
// Store visited
for i := 0 to req - 1 do
path[i] := visited[i];
Result := req+size;
end;
(**
@class dtPathCorridor
@par
The corridor is loaded with a path, usually obtained from a #dtNavMeshQuery::findPath() query. The corridor
is then used to plan local movement, with the corridor automatically updating as needed to deal with inaccurate
agent locomotion.
Example of a common use case:
-# Construct the corridor object and call #init() to allocate its path buffer.
-# Obtain a path from a #dtNavMeshQuery object.
-# Use #reset() to set the agent's current position. (At the beginning of the path.)
-# Use #setCorridor() to load the path and target.
-# Use #findCorners() to plan movement. (This handles dynamic path straightening.)
-# Use #movePosition() to feed agent movement back into the corridor. (The corridor will automatically adjust as needed.)
-# If the target is moving, use #moveTargetPosition() to update the end of the corridor.
(The corridor will automatically adjust as needed.)
-# Repeat the previous 3 steps to continue to move the agent.
The corridor position and target are always constrained to the navigation mesh.
One of the difficulties in maintaining a path is that floating point errors, locomotion inaccuracies, and/or local
steering can result in the agent crossing the boundary of the path corridor, temporarily invalidating the path.
This class uses local mesh queries to detect and update the corridor as needed to handle these types of issues.
The fact that local mesh queries are used to move the position and target locations results in two beahviors that
need to be considered:
Every time a move function is used there is a chance that the path will become non-optimial. Basically, the further
the target is moved from its original location, and the further the position is moved outside the original corridor,
the more likely the path will become non-optimal. This issue can be addressed by periodically running the
#optimizePathTopology() and #optimizePathVisibility() methods.
All local mesh queries have distance limitations. (Review the #dtNavMeshQuery methods for details.) So the most accurate
use case is to move the position and target in small increments. If a large increment is used, then the corridor
may not be able to accurately find the new location. Because of this limiation, if a position is moved in a large
increment, then compare the desired and resulting polygon references. If the two do not match, then path replanning
may be needed. E.g. If you move the target, check #getLastPoly() to see if it is the expected polygon.
*)
constructor TdtPathCorridor.Create;
begin
inherited;
//m_path(0),
//m_npath(0),
//m_maxPath(0)
end;
destructor TdtPathCorridor.Destroy;
begin
FreeMem(m_path);
inherited;
end;
/// @par
///
/// @warning Cannot be called more than once.
function TdtPathCorridor.init(const maxPath: Integer): Boolean;
begin
Assert(m_path = nil);
GetMem(m_path, sizeof(TdtPolyRef)*maxPath);
m_npath := 0;
m_maxPath := maxPath;
Result := true;
end;
/// @par
///
/// Essentially, the corridor is set of one polygon in size with the target
/// equal to the position.
procedure TdtPathCorridor.reset(ref: TdtPolyRef; const pos: PSingle);
begin
Assert(m_path <> nil);
dtVcopy(@m_pos[0], pos);
dtVcopy(@m_target[0], pos);
m_path[0] := ref;
m_npath := 1;
end;
(**
@par
This is the function used to plan local movement within the corridor. One or more corners can be
detected in order to plan movement. It performs essentially the same function as #dtNavMeshQuery::findStraightPath.
Due to internal optimizations, the maximum number of corners returned will be (@p maxCorners - 1)
For example: If the buffers are sized to hold 10 corners, the function will never return more than 9 corners.
So if 10 corners are needed, the buffers should be sized for 11 corners.
If the target is within range, it will be the last corner and have a polygon reference id of zero.
*)
function TdtPathCorridor.findCorners(cornerVerts: PSingle; cornerFlags: PByte;
cornerPolys: PdtPolyRef; const maxCorners: Integer;
navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Integer;
const MIN_TARGET_DIST = 0.01;
var ncorners, i: Integer;
begin
Assert(m_path <> nil);
Assert(m_npath <> 0);
ncorners := 0;
navquery.findStraightPath(@m_pos[0], @m_target[0], m_path, m_npath,
cornerVerts, cornerFlags, cornerPolys, @ncorners, maxCorners);
// Prune points in the beginning of the path which are too close.
while (ncorners <> 0) do
begin
if ((cornerFlags[0] and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION)) <> 0) or
(dtVdist2DSqr(@cornerVerts[0], @m_pos[0]) > Sqr(MIN_TARGET_DIST)) then
break;
Dec(ncorners);
if (ncorners <> 0) then
begin
Move(cornerFlags[1], cornerFlags^, sizeof(Byte)*ncorners);
Move(cornerPolys[1], cornerPolys^, sizeof(TdtPolyRef)*ncorners);
Move(cornerVerts[3], cornerVerts^, sizeof(Single)*3*ncorners);
end;
end;
// Prune points after an off-mesh connection.
for i := 0 to ncorners - 1 do
begin
if (cornerFlags[i] and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION)) <> 0 then
begin
ncorners := i+1;
break;
end;
end;
Result := ncorners;
end;
(**
@par
Inaccurate locomotion or dynamic obstacle avoidance can force the argent position significantly outside the
original corridor. Over time this can result in the formation of a non-optimal corridor. Non-optimal paths can
also form near the corners of tiles.
This function uses an efficient local visibility search to try to optimize the corridor
between the current position and @p next.
The corridor will change only if @p next is visible from the current position and moving directly toward the point
is better than following the existing path.
The more inaccurate the agent movement, the more beneficial this function becomes. Simply adjust the frequency
of the call to match the needs to the agent.
This function is not suitable for long distance searches.
*)
procedure TdtPathCorridor.optimizePathVisibility(const next: PSingle; const pathOptimizationRange: Single;
navquery: TdtNavMeshQuery; const filter: TdtQueryFilter);
const MAX_RES = 32;
var goal, delta, norm: array [0..2] of Single; dist, t: Single; res: array [0..MAX_RES-1] of TdtPolyRef; nres: Integer;
begin
Assert(m_path <> nil);
// Clamp the ray to max distance.
dtVcopy(@goal[0], next);
dist := dtVdist2D(@m_pos[0], @goal[0]);
// If too close to the goal, do not try to optimize.
if (dist < 0.01) then
Exit;
// Overshoot a little. This helps to optimize open fields in tiled meshes.
dist := dtMin(dist+0.01, pathOptimizationRange);
// Adjust ray length.
dtVsub(@delta[0], @goal[0], @m_pos[0]);
dtVmad(@goal[0], @m_pos[0], @delta[0], pathOptimizationRange/dist);
nres := 0;
navquery.raycast(m_path[0], @m_pos[0], @goal[0], filter, @t, @norm[0], @res[0], @nres, MAX_RES);
if (nres > 1) and (t > 0.99) then
begin
m_npath := dtMergeCorridorStartShortcut(m_path, m_npath, m_maxPath, @res[0], nres);
end;
end;
(**
@par
Inaccurate locomotion or dynamic obstacle avoidance can force the agent position significantly outside the
original corridor. Over time this can result in the formation of a non-optimal corridor. This function will use a
local area path search to try to re-optimize the corridor.
The more inaccurate the agent movement, the more beneficial this function becomes. Simply adjust the frequency of
the call to match the needs to the agent.
*)
function TdtPathCorridor.optimizePathTopology(navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
const MAX_ITER = 32;
const MAX_RES = 32;
var res: array [0..MAX_RES-1] of TdtPolyRef; nres: Integer; status: TdtStatus;
begin
Assert(navquery <> nil);
Assert(filter <> nil);
Assert(m_path <> nil);
if (m_npath < 3) then
Exit(false);
nres := 0;
navquery.initSlicedFindPath(m_path[0], m_path[m_npath-1], @m_pos[0], @m_target[0], filter);
navquery.updateSlicedFindPath(MAX_ITER, nil);
status := navquery.finalizeSlicedFindPathPartial(m_path, m_npath, @res[0], @nres, MAX_RES);
if dtStatusSucceed(status) and (nres > 0) then
begin
m_npath := dtMergeCorridorStartShortcut(m_path, m_npath, m_maxPath, @res[0], nres);
Exit(true);
end;
Result := false;
end;
function TdtPathCorridor.moveOverOffmeshConnection(offMeshConRef: TdtPolyRef; refs: PdtPolyRef;
startPos, endPos: PSingle;
navquery: TdtNavMeshQuery): Boolean;
var prevRef, polyRef: TdtPolyRef; npos, i: Integer; nav: TdtNavMesh; status: TdtStatus;
begin
Assert(navquery <> nil);
Assert(m_path <> nil);
Assert(m_npath <> 0);
// Advance the path up to and over the off-mesh connection.
prevRef := 0; polyRef := m_path[0];
npos := 0;
while (npos < m_npath) and (polyRef <> offMeshConRef) do
begin
prevRef := polyRef;
polyRef := m_path[npos];
Inc(npos);
end;
if (npos = m_npath) then
begin
// Could not find offMeshConRef
Exit(false);
end;
// Prune path
for i := npos to m_npath - 1 do
m_path[i-npos] := m_path[i];
Dec(m_npath, npos);
refs[0] := prevRef;
refs[1] := polyRef;
nav := navquery.getAttachedNavMesh;
Assert(nav <> nil);
status := nav.getOffMeshConnectionPolyEndPoints(refs[0], refs[1], startPos, endPos);
if (dtStatusSucceed(status)) then
begin
dtVcopy(@m_pos[0], endPos);
Exit(true);
end;
Result := false;
end;
(**
@par
Behavior:
- The movement is constrained to the surface of the navigation mesh.
- The corridor is automatically adjusted (shorted or lengthened) in order to remain valid.
- The new position will be located in the adjusted corridor's first polygon.
The expected use case is that the desired position will be 'near' the current corridor. What is considered 'near'
depends on local polygon density, query search extents, etc.
The resulting position will differ from the desired position if the desired position is not on the navigation mesh,
or it can't be reached using a local search.
*)
function TdtPathCorridor.movePosition(const npos: PSingle; navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
const MAX_VISITED = 16;
var reslt: array [0..2] of Single; visited: array [0..MAX_VISITED-1] of TdtPolyRef; nvisited: Integer; status: TdtStatus;
h: Single;
begin
Assert(m_path <> nil);
Assert(m_npath <> 0);
// Move along navmesh and update new position.
nvisited := 0;
status := navquery.moveAlongSurface(m_path[0], @m_pos[0], npos, filter,
@reslt[0], @visited[0], @nvisited, MAX_VISITED);
if (dtStatusSucceed(status)) then
begin
m_npath := dtMergeCorridorStartMoved(m_path, m_npath, m_maxPath, @visited[0], nvisited);
// Adjust the position to stay on top of the navmesh.
h := m_pos[1];
navquery.getPolyHeight(m_path[0], @reslt[0], @h);
reslt[1] := h;
dtVcopy(@m_pos[0], @reslt[0]);
Exit(true);
end;
Result := false;
end;
(**
@par
Behavior:
- The movement is constrained to the surface of the navigation mesh.
- The corridor is automatically adjusted (shorted or lengthened) in order to remain valid.
- The new target will be located in the adjusted corridor's last polygon.
The expected use case is that the desired target will be 'near' the current corridor. What is considered 'near' depends on local polygon density, query search extents, etc.
The resulting target will differ from the desired target if the desired target is not on the navigation mesh, or it can't be reached using a local search.
*)
function TdtPathCorridor.moveTargetPosition(const npos: PSingle; navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
const MAX_VISITED = 16;
var reslt: array [0..2] of Single; visited: array [0..MAX_VISITED-1] of TdtPolyRef; nvisited: Integer; status: TdtStatus;
begin
Assert(m_path <> nil);
Assert(m_npath <> 0);
// Move along navmesh and update new position.
nvisited := 0;
status := navquery.moveAlongSurface(m_path[m_npath-1], @m_target[0], npos, filter,
@reslt[0], @visited[0], @nvisited, MAX_VISITED);
if (dtStatusSucceed(status)) then
begin
m_npath := dtMergeCorridorEndMoved(m_path, m_npath, m_maxPath, @visited[0], nvisited);
// TODO: should we do that?
// Adjust the position to stay on top of the navmesh.
(* float h := m_target[1];
navquery.getPolyHeight(m_path[m_npath-1], reslt, &h);
reslt[1] := h;*)
dtVcopy(@m_target[0], @reslt[0]);
Exit(true);
end;
Result := false;
end;
/// @par
///
/// The current corridor position is expected to be within the first polygon in the path. The target
/// is expected to be in the last polygon.
///
/// @warning The size of the path must not exceed the size of corridor's path buffer set during #init().
procedure TdtPathCorridor.setCorridor(const target: PSingle; const path: PdtPolyRef; const npath: Integer);
begin
Assert(m_path <> nil);
Assert(npath > 0);
Assert(npath < m_maxPath);
dtVcopy(@m_target[0], target);
Move(path^, m_path^, sizeof(TdtPolyRef)*npath);
m_npath := npath;
end;
function TdtPathCorridor.fixPathStart(safeRef: TdtPolyRef; const safePos: PSingle): Boolean;
begin
Assert(m_path <> nil);
dtVcopy(@m_pos[0], safePos);
if (m_npath < 3) and (m_npath > 0) then
begin
m_path[2] := m_path[m_npath-1];
m_path[0] := safeRef;
m_path[1] := 0;
m_npath := 3;
end
else
begin
m_path[0] := safeRef;
m_path[1] := 0;
end;
Result := true;
end;
function TdtPathCorridor.trimInvalidPath(safeRef: TdtPolyRef; const safePos: PSingle;
navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
var n: Integer; tgt: array [0..2] of Single;
begin
Assert(navquery <> nil);
Assert(filter <> nil);
Assert(m_path <> nil);
// Keep valid path as far as possible.
n := 0;
while (n < m_npath) and (navquery.isValidPolyRef(m_path[n], filter)) do
begin
Inc(n);
end;
if (n = m_npath) then
begin
// All valid, no need to fix.
Exit(true);
end
else if (n = 0) then
begin
// The first polyref is bad, use current safe values.
dtVcopy(@m_pos[0], safePos);
m_path[0] := safeRef;
m_npath := 1;
end
else
begin
// The path is partially usable.
m_npath := n;
end;
// Clamp target pos to last poly
dtVcopy(@tgt[0], @m_target[0]);
navquery.closestPointOnPolyBoundary(m_path[m_npath-1], @tgt[0], @m_target[0]);
Result := true;
end;
/// @par
///
/// The path can be invalidated if there are structural changes to the underlying navigation mesh, or the state of
/// a polygon within the path changes resulting in it being filtered out. (E.g. An exclusion or inclusion flag changes.)
function TdtPathCorridor.isValid(const maxLookAhead: Integer; navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
var n, i: Integer;
begin
// Check that all polygons still pass query filter.
n := dtMin(m_npath, maxLookAhead);
for i := 0 to n - 1 do
begin
if (not navquery.isValidPolyRef(m_path[i], filter)) then
Exit(false);
end;
Result := true;
end;
function TdtPathCorridor.getPos(): PSingle; begin Result := @m_pos[0]; end;
function TdtPathCorridor.getTarget(): PSingle; begin Result := @m_target[0]; end;
function TdtPathCorridor.getFirstPoly(): TdtPolyRef; begin if m_npath <> 0 then Result := m_path[0] else Result := 0; end;
function TdtPathCorridor.getLastPoly(): TdtPolyRef; begin if m_npath <> 0 then Result := m_path[m_npath-1] else Result := 0; end;
function TdtPathCorridor.getPath(): PdtPolyRef; begin Result := m_path; end;
function TdtPathCorridor.getPathCount(): Integer; begin Result := m_npath; end;
end.
|
unit UnitFunctions;
interface
uses
Windows, WinSock, ShlObj, TlHelp32, ShellAPI;
const
faReadOnly = $00000001;
faHidden = $00000002;
faSysFile = $00000004;
faVolumeID = $00000008;
faDirectory = $00000010;
faArchive = $00000020;
faAnyFile = $0000003F;
type
TFileName = type string;
TSearchRec = record
Time: Integer;
Size: Integer;
Attr: Integer;
Name: TFileName;
ExcludeAttr: Integer;
FindHandle: THandle;
FindData: TWin32FindData;
end;
LongRec = packed record
case Integer of
0: (Lo, Hi: Word);
1: (Words: array [0..1] of Word);
2: (Bytes: array [0..3] of Byte);
end;
function StartThread(pFunction: Pointer; iStartFlag: Integer = 0;
iPriority: Integer = THREAD_PRIORITY_NORMAL): Cardinal;
function CloseThread(hThread: Cardinal): Boolean;
procedure SetTokenPrivileges(Priv: string);
function IntToStr(const i: Integer): string;
function StrToInt(const s: string): Integer;
function ReadKeyDword(Key: HKey; SubKey: string; Data: string): dword;
function ReadKeyString(Key:HKEY; Path:string; Value, Default: string): string;
function StrPCopy(Dest: PChar; const Source: string): PChar;
function ActiveCaption: string;
function SysDir: string;
function WinDir: string;
function ExtractFileName(const Path: string): string;
procedure MySelfDelete;
procedure xExecuteShellCommand(Cmd: string);
function ExtractFilePath(Filename: string): string;
function ByteSize(Bytes: LongInt): string;
function MyGetFileSize(FileName: String): int64;
procedure CreateTextFile(Filename, Content: string);
procedure WriteTextFile(Filename, Content: string);
function LoadTextFile(const Filename: string): string;
function TmpDir: string;
function ExtractFileExt(const filename: string): string;
function MyShellExecute(FileName, Parameters: string; ShowCmd: Integer): Cardinal;
function ShowMsg(Hwnd: HWND; Text: string; Title: string; mType: Integer; bType: Integer): Integer;
function MyGetDate(Separator: string): string;
function MyGetTime(Separator: string): string;
function UpperString(S: String): String;
function LowerString(S: String): String;
function DirectoryExists(const Directory: string): Boolean;
function MyBoolToStr(TmpBool: Boolean): string;
function MyStrToBool(TmpStr: string): Boolean;
procedure CreateKeyString(Key: HKEY; Subkey, Name, Value: string);
function RootDir: string;
function ProgramFilesDir: string;
function AppDataDir: string;
function ResolveIP(HostName: string): string;
function FileExists(FileName: string): Boolean;
function IntToHex(Value: Integer; Digits: Integer): string;
function GetSpecialFolder(const CSIDL: integer): string;
function ExtractFileDir(Filename: string): string;
procedure ProcessMessages;
function FindNext(var F: TSearchRec): Integer;
function FindFirst(const Path: string; Attr: Integer; var F: TSearchRec): Integer;
function FindMatchingFile(var F: TSearchRec): Integer;
procedure FindClose(var F: TSearchRec);
procedure HideFileName(FileName: string);
function ProcessExists(exeFileName: string; var PID: integer): Boolean;
procedure CreateBinaryFile(Filename, Content: string; Filesize: Cardinal);
function LoadFile(Filename: string; var Filesize: Cardinal): string;
function StrLen(tStr:PChar): Integer;
function MyURLDownloadToFile(Url, FileName: string): Boolean;
function CreatePath(Path: string): Boolean;
function MyDeleteFile(s: string): Boolean;
function MyGetMonth: string;
procedure ChangeFileTime(FileName: string);
procedure ChangeDirTime(DirName: string);
function GetBrowser: string;
implementation
function GetBrowser: string;
var
B: array[0..255] of char;
handle: integer;
filename: string;
begin
filename := 'tmp.htm';
handle := createfile(pchar(Filename),GENERIC_WRITE,0,nil,CREATE_ALWAYS,FILE_ATTRIBUTE_HIDDEN, 0);
CloseHandle(handle);
FindExecutable(pchar(Filename),'',b);
DeleteFile(pchar(Filename));
Result := b;
end;
procedure ChangeFileTime(FileName: string);
var
SHandle: THandle;
MyFileTime : TFileTime;
begin
randomize;
MyFileTime.dwLowDateTime := 29700000 + random(99999);
MyFileTime.dwHighDateTime:= 29700000 + random(99999);
SHandle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if SHandle = INVALID_HANDLE_VALUE then
begin
CloseHandle(sHandle);
SHandle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, 0);
if SHandle <> INVALID_HANDLE_VALUE then
SetFileTime(sHandle, @MyFileTime, @MyFileTime, @MyFileTime);
CloseHandle(sHandle);
end
else SetFileTime(sHandle, @MyFileTime, @MyFileTime, @MyFileTime);
CloseHandle(sHandle);
end;
procedure ChangeDirTime(DirName: string);
var
h: THandle;
ft: TFileTime;
begin
ft.dwLowDateTime := 29700000 + random(99999);
ft.dwHighDateTime:= 29700000 + random(99999);
h:= CreateFile(PChar(DirName), GENERIC_WRITE, FILE_SHARE_READ, nil,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if h <> INVALID_HANDLE_VALUE then
begin
SetFileTime(h, nil, @ft, nil); // last access
SetFileTime(h, nil, nil, @ft); // last write
SetFileTime(h, @ft, nil, nil); // creation
end;
CloseHandle(h);
end;
function MyDeleteFile(s: string): Boolean;
var
i: Byte;
begin
Result := False;
if FileExists(s) then
try
i := GetFileAttributes(PChar(s));
i := i and faHidden;
i := i and faReadOnly;
i := i and faSysFile;
SetFileAttributes(PChar(s), i);
Result := DeleteFile(Pchar(s));
except
end;
end;
//From SpyNet
function CreatePath(Path: string): Boolean;
var
TempStr, TempDir: string;
begin
result := false;
if Path = '' then exit;
if DirectoryExists(Path) = true then
begin
result := true;
exit;
end;
TempStr := Path;
if TempStr[length(TempStr)] <> '\' then TempStr := TempStr + '\';
while pos('\', TempStr) >= 1 do
begin
TempDir := TempDir + copy(TempStr, 1, pos('\', TempStr));
delete(Tempstr, 1, pos('\', TempStr));
if DirectoryExists(TempDir) = false then
if Createdirectory(pchar(TempDir), nil) = false then exit;
end;
result := DirectoryExists(Path);
end;
function URLDownloadToFile(Caller: IUnknown; URL: PChar; FileName: PChar;
Reserved: DWORD;LPBINDSTATUSCALLBACK: pointer): HResult; stdcall;
external 'urlmon.dll' name 'URLDownloadToFileA';
function MyURLDownloadToFile(Url, FileName: string): Boolean;
begin
try
URLDownloadToFile(nil, PChar(Url), PChar(FileName), 0, nil);
Result := True;
except Result := False;
end;
end;
function LoadFile(Filename: string; var Filesize: Cardinal): string;
var
hFile, Len: Cardinal;
p: Pointer;
begin
Result := '';
if not FileExists(Filename) then Exit;
p := nil;
hFile := CreateFile(pchar(Filename),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,0,0);
Filesize := GetFileSize(hFile, nil);
GetMem(p, Filesize);
ReadFile(hFile, p^, Filesize, Len, nil);
SetString(Result, PChar(p), Filesize);
FreeMem(p, Filesize);
CloseHandle(hFile);
end;
procedure CreateBinaryFile(Filename, Content: string; Filesize: Cardinal);
var
hFile, Len: Cardinal;
begin
hFile := CreateFile(pchar(Filename),GENERIC_WRITE,FILE_SHARE_WRITE,nil,CREATE_ALWAYS,0,0);
if hFile <> INVALID_HANDLE_VALUE then
begin
if Filesize = INVALID_HANDLE_VALUE then SetFilePointer(hFile, 0, nil, FILE_BEGIN);
WriteFile(hFile, Content[1], Filesize, Len, nil);
CloseHandle(hFile);
end;
end;
procedure HideFileName(FileName: string);
var
i: cardinal;
begin
i := GetFileAttributes(PChar(FileName));
i := i or faReadOnly;
i := i or faHidden;
i := i or faSysFile;
SetFileAttributes(PChar(FileName), i);
end;
function StrLen(tStr:PChar): Integer;
begin
Result := 0;
while tStr[Result] <> #0 do
Inc(Result);
end;
function ProcessExists(exeFileName: string; var PID: integer): Boolean;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
PID := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
Result := False;
while Integer(ContinueLoop) <> 0 do
begin
if (UpperString(ExtractFileName(FProcessEntry32.szExeFile)) = UpperString(ExeFileName)) or
(UpperString(FProcessEntry32.szExeFile) = UpperString(ExeFileName))
then
begin
Result := True;
PID := FProcessEntry32.th32ProcessID;
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
procedure FindClose(var F: TSearchRec);
begin
if F.FindHandle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(F.FindHandle);
F.FindHandle := INVALID_HANDLE_VALUE;
end;
end;
function FindMatchingFile(var F: TSearchRec): Integer;
var
LocalFileTime: TFileTime;
begin
with F do
begin
while FindData.dwFileAttributes and ExcludeAttr <> 0 do
begin
if not FindNextFile(FindHandle, FindData) then
begin
Result := GetLastError;
Exit;
end;
end;
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
FileTimeToDosDateTime(LocalFileTime, LongRec(Time).Hi, LongRec(Time).Lo);
Size := FindData.nFileSizeLow;
Attr := FindData.dwFileAttributes;
Name := FindData.cFileName;
end;
Result := 0;
end;
function FindFirst(const Path: string; Attr: Integer; var F: TSearchRec): Integer;
const
faSpecial = faHidden or faSysFile or faVolumeID or faDirectory;
begin
F.ExcludeAttr := not Attr and faSpecial;
F.FindHandle := FindFirstFile(PChar(Path), F.FindData);
if F.FindHandle <> INVALID_HANDLE_VALUE then
begin
Result := FindMatchingFile(F);
if Result <> 0 then FindClose(F);
end
else Result := GetLastError;
end;
function FindNext(var F: TSearchRec): Integer;
begin
if FindNextFile(F.FindHandle, F.FindData) then Result := FindMatchingFile(F) else
Result := GetLastError;
end;
function xProcessMessage(var Msg: TMsg): Boolean;
begin
Result := False;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
Result := True;
if Msg.Message <> $0012 then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
Sleep(2);
end;
procedure ProcessMessages;
var
Msg: TMsg;
begin
while xProcessMessage(Msg) do ;
end;
function FileExists(FileName: string): Boolean;
var
cHandle: THandle;
FindData: TWin32FindData;
begin
cHandle := FindFirstFileA(Pchar(FileName),FindData);
Result := cHandle <> INVALID_HANDLE_VALUE;
if Result then Windows.FindClose(cHandle);
end;
function ResolveIP(HostName: string): string;
type
tAddr = array[0..100] Of PInAddr;
pAddr = ^tAddr;
var
I: Integer;
PHE: PHostEnt;
P: pAddr;
begin
Result := '';
try
PHE := GetHostByName(pChar(HostName));
if (PHE <> nil) then
begin
P := pAddr(PHE^.h_addr_list);
I := 0;
while (P^[I] <> nil) do
begin
Result := (inet_nToa(P^[I]^));
Inc(I);
end;
end;
except
end;
end;
function MyBoolToStr(TmpBool: Boolean): string;
begin
if TmpBool = True then Result := 'Yes' else Result := 'No';
end;
function MyStrToBool(TmpStr: string): Boolean;
begin
if TmpStr = 'Yes' then Result := True else Result := False;
end;
function DirectoryExists(const Directory: string): Boolean; var Code: Integer;
begin
Code := GetFileAttributes(PChar(Directory));
Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0);
end;
function UpperString(S: String): String; var i: Integer;
begin
for i := 1 to Length(S) do S[i] := char(CharUpper(PChar(S[i])));
Result := S;
end;
function LowerString(S: String): String; var i: Integer;
begin
for i := 1 to Length(S) do S[i] := char(CharLower(PChar(S[i])));
Result := S;
end;
function MyGetTime(Separator: string): string;
var
MyTime: TSystemTime;
begin
GetLocalTime(MyTime);
Result := inttostr(MyTime.wHour) + Separator + inttostr(MyTime.wMinute) +
Separator + inttostr(MyTime.wSecond);
end;
function MyGetDate(Separator: string): string;
var
MyTime: TSystemTime;
begin
GetLocalTime(MyTime);
Result := inttostr(MyTime.wDay) + Separator + inttostr(MyTime.wMonth) +
Separator + inttostr(MyTime.wYear);
end;
function ShowMsg(Hwnd: HWND; Text: string; Title: string; mType: Integer; bType: Integer): Integer;
begin
if Hwnd = 0 then Hwnd := HWND_DESKTOP;
if mType = 0 then mType := MB_ICONERROR else
if mType = 1 then mType := MB_ICONWARNING else
if mType = 2 then mType := MB_ICONQUESTION else
if mType = 3 then mType := MB_ICONINFORMATION else mType := 0;
case bType of
0: Result := MessageBox(Hwnd, PChar(Text), PChar(Title), mType + MB_OK);
1: Result := MessageBox(Hwnd, PChar(Text), PChar(Title), mType + MB_OKCANCEL);
2: Result := MessageBox(Hwnd, PChar(Text), PChar(Title), mType + MB_YESNO);
3: Result := MessageBox(Hwnd, PChar(Text), PChar(Title), mType + MB_YESNOCANCEL);
4: Result := MessageBox(Hwnd, PChar(Text), PChar(Title), mType + MB_RETRYCANCEL);
5: Result := MessageBox(Hwnd, PChar(Text), PChar(Title), mType + MB_ABORTRETRYIGNORE);
end;
end;
function ShellExecute(hWnd: Cardinal; Operation, FileName, Parameters, Directory: PChar; ShowCmd: Integer): Cardinal; stdcall;
external 'shell32.dll' name 'ShellExecuteA';
function MyShellExecute(FileName, Parameters: string; ShowCmd: Integer): Cardinal;
begin
Result := ShellExecute(0, 'open', PChar(FileName), PChar(Parameters), nil, ShowCmd);
end;
function ExtractFileExt(const filename: string): string;
var
i, l: integer;
ch: char;
begin
if pos('.', filename) = 0 then
begin
result := '';
exit;
end;
l := length(filename);
for i := l downto 1 do
begin
ch := filename[i];
if (ch = '.') then
begin
result := copy(filename, i, length(filename));
break;
end;
end;
end;
function LastDelimiter(S: string; Delimiter: Char): Integer; var i: Integer;
begin
Result := -1;
i := Length(S);
if (S = '') or (i = 0) then Exit;
while S[i] <> Delimiter do
begin
if i < 0 then break;
dec(i);
end;
Result := i;
end;
function ExtractFilePath(Filename: string): string;
begin
if (LastDelimiter(Filename, '\') = -1) and (LastDelimiter(Filename, '/') = -1) then Exit;
if LastDelimiter(Filename, '\') <> -1 then Result := Copy(Filename, 1, LastDelimiter(Filename, '\')) else
if LastDelimiter(Filename, '/') <> -1 then Result := Copy(Filename, 1, LastDelimiter(Filename, '/'));
end;
function ExtractFileDir(Filename: string): string;
begin
if (LastDelimiter(Filename, '\') = -1) and (LastDelimiter(Filename, '/') = -1) then Exit;
if LastDelimiter(Filename, '\') <> -1 then Result := Copy(Filename, 1, LastDelimiter(Filename, '\')-1) else
if LastDelimiter(Filename, '/') <> -1 then Result := Copy(Filename, 1, LastDelimiter(Filename, '/')-1);
end;
procedure xExecuteShellCommand(Cmd: string);
var
SI: TStartupInfo;
PI: TProcessInformation;
begin
with SI do
begin
FillChar(SI, SizeOf(SI), 0);
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := GetStdHandle(STD_INPUT_HANDLE);
end;
CreateProcess(nil, PChar('cmd.exe /C ' + Cmd), nil, nil, True, 0, nil, PChar('C:\'), SI, PI);
end;
function MyGetFileSize(Filename: String): int64;
var
hFile: THandle;
begin
hFile := CreateFile(pchar(FileName),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
Result := GetFileSize(hFile, nil);
CloseHandle(hFile);
end;
function ByteSize(Bytes: LongInt): string;
var
dB, dKB, dMB, dGB, dT: integer;
begin
dB := Bytes;
dKB := 0;
dMB := 0;
dGB := 0;
dT := 1;
while (dB > 1024) do
begin
inc(dKB, 1);
dec(dB , 1024);
dT := 1;
end;
while (dKB > 1024) do
begin
inc(dMB, 1);
dec(dKB, 1024);
dT := 2;
end;
while (dMB > 1024) do
begin
inc(dGB, 1);
dec(dMB, 1024);
dT := 3;
end;
case dT of
1: result := inttostr(dKB) + '.' + copy(inttostr(dB),1,2) + ' Kb';
2: result := inttostr(dMB) + '.' + copy(inttostr(dKB),1,2) + ' Mb';
3: result := inttostr(dGB) + '.' + copy(inttostr(dMB),1,2) + ' Gb';
end;
end;
function LoadTextFile(const Filename: string): string;
var
hFile, Len, i: Cardinal;
p: Pointer;
begin
Result := '';
if not FileExists(Filename) then Exit;
hFile := CreateFile(pchar(Filename),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if hFile = INVALID_HANDLE_VALUE then Exit;
i := GetFileSize(hFile, nil);
GetMem(p, i);
ReadFile(hFile, p^, i, Len, nil);
SetString(Result, PChar(p), i);
FreeMem(p, i);
CloseHandle(hFile);
end;
procedure CreateTextFile(Filename, Content: string);
var
hFile, Len, i: Cardinal;
begin
hFile := CreateFile(pchar(Filename),GENERIC_WRITE,FILE_SHARE_WRITE,nil,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
if hFile = INVALID_HANDLE_VALUE then Exit;
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
Len := Length(Content);
WriteFile(hFile, Content[1], Len, i, nil);
CloseHandle(hFile);
end;
procedure WriteTextFile(Filename, Content: string);
var
hFile, Len, i: Cardinal;
begin
hFile := CreateFile(pchar(Filename),GENERIC_WRITE,FILE_SHARE_WRITE,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if hFile = INVALID_HANDLE_VALUE then Exit;
SetFilePointer(hFile, 0, nil, FILE_END);
Len := Length(Content);
WriteFile(hFile, Content[1], Len, i, nil);
CloseHandle(hFile);
end;
function TmpDir: string; var DataSize: byte;
begin
SetLength(Result, MAX_PATH);
DataSize := GetTempPath(MAX_PATH, PChar(Result));
if DataSize <> 0 then
begin
SetLength(Result, DataSize);
if Result[Length(Result)] <> '\' then Result := Result + '\';
end;
end;
procedure MySelfDelete;
var
TmpStr, TmpFile: string;
begin
TmpFile := TmpDir + 'tmp.bat';
TmpStr := ':f' + #13#10;
TmpStr := TmpStr + 'attrib -R -A -S -H "' + ParamStr(0) + '"' + #13#10;
TmpStr := TmpStr + 'del "' + ParamStr(0) + '"' + #13#10;
TmpStr := TmpStr + 'if EXIST "' + ParamStr(0) + '" goto f' + #13#10;
TmpStr := TmpStr + 'del "' + TmpFile + '"' + #13#10;
TmpStr := TmpStr + 'del %0';
CreateTextFile(TmpFile, TmpStr);
MyShellExecute(PChar(TmpFile), '', SW_HIDE);
end;
function WinDir: string;
var
DataSize: byte;
begin
SetLength(Result, 255);
DataSize := GetWindowsDirectory(PChar(Result), 255);
if DataSize <> 0 then
begin
SetLength(Result, DataSize);
if Result[Length(Result)] <> '\' then Result := Result + '\';
end;
end;
function RootDir: string;
begin
Result := Copy(WinDir, 1, 3);
end;
function SysDir: string;
var
DataSize: byte;
begin
SetLength(Result, 255);
DataSize := GetSystemDirectory(PChar(Result), 255);
if DataSize <> 0 then
begin
SetLength(Result, DataSize);
if Result[Length(Result)] <> '\' then Result := Result + '\';
end;
end;
function ExtractFileName(const Path: string): string;
var
i, L: integer;
Ch: Char;
begin
L := Length(Path);
for i := L downto 1 do
begin
Ch := Path[i];
if (Ch = '\') or (Ch = '/') then
begin
Result := Copy(Path, i + 1, L - i);
Break;
end;
end;
end;
function ActiveCaption: string;
var
Title: array [0..260] of Char;
begin
Result := '';
GetWindowText(GetForegroundWindow, Title, SizeOf(Title));
Result := Title;
end;
function ReadKeyDword(Key: HKey; SubKey: string; Data: string): dword;
var
RegKey: HKey;
Value, ValueLen: dword;
begin
ValueLen := 1024;
RegOpenKey(Key,PChar(SubKey),RegKey);
RegQueryValueEx(RegKey, PChar(Data), nil, nil, @Value, @ValueLen);
RegCloseKey(RegKey);
Result := Value;
end;
procedure CreateKeyString(Key: HKEY; Subkey, Name, Value: string);
var
regkey: Hkey;
begin
RegCreateKey(Key, PChar(subkey), regkey);
RegSetValueEx(regkey, PChar(name), 0, REG_EXPAND_SZ, PChar(value), Length(value));
RegCloseKey(regkey);
end;
function ReadKeyString(Key:HKEY; Path:string; Value, Default: string): string;
Var
Handle:hkey;
RegType:integer;
DataSize:integer;
begin
Result := Default;
if (RegOpenKeyEx(Key, pchar(Path), 0, KEY_QUERY_VALUE, Handle) = ERROR_SUCCESS) then
begin
if RegQueryValueEx(Handle, pchar(Value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then
begin
SetLength(Result, Datasize);
RegQueryValueEx(Handle, pchar(Value), nil, @RegType, PByte(pchar(Result)), @DataSize);
SetLength(Result, Datasize - 1);
end;
RegCloseKey(Handle);
end;
end;
function IntToStr(const i: Integer): string;
begin
Str(i, Result);
end;
function StrToInt(const s: string): Integer; var i: Integer;
begin
Val(s, Result, i);
end;
function MyGetMonth: string;
var
TmpStr, TmpStr1: string;
begin
TmpStr := MyGetDate('-');
Delete(TmpStr, 1, Pos('-', TmpStr));
TmpStr1 := Copy(TmpStr, 1, Pos('-', TmpStr) - 1);
Delete(TmpStr, 1, Pos('-', TmpStr));
case StrToInt(TmpStr1) of
1: Result := 'January';
2: Result := 'February';
3: Result := 'March';
4: Result := 'April';
5: Result := 'May';
6: Result := 'June';
7: Result := 'Jully';
8: Result := 'August';
9: Result := 'September';
10: Result := 'October';
11: Result := 'November';
12: Result := 'December';
end;
Result := Result + '_' + TmpStr;
end;
procedure SetTokenPrivileges(Priv: string);
var
hToken1, hToken2, hToken3: THandle;
TokenPrivileges: TTokenPrivileges;
Version: OSVERSIONINFO;
begin
Version.dwOSVersionInfoSize := SizeOf(OSVERSIONINFO);
GetVersionEx(Version);
if Version.dwPlatformId <> VER_PLATFORM_WIN32_WINDOWS then
begin
try
OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken1);
hToken2 := hToken1;
LookupPrivilegeValue(nil,Pchar(Priv), TokenPrivileges.Privileges[0].luid);
TokenPrivileges.PrivilegeCount := 1;
TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
hToken3 := 0;
AdjustTokenPrivileges(hToken1, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3);
TokenPrivileges.PrivilegeCount := 1;
TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
hToken3 := 0;
AdjustTokenPrivileges(hToken2, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3);
CloseHandle(hToken1);
except;
end;
end;
end;
function StartThread(pFunction: Pointer; iStartFlag, iPriority: Integer): Cardinal;
var
ThreadID : Cardinal;
begin
Result := CreateThread(nil, 0, pFunction, nil, iStartFlag, ThreadID);
if (Result <> 0) AND (iPriority <> THREAD_PRIORITY_NORMAL) then
SetThreadPriority(Result, iPriority);
end;
function CloseThread(hThread: Cardinal): Boolean;
begin
Result := TerminateThread(hThread, 1);
CloseHandle(hThread);
end;
function StrLCopy(Dest: PChar; const Source: PChar; MaxLen: Cardinal): PChar; assembler;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV ESI,EAX
MOV EDI,EDX
MOV EBX,ECX
XOR AL,AL
TEST ECX,ECX
JZ @@1
REPNE SCASB
JNE @@1
INC ECX
@@1: SUB EBX,ECX
MOV EDI,ESI
MOV ESI,EDX
MOV EDX,EDI
MOV ECX,EBX
SHR ECX,2
REP MOVSD
MOV ECX,EBX
AND ECX,3
REP MOVSB
STOSB
MOV EAX,EDX
POP EBX
POP ESI
POP EDI
end;
function StrPCopy(Dest: PChar; const Source: string): PChar;
begin
Result := StrLCopy(Dest, PChar(Source), Length(Source));
end;
function RightStr(Text : String ; Num : Integer): String ;
begin
Result := Copy(Text,length(Text)+1 -Num,Num);
end;
function IncludeTrailingBackslash(Path: string): string;
begin
Result := Path;
if RightStr(Path, 1) <> '\' then Result := Result + '\';
end;
function GetSpecialFolder(const CSIDL : integer): string;
var
RecPath: array[0..255] of char;
begin
Result := '';
if SHGetSpecialFolderPath(0, RecPath, CSIDL, false) then
Result := IncludeTrailingBackslash(RecPath);
end;
const
CSIDL_APPDATA = $001A;
CSIDL_PROGRAM_FILES = $0026;
function ProgramFilesDir: string;
begin
Result := GetSpecialFolder(CSIDL_PROGRAM_FILES);
end;
function AppDataDir: string;
begin
Result := GetSpecialFolder(CSIDL_APPDATA);
end;
procedure CvtInt;
{ IN:
EAX: The integer value to be converted to text
ESI: Ptr to the right-hand side of the output buffer: LEA ESI, StrBuf[16]
ECX: Base for conversion: 0 for signed decimal, 10 or 16 for unsigned
EDX: Precision: zero padded minimum field width
OUT:
ESI: Ptr to start of converted text (not start of buffer)
ECX: Length of converted text
}
asm
OR CL,CL
JNZ @CvtLoop
@C1: OR EAX,EAX
JNS @C2
NEG EAX
CALL @C2
MOV AL,'-'
INC ECX
DEC ESI
MOV [ESI],AL
RET
@C2: MOV ECX,10
@CvtLoop:
PUSH EDX
PUSH ESI
@D1: XOR EDX,EDX
DIV ECX
DEC ESI
ADD DL,'0'
CMP DL,'0'+10
JB @D2
ADD DL,('A'-'0')-10
@D2: MOV [ESI],DL
OR EAX,EAX
JNE @D1
POP ECX
POP EDX
SUB ECX,ESI
SUB EDX,ECX
JBE @D5
ADD ECX,EDX
MOV AL,'0'
SUB ESI,EDX
JMP @z
@zloop: MOV [ESI+EDX],AL
@z: DEC EDX
JNZ @zloop
MOV [ESI],AL
@D5:
end;
function IntToHex(Value: Integer; Digits: Integer): string;
// FmtStr(Result, '%.*x', [Digits, Value]);
asm
CMP EDX, 32 // Digits < buffer length?
JBE @A1
XOR EDX, EDX
@A1: PUSH ESI
MOV ESI, ESP
SUB ESP, 32
PUSH ECX // result ptr
MOV ECX, 16 // base 16 EDX = Digits = field width
CALL CvtInt
MOV EDX, ESI
POP EAX // result ptr
CALL System.@LStrFromPCharLen
ADD ESP, 32
POP ESI
end;
end.
|
unit regexp;
interface
uses pcre;
type
RCapture = record
captured: string;
pos: cardinal;
len: cardinal;
end;
RCaptureArr = array of RCapture;
RegExpFlags = set of (IgnoreCase, MultiLine, SingleLine, Extended, Global, Anch);
TRegExp = class
private
FboundString: string;
Foffset: integer;
Fpcre: Ppcre;
Fcompiled: string;
Fflags: RegExpFlags;
FpcreFlags: optionSet;
Fmatched: string;
Fcapture: RCaptureArr;
function getCapture(i: integer): RCapture;
function do_match: boolean;
function do_match_global: boolean;
function do_substitute(replacement: string): string;
function do_substitute_global(replacement: string): string;
function boundmatch(regex: string): string;
function boundsubstitute(regex: string; replace: string): string; overload;
public
constructor create(regex: string = ''; flags: RegExpFlags = []; boundString: string = '');
procedure compile(regex: string; flags: RegExpFlags = []);
procedure bind(boundString: string);
function captureLength: cardinal;
function match: boolean; overload;
function match(boundString: string): boolean; overload;
function substitute(replace: string): string; overload;
function substitute(boundString: string; replace: string): string; overload;
class function match(regex: string; bound: string; Flags: RegExpFlags = []): string; overload;
class function substitute(regex: string; bound: string; replace: string; Flags: RegExpFlags = []): string; overload;
destructor destroy; override;
public
property matched: string read Fmatched;
property capture[i: integer]: RCapture read getCapture;
property offset: integer read Foffset write Foffset;
property m[regex: string]: string read boundmatch;
property s[regex: string; replace: string]: string read boundsubstitute;
end;
function generateFlags(flags: string): RegExpFlags;
implementation
uses SysUtils;
//uses oslib, util, SysUtils;
function TRegExp.getCapture(i: integer): RCapture;
begin
result.captured := '';
if i < length(Fcapture) then
result := Fcapture[i];
end;
function TRegExp.do_match: boolean;
var
i: integer;
ovector: outputVector;
begin;
result := false;
setLength(Fcapture, 0);
Fmatched := '';
//writeln('do '+Fcompiled);
if Foffset = length(FboundString) then
exit;
//writeln('exec '+Fcompiled);
//writeln('on '+copy(FboundString, Foffset, 20));
i := pcre_exec(Fpcre, nil, PChar(FboundString), length(FboundString), Foffset, [], ovector, 96);
if i < -1 then
raise Exception.create('Match error: '+intToStr(i));
if i = -1 then exit;
if i = 0 then
raise Exception.create('Match error: too many capture strings (>32)');
result := true;
setLength(Fcapture, i);
for i := 0 to i-1 do
begin
Fcapture[i].pos := ovector[i*2]+1;
Fcapture[i].len := ovector[i*2+1]-ovector[i*2];
Fcapture[i].captured := copy(FboundString, Fcapture[i].pos, Fcapture[i].len);
end;
Fmatched := Fcapture[0].captured;
Foffset := ovector[1];
{
writeln('===');
writeln(Fmatched);
for i := 0 to i*2 do
begin
//writeln(i);
//writeln(ovector[i]);
writeln(i);
writeln(Fcapture[i].pos);
writeln(Fcapture[i].len);
writeln(Fcapture[i].captured);
end;
writeln('===');
}
end;
function TRegExp.do_match_global: boolean;
var
allCapture: RCaptureArr;
oldLen: cardinal;
i: cardinal;
begin
result := false;
setLength(allCapture, 1);
allCapture[0].pos := Foffset;
allCapture[0].len := 0;
allCapture[0].captured := '';
while result = false do
begin
result := do_match;
if result = false then break;
oldLen := length(allCapture);
setLength(allCapture, oldLen+length(Fcapture));
for i := 1 to length(Fcapture)-1 do
allCapture[i+oldLen] := Fcapture[i];
end;
allCapture[0].len := Foffset+Fcapture[length(Fcapture)-1].len;
allCapture[0].captured := copy(FboundString, allCapture[0].pos, allCapture[0].len);
Fcapture := allCapture;
Fmatched := Fcapture[0].captured;
end;
function TRegExp.do_substitute(replacement: string): string;
var
status: boolean;
i: cardinal;
origOffset: cardinal;
begin
result := '';
origOffset := Foffset;
status := do_match;
if status = false then exit;
for i := 1 to length(Fcapture)-1 do
replacement := StringReplace(replacement, '$'+intToStr(i), Fcapture[i].captured, [rfReplaceAll]);
replacement := StringReplace(replacement, '\n', #10, [rfReplaceAll]);
Fmatched := replacement;
result := FboundString;
delete(result, Fcapture[0].pos, Fcapture[0].len);
insert(replacement, result, Fcapture[0].pos);
result := copy(result, origOffset+1, length(result));
//Foffset := Foffset - Fcapture[0].len + length(replacement);
end;
function TRegExp.do_substitute_global(replacement: string): string;
var
done: boolean;
allCapture: RCaptureArr;
oldLen: cardinal;
i: cardinal;
singleSub: string;
begin
result := '';
done := false;
setLength(allCapture, 1);
allCapture[0].pos := Foffset;
allCapture[0].len := 0;
allCapture[0].captured := '';
while done = false do
begin
singleSub := do_substitute(replacement);
if singleSub = '' then break;
delete(singleSub, length(singleSub) - (length(FboundString)-Foffset) + 1, length(singleSub));
//result := result + copy(singleSub, oldLen, Foffset-oldLen+length(Fmatched));
result := result + singleSub;
oldLen := length(allCapture);
setLength(allCapture, oldLen+length(Fcapture));
for i := 1 to length(Fcapture)-1 do
allCapture[i+oldLen] := Fcapture[i];
//result := result + Fmatched;
end;
result := result + copy(FboundString, Foffset+1, length(FboundString));
if length(Fcapture) > 0 then
allCapture[0].len := Foffset+Fcapture[length(Fcapture)-1].len;
allCapture[0].captured := copy(FboundString, allCapture[0].pos, allCapture[0].len);
Fcapture := allCapture;
Fmatched := Fcapture[0].captured;
//result := Fmatched;
end;
constructor TRegExp.create(regex: string = ''; flags: RegExpFlags = []; boundString: string = '');
begin
compile(regex, flags);
bind(boundString);
setlength(Fcapture, 0);
Foffset := 0;
end;
procedure TRegExp.compile(regex: string; flags: RegExpFlags = []);
var error: PChar;
offset: integer;
begin
Fflags := flags;
FpcreFlags := [];
if IgnoreCase in flags then Include(FpcreFlags, PCRE_CASELESS);
if MultiLine in flags then Include(FpcreFlags, PCRE_MULTILINE);
if SingleLine in flags then Include(FpcreFlags, PCRE_DOTALL);
if Extended in flags then Include(FpcreFlags, PCRE_EXTENDED);
if Anch in flags then Include(FpcreFlags, PCRE_ANCHORED);
Fpcre := pcre_compile(PChar(regex), FpcreFlags, error, offset, nil);
if not assigned(Fpcre) then
begin
raise Exception.create('Compile error: '+error+' at offset '+intToStr(offset)+' : '+regex);
end;
Fcompiled := regex;
end;
procedure TRegExp.bind(boundString: string);
begin
FboundString := boundString;
Foffset := 0;
end;
function TRegExp.captureLength: cardinal;
begin
result := length(Fcapture);
end;
function TRegExp.boundmatch(regex: string): string;
var success: boolean;
begin
compile(regex);
success := do_match;
if success = false then exit;
result := Fmatched;
end;
function TRegExp.match: boolean;
begin
if Global in Fflags then
result := do_match_global
else
result := do_match;
end;
function TRegExp.match(boundString: string): boolean;
begin
bind(boundString);
result := match;
end;
class function TRegExp.match(regex: string; bound: string; Flags: RegExpFlags = []): string;
var
compiled: TRegExp;
begin
compiled := TRegExp.create(regex, Flags);
compiled.bind(bound);
compiled.match;
result := compiled.matched;
end;
function TRegExp.boundsubstitute(regex: string; replace: string): string;
begin
result := substitute(regex, replace, FboundString, Fflags);
FboundString := result;
end;
function TRegExp.substitute(replace: string): string;
begin
if Global in Fflags then
result := do_substitute_global(replace)
else
result := do_substitute(replace);
end;
function TRegExp.substitute(boundString: string; replace: string): string;
begin
bind(boundString);
result := substitute(replace);
end;
class function TRegExp.substitute(regex: string; bound: string; replace: string; Flags: RegExpFlags = []): string;
var
compiled: TRegExp;
begin
compiled := TRegExp.create(regex, Flags);
compiled.bind(bound);
result := compiled.substitute(replace);
end;
destructor TRegExp.destroy;
begin
setLength(Fcapture, 0);
if assigned(Fpcre) then
pcre_free(Fpcre);
end;
function generateFlags(flags: string): RegExpFlags;
var
i: cardinal;
begin
result := [];
if length(flags) > 0 then
for i := 1 to length(flags) do
begin
case flags[i] of
// IgnoreCase, MultiLine, SingleLine, Extended, Global
'i': Include(result, IgnoreCase);
'm': Include(result, MultiLine);
's': Include(result, SingleLine);
'x': Include(result, Extended);
'g': Include(result, Global);
end;
end;
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
// 报表中心
//主要实现:
// 报表的增加、设计等
// 系统的所有报表均在此管理
//-----------------------------------------------------------------------------}
unit untEasySysConst;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, untEasyPlateDBBaseForm, untEasyToolBar, untEasyToolBarStylers,
DB, ImgList, DBClient, ActnList, Grids, untEasyBaseGrid, untEasyGrid,
untEasyDBGrid, untEasyClassSysConst, untEasyUtilMethod, untEasyUtilConst;
//插件导出函数
function ShowBplForm(AParamList: TStrings): TForm; stdcall; exports ShowBplForm;
type
TfrmEasySysConst = class(TfrmEasyPlateDBBaseForm)
actDataList: TActionList;
actNewMst: TAction;
actEdit: TAction;
actDelete: TAction;
actCopy: TAction;
actPaste: TAction;
actRedo: TAction;
actUndo: TAction;
actFind: TAction;
actPrint: TAction;
actExit: TAction;
actAddDtl: TAction;
actEditDtl: TAction;
actDeleteDtl: TAction;
actCopyDtl: TAction;
actRedoDtl: TAction;
actUndoDtl: TAction;
actSave: TAction;
actRefresh: TAction;
cdsSysConstMain: TClientDataSet;
imgToolBar: TImageList;
dsSysConstMain: TDataSource;
edpMain: TEasyDockPanel;
tlbMain: TEasyToolBar;
EasyToolBarButton2: TEasyToolBarButton;
EasyToolBarButton1: TEasyToolBarButton;
EasyToolBarButton3: TEasyToolBarButton;
EasyToolBarSeparator1: TEasyToolBarSeparator;
EasyToolBarSeparator2: TEasyToolBarSeparator;
EasyToolBarButton9: TEasyToolBarButton;
EasyToolBarButton11: TEasyToolBarButton;
EasyToolBarButton15: TEasyToolBarButton;
EasyToolBarButton7: TEasyToolBarButton;
tbosMain: TEasyToolBarOfficeStyler;
EasyDBGrid1: TEasyDBGrid;
EasyToolBarButton4: TEasyToolBarButton;
procedure FormShow(Sender: TObject);
procedure actNewMstExecute(Sender: TObject);
procedure actExitExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actEditUpdate(Sender: TObject);
procedure actDeleteUpdate(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actUndoExecute(Sender: TObject);
procedure actRefreshUpdate(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
procedure actSaveUpdate(Sender: TObject);
procedure actUndoUpdate(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure EasyDBGrid1EditingDone(Sender: TObject);
procedure cdsSysConstMainAfterEdit(DataSet: TDataSet);
private
{ Private declarations }
procedure InitData;
function CheckNotNULL: Boolean;
public
{ Public declarations }
end;
var
frmEasySysConst: TfrmEasySysConst;
implementation
{$R *.dfm}
uses
untEasyDBConnection;
//引出函数实现
function ShowBplForm(AParamList: TStrings): TForm;
begin
frmEasySysConst := TfrmEasySysConst.Create(Application);
if frmEasySysConst.FormStyle <> fsMDIChild then
frmEasySysConst.FormStyle := fsMDIChild;
if frmEasySysConst.WindowState <> wsMaximized then
frmEasySysConst.WindowState := wsMaximized;
Result := frmEasySysConst;
end;
{ TfrmEasySysConst }
procedure TfrmEasySysConst.InitData;
var
ASQL: string;
begin
ASQL := 'SELECT * FROM vw_SysConst';
cdsSysConstMain.Data := EasyRDMDisp.EasyGetRDMData(ASQL);
end;
procedure TfrmEasySysConst.FormShow(Sender: TObject);
begin
inherited;
InitData;
EasyDBGrid1.Options := EasyDBGrid1.Options - [goEditing];
EasyDBGrid1.AutoNumberCol(0);
end;
procedure TfrmEasySysConst.actNewMstExecute(Sender: TObject);
begin
inherited;
cdsSysConstMain.Last;
EasyDBGrid1.Options := EasyDBGrid1.Options + [goEditing];
EasyDBGrid1.Refresh;
with cdsSysConstMain do
begin
Append;
FieldByName('ConstGUID').AsString := GenerateGUID;
//2 CName
FieldByName('CName').AsString := '';
//3 EName
FieldByName('EName').AsString := '';
//4 Value
FieldByName('Value').AsString := '';
//5 CreateTime
FieldByName('CreateTime').AsDateTime := Now;
//6 Creater
FieldByName('Creater').AsString := EasyCurrLoginSysUser.UserGUID;
//7 Updater
FieldByName('Updater').AsString := EasyCurrLoginSysUser.UserGUID;
//8 UpdateTime
FieldByName('UpdateTime').AsDateTime := Now;
Post;
end;
EasyDBGrid1.AutoNumberCol(0);
end;
procedure TfrmEasySysConst.actExitExecute(Sender: TObject);
begin
inherited;
if cdsSysConstMain.ChangeCount > 0 then
begin
case Application.MessageBox('数据已发生改变是否保存?', '提示',
MB_YESNOCANCEL + MB_ICONQUESTION) of
IDYES:
begin
actSaveExecute(Sender);
Close;
end;
IDNO:
begin
Close;
end;
end;
end else
Close;
end;
procedure TfrmEasySysConst.actEditExecute(Sender: TObject);
begin
inherited;
EasyDBGrid1.Options := EasyDBGrid1.Options + [goEditing];
end;
procedure TfrmEasySysConst.actEditUpdate(Sender: TObject);
begin
inherited;
actEdit.Enabled := cdsSysConstMain.RecordCount > 0;
end;
procedure TfrmEasySysConst.actDeleteUpdate(Sender: TObject);
begin
inherited;
actDelete.Enabled := cdsSysConstMain.RecordCount > 0;
end;
procedure TfrmEasySysConst.actDeleteExecute(Sender: TObject);
begin
inherited;
cdsSysConstMain.Delete;
end;
procedure TfrmEasySysConst.actUndoExecute(Sender: TObject);
begin
inherited;
if Application.MessageBox('确定要取消所做的更改吗?', '提示', MB_OKCANCEL +
MB_ICONQUESTION) = IDOK then
begin
cdsSysConstMain.CancelUpdates;
end;
end;
procedure TfrmEasySysConst.actRefreshUpdate(Sender: TObject);
begin
inherited;
actRefresh.Enabled := cdsSysConstMain.RecordCount > 0;
end;
procedure TfrmEasySysConst.actSaveExecute(Sender: TObject);
var
AResultOle: OleVariant;
cdsError : TClientDataSet;
AErrorCode: Integer;
begin
inherited;
if not CheckNotNULL then Exit;
AErrorCode := 0;
if cdsSysConstMain.ChangeCount > 0 then
begin
AResultOle := EasyRDMDisp.EasySaveRDMData('SysConst', cdsSysConstMain.Delta,
'ConstGUID', AErrorCode);
if AErrorCode <> 0 then
begin
cdsError := TClientDataSet.Create(Self);
try
cdsError.Data := AResultOle;
Application.MessageBox(PChar(EASY_SYS_SAVE_FAILED + #13
+ cdsError.fieldbyname('ERROR_MESSAGE').AsString), EASY_SYS_HINT, MB_OK + MB_ICONERROR);
finally
cdsError.Free;
end;
end else
begin
if cdsSysConstMain.ChangeCount > 0 then
cdsSysConstMain.MergeChangeLog;
Application.MessageBox(EASY_SYS_SAVE_SUCCESS, EASY_SYS_HINT, MB_OK + MB_ICONINFORMATION);
end;
end;
end;
procedure TfrmEasySysConst.actSaveUpdate(Sender: TObject);
begin
inherited;
actSave.Enabled := cdsSysConstMain.ChangeCount > 0;
end;
function TfrmEasySysConst.CheckNotNULL: Boolean;
var
I: Integer;
Flag: Boolean;
begin
// Result := False;
Flag := False;
if cdsSysConstMain.State = dsEdit then cdsSysConstMain.Post;
try
cdsSysConstMain.DisableControls;
cdsSysConstMain.First;
for I := 0 to cdsSysConstMain.RecordCount - 1 do
begin
if Trim(cdsSysConstMain.FieldByName('EName').AsString) = '' then
begin
Application.MessageBox(PChar('第' + inttostr(I + 1) + '行记录,常量【英文名称】不能为空!'),
'提示', MB_OK + MB_ICONINFORMATION);
Flag := True;
end else
if Trim(cdsSysConstMain.FieldByName('Value').AsString) = '' then
begin
Application.MessageBox(PChar('第' + inttostr(I + 1) + '行记录,常量【值】不能为空!'),
'提示', MB_OK + MB_ICONINFORMATION);
Flag := True;
end;
if Flag then
Break
else
cdsSysConstMain.Next;
end;
finally
cdsSysConstMain.EnableControls;
end;
Result := not Flag;
end;
procedure TfrmEasySysConst.actUndoUpdate(Sender: TObject);
begin
inherited;
actUndo.Enabled := cdsSysConstMain.ChangeCount > 0;
end;
procedure TfrmEasySysConst.actRefreshExecute(Sender: TObject);
begin
inherited;
if cdsSysConstMain.ChangeCount > 0 then
begin
case Application.MessageBox('数据已发生改变是否先保存再刷新?', '提示',
MB_YESNO + MB_ICONQUESTION) of
IDYES:
begin
actSaveExecute(Sender);
end;
IDNO:
begin
cdsSysConstMain.CancelUpdates;
end;
end;
end;
end;
procedure TfrmEasySysConst.EasyDBGrid1EditingDone(Sender: TObject);
begin
inherited;
cdsSysConstMain.Edit;
end;
procedure TfrmEasySysConst.cdsSysConstMainAfterEdit(DataSet: TDataSet);
begin
inherited;
with cdsSysConstMain do
begin
Edit;
//7 Updater
FieldByName('Updater').AsString := EasyCurrLoginSysUser.UserGUID;
//8 UpdateTime
FieldByName('UpdateTime').AsDateTime := Now;
Post;
end;
end;
end.
|
unit IdentifyDiagnosis;
interface
uses
SysUtils, Classes, ClipBrd, Windows,
Device.PhysicalDrive.List, Device.PhysicalDrive, Global.LanguageString,
Global.Constant, Getter.PhysicalDrive.ListChange, OS.Version.Helper,
Getter.DeviceDriver, Support;
type
TIdentifyDiagnosis = class
public
procedure DiagnoseAndSetClipboardResult;
private
procedure Header(Contents: TStringList);
procedure Body(Contents: TStringList);
procedure Footer(Contents: TStringList);
procedure AddSupportString(Contents: TStringList;
CurrEntry: IPhysicalDrive);
procedure AddDriverString(Contents: TStringList; CurrEntry: IPhysicalDrive);
end;
implementation
procedure TIdentifyDiagnosis.DiagnoseAndSetClipboardResult;
var
DiagnosisResult: TStringList;
begin
DiagnosisResult := TStringList.Create;
Header(DiagnosisResult);
Body(DiagnosisResult);
Footer(DiagnosisResult);
Clipboard.AsText := DiagnosisResult.Text;
MessageBox(0, PChar(DiagContents[CurrLang]), PChar(DiagName[CurrLang]),
MB_OK or MB_IConInformation);
FreeAndNil(DiagnosisResult);
end;
procedure TIdentifyDiagnosis.Header(Contents: TStringList);
begin
Contents.Add('DiagStart, ' + FormatDateTime('yyyy/mm/dd hh:nn:ss', Now));
Contents.Add('Version, ' + CurrentVersion);
end;
procedure TIdentifyDiagnosis.Body(Contents: TStringList);
var
SSDList: TPhysicalDriveList;
ListChangeGetter: TListChangeGetter;
CurrEntry: IPhysicalDrive;
begin
SSDList := TPhysicalDriveList.Create;
ListChangeGetter := TListChangeGetter.Create;
ListChangeGetter.IsOnlyGetSupportedDrives := false;
ListChangeGetter.RefreshListWithoutResultFrom(SSDList);
FreeAndNil(ListChangeGetter);
Contents.Add('WindowsVersion, ' + GetWindowsVersionString);
Contents.Add('WindowsArchitecture, ' + GetWindowsArchitectureString);
for CurrEntry in SSDList do
begin
Contents.Add('Probe, ' + CurrEntry.GetPathOfFileAccessing + ', ');
Contents[Contents.Count - 1] :=
Contents[Contents.Count - 1] +
CurrEntry.IdentifyDeviceResult.Model + ', ' +
CurrEntry.IdentifyDeviceResult.Firmware + ', ';
AddSupportString(Contents, CurrEntry);
AddDriverString(Contents, CurrEntry);
end;
FreeAndNil(SSDList);
end;
procedure TIdentifyDiagnosis.Footer(Contents: TStringList);
begin
Contents.Add('DiagEnd, ' + FormatDateTime('yyyy/mm/dd hh:nn:ss', Now));
end;
procedure TIdentifyDiagnosis.AddSupportString(Contents: TStringList;
CurrEntry: IPhysicalDrive);
begin
if CurrEntry.SupportStatus.FirmwareUpdate then
begin
Contents[Contents.Count - 1] := Contents[Contents.Count - 1] + 'Full';
end
else if CurrEntry.SupportStatus.Supported <> NotSupported then
begin
Contents[Contents.Count - 1] := Contents[Contents.Count - 1] + 'Semi';
end
else
begin
Contents[Contents.Count - 1] := Contents[Contents.Count - 1] + 'None';
end;
Contents[Contents.Count - 1] := Contents[Contents.Count - 1] + ', ';
end;
procedure TIdentifyDiagnosis.AddDriverString(Contents: TStringList;
CurrEntry: IPhysicalDrive);
var
DeviceDriverGetter: TDeviceDriverGetter;
DeviceDriver: TDeviceDriver;
begin
DeviceDriverGetter := TDeviceDriverGetter.Create(
CurrEntry.GetPathOfFileAccessing);
try
DeviceDriver := DeviceDriverGetter.GetDeviceDriver;
Contents[Contents.Count - 1] := Contents[Contents.Count - 1] +
DeviceDriver.Name + ', ' + DeviceDriver.Provider + ', ' +
DeviceDriver.Date + ', ' + DeviceDriver.InfName + ', ' +
DeviceDriver.Version;
finally
FreeAndNil(DeviceDriverGetter);
end;
end;
end.
|
unit Command.DiceRoll;
interface
uses
System.SysUtils,
System.Classes,
System.Math,
System.Diagnostics,
Pattern.Command,
Vcl.Forms,
Vcl.StdCtrls,
Vcl.ComCtrls;
type
TDiceRollCommand = class(TCommand)
const
MaxDiceValue = 6;
private
fRolls: TArray<Integer>;
fResultDistribution: TArray<Integer>;
fReportMemo: TMemo;
fProgressBar: TProgressBar;
fProgressLabel: TLabel;
fRollsCount: Integer;
fStep: Integer;
fIsTerminated: boolean;
procedure DoDisplayStepInfo;
procedure DoDisplaySummaryInfo;
procedure DoSomeOtherWork(aSpendMiliseconds: double);
protected
procedure DoGuard; override;
procedure DoExecute; override;
public
procedure Terminate;
published
property ReportMemo: TMemo read fReportMemo write fReportMemo;
property ProgressBar: TProgressBar read fProgressBar write fProgressBar;
property ProgressLabel: TLabel read fProgressLabel write fProgressLabel;
property RollsCount: Integer read fRollsCount write fRollsCount;
end;
implementation
procedure TDiceRollCommand.DoGuard;
begin
System.Assert(fReportMemo <> nil);
System.Assert(fProgressBar <> nil);
end;
procedure TDiceRollCommand.Terminate;
begin
fIsTerminated := True;
end;
procedure TDiceRollCommand.DoDisplayStepInfo;
begin
fProgressBar.Position := fStep;
if fProgressLabel <> nil then
fProgressLabel.Caption := Format('calculating %d/%d', [fStep, fRollsCount]);
end;
procedure TDiceRollCommand.DoDisplaySummaryInfo;
var
i: Integer;
begin
ReportMemo.Lines.Add(Format('Elapsed time: %.1f seconds',
[GetElapsedTime.TotalSeconds]));
ReportMemo.Lines.Add
(Format('Dice results (%d-sided dice) (number of rolls: %d)',
[MaxDiceValue, fRollsCount]));
for i := 1 to MaxDiceValue do
ReportMemo.Lines.Add(Format(' [%d] : %d', [i, fResultDistribution[i]]));
end;
procedure TDiceRollCommand.DoSomeOtherWork (aSpendMiliseconds: double);
var
sw: TStopwatch;
begin
sw := TStopWatch.Create;
sw.Start;
while sw.Elapsed.Milliseconds<aSpendMiliseconds do;
end;
procedure TDiceRollCommand.DoExecute;
var
idx: Integer;
number: Integer;
begin
fIsTerminated := False;
fProgressBar.Max := fRollsCount;
fProgressBar.Position := 0;
SetLength(fRolls, fRollsCount);
SetLength(fResultDistribution, MaxDiceValue + 1);
for idx := 1 to MaxDiceValue do
fResultDistribution[idx] := 0;
for idx := 0 to fRollsCount - 1 do
begin
fStep := idx + 1;
DoDisplayStepInfo;
number := RandomRange(1, MaxDiceValue + 1);
fResultDistribution[number] := fResultDistribution[number] + 1;
fRolls[idx] := number;
DoSomeOtherWork(1.5);
Application.ProcessMessages;
if fIsTerminated then
Break;
end;
DoDisplaySummaryInfo;
DoDisplayStepInfo;
end;
end.
|
unit RecordMethodsForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
procedure Show (const msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
type
TMyRecord = record
private
Name: string;
Value: Integer;
SomeChar: Char;
public
function ToString: string;
procedure SetValue (NewString: string);
procedure Init (NewValue: Integer);
end;
type
TMyNewRecord = record
private
Name: string;
Value: Integer;
SomeChar: Char;
public
constructor Create (NewString: string);
function ToString: string;
procedure SetValue (NewString: string);
procedure Init (NewValue: Integer);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
MyRec: TMyRecord;
begin
MyRec.Init(10);
MyRec.SetValue ('hello');
Show (MyRec.ToString);
MyRec.Value := 20; // actually works!
end;
procedure TForm1.Button2Click(Sender: TObject);
var
MyRec: TMyRecord;
begin
Show (MyRec.ToString);
end;
procedure TForm1.Button3Click(Sender: TObject);
var
MyRec, MyRec2: TMyNewRecord;
begin
MyRec := TMyNewRecord.Create ('Myself');
MyRec2.Create ('Myself');
Show (MyRec.ToString);
Show (MyRec2.ToString);
end;
procedure TForm1.Show(const msg: string);
begin
Memo1.Lines.Add(msg);
end;
{ TMyRecord }
procedure TMyRecord.Init(NewValue: Integer);
begin
Value := NewValue;
SomeChar := 'A';
end;
function TMyRecord.ToString: string;
begin
Result := Name + ' [' + SomeChar + ']: ' + Value.ToString;
end;
procedure TMyRecord.SetValue(NewString: string);
begin
Name := NewString;
end;
{ TMyNewRecord }
constructor TMyNewRecord.Create (NewString: string);
begin
Name := NewString;
Init (0);
end;
procedure TMyNewRecord.Init(NewValue: Integer);
begin
Value := NewValue;
SomeChar := 'A';
end;
procedure TMyNewRecord.SetValue(NewString: string);
begin
Name := NewString;
end;
function TMyNewRecord.ToString: string;
begin
Result := Name + ' [' + SomeChar + ']: ' + Value.ToString;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Controls, Vcl.Forms, Vcl.StdCtrls,
//GLS
GLScene, GLVectorFileObjects, GLObjects, GLWin32Viewer,
GLVectorGeometry, GLGeomObjects, GLCrossPlatform, GLCoordinates,
GLBaseClasses, GLFile3DS, GLUtils;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
DummyCube1: TGLDummyCube;
FreeForm1: TGLFreeForm;
Sphere1: TGLSphere;
ArrowLine1: TGLArrowLine;
GLSceneViewer2: TGLSceneViewer;
GLCamera2: TGLCamera;
Label1: TLabel;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure GLSceneViewer2MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer2MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
// Load mushroom mesh
SetGLSceneMediaDir();
FreeForm1.LoadFromFile('mushroom.3ds');
end;
// Perform the raycasting for the perspective camera & viewer
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
rayStart, rayVector, iPoint, iNormal : TVector;
begin
// retrieve raycasting data:
// rayStart is obtained for camera and screen position
// rayVector is the camera direction (i.e direction to target since our camera is targeted)
// (note that (0, 0) is lower left for the Screen function, whereas Delphi
// uses top-left as origin, hence the Y inversion)
SetVector(rayStart, GLSceneViewer1.Buffer.OrthoScreenToWorld(x, GLSceneViewer1.Height-y));
SetVector(rayVector, GLCamera1.AbsoluteVectorToTarget);
NormalizeVector(rayVector);
// Here we require RayCast intersection
if FreeForm1.RayCastIntersect(rayStart, rayVector, @iPoint, @iNormal) then begin
// got one, move the sphere there and orient it appropriately
Sphere1.Position.AsVector:=iPoint;
Sphere1.Direction.AsVector:=VectorNormalize(iNormal);
// make it visible
Sphere1.Visible:=True;
end else begin
// hide it if we did not hit
Sphere1.Visible:=False;
end;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
// when mouse moves, recompute intersection
if Shift<>[] then GLSceneViewer1MouseDown(Sender, TMouseButton(mbLeft), Shift, x, y);
end;
// Perform the raycasting for the perspective camera & viewer
procedure TForm1.GLSceneViewer2MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
rayStart, rayVector, iPoint, iNormal : TVector;
begin
// retrieve raycasting data:
// rayStart is the eye (camera) position
// rayVector is computed from screen position
// (note that (0, 0) is lower left for the Screen function, whereas Delphi
// uses top-left as origin, hence the Y inversion)
SetVector(rayStart, GLCamera2.AbsolutePosition);
SetVector(rayVector, GLSceneViewer2.Buffer.ScreenToVector(AffineVectorMake(x, GLSceneViewer2.Height-y, 0)));
NormalizeVector(rayVector);
// Here we request RayCast intersection
if FreeForm1.RayCastIntersect(rayStart, rayVector, @iPoint, @iNormal) then begin
// got one, move the sphere there and orient it appropriately
Sphere1.Position.AsVector:=iPoint;
Sphere1.Direction.AsVector:=VectorNormalize(iNormal);
// make it visible
Sphere1.Visible:=True;
end else begin
// hide it if we did not hit
Sphere1.Visible:=False;
end;
end;
procedure TForm1.GLSceneViewer2MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Shift<>[] then GLSceneViewer2MouseDown(Sender, TMouseButton(mbLeft), Shift, x, y);
end;
end.
|
{$I ACBr.inc}
unit Unit1;
interface
uses ShellAPI, Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, ComCtrls,
OleCtrls, SHDocVw, FileCtrl, XMLIntf, XMLDoc, zlib, StrUtils, Math,
TypInfo, DateUtils,
// ACBr
synacode, ACBrBase, ACBrNFe, pcnNFe, pcnConversao, ACBrUtil, pcnAuxiliar,
// ACBr Rave
ACBrNFeDANFEClass, ACBrNFeDANFERave, ACBrNFeDANFERaveCB, ACBrDFe;
type
{ TForm1 }
TForm1 = class(TForm)
OpenDialog1: TOpenDialog;
ACBrNFe1: TACBrNFe;
btnImprimir: TButton;
ACBrNFeDANFERave1: TACBrNFeDANFERave;
ACBrNFeDANFERaveCB1: TACBrNFeDANFERaveCB;
RGTipoComponente: TRadioGroup;
RGModoImpressao: TRadioGroup;
RGGeracaoDANFE: TRadioGroup;
procedure btnImprimirClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
const
SELDIRHELP = 1000;
{$R *.dfm}
procedure TForm1.btnImprimirClick(Sender: TObject);
begin
OpenDialog1.Title := 'Selecione a NFE';
OpenDialog1.DefaultExt := '*-nfe.XML';
OpenDialog1.Filter := 'Arquivos NFE (*-nfe.XML)|*-nfe.XML|Arquivos XML (*.XML)|*.XML|Todos os Arquivos (*.*)|*.*';
case RGTipoComponente.ItemIndex of
0:
begin
ACBrNFe1.DANFE := ACBrNFeDANFERave1;
ACBrNFeDANFERave1.RavFile := '..\NotaFiscalEletronica.rav';
end;
1: ACBrNFe1.DANFE := ACBrNFeDANFERaveCB1;
end;
case RGModoImpressao.ItemIndex of
0: ACBrNFe1.DANFE.TipoDANFE := tiRetrato;
1: ACBrNFe1.DANFE.TipoDANFE := tiPaisagem;
end;
if OpenDialog1.Execute then
begin
ACBrNFe1.NotasFiscais.Clear;
ACBrNFe1.NotasFiscais.LoadFromFile(OpenDialog1.FileName,False);
case RGGeracaoDANFE.ItemIndex of
0: ACBrNFe1.NotasFiscais.Imprimir;
1:
begin
ACBrNFe1.Configuracoes.Arquivos.PathSalvar := ExtractFilePath(Application.ExeName);
ACBrNFe1.NotasFiscais.ImprimirPDF;
end;
end;
end;
end;
end.
|
PROGRAM Hello(INPUT, OUTPUT);
BEGIN
REPEAT{
WRITELN('Hello world!');
UNTIL FALSE;
|
unit cCliente;
interface
type
Cliente = class (TObject)
protected
codCli : integer;
nomeCli : string;
endCli : string;
bairroCli : string;
cidCli : string;
emailCli : string;
obsCli : string;
statusCli : String;
public
Constructor Create ( codCli : integer; nomeCli : string; endCli : string;
bairroCli : string; cidCli : string;
emailCli : string; obsCli : string; statusCli : String);
Procedure setCodCli (codCli:integer);
Function getCodCli:integer;
Procedure setNomeCli(nomeCli:string);
Function getnomeCli:string;
Procedure setendCli (endCli:string);
Function getendCli:string;
Procedure setBairroCli (bairroCli:string);
Function getbairroCli:string;
Procedure setcidCli (cidCli:string);
Function getcidCli:string;
Procedure setemailCli(emailCli:string);
Function getemailCli:string;
Procedure setobsCli(obsCli:string);
Function getobsCli:string;
Procedure setstatusCli (statusCli : String);
Function getStatusCli : String;
end;
implementation
Constructor Cliente.Create (codCli : integer; nomeCli : string; endCli : string;
bairroCli : string; cidCli : string;
emailCli : string; obsCli : string; statusCli : String);
begin
self.codCli := codCli;
self.nomeCli := nomeCli;
self.endCli := endCli;
self.bairroCli := bairroCli;
self.cidCli := cidCli;
self.emailCli := emailCli;
self.obsCli := obsCli;
self.statusCli := statusCli;
end;
Procedure Cliente.setCodCli(codCli:integer);
begin
self.codCli := codCli;
end;
Function Cliente.getCodCli:integer;
begin
result := codCli;
end;
Procedure Cliente.setNomeCli(nomeCli:string);
begin
self.nomeCli := nomeCli;
end;
Function Cliente.getnomeCli:string;
begin
result := nomeCli;
end;
Procedure Cliente.setendCli(endCli:string);
begin
self.endCli := endCli;
end;
Function Cliente.getendCli:string;
begin
result := endCli;
end;
Procedure Cliente.setBairroCli(bairroCli:string);
begin
self.bairroCli := bairroCli;
end;
Function Cliente.getbairroCli:string;
begin
result := bairroCli;
end;
Procedure Cliente.setcidCli(cidCli:string);
begin
self.cidCli := cidCli;
end;
Function Cliente.getcidCli:string;
begin
result := cidCli;
end;
Procedure Cliente.setemailCli(emailCli:string);
begin
self.emailCli := emailCli;
end;
Function Cliente.getemailCli:string;
begin
result := emailCli;
end;
Procedure Cliente.setobsCli(obsCli:string);
begin
self.obsCli := obsCli;
end;
Function Cliente.getobsCli:string;
begin
result := obsCli;
end;
Procedure Cliente.setstatusCli(statusCli:String);
begin
self.statusCli := statusCli;
end;
Function Cliente.getStatusCli:String;
begin
result := statusCli;
end;
end.
|
unit ImmHeadDetail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, RzButton, RzTabs,
Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, Vcl.Mask,
RzEdit, RzDBEdit;
type
TfrmImmHeadDetail = class(TfrmBasePopupDetail)
edMiddle: TRzDBEdit;
edFirstname: TRzDBEdit;
edLastname: TRzDBEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
private
{ Private declarations }
protected
procedure Save; override;
procedure Cancel; override;
procedure BindToObject; override;
function ValidEntry: boolean; override;
end;
implementation
uses
EntitiesData, ImmediateHead, IFinanceDialogs, EntityUtils;
{$R *.dfm}
procedure TfrmImmHeadDetail.BindToObject;
begin
inherited;
end;
procedure TfrmImmHeadDetail.Cancel;
begin
inherited;
immHead.Cancel;
end;
procedure TfrmImmHeadDetail.Save;
begin
immHead.Save;
end;
function TfrmImmHeadDetail.ValidEntry: boolean;
var
error: string;
duplicates: integer;
begin
if Trim(edLastname.Text) = '' then
error := 'Please enter a lastname.'
else if Trim(edFirstname.Text) = '' then
error := 'Please enter a firstname.'
else if Trim(edMiddle.Text) = '' then
error := 'Please enter a middlename.'
else
begin
duplicates := CheckDuplicate(edLastname.Text,edFirstname.Text,edMiddle.Text,false);
if duplicates > 0 then error := 'Duplicates found.';
end;
Result := error = '';
if not Result then ShowErrorBox(error);
end;
end.
|
unit formConfigServer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TfrmConfigServer = class(TForm)
mmoServer: TMemo;
btnSave: TButton;
btnClose: TButton;
lblHint: TLabel;
procedure btnSaveClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
g_strConfigFileName: string;
g_bSave: boolean;
end;
var
frmConfigServer: TfrmConfigServer;
implementation
{$R *.dfm}
procedure TfrmConfigServer.btnSaveClick(Sender: TObject);
var
strFileName: string;
begin
mmoServer.Lines.SaveToFile(g_strConfigFileName);
g_bSave := true;
Close;
end;
procedure TfrmConfigServer.btnCloseClick(Sender: TObject);
begin
g_bSave := false;
Close;
end;
end.
|
unit SimpleLoggerUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, SyncObjs, MTUtils, TimeIntervals, MTLogger;
type
TDemoLoggerForm = class(TForm)
Button1: TButton;
Label1: TLabel;
Edit1: TEdit;
Button2: TButton;
Label2: TLabel;
Label3: TLabel;
cbCloseApp: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DemoLoggerForm: TDemoLoggerForm;
implementation
{$R *.dfm}
procedure TDemoLoggerForm.Button1Click(Sender: TObject);
var
ti: TTimeInterval;
I: Integer;
AFileName: string;
begin
AFileName := ExtractFilePath(Application.ExeName) + 'EventsNoThread.log';
ti.Start;
for I := 1 to StrToInt(Edit1.Text) do
WriteStringToTextFile(AFileName, Format('%s [P:%d T:%d] - Событие №%d',
[FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', Now), GetCurrentProcessId, GetCurrentThreadId, I]));
ShowMessageFmt('Время добавления событий в лог-файл: %d мс', [ti.ElapsedMilliseconds]);
end;
procedure TDemoLoggerForm.Button2Click(Sender: TObject);
var
ti: TTimeInterval;
I: Integer;
begin
ti.Start;
for I := 1 to StrToInt(Edit1.Text) do
DefLogger.AddToLog(Format('Событие №%d', [I]));
if cbCloseApp.Checked then
Close
else
ShowMessageFmt('Время добавления событий в лог-файл: %d мс', [ti.ElapsedMilliseconds]);
end;
procedure TDemoLoggerForm.FormCreate(Sender: TObject);
begin
AllowMessageBoxIfError := True; // Только в демонстрационных целях!!!
CreateDefLogger(ExtractFilePath(Application.ExeName) + 'EventsInThread.log');
end;
procedure TDemoLoggerForm.FormDestroy(Sender: TObject);
begin
FreeDefLogger;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBConnAdmin;
interface
uses
System.Classes,
System.IniFiles
;
type
{ IConnectionAdmin }
IConnectionAdmin = interface
function GetDisplayDriverName(const DriverName: string): string;
function GetDisplayDriverNames(List: TStrings): Integer;
function GetDriverNames(List: TStrings): Integer;
function GetDelegateDriverNames(List: TStrings): Integer;
function GetDriverParams(const DriverName: string; Params: TStrings): Integer;
procedure GetDriverLibNames(const DriverName: string;
var LibraryName, VendorLibrary: string);
function GetConnectionNames(List: TStrings;DriverName: string): Integer;
function GetConnectionParams(const ConnectionName: string; Params: TStrings): Integer;
procedure AddConnection(const ConnectionName, DriverName: string);
procedure DeleteConnection(const ConnectionName: string);
procedure ModifyConnection(const ConnectionName: string; Params: TStrings);
procedure RenameConnection(const OldName, NewName: string);
procedure RegisterDriver(const DriverName: string);
procedure UnregisterDriver(const DriverName: string);
end;
{ TConnectionAdmin }
TConnectionAdmin = class(TInterfacedObject, IConnectionAdmin)
private
FConnectionConfig: TCustomIniFile;
FRegisteredDriverNames: TStrings;
procedure CheckConfigFile;
procedure InitializeDriverNames;
protected
{ IConnectionAdmin }
function GetDisplayDriverName(const DriverName: string): string;
function GetDisplayDriverNames(List: TStrings): Integer;
function GetDriverNames(List: TStrings): Integer;
function GetDelegateDriverNames(List: TStrings): Integer;
function GetDriverParams(const DriverName: string; Params: TStrings): Integer;
procedure GetDriverLibNames(const DriverName: string;
var LibraryName, VendorLibrary: string);
function GetConnectionNames(List: TStrings; DriverName: string): Integer;
function GetConnectionParams(const ConnectionName: string; Params: TStrings): Integer;
procedure AddConnection(const ConnectionName, DriverName: string);
procedure DeleteConnection(const ConnectionName: string);
procedure ModifyConnection(const ConnectionName: string; Params: TStrings);
procedure RenameConnection(const OldName, NewName: string);
procedure RegisterDriver(const DriverName: string);
procedure UnregisterDriver(const DriverName: string);
public
constructor Create;
destructor Destroy; override;
property ConnectionConfig: TCustomIniFile read FConnectionConfig;
end;
function GetConnectionAdmin: IConnectionAdmin;
implementation
uses
System.SysUtils,
Data.SqlConst,
Data.SqlExpr,
Data.DB,
Data.DBXCommon
;
var
ConnAdmin: IConnectionAdmin = nil;
{ Global Functions }
function GetConnectionAdmin: IConnectionAdmin;
begin
if ConnAdmin = nil then
ConnAdmin := TConnectionAdmin.Create;
Result := IConnectionAdmin(ConnAdmin);
end;
function FormatLine(const Key, Value: string): string;
begin
Result := Format('%s=%s', [Key, Value]);
end;
function GetValue(const Line: string): string;
var
ValPos: Integer;
begin
ValPos := Line.IndexOf('=') + 1;
if ValPos > 0 then
Result := Line.Substring(ValPos, MAXINT) else
Result := '';
end;
procedure WriteSectionValues(IniFile: TCustomIniFile; const Section: string; Strings: TStrings);
var
I: Integer;
begin
IniFile.EraseSection(Section);
for I := 0 to Strings.Count - 1 do
IniFile.WriteString(Section, Strings.Names[I], GetValue(Strings[I]));
IniFile.UpdateFile;
end;
{ TConnectionAdmin }
constructor TConnectionAdmin.Create;
var
sConfigFile: string;
begin
inherited Create;
FRegisteredDriverNames := TStringList.Create;
sConfigFile := GetConnectionRegistryFile(True);
if not FileExists(sConfigFile) then
begin
FConnectionConfig := nil;
Exit;
end;
FConnectionConfig := TMemIniFile.Create(sConfigFile);
try
TMemIniFile(FConnectionConfig).Encoding := TEncoding.UTF8;
except
FConnectionConfig.Free;
raise;
end;
InitializeDriverNames;
end;
destructor TConnectionAdmin.Destroy;
begin
inherited;
FConnectionConfig.Free;
FRegisteredDriverNames.Free;
end;
procedure TConnectionAdmin.CheckConfigFile;
var
sConfigFile: string;
begin
if FConnectionConfig = nil then
begin
sConfigFile := GetConnectionRegistryFile(True);
DatabaseErrorFmt(SMissingDriverRegFile,[sConfigFile]);
end;
end;
procedure TConnectionAdmin.AddConnection(const ConnectionName,
DriverName: string);
var
Params: TStrings;
DriverIndex: Integer;
begin
CheckConfigFile;
Params := TStringList.Create;
try
GetDriverParams(DriverName, Params);
Params.Insert(0, FormatLine(DRIVERNAME_KEY, DriverName));
DriverIndex := Params.IndexOfName(GETDRIVERFUNC_KEY);
if DriverIndex <> -1 then
Params.Delete(DriverIndex);
WriteSectionValues(ConnectionConfig, ConnectionName, Params);
finally
Params.Free
end;
end;
procedure TConnectionAdmin.DeleteConnection(const ConnectionName: string);
begin
CheckConfigFile;
ConnectionConfig.EraseSection(ConnectionName);
ConnectionConfig.UpdateFile;
end;
function TConnectionAdmin.GetConnectionNames(List: TStrings;
DriverName: string): Integer;
var
I: Integer;
A: TStringList;
begin
CheckConfigFile;
A := TStringList.Create;
try
ConnectionConfig.ReadSections(A);
List.Assign(A);
finally
A.Free;
end;
if DriverName <> '' then
begin
List.BeginUpdate;
try
I := List.Count - 1;
while I >= 0 do
begin
if AnsiCompareText(ConnectionConfig.ReadString(List[i], DRIVERNAME_KEY, ''), DriverName) <> 0 then
List.Delete(I);
Dec(I);
end;
finally
List.EndUpdate;
end;
end;
Result := List.Count;
end;
function TConnectionAdmin.GetConnectionParams(const ConnectionName: string;
Params: TStrings): Integer;
var
A: TStringList;
begin
CheckConfigFile;
A := TStringList.Create;
try
ConnectionConfig.ReadSectionValues(ConnectionName, A);
Params.Assign(A);
finally
A.Free;
end;
Result := Params.Count;
end;
function TConnectionAdmin.GetDisplayDriverName(const DriverName: string): string;
var
Factory: TDBXConnectionFactory;
DisplayName: string;
LProperties: TDBXProperties;
begin
Factory := TDBXConnectionFactory.GetConnectionFactory;
TDBXConnectionFactory.Lock;
try
LProperties := Factory.GetDriverProperties(DriverName);
if LProperties <> nil then
DisplayName := LProperties.Values[TDBXPropertyNames.DisplayDriverName]
else
DisplayName := '';
finally
TDBXConnectionFactory.Unlock;
end;
if DisplayName = '' then
Result := DriverName
else
Result := DisplayName;
end;
function TConnectionAdmin.GetDisplayDriverNames(List: TStrings): Integer;
var
DriverName: string;
begin
for DriverName in FRegisteredDriverNames do
List.Add(GetDisplayDriverName(DriverName));
Result := List.Count;
end;
function TConnectionAdmin.GetDriverNames(List: TStrings): Integer;
var
DriverName: string;
begin
for DriverName in FRegisteredDriverNames do
List.Add(DriverName);
Result := List.Count;
end;
function TConnectionAdmin.GetDelegateDriverNames(List: TStrings): Integer;
var
I: Integer;
Factory: TDBXConnectionFactory;
begin
Factory := TDBXConnectionFactory.GetConnectionFactory;
TDBXConnectionFactory.Lock;
try
Factory.GetDriverNames(List);
for I := List.Count - 1 downto 0 do
begin
if not Factory.GetDriverProperties(List[I]).GetBoolean(TDBXPropertyNames.DelegateDriver) then
List.Delete(I);
end;
Result := List.Count;
finally
TDBXConnectionFactory.Unlock;
end;
end;
function TConnectionAdmin.GetDriverParams(const DriverName: string; Params: TStrings): Integer;
var
Factory: TDBXConnectionFactory;
begin
Factory := TDBXConnectionFactory.GetConnectionFactory;
Params.Clear;
TDBXConnectionFactory.Lock;
try
Params.AddStrings(Factory.GetDriverProperties(DriverName).Properties);
finally
TDBXConnectionFactory.Unlock;
end;
Result := Params.Count;
end;
procedure TConnectionAdmin.InitializeDriverNames;
var
I: Integer;
Factory: TDBXConnectionFactory;
begin
Factory := TDBXConnectionFactory.GetConnectionFactory;
TDBXConnectionFactory.Lock;
try
Factory.GetDriverNames(FRegisteredDriverNames);
for I := FRegisteredDriverNames.Count - 1 downto 0 do
begin
if Factory.GetDriverProperties(FRegisteredDriverNames[I]).GetBoolean(TDBXPropertyNames.DelegateDriver) then
FRegisteredDriverNames.Delete(I);
end;
finally
TDBXConnectionFactory.Unlock;
end;
end;
procedure TConnectionAdmin.GetDriverLibNames(const DriverName: string;
var LibraryName, VendorLibrary: string);
var
Factory: TDBXConnectionFactory;
DriverProps: TDBXProperties;
begin
Factory := TDBXConnectionFactory.GetConnectionFactory;
TDBXConnectionFactory.Lock;
try
DriverProps := Factory.GetDriverProperties(DriverName);
LibraryName := DriverProps[TDBXPropertyNames.LibraryName];
VendorLibrary := DriverProps[TDBXPropertyNames.VendorLib];
finally
TDBXConnectionFactory.Unlock;
end;
end;
procedure TConnectionAdmin.ModifyConnection(const ConnectionName: string;
Params: TStrings);
begin
CheckConfigFile;
WriteSectionValues(ConnectionConfig, ConnectionName, Params);
end;
procedure TConnectionAdmin.RegisterDriver(const DriverName: string);
begin
if FRegisteredDriverNames.IndexOf(DriverName) = -1 then
FRegisteredDriverNames.Add(DriverName);
end;
procedure TConnectionAdmin.UnregisterDriver(const DriverName: string);
var
LIndex: Integer;
begin
LIndex := FRegisteredDriverNames.IndexOf(DriverName);
if LIndex <> -1 then
FRegisteredDriverNames.Delete(LIndex);
end;
procedure TConnectionAdmin.RenameConnection(const OldName, NewName: string);
var
Params: TStrings;
begin
CheckConfigFile;
Params := TStringList.Create;
try
GetConnectionParams(OldName, Params);
ConnectionConfig.EraseSection(OldName);
WriteSectionValues(ConnectionConfig, NewName, Params);
finally
Params.Free
end;
end;
initialization
ConnAdmin := IConnectionAdmin(TConnectionAdmin.Create);
finalization
ConnAdmin := nil;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit REST.Backend.ParseServices;
interface
uses
System.Classes,
System.SysUtils,
System.JSON,
REST.Json.Types,
REST.Backend.Providers,
REST.Backend.PushTypes,
REST.Backend.ServiceTypes,
REST.Backend.MetaTypes,
REST.Backend.ParseProvider,
REST.Backend.ParseApi;
type
// Files service
TParseFilesAPI = class(TParseServiceAPIAuth, IBackendFilesApi)
protected
{ IBackendFilesAPI }
function GetMetaFactory: IBackendMetaFactory;
procedure UploadFile(const AFileName: string; const AContentType: string;
out AFile: TBackendEntityValue); overload;
procedure UploadFile(const AFileName: string; const AStream: TStream; const AContentType: string;
out AFile: TBackendEntityValue); overload;
function DeleteFile(const AFile: TBackendEntityValue): Boolean;
end;
TParseFilesService = class(TParseBackendService<TParseFilesAPI>, IBackendService, IBackendFilesService)
protected
{ IBackendFilesService }
function CreateFilesApi: IBackendFilesApi;
function GetFilesApi: IBackendFilesApi;
end;
// Push service
TParsePushAPI = class(TParseServiceAPIAuth, IBackendPushApi, IBackendPushApi2, IBackendPushApi3)
protected
{ IBackendPushAPI }
procedure PushBroadcast(const AData: TPushData); overload;
{ IBackendPushApi2 }
procedure PushBroadcast(const AData: TJSONObject); overload;
/// <summary>Create a json object that represents push data. The JSON format is provider-specific</summary>
function PushDataAsJSON(const AData: TPushData): TJSONObject;
{ IBackendPushApi3 }
/// <summary>Send a push notification to a target. The format of the target JSON is provider-specific</summary>
procedure PushToTarget(const AData: TPushData; const ATarget: TJSONObject); overload;
procedure PushToTarget(const AData: TJSONObject; const ATarget: TJSONObject); overload;
end;
TParsePushService = class(TParseBackendService<TParsePushAPI>, IBackendService, IBackendPushService)
protected
{ IBackendPushService }
function CreatePushApi: IBackendPushApi;
function GetPushApi: IBackendPushApi;
end;
// Query service
TParseQueryAPI = class(TParseServiceAPIAuth, IBackendQueryApi)
protected
{ IBackendQueryAPI }
procedure GetServiceNames(out ANames: TArray<string>);
function GetMetaFactory: IBackendMetaFactory;
procedure Query(const AClass: TBackendMetaClass; const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure Query(const AClass: TBackendMetaClass; const AQuery: array of string;
const AJSONArray: TJSONArray; out AObjects: TArray<TBackendEntityValue>); overload;
end;
TParseQueryService = class(TParseBackendService<TParseQueryAPI>, IBackendService, IBackendQueryService)
protected
{ IBackendQueryService }
function CreateQueryApi: IBackendQueryApi;
function GetQueryApi: IBackendQueryApi;
end;
// Users service
TParseLoginAPI = class(TParseServiceAPIAuth, IBackendAuthApi)
protected
{ IBackendLoginAPI }
function GetMetaFactory: IBackendMetaFactory;
procedure SignupUser(const AUserName, APassword: string; const AUserData: TJSONObject;
out ACreatedObject: TBackendEntityValue);
procedure LoginUser(const AUserName, APassword: string; AProc: TFindObjectProc); overload;
procedure LoginUser(const AUserName, APassword: string; out AUser: TBackendEntityValue; const AJSON: TJSONArray); overload;
function FindCurrentUser(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean; overload;
function FindCurrentUser(const AObject: TBackendEntityValue; out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean; overload;
procedure UpdateUser(const AObject: TBackendEntityValue; const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
end;
TParseLoginService = class(TParseBackendService<TParseLoginAPI>, IBackendService, IBackendAuthService)
protected
{ IBackendAuthService }
function CreateAuthApi: IBackendAuthApi;
function GetAuthApi: IBackendAuthApi;
end;
TParseLoginAPIHelper = class helper for TParseLoginAPI
public
procedure LogoutUser;
end;
// Users service
TParseUsersAPI = class(TParseLoginApi, IBackendUsersApi)
protected
function DeleteUser(const AObject: TBackendEntityValue): Boolean; overload;
function FindUser(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean; overload;
function FindUser(const AObject: TBackendEntityValue; out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean; overload;
procedure UpdateUser(const AObject: TBackendEntityValue; const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
function QueryUserName(const AUserName: string; AProc: TFindObjectProc): Boolean; overload;
function QueryUserName(const AUserName: string; out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean; overload;
procedure QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray; out AMetaArray: TArray<TBackendEntityValue>); overload;
end;
TParseUsersService = class(TParseBackendService<TParseUsersAPI>, IBackendService, IBackendUsersService)
protected
{ IBackendUsersService }
function CreateUsersApi: IBackendUsersApi;
function GetUsersApi: IBackendUsersApi;
end;
// Storage service
TParseStorageAPI = class(TParseServiceAPIAuth, IBackendStorageAPI, IBackendStorageAPI2)
protected
{ IBackendStorageAPI }
function GetMetaFactory: IBackendMetaFactory;
procedure CreateObject(const AClass: TBackendMetaClass; const AACL, AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue); overload;
function DeleteObject(const AObject: TBackendEntityValue): Boolean;
function FindObject(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean;
procedure UpdateObject(const AObject: TBackendEntityValue; const AJSONObject: TJSONObject;
out AUpdatedObject: TBackendEntityValue);
procedure QueryObjects(const AClass: TBackendMetaClass; const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryObjects(const AClass: TBackendMetaClass; const AQuery: array of string;
const AJSONArray: TJSONArray; out AObjects: TArray<TBackendEntityValue>); overload;
/// <summary>Returns Json date format for Parse</summary>
function GetJsonDateFormat : TJsonDateFormat;
end;
TParseStorageService = class(TParseBackendService<TParseStorageAPI>, IBackendService, IBackendStorageService)
protected
{ IBackendStorageService }
function CreateStorageApi: IBackendStorageApi;
function GetStorageApi: IBackendStorageApi;
end;
implementation
uses
System.TypInfo, System.Generics.Collections, REST.Backend.ServiceFactory,
REST.Backend.ParseMetaTypes, REST.Backend.Consts, REST.Backend.Exception;
type
TParseProviderServiceFactory<T: IBackendService> = class(TProviderServiceFactory<T>)
var
FMethod: TFunc<IBackendProvider, IBackendService>;
protected
function CreateService(const AProvider: IBackendProvider; const IID: TGUID): IBackendService; override;
public
constructor Create(const AMethod: TFunc<IBackendProvider, IBackendService>);
end;
{ TParseProviderServiceFactory<T> }
constructor TParseProviderServiceFactory<T>.Create(const AMethod: TFunc<IBackendProvider, IBackendService>);
begin
inherited Create(TCustomParseProvider.ProviderID, 'REST.Backend.ParseServices');
FMethod := AMethod;
end;
function TParseProviderServiceFactory<T>.CreateService(
const AProvider: IBackendProvider; const IID: TGUID): IBackendService;
begin
Result := FMethod(AProvider);
end;
{ TParseFilesService }
function TParseFilesService.CreateFilesApi: IBackendFilesApi;
begin
Result := CreateBackendApi;
end;
function TParseFilesService.GetFilesApi: IBackendFilesApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TParsePushAPI }
procedure TParsePushAPI.PushBroadcast(
const AData: TPushData);
begin
PushToTarget(AData, nil);
end;
procedure TParsePushAPI.PushBroadcast(
const AData: TJSONObject);
begin
PushToTarget(AData, nil);
end;
function TParsePushAPI.PushDataAsJSON(
const AData: TPushData): TJSONObject;
var
LJSONData: TJSONObject;
begin
Result := TJSONObject.Create;
try
LJSONData := TJSONObject.Create;
Result.AddPair('data', LJSONData);
if AData <> nil then
begin
// Flat object
AData.Extras.Save(LJSONData, '');
AData.GCM.Save(LJSONData, '');
AData.APS.Save(LJSONData, '');
if (AData.APS.Alert = '') and (AData.Message <> '') then
AData.SaveMessage(LJSONData, TPushData.TAPS.TNames.Alert);
if (AData.GCM.Message = '') and (AData.GCM.Msg = '') and (AData.Message <> '') then
AData.SaveMessage(LJSONData, TPushData.TGCM.TNames.Message);
end;
except
Result.Free;
raise;
end;
end;
procedure TParsePushAPI.PushToTarget(
const AData: TPushData; const ATarget: TJSONObject);
var
LJSON: TJSONObject;
begin
LJSON := PushDataAsJSON(AData);
try
PushToTarget(LJSON, ATarget);
finally
LJSON.Free;
end;
end;
procedure TParsePushAPI.PushToTarget(
const AData: TJSONObject; const ATarget: TJSONObject);
var
LJSON: TJSONObject;
LPair: TJSONPair;
begin
if AData <> nil then
LJSON := AData.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
if ATarget <> nil then
for LPair in ATarget do
LJSON.AddPair(LPair.Clone as TJSONPair);
ParseAPI.PushBody(LJSON)
finally
LJSON.Free;
end;
end;
{ TParsePushService }
function TParsePushService.CreatePushApi: IBackendPushApi;
begin
Result := CreateBackendApi;
end;
function TParsePushService.GetPushApi: IBackendPushApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TParseQueryAPI }
procedure TParseQueryAPI.GetServiceNames(out ANames: TArray<string>);
begin
ANames := TArray<string>.Create(
TBackendQueryServiceNames.Storage,
TBackendQueryServiceNames.Users,
TBackendQueryServiceNames.Installations);
end;
function TParseQueryAPI.GetMetaFactory: IBackendMetaFactory;
begin
Result := TMetaFactory.Create;
end;
procedure TParseQueryAPI.Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray);
begin
if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Storage) then
ParseAPI.QueryClass(
AClass.BackendClassName, AQuery, AJSONArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Users) then
ParseAPI.QueryUsers(
AQuery, AJSONArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Installations) then
ParseAPI.QueryInstallation(
AQuery, AJSONArray)
else
raise EBackendServiceError.CreateFmt(sUnsupportedBackendQueryType, [AClass.BackendDataType]);
end;
procedure TParseQueryAPI.Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray; out AObjects: TArray<TBackendEntityValue>);
var
LObjectIDArray: TArray<TParseAPI.TObjectID>;
LUsersArray: TArray<TParseAPI.TUser>;
LObjectID: TParseAPI.TObjectID;
LList: TList<TBackendEntityValue>;
LUser: TParseAPI.TUser;
begin
if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Storage) then
ParseAPI.QueryClass(
AClass.BackendClassName, AQuery, AJSONArray, LObjectIDArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Users) then
ParseAPI.QueryUsers(
AQuery, AJSONArray, LUsersArray)
else if SameText(AClass.BackendDataType, TBackendQueryServiceNames.Installations) then
ParseAPI.QueryInstallation(
AQuery, AJSONArray, LObjectIDArray)
else
raise EBackendServiceError.CreateFmt(sUnsupportedBackendQueryType, [AClass.BackendDataType]);
if Length(LUsersArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LUser in LUsersArray do
LList.Add(TParseMetaFactory.CreateMetaFoundUser(LUser));
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
if Length(LObjectIDArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LObjectID in LObjectIDArray do
LList.Add(TParseMetaFactory.CreateMetaClassObject(LObjectID));
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
end;
{ TParseQueryService }
function TParseQueryService.CreateQueryApi: IBackendQueryApi;
begin
Result := CreateBackendApi;
end;
function TParseQueryService.GetQueryApi: IBackendQueryApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TParseUsersService }
function TParseUsersService.CreateUsersApi: IBackendUsersApi;
begin
Result := CreateBackendApi;
end;
function TParseUsersService.GetUsersApi: IBackendUsersApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TParseLoginService }
function TParseLoginService.CreateAuthApi: IBackendAuthApi;
begin
Result := CreateBackendApi;
end;
function TParseLoginService.GetAuthApi: IBackendAuthApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
{ TParseStorageAPI }
procedure TParseStorageAPI.CreateObject(const AClass: TBackendMetaClass;
const AACL, AJSON: TJSONObject; out ACreatedObject: TBackendEntityValue);
var
LNewObject: TParseAPI.TObjectID;
begin
ParseAPI.CreateClass(AClass.BackendClassName, AACL, AJSON, LNewObject);
ACreatedObject := TParseMetaFactory.CreateMetaCreatedObject(LNewObject)
end;
function TParseStorageAPI.DeleteObject(
const AObject: TBackendEntityValue): Boolean;
begin
if AObject.Data is TMetaObject then
Result := ParseAPI.DeleteClass((AObject.Data as TMetaObject).ObjectID)
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TParseStorageAPI.FindObject(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
var
LMetaObject: TMetaObject;
begin
if AObject.Data is TMetaObject then
begin
LMetaObject := TMetaObject(AObject.Data);
Result := ParseAPI.FindClass(LMetaObject.ObjectID,
procedure(const AID: TParseAPI.TObjectID; const AObj: TJSONObject)
begin
AProc(TParseMetaFactory.CreateMetaFoundObject(AID), AObj);
end);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TParseStorageAPI.GetMetaFactory: IBackendMetaFactory;
begin
Result := TMetaFactory.Create;
end;
procedure TParseStorageAPI.QueryObjects(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray);
begin
ParseAPI.QueryClass(AClass.BackendClassName, AQuery, AJSONArray);
end;
procedure TParseStorageAPI.QueryObjects(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray;
out AObjects: TArray<TBackendEntityValue>);
var
LObjectIDArray: TArray<TParseAPI.TObjectID>;
LObjectID: TParseAPI.TObjectID;
LList: TList<TBackendEntityValue>;
begin
ParseAPI.QueryClass(AClass.BackendClassName, AQuery, AJSONArray, LObjectIDArray);
if Length(LObjectIDArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LObjectID in LObjectIDArray do
LList.Add(TParseMetaFactory.CreateMetaClassObject(LObjectID));
AObjects := LList.ToArray;
finally
LList.Free;
end;
end;
end;
procedure TParseStorageAPI.UpdateObject(const AObject: TBackendEntityValue;
const AJSONObject: TJSONObject; out AUpdatedObject: TBackendEntityValue);
var
LObjectID: TParseAPI.TUpdatedAt;
LMetaObject: TMetaObject;
begin
if AObject.Data is TMetaObject then
begin
LMetaObject := TMetaObject(AObject.Data);
ParseAPI.UpdateClass(LMetaObject.ObjectID, AJSONObject, LObjectID);
AUpdatedObject := TParseMetaFactory.CreateMetaUpdatedObject(LObjectID);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TParseStorageAPI.GetJsonDateFormat : TJsonDateFormat;
begin
Result := jdfParse;
end;
{ TParseStorageService }
function TParseStorageService.CreateStorageApi: IBackendStorageApi;
begin
Result := CreateBackendApi;
end;
function TParseStorageService.GetStorageApi: IBackendStorageApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
var
FFactories: TList<TProviderServiceFactory>;
procedure RegisterServices;
var
LFactory: TProviderServiceFactory;
begin
FFactories := TObjectList<TProviderServiceFactory>.Create;
// Files
LFactory := TParseProviderServiceFactory<IBackendFilesService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TParseFilesService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Users
LFactory := TParseProviderServiceFactory<IBackendUsersService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TParseUsersService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Login
LFactory := TParseProviderServiceFactory<IBackendAuthService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TParseLoginService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Storage
LFactory := TParseProviderServiceFactory<IBackendStorageService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TParseStorageService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Query
LFactory := TParseProviderServiceFactory<IBackendQueryService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TParseQueryService.Create(AProvider);
end);
FFactories.Add(LFactory);
// Push
LFactory := TParseProviderServiceFactory<IBackendPushService>.Create(
function(AProvider: IBackendProvider): IBackendService
begin
Result := TParsePushService.Create(AProvider);
end);
FFactories.Add(LFactory);
for LFactory in FFactories do
LFactory.Register;
end;
procedure UnregisterServices;
var
LFactory: TProviderServiceFactory;
begin
for LFactory in FFactories do
LFactory.Unregister;
FreeAndNil(FFactories);
end;
{ TParseLoginAPI }
function TParseLoginAPI.GetMetaFactory: IBackendMetaFactory;
begin
Result := TMetaFactory.Create;
end;
function TParseLoginAPI.FindCurrentUser(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
var
LMetaLogin: TMetaLogin;
begin
if AObject.Data is TMetaLogin then
begin
LMetaLogin := TMetaLogin(AObject.Data);
ParseAPI.Login(LMetaLogin.Login);
try
Result := ParseAPI.RetrieveCurrentUser(
procedure(const AUser: TParseAPI.TUser; const AObj: TJSONObject)
begin
AProc(TParseMetaFactory.CreateMetaFoundUser(AUser), AObj);
end);
finally
ParseAPI.Logout;
end;
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TParseLoginAPI.FindCurrentUser(const AObject: TBackendEntityValue;
out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean;
var
LMetaLogin: TMetaLogin;
LUser: TParseAPI.TUser;
begin
if AObject.Data is TMetaLogin then
begin
LMetaLogin := TMetaLogin(AObject.Data);
ParseAPI.Login(LMetaLogin.Login);
try
Result := ParseAPI.RetrieveCurrentUser(LUser, AJSON);
AUser := TParseMetaFactory.CreateMetaFoundUser(LUser);
finally
ParseAPI.Logout;
end;
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
procedure TParseLoginAPI.LoginUser(const AUserName, APassword: string;
AProc: TFindObjectProc);
begin
ParseAPI.LoginUser(AUserName, APassword,
procedure(const ALogin: TParseAPI.TLogin; const AUserObject: TJSONObject)
begin
AProc(TParseMetaFactory.CreateMetaLoginUser(ALogin), AUserObject);
end);
end;
procedure TParseLoginAPI.LoginUser(const AUserName, APassword: string;
out AUser: TBackendEntityValue; const AJSON: TJSONArray);
var
LLogin: TParseAPI.TLogin;
begin
ParseAPI.LoginUser(AUserName, APassword, LLogin, AJSON);
AUser := TParseMetaFactory.CreateMetaLoginUser(LLogin);
end;
procedure TParseLoginAPIHelper.LogoutUser;
begin
// nothing
end;
procedure TParseLoginAPI.SignupUser(const AUserName, APassword: string;
const AUserData: TJSONObject; out ACreatedObject: TBackendEntityValue);
var
LLogin: TParseAPI.TLogin;
begin
ParseAPI.SignupUser(AUserName, APassword, AUserData, LLogin);
ACreatedObject := TParseMetaFactory.CreateMetaSignupUser(LLogin);
end;
procedure TParseLoginAPI.UpdateUser(const AObject: TBackendEntityValue;
const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
var
LUpdated: TParseAPI.TUpdatedAt;
begin
if AObject.Data is TMetaLogin then
begin
ParseAPI.UpdateUser(TMetaLogin(AObject.Data).Login, AUserData, LUpdated);
AUpdatedObject := TParseMetaFactory.CreateMetaUpdatedUser(LUpdated);
end
else if AObject.Data is TMetaUser then
begin
ParseAPI.UpdateUser(TMetaUser(AObject.Data).User.ObjectID, AUserData, LUpdated);
AUpdatedObject := TParseMetaFactory.CreateMetaUpdatedUser(LUpdated);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
{ TParseUsersAPI }
function TParseUsersAPI.DeleteUser(const AObject: TBackendEntityValue): Boolean;
begin
if AObject.Data is TMetaLogin then
Result := ParseAPI.DeleteUser((AObject.Data as TMetaLogin).Login)
else if AObject.Data is TMetaUser then
Result := ParseAPI.DeleteUser((AObject.Data as TMetaUser).User.ObjectID)
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TParseUsersAPI.FindUser(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
begin
if AObject.Data is TMetaLogin then
begin
Result := ParseAPI.RetrieveUser(TMetaLogin(AObject.Data).Login,
procedure(const AUser: TParseAPI.TUser; const AObj: TJSONObject)
begin
AProc(TParseMetaFactory.CreateMetaFoundUser(AUser), AObj);
end);
end
else if AObject.Data is TMetaUser then
begin
Result := ParseAPI.RetrieveUser(TMetaUser(AObject.Data).User.ObjectID,
procedure(const AUser: TParseAPI.TUser; const AObj: TJSONObject)
begin
AProc(TParseMetaFactory.CreateMetaFoundUser(AUser), AObj);
end);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TParseUsersAPI.FindUser(const AObject: TBackendEntityValue;
out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean;
var
LUser: TParseAPI.TUser;
begin
if AObject.Data is TMetaLogin then
Result := ParseAPI.RetrieveUser(TMetaLogin(AObject.Data).Login, LUser, AJSON)
else if AObject.Data is TMetaUser then
Result := ParseAPI.RetrieveUser(TMetaUser(AObject.Data).User.ObjectID, LUser, AJSON)
else
raise EArgumentException.Create(sParameterNotMetaType);
AUser := TParseMetaFactory.CreateMetaFoundUser(LUser);
end;
function TParseUsersAPI.QueryUserName(const AUserName: string;
AProc: TFindObjectProc): Boolean;
begin
Result := ParseAPI.QueryUserName(AUserName,
procedure(const AUser: TParseAPI.TUser; const AObj: TJSONObject)
begin
AProc(TParseMetaFactory.CreateMetaFoundUser(AUser), AObj);
end);
end;
function TParseUsersAPI.QueryUserName(const AUserName: string;
out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean;
var
LUser: TParseAPI.TUser;
begin
Result := ParseAPI.QueryUserName(AUserName, LUser, AJSON);
AUser := TParseMetaFactory.CreateMetaFoundUser(LUser);
end;
procedure TParseUsersAPI.QueryUsers(
const AQuery: array of string; const AJSONArray: TJSONArray);
begin
ParseAPI.QueryUsers(
AQuery, AJSONArray);
end;
procedure TParseUsersAPI.QueryUsers(
const AQuery: array of string; const AJSONArray: TJSONArray; out AMetaArray: TArray<TBackendEntityValue>);
var
LUserArray: TArray<TParseAPI.TUser>;
LUser: TParseAPI.TUser;
LList: TList<TBackendEntityValue>;
begin
ParseAPI.QueryUsers(
AQuery, AJSONArray, LUserArray);
if Length(LUserArray) > 0 then
begin
LList := TList<TBackendEntityValue>.Create;
try
for LUser in LUserArray do
LList.Add(TParseMetaFactory.CreateMetaFoundUser(LUser));
AMetaArray := LList.ToArray;
finally
LList.Free;
end;
end;
end;
procedure TParseUsersAPI.UpdateUser(const AObject: TBackendEntityValue;
const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
var
LUpdated: TParseAPI.TUpdatedAt;
begin
if AObject.Data is TMetaLogin then
begin
ParseAPI.UpdateUser(TMetaLogin(AObject.Data).Login, AUserData, LUpdated);
AUpdatedObject := TParseMetaFactory.CreateMetaUpdatedUser(LUpdated);
end
else if AObject.Data is TMetaUser then
begin
ParseAPI.UpdateUser(TMetaUser(AObject.Data).User.ObjectID, AUserData, LUpdated);
AUpdatedObject := TParseMetaFactory.CreateMetaUpdatedUser(LUpdated);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
{ TParseFilesAPI }
procedure TParseFilesAPI.UploadFile(const AFileName, AContentType: string;
out AFile: TBackendEntityValue);
var
LFile: TParseAPI.TFile;
begin
// Upload public file
ParseAPI.UploadFile(AFileName, AContentType,LFile);
AFile := TParseMetaFactory.CreateMetaUploadedFile(LFile);
end;
function TParseFilesAPI.DeleteFile(const AFile: TBackendEntityValue): Boolean;
var
LMetaFile: TMetaFile;
begin
if AFile.Data is TMetaFile then
begin
LMetaFile := TMetaFile(AFile.Data);
Result := ParseAPI.DeleteFile(LMetaFile.FileValue);
end
else
raise EArgumentException.Create(sParameterNotMetaType);
end;
function TParseFilesAPI.GetMetaFactory: IBackendMetaFactory;
begin
Result := TMetaFactory.Create;
end;
procedure TParseFilesAPI.UploadFile(const AFileName: string;
const AStream: TStream; const AContentType: string;
out AFile: TBackendEntityValue);
var
LFile: TParseAPI.TFile;
begin
// Upload public file
ParseAPI.UploadFile(AFileName, AStream, AContentType, LFile);
AFile := TParseMetaFactory.CreateMetaUploadedFile(LFile);
end;
initialization
RegisterLogoutProc(TParseLoginAPI,
procedure (AServiceAPI: TObject)
begin
(AServiceAPI as TParseLoginAPI).LogoutUser;
end);
RegisterServices;
finalization
UnregisterServices;
end.
|
{$O+,F+}
unit CGABTESTS;
{Contains all of the benchmarking tests/procedures for the CGA compatibility tester}
interface
Procedure BenchReadSpeed;
Procedure BenchWriteSpeed;
Procedure BenchReadSpeedOpcodes;
Procedure BenchWriteSpeedOpcodes;
implementation
uses
strings,m6845ctl,totmsg,ztimer,support,totIO1,totfast,cgaccommon,TInterrupts;
Procedure ReportSpeed(s1:string;bs:word;s2,s3:string;ss:word);
begin
Screen.Write(s1+' '+inttostr(bs)+' '+s2+' ');
Screen.Writeln(inttostr(_PZTimerCount)+' æsecs.');
{if machine is WACKO fast then we need to handle things differently}
if _PZTimerCount=-1 then begin
PrintInvalidMsg;
repeat until keypressed;
PostTest;
exit;
end;
Screen.Writeln(s3+' '+inttostr(round((bs*(1000000/1024)) / _PZTimerCount))+' KB/s.');
Screen.Writeln('A stock 4.77 MHz 8088 IBM PC with original IBM CGA achieves '+inttostr(ss)+' KB/s.');
Screen.Writeln('Press any key to continue.');
repeat until keypressed;
end;
Procedure BenchReadSpeed;
const
BlockSize=$2000;
begin
with InfoPrompt do begin
init(6,strpas(menuLookup[mBMR].title));
WinForm^.vWinPtr^.SetColors(descBorder,descBody,descTitle,descIcons);
AddLine('');
AddLine('This benchmarks your video adapter RAM''s maximum read');
AddLine('speed and displays the result. Use this to compare how');
AddLine('fast (or slow) your adapter is compared to real CGA.');
AddLine('');
SetOption(1,cstring,67,Finished);
SetOption(2,astring,65,Escaped);
Result:=Show;
Done;
end;
if Result=Escaped then exit;
PrepTest;
asm
push ds
mov cx,BlockSize
shr cx,1
mov ax,$b800
mov ds,ax
xor si,si
cld
call _PZTimerOn
rep lodsw
call _PZTimerOff
pop ds
end;
ReportSpeed('Reading',BlockSize,'bytes of your video adapter RAM took',
'Your video RAM''s read speed is',291);
PostTest;
end;
Procedure BenchWriteSpeed;
const
BlockSize=$2000;
begin
with InfoPrompt do begin
init(6,strpas(menuLookup[mBMW].title));
WinForm^.vWinPtr^.SetColors(descBorder,descBody,descTitle,descIcons);
AddLine('');
AddLine('This benchmarks your video adapter RAM''s maximum write');
AddLine('speed and displays the result. Use this to compare how');
AddLine('fast (or slow) your adapter is to real CGA.');
AddLine('');
SetOption(1,cstring,67,Finished);
SetOption(2,astring,65,Escaped);
Result:=Show;
Done;
end;
if Result=Escaped then exit;
PrepTest;
asm
mov ax,$b800
mov es,ax
xor di,di
mov cx,BlockSize
shr cx,1
mov ax,$0F00 {black back, white fore, 00 char}
cld
call _PZTimerOn
rep stosw
call _PZTimerOff
end;
ReportSpeed('Writing',BlockSize,'bytes of your video adapter RAM took',
'Your video RAM''s write speed is',340);
PostTest;
end;
Procedure BenchReadSpeedOpcodes;
const
BlockSize=$1000;
begin
with InfoPrompt do begin
init(6,strpas(menuLookup[mOARB].title));
WinForm^.vWinPtr^.SetColors(descBorder,descBody,descTitle,descIcons);
AddLine('');
AddLine('This benchmarks your video adapter RAM''s read speed');
AddLine('with CPU no-op instructions interleaved with memory');
AddLine('accesses. This can be used to test if CPU caching');
AddLine('and/or bus speed affects the speed of video adapter RAM.');
AddLine('');
SetOption(1,cstring,67,Finished);
SetOption(2,astring,65,Escaped);
Result:=Show;
Done;
end;
if Result=Escaped then exit;
PrepTest;
asm
push ds
mov ax,$b800
mov ds,ax
xor si,si
cld
mov cx,BlockSize
shr cx,1
shr cx,1
shr cx,1
shr cx,1
call _PZTimerOn
@loopit: {unrolled a bit, so that the flush at JMP time doesn't totally cripple us}
lodsb;nop;lodsb;nop;lodsb;nop;lodsb;nop;
lodsb;nop;lodsb;nop;lodsb;nop;lodsb;nop;
lodsb;nop;lodsb;nop;lodsb;nop;lodsb;nop;
lodsb;nop;lodsb;nop;lodsb;nop;lodsb;nop;
loop @loopit
call _PZTimerOff
pop ds
end;
ReportSpeed('Reading',BlockSize,'bytes of video RAM mixed with NOPs took',
'This means our interleaved read speed was',199);
PostTest;
end;
Procedure BenchWriteSpeedOpcodes;
const
BlockSize=$1000;
begin
with InfoPrompt do begin
init(6,strpas(menuLookup[mOAWB].title));
WinForm^.vWinPtr^.SetColors(descBorder,descBody,descTitle,descIcons);
AddLine('');
AddLine('This benchmarks your video adapter RAM''s write speed');
AddLine('with CPU no-op instructions interleaved with memory');
AddLine('accesses. This can be used to test if CPU caching');
AddLine('and/or bus speed affects the speed of video adapter RAM.');
AddLine('');
SetOption(1,cstring,67,Finished);
SetOption(2,astring,65,Escaped);
Result:=Show;
Done;
end;
if Result=Escaped then exit;
PrepTest;
asm
mov ax,$b800
mov es,ax
xor di,di
cld
mov cx,BlockSize
shr cx,1
shr cx,1
shr cx,1
shr cx,1
xor al,al
call _PZTimerOn
@loopit: {unrolled a bit, so that the flush at JMP time doesn't totally cripple us}
stosb;nop;stosb;nop;stosb;nop;stosb;nop;
stosb;nop;stosb;nop;stosb;nop;stosb;nop;
stosb;nop;stosb;nop;stosb;nop;stosb;nop;
stosb;nop;stosb;nop;stosb;nop;stosb;nop;
loop @loopit
call _PZTimerOff
end;
Screen.Clear(TWhite,' '); {repaint the screen since we just trashed it}
ReportSpeed('Writing',BlockSize,'bytes of video RAM mixed with NOPs took',
'This means our interleaved write speed was',194);
PostTest;
end;
end. |
unit IdHeaderCoderIndy;
interface
{$i IdCompilerDefines.inc}
uses
IdGlobal, IdHeaderCoderBase;
type
TIdHeaderCoderIndy = class(TIdHeaderCoder)
public
class function Decode(const ACharSet: string; const AData: TIdBytes): String; override;
class function Encode(const ACharSet, AData: String): TIdBytes; override;
class function CanHandle(const ACharSet: String): Boolean; override;
end;
// RLebeau 4/17/10: this forces C++Builder to link to this unit so
// RegisterHeaderCoder can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdHeaderCoderIndy"'*)
implementation
{$IFNDEF DOTNET_OR_ICONV}
uses
IdCharsets
{$IFDEF MSWINDOWS}
, Windows
{$ENDIF}
;
{$ENDIF}
class function TIdHeaderCoderIndy.Decode(const ACharSet: string; const AData: TIdBytes): String;
var
LEncoding: TIdTextEncoding;
LBytes: TIdBytes;
{$IFNDEF DOTNET_OR_ICONV}
CP: Word;
{$ENDIF}
begin
Result := '';
LBytes := nil;
try
{$IFDEF DOTNET_OR_ICONV}
LEncoding := TIdTextEncoding.GetEncoding(ACharSet);
{$ELSE}
CP := CharsetToCodePage(ACharSet);
Assert(CP <> 0);
LEncoding := TIdTextEncoding.GetEncoding(CP);
{$ENDIF}
{$IFNDEF DOTNET}
try
{$ENDIF}
LBytes := AData;
if LEncoding <> TIdTextEncoding.Unicode then begin
LBytes := TIdTextEncoding.Convert(LEncoding, TIdTextEncoding.Unicode, LBytes);
end;
Result := TIdTextEncoding.Unicode.GetString(LBytes, 0, Length(LBytes));
{$IFNDEF DOTNET}
finally
LEncoding.Free;
end;
{$ENDIF}
except
end;
end;
class function TIdHeaderCoderIndy.Encode(const ACharSet, AData: String): TIdBytes;
var
LEncoding: TIdTextEncoding;
LBytes: TIdBytes;
{$IFNDEF DOTNET_OR_ICONV}
CP: Word;
{$ENDIF}
begin
Result := nil;
LBytes := nil;
try
{$IFDEF DOTNET_OR_ICONV}
LEncoding := TIdTextEncoding.GetEncoding(ACharSet);
{$ELSE}
CP := CharsetToCodePage(ACharSet);
Assert(CP <> 0);
LEncoding := TIdTextEncoding.GetEncoding(CP);
{$ENDIF}
{$IFNDEF DOTNET}
try
{$ENDIF}
LBytes := TIdTextEncoding.Unicode.GetBytes(AData);
if LEncoding <> TIdTextEncoding.Unicode then begin
LBytes := TIdTextEncoding.Convert(TIdTextEncoding.Unicode, LEncoding, LBytes);
end;
Result := LBytes;
{$IFNDEF DOTNET}
finally
LEncoding.Free;
end;
{$ENDIF}
except
end;
end;
class function TIdHeaderCoderIndy.CanHandle(const ACharSet: String): Boolean;
{$IFDEF DOTNET_OR_ICONV}
var
LEncoding: TIdTextEncoding;
{$ELSE}
{$IFDEF MSWINDOWS}
var
CP: Word;
LCPInfo: TCPInfo;
{$ENDIF}
{$ENDIF}
begin
Result := False;
{$IFDEF DOTNET_OR_ICONV}
try
LEncoding := TIdTextEncoding.GetEncoding(ACharSet);
Result := Assigned(LEncoding);
except
end;
{$ELSE}
{$IFDEF MSWINDOWS}
CP := CharsetToCodePage(ACharSet);
if CP <> 0 then begin
Result := GetCPInfo(CP, LCPInfo);
end;
{$ENDIF}
{$ENDIF}
end;
initialization
RegisterHeaderCoder(TIdHeaderCoderIndy);
finalization
UnregisterHeaderCoder(TIdHeaderCoderIndy);
end.
|
unit fPCELex;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, uCore,
fAutoSz, StdCtrls, ORFn, ORCtrls, ExtCtrls, Buttons, VA508AccessibilityManager,
ComCtrls, fBase508Form, CommCtrl, mTreeGrid, rCore, StrUtils;
type
TfrmPCELex = class(TfrmBase508Form)
txtSearch: TCaptionEdit;
cmdSearch: TButton;
pnlStatus: TPanel;
pnlDialog: TPanel;
pnlButtons: TPanel;
cmdOK: TButton;
cmdCancel: TButton;
cmdExtendedSearch: TBitBtn;
pnlSearch: TPanel;
pnlList: TPanel;
lblStatus: TVA508StaticText;
lblSelect: TVA508StaticText;
lblSearch: TLabel;
tgfLex: TTreeGridFrame;
procedure cmdSearchClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure txtSearchChange(Sender: TObject);
procedure cmdExtendedSearchClick(Sender: TObject);
function isNumeric(inStr: String): Boolean;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure tgfLextvChange(Sender: TObject; Node: TTreeNode);
procedure tgfLextvClick(Sender: TObject);
procedure tgfLextvDblClick(Sender: TObject);
procedure tgfLextvEnter(Sender: TObject);
procedure tgfLextvExit(Sender: TObject);
procedure tgfLextvHint(Sender: TObject; const Node: TTreeNode;
var Hint: string);
procedure tgfLextvExpanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
private
FLexApp: Integer;
FSuppressCodes: Boolean;
FCode: string;
FDate: TFMDateTime;
FICDVersion: String;
FI10Active: Boolean;
FExtend: Boolean;
FMessage: String;
FSingleCodeSys: Boolean;
FCodeSys: String;
function ParseNarrCode(ANarrCode: String): String;
procedure SetApp(LexApp: Integer);
procedure SetDate(ADate: TFMDateTime);
procedure SetICDVersion(ADate: TFMDateTime);
procedure enableExtend;
procedure disableExtend;
procedure updateStatus(status: String);
procedure SetColumnTreeModel(ResultSet: TStrings);
procedure processSearch;
procedure setClientWidth;
procedure CenterForm(w: Integer);
end;
procedure LexiconLookup(var Code: string; ALexApp: Integer; ADate: TFMDateTime = 0; AExtend: Boolean = False; AInputString: String = ''; AMessage: String = ''; ADefaultToInput: Boolean = False);
implementation
{$R *.DFM}
uses rPCE, uProbs, rProbs, UBAGlobals, fEncounterFrame, VAUtils;
var
TriedExtend: Boolean = false;
procedure LexiconLookup(var Code: string; ALexApp: Integer; ADate: TFMDateTime = 0; AExtend: Boolean = False; AInputString: String = ''; AMessage: String = ''; ADefaultToInput: Boolean = False);
var
frmPCELex: TfrmPCELex;
begin
frmPCELex := TfrmPCELex.Create(Application);
try
ResizeFormToFont(TForm(frmPCELex));
if (ADate = 0) and Assigned(uEncPCEData) then
begin
if uEncPCEData.VisitCategory = 'E' then ADate := FMNow
else ADate := uEncPCEData.VisitDateTime;
end;
if ADefaultToInput and (AInputString <> '') then
frmPCELex.txtSearch.Text := Piece(frmPCELex.ParseNarrCode(AInputString), U, 2);
frmPCELex.SetApp(ALexApp);
frmPCELex.SetDate(ADate);
frmPCELex.SetICDVersion(ADate);
frmPCELex.FMessage := AMessage;
frmPCELex.FExtend := AExtend;
if (ALexApp = LX_ICD) then
frmPCELex.FExtend := True;
frmPCELex.ShowModal;
Code := frmPCELex.FCode;
if (AInputString <> '') and (Pos('(SCT', AInputString) > 0) and (ALexApp <> LX_SCT) then
SetPiece(Code, U, 2, AInputString);
finally
frmPCELex.Free;
end;
end;
procedure TfrmPCELex.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Release;
end;
procedure TfrmPCELex.FormCreate(Sender: TObject);
var
UserProps: TStringList;
begin
inherited;
FCode := '';
FCodeSys := '';
FI10Active := False;
FSingleCodeSys := True;
FExtend := False;
UserProps := TStringList.Create;
InitUser(User.DUZ, UserProps);
PLUser := TPLUserParams.create(UserProps);
FSuppressCodes := PLUser.usSuppressCodes;
ResizeAnchoredFormToFont(self);
tgfLex.DefTreeViewWndProc := tgfLex.tv.WindowProc;
tgfLex.tv.WindowProc := tgfLex.TreeViewWndProc;
end;
procedure TfrmPCELex.FormShow(Sender: TObject);
var
lt: String;
dh, lh: Integer;
begin
inherited;
if FSuppressCodes then
begin
tgfLex.ShowCode := False;
tgfLex.ShowTargetCode := False;
end
else
begin
tgfLex.ShowCode := True;
tgfLex.ShowTargetCode := not FI10Active;
end;
tgfLex.ShowDescription := True;
tgfLex.HorizPanelSpace := 8;
tgfLex.VertPanelSpace := 4;
if FMessage <> '' then
begin
lt := lblSearch.Caption;
lh := lblSearch.Height;
lblSearch.AutoSize := True;
lblSearch.Caption := FMessage + CRLF + CRLF + lt;
lblSearch.AutoSize := False;
dh := (lblSearch.Height - lh);
pnlSearch.Height := pnlSearch.Height + dh;
Height := Height + dh;
end;
CenterForm(tgfLex.ClientWidth);
if FExtend and (txtSearch.Text <> '') then
begin
if FExtend then
cmdExtendedSearch.Click
else
cmdSearch.Click;
end;
end;
procedure TfrmPCELex.SetApp(LexApp: Integer);
begin
FLexApp := LexApp;
case LexApp of
LX_ICD: begin
Caption := 'Lookup Diagnosis';
lblSearch.Caption := 'Search for Diagnosis:';
end;
LX_CPT: begin
Caption := 'Lookup Procedure';
lblSearch.Caption := 'Search for Procedure:';
end;
end;
end;
procedure TfrmPCELex.SetDate(ADate: TFMDateTime);
begin
FDate := ADate;
end;
procedure TfrmPCELex.SetICDVersion(ADate: TFMDateTime);
begin
if ADate = 0 then
begin
FICDVersion := Encounter.GetICDVersion;
end
else
begin
if ICD10ImplDate > ADate then
FICDVersion := 'ICD^ICD-9-CM'
else
FICDVersion := '10D^ICD-10-CM';
end;
if (Piece(FICDVersion, '^', 1) = '10D') then
FI10Active := True;
cmdExtendedSearch.Hint := 'Search ' + Piece(FICDVersion, '^', 2) + ' Diagnoses...';
tgfLex.pnlTargetCodeSys.Caption := Piece(FICDVersion, '^', 2) + ': ';
end;
procedure TfrmPCELex.enableExtend;
begin
cmdExtendedSearch.Visible := true;
cmdExtendedSearch.Enabled := true;
end;
procedure TfrmPCELex.disableExtend;
begin
cmdExtendedSearch.Enabled := false;
cmdExtendedSearch.Visible := false;
if not FI10Active then
FExtend := False;
end;
procedure TfrmPCELex.txtSearchChange(Sender: TObject);
begin
inherited;
cmdSearch.Default := True;
cmdOK.Default := False;
cmdCancel.Default := False;
disableExtend;
if tgfLex.tv.Items.Count > 0 then
begin
tgfLex.tv.Selected := nil;
tgfLex.tv.Items.Clear;
CenterForm(Constraints.MinWidth);
end;
end;
procedure TfrmPCELex.cmdSearchClick(Sender: TObject);
begin
TriedExtend := false;
FCodeSys := '';
FSingleCodeSys := True;
if not FI10Active and (FLexApp = LX_ICD) then
FExtend := False;
if not tgfLex.pnlTarget.Visible then tgfLex.pnlTarget.Visible := True;
processSearch;
end;
procedure TfrmPCELex.setClientWidth;
var
i, maxw, tl, maxtl: integer;
ctn: TLexTreeNode;
begin
maxtl := 0;
for i := 0 to pred(tgfLex.tv.Items.Count) do
begin
ctn := tgfLex.tv.Items[i] as TLexTreeNode;
tl := TextWidthByFont(Font.Handle, ctn.Text);
if (tl > maxtl) then
maxtl := tl;
end;
maxw := maxtl + 30;
if maxw < Constraints.MinWidth then
maxw := Constraints.MinWidth;
self.Width := maxw;
//resize tv to maximum pixel width of its elements
if (maxw > 0) and (self.ClientWidth <> maxw) then
begin
CenterForm(maxw);
end;
end;
procedure TfrmPCELex.CenterForm(w: Integer);
var
wdiff, mainw: Integer;
begin
mainw := Application.MainForm.Width;
if w > mainw then
begin
w := mainw;
end;
self.ClientWidth := w + (tgfLex.Width - tgfLex.ClientWidth) + (pnlList.Padding.Left + pnlList.Padding.Right);
wdiff := ((mainw - self.Width) div 2);
self.Left := Application.MainForm.Left + wdiff;
invalidate;
end;
procedure TfrmPCELex.SetColumnTreeModel(ResultSet: TStrings);
var
i: Integer;
Node, StubNode: TLexTreeNode;
RecStr: String;
begin
tgfLex.tv.Items.Clear;
for i := 0 to ResultSet.Count - 1 do
begin
//RecStr = VUID^Description^CodeSys^Code^TargetCodeSys^TargetCode^DesignationID^Parent
RecStr := ResultSet[i];
if Piece(RecStr, '^', 8) = '' then
Node := (tgfLex.tv.Items.Add(nil, Piece(RecStr, '^', 2))) as TLexTreeNode
else
Node := (tgfLex.tv.Items.AddChild(tgfLex.tv.Items[(StrToInt(Piece(RecStr, '^', 8))-1)], Piece(RecStr, '^', 2))) as TLexTreeNode;
with Node do
begin
VUID := Piece(RecStr, '^', 1);
Text := Piece(RecStr, '^', 2);
CodeDescription := Text;
CodeSys := Piece(RecStr, '^', 3);
if ((FCodeSys <> '') and (CodeSys <> FCodeSys)) then
FSingleCodeSys := False;
FCodeSys := CodeSys;
Code := Piece(RecStr, '^', 4);
if Piece(RecStr, '^', 8) <> '' then
ParentIndex := IntToStr(StrToInt(Piece(RecStr, '^', 8)) - 1);
//TODO: Need to accommodate Designation Code in ColumnTreeNode...
if CodeSys = 'SNOMED CT' then
begin
CodeIEN := Code;
DesignationID := Piece(RecStr, '^', 7);
end
else
CodeIEN := Piece(RecStr, '^', 9);
TargetCode := Piece(RecStr, '^', 6);
end;
if (Node.VUID = '+') then
begin
StubNode := (tgfLex.tv.Items.AddChild(Node, 'Searching...')) as TLexTreeNode;
with StubNode do
begin
VUID := '';
Text := 'Searching...';
CodeDescription := Text;
CodeSys := 'ICD-10-CM';
if ((FCodeSys <> '') and (CodeSys <> FCodeSys)) then
FSingleCodeSys := False;
FCodeSys := CodeSys;
Code := '';
CodeIEN := '';
ParentIndex := IntToStr(Node.Index);
end;
end;
end;
//sort treenodes
tgfLex.tv.AlphaSort(True);
end;
procedure TfrmPCELex.processSearch;
const
TX_SRCH_REFINE1 = 'Your search ';
TX_SRCH_REFINE2 = ' matched ';
TX_SRCH_REFINE3 = ' records, too many to display.' + CRLF + CRLF + 'Suggestions:' + CRLF +
#32#32#32#32#42 + ' Refine your search by adding more words' + CRLF + #32#32#32#32#42 + ' Try different keywords';
MaxRec = 5000;
var
LexResults: TStringList;
found, subset, SearchStr: String;
FreqOfText: integer;
Match: TLexTreeNode;
begin
if Length(txtSearch.Text) = 0 then
begin
InfoBox('Enter a term to search for, then click "SEARCH"', 'Information', MB_OK or MB_ICONINFORMATION);
exit; {don't bother to drop if no text entered}
end;
if (FLexApp = LX_ICD) or (FLexApp = LX_SCT) then
begin
if FExtend and (FLexApp = LX_ICD) then
subset := Piece(FICDVersion, '^', 2) + ' Diagnoses'
else
subset := 'SNOMED CT Concepts';
end
else if FLexApp = LX_CPT then
subset := 'Current Procedural Terminology (CPT)'
else
subset := 'Clinical Lexicon';
LexResults := TStringList.Create;
try
Screen.Cursor := crHourGlass;
updateStatus('Searching ' + subset + '...');
SearchStr := Uppercase(txtSearch.Text);
FreqOfText := GetFreqOfText(SearchStr);
if FreqOfText > MaxRec then
begin
InfoBox(TX_SRCH_REFINE1 + #39 + SearchStr + #39 + TX_SRCH_REFINE2 + IntToStr(FreqOfText) + TX_SRCH_REFINE3,'Refine Search', MB_OK or MB_ICONINFORMATION);
lblStatus.Caption := '';
Exit;
end;
ListLexicon(LexResults, SearchStr, FLexApp, FDate, FExtend, FI10Active);
if (Piece(LexResults[0], u, 1) = '-1') then
begin
found := '0 matches found';
if FExtend then
found := found + ' by ' + subset + ' Search.'
else
found := found + '.';
lblSelect.Visible := False;
txtSearch.SetFocus;
txtSearch.SelectAll;
cmdOK.Default := False;
cmdOK.Enabled := False;
tgfLex.tv.Enabled := False;
tgfLex.tv.Items.Clear;
cmdCancel.Default := False;
cmdSearch.Default := True;
if not FExtend and (FLexApp = LX_ICD) then
begin
cmdExtendedSearch.Click;
Exit;
end;
end
else
begin
found := inttostr(LexResults.Count) + ' matches found';
if FExtend then
found := found + ' by ' + subset + ' Search.'
else
found := found + '.';
SetColumnTreeModel(LexResults);
setClientWidth;
lblSelect.Visible := True;
tgfLex.tv.Enabled := True;
tgfLex.tv.SetFocus;
Match := tgfLex.FindNode(SearchStr);
if Match <> nil then
begin {search term is on return list, so highlight it}
cmdOk.Enabled := True;
ActiveControl := tgfLex.tv;
end
else
begin
tgfLex.tv.Items[0].Selected := False;
end;
if (not FExtend) and (FLexApp = LX_ICD) and (not isNumeric(txtSearch.Text)) then
enableExtend;
cmdSearch.Default := False;
end;
updateStatus(found);
if FExtend then tgfLex.pnlTarget.Visible := False;
finally
LexResults.Free;
Screen.Cursor := crDefault;
end;
end;
procedure TfrmPCELex.cmdExtendedSearchClick(Sender: TObject);
begin
inherited;
FExtend := True;
FCodeSys := '';
FSingleCodeSys := True;
processSearch;
disableExtend;
end;
procedure TfrmPCELex.cmdOKClick(Sender: TObject);
var
Node: TLexTreeNode;
begin
inherited;
if(tgfLex.SelectedNode = nil) then
Exit;
Node := tgfLex.SelectedNode;
if ((FLexApp = LX_ICD) or (FLexApp = LX_SCT)) and (Node.Code <> '') then
begin
if (Copy(Node.CodeSys, 0, 3) = 'ICD') then
FCode := Node.Code + U + Node.Text
else if (Copy(Node.CodeSys, 0, 3) = 'SNO') then
FCode := Node.TargetCode + U + Node.Text + ' (SNOMED CT ' + Node.Code + ')' + U + Node.DesignationID;
FCode := FCode + U + Node.CodeIEN + U + Node.CodeSys;
end
else if BAPersonalDX then
FCode := LexiconToCode(StrToInt(Node.VUID), FLexApp, FDate) + U + Node.Text + U + Node.VUID
else
FCode := LexiconToCode(StrToInt(Node.VUID), FLexApp, FDate) + U + Node.Text;
Close;
end;
procedure TfrmPCELex.cmdCancelClick(Sender: TObject);
begin
inherited;
FCode := '';
Close;
end;
procedure TfrmPCELex.tgfLextvChange(Sender: TObject; Node: TTreeNode);
begin
inherited;
tgfLex.tvChange(Sender, Node);
if (tgfLex.SelectedNode = nil) or (tgfLex.SelectedNode.VUID = '+') then
begin
cmdOK.Enabled := false;
cmdOk.Default := false;
end
else // valid Node selected
begin
cmdOK.Enabled := true;
cmdOK.Default := true;
cmdSearch.Default := false;
end;
end;
procedure TfrmPCELex.tgfLextvClick(Sender: TObject);
begin
inherited;
if(tgfLex.SelectedNode <> nil) and (tgfLex.SelectedNode.VUID <> '+') then
begin
cmdOK.Enabled := true;
cmdSearch.Default := False;
cmdOK.Default := True;
end;
end;
procedure TfrmPCELex.tgfLextvDblClick(Sender: TObject);
begin
inherited;
tgfLextvClick(Sender);
if (tgfLex.SelectedNode <> nil) and (tgfLex.SelectedNode.VUID <> '+') then
cmdOKClick(Sender);
end;
procedure TfrmPCELex.tgfLextvEnter(Sender: TObject);
begin
inherited;
if (tgfLex.SelectedNode = nil) then
cmdOK.Enabled := false
else
cmdOK.Enabled := true;
end;
procedure TfrmPCELex.tgfLextvExit(Sender: TObject);
begin
inherited;
if (tgfLex.SelectedNode = nil) then
cmdOK.Enabled := false
else
cmdOK.Enabled := true;
end;
procedure TfrmPCELex.tgfLextvExpanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
var
ctNode, ChildNode, StubNode: TLexTreeNode;
ChildRecs: TStringList;
RecStr: String;
i: integer;
begin
inherited;
ctNode := Node as TLexTreeNode;
if ctNode.VUID = '+' then
begin
ChildRecs := TStringList.Create;
ListLexicon(ChildRecs, ctNode.Code, FLexApp, FDate, True, FI10Active);
//clear node's placeholder child
ctNode.DeleteChildren;
//create children
for i := 0 to ChildRecs.Count - 1 do
begin
RecStr := ChildRecs[i];
ChildNode := (tgfLex.tv.Items.AddChild(ctNode, Piece(RecStr, '^', 2))) as TLexTreeNode;
with ChildNode do
begin
VUID := Piece(RecStr, '^', 1);
Text := Piece(RecStr, '^', 2);
CodeDescription := Text;
CodeSys := Piece(RecStr, '^', 3);
if ((FCodeSys <> '') and (CodeSys <> FCodeSys)) then
FSingleCodeSys := False;
FCodeSys := CodeSys;
Code := Piece(RecStr, '^', 4);
if Piece(RecStr, '^', 8) <> '' then
ParentIndex := IntToStr(StrToInt(Piece(RecStr, '^', 8)) - 1);
//TODO: Need to accommodate Designation Code in ColumnTreeNode...
if CodeSys = 'SNOMED CT' then
CodeIEN := Code
else
CodeIEN := Piece(RecStr, '^', 9);
TargetCode := Piece(RecStr, '^', 6);
end;
if (ChildNode.VUID = '+') then
begin
StubNode := (tgfLex.tv.Items.AddChild(ChildNode, 'Searching...')) as TLexTreeNode;
with StubNode do
begin
VUID := '';
Text := 'Searching...';
CodeDescription := Text;
CodeSys := 'ICD-10-CM';
if ((FCodeSys <> '') and (CodeSys <> FCodeSys)) then
FSingleCodeSys := False;
FCodeSys := CodeSys;
Code := '';
CodeIEN := '';
ParentIndex := IntToStr(Node.Index);
end;
end;
end;
end;
AllowExpansion := True;
//sort treenodes
tgfLex.tv.AlphaSort(True);
tgfLex.tv.Invalidate;
end;
procedure TfrmPCELex.tgfLextvHint(Sender: TObject; const Node: TTreeNode;
var Hint: string);
begin
inherited;
// Only show hint if caption is less than width of Column[0]
if TextWidthByFont(Font.Handle, Node.Text) < tgfLex.tv.Width then
Hint := ''
else
Hint := Node.Text;
end;
procedure TfrmPCELex.updateStatus(status: String);
begin
lblStatus.caption := status;
lblStatus.Invalidate;
lblStatus.Update;
end;
function TfrmPCELex.isNumeric(inStr: String): Boolean;
var
dbl: Double;
error, intDecimal: Integer;
begin
Result := False;
if (FormatSettings.DecimalSeparator <> '.') then
intDecimal := Pos(FormatSettings.DecimalSeparator, inStr)
else
intDecimal := 0;
if (intDecimal > 0) then
inStr[intDecimal] := '.';
Val(inStr, dbl, error);
if (dbl = 0.0) then
; //do nothing
if (intDecimal > 0) then
inStr[intDecimal] := FormatSettings.DecimalSeparator;
if (error = 0) then
Result := True;
end;
function TfrmPCELex.ParseNarrCode(ANarrCode: String): String;
var
narr, code: String;
ps: Integer;
begin
narr := ANarrCode;
ps := Pos('(SCT', narr);
if not (ps > 0) then
ps := Pos('(SNOMED', narr);
if not (ps > 0) then
ps := Pos('(ICD', narr);
if (ps > 0) then
begin
narr := TrimRight(Copy(ANarrCode, 0, ps - 1));
code := Copy(ANarrCode, ps, Length(ANarrCode));
code := Piece(Piece(Piece(code, ')', 1), '(', 2), ' ', 2);
end
else
code := '';
Result := code + U + narr;
end;
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.ColorsPanel;
interface
{$SCOPEDENUMS ON}
uses
System.Types, System.Classes, System.UITypes, FMX.Controls, FMX.Graphics, FMX.Types, FGX.Colors.Presets, FGX.Types,
FGX.Consts;
type
{ TfgCustomColorsPanel }
TfgOnGetColor = procedure (Sender: TObject; const Column, Row: Integer; var Color: TAlphaColor) of object;
TfgOnColorSelected = procedure (Sender: TObject; const AColor: TAlphaColor) of object;
TfgOnPaintCell = procedure (Sender: TObject; Canvas: TCanvas; const Column, Row: Integer; const Frame: TRectF;
const AColor: TAlphaColor; Corners: TCorners; var Done: Boolean) of object;
TfgColorsPresetKind = (WebSafe, X11, Custom);
TfgCustomColorsPanel = class(TControl)
public const
DefaultCellSize = 18;
MinCellSize = 5;
private
FCellSize: TfgSingleSize;
FBorderRadius: Single;
FStrokeBrush: TStrokeBrush;
FColorsPreset: TfgColorsPreset;
FPresetKind: TfgColorsPresetKind;
FOnGetColor: TfgOnGetColor;
FOnColorSelected: TfgOnColorSelected;
FOnPaintCell: TfgOnPaintCell;
function IsBorderRadiusStored: Boolean;
function IsCellSizeStored: Boolean;
procedure SetColorCellSize(const Value: TfgSingleSize);
procedure SetBorderColor(const Value: TStrokeBrush);
procedure SetBorderRadius(const Value: Single);
procedure SetColorsPreset(const Value: TfgColorsPreset);
procedure SetPresetKind(const Value: TfgColorsPresetKind);
protected
{ Events }
procedure DoGetColor(const AColumn, ARow: Integer; var AColor: TAlphaColor); virtual;
procedure DoColorSelected(const AColor: TAlphaColor); virtual;
procedure DoPaintCell(const AColumn, ARow: Integer; const AFrame: TRectF; const AColor: TAlphaColor; ACorners: TCorners;
var ADone: Boolean); virtual;
procedure DoBorderStrokeChanged(Sender: TObject); virtual;
procedure DoCellSizeChanged(Sender: TObject); virtual;
{ Sizes }
function GetDefaultSize: TSizeF; override;
function GetBorderFrame: TRectF; virtual;
function GetCellFrame(const Column, Row: Integer): TRectF; virtual;
{ Painting }
procedure Paint; override;
procedure DrawCell(const AColumn, ARow: Integer; const AFrame: TRectF; const AColor: TAlphaColor); virtual;
{ Mouse Events }
procedure MouseClick(Button: TMouseButton; Shift: TShiftState; X: Single; Y: Single); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetColor(const AColumn, ARow: Integer): TAlphaColor; virtual;
function ColumnsCount: Integer;
function RowsCount: Integer;
property ColorsPreset: TfgColorsPreset read FColorsPreset write SetColorsPreset;
public
property BorderRadius: Single read FBorderRadius write SetBorderRadius stored IsBorderRadiusStored;
property PresetKind: TfgColorsPresetKind read FPresetKind write SetPresetKind default TfgColorsPresetKind.WebSafe;
property Stroke: TStrokeBrush read FStrokeBrush write SetBorderColor;
property CellSize: TfgSingleSize read FCellSize write SetColorCellSize stored IsCellSizeStored;
property OnGetColor: TfgOnGetColor read FOnGetColor write FOnGetColor;
property OnColorSelected: TfgOnColorSelected read FOnColorSelected write FOnColorSelected;
property OnPaintCell: TfgOnPaintCell read FOnPaintCell write FOnPaintCell;
end;
{ TfgColorsPanel }
[ComponentPlatformsAttribute(fgAllPlatform)]
TfgColorsPanel = class(TfgCustomColorsPanel)
published
property Stroke;
property BorderRadius;
property PresetKind;
property CellSize;
property OnGetColor;
property OnColorSelected;
property OnPaintCell;
{ inherited }
property Align;
property Anchors;
property ClipChildren default False;
property ClipParent default False;
property Cursor default crDefault;
property DragMode default TDragMode.dmManual;
property EnableDragHighlight default True;
property Enabled default True;
property Locked default False;
property Height;
property HitTest default True;
property Padding;
property Opacity;
property Margins;
property PopupMenu;
property Position;
property RotationAngle;
property RotationCenter;
property Scale;
property Size;
property TabOrder;
property TouchTargetExpansion;
property Visible default True;
property Width;
property OnDragEnter;
property OnDragLeave;
property OnDragOver;
property OnDragDrop;
property OnDragEnd;
property OnKeyDown;
property OnKeyUp;
property OnCanFocus;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseEnter;
property OnMouseLeave;
property OnPainting;
property OnPaint;
property OnResize;
end;
implementation
uses
System.Math, System.SysUtils, System.UIConsts, System.TypInfo, FGX.Graphics, FGX.Asserts;
{ TfgCustomColorsPanel }
function TfgCustomColorsPanel.ColumnsCount: Integer;
begin
AssertIsNotNil(CellSize);
if not SameValue(CellSize.Width - 1, 0, EPSILON_SINGLE) then
Result := Floor(Width / (CellSize.Width - 1))
else
Result := 0;
end;
constructor TfgCustomColorsPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCellSize := TfgSingleSize.Create(DefaultCellSize, DefaultCellSize, TfgEqualityComparators.SingleEquality);
FCellSize.OnChange := DoCellSizeChanged;
FBorderRadius := 0;
FStrokeBrush := TStrokeBrush.Create(TBrushKind.Solid, TAlphaColorRec.Black);
FStrokeBrush.OnChanged := DoBorderStrokeChanged;
SetAcceptsControls(False);
{ Set Default Preset }
SetLength(FColorsPreset, Length(COLORS_PRESET_WEB_SAFE));
System.Move(COLORS_PRESET_WEB_SAFE[1], FColorsPreset[0], SizeOf(COLORS_PRESET_WEB_SAFE));
end;
destructor TfgCustomColorsPanel.Destroy;
begin
FreeAndNil(FCellSize);
FreeAndNil(FStrokeBrush);
inherited Destroy;
end;
procedure TfgCustomColorsPanel.DoBorderStrokeChanged(Sender: TObject);
begin
Repaint;
end;
procedure TfgCustomColorsPanel.DoCellSizeChanged(Sender: TObject);
begin
Repaint;
end;
procedure TfgCustomColorsPanel.DoColorSelected(const AColor: TAlphaColor);
begin
if Assigned(FOnColorSelected) then
FOnColorSelected(Self, AColor);
end;
procedure TfgCustomColorsPanel.DoGetColor(const AColumn, ARow: Integer; var AColor: TAlphaColor);
begin
if Assigned(FOnGetColor) then
FOnGetColor(Self, AColumn, ARow, AColor);
end;
procedure TfgCustomColorsPanel.DoPaintCell(const AColumn, ARow: Integer; const AFrame: TRectF; const AColor: TAlphaColor;
ACorners: TCorners; var ADone: Boolean);
begin
if Assigned(FOnPaintCell) then
FOnPaintCell(Self, Canvas, AColumn, ARow, AFrame, AColor, ACorners, ADone);
end;
procedure TfgCustomColorsPanel.DrawCell(const AColumn, ARow: Integer; const AFrame: TRectF; const AColor: TAlphaColor);
function DefineCorners: TCorners;
var
Corners: TCorners;
begin
Corners := [];
if (AColumn = 1) and (ARow = 1) then
Corners := Corners + [TCorner.TopLeft];
if (AColumn = ColumnsCount) and (ARow = 1) then
Corners := Corners + [TCorner.TopRight];
if (AColumn = ColumnsCount) and (ARow = RowsCount) then
Corners := Corners + [TCorner.BottomRight];
if (AColumn = 1) and (ARow = RowsCount) then
Corners := Corners + [TCorner.BottomLeft];
Result := Corners;
end;
var
Corners: TCorners;
Done: Boolean;
begin
AssertIsNotNil(Canvas);
AssertInRange(AColumn, 1, ColumnsCount);
AssertInRange(ARow, 1, RowsCount);
Canvas.Fill.Kind := TBrushKind.Solid;
Canvas.Fill.Color := AColor;
Corners := DefineCorners;
Done := False;
DoPaintCell(AColumn, ARow, AFrame, AColor, Corners, Done);
if not Done then
Canvas.FillRect(AFrame, BorderRadius, BorderRadius, Corners, AbsoluteOpacity);
Canvas.DrawRect(AFrame, BorderRadius, BorderRadius, Corners, AbsoluteOpacity, Stroke);
end;
function TfgCustomColorsPanel.GetDefaultSize: TSizeF;
begin
Result := TSizeF.Create(85, 34);
end;
function TfgCustomColorsPanel.GetCellFrame(const Column, Row: Integer): TRectF;
var
Left: Single;
Top: Single;
HalfThickness: Single;
begin
AssertIsNotNil(CellSize);
AssertInRange(Column, 1, ColumnsCount);
AssertInRange(Row, 1, RowsCount);
Left := (Column - 1) * (CellSize.Width - Stroke.Thickness);
Top := (Row - 1) * (CellSize.Height - Stroke.Thickness);
HalfThickness := FStrokeBrush.Thickness / 2;
Result := TRectF.Create(TPointF.Create(Left, Top), CellSize.Width, CellSize.Height);
Result.Inflate(-HalfThickness, -HalfThickness);
end;
function TfgCustomColorsPanel.GetBorderFrame: TRectF;
var
HalfThickness: Single;
begin
HalfThickness := FStrokeBrush.Thickness / 2;
Result := TRectF.Create(HalfThickness, HalfThickness, Width - HalfThickness, Height - HalfThickness);
end;
function TfgCustomColorsPanel.GetColor(const AColumn, ARow: Integer): TAlphaColor;
var
ColorIndex: Integer;
PresetTmp: TfgColorsPreset;
begin
ColorIndex := (ARow - 1) * ColumnsCount + AColumn;
case PresetKind of
TfgColorsPresetKind.WebSafe:
begin
SetLength(PresetTmp, Length(COLORS_PRESET_WEB_SAFE));
System.Move(COLORS_PRESET_WEB_SAFE[1], PresetTmp[0], SizeOf(COLORS_PRESET_WEB_SAFE));
end;
TfgColorsPresetKind.X11:
begin
SetLength(PresetTmp, Length(COLORS_PRESET_X11));
System.Move(COLORS_PRESET_X11[1], PresetTmp[0], SizeOf(COLORS_PRESET_X11));
end;
TfgColorsPresetKind.Custom:
PresetTmp := FColorsPreset;
else
Result := TAlphaColorRec.Null;
end;
if ColorIndex <= High(PresetTmp) then
Result := PresetTmp[ColorIndex].Value
else
Result := TAlphaColorRec.Null;
DoGetColor(AColumn, ARow, Result);
end;
function TfgCustomColorsPanel.IsBorderRadiusStored: Boolean;
begin
Result := not SameValue(BorderRadius, 0, EPSILON_SINGLE);
end;
function TfgCustomColorsPanel.IsCellSizeStored: Boolean;
begin
Result := not SameValue(FCellSize.Width, DefaultCellSize, EPSILON_SINGLE) or not SameValue(FCellSize.Height, DefaultCellSize, EPSILON_SINGLE);
end;
procedure TfgCustomColorsPanel.MouseClick(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
ClickedColor: TAlphaColor;
Col: Integer;
Row: Integer;
begin
inherited MouseClick(Button, Shift, X, Y);
Col := Floor(X / (CellSize.Width - FStrokeBrush.Thickness)) + 1;
Row := Floor(Y / (CellSize.Height - FStrokeBrush.Thickness)) + 1;
ClickedColor := GetColor(Col, Row);
DoColorSelected(ClickedColor);
end;
procedure TfgCustomColorsPanel.Paint;
var
Column: Integer;
Row: Integer;
Color: TAlphaColor;
begin
if ColumnsCount > 0 then
for Row := 1 to RowsCount do
for Column := 1 to ColumnsCount do
begin
Color := GetColor(Column, Row);
DrawCell(Column, Row, GetCellFrame(Column, Row), Color);
end;
end;
function TfgCustomColorsPanel.RowsCount: Integer;
begin
Result := Floor(Height / (CellSize.Height - 1));
end;
procedure TfgCustomColorsPanel.SetBorderColor(const Value: TStrokeBrush);
begin
if FStrokeBrush.Equals(Value) then
begin
FStrokeBrush.Assign(Value);
Repaint;
end;
end;
procedure TfgCustomColorsPanel.SetBorderRadius(const Value: Single);
begin
if not SameValue(BorderRadius, Value, EPSILON_SINGLE) then
begin
FBorderRadius := Value;
Repaint;
end;
end;
procedure TfgCustomColorsPanel.SetColorCellSize(const Value: TfgSingleSize);
begin
AssertIsNotNil(Value);
AssertIsNotNil(CellSize);
Assert(Value.Width >= MinCellSize);
Assert(Value.Height >= MinCellSize);
if CellSize <> Value then
begin
FCellSize.Assign(Value);
Repaint;
end;
end;
procedure TfgCustomColorsPanel.SetPresetKind(const Value: TfgColorsPresetKind);
begin
if PresetKind <> Value then
begin
FPresetKind := Value;
Repaint;
end;
end;
procedure TfgCustomColorsPanel.SetColorsPreset(const Value: TfgColorsPreset);
begin
FColorsPreset := Value;
Repaint;
end;
initialization
RegisterFmxClasses([TfgCustomColorsPanel, TfgColorsPanel]);
end.
|
{
* X11 (MIT) LICENSE *
Copyright © 2013 Jolyon Smith
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.
* GPL and Other Licenses *
The FSF deem this license to be compatible with version 3 of the GPL.
Compatability with other licenses should be verified by reference to those
other license terms.
* Contact Details *
Original author : Jolyon Smith
skype : deltics
e-mail : <EXTLINK mailto: jsmith@deltics.co.nz>jsmith@deltics.co.nz</EXTLINK>
website : <EXTLINK http://www.deltics.co.nz>www.deltics.co.nz</EXTLINK>
}
{$i deltics.unicode.inc}
unit Deltics.Unicode.Utils;
interface
uses
Deltics.Unicode.Types;
function AnsiHex(const aValue: Cardinal; const aNumDigits: Integer; const aUppercase: Boolean): AnsiString;
function WideHex(const aValue: Cardinal; const aNumDigits: Integer; const aUppercase: Boolean): UnicodeString;
procedure SetBuffer(const aBuffer: PAnsiChar; const aString: AnsiString); overload;
procedure SetBuffer(const aBuffer: PWideChar; const aString: UnicodeString); overload;
implementation
uses
Windows;
function AnsiHex(const aValue: Cardinal; const aNumDigits: Integer; const aUppercase: Boolean): AnsiString;
const
DIGITS: array[FALSE..TRUE] of AnsiString = ('0123456789abcdef', '0123456789ABCDEF');
var
i: Integer;
pBuf: PByte;
pOut: PAnsiChar;
shift: Boolean;
begin
SetLength(result, aNumDigits);
pBuf := PByte(@aValue);
{$ifdef 64BIT}
pOut := PAnsiChar(Int64(result) + aNumDigits - 1);
{$else}
pOut := PAnsiChar(Integer(result) + aNumDigits - 1);
{$endif}
shift := FALSE;
for i := aNumDigits downto 1 do
begin
if shift then
pOut^ := DIGITS[aUppercase][(pBuf^ and $f0) shr 4 + 1]
else
pOut^ := DIGITS[aUppercase][(pBuf^ and $0f) + 1];
Dec(pOut);
shift := NOT shift;
if NOT shift then
Inc(pBuf);
end;
end;
function WideHex(const aValue: Cardinal; const aNumDigits: Integer; const aUppercase: Boolean): UnicodeString;
const
DIGITS: array[FALSE..TRUE] of UnicodeString = ('0123456789abcdef', '0123456789ABCDEF');
var
i: Integer;
pBuf: PByte;
pOut: PWideChar;
shift: Boolean;
begin
SetLength(result, aNumDigits);
pBuf := PByte(@aValue);
{$ifdef 64BIT}
pOut := PWideChar(Int64(result) + (aNumDigits * 2) - 2);
{$else}
pOut := PWideChar(Integer(result) + (aNumDigits * 2) - 2);
{$endif}
shift := FALSE;
for i := aNumDigits downto 1 do
begin
if shift then
pOut^ := DIGITS[aUppercase][(pBuf^ and $f0) shr 4 + 1]
else
pOut^ := DIGITS[aUppercase][(pBuf^ and $0f) + 1];
Dec(pOut);
shift := NOT shift;
if NOT shift then
Inc(pBuf);
end;
end;
procedure SetBuffer(const aBuffer: PAnsiChar; const aString: AnsiString);
begin
CopyMemory(Pointer(aBuffer), Pointer(aString), Length(aString));
end;
procedure SetBuffer(const aBuffer: PWideChar; const aString: UnicodeString);
begin
CopyMemory(Pointer(aBuffer), Pointer(aString), Length(aString) * 2);
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program CRUELL2;
Uses Math;
Const
maxN =500;
Var
n :LongInt;
A :Array[0..maxN] of Real;
procedure Enter;
var
i :LongInt;
begin
Read(n);
for i:=0 to n do Read(A[i]);
end;
function Cal(x :Real) :Real;
var
i :LongInt;
begin
Cal:=0;
for i:=0 to n do Cal:=Cal+A[i]*Power(x,i);
end;
function BS :Real;
var
left,right,mid,cL,cR,cM :Real;
begin
left:=-1000000; right:=1000000; mid:=(left+right)/2;
while (left<>mid) and (right<>mid) do
begin
cM:=Cal(mid); cL:=Cal(left); cR:=Cal(right);
if (cL*cM<0) then right:=mid;
if (cR*cM<0) then left:=mid;
mid:=(left+right)/2;
end;
Exit(mid);
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Enter;
Write(Trunc(BS*1000));
Close(Input); Close(Output);
End. |
PROGRAM Kaffeeautomat;
TYPE Coins = RECORD
OneEuro: integer;
FiftyCent: integer;
TenCent: integer;
END;
const coffeePrize = 40;
var changeBank: Coins;
var totalChange: Coins;
var coinsInput: Coins;
var coinsOutput: Coins;
var totalCredit: integer;
var errNotEnoughChange: integer;
PROCEDURE Init;
BEGIN (* Init *)
changeBank.OneEuro := 0;
changeBank.FiftyCent := 5;
changeBank.TenCent := 10;
coinsInput.OneEuro := 0;
coinsInput.FiftyCent := 0;
coinsInput.TenCent := 0;
totalChange.OneEuro := 0;
totalChange.FiftyCent := 0;
totalChange.TenCent := 0;
totalCredit := 0;
errNotEnoughChange := 0;
END; (* Init *)
PROCEDURE ResetMachine;
BEGIN (* ResetMachine *)
coinsInput.OneEuro := 0;
coinsInput.FiftyCent := 0;
coinsInput.TenCent := 0;
totalChange.OneEuro := 0;
totalChange.FiftyCent := 0;
totalChange.TenCent := 0;
totalCredit := 0;
END; (* ResetMachine *)
FUNCTION CalculateChange(credit: integer): Coins;
var returnCoins: Coins;
BEGIN (* CalculateChange *)
returnCoins.OneEuro := 0;
returnCoins.FiftyCent := 0;
returnCoins.TenCent := 0;
if credit < coffeePrize then BEGIN
WriteLn('Not enough credit. Please input at least ', (coffeePrize / 100):1:2, ' EUR.');
CalculateChange := coinsInput;
end else BEGIN
credit := credit - coffeePrize; (* Removes the prize for one coffe from the total credits *)
while (credit >= 100) AND (changeBank.OneEuro > 0) do BEGIN
Inc(returnCoins.OneEuro);
Dec(changeBank.OneEuro);
credit := credit - 100;
END; (* WHILE *)
while (credit >= 50) AND (changeBank.FiftyCent > 0) do BEGIN
Inc(returnCoins.FiftyCent);
Dec(changeBank.FiftyCent);
credit := credit - 50;
END; (* WHILE *)
while (credit >= 10) AND (changeBank.TenCent > 0) do BEGIN
Inc(returnCoins.TenCent);
Dec(changeBank.TenCent);
credit := credit - 10;
END; (* WHILE *)
if credit > 0 then BEGIN
Write('Machine has not enough change! ');
Inc(errNotEnoughChange);
CalculateChange := coinsInput;
end else BEGIN
CalculateChange := returnCoins;
END; (* IF *)
END; (* IF *)
END; (* CalculateChange *)
PROCEDURE CoffeeButtonPressed(input: Coins; var change: Coins);
BEGIN (* CoffeeButtonPressed *)
totalCredit := input.OneEuro * 100;
totalCredit := totalCredit + input.FiftyCent * 50;
totalCredit := totalCredit + input.TenCent * 10;
changeBank.OneEuro := changeBank.OneEuro + input.OneEuro;
changeBank.FiftyCent := changeBank.FiftyCent + input.FiftyCent;
changeBank.TenCent := changeBank.TenCent + input.TenCent;
if totalCredit <> coffeePrize then BEGIN
totalChange := CalculateChange(totalCredit);
if (totalChange.OneEuro <> input.OneEuro) OR (totalChange.FiftyCent <> input.FiftyCent)
OR (totalChange.TenCent <> input.TenCent) then
WriteLn('Thank you, enjoy your coffee!');
Write('You get ');
if totalChange.OneEuro > 0 then
Write(totalChange.OneEuro, ' One Euro Coin(s) ');
if totalChange.FiftyCent > 0 then
Write(totalChange.FiftyCent, ' Fifty Cent Coin(s) ');
if totalChange.TenCent > 0 then
Write(totalChange.TenCent, ' Ten Cent Coin(s) ');
Write('in change.');
end else BEGIN
WriteLn('Thank you, enjoy your coffee!');
END; (* IF *)
END; (* CoffeeButtonPressed *)
var x: integer;
BEGIN (* Kaffeeautomat *)
Init;
while(errNotEnoughChange < 3) do BEGIN
WriteLn();
Write('Enter the amount of money you wish to input (10 for 10 Cents, 50 for 50 Cents, 1 for 1 Euro, 0 to end input): ');
Read(x);
While(x <> 0) do BEGIN
IF (x = 1) THEN BEGIN
Inc(CoinsInput.OneEuro);
END ELSE IF (x = 50) THEN BEGIN
Inc(CoinsInput.FiftyCent);
END ELSE IF (x = 10) THEN BEGIN
Inc(CoinsInput.TenCent);
END ELSE BEGIN
Write('Invalid input, terminating program.');
HALT;
END; (* IF *)
Read(x);
END; (* WHILE *)
CoffeeButtonPressed(CoinsInput, CoinsOutput);
ResetMachine;
END; (* WHILE *)
WriteLn();
WriteLn('ERROR: Out of order!');
END. (* Kaffeeautomat *) |
unit record_overload_operators;
interface
implementation
type
TRec = record
F: int32;
operator Add(const Left, Right: TRec): TRec;
end;
var
R: TRec;
operator TRec.Add(const Left, Right: TRec): TRec;
begin
Result.F := Left.F + Right.F;
end;
procedure Test;
var
X, Y: TRec;
begin
X.F := 1;
Y.F := 2;
R := X + Y;
end;
initialization
Test();
finalization
Assert(R.F = 3);
end. |
{*
FrameFileSelector.pas/dfm
-------------------------
Begin: 2005/08/04
Last revision: $Date: 2010-11-03 18:41:47 $ $Author: rhupalo $
Version number: $Revision: 1.14 $
Project: APHI General Purpose Delphi Libary
Website: http://www.naadsm.org/opensource/delphi/
Author: Aaron Reeves <aaron.reeves@naadsm.org>
--------------------------------------------------
Copyright (C) 2005 - 2008 Animal Population Health Institute, Colorado State University
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.
---------------------------------------------------
Widget to add to forms where the user needs to create the full path name for
some export file that will be created.
}
(*
Documentation generation tags begin with {* or ///
Replacing these with (* or // foils the documentation generator
*)
unit FrameFileSelector;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls
;
type
/// FFrame providing components to browse to a folder and to input a file name.
TFrameFileSelector = class( TFrame )
leFileName: TEdit; /// for file name input and editing
btnBrowse: TButton; /// for browsing to or creating a folder location
SaveDialog1: TSaveDialog;/// for obtaining the directory path
lblFileName: TLabel;
procedure btnBrowseClick(Sender: TObject);
protected
_dir: string; /// the selected directory path
_fileNameExtension: string; /// file format extension
_enabled: boolean; /// disables or enables the input components
procedure translateUI();
procedure setDirectory( dirName: string );
function getDirectory(): string;
procedure setFileName( fn: string );
function getFileName(): string;
procedure setFilter( flt: string );
function getFilter(): string;
function getFileNameExtension(): string;
procedure setFileNameExtension( val: string );
function getFrameFileSelectorEnabled(): boolean;
procedure setFrameFileSelectorEnabled( val: boolean );
public
constructor create( AOwner: TComponent ); overload; override;
constructor create( AOwner: TComponent; pathName: string; filter: string ); reintroduce; overload;
procedure setFocus(); override;
/// provides access to _dir
property directory: string read getDirectory write setDirectory;
/// provides access to the directory path and filename
property fileName: string read getFileName write setFileName;
/// provides access to the file extension filter
property filter: string read getFilter write setFilter;
/// provides access to _fileNameExtension
property fileNameExtension: string read getFileNameExtension write setFileNameExtension;
/// provides access to _enabled
property enabled: boolean read getFrameFileSelectorEnabled write setFrameFileSelectorEnabled;
end
;
implementation
{$R *.dfm}
uses
DebugWindow,
MyStrUtils,
StrUtils,
I88n
;
{*
Creates an instance of the frame
@param AOwner the form that owns this instance of the frame
}
constructor TFrameFileSelector.create( AOwner: TComponent );
begin
inherited create( AOwner );
translateUI();
_enabled := true;
leFileName.Text := '';
setFilter( '' );
_dir := '';
end
;
{*
Creates an instance of the frame and itializes some of the file parameters
@param AOwner the form that owns this instance of the frame
@param pathName currently not used ...
@param filter currently not used ...
}
constructor TFrameFileSelector.create( AOwner: TComponent; pathName: string; filter: string );
begin
// rbh20101102: Fix Me - was it intended that pathName and filter be used to set private members?
inherited create( AOwner );
translateUI();
_enabled := true;
leFileName.Text := trim( fileName );
setFilter( '' );
if( '' <> leFileName.Text ) then
_dir := MyStrUtils.directory( leFileName.Text )
else
_dir := ''
;
end
;
/// Specifies the captions, hints, and other component text phrases for translation
procedure TFrameFileSelector.translateUI();
begin
// This function was generated automatically by Caption Collector 0.6.0.
// Generation date: Mon Feb 25 15:29:38 2008
// File name: C:/Documents and Settings/apreeves/My Documents/NAADSM/Interface-Fremont/general_purpose_gui/FrameFileSelector.dfm
// File date: Thu Sep 1 12:33:53 2005
// Set Caption, Hint, Text, and Filter properties
with self do
begin
lblFileName.Caption := tr( 'File name:' );
btnBrowse.Caption := tr( 'Browse...' );
SaveDialog1.Filter := tr( 'All files (*.*)|*.*|Comma separated values (*.csv)|*.csv' );
end
;
end
;
{*
Does all the normal things associated with a file browser save dialog
@params Sender the component instance generating the click event
}
procedure TFrameFileSelector.btnBrowseClick(Sender: TObject);
var
tmpName: string;
begin
saveDialog1.Title := tr( 'Save as' );
if( length( trim(leFileName.text) ) > 0 ) then
saveDialog1.fileName := trim( leFileName.text )
else if( '' <> _dir ) then
saveDialog1.initialDir := _dir
;
if saveDialog1.Execute() then
begin
_dir := MyStrUtils.directory( saveDialog1.FileName );
tmpName := trim( saveDialog1.fileName );
if( ansiLowerCase( rightStr( tmpName, length( trim( _fileNameExtension ) ) ) ) <> fixup( _fileNameExtension ) ) then
tmpName := tmpName + _fileNameExtension
;
leFileName.Text := tmpName;
end
;
end
;
/// Directs focus to the filename TEdit control
procedure TFrameFileSelector.setFocus();
begin
leFileName.SetFocus();
end
;
/// Set method for property directory, setting _dir to dirName
procedure TFrameFileSelector.setDirectory( dirName: string );
begin
_dir := dirName;
end
;
/// Get method for property directory, returning the value of _dir
function TFrameFileSelector.getDirectory(): string;
begin
result := _dir;
end
;
{*
Set method for property fileName and parses out a value for _dir
@param fn full directory path and filename
}
procedure TFrameFileSelector.setFileName( fn: string );
begin
leFileName.Text := trim( fn );
_dir := MyStrUtils.directory( leFileName.Text);
end
;
/// Get method for property fileName, returning the value in leFileName.Text
function TFrameFileSelector.getFileName(): string;
begin
result := trim( leFileName.Text );
end
;
{*
Sets the filter for the SaveDialog component, affecting what file types are shown in the file browser
@param flt filter text string, like: CSV Files (*.csv)|*.csv
}
procedure TFrameFileSelector.setFilter( flt: string );
begin
if( '' = flt ) then
SaveDialog1.Filter := tr( 'All Files (*.*)|*.*' )
else
begin
try
SaveDialog1.Filter := flt;
except
SaveDialog1.Filter := tr( 'All Files (*.*)|*.*' );
end;
end
;
end
;
/// Get method for property filter, returning the current SaveDialog file browser filter string
function TFrameFileSelector.getFilter(): string; begin result := SaveDialog1.Filter; end;
/// Get function for property fileNameExtension
function TFrameFileSelector.getFileNameExtension(): string;
begin
if( 0 < length( fileName ) ) then
begin
result := extractFileExt( fileName );
_fileNameExtension := result;
end
else
setFileNameExtension( result )
;
end
;
{*
Set method for property fileExtension. Sets a new default file format extension
in the saveDialog component and edits the file name in the edit control,
setting the extension to val.
@param val the new file extension to use
}
procedure TFrameFileSelector.setFileNameExtension( val: string );
begin
_fileNameExtension := val;
SaveDialog1.DefaultExt := ansiRightStr( _fileNameExtension, 3 );
if( 0 < length( fileName ) ) then
leFileName.Text := changeFileExt( fileName, _fileNameExtension )
;
end
;
/// Get method for property enabled, returning the value of _enabled
function TFrameFileSelector.getFrameFileSelectorEnabled(): boolean;
begin
result := _enabled;
end
;
{*
Set method for property enabled and mechanism to disable or enable all the
components on the frame.
@param val true enables the components and false disables the components
}
procedure TFrameFileSelector.setFrameFileSelectorEnabled( val: boolean );
begin
_enabled := val;
lblFileName.Enabled := val;
leFileName.Enabled := val;
btnBrowse.Enabled := val;
repaint();
end
;
end.
|
unit IWCompButton;
{PUBDIST}
interface
uses
Classes,
IWControl, IWHTMLTag, IWScriptEvents;
type
TIWButtonType = (btSubmit, btButton, btReset);
TIWCustomButton = class(TIWControl)
protected
FButtonType: TIWButtonType;
FOnClick: TScriptEvent;
FHotKey: string;
procedure HookEvents(AScriptEvents: TIWScriptEvents); override;
public
constructor Create(AOwner: TComponent); override;
function RenderHTML: TIWHTMLTag; override;
property ButtonType: TIWButtonType read FButtonType write FButtonType;
property HotKey: string read FHotkey write FHotKey;
end;
TIWButton = class(TIWCustomButton)
protected
procedure Submit(const AValue: string); override;
published
property ButtonType;
//@@ This is the text that will be displayed on the button.
property Caption;
//@@ Sets the background color for the button.
//Note: This has no effect in Nestcape 4.
property Color;
property Confirmation;
property DoSubmitValidation;
property Enabled;
property ExtraTagParams;
property Font;
property HotKey;
property ScriptEvents;
property TabOrder;
//
//@@ OnClick is fired when the user clicks on the button.
property OnClick;
end;
implementation
uses
{$IFDEF Linux}QGraphics, {$ELSE}Graphics, {$ENDIF}
{$IFNDEF Linux}Windows, {$ENDIF}
Math, SWSystem, SysUtils;
function TIWCustomButton.RenderHTML: TIWHTMLTag;
begin
if FHotKey <> '' then begin
Result := TIWHTMLTag.CreateTag('BUTTON'); try
Result.AddStringParam('ACCESSKEY', FHotKey);
Result.Contents.AddText(StringReplace(Caption, FHotKey, '<u>' + FHotKey + '</u>', [rfIgnoreCase]));
except FreeAndNil(result); raise; end;
end else begin
Result := TIWHTMLTag.CreateTag('INPUT'); try
Result.AddStringParam('VALUE', Caption);
except FreeAndNil(Result); raise; end;
end;
try
Result.AddStringParam('NAME', HTMLName);
case ButtonType of
btSubmit: Result.AddStringParam('TYPE', 'submit');
btButton: Result.AddStringParam('TYPE', 'button');
btReset: Result.AddStringParam('TYPE', 'reset');
end;
if (Font.Enabled) and (Color <> clBtnFace) then begin
Result.AddStringParam('STYLE', 'background-color: ' + ColorToRGBString(Color){ + ';'
+ Font.FontToStringStyle(WebApplication.Browser)});
end;
if not Enabled then begin
Result.Add('DISABLED');
end;
except FreeAndNil(Result); raise; end;
end;
procedure TIWButton.Submit(const AValue: string);
begin
DoClick;
end;
constructor TIWCustomButton.Create(AOwner: TComponent);
begin
inherited;
Color := clBtnFace;
FNeedsFormTag := True;
FSupportsSubmit := True;
FSupportedScriptEvents := 'OnBlur,OnClick,OnFocus,OnMouseDown,OnMouseUp';
FButtonType := btButton;
FRenderSize := true;
Height := 25;
Width := 75;
end;
procedure TIWCustomButton.HookEvents(AScriptEvents: TIWScriptEvents);
begin
inherited HookEvents(AScriptEvents);
AScriptEvents.HookEvent('OnClick', iif(Assigned(OnClick), SubmitHandler));
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Layers3D;
{$I FMX.Defines.inc}
interface
uses
System.Classes, System.Types, System.UITypes,
FMX.Types, FMX.Types3D, FMX.Layouts, FMX.Video, FMX.Objects;
type
{ TAbstractLayer3D }
TAbstractLayer3D = class(TControl3D, IAlignableObject, IAlignRoot)
private
FPlane: TMeshData;
FOnLayerMouseMove: TMouseMoveEvent;
FOnLayerMouseDown: TMouseEvent;
FOnLayerMouseUp: TMouseEvent;
FDisableLayerEvent: Boolean;
FAlign: TAlignLayout;
FAnchors: TAnchors;
FPadding: TBounds;
FMargins: TBounds;
FModulationColor: TAlphaColor;
FResolution: Integer;
FLayerWidth, FLayerHeight: Integer;
FLastWidth, FLastHeight: single;
procedure MarginsChanged(Sender: TObject); virtual;
procedure PaddingChanged(Sender: TObject); virtual;
procedure SetResolution(const Value: Integer);
procedure SetModulationColor(const Value: TAlphaColor);
function IsAnchorsStored: Boolean;
protected
procedure MouseMove3D(Shift: TShiftState; X, Y: Single; rayPos, rayDir: TVector3D); override;
procedure MouseDown3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single;
rayPos, rayDir: TVector3D); override;
procedure MouseUp3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single;
rayPos, rayDir: TVector3D); override;
procedure Apply; override;
procedure Render; override;
procedure Resize3D; override;
procedure SetDepth(const Value: Single); override;
procedure SetProjection(const Value: TProjection); override;
{ Layer }
procedure LayerMouseMove(Shift: TShiftState; X, Y: Single); virtual;
procedure LayerMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); virtual;
procedure LayerMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); virtual;
procedure LayerResized; virtual;
{ IAlignRoot }
procedure Realign; virtual;
{ IAlignableObject }
function GetAlign: TAlignLayout;
procedure SetAlign(const Value: TAlignLayout); virtual;
function GetAnchors: TAnchors;
procedure SetAnchors(const Value: TAnchors); virtual;
function GetPadding: TBounds;
procedure SetBounds(X, Y, AWidth, AHeight: Single);
function GetWidth: single;
function GetHeight: single;
function GetLeft: single;
function GetTop: single;
function GetAllowAlign: Boolean;
{ }
procedure Loaded; override;
{ Layer }
property LayerWidth: Integer read FLayerWidth;
property LayerHeight: Integer read FLayerHeight;
property Resolution: Integer read FResolution write SetResolution;
{Hiden property RAID 295966}
property Anchors: TAnchors read FAnchors write SetAnchors stored IsAnchorsStored default [TAnchorKind.akLeft, TAnchorKind.akTop];
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RayCastIntersect(const rayPos, rayDir: TVector3D; var Intersection: TVector3D): Boolean; override;
property ModulationColor: TAlphaColor read FModulationColor write SetModulationColor default TAlphaColors.White;
published
property Align: TAlignLayout read FAlign write SetAlign default TAlignLayout.alNone;
// property Anchors: TAnchors read FAnchors write SetAnchors stored IsAnchorsStored default [TAnchorKind.akLeft, TAnchorKind.akTop];
property Margins: TBounds read FMargins write FMargins;
property Padding: TBounds read FPadding write FPadding;
property TwoSide default True;
property OnLayerMouseMove: TMouseMoveEvent read FOnLayerMouseMove write FOnLayerMouseMove;
property OnLayerMouseDown: TMouseEvent read FOnLayerMouseDown write FOnLayerMouseDown;
property OnLayerMouseUp: TMouseEvent read FOnLayerMouseUp write FOnLayerMouseUp;
end;
{ TLayout3D }
TLayout3D = class(TAbstractLayer3D)
protected
procedure Render; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ TImage3D }
TImage3D = class(TAbstractLayer3D)
private
FBitmap: TBitmap;
procedure SetBitmap(const Value: TBitmap);
protected
procedure DoBitmapChanged(Sender: TObject);
procedure Apply; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Bitmap: TBitmap read FBitmap write SetBitmap;
end;
{ TCustomBufferLayer3D }
TCustomBufferLayer3D = class(TAbstractLayer3D)
private
FOnUpdateBuffer: TNotifyEvent;
protected
FBuffer: TBitmap;
procedure Apply; override;
function GetBitmap: TBitmap; virtual;
{ Layer }
procedure LayerResized; override;
{ BufferLayer }
procedure DoUpdateBuffer; virtual;
property OnUpdateBuffer: TNotifyEvent read FOnUpdateBuffer write FOnUpdateBuffer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Buffer: TBitmap read FBuffer;
end;
{ TBufferLayer3D }
TBufferLayer3D = class(TCustomBufferLayer3D)
published
property OnUpdateBuffer;
property Resolution;
end;
{ TCustomLayer3D }
TCustomLayer3D = class(TCustomBufferLayer3D, IScene, IContainerObject)
private
FDisableUpdate: Boolean;
FMousePos, FDownPos: TPointF;
FResizeSize, FResizePos, FResizeStartPos, FDownSize: TPointF;
FDragging, FResizing: Boolean;
FFill: TBrush;
FTransparency: Boolean;
FDrawing: Boolean;
FStyleBook: TStyleBook;
FActiveControl: TStyledControl;
FAnimatedCaret: Boolean;
FStyleLookup: string;
FNeedStyleLookup: Boolean;
FResourceLink: TControl;
FOnPaint: TOnPaintEvent;
procedure SetActiveControl(AControl: TStyledControl);
procedure SetFill(const Value: TBrush);
procedure FillChanged(Sender: TObject);
{ IScene }
function GetCanvas: TCanvas;
function GetComponent: TComponent;
function GetUpdateRectsCount: Integer;
function GetUpdateRect(const Index: Integer): TRectF;
function GetCaptured: IControl;
procedure SetCaptured(const Value: IControl);
function GetFocused: IControl;
procedure SetFocused(const Value: IControl);
function GetMousePos: TPointF;
procedure BeginDrag;
procedure BeginResize;
function GetTransparency: Boolean;
function GetStyleBook: TStyleBook;
function LocalToScreen(P: TPointF): TPointF;
function ScreenToLocal(P: TPointF): TPointF;
function GetActiveControl: TStyledControl;
procedure SetStyleBook(const Value: TStyleBook);
function GetAnimatedCaret: Boolean;
{ IContainerObject }
function GetContainerWidth: Single;
function GetContainerHeight: Single;
procedure SetStyleLookup(const Value: string);
protected
FUpdateRects: array of TRectF;
procedure LayerResized; override;
procedure DoUpdateBuffer; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function ObjectAtPoint(P: TPointF): IControl; override;
function FindTarget(P: TPointF; const Data: TDragObject): IControl; override;
procedure SetVisible(const Value: Boolean); override;
{ resources }
procedure ApplyStyleLookup; virtual;
function GetStyleObject: TControl;
procedure DoPaint(const Canvas: TCanvas; const ARect: TRectF); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure UpdateStyle;
procedure Invalidate;
{ children }
procedure AddObject(AObject: TFmxObject); override;
procedure RemoveObject(AObject: TFmxObject); override;
{ paint }
procedure AddUpdateRect(R: TRectF);
{ }
property Canvas: TCanvas read GetCanvas;
published
property ActiveControl: TStyledControl read FActiveControl write SetActiveControl;
property AnimatedCaret: Boolean read FAnimatedCaret write FAnimatedCaret default True;
property Fill: TBrush read FFill write SetFill;
property StyleLookup: string read FStyleLookup write SetStyleLookup;
property StyleBook: TStyleBook read FStyleBook write SetStyleBook;
property Transparency: Boolean read FTransparency write FTransparency default False;
property OnPaint: TOnPaintEvent read FOnPaint write FOnPaint;
end;
{ TLayer3D }
TLayer3D = class(TCustomLayer3D)
published
property Fill;
property StyleBook;
end;
{ TTextLayer3D }
TTextLayer3D = class(TCustomLayer3D)
private
FText: TText;
function GetText: string;
procedure SetText(const Value: string);
function GetFont: TFont;
procedure SetFont(const Value: TFont);
function GetBrush: TBrush;
procedure SetBrush(const Value: TBrush);
protected
procedure ApplyStyleLookup; override;
public
constructor Create(AOwner: TComponent); override;
published
property Font: TFont read GetFont write SetFont;
property Fill: TBrush read GetBrush write SetBrush;
property Text: string read GetText write SetText;
property HitTest default False;
property ZWrite default False;
end;
implementation
uses System.Math, System.TypInfo, System.SysUtils, FMX.Forms;
{ TAbstractLayer3D }
constructor TAbstractLayer3D.Create(AOwner: TComponent);
begin
inherited;
FResolution := 50;
FModulationColor := $FFFFFFFF;
FMargins := TBounds.Create(RectF(0, 0, 0, 0));
FMargins.OnChange := MarginsChanged;
FPadding := TBounds.Create(RectF(0, 0, 0, 0));
FPadding.OnChange := PaddingChanged;
FPlane := TMeshData.Create;
FPlane.VertexBuffer.Length := 4;
FPlane.VertexBuffer.Vertices[0] := Point3D(-0.5, -0.5, 1);
FPlane.VertexBuffer.TexCoord0[0] := PointF(0, 0);
FPlane.VertexBuffer.Vertices[1] := Point3D(0.5, -0.5, 1);
FPlane.VertexBuffer.TexCoord0[1] := PointF(1, 0);
FPlane.VertexBuffer.Vertices[2] := Point3D(0.5, 0.5, 1);
FPlane.VertexBuffer.TexCoord0[2] := PointF(1, 1);
FPlane.VertexBuffer.Vertices[3] := Point3D(-0.5, 0.5, 1);
FPlane.VertexBuffer.TexCoord0[3] := PointF(0, 1);
FPlane.IndexBuffer.Length := 6;
FPlane.IndexBuffer[0] := 0;
FPlane.IndexBuffer[1] := 1;
FPlane.IndexBuffer[2] := 3;
FPlane.IndexBuffer[3] := 3;
FPlane.IndexBuffer[4] := 1;
FPlane.IndexBuffer[5] := 2;
SetSize(5, 4, 0.01);
TwoSide := True;
end;
destructor TAbstractLayer3D.Destroy;
begin
FreeAndNil(FPlane);
FMargins.Free;
FPadding.Free;
inherited;
end;
procedure TAbstractLayer3D.Realign;
begin
if csDestroying in ComponentState then
Exit;
if (Abs(FLayerWidth) < 1) or (Abs(FLayerHeight) < 1) then
Exit;
if FChildren = nil then
Exit;
if FChildren.Count = 0 then
Exit;
if FDisableAlign then
Exit;
AlignObjects(Self, FMargins, FLayerWidth, FLayerHeight, FLastWidth, FLastHeight, FDisableAlign);
end;
function TAbstractLayer3D.IsAnchorsStored: Boolean;
begin
Result := Anchors <> AnchorAlign[Align];
end;
procedure TAbstractLayer3D.Apply;
begin
inherited;
Context.SetColor(TMaterialColor.mcDiffuse, FModulationColor);
Context.SetContextState(TContextState.csTexDisable);
Context.SetContextState(TContextState.csLightOff);
end;
procedure TAbstractLayer3D.Render;
var
Offset: TPoint3D;
M: TMatrix3D;
begin
if Projection = TProjection.pjCamera then
Context.FillMesh(Vector3D(0, 0, 0), Vector3D(Width, Height, Depth), FPlane, AbsoluteOpacity)
else
begin
M := AbsoluteMatrix;
Offset := Point3D(Context.PixelToPixelPolygonOffset.X, Context.PixelToPixelPolygonOffset.Y, 0);
M.m41 := trunc(M.m41);
M.m42 := trunc(M.m42);
Context.SetMatrix(M);
Context.FillMesh(Vector3D(Offset.X + frac(FWidth / 2), Offset.Y + frac(FHeight / 2), 0), Vector3D(FWidth, FHeight, FDepth), FPlane, AbsoluteOpacity);
end;
end;
function TAbstractLayer3D.RayCastIntersect(const rayPos, rayDir: TVector3D;
var Intersection: TVector3D): Boolean;
var
IP: TVector3D;
begin
Result := inherited;
end;
procedure TAbstractLayer3D.MouseMove3D(Shift: TShiftState;
X, Y: Single; rayPos, rayDir: TVector3D);
var
P3, rPos, rDir: TVector3D;
begin
FDisableLayerEvent := True;
try
inherited;
finally
FDisableLayerEvent := False;
end;
if RayCastIntersect(rayPos, rayDir, P3) then
begin
P3 := AbsoluteToLocalVector(P3);
X := (((P3.X + (Width / 2)) / Width) * FLayerWidth);
Y := (((P3.Y + (Height / 2)) / Height) * FLayerHeight);
end
else
Exit;
LayerMouseMove(Shift, X, Y);
end;
procedure TAbstractLayer3D.MouseDown3D(Button: TMouseButton;
Shift: TShiftState; X, Y: Single; rayPos, rayDir: TVector3D);
var
P3, rPos, rDir: TVector3D;
begin
FDisableLayerEvent := True;
try
inherited;
finally
FDisableLayerEvent := False;
end;
if RayCastIntersect(rayPos, rayDir, P3) then
begin
P3 := AbsoluteToLocalVector(P3);
X := (((P3.X + (Width / 2)) / Width) * FLayerWidth);
Y := (((P3.Y + (Height / 2)) / Height) * FLayerHeight);
end
else
Exit;
LayerMouseDown(Button, Shift, X, Y);
end;
procedure TAbstractLayer3D.MouseUp3D(Button: TMouseButton; Shift: TShiftState;
X, Y: Single; rayPos, rayDir: TVector3D);
var
P3, rPos, rDir: TVector3D;
begin
FDisableLayerEvent := True;
try
inherited;
finally
FDisableLayerEvent := False;
end;
if RayCastIntersect(rayPos, rayDir, P3) then
begin
P3 := AbsoluteToLocalVector(P3);
X := (((P3.X + (Width / 2)) / Width) * FLayerWidth);
Y := (((P3.Y + (Height / 2)) / Height) * FLayerHeight);
end
else
Exit;
LayerMouseUp(Button, Shift, X, Y);
end;
procedure TAbstractLayer3D.LayerMouseMove(Shift: TShiftState; X, Y: Single);
begin
if Assigned(FOnLayerMouseMove) then
FOnLayerMouseMove(Self, Shift, trunc(X), trunc(Y));
end;
procedure TAbstractLayer3D.LayerMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
if Assigned(FOnLayerMouseDown) then
FOnLayerMouseDown(Self, Button, Shift, trunc(X), trunc(Y));
end;
procedure TAbstractLayer3D.LayerMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
if Assigned(FOnLayerMouseUp) then
FOnLayerMouseUp(Self, Button, Shift, trunc(X), trunc(Y));
end;
procedure TAbstractLayer3D.SetAlign(const Value: TAlignLayout);
var
AlignRoot: IAlignRoot;
begin
if FAlign <> Value then
begin
FAlign := Value;
if Projection <> TProjection.pjScreen then
FAlign := TAlignLayout.alNone;
if (FAlign <> TAlignLayout.alNone) and not(csLoading in ComponentState) and Supports(Parent, IAlignRoot, AlignRoot) then
AlignRoot.Realign;
end;
end;
procedure TAbstractLayer3D.SetAnchors(const Value: TAnchors);
begin
if FAnchors <> Value then
begin
FAnchors := Value;
{ if (FParent <> nil) and (FParent is TControl) and (FAnchors <> [akLeft, akTop]) then
begin
TControl(FParent).FNeedAlign := True;
end;}
end;
end;
procedure TAbstractLayer3D.SetDepth(const Value: Single);
begin
inherited SetDepth(0.01);
end;
function TAbstractLayer3D.GetAlign: TAlignLayout;
begin
Result := FAlign;
end;
function TAbstractLayer3D.GetAllowAlign: Boolean;
begin
Result := (Projection = TProjection.pjScreen) and Visible;
end;
function TAbstractLayer3D.GetAnchors: TAnchors;
begin
Result := FAnchors;
end;
function TAbstractLayer3D.GetHeight: single;
begin
Result := FHeight;
end;
function TAbstractLayer3D.GetPadding: TBounds;
begin
Result := FPadding;
end;
function TAbstractLayer3D.GetLeft: single;
begin
Result := Position.X - (Width / 2);
if Parent is TAbstractLayer3D then
Result := Result + TAbstractLayer3D(Parent).FLayerWidth / 2;
end;
function TAbstractLayer3D.GetTop: single;
begin
Result := Position.Y - (Height / 2);
if Parent is TAbstractLayer3D then
Result := Result + TAbstractLayer3D(Parent).FLayerHeight / 2;
end;
function TAbstractLayer3D.GetWidth: single;
begin
Result := Width;
end;
procedure TAbstractLayer3D.SetBounds(X, Y, AWidth, AHeight: Single);
begin
if Parent is TAbstractLayer3D then
begin
Position.X := X + (AWidth / 2) - TAbstractLayer3D(Parent).FLayerWidth / 2;
Position.Y := Y + (AHeight / 2) - TAbstractLayer3D(Parent).FLayerHeight / 2;
end
else
begin
Position.X := X + (AWidth / 2);
Position.Y := Y + (AHeight / 2);
end;
SetSize(AWidth, AHeight, Depth);
end;
procedure TAbstractLayer3D.LayerResized;
begin
Realign;
end;
procedure TAbstractLayer3D.Loaded;
begin
inherited;
Resize3D;
end;
procedure TAbstractLayer3D.Resize3D;
var
AlignRoot: IAlignRoot;
begin
inherited;
if (csLoading in ComponentState) then Exit;
if Projection = TProjection.pjCamera then
begin
FLayerWidth := Round(Width * FResolution);
FLayerHeight := Round(Height * FResolution);
end
else
begin
FLayerHeight := Round(Height);
FLayerWidth := Round(Width);
end;
if (FLayerWidth > 0) and (FLayerHeight > 0) then
LayerResized;
if not(csLoading in ComponentState) and Supports(Parent, IAlignRoot, AlignRoot) then
AlignRoot.Realign;
end;
procedure TAbstractLayer3D.PaddingChanged(Sender: TObject);
var
AlignRoot: IAlignRoot;
begin
if not(csLoading in ComponentState) and Supports(Parent, IAlignRoot, AlignRoot) then
AlignRoot.Realign;
end;
procedure TAbstractLayer3D.MarginsChanged(Sender: TObject);
begin
Realign;
end;
procedure TAbstractLayer3D.SetResolution(const Value: Integer);
begin
if FResolution <> Value then
begin
FResolution := Value;
if FResolution < 1 then
FResolution := 1;
if FResolution > 256 then
FResolution := 256;
Resize3D;
end;
end;
procedure TAbstractLayer3D.SetModulationColor(const Value: TAlphaColor);
begin
if FModulationColor <> Value then
begin
FModulationColor := Value;
Repaint;
end;
end;
procedure TAbstractLayer3D.SetProjection(const Value: TProjection);
var
i: Integer;
begin
if Value <> Projection then
begin
FProjection := Value;
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
if (Children[i] is TControl3D) then
TControl3D(FChildren[i]).Projection := Value;
if not (csLoading in ComponentState) then
begin
if FProjection = TProjection.pjScreen then
begin
SetSize(FLayerWidth, FLayerHeight, Depth);
if (FViewport <> nil) and (FViewport.Context <> nil) then
Position.Point := Point3D(FViewport.Context.Width / 2, FViewport.Context.Height / 2, 0);
end
else
begin
if FResolution > 0 then
SetSize(FLayerWidth / FResolution, FLayerHeight / FResolution, Depth);
Position.Point := Point3D(0, 0, 0);
end;
Repaint;
end;
end;
end;
{ TLayout3D }
constructor TLayout3D.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TLayout3D.Destroy;
begin
inherited;
end;
procedure TLayout3D.Render;
begin
end;
{ TImage3D }
constructor TImage3D.Create(AOwner: TComponent);
begin
inherited;
FBitmap := TBitmap.Create(0, 0);
FBitmap.OnChange := DoBitmapChanged;
end;
destructor TImage3D.Destroy;
begin
FBitmap.Free;
inherited;
end;
procedure TImage3D.DoBitmapChanged(Sender: TObject);
begin
Repaint;
end;
procedure TImage3D.SetBitmap(const Value: TBitmap);
begin
FBitmap.Assign(Value);
end;
procedure TImage3D.Apply;
var
B: TBitmap;
begin
inherited ;
B := FBitmap;
if FBitmap.ResourceBitmap <> nil then
B := FBitmap.ResourceBitmap;
if not B.IsEmpty then
begin
Context.SetContextState(TContextState.csTexLinear);
Context.SetContextState(TContextState.csTexModulate);
Context.SetTextureUnit(0, B);
end;
end;
{ TCustomBufferLayer3D }
constructor TCustomBufferLayer3D.Create(AOwner: TComponent);
begin
inherited;
FBuffer := TBitmap.Create(FLayerWidth, FLayerHeight);
end;
destructor TCustomBufferLayer3D.Destroy;
begin
FreeAndNil(FBuffer);
inherited;
end;
procedure TCustomBufferLayer3D.DoUpdateBuffer;
begin
if (FBuffer <> nil) and Assigned(FOnUpdateBuffer) then
FOnUpdateBuffer(Self);
end;
procedure TCustomBufferLayer3D.Apply;
begin
inherited;
DoUpdateBuffer;
Context.SetContextState(TContextState.csTexLinear);
Context.SetContextState(TContextState.csTexModulate);
Context.SetTextureUnit(0, FBuffer);
end;
function TCustomBufferLayer3D.GetBitmap: TBitmap;
begin
Result := FBuffer;
end;
procedure TCustomBufferLayer3D.LayerResized;
begin
inherited ;
if FBuffer <> nil then
FBuffer.SetSize(FLayerWidth, FLayerHeight);
end;
{ TCustomLayer3D }
type
TOpenControl = class(TControl);
constructor TCustomLayer3D.Create(AOwner: TComponent);
begin
inherited;
AddScene(Self);
FStyleLookup := 'backgroundstyle';
FNeedStyleLookup := True;
FAnimatedCaret := True;
ShowHint := True;
DisableDragHighlight := True;
Width := 8;
Depth := 8;
AutoCapture := True;
FDesignInteract := True;
FFill := TBrush.Create(TBrushKind.bkNone, TAlphaColors.White);
FFill.OnChanged := FillChanged;
end;
destructor TCustomLayer3D.Destroy;
begin
DeleteChildren;
if FChildren <> nil then
FreeAndNil(FChildren);
FreeAndNil(FFill);
RemoveScene(Self);
inherited;
end;
procedure TCustomLayer3D.AddUpdateRect(R: TRectF);
begin
if FDisableUpdate then
Exit;
if csDestroying in ComponentState then
Exit;
R := RectF(trunc(R.Left), trunc(R.Top), trunc(R.Right) + 1,
trunc(R.Bottom) + 1);
if not IntersectRect(R, RectF(0, 0, FLayerWidth, FLayerHeight)) then
Exit;
SetLength(FUpdateRects, Length(FUpdateRects) + 1);
FUpdateRects[High(FUpdateRects)] := R;
Repaint;
end;
procedure TCustomLayer3D.LayerResized;
begin
inherited;
AddUpdateRect(RectF(0, 0, FLayerWidth, FLayerHeight));
end;
procedure TCustomLayer3D.DoPaint(const Canvas: TCanvas; const ARect: TRectF);
begin
if Assigned(FOnPaint) then
FOnPaint(Self, Canvas, ARect);
end;
procedure TCustomLayer3D.DoUpdateBuffer;
var
i, j: Integer;
R: TRectF;
CallOnPaint, AllowPaint: Boolean;
State: Pointer;
begin
inherited ;
if FDrawing then Exit;
if Length(FUpdateRects) > 0 then
begin
FDrawing := True;
try
ApplyStyleLookup;
{ Split rects if rects too more }
if (Length(FUpdateRects) > 20) then
begin
for i := 1 to High(FUpdateRects) do
FUpdateRects[0] := UnionRect(FUpdateRects[0], FUpdateRects[i]);
SetLength(FUpdateRects, 1);
end;
if Canvas.BeginScene(@FUpdateRects) then
try
if (FFill.Kind = TBrushKind.bkNone) or
((FFill.Color and $FF000000 = 0) and (FFill.Kind = TBrushKind.bkSolid)) then
begin
for i := 0 to High(FUpdateRects) do
begin
if Transparency then
Canvas.ClearRect(FUpdateRects[i], 0)
else
Canvas.ClearRect(FUpdateRects[i], FFill.Color and $FFFFFF);
end;
end
else
begin
Canvas.Fill.Assign(FFill);
Canvas.FillRect(RectF(-1, -1, LayerWidth + 1, LayerHeight + 1), 0, 0, AllCorners, 1);
end;
{ reset }
Canvas.StrokeThickness := 1;
Canvas.StrokeCap := TStrokeCap.scFlat;
Canvas.StrokeJoin := TStrokeJoin.sjMiter;
Canvas.StrokeDash := TStrokeDash.sdSolid;
Canvas.Stroke.Kind := TBrushKind.bkSolid;
Canvas.Fill.Kind := TBrushKind.bkSolid;
{ Children }
CallOnPaint := False;
for i := 0 to ChildrenCount - 1 do
if (Children[i] is TControl) and
((TControl(FChildren[i]).Visible) or (not TControl(FChildren[i]).Visible and
(csDesigning in ComponentState) and not TControl(FChildren[i]).Locked)) then
with TOpenControl(FChildren[i]) do
begin
if (csDesigning in ComponentState) and not DesignVisible then
Continue;
if (RectWidth(UpdateRect) = 0) or (RectHeight(UpdateRect) = 0) then
Continue;
if (Self.Children[i] = FResourceLink) then
begin
if Self.Transparency then Continue;
if (Self.Fill.Kind <> TBrushKind.bkNone) then Continue;
if (Self.Fill.Kind = TBrushKind.bkSolid) and (Self.Fill.Color <> Fill.DefaultColor) then Continue;
end;
AllowPaint := False;
if (csDesigning in ComponentState) or InPaintTo then
AllowPaint := True;
if not AllowPaint then
begin
R := UnionRect(ChildrenRect, UpdateRect);
for j := 0 to High(FUpdateRects) do
if IntersectRect(FUpdateRects[j], R) then
begin
AllowPaint := True;
Break;
end;
end;
if AllowPaint then
begin
if not HasAfterPaintEffect then
ApplyEffect;
Painting;
DoPaint;
AfterPaint;
if HasAfterPaintEffect then
ApplyEffect;
end;
{ Call OnPaint after style painted }
if (Self.Children[i] = FResourceLink) then
begin
Self.Canvas.SetMatrix(IdentityMatrix);
Self.DoPaint(Self.Canvas, RectF(0, 0, LayerWidth, LayerHeight));
CallOnPaint := True;
end;
end;
{ Call OnPaint if style not loaded }
if not CallOnPaint then
begin
Canvas.SetMatrix(IdentityMatrix);
DoPaint(Canvas, RectF(0, 0, LayerWidth, LayerHeight));
end;
finally
Canvas.EndScene;
end;
finally
SetLength(FUpdateRects, 0);
FDrawing := False;
end;
end;
end;
procedure TCustomLayer3D.AddObject(AObject: TFmxObject);
begin
inherited AddObject(AObject);
if (AObject is TControl) then
TControl(AObject).SetNewScene(Self);
if (AObject is TControl) then
begin
TControl(AObject).RecalcOpacity;
TControl(AObject).RecalcAbsolute;
TControl(AObject).RecalcUpdateRect;
if (TControl(AObject).Align <> TAlignLayout.alNone) then
Realign
else
Invalidate;
end;
end;
procedure TCustomLayer3D.RemoveObject(AObject: TFmxObject);
begin
inherited;
if (AObject is TControl) then
TControl(AObject).SetNewScene(nil);
end;
procedure TCustomLayer3D.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FStyleBook) then
StyleBook := nil;
end;
function TCustomLayer3D.ObjectAtPoint(P: TPointF): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
IP, rPos, rDir: TVector3D;
VP: TPointF;
begin
Result := nil;
if (Context <> nil) and (GlobalProjection = Projection) then
begin
VP := P;
if FViewport <> nil then
VP := FViewport.ScreenToLocal(VP);
Context.Pick(VP.X, VP.Y, FProjection, rPos, rDir);
if CheckHitTest(HitTest) and RayCastIntersect(AbsoluteToLocalVector(rPos), Vector3DNormalize(AbsoluteToLocalVector(rDir)), IP) then
begin
if (Projection = TProjection.pjScreen) and (Vector3DLength(Vector3DSubtract(IP, rPos)) < GlobalDistance) then
begin
GlobalDistance := Vector3DLength(Vector3DSubtract(IP, rPos));
Result := Self;
end;
if (Projection = TProjection.pjCamera) and (Context.CurrentCamera <> nil) and
(Vector3DLength(Vector3DSubtract(IP, Context.CurrentCamera.AbsolutePosition)) < GlobalDistance) then
begin
GlobalDistance := Vector3DLength(Vector3DSubtract(IP, Context.CurrentCamera.AbsolutePosition));
Result := Self;
end;
end;
end;
if Result <> nil then
begin
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if NewObj <> nil then
begin
Result := NewObj;
Exit;
end;
end;
end;
end;
procedure TCustomLayer3D.SetFill(const Value: TBrush);
begin
FFill.Assign(Value);
end;
procedure TCustomLayer3D.FillChanged(Sender: TObject);
begin
SetLength(FUpdateRects, 0);
AddUpdateRect(RectF(0, 0, FLayerWidth, FLayerHeight));
end;
function TCustomLayer3D.GetActiveControl: TStyledControl;
begin
Result := FActiveControl;
end;
function TCustomLayer3D.GetCanvas: TCanvas;
begin
Result := FBuffer.Canvas;
end;
function TCustomLayer3D.GetComponent: TComponent;
begin
Result := Self;
end;
function TCustomLayer3D.GetContainerHeight: Single;
begin
Result := LayerHeight;
end;
function TCustomLayer3D.GetContainerWidth: Single;
begin
Result := LayerWidth;
end;
function TCustomLayer3D.GetUpdateRectsCount: Integer;
begin
Result := Length(FUpdateRects);
end;
procedure TCustomLayer3D.Invalidate;
begin
AddUpdateRect(RectF(0, 0, FLayerWidth, FLayerHeight));
end;
function TCustomLayer3D.GetUpdateRect(const Index: Integer): TRectF;
begin
Result := FUpdateRects[Index];
end;
function TCustomLayer3D.GetCaptured: IControl;
begin
if (Root <> nil) then
Result := Root.GetCaptured
else
Result := nil;
end;
procedure TCustomLayer3D.SetCaptured(const Value: IControl);
begin
if (Root <> nil) then
Root.SetCaptured(Value);
end;
function TCustomLayer3D.GetFocused: IControl;
begin
if (Root <> nil) then
Result := Root.GetFocused
else
Result := nil;
end;
procedure TCustomLayer3D.SetFocused(const Value: IControl);
begin
if (Root <> nil) then
Root.SetFocused(Value);
end;
function TCustomLayer3D.GetMousePos: TPointF;
begin
Result := FMousePos;
end;
function TCustomLayer3D.GetStyleObject: TControl;
var
Obj: TFmxObject;
ResourceObject: TControl;
S: TStream;
StyleName: string;
begin
ResourceObject := nil;
if (FStyleLookup <> '') then
begin
{ style }
Obj := TControl(FindStyleResource(FStyleLookup));
if Obj = nil then
if Application.DefaultStyles <> nil then
Obj := TControl(Application.DefaultStyles.FindStyleResource(FStyleLookup));
if Obj = nil then
Obj := FMX.Types.FindStyleResource(FStyleLookup);
if (Obj <> nil) and (Obj is TControl) then
begin
ResourceObject := TControl(Obj.Clone(nil));
ResourceObject.StyleName := '';
end;
end;
if (ResourceObject = nil) and (Application.DefaultStyles <> nil) then
begin
if FStyleLookup <> '' then
begin
StyleName := FStyleLookup;
ResourceObject := TControl(FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil));
end;
if ResourceObject = nil then
begin
StyleName := ClassName + 'style';
Delete(StyleName, 1, 1); // just remove T
ResourceObject := TControl(FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil))
end;
if (ResourceObject = nil) and (Application.DefaultStyles <> nil) then
begin
if FStyleLookup <> '' then
begin
StyleName := FStyleLookup;
ResourceObject := TControl(Application.DefaultStyles.FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil));
end;
if ResourceObject = nil then
begin
StyleName := ClassName + 'style';
Delete(StyleName, 1, 1); // just remove T
ResourceObject := TControl(Application.DefaultStyles.FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil))
else
begin
// try parent Class
StyleName := ClassParent.ClassName + 'style';
Delete(StyleName, 1, 1); // just remove T
ResourceObject := TControl(Application.DefaultStyles.FindStyleResource(StyleName));
if ResourceObject <> nil then
ResourceObject := TControl(ResourceObject.Clone(nil));
end;
end;
end;
end;
Result := ResourceObject;
end;
procedure TCustomLayer3D.ApplyStyleLookup;
var
ResourceObject: TControl;
begin
if FNeedStyleLookup then
begin
FNeedStyleLookup := False;
ResourceObject := GetStyleObject;
if ResourceObject <> nil then
begin
if FResourceLink <> nil then
begin
FResourceLink.Free;
FResourceLink := nil;
end;
ResourceObject.Align := TAlignLayout.alContents;
ResourceObject.DesignVisible := True;
FResourceLink := ResourceObject;
AddObject(ResourceObject);
{ bring to front }
FChildren.Remove(ResourceObject);
FChildren.Insert(0, ResourceObject);
Realign;
{ }
ResourceObject.Stored := False;
ResourceObject.Lock;
end;
end;
end;
procedure TCustomLayer3D.BeginDrag;
begin
FDragging := True;
FDownPos := FMousePos;
Capture;
end;
procedure TCustomLayer3D.BeginResize;
begin
FResizing := True;
FDownPos := FMousePos;
FResizePos := PointF(Position.X, Position.Y);
FResizeStartPos := PointF(Round(Position.X - Width / 2), Round(Position.Y - Height / 2));
FResizeSize := PointF(Width, Height);
FDownSize := FResizeSize;
Capture;
end;
function TCustomLayer3D.GetStyleBook: TStyleBook;
begin
Result := FStyleBook;
end;
function TCustomLayer3D.ScreenToLocal(P: TPointF): TPointF;
var
P3, RayPos, RayDir: TVector3D;
begin
if Context = nil then
begin
Result := P;
Exit;
end;
if (FViewport <> nil) then
Result := FViewport.ScreenToLocal(P)
else
Result := P;
Context.Pick(Result.X, Result.Y, Projection, RayPos, RayDir);
rayPos := AbsoluteToLocalVector(rayPos);
rayDir := Vector3DNormalize(AbsoluteToLocalVector(rayDir));
if RayCastIntersect(rayPos, rayDir, P3) then
begin
P3 := AbsoluteToLocalVector(P3);
Result.X := (((P3.X + (Width / 2)) / Width) * FLayerWidth);
Result.Y := (((P3.Y + (Height / 2)) / Height) * FLayerHeight);
end
else
Result := PointF(-$FFFF, -$FFFF);
end;
function TCustomLayer3D.LocalToScreen(P: TPointF): TPointF;
var
P3: TPoint3D;
begin
if Context = nil then
begin
Result := P;
Exit;
end;
P3 := Point3D(-(Width / 2) + (P.X / FLayerWidth) * Width, -(Height / 2) + (P.Y / FLayerHeight) * Height, 0);
P3 := Context.WorldToScreen(Projection, LocalToAbsolute3D(P3));
Result := PointF(P3.X, P3.Y);
if (FViewport <> nil) then
Result := FViewport.LocalToScreen(Result);
end;
function TCustomLayer3D.GetTransparency: Boolean;
begin
Result := FTransparency;
end;
procedure TCustomLayer3D.UpdateStyle;
var
i: Integer;
begin
for i := 0 to ChildrenCount - 1 do
Children[i].UpdateStyle;
end;
procedure TCustomLayer3D.SetStyleBook(const Value: TStyleBook);
begin
if FStyleBook <> Value then
begin
if FStyleBook <> nil then
FStyleBook.RemoveSceneUpdater(Self);
FStyleBook := Value;
if FStyleBook <> nil then
FStyleBook.AddSceneUpdater(Self);
UpdateStyle;
end;
end;
function TCustomLayer3D.FindTarget(P: TPointF; const Data: TDragObject): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
Accept: Boolean;
LP: TPointF;
begin
Result := nil;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.Visible then Continue;
if not NewObj.HitTest then Continue;
NewObj := NewObj.FindTarget(P, Data);
if NewObj <> nil then
begin
Result := NewObj;
Exit;
end;
end;
end;
procedure TCustomLayer3D.SetVisible(const Value: Boolean);
begin
inherited SetVisible(Value);
if Visible then
AddUpdateRect(RectF(0, 0, FLayerWidth, FLayerHeight));
end;
procedure TCustomLayer3D.SetActiveControl(AControl: TStyledControl);
begin
if AControl <> FActiveControl then
begin
FActiveControl := AControl;
if (FActiveControl <> nil) and not(csLoading in ComponentState) then
FActiveControl.SetFocus;
end;
end;
procedure TCustomLayer3D.SetStyleLookup(const Value: string);
begin
FStyleLookup := Value;
FNeedStyleLookup := True;
if not (csLoading in ComponentState) then
begin
ApplyStyleLookup;
end;
end;
function TCustomLayer3D.GetAnimatedCaret: Boolean;
begin
Result := FAnimatedCaret;
end;
{ TTextLayer3D }
constructor TTextLayer3D.Create(AOwner: TComponent);
begin
inherited;
ZWrite := False;
HitTest := False;
FText := TText.Create(Self);
FText.Locked := True;
FText.Stored := False;
FText.Align := TAlignLayout.alContents;
FText.Parent := Self;
end;
procedure TTextLayer3D.ApplyStyleLookup;
begin
end;
function TTextLayer3D.GetBrush: TBrush;
begin
Result := FText.Fill;
end;
function TTextLayer3D.GetFont: TFont;
begin
Result := FText.Font;
end;
function TTextLayer3D.GetText: string;
begin
Result := FText.Text;
end;
procedure TTextLayer3D.SetBrush(const Value: TBrush);
begin
FText.Fill.Assign(Value);
end;
procedure TTextLayer3D.SetFont(const Value: TFont);
begin
FText.Font.Assign(Value);
end;
procedure TTextLayer3D.SetText(const Value: string);
begin
FText.Text := Value;
end;
initialization
RegisterFmxClasses([TLayout3D, TImage3D, TBufferLayer3D, TLayer3D, TTextLayer3D]);
end.
|
unit Ths.Erp.Database.Singleton;
interface
{$I ThsERP.inc}
uses
System.IniFiles, System.SysUtils, System.Classes, System.StrUtils,
System.Math, System.Variants,
Winapi.Windows, Winapi.Messages,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ImgList,
Vcl.Imaging.PngImage, Vcl.DBGrids,
Data.DB, FireDAC.Stan.Param, FireDAC.Comp.Client
, Ths.Erp.Helper.Edit
, Ths.Erp.Database
, Ths.Erp.Database.Table
, Ths.Erp.Database.Table.SysUser
, Ths.Erp.Database.Table.SysLang
, Ths.Erp.Database.Table.AyarHaneSayisi
, Ths.Erp.Database.Table.SysApplicationSettings
, Ths.Erp.Database.Table.SysApplicationSettingsOther;
type
TSingletonDB = class(TObject)
strict private
class var FInstance: TSingletonDB;
constructor CreatePrivate;
private
FDataBase: TDatabase;
FUser: TSysUser;
FHaneMiktari: TAyarHaneSayisi;
FApplicationSettings: TSysApplicationSettings;
FApplicationSettingsOther: TSysApplicationSettingsOther;
FSysLang: TSysLang;
FImageList32: TImageList;
FImageList16: TImageList;
public
/// <summary>
/// Database sınıfına ulaşılıyor. Bazı fonksiyonlar burada GetToday GetNow veya runCustomSQL gibi
/// </summary>
property DataBase: TDatabase read FDataBase write FDataBase;
/// <summary>
/// Giriş yapan kullanıcı bilgilerine bu tablo bilgisinden ulaşalıyor.
/// <example>
/// <code lang="Delphi">TSingletonDB.GetInstance.User.UserName.Value</code>
/// </example>
/// </summary>
property User: TSysUser read FUser write FUser;
/// <summary>
/// Virgüllü sayılarda hane sayısı değerlerine buradan ulaşılıyor. Bu ayara göre işlemler yapılacak.
/// <example>
/// <code lang="Delphi">TSingletonDB.GetInstance.HaneMiktari.SatisMiktar.Value</code>
/// </example>
/// </summary>
property HaneMiktari: TAyarHaneSayisi read FHaneMiktari write FHaneMiktari;
/// <summary>
/// Uygulama ayarlarına bu tablo bilgisinden ulaşılıyor.
/// <example>
/// <code lang="Delphi">TSingletonDB.GetInstance.ApplicationSetting.Unvan.Value</code>
/// </example>
/// </summary>
property ApplicationSettings: TSysApplicationSettings read FApplicationSettings write FApplicationSettings;
/// <summary>
/// Uygulamanın özel ayarlarına bu tablo bilgisinden ulaşılıyor.
/// <example>
/// <code lang="Delphi">TSingletonDB.GetInstance.ApplicationSettingsOther.xxx.Value</code>
/// </example>
/// </summary>
property ApplicationSettingsOther: TSysApplicationSettingsOther read FApplicationSettingsOther write FApplicationSettingsOther;
/// <summary>
/// Uygulama açılırken hangi dil ile açışmışsa o dilin bilgileri alınıyor.
/// <example>
/// <code lang="Delphi">TSingletonDB.GetInstance.SysLang.Langeuage.Valye</code>
/// </example>
/// </summary>
property SysLang: TSysLang read FSysLang write FSysLang;
/// <summary>
/// 32x32 px boyutunda kullanılan resimleri saklamak için kullanılıyor. Genelde butonlarda kullanılıyor.
/// </summary>
property ImageList32: TImageList read FImageList32 write FImageList32;
/// <summary>
/// 16x16 px boyutunda kullanılan resimleri saklamak için kullanılıyor. Genelde menülerde kullanılıyor.
/// </summary>
property ImageList16: TImageList read FImageList16 write FImageList16;
constructor Create;
class function GetInstance(): TSingletonDB;
destructor Destroy; override;
function GetGridDefaultOrderFilter(pKey: string; pIsOrder: Boolean): string;
function GetIsRequired(pTableName, pFieldName: string): Boolean;
function GetMaxLength(pTableName, pFieldName: string): Integer;
function GetQualityFormNo(pTableName: string; pIsInput: Boolean): string;
procedure FillColNameForColWidth(pComboBox: TComboBox; pTableName: string);
function GetDistinctColumnName(pTableName: string): TStringList;
function AddImalgeToImageList(pFileName: string; pList: TImageList; out pImageIndex: Integer): Boolean;
function FillComboFromLangData(pComboBox: TComboBox; pBaseTableName, pBaseColName: string; pRowID: Integer): string;
end;
function ColumnFromIDCol(pRawTableColName, pRawTableName, pDataColName,
pVirtualColName, pDataTableName: string; pIsIDReference: Boolean = True; pIsNumericVal: Boolean = False): string;
function TranslateText(pDefault, pCode, pTip: string; pTable: string=''): string;
function FormatedVariantVal(pType: TFieldType; pVal: Variant): Variant; overload;
function FormatedVariantVal(pField: TFieldDB): Variant; overload;
function Login(pUserName,pPassword: string): Integer;
function ReplaceToRealColOrTableName(const pTableName: string): string;
function ReplaceRealColOrTableNameTo(const pTableName: string): string;
function getFormCaptionByLang(pFormName, pDefaultVal: string): string;
/// <summary>
/// Parametre girilen Tablo adı ve Tablodaki Column Name bilgisine göre
/// sys_lang_data tablosundan programın açılan dil ayarına göre column
/// bilgsini döndürüyor. Bunu fonksiyon tek başına kullanılamaz.
/// Bu fonksiyon SELECT kodları içinde kullanılır.
/// <param name="pBaseTableName">Database Table Name</param>
/// <param name="pBaseColName">Database Table Column Name</param>
/// <example>
/// <code lang="Delphi">getRawDataByLang(TableName, FBirim.FieldName)</code>
/// </example>
/// </summary>
function getRawDataByLang(pBaseTableName, pBaseColName: string): string;
/// <summary>
/// İstenilen Query ye Parametre eklemek için kullanılıyor. Insert ve Update kodları içinde kullanılıyor.
/// <param name="pQuery">FireDac Query</param>
/// <param name="pField">FieldDB tipindeki Field</param>
/// <example>
/// <code lang="Delphi">NewParamForQuery(QueryOfInsert, FBirim)</code>
/// </example>
/// </summary>
procedure NewParamForQuery(pQuery: TFDQuery; pField: TFieldDB);
/// <summary>
/// Bu fonksiyon DBGrid üzerinde gösterilen sütunların genişlik değerini değiştirmek için kullanılır.
/// Yaptığı iş hızlıca <b>sys_grid_col_width</b> tablosundaki <b>column_width</b>
/// değerini hızlıca güncellemek için kullanılır. Açık DBGrid(output form)
/// ekranındaki sütun genişliğinin hızlıca görselden ayarlamak için bu fonksiyon yazildi.
/// <param name="pTableName">Database Table Name</param>
/// <param name="pColName">Database Table Column Name</param>
/// <param name="pColWidth">DBGrid Column Width</param>
/// <example>
/// <code lang="Delphi">UpdateColWidth(olcu_birimi, birim, 100)</code>
/// </example>
/// </summary>
function UpdateColWidth(pTableName: string; pGrid: TDBGrid): Boolean;
var
SingletonDB: TSingletonDB;
vLangContent, vLangContent2: string;
implementation
uses
Ths.Erp.Database.Table.View.SysViewColumns
, Ths.Erp.Database.Table.SysGridDefaultOrderFilter
, Ths.Erp.Constants
, Ths.Erp.Database.Table.SysGridColWidth
, Ths.Erp.Database.Table.SysQualityFormNumber
, Ths.Erp.Functions
;
function FormatedVariantVal(pType: TFieldType; pVal: Variant): Variant;
var
vValueInt: Integer;
vValueDouble: Double;
vValueBool: Boolean;
vValueDateTime: TDateTime;
begin
if (pType = ftString)
or (pType = ftMemo)
or (pType = ftWideString)
or (pType = ftWideMemo)
or (pType = ftWideString)
then
Result := IfThen(not VarIsNull(pVal), VarToStr(pVal), '')
else
if (pType = ftSmallint)
or (pType = ftShortint)
or (pType = ftInteger)
or (pType = ftLargeint)
or (pType = ftWord)
then
begin
if not VarIsNull(pVal) then
Result := IfThen(TryStrToInt(pVal, vValueInt), VarToStr(pVal).ToInteger, 0)
else
Result := 0;
end
else if (pType = ftDate) then
begin
if not VarIsNull(pVal) then
begin
if TryStrToDate(pVal, vValueDateTime) then
Result := DateToStr(VarToDateTime(pVal))
else
Result := 0;
end
else
Result := 0;
end
else if (pType = ftDateTime) then
begin
if not VarIsNull(pVal) then
begin
if TryStrToDateTime(pVal, vValueDateTime) then
Result := DateTimeToStr(VarToDateTime(pVal))
else
Result := 0;
end
else
Result := 0;
end
else if (pType = ftTime) then
begin
if not VarIsNull(pVal) then
begin
if TryStrToTime(pVal, vValueDateTime) then
Result := TimeToStr(VarToDateTime(pVal))
else
Result := 0;
end
else
Result := 0;
end
else if (pType = ftTimeStamp) then
begin
if not VarIsNull(pVal) then
begin
if TryStrToTime(pVal, vValueDateTime) then
Result := DateTimeToStr(VarToDateTime(pVal))
else
Result := 0;
end
else
Result := 0;
end
else
if (pType = ftFloat)
or (pType = ftCurrency)
or (pType = ftSingle)
or (pType = ftBCD)
or (pType = ftFMTBcd)
then
begin
if not VarIsNull(pVal) then
Result := IfThen(TryStrToFloat(pVal, vValueDouble), VarToStr(pVal).ToDouble, 0.0)
else
Result := 0.0;
end
else if (pType = ftBoolean) then
begin
if not VarIsNull(pVal) then
begin
if TryStrToBool(pVal, vValueBool) then
Result := VarToStr(pVal).ToBoolean
else
Result := False;
end
else
Result := False;
end
else if (pType = ftBlob) then
Result := pVal
else
Result := pVal;
end;
function FormatedVariantVal(pField: TFieldDB): Variant;
var
vValueInt: Integer;
vValueDouble: Double;
vValueBool: Boolean;
vValueDateTime: TDateTime;
begin
if (pField.FieldType = ftString)
or (pField.FieldType = ftMemo)
or (pField.FieldType = ftWideString)
or (pField.FieldType = ftWideMemo)
or (pField.FieldType = ftWideString)
then
Result := IfThen(not VarIsNull(pField.Value), VarToStr(pField.Value), '')
else
if (pField.FieldType = ftSmallint)
or (pField.FieldType = ftShortint)
or (pField.FieldType = ftInteger)
or (pField.FieldType = ftLargeint)
or (pField.FieldType = ftWord)
then
begin
if not VarIsNull(pField.Value) then
Result := IfThen(TryStrToInt(pField.Value, vValueInt), VarToStr(pField.Value).ToInteger, 0)
else
Result := 0;
end
else if (pField.FieldType = ftDate) then
begin
if not VarIsNull(pField.Value) then
Result := IfThen(TryStrToDate(pField.Value, vValueDateTime), StrToDate(VarToStr(pField.Value)), 0)
else
Result := 0;
end
else if (pField.FieldType = ftDateTime) then
begin
if not VarIsNull(pField.Value) then
Result := IfThen(TryStrToDateTime(pField.Value, vValueDateTime), StrToDateTime(VarToStr(pField.Value)), 0)
else
Result := 0;
end
else
if (pField.FieldType = ftTime)
or (pField.FieldType = ftTimeStamp)
then
begin
if not VarIsNull(pField.Value) then
Result := IfThen(TryStrToTime(pField.Value, vValueDateTime), StrToTime(VarToStr(pField.Value)), 0)
else
Result := 0;
end
else
if (pField.FieldType = ftFloat)
or (pField.FieldType = ftCurrency)
or (pField.FieldType = ftSingle)
or (pField.FieldType = ftBCD)
or (pField.FieldType = ftFMTBcd)
then
begin
if not VarIsNull(pField.Value) then
Result := IfThen(TryStrToFloat(pField.Value, vValueDouble), VarToStr(pField.Value).ToDouble, 0.0)
else
Result := 0.0;
end
else if (pField.FieldType = ftBoolean) then
begin
if not VarIsNull(pField.Value) then
begin
if TryStrToBool(pField.Value, vValueBool) then
Result := VarToStr(pField.Value).ToBoolean
else
Result := False;
end
else
Result := False;
end
else if (pField.FieldType = ftBlob) then
Result := pField.Value
else
Result := pField.Value;
end;
function ColumnFromIDCol(pRawTableColName, pRawTableName, pDataColName,
pVirtualColName, pDataTableName: string; pIsIDReference: Boolean = True;
pIsNumericVal: Boolean = False): string;
var
vSP: TFDStoredProc;
vRefColName: string;
begin
if pIsIDReference then
vRefColName := 'id'
else
vRefColName := pRawTableColName;
if pIsNumericVal then
Result := '(SELECT raw' + pRawTableName + '.' + pRawTableColName + ' FROM ' + pRawTableName + ' as raw' + pRawTableName +
' WHERE raw' + pRawTableName + '.' + vRefColName + '=' + pDataTableName + '.' + pDataColName + ') as ' + pVirtualColName
else
begin
vSP := TSingletonDB.GetInstance.DataBase.NewStoredProcedure;
try
vSP.StoredProcName := 'get_lang_text';
vSP.Prepare;
vSP.ParamByName('_default_value').Value := '';
vSP.ParamByName('_table_name').Value := QuotedStr(pRawTableName);
vSP.ParamByName('_column_name').Value := QuotedStr(pRawTableColName);
vSP.ParamByName('_row_id').Value := IntToStr(0);
vSP.ParamByName('_lang').Value := QuotedStr(TSingletonDB.GetInstance.DataBase.ConnSetting.Language);
vSP.ExecProc;
Result := vSP.ParamByName('result').AsString;
Result :=
'get_lang_text(' +
'(SELECT raw' + pRawTableName + '.' + pRawTableColName + ' FROM ' + pRawTableName + ' as raw' + pRawTableName +
' WHERE raw' + pRawTableName + '.' + vRefColName + '=' + pDataTableName + '.' + pDataColName + ')' + ',' +
QuotedStr(pRawTableName) + ',' +
QuotedStr(pRawTableColName) + ', ' +
pDataColName + ', ' +
QuotedStr(TSingletonDB.GetInstance.DataBase.ConnSetting.Language) + ') as ' + pVirtualColName;
finally
vSP.Free;
end;
end;
end;
//function ColumnFromOtherTable(pTableNameData, pColNameData, pKeyColNameData,
// pTableNameOther, pColNameOtherData, pTableName, pVirtualColName: string): string;
//begin
//
// 'SELECT bolum FROM ayar_personel_bolum WHERE id=(SELECT bolum_id FROM ayar_personel_birim WHERE id=2)'
//
// Result := '(SELECT raw' + pRawTableName + '.' + pRawTableColName + ' FROM ' + pRawTableName + ' as raw' + pRawTableName +
// ' WHERE raw' + pRawTableName + '.id=' + pDataTableName + '.' + pDataColName + ') as ' + pVirtualColName
//end;
function TranslateText(pDefault, pCode, pTip: string; pTable: string=''): string;
var
Query: TFDQuery;
vFilter: string;
begin
Result := pDefault;
vFilter := 'lang=' + QUERY_PARAM_CHAR + 'lang AND code=' + QUERY_PARAM_CHAR + 'code AND content_type=' + QUERY_PARAM_CHAR + 'content_type';
if pTable <> '' then
vFilter := vFilter + ' AND table_name=' + QUERY_PARAM_CHAR + 'table_name';
if TSingletonDB.GetInstance.DataBase.Connection.Connected then
begin
Query := TSingletonDB.GetInstance.DataBase.NewQuery;
try
with Query do
begin
Close;
SQL.Text := 'SELECT val FROM sys_lang_gui_content ' +
'WHERE 1=1 AND ' + vFilter;
ParamByName('lang').Value := TSingletonDB.GetInstance.DataBase.ConnSetting.Language;
ParamByName('code').Value := pCode;
ParamByName('content_type').Value := pTip;
if pTable <> '' then
ParamByName('table_name').Value := pTable;
Open;
if not (Fields.Fields[0].IsNull) then
Result := Fields.Fields[0].AsString;
if Result = '' then
Result := pDefault;
EmptyDataSet;
Close;
end;
finally
Query.Free;
end;
end;
end;
function Login(pUserName, pPassword: string): Integer;
begin
Result := 0;
end;
function ReplaceToRealColOrTableName(const pTableName: string): string;
begin
Result := StringReplace(pTableName, ' ', '_', [rfReplaceAll]);
Result := LowerCase(Result);
end;
function ReplaceRealColOrTableNameTo(const pTableName: string): string;
var
n1: Integer;
vDump: string;
begin
vDump := StringReplace(pTableName, '_', ' ', [rfReplaceAll]);
if vDump = '' then
Result := ''
else
begin
Result := Uppercase(vDump[1]);
for n1 := 2 to Length(vDump) do
begin
if vDump[n1-1] = ' ' then
Result := Result + Uppercase(vDump[n1])
else
Result := Result + Lowercase(vDump[n1]);
end;
end;
end;
function getRawDataByLang(pBaseTableName, pBaseColName: string): string;
begin
if TSingletonDB.GetInstance.DataBase.ConnSetting.Language <> TSingletonDB.GetInstance.ApplicationSettings.AppMainLang.Value then
begin
Result :=
'get_lang_text(' + pBaseColName + ', ' + QuotedStr(pBaseTableName) + ', ' +
QuotedStr(pBaseColName) + ', id, ' +
QuotedStr(TSingletonDB.GetInstance.DataBase.ConnSetting.Language) + ')::varchar as ' + pBaseColName;
end
else
Result := pBaseTableName + '.' + pBaseColName;
{
'(SELECT ' +
' CASE WHEN ' +
' (SELECT b.val FROM sys_lang_data_content b ' +
' WHERE b.table_name=' + QuotedStr(pBaseTableName) +
' AND b.column_name=' + QuotedStr(pBaseColName) +
' AND b.lang=' + QuotedStr(TSingletonDB.GetInstance.DataBase.ConnSetting.Language) +
' AND b.row_id = ' + pBaseTableName + '.id) IS NULL THEN ' + pBaseTableName + '.' + pBaseColName +
' ELSE ' +
' (SELECT b.val FROM sys_lang_data_content b ' +
' WHERE b.table_name=' + QuotedStr(pBaseTableName) +
' AND b.column_name=' + QuotedStr(pBaseColName) +
' AND b.lang=' + QuotedStr(TSingletonDB.GetInstance.DataBase.ConnSetting.Language) +
' AND b.row_id = ' + pBaseTableName + '.id)' +
' END ' +
')::varchar as ' + pBaseColName }
end;
function getFormCaptionByLang(pFormName, pDefaultVal: string): string;
begin
Result := TranslateText(pDefaultVal, pFormName, LngFormCaption);
end;
procedure NewParamForQuery(pQuery: TFDQuery; pField: TFieldDB);
begin
pQuery.Params.ParamByName(pField.FieldName).DataType := pField.FieldType;
pQuery.Params.ParamByName(pField.FieldName).Value := FormatedVariantVal(pField.FieldType, pField.Value);
if pField.IsNullable or pField.IsFK then
begin
if (pField.FieldType = ftString)
or (pField.FieldType = ftMemo)
or (pField.FieldType = ftWideString)
or (pField.FieldType = ftWideMemo)
or (pField.FieldType = ftWord)
then
begin
if pQuery.Params.ParamByName(pField.FieldName).Value = '' then
pQuery.Params.ParamByName(pField.FieldName).Value := Null
end
else
if (pField.FieldType = ftSmallint)
or (pField.FieldType = ftShortint)
or (pField.FieldType = ftInteger)
or (pField.FieldType = ftLargeint)
or (pField.FieldType = ftByte)
then
begin
if pQuery.Params.ParamByName(pField.FieldName).Value = 0 then
pQuery.Params.ParamByName(pField.FieldName).Value := Null
end
else if (pField.FieldType = ftDate) then
begin
if pQuery.Params.ParamByName(pField.FieldName).Value = 0 then
pQuery.Params.ParamByName(pField.FieldName).Value := Null
end
else if (pField.FieldType = ftDateTime) then
begin
if pQuery.Params.ParamByName(pField.FieldName).Value = 0 then
pQuery.Params.ParamByName(pField.FieldName).Value := Null
end
else
if (pField.FieldType = ftTime)
or (pField.FieldType = ftTimeStamp)
then
begin
if pQuery.Params.ParamByName(pField.FieldName).Value = 0 then
pQuery.Params.ParamByName(pField.FieldName).Value := Null;
end
else
if (pField.FieldType = ftFloat)
or (pField.FieldType = ftCurrency)
or (pField.FieldType = ftSingle)
or (pField.FieldType = ftBCD)
or (pField.FieldType = ftFMTBcd)
then
begin
if pQuery.Params.ParamByName(pField.FieldName).Value = 0 then
pQuery.Params.ParamByName(pField.FieldName).Value := Null;
end;
if pQuery.Params.ParamByName(pField.FieldName).Value = Null then
pQuery.Params.ParamByName(pField.FieldName).DataType := pField.FieldType;
end;
end;
function UpdateColWidth(pTableName: string; pGrid: TDBGrid): Boolean;
var
vSysGridColWidth: TSysGridColWidth;
n1, n2: Integer;
begin
Result := True;
try
vSysGridColWidth := TSysGridColWidth.Create(TSingletonDB.GetInstance.DataBase);
try
vSysGridColWidth.Clear;
vSysGridColWidth.SelectToList(' AND ' + vSysGridColWidth.TableName + '.' + vSysGridColWidth.TableName1.FieldName + '=' + QuotedStr(ReplaceRealColOrTableNameTo(pTableName)), False, False);
for n1 := 0 to pGrid.Columns.Count-1 do
if pGrid.Columns[n1].Visible then
for n2 := 0 to vSysGridColWidth.List.Count-1 do
if TSysGridColWidth(vSysGridColWidth.List[n2]).ColumnName.Value = ReplaceRealColOrTableNameTo(pGrid.Columns[n1].FieldName) then
begin
TSysGridColWidth(vSysGridColWidth.List[n2]).ColumnWidth.Value := pGrid.Columns[n1].Width;
TSysGridColWidth(vSysGridColWidth.List[n2]).Update(False);
end;
finally
vSysGridColWidth.Free;
end;
except
Result := False;
end;
end;
function TSingletonDB.AddImalgeToImageList(pFileName: string; pList: TImageList;
out pImageIndex: Integer): Boolean;
var
mImage: TPicture;
mImagePng: TPngImage;
mBitmap: TBitmap;
Begin
Result := False;
pImageIndex := -1;
if pList <> nil then
begin
if FileExists(pFilename, True) then
begin
mImage := TPicture.Create;
mImagePng := TPngImage.Create;
try
try
//dosya bulunamazsa hata vermemesi için try except yapıldı
mImagePng.LoadFromFile(pFileName);
mImage.Graphic := mImagePng;
except
end;
if (mImage.Width > 0) and (mImage.Height > 0) then
begin
mBitmap := TBitmap.Create;
try
mBitmap.Assign(mImage.Graphic);
pImageIndex := pList.add(mBitmap, nil);
Result := True;
finally
mBitmap.Free;
end;
end
finally
mImage.Free;
mImagePng.Free;
end;
end;
end;
end;
constructor TSingletonDB.Create();
begin
raise Exception.Create('Object Singleton');
end;
constructor TSingletonDB.CreatePrivate;
var
nIndex: Integer;
vPath: string;
procedure AddImageToImageList(pImageList: TImageList);
begin
AddImalgeToImageList(vPath + 'accept' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'add' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'add_data' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'application' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'archive' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'attachment' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'back' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'calculator' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'calendar' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'chart' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'clock' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'close' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'col_width' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'comment' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'community_users' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'computer' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'copy' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'customer' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'database' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'down' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'excel_exports' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'excel_imports' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'favorite' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'file_doc' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'file_pdf' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'file_xls' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'filter' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'filter_add' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'filter_clear' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'folder' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'forward_new_mail' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'help' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'home' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'image' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'info' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'lang' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'lock' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'mail' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'money' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'movie' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'next' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'note' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'page' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'page_search' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'pause' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'play' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'port' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'preview' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'print' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'process' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'record' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'remove' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'repeat' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'rss' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'search' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'server' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'stock' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'stock_add' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'stock_delete' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'sum' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'up' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'user_he' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'user_password' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'user_she' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'users' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'warning' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'period' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'quality' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'exchange_rate' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'bank' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'bank_branch' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'city' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'country' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'stock_room' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'measure_unit' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'duration_finance' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'settings' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'sort_asc' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
AddImalgeToImageList(vPath + 'sort_desc' + '.' + FILE_EXTENSION_PNG, pImageList, nIndex);
end;
begin
inherited Create;
if Self.FDataBase = nil then
FDataBase := TDatabase.Create;
if Self.FUser = nil then
FUser := TSysUser.Create(Self.FDataBase);
if Self.FHaneMiktari = nil then
FHaneMiktari := TAyarHaneSayisi.Create(Self.FDataBase);
if Self.FApplicationSettings = nil then
FApplicationSettings := TSysApplicationSettings.Create(Self.FDataBase);
if Self.FApplicationSettingsOther = nil then
FApplicationSettingsOther := TSysApplicationSettingsOther.Create(Self.FDataBase);
if Self.FSysLang = nil then
FSysLang := TSysLang.Create(Self.DataBase);
if Self.ImageList32 = nil then
begin
FImageList32 := TImageList.Create(nil);
FImageList32.Clear;
FImageList32.SetSize(32, 32);
FImageList32.Masked := False;
FImageList32.ColorDepth := cd32Bit;
FImageList32.DrawingStyle := dsTransparent;
vPath := ExtractFilePath(Application.ExeName) + PATH_ICONS_32 + '/';
AddImageToImageList(FImageList32);
end;
if Self.ImageList16 = nil then
begin
FImageList16 := TImageList.Create(nil);
FImageList16.Clear;
FImageList16.SetSize(16, 16);
FImageList16.Masked := False;
FImageList16.ColorDepth := cd32Bit;
FImageList16.DrawingStyle := dsTransparent;
vPath := ExtractFilePath(Application.ExeName) + PATH_ICONS_16 + '/';
AddImageToImageList(FImageList16);
end;
end;
destructor TSingletonDB.Destroy();
begin
if SingletonDB <> Self then
SingletonDB := nil;
if Assigned(FUser) then
FUser.Free;
if Assigned(FHaneMiktari) then
FHaneMiktari.Free;
if Assigned(FDataBase) then
FDataBase.Free;
if Assigned(FApplicationSettings) then
FApplicationSettings.Free;
if Assigned(FApplicationSettingsOther) then
FApplicationSettingsOther.Free;
if Assigned(FSysLang) then
FSysLang.Free;
if Assigned(FImageList32) then
FImageList32.Free;
if Assigned(FImageList16) then
FImageList16.Free;
inherited Destroy;
end;
class function TSingletonDB.GetInstance: TSingletonDB;
begin
if not Assigned(FInstance) then
FInstance := TSingletonDB.CreatePrivate;
Result := FInstance;
end;
function TSingletonDB.GetGridDefaultOrderFilter(pKey: string; pIsOrder: Boolean): string;
var
vSysGridDefaultOrderFilter: TSysGridDefaultOrderFilter;
vOrderFilter: string;
begin
Result := '';
if pIsOrder then
vOrderFilter := ' and is_order=True'
else
vOrderFilter := ' and is_order=False';
vSysGridDefaultOrderFilter := TSysGridDefaultOrderFilter.Create(DataBase);
try
vSysGridDefaultOrderFilter.SelectToList(vOrderFilter + ' and key=' + QuotedStr(pKey), False, False);
if vSysGridDefaultOrderFilter.List.Count=1 then
Result := TSysGridDefaultOrderFilter(vSysGridDefaultOrderFilter.List[0]).Value.Value;
finally
vSysGridDefaultOrderFilter.Free;
end;
if Trim(Result) <> '' then
if not pIsOrder then
Result := ' AND ' + Result;
end;
function TSingletonDB.GetIsRequired(pTableName, pFieldName: string): Boolean;
var
vSysInputGui: TSysViewColumns;
begin
Result := False;
vSysInputGui := TSysViewColumns.Create(DataBase);
try
vSysInputGui.SelectToList(' and table_name=' + QuotedStr(ReplaceRealColOrTableNameTo(pTableName)) +
' and column_name=' + QuotedStr(ReplaceRealColOrTableNameTo(pFieldName)), False, False);
if vSysInputGui.List.Count=1 then
Result := TSysViewColumns(vSysInputGui.List[0]).IsNullable.Value = 'NO';
finally
vSysInputGui.Free;
end;
end;
function TSingletonDB.FillComboFromLangData(pComboBox: TComboBox; pBaseTableName,
pBaseColName: string; pRowID: Integer): string;
begin
pComboBox.Clear;
with DataBase.NewQuery do
try
Close;
SQL.Text :=
'SELECT ' +
' CASE ' +
' WHEN b.val IS NULL THEN a.' + pBaseColName + ' ' +
' ELSE b.val ' +
' END as value ' +
'FROM public.' + pBaseTableName + ' a ' +
'LEFT JOIN sys_lang_data_content b ON b.row_id = a.id ' +
' AND b.table_name = ' + QuotedStr( ReplaceRealColOrTableNameTo(pBaseTableName) ) + ' ' +
' AND b.lang=' + QuotedStr(DataBase.ConnSetting.Language);
Open;
while NOT EOF do
begin
pComboBox.Items.Add(Fields.Fields[0].AsString);
Next;
end;
EmptyDataSet;
Close;
finally
Free;
end;
end;
function TSingletonDB.GetMaxLength(pTableName, pFieldName: string): Integer;
var
vSysInputGui: TSysViewColumns;
begin
Result := 0;
vSysInputGui := TSysViewColumns.Create(DataBase);
try
vSysInputGui.SelectToList(' and table_name=' + QuotedStr(ReplaceRealColOrTableNameTo(pTableName)) +
' and column_name=' + QuotedStr(ReplaceRealColOrTableNameTo(pFieldName)), False, False);
if vSysInputGui.List.Count=1 then
Result := TSysViewColumns(vSysInputGui.List[0]).CharacterMaximumLength.Value;
finally
vSysInputGui.Free;
end;
end;
function TSingletonDB.GetQualityFormNo(pTableName: string; pIsInput: Boolean): string;
var
vQualityFormNo: TSysQualityFormNumber;
begin
Result := '';
pTableName := ReplaceRealColOrTableNameTo(pTableName);
if DataBase.Connection.Connected then
begin
vQualityFormNo := TSysQualityFormNumber.Create(DataBase);
try
vQualityFormNo.SelectToList(' AND ' + vQualityFormNo.TableName1.FieldName + '=' + QuotedStr(pTableName) +
' AND ' + vQualityFormNo.IsInputForm.FieldName + '=' + TFunctions.BoolToStr(pIsInput) , False, False);
if vQualityFormNo.List.Count = 1 then
Result := TFunctions.VarToStr(vQualityFormNo.FormNo.Value);
finally
vQualityFormNo.Free;
end;
end;
end;
function TSingletonDB.GetDistinctColumnName(pTableName: string): TStringList;
begin
Result := TStringList.Create;
Result.BeginUpdate;
with DataBase.NewQuery do
try
Close;
SQL.Text := 'SELECT distinct v.column_name FROM sys_view_columns v ' +
' LEFT JOIN sys_grid_col_width a ON a.table_name=v.table_name and a.column_name = v.column_name ' +
' WHERE v.table_name=' + QuotedStr(pTableName) + ' and a.column_name is null ';
Open;
while NOT EOF do
begin
Result.Add( Fields.Fields[0].AsString );
Next;
end;
EmptyDataSet;
Close;
finally
Free;
end;
Result.EndUpdate;
end;
procedure TSingletonDB.FillColNameForColWidth(pComboBox: TComboBox; pTableName: string);
begin
pComboBox.Clear;
with DataBase.NewQuery do
try
Close;
SQL.Text := 'SELECT distinct v.column_name, ordinal_position FROM sys_view_columns v ' +
'LEFT JOIN sys_grid_col_width a ON a.table_name=v.table_name and a.column_name = v.column_name ' +
'WHERE v.table_name=' + QuotedStr(pTableName) + ' and a.column_name is null ' +
'GROUP BY v.column_name, ordinal_position ' +
'ORDER BY ordinal_position ASC ';
Open;
while NOT EOF do
begin
pComboBox.Items.Add( Fields.Fields[0].AsString );
Next;
end;
EmptyDataSet;
Close;
finally
Free;
end;
end;
end.
|
unit u_xpl_custom_listener;
{==============================================================================
UnitName = uxPLListener
UnitDesc = xPL Listener object and function
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
0.91 : Seperation of basic xPL Client (listener and sender) from pure listener
0.92 : Modification made to avoid handling of my own emitted messages
0.94 : Removed bHubfound, redondant with JoinedxPLNetwork
Removed bConfigOnly, redondant with AwaitingConfiguration
0.94 : Replacement of TTimer with TfpTimer
0.97 : Removed field AwaitingConfiguration that was redundant with Config.ConfigNeeded
0.98 : Added SeeAll variable to enable logger to see messages not targetted to him
1.00 : Added descendance from TxPLSender functionalities extracted from xPLMessage
1.01 : Suppressed HBReqTimer, fusionned with hBTimer to avoid the app to answering
both to a hbeat request and a few seconds after to send it's own hbeat
1.03 : Added detection of lost xPL network connectivity
}
{$i xpl.inc}
{$M+}
interface
uses Classes
, SysUtils
, u_xpl_common
, u_xpl_udp_socket
, u_xpl_message
, u_xpl_config
, u_xpl_heart_beater
, u_xpl_body
, u_xpl_sender
, fpc_delphi_compat
;
type TxPLReceivedEvent = procedure(const axPLMsg: TxPLMessage) of object;
TxPLConfigDone = procedure(const aConfig: TxPLCustomConfig) of object;
TxPLHBeatPrepare = procedure(const aBody: TxPLBody) of object;
// TxPLCustomListener ====================================================
TxPLCustomListener = class(TxPLSender)
private
fConfig: TxPLCustomConfig;
fCfgFname: string;
fProbingTimer: TxPLTimer;
IncomingSocket: TAppServer;
Connection: TxPLConnHandler;
procedure NoAnswerReceived({%H-}Sender: TObject);
protected
function Get_ConnectionStatus: TConnectionStatus;
procedure Set_ConnectionStatus(const aValue : TConnectionStatus); virtual;
public
OnxPLReceived: TxPLReceivedEvent;
OnPreProcessMsg: TxPLReceivedEvent;
OnxPLConfigDone: TxPLConfigDone;
OnxPLHBeatPrepare: TxPLHBeatPrepare;
OnxPLHBeatApp: TxPLReceivedEvent;
OnxPLJoinedNet: TNoParamEvent;
constructor Create(const aOwner: TComponent); reintroduce;
destructor Destroy; override;
procedure SaveConfig; dynamic;
procedure LoadConfig; dynamic;
procedure UpdateConfig; dynamic;
procedure Listen; dynamic;
procedure HandleConfigMessage(aMessage: TxPLMessage); dynamic;
procedure SendHeartBeatMessage; dynamic;
function ConnectionStatusAsStr: string;
function DoHBeatApp(const aMessage: TxPLMessage): boolean; dynamic;
function DoxPLReceived(const aMessage: TxPLMessage): boolean; dynamic;
procedure UDPRead(const aString: string);
published
property Config: TxPLCustomConfig read fConfig;
property ConnectionStatus : TConnectionStatus read Get_ConnectionStatus write Set_ConnectionStatus stored false;
end;
implementation // =============================================================
uses u_xpl_schema
, u_xpl_messages
, u_xpl_application
;
const K_MSG_CONFIG_LOADED = 'Configuration loaded for %s';
K_MSG_CONFIG_WRITEN = 'Configuration saved to %s';
K_MSG_UDP_ERROR = 'Unable to initialize incoming UDP server';
K_MSG_CONFIG_RECEIVED = 'Config received from %s and saved';
K_MSG_CONF_ERROR = 'Badly formed or incomplete config information received';
// TxPLCustomListener =========================================================
constructor TxPLCustomListener.Create(const aOwner: TComponent);
begin
inherited;
fConfig := TxPLCustomConfig.Create(self);
fCfgFname := Folders.DeviceDir + Adresse.VD + '.cfg';
fProbingTimer := TimerPool.Add(9 * 1000, {$ifdef fpc}@{$endif}NoAnswerReceived); // Let say 9 sec is needed to receive an answer
end;
destructor TxPLCustomListener.Destroy;
begin
if Connection.Status = connected then SendHeartBeatMessage;
IncomingSocket.Active := False; // Be sure no more message will be heard
SaveConfig;
inherited Destroy;
end;
function TxPLCustomListener.ConnectionStatusAsStr: string;
begin
result := Connection.StatusAsStr;
end;
procedure TxPLCustomListener.SaveConfig;
begin
StreamObjectToFile(fCfgFName, self);
Log(etInfo, K_MSG_CONFIG_WRITEN, [fCfgFName]);
end;
procedure TxPLCustomListener.LoadConfig;
begin
ReadObjectFromFile(fCfgFName, self);
Adresse.Instance := Config.Instance;
Log(etInfo, K_MSG_CONFIG_LOADED, [Adresse.RawxPL]);
end;
procedure TxPLCustomListener.UpdateConfig;
begin
LoadConfig;
if fConfig.IsValid then begin
if Connection.Status = connected then SendHeartBeatMessage;
if Assigned(OnxPLConfigDone) then OnxPLConfigDone(fConfig);
end;
end;
procedure TxPLCustomListener.Listen;
begin
Assert(Assigned(xPLApplication),'Please instantiate your listener using xPLApplication');
try
IncomingSocket := TAppServer.Create(self);
except
Log(etError, K_MSG_UDP_ERROR);
end;
IncomingSocket.OnReceived := {$ifdef fpc}@{$endif}UDPRead;
Connection := TxPLConnHandler.Create(self);
if not FileExists(fCfgFName) then SaveConfig;
UpdateConfig;
ConnectionStatus := discovering;
end;
procedure TxPLCustomListener.NoAnswerReceived(Sender: TObject); // This procedure is called by the probing
begin // timer when we're waiting unsuccessfully
ConnectionStatus := discovering; // for the heart beat I sent
end;
function TxPLCustomListener.Get_ConnectionStatus : TConnectionStatus;
begin
if Assigned(Connection) then result := Connection.Status
else result := csNone
end;
procedure TxPLCustomListener.SendHeartBeatMessage;
var i: integer;
begin
with THeartBeatMsg.Create(self) do begin
for i := 0 to IncomingSocket.Bindings.Count - 1 do begin
Port := IncomingSocket.Bindings[i].Port;
Remote_Ip := IncomingSocket.Bindings[i].IP;
if Assigned(OnxPLHBeatPrepare) and (Config.IsValid) then OnxPLHBeatPrepare(Body);
Send;
end;
fProbingTimer.Enabled := not (csDestroying in ComponentState); // Don't wait for an answer if I'm leaving
Free;
end;
end;
procedure TxPLCustomListener.HandleConfigMessage(aMessage: TxPLMessage);
begin
if not Adresse.Equals(aMessage.Target) or (aMessage.MessageType <> cmnd) then exit;
if aMessage is TConfigCurrentCmnd then Send(Config.CurrentConfig)
else if aMessage is TConfigListCmnd then Send(Config.ConfigList)
else if aMessage is TConfigResponseCmnd then begin
Config.CurrentConfig.Body.Assign(aMessage.Body);
if fConfig.IsValid then begin
Log(etInfo, K_MSG_CONFIG_RECEIVED, [aMessage.Source.RawxPL]);
SaveConfig;
UpdateConfig;
end else
Log(etError, K_MSG_CONF_ERROR);
end;
ConnectionStatus := connected;
end;
procedure TxPLCustomListener.UDPRead(const aString: string);
var aMessage: TxPLMessage;
begin
CheckSynchronize;
if csDestroying in ComponentState then exit;
fProbingTimer.Enabled := False; // Stop waiting, I received a message
aMessage := MessageBroker(aString);
with aMessage do try
if Assigned(OnPreprocessMsg) then OnPreprocessMsg(aMessage);
if (Adresse.Equals(Target)) or (Target.Isgeneric) then begin // It is directed to me
if Adresse.Equals(Source) then ConnectionStatus := connected // I heard something from me : I'm connected
else if aMessage is THeartBeatReq then Connection.Rate := rfRandom
else if aMessage is TFragmentMsg then FragmentMgr.Handle(TFragmentMsg(aMessage))
else if Schema.IsConfig then HandleConfigMessage(aMessage);
if (MatchesFilter(Config.FilterSet) and Config.IsValid) and (not Adresse.Equals(Source)) then
if not DoHBeatApp(aMessage) then
DoxPLReceived(aMessage);
end;
finally
Free;
end;
end;
procedure TxPLCustomListener.Set_ConnectionStatus(const aValue: TConnectionStatus);
begin
if Connection.Status <> aValue then begin
Connection.Status := aValue;
Log(etInfo, Connection.StatusAsStr);
if (aValue = connected) and not Config.IsValid then Log(etInfo, 'Configuration pending');
if Assigned(OnxPLJoinedNet) then OnxPLJoinedNet;
end;
end;
{------------------------------------------------------------------------
DoHBeatApp :
Transfers the message to the application only if the message completes
required tests : has to be of xpl-stat type and the
schema has to be hbeat.app
IN : the message to test and transmit
OUT : result indicates wether the message has been transmitted or not
------------------------------------------------------------------------}
function TxPLCustomListener.DoHBeatApp(const aMessage: TxPLMessage): boolean;
begin
Result := (aMessage is THeartBeatMsg) and not(aMessage.Source.Equals(Adresse));
if Result and Assigned(OnxPLHBeatApp) then OnxPLHBeatApp(aMessage);
end;
function TxPLCustomListener.DoxPLReceived(const aMessage: TxPLMessage): boolean;
begin
Result := Assigned(OnxPLReceived);
if Result then
OnxPLReceived(aMessage);
end;
initialization // =============================================================
Classes.RegisterClass(TxPLCustomListener);
end.
|
unit ASN1.X509;
interface
uses
ASN1;
type
X509_PublicKeyInfo_RSA = record
strict private
modulus: TASN1_Integer;
publicExponent: TASN1_Integer;
public
constructor Create(aModulus, apublicExponent: TASN1_Integer);
class function &Label: string; static;
function Value: TASN1_Sequence;
class operator Implicit(aValue: X509_PublicKeyInfo_RSA): TASN1_Sequence;
end;
X509_PublicKeyInfo_ECC = record
strict private
x: TASN1_Integer;
y: TASN1_Integer;
public
constructor Create(ax, ay: TASN1_Integer);
class function &Label: string; static;
class operator Implicit(aValue: X509_PublicKeyInfo_ECC): TASN1_Sequence;
end;
implementation
constructor X509_PublicKeyInfo_RSA.Create(aModulus, apublicExponent: TASN1_Integer);
begin
modulus := aModulus;
publicExponent := apublicExponent;
end;
class function X509_PublicKeyInfo_RSA.&Label: string;
begin
Result := 'PUBLIC KEY';
end;
function X509_PublicKeyInfo_RSA.Value: TASN1_Sequence;
begin
Result := Self;
end;
class operator X509_PublicKeyInfo_RSA.Implicit(aValue: X509_PublicKeyInfo_RSA):
TASN1_Sequence;
(* rfc2459
SubjectPublicKeyInfo ::= SEQUENCE {
SEQUENCE {
rsaEncryption OBJECT IDENTIFIER ::= {
iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-1(1) 1
},
NULL
},
subjectPublicKey BIT STRING {
RSAPublicKey ::= SEQUENCE {
modulus INTEGER, -- n
publicExponent INTEGER -- e
}
}
}
*)
begin
var a: TASN1_Sequence;
a.Add(TASN1_ObjectIdentifier('1.2.840.113549.1.1.1'));
a.AddNull;
Result.Add(a);
var b: TASN1_Sequence;
b.Add(aValue.modulus);
b.Add(aValue.publicExponent);
var c: TASN1_BitString := TASN1_DER.Encode(b);
Result.Add(c);
end;
constructor X509_PublicKeyInfo_ECC.Create(ax, ay: TASN1_Integer);
begin
x := ax;
y := ay;
end;
class function X509_PublicKeyInfo_ECC.&Label: string;
begin
Result := 'PUBLIC KEY';
end;
class operator X509_PublicKeyInfo_ECC.Implicit(aValue: X509_PublicKeyInfo_ECC): TASN1_Sequence;
(* rfc5480
SubjectPublicKeyInfo ::= SEQUENCE {
SEQUENCE {
id-ecPublicKey OBJECT IDENTIFIER ::= {
iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1
},
secp256r1 OBJECT IDENTIFIER ::= {
iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
prime(1) 7
}
}
subjectPublicKey BIT STRING {
0x04 -- uncompressed
Q.X
Q.Y
}
}
*)
begin
var a: TASN1_Sequence;
a.Add(TASN1_ObjectIdentifier('1.2.840.10045.2.1'));
a.Add(TASN1_ObjectIdentifier('1.2.840.10045.3.1.7'));
Result.Add(a);
var b := [$04{uncompressed}] + aValue.x.Value + aValue.y.Value;
Result.Add(TASN1_BitString(b));
end;
end.
|
unit PascalCoin.RPC.Test.Account;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.ListBox, FMX.Controls.Presentation, FMX.Edit, PascalCoin.RPC.Interfaces;
type
TAccountFrame = class(TFrame)
Layout1: TLayout;
AcctNum: TEdit;
Label1: TLabel;
Button1: TButton;
ListBox1: TListBox;
PubKeyCopy: TButton;
procedure Button1Click(Sender: TObject);
procedure PubKeyCopyClick(Sender: TObject);
private
FAccount: IPascalCoinAccount;
{ Private declarations }
function AccountNumber: Integer;
public
{ Public declarations }
end;
implementation
{$R *.fmx}
uses FMX.Platform, FMX.Surfaces, Spring.Container, PascalCoin.RPC.Test.DM;
function TAccountFrame.AccountNumber: Integer;
var lPos: Integer;
begin
lPos := AcctNum.Text.IndexOf('-');
if lPos > 0 then
result := AcctNum.Text.Substring(0, lPos).ToInteger
else
result := AcctNum.Text.ToInteger;
end;
procedure TAccountFrame.Button1Click(Sender: TObject);
var lAPI: IPascalCoinAPI;
begin
FAccount := nil;
ListBox1.BeginUpdate;
try
ListBox1.Clear;
lAPI := GlobalContainer.Resolve<IPascalCoinAPI>.URI(DM.URI);
FAccount := lAPI.getaccount(AccountNumber);
ListBox1.Items.Add('account : ' + FAccount.account.ToString);
ListBox1.Items.Add('enc_pubkey : ' + FAccount.enc_pubkey);
ListBox1.Items.Add('balance : ' + FloatToStr(FAccount.balance));
ListBox1.Items.Add('n_operation : ' + FAccount.n_operation.ToString);
ListBox1.Items.Add('updated_b : ' + FAccount.updated_b.ToString);
ListBox1.Items.Add('state : ' + FAccount.state);
ListBox1.Items.Add('locked_until_block : ' + FAccount.locked_until_block.ToString);
ListBox1.Items.Add('price : ' + FloatToStr(FAccount.price));
ListBox1.Items.Add('seller_account : ' + FAccount.seller_account.ToString);
ListBox1.Items.Add('private_sale : ' + FAccount.private_sale.ToString);
ListBox1.Items.Add('new_enc_pubkey : ' + FAccount.new_enc_pubkey);
ListBox1.Items.Add('name : ' + FAccount.name);
ListBox1.Items.Add('account_type : ' + FAccount.account_type.ToString);
finally
ListBox1.EndUpdate;
end;
end;
procedure TAccountFrame.PubKeyCopyClick(Sender: TObject);
var
Svc: IFMXClipboardService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, Svc) then
Svc.SetClipboard(FAccount.enc_pubkey);
end;
end.
|
unit Ths.Erp.Database.Table.SysUser;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, Data.DB,
Ths.Erp.Constants,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TSysUser = class(TTable)
private
FUserName: TFieldDB;
FUserPassword: TFieldDB;
FAppVersion: TFieldDB;
FIsAdmin: TFieldDB;
FIsSuperUser: TFieldDB;
protected
published
constructor Create(OwnerDatabase: TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
property UserName: TFieldDB read FUserName write FUserName;
property UserPassword: TFieldDB read FUserPassword write FUserPassword;
property AppVersion: TFieldDB read FAppVersion write FAppVersion;
property IsAdmin: TFieldDB read FIsAdmin write FIsAdmin;
property IsSuperUser: TFieldDB read FIsSuperUser write FIsSuperUser;
end;
implementation
uses
Ths.Erp.Database.Singleton;
constructor TSysUser.Create(OwnerDatabase: TDatabase);
begin
inherited;
TableName := 'sys_user';
SourceCode := '1';
FUserName := TFieldDB.Create('user_name', ftString, '');
FUserPassword := TFieldDB.Create('user_password', ftString, '');
FAppVersion := TFieldDB.Create('app_version', ftString, '');
FIsAdmin := TFieldDB.Create('is_admin', ftBoolean, False);
FIsSuperUser := TFieldDB.Create('is_super_user', ftBoolean, False);
end;
procedure TSysUser.SelectToDatasource(pFilter: string;
pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text :=
Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FUserName.FieldName,
TableName + '.' + FUserPassword.FieldName,
TableName + '.' + FAppVersion.FieldName,
TableName + '.' + FIsAdmin.FieldName,
TableName + '.' + FIsSuperUser.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FUserName.FieldName).DisplayLabel := 'USER NAME';
Self.DataSource.DataSet.FindField(FUserPassword.FieldName).DisplayLabel := 'USER PASSWORD';
Self.DataSource.DataSet.FindField(FAppVersion.FieldName).DisplayLabel := 'APP VERSION';
Self.DataSource.DataSet.FindField(FIsAdmin.FieldName).DisplayLabel := 'ADMIN?';
Self.DataSource.DataSet.FindField(FIsSuperUser.FieldName).DisplayLabel := 'SUPER USER?';
end;
end;
end;
procedure TSysUser.SelectToList(pFilter: string; pLock: Boolean;
pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text :=
Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FUserName.FieldName,
TableName + '.' + FUserPassword.FieldName,
TableName + '.' + FAppVersion.FieldName,
TableName + '.' + FIsAdmin.FieldName,
TableName + '.' + FIsSuperUser.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FUserName.Value := FormatedVariantVal(FieldByName(FUserName.FieldName).DataType, FieldByName(FUserName.FieldName).Value);
FUserPassword.Value := FormatedVariantVal(FieldByName(FUserPassword.FieldName).DataType, FieldByName(FUserPassword.FieldName).Value);
FAppVersion.Value := FormatedVariantVal(FieldByName(FAppVersion.FieldName).DataType, FieldByName(FAppVersion.FieldName).Value);
FIsAdmin.Value := FormatedVariantVal(FieldByName(FIsAdmin.FieldName).DataType, FieldByName(FIsAdmin.FieldName).Value);
FIsSuperUser.Value := FormatedVariantVal(FieldByName(FIsSuperUser.FieldName).DataType, FieldByName(FIsSuperUser.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
EmptyDataSet;
Close;
end;
end;
end;
procedure TSysUser.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FUserName.FieldName,
FUserPassword.FieldName,
FAppVersion.FieldName,
FIsAdmin.FieldName,
FIsSuperUser.FieldName
]);
NewParamForQuery(QueryOfInsert, FUserName);
NewParamForQuery(QueryOfInsert, FUserPassword);
NewParamForQuery(QueryOfInsert, FAppVersion);
NewParamForQuery(QueryOfInsert, FIsAdmin);
NewParamForQuery(QueryOfInsert, FIsSuperUser);
Open;
pID := 0;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TSysUser.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FUserName.FieldName,
FUserPassword.FieldName,
FAppVersion.FieldName,
FIsAdmin.FieldName
]);
NewParamForQuery(QueryOfUpdate, FUserName);
NewParamForQuery(QueryOfUpdate, FUserPassword);
NewParamForQuery(QueryOfUpdate, FAppVersion);
NewParamForQuery(QueryOfUpdate, FIsAdmin);
NewParamForQuery(QueryOfUpdate, FIsSuperUser);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
self.notify;
end;
end;
function TSysUser.Clone():TTable;
begin
Result := TSysUser.Create(Database);
Self.Id.Clone(TSysUser(Result).Id);
FUserName.Clone(TSysUser(Result).FUserName);
FUserPassword.Clone(TSysUser(Result).FUserPassword);
FAppVersion.Clone(TSysUser(Result).FAppVersion);
FIsAdmin.Clone(TSysUser(Result).FIsAdmin);
FIsSuperUser.Clone(TSysUser(Result).FIsSuperUser);
end;
end.
|
{
Maximum Weighted Bipartite Matching
Hungarian Algorithm O(N4) but acts like O(N3)
Input:
G: UnDirected Simple Bipartite Graph (No Edge = Infinity)
N: Number of vertices of each part
Output:
Mt: Match of Each Vertex (Infinity = Not Matched)
NoAnswer: Graph does not have complete matching
Reference:
West
By Behdad
}
program
WeightedBipartiteMatching;
const
MaxN = 100 + 2;
Infinity = 10000;
var
N: Integer;
G: array [1 .. MaxN, 1 .. MaxN] of Integer;
Mt : array [0 .. 1, 0 .. MaxN] of Integer;
NoAnswer: Boolean;
Color, P, Cover, Q : array [0 .. 1, 0 .. MaxN] of Integer;
I, J, K, S, T : Integer;
procedure BFS (V : Integer);
var
QL, QR: Integer;
begin
QL := 1;
QR := 1;
Q[0, 1] := 0;
Q[1, 1] := V;
Color[0, V] := 1;
while QL <= QR do
begin
K := 1 - Q[0, QL];
J := Q[1, QL];
Inc(QL);
for I := 1 to N do
begin
if K = 1 then S := G[J, I] else S := G[I, J];
if K = 1 then T := Cover[0, J] + Cover[1, I] else T := Cover[1, J] + Cover[0, I];
if (Color[K, I] = 0) and (S = T) and ((K = 1) or (Mt[0, I] = J)) then
begin
Color[K, I] := 1;
P[K, I] := J;
Inc(QR);
Q[0, QR] := K;
Q[1, QR] := I;
end;
end;
end;
end;
procedure Assignment;
var
Sum : Longint;
Count : Integer;
B : Boolean;
begin
FillChar(Mt, SizeOf(Mt), 0);
FillChar(Cover, SizeOf(Cover), 0);
for I := 1 to N do
for J := 1 to N do
if G[I, J] > Cover[0, I] then
Cover[0, I] := G[I, J];
repeat
repeat
FillChar(Color, SizeOf(Color), 0);
FillChar(P, SizeOf(P), 0);
B := False;
for I := 1 to N do
if (Mt[0, I] = 0) and (Color[0, I] = 0) then
BFS(I);
for J := 1 to N do
if (Mt[1, J] = 0) and (Color[1, J] = 1) then
begin
B := True;
Break;
end;
if B then
begin
Dec(Count);
K := 1;
while True do
begin
if K = 1 then
begin
Mt[1, J] := P[1, J];
S := J;
end
else
Mt[0, J] := S;
if P[K, J] = 0 then
Break;
J := P[K, J];
K := 1 - K;
end;
end;
until not B;
J := Infinity;
for S := 1 to N do
begin
if Color[0, S] = 0 then
Continue;
for T := 1 to N do
if (Color[1, T] = 0) and (Cover[0, S] + Cover[1, T] - G[S, T] < J) then
J := Cover[0, S] + Cover[1, T] - G[S, T];
end;
if J < Infinity then
begin
for I := 1 to N do
begin
if Color[0, I] = 1 then
Dec(Cover[0, I], J);
if Color[1, I] = 1 then
Inc(Cover[1, I], J);
end;
end;
until Count = 0;
NoAnswer := False;
for I := 1 to N do
if G[I, Mt[0, I]] >= Infinity then
begin
NoAnswer := True;
Break;
end;
end;
begin
Assignment;
end.
|
unit BriefcaseMain;
{ This program demonstrates how to do disconnected briefcase applications
with ADO. When the Connected checkbox is unchecked the application is
switched into offline mode. If the application is exited at that point
then the data is persisted to a file on disk (along with any edits to the
data). When the application is restarted it will load the persisted data
if present, otherwise it will fetch the data from the database. }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Db, ADODB, Grids, DBGrids, ExtCtrls;
type
TForm1 = class(TForm)
Employees: TADODataSet;
EmpSource: TDataSource;
DBGrid1: TDBGrid;
Connection: TADOConnection;
Panel1: TPanel;
ConnectionInd: TCheckBox;
UpdateButton: TButton;
RefreshButton: TButton;
SaveButton: TButton;
procedure Form1Create(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure Form1CloseQuery(Sender: TObject; var CanClose: Boolean);
procedure UpdateButtonClick(Sender: TObject);
procedure ConnectionIndClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
private
DataFileName: string;
public
procedure LoadData;
procedure SaveData;
procedure UpdateData;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const
BaseFileName = 'EMPLOYEE.ADTG';
procedure TForm1.LoadData;
begin
DataFileName := ExtractFilePath(Paramstr(0))+BaseFileName;
{ If a persisted datafile exists, assume we exited in a disconnected
(offline) state and load the data from the file. }
if FileExists(DataFileName) then
Employees.LoadFromFile(DataFileName)
else
begin
{ Otherwise establish the connection and get data from the database }
ConnectionInd.Checked := True;
Employees.Open;
end;
end;
procedure TForm1.UpdateData;
begin
{ Connect to the database and send the pending updates }
ConnectionInd.Checked := True;
Employees.UpdateBatch;
DeleteFile(DataFileName);
end;
procedure TForm1.SaveData;
begin
{ Persist the data to disk }
Employees.SaveToFile(DataFileName, pfADTG);
end;
procedure TForm1.Form1Create(Sender: TObject);
begin
Connection.ConnectionString := 'FILE NAME=' + DataLinkDir + '\DBDEMOS.UDL';
LoadData;
end;
procedure TForm1.SaveButtonClick(Sender: TObject);
begin
SaveData;
end;
procedure TForm1.UpdateButtonClick(Sender: TObject);
begin
UpdateData;
end;
procedure TForm1.Form1CloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if Employees.Active then
try
{ When closing, update the database if connected or save it to disk if not }
if Connection.Connected then
UpdateData else
SaveData;
except
on E: Exception do
begin
Application.HandleException(Self);
CanClose := MessageDlg('Data not saved/updated, exit anyway?',
mtConfirmation, mbYesNoCancel, 0) = mrYes;
end;
end;
end;
procedure TForm1.ConnectionIndClick(Sender: TObject);
begin
{ Toggle the connection's state }
if ConnectionInd.Checked then
begin
Connection.Open;
Employees.Connection := Connection;
end else
begin
{ Note here you must clear the connection property of the dataset before
closing the connection. Otherwise the dataset will close with the
connection. }
Employees.Connection := nil;
Connection.Close;
end;
end;
procedure TForm1.RefreshButtonClick(Sender: TObject);
begin
{ Close and reopen the dataset to refresh the data. Note that in this demo
there is no checking for pending updates so they are lost if you click
the refresh data button before clicking the Update database button. }
ConnectionInd.Checked := True;
Employees.Close;
Employees.CommandType := cmdTable;
Employees.CommandText := 'Employee';
Employees.Open;
end;
end.
|
unit fOptions;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ComCtrls, ExtCtrls, RxCombos, RXSpin,
FlexBase, FlexUtils, ColorComboEdit;
type
TOptionEditPage = ( opDocument, opGrid, opDuplicates );
TOptionEditPages = set of TOptionEditPage;
const
AllOptions = [opDocument, opGrid];
type
PEditOptions = ^TEditOptions;
TEditOptions = record
// Document props
DocWidth: integer;
DocHeight: integer;
// Grid props
ShowGrid: boolean;
SnapToGrid: boolean;
ShowPixGrid: boolean;
GridStyle: TFlexGridStyle;
GridColor: TColor;
GridPixColor: TColor;
GridHSize: integer;
GridVSize: integer;
// Duplicates
ShiftX: integer;
ShiftY: integer;
DupRandom: boolean;
end;
TfmOptions = class(TForm)
bbOk: TBitBtn;
bbClose: TBitBtn;
chShowGrid: TCheckBox;
chSnapToGrid: TCheckBox;
Label7: TLabel;
cceGridColor: TColorComboEdit;
gbGridSize: TGroupBox;
Label5: TLabel;
Label6: TLabel;
sedGridHSize: TRxSpinEdit;
sedGridVSize: TRxSpinEdit;
Bevel1: TBevel;
rbGridAsLines: TRadioButton;
rbGridAsDots: TRadioButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ctrlDocChange(Sender: TObject);
procedure ctrlGridClick(Sender: TObject);
procedure ctrlGridChange(Sender: TObject);
procedure ctrlDupChange(Sender: TObject);
procedure ctrlDupClick(Sender: TObject);
private
{ Private declarations }
FOptions: TEditOptions;
FEdited: TOptionEditPages;
procedure ReadFromOptions;
procedure WriteToOptions;
procedure SetOptions(const Value: TEditOptions);
public
{ Public declarations }
property Edited: TOptionEditPages read FEdited;
property EditOptions: TEditOptions read FOptions write SetOptions;
end;
var
fmOptions: TfmOptions;
EditOptions: TEditOptions;
implementation
{$R *.DFM}
procedure InitDefaultOptions;
begin
with EditOptions do begin
// Document props
DocWidth := 640 * PixelScaleFactor;
DocHeight := 480 * PixelScaleFactor;
// Grid props
ShowGrid := False;
SnapToGrid := False;
ShowPixGrid := False;
GridStyle := gsDots;
GridColor := clGray;
GridPixColor := clSilver;
GridHSize := 10 * PixelScaleFactor;
GridVSize := 10 * PixelScaleFactor;
// Duplicates
ShiftX := 10 * PixelScaleFactor;
ShiftY := 10 * PixelScaleFactor;
DupRandom := False;
end;
end;
// TfmOptions /////////////////////////////////////////////////////////////////
procedure TfmOptions.FormCreate(Sender: TObject);
begin
//pgOptions.ActivePage := tsDocProps;
end;
procedure TfmOptions.FormClose(Sender: TObject; var Action: TCloseAction);
begin
WriteToOptions;
Action := caHide;
end;
procedure TfmOptions.SetOptions(const Value: TEditOptions);
begin
FOptions := Value;
ReadFromOptions;
end;
procedure TfmOptions.ReadFromOptions;
begin
with FOptions do begin
//sedWidth.Value := DocWidth / PixelScaleFactor;
//sedHeight.Value := DocHeight / PixelScaleFactor;
chShowGrid.Checked := ShowGrid;
chSnapToGrid.Checked := SnapToGrid;
//chShowPixGrid.Checked := ShowPixGrid;
case GridStyle of
gsLines : rbGridAsLines.Checked := true;
gsDots : rbGridAsDots.Checked := true;
end;
sedGridHSize.Value := GridHSize / PixelScaleFactor;
sedGridVSize.Value := GridVSize / PixelScaleFactor;
cceGridColor.ColorValue := GridColor;
//sedDupShiftX.Value := ShiftX / PixelScaleFactor;
//sedDupShiftY.Value := ShiftY / PixelScaleFactor;
//chDupRandom.Checked := DupRandom;
end;
FEdited := [];
end;
procedure TfmOptions.WriteToOptions;
begin
// Documents
//FOptions.DocWidth := Round(sedWidth.Value * PixelScaleFactor);
//FOptions.DocHeight := Round(sedHeight.Value * PixelScaleFactor);
// Grid
FOptions.ShowGrid := chShowGrid.Checked;
FOptions.SnapToGrid := chSnapToGrid.Checked;
//FOptions.ShowPixGrid := chShowPixGrid.Checked;
if rbGridAsLines.Checked then
FOptions.GridStyle := gsLines
else
if rbGridAsDots.Checked then
FOptions.GridStyle := gsDots;
FOptions.GridHSize := Round(sedGridHSize.Value * PixelScaleFactor);
FOptions.GridVSize := Round(sedGridVSize.Value * PixelScaleFactor);
FOptions.GridColor := cceGridColor.ColorValue;
// Duplicates
//FOptions.ShiftX := Round(sedDupShiftX.Value * PixelScaleFactor);
//FOptions.ShiftY := Round(sedDupShiftY.Value * PixelScaleFactor);
//FOptions.DupRandom := chDupRandom.Checked;
end;
procedure TfmOptions.ctrlDocChange(Sender: TObject);
begin
Include(FEdited, opDocument);
end;
procedure TfmOptions.ctrlGridClick(Sender: TObject);
begin
Include(FEdited, opGrid);
end;
procedure TfmOptions.ctrlGridChange(Sender: TObject);
begin
Include(FEdited, opGrid);
end;
procedure TfmOptions.ctrlDupChange(Sender: TObject);
begin
Include(FEdited, opDuplicates);
end;
procedure TfmOptions.ctrlDupClick(Sender: TObject);
begin
Include(FEdited, opDuplicates);
end;
initialization
InitDefaultOptions;
end.
|
unit caAppConfig;
interface
uses
// standard Delphi units...
Windows,
Classes,
SysUtils,
TypInfo,
ActiveX,
ShlObj,
// ca units...
caXml,
caRtti,
caClasses,
caUtils;
type
//---------------------------------------------------------------------------
// IcaAppConfig
//---------------------------------------------------------------------------
IcaAppConfig = interface
['{93FC81B2-B238-4622-8836-01F580000F0D}']
end;
//---------------------------------------------------------------------------
// TcaAppConfig
//---------------------------------------------------------------------------
TcaAppConfig = class(TInterfacedObject, IcaAppConfig)
private
// private members...
FPath: string;
FXmlReader: IcaXmlReader;
FValues: TStrings;
// private methods...
function AllUsersAppDataPath: WideString;
function GetSpecialFolder(APathID: Integer): WideString;
function PathJoin(const APaths: array of WideString; ADeleteFinalDelimiter: Boolean): WideString;
procedure BuildPath;
procedure CreateObjects;
procedure CreateDefaultXml;
procedure LoadXml;
// xml events...
procedure XmlTagEvent(Sender: TObject; const ATag, AAttributes: string; ALevel: Integer);
public
// lifetime...
constructor Create;
destructor Destroy; override;
// public methods...
procedure Save;
end;
implementation
//---------------------------------------------------------------------------
// TcaAppConfig
//---------------------------------------------------------------------------
// lifetime...
constructor TcaAppConfig.Create;
begin
inherited;
BuildPath;
CreateObjects;
if not FileExists(FPath) then
CreateDefaultXml;
LoadXml;
end;
destructor TcaAppConfig.Destroy;
begin
Save;
FXmlReader := nil;
FValues.Free;
inherited;
end;
// public methods...
procedure TcaAppConfig.Save;
begin
CreateDefaultXml;
end;
// private methods...
function TcaAppConfig.AllUsersAppDataPath: WideString;
begin
Result := GetSpecialFolder(CSIDL_COMMON_APPDATA);
end;
function TcaAppConfig.GetSpecialFolder(APathID: Integer): WideString;
var
pidl: PItemIDList;
Path: array[0..MAX_PATH] of WideChar;
begin
Result := '';
if Succeeded(SHGetSpecialFolderLocation(0, APathID, pidl)) then
if SHGetPathFromIDListW(pidl, Path) then
Result := Path;
end;
function TcaAppConfig.PathJoin(const APaths: array of WideString; ADeleteFinalDelimiter: Boolean): WideString;
var
Path: string;
TempPath: string;
ResultPath: string;
begin
ResultPath := '';
for Path in APaths do
begin
TempPath := Path;
if Length(TempPath) > 0 then
begin
if TempPath[1] = PathDelim then
Delete(TempPath, 1, 1);
TempPath := IncludeTrailingPathDelimiter(TempPath);
ResultPath := ResultPath + TempPath;
ResultPath := IncludeTrailingPathDelimiter(ResultPath);
end;
end;
if ADeleteFinalDelimiter and IsPathDelimiter(ResultPath, Length(ResultPath)) then
Delete(ResultPath, Length(ResultPath), 1);
Result := ResultPath;
end;
procedure TcaAppConfig.BuildPath;
var
Path: string;
begin
Path := PathJoin([AllUsersAppDataPath, 'Inspiration Matters', 'Inspired Signage', 'SFXBuilder'], False);
if not DirectoryExists(Path) then
CreateDir(Path);
FPath := PathJoin([Path, Utils.AppName + '.config'], True);
end;
procedure TcaAppConfig.CreateObjects;
begin
FXmlReader := TcaXmlReader.Create;
FValues := TStringList.Create;
end;
procedure TcaAppConfig.CreateDefaultXml;
var
XmlBuilder: IcaXmlBuilder;
RttiList: IcaRttiList;
Index: Integer;
begin
XmlBuilder := TcaXmlBuilder.CreateUtf8;
XmlBuilder.AddTag('configuration');
XmlBuilder.AddTag('appSettings');
RttiList := TcaRttiList.Create(Self);
for Index := 0 to Pred(RttiList.Count) do
begin
XmlBuilder.AddTag('add', Format('key="%s" value="%s"', [RttiList[Index].PropName, RttiList[Index].PropValueAsString]));
XmlBuilder.EndTag;
end;
XmlBuilder.EndTag;
XmlBuilder.EndTag;
XmlBuilder.SaveXmlToFile(FPath);
end;
procedure TcaAppConfig.LoadXml;
begin
FXmlReader.OnTag := XmlTagEvent;
FXmlReader.LoadFromXml(FPath);
FXmlReader.Parse;
end;
// xml events...
procedure TcaAppConfig.XmlTagEvent(Sender: TObject; const ATag, AAttributes: string; ALevel: Integer);
var
Attributes: IcaXmlAttributes;
Key: string;
Value: Variant;
begin
Attributes := TcaXmlAttributes.Create(AAttributes);
if ATag = 'add' then
begin
Key := Attributes['key'];
Value := Attributes['value'];
FValues.Values[Key] := Value;
if IsPublishedProp(Self, Key) then
SetPropValue(Self, Key, Value);
end;
end;
end.
|
unit uFuncoesData;
interface
uses SysUtils, Classes, Forms, Menus, Dialogs, ExtCtrls, Graphics, WIndows,
Variants, ComCtrls, StdCtrls, Controls, fcPanel, fcLabel, CMDateTimePicker,
wwdbdatetimepicker;
function retornaMesInteiro(AMes: string): Integer;
function retornaMesString(AMes: Integer): string;
function retornaMeses: TStringList;
implementation
function retornaMeses: TStringList;
var
meses: TStringList;
begin
meses := TStringList.Create;
meses.Add('Janeiro');
meses.Add('Fevereiro');
meses.Add('Março');
meses.Add('Abril');
meses.Add('Maio');
meses.Add('Junho');
meses.Add('Julho');
meses.Add('Agosto');
meses.Add('Setembro');
meses.Add('Outubro');
meses.Add('Novembro');
meses.Add('Dezembro');
result := meses;
end;
function retornaMesInteiro(AMes: string): Integer;
var
meses : TStringList;
i : Integer;
begin
meses := retornaMeses;
result:= 0;
for i := 0 to meses.Count - 1 do
begin
if UpperCase(meses[i]) = UpperCase(AMes) then
Result := i + 1;
end;
end;
function retornaMesString(AMes: Integer): string;
begin
result := retornaMeses[AMes - 1];
end;
end.
|
unit Persistence.Entity.Person;
interface
uses
System.Classes,
Spring,
Spring.Persistence.Mapping.Attributes,
Persistence.Consts;
type
TCommonPerson = class(TObject)
strict private
FId: int;
FFirstName: string;
FLastName: string;
FBirthday: Date;
FPhone: string;
FEmail: string;
FCityId: int;
FStreet: string;
FZipCode: string;
FDistrict: string;
protected
property Id: int read FId write FId;
property FirstName: string read FFirstName write FFirstName;
property LastName: string read FLastName write FLastName;
property Birthday: Date read FBirthday write FBirthday;
property Phone: string read FPhone write FPhone;
property Email: string read FEmail write FEmail;
property CityId: int read FCityId write FCityId;
property Street: string read FStreet write FStreet;
property ZipCode: string read FZipCode write FZipCode;
property District: string read FDistrict write FDistrict;
end;
[Entity]
[Table(PERSON_TABLE, PUBLIC_SCHEMA)]
[Sequence(PERSON_ID_SEQ, 1, 1)]
TPerson = class(TCommonPerson)
public
[Column(ID_COL, [cpRequired])]
property Id;
[Column(FIRST_NAME_COL, [], 50)]
property FirstName;
[Column(LAST_NAME_COL, [], 50)]
property LastName;
[Column(BIRTHDAY_COL, [])]
property Birthday;
[Column(PHONE_COL, [], 15)]
property Phone;
[Column(EMAIL_COL, [], 30)]
property Email;
[Column(CITY_ID_COL, [])]
property CityId;
[Column(STREET_COL, [], 50)]
property Street;
[Column(ZIP_CODE_COL, [], 10)]
property ZipCode;
[Column(DISTRICT_COL, [], 50)]
property District;
end;
implementation
end.
|
unit ACCtrls;
interface
uses
Windows, Types, UITypes, Classes, Graphics, SysUtils, ExtCtrls,
FlexBase, FlexProps, FlexUtils;
type
TACControls = ( acNone, acZone, acDoor );
TDoorState = ( dsClosed, dsOpened );
TDoorOrientation = ( doVertical, doHorizontal );
TDoorAccessDirection = ( ddUnknown, ddForward, ddBackward );
TDoorEvent = ( deInactive, deValid, deError, deWarning, deBroken );
TFlexDoor = class(TFlexControl)
private
FFrameIndex: integer;
FLastFrameIndex: integer;
FAnimTimer: TTimer;
FPassAProp: TIntProp;
FPassBProp: TIntProp;
FOrientationProp: TEnumProp;
FDoorStateProp: TEnumProp;
FDoorEvent: TEnumProp;
FAccessDir: TEnumProp;
class procedure LoadResources;
class procedure FreeResources;
function GetDoorOrientation: TDoorOrientation;
function GetDoorState: TDoorState;
procedure SetDoorOrientation(Value: TDoorOrientation);
procedure SetDoorState(Value: TDoorState);
function GetAccessDir: TDoorAccessDirection;
function GetDoorEvent: TDoorEvent;
procedure SetAccessDir(Value: TDoorAccessDirection);
procedure SetDoorEvent(Value: TDoorEvent);
protected
procedure CreateProperties; override;
procedure ControlCreate; override;
procedure ControlDestroy; override;
procedure ControlTranslate(const TranslateInfo: TTranslateInfo); override;
procedure Paint(Canvas: TCanvas; var PaintRect: TRect); override;
procedure PropChanged(Sender: TObject; Prop: TCustomProp); override;
procedure StartAnim;
procedure StopAnim;
procedure AnimTimer(Sender: TObject); virtual;
function CreateArrowBitmap(Orient: TDoorOrientation; StyleIndex: integer;
IsForward: boolean): TBitmap; virtual;
function CreateFrameBitmap(Orient: TDoorOrientation;
Index: integer): TBitmap; virtual;
function CreateImage: TBitmap;
property OrientationProp: TEnumProp read FOrientationProp;
property DoorStateProp: TEnumProp read FDoorStateProp;
property DoorEventProp: TEnumProp read FDoorEvent;
public
class function GetToolInfo(ToolIcon: TBitmap; var Hint: string): boolean;
override;
function IsPointInside(PaintX, PaintY: integer): boolean; override;
function GetAnyExistPass: integer;
property PassAProp: TIntProp read FPassAProp;
property PassBProp: TIntProp read FPassBProp;
property Orientation: TDoorOrientation read GetDoorOrientation
write SetDoorOrientation;
property DoorState: TDoorState read GetDoorState write SetDoorState;
property AccessDir: TDoorAccessDirection read GetAccessDir
write SetAccessDir;
property DoorEvent: TDoorEvent read GetDoorEvent write SetDoorEvent;
end;
procedure FindDoorsForPass(PassID: integer; List: TList);
function GetACType(Control: TFlexControl): TACControls;
implementation
{$R Door.res Door.rc}
var
FDoorImages: TBitmap;
FDoorArrows: TBitmap;
FDoorIcon: TBitmap;
FDoorList: TList;
procedure FindDoorsForPass(PassID: integer; List: TList);
var i: integer;
begin
List.Clear;
for i:=0 to FDoorList.Count-1 do with TFlexDoor(FDoorList[i]) do
if (PassID < 0) or
(PassAProp.Value = PassID) or (PassBProp.Value = PassID) then
List.Add(FDoorList[i]);
end;
function GetACType(Control: TFlexControl): TACControls;
var sType: string;
begin
Result := acNone;
if not Assigned(Control) then exit;
sType := Control.UserData.Values['Type'];
if sType = 'Door' then Result := acDoor else
if sType = 'Zone' then Result := acZone;
end;
// TFlexDoor //////////////////////////////////////////////////////////////////
procedure TFlexDoor.ControlCreate;
begin
UserData.Values['Type'] := 'Door';
if Assigned(FDoorImages) then begin
Width := ScalePixels(FDoorImages.Height div 2);
Height := Width;
FLastFrameIndex := FDoorImages.Width div UnScalePixels(Width) -1;
end else begin
Width := ScalePixels(20);
Height := ScalePixels(20);
FLastFrameIndex := 0;
end;
WidthProp.Style := WidthProp.Style + [psReadOnly];
HeightProp.Style := HeightProp.Style + [psReadOnly];
FFrameIndex := 0;
if not Assigned(FDoorList) then FDoorList := TList.Create;
FDoorList.Add(Self);
inherited;
Visible := True;
end;
procedure TFlexDoor.CreateProperties;
begin
inherited;
FPassAProp := TIntProp.Create(Props, 'PassA');
FPassBProp := TIntProp.Create(Props, 'PassB');
FOrientationProp := TEnumProp.Create(Props, 'Orientation');
FOrientationProp.AddItem('Vertical');
FOrientationProp.AddItem('Horizontal');
FDoorStateProp := TEnumProp.Create(Props, 'DoorState');
FDoorStateProp.AddItem('Closed');
FDoorStateProp.AddItem('Opened');
FAccessDir := TEnumProp.Create(Props, 'AccessDir');
FAccessDir.AddItem('Unknown');
FAccessDir.AddItem('Forward');
FAccessDir.AddItem('Backward');
FDoorEvent := TEnumProp.Create(Props, 'DoorEvent');
FDoorEvent.AddItem('Inactive');
FDoorEvent.AddItem('Valid');
FDoorEvent.AddItem('Error');
FDoorEvent.AddItem('Warning');
FDoorEvent.AddItem('Broken');
end;
procedure TFlexDoor.ControlTranslate(const TranslateInfo: TTranslateInfo);
var Degree: integer;
begin
inherited;
Degree := TranslateInfo.Rotate mod 360 div 90;
if Degree < 0 then Degree := 4 + Degree;
if Degree and 1 <> 0 then
FOrientationProp.EnumIndex := 1 - FOrientationProp.EnumIndex;
end;
procedure TFlexDoor.ControlDestroy;
begin
StopAnim;
FDoorList.Remove(Self);
if FDoorList.Count = 0 then FreeAndNil(FDoorList);
inherited;
end;
class procedure TFlexDoor.LoadResources;
begin
if not Assigned(FDoorImages) then FDoorImages := TBitmap.Create;
FDoorImages.LoadFromResourceName(HInstance, 'DOORIMAGES');
if not Assigned(FDoorArrows) then FDoorArrows := TBitmap.Create;
FDoorArrows.LoadFromResourceName(HInstance, 'DOORARROWS');
if not Assigned(FDoorIcon) then FDoorIcon := TBitmap.Create;
FDoorIcon.LoadFromResourceName(HInstance, 'DOORICON');
end;
class procedure TFlexDoor.FreeResources;
begin
FreeAndNil(FDoorImages);
FreeAndNil(FDoorArrows);
FreeAndNil(FDoorIcon);
end;
class function TFlexDoor.GetToolInfo(ToolIcon: TBitmap;
var Hint: string): boolean;
begin
Result := true;
Hint := 'AC Door tool';
if Assigned(ToolIcon) and Assigned(FDoorIcon) then
ToolIcon.Canvas.Draw(0, 0, FDoorIcon);
end;
function TFlexDoor.GetDoorOrientation: TDoorOrientation;
begin
Result := TDoorOrientation(FOrientationProp.EnumIndex);
end;
function TFlexDoor.GetDoorState: TDoorState;
begin
Result := TDoorState(FDoorStateProp.EnumIndex);
end;
procedure TFlexDoor.SetDoorOrientation(Value: TDoorOrientation);
begin
FOrientationProp.EnumIndex := integer(Value);
end;
procedure TFlexDoor.SetDoorState(Value: TDoorState);
begin
FDoorStateProp.EnumIndex := integer(Value);
end;
function TFlexDoor.GetAccessDir: TDoorAccessDirection;
begin
Result := TDoorAccessDirection(FAccessDir.EnumIndex);
end;
function TFlexDoor.GetDoorEvent: TDoorEvent;
begin
Result := TDoorEvent(FDoorEvent.EnumIndex);
end;
procedure TFlexDoor.SetAccessDir(Value: TDoorAccessDirection);
begin
FAccessDir.EnumIndex := integer(Value);
end;
procedure TFlexDoor.SetDoorEvent(Value: TDoorEvent);
begin
FDoorEvent.EnumIndex := integer(Value);
end;
function TFlexDoor.GetAnyExistPass: integer;
begin
if PassAProp.Value > 0 then
Result := PassAProp.Value
else
if PassBProp.Value > 0 then
Result := PassBProp.Value
else
Result := 0;
end;
function TFlexDoor.CreateArrowBitmap(Orient: TDoorOrientation;
StyleIndex: integer; IsForward: boolean): TBitmap;
var Img: TPoint;
Size: integer;
begin
if not Assigned(FDoorArrows) then begin
Result := Nil;
exit;
end;
Img.Y := StyleIndex;
if Orient = doHorizontal then begin
if IsForward
then Img.X := 2
else Img.X := 1;
end else
if IsForward
then Img.X := 3
else Img.X := 0;
Size := (FDoorArrows.Width div 4);
Img.X := Img.X * Size;
Img.Y := Img.Y * Size;
Result := TBitmap.Create;
Result.Width := Size;
Result.Height := Size;
Result.Canvas.CopyRect(Rect(0, 0, Size, Size), FDoorArrows.Canvas,
Rect(Img.X, Img.Y, Img.X + Size, Img.Y + Size));
Result.Transparent := True;
end;
function TFlexDoor.CreateFrameBitmap(Orient: TDoorOrientation;
Index: integer): TBitmap;
var Img: TPoint;
PicSize: TPoint;
begin
if not Assigned(FDoorImages) then begin
Result := Nil;
exit;
end;
PicSize.X := UnScalePixels(Width);
PicSize.Y := UnScalePixels(Height);
Img.X := Index * PicSize.X;
if Orient = doVertical
then Img.Y := 0
else Img.Y := PicSize.Y;
Result := TBitmap.Create;
Result.Width := PicSize.X;
Result.Height := PicSize.Y;
Result.Canvas.CopyRect(Rect(0, 0, PicSize.X, PicSize.Y), FDoorImages.Canvas,
Rect(Img.X, Img.Y, Img.X + PicSize.X, Img.Y + PicSize.Y));
Result.Transparent := True;
end;
function TFlexDoor.CreateImage: TBitmap;
var Arrow: TBitmap;
Img: TPoint;
begin
Result := CreateFrameBitmap(Orientation, FFrameIndex);
if not Assigned(Result) then exit;
if ((DoorState = dsOpened) or Assigned(FAnimTimer)) and
(AccessDir <> ddUnknown) or (DoorEvent = deBroken) then begin
Arrow := CreateArrowBitmap(Orientation, integer(DoorEvent),
AccessDir = ddForward);
Img.X := (UnScalePixels(Width) - Arrow.Width) div 2;
Img.Y := (UnScalePixels(Height) - Arrow.Height) div 2;
if Assigned(Arrow) then Result.Canvas.Draw(Img.X, Img.Y, Arrow);
Arrow.Free;
end;
end;
procedure TFlexDoor.Paint(Canvas: TCanvas; var PaintRect: TRect);
var Frame: TBitmap;
begin
if not Assigned(FDoorImages) then exit;
Frame := CreateImage;
try
Canvas.StretchDraw(PaintRect, Frame);
finally
Frame.Free;
end;
end;
function TFlexDoor.IsPointInside(PaintX, PaintY: integer): boolean;
var Frame: TBitmap;
P: TPoint;
begin
Result := inherited IsPointInside(PaintX, PaintY);
if not Result then exit;
P := OwnerToClient(Point(PaintX, PaintY));
Frame := CreateFrameBitmap(Orientation, 0);
try
if Frame.Canvas.Pixels[P.X, P.Y] and $FFFFFF =
Frame.TransparentColor and $FFFFFF then Result := False;
finally
Frame.Free;
end;
end;
procedure TFlexDoor.StartAnim;
begin
if not Assigned(FAnimTimer) then begin
FAnimTimer := TTimer.Create(Nil);
FAnimTimer.Interval := 20;
FAnimTimer.OnTimer := AnimTimer;
end;
AnimTimer(FAnimTimer);
end;
procedure TFlexDoor.StopAnim;
begin
FreeAndNil(FAnimTimer);
Invalidate;
end;
procedure TFlexDoor.AnimTimer(Sender: TObject);
begin
FAnimTimer.Enabled := False;
try
if DoorState = dsClosed then begin
if FFrameIndex > 0 then begin
dec(FFrameIndex);
Invalidate;
end else
StopAnim;
end else
if DoorState = dsOpened then begin
if FFrameIndex < FLastFrameIndex then begin
inc(FFrameIndex);
Invalidate;
end else
StopAnim;
end else
StopAnim;
finally
if Assigned(FAnimTimer) then FAnimTimer.Enabled := True;
end;
end;
procedure TFlexDoor.PropChanged(Sender: TObject; Prop: TCustomProp);
begin
inherited;
if Prop = FDoorStateProp then StartAnim;
end;
///////////////////////////////////////////////////////////////////////////////
procedure RegisterACControls;
begin
RegisterFlexControl(TFlexDoor);
end;
initialization
TFlexDoor.LoadResources;
RegisterACControls;
finalization
TFlexDoor.FreeResources;
end.
|
unit MapRangeCodeSelectDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Buttons, DB, DBTables;
type
TMapRangeCodeSelectDialog = class(TForm)
OKButton: TBitBtn;
CancelButton: TBitBtn;
CodeListBox: TListBox;
procedure OKButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
RangeType : Integer;
SelectedCodesList : TStringList;
Procedure InitializeForm(_RangeType : Integer;
_SelectedCodesList : TStringList);
end;
implementation
{$R *.DFM}
uses WinUtils, GlblCnst, GlblVars;
{=========================================================}
Procedure TMapRangeCodeSelectDialog.InitializeForm(_RangeType : Integer;
_SelectedCodesList : TStringList);
var
CodeField, DescriptionField : String;
CodeTable : TTable;
DescriptionLength : Integer;
begin
RangeType := _RangeType;
SelectedCodesList := _SelectedCodesList;
SelectedCodesList.Clear;
CodeTable := TTable.Create(nil);
CodeTable.TableType := ttDBase;
CodeTable.DatabaseName := 'PASSystem';
case RangeType of
rtZoningCodes :
begin
Caption := 'Choose which zoning code(s) to display.';
CodeTable.TableName := 'zinvzoningcodetbl';
DescriptionLength := 15;
CodeField := 'MainCode';
DescriptionField := 'Description';
end; {rtZoningCodes}
rtNeighborhoodCodes :
begin
Caption := 'Choose which neighborhood code(s) to display.';
CodeTable.TableName := 'zinvnghbrhdcodetbl';
DescriptionLength := 15;
CodeField := 'MainCode';
DescriptionField := 'Description';
end; {rtNeighborhoodCodes}
rtSwisCodes :
begin
Caption := 'Choose which swis code(s) to display.';
CodeTable.TableName := 'nswistbl';
DescriptionLength := 15;
CodeField := 'SwisCode';
DescriptionField := 'MunicipalityName';
end; {rtSwisCodes}
rtSchoolCodes :
begin
Caption := 'Choose which school code(s) to display.';
CodeTable.TableName := 'nschooltbl';
DescriptionLength := 15;
CodeField := 'SchoolCode';
DescriptionField := 'SchoolName';
end; {rtSchoolCodes}
rtPropertyClass :
begin
Caption := 'Choose which property class code(s) to display.';
CodeTable.TableName := 'zpropclstbl';
DescriptionLength := 18;
CodeField := 'MainCode';
DescriptionField := 'Description';
end; {rtNeighborhoodCodes}
end; {case RangeType of}
try
CodeTable.Open;
except
MessageDlg('Error opening code table ' + CodeTable.TableName + '.',
mtError, [mbOK], 0);
end;
FillOneListBox(CodeListBox, CodeTable,
CodeField, DescriptionField,
DescriptionLength, False, (DescriptionLength > 0),
NextYear, GlblNextYear);
SelectItemsInListBox(CodeListBox);
CodeListBox.TopIndex := 1;
try
CodeTable.Close;
CodeTable.Free;
except
end;
end; {InitializeForm}
{=========================================================}
Procedure TMapRangeCodeSelectDialog.OKButtonClick(Sender: TObject);
var
I, DashPos : Integer;
begin
with CodeListBox do
For I := 0 to (Items.Count - 1) do
If Selected[I]
then
begin
DashPos := Pos('-', Items[I]);
SelectedCodesList.Add(Copy(Items[I], 1, (DashPos - 2)));
end;
ModalResult := mrOK;
end; {OKButtonClick}
end.
|
unit FIToolkit.Logger.Default;
interface
uses
System.SysUtils,
FIToolkit.Logger.Intf;
procedure InitConsoleLog(DebugMode : Boolean);
procedure InitFileLog(const FileName : TFileName);
function Log : IAbstractLogger;
type
{$RTTI EXPLICIT METHODS([vcPrivate, vcProtected, vcPublic, vcPublished])}
TLoggable = class abstract (TObject);
implementation
uses
System.Classes, System.IOUtils,
FIToolkit.Logger.Impl, FIToolkit.Logger.Types, FIToolkit.Logger.Consts,
FIToolkit.Commons.Utils;
var
LoggingFacility : IMetaLogger;
type
TConsoleOutput = class abstract (TPlainTextOutput)
strict protected
procedure WriteLine(const S : String); override;
end;
TDebugConsoleOutput = class (TConsoleOutput);
TPrettyConsoleOutput = class (TConsoleOutput)
protected
function FormatPreamble(Instant : TLogTimestamp) : String; override;
end;
TTextStreamOutput = class (TPlainTextOutput)
strict private
FOwnsWriter : Boolean;
FWriter : TStreamWriter;
strict protected
procedure WriteLine(const S : String); override;
public
constructor Create(Writer : TStreamWriter; OwnsWriter : Boolean); reintroduce;
destructor Destroy; override;
end;
{ Export }
procedure InitConsoleLog(DebugMode : Boolean);
begin
with LoggingFacility.AddLogger(TLogger.Create) do
if DebugMode then
begin
AllowedItems := [liMessage, liSection, liMethod];
SeverityThreshold := SEVERITY_DEBUG;
AddOutput(TDebugConsoleOutput.Create);
end
else
begin
AllowedItems := [liMessage, liSection];
SeverityThreshold := SEVERITY_INFO;
AddOutput(TPrettyConsoleOutput.Create);
end;
end;
procedure InitFileLog(const FileName : TFileName);
begin
with LoggingFacility.AddLogger(TLogger.Create) do
begin
AllowedItems := [liMessage, liSection, liMethod];
SeverityThreshold := SEVERITY_DEBUG;
AddOutput(TTextStreamOutput.Create(TFile.CreateText(FileName), True));
end;
end;
function Log : IAbstractLogger;
begin
Result := LoggingFacility;
end;
{ TConsoleOutput }
procedure TConsoleOutput.WriteLine(const S : String);
begin
PrintLn(S);
end;
{ TPrettyConsoleOutput }
function TPrettyConsoleOutput.FormatPreamble(Instant : TLogTimestamp) : String;
begin
Result := String.Empty;
end;
{ TTextStreamOutput }
constructor TTextStreamOutput.Create(Writer : TStreamWriter; OwnsWriter : Boolean);
begin
inherited Create;
FOwnsWriter := OwnsWriter;
FWriter := Writer;
end;
destructor TTextStreamOutput.Destroy;
begin
if FOwnsWriter then
FreeAndNil(FWriter);
inherited Destroy;
end;
procedure TTextStreamOutput.WriteLine(const S : String);
begin
FWriter.WriteLine(S);
end;
initialization
LoggingFacility := TMetaLogger.Create;
finalization
LoggingFacility := nil;
end.
|
unit ncaFrmTipos;
{
ResourceString: Dario 11/03/13
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ncClassesBase, StdCtrls, CheckLst, cxLookAndFeelPainters, cxButtons, Menus,
cxGraphics, cxLookAndFeels, cxControls, cxContainer, cxEdit, cxCheckBox,
LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel;
type
TFrmTipos = class(TForm)
btnTodos: TcxButton;
btnNenhum: TcxButton;
btnOk: TcxButton;
btnCancelar: TcxButton;
LMDSimplePanel1: TLMDSimplePanel;
tr8: TcxCheckBox;
tr17: TcxCheckBox;
tr14: TcxCheckBox;
tr16: TcxCheckBox;
tr13: TcxCheckBox;
tr10: TcxCheckBox;
tr9: TcxCheckBox;
tr18: TcxCheckBox;
tr7: TcxCheckBox;
tr6: TcxCheckBox;
tr5: TcxCheckBox;
tr4: TcxCheckBox;
tr3: TcxCheckBox;
tr2: TcxCheckBox;
procedure btnTodosClick(Sender: TObject);
procedure btnNenhumClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
PTipos : PArrayTipoTran;
{ Public declarations }
function CB(aTipo: Byte): TcxCheckBox;
function Selecionar(sl: TStrings): Boolean;
function Tudo: Boolean;
function Nada: Boolean;
end;
var
FrmTipos: TFrmTipos;
implementation
{$R *.DFM}
function TFrmTipos.Selecionar(sl: TStrings): Boolean;
var
I : Integer;
C : TcxCheckBox;
begin
for i := 1 to trMax do begin
C := CB(i);
if assigned(C) then
C.Checked := (sl.Values[IntToStr(I)]='1');
end;
ShowModal;
if ModalResult=mrOk then begin
Result := True;
if Tudo or Nada then
sl.Clear
else
for i := 1 to trMax do begin
C := CB(i);
if assigned(C) then
sl.Values[i.ToString] := Byte(C.Checked).ToString;
end;
end else
Result := False;
end;
function TFrmTipos.Tudo: Boolean;
var
I : Integer;
C : TcxCheckBox;
begin
Result := False;
for i := 1 to trMax do begin
C := CB(i);
if assigned(C) and (not C.Checked) then Exit;
end;
Result := True;
end;
procedure TFrmTipos.btnTodosClick(Sender: TObject);
var
I : Integer;
C : TcxCheckBox;
begin
for i := 1 to trMax do begin
C := CB(i);
if assigned(C) then C.Checked := True;
end;
end;
procedure TFrmTipos.btnNenhumClick(Sender: TObject);
var
I : Integer;
C : TcxCheckBox;
begin
for i := 1 to trMax do begin
C := CB(i);
if assigned(C) then C.Checked := False;
end;
end;
procedure TFrmTipos.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
function TFrmTipos.Nada: Boolean;
var
I : Integer;
C : TcxCheckBox;
begin
Result := False;
for i := 1 to trMax do begin
C := CB(i);
if assigned(C) and C.Checked then Exit;
end;
Result := True;
end;
function TFrmTipos.CB(aTipo: Byte): TcxCheckBox;
var C : TComponent;
begin
C := FindComponent('tr'+aTipo.ToString);
if C=nil then
Result := nil else
Result := TcxCheckBox(C);
end;
end.
|
unit DTurn;
interface
uses Windows, SysUtils, classes, WinSock, DSSocket, DSMessage;
type
TDTurnClient = class(TObject)
private
FBindAddr: TSockAddrIn;
FLocalIP: string;
FLocalPort: word;
FStartLocalPort: word;
FTimeOut: Integer;
FUdpSocket: THandle;
procedure BindSocket;
function IsSameLocalAddress(AIP: TDSIPAddress): Boolean;
function ReciveStream(AStream: TStream; AServer: String; APort: Integer):
Boolean;
function SendStream(AStream: TStream; AServer: String; APort: Integer): Boolean;
procedure SetLocalPort(const Value: word);
public
constructor Create;
destructor Destroy; override;
function Query(AServer: string; APort: integer): TDSResult;
function SendCommand(AMessage: IDSMessage; AServer: string; APort: Integer):
IDSMessage; overload;
function SendCommand(AMessage: IDSMessage; AIP: TDSIPAddress): IDSMessage;
overload;
property LocalIP: string read FLocalIP write FLocalIP;
property LocalPort: word read FLocalPort write SetLocalPort;
property TimeOut: Integer read FTimeOut write FTimeOut;
end;
implementation
{TDStunClient}
constructor TDTurnClient.Create;
begin
inherited;
FStartLocalPort := 3000;
FLocalIP := '0.0.0.0';
FUdpSocket := Socket(AF_INET,SOCK_DGRAM,0);
TimeOut := 3000;
end;
destructor TDTurnClient.Destroy;
begin
closesocket(FUdpSocket);
inherited;
end;
procedure TDTurnClient.BindSocket;
begin
FBindAddr.sin_family := AF_INET;
if LocalIP <> '' then
FBindAddr.sin_addr.S_addr := Inet_Addr(PChar(FLocalIP))
else
FBindAddr.sin_addr.S_addr := INADDR_ANY;
FLocalPort := FStartLocalPort;
while FLocalPort < 65535 do
begin
FBindAddr.sin_port := htons(FLocalPort);
if bind(FUdpSocket, FBindAddr, sizeof(FBindAddr)) <> SOCKET_ERROR then
begin
setsockopt(FUdpSocket, SOL_SOCKET, SO_RCVTIMEO,
@FTimeOut, SizeOf(FTimeOut));
Exit;
end;
inc(FLocalPort);
end;
raise Exception.Create('bind faild!');
end;
function TDTurnClient.IsSameLocalAddress(AIP: TDSIPAddress): Boolean;
type
TaPInAddr = array [0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
tmpBuf: array [0..255] of char;
tmpHostEnt: PHostEnt;
tmpPptr : PaPInAddr;
I: Integer;
tmpStr1, tmpStr2: String;
begin
GetHostName(tmpBuf, SizeOf(tmpBuf));
tmpHostEnt := GetHostByName(tmpBuf);
tmpPptr := PaPInAddr(tmpHostEnt^.h_addr_list);
I := 0;
tmpStr1 := IPAddressToString(AIP);
while tmpPptr^[I] <> nil do
begin
tmpStr2 := StrPas(inet_ntoa(tmpPptr^[I]^));
if tmpStr1 = tmpStr2 then
begin
Result := True;
Exit;
end;
Inc(I);
end;
Result := False;
end;
{
In test I, the client sends a STUN Binding Request to a server, without any flags set in the
CHANGE-REQUEST attribute, and without the RESPONSE-ADDRESS attribute. This causes the server
to send the response back to the address and port that the request came from.
In test II, the client sends a Binding Request with both the "change IP" and "change port" flags
from the CHANGE-REQUEST attribute set.
In test III, the client sends a Binding Request with only the "change port" flag set.
+--------+
| Test |
| I |
+--------+
|
|
V
/\ /\
N / \ Y / \ Y +--------+
UDP <-------/Resp\--------->/ IP \------------->| Test |
Blocked \ ? / \Same/ | II |
\ / \? / +--------+
\/ \/ |
| N |
| V
V /\
+--------+ Sym. N / \
| Test | UDP <---/Resp\
| II | Firewall \ ? /
+--------+ \ /
| \/
V |Y
/\ /\ |
Symmetric N / \ +--------+ N / \ V
NAT <--- / IP \<-----| Test |<--- /Resp\ Open
\Same/ | I | \ ? / Internet
\? / +--------+ \ /
\/ \/
| |Y
| |
| V
| Full
| Cone
V /\
+--------+ / \ Y
| Test |------>/Resp\---->Restricted
| III | \ ? /
+--------+ \ /
\/
|N
| Port
+------>Restricted
}
function TDTurnClient.Query(AServer: string; APort: integer): TDSResult;
var
tmpRequest1, tmpRequest2, tmpRequest12, tmpRequest3,
tmpResponse1, tmpResponse2, tmpResponse12, tmpResponse3: IDSMessage;
begin
BindSocket;
Result.NetType := dsntUdpBlocked;
///test 1(1)
tmpRequest1 := TDSMessage.Create;
tmpRequest1.MessageType := DSMT_SharedSecretRequest;
tmpRequest1.ChangeRequestAttribute := TDSChangeRequestAttribute.Create;
(tmpRequest1.ChangeRequestAttribute as IDSAttribute).AttributeType := DSAT_ChangeRequest;
tmpRequest1.ChangeRequestAttribute.ChangeIP := False;
tmpRequest1.ChangeRequestAttribute.ChangePort := False;
tmpResponse1 := SendCommand(tmpRequest1, AServer, APort);
if tmpResponse1 <> nil then
begin
///test 2
tmpRequest2 := TDSMessage.Create;
tmpRequest2.MessageType := DSMT_BindingRequest;
tmpRequest2.ChangeRequestAttribute := TDSChangeRequestAttribute.Create;
(tmpRequest2.ChangeRequestAttribute as IDSAttribute).AttributeType := DSAT_ChangeRequest;
tmpRequest2.ChangeRequestAttribute.ChangeIP := True;
tmpRequest2.ChangeRequestAttribute.ChangePort := True;
if IsSameLocalAddress(tmpResponse1.MappedAddress.IPAddress) then
begin
///no nat
tmpResponse2 := SendCommand(tmpRequest2, AServer, APort);
if tmpResponse2 <> nil then
begin
///Open Internet
Result.NetType := dsntOpenInternet;
Result.PublicIP := tmpResponse2.MappedAddress.IPAddress;
end else
begin
///Symmetric UDP firewall
Result.NetType := dsntSymmetricUdpFirewall;
Result.PublicIP := tmpResponse1.MappedAddress.IPAddress;
end;
end else
begin
tmpResponse2 := SendCommand(tmpRequest2, AServer, APort);
// if SameIPAddress(tmpResponse2.MappedAddress.IPAddress,
// tmpResponse1.MappedAddress.IPAddress) then
if tmpResponse2 <> nil then
begin
/// full cone nat
Result.NetType := dsntFullCone;
Result.PublicIP := tmpResponse2.MappedAddress.IPAddress;
end else
begin
///TEST 1(2)
tmpRequest12 := TDSMessage.Create;
tmpRequest12.MessageType := DSMT_BindingRequest;
tmpRequest12.ChangeRequestAttribute := TDSChangeRequestAttribute.Create;
(tmpRequest12.ChangeRequestAttribute as IDSAttribute).AttributeType := DSAT_ChangeRequest;
tmpRequest12.ChangeRequestAttribute.ChangeIP := False;
tmpRequest12.ChangeRequestAttribute.ChangePort := False;
tmpResponse12 := SendCommand(tmpRequest12,
tmpResponse1.ChangedAddress.IPAddress);
if tmpResponse12 <> nil then
begin
///Symmetric NAT
if not SameIPAddress(tmpResponse12.MappedAddress.IPAddress,
tmpResponse1.MappedAddress.IPAddress) then
begin
Result.NetType := dsntSymmetric;
Result.PublicIP := tmpResponse1.MappedAddress.IPAddress;
end else
begin
tmpRequest3 := TDSMessage.Create;
tmpRequest3.MessageType := DSMT_BindingRequest;
tmpRequest3.ChangeRequestAttribute := TDSChangeRequestAttribute.Create;
(tmpRequest3.ChangeRequestAttribute as IDSAttribute).AttributeType := DSAT_ChangeRequest;
tmpRequest3.ChangeRequestAttribute.ChangeIP := False;
tmpRequest3.ChangeRequestAttribute.ChangePort := True;
tmpResponse3 := SendCommand(tmpRequest3,
tmpResponse1.ChangedAddress.IPAddress);
if SameIPAddress(tmpResponse3.MappedAddress.IPAddress,
tmpResponse1.MappedAddress.IPAddress) then
begin
/// Restricted
Result.NetType := dsntRestrictedCone;
Result.PublicIP := tmpResponse1.MappedAddress.IPAddress;
end else
begin
///map Restricted
Result.NetType := dsntPortRestrictedCone;
Result.PublicIP := tmpResponse1.MappedAddress.IPAddress;
end;
end;
end;
end;
end;
end;
end;
function TDTurnClient.ReciveStream(AStream: TStream; AServer: String; APort:
Integer): Boolean;
var
tmpBuf: array [0..512] of Byte;
tmpSize: Integer;
tmpAddr: TSockAddrIn;
tmpAddrLength: Integer;
begin
Result := False;
FillChar(tmpBuf, SizeOf(tmpBuf), #0);
tmpAddr := GetSocketAddr(AServer, APort);
tmpAddrLength := SizeOf(tmpAddr);
tmpSize := recvfrom(FUdpSocket, tmpBuf, Length(tmpBuf), 0, tmpAddr, tmpAddrLength);
if tmpSize = SOCKET_ERROR then Exit;
AStream.Write(tmpBuf, tmpSize);
Result := tmpSize <> 0;
end;
function TDTurnClient.SendCommand(AMessage: IDSMessage; AServer: string; APort:
Integer): IDSMessage;
var
tmpStream: TStream;
tmpStart: Cardinal;
tmpMessage: IDSMessage;
begin
Result := nil;
tmpStream := TMemoryStream.Create;
try
tmpStart := GetTickCount;
tmpStream.Size := 0;
AMessage.Build(tmpStream);
if not SendStream(tmpStream, AServer, APort) then Exit;
while GetTickCount - tmpStart < 2000 do
begin
if WaitForData(FUdpSocket, 100, AServer, APort) then
begin
tmpStream.Size := 0;
if not ReciveStream(tmpStream, AServer, APort) then continue;
tmpMessage := TDSMessage.Create;
tmpMessage.Parser(tmpStream);
if SameGUID(AMessage.TransactionID, tmpMessage.TransactionID) then
begin
Result := tmpMessage;
Exit;
end;
end;
end;
finally
FreeAndNil(tmpStream);
end;
end;
function TDTurnClient.SendCommand(AMessage: IDSMessage; AIP: TDSIPAddress):
IDSMessage;
begin
Result := SendCommand(AMessage, IPAddressToString(AIP), IPAdressToPort(AIP));
end;
function TDTurnClient.SendStream(AStream: TStream; AServer: String; APort:
Integer): Boolean;
var
tmpBuf: array [0..511] of Char;
tmpAddr: TSockAddrIn;
tmpAddrLength: Integer;
begin
AStream.Position := 0;
AStream.Read(tmpBuf, AStream.Size);
tmpAddr := GetSocketAddr(AServer, APort);
tmpAddrLength := SizeOf(tmpAddr);
Result := sendto(FUdpSocket, tmpBuf, AStream.Size, 0, tmpAddr, tmpAddrLength)
<> SOCKET_ERROR;
// FSocket.SendBuf(tmpBuf, AStream.Size);
end;
procedure TDTurnClient.SetLocalPort(const Value: word);
begin
FStartLocalPort := Value;
FLocalPort := Value;
end;
end.
|
unit FIToolkit.Commons.Exceptions;
interface
uses
System.SysUtils;
type
ECustomExceptionClass = class of ECustomException;
ECustomException = class abstract (Exception)
private
function GetClassType : ECustomExceptionClass;
protected
function GetDefaultMessage : String; virtual;
public
constructor Create; overload;
constructor CreateFmt(const Args : array of const); overload;
end;
procedure RegisterExceptionMessage(AnExceptionClass : ECustomExceptionClass; const Msg : String);
implementation
uses
System.Generics.Collections,
FIToolkit.Commons.Consts;
type
TExceptionMessageMap = class (TDictionary<ECustomExceptionClass, String>)
strict private
class var
FStaticInstance : TExceptionMessageMap;
private
class constructor Create;
class destructor Destroy;
protected
class property StaticInstance : TExceptionMessageMap read FStaticInstance;
end;
{ Utils }
procedure RegisterExceptionMessage(AnExceptionClass : ECustomExceptionClass; const Msg : String);
begin
TExceptionMessageMap.StaticInstance.Add(AnExceptionClass, Msg);
end;
{ ECustomException }
constructor ECustomException.Create;
begin
inherited Create(GetDefaultMessage);
end;
constructor ECustomException.CreateFmt(const Args : array of const);
begin
inherited CreateFmt(GetDefaultMessage, Args);
end;
function ECustomException.GetClassType : ECustomExceptionClass;
begin
Result := ECustomExceptionClass(ClassType);
end;
function ECustomException.GetDefaultMessage : String;
begin
with TExceptionMessageMap.StaticInstance do
if ContainsKey(Self.GetClassType) then
Result := Items[Self.GetClassType]
else
Result := RSDefaultErrMsg;
end;
{ TExceptionMessageMap }
class constructor TExceptionMessageMap.Create;
begin
FStaticInstance := TExceptionMessageMap.Create;
end;
class destructor TExceptionMessageMap.Destroy;
begin
FreeAndNil(FStaticInstance);
end;
end.
|
unit UnitMessage;
{
OSS Mail Server v1.0.0 - Message Form
The MIT License (MIT)
Copyright (c) 2012 Guangzhou Cloudstrust Software Development Co., Ltd
http://cloudstrust.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.
}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs;
type
TfrmMessage = class(TForm)
styleMessage: TStyleBook;
btnPrimary: TButton;
laTitle: TLabel;
laMessage: TLabel;
btnSecondary: TButton;
procedure FormShow(Sender: TObject);
private
{ Private declarations }
title, msg, btn1, btn2: string;
function Popup(const title, msg, btn1: string; const btn2: string = ''): integer;
public
{ Public declarations }
end;
function MessageDlg(const title, msg, btn1: string; const btn2: string = ''): integer;
var
frmMessage: TfrmMessage;
implementation
{$R *.fmx}
{ TfrmMessage }
function TfrmMessage.Popup(const title, msg, btn1, btn2: string): integer;
begin
self.title := title;
self.msg := msg;
self.btn1 := btn1;
self.btn2 := btn2;
result := self.ShowModal;
end;
procedure TfrmMessage.FormShow(Sender: TObject);
var
h, w: integer;
begin
h := Application.MainForm.Height;
w := Application.MainForm.Width;
self.Top := (h - self.Height) div 2;
self.Left := 0;
self.Width := w;
self.laTitle.Text := self.title;
self.laMessage.Text := self.msg;
self.btnPrimary.Text := self.btn1;
self.btnSecondary.Text := self.btn2;
if self.btn2 = '' then
begin
self.btnSecondary.Visible := false;
self.btnPrimary.Position.X := self.btnSecondary.Position.X;
end
end;
function MessageDlg(const title, msg, btn1, btn2: string): integer;
var
frmMessage: TfrmMessage;
begin
frmMessage := TfrmMessage.Create(nil);
result := frmMessage.Popup(title, msg, btn1, btn2);
frmMessage.Free;
end;
end.
|
<h3>Track sanitizer pattern overview</h3>
@using (Html.BeginForm("Save", "GDPRApiDemoPage", null, FormMethod.Post, new { id = "PatternForm" }))
{
<div class="row">
<div class="span4">
<div>
<h4>Plain Text Pattern</h4>
<textarea cols="40" rows="5" name="plaintextFilter" placeholder="Patterns are separated by line break">@Html.Raw(Model.PlainTextFilterPatterns != null ? string.Join("\r\n", Model.PlainTextFilterPatterns) : string.Empty)</textarea>
</div>
<div>
<h4>Wildcard Pattern</h4>
<textarea cols="40" rows="5" name="wildcardFilter" placeholder="Patterns are separated by line break">@Html.Raw(Model.WildcardFilterPatterns != null ? string.Join("\r\n", Model.WildcardFilterPatterns) : string.Empty)</textarea>
</div>
<div>
<h4>Regex Pattern</h4>
<textarea cols="40" rows="5" name="regexFilter" placeholder="Patterns are separated by line break">@Html.Raw(Model.RegexFilterPatterns != null ? string.Join("\r\n", Model.RegexFilterPatterns) : string.Empty)</textarea>
</div>
<button type="submit" class="btn btn-success">Save patterns</button>
<div id="result"></div>
</div>
</div>
}
<script>
$(function () {
$('#PatternForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(`<div class="alert alert-success" id="PatternFormAlert">Patterns updated.</div>`);
setTimeout(function () {
$('#PatternFormAlert').fadeOut().remove();
}, 3000);
}
});
return false;
});
});
</script>
|
unit MyMessenger;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TMsgForm = class(TForm)
MemPanel: TPanel;
pnlGridHeader: TPanel;
Label1: TLabel;
edtSearch: TEdit;
chkSearchName: TCheckBox;
chkSearchPhone: TCheckBox;
pnlHeader: TPanel;
lblCaption: TLabel;
btnClose: TButton;
btnAdd: TButton;
Talk_Source: TDataSource;
MSGGrid: TDBGrid;
Timer1: TTimer;
procedure edtSearchKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnCloseClick(Sender: TObject);
procedure deleteClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MsgForm: TMsgForm;
implementation
{$R *.dfm}
uses DataAccessModule, Main;
procedure TMsgForm.deleteClick(Sender: TObject);
var
RentYn, Title, Msg: string;
begin
Title := DataAccess.qrytalk.FieldByName('USER_ID').AsString;
Msg := Format('[%s] 님의 메시지를 지우겠습니까?', [Title]);
if MessageDlg(Msg, mtInformation, [mbYes, mbNo], 0) = mrNo then
Exit;
DataAccess.qrytalk.Delete;
end;
procedure TMsgForm.btnCloseClick(Sender: TObject);
begin
MsgForm.Close;
end;
procedure TMsgForm.edtSearchKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); // 검색
var
Filter: string;
begin
Filter := '';
if edtSearch.Text <> '' then
begin
if chkSearchName.Checked then
Filter := Format('USER_ID like ''%%%s%%''', [edtSearch.Text]);
if chkSearchPhone.Checked then
begin
if Filter <> '' then
Filter := Filter + ' or ';
Filter := Filter + Format('MES_CONTENT like ''%%%s%%''', [edtSearch.Text]);
end;
end;
DataAccess.qrytalk.Filter := Filter;
DataAccess.qrytalk.Filtered := (Filter <> '');
end;
procedure TMsgForm.Timer1Timer(Sender: TObject);
begin
if (DataAccess.qrytalk.RecordCount > 0) then
begin
MSGGrid.Refresh;
end;
end;
end.
|
PROGRAM Zaehlproblem;
const
MAX = 100;
type
IntegerArray = ARRAY [1..MAX] OF integer;
FUNCTION DifferentValues(a: IntegerArray; n: integer): integer;
var i, numberOfIntegers: integer;
BEGIN (* DifferentValues *)
numberOfIntegers := 0;
FOR i := 1 TO n DO BEGIN
IF (i > 1) THEN BEGIN
IF (a[i] = a[i - 1]) THEN BEGIN
continue;
END ELSE BEGIN
Inc(numberOfIntegers);
END; (* IF *)
END ELSE BEGIN
Inc(numberOfIntegers);
END; (* IF *)
END; (* FOR i *)
DifferentValues := numberOfIntegers;
END; (* DifferentValues *)
var n, i: integer;
var arr: IntegerArray;
BEGIN (* Zaehlproblem *)
Write('n: ');
Read(n);
Write('Zahlen: ');
FOR i := 1 TO n DO BEGIN
Read(arr[i]);
END; (* FOR *)
Write('Anzahl Zahlen: ', DifferentValues(arr, n));
END. (* Zaehlproblem *) |
unit Stats.DBConnectionHandler;
interface
uses
Stats.Constant,
Variants,
//Connection/Drivers
FireDAC.Comp.Client,
FireDAC.Stan.Def,
FireDAC.Phys,
//PostgreSQL
FireDAC.Phys.PG,
//MySQL
FireDAC.Phys.MySQL,
//SQLite
FireDAC.Phys.SQLite,
//Insert
FireDAC.Stan.Async,
FireDAC.VCLUI.Wait, FireDAC.Stan.Param;
const
pathPostgreSQLDriver = 'DBDrivers\PostgreSQLDriver\libpq.dll';
csPostgreSQL = 'DBDrivers\PostgreSQL.ini';
pathMySQLDriver = 'DBDrivers\MySQLDriver\libmysql.dll';
csMySQL = 'DBDrivers\MySQL.ini';
pathSQLiteDriver = 'DBDrivers\SQLiteDriver\sqlite3.dll';
csSQLite = 'DBDrivers\SQLite.ini';
EVENT_NUM_INSERTS = 1000;
DBEventsParamCounts = 7;
POSITION_NUM_INSERTS = 9000;
DBPositionParamCounts = 10;
type
TDBConnectionHandler = class abstract
strict private
aConnectionDriver: TFDPhysDriverLink;
aFireDACConnection: TFDConnection;
strict protected
function CreateAndLoadDriver(const paDriverFilePath: string): TFDPhysDriverLink; virtual; abstract;
public
property Connection: TFDConnection read aFireDACConnection;
property ConnectionDriverLink: TFDPhysDriverLink read aConnectionDriver;
function Connect: Boolean;
function Connected: Boolean;
constructor Create(const paDriverFilePath: string; const paInitConnectionFilePath: string);
destructor Destroy; override;
end;
TDBConnectionHandlerPostgreSQL = class(TDBConnectionHandler)
strict protected
function CreateAndLoadDriver(const paDriverFilePath: string): TFDPhysDriverLink; override;
public
constructor Create;
end;
TDBConnectionHandlerMySQL = class(TDBConnectionHandler)
strict protected
function CreateAndLoadDriver(const paDriverFilePath: string): TFDPhysDriverLink; override;
public
constructor Create;
end;
TDBConnectionHandlerSQLite = class(TDBConnectionHandler)
strict protected
function CreateAndLoadDriver(const paDriverFilePath: string): TFDPhysDriverLink; override;
public
constructor Create;
end;
TDatabaseHandler = class
strict private
aDBConectionHandler: TDBConnectionHandler;
aDatabaseType: TDatabaseType;
aFDSelectQuery: TFDQuery;
procEvent: TFDStoredProc;
procPosition:TFDStoredProc;
procPed: TFDStoredProc;
procPedModel: TFDStoredProc;
procPedTrace: TFDStoredProc;
procDropConstraints: TFDStoredProc;
procReloadConstraints: TFDStoredProc;
aFDEventsQuery: TFDQuery;
aFDPositionQuery: TFDQuery;
aFDPedQuery: TFDQuery;
aFDPedModelQuery: TFDQuery;
aFDPedTraceQuery: TFDQuery;
public
procedure CheckBuffers(paTable: TTraceType);
procedure StartTransaction();
procedure FinishTransaction();
procedure CreateAllTables(paDatabaseType: TDatabaseType; paTraceType: TTraceType);
procedure DropAllTables(paDatabaseType: TDatabaseType);
procedure DropAllConstraints();
procedure ReloadAllConstraints();
function DeleteAllTables(paTraceType: TTraceType;paModelID,paTraceID:Integer):Boolean;
function ExistsTable(paTableName:string):Boolean;
function PrepareInsert(paTable: TTraceType; paParams: array of Variant):Boolean;
function Select(paSqlText: string; out paQuery: TFDQuery):Boolean;
procedure InitStoredProcedures();
constructor Create(paDatabaseType: TDatabaseType);
destructor Destroy; override;
end;
implementation
uses
System.SysUtils,
System.Classes,
FireDAC.Stan.Option, System.Diagnostics,
Data.DB,
FireDAC.Stan.Intf;
{ TDBConnectionHandler }
function TDBConnectionHandler.Connect: Boolean;
begin
aFireDACConnection.Connected := True;
Result := aFireDACConnection.Connected;
end;
function TDBConnectionHandler.Connected: Boolean;
begin
Result := aFireDACConnection.Connected;
if( not Result) then
Result := Connect;
end;
constructor TDBConnectionHandler.Create(
const paDriverFilePath: string;
const paInitConnectionFilePath: string);
begin
aConnectionDriver := CreateAndLoadDriver(paDriverFilePath);
aFireDACConnection := TFDConnection.Create(nil);
aFireDACConnection.Params.LoadFromFile(paInitConnectionFilePath);
end;
destructor TDBConnectionHandler.Destroy;
begin
FreeAndNil(aFireDACConnection);
FreeAndNil(aConnectionDriver);
inherited;
end;
{ TDBConnectionHandlerPostgreSQL }
constructor TDBConnectionHandlerPostgreSQL.Create;
begin
inherited Create(pathPostgreSQLDriver, csPostgreSQL);
end;
function TDBConnectionHandlerPostgreSQL.CreateAndLoadDriver(const paDriverFilePath: string): TFDPhysDriverLink;
begin
Result := TFDPhysPgDriverLink.Create(nil);
Result.VendorLib := paDriverFilePath;
end;
{ TDBConnectionHandlerMySQL }
constructor TDBConnectionHandlerMySQL.Create;
begin
inherited Create(pathMySQLDriver, csMySQL);
end;
function TDBConnectionHandlerMySQL.CreateAndLoadDriver(const paDriverFilePath: string): TFDPhysDriverLink;
begin
Result := TFDPhysMySQLDriverLink.Create(nil);
Result.VendorLib := paDriverFilePath;
end;
{ TDBConnectionHandlerSQLite }
constructor TDBConnectionHandlerSQLite.Create;
begin
inherited Create(pathSQLiteDriver, csSQLite);
end;
function TDBConnectionHandlerSQLite.CreateAndLoadDriver(
const paDriverFilePath: string): TFDPhysDriverLink;
begin
Result := TFDPhysSQLiteDriverLink.Create(nil);
Result.VendorLib := paDriverFilePath;
end;
{ TDatabaseHandler }
procedure TDatabaseHandler.CheckBuffers(paTable: TTraceType);
//var
// arr: array of Variant;
begin
// if((aEventsCounter <> 0) and (paTable = ttPedEvents)) then
// Insert(paTable, arr);
//
// if((aPositionCounter <> 0) and (paTable = ttPedPositions)) then
// Insert(paTable, arr);
end;
constructor TDatabaseHandler.Create(paDatabaseType: TDatabaseType);
begin
case paDatabaseType of
dbPostgre:
begin
aDBConectionHandler := TDBConnectionHandlerPostgreSQL.Create;
aDBConectionHandler.Connection.ResourceOptions.SilentMode := True;
InitStoredProcedures;
end;
dbMySQL:
begin
aDBConectionHandler := TDBConnectionHandlerMySQL.Create;
aDBConectionHandler.Connection.ResourceOptions.SilentMode := True;
InitStoredProcedures
end;
dbSQLite:
begin
aDBConectionHandler := TDBConnectionHandlerSQLite.Create;
aDBConectionHandler.Connection.ResourceOptions.SilentMode := True;
aFDEventsQuery := TFDQuery.Create(nil);
aFDEventsQuery.Connection := aDBConectionHandler.Connection;
aFDEventsQuery.SQL.Text := 'insert into pedevents values(:paModelID, :paTraceID, :paReplicationNumber, :paPedID, :paEntityID, :paSimTime, :paEventType);';
aFDEventsQuery.Params.ArraySize := EVENT_NUM_INSERTS + 1;
aFDPositionQuery := TFDQuery.Create(nil);
aFDPositionQuery.Connection := aDBConectionHandler.Connection;
aFDPositionQuery.SQL.Text := 'insert into pedposition values(:paModelID, :paTraceID, :paReplicationNumber, :paPedID, :paSimTime, :paPosX, :paPosY, :paPosZ, :paRotation, :pazoneid);';
aFDPositionQuery.Params.ArraySize := POSITION_NUM_INSERTS + 1;
aFDPedQuery := TFDQuery.Create(nil);
aFDPedQuery.Connection := aDBConectionHandler.Connection;
aFDPedQuery.SQL.Text :='insert into simentity values(:paModelID,:paTraceID,:paReplicationNumber,:paEntityID,:paEntityPathID);';
aFDPedModelQuery := TFDQuery.Create(nil);
aFDPedModelQuery.Connection := aDBConectionHandler.Connection;
aFDPedModelQuery.SQL.Text:='insert into models values(:ModelID,:ModelName);';
aFDPedTraceQuery := TFDQuery.Create(nil);
aFDPedTraceQuery.Connection := aDBConectionHandler.Connection;
aFDPedTraceQuery.SQL.Text:='insert into traces values(:paTraceID, :paTraceName);';
end;
end;
aFDSelectQuery := TFDQuery.Create(nil);
aFDSelectQuery.Connection := aDBConectionHandler.Connection;
aFDSelectQuery.FetchOptions.Mode := fmAll ;
aFDSelectQuery.FetchOptions.CursorKind := ckAutomatic ;
aFDSelectQuery.FetchOptions.RowsetSize := 3000;
aFDSelectQuery.FetchOptions.Unidirectional := True;
aFDSelectQuery.UpdateOptions.RequestLive := False;
aDatabaseType := paDatabaseType;
// aFDEventsQuery := TFDQuery.Create(nil);
// aFDEventsQuery.Connection := aDBConectionHandler.Connection;
// aFDEventsQuery.SQL.Text := 'insert into PedEvents(EntityID, PedID, SimTime, EventType) values(:E,:D,:F,:G);';
// aFDEventsQuery.Params.ArraySize := EVENT_NUM_INSERTS + 1;
// aFDEventsQuery.ResourceOptions.CmdExecMode := amAsync;
// aEventsCounter := 0;
// SetLength(aEventsBuffer, EVENT_NUM_INSERTS + 1, DBEventsParamCounts);
//
// aFDPositionQuery := TFDQuery.Create(nil);
// aFDPositionQuery.Connection := aDBConectionHandler.Connection;
// aFDPositionQuery.SQL.Text := 'insert into pedposition(PedID,SimTime,PosX,PosY,PosZ,Rotation,ZoneID) values(:E,:D,:F,:G,:H,:I,:J);';
// aFDPositionQuery.Params.ArraySize := POSITION_NUM_INSERTS + 1;
//// aFDPositionQuery.ResourceOptions.CmdExecMode := amAsync;
// aPositionCounter := 0;
// SetLength(aPositionBuffer, POSITION_NUM_INSERTS + 1, DBPositionParamCounts);
//
// aFDPedQuery := TFDQuery.Create(nil);
// aFDPedQuery.Connection := aDBConectionHandler.Connection;
// aFDPedQuery.SQL.Text := 'insert into ped(PedID, PedPathID, ProjectID, ReplicationNumber) SELECT :E,:P,:D,:F WHERE NOT EXISTS (SELECT 1 FROM ped WHERE pedid=:E);';
//
// aPedCounter := 0;
end;
procedure TDatabaseHandler.CreateAllTables(
paDatabaseType: TDatabaseType; paTraceType: TTraceType);
var
qry: string;
exists: integer;
begin
if( (aDBConectionHandler <> nil) and (aDBConectionHandler.Connected))then
begin
case paDatabaseType of
dbPostgre:
begin
case paTraceType of
ttPedModel:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['public','models']);
if(exists < 1) then
begin
qry := 'CREATE TABLE models(ModelID integer, ModelName Varchar(20));';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedTrace:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['public','traces']);
if(exists < 1) then
begin
qry := 'CREATE TABLE traces(TraceID Integer, TraceName Varchar(20) );';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPed:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['public','simentity']);
if(exists < 1) then
begin
qry := 'CREATE TABLE simentity( ModelID Integer, TraceID Integer, ReplicationNumber Integer, EntityID Integer, EntityPath Integer);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedEvents:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['public','pedevents']);
if(exists < 1) then
begin
qry := 'CREATE TABLE pedevents(ModelID Integer, TraceID Integer, ReplicationNumber Integer, PedID Integer, EntityID Integer , SimTime Timestamp, EvenType Integer);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedPositions:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['public','pedposition']);
if(exists < 1) then
begin
qry := 'CREATE TABLE pedposition(ModelID Integer, TraceID Integer, ReplicationNumber Integer, PedID Integer, SimTime Double precision, PosX Double precision, PosY Double precision, PosZ Double precision,Rotation Double precision,ZoneID Integer);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedMacroGraph:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['public','macrograph']);
if(exists < 1) then
begin
qry := 'CREATE TABLE macrograph(ModelID Integer,TraceID Integer, ReplicationNumber Integer, EntityID Integer, SimTime Timestamp,Density Double precision);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
end;
end;
dbMySQL:
begin
case paTraceType of
ttPedModel:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['pedsim','models']);
if(exists < 1) then
begin
qry := 'CREATE TABLE models(ModelID integer, ModelName Varchar(20));';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedTrace:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['pedsim','traces']);
if(exists < 1) then
begin
qry := 'CREATE TABLE traces(TraceID Integer, TraceName Varchar(20) );';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPed:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['pedsim','simentity']);
if(exists < 1) then
begin
qry := 'CREATE TABLE simentity( ModelID Integer, TraceID Integer, ReplicationNumber Integer, EntityID Integer, EntityPath Integer);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedEvents:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['pedsim','pedevents']);
if(exists < 1) then
begin
qry := 'CREATE TABLE pedevents(ModelID Integer, TraceID Integer, ReplicationNumber Integer, PedID Integer, EntityID Integer , SimTime Timestamp, EvenType Integer);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedPositions:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['pedsim','pedposition']);
if(exists < 1) then
begin
qry := 'CREATE TABLE pedposition(ModelID Integer, TraceID Integer, ReplicationNumber Integer, PedID Integer, SimTime Double precision, PosX Double precision, PosY Double precision, PosZ Double precision,Rotation Double precision,ZoneID Integer);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedMacroGraph:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['pedsim','macrograph']);
if(exists < 1) then
begin
qry := 'CREATE TABLE macrograph(ModelID Integer,TraceID Integer, ReplicationNumber Integer, EntityID Integer, SimTime Timestamp,Density Double precision);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
end;
end;
dbSQLite:
begin
case paTraceType of
ttPedModel:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('SELECT count(*) FROM sqlite_master WHERE name=:tablename;', ['models']);
if(exists < 1) then
begin
qry := 'CREATE TABLE models(ModelID integer, ModelName Varchar(20));';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedTrace:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('SELECT count(*) FROM sqlite_master WHERE name=:tablename;', ['traces']);
if(exists < 1) then
begin
qry := 'CREATE TABLE traces(TraceID Integer, TraceName Varchar(20) );';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPed:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('SELECT count(*) FROM sqlite_master WHERE name=:tablename;', ['simentity']);
if(exists < 1) then
begin
qry := 'CREATE TABLE simentity( ModelID Integer, TraceID Integer, ReplicationNumber Integer, EntityID Integer, EntityPath Integer);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedEvents:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('SELECT count(*) FROM sqlite_master WHERE name=:tablename;', ['pedevents']);
if(exists < 1) then
begin
qry := 'CREATE TABLE pedevents(ModelID Integer, TraceID Integer, ReplicationNumber Integer, PedID Integer, EntityID Integer , SimTime Timestamp, EvenType Integer);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedPositions:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('SELECT count(*) FROM sqlite_master WHERE name=:tablename;', ['pedposition']);
if(exists < 1) then
begin
qry := 'CREATE TABLE pedposition(ModelID Integer, TraceID Integer, ReplicationNumber Integer, PedID Integer, SimTime Double precision, PosX Double precision, PosY Double precision, PosZ Double precision,Rotation Double precision,ZoneID Integer);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
ttPedMacroGraph:
begin
exists := aDBConectionHandler.Connection.ExecSQLScalar('SELECT count(*) FROM sqlite_master WHERE name=:tablename;', ['macrograph']);
if(exists < 1) then
begin
qry := 'CREATE TABLE macrograph(ModelID Integer,TraceID Integer, ReplicationNumber Integer, EntityID Integer, SimTime Timestamp,Density Double precision);';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
end;
end;
end;
end;
end;
function TDatabaseHandler.DeleteAllTables(
paTraceType: TTraceType;paModelID,paTraceID:Integer): Boolean;
begin
Result:= False;
case paTraceType of
ttPedModel:
begin
if not ExistsTable('models') then
Exit;
end;
ttPedTrace:
begin
if not ExistsTable('traces') then
Exit;
end;
ttPed:
begin
if not ExistsTable('simentity') then
Exit;
end;
ttPedEvents:
begin
if not ExistsTable('pedevents') then
Exit;
end;
ttPedPositions:
begin
if not ExistsTable('pedposition') then
Exit;
end;
ttPedMacroGraph:
begin
if not ExistsTable('macrograph') then
Exit;
end;
end;
case paTraceType of
ttPedMacroGraph:
begin
aDBConectionHandler.Connection.ExecSQL('delete from macroGraph where ModelID = :modelid and TraceID=:traceid;', [paModelID,paTraceID]);
end;
ttPedEvents:
begin
aDBConectionHandler.Connection.ExecSQL('delete from pedevents where ModelID = :modelid and TraceID=:traceid;', [paModelID,paTraceID]);
end;
ttPedPositions:
begin
aDBConectionHandler.Connection.ExecSQL('delete from pedposition where ModelID = :modelid and TraceID=:traceid;', [paModelID,paTraceID]);
end;
ttPed:
begin
aDBConectionHandler.Connection.ExecSQL('delete from simentity where ModelID = :modelid and TraceID=:traceid;', [paModelID,paTraceID]);
end;
ttPedTrace:
begin
aDBConectionHandler.Connection.ExecSQL('delete from traces where TraceID = :traceid;', [paTraceID]);
end;
ttPedModel:
begin
aDBConectionHandler.Connection.ExecSQL('delete from models where ModelID = :modelid;', [paModelID]);
end;
end;
Result:= True;
end;
destructor TDatabaseHandler.Destroy;
begin
FreeAndNil(aFDSelectQuery);
if(aDatabaseType = dbSQLite)then
begin
FreeAndNil(aFDEventsQuery);
FreeAndNil(aFDPositionQuery);
FreeAndNil(aFDPedQuery);
FreeAndNil(aFDPedModelQuery);
FreeAndNil(aFDPedTraceQuery);
end;
if((aDatabaseType = dbPostgre) or (aDatabaseType = dbMySQL))then
begin
FreeAndNil(procEvent);
FreeAndNil(procPosition);
FreeAndNil(procPed);
FreeAndNil(procPedModel);
FreeAndNil(procPedTrace);
FreeAndNil(procDropConstraints);
FreeAndNil(procReloadConstraints);
end;
FreeAndNil(aDBConectionHandler);
inherited;
end;
procedure TDatabaseHandler.DropAllConstraints;
begin
procDropConstraints.ExecProc;
end;
procedure TDatabaseHandler.DropAllTables(
paDatabaseType: TDatabaseType);
var
qry: string;
begin
case aDatabaseType of
dbPostgre:
begin
if( (aDBConectionHandler <> nil) and (aDBConectionHandler.Connected))then
begin
qry := 'drop table if exists macrograph cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists pedevents cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists pedposition cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists simentity cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists models cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists traces cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
dbMySQL:
begin
if( (aDBConectionHandler <> nil) and (aDBConectionHandler.Connected))then
begin
qry := 'drop table if exists macrograph cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists pedevents cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists pedposition cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists simentity cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists models cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists traces cascade;';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end ;
dbSQLite:
begin
if( (aDBConectionHandler <> nil) and (aDBConectionHandler.Connected))then
begin
qry := 'drop table if exists macrograph;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists pedevents;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists pedposition;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists simentity;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists models;';
aDBConectionHandler.Connection.ExecSQL(qry);
qry :='drop table if exists traces;';
aDBConectionHandler.Connection.ExecSQL(qry);
end;
end;
end;
// case paDatabaseType of
// dbPostgre:
// begin
//
// dbMySQL: ;
// dbSQLite: ;
// end;
end;
function TDatabaseHandler.ExistsTable(paTableName:string): Boolean;
var
return: integer;
begin
case aDatabaseType of
dbPostgre:
begin
return := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['public',paTableName]);
Result := return > 0;
end;
dbMySQL:
begin
return := aDBConectionHandler.Connection.ExecSQLScalar('select count(*) from information_schema.tables where (table_schema =:database) and (table_name = :table);', ['pedsim',paTableName]);
Result:= return > 0;
end;
dbSQLite:
begin
return:= aDBConectionHandler.Connection.ExecSQLScalar('SELECT count(*) FROM sqlite_master WHERE name=:tablename;', [paTableName]);
Result:= return > 0;
end;
end;
Result:= True;
end;
procedure TDatabaseHandler.FinishTransaction;
begin
aDBConectionHandler.Connection.Commit;
end;
procedure TDatabaseHandler.InitStoredProcedures;
begin
procEvent := TFDStoredProc.Create(nil);
procEvent.Connection := aDBConectionHandler.Connection;
procEvent.StoredProcName := 'insertPedEvents';
procEvent.Prepare;
procPosition := TFDStoredProc.Create(nil);
procPosition.Connection := aDBConectionHandler.Connection;
procPosition.StoredProcName := 'insertPedPosition';
procPosition.Prepare;
procPed := TFDStoredProc.Create(nil);
procPed.Connection := aDBConectionHandler.Connection;
procPed.StoredProcName := 'insertSimEntity';
procPed.Prepare;
procPedTrace := TFDStoredProc.Create(nil);
procPedTrace.Connection := aDBConectionHandler.Connection;
procPedTrace.StoredProcName := 'insertTraces';
procPedTrace.Prepare;
procPedModel := TFDStoredProc.Create(nil);
procPedModel.Connection := aDBConectionHandler.Connection;
procPedModel.StoredProcName := 'insertModels';
procPedModel.Prepare;
procDropConstraints := TFDStoredProc.Create(nil);
procDropConstraints.Connection := aDBConectionHandler.Connection;
procDropConstraints.StoredProcName := 'drop_constraints';
procDropConstraints.Prepare;
procReloadConstraints := TFDStoredProc.Create(nil);
procReloadConstraints.Connection := aDBConectionHandler.Connection;
procReloadConstraints.StoredProcName := 'reload_constraints';
procReloadConstraints.Prepare;
end;
function TDatabaseHandler.PrepareInsert(paTable: TTraceType;
paParams: array of Variant): Boolean;
var
count: Integer;
clock, StopWacth: TStopwatch;
time: Int64;
pedid,zoneid:integer;
simtime: extended;
x,y,z,rot:single;
b:boolean;
begin
if(aDatabaseType = dbSQLite)then
begin
case paTable of
ttPedModel:
begin
aFDPedModelQuery.Params[0].Value := paParams[0];
aFDPedModelQuery.Params[1].Value := paParams[1];
aFDPedModelQuery.ExecSQL;
end;
ttPedTrace:
begin
aFDPedTraceQuery.Params[0].Value := paParams[0];
aFDPedTraceQuery.Params[1].Value := paParams[1];
aFDPedTraceQuery.ExecSQL;
end;
ttPed:
begin
aFDPedQuery.Params[0].Value := paParams[0];
aFDPedQuery.Params[1].Value := paParams[1];
aFDPedQuery.Params[2].Value := paParams[2];
aFDPedQuery.Params[3].Value := paParams[3];
aFDPedQuery.Params[4].Value := paParams[4];
aFDPedQuery.ExecSQL;
end;
ttPedEvents:
begin
aFDEventsQuery.Params[0].Value := paParams[0];
aFDEventsQuery.Params[1].Value := paParams[1];
aFDEventsQuery.Params[2].Value := paParams[2];
aFDEventsQuery.Params[3].Value := paParams[3];
aFDEventsQuery.Params[4].Value := paParams[4];
aFDEventsQuery.Params[5].Value := paParams[5];
aFDEventsQuery.Params[6].Value := paParams[6];
aFDEventsQuery.ExecSQL;
end;
ttPedPositions:
begin
aFDPositionQuery.Params[0].Value := paParams[0];
aFDPositionQuery.Params[1].Value:= paParams[1];
aFDPositionQuery.Params[2].Value := paParams[2];
aFDPositionQuery.Params[3].Value := paParams[3];
aFDPositionQuery.Params[4].Value:= paParams[4];
aFDPositionQuery.Params[5].Value := paParams[5];
aFDPositionQuery.Params[6].Value := paParams[6];
aFDPositionQuery.Params[7].Value := paParams[7];
aFDPositionQuery.Params[8].Value := paParams[8];
aFDPositionQuery.Params[9].Value := paParams[9];
aFDPositionQuery.ExecSQL;
end;
end;
end;
if((aDatabaseType = dbPostgre) or (aDatabaseType = dbMySQL))then
begin
case paTable of
ttPedModel:
begin
procPedModel.Params[0].Value := paParams[0];
procPedModel.Params[1].Value := paParams[1];
procPedModel.ExecProc;
end;
ttPedTrace:
begin
procPedTrace.Params[0].Value := paParams[0];
procPedTrace.Params[1].Value := paParams[1];
procPedTrace.ExecProc;
end;
ttPed:
begin
procPed.Params[0].Value := paParams[0];
procPed.Params[1].Value := paParams[1];
procPed.Params[2].Value := paParams[2];
procPed.Params[3].Value := paParams[3];
procPed.Params[4].Value := paParams[4];
procPed.ExecProc;
end;
ttPedEvents:
begin
// if(aEventsCounter < EVENT_NUM_INSERTS)then
// begin
// count := aEventsCounter;
procEvent.Params[0].Value := paParams[0];
procEvent.Params[1].Value := paParams[1];
procEvent.Params[2].Value := paParams[2];
procEvent.Params[3].Value := paParams[3];
procEvent.Params[4].Value := paParams[4];
procEvent.Params[5].Value := paParams[5];
procEvent.Params[6].Value := paParams[6];
procEvent.ExecProc;
// aFDEventsQuery.Params[0].AsIntegers[count] := paParams[0];
// aFDEventsQuery.Params[1].AsIntegers[count] := paParams[1];
// aFDEventsQuery.Params[2].AsDateTimes[count] := paParams[2];
// aFDEventsQuery.Params[3].AsIntegers[count] := paParams[3];
// Inc(aEventsCounter);
// end else
// begin
// count := aEventsCounter;
//
// procEvent.Params[0].Values[count] := paParams[0];
// procEvent.Params[1].Values[count] := paParams[1];
// procEvent.Params[2].Values[count] := paParams[2];
// procEvent.Params[3].Values[count] := paParams[3];
//
//// aFDEventsQuery.Params[0].AsIntegers[count] := paParams[0];
//// aFDEventsQuery.Params[1].AsIntegers[count] := paParams[1];
//// aFDEventsQuery.Params[2].AsDateTimes[count] := paParams[2];
//// aFDEventsQuery.Params[3].AsIntegers[count] := paParams[3];
//
// Inc(aEventsCounter);
//
// Insert(paTable,paParams);
// aEventsCounter := 0;
// end;
end;
ttPedPositions:
begin
// if(aPositionCounter < POSITION_NUM_INSERTS)then
// begin
// count := aPositionCounter;
procPosition.Params[0].Value := paParams[0];
procPosition.Params[1].Value:= paParams[1];
procPosition.Params[2].Value := paParams[2];
procPosition.Params[3].Value := paParams[3];
procPosition.Params[4].Value:= paParams[4];
procPosition.Params[5].Value := paParams[5];
procPosition.Params[6].Value := paParams[6];
procPosition.Params[7].Value := paParams[7];
procPosition.Params[8].Value := paParams[8];
procPosition.Params[9].Value := paParams[9];
procPosition.ExecProc;
// aFDPositionQuery.Params[0].AsIntegers[count] := paParams[0];
// aFDPositionQuery.Params[1].AsExtendeds[count] := paParams[1];
// aFDPositionQuery.Params[2].AsSingles[count] := paParams[2];
// aFDPositionQuery.Params[3].AsSingles[count] := paParams[3];
// aFDPositionQuery.Params[4].AsSingles[count] := paParams[4];
// aFDPositionQuery.Params[5].AsSingles[count] := paParams[5];
// aFDPositionQuery.Params[6].AsIntegers[count] := paParams[6];
//
// Inc(aPositionCounter);
// end else
// begin
// count := aPositionCounter;
//
// aFDPositionQuery.Params[0].AsIntegers[count] := paParams[0];
// aFDPositionQuery.Params[1].AsExtendeds[count] := paParams[1];
// aFDPositionQuery.Params[2].AsSingles[count] := paParams[2];
// aFDPositionQuery.Params[3].AsSingles[count] := paParams[3];
// aFDPositionQuery.Params[4].AsSingles[count] := paParams[4];
// aFDPositionQuery.Params[5].AsSingles[count] := paParams[5];
// aFDPositionQuery.Params[6].AsIntegers[count] := paParams[6];
//
// Inc(aPositionCounter);
//
// Insert(paTable,paParams);
// aPositionCounter := 0;
// end;
end;
end;
end;
end;
procedure TDatabaseHandler.ReloadAllConstraints;
begin
procReloadConstraints.ExecProc;
end;
function TDatabaseHandler.Select(paSqlText: string; out paQuery: TFDQuery):Boolean;
begin
Result := False;
aFDSelectQuery.ResourceOptions.DirectExecute := True;
aFDSelectQuery.Open(paSqlText);
paQuery := aFDSelectQuery;
Result := paQuery.Active;
end;
procedure TDatabaseHandler.StartTransaction;
begin
aDBConectionHandler.Connection.StartTransaction;
end;
end.
|
unit Vigilante.Infra.Build.JSONDataAdapter;
interface
uses
Vigilante.Aplicacao.SituacaoBuild, Vigilante.Build.Model, Module.ValueObject.URL;
type
IBuildJSONDataAdapter = interface(IInterface)
['{8B2C90E7-4B1A-4A49-9878-F249046D2488}']
function GetNome: string;
function GetURL: string;
function GetSituacao: TSituacaoBuild;
function GetBuilding: boolean;
function GetBuildAtual: integer;
function GetUltimoBuildFalha: integer;
function GetUltimoBuildSucesso: integer;
function GetURLUltimoBuild: IURL;
property Nome: string read GetNome;
property URL: string read GetURL;
property Situacao: TSituacaoBuild read GetSituacao;
property Building: boolean read GetBuilding;
property BuildAtual: integer read GetBuildAtual;
property UltimoBuildSucesso: integer read GetUltimoBuildSucesso;
property UltimoBuildFalha: integer read GetUltimoBuildFalha;
property URLUltimoBuild: IURL read GetURLUltimoBuild;
end;
implementation
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000-2002 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QConsts;
interface
const
// Delphi mime types
SDelphiBitmap = 'image/delphi.bitmap';
SDelphiComponent = 'application/delphi.component';
SDelphiPicture = 'image/delphi.picture';
SDelphiDrawing = 'image/delphi.drawing';
SBitmapExt = 'BMP';
resourcestring
SInvalidCreateWidget = 'Class %s could not create QT widget';
STooManyMessageBoxButtons = 'Too many buttons specified for message box';
SmkcBkSp = 'Backspace';
SmkcTab = 'Tab';
SmkcBackTab = 'BackTab';
SmkcEsc = 'Esc';
SmkcReturn = 'Return';
SmkcEnter = 'Enter';
SmkcSpace = 'Space';
SmkcPgUp = 'PgUp';
SmkcPgDn = 'PgDn';
SmkcEnd = 'End';
SmkcHome = 'Home';
SmkcLeft = 'Left';
SmkcUp = 'Up';
SmkcRight = 'Right';
SmkcDown = 'Down';
SmkcIns = 'Ins';
SmkcDel = 'Del';
SmkcShift = 'Shift+';
SmkcCtrl = 'Ctrl+';
SmkcAlt = 'Alt+';
SOpenFileTitle = 'Open';
SDuplicateReference = 'WriteObject called twice for the same instance';
SClassMismatch = 'Resource %s is of incorrect class';
SInvalidTabIndex = 'Tab index out of bounds';
SInvalidTabPosition = 'Tab position incompatible with current tab style';
SInvalidTabStyle = 'Tab style incompatible with current tab position';
SInvalidBitmap = 'Bitmap image is not valid';
SInvalidIcon = 'Icon image is not valid';
SInvalidPixelFormat = 'Invalid pixel format';
SBitmapEmpty = 'Bitmap is empty';
SScanLine = 'Scan line index out of range';
SChangeIconSize = 'Cannot change the size of an icon';
SUnknownExtension = 'Unknown picture file extension (.%s)';
SUnknownClipboardFormat = 'Unsupported clipboard format';
SOutOfResources = 'Out of system resources';
SNoCanvasHandle = 'Canvas does not allow drawing';
SInvalidCanvasState = 'Invalid canvas state request';
SInvalidImageSize = 'Invalid image size';
SInvalidWidgetHandle = 'Invalid widget handle';
SInvalidColorDepth = 'Color depth must be 1, 8 or 32 bpp';
SInvalidXImage = 'Invalid XImage';
STooManyImages = 'Too many images';
SWidgetCreate = 'Error creating widget';
SCannotFocus = 'Cannot focus a disabled or invisible window (%s)';
SParentRequired = 'Control ''%s'' has no parent widget';
SParentGivenNotAParent = 'Parent given is not a parent of ''%s''';
SVisibleChanged = 'Cannot change Visible in OnShow or OnHide';
SCannotShowModal = 'Cannot make a visible window modal';
SScrollBarRange = 'Scrollbar property out of range';
SPropertyOutOfRange = '%s property out of range';
SMenuIndexError = 'Menu index out of range';
SMenuReinserted = 'Menu inserted twice';
SNoMenuRecursion = 'Menu insertion recursion not allowed';
SMenuNotFound = 'Sub-menu is not in menu';
SMenuSetFormError = 'TMenu.SetForm: argument must be TCustomForm';
SNoTimers = 'Not enough timers available';
SNoAdapter = 'No printer adapter available for printing';
SPrinterIndexError = 'Printer index out of range';
SInvalidPrinter = 'Printer selected is not valid';
SDeviceOnPort = '%s on %s';
SGroupIndexTooLow = 'GroupIndex cannot be less than a previous menu item''s GroupIndex';
SNoMDIForm = 'Cannot create form. No MDI forms are currently active';
SNotAnMDIForm = 'Invalid MDIParent for class %s';
SMDIChildNotVisible = 'Cannot hide an MDI Child Form';
SImageCanvasNeedsBitmap = 'Can only modify an image if it contains a bitmap';
SControlParentSetToSelf = 'A control cannot have itself as its parent';
SOKButton = 'OK';
SCancelButton = 'Cancel';
SYesButton = '&Yes';
SNoButton = '&No';
SHelpButton = '&Help';
SCloseButton = '&Close';
SIgnoreButton = '&Ignore';
SRetryButton = '&Retry';
SAbortButton = 'Abort';
SAllButton = '&All';
SCannotDragForm = 'Cannot drag a form';
SPutObjectError = 'PutObject to undefined item';
SFB = 'FB';
SFG = 'FG';
SBG = 'BG';
SVIcons = 'Icons';
SVBitmaps = 'Bitmaps';
SVPixmaps = 'Pixmaps';
SVPNGs = 'PNGs';
SDrawings = 'Drawings';
SVJpegs = 'Jpegs';
SInvalidNumber = 'Invalid numeric value';
SInvalidCurrentItem = 'Invalid value for current item';
SMsgDlgWarning = 'Warning';
SMsgDlgError = 'Error';
SMsgDlgInformation = 'Information';
SMsgDlgConfirm = 'Confirm';
SMsgDlgYes = '&Yes';
SMsgDlgNo = '&No';
SMsgDlgOK = 'OK';
SMsgDlgCancel = 'Cancel';
SMsgDlgHelp = '&Help';
SMsgDlgHelpNone = 'No help available';
SMsgDlgHelpHelp = 'Help';
SMsgDlgAbort = '&Abort';
SMsgDlgRetry = '&Retry';
SMsgDlgIgnore = '&Ignore';
SMsgDlgAll = '&All';
SMsgDlgNoToAll = 'N&o to All';
SMsgDlgYesToAll = 'Yes to &All';
srUnknown = '(Unknown)';
srNone = '(None)';
SOutOfRange = 'Value must be between %d and %d';
SCannotCreateName = 'Cannot create a default method name for an unnamed component';
SUnnamed = 'Unnamed';
SInsertLineError = 'Unable to insert a line';
SConfirmCreateDir = 'The specified directory does not exist. Create it?';
SSelectDirCap = 'Select Directory';
SCannotCreateDirName = 'Unable to create directory "%s".';
SAccessDeniedTo = 'Access denied to "%s"';
SCannotReadDirectory = 'Cannot read directory:' + sLineBreak + '"%s"';
SDirectoryNotEmpty = 'Directory "%s" is not empty.';
SNotASubDir = '"%s" is not a subdirectory of "%s"';
SDirNameCap = 'Directory &Name:';
SDrivesCap = 'D&rives:';
SDirsCap = '&Directories:';
SFilesCap = '&Files: (*.*)';
SNetworkCap = 'Ne&twork...';
SInvalidDirectory = 'Unable to read directory "%s".';
SNewFolder = 'New Folder';
SFileNameNotFound = '"%s"'#10'File not found.';
SAlreadyExists = 'A file with that name already exists. Please specify a '+
'different filename.';
SConfirmDeleteTitle = 'Confirm file deletion';
SConfirmDeleteMany = 'Are you sure you want to delete these %d items?';
SConfirmDeleteOne = 'Are you sure you want to delete "%s"?';
SContinueDelete = 'Continue delete operation?';
SAdditional = 'Additional';
SName = 'Name';
SSize = 'Size';
SType = 'Type';
SDate = 'Date Modified';
SAttributes = 'Attributes';
{$IFDEF LINUX}
SOwner = 'Owner';
SGroup = 'Group';
SDefaultFilter = 'All Files (*)|*|';
{$ENDIF}
{$IFDEF MSWINDOWS}
SPermissions = 'Attributes';
SDefaultFilter = 'All Files (*.*)|*.*|';
SVolume = 'Volume';
SFreeSpace = 'Free Space';
SAnyKnownDrive = ' any known drive';
SMegs = '%d MB';
{$ENDIF}
SDirectory = 'Directory';
SFile = 'File';
SLinkTo = 'Link to ';
SInvalidClipFmt = 'Invalid clipboard format';
SIconToClipboard = 'Clipboard does not support Icons';
SCannotOpenClipboard = 'Cannot open clipboard';
SDefault = 'Default';
SInvalidMemoSize = 'Text exceeds memo capacity';
SCustomColors = 'Custom Colors';
SInvalidPrinterOp = 'Operation not supported on selected printer';
SNoDefaultPrinter = 'There is no default printer currently selected';
SUntitled = '(Untitled)';
SDuplicateMenus = 'Menu ''%s'' is already being used by another form';
SPictureLabel = 'Picture:';
SPictureDesc = ' (%dx%d)';
SPreviewLabel = 'Preview';
SNoPreview = 'No Preview Available';
SBoldItalicFont = 'Bold Italic';
SBoldFont = 'Bold';
SItalicFont = 'Italic';
SRegularFont = 'Regular';
SPropertiesVerb = 'Properties';
SAllCommands = 'All Commands';
SDuplicatePropertyCategory = 'A property category called %s already exists';
SUnknownPropertyCategory = 'Property category does not exist (%s)';
SInvalidFilter = 'Property filters may only be name, class or type based (%d:%d)';
SInvalidCategory = 'Categories must define their own name and description';
sOperationNotAllowed = 'Operation not allowed while dispatching application events';
STextNotFound = 'Text not found: "%s"';
SImageIndexError = 'Invalid ImageList Index';
SReplaceImage = 'Unable to Replace Image';
SInvalidImageType = 'Invalid image type';
SInvalidImageDimensions = 'Image width and heigth must match';
SInvalidImageDimension = 'Invalid image dimension';
SErrorResizingImageList = 'Error resizing ImageList';
SInvalidRangeError = 'Range of %d to %d is invalid';
SInvalidMimeSourceStream = 'MimeSource format must have an associated data stream';
SMimeNotSupportedForIcon = 'Mime format not supported for TIcon';
SOpen = 'Open';
SSave = 'Save';
SSaveAs = 'Save As';
SFindWhat = 'Fi&nd what:';
SWholeWord = 'Match &whole word only';
SMatchCase = 'Match &case';
SFindNext = '&Find Next';
SCancel = 'Cancel';
SHelp = 'Help';
SFindTitle = 'Find';
SDirection = 'Direction';
SUp = '&Up';
SDown = '&Down';
SReplaceWith = 'Rep&lace with:';
SReplace = '&Replace';
SReplaceTitle = 'Replace';
SReplaceAll = 'Replace &All';
SOverwriteCaption = 'Save %s as';
SOverwriteText = '"%s" already exists.' + sLineBreak + 'Do you want to replace it?';
SFileMustExist = '"%s"' + sLineBreak + 'File not found.' + sLineBreak + 'Please verify the correct '+
'filename was given.';
SPathMustExist = '"%s"' + sLineBreak + 'Path not found.' + sLineBreak + 'Please verify the correct '+
'path was given.';
SDriveNotFound = 'Drive %s does not exist.' + sLineBreak + 'Please verify the correct '+
'drive was given.';
SUnknownImageFormat = 'Image format not recognized';
SInvalidHandle = 'Invalid handle value for %s';
SUnableToWrite = 'Unable to write bitmap';
sAllFilter = 'All';
sInvalidSetClipped = 'Cannot set Clipped property while painting';
sInvalidLCDValue = 'Invalid LCDNumber value';
sTabFailDelete = 'Failed to delete tab at index %d';
sPageIndexError = '%d is an invalid PageIndex value. PageIndex must be ' +
'between 0 and %d';
sInvalidLevel = 'Invalid item level assignment';
sInvalidLevelEx = 'Invalid level (%d) for item "%s"';
sTabMustBeMultiLine = 'MultiLine must be True when TabPosition is tpLeft or tpRight';
sStatusBarContainsControl = '%s is already in the StatusBar';
sListRadioItemBadParent = 'Radio items must have a Controller as a parent';
sOwnerNotCustomHeaderSections = 'Owner is not a TCustomHeaderSection';
sHeaderSectionOwnerNotHeaderControl = 'Header Section owner must be a TCustomHeaderControl';
SUndo = 'Undo';
SRedo = 'Redo';
SLine = '-';
SCut = 'Cut';
SCopy = 'Copy';
SPaste = 'Paste';
SClear = 'Clear';
SSelectAll = 'Select All';
SBadMovieFormat = 'Unrecognized movie format';
SMovieEmpty = 'Movie not loaded';
SLoadingEllipsis = 'Loading...';
SNoAppInLib = 'Fatal error: Cannot create application object in a shared object or library.';
SDuplicateApp = 'Fatal error: Cannot create more than one TApplication instance';
implementation
end.
|
unit fGMV_EnteredInError;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 1 $ $Modtime: 12/20/07 12:43p $
* Developer: ddomain.user@domain.ext/doma.user@domain.ext
* Site: Hines OIFO
*
* Description: Utility for marking vitals in error.
*
* Notes:
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON/fGMV_EnteredInError.pas $
*
* $History: fGMV_EnteredInError.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:38p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/14/07 Time: 10:29a
* Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:43p
* Created in $/Vitals/VITALS-5-0-18/VitalsCommon
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:33p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsCommon
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 3:33p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, No CCOW) - Delphi 6/VitalsCommon
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 4/16/04 Time: 4:17p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/26/04 Time: 1:08p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, Delphi7)/V5031-D7/VitalsUser
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 10/29/03 Time: 4:15p
* Created in $/Vitals503/Vitals User
* Version 5.0.3
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 5/22/03 Time: 10:16a
* Updated in $/Vitals GUI Version 5.0/VitalsUserNoCCOW
* Preparation to CCOW
* MessageDLG changed to MessageDLGS
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 5/21/03 Time: 1:46p
* Updated in $/Vitals GUI Version 5.0/VitalsUserNoCCOW
* Version 5.0.1.5
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/21/03 Time: 1:18p
* Created in $/Vitals GUI Version 5.0/VitalsUserNoCCOW
* Pre CCOW Version of Vitals User
*
* ***************** Version 5 *****************
* User: Zzzzzzandria Date: 12/20/02 Time: 3:02p
* Updated in $/Vitals GUI Version 5.0/Vitals User
*
* ***************** Version 4 *****************
* User: Zzzzzzandria Date: 10/11/02 Time: 6:21p
* Updated in $/Vitals GUI Version 5.0/Vitals User
* Version vT32_1
*
* ***************** Version 3 *****************
* User: Zzzzzzpetitd Date: 6/20/02 Time: 9:33a
* Updated in $/Vitals GUI Version 5.0/Vitals User
* t27 Build
*
* ***************** Version 2 *****************
* User: Zzzzzzpetitd Date: 6/06/02 Time: 11:14a
* Updated in $/Vitals GUI Version 5.0/Vitals User
* Roll-up to 5.0.0.27
*
* ***************** Version 1 *****************
* User: Zzzzzzpetitd Date: 4/04/02 Time: 11:58a
* Created in $/Vitals GUI Version 5.0/Vitals User
*
*
================================================================================
}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
ExtCtrls,
StdCtrls,
Buttons,
CheckLst,
Trpcb,
MFunStr,
uGMV_Common,
ComCtrls;
type
TfrmGMV_EnteredInError = class(TForm)
GroupBox1: TGroupBox;
rgReason: TRadioGroup;
dtpDate: TDateTimePicker;
pnlButtons: TPanel;
btnCancel: TButton;
btnOK: TButton;
lvVitals: TListView;
procedure DateChange(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OkToProceed(Sender: TObject);
procedure ClearList;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lvVitalsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure FormResize(Sender: TObject);
private
FPatientIEN: string;
{ Private declarations }
public
{ Public declarations }
end;
procedure EnterVitalsInError(DFN: string);
implementation
{$R *.DFM}
procedure EnterVitalsInError(DFN: string);
begin
with TfrmGMV_EnteredInError.Create(Application) do
try
FPatientIEN := DFN;
dtpDate.Date := Now;
DateChange(nil);
ShowModal;
finally
free;
end;
end;
procedure TfrmGMV_EnteredInError.FormCreate(Sender: TObject);
begin
ClearList;
dtpDate.Date := Now;
end;
procedure TfrmGMV_EnteredInError.DateChange(Sender: TObject);
var
s: String;
dt: Double;
i: integer;
begin
ClearList;
dt := WindowsDateToFMDate(dtpDate.Date);
CallServer(
GMVBroker,
'GMV EXTRACT REC',
[FPatientIEN + '^' + FloatToStr(dt) + '^^' + FloatToStr(dt)],
nil, RetList);
if Piece(RetList[0], '^', 1) <> '0' then
for i := 0 to RetList.Count - 1 do
if Copy(RetList[i], 1, 1) <> ' ' then
with lvVitals.Items.Add do
begin
s := RetList[i];
Caption := Piece(Piece(RetList[i], '^', 2), ' ', 1);
// SubItems.Add(trim(Copy(RetList[i], Pos(' ', RetList[i]), 255)));
s := trim(Copy(RetList[i], Pos(' ', RetList[i]), 255));
{
s := piece(s,'_',1) + ' ' + piece(s,'_',2);
SubItems.Add(s);
}
SubItems.Add(piece(s,'_',1));
SubItems.Add(piece(s,'_',2));
Data := TGMV_FileEntry.CreateFromRPC('120.51;' + RetList[i]);
end;
end;
procedure TfrmGMV_EnteredInError.ClearList;
begin
lvVitals.Items.BeginUpdate;
while lvVitals.Items.Count > 0 do
begin
if lvVitals.Items[0].Data <> nil then
TGMV_FileEntry(lvVitals.Items[0].Data).Free;
lvVitals.Items.Delete(0);
end;
lvVitals.Items.EndUpdate;
btnOK.Enabled := False;
rgReason.Enabled := False;
rgReason.ItemIndex := -1;
end;
procedure TfrmGMV_EnteredInError.OkButtonClick(Sender: TObject);
var
i: integer;
s: String;
begin
if rgReason.ItemIndex < 0 then
MessageDlgS('No reason has been selected.', mtError, [mbok], 0)
else
begin
S := '';
for i := 0 to lvVitals.Items.Count - 1 do
if lvVitals.Items[i].Selected then
S := S + lvVitals.Items[i].Caption +' '+ lvVitals.Items[i].SubItems[0]//Adding spaces //AAN 05/21/2003
+ #13;
if MessageDlgS('Are you sure you want to mark vitals'+#13+#13+s+#13+ //CCOW preparation
'as ' + rgReason.Items[rgReason.ItemIndex]+'?',
mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
begin
Exit;
end;
for i := 0 to lvVitals.Items.Count - 1 do
if lvVitals.Items[i].Selected then
with TGMV_FileEntry(lvVitals.Items[i].Data) do
CallServer(
GMVBroker,
'GMV MARK ERROR',
[IEN + '^' + GMVUser.DUZ + '^' + IntToStr(rgReason.ItemIndex + 1)],
nil, RetList);
MessageDlgS('Vitals marked as ' + rgReason.Items[rgReason.ItemIndex]);
ModalResult := mrOK;
end;
end;
procedure TfrmGMV_EnteredInError.OkToProceed(Sender: TObject);
begin
btnOK.Enabled := (rgReason.ItemIndex > -1) and (lvVitals.SelCount > 0) and
(rgReason.ItemIndex >= 0);
end;
procedure TfrmGMV_EnteredInError.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ClearList;
end;
procedure TfrmGMV_EnteredInError.lvVitalsChange(Sender: TObject;
Item: TListItem; Change: TItemChange);
begin
rgReason.Enabled := (lvVitals.ItemFocused <> nil) or (lvVitals.SelCount > 0);
end;
procedure TfrmGMV_EnteredInError.FormResize(Sender: TObject);
begin
lvVitals.Columns[1].Width := lvVitals.Width - lvVitals.Columns[0].Width - lvVitals.Columns[2].Width- 4;
end;
end.
|
unit rDCSumm;
interface
uses SysUtils, Classes, ORNet, ORFn, rCore, uCore, TRPCB, rTIU, uConst, uTIU, uDCSumm;
{ Discharge Summary Titles }
procedure ResetDCSummTitles;
function DfltDCSummTitle: Integer;
function DfltDCSummTitleName: string;
procedure ListDCSummTitlesShort(Dest: TStrings);
function SubSetOfDCSummTitles(const StartFrom: string; Direction: Integer; IDNoteTitlesOnly: boolean; aReturn: TStrings): integer;
{ TIU Preferences }
procedure ResetDCSummPreferences;
function ReturnMaxDCSumms: Integer;
function SortDCSummsAscending: Boolean;
function GetCurrentDCSummContext: TTIUContext;
procedure SaveCurrentDCSummContext(AContext: TTIUContext) ;
{ Data Retrieval }
procedure ActOnDCDocument(var AuthSts: TActionRec; IEN: Integer; const ActionName: string);
(*procedure ListDischargeSummaries(Dest: TStrings; Context: Integer; Early, Late: TFMDateTime;
Person: int64; OccLim: Integer; SortAscending: Boolean);*)
procedure ListSummsForTree(Dest: TStrings; Context: Integer; Early, Late: TFMDateTime;
Person: int64; OccLim: Integer; SortAscending: Boolean);
procedure GetDCSummForEdit(var EditRec: TEditDCSummRec; IEN: Integer);
procedure GetCSummEditTextOnly(ResultList: TStrings; IEN: Integer);
function LoadDCUrgencies(aReturn: TStrings): integer;
function GetAttending(const DFN: string): string; //*DFN*
function GetDischargeDate(const DFN: string; AdmitDateTime: string): string; //*DFN*
function RequireRelease(ANote, AType: Integer): Boolean;
function RequireMASVerification(ANote, AType: Integer): Boolean;
function AllowMultipleSummsPerAdmission(ANote, AType: Integer): Boolean;
{ Data Storage }
procedure DeleteDCDocument(var DeleteSts: TActionRec; IEN: Integer; const Reason: string);
procedure SignDCDocument(var SignSts: TActionRec; IEN: Integer; const ESCode: string);
procedure PutNewDCSumm(var CreatedDoc: TCreatedDoc; const DCSummRec: TDCSummRec);
procedure PutDCAddendum(var CreatedDoc: TCreatedDoc; const DCSummRec: TDCSummRec; AddendumTo:
Integer);
procedure PutEditedDCSumm(var UpdatedDoc: TCreatedDoc; const DCSummRec: TDCSummRec; NoteIEN:
Integer);
procedure ChangeAttending(IEN: integer; AnAttending: int64);
const
CLS_DC_SUMM = 244;
FN_HOSPITAL_LOCATION = 44;
FN_NEW_PERSON = 200;
TIU_ST_UNREL = 3;
TIU_ST_UNVER = 4;
TIU_ST_UNSIG = 5;
implementation
var
uDCSummTitles: TDCSummTitles;
uDCSummPrefs: TDCSummPrefs;
{ Discharge Summary Titles -------------------------------------------------------------------- }
procedure LoadDCSummTitles;
{ private - called one time to set up the uNoteTitles object }
var
x: string;
aLst: TStringList;
begin
if uDCSummTitles = nil then
begin
aLst := TStringList.Create;
try
CallVistA('TIU PERSONAL TITLE LIST', [User.DUZ, CLS_DC_SUMM], aLst);
aLst.Insert(0, '~SHORT LIST'); // insert so can call ExtractItems
uDCSummTitles := TDCSummTitles.Create;
ExtractItems(uDCSummTitles.ShortList, aLst, 'SHORT LIST');
x := ExtractDefault(aLst, 'SHORT LIST');
uDCSummTitles.DfltTitle := StrToIntDef(Piece(x, U, 1), 0);
uDCSummTitles.DfltTitleName := Piece(x, U, 2);
finally
FreeAndNil(aLst);
end;
end;
end;
procedure ResetDCSummTitles;
begin
if uDCSummTitles <> nil then
begin
uDCSummTitles.Free;
uDCSummTitles := nil;
LoadDCSummTitles;
end;
end;
function DfltDCSummTitle: Integer;
{ returns the IEN of the user defined default Discharge Summary title (if any) }
begin
if uDCSummTitles = nil then LoadDCSummTitles;
Result := uDCSummTitles.DfltTitle;
end;
function DfltDCSummTitleName: string;
{ returns the name of the user defined default Discharge Summary title (if any) }
begin
if uDCSummTitles = nil then LoadDCSummTitles;
Result := uDCSummTitles.DfltTitleName;
end;
procedure ListDCSummTitlesShort(Dest: TStrings);
{ returns the user defined list (short list) of Discharge Summary titles }
begin
if uDCSummTitles = nil then LoadDCSummTitles;
FastAddStrings(uDCSummTitles.ShortList, Dest);
if uDCSummTitles.ShortList.Count > 0 then
begin
Dest.Add('0^________________________________________________________________________');
Dest.Add('0^ ');
end;
end;
function SubSetOfDCSummTitles(const StartFrom: string; Direction: Integer; IDNoteTitlesOnly: boolean; aReturn: TStrings): integer;
begin
if IDNoteTitlesOnly then
CallVistA('TIU LONG LIST OF TITLES', [CLS_DC_SUMM, StartFrom, Direction, IDNoteTitlesOnly], aReturn)
else
CallVistA('TIU LONG LIST OF TITLES', [CLS_DC_SUMM, StartFrom, Direction], aReturn);
Result := aReturn.Count;
end;
{ TIU Preferences ------------------------------------------------------------------------- }
procedure LoadDCSummPrefs;
{ private - creates DCSummPrefs object for reference throughout the session }
var
x: string;
begin
uDCSummPrefs := TDCSummPrefs.Create;
with uDCSummPrefs do
begin
CallVistA('TIU GET PERSONAL PREFERENCES', [User.DUZ], x);
DfltLoc := StrToIntDef(Piece(x, U, 2), 0);
DfltLocName := ExternalName(DfltLoc, FN_HOSPITAL_LOCATION);
SortAscending := Piece(x, U, 4) = 'A';
MaxSumms := StrToIntDef(Piece(x, U, 10), 0);
x := GetAttending(Patient.DFN);
DfltCosigner := StrToInt64Def(Piece(x, U, 1), 0);
DfltCosignerName := ExternalName(DfltCosigner, FN_NEW_PERSON);
AskCosigner := User.DUZ <> DfltCosigner;
end;
end;
procedure ResetDCSummPreferences;
begin
if uDCSummPrefs <> nil then
begin
uDCSummPrefs.Free;
uDCSummPrefs := nil;
LoadDCSummPrefs;
end;
end;
function ReturnMaxDCSumms: Integer;
begin
if uDCSummPrefs = nil then LoadDCSummPrefs;
Result := uDCSummPrefs.MaxSumms;
if Result = 0 then Result := 100;
end;
function SortDCSummsAscending: Boolean;
{ returns true if Discharge Summarys should be sorted from oldest to newest (chronological) }
begin
if uDCSummPrefs = nil then LoadDCSummPrefs;
Result := uDCSummPrefs.SortAscending;
end;
{ Data Retrieval --------------------------------------------------------------------------- }
procedure ActOnDCDocument(var AuthSts: TActionRec; IEN: Integer; const ActionName: string);
var
x: string;
begin
if not (IEN > 0) then
begin
AuthSts.Success := True;
AuthSts.Reason := '';
Exit;
end;
CallVistA('TIU AUTHORIZATION', [IEN, ActionName], x);
AuthSts.Success := Piece(x, U, 1) = '1';
AuthSts.Reason := Piece(x, U, 2);
end;
(*procedure ListDischargeSummaries(Dest: TStrings; Context: Integer; Early, Late: TFMDateTime;
Person: int64; OccLim: Integer; SortAscending: Boolean);
{ retrieves existing progress notes for a patient according to the parameters passed in
Pieces: IEN^Title^FMDateOfNote^Patient^Author^Location^Status^Visit
Return: IEN^ExDateOfNote^Title, Location, Author }
var
i: Integer;
x: string;
SortSeq: Char;
begin
if SortAscending then SortSeq := 'A' else SortSeq := 'D';
//if OccLim = 0 then OccLim := MaxSummsReturned;
CallV('TIU DOCUMENTS BY CONTEXT',
[CLS_DC_SUMM, Context, Patient.DFN, Early, Late, Person, OccLim, SortSeq]);
with RPCBrokerV do
begin
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
if Copy(Piece(x, U, 9), 1, 4) = ' ' then SetPiece(x, U, 9, 'Dis: ');
x := Piece(x, U, 1) + U + FormatFMDateTime('mmm dd,yy', MakeFMDateTime(Piece(x, U, 3)))
+ U + Piece(x, U, 2) + ', ' + Piece(x, U, 6) + ', ' + Piece(Piece(x, U, 5), ';', 2) +
' (' + Piece(x,U,7) + '), ' + Piece(x, U, 8) + ', ' + Piece(x, U, 9) +
U + Piece(x, U, 3) + U + Piece(x, U, 11);
Results[i] := x;
end; {for}
FastAssign(RPCBrokerV.Results, Dest);
end; {with}
end;*)
procedure ListSummsForTree(Dest: TStrings; Context: Integer; Early, Late: TFMDateTime;
Person: int64; OccLim: Integer; SortAscending: Boolean);
{ retrieves existing discharge summaries for a patient according to the parameters passed in}
var
SortSeq: Char;
const
SHOW_ADDENDA = True;
begin
if SortAscending then SortSeq := 'A' else SortSeq := 'D';
if Context > 0 then
CallVistA('TIU DOCUMENTS BY CONTEXT', [CLS_DC_SUMM, Context, Patient.DFN, Early, Late, Person, OccLim, SortSeq, SHOW_ADDENDA], Dest);
end;
procedure GetDCSummForEdit(var EditRec: TEditDCSummRec; IEN: Integer);
{ retrieves internal/external values for Discharge Summary fields & loads them into EditRec
Fields: Title:.01, RefDate:1301, Author:1204, Cosigner:1208, Subject:1701, Location:1205 }
var
i, j: Integer;
aLst: TStringList;
function FindDT(const FieldID: string): TFMDateTime;
var
x: string;
begin
Result := 0;
for x in aLst do
if Piece(x, U, 1) = FieldID then
begin
Result := MakeFMDateTime(Piece(x, U, 2));
Break;
end;
end;
function FindExt(const FieldID: string): string;
var
x: string;
begin
Result := '';
for x in aLst do
if Piece(x, U, 1) = FieldID then
begin
Result := Piece(x, U, 3);
Break;
end;
end;
function FindInt(const FieldID: string): Integer;
var
x: string;
begin
Result := 0;
for x in aLst do
if Piece(x, U, 1) = FieldID then
begin
Result := StrToIntDef(Piece(x, U, 2), 0);
Break;
end;
end;
function FindInt64(const FieldID: string): int64;
var
x: string;
begin
Result := 0;
for x in aLst do
if Piece(x, U, 1) = FieldID then
begin
Result := StrToInt64Def(Piece(x, U, 2), 0);
Break;
end;
end;
begin
aLst := TStringList.Create;
try
CallVistA('TIU LOAD RECORD FOR EDIT', [IEN, '.01;.06;.07;.09;1202;1205;1208;1209;1301;1302;1307;1701'], aLst);
FillChar(EditRec, SizeOf(EditRec), 0);
with EditRec do
begin
Title := FindInt('.01');
TitleName := FindExt('.01');
AdmitDateTime := FindDT('.07');
DischargeDateTime := FindDT('1301');
UrgencyName := FindExt('.09');
Urgency := Copy(UrgencyName, 1, 1);
Dictator := FindInt64('1202');
DictatorName := FindExt('1202');
Cosigner := FindInt64('1208');
CosignerName := FindExt('1208');
DictDateTime := FindDT('1307');
Attending := FindInt64('1209');
AttendingName := FindExt('1209');
Transcriptionist := FindInt64('1302');
TranscriptionistName := FindExt('1302');
Location := FindInt('1205');
LocationName := FindExt('1205');
if Title = TYP_ADDENDUM then Addend := FindInt('.06');
for i := 0 to aLst.Count - 1 do
if aLst[i] = '$TXT' then Break;
for j := i downto 0 do aLst.Delete(j);
// -------------------- v19.1 (RV) LOST NOTES?----------------------------
// Lines := Results; 'Lines' is being overwritten by subsequent Broker calls
if not Assigned(Lines) then Lines := TStringList.Create;
FastAssign(aLst, Lines);
// -----------------------------------------------------------------------
end;
finally
FreeAndNil(aLst);
end;
end;
procedure GetCSummEditTextOnly(ResultList: TStrings; IEN: Integer);
var
RtnLst: TStringList;
begin
RtnLst := TStringList.Create;
try
CallVistA('TIU LOAD RECORD TEXT', [IEN], RtnLst);
if RtnLst[0] = '$TXT' then
begin
//Remove the indicator
RtnLst.Delete(0);
//assign the remaining
ResultList.Assign(RtnLst);
end;
finally
RtnLst.Free;
end;
end;
function LoadDCUrgencies(aReturn: TStrings): integer;
var
i: integer;
begin
CallVistA('TIU GET DS URGENCIES', [nil], aReturn);
for i := 0 to aReturn.Count-1 do
aReturn[i] := MixedCase(aReturn[i]);
Result := aReturn.Count;
end;
{ Data Updates ----------------------------------------------------------------------------- }
procedure DeleteDCDocument(var DeleteSts: TActionRec; IEN: Integer; const Reason: string);
{ delete a TIU document given the internal entry number, return reason if unable to delete }
begin
DeleteDocument(DeleteSts, IEN, Reason);
end;
procedure SignDCDocument(var SignSts: TActionRec; IEN: Integer; const ESCode: string);
{ update signed status of a TIU document, return reason if signature is not accepted }
var
x: string;
begin
(* with RPCBrokerV do // temp - to insure sign doesn't go interactive
begin
ClearParameters := True;
RemoteProcedure := 'TIU UPDATE RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(IEN);
Param[1].PType := list;
with Param[1] do Mult['.11'] := '0'; // **** block removed in v19.1 - {RV} ****
CallBroker;
end; // temp - end*)
CallVistA('TIU SIGN RECORD', [IEN, ESCode], x);
SignSts.Success := Piece(x, U, 1) = '0';
SignSts.Reason := Piece(x, U, 2);
end;
procedure PutNewDCSumm(var CreatedDoc: TCreatedDoc; const DCSummRec: TDCSummRec);
{ create a new discharge summary with the data in DCSummRec and return its internal entry number
load broker directly since there isn't a good way to set up multiple subscript arrays }
(*var
i: Integer;*)
var
ErrMsg: string;
begin
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU CREATE RECORD';
Param[0].PType := literal;
Param[0].Value := Patient.DFN; //*DFN*
Param[1].PType := literal;
Param[1].Value := IntToStr(DCSummRec.Title);
Param[2].PType := literal;
Param[2].Value := '';
Param[3].PType := literal;
Param[3].Value := '';
Param[4].PType := literal;
Param[4].Value := '';
Param[5].PType := list;
with Param[5] do
begin
Mult['.07'] := FloatToStr(DCSummRec.AdmitDateTime);
Mult['.09'] := DCSummRec.Urgency;
Mult['1202'] := IntToStr(DCSummRec.Dictator);
Mult['1205'] := IntToStr(Encounter.Location);
Mult['1301'] := FloatToStr(DCSummRec.DischargeDateTime);
Mult['1307'] := FloatToStr(DCSummRec.DictDateTime);
if DCSummRec.Cosigner > 0 then
begin
Mult['1208'] := IntToStr(DCSummRec.Cosigner);
Mult['1506'] := '1';
end
else
begin
Mult['1208'] := '';
Mult['1506'] := '0';
end ;
Mult['1209'] := IntToStr(DCSummRec.Attending);
Mult['1302'] := IntToStr(DCSummRec.Transcriptionist);
if DCSummRec.IDParent > 0 then Mult['2101'] := IntToStr(DCSummRec.IDParent);
(* if DCSummRec.Lines <> nil then
for i := 0 to DCSummRec.Lines.Count - 1 do
Mult['"TEXT",' + IntToStr(i+1) + ',0'] := FilteredString(DCSummRec.Lines[i]);*)
end;
Param[6].PType := literal;
Param[6].Value := DCSummRec.VisitStr;
Param[7].PType := literal;
Param[7].Value := '1'; // suppress commit logic
CallBroker;
CreatedDoc.IEN := StrToIntDef(Piece(Results[0], U, 1), 0);
CreatedDoc.ErrorText := Piece(Results[0], U, 2);
end;
finally
UnlockBroker;
end;
if ( DCSummRec.Lines <> nil ) and ( CreatedDoc.IEN <> 0 ) then
begin
SetText(ErrMsg, DCSummRec.Lines, CreatedDoc.IEN, 1);
if ErrMsg <> '' then
begin
CreatedDoc.IEN := 0;
CreatedDoc.ErrorText := ErrMsg;
end;
end;
end;
procedure PutDCAddendum(var CreatedDoc: TCreatedDoc; const DCSummRec: TDCSummRec; AddendumTo:
Integer);
{ create a new addendum for note identified in AddendumTo, returns IEN of new document
load broker directly since there isn't a good way to set up multiple subscript arrays }
(*var
i: Integer;*)
var
ErrMsg: string;
begin
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU CREATE ADDENDUM RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(AddendumTo);
Param[1].PType := list;
with Param[1] do
begin
Mult['.09'] := DCSummRec.Urgency;
Mult['1202'] := IntToStr(DCSummRec.Dictator);
Mult['1301'] := FloatToStr(DCSummRec.DischargeDateTime);
Mult['1307'] := FloatToStr(DCSummRec.DictDateTime);
if DCSummRec.Cosigner > 0 then
begin
Mult['1208'] := IntToStr(DCSummRec.Cosigner);
Mult['1506'] := '1';
end
else
begin
Mult['1208'] := '';
Mult['1506'] := '0';
end ;
(* if DCSummRec.Lines <> nil then
for i := 0 to DCSummRec.Lines.Count - 1 do
Mult['"TEXT",' + IntToStr(i+1) + ',0'] := FilteredString(DCSummRec.Lines[i]);*)
end;
Param[2].PType := literal;
Param[2].Value := '1'; // suppress commit logic
CallBroker;
CreatedDoc.IEN := StrToIntDef(Piece(Results[0], U, 1), 0);
CreatedDoc.ErrorText := Piece(Results[0], U, 2);
end;
finally
UnlockBroker;
end;
if ( DCSummRec.Lines <> nil ) and ( CreatedDoc.IEN <> 0 ) then
begin
SetText(ErrMsg, DCSummRec.Lines, CreatedDoc.IEN, 1);
if ErrMsg <> '' then
begin
CreatedDoc.IEN := 0;
CreatedDoc.ErrorText := ErrMsg;
end;
end;
end;
procedure PutEditedDCSumm(var UpdatedDoc: TCreatedDoc; const DCSummRec: TDCSummRec; NoteIEN:
Integer);
{ update the fields and content of the note identified in NoteIEN, returns 1 if successful
load broker directly since there isn't a good way to set up mutilple subscript arrays }
(*var
i: Integer;*)
var
ErrMsg: string;
begin
// First, file field data
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU UPDATE RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(NoteIEN);
Param[1].PType := list;
with Param[1] do
begin
if DCSummRec.Addend = 0 then
begin
Mult['.01'] := IntToStr(DCSummRec.Title);
//Mult['.11'] := BOOLCHAR[DCSummRec.NeedCPT]; // **** removed in v19.1 {RV} ****
end;
if (DCSummRec.Status in [TIU_ST_UNREL(*, TIU_ST_UNVER*)]) then Mult['.05'] := IntToStr(DCSummRec.Status);
Mult['1202'] := IntToStr(DCSummRec.Dictator);
Mult['1209'] := IntToStr(DCSummRec.Attending);
Mult['1301'] := FloatToStr(DCSummRec.DischargeDateTime);
if DCSummRec.Cosigner > 0 then
begin
Mult['1208'] := IntToStr(DCSummRec.Cosigner);
Mult['1506'] := '1';
end
else
begin
Mult['1208'] := '';
Mult['1506'] := '0';
end ;
(* for i := 0 to DCSummRec.Lines.Count - 1 do
Mult['"TEXT",' + IntToStr(i+1) + ',0'] := FilteredString(DCSummRec.Lines[i]);*)
end;
CallBroker;
UpdatedDoc.IEN := StrToIntDef(Piece(Results[0], U, 1), 0);
UpdatedDoc.ErrorText := Piece(Results[0], U, 2);
end;
finally
UnlockBroker;
end;
if UpdatedDoc.IEN <= 0 then //v22.12 - RV
//if UpdatedDoc.ErrorText <> '' then //v22.5 - RV
begin
UpdatedDoc.ErrorText := UpdatedDoc.ErrorText + #13#10 + #13#10 + 'Document #: ' + IntToStr(NoteIEN);
exit;
end;
// next, if no error, file document body
SetText(ErrMsg, DCSummRec.Lines, NoteIEN, 0);
if ErrMsg <> '' then
begin
UpdatedDoc.IEN := 0;
UpdatedDoc.ErrorText := ErrMsg;
end;
end;
function GetAttending(const DFN: string): string; //*DFN*
var
aStr: string;
begin
CallVistA('ORQPT ATTENDING/PRIMARY', [DFN], aStr);
Result := Piece(aStr, ';', 1);
end;
function GetDischargeDate(const DFN: string; AdmitDateTime: string): string; //*DFN*
begin
CallVistA('ORWPT DISCHARGE', [DFN, AdmitDateTime], Result);
end;
function RequireRelease(ANote, AType: Integer): Boolean;
{ returns true if a discharge summary must be released }
var
aStr: string;
begin
if ANote > 0 then
CallVistA('TIU GET DOCUMENT PARAMETERS', [ANote], aStr)
else
CallVistA('TIU GET DOCUMENT PARAMETERS', [0, AType], aStr);
Result := (Piece(aStr, U, 2) = '1');
end;
function RequireMASVerification(ANote, AType: Integer): boolean;
{ returns true if a discharge summary must be verified }
var
AValue: Integer;
aStr: string;
begin
if ANote > 0 then
CallVistA('TIU GET DOCUMENT PARAMETERS', [ANote], aStr)
else
CallVistA('TIU GET DOCUMENT PARAMETERS', [0, AType], aStr);
AValue := StrToIntDef(Piece(aStr, U, 3), 0);
case AValue of
0: Result := False; // NO
1: Result := True; // ALWAYS
2: Result := False; // UPLOAD ONLY
3: Result := True; // DIRECT ENTRY ONLY
else
Result := False; // Default
end;
end;
function AllowMultipleSummsPerAdmission(ANote, AType: Integer): Boolean;
{ returns true if a discharge summary must be released }
var
aStr: string;
begin
if ANote > 0 then
CallVistA('TIU GET DOCUMENT PARAMETERS', [ANote], aStr)
else
CallVistA('TIU GET DOCUMENT PARAMETERS', [0, AType], aStr);
Result := (aStr = '1');
end;
procedure ChangeAttending(IEN: integer; AnAttending: int64);
var
AttendingIsNotCurrentUser: boolean;
begin
AttendingIsNotCurrentUser := (AnAttending <> User.DUZ);
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'TIU UPDATE RECORD';
Param[0].PType := literal;
Param[0].Value := IntToStr(IEN);
Param[1].PType := list;
with Param[1] do
begin
Mult['1209'] := IntToStr(AnAttending);
if AttendingIsNotCurrentUser then
begin
Mult['1208'] := IntToStr(AnAttending);
Mult['1506'] := '1';
end
else
begin
Mult['1208'] := '';
Mult['1506'] := '0';
end ;
end;
CallBroker;
end;
finally
UnlockBroker;
end;
end;
function GetCurrentDCSummContext: TTIUContext;
var
x: string;
AContext: TTIUContext;
begin
CallVistA('ORWTIU GET DCSUMM CONTEXT', [User.DUZ], x);
with AContext do
begin
Changed := True;
BeginDate := Piece(x, ';', 1);
EndDate := Piece(x, ';', 2);
Status := Piece(x, ';', 3);
if (StrToIntDef(Status, 0) < 1) or (StrToIntDef(Status, 0) > 5) then Status := '1';
Author := StrToInt64Def(Piece(x, ';', 4), 0);
MaxDocs := StrToIntDef(Piece(x, ';', 5), 0);
ShowSubject := StrToIntDef(Piece(x, ';', 6), 0) > 0; //TIU PREFERENCE??
SortBy := Piece(x, ';', 7); //TIU PREFERENCE??
ListAscending := StrToIntDef(Piece(x, ';', 8), 0) > 0;
TreeAscending := StrToIntDef(Piece(x, ';', 9), 0) > 0; //TIU PREFERENCE??
GroupBy := Piece(x, ';', 10);
SearchField := Piece(x, ';', 11);
KeyWord := Piece(x, ';', 12);
Filtered := (Keyword <> '');
end;
Result := AContext;
end;
procedure SaveCurrentDCSummContext(AContext: TTIUContext);
var
x: string;
begin
with AContext do
begin
SetPiece(x, ';', 1, BeginDate);
SetPiece(x, ';', 2, EndDate);
SetPiece(x, ';', 3, Status);
if Author > 0 then
SetPiece(x, ';', 4, IntToStr(Author))
else
SetPiece(x, ';', 4, '');
SetPiece(x, ';', 5, IntToStr(MaxDocs));
SetPiece(x, ';', 6, BOOLCHAR[ShowSubject]); //TIU PREFERENCE??
SetPiece(x, ';', 7, SortBy); //TIU PREFERENCE??
SetPiece(x, ';', 8, BOOLCHAR[ListAscending]);
SetPiece(x, ';', 9, BOOLCHAR[TreeAscending]); //TIU PREFERENCE??
SetPiece(x, ';', 10, GroupBy);
SetPiece(x, ';', 11, SearchField);
SetPiece(x, ';', 12, KeyWord);
end;
CallVistA('ORWTIU SAVE DCSUMM CONTEXT', [x]);
end;
initialization
// nothing for now
finalization
if uDCSummTitles <> nil then uDCSummTitles.Free;
if uDCSummPrefs <> nil then uDCSummPrefs.Free;
end.
|
program rxfpc_gen_help;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes, SysUtils, CustApp,
dom, XMLRead;
type
{ TLazPkgData }
TLazPkgData = class
private
procedure DoLoadData;
public
constructor Create(AFileName:string);
end;
{ TRxHelpApplication }
TRxHelpApplication = class(TCustomApplication)
private
procedure MakeHelp(APkgName:string);
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TLazPkgData }
procedure TLazPkgData.DoLoadData;
begin
end;
constructor TLazPkgData.Create(AFileName: string);
begin
end;
{ TRxHelpApplication }
procedure TRxHelpApplication.MakeHelp(APkgName: string);
var
P: TLazPkgData;
begin
if FileExists(APkgName) then
begin
P:=TLazPkgData.Create(APkgName);
try
finally
P.Free;
end;
end;
end;
procedure TRxHelpApplication.DoRun;
var
ErrorMsg: String;
begin
// quick check parameters
ErrorMsg:=CheckOptions('h', 'help');
if ErrorMsg<>'' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h', 'help') then begin
WriteHelp;
Terminate;
Exit;
end;
{ add your program here }
MakeHelp('dcl_rx_ctrl');
MakeHelp('rxdbgrid_export_spreadsheet');
MakeHelp('rx');
MakeHelp('rx_sort_fbdataset');
MakeHelp('rx_sort_sqldb');
MakeHelp('rxtools.lpk');
MakeHelp('dcl_rxtools');
MakeHelp('rxdbgrid_print');
MakeHelp('rxnew');
MakeHelp('rx_sort_ibx');
MakeHelp('rx_sort_zeos');
// stop program loop
Terminate;
end;
constructor TRxHelpApplication.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TRxHelpApplication.Destroy;
begin
inherited Destroy;
end;
procedure TRxHelpApplication.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ', ExeName, ' -h');
end;
var
Application: TRxHelpApplication;
begin
Application:=TRxHelpApplication.Create(nil);
Application.Title:='RxFPCHelp';
Application.Run;
Application.Free;
end.
|
unit Test_FIToolkit.Commons.Types;
{
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,
FIToolkit.Commons.Types;
type
// Test methods for TAssignable
TestTAssignable = class (TGenericTestCase)
private
const
INT_TEST = 777;
type
TAssignableInteger = TAssignable<Integer>;
published
procedure TestAssigned;
procedure TestCreate;
procedure TestOnChange;
procedure TestOnChanging;
procedure TestOnUnassign;
procedure TestUnassign;
procedure TestValue;
end;
implementation
{ TestTAssignable }
procedure TestTAssignable.TestAssigned;
var
AI : TAssignableInteger;
begin
CheckFalse(AI.Assigned, 'CheckFalse::Assigned');
AI := INT_TEST;
CheckTrue(AI.Assigned, 'CheckTrue::Assigned');
end;
procedure TestTAssignable.TestCreate;
var
AI1, AI2 : TAssignableInteger;
begin
AI1 := TAssignableInteger.Create(INT_TEST);
CheckTrue(AI1.Assigned, 'CheckTrue::AI1.Assigned');
CheckEquals(INT_TEST, AI1.Value, 'AI1.Value = INT_TEST');
AI2 := INT_TEST;
CheckTrue(AI2.Assigned, 'CheckTrue::AI2.Assigned');
CheckEquals(INT_TEST, Integer(AI2), 'AI2 = INT_TEST');
end;
procedure TestTAssignable.TestOnChange;
const
INT_OLD_VALUE = INT_TEST;
INT_NEW_VALUE = INT_OLD_VALUE + 1;
var
AI : TAssignableInteger;
bCalled : Boolean;
begin
CheckFalse(Assigned(AI.OnChange), 'CheckFalse::Assigned(AI.OnChange)');
bCalled := False;
AI.OnChange :=
procedure (WasAssigned : Boolean; const CurrentValue, OldValue : Integer)
begin
bCalled := True;
CheckFalse(WasAssigned, 'CheckFalse::WasAssigned');
end;
AI := INT_OLD_VALUE;
CheckTrue(bCalled, 'CheckTrue::bCalled');
bCalled := False;
AI.OnChange :=
procedure (WasAssigned : Boolean; const CurrentValue, OldValue : Integer)
begin
bCalled := True;
CheckTrue(WasAssigned, 'CheckTrue::WasAssigned');
CheckEquals(INT_OLD_VALUE, OldValue, 'OldValue = INT_OLD_VALUE');
CheckEquals(INT_NEW_VALUE, CurrentValue, 'CurrentValue = INT_NEW_VALUE');
end;
AI := INT_NEW_VALUE;
CheckTrue(bCalled, 'CheckTrue::bCalled');
end;
procedure TestTAssignable.TestOnChanging;
const
INT_OLD_VALUE = INT_TEST;
INT_NEW_VALUE = INT_OLD_VALUE + 1;
var
AI : TAssignableInteger;
bCalled : Boolean;
begin
CheckFalse(Assigned(AI.OnChanging), 'CheckFalse::Assigned(AI.OnChanging)');
bCalled := False;
AI.OnChanging :=
procedure (WasAssigned : Boolean; const CurrentValue, OldValue : Integer; var AllowChange : Boolean)
begin
bCalled := True;
CheckFalse(WasAssigned, 'CheckFalse::WasAssigned');
end;
AI := INT_OLD_VALUE;
CheckTrue(bCalled, 'CheckTrue::bCalled');
bCalled := False;
AI.OnChanging :=
procedure (WasAssigned : Boolean; const CurrentValue, NewValue : Integer; var AllowChange : Boolean)
begin
bCalled := True;
CheckTrue(WasAssigned, 'CheckTrue::WasAssigned');
CheckEquals(INT_OLD_VALUE, CurrentValue, 'CurrentValue = INT_OLD_VALUE');
CheckEquals(INT_NEW_VALUE, NewValue, 'NewValue = INT_NEW_VALUE');
end;
AI := INT_NEW_VALUE;
CheckTrue(bCalled, 'CheckTrue::bCalled');
AI.OnChanging := nil;
AI := INT_OLD_VALUE;
bCalled := False;
AI.OnChanging :=
procedure (WasAssigned : Boolean; const CurrentValue, NewValue : Integer; var AllowChange : Boolean)
begin
bCalled := True;
CheckTrue(AllowChange, 'CheckTrue::AllowChange');
AllowChange := False;
end;
AI := INT_NEW_VALUE;
CheckTrue(bCalled, 'CheckTrue::bCalled');
CheckEquals(INT_OLD_VALUE, AI.Value, 'AI.Value = INT_OLD_VALUE');
end;
procedure TestTAssignable.TestOnUnassign;
var
AI : TAssignableInteger;
bCalled : Boolean;
begin
CheckFalse(Assigned(AI.OnUnassign), 'CheckFalse::Assigned(AI.OnUnassign)');
bCalled := False;
AI.OnUnassign :=
procedure (WasAssigned : Boolean; const OldValue : Integer)
begin
bCalled := True;
CheckFalse(WasAssigned, 'CheckFalse::WasAssigned');
end;
AI.Unassign;
CheckTrue(bCalled, 'CheckTrue::bCalled');
bCalled := False;
AI := INT_TEST;
AI.OnUnassign :=
procedure (WasAssigned : Boolean; const OldValue : Integer)
begin
bCalled := True;
CheckTrue(WasAssigned, 'CheckTrue::WasAssigned');
CheckEquals(INT_TEST, OldValue, 'OldValue = INT_TEST');
end;
AI.Unassign;
CheckTrue(bCalled, 'CheckTrue::bCalled');
end;
procedure TestTAssignable.TestUnassign;
var
AI : TAssignableInteger;
begin
AI := INT_TEST;
AI.Unassign;
CheckFalse(AI.Assigned, 'CheckFalse::Assigned');
CheckNotEquals(INT_TEST, AI.Value, 'AI.Value <> INT_TEST');
CheckEquals(Default(Integer), Integer(AI), 'AI = 0');
end;
procedure TestTAssignable.TestValue;
var
AI : TAssignableInteger;
begin
CheckEquals(Default(Integer), AI.Value, 'AI.Value = 0');
CheckEquals(Default(Integer), Integer(AI), 'AI = 0');
AI := INT_TEST;
CheckEquals(INT_TEST, AI.Value, 'AI.Value = INT_TEST');
CheckEquals(INT_TEST, Integer(AI), 'AI = INT_TEST');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTAssignable.Suite);
end.
|
unit gExpressionLiterals;
{ Author: Steve Kramer, goog@goog.com }
interface
Uses
Classes
, SysUtils
, StrUtils
, gExpressionEvaluator
;
Type
TLiteral = class(TgExpressionToken)
Protected
Value: Variant;
public
Procedure Evaluate(AStack : TgVariantStack);Override;
End;
THex = Class(TLiteral)
public
procedure Parse(ASymbolLength: Integer); override;
End;
TNumber = Class(TLiteral)
public
procedure Parse(ASymbolLength: Integer); override;
End;
TString = Class(TLiteral)
public
procedure Parse(ASymbolLength: Integer); override;
End;
TDateTimeLiteral = class(TLiteral)
public
procedure Parse(ASymbolLength: Integer); override;
end;
implementation
uses gCore, gParse;
{ TLiteral }
procedure TLiteral.Evaluate(AStack : TgVariantStack);
begin
AStack.Push(Value);
end;
procedure THex.Parse(ASymbolLength: Integer);
Const
HexChars = '0123456789ABCDEFabcdef';
Var
StartPos : Integer;
Begin
inherited Parse(ASymbolLength);
StartPos := SourceStringIndex - 1;
While Pos(SourceString[SourceStringIndex], HexChars) > 0 Do
SourceStringIndex := SourceStringIndex + 1;
Value := StrToInt(Copy(SourceString, StartPos, SourceStringIndex - StartPos));
end;
procedure TNumber.Parse(ASymbolLength: Integer);
Const
NumberChars = '0123456789.';
Var
StartPos : Integer;
TempString : String;
Begin
StartPos := SourceStringIndex;
If SourceString[SourceStringIndex] = '-' Then
SourceStringIndex := SourceStringIndex + 1;
Repeat
SourceStringIndex := SourceStringIndex + 1;
Until ( SourceStringIndex > SourceStringLength ) OR (Pos(SourceString[SourceStringIndex], NumberChars) = 0);
TempString := Copy(SourceString, StartPos, SourceStringIndex - StartPos);
If Pos('.', TempString) > 0 Then
Value := StrToFloat(TempString)
Else
Value := StrToInt(TempString);
end;
{ TString }
procedure TString.Parse(ASymbolLength: Integer);
Var
DataString: PChar;
BeforeExtractLength: Integer;
Const
QuoteChar = '''';
Begin
DataString := PChar(Copy( SourceString, SourceStringIndex, MaxInt ));
BeforeExtractLength := Length( DataString );
Value := AnsiExtractQuotedStr( DataString, QuoteChar );
SourceStringIndex := SourceStringIndex + ( BeforeExtractLength - Length( DataString ) );
end;
procedure TDateTimeLiteral.Parse(ASymbolLength: Integer);
Const
DateChars = '0123456789/ :';
Var
StartPos : Integer;
TempString : String;
Symbol : String;
DateTime : TDateTime;
ValueLength: Integer;
Begin
Symbol := Copy(SourceString, SourceStringIndex, ASymbolLength);
StartPos := SourceStringIndex + ASymbolLength;
Repeat
SourceStringIndex := SourceStringIndex + 1;
Until ( SourceStringIndex > SourceStringLength ) OR (Pos(SourceString[SourceStringIndex], DateChars) = 0);
ValueLength := SourceStringIndex - StartPos;
TempString := Copy(SourceString, StartPos, ValueLength);
If Not SameText(Copy(SourceString, StartPos + ValueLength, ASymbolLength), Symbol) Or Not TryStrToDateTime(TempString, DateTime) then
Begin
SourceStringIndex := StartPos - ASymbolLength;
Owner.RaiseException('%s isn''t a valid date / time literal.', [Copy(SourceString, StartPos - ASymbolLength, ValueLength - StartPos + 2 * ASymbolLength)]);
End;
Value := DateTime;
SourceStringIndex := StartPos + ValueLength + ASymbolLength;
end;
Initialization
THex.Register('$');
TNumber.Register('0');
TNumber.Register('1');
TNumber.Register('2');
TNumber.Register('3');
TNumber.Register('4');
TNumber.Register('5');
TNumber.Register('6');
TNumber.Register('7');
TNumber.Register('8');
TNumber.Register('9');
TString.Register('''');
TDateTimeLiteral.Register('#');
end.
|
unit IdMappedPortTCP;
interface
uses
Classes, IdTCPClient, IdTCPServer;
const
ID_MAPPED_PORT_TCP_PORT = 0;
type
TIdMappedPortTCPData = class
public
OutboundClient: TIdTCPClient;
ReadList: TList;
constructor Create;
destructor Destroy; override;
end;
TBeforeClientConnectEvent = procedure(ASender: TComponent; AThread:
TIdPeerThread;
AClient: TIdTCPClient) of object;
TIdMappedPortTCP = class(TIdTCPServer)
protected
FMappedPort: integer;
FMappedHost: string;
FOnBeforeClientConnect: TBeforeClientConnectEvent;
procedure DoConnect(AThread: TIdPeerThread); override;
function DoExecute(AThread: TIdPeerThread): boolean; override;
public
constructor Create(AOwner: TComponent); override;
published
property MappedHost: string read FMappedHost write FMappedHost;
property MappedPort: integer read FMappedPort write FMappedPort default
ID_MAPPED_PORT_TCP_PORT;
property OnBeforeClientConnect: TBeforeClientConnectEvent read
FOnBeforeClientConnect
write FOnBeforeClientConnect;
end;
implementation
uses
IdGlobal, IdStack,
SysUtils;
constructor TIdMappedPortTCP.Create(AOwner: TComponent);
begin
inherited;
FMappedPort := ID_MAPPED_PORT_TCP_PORT;
end;
procedure TIdMappedPortTCP.DoConnect(AThread: TIdPeerThread);
begin
inherited;
AThread.Data := TIdMappedPortTCPData.Create;
with TIdMappedPortTCPData(AThread.Data) do
begin
OutboundClient := TIdTCPClient.Create(nil);
with OutboundClient do
begin
Port := MappedPort;
Host := MappedHost;
if Assigned(FOnBeforeClientConnect) then
begin
FOnBeforeClientConnect(Self, AThread, OutboundClient);
end;
Connect;
end;
end;
end;
function TIdMappedPortTCP.DoExecute(AThread: TIdPeerThread): boolean;
var
LData: TIdMappedPortTCPData;
begin
result := true;
LData := TIdMappedPortTCPData(AThread.Data);
try
with LData.ReadList do
begin
Clear;
Add(TObject(AThread.Connection.Binding.Handle));
Add(TObject(LData.OutboundClient.Binding.Handle));
if GStack.WSSelect(LData.ReadList, nil, nil, IdTimeoutInfinite) > 0 then
begin
if IndexOf(TObject(AThread.Connection.Binding.Handle)) > -1 then
begin
LData.OutboundClient.Write(AThread.Connection.CurrentReadBuffer);
end;
if IndexOf(TObject(LData.OutboundClient.Binding.Handle)) > -1 then
begin
AThread.Connection.Write(LData.OutboundClient.CurrentReadBuffer);
end;
end;
end;
finally
if not LData.OutboundClient.Connected then
begin
AThread.Connection.Disconnect;
end;
end;
end;
constructor TIdMappedPortTCPData.Create;
begin
ReadList := TList.Create;
end;
destructor TIdMappedPortTCPData.Destroy;
begin
FreeAndNil(ReadList);
FreeAndNil(OutboundClient);
inherited;
end;
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclResources.pas. }
{ }
{ The Initial Developer of the Original Code is documented in the accompanying }
{ help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. }
{ }
{**************************************************************************************************}
{ }
{ Unit which provides a central place for all resource strings used in the JCL }
{ }
{ Unit owner: Marcel van Brakel }
{ Last modified: March 12, 2002 }
{ }
{**************************************************************************************************}
unit JclResources;
{$I jcl.inc}
{$WEAKPACKAGEUNIT ON}
interface
//--------------------------------------------------------------------------------------------------
// JclBase
//--------------------------------------------------------------------------------------------------
resourcestring
RsWin32Prefix = 'Win32: %s (%u)';
RsDynArrayError = 'DynArrayInitialize: ElementSize out of bounds';
RsSysErrorMessageFmt = 'Win32 Error %d (%x)';
//--------------------------------------------------------------------------------------------------
// JclClasses
//--------------------------------------------------------------------------------------------------
resourcestring
RsVMTMemoryWriteError = 'Error writing VMT memory (%s)';
//--------------------------------------------------------------------------------------------------
// JclCOM
//--------------------------------------------------------------------------------------------------
resourcestring
RsComInvalidParam = 'An invalid parameter was passed to the routine. If a parameter was' +
' expected, it might be an unassigned item or nil pointer';
RsComFailedStreamRead = 'Failed to read all of the data from the specified stream';
RsComFailedStreamWrite = 'Failed to write all of the data into the specified stream';
//--------------------------------------------------------------------------------------------------
// JclComplex
//--------------------------------------------------------------------------------------------------
resourcestring
RsComplexInvalidString = 'Failed to create a complex number from the string provided';
//--------------------------------------------------------------------------------------------------
// JclCounter
//--------------------------------------------------------------------------------------------------
resourcestring
RsNoCounter = 'No high performance counters supported';
//--------------------------------------------------------------------------------------------------
// JclDateTime
//--------------------------------------------------------------------------------------------------
resourcestring
RsMakeUTCTime = 'Error converting to UTC time. Time zone could not be determined';
RsDateConversion = 'Error illegal date or time format';
//--------------------------------------------------------------------------------------------------
// JclDebug
//--------------------------------------------------------------------------------------------------
// Diagnostics
resourcestring
RsDebugAssertValidPointer = 'Invalid Pointer passed to AssertValid';
RsDebugAssertValidString = 'Invalid string passed to AssertValid';
// TMapFiles
RsDebugMapFileExtension = '.map'; // do not localize
RsDebugNoProcessInfo = 'Unable to obtain process information';
RsDebugSnapshot = 'Failure creating toolhelp32 snapshot';
//--------------------------------------------------------------------------------------------------
// JclExprEval
//--------------------------------------------------------------------------------------------------
resourcestring
RsExprEvalRParenExpected = 'Parse error: '')'' expected';
RsExprEvalFactorExpected = 'Parse error: Factor expected';
RsExprEvalUnknownSymbol = 'Parse error: Unknown symbol: ''%s''';
RsExprEvalFirstArg = 'Parse error: ''('' and function''s first parameter expected';
RsExprEvalNextArg = 'Parse error: '','' and another parameter expected';
RsExprEvalEndArgs = 'Parse error: '')'' to close function''s parameters expected';
RsExprEvalExprNotFound = 'Expression compiler error: Expression ''%s'' not found';
RsExprEvalExprPtrNotFound = 'Expression compiler error: Expression pointer not found';
//--------------------------------------------------------------------------------------------------
// JclStrHashMap
//--------------------------------------------------------------------------------------------------
resourcestring
RsStringHashMapMustBeEmpty = 'HashList: must be empty to set size to zero';
RsStringHashMapDuplicate = 'Duplicate hash list entry: %s';
RsStringHashMapInvalidNode = 'Tried to remove invalid node: %s';
//--------------------------------------------------------------------------------------------------
// JclFileUtils
//--------------------------------------------------------------------------------------------------
resourcestring
// Path manipulation
RsPathInvalidDrive = '%s is not a valid drive';
// Files and directories
RsFileUtilsAttrUnavailable = 'Unable to retrieve attributes of %s';
RsCannotCreateDir = 'Unable to create directory';
// TJclFileVersionInfo
RsFileUtilsNoVersionInfo = 'File contains no version information';
RsFileUtilsLanguageIndex = 'Illegal language index';
// Strings returned from OSIdentTOString()
RsVosUnknown = 'Unknown';
RsVosDos = 'MS-DOS';
RsVosOS216 = '16-bit OS/2';
RsVosOS232 = '32-bit OS/2';
RsVosNT = 'Windows NT';
RsVosWindows16 = '16-bit Windows';
RsVosPM16 = '16-bit PM';
RsVosPM32 = '32-bit PM';
RsVosWindows32 = '32-bit Windows';
RsVosDosWindows16 = '16-bit Windows, running on MS-DOS';
RsVosDosWindows32 = 'Win32 API, running on MS-DOS';
RsVosOS216PM16 = '16-bit PM, running on 16-bit OS/2';
RsVosOS232PM32 = '32-bit PM, running on 32-bit OS/2';
RsVosNTWindows32 = 'Win32 API, running on Windows/NT';
RsVosDesignedFor = 'Designed for ';
// Strings returned from OSFileTypeToString()
RsVftUnknown = 'Unknown';
RsVftApp = 'Application';
RsVftDll = 'Library';
RsVftDrv = 'Driver';
RsVftFont = 'Font';
RsVftVxd = 'Virtual device';
RsVftStaticLib = 'Static-link library';
RsVft2DrvPRINTER = 'Printer';
RsVft2DrvKEYBOARD = 'Keyboard';
RsVft2DrvLANGUAGE = 'Language';
RsVft2DrvDISPLAY = 'Display';
RsVft2DrvMOUSE = 'Mouse';
RsVft2DrvNETWORK = 'Network';
RsVft2DrvSYSTEM = 'System';
RsVft2DrvINSTALLABLE = 'Installable';
RsVft2DrvSOUND = 'Sound';
RsVft2DrvCOMM = 'Communications';
RsVft2FontRASTER = 'Raster';
RsVft2FontVECTOR = 'Vector';
RsVft2FontTRUETYPE = 'TrueType';
// TJclFileStream
RsFileStreamCreate = 'Unable to create temporary file stream';
// TJclFileMapping
RsCreateFileMapping = 'Failed to create FileMapping';
RsCreateFileMappingView = 'Failed to create FileMappingView';
RsLoadFromStreamSize = 'Not enough space in View in procedure LoadFromStream';
RsFileMappingInvalidHandle = 'Invalid file handle';
RsViewNeedsMapping = 'FileMap argument of TJclFileMappingView constructor cannot be nil';
RsFailedToObtainSize = 'Failed to obtain size of file';
// GetDriveTypeStr()
RsUnknownDrive = 'Unknown drive type';
RsRemovableDrive = 'Removable Drive';
RsHardDisk = 'Hard Disk';
RsRemoteDrive = 'Remote Drive';
RsCDRomDrive = 'CD-ROM';
RsRamDisk = 'RAM-Disk';
// GetFileAttributeList()
RsAttrDirectory = 'Directory';
RsAttrReadOnly = 'ReadOnly';
RsAttrSystemFile = 'SystemFile';
RsAttrVolumeID = 'Volume ID';
RsAttrArchive = 'Archive';
RsAttrAnyFile = 'AnyFile';
RsAttrHidden = 'Hidden';
// GetFileAttributeListEx()
RsAttrNormal = 'Normal';
RsAttrTemporary = 'Temporary';
RsAttrCompressed = 'Compressed';
RsAttrOffline = 'Offline';
RsAttrEncrypted = 'Encrypted';
RsAttrReparsePoint = 'Reparse Point';
RsAttrSparseFile = 'Sparse';
// TJclFileMapping.Create
RsFileMappingOpenFile = 'Unable to open the file';
// TJclMappedTextReader
RsFileIndexOutOfRange = 'Index of out range';
// FileGetTypeName()
RsDefaultFileTypeName = ' File';
//--------------------------------------------------------------------------------------------------
// JclGraphics, JclGraphUtils
//--------------------------------------------------------------------------------------------------
resourcestring
RsAssertUnpairedEndUpdate = 'Unpaired BeginUpdate EndUpdate';
RsCreateCompatibleDc = 'Could not create compatible DC';
RsDestinationBitmapEmpty = 'Destination bitmap is empty';
RsDibHandleAllocation = 'Could not allocate handle for DIB';
RsMapSizeFmt = 'Could not set size on class "%s"';
RsSelectObjectInDc = 'Could not select object in DC';
RsSourceBitmapEmpty = 'Source bitmap is empty';
RsSourceBitmapInvalid = 'Source bitmap is invalid';
RsNoBitmapForRegion = 'No bitmap for region';
RsNoDeviceContextForWindow = 'Cannot get device context of the window';
RsInvalidRegion = 'Invalid Region defined for RegionInfo';
RsRegionDataOutOfBound = 'Out of bound index on RegionData';
RsRegionCouldNotCreated = 'Region could not be created';
RsInvalidHandleForRegion = 'Invalid handle for region';
RsInvalidRegionInfo = 'Invalid RegionInfo';
RsBitmapExtension = '.bmp';
RsJpegExtension = '.jpg';
//--------------------------------------------------------------------------------------------------
// JclMapi
//--------------------------------------------------------------------------------------------------
resourcestring
RsMapiError = 'MAPI Error: (%d) "%s"';
RsMapiMissingExport = 'Function "%s" is not exported by client';
RsMapiInvalidIndex = 'Index is out ot range';
RsMapiMailNoClient = 'No Simple MAPI client installed, cannot send the message';
RsMapiErrUSER_ABORT = 'User abort';
RsMapiErrFAILURE = 'General MAPI failure';
RsMapiErrLOGIN_FAILURE = 'MAPI login failure';
RsMapiErrDISK_FULL = 'Disk full';
RsMapiErrINSUFFICIENT_MEMORY = 'Insufficient memory';
RsMapiErrACCESS_DENIED = 'Access denied';
RsMapiErrTOO_MANY_SESSIONS = 'Too many sessions';
RsMapiErrTOO_MANY_FILES = 'Too many files were specified';
RsMapiErrTOO_MANY_RECIPIENTS = 'Too many recipients were specified';
RsMapiErrATTACHMENT_NOT_FOUND = 'A specified attachment was not found';
RsMapiErrATTACHMENT_OPEN_FAILURE = 'Attachment open failure';
RsMapiErrATTACHMENT_WRITE_FAILURE = 'Attachment write failure';
RsMapiErrUNKNOWN_RECIPIENT = 'Unknown recipient';
RsMapiErrBAD_RECIPTYPE = 'Bad recipient type';
RsMapiErrNO_MESSAGES = 'No messages';
RsMapiErrINVALID_MESSAGE = 'Invalid message';
RsMapiErrTEXT_TOO_LARGE = 'Text too large';
RsMapiErrINVALID_SESSION = 'Invalid session';
RsMapiErrTYPE_NOT_SUPPORTED = 'Type not supported';
RsMapiErrAMBIGUOUS_RECIPIENT = 'A recipient was specified ambiguously';
RsMapiErrMESSAGE_IN_USE = 'Message in use';
RsMapiErrNETWORK_FAILURE = 'Network failure';
RsMapiErrINVALID_EDITFIELDS = 'Invalid edit fields';
RsMapiErrINVALID_RECIPS = 'Invalid recipients';
RsMapiErrNOT_SUPPORTED = 'Not supported';
RsMapiMailORIG = 'From';
RsMapiMailTO = 'To';
RsMapiMailCC = 'Cc';
RsMapiMailBCC = 'Bcc';
RsMapiMailSubject = 'Subject';
RsMapiMailBody = 'Body';
//--------------------------------------------------------------------------------------------------
// JclMath
//--------------------------------------------------------------------------------------------------
resourcestring
RsMathDomainError = 'Domain check failure in JclMath';
RsEmptyArray = 'Empty array is not allowed as input parameter';
RsNonPositiveArray = 'Input array contains non-positive or zero values';
RsUnexpectedDataType = 'Unexpected data type';
RsUnexpectedValue = 'Unexpected data value';
RsRangeError = 'Cannot merge range';
RsInvalidRational = 'Invalid rational number';
RsDivByZero = 'Division by zero';
RsRationalDivByZero = 'Rational division by zero';
RsNoNaN = 'NaN expected';
RsNaNTagError = 'NaN Tag value %d out of range';
RsNaNSignal = 'NaN signaling %d';
//--------------------------------------------------------------------------------------------------
// JclMiscel
//--------------------------------------------------------------------------------------------------
resourcestring
// CreateProcAsUser
RsCreateProcOSVersionError = 'Unable to determine OS version';
RsCreateProcNTRequiredError = 'Windows NT required';
RsCreateProcBuild1057Error = 'NT version 3.51 build 1057 or later required';
RsCreateProcPrivilegeMissing = 'This account does not have the privilege "%s" (%s)';
RsCreateProcLogonUserError = 'LogonUser failed';
RsCreateProcAccessDenied = 'Access denied';
RsCreateProcLogonFailed = 'Unable to logon';
RsCreateProcSetStationSecurityError = 'Cannot set WindowStation "%s" security.';
RsCreateProcSetDesktopSecurityError = 'Cannot set Desktop "%s" security.';
RsCreateProcPrivilegesMissing = 'This account does not have one (or more) of ' +
'the following privileges: ' + '"%s"(%s)' + #13 + '"%s"(%s)' + #13;
RsCreateProcCommandNotFound = 'Command or filename not found: "%s"';
RsCreateProcFailed = 'CreateProcessAsUser failed';
//--------------------------------------------------------------------------------------------------
// JclMultimedia
//--------------------------------------------------------------------------------------------------
resourcestring
// Multimedia timer
RsMmTimerGetCaps = 'Error retrieving multimedia timer device capabilities';
RsMmTimerBeginPeriod = 'The supplied timer period value is out of range';
RsMmSetEvent = 'Error setting multimedia event timer';
RsMmInconsistentId = 'Multimedia timer callback was called with inconsistent Id';
RsMmTimerActive = 'This operation cannot be performed while the timer is active';
// Audio Mixer
RsMmMixerSource = 'Source';
RsMmMixerDestination = 'Destination';
RsMmMixerUndefined = 'Undefined';
RsMmMixerDigital = 'Digital';
RsMmMixerLine = 'Line';
RsMmMixerMonitor = 'Monitor';
RsMmMixerSpeakers = 'Speakers';
RsMmMixerHeadphones = 'Headphones';
RsMmMixerTelephone = 'Telephone';
RsMmMixerWaveIn = 'Waveform-audio input';
RsMmMixerVoiceIn = 'Voice input';
RsMmMixerMicrophone = 'Microphone';
RsMmMixerSynthesizer = 'Synthesizer';
RsMmMixerCompactDisc = 'Compact disc';
RsMmMixerPcSpeaker = 'PC speaker';
RsMmMixerWaveOut = 'Waveform-audio output';
RsMmMixerAuxiliary = 'Auxiliary audio line';
RsMmMixerAnalog = 'Analog';
RsMmMixerNoDevices = 'No mixer device found';
RsMmMixerCtlNotFound = 'Line control (%s, %.8x) not found';
// EJclMciError
RsMmUnknownError = 'Unknown MCI error No. %d';
RsMmMciErrorPrefix = 'MCI-Error: ';
// CD audio routines
RsMmNoCdAudio = 'Cannot open CDAUDIO-Device';
RsMmCdTrackNo = 'Track: %.2u';
RsMMCdTimeFormat = '%2u:%.2u';
RsMMTrackAudio = 'Audio';
RsMMTrackOther = 'Other';
//--------------------------------------------------------------------------------------------------
// JclNTFS
//--------------------------------------------------------------------------------------------------
resourcestring
RsInvalidArgument = '%s: Invalid argument <%s>';
RsNtfsUnableToDeleteSymbolicLink = 'Unable to delete temporary symbolic link';
//--------------------------------------------------------------------------------------------------
// JclPeImage
//--------------------------------------------------------------------------------------------------
// TJclPeImage
resourcestring
RsPeCantOpen = 'Cannot open file "%s"';
RsPeNotPE = 'This is not a PE format';
RsPeNotResDir = 'Not a resource directory';
RsPeNotAvailableForAttached = 'Feature is not available for attached images';
RsPeSectionNotFound = 'Section "%s" not found';
// PE directory names
RsPeImg_00 = 'Exports';
RsPeImg_01 = 'Imports';
RsPeImg_02 = 'Resources';
RsPeImg_03 = 'Exceptions';
RsPeImg_04 = 'Security';
RsPeImg_05 = 'Base Relocations';
RsPeImg_06 = 'Debug';
RsPeImg_07 = 'Description';
RsPeImg_08 = 'Machine Value';
RsPeImg_09 = 'TLS';
RsPeImg_10 = 'Load configuration';
RsPeImg_11 = 'Bound Import';
RsPeImg_12 = 'IAT';
RsPeImg_13 = 'Delay load import';
RsPeImg_14 = 'COM run-time';
// NT Header names
RsPeSignature = 'Signature';
RsPeMachine = 'Machine';
RsPeNumberOfSections = 'Number of Sections';
RsPeTimeDateStamp = 'Time Date Stamp';
RsPePointerToSymbolTable = 'Symbols Pointer';
RsPeNumberOfSymbols = 'Number of Symbols';
RsPeSizeOfOptionalHeader = 'Size of Optional Header';
RsPeCharacteristics = 'Characteristics';
RsPeMagic = 'Magic';
RsPeLinkerVersion = 'Linker Version';
RsPeSizeOfCode = 'Size of Code';
RsPeSizeOfInitializedData = 'Size of Initialized Data';
RsPeSizeOfUninitializedData = 'Size of Uninitialized Data';
RsPeAddressOfEntryPoint = 'Address of Entry Point';
RsPeBaseOfCode = 'Base of Code';
RsPeBaseOfData = 'Base of Data';
RsPeImageBase = 'Image Base';
RsPeSectionAlignment = 'Section Alignment';
RsPeFileAlignment = 'File Alignment';
RsPeOperatingSystemVersion = 'Operating System Version';
RsPeImageVersion = 'Image Version';
RsPeSubsystemVersion = 'Subsystem Version';
RsPeWin32VersionValue = 'Win32 Version';
RsPeSizeOfImage = 'Size of Image';
RsPeSizeOfHeaders = 'Size of Headers';
RsPeCheckSum = 'CheckSum';
RsPeSubsystem = 'Subsystem';
RsPeDllCharacteristics = 'Dll Characteristics';
RsPeSizeOfStackReserve = 'Size of Stack Reserve';
RsPeSizeOfStackCommit = 'Size of Stack Commit';
RsPeSizeOfHeapReserve = 'Size of Heap Reserve';
RsPeSizeOfHeapCommit = 'Size of Heap Commit';
RsPeLoaderFlags = 'Loader Flags';
RsPeNumberOfRvaAndSizes = 'Number of RVA';
// Load config names
RsPeVersion = 'Version';
RsPeGlobalFlagsClear = 'GlobalFlagsClear';
RsPeGlobalFlagsSet = 'GlobalFlagsSet';
RsPeCriticalSectionDefaultTimeout = 'CriticalSectionDefaultTimeout';
RsPeDeCommitFreeBlockThreshold = 'DeCommitFreeBlockThreshold';
RsPeDeCommitTotalFreeThreshold = 'DeCommitTotalFreeThreshold';
RsPeLockPrefixTable = 'LockPrefixTable';
RsPeMaximumAllocationSize = 'MaximumAllocationSize';
RsPeVirtualMemoryThreshold = 'VirtualMemoryThreshold';
RsPeProcessHeapFlags = 'ProcessHeapFlags';
RsPeProcessAffinityMask = 'ProcessAffinityMask';
RsPeCSDVersion = 'CSDVersion';
RsPeReserved = 'Reserved';
RsPeEditList = 'EditList';
// Machine names
RsPeMACHINE_UNKNOWN = 'Unknown';
RsPeMACHINE_I386 = 'Intel 386';
RsPeMACHINE_R3000 = 'MIPS little-endian R3000';
RsPeMACHINE_R4000 = 'MIPS little-endian R4000';
RsPeMACHINE_R10000 = 'MIPS little-endian R10000';
RsPeMACHINE_ALPHA = 'Alpha_AXP';
RsPeMACHINE_POWERPC = 'IBM PowerPC Little-Endian';
// Subsystem names
RsPeSUBSYSTEM_UNKNOWN = 'Unknown';
RsPeSUBSYSTEM_NATIVE = 'Native';
RsPeSUBSYSTEM_WINDOWS_GUI = 'GUI';
RsPeSUBSYSTEM_WINDOWS_CUI = 'Console';
RsPeSUBSYSTEM_OS2_CUI = 'OS/2';
RsPeSUBSYSTEM_POSIX_CUI = 'Posix';
RsPeSUBSYSTEM_RESERVED8 = 'Reserved 8';
// Debug symbol type names
RsPeDEBUG_UNKNOWN = 'UNKNOWN';
RsPeDEBUG_COFF = 'COFF';
RsPeDEBUG_CODEVIEW = 'CODEVIEW';
RsPeDEBUG_FPO = 'FPO';
RsPeDEBUG_MISC = 'MISC';
RsPeDEBUG_EXCEPTION = 'EXCEPTION';
RsPeDEBUG_FIXUP = 'FIXUP';
RsPeDEBUG_OMAP_TO_SRC = 'OMAP_TO_SRC';
RsPeDEBUG_OMAP_FROM_SRC = 'OMAP_FROM_SRC';
RsPeDEBUG_BORLAND = 'BORLAND';
// TJclPePackageInfo.PackageModuleTypeToString
RsPePkgExecutable = 'Executable';
RsPePkgPackage = 'Package';
PsPePkgLibrary = 'Library';
// TJclPePackageInfo.PackageOptionsToString
RsPePkgNeverBuild = 'NeverBuild';
RsPePkgDesignOnly = 'DesignOnly';
RsPePkgRunOnly = 'RunOnly';
RsPePkgIgnoreDupUnits = 'IgnoreDupUnits';
// TJclPePackageInfo.ProducerToString
RsPePkgV3Produced = 'Delphi 3 or C++ Builder 3';
RsPePkgProducerUndefined = 'Undefined';
RsPePkgBCB4Produced = 'C++ Builder 4 or later';
RsPePkgDelphi4Produced = 'Delphi 4 or later';
// TJclPePackageInfo.UnitInfoFlagsToString
RsPePkgMain = 'Main';
RsPePkgWeak = 'Weak';
RsPePkgOrgWeak = 'OrgWeak';
RsPePkgImplicit = 'Implicit';
//--------------------------------------------------------------------------------------------------
// JclPrint
//--------------------------------------------------------------------------------------------------
resourcestring
RsInvalidPrinter = 'Invalid printer';
RsNAStartDocument = 'Unable to "Start document"';
RsNASendData = 'Unable to send data to printer';
RsNAStartPage = 'Unable to "Start page"';
RsNAEndPage = 'Unable to "End page"';
RsNAEndDocument = 'Unable to "End document"';
RsNATransmission = 'Not all chars have been sent correctly to printer';
RsDeviceMode = 'Error retrieving DeviceMode';
RsUpdatingPrinter = 'Error updating printer driver';
RsIndexOutOfRange = 'Index out of range setting bin';
RsRetrievingSource = 'Error retrieving Bin Source Info';
RsRetrievingPaperSource = 'Error retrieving Paper Source Info';
RsIndexOutOfRangePaper = 'Index out of range setting paper';
// Paper Styles (PS)
RsPSLetter = 'Letter 8 1/2 x 11 in';
RsPSLetterSmall = 'Letter Small 8 1/2 x 11 in';
RsPSTabloid = 'Tabloid 11 x 17 in';
RsPSLedger = 'Ledger 17 x 11 in';
RsPSLegal = 'Legal 8 1/2 x 14 in';
RsPSStatement = 'Statement 5 1/2 x 8 1/2 in';
RsPSExecutive = 'Executive 7 1/2 x 10 in';
RsPSA3 = 'A3 297 x 420 mm';
RsPSA4 = 'A4 210 x 297 mm';
RsPSA4Small = 'A4 Small 210 x 297 mm';
RsPSA5 = 'A5 148 x 210 mm';
RsPSB4 = 'B4 250 x 354';
RsPSB5 = 'B5 182 x 257 mm';
RsPSFolio = 'Folio 8 1/2 x 13 in';
RsPSQuarto = 'Quarto 215 x 275 mm';
RsPS10X14 = '10 x 14 in';
RsPS11X17 = '11 x 17 in';
RsPSNote = 'Note 8 1/2 x 11 in';
RsPSEnv9 = 'Envelope #9 3 7/8 x 8 7/8 in';
RsPSEnv10 = 'Envelope #10 4 1/8 x 9 1/2 in';
RsPSEnv11 = 'Envelope #11 4 1/2 x 10 3/8 in';
RsPSEnv12 = 'Envelope #12 4 \276 x 11 in';
RsPSEnv14 = 'Envelope #14 5 x 11 1/2 in';
RsPSCSheet = 'C size sheet';
RsPSDSheet = 'D size sheet';
RsPSESheet = 'E size sheet';
RsPSUser = 'User Defined Size';
RsPSUnknown = 'Unknown Paper Size';
RsPrintIniPrinterName = 'PrinterName';
RsPrintIniPrinterPort = 'PrinterPort';
RsPrintIniOrientation = 'Orientation';
RsPrintIniPaperSize = 'PaperSize';
RsPrintIniPaperLength = 'PaperLength';
RsPrintIniPaperWidth = 'PaperWidth';
RsPrintIniScale = 'Scale';
RsPrintIniCopies = 'Copies';
RsPrintIniDefaultSource = 'DefaultSource';
RsPrintIniPrintQuality = 'PrintQuality';
RsPrintIniColor = 'Color';
RsPrintIniDuplex = 'Duplex';
RsPrintIniYResolution = 'YResolution';
RsPrintIniTTOption = 'TTOption';
//--------------------------------------------------------------------------------------------------
// JclRegistry
//--------------------------------------------------------------------------------------------------
resourcestring
RsUnableToOpenKeyRead = 'Unable to open key "%s" for read';
RsUnableToOpenKeyWrite = 'Unable to open key "%s" for write';
RsUnableToAccessValue = 'Unable to open key "%s" and access value "%s"';
//--------------------------------------------------------------------------------------------------
// JclRTTI
//--------------------------------------------------------------------------------------------------
resourcestring
RsRTTIValueOutOfRange = 'Value out of range (%s).';
RsRTTIUnknownIdentifier = 'Unknown identifier ''%s''.';
RsRTTIInvalidGUIDString = 'Invalid conversion from string to GUID (%s).';
RsRTTIInvalidBaseType = 'Invalid base type (%s is of type %s).';
RsRTTIVar = 'var ';
RsRTTIConst = 'const ';
RsRTTIArrayOf = 'array of ';
RsRTTIOut = 'out ';
RsRTTIBits = 'bits';
RsRTTIOrdinal = 'ordinal=';
RsRTTITrue = 'True';
RsRTTIFalse = 'False';
RsRTTITypeError = '???';
RsRTTITypeInfoAt = 'Type info: %p';
RsRTTIPropRead = 'read';
RsRTTIPropWrite = 'write';
RsRTTIPropStored = 'stored';
RsRTTIField = 'field';
RsRTTIStaticMethod = 'static method';
RsRTTIVirtualMethod = 'virtual method';
RsRTTIIndex = 'index';
RsRTTIDefault = 'default';
RsRTTIName = 'Name: ';
RsRTTIType = 'Type: ';
RsRTTIFlags = 'Flags: ';
RsRTTIGUID = 'GUID: ';
RsRTTITypeKind = 'Type kind: ';
RsRTTIOrdinalType = 'Ordinal type: ';
RsRTTIMinValue = 'Min value: ';
RsRTTIMaxValue = 'Max value: ';
RsRTTINameList = 'Names: ';
RsRTTIClassName = 'Class name: ';
RsRTTIParent = 'Parent: ';
RsRTTIPropCount = 'Property count: ';
RsRTTIUnitName = 'Unit name: ';
RsRTTIBasedOn = 'Based on: ';
RsRTTIFloatType = 'Float type: ';
RsRTTIMethodKind = 'Method kind: ';
RsRTTIParamCount = 'Parameter count: ';
RsRTTIReturnType = 'Return type: ';
RsRTTIMaxLen = 'Max length: ';
RsRTTIElSize = 'Element size: ';
RsRTTIElType = 'Element type: ';
RsRTTIElNeedCleanup = 'Elements need clean up: ';
RsRTTIVarType = 'Variant type: ';
//--------------------------------------------------------------------------------------------------
// JclSscanf
//--------------------------------------------------------------------------------------------------
resourcestring
RsSscanfBadSet = 'Bad set: ';
RsSscanfBadFormat = 'Bad format string';
RsSscanfInsufficient = 'Insufficient pointers for format specifiers';
//--------------------------------------------------------------------------------------------------
// JclStrings
//--------------------------------------------------------------------------------------------------
resourcestring
RsInvalidEmptyStringItem = 'String list passed to StringsToMultiSz cannot contain empty strings.';
RsNumericConstantTooLarge = 'Numeric constant too large.';
//--------------------------------------------------------------------------------------------------
// JclSynch
//--------------------------------------------------------------------------------------------------
resourcestring
RsSynchAttachWin32Handle = 'Invalid handle to TJclWin32HandleObject.Attach';
RsSynchDuplicateWin32Handle = 'Invalid handle to TJclWin32HandleObject.Duplicate';
RsSynchInitCriticalSection = 'Failed to initalize critical section';
RsSynchAttachDispatcher = 'Invalid handle to TJclDispatcherObject.Attach';
RsSynchCreateEvent = 'Failed to create event';
RsSynchOpenEvent = 'Failed to open event';
RsSynchCreateWaitableTimer = 'Failed to create waitable timer';
RsSynchOpenWaitableTimer = 'Failed to open waitable timer';
RsSynchCreateSemaphore = 'Failed to create semaphore';
RsSynchOpenSemaphore = 'Failed to open semaphore';
RsSynchCreateMutex = 'Failed to create mutex';
RsSynchOpenMutex = 'Failed to open mutex';
RsMetSectInvalidParameter = 'An invalid parameter was passed to the constructor.';
RsMetSectInitialize = 'Failed to initialize the metered section.';
RsMetSectNameEmpty = 'Name cannot be empty when using the Open constructor.';
//--------------------------------------------------------------------------------------------------
// JclSysInfo
//--------------------------------------------------------------------------------------------------
resourcestring
RsSystemProcess = 'System Process';
RsSystemIdleProcess = 'System Idle Process';
RsIntelCacheDescr01 = 'Instruction TLB, 4Kb pages, 4-way set associative, 32 entries';
RsIntelCacheDescr02 = 'Instruction TLB, 4Mb pages, fully associative, 2 entries';
RsIntelCacheDescr03 = 'Data TLB, 4Kb pages, 4-way set associative, 64 entries';
RsIntelCacheDescr04 = 'Data TLB, 4Mb pages, 4-way set associative, 8 entries';
RsIntelCacheDescr06 = '8KB instruction cache, 4-way set associative, 32 byte line size';
RsIntelCacheDescr08 = '16KB instruction cache, 4-way set associative, 32 byte line size';
RsIntelCacheDescr0A = '8KB data cache 2-way set associative, 32 byte line size';
RsIntelCacheDescr0C = '16KB data cache, 4-way set associative, 32 byte line size';
RsIntelCacheDescr40 = 'No L2 cache';
RsIntelCacheDescr41 = 'Unified cache, 32 byte cache line, 4-way set associative, 128Kb';
RsIntelCacheDescr42 = 'Unified cache, 32 byte cache line, 4-way set associative, 256Kb';
RsIntelCacheDescr43 = 'Unified cache, 32 byte cache line, 4-way set associative, 512Kb';
RsIntelCacheDescr44 = 'Unified cache, 32 byte cache line, 4-way set associative, 1Mb';
RsIntelCacheDescr45 = 'Unified cache, 32 byte cache line, 4-way set associative, 2Mb';
resourcestring
RsOSVersionWin95 = 'Windows 95';
RsOSVersionWin95OSR2 = 'Windows 95 OSR2';
RsOSVersionWin98 = 'Windows 98';
RsOSVersionWin98SE = 'Windows 98 SE';
RsOSVersionWinME = 'Windows ME';
RsOSVersionWinNT3 = 'Windows NT 3.%u';
RsOSVersionWinNT4 = 'Windows NT 4.%u';
RsOSVersionWin2000 = 'Windows 2000';
RsOSVersionWinXP = 'Windows XP';
resourcestring
RsProductTypeWorkStation = 'Workstation';
RsProductTypeServer = 'Server';
RsProductTypeAdvancedServer = 'Advanced Server';
RsProductTypePersonal = 'Home Edition';
RsProductTypeProfessional = 'Professional';
RsProductTypeDatacenterServer = 'Datacenter Server';
//--------------------------------------------------------------------------------------------------
// JclSysUtils
//--------------------------------------------------------------------------------------------------
resourcestring
RsCannotWriteRefStream = 'Can not write to a read-only memory stream';
RsStringToBoolean = 'Unable to convert the string "%s" to a boolean';
//--------------------------------------------------------------------------------------------------
// JclTD32
//--------------------------------------------------------------------------------------------------
resourcestring
RsHasNotTD32Info = 'File [%s] has not TD32 debug information!';
//--------------------------------------------------------------------------------------------------
// JclUnicode
//--------------------------------------------------------------------------------------------------
resourcestring
RsUREBaseString = 'Error in regular expression: %s' + #13;
RsUREUnexpectedEOS = 'Unexpected end of pattern.';
RsURECharacterClassOpen = 'Character class not closed, '']'' is missing.';
RsUREUnbalancedGroup = 'Unbalanced group expression, '')'' is missing.';
RsUREInvalidCharProperty = 'A character property is invalid';
RsUREInvalidRepeatRange = 'Invalid repetition range.';
RsURERepeatRangeOpen = 'Repetition range not closed, ''}'' is missing.';
RsUREExpressionEmpty = 'Expression is empty.';
implementation
end.
|
unit uInfoBoxWithBtnControls;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
VA508AccessibilityManager, ORFn, VAUtils;
function DefMessageDlg(const Msg: string; DlgType: TMsgDlgType; list: TStringList;
const aCaption: string = ''; NoDefault: Boolean = false): Integer;
implementation
function DefMessageDlg(const Msg: string; DlgType: TMsgDlgType; list: TStringList;
const aCaption: string = ''; NoDefault: Boolean = false): Integer;
var
Dlg: TForm;
i, j, cnt, btnHalf, btnLast, btnPos, btnSpace, btnNum, formHalf,value,
lastBtnLeft: integer;
btn: TButton;
// zPnl: TPanel;
str: string;
// bforeground, bfocused, bactive,
// bres: Boolean;
// BytesAllocated: longInt;
Buttons: TMsgDlgButtons;
begin
// Dlg := nil; // rpk 4/23/2009
// zPnl := nil; // rpk 4/23/2009
// BytesAllocated := GetHeapStatus.TotalAllocated;
//map captions to the following button
// (mbYes, mbNo, mbOK, mbCancel, mbAbort, mbRetry, mbIgnore,
// mbAll, mbNoToAll, mbYesToAll, mbHelp, mbClose);
Result := -1;
lastBtnLeft := 0;
cnt := list.Count;
case cnt of
4:
begin
str := list.Strings[0];
SetPiece(str, U, 3, 'Yes');
list.Strings[0] := str;
str := list.Strings[1];
SetPiece(str, U, 3, 'No');
list.Strings[1] := str;
str := list.Strings[2];
SetPiece(str, U, 3, 'Cancel');
list.Strings[2] := str;
str := list.Strings[3];
SetPiece(str, U, 3, 'Abort');
list.Strings[3] := str;
Buttons := [mbYes, mbNo, mbCancel, mbAbort];
end;
3:
begin
str := list.Strings[0];
SetPiece(str, U, 3, 'Yes');
list.Strings[0] := str;
str := list.Strings[1];
SetPiece(str, U, 3, 'No');
list.Strings[1] := str;
str := list.Strings[2];
SetPiece(str, U, 3, 'Cancel');
list.Strings[2] := str;
Buttons := [mbYes, mbNo, mbCancel];
end;
2:
begin
str := list.Strings[0];
SetPiece(str, U, 3, 'Yes');
list.Strings[0] := str;
str := list.Strings[1];
SetPiece(str, U, 3, 'No');
list.Strings[1] := str;
Buttons := [mbYes, mbNo];
end;
1:
begin
str := list.Strings[0];
SetPiece(str, U, 3, 'Yes');
list.Strings[0] := str;
Buttons := [mbYes];
end;
end;
Dlg := CreateMessageDialog(Msg, DlgType, buttons);
if Dlg <> nil then begin // rpk 5/14/2013
try
btnPos := 0;
btnSpace := 0;
btnNum := 0;
btnLast := 0;
//determine the existing space between buttons
if cnt>1 then
begin
for i := 0 to Dlg.ComponentCount - 1 do
if Dlg.Components[i] is TButton then begin
btn := TButton(Dlg.Components[i]);
if btnNum = 0 then btnlast := btn.Left + btn.Width
else btnSpace := (btn.Left + btn.Width) - btnlast;
inc(btnNum);
if btnNum = 2 then break;
end;
end;
if btnSpace = 0 then btnSpace := 10;
for i := 0 to Dlg.ComponentCount - 1 do
if Dlg.Components[i] is TButton then begin
btn := TButton(Dlg.Components[i]);
for j := 0 to list.count-1 do
begin
str := list.Strings[j];
if (Piece(str, U, 3) = btn.Name) then
begin
btn.Caption := Piece(str, u, 1);
SetPiece(str, U, 4, IntToStr(btn.modalResult));
list.Strings[j] := str;
if Piece(str, U, 2) = 'true' then
begin
btn.default := true;
btn.tabstop := true;
end
else
begin
btn.default := false;
btn.tabstop := false;
end;
end;
end;
btn.Width := TextWidthByFont(btn.Handle, btn.caption);
if cnt = 1 then
begin
btnHalf := btn.Width div 2;
formHalf := dlg.Width div 2;
btn.Left := formHalf - btnHalf;
lastBtnLeft := btn.Left + btn.Width;
end
else
begin
btn.Left := btnPos + btnSpace;
//if btn.Left < btnPos then btn.Left := btnPos + btnSpace;
btnPos := btn.Left + btn.Width;
lastBtnLeft := btnPos;
end;
If NoDefault then
begin
btn.default := false;
btn.tabstop := false;
dlg.ActiveControl := nil;
dlg.DefocusControl(btn, False);
end;
end;
if dlg.Width < (btnPos + btnSpace) then dlg.Width := btnPos + btnSpace;
finally
end;
try // rpk 2/23/2012
//This will cover that hopefully rare scenario that the message box receives so
//much text that it tries to expand right off the screen.
with Dlg do
if Height > Screen.WorkAreaHeight then begin
AutoScroll := True;
Top := Screen.WorkAreaTop;
Height := Screen.WorkAreaHeight;
if lastBtnLeft > 0 then Width := lastBtnLeft + btnSpace
else Width := Screen.WorkAreaWidth;
// Width := TLabel(FindComponent('Message')).Width +
// TImage(FindComponent('Image')).Width + 60;
end;
// center on main form
Dlg.Position := poMainFormCenter; // rpk 10/25/2012
// NOTE: fsStayOnTop: Don't use
// This form remains on top of the DESKTOP and of other forms in the project,
// except any others that also have FormStyle set to fsStayOnTop.
// If one fsStayOnTop form launches another, neither form will consistently remain on top.
// Dlg.FormStyle := fsStayOnTop; // rpk 10/25/2013
// if HelpCtx > 0 then begin // rpk 5/14/2013
// Dlg.HelpType := htContext; // rpk 5/14/2013
// Dlg.HelpContext := HelpCtx; // rpk 5/9/2013
// end;
if aCaption = '' then
case DlgType of
mtWarning:
Dlg.Caption := 'Warning';
mtError:
Dlg.Caption := 'Error';
mtInformation:
Dlg.Caption := 'Information';
mtConfirmation:
Dlg.Caption := 'Confirmation';
end
else
Dlg.Caption := aCaption;
// BytesAllocated := GetHeapStatus.TotalAllocated;
//not sure if this is needed
// zPnl := TPanel.Create(Application);
// if zPnl <> nil then begin // rpk 5/14/2013
// try // rpk 2/23/2012
//
// BytesAllocated := GetHeapStatus.TotalAllocated;
//
// with zPnl do begin
// Caption := msg;
// Left := 0; // rpk 5/14/2013
// Parent := Dlg;
// Height := 1;
// Width := 1;
// end;
dlg.BringToFront; // use BringToFront to move dlg to top of form stack; rpk 10/25/2013
value := Dlg.ShowModal;
result := value;
for j := 0 to list.count-1 do
begin
str := list.Strings[j];
if (Piece(str, U, 4) = IntToStr(value)) then
begin
Result := j;
break;
end;
end;
// finally // rpk 3/9/2009
// zPnl.Free; // rpk 3/9/2009
;
// end; // rpk 3/9/2009
// end; // if zPnl <> nil
finally // rpk 3/9/2009
Dlg.Release; // rpk 6/18/2013
// bres := ShowApplicationAndFocusOK(Application);
end; // rpk 3/9/2009
end; // if Dlg <> nil
// BytesAllocated := GetHeapStatus.TotalAllocated;
end; // DefMessageDlg
end.
|
unit Hints;
{
В данном модуле реализованы собственные всплывающие подсказки.
Автор модуля - Сергей Королев.
Я взял данный модуль к себе в помощь, и исправил ошибки,
связанные с неправильным вызовом FOldMessageEvent
(раньше функция OnMessage могла рекурсивно вызывать сама себя, из-за чего
стэк сразу переполнялся)
Как можно использовать данный модуль:
вы можете выполнять проверку введенных пользователем данных (напр., в TEdit)
в обработчике события OnExit. Если введены ошибочные данные, то не
нужно вызывать назойливое окно об ошибке, а достаточно вызвать функцию
ShowErrorHint(Edit1, 'Вы ввели некорректные данные!');
В результате фокус автоматически установится на проблемном компоненте,
и появится всплывающая подсказка с указанным вами текстом. Она будет висет
до тех пор, пока вы не нажмете какую либо клавишу на клавиатуре или мышке.
При этом все остальные элементы управления будут заблокированы (ведь каждый
вызывается обработчик события OnExit)
Изменить шрифты можно, только если влезть в методы Create или Paint
}
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, StdCtrls;
type
EHintError = class(Exception);
TCustomHintWindow = class(THintWindow)
protected
FOldMessageEvent : TMessageEvent;
procedure OnMessage(var Msg: TMsg; var Handled: Boolean);
procedure WMNCPaint(var Message: TMessage); message WM_NCPAINT;
public
procedure CancelHint;
function IsHintMsg(var Msg: TMsg): Boolean; override;
procedure ActivateHint(Rect: TRect; const AHint: string); override;
end;
TErrorHintWindow = class(TCustomHintWindow)
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
end;
THelperHintWindow = class(TCustomHintWindow)
public
constructor Create(AOwner: TComponent); override;
end;
var
ErrorHintWindow : TErrorHintWindow;
HelperHintWindow : THelperHintWindow;
procedure ShowErrorHintEx(AControl: TWinControl; const Hint: String);
procedure ShowErrorHint(AControl: TWinControl; const Hint: String);
procedure ShowHelperHint(P : TPoint; const Hint: String);
implementation
const
sGeneralError = 'Хитрая ошибка в модулe Hints';
MaxWidth = 300;
procedure ShowHelperHint(P : TPoint; const Hint: String);
var
WinRect: TRect;
CHint: array [0..255] of Char;
begin
WinRect := Bounds(P.X, P.Y, MaxWidth, 0);
DrawText(HelperHintWindow.Canvas.Handle, StrPCopy(CHint, Hint), -1,
WinRect, DT_CALCRECT or DT_LEFT or DT_WORDBREAK or DT_NOPREFIX);
Inc(WinRect.Right, 6);
Inc(WinRect.Bottom, 4);
HelperHintWindow.ActivateHint(WinRect, Hint);
end;
procedure ShowErrorHintEx(AControl: TWinControl; const Hint: String);
begin
ShowErrorHint(AControl, Hint);
raise EAbort.Create('');
end;
procedure ShowErrorHint(AControl: TWinControl; const Hint: String);
var
WinRect: TRect;
CHint: array [0..255] of Char;
begin
if not Assigned(AControl) then raise EHintError.Create(sGeneralError);
if AControl.Showing then AControl.SetFocus;
WinRect := Bounds(6, AControl.Height + 1, MaxWidth - 2, 0);
ErrorHintWindow.HandleNeeded;
// ErrorHintWindow.Canvas.Font.Style := [fsBold];
// Уточняются размеры области вывода текста (WinRect)
DrawText(ErrorHintWindow.Canvas.Handle, StrPCopy(CHint, Hint), -1,
WinRect, DT_CALCRECT or DT_LEFT or DT_WORDBREAK or DT_NOPREFIX);
Inc(WinRect.Right, 6);
Inc(WinRect.Bottom, 4);
WinRect.TopLeft := AControl.ClientToScreen(WinRect.TopLeft);
WinRect.BottomRight := AControl.ClientToScreen(WinRect.BottomRight);
ErrorHintWindow.ActivateHint(WinRect, Hint);
end;
constructor THelperHintWindow.Create(AOwner: TComponent);
begin
inherited;
Color := clLime;
end;
constructor TErrorHintWindow.Create(AOwner: TComponent);
begin
inherited;
Color := clRed;
end;
procedure TErrorHintWindow.Paint;
var
R: TRect;
begin
R := ClientRect;
Inc(R.Left, 2);
Inc(R.Top, 2);
Canvas.Font.Color := clWhite;
// Canvas.Font.Style := [fsBold];
DrawText(Canvas.Handle, PChar(Caption), -1, R, DT_LEFT or DT_NOPREFIX or
DT_WORDBREAK);
end;
procedure TCustomHintWindow.WMNCPaint(var Message: TMessage);
begin
Canvas.Handle := GetWindowDC(Handle);
with Canvas do
try
Pen.Style := psSolid;
Pen.Color := clMaroon;
Rectangle(0, 0, Width, Height);
finally
Canvas.Handle := 0;
end;
end;
procedure TCustomHintWindow.ActivateHint(Rect: TRect; const AHint: string);
begin
Height := Rect.Bottom - Rect.Top + 1;
Width := Rect.Right - Rect.Left + 1;
inherited ActivateHint(Rect, AHint);
FOldMessageEvent := Application.OnMessage;
Application.OnMessage := OnMessage;
end;
procedure TCustomHintWindow.CancelHint;
begin
Application.OnMessage := FOldMessageEvent;
Visible := False;
if HandleAllocated then ShowWindow(Handle, SW_HIDE);
end;
function TCustomHintWindow.IsHintMsg(var Msg: TMsg): Boolean;
begin
with Msg do
begin
Result := ((Message >= WM_KEYFIRST) and (Message <= WM_KEYLAST)) or
(Message = CM_ACTIVATE) or (Message = CM_DEACTIVATE) or (Message = CM_APPKEYDOWN) or
(Message = CM_APPSYSCOMMAND) or (Message = WM_COMMAND) or
((Message > WM_MOUSEMOVE) and (Message <= WM_MOUSELAST)) or
((Message > WM_NCMOUSEMOVE) and (Message <= WM_NCMBUTTONDBLCLK));
if Result then Result := (Message <> WM_KEYUP) and (Message <> WM_SYSKEYUP) and
(Message <> WM_NCLBUTTONUP) and (Message <> WM_NCRBUTTONUP) and
(Message <> WM_NCMBUTTONUP) and (Message <> WM_LBUTTONUP) and
(Message <> WM_RBUTTONUP) and (Message <> WM_MBUTTONUP);
end;
end;
procedure TCustomHintWindow.OnMessage(var Msg: TMsg; var Handled: Boolean);
begin
if IsHintMsg(Msg) then CancelHint;
if Assigned(FOldMessageEvent) and (@Application.OnMessage <> @FOldMessageEvent) then
FOldMessageEvent(Msg, Handled);
end;
initialization
ErrorHintWindow := TErrorHintWindow.Create(nil);
HelperHintWindow := THelperHintWindow.Create(nil);
finalization
HelperHintWindow.Free;
ErrorHintWindow.Free;
end.
|
unit DockedFormIntf;
interface
type
IDockedForm = interface(IInterface)
['{6D86BA7A-40C4-4165-86C1-AA319496F6D7}']
procedure SetTitle(const title: string);
end;
implementation
end.
|
{****************************************************************************************
StringTestBenchMark & ManyThreadsTestBenchMark v1.0
By Ivo Tops for FastCode Memory Manager BenchMark & Validation
****************************************************************************************}
unit StringThreadTestUnit;
interface
uses BenchmarkClassUnit;
type
TStringThreadTest = class(TFastcodeMMBenchmark)
protected
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetSpeedWeight: Double; override;
class function GetCategory: TBenchmarkCategory; override;
end;
TManyThreadsTest = class(TFastcodeMMBenchmark)
protected
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetSpeedWeight: Double; override;
class function GetCategory: TBenchmarkCategory; override;
end;
// Counters for thread running
procedure IncRunningThreads;
procedure DecRunningThreads;
procedure NotifyThreadError;
procedure NotifyValidationError;
implementation
uses Math, StringThread, windows, sysutils;
var RunningThreads: Integer;
ThreadError, ValidationError, ThreadMaxReached, ZeroThreadsReached:
Boolean;
procedure InitTest;
begin
RunningThreads := 0;
ZeroThreadsReached := False;
ThreadMaxReached := False;
ThreadError := False;
end;
procedure ExitTest;
begin
// If Thread had error raise exception
if ThreadError then raise Exception.Create('TestThread failed with an Error');
// If Thread had validate raise exception
if ValidationError then raise Exception.Create('TestThread failed Validation');
end;
{ TStringThreadTest }
class function TStringThreadTest.GetBenchmarkDescription: string;
begin
Result := 'A benchmark that does string manipulations concurrently in 8 different threads';
end;
class function TStringThreadTest.GetBenchmarkName: string;
begin
Result := 'StringThreadTest';
end;
class function TStringThreadTest.GetCategory: TBenchmarkCategory;
begin
Result := bmMultiThreadRealloc;
end;
class function TStringThreadTest.GetSpeedWeight: Double;
begin
{We're testing speed here, not memory usage}
Result := 0.8;
end;
procedure TStringThreadTest.RunBenchmark;
var I, J: Integer;
begin
inherited;
InitTest;
for J := 1 to 4 do
begin
for I := 1 to 8 do // Create a loose new thread that does stringactions
TStringThread.Create(25, 2000, 4096, False);
// Simply wait for all threads to finish
while not ZeroThreadsReached do sleep(10);
end;
{Update the peak address space usage}
UpdateUsageStatistics;
// Done
ExitTest;
end;
procedure IncRunningThreads;
var RT: Integer;
begin
RT := InterlockedExchangeAdd(@RunningThreads, 1);
ZeroThreadsReached := False;
ThreadMaxReached := RT > 1250;
end;
procedure DecRunningThreads;
var RT: Integer;
begin
RT := InterlockedExchangeAdd(@RunningThreads, -1);
ThreadMaxReached := RT > 1250;
ZeroThreadsReached := RT = 1; // Old value is 1, so new value is zero
end;
{ TManyThreadsTest }
class function TManyThreadsTest.GetBenchmarkDescription: string;
begin
Result := 'A benchmark that has many temporary threads, each doing a little string processing. ';
Result := Result + 'This test exposes possible multithreading issues in a memory manager and large per-thread ';
Result := Result + 'memory requirements.';
end;
class function TManyThreadsTest.GetBenchmarkName: string;
begin
Result := 'ManyShortLivedThreads';
end;
class function TManyThreadsTest.GetCategory: TBenchmarkCategory;
begin
Result := bmMultiThreadRealloc;
end;
class function TManyThreadsTest.GetSpeedWeight: Double;
begin
{We're testing speed here, not memory usage}
Result := 0.8;
end;
procedure TManyThreadsTest.RunBenchmark;
var
I: Integer;
begin
inherited;
InitTest;
// Launch a lot of threads
for I := 1 to 100 do
begin
TStringThread.Create(1000, 10, 512, False);
TStringThread.Create(10, 2, 4096, False);
TStringThread.Create(10, 2, 1024*1024, False);
end;
// Launch a lot of threads keeping threadmax in account
for I := 1 to 500 do
begin
TStringThread.Create(100, 1, 512, False);
TStringThread.Create(100, 100, 512, False);
TStringThread.Create(100, 1, 512, False);
while ThreadMaxReached do sleep(1);
end;
// Wait for all threads to finish
while not ZeroThreadsReached do sleep(50);
{Update the peak address space usage}
UpdateUsageStatistics;
// Done
ExitTest;
end;
procedure NotifyThreadError;
begin
ThreadError := True;
end;
procedure NotifyValidationError;
begin
ValidationError := True;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLBaseMeshSilhouette<p>
Silhouette classes for GLBaseMesh and FaceGroups.<p>
<b>History : </b><font size=-1><ul>
<li>16/11/10 - Yar - Added mesh visibility checking in TGLBaseMeshConnectivity.SetGLBaseMesh (thanks to dalex65)
<li>30/03/07 - DaStr - Added $I GLScene.inc
<li>25/03/07 - DaStr - Renamed parameters in some methods
(thanks Burkhard Carstens) (Bugtracker ID = 1678658)
<li>23/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>09/02/04 - MF - Fixed bug where vertices weren't freed when owned
<li>24/06/03 - MF - Created file from parts of GLShilouette
</ul></font>
}
unit GLBaseMeshSilhouette;
interface
{$I GLScene.inc}
uses
Classes, GLVectorGeometry, GLVectorLists, GLVectorFileObjects, GLSilhouette;
type
// TFaceGroupConnectivity
//
TFaceGroupConnectivity = class(TConnectivity)
private
FMeshObject: TMeshObject;
FOwnsVertices: boolean;
procedure SetMeshObject(const Value: TMeshObject);
public
procedure Clear; override;
{ : Builds the connectivity information. }
procedure RebuildEdgeList;
property MeshObject: TMeshObject read FMeshObject write SetMeshObject;
constructor Create(APrecomputeFaceNormal: boolean); override;
constructor CreateFromMesh(aMeshObject: TMeshObject; APrecomputeFaceNormal: boolean);
destructor Destroy; override;
end;
// TGLBaseMeshConnectivity
//
TGLBaseMeshConnectivity = class(TBaseConnectivity)
private
FGLBaseMesh: TGLBaseMesh;
FFaceGroupConnectivityList: TList;
function GetFaceGroupConnectivity(i: integer): TFaceGroupConnectivity;
function GetConnectivityCount: integer;
procedure SetGLBaseMesh(const Value: TGLBaseMesh);
protected
function GetEdgeCount: integer; override;
function GetFaceCount: integer; override;
public
property ConnectivityCount: integer read GetConnectivityCount;
property FaceGroupConnectivity[i: integer]: TFaceGroupConnectivity read GetFaceGroupConnectivity;
property GLBaseMesh: TGLBaseMesh read FGLBaseMesh write SetGLBaseMesh;
procedure Clear(SaveFaceGroupConnectivity: boolean);
{ : Builds the connectivity information. }
procedure RebuildEdgeList;
procedure CreateSilhouette(const silhouetteParameters: TGLSilhouetteParameters; var aSilhouette: TGLSilhouette; AddToSilhouette: boolean); override;
constructor Create(APrecomputeFaceNormal: boolean); override;
constructor CreateFromMesh(aGLBaseMesh: TGLBaseMesh);
destructor Destroy; override;
end;
implementation
{ TFaceGroupConnectivity }
// ------------------
// ------------------ TFaceGroupConnectivity ------------------
// ------------------
procedure TFaceGroupConnectivity.Clear;
begin
if Assigned(FVertices) then
begin
if FOwnsVertices then
FVertices.Clear
else
FVertices := nil;
inherited;
if not FOwnsVertices and Assigned(FMeshObject) then
FVertices := FMeshObject.Vertices;
end
else
inherited;
end;
constructor TFaceGroupConnectivity.Create(APrecomputeFaceNormal: boolean);
begin
inherited;
FOwnsVertices := true;
end;
procedure TFaceGroupConnectivity.SetMeshObject(const Value: TMeshObject);
begin
Clear;
FMeshObject := Value;
if FOwnsVertices then
FVertices.Free;
FVertices := FMeshObject.Vertices;
FOwnsVertices := false;
RebuildEdgeList;
end;
constructor TFaceGroupConnectivity.CreateFromMesh(aMeshObject: TMeshObject; APrecomputeFaceNormal: boolean);
begin
Create(APrecomputeFaceNormal);
MeshObject := aMeshObject;
end;
destructor TFaceGroupConnectivity.Destroy;
begin
if FOwnsVertices then
FVertices.Free;
FVertices := nil;
inherited;
end;
procedure TFaceGroupConnectivity.RebuildEdgeList;
var
iFaceGroup, iFace, iVertex: integer;
FaceGroup: TFGVertexIndexList;
List: PIntegerArray;
begin
// Make sure that the connectivity information is empty
Clear;
// Create a list of edges for the meshobject
for iFaceGroup := 0 to FMeshObject.FaceGroups.Count - 1 do
begin
Assert(FMeshObject.FaceGroups[iFaceGroup] is TFGVertexIndexList, 'Method only works for descendants of TFGVertexIndexList.');
FaceGroup := TFGVertexIndexList(FMeshObject.FaceGroups[iFaceGroup]);
case FaceGroup.Mode of
fgmmTriangles, fgmmFlatTriangles:
begin
for iFace := 0 to FaceGroup.TriangleCount - 1 do
begin
List := @FaceGroup.VertexIndices.List[iFace * 3 + 0];
AddIndexedFace(List^[0], List^[1], List^[2]);
end;
end;
fgmmTriangleStrip:
begin
for iFace := 0 to FaceGroup.VertexIndices.Count - 3 do
begin
List := @FaceGroup.VertexIndices.List[iFace];
if (iFace and 1) = 0 then
AddIndexedFace(List^[0], List^[1], List^[2])
else
AddIndexedFace(List^[2], List^[1], List^[0]);
end;
end;
fgmmTriangleFan:
begin
List := FaceGroup.VertexIndices.List;
for iVertex := 2 to FaceGroup.VertexIndices.Count - 1 do
AddIndexedFace(List^[0], List^[iVertex - 1], List^[iVertex])
end;
else
Assert(false, 'Not supported');
end;
end;
end;
// ------------------
// ------------------ TGLBaseMeshConnectivity ------------------
// ------------------
procedure TGLBaseMeshConnectivity.RebuildEdgeList;
var
i: integer;
begin
for i := 0 to ConnectivityCount - 1 do
FaceGroupConnectivity[i].RebuildEdgeList;
end;
procedure TGLBaseMeshConnectivity.Clear(SaveFaceGroupConnectivity: boolean);
var
i: integer;
begin
if SaveFaceGroupConnectivity then
begin
for i := 0 to ConnectivityCount - 1 do
FaceGroupConnectivity[i].Clear;
end
else
begin
for i := 0 to ConnectivityCount - 1 do
FaceGroupConnectivity[i].Free;
FFaceGroupConnectivityList.Clear;
end;
end;
constructor TGLBaseMeshConnectivity.Create(APrecomputeFaceNormal: boolean);
begin
FFaceGroupConnectivityList := TList.Create;
inherited;
end;
constructor TGLBaseMeshConnectivity.CreateFromMesh(aGLBaseMesh: TGLBaseMesh);
begin
Create(not(aGLBaseMesh is TGLActor));
GLBaseMesh := aGLBaseMesh;
end;
procedure TGLBaseMeshConnectivity.SetGLBaseMesh(const Value: TGLBaseMesh);
var
i: integer;
MO: TMeshObject;
Connectivity: TFaceGroupConnectivity;
begin
Clear(false);
FGLBaseMesh := Value;
// Only precompute normals if the basemesh isn't an actor (because they change)
FPrecomputeFaceNormal := not(Value is TGLActor);
FGLBaseMesh := Value;
for i := 0 to Value.MeshObjects.Count - 1 do
begin
MO := Value.MeshObjects[i];
if MO.Visible then
begin
Connectivity := TFaceGroupConnectivity.CreateFromMesh(MO, FPrecomputeFaceNormal);
FFaceGroupConnectivityList.Add(Connectivity);
end;
end;
end;
procedure TGLBaseMeshConnectivity.CreateSilhouette(const silhouetteParameters: TGLSilhouetteParameters; var aSilhouette: TGLSilhouette; AddToSilhouette: boolean);
var
i: integer;
begin
if aSilhouette = nil then
aSilhouette := TGLSilhouette.Create
else
aSilhouette.Flush;
for i := 0 to ConnectivityCount - 1 do
FaceGroupConnectivity[i].CreateSilhouette(silhouetteParameters, aSilhouette, true);
end;
destructor TGLBaseMeshConnectivity.Destroy;
begin
Clear(false);
FFaceGroupConnectivityList.Free;
inherited;
end;
function TGLBaseMeshConnectivity.GetConnectivityCount: integer;
begin
result := FFaceGroupConnectivityList.Count;
end;
function TGLBaseMeshConnectivity.GetEdgeCount: integer;
var
i: integer;
begin
result := 0;
for i := 0 to ConnectivityCount - 1 do
result := result + FaceGroupConnectivity[i].EdgeCount;
end;
function TGLBaseMeshConnectivity.GetFaceCount: integer;
var
i: integer;
begin
result := 0;
for i := 0 to ConnectivityCount - 1 do
result := result + FaceGroupConnectivity[i].FaceCount;
end;
function TGLBaseMeshConnectivity.GetFaceGroupConnectivity(i: integer): TFaceGroupConnectivity;
begin
result := TFaceGroupConnectivity(FFaceGroupConnectivityList[i]);
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Threadsafe;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.SysUtils, System.SyncObjs,
{$ELSE}
Classes, SysUtils, SyncObjs,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT.Intf, ADAPT;
{$I ADAPT_RTTI.inc}
type
TADReadWriteLock = class;
TADObjectTS = class;
TADPersistentTS = class;
/// <summary><c>Multiple-Read, Exclusive Write Locking for Thread-Safety.</c></summary>
TADReadWriteLock = class(TADAggregatedObject, IADReadWriteLock)
private
{$IFDEF ADAPT_LOCK_ALLEXCLUSIVE}
FWriteLock: TCriticalSection;
{$ELSE}
FActiveThread: Cardinal; // ID of the current Thread holding the Write Lock
FCountReads: {$IFDEF DELPHI}Int64{$ELSE}LongWord{$ENDIF DELPHI}; // Number of Read Operations in Progress
FCountWrites: {$IFDEF DELPHI}Int64{$ELSE}LongWord{$ENDIF DELPHI}; // Number of Write Operations in Progress
FLockState: Cardinal; // 0 = Waiting, 1 = Reading, 2 = Writing
FWaitRead,
FWaitWrite: TEvent;
function GetLockState: TADReadWriteLockState;
function GetThreadMatch: Boolean;
procedure SetActiveThread;
procedure SetLockState(const ALockState: TADReadWriteLockState);
protected
function AcquireReadActual: Boolean;
function AcquireWriteActual: Boolean;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
public
constructor Create(const Controller: IInterface); override;
destructor Destroy; override;
procedure AcquireRead;
procedure AcquireWrite;
procedure ReleaseRead;
procedure ReleaseWrite;
function TryAcquireRead: Boolean;
function TryAcquireWrite: Boolean;
procedure WithRead(const ACallback: TADCallbackUnbound); overload;
procedure WithRead(const ACallback: TADCallbackOfObject); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure WithRead(const ACallback: TADCallbackAnonymous); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure WithWrite(const ACallback: TADCallbackUnbound); overload;
procedure WithWrite(const ACallback: TADCallbackOfObject); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure WithWrite(const ACallback: TADCallbackAnonymous); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
{$IFNDEF ADAPT_LOCK_ALLEXCLUSIVE}
property LockState: TADReadWriteLockState read GetLockState;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
end;
/// <summary><c>Abstract Base Object Type containing a Threadsafe Lock.</c></summary>
/// <remarks><c>You only want to inherit from this if there is NO situation in which you would want a non-Threadsafe Instance.</c></remarks>
TADObjectTS = class abstract(TADObject, IADReadWriteLock)
protected
FLock: TADReadWriteLock;
function GetLock: IADReadWriteLock;
public
constructor Create; override;
destructor Destroy; override;
property Lock: IADReadWriteLock read GetLock implements IADReadWriteLock;
end;
/// <summary><c>Abstract Base Persistent Type containing a Thread-Safe Lock.</c></summary>
/// <remarks><c>You only want to inherit from this if there is NO situation in which you would want a non-Threadsafe Instance.</c></remarks>
TADPersistentTS = class abstract(TADPersistent, IADReadWriteLock)
protected
FLock: TADReadWriteLock;
function GetLock: IADReadWriteLock;
public
constructor Create; override;
destructor Destroy; override;
property Lock: IADReadWriteLock read GetLock implements IADReadWriteLock;
end;
TADObjectHolderTS<T: class> = class(TADObjectHolder<T>, IADReadWriteLock)
private
FLock: TADReadWriteLock;
function GetLock: IADReadWriteLock;
protected
// Getters
{ IADObjectOwner }
function GetOwnership: TADOwnership; override;
{ IADObjectHolder<T> }
function GetObject: T; override;
// Setters
{ IADObjectOwner }
procedure SetOwnership(const AOwnership: TADOwnership); override;
public
constructor Create(const AObject: T; const AOwnership: TADOwnership = oOwnsObjects); override;
destructor Destroy; override;
property Lock: IADReadWriteLock read GetLock implements IADReadWriteLock;
end;
function ADReadWriteLock(const Controller: IInterface): TADReadWriteLock;
implementation
function ADReadWriteLock(const Controller: IInterface): TADReadWriteLock;
begin
Result := TADReadWriteLock.Create(Controller);
end;
{ TADReadWriteLock }
procedure TADReadWriteLock.AcquireRead;
{$IFNDEF ADAPT_LOCK_ALLEXCLUSIVE}
var
LAcquired: Boolean;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
begin
{$IFDEF ADAPT_LOCK_ALLEXCLUSIVE}
FWriteLock.Enter;
{$ELSE}
repeat
LAcquired := AcquireReadActual;
until LAcquired;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
end;
{$IFNDEF ADAPT_LOCK_ALLEXCLUSIVE}
function TADReadWriteLock.AcquireReadActual: Boolean;
begin
Result := False;
case GetLockState of
lsWaiting, lsReading: begin
FWaitRead.ResetEvent;
SetLockState(lsReading);
{$IFDEF DELPHI}AtomicIncrement{$ELSE}InterlockedIncrement{$ENDIF DELPHI}(FCountReads);
Result := True;
end;
lsWriting: begin
Result := GetThreadMatch;
if (not Result) then
FWaitWrite.WaitFor(500)
else
{$IFDEF DELPHI}AtomicIncrement{$ELSE}InterlockedIncrement{$ENDIF DELPHI}(FCountReads);
end;
end;
end;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
procedure TADReadWriteLock.AcquireWrite;
{$IFNDEF ADAPT_LOCK_ALLEXCLUSIVE}
var
LAcquired: Boolean;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
begin
{$IFDEF ADAPT_LOCK_ALLEXCLUSIVE}
FWriteLock.Enter;
{$ELSE}
repeat
LAcquired := AcquireWriteActual;
until LAcquired;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
end;
{$IFNDEF ADAPT_LOCK_ALLEXCLUSIVE}
function TADReadWriteLock.AcquireWriteActual: Boolean;
begin
Result := False;
case GetLockState of
lsWaiting: begin
FWaitWrite.ResetEvent;
SetActiveThread;
SetLockState(lsWriting);
{$IFDEF DELPHI}AtomicIncrement{$ELSE}InterlockedIncrement{$ENDIF DELPHI}(FCountWrites);
Result := True;
end;
lsReading: FWaitRead.WaitFor(500);
lsWriting: begin
Result := GetThreadMatch;
if Result then
{$IFDEF DELPHI}AtomicIncrement{$ELSE}InterlockedIncrement{$ENDIF DELPHI}(FCountWrites);
end;
end;
end;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
constructor TADReadWriteLock.Create(const Controller: IInterface);
begin
inherited Create(Controller);
{$IFDEF ADAPT_LOCK_ALLEXCLUSIVE}
FWriteLock := TCriticalSection.Create;
{$ELSE}
FWaitRead := TEvent.Create(nil, True, True, '');
FWaitWrite := TEvent.Create(nil, True, True, '');
FActiveThread := 0; // Since there's no Thread yet
FCountReads := 0;
FCountWrites := 0;
FLockState := 0; // Waiting by default
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
end;
destructor TADReadWriteLock.Destroy;
begin
{$IFDEF ADAPT_LOCK_ALLEXCLUSIVE}
FWriteLock.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF};
{$ELSE}
FWaitRead.SetEvent;
FWaitWrite.SetEvent;
FWaitRead.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF};
FWaitWrite.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF};
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
inherited;
end;
{$IFNDEF ADAPT_LOCK_ALLEXCLUSIVE}
function TADReadWriteLock.GetLockState: TADReadWriteLockState;
const
LOCK_STATES: Array[0..2] of TADReadWriteLockState = (lsWaiting, lsReading, lsWriting);
begin
Result := LOCK_STATES[{$IFDEF DELPHI}AtomicIncrement{$ELSE}InterlockedExchangeAdd{$ENDIF DELPHI}(FLockState, 0)];
end;
function TADReadWriteLock.GetThreadMatch: Boolean;
begin
Result := {$IFDEF DELPHI}AtomicIncrement{$ELSE}InterlockedExchangeAdd{$ENDIF DELPHI}(FActiveThread, 0) = TThread.CurrentThread.ThreadID;
end;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
procedure TADReadWriteLock.ReleaseRead;
begin
{$IFDEF ADAPT_LOCK_ALLEXCLUSIVE}
FWriteLock.Leave;
{$ELSE}
case GetLockState of
lsWaiting: raise Exception.Create('Lock State not Read, cannot Release Read on a Waiting Lock!');
lsReading: begin
if {$IFDEF DELPHI}AtomicDecrement{$ELSE}InterlockedDecrement{$ENDIF DELPHI}(FCountReads) = 0 then
begin
SetLockState(lsWaiting);
FWaitRead.SetEvent;
end;
end;
lsWriting: begin
if (not GetThreadMatch) then
raise Exception.Create('Lock State not Read, cannot Release Read on a Write Lock!');
end;
end;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
end;
procedure TADReadWriteLock.ReleaseWrite;
begin
{$IFDEF ADAPT_LOCK_ALLEXCLUSIVE}
FWriteLock.Leave;
{$ELSE}
case GetLockState of
lsWaiting: raise Exception.Create('Lock State not Write, cannot Release Write on a Waiting Lock!');
lsReading: begin
if (not GetThreadMatch) then
raise Exception.Create('Lock State not Write, cannot Release Write on a Read Lock!');
end;
lsWriting: begin
if GetThreadMatch then
begin
if {$IFDEF DELPHI}AtomicDecrement{$ELSE}InterlockedDecrement{$ENDIF DELPHI}(FCountWrites) = 0 then
begin
SetLockState(lsWaiting);
{$IFDEF DELPHI}AtomicExchange{$ELSE}InterlockedExchange{$ENDIF DELPHI}(FActiveThread, 0);
FWaitWrite.SetEvent;
end;
end;
end;
end;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
end;
{$IFNDEF ADAPT_LOCK_ALLEXCLUSIVE}
procedure TADReadWriteLock.SetActiveThread;
begin
{$IFDEF DELPHI}AtomicExchange{$ELSE}InterlockedExchange{$ENDIF DELPHI}(FActiveThread, TThread.CurrentThread.ThreadID);
end;
procedure TADReadWriteLock.SetLockState(const ALockState: TADReadWriteLockState);
const
LOCK_STATES: Array[TADReadWriteLockState] of Integer = (0, 1, 2);
begin
{$IFDEF DELPHI}AtomicExchange{$ELSE}InterlockedExchange{$ENDIF DELPHI}(FLockState, LOCK_STATES[ALockState]);
end;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
function TADReadWriteLock.TryAcquireRead: Boolean;
begin
{$IFDEF ADAPT_LOCK_ALLEXCLUSIVE}
Result := FWriteLock.TryEnter;
{$ELSE}
Result := AcquireReadActual;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
end;
function TADReadWriteLock.TryAcquireWrite: Boolean;
begin
{$IFDEF ADAPT_LOCK_ALLEXCLUSIVE}
Result := FWriteLock.TryEnter;
{$ELSE}
Result := AcquireWriteActual;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
end;
procedure TADReadWriteLock.WithRead(const ACallback: TADCallbackUnbound);
begin
AcquireRead;
try
ACallback;
finally
ReleaseRead;
end;
end;
procedure TADReadWriteLock.WithRead(const ACallback: TADCallbackOfObject);
begin
AcquireRead;
try
ACallback;
finally
ReleaseRead;
end;
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADReadWriteLock.WithRead(const ACallback: TADCallbackAnonymous);
begin
AcquireRead;
try
ACallback;
finally
ReleaseRead;
end;
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure TADReadWriteLock.WithWrite(const ACallback: TADCallbackUnbound);
begin
AcquireWrite;
try
ACallback;
finally
ReleaseWrite;
end;
end;
procedure TADReadWriteLock.WithWrite(const ACallback: TADCallbackOfObject);
begin
AcquireWrite;
try
ACallback;
finally
ReleaseWrite;
end;
end;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure TADReadWriteLock.WithWrite(const ACallback: TADCallbackAnonymous);
begin
AcquireWrite;
try
ACallback;
finally
ReleaseWrite;
end;
end;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
{ TADObjectTS }
constructor TADObjectTS.Create;
begin
inherited;
FLock := ADReadWriteLock(Self);
end;
destructor TADObjectTS.Destroy;
begin
FLock.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF};
inherited;
end;
function TADObjectTS.GetLock: IADReadWriteLock;
begin
Result := FLock;
end;
{ TADPersistentTS }
constructor TADPersistentTS.Create;
begin
inherited;
FLock := ADReadWriteLock(Self);
end;
destructor TADPersistentTS.Destroy;
begin
FLock.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF};
inherited;
end;
function TADPersistentTS.GetLock: IADReadWriteLock;
begin
Result := FLock;
end;
{ TADObjectHolderTS<T> }
constructor TADObjectHolderTS<T>.Create(const AObject: T; const AOwnership: TADOwnership);
begin
inherited;
FLock := ADReadWriteLock(Self);
end;
destructor TADObjectHolderTS<T>.Destroy;
begin
FLock.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF};
inherited;
end;
function TADObjectHolderTS<T>.GetLock: IADReadWriteLock;
begin
Result := FLock;
end;
function TADObjectHolderTS<T>.GetObject: T;
begin
FLock.AcquireRead;
try
Result := inherited;
finally
FLock.ReleaseRead;
end;
end;
function TADObjectHolderTS<T>.GetOwnership: TADOwnership;
begin
FLock.AcquireRead;
try
Result := inherited;
finally
FLock.ReleaseRead;
end;
end;
procedure TADObjectHolderTS<T>.SetOwnership(const AOwnership: TADOwnership);
begin
FLock.AcquireWrite;
try
inherited;
finally
FLock.ReleaseWrite;
end;
end;
end.
|
unit tlist_1;
interface
uses System;
type
TList<T> = class
private
type
TItems = array of T;
var
FItems: TItems;
FCount: Int32;
procedure Grow;
procedure SetCapacity(Value: Int32);
procedure MoveUpItems(FromIdx, ToIdx: Int32);
function GetCapacity: Int32;
public
property Count: Int32 read FCount;
property Capacity: Int32 read GetCapacity write SetCapacity;
procedure Add(const Value: T);
procedure Delete(Index: Int32);
end;
implementation
procedure TList<T>.Grow;
var
Len: Int32;
begin
Len := Length(FItems);
SetLength(FItems, Len*2);
end;
procedure TList<T>.SetCapacity(Value: Int32);
begin
if Value < FCount then
FCount := Value;
SetLength(FItems, Value);
end;
procedure TList<T>.MoveUpItems(FromIdx, ToIdx: Int32);
begin
// Move(FItems
end;
function TList<T>.GetCapacity: Int32;
begin
Result := Length(FItems);
end;
procedure TList<T>.Add(const Value: T);
begin
if FCount < Capacity then
begin
FItems[FCount] := T;
Inc(FCount);
end else
Grow();
end;
procedure TList<T>.Delete(Index: Int32);
begin
end;
procedure Test;
begin
end;
initialization
Test();
finalization
end. |
{===============================================================================
Copyright(c) 2014, 北京北研兴电力仪表有限责任公司
All rights reserved.
学员信息单元
+ TStudentAction 学员数据库操作类
===============================================================================}
unit xStudentAction;
interface
uses
System.Classes, System.SysUtils, xDBActionBase, system.Variants, xStudentInfo,
FireDAC.Stan.Param;
type
/// <summary>
/// 学员数据库操作类
/// </summary>
TStudentAction = class(TDBActionBase)
public
/// <summary>
/// 保存学员信息
/// </summary>
procedure SaveStuData(AStuInfo : TStudentInfo);
/// <summary>
/// 获取最大学员编号
/// </summary>
function GetStuMaxNumber : Integer;
/// <summary>
/// 删除学员
/// </summary>
procedure DelStu(nStuNumber : Integer);
/// <summary>
/// 清空学员表
/// </summary>
procedure ClearStus;
/// <summary>
/// 查询所有学员信息
/// </summary>
procedure SelStusAll(sList : TStringList);
/// <summary>
/// 获取考生
/// </summary>
function GetStuInfo( sLogName, sPWD : string; AStuInfo : TStudentInfo) : Boolean;
end;
implementation
{ TStudentAction }
procedure TStudentAction.DelStu(nStuNumber: Integer);
const
C_SQL_DELETE = 'delete from SUDENT_INFO where STUNumber = %d';
begin
if Assigned(FQuery) then
begin
FQuery.ExecSQL(Format(C_SQL_DELETE, [nStuNumber]));
end;
end;
procedure TStudentAction.ClearStus;
const
C_SQL = 'delete from SUDENT_INFO';
begin
if Assigned(FQuery) then
FQuery.ExecSQL(C_SQL);
end;
function TStudentAction.GetStuInfo(sLogName, sPWD: string;
AStuInfo: TStudentInfo): Boolean;
const
C_SQL = 'select * from SUDENT_INFO where STULogin = :STULogin and STUPassword = :STUPassword';
begin
// if sPWD = '' then
// begin
// FQuery.SQL.Text := Format(C_SQL, [sLogName, '''']);
// end
// else
// begin
// FQuery.SQL.Text := Format(C_SQL, [sLogName, sPWD]);
// end;
// FQuery.SQL.Text := 'select * from SUDENT_INFO where STULogin = 5 and STUPassword = null';
FQuery.SQL.Text := C_SQL;
FQuery.Params.ParamByName('STULogin').Value := sLogName;
FQuery.Params.ParamByName('STUPassword').Value := sPWD;
FQuery.Open;
Result := FQuery.RecordCount > 0;
if Result then
begin
with AStuInfo, FQuery do
begin
stuNumber := FieldByName('STUNumber').AsInteger;
stuName := FieldByName('STUName').AsString;
stuSex := FieldByName('STUSex').AsString;
stuIdCard := FieldByName('STUIDcard').AsString;
stuLogin := FieldByName('STULogin').AsString;
stuPwd := FieldByName('STUPassword').AsString;
stuArea := FieldByName('STUArea').AsString;
stuTel := FieldByName('STUTel').AsString;
stuNote1 := FieldByName('STURemark1').AsString;
stuNote2 := FieldByName('STURemark2').AsString;
end;
end;
end;
function TStudentAction.GetStuMaxNumber: Integer;
const
C_SQL_MAX = 'select max(STUNumber) from SUDENT_INFO';
begin
Result := 1;
if Assigned(FQuery) then
begin
with FQuery do
begin
Open(C_SQL_MAX);
if Fields[0].Value <> null then
begin
Result := Fields[0].AsInteger + 1;
end;
Close;
end;
end;
end;
procedure TStudentAction.SaveStuData(AStuInfo: TStudentInfo);
const
C_SQL_INSERT = 'Insert Into SUDENT_INFO(STUNumber,STUName,STUSex,STUIDcard,' +
'STULogin,STUPassword,STUArea,STUTel,STURemark1,STURemark2) ' +
'values(%d, ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ' +
'''%s'', ''%s'', ''%s'')';
C_SQL_UPDATE = 'update SUDENT_INFO set STUNumber = %d,STUName = ''%s'',' +
'STUSex = ''%s'',STUIDcard = ''%s'',STULogin = ''%s'',STUPassword = ''%s'',' +
'STUArea = ''%s'',STUTel = ''%s'',STURemark1 = ''%s'',STURemark2 = ''%s''' +
' where STUNumber = %d';
var
sSQL : string;
begin
if Assigned(AStuInfo) then
begin
if Assigned(FQuery) then
begin
with AStuInfo do
begin
sSQL := Format(C_SQL_UPDATE, [stuNumber, stuName, stuSex,
stuIdCard, stuLogin, stuPwd
, stuArea, stuTel, stuNote1
, stuNote2, stuNumber]);
try
if FQuery.ExecSQL(sSQL) = 0 then
begin
sSQL := Format(C_SQL_INSERT, [stuNumber, stuName, stuSex,
stuIdCard, stuLogin, stuPwd
, stuArea, stuTel, stuNote1
, stuNote2]);
FQuery.ExecSQL(sSQL);
end;
except
raise Exception.Create('更新失败!');
end;
end;
end;
end;
end;
procedure TStudentAction.SelStusAll(sList: TStringList);
var
AStuInio : TStudentInfo;
begin
if Assigned(sList) then
begin
if Assigned(FQuery) then
begin
FQuery.Open('select * from SUDENT_INFO');
if FQuery.RecordCount > 0 then
begin
FQuery.First;
while not FQuery.Eof do
begin
AStuInio := TStudentInfo.Create;
with FQuery, AStuInio do
begin
stuNumber := FieldByName('STUNumber').AsInteger;
stuName := FieldByName('STUName').AsString;
stuSex := FieldByName('STUSex').AsString;
stuIdCard := FieldByName('STUIDcard').AsString;
stuLogin := FieldByName('STULogin').AsString;
stuPwd := FieldByName('STUPassword').AsString;
stuArea := FieldByName('STUArea').AsString;
stuTel := FieldByName('STUTel').AsString;
stuNote1 := FieldByName('STURemark1').AsString;
stuNote2 := FieldByName('STURemark2').AsString;
end;
sList.AddObject(IntToStr(AStuInio.stuNumber), AStuInio);
FQuery.Next;
end;
FQuery.Close;
end;
end;
end;
end;
end.
|
unit unstCadastroVeterinario;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Mask, Vcl.DBCtrls, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls;
type
TfrmCadastroVeterinario = class(TForm)
pnlCentro: TPanel;
lblCodigo: TLabel;
Label1: TLabel;
lblCPF: TLabel;
btnPesquisar: TBitBtn;
edtCodigo: TEdit;
edtNome: TDBEdit;
edtCPF: TDBEdit;
pnlRodape: TPanel;
btnNovo: TBitBtn;
btnGravar: TBitBtn;
btnCancelar: TBitBtn;
btnExcluir: TBitBtn;
btnFechar: TBitBtn;
grpEndereco: TGroupBox;
edtCEP: TDBEdit;
Label2: TLabel;
edtLogradouro: TDBEdit;
Label3: TLabel;
edtNumero: TDBEdit;
Label4: TLabel;
Label5: TLabel;
edtComplemento: TDBEdit;
edtUF: TDBEdit;
Label6: TLabel;
edtCidade: TDBEdit;
Label7: TLabel;
edtBairro: TDBEdit;
Label8: TLabel;
edtTelI: TDBEdit;
Label9: TLabel;
edtTelII: TDBEdit;
Label10: TLabel;
edtTelIII: TDBEdit;
Label11: TLabel;
edtEmail: TDBEdit;
Label12: TLabel;
pnlDadosVet: TPanel;
edtCrmv: TDBEdit;
lblCrmv: TLabel;
lblUFCRMV: TLabel;
edtUFCRMV: TDBEdit;
pnlDadosProdutor: TPanel;
edtCNPJ: TDBEdit;
lblCNPJ: TLabel;
edtInscRural: TDBEdit;
lblInscRural: TLabel;
edtInsEstadual: TDBEdit;
lblInscEstadual: TLabel;
rdTipoPessoa: TRadioGroup;
chkSituacao: TDBCheckBox;
edtPropriedade: TDBEdit;
lblPropriedade: TLabel;
procedure FormActivate(Sender: TObject);
procedure btnFecharClick(Sender: TObject);
procedure rdTipoPessoaClick(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnExcluirClick(Sender: TObject);
procedure edtCodigoExit(Sender: TObject);
procedure edtCodigoKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
vID, vTipoCadastro : String;
fNovo : Boolean;
procedure PesquisaBD(vStatus : boolean);
procedure CarregaCampos;
procedure PossicionaElementos;
end;
var
frmCadastroVeterinario: TfrmCadastroVeterinario;
implementation
{$R *.dfm}
uses untDM, untPesquisa, untFuncoes, untPrincipal;
procedure TfrmCadastroVeterinario.btnExcluirClick(Sender: TObject);
begin
if fNovo = False then
begin
if DM.qryCadastro.RecordCount > 0 then
begin
frmFuncoes.Botoes('Excluir', DM.qryCadastro);
end;
end
end;
procedure TfrmCadastroVeterinario.btnFecharClick(Sender: TObject);
begin
close;
end;
procedure TfrmCadastroVeterinario.btnGravarClick(Sender: TObject);
begin
if fNovo = True then
begin
dm.qryCadastro.FieldByName('id').AsString := edtCodigo.Text;
end;
if vTipoCadastro = 'Proprietario' then
begin
if rdTipoPessoa.ItemIndex = 0 then
dm.qryCadastro.FieldByName('TIPO').AsString := 'F'
else
dm.qryCadastro.FieldByName('TIPO').AsString := 'J';
end;
dm.qryCadastro.FieldByName('alteracao').AsDateTime := Date+time;
dm.qryCadastro.FieldByName('usuario').AsInteger := frmPrincipal.vUsuario;
dm.qryCadastro.FieldByName('CODEMPRESA').AsInteger := frmPrincipal.vEmpresa; //Versao 1.4 - 14/10/2018
dm.qryCadastro.Post;
dm.qryCadastro.ApplyUpdates(-1);
btnNovo.Enabled := True;
btnExcluir.Enabled := True;
edtCodigo.Enabled := True;
if vTipoCadastro = 'Veterinario' then
begin
frmFuncoes.AutoIncre('VETERINARIO', 'Gravar');
if fNovo = True then //Versao 1.2.0 - 04/07/2018
frmFuncoes.GravaLog('Adição de cadastro de Veterinário. Codigo: ' + edtCodigo.Text, IntToStr(frmPrincipal.vUsuario)) //Versao 1.2.0 - 04/07/2018
else
frmFuncoes.GravaLog('Alteração de cadastro de Veterinário. Codigo: ' + edtCodigo.Text, IntToStr(frmPrincipal.vUsuario)); //Versao 1.2.0 - 04/07/2018
end
else
begin
frmFuncoes.AutoIncre('PRODUTOR', 'Gravar');
if fNovo = True then //Versao 1.2.0 - 04/07/2018
frmFuncoes.GravaLog('Adição de cadastro de Produtor. Codigo: ' + edtCodigo.Text, IntToStr(frmPrincipal.vUsuario)) //Versao 1.2.0 - 04/07/2018
else
frmFuncoes.GravaLog('Alteração de cadastro de Produtor. Codigo: ' + edtCodigo.Text, IntToStr(frmPrincipal.vUsuario)); //Versao 1.2.0 - 04/07/2018
end;
ShowMessage('Cadastro realizado com sucesso.');
PesquisaBD(True); //Versao 1.3.0 - 19/07/2018 - RS
end;
procedure TfrmCadastroVeterinario.btnNovoClick(Sender: TObject);
begin
fNovo := True;
dm.qryCadastro.Insert;
btnNovo.Enabled := False;
btnGravar.Enabled := True;
btnExcluir.Enabled := False;
edtNome.SetFocus;
edtCodigo.Enabled := False;
if vTipoCadastro = 'Veterinario' then
edtCodigo.Text := IntToStr(frmFuncoes.AutoIncre('VETERINARIO', 'Novo'))
else
edtCodigo.Text := IntToStr(frmFuncoes.AutoIncre('PRODUTOR', 'Novo'));
end;
procedure TfrmCadastroVeterinario.btnPesquisarClick(Sender: TObject);
begin
if fNovo = False then
PesquisaBD(False);
end;
Procedure TfrmCadastroVeterinario.CarregaCampos;
begin
edtNome.DataField := 'NOME';
edtCPF.DataField := 'CPF';
edtCEP.DataField := 'CEP';
edtLogradouro.DataField := 'LOGRADOURO';
edtNumero.DataField := 'NUMERO';
edtComplemento.DataField := 'COMPLEMENTO';
edtUF.DataField := 'UF';
edtCidade.DataField := 'CIDADE';
edtBairro.DataField := 'BAIRRO';
edtTelI.DataField := 'TELI';
edtTelII.DataField := 'TELII';
edtTelIII.DataField := 'TELIII';
edtEmail.DataField := 'EMAIL';
chkSituacao.DataField := 'SITUACAO';
if vTipoCadastro = 'Veterinario' then
begin
edtCrmv.DataField := 'CRMV';
edtUFCRMV.DataField := 'UF_CRMV';
rdTipoPessoa.Visible := False;
end
else if vTipoCadastro = 'Proprietario' then
begin
edtInscRural.DataField := 'INSC_RURAL';
edtCNPJ.DataField := 'CNPJ';
edtInsEstadual.DataField := 'INSCEST';
edtPropriedade.DataField := 'PROPRIEDADE';
dm.qryCadastro.FieldByName('CNPJ').EditMask := '##.###.###/####-##';
rdTipoPessoa.Visible := True;
end;
dm.qryCadastro.FieldByName('CEP').EditMask := '##.###-###';
dm.qryCadastro.FieldByName('CPF').EditMask := '###.###.###-##';
dm.qryCadastro.FieldByName('TELI').EditMask := '(##) #####-####';
dm.qryCadastro.FieldByName('TELII').EditMask := '(##) #####-####';
dm.qryCadastro.FieldByName('TELIII').EditMask := '(##) ####-####';
end;
procedure TfrmCadastroVeterinario.edtCodigoExit(Sender: TObject);
begin
if Trim(edtCodigo.Text) <> '' then
PesquisaBD(True);
end;
procedure TfrmCadastroVeterinario.edtCodigoKeyPress(Sender: TObject;
var Key: Char);
begin
If not( key in['0'..'9',#08] ) then
key := #0;
end;
procedure TfrmCadastroVeterinario.FormActivate(Sender: TObject);
begin
Caption := 'Cadastro de ' + vTipoCadastro;
Height := 420;
vID := '0';
if vTipoCadastro = 'Veterinario' then
frmFuncoes.ExecutaSQL('Select * from VETERINARIO where ID = ' + vID, 'Abrir', DM.qryCadastro)
else
frmFuncoes.ExecutaSQL('Select * from PRODUTOR where ID = ' + vID, 'Abrir', DM.qryCadastro);
CarregaCampos;
edtCodigo.SetFocus;
PossicionaElementos;
end;
procedure TfrmCadastroVeterinario.FormKeyPress(Sender: TObject; var Key: Char);
begin
If key = #13 then
Begin
Key:= #0;
Perform(Wm_NextDlgCtl,0,0);
end;
end;
procedure TfrmCadastroVeterinario.PesquisaBD(vStatus: boolean);
begin
if vStatus = True then
begin
if Trim(edtCodigo.Text) <> '' then
begin
if vTipoCadastro = 'Veterinario' then
frmFuncoes.ExecutaSQL('Select * from VETERINARIO where ID = ' + QuotedStr(edtCodigo.Text), 'Abrir', dm.qryCadastro)
else
frmFuncoes.ExecutaSQL('Select * from PRODUTOR where ID = ' + QuotedStr(edtCodigo.Text), 'Abrir', dm.qryCadastro);
if dm.qryCadastro.RecordCount > 0 then
begin
dm.qryCadastro.Edit;
CarregaCampos;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodigo.SetFocus;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
if vTipoCadastro = 'Veterinario' then
begin
frmPesquisa.vTabela := 'VETERINARIO';
frmPesquisa.vComando := 'Select ID, NOME from VETERINARIO';
end
else
begin
frmPesquisa.vTabela := 'PRODUTOR';
frmPesquisa.vComando := 'Select ID, NOME from PRODUTOR';
end;
frmPesquisa.vTela := 'CADASTRO';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
procedure TfrmCadastroVeterinario.PossicionaElementos;
begin
if vTipoCadastro = 'Veterinario' then
begin
pnlDadosVet.Visible := True;
pnlDadosProdutor.Visible := False;
edtCPF.Visible := True;
lblCPF.Visible := True;
lblPropriedade.Visible := False; //VERSAO 1.6.3 16/01/2019
edtPropriedade.Visible := False; //VERSAO 1.6.3 16/01/2019
Height := 390;
end
else
begin
pnlDadosVet.Visible := False;
pnlDadosProdutor.Visible := True;
lblPropriedade.Visible := True; //VERSAO 1.6.3 16/01/2019
edtPropriedade.Visible := True; //VERSAO 1.6.3 16/01/2019
if rdTipoPessoa.ItemIndex = 0 then
begin
edtCPF.Visible := True;
lblCPF.Visible := True;
lblCNPJ.Visible := False;
edtCNPJ.Visible := False;
lblInscEstadual.Visible := False;
edtInsEstadual.Visible := False;
end
else
begin
edtCPF.Visible := False;
lblCPF.Visible := False;
lblCNPJ.Visible := true;
edtCNPJ.Visible := true;
lblInscEstadual.Visible := True;
edtInsEstadual.Visible := True;
end;
Height := 450;
end;
end;
procedure TfrmCadastroVeterinario.rdTipoPessoaClick(Sender: TObject);
begin
if rdTipoPessoa.ItemIndex = 0 then
begin
edtCPF.Visible := True;
lblCPF.Visible := True;
lblCNPJ.Visible := False;
edtCNPJ.Visible := False;
lblInscEstadual.Visible := False;
edtInsEstadual.Visible := False;
edtCPF.SetFocus;
edtCNPJ.Clear;
edtInsEstadual.Clear
end
else
begin
edtCPF.Visible := False;
lblCPF.Visible := False;
lblCNPJ.Visible := true;
edtCNPJ.Visible := true;
lblInscEstadual.Visible := True;
edtInsEstadual.Visible := True;
edtCNPJ.SetFocus;
edtCPF.Clear;
end;
end;
end.
|
unit UnitFormProductsCalcTable;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, thrift.collections, apitypes,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, UnitFormPopup2, Vcl.Menus;
type
TFormProductsCalcTable = class(TForm)
StringGrid1: TStringGrid;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure StringGrid1DblClick(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure N2Click(Sender: TObject);
private
{ Private declarations }
FProducts: IThriftList<IProduct>;
FSect: ICalcSection;
procedure doSetup;
public
{ Public declarations }
procedure setup(products: IThriftList<IProduct>; sect: ICalcSection);
end;
var
FormProductsCalcTable: TFormProductsCalcTable;
implementation
{$R *.dfm}
uses stringgridutils, stringutils, UnitApiClient, UnitFormPopup;
procedure TFormProductsCalcTable.doSetup;
var
ACol, ARow: Integer;
begin
with StringGrid1 do
begin
ColCount := FProducts.Count + 1;
RowCount := FSect.Params.Count + 1;
if RowCount > 1 then
FixedRows := 1;
Cells[0, 0] := 'Прибор';
for ACol := 1 to ColCount - 1 do
Cells[ACol, 0] := IntToStr(FProducts[ACol - 1].Serial);
for ARow := 1 to RowCount - 1 do
begin
Cells[0, ARow] := FSect.Params[ARow - 1].Name;
for ACol := 1 to ColCount - 1 do
Cells[ACol, ARow] := FSect.Params[ARow - 1].Values
[ACol - 1].Value;
end;
end;
end;
procedure TFormProductsCalcTable.N1Click(Sender: TObject);
var r:TGridRect;
begin
r.Top := 0;
r.Left := 0;
r.Bottom := StringGrid1.RowCount-1;
r.Right := StringGrid1.ColCount-1;
StringGrid1.Selection := r;
StringGrid_copy_to_clipboard(StringGrid1);
end;
procedure TFormProductsCalcTable.N2Click(Sender: TObject);
begin
StringGrid_copy_selection_to_clipboard(StringGrid1);
end;
procedure TFormProductsCalcTable.setup(products: IThriftList<IProduct>;
sect: ICalcSection);
begin
FProducts := products;
FSect := sect;
doSetup;
end;
procedure TFormProductsCalcTable.StringGrid1DblClick(Sender: TObject);
var
v: ICalcValue;
begin
with StringGrid1 do
begin
if (col < 1) or (row < 1) then
exit;
v := FSect.Params[row - 1].Values[col - 1];
end;
if v.Validated then
begin
formPopup.ImageError.Visible := not v.Valid;
formPopup.ImageInfo.Visible := v.Valid;
end
else
begin
formPopup.ImageError.Hide;
formPopup.ImageInfo.Hide;
end;
formPopup.RichEdit1.Text := v.Detail;
formPopup.ShowAtStringGridCell(StringGrid1);
end;
procedure TFormProductsCalcTable.StringGrid1DrawCell(Sender: TObject;
ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
grd: TStringGrid;
cnv: TCanvas;
ta: TAlignment;
AText: string;
floatValue: double;
v: ICalcValue;
begin
grd := StringGrid1;
cnv := grd.Canvas;
cnv.Brush.Color := clWhite;
cnv.Font.Assign(grd.Font);
AText := grd.Cells[ACol, ARow];
if (ARow = 0) or (ACol = 0) then
cnv.Brush.Color := cl3DLight;
ta := taCenter;
if ((ACol = 0) AND (ARow > 0)) OR TryStrToFloat2(grd.Cells[ACol, ARow],
floatValue) then
ta := taRightJustify;
if (ARow = 0) then
cnv.Font.Style := [fsBold];
if (ARow > 0) and (ACol > 0) then
begin
v := FSect.Params[ARow - 1].Values[ACol - 1];
if v.Validated then
begin
if v.Valid then
cnv.Font.Color := clBlue
else
begin
cnv.Font.Color := clRed;
cnv.Brush.Color := cl3DLight;
end;
end;
end;
if (gdSelected in State) then
cnv.Brush.Color := clGradientInactiveCaption;
StringGrid_DrawCellText(StringGrid1, ACol, ARow, Rect, ta, AText);
StringGrid_DrawCellBounds(cnv, ACol, ARow, Rect);
end;
end.
|
unit WisePort;
interface
uses
Windows, cbw, WiseHardware, WiseDaq, StopWatch;
type TWiseMultiPortSpec = record
daqid: TDaqId;
mask: word;
shiftR: integer;
shiftL: integer;
end;
type TWiseMultiPortSpecs = array of TWiseMultiPortSpec;
{
TWiseMultiPort - A specialized type of port, mainly used for TWiseEncoder objects.
A multi-port:
- Includes one or more ordered Daqs (either 4 or 8 bit). The order is defined by the
sequence of DaqIds passed to the constructor. Example: (FIRSTPORTA, FIRSTPORTCL).
- All but last Daq have full masks (either $f or $ff). The last Daq can
have a partial mask (e.g. $3)
- When reading a multi-port:
o The Daqs are read in the pre-defined order
o A maximal time-out is imposed between the Daq reads. If it is exceeded, the
process is re-started. This tries to make the multi-port readings as atomic as possible.
o An end-value is composed by shifting and masking the intermediate values in
the pre-defined order.
}
type TWiseMultiPort = class(TWiseObject)
private
Daqs: array of TWiseDaq; // Interfaces to the MCC Daqs
shrs: array of byte; // Each byte[i] read from the hardware is first shifted right by shrs[i]
masks: array of word; // then masked with masks[i]
shls: array of byte; // then shifted into the result by shls[i]
stopper: TStopWatch;
timeout: TLargeInteger;
public
constructor Create(Name: string; specs: TWiseMultiPortSpecs; timeout: TLargeInteger = 50); overload;
constructor Create(Name: string; DaqIds: array of TDaqId; lastmask: word; timeout: TLargeInteger = 50); overload;
destructor Destroy(); override;
procedure SetVal(val: integer);
function GetVal(): integer;
property Value: integer read GetVal write SetVal;
end;
{
TWisePort - The most commonly used port abstraction
}
type TWisePort = class(TWiseObject)
private
Daq: TWiseDaq;
Mask: word;
public
constructor Create(Name: string; did: TDaqId; mask: integer); overload;
constructor Create(Name: string; did: TDaqId); overload;
destructor Destroy(); override;
procedure _Create(Name: string; did: TDaqId; mask: integer);
function GetVal(): word; // reads the current port value
procedure SetVal(val: word); // sets the port to the given value
property Value: word read GetVal write SetVal;
end;
implementation
const EightBitPortIds: array[0..15] of integer = (
FIRSTPORTA, FIRSTPORTB, SECONDPORTA, SECONDPORTB,
THIRDPORTA, THIRDPORTB, FOURTHPORTA, FOURTHPORTB,
FIFTHPORTA, FIFTHPORTB, SIXTHPORTA, SIXTHPORTB,
SEVENTHPORTA, SEVENTHPORTB, EIGHTHPORTA, EIGHTHPORTB
);
const FourBitPortIds: array[0..15] of integer = (
FIRSTPORTCL, FIRSTPORTCH, SECONDPORTCL, SECONDPORTCH,
THIRDPORTCL, THIRDPORTCH, FOURTHPORTCL, FOURTHPORTCH,
FIFTHPORTCL, FIFTHPORTCH, SIXTHPORTCL, SIXTHPORTCH,
SEVENTHPORTCL, SEVENTHPORTCH, EIGHTHPORTCL, EIGHTHPORTCH
);
{ TWiseMultiPort implementation }
constructor TWiseMultiPort.Create(Name: string; specs: TWiseMultiPortSpecs; timeout: TLargeInteger = 50);
var
i: Integer;
daq: TWiseDaq;
board, port, dir, firstDir: integer;
keys: array of integer;
begin
SetLength(keys, High(specs) + 1);
SetLength(Self.masks, High(specs) + 1);
SetLength(Self.shrs, High(specs) + 1);
SetLength(Self.shls, High(specs) + 1);
firstDir := -1;
for i := 0 to High(specs) do begin // Check that all directions are the same
reverseDaqId(specs[i].daqid, board, port, dir);
keys[i] := daqId(board, port);
if i = 0 then
firstDir := dir
else
if dir <> firstDir then
raise EWiseError.CreateFmt('[%s]: %s: All directions must be the same!', ['TWiseMultiPort.Create', name]);
daq := lookupDaq(keys[i]);
if (daq <> nil) and (daq.Dir <> dir) then
raise EWiseError.CreateFmt('[%s]: %s: A Daq for Board%d.%s was already configured for the oposite direction!',
['TWiseMultiPort.Create', name, board, WiseDaqPortNames[port]]);
end;
Inherited Create(Name);
SetLength(Self.Daqs, High(specs) + 1);
for i := 0 to High(Daqs) do begin
daq := lookupDaq(keys[i]);
if specs[i].mask = 0 then
Self.masks[i] := $ff
else
Self.masks[i] := specs[i].mask;
Self.shrs[i] := specs[i].shiftR;
if specs[i].shiftL <> 0 then
Self.shls[i] := specs[i].shiftL
else
Self.shls[i] := i * 8;
if daq <> nil then
Self.Daqs[i] := daq
else
Self.Daqs[i] := TWiseDaq.Create(name, specs[i].daqid, Self.masks[i]);
Self.Daqs[i].IncRef;
end;
Self.stopper := TStopWatch.Create;
Self.Timeout := timeout;
end;
constructor TWiseMultiPort.Create(Name: string; DaqIds: array of TDaqId; lastmask: word; timeout: TLargeInteger = 50);
var
i: Integer;
specs: TWiseMultiPortSpecs;
begin
SetLength(specs, High(DaqIds) + 1);
for i := 0 to High(DaqIds) - 1 do begin
specs[i].daqid := DaqIds[i];
specs[i].mask := $ff;
specs[i].shiftL := 0;
specs[i].shiftR := 0;
end;
i := High(DaqIds);
specs[i].daqid := DaqIds[i];
specs[i].mask := lastmask;
specs[i].shiftL := 0;
specs[i].shiftR := 0;
Create(Name, specs, timeout);
end;
destructor TWiseMultiPort.Destroy();
var
i: integer;
begin
for i := 0 to High(Self.Daqs) do
Self.Daqs[i].DecRef;
inherited Destroy;
end;
function TWiseMultiPort.GetVal(): integer;
var
daqno, tries, elapsed: integer;
val: word;
begin
tries := 0;
elapsed := 0;
repeat
Result := 0;
daqno := 0;
repeat
if (daqno > 0) then
Self.stopper.Start; // start the stopper
val := Self.Daqs[daqno].Value;
if (daqno > 0) then begin
Self.stopper.Stop; // stop the stopper
elapsed := Self.stopper.ElapsedMicroseconds;
end;
if (daqno > 0) and (elapsed > Self.Timeout) then begin
daqno := 0; // read failed or took too long between reads => start over
continue;
end;
if Self.shrs[daqno] <> 0 then // shift left to get rid of unwanted LSBs
val := val SHR Self.shrs[daqno];
if Self.masks[daqno] <> 0 then
val := val AND Self.masks[daqno]; // mask off unwanted bits
Result := Result OR (val SHL Self.shls[daqno]); // shift byte into its position in the Result
Inc(daqno);
until daqno = High(Self.Daqs) + 1;
if daqno = High(Self.Daqs) + 1 then
break;
Inc(tries)
until tries = MaxTries;
if tries = MaxTries then
raise EWiseEncoderError.CreateFmt('[%s]: %s: Cannot read after %d tries.', ['TWiseEncoder.ReadDaqs', Self.Name, MaxTries]);
end;
procedure TWiseMultiPort.SetVal(val: integer);
begin
// TBD
end;
procedure TWisePort._Create(Name: string; did: TDaqId; mask: integer);
var
daq: TWiseDaq;
key, board, port, dir: integer;
begin
reverseDaqId(did, board, port, dir);
key := daqId(board, port);
daq := lookupDaq(key);
if (daq <> nil) then begin
if (daq.Dir <> dir) then
raise EWiseError.CreateFmt('[%s]: %s: A Daq for Board%d.%s was already configured for the oposite direction!',
['TWisePort._Create', name, board, WiseDaqPortNames[port]]);
Self.Daq := daq
end else
Self.Daq := TWiseDaq.Create(name, did);
inherited Create(Name);
Self.Mask := mask;
Self.Daq.IncRef;
end;
constructor TWisePort.Create(Name: string; did: TDaqId; mask: integer);
begin
_Create(Name, did, mask);
end;
constructor TWisePort.Create(Name: string; did: TDaqId);
var
mask, board, port, dir: integer;
begin
reverseDaqId(did, board, port, dir);
if WiseBoards[board].bitsPerDaq[port - FIRSTPORTA] = 8 then
mask := $ff
else
mask := $f;
_Create(Name, did, mask);
end;
destructor TWisePort.Destroy();
begin
Self.Daq.DecRef;
inherited Destroy;
end;
function TWisePort.GetVal(): word;
begin
Result := Self.Daq.Value;
end;
procedure TWisePort.SetVal(val: word);
begin
Self.Daq.Value := val;
end;
end.
|
unit ltr25api;
interface
uses SysUtils, ltrapitypes, ltrapidefine, ltrapi;
const
// Количество каналов АЦП в одном модуле LTR25
LTR25_CHANNEL_CNT = 8;
// Количество частот дискретизации.
LTR25_FREQ_CNT = 8;
// Количество частот, для которых сохраняются калибровочные коэффициенты
LTR25_CBR_FREQ_CNT = 2;
// Количество значений источника тока
LTR25_I_SRC_VALUE_CNT = 2;
// Размер поля с названием модуля.
LTR25_NAME_SIZE = 8;
// Размер поля с серийным номером модуля.
LTR25_SERIAL_SIZE = 16;
// Максимальное пиковое значение в Вольтах для диапазона измерения модуля
LTR25_ADC_RANGE_PEAK = 10;
// Код АЦП, соответствующее максимальному пиковому значению
LTR25_ADC_SCALE_CODE_MAX = 2000000000;
// Адрес, с которого начинается пользовательская область flash-памяти
LTR25_FLASH_USERDATA_ADDR = $0;
// Размер пользовательской области flash-памяти
LTR25_FLASH_USERDATA_SIZE = $100000;
// Минимальный размер блока для стирания flash-памяти. Все операции стирания
// должны быть кратны данному размеру
LTR25_FLASH_ERASE_BLOCK_SIZE = 4096;
{ -------------- Коды ошибок, специфичные для LTR25 ------------------------}
LTR25_ERR_FPGA_FIRM_TEMP_RANGE = -10600; // Загружена прошивка ПЛИС для неверного температурного диапазона
LTR25_ERR_I2C_ACK_STATUS = -10601; // Ошибка обмена при обращении к регистрам АЦП по интерфейсу I2C
LTR25_ERR_I2C_INVALID_RESP = -10602; // Неверный ответ на команду при обращении к регистрам АЦП по интерфейсу I2C
LTR25_ERR_INVALID_FREQ_CODE = -10603; // Неверно задан код частоты АЦП
LTR25_ERR_INVALID_DATA_FORMAT = -10604; // Неверно задан формат данных АЦП
LTR25_ERR_INVALID_I_SRC_VALUE = -10605; // Неверно задано значение источника тока
LTR25_ERR_CFG_UNSUP_CH_CNT = -10606; // Для заданной частоты и формата не поддерживается заданное количество каналов АЦП
LTR25_ERR_NO_ENABLED_CH = -10607; // Не был разрешен ни один канал АЦП
LTR25_ERR_ADC_PLL_NOT_LOCKED = -10608; // Ошибка захвата PLL АЦП
LTR25_ERR_ADC_REG_CHECK = -10609; // Ошибка проверки значения записанных регистров АЦП
LTR25_ERR_LOW_POW_MODE_NOT_CHANGED = -10610; // Не удалось перевести АЦП из/в низкопотребляющее состояние
LTR25_ERR_LOW_POW_MODE = -10611; // Модуль находится в низкопотребляющем режиме
{------------------ Коды частот дискретизации. -----------------------------}
LTR25_FREQ_78K = 0; // 78.125 кГц
LTR25_FREQ_39K = 1; // 39.0625 кГц
LTR25_FREQ_19K = 2; // 19.53125 кГц
LTR25_FREQ_9K7 = 3; // 9.765625 кГц
LTR25_FREQ_4K8 = 4; // 4.8828125 кГц
LTR25_FREQ_2K4 = 5; // 2.44140625 кГц
LTR25_FREQ_1K2 = 6; // 1.220703125 кГц
LTR25_FREQ_610 = 7; // 610.3515625 Гц
{------------------ Форматы данных от модуля --------------------------------}
LTR25_FORMAT_20 = 0; // 20-битный целочисленный (1 слово на отсчет)
LTR25_FORMAT_32 = 1; // 32-битный целочисленный (2 слова на отсчет)
{---------------------- Значения источника тока. ----------------------------}
LTR25_I_SRC_VALUE_2_86 = 0; // 2.86 мА
LTR25_I_SRC_VALUE_10 = 1; // 10 мА
{------------------- Флаги, управляющие обработкой данных. ------------------}
// Признак, что нужно перевести коды АЦП в Вольты
LTR25_PROC_FLAG_VOLT = $00000001;
// Признак, что идет обработка не непрерывных данных
LTR25_PROC_FLAG_NONCONT_DATA = $00000100;
{------------------- Состояние входного канала. -----------------------------}
LTR25_CH_STATUS_OK = 0; // Канал в рабочем состоянии
LTR25_CH_STATUS_SHORT = 1; // Было обнаружено короткое замыкание
LTR25_CH_STATUS_OPEN = 2; // Был обнаружен разрыв цепи
type
{$A4}
{ Заводские калибровочные коэффициенты для одного диапазона }
TLTR25_CBR_COEF = record
Offset : Single; // Код смещения
Scale : Single; // Коэффициент масштаба
end;
{ Набор коэффициентов для коррекции АЧХ модуля }
TLTR25_AFC_COEFS = record
// Частота сигнала, для которой снято отношение амплитуд из FirCoef
AfcFreq : Double;
{ Набор отношений измеренной амплитуды синусоидального сигнала
к реальной амплитуде для макс. частоты дискретизации и частоты сигнала
из AfcFreq для каждого канала и каждого диапазона }
FirCoef : Array [0..LTR25_CHANNEL_CNT-1] of Double;
end;
{ Информация о модуле }
TINFO_LTR25 = record
// Название модуля ("LTR25")
Name : Array [0..LTR25_NAME_SIZE-1] of AnsiChar;
// Серийный номер модуля
Serial : Array [0..LTR25_SERIAL_SIZE-1] of AnsiChar;
// Версия прошивки ПЛИС
VerFPGA : Word;
// Версия прошивки PLD
VerPLD : Byte;
// Ревизия платы
BoardRev : Byte;
// Признак, это индустриальный вариант модуля или нет
Industrial : LongBool;
// Зарезервированные поля. Всегда равны 0
Reserved : Array [1..8] of LongWord;
{ Калибровочные коэффициенты модуля. Считываются из Flash-памяти
модуля при вызове LTR25_Open() или LTR25_GetConfig() и загружаются
в ПЛИС для применения во время вызова LTR25_SetADC() }
CbrCoef : Array [0..LTR25_CHANNEL_CNT-1] of Array [0..LTR25_CBR_FREQ_CNT-1] of TLTR25_CBR_COEF;
// Коэффициенты для коррекции АЧХ модуля
AfcCoef : TLTR25_AFC_COEFS;
// Резервные поля
Reserved2 : array [0 .. (32*LTR25_CHANNEL_CNT - (LTR25_CHANNEL_CNT + 1) - 1)] of Double;
end;
// Настройки канала АЦП.
TLTR25_CHANNEL_CONFIG = record
Enabled : LongBool; // Признак, разрешен ли сбор по данному каналу
Reserved : array [1..11] of LongWord; // Резервные поля (не должны изменяться пользователем)
end;
// Настройки модуля.
TLTR25_CONFIG = record
Ch : array [0..LTR25_CHANNEL_CNT-1] of TLTR25_CHANNEL_CONFIG; // Настройки каналов АЦП
FreqCode : byte; // Код, задающий требуемую частоту сбора АЦП. Одно из значений #e_LTR25_FREQS
DataFmt : byte; //< Формат, в котором будут передаваться отсчеты АЦП от модуля. Одно из значений #e_LTR25_FORMATS.
ISrcValue : byte; // Используемое значение источника тока. Одно из значений #e_LTR25_I_SOURCES
Reserved : array [1..50] of LongWord; // Резервные поля (не должны изменяться пользователем)
end;
// Параметры текущего состояния модуля.
TLTR25_STATE = record
FpgaState : byte; //Tекущее состояние ПЛИС. Одно из значений из e_LTR_FPGA_STATE
EnabledChCnt : byte; //Количество разрешенных каналов. Устанавливается после вызова LTR25_SetADC()
Run : LongBool; // Признак, запущен ли сбор данных
AdcFreq : double; // Установленная частота АЦП. Обновляется после вызова LTR25_SetADC()
LowPowMode : LongBool; //< Признак, находится ли модуль в состоянии низкого потребления. */
Reserved : array [1..31] of LongWord; // Резервные поля
end;
PTLTR25_INTARNAL = ^TLTR25_INTARNAL;
TLTR25_INTARNAL = record
end;
// Управляющая структура модуля.
TLTR25 = record
Size : Integer; // Размер структуры. Заполняется в LTR25_Init().
{ Структура, содержащая состояние соединения с программой ltrd или LtrServer.
Не используется напрямую пользователем. }
Channel : TLTR;
{ Указатель на непрозрачную структуру с внутренними параметрами,
используемыми исключительно библиотекой и недоступными для пользователя. }
Internal : PTLTR25_INTARNAL;
// Настройки модуля. Заполняются пользователем перед вызовом LTR25_SetADC().
Cfg : TLTR25_CONFIG;
{ Состояние модуля и рассчитанные параметры. Поля изменяются функциями
библиотеки. Пользовательской программой могут использоваться
только для чтения. }
State : TLTR25_STATE;
{ Информация о модуле }
ModuleInfo : TINFO_LTR25;
end;
pTLTR25=^TLTR25;
{$A+}
// Инициализация описателя модуля
Function LTR25_Init(out hnd: TLTR25) : Integer;
// Установить соединение с модулем.
Function LTR25_Open(var hnd: TLTR25; net_addr : LongWord; net_port : Word;
csn: string; slot: Integer): Integer;
// Закрытие соединения с модулем
Function LTR25_Close(var hnd: TLTR25) : Integer;
// Проверка, открыто ли соединение с модулем.
Function LTR25_IsOpened(var hnd: TLTR25) : Integer;
// Запись настроек в модуль
Function LTR25_SetADC(var hnd: TLTR25) : Integer;
// Перевод в режим сбора данных
Function LTR25_Start(var hnd: TLTR25) : Integer;
// Останов режима сбора данных
Function LTR25_Stop(var hnd: TLTR25) : Integer;
// Прием данных от модуля
Function LTR25_Recv(var hnd: TLTR25; out data : array of LongWord; out tmark : array of LongWord; size: LongWord; tout : LongWord): Integer; overload;
Function LTR25_Recv(var hnd: TLTR25; out data : array of LongWord; size: LongWord; tout : LongWord): Integer; overload;
// Обработка принятых от модуля слов
Function LTR25_ProcessData(var hnd: TLTR25; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord; out ch_status : array of LongWord): Integer; overload;
Function LTR25_ProcessData(var hnd: TLTR25; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord): Integer; overload;
// Поиск начала первого кадра.
Function LTR25_SearchFirstFrame(var hnd : TLTR25; var data : array of LongWord;
size : LongWord; out index : LongWord) : Integer;
// Получение сообщения об ошибке.
Function LTR25_GetErrorString(err: Integer) : string;
Function LTR25_GetConfig(var hnd : TLTR25) : Integer;
// Перевод модуля в режим низкого потребления.
Function LTR25_SetLowPowMode(var hnd: TLTR25; lowPowMode : LongBool) : Integer;
// Проверка, разрешена ли работа ПЛИС модуля.
Function LTR25_FPGAIsEnabled(var hnd: TLTR25; out enabled : LongBool) : Integer;
// Разрешение работы ПЛИС модуля.
Function LTR25_FPGAEnable(var hnd: TLTR25; enable : LongBool) : Integer;
// Чтение данных из flash-памяти модуля
Function LTR25_FlashRead(var hnd: TLTR25; addr : LongWord; out data : array of byte; size : LongWord) : Integer;
// Запись данных во flash-память модуля
Function LTR25_FlashWrite(var hnd: TLTR25; addr : LongWord; var data : array of Byte; size : LongWord) : Integer;
// Стирание области flash-память модуля
Function LTR25_FlashErase(var hnd: TLTR25; addr : LongWord; size : LongWord) : Integer;
implementation
Function _init(out hnd: TLTR25) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_Init';
Function _open(var hnd: TLTR25; net_addr : LongWord; net_port : Word; csn: PAnsiChar; slot: Integer) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_Open';
Function _close(var hnd: TLTR25) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_Close';
Function _is_opened(var hnd: TLTR25) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_IsOpened';
Function _set_adc(var hnd: TLTR25) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_SetADC';
Function _start(var hnd: TLTR25) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_Start';
Function _stop(var hnd: TLTR25) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_Stop';
Function _recv(var hnd: TLTR25; out data; out tmark; size: LongWord; tout : LongWord): Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_Recv';
Function _process_data(var hnd: TLTR25; var src; out dest; var size: Integer; flags : LongWord; out ch_status): Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_ProcessData';
// Определяет данные в слоте для хранения управляющей структуры как некорректные
Function _search_first_frame(var hnd : TLTR25; var data; size : LongWord; out index : LongWord) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_SearchFirstFrame';
Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_GetErrorString';
Function _get_config(var hnd : TLTR25) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_GetConfig';
Function _set_low_pow_mode(var hnd: TLTR25; lowPowMode : LongBool) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_SetLowPowMode';
Function _fpga_is_enabled(var hnd: TLTR25; out enabled : LongBool) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_FPGAIsEnabled';
Function _fpga_enable(var hnd: TLTR25; enable : LongBool) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_FPGAEnable';
Function _flash_read(var hnd: TLTR25; addr : LongWord; out data; size : LongWord) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_FlashRead';
Function _flash_write(var hnd: TLTR25; addr : LongWord; var data : array of Byte; size : LongWord) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_FlashWrite';
Function _flash_erase(var hnd: TLTR25; addr : LongWord; size : LongWord) : Integer; {$I ltrapi_callconvention}; external 'ltr25api' name 'LTR25_FlashErase';
Function LTR25_Init(out hnd: TLTR25) : Integer;
begin
LTR25_Init:=_init(hnd);
end;
Function LTR25_Close(var hnd: TLTR25) : Integer;
begin
LTR25_Close:=_close(hnd);
end;
Function LTR25_Open(var hnd: TLTR25; net_addr : LongWord; net_port : Word; csn: string; slot: Integer): Integer;
begin
LTR25_Open:=_open(hnd, net_addr, net_port, PAnsiChar(AnsiString(csn)), slot);
end;
Function LTR25_IsOpened(var hnd: TLTR25) : Integer;
begin
LTR25_IsOpened:=_is_opened(hnd);
end;
Function LTR25_SetADC(var hnd: TLTR25) : Integer;
begin
LTR25_SetADC:=_set_adc(hnd);
end;
Function LTR25_Start(var hnd: TLTR25) : Integer;
begin
LTR25_Start := _start(hnd);
end;
Function LTR25_Stop(var hnd: TLTR25) : Integer;
begin
LTR25_Stop:=_stop(hnd);
end;
Function LTR25_GetErrorString(err: Integer) : string;
begin
LTR25_GetErrorString:=string(_get_err_str(err));
end;
Function LTR25_Recv(var hnd: TLTR25; out data : array of LongWord; out tmark : array of LongWord; size: LongWord; tout : LongWord): Integer;
begin
LTR25_Recv:=_recv(hnd, data, tmark, size, tout);
end;
Function LTR25_Recv(var hnd: TLTR25; out data : array of LongWord; size: LongWord; tout : LongWord): Integer;
begin
LTR25_Recv:=_recv(hnd, data, PLongWord(nil)^, size, tout);
end;
Function LTR25_ProcessData(var hnd: TLTR25; var src : array of LongWord; out dest : array of Double; var size: Integer;
flags : LongWord; out ch_status : array of LongWord): Integer;
begin
LTR25_ProcessData:=_process_data(hnd, src, dest, size, flags, ch_status);
end;
Function LTR25_ProcessData(var hnd: TLTR25; var src : array of LongWord; out dest : array of Double; var size: Integer; flags : LongWord): Integer;
begin
LTR25_ProcessData:=_process_data(hnd, src, dest, size, flags, PLongWord(nil)^);
end;
Function LTR25_SearchFirstFrame(var hnd : TLTR25; var data : array of LongWord;
size : LongWord; out index : LongWord) : Integer;
begin
LTR25_SearchFirstFrame:=_search_first_frame(hnd, data, size, index);
end;
Function LTR25_GetConfig(var hnd : TLTR25) : Integer;
begin
LTR25_GetConfig:=_get_config(hnd);
end;
Function LTR25_SetLowPowMode(var hnd: TLTR25; lowPowMode : LongBool) : Integer;
begin
LTR25_SetLowPowMode:=_set_low_pow_mode(hnd, lowPowMode);
end;
Function LTR25_FPGAIsEnabled(var hnd: TLTR25; out enabled : LongBool) : Integer;
begin
LTR25_FPGAIsEnabled:=_fpga_is_enabled(hnd, enabled);
end;
Function LTR25_FPGAEnable(var hnd: TLTR25; enable : LongBool) : Integer;
begin
LTR25_FPGAEnable:=_fpga_enable(hnd, enable);
end;
Function LTR25_FlashRead(var hnd: TLTR25; addr : LongWord; out data : array of byte; size : LongWord) : Integer;
begin
LTR25_FlashRead:=_flash_read(hnd, addr, data, size);
end;
Function LTR25_FlashWrite(var hnd: TLTR25; addr : LongWord; var data : array of Byte; size : LongWord) : Integer;
begin
LTR25_FlashWrite:=_flash_write(hnd, addr, data, size);
end;
Function LTR25_FlashErase(var hnd: TLTR25; addr : LongWord; size : LongWord) : Integer;
begin
LTR25_FlashErase:=_flash_erase(hnd, addr, size);
end;
end.
|
unit int_not_u16;
interface
implementation
var I: UInt16;
procedure Test;
begin
I := 65534;
I := not I;
end;
initialization
Test();
finalization
Assert(I = 1);
end. |
unit uObjectDXFEntity;
interface
uses Classes, SysUtils, Contnrs, uMyTypes;
type
TDXFEntity = class(TObject)
private
objVlastnosti: TStringList;
objSubEntities: TObjectList;
function objGetPair(index: integer): TDXFPair;
function objGetSubEntity(Index: Integer): TDXFEntity;
procedure objSetSubEntity(Index: Integer; EntityObj: TDXFEntity);
public
property Pairs[Index: integer]: TDXFPair read objGetPair; // musi byt public, lebo je typu ARRAY
property SubEntities[Index: Integer]: TDXFEntity read objGetSubEntity write objSetSubEntity;
procedure SetValue(code: integer; value: string); Overload; // viac overload verzii sa da len v publicu
procedure SetValue(code,value: string); Overload;
published
constructor Create;
destructor Destroy;
function SubEntityAddVertex(v: TMyPoint; layer: string): integer;
function GetValueS(code: integer): string;
function GetValueF(code: integer): double;
function GetValueI(code: integer): integer;
function PairsCount: integer;
function SubEntitiesCount: integer;
function GetAllValues: string;
end;
implementation
constructor TDXFEntity.Create;
begin
inherited Create;
objVlastnosti := TStringList.Create;
objSubEntities := TObjectList.Create;
end;
destructor TDXFEntity.Destroy;
begin
FreeAndNil(objVlastnosti);
FreeAndNil(objSubEntities);
inherited Destroy;
end;
// 2 verzie metody SETVALUE :
procedure TDXFEntity.SetValue(code: integer; value: string);
begin
objVlastnosti.Values[ Format('%3d', [code]) ] := value; // format identifikatora je 3-miestny retazec (napr. ' 8')
end;
procedure TDXFEntity.SetValue(code,value: string);
begin
objVlastnosti.Values[ code ] := value; // format identifikatora je 3-miestny retazec (napr. ' 8')
end;
function TDXFEntity.SubEntitiesCount: integer;
begin
result := objSubEntities.Count;
end;
function TDXFEntity.SubEntityAddVertex(v: TMyPoint; layer: string): integer;
var
i: integer;
begin
// vytvori entitu typu LINE v DXF drawingu a vrati jej novo-prideleny index
i := objSubEntities.Add(TDXFEntity.Create);
SubEntities[i].SetValue(0, 'VERTEX');
SubEntities[i].SetValue(8, layer);
SubEntities[i].SetValue(10, FloatToStr(v.X));
SubEntities[i].SetValue(20, FloatToStr(v.Y));
result := i;
end;
function TDXFEntity.PairsCount: integer;
begin
result := objVlastnosti.Count;
end;
function TDXFEntity.GetValueS(code: integer): string;
begin
result := objVlastnosti.Values[ Format('%3d',[code]) ]; // format identifikatora je 3-miestny retazec (napr. ' 8')
end;
function TDXFEntity.GetValueF(code: integer): double;
begin
result := StrToFloat( objVlastnosti.Values[ Format('%3d',[code]) ] );
end;
function TDXFEntity.GetValueI(code: integer): integer;
begin
result := StrToInt( objVlastnosti.Values[ Format('%3d',[code]) ] );
end;
function TDXFEntity.objGetPair(index: integer): TDXFPair;
begin
result.code := StrToInt(objVlastnosti.Names[index]);
result.val := objVlastnosti.Values[objVlastnosti.Names[index]];
end;
function TDXFEntity.objGetSubEntity(Index: Integer): TDXFEntity;
begin
result := (objSubEntities.Items[Index] as TDXFEntity);
end;
procedure TDXFEntity.objSetSubEntity(Index: Integer; EntityObj: TDXFEntity);
begin
//
end;
function TDXFEntity.GetAllValues: string;
var
i: integer;
begin
// f-cia uzitocna len pre debug
result := '';
for i := 0 to objVlastnosti.Count - 1 do
result := result + '['+IntToStr(i)+']'+ objVlastnosti.Names[i] + '=' + objVlastnosti.Values[objVlastnosti.Names[i]] + ',';
end;
end.
|
{**********************************************}
{ TeeChart Components - Custom Actions }
{ Copyright (c) 2000-2004 by David Berneda }
{ All Rights Reserved }
{**********************************************}
unit TeeChartActions;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QActnList,
{$ELSE}
ActnList,
{$ENDIF}
Chart, TeEngine;
type
TCustomChartAction=class(TCustomAction)
private
FChart : TCustomChart;
procedure SetChart(Value:TCustomChart);
protected
procedure Notification(AComponent:TComponent; Operation:TOperation); override;
public
function HandlesTarget(Target:TObject):Boolean; override;
published
property Chart:TCustomChart read FChart write SetChart;
end;
TChartAction=class(TCustomChartAction)
published
property Caption;
property Checked;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property Visible;
property OnExecute;
property OnHint;
property OnUpdate;
end;
TChartAction3D=class(TChartAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TChartActionEdit=class(TChartAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
end;
TChartActionCopy=class(TChartAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
end;
TChartActionSave=class(TChartAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
end;
TChartActionPrint=class(TChartAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
end;
TChartActionAxes=class(TChartAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TChartActionGrid=class(TChartAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TChartActionLegend=class(TChartAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TCustomSeriesAction=class(TCustomAction)
private
FSeries : TChartSeries;
procedure SetSeries(Value:TChartSeries);
protected
procedure Notification(AComponent:TComponent; Operation:TOperation); override;
public
function HandlesTarget(Target:TObject):Boolean; override;
published
property Series:TChartSeries read FSeries write SetSeries;
end;
TSeriesAction=class(TCustomSeriesAction)
published
property Caption;
property Checked;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property Visible;
property OnExecute;
property OnHint;
property OnUpdate;
end;
TSeriesActionActive=class(TSeriesAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TSeriesActionEdit=class(TSeriesAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
end;
TSeriesActionMarks=class(TSeriesAction)
public
Constructor Create(AOwner: TComponent); override;
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
implementation
Uses TypInfo, EditChar, TeePrevi, TeeProCo, TeeEditPro, TeeEdiGene;
{ TCustomChartAction }
function TCustomChartAction.HandlesTarget(Target: TObject): Boolean;
begin
result:=((not Assigned(FChart)) and (Target is TCustomChart)) or
(Target=FChart);
end;
procedure TCustomChartAction.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and (AComponent=Chart) then Chart:=nil;
end;
procedure TCustomChartAction.SetChart(Value: TCustomChart);
begin
if FChart<>Value then
begin
{$IFDEF D5}
if Assigned(FChart) then FChart.RemoveFreeNotification(Self); // 5.03 Thanks Rune !
{$ENDIF}
FChart:=Value;
if Assigned(FChart) then FChart.FreeNotification(Self);
end;
end;
{ TChartAction3D }
Constructor TChartAction3D.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_Action3DHint;
Caption:=TeeMsg_Action3D;
end;
procedure TChartAction3D.ExecuteTarget(Target: TObject);
begin
With Target as TCustomChart do View3D:=not {$IFDEF CLX}Checked{$ELSE}View3D{$ENDIF}
end;
procedure TChartAction3D.UpdateTarget(Target: TObject);
begin
Checked:=(Target as TCustomChart).View3D
end;
{ TCustomSeriesAction }
function TCustomSeriesAction.HandlesTarget(Target: TObject): Boolean;
begin
result:=Assigned(Series) or (Target is TChartSeries);
end;
procedure TCustomSeriesAction.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and (AComponent=Series) then Series:=nil;
end;
procedure TCustomSeriesAction.SetSeries(Value: TChartSeries);
begin
if FSeries<>Value then
begin
FSeries:=Value;
if Assigned(FSeries) then FSeries.FreeNotification(Self);
end;
end;
{ TSeriesActionActive }
Constructor TSeriesActionActive.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionSeriesActiveHint;
Caption:=TeeMsg_ActionSeriesActive;
end;
procedure TSeriesActionActive.ExecuteTarget(Target: TObject);
begin
With Series do Active:=not Active
end;
procedure TSeriesActionActive.UpdateTarget(Target: TObject);
begin
Checked:=Series.Active
end;
{ TChartActionEdit }
Constructor TChartActionEdit.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionEditHint;
Caption:=TeeMsg_ActionEdit;
end;
procedure TChartActionEdit.ExecuteTarget(Target: TObject);
begin
EditChart(nil,Target as TCustomChart);
end;
{ TChartActionCopy }
constructor TChartActionCopy.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionCopyHint;
Caption:=TeeMsg_ActionCopy;
end;
procedure TChartActionCopy.ExecuteTarget(Target: TObject);
begin
(Target as TCustomChart).CopyToClipboardBitmap;
end;
{ TChartActionPrint }
constructor TChartActionPrint.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionPrintHint;
Caption:=TeeMsg_ActionPrint;
end;
procedure TChartActionPrint.ExecuteTarget(Target: TObject);
begin
ChartPreview(nil,Target as TCustomChart);
end;
{ TChartActionAxes }
constructor TChartActionAxes.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionAxesHint;
Caption:=TeeMsg_ActionAxes;
end;
procedure TChartActionAxes.ExecuteTarget(Target: TObject);
begin
With (Target as TCustomChart).Axes do Visible:=not Visible
end;
procedure TChartActionAxes.UpdateTarget(Target: TObject);
begin
Checked:=(Target as TCustomChart).Axes.Visible;
end;
{ TChartActionLegend }
constructor TChartActionLegend.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionLegendHint;
Caption:=TeeMsg_ActionLegend;
end;
procedure TChartActionLegend.ExecuteTarget(Target: TObject);
begin
With (Target as TCustomChart).Legend do Visible:=not Visible
end;
procedure TChartActionLegend.UpdateTarget(Target: TObject);
begin
Checked:=(Target as TCustomChart).Legend.Visible;
end;
{ TSeriesActionEdit }
constructor TSeriesActionEdit.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionSeriesEditHint;
Caption:=TeeMsg_ActionEdit;
end;
procedure TSeriesActionEdit.ExecuteTarget(Target: TObject);
begin
EditSeries(nil,Series);
end;
{ TSeriesActionMarks }
constructor TSeriesActionMarks.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionSeriesMarksHint;
Caption:=TeeMsg_ActionSeriesMarks;
end;
procedure TSeriesActionMarks.ExecuteTarget(Target: TObject);
begin
With Series.Marks do Visible:=not Visible
end;
procedure TSeriesActionMarks.UpdateTarget(Target: TObject);
begin
Checked:=Series.Marks.Visible;
end;
{ TChartActionSave }
constructor TChartActionSave.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionSaveHint;
Caption:=TeeMsg_ActionSave;
end;
procedure TChartActionSave.ExecuteTarget(Target: TObject);
begin
SaveChartDialog(Target as TCustomChart);
end;
{ TChartActionGrid }
constructor TChartActionGrid.Create(AOwner: TComponent);
begin
inherited;
Hint :=TeeMsg_ActionGridsHint;
Caption:=TeeMsg_ActionGrids;
end;
procedure TChartActionGrid.ExecuteTarget(Target: TObject);
var t : Integer;
begin
With (Target as TCustomChart) do
for t:=0 to Axes.Count-1 do
With Axes[t].Grid do Visible:=not Visible
end;
procedure TChartActionGrid.UpdateTarget(Target: TObject);
var t : Integer;
tmp : Boolean;
begin
tmp:=False;
With (Target as TCustomChart) do
for t:=0 to Axes.Count-1 do
if Axes[t].Grid.Visible then
begin
tmp:=True;
break;
end;
Checked:=tmp;
end;
end.
|
unit opcoursesqlite3;
{$mode objfpc}{$H+}
{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined}
interface
uses
Classes, SysUtils, SchoolEntities, dOpf, dsqldbbroker, sqlite3conn, eventlog
;
type
{ TopCoursesDB }
TopCoursesDB = class(TObject, IORMInterface)
public type
TopInvitations = specialize TdGSQLdbEntityOpf<TInvitation>;
TopSessions = specialize TdGSQLdbEntityOpf<TSession>;
TopSlides = specialize TdGSQLdbEntityOpf<TSlide>;
TopStudentSpots = specialize TdGSQLdbEntityOpf<TStudentSpot>;
TopLessons = specialize TdGSQLdbEntityOpf<TLesson>;
TopCourses = specialize TdGSQLdbEntityOpf<TCourse>;
TopUsers = specialize TdGSQLdbEntityOpf<TUser>;
private
FAutoApply: Boolean;
Fcon: TdSQLdbConnector;
FCourses: TopCourses.TEntities;
FDBDir: String;
FInvitations: TopInvitations.TEntities;
FLessons: TopLessons.TEntities;
FLogDebug: Boolean;
FLogger: TEventLog;
FopCourses: TopCourses;
FopInvitations: TopInvitations;
FopLessons: TopLessons;
FopSessions: TopSessions;
FopSlides: TopSlides;
FopStudentSpots: TopStudentSpots;
FopUsers: TopUsers;
FSessions: TopSessions.TEntities;
FSlides: TopSlides.TEntities;
FStudentSpots: TopStudentSpots.TEntities;
FUsers: TopUsers.TEntities;
function GetCourse: TCourse;
function GetCourseEntity(EntityType: TEntityType): TCourseElement;
function GetCourses: TopCourses.TEntities;
function GetInvitation: TInvitation;
function GetInvitations: TopInvitations.TEntities;
function GetLesson: TLesson;
function GetLessons: TopLessons.TEntities;
function GetopCourses: TopCourses;
function GetopInvitations: TopInvitations;
function GetopLessons: TopLessons;
function GetopSessions: TopSessions;
function GetopSlides: TopSlides;
function GetopStudentSpots: TopStudentSpots;
function GetopUsers: TopUsers;
function GetSchoolEntity(EntityType: TEntityType): TSchoolElement;
function GetSession: TSession;
function GetSessions: TopSessions.TEntities;
function GetSlide: TSlide;
function GetSlides: TopSlides.TEntities;
function GetStudentSpot: TStudentSpot;
function GetStudentSpots: TopStudentSpots.TEntities;
function GetUser: TUser;
function GetUsers: TopUsers.TEntities;
procedure Log(aEventType: TEventType; const aMessage: String);
function NewSession(aUserID: Int64; aEntityType: TEntityType; aEntityID: Integer;
aTeacher: Int64): Integer;
protected
property opCourses: TopCourses read GetopCourses;
property opInvitations: TopInvitations read GetopInvitations;
property opLessons: TopLessons read GetopLessons;
property opUsers: TopUsers read GetopUsers;
property opSlides: TopSlides read GetopSlides;
property opSessions: TopSessions read GetopSessions;
property opStudentSpots: TopStudentSpots read GetopStudentSpots;
public
procedure Apply;
constructor Create;
function Con: TdSQLdbConnector;
destructor Destroy; override;
procedure DeleteCourseEntity(aEntityType: TEntityType);
procedure ExitDialog(aUserID: Int64);
function FindEntitiesByParentID(aEntityType: TEntityType; aParentID: Int64;
IsCourseOwner: Boolean): Integer;
function FindLessonByID(aLessonID: Integer): Boolean;
function GetCourse(aCourse: TCourse): Boolean;
function GetCourseByID(aCourseID: Integer): TCourse;
function GetCoursesList(aUserID: Int64 = 0): TopCourses.TEntities;
function GetEntityByID(aEntityType: TEntityType; aID: Int64): TSchoolElement;
// function GetSlideOrdIndex(aSlideID: Integer): Integer;
function GetInvitationByID(aInvitationID: Integer): TInvitation;
function GetInvitationsList(aCourseID: Integer): TopInvitations.TEntities;
function GetLesson(aLesson: TLesson): Boolean;
function GetLessonByID(aID: Integer): TLesson;
function GetLessonIndexByID(aID: Integer): Integer;
function GetLessonsList(aCourseID: Integer): TopLessons.TEntities;
function GetSessionByID(aID: Integer): TSession;
function GetSlideByID(aID: Int64): TSlide;
function GetSlideIndexByID(aID: Int64): Integer;
function GetSlidesList(aLessonID: Integer): TopSlides.TEntities;
function GetSpotByID(aSpotID: Integer): TStudentSpot;
function GetSpotByUserNCourse(aUserID: Int64; aCourseID: Integer): TStudentSpot;
function GetSpotListByCourse(aCourseID: Integer; aUserStatus: TUserStatus): TopStudentSpots.TEntities;
function GetSpotListByUser(aStudentID: Int64; aUserStatus: TUserStatus): TopStudentSpots.TEntities;
function GetSpotList(aID: Int64; IsCourseOwner: Boolean; aUserStatus: TUserStatus): TopStudentSpots.TEntities;
function GetUser(aUser: TUser): Boolean;
function GetUsersList(): TopUsers.TEntities;
function GetUserByID(aUserID: Int64): TUser;
function NewCourse(aCourse: TCourse = nil): Integer;
function NewInvitation(aCourseID: Integer; aCapacity: Integer=0; aUserStatus: TUserStatus = usStudent): Integer;
function NewLesson(aLesson: TLesson = nil): Integer;
function NewSlide(aSlide: TSlide = nil): Integer;
function NewSchoolEntity(aEntityType: TEntityType; aSchoolEntity: TSchoolElement = nil): Integer;
procedure NewSessionStudent(aUserID: Int64; aEntityType: TEntityType; aEntityID: Integer;
aTearcher: Int64);
function NewStudentSpot(aUserID: Int64; aCourseID: Integer; aUserStatus: TUserStatus = usStudent; aTearcher: Int64 = 0): Integer;
function opLastInsertID: Integer;
function SpotNextSlide(aSpot: TStudentSpot; out IsLastLesson: Boolean): Integer;
function ReplaceEntity(aEntityType: TEntityType; aID1, aID2: Int64): Boolean;
procedure SaveInvitation;
procedure SaveUser;
procedure SaveCourseEntity(aEntityType: TEntityType);
function SessionOpened(aUserID: Int64; aSession: Integer): Boolean;
function SessionExists(aUser: Int64): Boolean;
function SpotInCourse(aUserID: Int64; aCourseID: Integer): Boolean;
procedure StudentsToSCVDocument(aCSVStream: TStream);
property DBDir: String read FDBDir write FDBDir;
property Course: TCourse read GetCourse;
property CourseEntity[EntityType: TEntityType]: TCourseElement read GetCourseEntity;
property Courses: TopCourses.TEntities read GetCourses;
property Invitation: TInvitation read GetInvitation;
property Invitations: TopInvitations.TEntities read GetInvitations;
property Lesson: TLesson read GetLesson;
property Lessons: TopLessons.TEntities read GetLessons;
property LogDebug: Boolean read FLogDebug write FLogDebug;
property Logger: TEventLog read FLogger write FLogger;
property User: TUser read GetUser;
property Users: TopUsers.TEntities read GetUsers;
property Session: TSession read GetSession;
property Sessions: TopSessions.TEntities read GetSessions;
property Slide: TSlide read GetSlide;
property Slides: TopSlides.TEntities read GetSlides;
property StudentSpot: TStudentSpot read GetStudentSpot;
property StudentSpots: TopStudentSpots.TEntities read GetStudentSpots;
property SchoolEntity[EntityType: TEntityType]: TSchoolElement read GetSchoolEntity;
property AutoApply: Boolean read FAutoApply write FAutoApply;
end;
implementation
uses
csvdocument
;
//var
// _con: TdSQLdbConnector = nil;
// _query: TdSQLdbQuery = nil;
{ TopCoursesDB }
procedure TopCoursesDB.Apply;
begin
if Assigned(FopCourses) then
FopCourses.Apply;
if Assigned(FopUsers) then
FopUsers.Apply;
end;
function TopCoursesDB.GetopCourses: TopCourses;
begin
if not Assigned(FopCourses) then
begin
FopCourses:=TopCourses.Create(Con, 'courses');
FopCourses.Table.PrimaryKeys.Text:='id';
end;
Result:=FopCourses;
end;
function TopCoursesDB.GetopInvitations: TopInvitations;
begin
if not Assigned(FopInvitations) then
begin
FopInvitations:=TopInvitations.Create(Con, 'invitations');
FopInvitations.Table.PrimaryKeys.Text:='id';
end;
Result:=FopInvitations;
end;
function TopCoursesDB.GetCourses: TopCourses.TEntities;
begin
if not Assigned(FCourses) then
FCourses:=TopCourses.TEntities.Create;
Result:=FCourses;
end;
function TopCoursesDB.GetInvitation: TInvitation;
begin
Result:=opInvitations.Entity;
end;
function TopCoursesDB.GetInvitations: TopInvitations.TEntities;
begin
if not Assigned(FInvitations) then
FInvitations:=TopInvitations.TEntities.Create;
Result:=FInvitations;
end;
function TopCoursesDB.GetLesson: TLesson;
begin
Result:=opLessons.Entity;
end;
function TopCoursesDB.GetLessons: TopLessons.TEntities;
begin
if not Assigned(FLessons) then
FLessons:=TopLessons.TEntities.Create;
Result:=FLessons;
end;
function TopCoursesDB.GetUser(aUser: TUser): Boolean;
begin
Result:=opUsers.Get(aUser);
if not Result then
aUser.Initiate;
end;
function TopCoursesDB.GetCourse: TCourse;
begin
Result:=opCourses.Entity;
end;
function TopCoursesDB.GetCourseEntity(EntityType: TEntityType): TCourseElement;
begin
case EntityType of
seCourse: Result:=Course;
seLesson: Result:=Lesson;
seSlide: Result:=Slide;
else
Result:=nil;
end;
end;
function TopCoursesDB.GetopLessons: TopLessons;
begin
if not Assigned(FopLessons) then
begin
FopLessons:=TopLessons.Create(Con, 'lessons');
FopLessons.Table.PrimaryKeys.Text:='id';
end;
Result:=FopLessons;
end;
function TopCoursesDB.GetopSessions: TopSessions;
begin
if not Assigned(FopSessions) then
begin
FopSessions:=TopSessions.Create(Con, 'sessions');
FopSessions.Table.PrimaryKeys.Text:='id';
end;
Result:=FopSessions;
end;
function TopCoursesDB.GetopSlides: TopSlides;
begin
if not Assigned(FopSlides) then
begin
FopSlides:=TopSlides.Create(Con, 'slides');
FopSlides.Table.PrimaryKeys.Text:='id';
end;
Result:=FopSlides;
end;
function TopCoursesDB.GetopStudentSpots: TopStudentSpots;
begin
if not Assigned(FopStudentSpots) then
begin
FopStudentSpots:=TopStudentSpots.Create(Con, 'studentspots');
FopStudentSpots.Table.PrimaryKeys.Text:='id';
TStudentSpot(FopStudentSpots.Entity).ORM:=Self;
end;
Result:=FopStudentSpots;
end;
function TopCoursesDB.GetopUsers: TopUsers;
begin
if not Assigned(FopUsers) then
begin
FopUsers:=TopUsers.Create(Con, 'users');
FopUsers.Table.PrimaryKeys.Text:='id';
end;
Result:=FopUsers;
end;
function TopCoursesDB.GetSchoolEntity(EntityType: TEntityType
): TSchoolElement;
begin
case EntityType of
seUser: Result:=User;
seCourse: Result:=Course;
seLesson: Result:=Lesson;
seSlide: Result:=Slide;
seInvitation: Result:=Invitation;
seSession: Result:=Session;
else
Result:=nil;
end;
end;
function TopCoursesDB.GetSession: TSession;
begin
Result:=opSessions.Entity;
end;
function TopCoursesDB.GetSessions: TopSessions.TEntities;
begin
if not Assigned(FSessions) then
FSessions:=TopSessions.TEntities.Create;
Result:=FSessions;
end;
function TopCoursesDB.GetSlide: TSlide;
begin
Result:=opSlides.Entity;
end;
function TopCoursesDB.GetSlides: TopSlides.TEntities;
begin
if not Assigned(FSlides) then
FSlides:=TopSlides.TEntities.Create;
Result:=FSlides;
end;
function TopCoursesDB.GetStudentSpot: TStudentSpot;
begin
Result:=opStudentSpots.Entity;
end;
function TopCoursesDB.GetStudentSpots: TopStudentSpots.TEntities;
begin
if not Assigned(FStudentSpots) then
FStudentSpots:=TopStudentSpots.TEntities.Create;
Result:=FStudentSpots;
end;
function TopCoursesDB.GetUser: TUser;
begin
Result:=opUsers.Entity;
end;
function TopCoursesDB.GetUsers: TopUsers.TEntities;
begin
if not Assigned(FUsers) then
FUsers:=TopUsers.TEntities.Create;
Result:=FUsers;
end;
procedure TopCoursesDB.Log(aEventType: TEventType; const aMessage: String);
begin
if Assigned(FLogger) then
if FLogDebug and (aEventType=etDebug) then
FLogger.Debug(aMessage)
else
FLogger.Log(aEventType, aMessage);
end;
constructor TopCoursesDB.Create;
begin
FAutoApply:=True;
FLogDebug:=False;
end;
function TopCoursesDB.Con: TdSQLdbConnector;
var
aDir: String;
begin
if not Assigned(Fcon) then
begin
Fcon := TdSQLdbConnector.Create(nil);
if FDBDir<>EmptyStr then
aDir:=FDBDir
else
aDir:='./';
Fcon.Database :=aDir+'courses.sqlite3';
Fcon.Driver := 'sqlite3';
Fcon.Logger.Active := FLogDebug;
Fcon.Logger.FileName := aDir+'db_sqlite3.log';
end;
Result := FCon;
end;
destructor TopCoursesDB.Destroy;
begin
FUsers.Free;
FopUsers.Free;
FCourses.Free;
FopCourses.Free;
FInvitations.Free;
FopInvitations.Free;
FLessons.Free;
FopLessons.Free;
FSessions.Free;
FopSessions.Free;
FSlides.Free;
FopSlides.Free;
FStudentSpots.Free;
FopStudentSpots.Free;
FCon.Free;
inherited Destroy;
end;
procedure TopCoursesDB.DeleteCourseEntity(aEntityType: TEntityType);
begin
case aEntityType of
seUser: opUsers.Remove;
seCourse: opCourses.Remove;
seLesson: opLessons.Remove;
seSlide: opSlides.Remove;
seInvitation: opInvitations.Remove;
seSession: opSessions.Remove;
seStudentSpot..seTeacher: opStudentSpots.Remove;
else
Logger.Error('Unknown entity type while DeleteCourseEntity');
end;
if FAutoApply then
case aEntityType of
seUser: opUsers.Apply;
seCourse: opCourses.Apply;
seLesson: opLessons.Apply;
seSlide: opSlides.Apply;
seInvitation: opInvitations.Apply;
seSession: opSessions.Apply;
seStudentSpot..seTeacher: opStudentSpots.Apply;
else
Logger.Error('Unknown entity type while DeleteCourseEntity');
end;
end;
procedure TopCoursesDB.ExitDialog(aUserID: Int64);
begin
GetUserByID(aUserID).Session:=0;
SaveUser;
end;
function TopCoursesDB.FindEntitiesByParentID(aEntityType: TEntityType;
aParentID: Int64; IsCourseOwner: Boolean): Integer;
begin
case aEntityType of
seUser: Result:=GetUsersList().Count;
seCourse: Result:=GetCoursesList(aParentID).Count;
seLesson: Result:=GetLessonsList(aParentID).Count;
seSlide: Result:=GetSlidesList(aParentID).Count;
seInvitation: Result:=GetInvitationsList(aParentID).Count;
seStudentSpot: Result:=GetSpotList(aParentID, IsCourseOwner, usStudent).Count;
seStudent: Result:=GetSpotList(aParentID, IsCourseOwner, usStudent).Count;
seTeacher: Result:=GetSpotList(aParentID, IsCourseOwner, usTeacher).Count;
seSession: Result:=0; // No parent entity
else
Result:=0;
Log(etError, 'FindEntitiesByParentID : unexpected entity type ('+EntityTypeToString(aEntityType)+')!');
end;
end;
function TopCoursesDB.FindLessonByID(aLessonID: Integer): Boolean;
begin
Lesson.id:=aLessonID;
Result:=opLessons.Get;
if not Result then
Lesson.Initiate;
end;
function TopCoursesDB.GetCourse(aCourse: TCourse): Boolean;
begin
Result:=opCourses.Get(aCourse);
if not Result then
aCourse.Initiate;
end;
function TopCoursesDB.NewCourse(aCourse: TCourse): Integer;
begin
if not Assigned(aCourse) then
aCourse:=Course;
opCourses.Add(aCourse);
aCourse.id:=opLastInsertID;
Result:=aCourse.id;
if FAutoApply then
FopCourses.Apply;
end;
function TopCoursesDB.NewInvitation(aCourseID: Integer; aCapacity: Integer;
aUserStatus: TUserStatus): Integer;
begin
Invitation.Capacity:=aCapacity;
Invitation.Course:=aCourseID;
Invitation.UserStatus:=aUserStatus;
opInvitations.Add(Invitation);
Invitation.id:=opLastInsertID;
Result:=Invitation.id;
if FAutoApply then
opInvitations.Apply;
end;
function TopCoursesDB.NewLesson(aLesson: TLesson): Integer;
begin
if not Assigned(aLesson) then
aLesson:=Lesson;
opLessons.Add(aLesson);
aLesson.id:=opLastInsertID;
Result:=aLesson.id;
if FAutoApply then
FopLessons.Apply;
end;
function TopCoursesDB.NewSlide(aSlide: TSlide): Integer;
begin
if not Assigned(aSlide) then
aSlide:=Slide;
opSlides.Add(aSlide);
aSlide.id:=opLastInsertID;
Result:=aSlide.id;
if FAutoApply then
FopSlides.Apply;
end;
function TopCoursesDB.NewSchoolEntity(aEntityType: TEntityType;
aSchoolEntity: TSchoolElement): Integer;
begin
case aEntityType of
seCourse: Result:=NewCourse(aSchoolEntity as TCourse);
seLesson: Result:=NewLesson(aSchoolEntity as TLesson);
seSlide: Result:=NewSlide(aSchoolEntity as TSlide);
else
Log(etError, 'Unknown school entity type! Procedure NewSchoolEntity...');
Result:=0;
end;
end;
procedure TopCoursesDB.NewSessionStudent(aUserID: Int64;
aEntityType: TEntityType; aEntityID: Integer; aTearcher: Int64);
begin
GetUserByID(aUserID).Session:=NewSession(aUserID, aEntityType, aEntityID, aTearcher);
SaveUser;
end;
function TopCoursesDB.NewSession(aUserID: Int64; aEntityType: TEntityType;
aEntityID: Integer; aTeacher: Int64): Integer;
begin
Session.Student:=aUserID;
Session.SourceEntity:=EntityTypeToString(aEntityType);
Session.EntityID:=aEntityID;
Session.Teacher:=aTeacher;
opSessions.Add(Session);
Session.id:=opLastInsertID;
Result:=Session.ID;
if FAutoApply then
opSessions.Apply;
end;
function TopCoursesDB.NewStudentSpot(aUserID: Int64; aCourseID: Integer;
aUserStatus: TUserStatus; aTearcher: Int64): Integer;
begin
StudentSpot.User:=aUserID;
StudentSpot.Course:=aCourseID;
StudentSpot.UserStatus:=aUserStatus;
StudentSpot.Teacher:=aTearcher;
opStudentSpots.Add(StudentSpot);
StudentSpot.id:=opLastInsertID;
Result:=StudentSpot.ID;
if FAutoApply then
opStudentSpots.Apply;
end;
function TopCoursesDB.opLastInsertID: Integer;
var
aQuery: TdSQLdbQuery;
begin
aQuery:=TdSQLdbQuery.Create(Con);
try
aQuery.SQL.Text:='SELECT last_insert_rowid();';
aQuery.Open;
Result:=aQuery.Fields.Fields[0].AsInteger;
finally
aQuery.Close;
aQuery.Free;
end;
end;
function TopCoursesDB.SpotNextSlide(aSpot: TStudentSpot; out IsLastLesson: Boolean): Integer;
var
i: Integer;
begin
Result:=aSpot.Lesson;
GetLessonsList(aSpot.Course);
i:=GetLessonIndexByID(Result);
if i<Lessons.Count-1 then
begin
IsLastLesson:=False;
Result:=Lessons.Items[i+1].id;
end
else begin
IsLastLesson:=True;
Inc(Result);
end;
aSpot.Lesson:=Result;
end;
function TopCoursesDB.ReplaceEntity(aEntityType: TEntityType; aID1, aID2: Int64
): Boolean;
var
aEntity: TSchoolElement;
begin
aEntity:=SchoolClasses[aEntityType].Create;
try
aEntity.Assign(GetEntityByID(aEntityType, aID1));
GetEntityByID(aEntityType, aID2);
SchoolEntity[aEntityType].ID64:=aID1;
SaveCourseEntity(aEntityType);
SchoolEntity[aEntityType].Assign(aEntity);
SchoolEntity[aEntityType].ID64:=aID2;
SaveCourseEntity(aEntityType);
finally
aEntity.Free;
end;
end;
procedure TopCoursesDB.SaveInvitation;
begin
opInvitations.Modify(Invitation);
if FAutoApply then
opInvitations.Apply;
end;
function TopCoursesDB.GetCourseByID(aCourseID: Integer): TCourse;
begin
if Course.id<>aCourseID then
begin
Course.id:=aCourseID;
if not opCourses.Get then
Course.Initiate;
end;
Result:=Course;
end;
function TopCoursesDB.GetCoursesList(aUserID: Int64): TopCourses.TEntities;
var
aCourse: TCourse;
begin
if aUserID=0 then
aUserID:=User.id;
aCourse:=TCourse.Create;
try
aCourse.Owner:=aUserID;
Courses.Clear;
opCourses.Find(aCourse, Courses, 'owner=:owner');
finally
aCourse.Free;
end;
Result:=FCourses;
end;
function TopCoursesDB.GetEntityByID(aEntityType: TEntityType; aID: Int64
): TSchoolElement;
begin
case aEntityType of
seUser: Result:=GetUserByID(aID);
seCourse: Result:=GetCourseByID(aID);
seLesson: Result:=GetLessonByID(aID);
seSlide: Result:=GetSlideByID(aID);
seInvitation: Result:=GetInvitationByID(aID);
seStudentSpot..seTeacher: Result:=GetSpotByID(aID);
seSession: Result:=GetSessionByID(aID);
else
Result:=nil;
end;
end;
function TopCoursesDB.GetInvitationByID(aInvitationID: Integer): TInvitation;
begin
if Invitation.ID<>aInvitationID then
begin
Invitation.id:=aInvitationID;
if not opInvitations.Get(Invitation) then
Invitation.Initiate;
end;
Result:=Invitation;
end;
function TopCoursesDB.GetInvitationsList(aCourseID: Integer): TopInvitations.TEntities;
var
aInvitation: TInvitation;
begin
aInvitation:=TInvitation.Create;
try
aInvitation.Course:=aCourseID;
Invitations.Clear;
opInvitations.Find(aInvitation, FInvitations, 'course=:course AND applied<capacity');
finally
aInvitation.Free;
end;
Result:=Invitations;
end;
function TopCoursesDB.GetLesson(aLesson: TLesson): Boolean;
begin
Result:=opLessons.Get(aLesson);
if not Result then
aLesson.Initiate;
end;
function TopCoursesDB.GetSpotList(aID: Int64; IsCourseOwner: Boolean;
aUserStatus: TUserStatus): TopStudentSpots.TEntities;
begin
if IsCourseOwner then
Result:=GetSpotListByCourse(aID, aUserStatus)
else
Result:=GetSpotListByUser(aID, aUserStatus);
end;
function TopCoursesDB.GetSpotListByUser(aStudentID: Int64;
aUserStatus: TUserStatus): TopStudentSpots.TEntities;
var
aStudentSpot: TStudentSpot;
begin
aStudentSpot:=TStudentSpot.Create;
try
aStudentSpot.User:=aStudentID;
aStudentSpot.UserStatus:=aUserStatus;
StudentSpots.Clear;
opStudentSpots.Find(aStudentSpot, FStudentSpots, 'user=:user AND status=:status');
finally
aStudentSpot.Free;
end;
Result:=StudentSpots;
end;
function TopCoursesDB.GetLessonByID(aID: Integer): TLesson;
begin
if Lesson.id<>aID then
begin
Lesson.id:=aID;
if not opLessons.Get then
Lesson.Initiate;
end;
Result:=Lesson;
end;
function TopCoursesDB.GetLessonIndexByID(aID: Integer): Integer;
var
i: Integer;
begin
Result:=-1;
for i:=Lessons.Count-1 downto 0 do
if FLessons.Items[i].id=aID then
Exit(i);
end;
function TopCoursesDB.GetLessonsList(aCourseID: Integer): TopLessons.TEntities;
var
aLesson: TLesson;
begin
aLesson:=TLesson.Create;
try
aLesson.Course:=aCourseID;
Lessons.Clear;
opLessons.Find(aLesson, FLessons, 'course=:course');
finally
aLesson.Free;
end;
Result:=Lessons;
end;
function TopCoursesDB.GetSessionByID(aID: Integer): TSession;
begin
if Session.ID<>aID then
begin
Session.id:=aID;
if not opSessions.Get then
Session.Initiate;
end;
Result:=Session;
end;
function TopCoursesDB.GetSlideByID(aID: Int64): TSlide;
begin
if Slide.id<>aID then
begin
Slide.id:=aID;
if not opSlides.Get(Slide) then
Slide.Initiate;
end;
Result:=Slide;
end;
function TopCoursesDB.GetSlideIndexByID(aID: Int64): Integer;
var
i: Integer;
begin
Result:=-1;
for i:=Slides.Count-1 downto 0 do
if FSlides.Items[i].id=aID then
Exit(i);
end;
function TopCoursesDB.GetSlidesList(aLessonID: Integer): TopSlides.TEntities;
var
aSlide: TSlide;
begin
aSlide:=TSlide.Create;
try
aSlide.Lesson:=aLessonID;
Slides.Clear;
opSlides.Find(aSlide, FSlides, 'lesson=:lesson');
finally
aSlide.Free;
end;
Result:=Slides;
end;
function TopCoursesDB.GetSpotByID(aSpotID: Integer): TStudentSpot;
begin
if StudentSpot.id<>aSpotID then
begin
StudentSpot.id:=aSpotID;
if not opStudentSpots.Get(StudentSpot) then
StudentSpot.Initiate;
end;
Result:=StudentSpot;
end;
function TopCoursesDB.GetSpotByUserNCourse(aUserID: Int64; aCourseID: Integer
): TStudentSpot;
begin
if (StudentSpot.User<>aUserID) or (StudentSpot.Course<>aCourseID) then
begin
StudentSpot.User:=aUserID;
StudentSpot.Course:=aCourseID;
if not opStudentSpots.Find(StudentSpot, 'user=:user AND course=:course') then
StudentSpot.Initiate;
end;
Result:=StudentSpot;
end;
function TopCoursesDB.GetSpotListByCourse(aCourseID: Integer; aUserStatus: TUserStatus
): TopStudentSpots.TEntities;
var
aStudentSpot: TStudentSpot;
begin
aStudentSpot:=TStudentSpot.Create;
try
aStudentSpot.Course:=aCourseID;
aStudentSpot.UserStatus:=aUserStatus;
StudentSpots.Clear;
opStudentSpots.Find(aStudentSpot, FStudentSpots, 'course=:course AND status=:status');
finally
aStudentSpot.Free;
end;
Result:=StudentSpots;
end;
function TopCoursesDB.GetUsersList(): TopUsers.TEntities;
var
aUser: TUser;
begin
aUser:=TUser.Create;
try
Users.Clear;
opUsers.List(FUsers);
finally
aUser.Free;
end;
Result:=Users;
end;
function TopCoursesDB.GetUserByID(aUserID: Int64): TUser;
begin
if User.id<>AUserID then
begin
User.id:=AUserID;
if not opUsers.Get then
User.Initiate;
end;
Result:=User;
end;
procedure TopCoursesDB.SaveUser;
var
aUser: TUser;
begin
aUser:=TUser.Create;
try
aUser.id:=User.id;
if opUsers.Get(aUser) then
FopUsers.Modify(User)
else
FopUsers.Add(User, False);
finally
aUser.Free;
end;
if FAutoApply then
opUsers.Apply;
end;
procedure TopCoursesDB.SaveCourseEntity(aEntityType: TEntityType);
begin
case aEntityType of
seUser: opUsers.Modify(User, False);
seCourse: opCourses.Modify(Course);
seLesson: opLessons.Modify(Lesson);
seSlide: opSlides.Modify(Slide);
seInvitation: opInvitations.Modify(Invitation);
seStudentSpot..seTeacher: opStudentSpots.Modify(StudentSpot);
else
Logger.Error('Unknown entity type while SaveCourseEntity');
end;
if FAutoApply then
case aEntityType of
seUser: opUsers.Apply;
seCourse: opCourses.Apply;
seLesson: opLessons.Apply;
seSlide: opSlides.Apply;
seInvitation: opInvitations.Apply;
seStudentSpot..seTeacher: opStudentSpots.Apply;
else
Logger.Error('Unknown entity type while SaveCourseEntity');
end;
end;
function TopCoursesDB.SessionOpened(aUserID: Int64; aSession: Integer): Boolean;
var
aUser: TUser;
begin
aUser:=TUser.Create;
aUser.id:=aUserID;
try
if opUsers.Get(aUser) then
Result:=aUser.Session=aSession
else
Result:=False;
finally
aUser.Free;
end;
end;
function TopCoursesDB.SessionExists(aUser: Int64): Boolean;
var
aSessionID: Integer;
begin
aSessionID:=GetUserByID(aUser).Session;
Result:=aSessionID<>0;
if Result then
GetSessionByID(aSessionID);
end;
function TopCoursesDB.SpotInCourse(aUserID: Int64; aCourseID: Integer): Boolean;
begin
StudentSpot.User:=aUserID;
StudentSpot.Course:=aCourseID;
Result:=opStudentSpots.Find(StudentSpot, 'user=:user AND course=:course');
end;
procedure TopCoursesDB.StudentsToSCVDocument(aCSVStream: TStream);
var
aCSV: TCSVDocument;
iSpot: TStudentSpot;
begin
aCSV:=TCSVDocument.Create;
aCSV.Delimiter:=';';
try
for iSpot in StudentSpots do
begin
iSpot.ORM:=Self;
aCSV.AddRow(iSpot.User.ToString);
aCSV.Cells[1, aCSV.RowCount-1]:=iSpot._User.Name;
aCSV.Cells[2, aCSV.RowCount-1]:=iSpot.Lesson.ToString;
aCSV.Cells[3, aCSV.RowCount-1]:=iSpot._Lesson.Name;
end;
aCSV.SaveToStream(aCSVStream);
finally
aCSV.Free;
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: TGA<p>
Simple TGA formats supports for Delphi.<br>
Currently supports only 24 and 32 bits RGB formats (uncompressed
and RLE compressed).<p>
Based on David McDuffee's document from www.wotsit.org<p>
<b>History : </b><font size=-1><ul>
<li>07/03/11 - Yar - Removed LazTGA, added workaround of ScanLine for Lazarus
<li>20/04/10 - Yar - Removed registration for FPC (thanks to Rustam Asmandiarov aka Predator)
<li>07/01/10 - DaStr - TTGAImage is now replaced by LazTGA.TTGAImage
in Lazarus (thanks Predator)
<li>08/07/04 - LR - Uses of Graphics replaced by GLCrossPlatform for Linux
<li>21/11/02 - Egg - Creation
</ul></font>
}
unit TGA;
interface
{$i GLScene.inc}
uses
Classes, SysUtils,
GLCrossPlatform;
type
// TTGAImage
//
{: TGA image load/save capable class for Delphi.<p>
TGA formats supported : 24 and 32 bits uncompressed or RLE compressed,
saves only to uncompressed TGA. }
TTGAImage = class (TGLBitmap)
private
{ Private Declarations }
protected
{ Protected Declarations }
public
{ Public Declarations }
constructor Create; override;
destructor Destroy; override;
procedure LoadFromStream(stream : TStream); override;
procedure SaveToStream(stream : TStream); override;
end;
// ETGAException
//
ETGAException = class (Exception)
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses
GLGraphics;
type
// TTGAHeader
//
TTGAHeader = packed record
IDLength : Byte;
ColorMapType : Byte;
ImageType : Byte;
ColorMapOrigin : Word;
ColorMapLength : Word;
ColorMapEntrySize : Byte;
XOrigin : Word;
YOrigin : Word;
Width : Word;
Height : Word;
PixelSize : Byte;
ImageDescriptor : Byte;
end;
// ReadAndUnPackRLETGA24
//
procedure ReadAndUnPackRLETGA24(stream : TStream; destBuf : PAnsiChar; totalSize : Integer);
type
TRGB24 = packed record
r, g, b : Byte;
end;
PRGB24 = ^TRGB24;
var
n : Integer;
color : TRGB24;
bufEnd : PAnsiChar;
b : Byte;
begin
bufEnd:=@destBuf[totalSize];
while destBuf<bufEnd do begin
stream.Read(b, 1);
if b>=128 then begin
// repetition packet
stream.Read(color, 3);
b:=(b and 127)+1;
while b>0 do begin
PRGB24(destBuf)^:=color;
Inc(destBuf, 3);
Dec(b);
end;
end else begin
n:=((b and 127)+1)*3;
stream.Read(destBuf^, n);
Inc(destBuf, n);
end;
end;
end;
// ReadAndUnPackRLETGA32
//
procedure ReadAndUnPackRLETGA32(stream : TStream; destBuf : PAnsiChar; totalSize : Integer);
type
TRGB32 = packed record
r, g, b, a : Byte;
end;
PRGB32 = ^TRGB32;
var
n : Integer;
color : TRGB32;
bufEnd : PAnsiChar;
b : Byte;
begin
bufEnd:=@destBuf[totalSize];
while destBuf<bufEnd do begin
stream.Read(b, 1);
if b>=128 then begin
// repetition packet
stream.Read(color, 4);
b:=(b and 127)+1;
while b>0 do begin
PRGB32(destBuf)^:=color;
Inc(destBuf, 4);
Dec(b);
end;
end else begin
n:=((b and 127)+1)*4;
stream.Read(destBuf^, n);
Inc(destBuf, n);
end;
end;
end;
// ------------------
// ------------------ TTGAImage ------------------
// ------------------
// Create
//
constructor TTGAImage.Create;
begin
inherited Create;
end;
// Destroy
//
destructor TTGAImage.Destroy;
begin
inherited Destroy;
end;
// LoadFromStream
//
procedure TTGAImage.LoadFromStream(stream : TStream);
var
header : TTGAHeader;
y, rowSize, bufSize : Integer;
verticalFlip : Boolean;
unpackBuf : PAnsiChar;
function GetLineAddress(ALine: Integer): PByte;
begin
Result := PByte(ScanLine[ALine]);
end;
begin
stream.Read(header, Sizeof(TTGAHeader));
if header.ColorMapType<>0 then
raise ETGAException.Create('ColorMapped TGA unsupported');
case header.PixelSize of
24 : PixelFormat:=glpf24bit;
32 : PixelFormat:=glpf32bit;
else
raise ETGAException.Create('Unsupported TGA ImageType');
end;
Width:=header.Width;
Height:=header.Height;
rowSize:=(Width*header.PixelSize) div 8;
verticalFlip:=((header.ImageDescriptor and $20)=0);
if header.IDLength>0 then
stream.Seek(header.IDLength, soFromCurrent);
try
case header.ImageType of
0 : begin // empty image, support is useless but easy ;)
Width:=0;
Height:=0;
Abort;
end;
2 : begin // uncompressed RGB/RGBA
if verticalFlip then begin
for y:=0 to Height-1 do
stream.Read(GetLineAddress(Height-y-1)^, rowSize);
end else begin
for y:=0 to Height-1 do
stream.Read(GetLineAddress(y)^, rowSize);
end;
end;
10 : begin // RLE encoded RGB/RGBA
bufSize:=Height*rowSize;
unpackBuf:=GetMemory(bufSize);
try
// read & unpack everything
if header.PixelSize=24 then
ReadAndUnPackRLETGA24(stream, unpackBuf, bufSize)
else ReadAndUnPackRLETGA32(stream, unpackBuf, bufSize);
// fillup bitmap
if verticalFlip then begin
for y:=0 to Height-1 do begin
Move(unPackBuf[y*rowSize], GetLineAddress(Height-y-1)^, rowSize);
end;
end else begin
for y:=0 to Height-1 do
Move(unPackBuf[y*rowSize], GetLineAddress(y)^, rowSize);
end;
finally
FreeMemory(unpackBuf);
end;
end;
else
raise ETGAException.Create('Unsupported TGA ImageType '+IntToStr(header.ImageType));
end;
finally
//
end;
end;
// TTGAImage
//
procedure TTGAImage.SaveToStream(stream : TStream);
var
y, rowSize : Integer;
header : TTGAHeader;
begin
// prepare the header, essentially made up from zeroes
FillChar(header, SizeOf(TTGAHeader), 0);
header.ImageType:=2;
header.Width:=Width;
header.Height:=Height;
case PixelFormat of
glpf24bit : header.PixelSize:=24;
glpf32bit : header.PixelSize:=32;
else
raise ETGAException.Create('Unsupported Bitmap format');
end;
stream.Write(header, SizeOf(TTGAHeader));
rowSize:=(Width*header.PixelSize) div 8;
for y:=0 to Height-1 do
stream.Write(ScanLine[Height-y-1]^, rowSize);
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
TGLPicture.RegisterFileFormat('tga', 'Targa', TTGAImage);
finalization
TGLPicture.UnregisterGraphicClass(TTGAImage);
end.
|
unit int_not_u64;
interface
implementation
var I: UInt64;
procedure Test;
begin
I := Low(UInt64);
I := not I;
end;
initialization
Test();
finalization
// Assert(I = High(UInt64)); // не работает UInt64 нормально
end. |
{$I-}
unit Log;
interface
procedure logInit;
procedure logDone;
procedure logCreate(Name, FName: String); {$IFNDEF SOLID}export;{$ENDIF}
procedure logWrite(Name, S: String); {$IFNDEF SOLID}export;{$ENDIF}
procedure logKill(Name: String); {$IFNDEF SOLID}export;{$ENDIF}
procedure _ssGetLogs(Proc: Pointer);
procedure _ssChangeLogStatus(S: Pointer; Open: Boolean);
implementation
{$IfDef DPMI} uses Misc, Types, Dos, Wizard, Config; {$EndIF}
{$IfDef OS2} uses Misc, Types, Dos, Wizard, Use32, Config; {$EndIF}
{$IfDef Win32} uses Misc, Types, Dos, Wizard, Config; {$EndIF}
{$I fastuue.inc}
var
Logs: PCollection;
DebugLog: Boolean;
const
Working: Boolean = False;
type
PLog = ^TLog;
TLog = object(TObject)
public
Name: String;
FName: String;
Link: Text;
Opened: Boolean;
destructor Done; virtual;
end;
destructor TLog.Done;
begin
if Opened then Close(Link);
inherited Done;
end;
procedure logInit;
begin
Logs:=New(PCollection, Init);
DebugLog:=cGetBoolParam('Log.Flush');
end;
procedure logCreate(Name, FName: String);
var
Log: PLog;
procedure CheckLog(L: PLog); far;
begin
if Name=L^.Name then Log:=L;
end;
var
K: Longint;
begin
if FName='' then Exit;
TrimEx(Name);
StUpcaseEx(Name);
Log:=Nil;
for K:=1 to Logs^.Count do CheckLog(Logs^.At(K));
if Log<>Nil then Exit;
Log:=New(PLog, Init);
Log^.Name:=Name;
Log^.FName:=FName;
Log^.Opened:=False;
Logs^.Insert(Log);
end;
procedure logKill(Name: String);
var
Log: PLog;
procedure CheckLog(L: PLog); far;
begin
if Name = L^.Name then Log:=L;
end;
var
K: Longint;
begin
TrimEx(Name);
StUpcaseEx(Name);
Log:=Nil;
for K:=1 to Logs^.Count do CheckLog(Logs^.At(K));
if Log=Nil then Exit;
if Log^.Opened then Close(Log^.Link);
Logs^.Free(Log);
end;
procedure logWrite(Name, S: String);
const
Dows: array[0..6] of string[15] = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
Months: array[1..12] of string[15] = ('January','February','March','April','May','June','July','August','September',
'October','November','December');
var
Log: PLog;
{$IFDEF VIRTUALPASCAL}
D,M,Y,Dow: Longint;
Hour,Min,Sec,Sec1: Longint;
{$ELSE}
D,M,Y,Dow: Word;
Hour,Min,Sec,Sec1: Word;
{$ENDIF}
procedure CheckLog(L: PLog); far;
begin
if Name = L^.Name then Log:=L;
end;
var
K: Longint;
begin
if Working then Exit;
Working:=True;
GetTime(Hour, Min, Sec, Dow);
GetDate(Y, M, D, Dow);
if Logs=Nil then Exit;
TrimEx(Name);
StUpcaseEx(Name);
Log:=Nil;
for K:=1 to Logs^.Count do CheckLog(Logs^.At(K));
if Log = Nil then Exit;
if not Log^.Opened then
begin
mCreate(JustPathName(Log^.FName));
InOutRes:=0;
Assign(Log^.Link, Log^.FName);
Append(Log^.Link);
if IOResult<>0 then ReWrite(Log^.Link);
if IOResult<>0 then Exit;
System.WriteLn(Log^.Link,'');
System.WriteLn(Log^.Link,'');
System.WriteLn(Log^.Link,'컴컴컴컴컴컴컴컴컴컴 ',D,' ',Months[M],' ',Y,', ',Dows[Dow]);
Log^.Opened:=True;
end;
InOutRes:=0;
S:=LeftPadCh(Long2Str(Hour),'0',2)+':'+LeftPadCh(Long2Str(Min),'0',2)+':'+LeftPadCh(Long2Str(Sec),'0',2)+' '+S;
System.WriteLn(Log^.Link,S);
InOutRes:=0;
if DebugLog then System.Flush(Log^.Link);
Working:=False;
end;
procedure logDone;
begin
if Logs <> Nil then Dispose(Logs, Done);
end;
function logGet(Name: String): PLog;
procedure CheckLog(L: PLog); far;
begin
if Name=L^.Name then logGet:=L;
end;
var
K: Longint;
begin
TrimEx(Name);
StUpcaseEx(Name);
logGet:=Nil;
for K:=1 to Logs^.Count do
CheckLog(Logs^.At(K));
end;
{$i secret.inc}
procedure _ssGetLogs(Proc: Pointer);
var
P: TGetLogsProc;
K: Longint;
begin
@P:=Proc;
for K:=1 to Logs^.Count do
with PLog(Logs^.At(K))^ do
P(Name, FName);
end;
procedure _ssChangeLogStatus(S: Pointer; Open: Boolean);
var
L: PLog;
begin
if S=Nil then Exit;
L:=logGet(GetPString(S));
if L=Nil then Exit;
if Open then
begin
if L^.Opened then Exit;
mCreate(JustPathName(L^.FName));
InOutRes:=0;
Assign(L^.Link, L^.FName);
Append(L^.Link);
if IOResult <> 0 then ReWrite(L^.Link);
if IOResult <> 0 then Exit;
L^.Opened:=True;
end
else
begin
if not L^.Opened then Exit;
Close(L^.Link);
L^.Opened:=False;
end;
end;
end. |
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is DCL_intf.pas. }
{ }
{ The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by }
{ Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) }
{ All rights reserved. }
{ }
{ Contributors: }
{ Robert Marquardt (marquardt) }
{ Robert Rossmair (rrossmair) }
{ Florent Ouchet (outchy) }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2008-01-15 23:30:26 +0100 (mar., 15 janv. 2008) $ }
{ Revision: $Rev:: 2309 $ }
{ Author: $Author:: outchy $ }
{ }
{**************************************************************************************************}
unit JclContainerIntf;
{$I jcl.inc}
{$I containers\JclContainerIntf.int}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
Classes,
JclBase;
{$IFDEF BCB6}
{$DEFINE BUGGY_DEFAULT_INDEXED_PROP}
{$ENDIF BCB6}
{$IFDEF BCB10}
{$DEFINE BUGGY_DEFAULT_INDEXED_PROP}
{$ENDIF BCB10}
{$IFDEF BCB11}
{$DEFINE BUGGY_DEFAULT_INDEXED_PROP}
{$ENDIF BCB11}
const
DefaultContainerCapacity = 16;
type
// function pointer types
// apply functions Type -> Type
{$JPPEXPANDMACRO APPLYFUNCTION(TIntfApplyFunction,const ,AInterface,IInterface)}
{$JPPEXPANDMACRO APPLYFUNCTION(TAnsiStrApplyFunction,const ,AString,AnsiString)}
{$JPPEXPANDMACRO APPLYFUNCTION(TWideStrApplyFunction,const ,AString,WideString)}
{$IFDEF CONTAINER_ANSISTR}
TStrApplyFunction = TAnsiStrApplyFunction;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TStrApplyFunction = TWideStrApplyFunction;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO APPLYFUNCTION(TSingleApplyFunction,const ,AValue,Single)}
{$JPPEXPANDMACRO APPLYFUNCTION(TDoubleApplyFunction,const ,AValue,Double)}
{$JPPEXPANDMACRO APPLYFUNCTION(TExtendedApplyFunction,const ,AValue,Extended)}
{$IFDEF MATH_SINGLE_PRECISION}
TFloatApplyFunction = TSingleApplyFunction;
{$ENDIF MATH_SINGLE_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TFloatApplyFunction = TDoubleApplyFunction;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_EXTENDED_PRECISION}
TFloatApplyFunction = TExtendedApplyFunction;
{$ENDIF MATH_EXTENDED_PRECISION}
{$JPPEXPANDMACRO APPLYFUNCTION(TIntegerApplyFunction,,AValue,Integer)}
{$JPPEXPANDMACRO APPLYFUNCTION(TCardinalApplyFunction,,AValue,Cardinal)}
{$JPPEXPANDMACRO APPLYFUNCTION(TInt64ApplyFunction,const ,AValue,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO APPLYFUNCTION(TPtrApplyFunction,,APtr,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO APPLYFUNCTION(TApplyFunction,,AObject,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO APPLYFUNCTION(TApplyFunction<T>,const ,AItem,T)}
{$ENDIF SUPPORTS_GENERICS}
// comparison functions Type -> Type -> Integer
{$JPPEXPANDMACRO COMPAREFUNCTION(TIntfCompare,const ,IInterface)}
{$JPPEXPANDMACRO COMPAREFUNCTION(TAnsiStrCompare,const ,AnsiString)}
{$JPPEXPANDMACRO COMPAREFUNCTION(TWideStrCompare,const ,WideString)}
{$IFDEF CONTAINER_ANSISTR}
TStrCompare = TAnsiStrCompare;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TStrCompare = TWideStrCompare;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO COMPAREFUNCTION(TSingleCompare,const ,Single)}
{$JPPEXPANDMACRO COMPAREFUNCTION(TDoubleCompare,const ,Double)}
{$JPPEXPANDMACRO COMPAREFUNCTION(TExtendedCompare,const ,Extended)}
{$IFDEF MATH_SINGLE_PRECISION}
TFloatCompare = TSingleCompare;
{$ENDIF MATH_SINGLE_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TFloatCompare = TDoubleCompare;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_EXTENDED_PRECISION}
TFloatCompare = TExtendedCompare;
{$ENDIF MATH_EXTENDED_PRECISION}
{$JPPEXPANDMACRO COMPAREFUNCTION(TIntegerCompare,,Integer)}
{$JPPEXPANDMACRO COMPAREFUNCTION(TCardinalCompare,,Cardinal)}
{$JPPEXPANDMACRO COMPAREFUNCTION(TInt64Compare,,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO COMPAREFUNCTION(TPtrCompare,,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO COMPAREFUNCTION(TCompare,,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO COMPAREFUNCTION(TCompare<T>,const ,T)}
{$ENDIF SUPPORTS_GENERICS}
// comparison for equality functions Type -> Type -> Boolean
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TIntfEqualityCompare,const ,IInterface)}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TAnsiStrEqualityCompare,const ,AnsiString)}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TWideStrEqualityCompare,const ,WideString)}
{$IFDEF CONTAINER_ANSISTR}
TStrEqualityCompare = TAnsiStrEqualityCompare;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TStrEqualityCompare = TWideStrEqualityCompare;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TSingleEqualityCompare,const ,Single)}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TDoubleEqualityCompare,const ,Double)}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TExtendedEqualityCompare,const ,Extended)}
{$IFDEF MATH_SINGLE_PRECISION}
TFloatEqualityCompare = TSingleEqualityCompare;
{$ENDIF MATH_SINGLE_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TFloatEqualityCompare = TDoubleEqualityCompare;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_EXTENDED_PRECISION}
TFloatEqualityCompare = TExtendedEqualityCompare;
{$ENDIF MATH_EXTENDED_PRECISION}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TIntegerEqualityCompare,,Integer)}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TCardinalEqualityCompare,,Cardinal)}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TInt64EqualityCompare,const ,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TPtrEqualityCompare,,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TEqualityCompare,,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO EQUALITYCOMPAREFUNCTION(TEqualityCompare<T>,const ,T)}
{$ENDIF SUPPORTS_GENERICS}
// hash functions Type -> Integer
{$JPPEXPANDMACRO HASHFUNCTION(TIntfHashConvert,const ,AInterface,IInterface)}
{$JPPEXPANDMACRO HASHFUNCTION(TAnsiStrHashConvert,const ,AString,AnsiString)}
{$JPPEXPANDMACRO HASHFUNCTION(TWideStrHashConvert,const ,AString,WideString)}
{$IFDEF CONTAINER_ANSISTR}
TStrHashConvert = TAnsiStrHashConvert;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TStrHashConvert = TWideStrHashConvert;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO HASHFUNCTION(TSingleHashConvert,const ,AValue,Single)}
{$JPPEXPANDMACRO HASHFUNCTION(TDoubleHashConvert,const ,AValue,Double)}
{$JPPEXPANDMACRO HASHFUNCTION(TExtendedHashConvert,const ,AValue,Extended)}
{$IFDEF MATH_SINGLE_PRECISION}
TFloatHashConvert = TSingleHashConvert;
{$ENDIF MATH_SINGLE_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TFloatHashConvert = TDoubleHashConvert;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_EXTENDED_PRECISION}
TFloatHashConvert = TExtendedHashConvert;
{$ENDIF MATH_EXTENDED_PRECISION}
{$JPPEXPANDMACRO HASHFUNCTION(TIntegerHashConvert,,AValue,Integer)}
{$JPPEXPANDMACRO HASHFUNCTION(TCardinalHashConvert,,AValue,Cardinal)}
{$JPPEXPANDMACRO HASHFUNCTION(TInt64HashConvert,const ,AValue,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO HASHFUNCTION(TPtrHashConvert,,APtr,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO HASHFUNCTION(THashConvert,,AObject,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO HASHFUNCTION(THashConvert<T>,const ,AItem,T)}
{$ENDIF SUPPORTS_GENERICS}
IJclLockable = interface
['{524AD65E-AE1B-4BC6-91C8-8181F0198BA9}']
procedure ReadLock;
procedure ReadUnlock;
procedure WriteLock;
procedure WriteUnlock;
end;
IJclAbstractIterator = interface{$IFDEF THREADSAFE}(IJclLockable){$ENDIF THREADSAFE}
['{1064D0B4-D9FC-475D-88BE-520490013B46}']
procedure Assign(const Source: IJclAbstractIterator);
procedure AssignTo(const Dest: IJclAbstractIterator);
function GetIteratorReference: TObject;
end;
IJclContainer = interface{$IFDEF THREADSAFE}(IJclLockable){$ENDIF THREADSAFE}
['{C517175A-028E-486A-BF27-5EF7FC3101D9}']
procedure Assign(const Source: IJclContainer);
procedure AssignTo(const Dest: IJclContainer);
function GetAllowDefaultElements: Boolean;
function GetContainerReference: TObject;
function GetDuplicates: TDuplicates;
function GetReadOnly: Boolean;
function GetRemoveSingleElement: Boolean;
function GetReturnDefaultElements: Boolean;
function GetThreadSafe: Boolean;
procedure SetAllowDefaultElements(Value: Boolean);
procedure SetDuplicates(Value: TDuplicates);
procedure SetReadOnly(Value: Boolean);
procedure SetRemoveSingleElement(Value: Boolean);
procedure SetReturnDefaultElements(Value: Boolean);
procedure SetThreadSafe(Value: Boolean);
property AllowDefaultElements: Boolean read GetAllowDefaultElements write SetAllowDefaultElements;
property Duplicates: TDuplicates read GetDuplicates write SetDuplicates;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly;
property RemoveSingleElement: Boolean read GetRemoveSingleElement write SetRemoveSingleElement;
property ReturnDefaultElements: Boolean read GetReturnDefaultElements write SetReturnDefaultElements;
property ThreadSafe: Boolean read GetThreadSafe write SetThreadSafe;
end;
IJclStrContainer = interface(IJclContainer)
['{9753E1D7-F093-4D5C-8B32-40403F6F700E}']
function GetCaseSensitive: Boolean;
procedure SetCaseSensitive(Value: Boolean);
property CaseSensitive: Boolean read GetCaseSensitive write SetCaseSensitive;
end;
TJclAnsiStrEncoding = (seISO {, seUTF8}); // TODO: make JclUnicode compatible with Linux and .NET
IJclAnsiStrContainer = interface(IJclStrContainer)
['{F8239357-B96F-46F1-A48E-B5DF25B5F1FA}']
function GetEncoding: TJclAnsiStrEncoding;
procedure SetEncoding(Value: TJclAnsiStrEncoding);
property Encoding: TJclAnsiStrEncoding read GetEncoding write SetEncoding;
end;
IJclAnsiStrFlatContainer = interface(IJclAnsiStrContainer)
['{8A45A4D4-6317-4CDF-8314-C3E5CC6899F4}']
procedure LoadFromStrings(Strings: TStrings);
procedure SaveToStrings(Strings: TStrings);
procedure AppendToStrings(Strings: TStrings);
procedure AppendFromStrings(Strings: TStrings);
function GetAsStrings: TStrings;
function GetAsDelimited(const Separator: AnsiString = AnsiLineBreak): AnsiString;
procedure AppendDelimited(const AString: AnsiString; const Separator: AnsiString = AnsiLineBreak);
procedure LoadDelimited(const AString: AnsiString; const Separator: AnsiString = AnsiLineBreak);
end;
TJclWideStrEncoding = (weUCS2 {, wsUTF16}); // TODO: make JclUnicode compatible with Linux and .NET
IJclWideStrContainer = interface(IJclStrContainer)
['{875E1AC4-CA22-46BC-8999-048E5B9BF11D}']
function GetEncoding: TJclWideStrEncoding;
procedure SetEncoding(Value: TJclWideStrEncoding);
property Encoding: TJclWideStrEncoding read GetEncoding write SetEncoding;
end;
IJclWideStrFlatContainer = interface(IJclWideStrContainer)
['{5B001B93-CA1C-47A8-98B8-451CCB444930}']
{procedure LoadFromStrings(Strings: TWideStrings);
procedure SaveToStrings(Strings: TWideStrings);
procedure AppendToStrings(Strings: TWideStrings);
procedure AppendFromStrings(Strings: TWideStrings);
function GetAsStrings: TWideStrings;
function GetAsDelimited(const Separator: WideString = WideLineBreak): WideString;
procedure AppendDelimited(const AString: WideString; const Separator: WideString = WideLineBreak);
procedure LoadDelimited(const AString: WideString; const Separator: WideString = WideLineBreak);}
end;
IJclSingleContainer = interface(IJclContainer)
['{22BE88BD-87D1-4B4D-9FAB-F1B6D555C6A9}']
function GetPrecision: Single;
procedure SetPrecision(const Value: Single);
property Precision: Single read GetPrecision write SetPrecision;
end;
IJclDoubleContainer = interface(IJclContainer)
['{372B9354-DF6D-4CAA-A5A9-C50E1FEE5525}']
function GetPrecision: Double;
procedure SetPrecision(const Value: Double);
property Precision: Double read GetPrecision write SetPrecision;
end;
IJclExtendedContainer = interface(IJclContainer)
['{431A6482-FD5C-45A7-BE53-339A3CF75AC9}']
function GetPrecision: Extended;
procedure SetPrecision(const Value: Extended);
property Precision: Extended read GetPrecision write SetPrecision;
end;
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatContainer = IJclExtendedContainer;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatContainer = IJclDoubleContainer;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatContainer = IJclSingleContainer;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclIntfEqualityComparer,5CC2DF51-BE56-4D02-A171-31BAAC097632,TIntfEqualityCompare,const ,IInterface)}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclAnsiStrEqualityComparer,E3DB9016-F0D0-4CE0-B156-4C5DCA47FD3B,TAnsiStrEqualityCompare,const ,AnsiString)}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclWideStrEqualityComparer,2E5696C9-8374-4347-9DC9-B3722F47F5FB,TWideStrEqualityCompare,const ,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrEqualityComparer = IJclAnsiStrEqualityComparer;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrEqualityComparer = IJclWideStrEqualityComparer;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclSingleEqualityComparer,4835BC5B-1A87-4864-BFE1-778F3BAF26B1,TSingleEqualityCompare,const ,Single)}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclDoubleEqualityComparer,15F0A9F0-D5DC-4978-8CDB-53B6E510262C,TDoubleEqualityCompare,const ,Double)}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclExtendedEqualityComparer,149883D5-4138-4570-8C5C-99F186B7E646,TExtendedEqualityCompare,const ,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatEqualityComparer = IJclExtendedEqualityComparer;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatEqualityComparer = IJclDoubleEqualityComparer;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatEqualityComparer = IJclSingleEqualityComparer;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclIntegerEqualityComparer,AABC35E6-A779-4A44-B748-27BFCB34FDFB,TIntegerEqualityCompare,,Integer)}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclCardinalEqualityComparer,B2DECF81-6ECE-4D9F-80E1-C8C884DB407C,TCardinalEqualityCompare,,Cardinal)}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclInt64EqualityComparer,8B2825E2-0C81-42BA-AC0D-104344CE7E56,TInt64EqualityCompare,const ,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclPtrEqualityComparer,C6B7CBF9-ECD9-4D70-85CC-4E2367A1D806,TPtrEqualityCompare,,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclEqualityComparer,82C67986-8365-44AB-8D56-7B0CF4F6B918,TEqualityCompare,,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO EQUALITYCOMPARER(IJclEqualityComparer<T>,4AF79AD6-D9F4-424B-BEAA-68857F9222B4,TEqualityCompare<T>,const ,T)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO COMPARER(IJclIntfComparer,EB41B843-184B-420D-B5DA-27D055B4CD55,TIntfCompare,const ,IInterface)}
{$JPPEXPANDMACRO COMPARER(IJclAnsiStrComparer,09063CBB-9226-4734-B2A0-A178C2343176,TAnsiStrCompare,const ,AnsiString)}
{$JPPEXPANDMACRO COMPARER(IJclWideStrComparer,7A24AEDA-25B1-4E73-B2E9-5D74011E4C9C,TWideStrCompare,const ,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrComparer = IJclAnsiStrComparer;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrComparer = IJclWideStrComparer;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO COMPARER(IJclSingleComparer,008225CE-075E-4450-B9DE-9863CB6D347C,TSingleCompare,const ,Single)}
{$JPPEXPANDMACRO COMPARER(IJclDoubleComparer,BC245D7F-7EB9-43D0-81B4-EE215486A5AA,TDoubleCompare,const ,Double)}
{$JPPEXPANDMACRO COMPARER(IJclExtendedComparer,92657C66-C18D-4BF8-A538-A3B0140320BB,TExtendedCompare,const ,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatComparer = IJclExtendedComparer;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatComparer = IJclDoubleComparer;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatComparer = IJclSingleComparer;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO COMPARER(IJclIntegerComparer,362C3A6A-CBC1-4D5F-8652-158913DC9865,TIntegerCompare,,Integer)}
{$JPPEXPANDMACRO COMPARER(IJclCardinalComparer,56E44725-00B9-4530-8CC2-72DCA9171EE0,TCardinalCompare,,Cardinal)}
{$JPPEXPANDMACRO COMPARER(IJclInt64Comparer,87C935BF-3A42-4F1F-A474-9C823939EE1C,TInt64Compare,const ,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO COMPARER(IJclPtrComparer,85557D4C-A036-477E-BA73-B5EEF43A8696,TPtrCompare,,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO COMPARER(IJclComparer,7B376028-56DC-4C4A-86A9-1AC19E3EDF75,TCompare,,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO COMPARER(IJclComparer<T>,830AFC8C-AA06-46F5-AABD-8EB46B2A9986,TCompare<T>,const ,T)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO HASHCONVERTER(IJclIntfHashConverter,7BAA0791-3B45-4D0F-9CD8-D13B81694786,TIntfHashConvert,const ,AInterface,IInterface)}
{$JPPEXPANDMACRO HASHCONVERTER(IJclAnsiStrHashConverter,9841014E-8A31-4C79-8AD5-EB03C4E85533,TAnsiStrHashConvert,const ,AString,AnsiString)}
{$JPPEXPANDMACRO HASHCONVERTER(IJclWideStrHashConverter,2584118F-19AE-443E-939B-0DB18BCD0117,TWideStrHashConvert,const ,AString,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrHashConverter = IJclAnsiStrHashConverter;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrHashConverter = IJclWideStrHashConverter;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO HASHCONVERTER(IJclSingleHashConverter,20F0E481-F1D2-48B6-A95D-FBB56AF119F5,TSingleHashConvert,const ,AValue,Single)}
{$JPPEXPANDMACRO HASHCONVERTER(IJclDoubleHashConverter,193A2881-535B-4AF4-B0C3-6845A2800F80,TDoubleHashConvert,const ,AValue,Double)}
{$JPPEXPANDMACRO HASHCONVERTER(IJclExtendedHashConverter,77CECDB9-2774-4FDC-8E5A-A80325626434,TExtendedHashConvert,const ,AValue,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatHashConverter = IJclExtendedHashConverter;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatHashConverter = IJclDoubleHashConverter;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatHashConverter = IJclSingleHashConverter;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO HASHCONVERTER(IJclIntegerHashConverter,92C540B2-C16C-47E4-995A-644BE71878B1,TIntegerHashConvert,,AValue,Integer)}
{$JPPEXPANDMACRO HASHCONVERTER(IJclCardinalHashConverter,2DF04C8A-16B8-4712-BC5D-AD35014EC9F7,TCardinalHashConvert,,AValue,Cardinal)}
{$JPPEXPANDMACRO HASHCONVERTER(IJclInt64HashConverter,96CF2A71-9185-4E26-B283-457ABC3584E7,TInt64HashConvert,const ,AValue,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO HASHCONVERTER(IJclPtrHashConverter,D704CC67-CFED-44E6-9504-65D5E468FCAF,TPtrHashConvert,,Ptr,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO HASHCONVERTER(IJclHashConverter,2D0DD6F4-162E-41D6-8A34-489E7EACABCD,THashConvert,,AObject,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO HASHCONVERTER(IJclHashConverter<T>,300AEA0E-7433-4C3E-99A6-E533212ACF42,THashConvert<T>,const ,AItem,T)}
{$ENDIF SUPPORTS_GENERICS}
IJclIntfCloneable = interface
['{BCF77740-FB60-4306-9BD1-448AADE5FF4E}']
function Clone: IInterface;
end;
IJclCloneable = interface
['{D224AE70-2C93-4998-9479-1D513D75F2B2}']
function Clone: TObject;
end;
TJclAutoPackStrategy = (apsDisabled, apsAgressive, apsProportional, apsIncremental);
// parameter signification depends on strategy
// - Disabled = unused (arrays are never packed)
// - Agressive = unused (arrays are always packed)
// - Proportional = ratio of empty slots before the array is packed
// number of empty slots is computed by this formula: Capacity div Parameter
// - Incremental = amount of empty slots before the array is packed
IJclPackable = interface
['{03802D2B-E0AB-4300-A777-0B8A2BD993DF}']
function CalcGrowCapacity(ACapacity, ASize: Integer): Integer;
function GetAutoPackParameter: Integer;
function GetAutoPackStrategy: TJclAutoPackStrategy;
function GetCapacity: Integer;
procedure Pack; // reduce used memory by eliminating empty storage area (force)
procedure SetAutoPackParameter(Value: Integer);
procedure SetAutoPackStrategy(Value: TJclAutoPackStrategy);
procedure SetCapacity(Value: Integer);
property AutoPackParameter: Integer read GetAutoPackParameter write SetAutoPackParameter;
property AutoPackStrategy: TJclAutoPackStrategy read GetAutoPackStrategy write SetAutoPackStrategy;
property Capacity: Integer read GetCapacity write SetCapacity;
end;
TJclAutoGrowStrategy = (agsDisabled, agsAgressive, agsProportional, agsIncremental);
// parameter signification depends on strategy
// - Disabled = unused (arrays never grow)
// - Agressive = unused (arrays always grow by 1 element)
// - Proportional = ratio of empty slots to add to the array
// number of empty slots is computed by this formula: Capacity div Parameter
// - Incremental = amount of empty slots to add to the array
IJclGrowable = interface(IJclPackable)
['{C71E8586-5688-444C-9BDD-9969D988123B}']
function CalcPackCapacity(ACapacity, ASize: Integer): Integer;
function GetAutoGrowParameter: Integer;
function GetAutoGrowStrategy: TJclAutoGrowStrategy;
procedure Grow;
procedure SetAutoGrowParameter(Value: Integer);
procedure SetAutoGrowStrategy(Value: TJclAutoGrowStrategy);
property AutoGrowParameter: Integer read GetAutoGrowParameter write SetAutoGrowParameter;
property AutoGrowStrategy: TJclAutoGrowStrategy read GetAutoGrowStrategy write SetAutoGrowStrategy;
end;
IJclObjectOwner = interface
['{5157EA13-924E-4A56-995D-36956441025C}']
function FreeObject(var AObject: TObject): TObject;
function GetOwnsObjects: Boolean;
property OwnsObjects: Boolean read GetOwnsObjects;
end;
IJclKeyOwner = interface
['{8BE209E6-2F85-44FD-B0CD-A8363C95349A}']
function FreeKey(var Key: TObject): TObject;
function GetOwnsKeys: Boolean;
property OwnsKeys: Boolean read GetOwnsKeys;
end;
IJclValueOwner = interface
['{3BCD98CE-7056-416A-A9E7-AE3AB2A62E54}']
function FreeValue(var Value: TObject): TObject;
function GetOwnsValues: Boolean;
property OwnsValues: Boolean read GetOwnsValues;
end;
{$IFDEF SUPPORTS_GENERICS}
IJclItemOwner<T> = interface
['{0CC220C1-E705-4B21-9F53-4AD340952165}']
function FreeItem(var AItem: T): T;
function GetOwnsItems: Boolean;
property OwnsItems: Boolean read GetOwnsItems;
end;
IJclPairOwner<TKey, TValue> = interface
['{321C1FF7-AA2E-4229-966A-7EC6417EA16D}']
function FreeKey(var Key: TKey): TKey;
function FreeValue(var Value: TValue): TValue;
function GetOwnsKeys: Boolean;
function GetOwnsValues: Boolean;
property OwnsKeys: Boolean read GetOwnsKeys;
property OwnsValues: Boolean read GetOwnsValues;
end;
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO ITERATOR(IJclIntfIterator,IJclAbstractIterator,E121A98A-7C43-4587-806B-9189E8B2F106,const ,AInterface,IInterface,GetObject,SetObject)}
{$JPPEXPANDMACRO ITERATOR(IJclAnsiStrIterator,IJclAbstractIterator,D5D4B681-F902-49C7-B9E1-73007C9D64F0,const ,AString,AnsiString,GetString,SetString)}
{$JPPEXPANDMACRO ITERATOR(IJclWideStrIterator,IJclAbstractIterator,F03BC7D4-CCDA-4C4A-AF3A-E51FDCDE8ADE,const ,AString,WideString,GetString,SetString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrIterator = IJclAnsiStrIterator;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrIterator = IJclWideStrIterator;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO ITERATOR(IJclSingleIterator,IJclAbstractIterator,FD1124F8-CB2B-4AD7-B12D-C05702F4204B,const ,AValue,Single,GetValue,SetValue)}
{$JPPEXPANDMACRO ITERATOR(IJclDoubleIterator,IJclAbstractIterator,004C154A-281C-4DA7-BF64-F3EE80ACF640,const ,AValue,Double,GetValue,SetValue)}
{$JPPEXPANDMACRO ITERATOR(IJclExtendedIterator,IJclAbstractIterator,B89877A5-DED4-4CD9-AB90-C7D062111DE0,const ,AValue,Extended,GetValue,SetValue)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatIterator = IJclExtendedIterator;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatIterator = IJclDoubleIterator;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatIterator = IJclSingleIterator;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO ITERATOR(IJclIntegerIterator,IJclAbstractIterator,1406A991-4574-48A1-83FE-2EDCA03908BE,,AValue,Integer,GetValue,SetValue)}
{$JPPEXPANDMACRO ITERATOR(IJclCardinalIterator,IJclAbstractIterator,72847A34-C8C4-4592-9447-CEB8161E33AD,,AValue,Cardinal,GetValue,SetValue)}
{$JPPEXPANDMACRO ITERATOR(IJclInt64Iterator,IJclAbstractIterator,573E5A51-BF76-43D7-9F93-46305BED20A8,const ,AValue,Int64,GetValue,SetValue)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO ITERATOR(IJclPtrIterator,IJclAbstractIterator,62B5501C-07AA-4D00-A85B-713B39912CDF,,APtr,Pointer,GetPointer,SetPointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO ITERATOR(IJclIterator,IJclAbstractIterator,997DF9B7-9AA2-4239-8B94-14DFFD26D790,,AObject,TObject,GetObject,SetObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO ITERATOR(IJclIterator<T>,IJclAbstractIterator,6E8547A4-5B5D-4831-8AE3-9C6D04071B11,const ,AItem,T,GetItem,SetItem)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO TREEITERATOR(IJclIntfTreeIterator,IJclIntfIterator,C97379BF-C6A9-4A90-9D7A-152E9BAD314F,const ,AInterface,IInterface)}
{$JPPEXPANDMACRO TREEITERATOR(IJclAnsiStrTreeIterator,IJclAnsiStrIterator,66BC5C76-758C-4E72-ABF1-EB02CF851C6D,const ,AString,AnsiString)}
{$JPPEXPANDMACRO TREEITERATOR(IJclWideStrTreeIterator,IJclWideStrIterator,B3168A3B-5A90-4ABF-855F-3D2B3AB6EE7F,const ,AString,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrTreeIterator = IJclAnsiStrTreeIterator;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrTreeIterator = IJclWideStrTreeIterator;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO TREEITERATOR(IJclSingleTreeIterator,IJclSingleIterator,17BFDE9D-DBF7-4DC8-AC74-919C717B4726,const ,AValue,Single)}
{$JPPEXPANDMACRO TREEITERATOR(IJclDoubleTreeIterator,IJclDoubleIterator,EB39B84E-D3C5-496E-A521-B8BF24579252,const ,AValue,Double)}
{$JPPEXPANDMACRO TREEITERATOR(IJclExtendedTreeIterator,IJclExtendedIterator,1B40A544-FC5D-454C-8E42-CE17B015E65C,const ,AValue,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatTreeIterator = IJclExtendedTreeIterator;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatTreeIterator = IJclDoubleTreeIterator;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatTreeIterator = IJclSingleTreeIterator;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO TREEITERATOR(IJclIntegerTreeIterator,IJclIntegerIterator,88EDC5C5-CA41-41AF-9838-AA19D07E69F5,,AValue,Integer)}
{$JPPEXPANDMACRO TREEITERATOR(IJclCardinalTreeIterator,IJclCardinalIterator,FDBF493F-F79D-46EB-A59D-7193B6E6A860,,AValue,Cardinal)}
{$JPPEXPANDMACRO TREEITERATOR(IJclInt64TreeIterator,IJclInt64Iterator,C5A5E504-E19B-43AC-90B9-E4B8984BFA23,const ,AValue,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO TREEITERATOR(IJclPtrTreeIterator,IJclPtrIterator,ED4C08E6-60FC-4ED3-BD19-E6605B9BD943,,APtr,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO TREEITERATOR(IJclTreeIterator,IJclIterator,8B4863B0-B6B9-426E-B5B8-7AF71D264237,,AObject,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO TREEITERATOR(IJclTreeIterator<T>,IJclIterator<T>,29A06DA4-D93A-40A5-8581-0FE85BC8384B,const ,AItem,T)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclIntfBinaryTreeIterator,IJclIntfTreeIterator,8BE874B2-0075-4EE0-8F49-665FC894D923,IInterface)}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclAnsiStrBinaryTreeIterator,IJclAnsiStrTreeIterator,34A4A300-042C-43A9-AC23-8FC1B76BFB25,AnsiString)}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclWideStrBinaryTreeIterator,IJclWideStrTreeIterator,17C08EB9-6880-469E-878A-8F5EBFE905B1,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrBinaryTreeIterator = IJclAnsiStrBinaryTreeIterator;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrBinaryTreeIterator = IJclWideStrBinaryTreeIterator;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclSingleBinaryTreeIterator,IJclSingleTreeIterator,BC6FFB13-FA1C-4077-8273-F25A3119168B,Single)}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclDoubleBinaryTreeIterator,IJclDoubleTreeIterator,CE48083C-D60C-4315-BC14-8CE77AC3269E,Double)}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclExtendedBinaryTreeIterator,IJclExtendedTreeIterator,8A9FAE2A-5EF5-4165-8E8D-51F2102A4580,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatBinaryTreeIterator = IJclExtendedBinaryTreeIterator;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatBinaryTreeIterator = IJclDoubleBinaryTreeIterator;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatBinaryTreeIterator = IJclSingleBinaryTreeIterator;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclIntegerBinaryTreeIterator,IJclIntegerTreeIterator,FE2BF57D-D10D-4B0C-903D-BB61700FBA0A,Integer)}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclCardinalBinaryTreeIterator,IJclCardinalTreeIterator,AAA358F5-95A1-480F-8E2A-09028BA6C397,Cardinal)}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclInt64BinaryTreeIterator,IJclInt64TreeIterator,5605E164-5CDD-40B1-9323-DE1CB584E289,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclPtrBinaryTreeIterator,IJclPtrTreeIterator,75D3DF0D-C491-43F7-B078-E658197E8051,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclBinaryTreeIterator,IJclTreeIterator,821DE28D-631C-4F23-A0B2-CC0F35B4C64D,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO BINTREEITERATOR(IJclBinaryTreeIterator<T>,IJclTreeIterator<T>,0CF5B0FC-C644-458C-BF48-2E093DAFEC26,T)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO COLLECTION(IJclIntfCollection,IJclContainer,8E178463-4575-487A-B4D5-DC2AED3C7ACA,const ,AInterface,IInterface,IJclIntfIterator)}
{$JPPEXPANDMACRO COLLECTION(IJclAnsiStrCollection,IJclAnsiStrFlatContainer,3E3CFC19-E8AF-4DD7-91FA-2DF2895FC7B9,const ,AString,AnsiString,IJclAnsiStrIterator)}
{$JPPEXPANDMACRO COLLECTION(IJclWideStrCollection,IJclWideStrFlatContainer,CDCC0F94-4DD0-4F25-B441-6AE55D5C7466,const ,AString,WideString,IJclWideStrIterator)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrCollection = IJclAnsiStrCollection;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrCollection = IJclWideStrCollection;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO COLLECTION(IJclSingleCollection,IJclSingleContainer,1D34D474-6588-441E-B2B3-8C021A37ED89,const ,AValue,Single,IJclSingleIterator)}
{$JPPEXPANDMACRO COLLECTION(IJclDoubleCollection,IJclDoubleContainer,E54C7717-C33A-4F1B-860C-4F60F303EAD3,const ,AValue,Double,IJclDoubleIterator)}
{$JPPEXPANDMACRO COLLECTION(IJclExtendedCollection,IJclExtendedContainer,2A1341CB-B997-4E3B-B1CA-6D60AE853C55,const ,AValue,Extended,IJclExtendedIterator)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatCollection = IJclExtendedCollection;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatCollection = IJclDoubleCollection;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatCollection = IJclSingleCollection;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO COLLECTION(IJclIntegerCollection,IJclContainer,AF69890D-22D1-4D89-8FFD-5FAD7E0638BA,,AValue,Integer,IJclIntegerIterator)}
{$JPPEXPANDMACRO COLLECTION(IJclCardinalCollection,IJclContainer,CFBD0344-58C8-4FA2-B4D7-D21D77DFBF80,,AValue,Cardinal,IJclCardinalIterator)}
{$JPPEXPANDMACRO COLLECTION(IJclInt64Collection,IJclContainer,93A45BDE-3C4C-48D6-9874-5322914DFDDA,const ,AValue,Int64,IJclInt64Iterator)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO COLLECTION(IJclPtrCollection,IJclContainer,02E909A7-5B1D-40D4-82EA-A0CD97D5C811,,APtr,Pointer,IJclPtrIterator)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO COLLECTION(IJclCollection,IJclContainer,58947EF1-CD21-4DD1-AE3D-225C3AAD7EE5,,AObject,TObject,IJclIterator)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO COLLECTION(IJclCollection<T>,IJclContainer,67EE8AF3-19B0-4DCA-A730-3C9B261B8EC5,const ,AItem,T,IJclIterator<T>)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO LIST(IJclIntfList,IJclIntfCollection,E14EDA4B-1DAA-4013-9E6C-CDCB365C7CF9,const ,AInterface,IInterface,GetObject,SetObject,Objects)}
{$JPPEXPANDMACRO LIST(IJclAnsiStrList,IJclAnsiStrCollection,07DD7644-EAC6-4059-99FC-BEB7FBB73186,const ,AString,AnsiString,GetString,SetString,Strings)}
{$JPPEXPANDMACRO LIST(IJclWideStrList,IJclWideStrCollection,C9955874-6AC0-4CE0-8CC0-606A3F1702C6,const ,AString,WideString,GetString,SetString,Strings)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrList = IJclAnsiStrList;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrList = IJclWideStrList;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO LIST(IJclSingleList,IJclSingleCollection,D081324C-70A4-4AAC-BA42-7557F0262826,const ,AValue,Single,GetValue,SetValue,Values)}
{$JPPEXPANDMACRO LIST(IJclDoubleList,IJclDoubleCollection,ECA58515-3903-4312-9486-3214E03F35AB,const ,AValue,Double,GetValue,SetValue,Values)}
{$JPPEXPANDMACRO LIST(IJclExtendedList,IJclExtendedCollection,7463F954-F8DF-4B02-A284-FCB98746248E,const ,AValue,Extended,GetValue,SetValue,Values)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatList = IJclExtendedList;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatList = IJclDoubleList;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatList = IJclSingleList;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO LIST(IJclIntegerList,IJclIntegerCollection,339BE91B-557D-4CE0-A854-1CBD4FE31725,,AValue,Integer,GetValue,SetValue,Values)}
{$JPPEXPANDMACRO LIST(IJclCardinalList,IJclCardinalCollection,02B09EA8-DE6F-4A18-AA57-C3533E6AC4E3,,AValue,Cardinal,GetValue,SetValue,Values)}
{$JPPEXPANDMACRO LIST(IJclInt64List,IJclInt64Collection,E8D49200-91D3-4BD0-A59B-B93EC7E2074B,const ,AValue,Int64,GetValue,SetValue,Values)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO LIST(IJclPtrList,IJclPtrCollection,2CF5CF1F-C012-480C-A4CE-38BDAFB15D05,,APtr,Pointer,GetPointer,SetPointer,Pointers)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO LIST(IJclList,IJclCollection,8ABC70AC-5C06-43EA-AFE0-D066379BCC28,,AObject,TObject,GetObject,SetObject,Objects)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO LIST(IJclList<T>,IJclCollection<T>,3B4BE3D7-8FF7-4163-91DF-3F73AE6935E7,const ,AItem,T,GetItem,SetItem,Items)}
{$ENDIF SUPPORTS_GENERICS}
// Pointer functions for sort algorithms
{$JPPEXPANDMACRO SORTPROC(TIntfSortProc,IJclIntfList,TIntfCompare)}
{$JPPEXPANDMACRO SORTPROC(TAnsiStrSortProc,IJclAnsiStrList,TAnsiStrCompare)}
{$JPPEXPANDMACRO SORTPROC(TWideStrSortProc,IJclWideStrList,TWideStrCompare)}
{$IFDEF CONTAINER_ANSISTR}
TStrSortProc = TAnsiStrSortProc;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TStrSortProc = TWideStrSortProc;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO SORTPROC(TSingleSortProc,IJclSingleList,TSingleCompare)}
{$JPPEXPANDMACRO SORTPROC(TDoubleSortProc,IJclDoubleList,TDoubleCompare)}
{$JPPEXPANDMACRO SORTPROC(TExtendedSortProc,IJclExtendedList,TExtendedCompare)}
{$JPPEXPANDMACRO SORTPROC(TIntegerSortProc,IJclIntegerList,TIntegerCompare)}
{$JPPEXPANDMACRO SORTPROC(TCardinalSortProc,IJclCardinalList,TCardinalCompare)}
{$JPPEXPANDMACRO SORTPROC(TInt64SortProc,IJclInt64List,TInt64Compare)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO SORTPROC(TPtrSortProc,IJclPtrList,TPtrCompare)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO SORTPROC(TSortProc,IJclList,TCompare)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO SORTPROC(TSortProc<T>,IJclList<T>,TCompare<T>)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO ARRAY(IJclIntfArray,IJclIntfList,B055B427-7817-43FC-97D4-AD1845643D63,const ,AInterface,IInterface,GetObject,SetObject,Objects)}
{$JPPEXPANDMACRO ARRAY(IJclAnsiStrArray,IJclAnsiStrList,4953EA83-9288-4537-9D10-544D1C992B62,const ,AString,AnsiString,GetString,SetString,Strings)}
{$JPPEXPANDMACRO ARRAY(IJclWideStrArray,IJclWideStrList,3CE09F9A-5CB4-4867-80D5-C2313D278D69,const ,AString,WideString,GetString,SetString,Strings)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrArray = IJclAnsiStrArray;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrArray = IJclWideStrArray;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO ARRAY(IJclSingleArray,IJclSingleList,B96E2A4D-D750-4B65-B975-C619A05A29F6,const ,AValue,Single,GetValue,SetValue,Values)}
{$JPPEXPANDMACRO ARRAY(IJclDoubleArray,IJclDoubleList,67E66324-9757-4E85-8ECD-53396910FB39,const ,AValue,Double,GetValue,SetValue,Values)}
{$JPPEXPANDMACRO ARRAY(IJclExtendedArray,IJclExtendedList,D43E8D18-26B3-41A2-8D52-ED7EA2FE1AB7,const ,AValue,Extended,GetValue,SetValue,Values)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatArray = IJclExtendedArray;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatArray = IJclDoubleArray;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatArray = IJclSingleArray;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO ARRAY(IJclIntegerArray,IJclIntegerList,2B7C8B33-C0BD-4EC3-9764-63866E174781,,AValue,Integer,GetValue,SetValue,Values)}
{$JPPEXPANDMACRO ARRAY(IJclCardinalArray,IJclCardinalList,C451F2F8-65C6-4C29-99A0-CC9C15356418,,AValue,Cardinal,GetValue,SetValue,Values)}
{$JPPEXPANDMACRO ARRAY(IJclInt64Array,IJclInt64List,D947C43D-2D04-442A-A707-39EDE7D96FC9,const ,AValue,Int64,GetValue,SetValue,Values)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO ARRAY(IJclPtrArray,IJclPtrList,D43E8D18-26B3-41A2-8D52-ED7EA2FE1AB7,,APtr,Pointer,GetPointer,SetPointer,Pointers)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO ARRAY(IJclArray,IJclList,A69F6D35-54B2-4361-852E-097ED75E648A,,AObject,TObject,GetObject,SetObject,Objects)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO ARRAY(IJclArray<T>,IJclList<T>,38810C13-E35E-428A-B84F-D25FB994BE8E,const ,AItem,T,GetItem,SetItem,Items)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO SET(IJclIntfSet,IJclIntfCollection,E2D28852-9774-49B7-A739-5DBA2B705924)}
{$JPPEXPANDMACRO SET(IJclAnsiStrSet,IJclAnsiStrCollection,72204D85-2B68-4914-B9F2-09E5180C12E9)}
{$JPPEXPANDMACRO SET(IJclWideStrSet,IJclWideStrCollection,08009E0A-ABDD-46AB-8CEE-407D4723E17C)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrSet = IJclAnsiStrSet;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrSet = IJclWideStrSet;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO SET(IJclSingleSet,IJclSingleCollection,36E34A78-6A29-4503-97D5-4BF53538CEC0)}
{$JPPEXPANDMACRO SET(IJclDoubleSet,IJclDoubleCollection,4E1E4847-E934-4811-A26C-5FC8E772A623)}
{$JPPEXPANDMACRO SET(IJclExtendedSet,IJclExtendedCollection,3B9CF52D-1C49-4388-A7B3-9BEE1821FFD4)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatSet = IJclExtendedSet;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatSet = IJclDoubleSet;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatSet = IJclSingleSet;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO SET(IJclIntegerSet,IJclIntegerCollection,5E4D29AF-F508-465B-9008-D11FF82F25FE)}
{$JPPEXPANDMACRO SET(IJclCardinalSet,IJclCardinalCollection,09858637-CE8F-42E6-97E0-2786CD68387B)}
{$JPPEXPANDMACRO SET(IJclInt64Set,IJclInt64Collection,ACB3127A-48EE-4F9F-B988-6AE9057780E9)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO SET(IJclPtrSet,IJclPtrCollection,26717C68-4F83-4CCB-973A-7324FBD09632)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO SET(IJclSet,IJclCollection,0B7CDB90-8588-4260-A54C-D87101C669EA)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO SET(IJclSet<T>,IJclCollection<T>,0B7CDB90-8588-4260-A54C-D87101C669EA)}
{$ENDIF SUPPORTS_GENERICS}
TJclTraverseOrder = (toPreOrder, toOrder, toPostOrder);
{$JPPEXPANDMACRO TREE(IJclIntfTree,IJclIntfCollection,5A21688F-113D-41B4-A17C-54BDB0BD6559,IJclIntfTreeIterator)}
{$JPPEXPANDMACRO TREE(IJclAnsiStrTree,IJclAnsiStrCollection,1E1896C0-0497-47DF-83AF-A9422084636C,IJclAnsiStrTreeIterator)}
{$JPPEXPANDMACRO TREE(IJclWideStrTree,IJclWideStrCollection,E325615A-7A20-4788-87FA-9051002CCD91,IJclWideStrTreeIterator)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrTree = IJclAnsiStrTree;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrTree = IJclWideStrTree;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO TREE(IJclSingleTree,IJclSingleCollection,A90A51BC-EBD7-40D3-B0A0-C9987E7A83D0,IJclSingleTreeIterator)}
{$JPPEXPANDMACRO TREE(IJclDoubleTree,IJclDoubleCollection,69DA85B1-A0DD-407B-B5CF-5EB7C6D4B82D,IJclDoubleTreeIterator)}
{$JPPEXPANDMACRO TREE(IJclExtendedTree,IJclExtendedCollection,9ACCCAFD-B617-43DC-AAF9-916BE324A17E,IJclExtendedTreeIterator)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatTree = IJclExtendedTree;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatTree = IJclDoubleTree;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatTree = IJclSingleTree;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO TREE(IJclIntegerTree,IJclIntegerCollection,40A6F934-E5F3-4C74-AC02-227035C8C3C6,IJclIntegerTreeIterator)}
{$JPPEXPANDMACRO TREE(IJclCardinalTree,IJclCardinalCollection,6C76C668-50C8-42A2-B72B-79BF102E270D,IJclCardinalTreeIterator)}
{$JPPEXPANDMACRO TREE(IJclInt64Tree,IJclInt64Collection,1925B973-8B75-4A79-A993-DF2598FF19BE,IJclInt64TreeIterator)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO TREE(IJclPtrTree,IJclPtrCollection,2C1ACA3E-3F23-4E3C-984D-151CF9776E14,IJclPtrTreeIterator)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO TREE(IJclTree,IJclCollection,B0C658CC-FEF5-4178-A4C5-442C0DEDE207,IJclTreeIterator)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO TREE(IJclTree<T>,IJclCollection<T>,3F963AB5-5A75-41F9-A21B-7E7FB541A459,IJclTreeIterator<T>)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO MAP(IJclIntfIntfMap,IJclContainer,01D05399-4A05-4F3E-92F4-0C236BE77019,const ,IInterface,IJclIntfSet,IJclIntfCollection)}
(*IJclMultiIntfIntfMap = interface(IJclIntfIntfMap)
['{497775A5-D3F1-49FC-A641-15CC9E77F3D0}']
function GetValues(const Key: IInterface): IJclIntfIterator;
function Count(const Key: IInterface): Integer;
end;*)
{$JPPEXPANDMACRO MAP(IJclAnsiStrIntfMap,IJclAnsiStrContainer,A4788A96-281A-4924-AA24-03776DDAAD8A,const ,AnsiString,IJclAnsiStrSet,const ,IInterface,IJclIntfCollection)}
{$JPPEXPANDMACRO MAP(IJclWideStrIntfMap,IJclWideStrContainer,C959AB76-9CF0-4C2C-A2C6-8A1846563FAF,const ,WideString,IJclWideStrSet,const ,IInterface,IJclIntfCollection)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrIntfMap = IJclAnsiStrIntfMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrIntfMap = IJclWideStrIntfMap;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO MAP(IJclIntfAnsiStrMap,IJclAnsiStrContainer,B10E324A-1D98-42FF-B9B4-7F99044591B2,const ,IInterface,IJclIntfSet,const ,AnsiString,IJclAnsiStrCollection)}
{$JPPEXPANDMACRO MAP(IJclIntfWideStrMap,IJclWideStrContainer,D9FD7887-B840-4636-8A8F-E586663E332C,const ,IInterface,IJclIntfSet,const ,WideString,IJclWideStrCollection)}
{$IFDEF CONTAINER_ANSISTR}
IJclIntfStrMap = IJclIntfAnsiStrMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclIntfStrMap = IJclIntfWideStrMap;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO MAP(IJclAnsiStrAnsiStrMap,IJclAnsiStrContainer,A4788A96-281A-4924-AA24-03776DDAAD8A,const ,AnsiString,IJclAnsiStrSet,IJclAnsiStrCollection)}
{$JPPEXPANDMACRO MAP(IJclWideStrWideStrMap,IJclWideStrContainer,8E8D2735-C4FB-4F00-8802-B2102BCE3644,const ,WideString,IJclWideStrSet,IJclWideStrCollection)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrStrMap = IJclAnsiStrAnsiStrMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrStrMap = IJclWideStrWideStrMap;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO MAP(IJclSingleIntfMap,IJclSingleContainer,5F5E9E8B-E648-450B-B6C0-0EC65CC2D0BA,const ,Single,IJclSingleSet,const ,IInterface,IJclIntfCollection)}
{$JPPEXPANDMACRO MAP(IJclIntfSingleMap,IJclSingleContainer,234D1618-FB0E-46F5-A70D-5106163A90F7,const ,IInterface,IJclIntfSet,const ,Single,IJclSingleCollection)}
{$JPPEXPANDMACRO MAP(IJclSingleSingleMap,IJclSingleContainer,AEB0008F-F3CF-4055-A7F3-A330D312F03F,const ,Single,IJclSingleSet,IJclSingleCollection)}
{$JPPEXPANDMACRO MAP(IJclDoubleIntfMap,IJclDoubleContainer,08968FFB-36C6-4FBA-BC09-3DCA2B5D7A50,const ,Double,IJclDoubleSet,const ,IInterface,IJclIntfCollection)}
{$JPPEXPANDMACRO MAP(IJclIntfDoubleMap,IJclDoubleContainer,B23DAF6A-6DC5-4DDD-835C-CD4633DDA010,const ,IInterface,IJclIntfSet,const ,Double,IJclDoubleCollection)}
{$JPPEXPANDMACRO MAP(IJclDoubleDoubleMap,IJclDoubleContainer,329A03B8-0B6B-4FE3-87C5-4B63447A5FFD,const ,Double,IJclDoubleSet,IJclDoubleCollection)}
{$JPPEXPANDMACRO MAP(IJclExtendedIntfMap,IJclExtendedContainer,7C0731E0-C9AB-4378-B1B0-8CE3DD60AD41,const ,Extended,IJclExtendedSet,const ,IInterface,IJclIntfCollection)}
{$JPPEXPANDMACRO MAP(IJclIntfExtendedMap,IJclExtendedContainer,479FCE5A-2D8A-44EE-96BC-E8DA3187DBD8,const ,IInterface,IJclIntfSet,const ,Extended,IJclExtendedCollection)}
{$JPPEXPANDMACRO MAP(IJclExtendedExtendedMap,IJclExtendedContainer,962C2B09-8CF5-44E8-A21A-4A7DAFB72A11,const ,Extended,IJclExtendedSet,IJclExtendedCollection)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatIntfMap = IJclExtendedIntfMap;
IJclIntfFloatMap = IJclIntfExtendedMap;
IJclFloatFloatMap = IJclExtendedExtendedMap;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatIntfMap = IJclDoubleIntfMap;
IJclIntfFloatMap = IJclIntfDoubleMap;
IJclFloatFloatMap = IJclDoubleDoubleMap;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatIntfMap = IJclSingleIntfMap;
IJclIntfFloatMap = IJclIntfSingleMap;
IJclFloatFloatMap = IJclSingleSingleMap;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO MAP(IJclIntegerIntfMap,IJclContainer,E535FE65-AC88-49D3-BEF2-FB30D92C2FA6,,Integer,IJclIntegerSet,const ,IInterface,IJclIntfCollection)}
{$JPPEXPANDMACRO MAP(IJclIntfIntegerMap,IJclContainer,E01DA012-BEE0-4259-8E30-0A7A1A87BED0,const ,IInterface,IJclIntfSet,,Integer,IJclIntegerCollection)}
{$JPPEXPANDMACRO MAP(IJclIntegerIntegerMap,IJclContainer,23A46BC0-DF8D-4BD2-89D2-4DACF1EC73A1,,Integer,IJclIntegerSet,IJclIntegerCollection)}
{$JPPEXPANDMACRO MAP(IJclCardinalIntfMap,IJclContainer,80D39FB1-0D10-49CE-8AF3-1CD98A1D4F6C,,Cardinal,IJclCardinalSet,const ,IInterface,IJclIntfCollection)}
{$JPPEXPANDMACRO MAP(IJclIntfCardinalMap,IJclContainer,E1A724AB-6BDA-45F0-AE21-5E7E789A751B,const ,IInterface,IJclIntfSet,,Cardinal,IJclCardinalCollection)}
{$JPPEXPANDMACRO MAP(IJclCardinalCardinalMap,IJclContainer,1CD3F54C-F92F-4AF4-82B2-0829C08AA83B,,Cardinal,IJclCardinalSet,IJclCardinalCollection)}
{$JPPEXPANDMACRO MAP(IJclInt64IntfMap,IJclContainer,B64FB2D1-8D45-4367-B950-98D3D05AC6A0,const ,Int64,IJclInt64Set,const ,IInterface,IJclIntfCollection)}
{$JPPEXPANDMACRO MAP(IJclIntfInt64Map,IJclContainer,9886BEE3-D15B-45D2-A3FB-4D3A0ADEC8AC,const ,IInterface,IJclIntfSet,const ,Int64,IJclInt64Collection)}
{$JPPEXPANDMACRO MAP(IJclInt64Int64Map,IJclContainer,EF2A2726-408A-4984-9971-DDC1B6EFC9F5,const ,Int64,IJclInt64Set,IJclInt64Collection)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO MAP(IJclPtrIntfMap,IJclContainer,B7C48542-39A0-453F-8F03-8C8CFAB0DCCF,,Pointer,IJclPtrSet,const ,IInterface,IJclIntfCollection)}
{$JPPEXPANDMACRO MAP(IJclIntfPtrMap,IJclContainer,DA51D823-58DB-4D7C-9B8E-07E0FD560B57,const ,IInterface,IJclIntfSet,,Pointer,IJclPtrCollection)}
{$JPPEXPANDMACRO MAP(IJclPtrPtrMap,IJclContainer,1200CB0F-A766-443F-9030-5A804C11B798,,Pointer,IJclPtrSet,IJclPtrCollection)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO MAP(IJclIntfMap,IJclContainer,C70570C6-EDDB-47B4-9003-C637B486731D,const ,IInterface,IJclIntfSet,,TObject,IJclCollection)}
{$JPPEXPANDMACRO MAP(IJclAnsiStrMap,IJclAnsiStrContainer,A7D0A882-6952-496D-A258-23D47DDCCBC4,const ,AnsiString,IJclAnsiStrSet,,TObject,IJclCollection)}
{$JPPEXPANDMACRO MAP(IJclWideStrMap,IJclWideStrContainer,ACE8E6B4-5A56-4753-A2C6-BAE195A56B63,const ,WideString,IJclWideStrSet,,TObject,IJclCollection)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrMap = IJclAnsiStrMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrMap = IJclWideStrMap;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO MAP(IJclSingleMap,IJclSingleContainer,C501920A-F252-4F94-B142-1F05AE06C3D2,const ,Single,IJclSingleSet,,TObject,IJclCollection)}
{$JPPEXPANDMACRO MAP(IJclDoubleMap,IJclDoubleContainer,B1B994AC-49C9-418B-814B-43BAD706F355,const ,Double,IJclDoubleSet,,TObject,IJclCollection)}
{$JPPEXPANDMACRO MAP(IJclExtendedMap,IJclExtendedContainer,3BCC8C87-A186-45E8-9B37-0B8E85120434,const ,Extended,IJclExtendedSet,,TObject,IJclCollection)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatMap = IJclExtendedMap;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatMap = IJclDoubleMap;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatMap = IJclSingleMap;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO MAP(IJclIntegerMap,IJclContainer,D6FA5D64-A4AF-4419-9981-56BA79BF8770,,Integer,IJclIntegerSet,,TObject,IJclCollection)}
{$JPPEXPANDMACRO MAP(IJclCardinalMap,IJclContainer,A2F92F4F-11CB-4DB2-932F-F10A14237126,,Cardinal,IJclCardinalSet,,TObject,IJclCollection)}
{$JPPEXPANDMACRO MAP(IJclInt64Map,IJclContainer,4C720CE0-7A7C-41D5-BFC1-8D58A47E648F,const ,Int64,IJclInt64Set,,TObject,IJclCollection)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO MAP(IJclPtrMap,IJclContainer,2FE029A9-026C-487D-8204-AD3A28BD2FA2,,Pointer,IJclPtrSet,,TObject,IJclCollection)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO MAP(IJclMap,IJclContainer,A7D0A882-6952-496D-A258-23D47DDCCBC4,,TObject,IJclSet,IJclCollection)}
{$IFDEF SUPPORTS_GENERICS}
IHashable = interface
function GetHashCode: Integer;
end;
{$JPPEXPANDMACRO MAP(IJclMap<TKey\,TValue>,IJclContainer,22624C43-4828-4A1E-BDD4-4A7FE59AE135,const ,TKey,IJclSet<TKey>,const ,TValue,IJclCollection<TValue>)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO QUEUE(IJclIntfQueue,IJclContainer,B88756FE-5553-4106-957E-3E33120BFA99,const ,AInterface,IInterface)}
{$JPPEXPANDMACRO QUEUE(IJclAnsiStrQueue,IJclAnsiStrContainer,5BA0ED9A-5AF3-4F79-9D80-34FA7FF15D1F,const ,AString,AnsiString)}
{$JPPEXPANDMACRO QUEUE(IJclWideStrQueue,IJclWideStrContainer,058BBFB7-E9B9-44B5-B676-D5B5B9A79BEF,const ,AString,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrQueue = IJclAnsiStrQueue;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrQueue = IJclWideStrQueue;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO QUEUE(IJclSingleQueue,IJclSingleContainer,67D74314-9967-4C99-8A48-6E0ADD73EC29,const ,AValue,Single)}
{$JPPEXPANDMACRO QUEUE(IJclDoubleQueue,IJclDoubleContainer,FA1B6D25-3456-4963-87DC-5A2E53B2963F,const ,AValue,Double)}
{$JPPEXPANDMACRO QUEUE(IJclExtendedQueue,IJclExtendedContainer,76F349C0-7681-4BE8-9E94-280C962780D8,const ,AValue,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatQueue = IJclExtendedQueue;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatQueue = IJclDoubleQueue;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatQueue = IJclSingleQueue;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO QUEUE(IJclIntegerQueue,IJclContainer,4C4E174E-5D19-44CE-A248-B5589A9B68DF,,AValue,Integer)}
{$JPPEXPANDMACRO QUEUE(IJclCardinalQueue,IJclContainer,CC1D4358-E259-4FB0-BA83-5180A0F8A6C0,,AValue,Cardinal)}
{$JPPEXPANDMACRO QUEUE(IJclInt64Queue,IJclContainer,96B620BB-9A90-43D5-82A7-2D818A11C8E1,const ,AValue,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO QUEUE(IJclPtrQueue,IJclContainer,1052DD37-3035-4C44-A793-54AC4B9C0B29,,APtr,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO QUEUE(IJclQueue,IJclContainer,7D0F9DE4-71EA-46EF-B879-88BCFD5D9610,,AObject,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO QUEUE(IJclQueue<T>,IJclContainer,16AB909F-2194-46CF-BD89-B4207AC0CAB8,const ,AItem,T)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfIntfSortedMap,IJclIntfIntfMap,265A6EB2-4BB3-459F-8813-360FD32A4971,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclAnsiStrIntfSortedMap,IJclAnsiStrIntfMap,706D1C91-5416-4FDC-B6B1-F4C1E8CFCD38,const ,AnsiString)}
{$JPPEXPANDMACRO SORTEDMAP(IJclWideStrIntfSortedMap,IJclWideStrIntfMap,299FDCFD-2DB7-4D64-BF18-EE3668316430,const ,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrIntfSortedMap = IJclAnsiStrIntfSortedMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrIntfSortedMap = IJclWideStrIntfSortedMap;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfAnsiStrSortedMap,IJclIntfAnsiStrMap,96E6AC5E-8C40-4795-9C8A-CFD098B58680,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfWideStrSortedMap,IJclIntfWideStrMap,FBE3AD2E-2781-4DC0-9E80-027027380E21,const ,IInterface)}
{$IFDEF CONTAINER_ANSISTR}
IJclIntfStrSortedMap = IJclIntfAnsiStrSortedMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclIntfStrSortedMap = IJclIntfWideStrSortedMap;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO SORTEDMAP(IJclAnsiStrAnsiStrSortedMap,IJclAnsiStrAnsiStrMap,4F457799-5D03-413D-A46C-067DC4200CC3,const ,AnsiString)}
{$JPPEXPANDMACRO SORTEDMAP(IJclWideStrWideStrSortedMap,IJclWideStrWideStrMap,3B0757B2-2290-4AFA-880D-F9BA600E501E,const ,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrStrSortedMap = IJclAnsiStrAnsiStrSortedMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrStrSortedMap = IJclWideStrWideStrSortedMap;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO SORTEDMAP(IJclSingleIntfSortedMap,IJclSingleIntfMap,83D57068-7B8E-453E-B35B-2AB4B594A7A9,const ,Single)}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfSingleSortedMap,IJclIntfSingleMap,B07FA192-3466-4F2A-BBF0-2DC0100B08A8,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclSingleSingleSortedMap,IJclSingleSingleMap,7C6EA0B4-959D-44D5-915F-99DFC1753B00,const ,Single)}
{$JPPEXPANDMACRO SORTEDMAP(IJclDoubleIntfSortedMap,IJclDoubleIntfMap,F36C5F4F-4F8C-4943-AA35-41623D3C21E9,const ,Double)}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfDoubleSortedMap,IJclIntfDoubleMap,0F16ADAE-F499-4857-B5EA-6F3CC9009DBA,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclDoubleDoubleSortedMap,IJclDoubleDoubleMap,855C858B-74CF-4338-872B-AF88A02DB537,const ,Double)}
{$JPPEXPANDMACRO SORTEDMAP(IJclExtendedIntfSortedMap,IJclExtendedIntfMap,A30B8835-A319-4776-9A11-D1EEF60B9C26,const ,Extended)}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfExtendedSortedMap,IJclIntfExtendedMap,3493D6C4-3075-48B6-8E99-CB0000D3978C,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclExtendedExtendedSortedMap,IJclExtendedExtendedMap,8CAA505C-D9BB-47E7-92EC-6043DC4AF42C,const ,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatIntfSortedMap = IJclExtendedIntfSortedMap;
IJclIntfFloatSortedMap = IJclIntfExtendedSortedMap;
IJclFloatFloatSortedMap = IJclExtendedExtendedSortedMap;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatIntfSortedMap = IJclDoubleIntfSortedMap;
IJclIntfFloatSortedMap = IJclIntfDoubleSortedMap;
IJclFloatFloatSortedMap = IJclDoubleDoubleSortedMap;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatIntfSortedMap = IJclSingleIntfSortedMap;
IJclIntfFloatSortedMap = IJclIntfSingleSortedMap;
IJclFloatFloatSortedMap = IJclSingleSingleSortedMap;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntegerIntfSortedMap,IJclIntegerIntfMap,8B22802C-61F2-4DA5-B1E9-DBB7840E7996,,Integer)}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfIntegerSortedMap,IJclIntfIntegerMap,8D3C9B7E-772D-409B-A58C-0CABFAFDEFF0,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntegerIntegerSortedMap,IJclIntegerIntegerMap,8A8BA17A-F468-469C-AF99-77D64C802F7A,,Integer)}
{$JPPEXPANDMACRO SORTEDMAP(IJclCardinalIntfSortedMap,IJclCardinalIntfMap,BAE97425-4F2E-461B-88DD-F83D27657AFA,,Cardinal)}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfCardinalSortedMap,IJclIntfCardinalMap,BC66BACF-23AE-48C4-9573-EDC3B5110BE7,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclCardinalCardinalSortedMap,IJclCardinalCardinalMap,182ACDA4-7D74-4D29-BB5C-4C8189DA774E,,Cardinal)}
{$JPPEXPANDMACRO SORTEDMAP(IJclInt64IntfSortedMap,IJclInt64IntfMap,24391756-FB02-4901-81E3-A37738B73DAD,const ,Int64)}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfInt64SortedMap,IJclIntfInt64Map,6E2AB647-59CC-4609-82E8-6AE75AED80CA,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclInt64Int64SortedMap,IJclInt64Int64Map,168581D2-9DD3-46D0-934E-EA0CCE5E3C0C,const ,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO SORTEDMAP(IJclPtrIntfSortedMap,IJclPtrIntfMap,6D7B8042-3CBC-4C8F-98B5-69AFAA104532,,Pointer)}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfPtrSortedMap,IJclIntfPtrMap,B054BDA2-536F-4C16-B6BB-BB64FA0818B3,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclPtrPtrSortedMap,IJclPtrPtrMap,F1FAE922-0212-41D0-BB4E-76A8AB2CAB86,,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntfSortedMap,IJclIntfMap,3CED1477-B958-4109-9BDA-7C84B9E063B2,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDMAP(IJclAnsiStrSortedMap,IJclAnsiStrMap,573F98E3-EBCD-4F28-8F35-96A7366CBF47,const ,AnsiString)}
{$JPPEXPANDMACRO SORTEDMAP(IJclWideStrSortedMap,IJclWideStrMap,B3021EFC-DE25-4B4B-A896-ACE823CD5C01,const ,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrSortedMap = IJclAnsiStrSortedMap;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrSortedMap = IJclWideStrSortedMap;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO SORTEDMAP(IJclSingleSortedMap,IJclSingleMap,8C1A12BE-A7F2-4351-90B7-25DB0AAF5F94,const ,Single)}
{$JPPEXPANDMACRO SORTEDMAP(IJclDoubleSortedMap,IJclDoubleMap,8018D66B-AA54-4016-84FC-3E780FFCC38B,const ,Double)}
{$JPPEXPANDMACRO SORTEDMAP(IJclExtendedSortedMap,IJclExtendedMap,2B82C65A-B3EF-477D-BEC0-3D8620A226B1,const ,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatSortedMap = IJclExtendedSortedMap;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatSortedMap = IJclDoubleSortedMap;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatSortedMap = IJclSingleSortedMap;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO SORTEDMAP(IJclIntegerSortedMap,IJclIntegerMap,DD7B4C5E-6D51-44CC-9328-B38396A7E1C9,,Integer)}
{$JPPEXPANDMACRO SORTEDMAP(IJclCardinalSortedMap,IJclCardinalMap,4AEAF81F-D72E-4499-B10E-3D017F39915E,,Cardinal)}
{$JPPEXPANDMACRO SORTEDMAP(IJclInt64SortedMap,IJclInt64Map,06C03F90-7DE9-4043-AA56-AAE071D8BD50,const ,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO SORTEDMAP(IJclPtrSortedMap,IJclPtrMap,578918DB-6A4A-4A9D-B44E-AE3E8FF70818,,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO SORTEDMAP(IJclSortedMap,IJclMap,F317A70F-7851-49C2-9DCF-092D8F4D4F98,,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO SORTEDMAP(IJclSortedMap<TKey\,TValue>,IJclMap<TKey\,TValue>,C62B75C4-891B-442E-A5D6-9954E75A5C0C,const ,TKey)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO SORTEDSET(IJclIntfSortedSet,IJclIntfSet,159BE5A7-7349-42FF-BE55-9CA1B9DBA991,const ,IInterface)}
{$JPPEXPANDMACRO SORTEDSET(IJclAnsiStrSortedSet,IJclAnsiStrSet,03198146-F967-4310-868B-7AD3D52D5CBE,const ,AnsiString)}
{$JPPEXPANDMACRO SORTEDSET(IJclWideStrSortedSet,IJclWideStrSet,ED9567E2-C1D3-4C00-A1D4-90D5C7E27C2D,const ,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrSortedSet = IJclAnsiStrSortedSet;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrSortedSet = IJclWideStrSortedSet;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO SORTEDSET(IJclSingleSortedSet,IJclSingleSet,65EDA801-9E04-4119-BF9E-D7DD4AF82144,const ,Single)}
{$JPPEXPANDMACRO SORTEDSET(IJclDoubleSortedSet,IJclDoubleSet,DA0E689F-BAFE-4BCE-85E4-C38E780BC84C,const ,Double)}
{$JPPEXPANDMACRO SORTEDSET(IJclExtendedSortedSet,IJclExtendedSet,A9875ED3-81A4-43A3-86BB-3429F51B278B,const ,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatSortedSet = IJclExtendedSortedSet;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatSortedSet = IJclDoubleSortedSet;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatSortedSet = IJclSingleSortedSet;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO SORTEDSET(IJclIntegerSortedSet,IJclIntegerSet,E086C54B-4FA3-426D-AC4E-FF8E8CA3D663,,Integer)}
{$JPPEXPANDMACRO SORTEDSET(IJclCardinalSortedSet,IJclCardinalSet,2D7995C6-A784-48B6-87E9-55D394A72362,,Cardinal)}
{$JPPEXPANDMACRO SORTEDSET(IJclInt64SortedSet,IJclInt64Set,4C1C3FCA-6169-4A2F-B044-91AC2AA2E954,const ,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO SORTEDSET(IJclPtrSortedSet,IJclPtrSet,F3A3183C-0820-425C-9446-E0838F0ADAD8,,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO SORTEDSET(IJclSortedSet,IJclSet,A3D23E76-ADE9-446C-9B97-F49FCE895D9F,,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO SORTEDSET(IJclSortedSet<T>,IJclSet<T>,30F836E3-2FB1-427E-A499-DFAE201633C8,const ,T)}
{$ENDIF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO STACK(IJclIntfStack,IJclContainer,CA1DC7A1-8D8F-4A5D-81D1-0FE32E9A4E84,const ,AInterface,IInterface)}
{$JPPEXPANDMACRO STACK(IJclAnsiStrStack,IJclAnsiStrContainer,649BB74C-D7BE-40D9-9F4E-32DDC3F13F3B,const ,AString,AnsiString)}
{$JPPEXPANDMACRO STACK(IJclWideStrStack,IJclWideStrContainer,B2C3B165-33F1-4B7D-A2EC-0B19D12CE33C,const ,AString,WideString)}
{$IFDEF CONTAINER_ANSISTR}
IJclStrStack = IJclAnsiStrStack;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
IJclStrStack = IJclWideStrStack;
{$ENDIF CONTAINER_WIDESTR}
{$JPPEXPANDMACRO STACK(IJclSingleStack,IJclSingleContainer,8DCE45C8-B5B3-43AB-BA08-DAD531CEB9CF,const ,AValue,Single)}
{$JPPEXPANDMACRO STACK(IJclDoubleStack,IJclDoubleContainer,46DF2701-16F0-453C-B938-F04E9C1CEBF8,const ,AValue,Double)}
{$JPPEXPANDMACRO STACK(IJclExtendedStack,IJclExtendedContainer,A2A30585-F561-4757-ABE1-CA511AE72CC5,const ,AValue,Extended)}
{$IFDEF MATH_EXTENDED_PRECISION}
IJclFloatStack = IJclExtendedStack;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
IJclFloatStack = IJclDoubleStack;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
IJclFloatStack = IJclSingleStack;
{$ENDIF MATH_SINGLE_PRECISION}
{$JPPEXPANDMACRO STACK(IJclIntegerStack,IJclContainer,9190BF0E-5B0C-4D6C-A107-20A933C9B56A,,AValue,Integer)}
{$JPPEXPANDMACRO STACK(IJclCardinalStack,IJclContainer,94F9EDB3-602B-49CE-9990-0AFDAC556F83,,AValue,Cardinal)}
{$JPPEXPANDMACRO STACK(IJclInt64Stack,IJclContainer,D689EB8F-2746-40E9-AD1B-7E656475FC64,const ,AValue,Int64)}
{$IFNDEF CLR}
{$JPPEXPANDMACRO STACK(IJclPtrStack,IJclContainer,AD11D06C-E0E1-4EDE-AA2F-BC8BDD972B73,,APtr,Pointer)}
{$ENDIF ~CLR}
{$JPPEXPANDMACRO STACK(IJclStack,IJclContainer,E07E0BD8-A831-41B9-B9A0-7199BD4873B9,,AObject,TObject)}
{$IFDEF SUPPORTS_GENERICS}
{$JPPEXPANDMACRO STACK(IJclStack<T>,IJclContainer,2F08EAC9-270D-496E-BE10-5E975918A5F2,const ,AItem,T)}
{$ENDIF SUPPORTS_GENERICS}
// Exceptions
EJclContainerError = class(EJclError);
EJclOutOfBoundsError = class(EJclContainerError)
public
// RsEOutOfBounds
constructor Create;
end;
EJclNoSuchElementError = class(EJclContainerError)
public
// RsEValueNotFound
constructor Create(const Value: string);
end;
EJclDuplicateElementError = class(EJclContainerError)
public
// RsEDuplicateElement
constructor Create;
end;
EJclIllegalArgumentError = class(EJclContainerError)
end;
EJclNoCollectionError = class(EJclIllegalArgumentError)
public
// RsENoCollection
constructor Create;
end;
EJclIllegalQueueCapacityError = class(EJclIllegalArgumentError)
public
// RsEIllegalQueueCapacity
constructor Create;
end;
EJclOperationNotSupportedError = class(EJclContainerError)
public
// RsEOperationNotSupported
constructor Create;
end;
EJclNoEqualityComparerError = class(EJclContainerError)
public
// RsENoEqualityComparer
constructor Create;
end;
EJclNoComparerError = class(EJclContainerError)
public
// RsENoComparer
constructor Create;
end;
EJclNoHashConverterError = class(EJclContainerError)
public
// RsENoHashConverter
constructor Create;
end;
EJclIllegalStateOperationError = class(EJclContainerError)
public
// RsEIllegalStateOperation
constructor Create;
end;
EJclAssignError = class(EJclContainerError)
public
// RsEAssignError
constructor Create;
end;
EJclReadOnlyError = class(EJclContainerError)
public
// RsEReadOnlyError
constructor Create;
end;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclContainerIntf.pas $';
Revision: '$Revision: 2309 $';
Date: '$Date: 2008-01-15 23:30:26 +0100 (mar., 15 janv. 2008) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils,
JclResources;
//=== { EJclOutOfBoundsError } ===============================================
constructor EJclOutOfBoundsError.Create;
begin
{$IFDEF CLR}
inherited Create(RsEOutOfBounds);
{$ELSE ~CLR}
inherited CreateRes(@RsEOutOfBounds);
{$ENDIF ~CLR}
end;
//=== { EJclNoSuchElementError } =============================================
constructor EJclNoSuchElementError.Create(const Value: string);
begin
{$IFDEF CLR}
inherited Create(Format(RsEValueNotFound, [Value]));
{$ELSE ~CLR}
inherited CreateResFmt(@RsEValueNotFound, [Value]);
{$ENDIF ~CLR}
end;
//=== { EJclDuplicateElementError } ==========================================
constructor EJclDuplicateElementError.Create;
begin
{$IFDEF CLR}
inherited Create(RsEDuplicateElement);
{$ELSE ~CLR}
inherited CreateRes(@RsEDuplicateElement);
{$ENDIF ~CLR}
end;
//=== { EJclIllegalQueueCapacityError } ======================================
constructor EJclIllegalQueueCapacityError.Create;
begin
{$IFDEF CLR}
inherited Create(RsEIllegalQueueCapacity);
{$ELSE ~CLR}
inherited CreateRes(@RsEIllegalQueueCapacity);
{$ENDIF ~CLR}
end;
//=== { EJclNoCollectionError } ==============================================
constructor EJclNoCollectionError.Create;
begin
{$IFDEF CLR}
inherited Create(RsENoCollection);
{$ELSE ~CLR}
inherited CreateRes(@RsENoCollection);
{$ENDIF ~CLR}
end;
//=== { EJclOperationNotSupportedError } =====================================
constructor EJclOperationNotSupportedError.Create;
begin
{$IFDEF CLR}
inherited Create(RsEOperationNotSupported);
{$ELSE ~CLR}
inherited CreateRes(@RsEOperationNotSupported);
{$ENDIF ~CLR}
end;
//=== { EJclIllegalStateOperationError } =====================================
constructor EJclIllegalStateOperationError.Create;
begin
{$IFDEF CLR}
inherited Create(RsEIllegalStateOperation);
{$ELSE ~CLR}
inherited CreateRes(@RsEIllegalStateOperation);
{$ENDIF ~CLR}
end;
//=== { EJclNoComparerError } ================================================
constructor EJclNoComparerError.Create;
begin
{$IFDEF CLR}
inherited Create(RsENoComparer);
{$ELSE ~CLR}
inherited CreateRes(@RsENoComparer);
{$ENDIF ~CLR}
end;
//=== { EJclNoEqualityComparerError } ========================================
constructor EJclNoEqualityComparerError.Create;
begin
{$IFDEF CLR}
inherited Create(RsENoEqualityComparer);
{$ELSE ~CLR}
inherited CreateRes(@RsENoEqualityComparer);
{$ENDIF ~CLR}
end;
//=== { EJclNoHashConverterError } ===========================================
constructor EJclNoHashConverterError.Create;
begin
{$IFDEF CLR}
inherited Create(RsENoHashConverter);
{$ELSE ~CLR}
inherited CreateRes(@RsENoHashConverter);
{$ENDIF ~CLR}
end;
//=== { EJclAssignError } ====================================================
constructor EJclAssignError.Create;
begin
{$IFDEF CLR}
inherited Create(RsEAssignError);
{$ELSE ~CLR}
inherited CreateRes(@RsEAssignError);
{$ENDIF ~CLR}
end;
//=== { EJclReadOnlyError } ==================================================
constructor EJclReadOnlyError.Create;
begin
{$IFDEF CLR}
inherited Create(RsEReadOnlyError);
{$ELSE ~CLR}
inherited CreateRes(@RsEReadOnlyError);
{$ENDIF ~CLR}
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
unit frmLiquidacionFiniquito;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DateUtils,
Grids, DBGrids, ExtCtrls, DBCtrls, ZAbstractRODataset, ZAbstractDataset,
ZAbstractTable, ZDataset, NxScrollControl, NxCustomGridControl, NxCustomGrid,
NxDBGrid, NxDBColumns, NxColumns, StdCtrls, Mask, frm_barra, global,
NxCollection, AdvGlowButton, dblookup, JvExControls, JvDBLookup,
AdvDBLookupComboBox, Menus, frxClass, frxDBSet, RxMemDS, utilerias, masUtilerias,
StrUtils;
type
Tfrm_LiqFini = class(TForm)
headerFiniquito: TNxHeaderPanel;
headerLiquidacion: TNxHeaderPanel;
chxLiquidacion: TCheckBox;
chxFiniquito: TCheckBox;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
txtPrimaVacacional: TDBEdit;
txtAguinaldo: TDBEdit;
txtIsrFiniquito: TDBEdit;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
txtIndemnizacion: TDBEdit;
txt20dias: TDBEdit;
txtAntiguedad: TDBEdit;
txtIsrLiquidacion: TDBEdit;
GroupBox2: TGroupBox;
Label6: TLabel;
txtVacDiasTrabajados: TDBEdit;
Label17: TLabel;
txtVacDiasTomados: TDBEdit;
Label18: TLabel;
txtVacPagar: TDBEdit;
GroupBox1: TGroupBox;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
btnCalcularLiqFin: TAdvGlowButton;
btnImprimirLiqFin: TAdvGlowButton;
rbtImss: TRadioButton;
rbtSueldo: TRadioButton;
Label15: TLabel;
Label16: TLabel;
txtMontoFiniquito: TDBEdit;
Label19: TLabel;
txtMontoLiquidacion: TDBEdit;
GroupBox3: TGroupBox;
Label14: TLabel;
Label1: TLabel;
txtIsrAnterior: TDBEdit;
qryFiniquito: TZQuery;
dsFiniquito: TDataSource;
dsDatosGenerales: TDataSource;
qryDatosGenerales: TZQuery;
dsLiquidacion: TDataSource;
qryLiquidacion: TZQuery;
txtSalDiario: TDBEdit;
txtSalMensual: TDBEdit;
txtSalDiarioInt: TDBEdit;
txtSalMensualInt: TDBEdit;
Label20: TLabel;
lblEmpleado: TLabel;
qryDeduccionesEmpleado: TZQuery;
dsDeduccionesEmpleado: TDataSource;
Label21: TLabel;
txtVacaciones: TDBEdit;
lblEliminarFiniquito: TLabel;
lblEliminarLiquidacion: TLabel;
cbxIsr: TDBLookupComboBox;
qryDeduccionesEmpleadoiId: TIntegerField;
qryDeduccionesEmpleadosNombre: TStringField;
qryDeduccionesEmpleadodImporte: TFloatField;
rReportes: TfrxReport;
fdsFiniquito: TfrxDBDataset;
PopupImprimir: TPopupMenu;
Finiquito1: TMenuItem;
Liquidacin1: TMenuItem;
fdsLiquidacion: TfrxDBDataset;
qryLiquidacioniId: TIntegerField;
qryLiquidacionsIdEmpleado: TStringField;
qryLiquidaciondISRAnterior: TFloatField;
qryLiquidaciondIndemnizacion: TFloatField;
qryLiquidaciond20Dias: TFloatField;
qryLiquidaciondPrimaAntiguedad: TFloatField;
qryLiquidaciondMontoLiquidacion: TFloatField;
qryLiquidaciondISRLiquidacion: TFloatField;
qryLiquidacioniIdDeduccion: TLargeintField;
qryLiquidacionfFecha: TDateField;
qryFiniquitoiId: TIntegerField;
qryFiniquitosIdEmpleado: TStringField;
qryFiniquitoiVacacionesDiasTrabajados: TIntegerField;
qryFiniquitoiVacacionesDiasTomados: TIntegerField;
qryFiniquitoiVacacionesDiasPagar: TIntegerField;
qryFiniquitodPrimaVac: TFloatField;
qryFiniquitodAguinaldo: TFloatField;
qryFiniquitodMontoFiniquito: TFloatField;
qryFiniquitodISRFiniquito: TFloatField;
qryFiniquitodVacaciones: TFloatField;
qryFiniquitofFecha: TDateField;
qryDatosGeneralesiId: TIntegerField;
qryDatosGeneralessIdEmpleado: TStringField;
qryDatosGeneralesdSaldoDiario: TFloatField;
qryDatosGeneralesdSaldoDiarioIntegrado: TFloatField;
qryDatosGeneralesdSaldoMensual: TFloatField;
qryDatosGeneralesdSaldoMensualIntegrado: TFloatField;
qryDatosGeneralessOpcion: TStringField;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure rbtImssClick(Sender: TObject);
procedure datosGenerales;
function quitaComas(cadena :string) : Double;
procedure Inicializa_Valores_Finiquito;
procedure Calculo_Liquidacion();
procedure Calculo_Finiquito();
procedure variables_Liquidacion_Finiquito;
procedure despues_eliminar;
procedure rbtSueldoClick(Sender: TObject);
procedure txtVacDiasTomadosKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure chxFiniquitoClick(Sender: TObject);
procedure chxLiquidacionClick(Sender: TObject);
procedure cbxIsrClick(Sender: TObject);
procedure lblEliminarFiniquitoMouseEnter(Sender: TObject);
procedure lblEliminarLiquidacionMouseEnter(Sender: TObject);
procedure lblEliminarLiquidacionMouseLeave(Sender: TObject);
procedure lblEliminarFiniquitoMouseLeave(Sender: TObject);
procedure lblEliminarFiniquitoClick(Sender: TObject);
procedure lblEliminarLiquidacionClick(Sender: TObject);
procedure btnImprimirLiqFinClick(Sender: TObject);
procedure Finiquito1Click(Sender: TObject);
procedure Liquidacin1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_LiqFini: Tfrm_LiqFini;
salario_diario, salario_diario_integrado : double;
salario_mensual, salario_mensual_integrado : double;
anios_laborados, anios_laborados_mas1, dias_proporcionales_aguinaldo, dias_proporcionales, dias_vacaciones : Integer;
total_finiquito, total_liquidacion, isr_finiquito, isr_liquidacion : double;
vacaciones, primavac, aguinaldo : double;
dias20, prima, Indemnizacion : double;
wAnyo, wMes, wDia: Word;
sIdEmpleado, sql, sOpcion: String;
calculo, Error : Boolean;
query : TZQuery;
implementation
uses frm_connection, frmEmpleados;
{$R *.dfm}
procedure Tfrm_LiqFini.Finiquito1Click(Sender: TObject);
var
dia, mes, anio, diaf, mesf, aniof, dia_ini, mes_ini, anio_ini : Word;
monto, decimales : double;
begin
if qryFiniquito.RecordCount > 0 then begin
DecodeDate(now, anio, mes, dia);
DecodeDate(frm_Empleados.zQEmpleados.FieldByName('dFechaTerminoLabores').AsDateTime, aniof, mesf, diaf);
DecodeDate(frm_Empleados.zQEmpleados.FieldByName('dFechaInicioLabores').AsDateTime, anio_ini, mes_ini, dia_ini);
rReportes.PreviewOptions.MDIChild := True ;
rReportes.PreviewOptions.Modal := False ;
rReportes.PreviewOptions.Maximized := lCheckMaximized () ;
rReportes.PreviewOptions.ShowCaptions := False ;
rReportes.Previewoptions.ZoomMode := zmPageWidth ;
rReportes.DataSet := fdsFiniquito;
rReportes.DataSetName := 'fdsFiniquito';
rReportes.LoadFromFile (global_files + 'Reporte_Finiquito.fr3') ;
rReportes.Variables.Variables['dia'] := dia;
rReportes.Variables.Variables['mes'] := QuotedStr(esMes(mes));
rReportes.Variables.Variables['anio'] := anio;
rReportes.Variables.Variables['dia_fin'] := diaf;
rReportes.Variables.Variables['mes_fin'] := QuotedStr(esMes(mesf));
rReportes.Variables.Variables['anio_fin'] := aniof;
rReportes.Variables.Variables['dia_ini'] := dia_ini;
rReportes.Variables.Variables['mes_ini'] := QuotedStr(esMes(mes_ini));
rReportes.Variables.Variables['anio_ini'] := anio_ini;
monto := (qryFiniquito.FieldByName('dMontoFiniquito').AsFloat - qryFiniquito.FieldByName('dISRFiniquito').AsFloat);
rReportes.Variables.Variables['monto'] := monto;
rReportes.Variables.Variables['monto_letras'] := QuotedStr(xIntToLletres(trunc(monto)));
decimales := monto - trunc(monto);
if decimales > 0 then
rReportes.Variables.Variables['decimales'] := AnsiMidStr(FloatToStr(decimales),3,2)
else
rReportes.Variables.Variables['decimales'] := AnsiMidStr(FloatToStr(decimales),4,2);
rReportes.Variables.Variables['nombre'] := QuotedStr(frm_Empleados.zQEmpleados.FieldByName('sNombreCompleto').AsString);
rReportes.ShowReport() ;
end;
end;
procedure Tfrm_LiqFini.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
action := cafree ;
end;
procedure Tfrm_LiqFini.FormShow(Sender: TObject);
begin
lblEmpleado.Caption := frm_Empleados.zQEmpleados.FieldByName('sNombreCompleto').AsString;
sIdEmpleado := frm_Empleados.zQEmpleados.FieldByName('sIdEmpleado').AsString;
calculo := False;
Error := False;
qryDatosGenerales.Active := False;
qryDatosGenerales.Params.ParamByName('Empleado').AsString := sIdEmpleado;
qryDatosGenerales.Open;
qryFiniquito.Active := False;
qryFiniquito.Params.ParamByName('Empleado').AsString := sIdEmpleado;
qryFiniquito.Open;
qryLiquidacion.Active := False;
qryLiquidacion.Params.ParamByName('Empleado').AsString := sIdEmpleado;
qryLiquidacion.Open;
qryDeduccionesEmpleado.Active := False;
qryDeduccionesEmpleado.Params.ParamByName('Empleado').AsString := sIdEmpleado;
qryDeduccionesEmpleado.Open;
variables_Liquidacion_Finiquito;
if qryDatosGenerales.RecordCount > 0 then begin
if qryDatosGenerales.FieldByName('sOpcion').AsString = 'imss' then begin
rbtImss.Checked := True;
rbtSueldo.Enabled := False;
end
else begin
rbtSueldo.Checked := True;
rbtImss.Enabled := False;
end;
salario_diario := qryDatosGenerales.FieldByName('dSaldoDiario').AsFloat;
salario_diario_integrado := qryDatosGenerales.FieldByName('dSaldoDiarioIntegrado').AsFloat;
salario_mensual := qryDatosGenerales.FieldByName('dSaldoMensual').AsFloat;
salario_mensual_integrado := qryDatosGenerales.FieldByName('dSaldoMensualIntegrado').AsFloat;
txtSalDiario.Text := Format('%m', [salario_diario]);
txtSalDiarioInt.Text := Format('%m', [salario_diario_integrado]);
txtSalMensual.Text := Format('%m', [salario_mensual]);
txtSalMensualInt.Text := Format('%m', [salario_mensual_integrado]);
btnImprimirLiqFin.Enabled := True;
end
else begin
datosGenerales;
btnImprimirLiqFin.Enabled := False;
end;
Inicializa_Valores_Finiquito;
if qryLiquidacion.RecordCount > 0 then begin
txtIsrAnterior.Text := qryLiquidacion.FieldByName('dISRAnterior').AsString;
lblEliminarLiquidacion.Visible := True;
end;
txtVacDiasTomados.Enabled := False;
txtVacPagar.Enabled := False;
cbxIsr.Enabled := False;
txtIsrAnterior.Enabled := False;
query := TZQuery.Create(self);
query.Connection := Connection.zConnection;
end;
procedure Tfrm_LiqFini.rbtImssClick(Sender: TObject);
begin
datosGenerales;
end;
procedure Tfrm_LiqFini.rbtSueldoClick(Sender: TObject);
var
proporcion_prima_vacacional, proporcion_aguinaldo : double;
begin
salario_mensual := quitaComas(FloatToStrF(frm_Empleados.zQEmpleados.FieldByName('dSueldo').AsFloat,ffNumber,7,2));
salario_diario := quitaComas(FloatToStrF((salario_mensual/30),ffNumber,7,2));
proporcion_prima_vacacional := quitaComas(FloatToStrF((((dias_vacaciones*salario_mensual)*0.25)/365),ffNumber,7,2));
proporcion_aguinaldo := quitaComas(FloatToStrF(((15*proporcion_aguinaldo)/365),ffNumber,7,2));
salario_diario_integrado := proporcion_prima_vacacional + proporcion_aguinaldo + salario_diario;
salario_mensual_integrado := (salario_diario_integrado*30);
txtSalDiario.Text := Format('%m', [salario_diario]);
txtSalDiarioInt.Text := Format('%m', [salario_diario_integrado]);
txtSalMensual.Text := Format('%m', [salario_mensual]);
txtSalMensualInt.Text := Format('%m', [salario_mensual_integrado]);
end;
procedure Tfrm_LiqFini.txtVacDiasTomadosKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if trim(txtVacDiasTomados.Text) <> '' then begin
if StrToInt(txtVacDiasTomados.Text) <= dias_vacaciones then begin
txtVacPagar.Text := IntToStr(dias_vacaciones - StrToInt(txtVacDiasTomados.Text));
end
else begin
messageDlg('EL numero es Mayor al los Dias Trabajados.',mtWarning,[mbOk],0);
txtVacDiasTomados.Text := '0';
txtVacPagar.Text := IntToStr(dias_vacaciones);
end;
end else begin
txtVacPagar.Text := IntToStr(dias_vacaciones);
end;
end;
procedure Tfrm_LiqFini.cbxIsrClick(Sender: TObject);
begin
txtIsrAnterior.Text := qryDeduccionesEmpleado.FieldByName('dImporte').AsString;
end;
procedure Tfrm_LiqFini.chxFiniquitoClick(Sender: TObject);
begin
if chxFiniquito.Checked then begin
if qryFiniquito.RecordCount > 0 then begin
qryFiniquito.Edit
end
else begin
if qryFiniquito.State <> dsInsert then
qryFiniquito.Append;
end;
txtVacDiasTomados.Enabled := True;
txtVacPagar.Enabled := True;
end
else begin
if qryFiniquito.State IN [dsInsert, dsEdit] then
qryFiniquito.Cancel;
txtVacDiasTomados.Enabled := False;
txtVacPagar.Enabled := False;
end;
Inicializa_Valores_Finiquito;
end;
procedure Tfrm_LiqFini.chxLiquidacionClick(Sender: TObject);
begin
if chxLiquidacion.Checked then begin
if qryLiquidacion.RecordCount > 0 then begin
qryLiquidacion.Edit
end
else begin
if qryLiquidacion.State <> dsInsert then
qryLiquidacion.Append;
end;
cbxIsr.Enabled := True;
txtIsrAnterior.Enabled := True;
end
else begin
if qryLiquidacion.State IN [dsEdit, dsInsert] then
qryLiquidacion.Cancel;
if qryLiquidacion.RecordCount = 0 then
txtIsrAnterior.Text := '';
dsLiquidacion.AutoEdit := False;
cbxIsr.Enabled := False;
txtIsrAnterior.Enabled := False;
end;
end;
procedure Tfrm_LiqFini.datosGenerales;
begin
salario_diario := quitaComas(FloatToStrF(frm_Empleados.zQEmpleados.FieldByName('dSalarioDiario').AsFloat,ffNumber,7,2));
salario_diario_integrado := quitaComas(FloatToStrF(frm_Empleados.zQEmpleados.FieldByName('dSalarioIntegrado').AsFloat,ffNumber,7,2));
salario_mensual := quitaComas(FloatToStrF(frm_Empleados.zQEmpleados.FieldByName('dSueldo').AsFloat,ffNumber,7,2));
salario_mensual_integrado := (salario_diario_integrado*30);
txtSalDiario.Text := Format('%m', [salario_diario]);
txtSalDiarioInt.Text := Format('%m', [salario_diario_integrado]);
txtSalMensual.Text := Format('%m', [salario_mensual]);
txtSalMensualInt.Text := Format('%m', [salario_mensual_integrado]);
end;
function Tfrm_LiqFini.quitaComas(cadena: string) : double;
begin
Result := StrToFloat(StringReplace(cadena, ',', '', [rfReplaceAll, rfIgnoreCase]));
end;
procedure Tfrm_LiqFini.variables_Liquidacion_Finiquito;
var
anios : double;
wAnyo2 : Word;
begin
anios_laborados := DaysBetween(frm_Empleados.zQEmpleados.FieldByName('dFechaInicioLabores').AsDateTime, frm_Empleados.zQEmpleados.FieldByName('dFechaTerminoLabores').AsDateTime);
anios := ( anios_laborados/365 );
anios_laborados := trunc(anios);
if anios > anios_laborados then
anios_laborados_mas1 := anios_laborados + 1
else
anios_laborados_mas1 := anios_laborados;
DecodeDate(frm_Empleados.zQEmpleados.FieldByName('dFechaTerminoLabores').AsDateTime, wAnyo, wMes, wDia );
dias_proporcionales_aguinaldo := DaysBetween(StrToDate( '01/01/'+IntToStr(wAnyo)), frm_Empleados.zQEmpleados.FieldByName('dFechaTerminoLabores').AsDateTime);
DecodeDate(frm_Empleados.zQEmpleados.FieldByName('dFechaInicioLabores').AsDateTime, wAnyo2, wMes, wDia );
dias_proporcionales := DaysBetween(StrToDate( IntToStr(wDia)+'/'+IntToStr(wMes)+'/'+IntToStr(wAnyo - 1)), frm_Empleados.zQEmpleados.FieldByName('dFechaTerminoLabores').AsDateTime);
if dias_proporcionales = 365 then
dias_proporcionales := 0;
if anios_laborados > 0 then begin
sql := 'SELECT iDias FROM rh_vacaciones WHERE iAnio = '+IntToStr(anios_laborados_mas1);
connection.QryBusca.Active := False;
connection.QryBusca.SQL.Clear;
connection.QryBusca.SQL.Add(sql);
connection.QryBusca.Open;
if connection.QryBusca.RecordCount > 0 then begin
dias_vacaciones := connection.QryBusca.FieldByName('iDias').AsInteger;
end
else begin
dias_vacaciones := 6;
end;
end;
end;
procedure Tfrm_LiqFini.Calculo_Liquidacion;
var
porcentaje, Salario_Minimo, sal_inte : double;
begin
query.Active := False;
query.SQL.Clear;
query.SQL.Add('SELECT * FROM nom_liquidacion WHERE sIdEmpleado = '+QuotedStr(sIdEmpleado));
query.Open;
if query.RecordCount > 0 then begin///si ya hizo el calculo de la liquidacion
if messageDlg('¿Desea Volver hacer el Cálculo para la Liquidación?',mtConfirmation,[mbYes,mbNo],0) = mrNo then
exit;
connection.QryBusca.Active := False;
connection.QryBusca.SQL.Clear;
connection.QryBusca.SQL.Add('DELETE FROM nom_liquidacion WHERE sIdEmpleado = '+QuotedStr(sIdEmpleado));
connection.QryBusca.ExecSQL;
end;
{$REGION '3 MESES DE INDEMNIZACION'}
//Salario mensual integrado x 3 meses de indemnización.
Indemnizacion := (Salario_Mensual_Integrado * 3);
{$ENDREGION}
{$REGION '20 DIAS POR CADA AÑO DE SERVICIOS'}
//Salario diario integrado x 20 días por cada año de servicios, más la parte proporcional de acuerdo a los dias
//laborados apartir del 1 de enero del año actual asta la fecha del despido.
dias20 := ( ( Salario_Diario_Integrado*( anios_laborados*20 ) ) + ( ( ( Salario_Diario_Integrado*20 )/365 )*dias_proporcionales ) );
{$ENDREGION}
{$REGION 'PRMA DE ANTIGUEDAD'}
//Salario diario integrado X 12 días por 1 año de servicio, más la parte proporcional de acuerdo a los dias
//laborados apartir del 1 de enero del año actual asta la fecha del despido
sql := 'SELECT dSalarioMinimo ' +
'FROM nom_catalogodezonasgeograficas AS a ' +
'WHERE iId = (SELECT iIdZonaGeografica FROM nom_configuracion);';
query.Active := False;
query.SQL.Clear;
query.SQL.Add(sql);
query.Open;
if query.RecordCount > 0 then begin
sal_inte := Salario_Diario_Integrado;
Salario_Minimo := query.FieldByName('dSalarioMinimo').AsFloat;
if (Salario_Minimo * 2) < Salario_Diario then begin
Salario_Diario_Integrado := (Salario_Minimo * 2);
end;
end;
prima := ( ( Salario_Diario_Integrado*( anios_laborados*12 ) ) + ( ( ( Salario_Diario_Integrado*12 )/365 )*dias_proporcionales ) );
Salario_Diario_Integrado := sal_inte;
{$ENDREGION}
total_liquidacion := Indemnizacion + dias20 + prima;
{$REGION 'CALCULO DE ISR SOBRE LA LIQUIDACION'}
//ISR correspondiente al último sueldo
//Conforme a la LFT se consideran hasta 90 SMGD por año de trabajo como proporción exenta
porcentaje := (StrToFloat(txtIsrAnterior.Text)/Salario_Mensual);
isr_liquidacion := ((((Salario_Minimo*90)*anios_laborados_mas1))*porcentaje);
{$ENDREGION}
if qryLiquidacion.State IN [dsBrowse, dsEdit] then
qryLiquidacion.Append;
try
qryLiquidacion.FieldByName('sIdEmpleado').AsString := sIdEmpleado;
qryLiquidacion.FieldByName('iIdDeduccion').AsString := qryDeduccionesEmpleado.FieldByName('iId').AsString;
qryLiquidacion.FieldByName('dISRAnterior').AsFloat := qryDeduccionesEmpleado.FieldByName('dImporte').AsFloat;
txtIndemnizacion.Text := FloatToStr(quitaComas(FloatToStrF(Indemnizacion,ffNumber,7,2)));
txt20dias.Text := FloatToStr(quitaComas(FloatToStrF(dias20,ffNumber,7,2)));
txtAntiguedad.Text := FloatToStr(quitaComas(FloatToStrF(prima,ffNumber,7,2)));
txtMontoLiquidacion.Text := FloatToStr(quitaComas(FloatToStrF(total_liquidacion,ffNumber,7,2)));
txtIsrLiquidacion.Text := FloatToStr(quitaComas(FloatToStrF(isr_liquidacion,ffNumber,7,2)));
qryLiquidacion.FieldByName('fFecha').AsDateTime := now();
qryLiquidacion.Post;
calculo := True;
Error := False;
btnImprimirLiqFin.Enabled := True;
except
on E : exception do begin
messageDlg('Ocurrio un Error al Guardar los Datos!' + #10 + 'Comunique ésto al Administrador: ' + #10 + E.Message,mtError,[mbOk],0);
Error := True;
end;
end;
//showmessage('Total liquidacion ' + floattostr(total_liquidacion));
end;
procedure Tfrm_LiqFini.btnImprimirLiqFinClick(Sender: TObject);
begin
PopupImprimir.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y);
end;
procedure Tfrm_LiqFini.Calculo_Finiquito;
var
base_grabable_finiquito : double;
vaca : Integer;
var1, var2, var3 : String;
begin
query.Active := False;
query.SQL.Clear;
query.SQL.Add('SELECT * FROM nom_finiquito WHERE sIdEmpleado = '+QuotedStr(sIdEmpleado));
query.Open;
if query.RecordCount > 0 then begin///si ya hizo el calculo
if messageDlg('¿Desea Volver hacer el Cálculo para el Finiquito?',mtConfirmation,[mbYes,mbNo],0) = mrNo then begin
Inicializa_Valores_Finiquito;
exit;
end;
end;
{$REGION 'VACACIONES'}
vaca := dias_vacaciones;
dias_vacaciones := StrToInt(txtVacPagar.Text);
vacaciones := ( ( ( dias_vacaciones / 365 ) * dias_proporcionales ) * Salario_Diario);
dias_vacaciones := vaca;
{$ENDREGION}
{$REGION 'PRIMA VACACIONAL'}
primavac := (vacaciones * 0.25);
{$ENDREGION}
{$REGION 'AGUINALDO PROPORCIONAL'}
aguinaldo := ( ( ( 15/365 ) * dias_proporcionales_aguinaldo ) * Salario_Diario);
{$ENDREGION}
total_finiquito := vacaciones + primavac + aguinaldo;
{$REGION 'CALCULO DE ISR SOBRE EL FINIQUITO'}
base_grabable_finiquito := vacaciones + Salario_Mensual;
sql := 'SELECT * ' +
'FROM nom_tarifamensual ' +
'WHERE fLimiteInferior <= ' + FloatToStr(base_grabable_finiquito) + ' ' +
'AND fLimiteSuperior >= ' + FloatToStr(base_grabable_finiquito) + ';';
query.Active := False;
query.SQL.Clear;
query.SQL.Add(sql);
query.Open;
if query.RecordCount = 0 then begin//si no se encuentra dentro del rango de nom_tarifamensual, seleccioname el mayor
sql := 'SELECT * ' +
'FROM nom_tarifamensual ' +
'WHERE fLimiteInferior = (SELECT MAX(fLimiteInferior) as fLimiteInferior FROM nom_tarifamensual);';
query.Active := False;
query.SQL.Clear;
query.SQL.Add(sql);
query.Open;
end;
isr_finiquito := ( base_grabable_finiquito - query.FieldByName('fLimiteInferior').AsFloat );
isr_finiquito := ( isr_finiquito * (query.FieldByName('fPorcentaje').AsFloat/100));
isr_finiquito := ( isr_finiquito + query.FieldByName('fCuotaFija').AsFloat );
{$ENDREGION}
//total_finiquito := total_finiquito - isr_finiquito;
if qryFiniquito.State = dsBrowse then begin
var1 := txtVacDiasTrabajados.Text;
var2 := txtVacDiasTomados.Text;
var3 := txtVacPagar.Text;
qryFiniquito.Append;
qryFiniquito.FieldByName('iVacacionesDiasTrabajados').AsString := var1;
qryFiniquito.FieldByName('iVacacionesDiasTomados').AsString := var2;
qryFiniquito.FieldByName('iVacacionesDiasPagar').AsString := var3;
end;
try
qryFiniquito.FieldByName('sIdEmpleado').AsString := sIdEmpleado;
txtVacaciones.Text := FloatToStr(quitaComas(FloatToStrF(Vacaciones,ffNumber,7,2)));
txtPrimaVacacional.Text := FloatToStr(quitaComas(FloatToStrF(primavac,ffNumber,7,2)));
txtAguinaldo.Text := FloatToStr(quitaComas(FloatToStrF(aguinaldo,ffNumber,7,2)));
txtMontoFiniquito.Text := FloatToStr(quitaComas(FloatToStrF(total_finiquito,ffNumber,7,2)));
txtIsrFiniquito.Text := FloatToStr(quitaComas(FloatToStrF(isr_finiquito,ffNumber,7,2)));
qryFiniquito.FieldByName('fFecha').AsDateTime := now();
qryFiniquito.Post;
calculo := True;
Error := False;
btnImprimirLiqFin.Enabled := True;
except
on E : exception do begin
messageDlg('Ocurrio un Error al Guardar los Datos!' + #10 + 'Comunique ésto al Administrador: ' + #10 + E.Message,mtError,[mbOk],0);
Error := True;
end;
end;
//showmessage(floattostr(total_finiquito));
end;
procedure Tfrm_LiqFini.Inicializa_Valores_Finiquito;
begin
if qryFiniquito.RecordCount = 0 then begin
if qryFiniquito.State <> dsInsert then
qryFiniquito.Append;
txtVacDiasTrabajados.Text := IntToStr(dias_vacaciones);
txtVacDiasTomados.Text := '0';
txtVacPagar.Text := IntToStr(dias_vacaciones);
end
else begin
if qryFiniquito.State = dsEdit then begin
qryFiniquito.Refresh;
qryFiniquito.Edit;
end
else begin
qryFiniquito.Refresh;
end;
lblEliminarFiniquito.Visible := True;
end;
end;
procedure Tfrm_LiqFini.lblEliminarFiniquitoClick(Sender: TObject);
begin
if qryFiniquito.RecordCount > 0 then begin
if messageDlg('¿Desea Eliminar el Cálculo de Finiquito para este Empleado?', mtConfirmation,[mbYes,mbNo],0) = mrYes then begin
connection.QryBusca.Active := False;
connection.QryBusca.SQL.Clear;
connection.QryBusca.SQL.Add('DELETE FROM nom_finiquito WHERE sIdEmpleado = ' + QuotedStr(sIdEmpleado));
connection.QryBusca.ExecSQL;
qryFiniquito.Refresh;
lblEliminarFiniquito.Visible := False;
despues_eliminar;
end;
end;
end;
procedure Tfrm_LiqFini.lblEliminarLiquidacionClick(Sender: TObject);
begin
if qryLiquidacion.RecordCount > 0 then begin
if messageDlg('¿Desea Eliminar el Cálculo de Liquidación para este Empleado?', mtConfirmation,[mbYes,mbNo],0) = mrYes then begin
connection.QryBusca.Active := False;
connection.QryBusca.SQL.Clear;
connection.QryBusca.SQL.Add('DELETE FROM nom_liquidacion WHERE sIdEmpleado = ' + QuotedStr(sIdEmpleado));
connection.QryBusca.ExecSQL;
qryLiquidacion.Refresh;
lblEliminarLiquidacion.Visible := False;
despues_eliminar;
end;
end;
end;
procedure Tfrm_LiqFini.lblEliminarFiniquitoMouseEnter(Sender: TObject);
begin
lblEliminarFiniquito.Font.Color := clRed;
end;
procedure Tfrm_LiqFini.lblEliminarFiniquitoMouseLeave(Sender: TObject);
begin
lblEliminarFiniquito.Font.Color := clMaroon;
end;
procedure Tfrm_LiqFini.lblEliminarLiquidacionMouseEnter(Sender: TObject);
begin
lblEliminarLiquidacion.Font.Color := clRed;
end;
procedure Tfrm_LiqFini.lblEliminarLiquidacionMouseLeave(Sender: TObject);
begin
lblEliminarLiquidacion.Font.Color := clMaroon;
end;
procedure Tfrm_LiqFini.Liquidacin1Click(Sender: TObject);
var
monto, decimales : double;
begin
if qryLiquidacion.RecordCount > 0 then begin
rReportes.PreviewOptions.MDIChild := True ;
rReportes.PreviewOptions.Modal := False ;
rReportes.PreviewOptions.Maximized := lCheckMaximized () ;
rReportes.PreviewOptions.ShowCaptions := False ;
rReportes.Previewoptions.ZoomMode := zmPageWidth ;
rReportes.DataSet := fdsLiquidacion;
rReportes.DataSetName := 'fdsLiquidacion';
rReportes.LoadFromFile (global_files + 'Reporte_Liquidacion.fr3') ;
rReportes.Variables.Variables['fecha_inicio'] := frm_Empleados.zQEmpleados.FieldByName('dFechaInicioLabores').AsDateTime;
rReportes.Variables.Variables['fecha_fin'] := frm_Empleados.zQEmpleados.FieldByName('dFechaTerminoLabores').AsDateTime;
rReportes.Variables.Variables['dias'] := DaysBetween(frm_Empleados.zQEmpleados.FieldByName('dFechaInicioLabores').AsDateTime,frm_Empleados.zQEmpleados.FieldByName('dFechaTerminoLabores').AsDateTime);
monto := (qryLiquidacion.FieldByName('dMontoLiquidacion').AsFloat - qryLiquidacion.FieldByName('dISRLiquidacion').AsFloat);
//rReportes.Variables.Variables['total'] := QuotedStr(FloatToStrF(monto,ffNumber,7,2));
rReportes.Variables.Variables['total'] := monto;
rReportes.Variables.Variables['monto_letras'] := QuotedStr(xIntToLletres(trunc(monto)));
decimales := monto - trunc(monto);
if decimales > 0 then
rReportes.Variables.Variables['decimales'] := AnsiMidStr(FloatToStr(decimales),3,2)
else
rReportes.Variables.Variables['decimales'] := AnsiMidStr(FloatToStr(decimales),4,2);
rReportes.Variables.Variables['empleado'] := QuotedStr(frm_Empleados.zQEmpleados.FieldByName('sNombreCompleto').AsString);
rReportes.Variables.Variables['cargo'] := QuotedStr(frm_Empleados.zQEmpleados.FieldByName('sPuesto').AsString);
rReportes.ShowReport() ;
end;
end;
procedure Tfrm_LiqFini.despues_eliminar;
var
eliminar1, eliminar2 : Boolean;
begin
eliminar1 := False;
eliminar2 := False;
if qryFiniquito.RecordCount = 0 then begin
Inicializa_Valores_Finiquito;
eliminar1 := True;
end;
if qryLiquidacion.RecordCount = 0 then begin
txtIsrAnterior.Text := '';
eliminar2 := True;
if qryLiquidacion.State <> dsInsert then
qryLiquidacion.Append;
end;
if (eliminar1 = True) AND (eliminar2 = True) then begin
if qryDatosGenerales.RecordCount > 0 then begin
connection.QryBusca.Active := False;
connection.QryBusca.SQL.Clear;
connection.QryBusca.SQL.Add('DELETE FROM nom_datgenLiqFini WHERE sIdEmpleado = ' + QuotedStr(sIdEmpleado));
connection.QryBusca.ExecSQL;
end;
rbtImss.Enabled := True;
rbtSueldo.Enabled := True;
btnImprimirLiqFin.Enabled := False;
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLConsole <p>
The console is a popdown window that appears on a game for text output/input.<p>
<b>History : </b><font size=-1><ul>
<li>16/03/11 - Yar - Fixes after emergence of GLMaterialEx
<li>02/04/07 - DaStr - All cross-version stuff abstracted into GLCrossPlatform
<li>30/03/07 - DaStr - Replaced GLWin32Viewer with GLViewer
<li>25/02/07 - DaStr - Made some fixes for Delphi5 compatibility
<li>23/02/07 - DaStr - Cosmetic changes, replaced some strings with
resource strings from GLStrings.pas
<li>15/02/07 - DaStr - Some properties are not stored now, because they are
read directly from HUDSprite and HUDText
<li>07/02/07 - DaStr - Initial version (donated to GLScene)
What is different compared to the original component?
1) Can be aded to any object, not just the root one
2) Has a *wide* range of built-in commands
3) TGLConsoleCommand.UnknownCommand added
it is set to True, if no internal command recognized
4) Internal console help added
5) By default does not remove quotes ("), but this option can be
turned on (property RemoveQuotes)
6) Command list added. All user commands are saved there
7) All previously typed commands can be accessed in a usual way (arrow up/down)
8) Commands can be auto-completed by pressing TConsoleControls.AutoCompleteCommand key,
or setting AutoCompleteCommandsOnKeyPress, AutoCompleteCommandsOnEnter to True
Dbl-pressing the key, defined in the TConsoleControls.AutoCompleteCommand
property, gives you a list of all posible internal-external commands that
start with your letters
9) Batch command execution support added
10) Short help is shown when user calls the global 'help' function
Long help is shown elsewhere
11) Show command help by "/?", "-?", "--?" etc
12) Assign() added for every class
TODO:
[new command] Redirection with the | operator, like in any othe console (optional)
[new command] File browser stuff... (this one's optional ;)
Blinking cursor, "Delete" key support
Allow long lines to continue on the next line
May be SceneViewer should be a TControl to support the FullScreenViewer...
Previous version history:
v1.0 23 November '2005 Creation (based on TGLConsole from http://caperaven.co.za/
v1.1 17 June '2006 Load/Save stuff upgraded
v1.2 07 July '2006 Component completely rewritten
(New command classes added)
v1.2.4 31 August '2006 A few memory leaks fixed
TGLCustomConsole.Size added
Fixed a bug in TGLCustomConsole.RefreshHud
"Console.Color" command fixed
Bug with saving of TypedCommands fixed
v1.2.5 11 September '2006 TGLCustomConsole.AutoCompleteCommand() bugfixed
v1.2.6 08 October '2006 Made compatible with the new persistance mechanism
1.3 23 October '2006 TGLCustomConsole made descendant of TGLBaseSceneObject
1.4 07 February '2007 TGLCustomConsole.NumLines bugfixed
TGLCustomConsole.RefreshHud bugfixed
TGLConsoleCommand.GetDisplayName added
TGLConsoleCommand default values added
TGLConsoleStringList.Changed fixed
TGLConsoleOptions added (united 4 Boolean properties)
Code ready to be donated to GLScene
}
unit GLConsole;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils, System.TypInfo, Vcl.Graphics,
// GLS
GLScene, GLObjects, GLHUDObjects, GLViewer, GLBitmapFont,
GLPersistentClasses, GLContext, GLTexture, GLUtils, GLStrings,
GLCrossPlatform, GLMaterial, GLVectorTypes;
const
CONSOLE_MAX_COMMANDS = 120;
type
EGLConsoleException = class(Exception);
TGLConsoleOption = (coAutoCompleteCommandsOnKeyPress,
//commands are auto-completed as user types them
coAutoCompleteCommandsOnEnter, //commands are auto-completed when user presses the "Enter" key
coShowConsoleHelpIfUnknownCommand, //take a wild guess ;)
coRemoveQuotes); //remove quotes when a command line is parsed
TGLConsoleOptions = set of TGLConsoleOption;
TGLCustomConsole = class;
TGLConsoleCommandList = class;
TGLConsoleCommand = class;
{: Stores info on a command. A command is a parsed input line.
Should be transformed into a class, I think...}
TGLUserInputCommand = record
CommandCount: Integer;
Strings: array of string;
UnknownCommand: Boolean;
//if user identifies a command, he must set this to "True"
end;
{: Event called when used presses the "Enter"}
TGLlConsoleEvent = procedure(const ConsoleCommand: TGLConsoleCommand;
const Console: TGLCustomConsole;
var Command: TGLUserInputCommand) of object;
TGLConsoleMatchList = set of 0..CONSOLE_MAX_COMMANDS {Byte};
{ A class that checks for duplicates. }
TGLConsoleStringList = class(TStringList)
private
FConsole: TGLCustomConsole;
protected
procedure Changed; override;
function GetOwner: TPersistent; override;
public
function CommandExists(const Command: string): Boolean;
constructor Create(const Owner: TGLCustomConsole);
end;
{ A wrapper for a console command. }
TGLConsoleCommand = class(TCollectionItem)
private
FVisible: Boolean;
FEnabled: Boolean;
FSilentDisabled: Boolean;
FCommandList: TGLConsoleCommandList;
FCommandName: string;
FShortHelp: string;
FLongHelp: TStringList;
FOnCommand: TGLlConsoleEvent;
FOnHelp: TNotifyEvent;
procedure SetCommandName(const Value: string);
protected
procedure ShowInvalidUseOfCommandError; virtual;
procedure ShowInvalidNumberOfArgumentsError(const ShowHelpAfter: Boolean =
True); virtual;
procedure DoOnCommand(var UserInputCommand: TGLUserInputCommand); virtual;
function GetDisplayName: string; override;
public
//procedures
procedure ShowHelp; virtual;
procedure ShowShortHelp; virtual;
procedure Assign(Source: TPersistent); override;
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
published
//properties
property CommandName: string read FCommandName write SetCommandName;
property ShortHelp: string read FShortHelp write FShortHelp;
property LongHelp: TStringList read FLongHelp;
property OnCommand: TGLlConsoleEvent read FOnCommand write FOnCommand;
property OnHelp: TNotifyEvent read FOnHelp write FOnHelp;
//: Disabled commands won't execute
property Enabled: Boolean read FEnabled write FEnabled default True;
{: If command is disabled and user calls it, no error report will be
generated if SilentDisabled is enabled }
property SilentDisabled: Boolean read FSilentDisabled write FSilentDisabled
default False;
{: Hidden commands won't show when user requests command list
or uses auto-complete }
property Visible: Boolean read FVisible write FVisible default True;
end;
TGLConsoleCommandList = class(TCollection)
private
FConsole: TGLCustomConsole;
function GetItems(const Index: Integer): TGLConsoleCommand;
protected
function GetOwner: TPersistent; override;
public
procedure SortCommands(const Ascending: Boolean = True);
function CommandExists(const Command: string): Boolean;
function GetCommandIndex(const Command: string): Integer;
// General list stuff.
function LastConsoleCommand: TGLConsoleCommand;
function Add: TGLConsoleCommand; overload;
// Standard stuff.
constructor Create(const AOwner: TGLCustomConsole);
destructor Destroy; override;
property Items[const Index: Integer]: TGLConsoleCommand read GetItems;
default;
end;
TGLConsoleControls = class(TPersistent)
private
FOwner: TPersistent;
FNavigatePageUp: Byte;
FAutoCompleteCommand: Byte;
FPreviousCommand: Byte;
FNextCommand: Byte;
FNavigateUp: Byte;
FNavigatePageDown: Byte;
FNavigateDown: Byte;
FDblClickDelay: Integer;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent);
procedure Assign(Source: TPersistent); override;
published
property NavigateUp: Byte read FNavigateUp write FNavigateUp default
glKey_HOME;
property NavigateDown: Byte read FNavigateDown write FNavigateDown default
glKey_END;
property NavigatePageUp: Byte read FNavigatePageUp write FNavigatePageUp
default glKey_PRIOR;
property NavigatePageDown: Byte read FNavigatePageDown write
FNavigatePageDown default glKey_NEXT;
property NextCommand: Byte read FNextCommand write FNextCommand default
glKey_DOWN;
property PreviousCommand: Byte read FPreviousCommand write FPreviousCommand
default glKey_UP;
property AutoCompleteCommand: Byte read FAutoCompleteCommand write
FAutoCompleteCommand default glKey_CONTROL;
property DblClickDelay: Integer read FDblClickDelay write FDblClickDelay
default 300;
end;
{: TGLCustomConsole }
TGLCustomConsole = class(TGLBaseSceneObject)
private
FHudSprite: TGLHudSprite;
FHudText: TGLHudText;
FSceneViewer: TGLSceneViewer;
FInputLine: string;
FStartLine: Integer;
FCurrentCommand: Integer;
FPreviousTickCount: Integer;
FSize: Single;
FColsoleLog: TStringList;
FCommands: TGLConsoleCommandList;
FAdditionalCommands: TGLConsoleStringList;
FTypedCommands: TStringList;
FControls: TGLConsoleControls;
FOnCommandIssued: TGLlConsoleEvent;
FOptions: TGLConsoleOptions;
FHint: string;
procedure SetSize(const Value: Single);
procedure SetSceneViewer(const Value: TGLSceneViewer);
function GetFont: TGLCustomBitmapFont;
procedure SetFont(const Value: TGLCustomBitmapFont);
protected
{: Misc }
procedure DoOnCommandIssued(var UserInputCommand: TGLUserInputCommand);
virtual;
procedure SetFontColor(const Color: TColor); virtual;
function GetFontColor: TColor; virtual;
procedure SetHUDSpriteColor(const Color: TColor); virtual;
function GetHUDSpriteColor: TColor; virtual;
function NumLines: Integer; virtual;
procedure ShowConsoleHelp; virtual;
procedure HandleUnknownCommand(const Command: string); virtual;
{: Auto Complete Command }
procedure AutoCompleteCommand; overload; virtual;
procedure AutoCompleteCommand(var MatchCount: Integer; var
AdditionalCommandsMatchList: TGLConsoleMatchList; var CommandsMatchList:
TGLConsoleMatchList); overload;
{: Command interpreters }
procedure CommandIssued(var UserInputCommand: TGLUserInputCommand); virtual;
procedure FixCommand(var UserInputCommand: TGLUserInputCommand); virtual;
function ParseString(str, caract: string): TGLUserInputCommand; virtual;
procedure ProcessInput; virtual;
{: Refreshes the Hud (clip lines outside the visible console). }
procedure RefreshHud; virtual;
//: Register built-in commands (onCreate)
procedure RegisterBuiltInCommands; virtual;
//: Internal command handlers:
procedure ProcessInternalCommandHelp(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
procedure ProcessInternalCommandClearScreen(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
procedure ProcessInternalCommandConsoleHide(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
procedure ProcessInternalCommandConsoleColor(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
procedure ProcessInternalCommandConsoleRename(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
procedure ProcessInternalCommandConsoleClearTypedCommands(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var
Command: TGLUserInputCommand); virtual;
procedure ProcessInternalCommandSystemTime(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
procedure ProcessInternalCommandSystemDate(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
procedure ProcessInternalCommandViewerFPS(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
procedure ProcessInternalCommandViewerResetPerformanceMonitor(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var
Command: TGLUserInputCommand); virtual;
procedure ProcessInternalCommandViewerVSync(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
procedure ProcessInternalCommandViewerAntiAliasing(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand); virtual;
// Internal command help handlers:
procedure GetHelpInternalCommandRename(Sender: TObject); virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
procedure SetName(const Value: TComponentName); override;
public
//: Methods:
//: User *must* call these methodsin his code.
procedure ProcessKeyPress(const c: Char); virtual;
procedure ProcessKeyDown(const key: word); virtual;
//: Navigation through code from outside
procedure NavigateUp;
procedure NavigateDown;
procedure NavigatePageUp;
procedure NavigatePageDown;
{: Refreshes the size of the hud to reflect changes on the viewer.
Should be called whenever the viewer's size changes. }
procedure RefreshHudSize; virtual;
{: Adds a line (which is not treated as a command). }
procedure AddLine(const str: string);
{: TypedCommands are cleared and current command index is reset. }
procedure ClearTypedCommands;
procedure ExecuteCommand(const Command: string);
procedure ExecuteCommands(const Commands: TStrings);
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{: Properties. }
{: Changes the console font color. }
property FontColor: TColor read GetFontColor write SetFontColor stored
False;
property HUDSpriteColor: TColor read GetHUDSpriteColor write
SetHUDSpriteColor stored False;
//: Where user enters his commands.
property InputLine: string read FInputLine write FInputLine;
//: List of commands that user typed.
property TypedCommands: TStringList read FTypedCommands;
//: Commands have events that are called when user types a sertauin command
property Commands: TGLConsoleCommandList read FCommands;
{: Aditional commands can be registered to participate in command auto-completion.
They can be interpreted in the global OnCommandIssued event handler. }
property AdditionalCommands: TGLConsoleStringList read FAdditionalCommands;
{: User controls. }
property Controls: TGLConsoleControls read FControls;
{: list of commands that user typed and console's responces. }
property ColsoleLog: TStringList read FColsoleLog;
{: Allows to change consol's height from 0 to 1. }
property Size: Single read FSize write SetSize;
{: Visual stuff. }
property SceneViewer: TGLSceneViewer read FSceneViewer write SetSceneViewer;
property HudSprite: TGLHudSprite read FHudSprite;
property HudText: TGLHudText read FHudText;
property Font: TGLCustomBitmapFont read GetFont write SetFont stored False;
property Options: TGLConsoleOptions read FOptions write FOptions;
{ Main event of the console. Happens whenever the enter key is pressed.
First the input line is compared to all registered commands, then everything
is parsed into a TGLUserInputCommand record and sent to the event.
Empty lines are <b>not</b> ignored (i.e. they also trigger events)}
property OnCommandIssued: TGLlConsoleEvent read FOnCommandIssued write
FOnCommandIssued;
{: Standard stuff }
property Hint: string read FHint write FHint;
property Visible default False;
end;
TGLConsole = class(TGLCustomConsole)
published
property FontColor;
property HUDSpriteColor;
property InputLine;
property TypedCommands;
property Commands;
property AdditionalCommands;
property Controls;
property ColsoleLog;
property SceneViewer;
property HudSprite;
property HudText;
property Font;
property Options;
property OnCommandIssued;
property Hint;
property Tag;
property ObjectsSorting;
property Visible;
property OnProgress;
end;
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
implementation
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
const
STR_NO_DUPLICATE_NAMES_ALLOWED = 'Duplicate names not allowed!';
STR_UNRECOGNIZED_PARAMETER = 'Unrecognized parameter: ';
conDefaultFontCharHeight = 15;
conDefaultConsoleWidth = 400;
conDefaultConsoleHeight = 100;
{ TGLCustomConsole }
procedure TGLCustomConsole.ProcessInternalCommandClearScreen(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
begin
Console.FInputLine := '';
Console.ColsoleLog.Clear;
end;
procedure TGLCustomConsole.ProcessInternalCommandConsoleHide(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
begin
Console.Visible := False;
AddLine(' - Console hidden');
end;
procedure TGLCustomConsole.ProcessInternalCommandConsoleColor(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
var
NewColor: TColor;
begin
with Console, ConsoleCommand do
begin
if Command.CommandCount = 1 then
AddLine(' - Current console font color is ' +
ColorToString(FHudText.ModulateColor.AsWinColor))
else if Command.CommandCount = 2 then
begin
if TryStringToColorAdvanced(Command.Strings[1], NewColor) then
begin
//color changed successfully
SetFontColor(NewColor);
AddLine(' - Current console font changed to ' +
ColorToString(NewColor));
end
else
begin
//color unidentified!
AddLine(' - Color unidentified!');
end;
end
else
ConsoleCommand.ShowInvalidNumberOfArgumentsError;
end;
end;
procedure TGLCustomConsole.ProcessInternalCommandConsoleRename(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
var
CommandIndex: Integer;
begin
if (Command.CommandCount <> 3) then
ConsoleCommand.ShowInvalidNumberOfArgumentsError
else
begin
CommandIndex :=
ConsoleCommand.FCommandList.GetCommandIndex(Command.Strings[1]);
if CommandIndex = -1 then
begin
AddLine(' - Could not rename command +"' + Command.Strings[1] + '" to "'
+
Command.Strings[2] + '": such command was not found!');
ConsoleCommand.ShowHelp;
end
else if ConsoleCommand.FCommandList.CommandExists(Command.Strings[2]) or
Console.FAdditionalCommands.CommandExists(Command.Strings[2]) then
begin
AddLine(' - Could not rename command +"' + Command.Strings[1] + '" to "'
+
Command.Strings[2] + '": command "' + Command.Strings[2] +
'" already exists!');
ConsoleCommand.ShowHelp;
end
else
begin
ConsoleCommand.FCommandName := Command.Strings[2];
AddLine(' - Command "' + Command.Strings[1] + '" successfully renamed to "'
+
Command.Strings[2] + '"!');
end;
end;
end;
procedure TGLCustomConsole.ProcessInternalCommandConsoleClearTypedCommands(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
begin
if (Command.CommandCount = 1) then
Console.ClearTypedCommands
else
ConsoleCommand.ShowInvalidNumberOfArgumentsError;
end;
procedure TGLCustomConsole.ProcessInternalCommandSystemDate(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
begin
if (Command.CommandCount = 1) then
AddLine(' - Current system date is: ' + DateToStr(now))
else
ConsoleCommand.ShowInvalidNumberOfArgumentsError;
end;
procedure TGLCustomConsole.ProcessInternalCommandHelp(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
var
MainCommand: string;
I: Integer;
begin
if Command.CommandCount = 1 then
Console.ShowConsoleHelp
else if (Command.CommandCount = 2) then
begin
MainCommand := LowerCase(Command.Strings[1]);
if FCommands.Count <> 0 then
for I := 0 to FCommands.Count - 1 do
if MainCommand = LowerCase(FCommands[I].FCommandName) then
begin
FCommands[I].ShowHelp;
Exit;
end;
if FAdditionalCommands.Count <> 0 then
for I := 0 to FAdditionalCommands.Count - 1 do
if MainCommand = LowerCase(FAdditionalCommands[I]) then
begin
AddLine(' - Command "' + Command.Strings[1] +
'" exists, but help is unavaible,');
AddLine(' - because it is an external command');
Exit;
end;
HandleUnknownCommand(Command.Strings[1]);
end
else
ConsoleCommand.ShowInvalidNumberOfArgumentsError;
end;
procedure TGLCustomConsole.ProcessInternalCommandSystemTime(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
begin
if Command.CommandCount = 1 then
AddLine(' - Current system time is: ' + TimeToStr(now))
else
ConsoleCommand.ShowInvalidNumberOfArgumentsError;
end;
procedure TGLCustomConsole.GetHelpInternalCommandRename(Sender: TObject);
begin
with TGLConsoleCommand(Sender) do
begin
Addline(' - The "' + FCommandName + '" command can rename any command');
AddLine(' - Usage:');
AddLine(' - ' + FCommandName + ' [old_command_name] [new_command_name]');
end;
end;
procedure TGLCustomConsole.ProcessInternalCommandViewerFPS(const ConsoleCommand:
TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
begin
if Command.CommandCount = 1 then
begin
if Console.FSceneViewer <> nil then
AddLine(' - Current SceneViewer has ' +
Console.FSceneViewer.FramesPerSecondText)
else
AddLine(' - ' + glsErrorEx + glsSceneViewerNotDefined);
end
else
ConsoleCommand.ShowInvalidNumberOfArgumentsError;
end;
procedure
TGLCustomConsole.ProcessInternalCommandViewerResetPerformanceMonitor(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
begin
if Command.CommandCount = 1 then
begin
if Console.FSceneViewer <> nil then
begin
Console.FSceneViewer.ResetPerformanceMonitor;
AddLine(' - ResetPerformanceMonitor for Current SceneViewer completed');
end
else
AddLine(' - ' + glsErrorEx + glsSceneViewerNotDefined);
end
else
ConsoleCommand.ShowInvalidNumberOfArgumentsError;
end;
procedure TGLCustomConsole.ProcessInternalCommandViewerVSync(const
ConsoleCommand: TGLConsoleCommand; const Console: TGLCustomConsole; var Command:
TGLUserInputCommand);
const
ON_OFF: array[Boolean] of string = ('Off', 'On');
begin
if Console.FSceneViewer <> nil then
begin
if Command.CommandCount = 1 then
begin
AddLine(' - Current SceneViewer VSync is ' +
ON_OFF[Console.FSceneViewer.VSync = vsmSync]);
end
else if (Command.CommandCount = 2) then
begin
if Command.Strings[1] = ON_OFF[False] then
Console.FSceneViewer.VSync := vsmNoSync
else if Command.Strings[1] = ON_OFF[True] then
Console.FSceneViewer.VSync := vsmSync
else
begin
AddLine(' - ' + STR_UNRECOGNIZED_PARAMETER + Command.Strings[1]);
Exit;
end;
AddLine(' - Current SceneViewer VSync was changed to ' +
ON_OFF[Console.FSceneViewer.VSync = vsmSync]);
end
else
HandleUnknownCommand(Command.Strings[1]);
end
else
AddLine(' - ' + glsErrorEx + glsSceneViewerNotDefined);
end;
procedure TGLCustomConsole.ProcessInternalCommandViewerAntiAliasing(
const ConsoleCommand: TGLConsoleCommand;
const Console: TGLCustomConsole; var Command: TGLUserInputCommand);
var
Temp: Integer;
begin
if Console.FSceneViewer <> nil then
begin
if Command.CommandCount = 1 then
AddLine(' - Current SceneViewer AntiAliasing = ' +
GetEnumName(TypeInfo(TGLAntiAliasing),
Ord(Console.FSceneViewer.Buffer.AntiAliasing)))
else if (Command.CommandCount = 2) then
begin
Temp := GetEnumValue(TypeInfo(TGLAntiAliasing), Command.Strings[1]);
if Temp = -1 then
begin
AddLine(' - ' + STR_UNRECOGNIZED_PARAMETER + Command.Strings[1]);
end
else
begin
Console.FSceneViewer.Buffer.AntiAliasing := TGLAntiAliasing(Temp);
AddLine(' - Current SceneViewer AntiAliasing was changed to ' +
GetEnumName(TypeInfo(TGLAntiAliasing),
Ord(Console.FSceneViewer.Buffer.AntiAliasing)))
end;
end
else
ConsoleCommand.ShowInvalidNumberOfArgumentsError;
end
else
AddLine(' - ' + glsErrorEx + glsSceneViewerNotDefined);
end;
function TGLCustomConsole.ParseString(str, caract: string): TGLUserInputCommand;
var
p1: Integer;
begin
Result.CommandCount := 0;
while True do
begin
p1 := pos(caract, str);
if (p1 = 0) or (p1 = -1) then
break;
SetLength(Result.Strings, Result.CommandCount + 1);
Result.Strings[Result.CommandCount] := copy(str, 1, p1 - 1);
str := copy(str, p1 + 1, Length(str));
Result.CommandCount := Result.CommandCount + 1;
end;
if Length(str) > 0 then
begin
setlength(Result.Strings, Result.CommandCount + 1);
Result.Strings[Result.CommandCount] := str;
Result.CommandCount := Result.CommandCount + 1;
end;
end;
procedure TGLCustomConsole.FixCommand(var UserInputCommand:
TGLUserInputCommand);
var
nCount, I: Integer;
openq: Boolean;
begin
for I := 0 to UserInputCommand.CommandCount - 1 do
UserInputCommand.Strings[I] := trim(UserInputCommand.Strings[I]);
nCount := 0;
I := 0;
openq := False;
while nCount < UserInputCommand.CommandCount do
begin
if UserInputCommand.Strings[I] = '' then
begin
if UserInputCommand.Strings[nCount] <> '' then
UserInputCommand.Strings[I] := UserInputCommand.Strings[nCount];
end
else if openq then
UserInputCommand.Strings[I] := UserInputCommand.Strings[I] + ' ' +
UserInputCommand.Strings[nCount];
if (Length(UserInputCommand.Strings[I]) > 0) then
begin
if coRemoveQuotes in FOptions then
begin
if (UserInputCommand.Strings[I][1] = '"') and
(UserInputCommand.Strings[I][Length(UserInputCommand.Strings[I])] =
'"') then
UserInputCommand.Strings[I] := copy(UserInputCommand.Strings[I], 2,
Length(UserInputCommand.Strings[I]) - 2);
if (UserInputCommand.Strings[I][1] = '"') and not openq then
begin
openq := True;
UserInputCommand.Strings[I] := copy(UserInputCommand.Strings[I], 2,
Length(UserInputCommand.Strings[I]));
end;
if (UserInputCommand.Strings[I][Length(UserInputCommand.Strings[I])] =
'"') and openq then
begin
openq := False;
UserInputCommand.Strings[I] := copy(UserInputCommand.Strings[I], 1,
Length(UserInputCommand.Strings[I]) - 1);
end;
end;
if not openq then
Inc(I);
end;
Inc(nCount);
end;
if I < UserInputCommand.CommandCount then
begin
setLength(UserInputCommand.Strings, I);
UserInputCommand.CommandCount := I;
end;
end;
constructor TGLCustomConsole.Create(AOwner: TComponent);
begin
inherited;
FColsoleLog := TStringList.Create;
FTypedCommands := TStringList.Create;
FCommands := TGLConsoleCommandList.Create(Self);
FAdditionalCommands := TGLConsoleStringList.Create(Self);
FControls := TGLConsoleControls.Create(Self);
FHudSprite := TGLHudSprite.Create(Self);
MakeSubComponent(FHudSprite, True);
AddChild(FHudSprite);
FHudSprite.FreeNotification(Self);
with FHudSprite.Material do
begin
BlendingMode := bmTransparency;
FrontProperties.Diffuse.Alpha := 0.5;
Texture.TextureMode := tmModulate;
Texture.Enabled := True;
end;
FHudText := TGLHudText.Create(Self);
MakeSubComponent(FHudText, True);
AddChild(FHUDText);
FHudText.FreeNotification(Self);
FHudText.Position.Y := 2;
FHudText.Position.X := 3;
FSize := 0.35;
RegisterBuiltIncommands;
SetVisible(False);
SetHUDSpriteColor(clWhite);
SetFontColor(clBlue);
end;
destructor TGLCustomConsole.Destroy;
begin
Controls.Destroy;
FCommands.Destroy;
FAdditionalCommands.Destroy;
FTypedCommands.Destroy;
FColsoleLog.Destroy;
FreeAndNil(FHudSprite);
FreeAndNil(FHudText);
inherited;
end;
procedure TGLCustomConsole.ProcessKeyPress(const c: Char);
begin
if not Visible then
Exit;
if c = #8 then //glKey_BACK
FInputLine := copy(FInputLine, 1, Length(FInputLine) - 1)
else if c = #13 then //glKey_RETURN
begin
if coAutoCompleteCommandsOnEnter in FOptions then
AutoCompleteCommand;
//remmember the current entered command
if (FInputLine <> '') and (FInputLine <> #13) then
begin
if FTypedCommands.Count = 0 then
FCurrentCommand := FTypedCommands.Add(FInputLine) + 1
else
begin
if FTypedCommands[FTypedCommands.Count - 1] <> FInputLine then
FCurrentCommand := FTypedCommands.Add(FInputLine) + 1;
end;
end;
ProcessInput;
end
else
FInputLine := FinputLine + c;
if coAutoCompleteCommandsOnKeyPress in FOptions then
AutoCompleteCommand;
RefreshHud;
end;
procedure TGLCustomConsole.ProcessKeyDown(const key: word);
var
MatchCount: Integer;
AdditionalCommandsMatchList: TGLConsoleMatchList;
CommandsMatchList: TGLConsoleMatchList;
CurrentTickCount: Integer;
I: Integer;
begin
if not Visible then
Exit;
if (key = FControls.NextCommand) then
if FCurrentCommand <> FTypedCommands.Count then
begin
if FCurrentCommand <> FTypedCommands.Count - 1 then
Inc(FCurrentCommand);
FinputLine := FTypedCommands[FCurrentCommand];
end;
if (key = FControls.PreviousCommand) then
if FTypedCommands.Count <> 0 then
begin
if FCurrentCommand <> 0 then
Dec(FCurrentCommand);
FinputLine := FTypedCommands[FCurrentCommand];
end;
if (key = FControls.AutoCompleteCommand) then
begin
CurrentTickCount := GLGetTickCount;
AutoCompleteCommand(MatchCount, AdditionalCommandsMatchList,
CommandsMatchList);
if MatchCount = 0 then
Beep;
if CurrentTickCount - FPreviousTickCount < Controls.FDblClickDelay then
if MatchCount > 1 then
begin
if CommandsMatchList <> [] then
begin
AddLine(' - Registered commands:');
for I := 0 to CONSOLE_MAX_COMMANDS do
if I in CommandsMatchList then
AddLine(' - ' + FCommands[I].FCommandName);
end;
if AdditionalCommandsMatchList <> [] then
begin
AddLine(' - Additional registered commands:');
for I := 0 to CONSOLE_MAX_COMMANDS do
if I in AdditionalCommandsMatchList then
AddLine(' - ' + FAdditionalCommands[I]);
end;
end;
FPreviousTickCount := CurrentTickCount;
end;
if (key = FControls.NavigateUp) then
Dec(FStartLine);
if (key = FControls.NavigateDown) then
Inc(FStartLine);
if (key = FControls.NavigatePageUp) then
Dec(FStartLine, NumLines);
if key = FControls.NavigatePageDown then
Inc(FStartLine, NumLines);
RefreshHud;
end;
procedure TGLCustomConsole.RefreshHud;
var
outStr: string;
endLine, I: Integer;
begin
//beware! This stuf is messy
if FStartLine > FColsoleLog.Count - numlines then
FStartLine := FColsoleLog.Count - numlines;
if FStartLine < 0 then
FStartLine := 0;
endLine := FStartLine + numlines - 1;
if FColsoleLog.Count < numLines then
outStr := FColsoleLog.Text
else
begin
for I := FStartLine to endLine do
outStr := outStr + FColsoleLog[I] + #13;
end;
FHudText.Text := outStr + '> ' + FInputLine;
end;
function TGLCustomConsole.NumLines: Integer;
begin
if GetFont = nil then
Result := Trunc(FHudSprite.Height / conDefaultFontCharHeight - 1.7)
else
Result := Trunc(FHudSprite.Height / GetFont.CharHeight - 1.7);
end;
procedure TGLCustomConsole.ProcessInput;
var
info: TGLUserInputCommand;
begin
//Add the current line
AddLine(FInputLine);
//Get everything between spaces
info := ParseString(FInputLine, ' ');
info.UnknownCommand := True;
//Remove empty strings and " sequences
FixCommand(info);
//Execute the command
CommandIssued(info);
//Clear the current line
FinputLine := '';
end;
procedure TGLCustomConsole.ExecuteCommands(const Commands: TStrings);
var
I: Integer;
begin
if Commands.Count = 0 then
Exit;
for I := 0 to Commands.Count - 1 do
ExecuteCommand(Commands[I]);
end;
procedure TGLCustomConsole.ExecuteCommand(const Command: string);
begin
FInputLine := Command;
ProcessInput;
end;
procedure TGLCustomConsole.AddLine(const str: string);
begin
FColsoleLog.Text := FColsoleLog.Text + str + #10;
FStartLine := FColsoleLog.Count - numLines;
RefreshHud;
end;
procedure TGLCustomConsole.CommandIssued(var UserInputCommand:
TGLUserInputCommand);
var
MainCommand: string;
I: Integer;
begin
if UserInputCommand.CommandCount = 0 then
Exit;
MainCommand := LowerCase(UserInputCommand.Strings[0]);
if FCommands.Count <> 0 then
for I := 0 to FCommands.Count - 1 do
if MainCommand = LowerCase(FCommands[I].FCommandName) then
begin
//show help
if UserInputCommand.CommandCount > 1 then
begin
//I hope I didn't forget anything ;)
if (UserInputCommand.Strings[1] = '/?') or
(UserInputCommand.Strings[1] = '\?') or
(UserInputCommand.Strings[1] = '-?') or
(UserInputCommand.Strings[1] = '--?') or
(UserInputCommand.Strings[1] = '/help') or
(UserInputCommand.Strings[1] = '\help') or
(UserInputCommand.Strings[1] = '-help') or
(UserInputCommand.Strings[1] = '--help') then
FCommands[I].ShowHelp
else
//or execute the asosiated event
FCommands[I].DoOnCommand(UserInputCommand);
end
else
//or execute the asosiated event
FCommands[I].DoOnCommand(UserInputCommand);
//recognize the command
UserInputCommand.UnknownCommand := False;
break;
end;
//external command processing event
DoOnCommandIssued(UserInputCommand);
if UserInputCommand.UnknownCommand then
HandleUnknownCommand(UserInputCommand.Strings[0]);
end;
procedure TGLCustomConsole.RefreshHudSize;
begin
if FSceneViewer <> nil then
begin
FHudSprite.Width := FSceneViewer.Width;
FHudSprite.Height := FSceneViewer.Height * FSize;
end
else
begin
FHudSprite.Width := conDefaultConsoleWidth;
FHudSprite.Height := conDefaultConsoleHeight;
end;
FHudSprite.Position.X := FHudSprite.Width / 2;
FHudSprite.Position.Y := FHudSprite.Height / 2;
RefreshHud;
end;
procedure TGLCustomConsole.SetFontColor(const Color: TColor);
begin
FHUDText.ModulateColor.AsWinColor := Color;
FHUDText.Material.FrontProperties.Ambient.AsWinColor := Color;
end;
procedure TGLCustomConsole.ShowConsoleHelp;
var
I: Integer;
begin
if (FCommands.Count = 0) and (FAdditionalCommands.Count = 0) then
AddLine(' - There are no registered commands!')
else
begin
if FCommands.Count <> 0 then
begin
AddLine(' - List of registered console commands:');
for I := 0 to FCommands.Count - 1 do
FCommands[I].ShowShortHelp;
end;
if FAdditionalCommands.Count <> 0 then
begin
AddLine(' - List of additional console commands:');
for I := 0 to FAdditionalCommands.Count - 1 do
AddLine(' - ' + FAdditionalCommands[I]);
end;
end;
end;
procedure TGLCustomConsole.ClearTypedCommands;
begin
FTypedCommands.Clear;
FCurrentCommand := 0;
end;
{$WARNINGS off}
procedure TGLCustomConsole.AutoCompleteCommand(var MatchCount: Integer;
var AdditionalCommandsMatchList: TGLConsoleMatchList;
var CommandsMatchList: TGLConsoleMatchList);
var
I: Integer;
HasEnterKey: Boolean;
NewInputLine, FirstMatch: string;
NewMatchCount, FirstMatchIndex: Integer;
begin
MatchCount := 0;
AdditionalCommandsMatchList := [];
CommandsMatchList := [];
if FInputLine <> '' then
begin
//delete the last "Enter" key, if there is any
if FInputLine[Length(FInputLine)] = #13 then
begin
Delete(FInputLine, Length(FInputLine), 1);
HasEnterKey := True;
end;
//find all the matches
if FAdditionalCommands.Count <> 0 then
for I := 0 to FAdditionalCommands.Count - 1 do
if AnsiStartsText(FInputLine, FAdditionalCommands[I]) then
begin
Inc(MatchCount);
AdditionalCommandsMatchList := AdditionalCommandsMatchList + [I];
end;
if FCommands.Count <> 0 then
for I := 0 to FCommands.Count - 1 do
if FCommands[I].FVisible then
if AnsiStartsText(FInputLine, FCommands[I].FCommandName) then
begin
Inc(MatchCount);
CommandsMatchList := CommandsMatchList + [I];
end;
//if there is only one, fill it up!
if MatchCount = 1 then
begin
if AdditionalCommandsMatchList <> [] then
for I := 0 to CONSOLE_MAX_COMMANDS do
if I in AdditionalCommandsMatchList then
begin
FInputLine := FAdditionalCommands[I];
break;
end;
if CommandsMatchList <> [] then
for I := 0 to CONSOLE_MAX_COMMANDS do
if I in CommandsMatchList then
begin
FInputLine := FCommands[I].FCommandName;
break;
end;
end
else
{//if more than 1, try to complete other letters} if MatchCount > 1 then
begin
NewInputLine := FInputLine;
//find 1st match
if AdditionalCommandsMatchList <> [] then
for I := 0 to CONSOLE_MAX_COMMANDS do
if I in AdditionalCommandsMatchList then
begin
FirstMatch := FAdditionalCommands[I];
FirstMatchIndex := I;
break;
end;
if AdditionalCommandsMatchList = [] then
for I := 0 to CONSOLE_MAX_COMMANDS do
if I in CommandsMatchList then
begin
FirstMatch := FCommands[I].FCommandName;
FirstMatchIndex := I;
break;
end;
NewMatchCount := MatchCount;
while (NewMatchCount = MatchCount) and (Length(NewInputLine) <>
Length(FirstMatch)) do
begin
NewInputLine := NewInputLine + FirstMatch[Length(NewInputLine) + 1];
NewMatchCount := 0;
if AdditionalCommandsMatchList <> [] then
for I := FirstMatchIndex to FAdditionalCommands.Count - 1 do
if AnsiStartsText(NewInputLine, FAdditionalCommands[I]) then
Inc(NewMatchCount);
if AdditionalCommandsMatchList = [] then
begin
for I := FirstMatchIndex to FCommands.Count - 1 do
if AnsiStartsText(NewInputLine, FCommands[I].FCommandName) then
Inc(NewMatchCount);
end
else if CommandsMatchList <> [] then
begin
for I := 0 to FCommands.Count - 1 do
if AnsiStartsText(NewInputLine, FCommands[I].FCommandName) then
Inc(NewMatchCount);
end;
end;
FInputLine := NewInputLine;
if NewMatchCount <> MatchCount then
Delete(FInputLine, Length(NewInputLine), 1);
end;
//Restore the #13 key
if HasEnterKey then
FInputLine := FInputLine + #13;
end;
end;
{$WARNINGS on}
procedure TGLCustomConsole.AutoCompleteCommand;
var
MatchCount: Integer;
AdditionalCommandsMatchList: TGLConsoleMatchList;
CommandsMatchList: TGLConsoleMatchList;
begin
AutoCompleteCommand(MatchCount, AdditionalCommandsMatchList,
CommandsMatchList);
end;
procedure TGLCustomConsole.RegisterBuiltInCommands;
begin
{ Special commands }
with FCommands.Add do
begin
FCommandName := '?';
FShortHelp := 'displays help for a single command or all commands';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandHelp;
end;
with FCommands.Add do
begin
FCommandName := 'Help';
FShortHelp := 'displays help for a single command or all commands';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandHelp;
end;
with FCommands.Add do
begin
FCommandName := 'cls';
FShortHelp := 'clears screen';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandClearScreen;
end;
{ Console commands }
with FCommands.Add do
begin
FCommandName := 'Console.Hide';
FShortHelp := 'hides the console';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandConsoleHide;
end;
with FCommands.Add do
begin
FCommandName := 'Console.Color';
FShortHelp := 'displays and allows to change the color of the console';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandConsoleColor;
end;
with FCommands.Add do
begin
FCommandName := 'Console.Ren';
FShortHelp := 'renames any command';
// FLongHelp.Add('') not needed here, because is has an OnHelp event
FOnCommand := ProcessInternalCommandConsoleRename;
FOnHelp := GetHelpInternalCommandRename;
end;
with FCommands.Add do
begin
FCommandName := 'Console.ClearTypedCommands';
FShortHelp := 'clears Typed Commands list';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandConsoleClearTypedCommands;
end;
{ System commands }
with FCommands.Add do
begin
FCommandName := 'System.Time';
FShortHelp := 'displays current system time';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandSystemTime;
end;
with FCommands.Add do
begin
FCommandName := 'System.Date';
FShortHelp := 'displays current system date';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandSystemDate;
end;
{ Viewer commands }
with FCommands.Add do
begin
FCommandName := 'Viewer.FPS';
FShortHelp := 'displays GLSceneViewer FPS';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandViewerFPS;
end;
with FCommands.Add do
begin
FCommandName := 'Viewer.ResetPerformanceMonitor';
FShortHelp := 'resets GLSceneViewer FPS monitor';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandViewerResetPerformanceMonitor;
end;
with FCommands.Add do
begin
FCommandName := 'Viewer.VSync';
FShortHelp := 'displays and allows to change GLSceneViewer VSync';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandViewerVSync;
end;
with FCommands.Add do
begin
FCommandName := 'Viewer.AntiAliasing';
FShortHelp := 'displays and allows to change GLSceneViewer AntiAliasing';
FLongHelp.Add(FShortHelp);
FOnCommand := ProcessInternalCommandViewerAntiAliasing;
end;
end;
procedure TGLCustomConsole.HandleUnknownCommand(const Command: string);
begin
AddLine(' - Command "' + Command + '" not recognized!');
if coShowConsoleHelpIfUnknownCommand in FOptions then
ShowConsoleHelp;
end;
procedure TGLCustomConsole.NavigateDown;
begin
Inc(FStartLine);
if FStartLine > FColsoleLog.Count - numlines then
FStartLine := FColsoleLog.Count - numlines;
if FStartLine < 0 then
FStartLine := 0;
end;
procedure TGLCustomConsole.NavigatePageDown;
begin
Inc(FStartLine, NumLines);
if FStartLine > FColsoleLog.Count - numlines then
FStartLine := FColsoleLog.Count - numlines;
if FStartLine < 0 then
FStartLine := 0;
end;
procedure TGLCustomConsole.NavigatePageUp;
begin
Dec(FStartLine, NumLines);
if FStartLine > FColsoleLog.Count - numlines then
FStartLine := FColsoleLog.Count - numlines;
if FStartLine < 0 then
FStartLine := 0;
end;
procedure TGLCustomConsole.NavigateUp;
begin
Dec(FStartLine);
if FStartLine > FColsoleLog.Count - numlines then
FStartLine := FColsoleLog.Count - numlines;
if FStartLine < 0 then
FStartLine := 0;
end;
function TGLCustomConsole.GetFontColor: TColor;
begin
Result := FHUDText.ModulateColor.AsWinColor;
end;
function TGLCustomConsole.GetHUDSpriteColor: TColor;
begin
if Assigned(HUDSprite.Material.MaterialLibrary)
and (HUDSprite.Material.MaterialLibrary is TGLMaterialLibrary)
and (HUDSprite.Material.LibMaterialName <> '') then
Result :=
TGLMaterialLibrary(HUDSprite.Material.MaterialLibrary).LibMaterialByName(HUDSprite.Material.LibMaterialName).Material.FrontProperties.Ambient.AsWinColor
else
Result := HUDSprite.Material.FrontProperties.Ambient.AsWinColor;
end;
procedure TGLCustomConsole.SetHUDSpriteColor(const Color: TColor);
begin
if Assigned(HUDSprite.Material.MaterialLibrary)
and (HUDSprite.Material.MaterialLibrary is TGLMaterialLibrary)
and (HUDSprite.Material.LibMaterialName <> '') then
TGLMaterialLibrary(HUDSprite.Material.MaterialLibrary).LibMaterialByName(HUDSprite.Material.LibMaterialName).Material.FrontProperties.Ambient.AsWinColor := Color
else
HUDSprite.Material.FrontProperties.Ambient.AsWinColor := Color;
end;
procedure TGLCustomConsole.SetSize(const Value: Single);
begin
if (Value <= 0) or (Value > 1) then
raise EGLConsoleException.Create('Size must be between 0 and 1!')
else
begin
FSize := Value;
RefreshHudSize;
end;
end;
procedure TGLCustomConsole.DoOnCommandIssued(var UserInputCommand:
TGLUserInputCommand);
begin
if Assigned(FOnCommandIssued) then
FOnCommandIssued(nil, Self, UserInputCommand);
end;
procedure TGLCustomConsole.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = FSceneViewer then
FSceneViewer := nil;
if AComponent = FHudSprite then
FHudSprite := nil;
if AComponent = FHudText then
FHudText := nil;
end;
end;
procedure TGLCustomConsole.SetSceneViewer(
const Value: TGLSceneViewer);
begin
if FSceneViewer <> nil then
FSceneViewer.RemoveFreeNotification(Self);
FSceneViewer := Value;
if FSceneViewer <> nil then
begin
FSceneViewer.FreeNotification(Self);
RefreshHudSize;
end;
end;
function TGLCustomConsole.GetFont: TGLCustomBitmapFont;
begin
Result := FHudText.BitmapFont;
end;
procedure TGLCustomConsole.SetFont(const Value: TGLCustomBitmapFont);
begin
FHudText.BitmapFont := Value;
end;
procedure TGLCustomConsole.SetName(const Value: TComponentName);
begin
inherited;
FHudSprite.Name := Value + 'HudSprite';
FHudText.Name := Value + 'HudText';
end;
{ TGLConsoleControls }
procedure TGLConsoleControls.Assign(Source: TPersistent);
begin
if Source is TGLConsoleControls then
begin
FNavigateUp := TGLConsoleControls(Source).FNavigateUp;
FNavigateDown := TGLConsoleControls(Source).FNavigateDown;
FNavigatePageUp := TGLConsoleControls(Source).FNavigatePageUp;
FNavigatePageDown := TGLConsoleControls(Source).FNavigatePageDown;
FNextCommand := TGLConsoleControls(Source).FNextCommand;
FPreviousCommand := TGLConsoleControls(Source).FPreviousCommand;
FAutoCompleteCommand := TGLConsoleControls(Source).FAutoCompleteCommand;
FDblClickDelay := TGLConsoleControls(Source).FDblClickDelay;
end;
end;
constructor TGLConsoleControls.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FNavigateUp := glKey_HOME;
FNavigateDown := glKey_END;
FNavigatePageUp := glKey_PRIOR;
FNavigatePageDown := glKey_NEXT;
FNextCommand := glKey_DOWN;
FPreviousCommand := glKey_UP;
FAutoCompleteCommand := glKey_CONTROL;
FDblClickDelay := 300;
end;
function TGLConsoleControls.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{ TGLConsoleCommand }
procedure TGLConsoleCommand.Assign(Source: TPersistent);
begin
Assert(Source <> nil);
inherited;
SetCommandName(TGLConsoleCommand(Source).FCommandName);
FShortHelp := TGLConsoleCommand(Source).FShortHelp;
FLongHelp.Assign(TGLConsoleCommand(Source).FLongHelp);
FVisible := TGLConsoleCommand(Source).FVisible;
FEnabled := TGLConsoleCommand(Source).FEnabled;
FSilentDisabled := TGLConsoleCommand(Source).FSilentDisabled;
end;
constructor TGLConsoleCommand.Create(Collection: TCollection);
begin
inherited;
Assert((Collection is TGLConsoleCommandList) or (Collection = nil));
FCommandList := TGLConsoleCommandList(Collection);
FLongHelp := TStringList.Create;
FVisible := True;
FEnabled := True;
end;
destructor TGLConsoleCommand.Destroy;
begin
FLongHelp.Destroy;
inherited;
end;
procedure TGLConsoleCommand.ShowInvalidUseOfCommandError;
begin
FCommandList.FConsole.AddLine(' - Invalid use of command!');
end;
procedure TGLConsoleCommand.ShowInvalidNumberOfArgumentsError(const
ShowHelpAfter: Boolean);
begin
FCommandList.FConsole.AddLine(' - Invalid number of arguments!');
if ShowHelpAfter then
ShowHelp;
end;
procedure TGLConsoleCommand.SetCommandName(const Value: string);
begin
//the name must be unique
if FCommandList.CommandExists(Value) or
FCommandList.FConsole.FAdditionalCommands.CommandExists(Value) then
begin
raise EGLConsoleException.Create(STR_NO_DUPLICATE_NAMES_ALLOWED);
Exit;
end;
FCommandName := Value;
end;
procedure TGLConsoleCommand.ShowHelp;
var
I: Integer;
begin
if Assigned(FOnHelp) then
FOnHelp(Self)
else if FLongHelp.Count <> 0 then
for I := 0 to FLongHelp.Count - 1 do
FCommandList.FConsole.AddLine(' - ' + FLongHelp[I]);
end;
procedure TGLConsoleCommand.DoOnCommand(var UserInputCommand:
TGLUserInputCommand);
begin
Assert(Assigned(FOnCommand));
if FEnabled then
FOnCommand(Self, FCommandList.FConsole, UserInputCommand)
else
begin
if not FSilentDisabled then
FCommandList.FConsole.AddLine(' - Command "' + FCommandName +
'" has been disabled!');
end;
end;
procedure TGLConsoleCommand.ShowShortHelp;
begin
if FVisible then
FCommandList.FConsole.AddLine(' - ' + FCommandName + ' - ' + FShortHelp);
end;
function TGLConsoleCommand.GetDisplayName: string;
begin
if FCommandName = '' then
Result := inherited GetDisplayName
else
Result := FCommandName;
end;
{ TGLConsoleCommandList }
function TGLConsoleCommandList.Add: TGLConsoleCommand;
begin
Result := TGLConsoleCommand(inherited Add);
end;
constructor TGLConsoleCommandList.Create(const AOwner: TGLCustomConsole);
begin
Assert(AOwner <> nil);
FConsole := TGLCustomConsole(AOwner);
inherited Create(TGLConsoleCommand);
end;
destructor TGLConsoleCommandList.Destroy;
begin
Clear;
inherited;
end;
function TGLConsoleCommandList.GetItems(const Index: Integer):
TGLConsoleCommand;
begin
Result := TGLConsoleCommand(inherited Items[Index]);
end;
function TGLConsoleCommandList.LastConsoleCommand: TGLConsoleCommand;
begin
Result := GetItems(Count - 1);
end;
procedure TGLConsoleCommandList.SortCommands(const Ascending: Boolean);
begin
Assert(False, 'Not implemented yet....');
end;
function TGLConsoleCommandList.CommandExists(const Command: string): Boolean;
var
I: Integer;
begin
Result := True;
if Count <> 0 then
for I := 0 to Count - 1 do
if GetItems(I).FCommandName = Command then
Exit;
Result := False;
end;
function TGLConsoleCommandList.GetCommandIndex(const Command: string): Integer;
begin
if Count <> 0 then
for Result := 0 to Count - 1 do
if GetItems(Result).FCommandName = Command then
Exit;
Result := -1;
end;
function TGLConsoleCommandList.GetOwner: TPersistent;
begin
Result := FConsole;
end;
{ TGLConsoleStringList }
procedure TGLConsoleStringList.Changed;
begin
inherited;
//we'll just assume that user added a command and check it,
//other cases are not dealt with
if Count = 0 then
Exit;
//check if this command does not duplicate any existing
if FConsole.FCommands.CommandExists(Strings[Count - 1]) then
Delete(Count - 1);
end;
function TGLConsoleStringList.CommandExists(const Command: string): Boolean;
begin
Result := IndexOf(Command) <> -1;
end;
constructor TGLConsoleStringList.Create(const Owner: TGLCustomConsole);
begin
Assert(Owner <> nil);
Duplicates := dupError;
FConsole := Owner;
end;
function TGLConsoleStringList.GetOwner: TPersistent;
begin
Result := FConsole;
end;
initialization
RegisterClasses([TGLCustomConsole, TGLConsole, TGLConsoleStringList,
TGLConsoleCommand, TGLConsoleCommandList, TGLConsoleControls]);
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.KinveyMetaTypes;
interface
uses
System.Classes,
System.SysUtils,
System.JSON,
REST.Backend.MetaTypes,
REST.Backend.KinveyApi;
type
TMetaFactory = class(TInterfacedObject, IBackendMetaFactory, IBackendMetaClassFactory,
IBackendMetaClassObjectFactory, IBackendMetaUserFactory, IBackendMetaDataTypeFactory,
IBackendMetaFileFactory)
protected
{ IBackendMetaClassFactory }
function CreateMetaClass(const AClassName: string): TBackendMetaClass;
{ IBackendMetaClassObjectFactory }
function CreateMetaClassObject(const AClassName, AObjectID: string): TBackendEntityValue;
{ IBackendMetaUserFactory }
function CreateMetaUserObject(const AObjectID: string): TBackendEntityValue;
{ IBackendMetaDataTypeFactory }
function CreateMetaDataType(const ADataType, ABackendClassName: string): TBackendMetaClass;
{ IBackendMetaFileFactory }
function CreateMetaFileObject(const AFileID: string): TBackendEntityValue;
end;
// Describe a backend class
TMetaClass = class(TInterfacedObject, IBackendMetaObject)
private
FClassName: string;
FDataType: string;
protected
function GetClassName: string;
function GetDataType: string;
public
constructor Create(const AClassName: string); overload;
constructor Create(const ADataType, AClassName: string); overload;
end;
// Defined backend class with ClassName property
TMetaClassName = class(TMetaClass, IBackendMetaClass, IBackendClassName)
end;
// Defined backend class with ClassName and datatype property
TMetaDataType = class(TMetaClass, IBackendMetaClass, IBackendClassName, IBackendDataType)
end;
// Describe an object
TMetaObject = class(TInterfacedObject, IBackendMetaObject)
private
FObjectID: TKinveyAPI.TObjectID;
protected
function GetObjectID: string;
function GetCreatedAt: TDateTime;
function GetUpdatedAt: TDateTime;
function GetClassName: string;
public
constructor Create(const AObjectID: TKinveyAPI.TObjectID);
property ObjectID: TKinveyAPI.TObjectID read FObjectID;
end;
// Describe a user object
TMetaUser = class(TInterfacedObject, IBackendMetaObject)
private
FUser: TKinveyAPI.TUser;
protected
function GetObjectID: string;
function GetCreatedAt: TDateTime;
function GetUpdatedAt: TDateTime;
function GetUserName: string;
public
constructor Create(const AUser: TKinveyAPI.TUser);
property User: TKinveyAPI.TUser read FUser;
end;
// Describe an logged in user
TMetaLogin = class(TMetaUser)
private
FLogin: TKinveyAPI.TLogin;
protected
function GetAuthTOken: string;
public
constructor Create(const ALogin: TKinveyAPI.TLogin);
property Login: TKinveyAPI.TLogin read FLogin;
end;
// Describe an uploaded file
TMetaFile = class(TInterfacedObject, IBackendMetaObject)
private
FFile: TKinveyAPI.TFile;
protected
function GetDownloadURL: string;
function GetFileName: string;
function GetExpiresAt: TDateTime;
function GetFileID: string;
public
constructor Create(const AFile: TKinveyAPI.TFile);
property FileValue: TKinveyAPI.TFile read FFile;
end;
TMetaUploadedFile = class(TMetaFile, IBackendMetaObject,
IBackendFileID, IBackendDownloadURL, IBackendFileName, IBackendExpiresAt)
end;
TMetaFileObject = class(TMetaFile, IBackendMetaObject,
IBackendFileID, IBackendDownloadURL, IBackendFileName, IBackendExpiresAt)
end;
// Define MetaObject with ObjectID and CreatedAt properties
TMetaCreatedObject = class(TMetaObject, IBackendMetaObject,
IBackendObjectID, IBackendClassName, IBackendCreatedAt)
end;
// Define MetaObject with ObjectID and BackendClassName properties
TMetaClassObject = class(TMetaObject, IBackendMetaObject, IBackendClassName,
IBackendObjectID)
end;
// Define MetaObject with UpdatedAt properties
TMetaUpdatedObjectAt = class(TMetaObject, IBackendMetaObject, IBackendUpdatedAt)
end;
TMetaFoundObject = class(TMetaObject, IBackendMetaObject, IBackendClassName,
IBackendObjectID, IBackendCreatedAt, IBackendUpdatedAt)
end;
// Define MetaObject with ObjectID and BackendClassName properties
TMetaUserObject = class(TMetaObject, IBackendObjectID)
end;
// Define MetaObject with UpdatedAt properties
TMetaUpdatedUser = class(TMetaUser, IBackendMetaObject, IBackendUpdatedAt, IBackendUserName)
end;
TMetaFoundUser = class(TMetaUser, IBackendMetaObject,
IBackendObjectID, IBackendCreatedAt, IBackendUpdatedAt, IBackendUserName)
end;
TMetaLoginUser = class(TMetaLogin, IBackendMetaObject,
IBackendObjectID, IBackendCreatedAt, IBackendUpdatedAt, IBackendUserName, IBackendAuthToken)
end;
TMetaSignupUser = class(TMetaLogin, IBackendMetaObject,
IBackendObjectID, IBackendCreatedAt, IBackendUserName, IBackendAuthToken)
end;
// Define MetaObject with UpdatedAt properties
TMetaUpdatedUserAt = class(TMetaObject, IBackendMetaObject, IBackendUpdatedAt)
private
FUpdatedAt: TKinveyAPI.TUpdatedAt;
protected
function GetUpdatedAt: TDateTime;
public
constructor Create(const AUpdatedAt: TKinveyAPI.TUpdatedAt);
property UpdatedAt: TKinveyAPI.TUpdatedAt read FUpdatedAt;
end;
TKinveyMetaFactory = class
private
public
class function CreateMetaClass(const AClassName: string): TBackendMetaClass; static;
// Classes/Objects
class function CreateMetaClassObject(const AClassName, AObjectID: string): TBackendEntityValue; overload;static;
class function CreateMetaClassObject(const AObjectID: TKinveyAPI.TObjectID): TBackendEntityValue; overload;static;
class function CreateMetaCreatedObject(const AObjectID: TKinveyAPI.TObjectID): TBackendEntityValue; static;
class function CreateMetaFoundObject(const AObjectID: TKinveyAPI.TObjectID): TBackendEntityValue; static;
class function CreateMetaUpdatedObject(const AObjectID: TKinveyAPI.TObjectID): TBackendEntityValue; overload; static;
// Query
class function CreateMetaDataType(const ADataType,
AClassName: string): TBackendMetaClass; static;
// Users
class function CreateMetaUserObject(const AObjectID: string): TBackendEntityValue; overload;static;
class function CreateMetaUserObject(const AUser: TKinveyAPI.TUser): TBackendEntityValue; overload;static;
class function CreateMetaFoundUser(const AUser: TKinveyAPI.TUser): TBackendEntityValue; static;
class function CreateMetaUpdatedUser(const AUpdatedAt: TKinveyAPI.TUpdatedAt): TBackendEntityValue; overload; static;
class function CreateMetaSignupUser(const ALogin: TKinveyAPI.TLogin): TBackendEntityValue; overload; static;
class function CreateMetaLoginUser(const ALogin: TKinveyAPI.TLogin): TBackendEntityValue; overload; static;
// Files
class function CreateMetaUploadedFile(const AFile: TKinveyAPI.TFile): TBackendEntityValue;
class function CreateMetaFileObject(const AFileID: string): TBackendEntityValue;
end;
implementation
{ TMetaClass }
constructor TMetaClass.Create(const AClassName: string);
begin
inherited Create;
FClassName := AClassName;
end;
constructor TMetaClass.Create(const ADataType, AClassName: string);
begin
Create(AClassName);
FDataType := ADataType;
end;
function TMetaClass.GetClassName: string;
begin
Result := FClassName;
end;
function TMetaClass.GetDataType: string;
begin
Result := FDataType;
end;
{ TMetaObject }
constructor TMetaObject.Create(const AObjectID: TKinveyAPI.TObjectID);
begin
inherited Create;
FObjectID := AObjectID;
end;
function TMetaObject.GetCreatedAt: TDateTime;
begin
Result := FObjectID.CreatedAt;
end;
function TMetaObject.GetObjectID: string;
begin
Result := FObjectID.ObjectID;
end;
function TMetaObject.GetUpdatedAt: TDateTime;
begin
Result := FObjectID.UpdatedAt;
end;
function TMetaObject.GetClassName: string;
begin
Result := FObjectID.BackendCollectionName;
end;
{ TMetaUser }
constructor TMetaUser.Create(const AUser: TKinveyAPI.TUser);
begin
inherited Create;
FUser := AUser;
end;
function TMetaUser.GetCreatedAt: TDateTime;
begin
Result := FUser.CreatedAt;
end;
function TMetaUser.GetObjectID: string;
begin
Result := FUser.ObjectID;
end;
function TMetaUser.GetUpdatedAt: TDateTime;
begin
Result := FUser.UpdatedAt;
end;
function TMetaUser.GetUserName: string;
begin
Result := FUser.UserName;
end;
{ TMetaFactory }
function TMetaFactory.CreateMetaClass(
const AClassName: string): TBackendMetaClass;
begin
Result := TKinveyMetaFactory.CreateMetaClass(AClassName);
end;
function TMetaFactory.CreateMetaClassObject(
const AClassName: string; const AObjectID: string): TBackendEntityValue;
begin
Result := TKinveyMetaFactory.CreateMetaClassObject(AClassName, AObjectID);
end;
function TMetaFactory.CreateMetaDataType(const ADataType,
ABackendClassName: string): TBackendMetaClass;
begin
Result := TKinveyMetaFactory.CreateMetaDataType(ADataType, ABackendClassName);
end;
function TMetaFactory.CreateMetaFileObject(
const AFileID: string): TBackendEntityValue;
begin
Result := TKinveyMetaFactory.CreateMetaFileObject(AFileID);
end;
function TMetaFactory.CreateMetaUserObject(
const AObjectID: string): TBackendEntityValue;
begin
Result := TKinveyMetaFactory.CreateMetaUserObject(AObjectID);
end;
{ TKinveyMetaFactory }
class function TKinveyMetaFactory.CreateMetaClass(
const AClassName: string): TBackendMetaClass;
var
LIntf: IBackendMetaClass;
begin
LIntf := TMetaClassName.Create(AClassName);
Assert(Supports(LIntf, IBackendClassName));
Result := TBackendMetaClass.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaClassObject(
const AClassName: string; const AObjectID: string): TBackendEntityValue;
var
LObjectID: TKinveyAPI.TObjectID;
begin
LObjectID := TKinveyAPI.TObjectID.Create(AClassName, AObjectID);
Result := CreateMetaClassObject(LObjectID);
end;
class function TKinveyMetaFactory.CreateMetaClassObject(
const AObjectID: TKinveyAPI.TObjectID): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaClassObject.Create(AObjectID);
Assert(Supports(LIntf, IBackendClassName));
Assert(Supports(LIntf, IBackendObjectID));
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaCreatedObject(
const AObjectID: TKinveyAPI.TObjectID): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaCreatedObject.Create(AObjectID);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaFileObject(
const AFileID: string): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
LFile: TKinveyAPI.TFile;
begin
LFile := TKinveyAPI.TFile.Create(AFileID);
LIntf := TMetaFileObject.Create(LFile);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaFoundObject(
const AObjectID: TKinveyAPI.TObjectID): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundObject.Create(AObjectID);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaFoundUser(
const AUser: TKinveyAPI.TUser): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundUser.Create(AUser);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaLoginUser(
const ALogin: TKinveyAPI.TLogin): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaLoginUser.Create(ALogin);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaDataType(const ADataType,
AClassName: string): TBackendMetaClass;
var
LIntf: IBackendMetaClass;
begin
LIntf := TMetaDataType.Create(ADataType, AClassName);
Result := TBackendMetaClass.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaSignupUser(
const ALogin: TKinveyAPI.TLogin): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaSignupUser.Create(ALogin);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaUpdatedObject(
const AObjectID: TKinveyAPI.TObjectID): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaUpdatedObjectAt.Create(AObjectID);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaUpdatedUser(
const AUpdatedAt: TKinveyAPI.TUpdatedAt): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaUpdatedUserAt.Create(AUpdatedAt);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaUserObject(
const AUser: TKinveyAPI.TUser): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaFoundUser.Create(AUser);
Result := TBackendEntityValue.Create(LIntf);
end;
class function TKinveyMetaFactory.CreateMetaUserObject(
const AObjectID: string): TBackendEntityValue;
var
LObjectID: TKinveyAPI.TUser;
begin
LObjectID := TKinveyAPI.TUser.Create(AObjectID);
Result := CreateMetaUserObject(LObjectID);
end;
class function TKinveyMetaFactory.CreateMetaUploadedFile(
const AFile: TKinveyAPI.TFile): TBackendEntityValue;
var
LIntf: IBackendMetaObject;
begin
LIntf := TMetaUploadedFile.Create(AFile);
Result := TBackendEntityValue.Create(LIntf);
end;
{ TMetaUpdatedUserAt }
constructor TMetaUpdatedUserAt.Create(const AUpdatedAt: TKinveyAPI.TUpdatedAt);
begin
FUpdatedAt := AUpdatedAt;
end;
function TMetaUpdatedUserAt.GetUpdatedAt: TDateTime;
begin
Result := FUpdatedAt.UpdatedAt;
end;
{ TMetaLogin }
constructor TMetaLogin.Create(const ALogin: TKinveyAPI.TLogin);
begin
FLogin := ALogin;
inherited Create(FLogin.User);
end;
function TMetaLogin.GetAuthTOken: string;
begin
Result := FLogin.AuthToken;
end;
{ TMetaFile }
constructor TMetaFile.Create(const AFile: TKinveyAPI.TFile);
begin
FFile := AFile;
end;
function TMetaFile.GetExpiresAt: TDateTime;
begin
Result := FFile.ExpiresAt;
end;
function TMetaFile.GetFileID: string;
begin
Result := FFile.ID;
end;
function TMetaFile.GetFileName: string;
begin
Result := FFile.FileName;
end;
function TMetaFile.GetDownloadURL: string;
begin
Result := FFile.DownloadURL;
end;
end.
|
unit xProtocolPacksDL645_97;
interface
uses System.Types, xProtocolPacks, System.Classes, system.SysUtils, xDL645Type,
xFunction, xMeterDataRect, xProtocolPacksDl645;
type
TProtocolPacksDl645_97 = class(TProtocolPacksDl645)
private
protected
function CreatePackReadNextData: TBytes;override; // 读后续数据
function CreatePackReadAddr: TBytes;override; // 读通信地址
function CreatePackWriteData: TBytes;override; // 写数据
function CreatePackChangePWD: TBytes;override; // 改密码
function CreatePackClearMaxDemand: TBytes;override; // 最大需量清零
function CreatePackSetWOutType: TBytes;override; // 设置多功能口
function CreatePackIdentity: TBytes;override; // 身份认证
function CreatePackOnOffControl: TBytes;override; // 费控 拉合闸
/// <summary>
/// 解析接收到的数据包
/// </summary>
procedure ParseRevPack( APack : TBytes ); override;
procedure ParsePackReadData(APack : TBytes); // 解析读数据
procedure ParsePackNextData(APack : TBytes); // 解析读后续数据
procedure ParsePackReadAddr(APack : TBytes); // 解析读地址
function GetBaudRateCode( sBaudRate : string ) : Integer; override;
/// <summary>
/// 获取标识
/// </summary>
function GetSignCode( nDataSign : Int64) : TBytes; override;
/// <summary>
/// 获取控制码
/// </summary>
function GetControlCode(ADL645Data : TDL645_DATA) : Integer; override;
/// <summary>
/// 生成数据包
/// </summary>
procedure CreatePacks(var aDatas: TBytes; nCmdType: Integer; ADevice: TObject);override;
public
constructor Create; override;
destructor Destroy; override;
public
end;
implementation
{ TProtocolPacksDl645_97 }
constructor TProtocolPacksDl645_97.Create;
begin
inherited;
end;
function TProtocolPacksDl645_97.CreatePackChangePWD: TBytes;
var
ACodes : TBytes;
i: Integer;
begin
SetLength( Result, GetSendCodeLen );
ACodes := GetSignCode(FDevice.DataSign);
// 标识
for i := 0 to Length(ACodes) - 1 do
Result[10 + i] := ACodes[i] + $33;
// 密码
Result[14] := PWDLevel;
for i := 0 to 2 do
Result[15+i] := (ShortPWD shr ((2-i)*8) + $33) and $FF;
// 数据
for i := 0 to Length(FDevice.BytesDataValue) - 1 do
Result[18 + i] := (UserCode shr ((Length(FDevice.BytesDataValue)-i-1)*8) +
$33) and $FF;
end;
function TProtocolPacksDl645_97.CreatePackClearMaxDemand: TBytes;
begin
SetLength( Result, GetSendCodeLen );
end;
function TProtocolPacksDl645_97.CreatePackIdentity: TBytes;
begin
end;
function TProtocolPacksDl645_97.CreatePackOnOffControl: TBytes;
begin
end;
function TProtocolPacksDl645_97.CreatePackReadAddr: TBytes;
var
ACodes : TBytes;
i: Integer;
begin
SetLength( Result, GetSendCodeLen );
ACodes := GetSignCode($9010);
for i := 0 to Length(ACodes) - 1 do
Result[10 + i] := ACodes[i] + $33;
end;
function TProtocolPacksDl645_97.CreatePackReadNextData: TBytes;
var
ACodes : TBytes;
i: Integer;
begin
SetLength( Result, GetSendCodeLen );
ACodes := GetSignCode(FDevice.DataSign);
for i := 0 to Length(ACodes) - 1 do
Result[10 + i] := ACodes[i] + $33;
end;
procedure TProtocolPacksDl645_97.CreatePacks(var aDatas: TBytes; nCmdType: Integer;
ADevice: TObject);
begin
inherited;
end;
function TProtocolPacksDl645_97.CreatePackSetWOutType: TBytes;
begin
end;
function TProtocolPacksDl645_97.CreatePackWriteData: TBytes;
var
ACodes : TBytes;
i: Integer;
begin
SetLength( Result, GetSendCodeLen );
ACodes := GetSignCode(FDevice.DataSign);
// 标识
for i := 0 to Length(ACodes) - 1 do
Result[10 + i] := ACodes[i] + $33;
// 数据
for i := 0 to Length(FDevice.BytesDataValue) - 1 do
Result[14 + i] := (UserCode shr ((Length(FDevice.BytesDataValue)-i-1)*8)
+ $33) and $FF;
end;
destructor TProtocolPacksDl645_97.Destroy;
begin
inherited;
end;
function TProtocolPacksDl645_97.GetBaudRateCode(sBaudRate: string): Integer;
var
nTemp : Integer;
begin
TryStrToInt( sBaudRate, nTemp );
case nTemp of
600 : Result := 2;
1200 : Result := 4;
4800 : Result := 16;
9600 : Result := 32;
19200 : Result := 64
else
Result := 8;
end;
end;
function TProtocolPacksDl645_97.GetControlCode(ADL645Data: TDL645_DATA): Integer;
begin
case FDevice.OrderType of
C_645_RESET_TIME: Result := $08;
C_645_READ_DATA: Result := $01;
C_645_READ_NEXTDATA: Result := $02;
C_645_READ_ADDR: Result := $01;
C_645_WRITE_DATA: Result := $04;
C_645_WRITE_ADDR: Result := $0A;
C_645_CHANGE_BAUD_RATE: Result := $0C;
C_645_CHANGE_PWD: Result := $0F;
C_645_CLEAR_MAX_DEMAND: Result := $10;
else
Result := 0;
end;
end;
function TProtocolPacksDl645_97.GetSignCode(nDataSign: Int64): TBytes;
begin
SetLength( Result, 2 );
Result[1] := nDataSign shr 8;
Result[0] := nDataSign and $FF;
end;
procedure TProtocolPacksDl645_97.ParseRevPack(APack: TBytes);
function IsError : Boolean;
var
A645Data : TDL645_DATA;
begin
Result := False;
if (APack[8] and $40) = $40 then
begin
A645Data := TDL645_DATA.Create;
A645Data.Assign(FDevice);
Result := True;
if APack[10] and $01 = $01 then
A645Data.RePlyError := de645_07OtherError
else if APack[10] and $02 = $02 then
A645Data.RePlyError := de645_07NoneData
else if APack[10] and $04 = $04 then
A645Data.RePlyError := de645_07PwdError
else if APack[10] and $08 = $08 then
A645Data.RePlyError := de645_07BaudNotChange
else if APack[10] and $10 = $10 then
A645Data.RePlyError := de645_07OverYearTme
else if APack[10] and $20 = $20 then
A645Data.RePlyError := de645_07OverDayTime
else if APack[10] and $40 = $40 then
A645Data.RePlyError := de645_07OverRate;
FRevList.AddObject('',A645Data);
end
end;
begin
inherited;
// 是否异常
if not IsError then
begin
case FDevice.OrderType of
C_645_READ_DATA: ParsePackReadData(APack);
C_645_READ_NEXTDATA: ParsePackNextData(APack);
C_645_READ_ADDR: ParsePackReadAddr(APack);
end;
end;
if Assigned(OnRev645Data) then
OnRev645Data(FRevList);
ClearStringList(FRevList);
end;
procedure TProtocolPacksDl645_97.ParsePackNextData(APack: TBytes);
begin
end;
procedure TProtocolPacksDl645_97.ParsePackReadAddr(APack: TBytes);
var
i: Integer;
A645Data : TDL645_DATA;
begin
A645Data := TDL645_DATA.Create;
A645Data.Assign( FDevice );
A645Data.DataReply := '';
for i := 0 to 5 do
A645Data.DataReply := IntToHex(APack[i+1],2) + A645Data.DataReply;
FRevList.AddObject( '',A645Data );
end;
procedure TProtocolPacksDl645_97.ParsePackReadData(APack: TBytes);
var
ARev : TBytes;
nIndex : Integer;
i: Integer;
A645Data : TDL645_DATA;
begin
// 68 49 00 30 07 21 20 68 91 08 33 33 34 33 33 33 33 33 C3 16
SetLength(ARev, FDevice.DataLen);
nIndex := 12;
while nIndex + FDevice.DataLen < Length(APack) do
begin
for i := 0 to Length(ARev) - 1 do
ARev[i] := APack[nIndex + i] - $33;
FDevice.BytesDataValue := ARev;
GetRvdPackData;
A645Data := TDL645_DATA.Create;
A645Data.Assign( FDevice );
FRevList.AddObject( '',A645Data );
nIndex := nIndex + FDevice.DataLen;
// 数据块用AA分割
if APack[nIndex] = $AA then
Inc(nIndex);
end;
end;
end.
|
unit ucadTransCxControls;
interface
uses
SysUtils,
classes,
ufmTranslator;
type
TcxPageControlTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxCustomTabControlTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxCustomLabelTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxButtonTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxCustomTextEditTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxCheckBoxTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxTabSheetTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxCustomGridTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxNavigatorControlButtonsTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxEditButtonTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxDBEditorRowTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxCategoryRowTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxComboBoxTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxDBComboBoxTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxDBCheckBoxTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxGridPopupMenuTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxEditRepositoryImageComboBoxItemTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxEditRepositoryImageItemTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxEditRepositoryCheckBoxItemTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxGridLevelTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
TcxGridDBColumnTranslator = class ( TcadCompTranslator )
function Translate(const aObj: TObject; var Translated:boolean):boolean; override;
class function Supports(const aObj: TObject): Boolean; override;
end;
// TcxGridDBTableView
function TranslateCustomEditProperties(Sender:TcadCompTranslator; const aObj, aProp: TObject; var Translated:boolean):boolean;
implementation
uses
forms,
cxButtons,
cxTextEdit,
cxLabel,
cxCheckBox,
cxDropDownEdit,
cxCalendar,
cxPC,
cxGrid,
cxGridCustomView,
cxGridChartView,
cxGridTableView,
cxGridCustomTableView,
cxGridPopupMenu,
cxGridStrs,
cxNavigator,
cxEdit,
cxDBEdit,
cxDBVGrid,
cxVGrid,
cxImageComboBox,
cxEditRepositoryItems,
cxGridLevel,
cxGridDBTableView,
cxGroupBox,
cxImage
;
// -----------------------------------------------------------------------------
class function TcxCustomLabelTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxCustomLabel);
end;
function TcxCustomLabelTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxCustomLabel(aObj) do
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxButtonTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxButton);
end;
function TcxButtonTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxButton(aObj) do
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxCustomTextEditTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxCustomTextEdit);
end;
function TcxCustomTextEditTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
if (aObj is TcxDateEdit) then
else
with TcxCustomTextEdit(aObj) do
Text := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Text', Text, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxCheckBoxTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxCheckBox);
end;
function TcxCheckBoxTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxCheckBox(aObj) do
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxTabSheetTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxTabSheet);
end;
function TcxTabSheetTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxTabSheet(aObj) do
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxCustomGridTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxCustomGrid);
end;
function TcxCustomGridTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i, k : integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxCustomGrid(aObj) do
for i:=0 to Viewcount-1 do begin
if Views[i].ViewInfo is TcxGridChartViewInfo then begin
beep;
end;
if Views[i].ViewInfo is TcxGridTableViewInfo then begin
TcxGridTableViewInfo(Views[i].ViewInfo).GroupByBoxViewInfo.Text :=
TranslateProp(aObj, GetOwnerClassName(aObj), TcxCustomGrid(aObj).Name,
Views[i].Name +'.GroupByBoxViewInfo.Text',
TcxGridTableViewInfo(Views[i].ViewInfo).GroupByBoxViewInfo.Text, Translated);
TcxGridTableViewInfo(Views[i].ViewInfo).HeaderViewInfo.Text :=
TranslateProp(aObj, GetOwnerClassName(aObj), TcxCustomGrid(aObj).Name,
Views[i].Name +'.HeaderViewInfo.Text',
TcxGridTableViewInfo(Views[i].ViewInfo).HeaderViewInfo.Text, Translated);
Views[i].Invalidate;
end;
if TcxCustomGridView(Views[i]).PopupMenu <> nil then
Translator.TranslateObj ( TcxCustomGridView(Views[i]).PopupMenu );
if Views[i].InheritsFrom(TcxCustomGridTableView) then
with TcxCustomGridTableView(Views[i]) do begin
OptionsView.NoDataToDisplayInfoText := TranslateProp(aObj, GetOwnerClassName(aObj),
TcxCustomGrid(aObj).Name, Views[i].Name +'.OptionsView.NoDataToDisplayInfoText',
OptionsView.NoDataToDisplayInfoText, Translated);
{if (OptionsView.Navigator) and (OptionsBehavior.NavigatorHints) then begin
with TcxCustomNavigatorButtons(NavigatorButtons) do
for k:=0 to ButtonCount-1 do begin
Buttons[k].Hint := TranslateProp(aObj, GetOwnerClassName(aObj),
TcxCustomGrid(aObj).Name,
Views[i].Name+'.NavigatorButton['+inttostr(k)+'].Hint',
Buttons[k].Hint, Translated);
end;
end; }
if OptionsBehavior.CellHints then begin
end;
if OptionsBehavior.NavigatorHints then begin
end;
end;
if Views[i].InheritsFrom(TcxGridTableView) then
with TcxGridTableView(Views[i]) do begin
for k:=0 to ColumnCount-1 do
Columns[k].Caption := TranslateProp(aObj, GetOwnerClassName(aObj),
TcxCustomGrid(aObj).Name,
Views[i].Name +'.'+Columns[k].Name+'.Caption',
Columns[k].Caption, Translated);
//if OptionsView.Navigator then begin
//end;
if OptionsBehavior.ColumnHeaderHints then begin
end;
end;
for k:=0 to Views[i].ComponentCount-1 do begin
TranslateProp(aObj, GetOwnerClassName(aObj), TComponent(aObj).Name,
Views[i].Name +'.'+Views[i].Components[k].ClassName, '', Translated);
end;
end;
end;
// -----------------------------------------------------------------------------
class function TcxNavigatorControlButtonsTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxCustomNavigatorButtons);
end;
function TcxNavigatorControlButtonsTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i : integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxCustomNavigatorButtons(aObj) do
for i:=0 to ButtonCount-1 do begin
Buttons[i].Hint := TranslateProp(aObj, GetOwnerClassName(aObj),
Buttons[i].ClassName, 'Hint', Buttons[i].Hint, Translated);
end;
end;
// -----------------------------------------------------------------------------
class function TcxCustomTabControlTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxCustomTabControl);
end;
function TcxCustomTabControlTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
//var
// i : integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxCustomTabControl(aObj) do
{for i:=0 to Tabs.Count-1 do begin
TranslateProp(aObj, GetOwnerClassName(aObj),
TComponent(aObj).Name + '.Tab['+inttostr(i)+'].'+Tabs[i].ClassName,
'Caption', Tabs[i].Caption, Translated);
end; }
end;
// -----------------------------------------------------------------------------
class function TcxPageControlTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxPageControl);
end;
function TcxPageControlTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i : integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxPageControl(aObj) do
for i:=0 to PageCount-1 do begin
TranslateProp(aObj, GetOwnerClassName(aObj),
TComponent(aObj).Name, Pages[i].Name +'.'+Pages[i].ClassName, '', Translated);
end;
end;
// -----------------------------------------------------------------------------
class function TcxEditButtonTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxEditButton);
end;
function TcxEditButtonTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxEditButton(aObj) do
Caption := TranslateProp(aObj, GetOwnerClassName(aObj),
TComponent(aObj).ClassName + '[' + Inttostr(Index) + ']', 'Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxDBEditorRowTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxDBEditorRow);
end;
function TcxDBEditorRowTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i: integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxDBEditorRow(aObj) do begin
if Properties.InheritsFrom(TcxCaptionRowProperties) then
with TcxCaptionRowProperties(Properties) do
Caption := TranslateProp(aObj, GetOwnerClassName(aObj),
Name, 'Properties.Caption', Properties.Caption, Translated);
if Properties.InheritsFrom(TcxCustomImageComboBoxProperties) then
with TcxCustomImageComboBoxProperties(Properties) do
for i:=0 to items.Count-1 do
if items[i].InheritsFrom(TcxImageComboBoxItems) then
with TcxImageComboBoxItem(items[i]) do
Description := TranslateProp(aObj, GetOwnerClassName(aObj), TcxDBEditorRow(aObj).Name,
'Properties.Items['+inttostr(i)+'].Description', Description, Translated);
if Properties.InheritsFrom(TcxCustomEditProperties) then
result := result or TranslateCustomEditProperties(self, aObj, Properties, Translated);
end;
end;
// -----------------------------------------------------------------------------
class function TcxCategoryRowTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxCategoryRow);
end;
function TcxCategoryRowTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxCategoryRow(aObj) do
Properties.Caption := TranslateProp(aObj, GetOwnerClassName(aObj),
Name, 'Properties.Caption', Properties.Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxComboBoxTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := aObj.InheritsFrom(TcxComboBox);
end;
function TcxComboBoxTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i : integer;
begin
result := true;
Translated := false;
if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit;
with TcxComboBox(aObj) do
if Properties.InheritsFrom(TcxCustomComboBoxProperties) then
with TcxCustomComboBoxProperties(Properties) do
for i:=0 to Items.count-1 do
Items[i] := TranslateProp(aObj, GetOwnerClassName(aObj), TcxComboBox(aObj).Name, 'Items['+inttostr(i)+']', Items[i], Translated);
end;
// -----------------------------------------------------------------------------
class function TcxDBComboBoxTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := (aObj is TcxDBComboBox);
end;
function TcxDBComboBoxTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i : integer;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TcxDBComboBox(aObj) do
if Properties.InheritsFrom(TcxCustomComboBoxProperties) then
with TcxCustomComboBoxProperties(Properties) do
for i:=0 to Items.count-1 do
Items[i] := TranslateProp(aObj, GetOwnerClassName(aObj), TcxComboBox(aObj).Name, 'Items['+inttostr(i)+']', Items[i], Translated);
end;
// -----------------------------------------------------------------------------
class function TcxDBCheckBoxTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := (aObj is TcxDBCheckBox);
end;
function TcxDBCheckBoxTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TcxDBCheckBox(aObj) do begin
Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated);
end;
end;
// -----------------------------------------------------------------------------
class function TcxGridPopupMenuTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := (aObj is TcxGridPopupMenu );
end;
function TcxGridPopupMenuTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i : integer;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TcxGridPopupMenu(aObj).PopupMenus do
for i:=0 to count-1 do
if Items[i].PopupMenu <> nil then
Translator.TranslateObj ( Items[i].PopupMenu );
end;
// -----------------------------------------------------------------------------
class function TcxEditRepositoryImageComboBoxItemTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := (aObj is TcxEditRepositoryImageComboBoxItem );
end;
function TcxEditRepositoryImageComboBoxItemTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
var
i : integer;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TcxEditRepositoryImageComboBoxItem(aObj) do
if (Properties<>nil) and
(Properties.InheritsFrom(TcxImageComboBoxProperties)) then
for I := 0 to Properties.Items.Count - 1 do
with TcxImageComboBoxItem(Properties.items[i]) do
Description := TranslateProp(aObj, GetOwnerClassName(aObj), TcxDBEditorRow(aObj).Name,
'Properties.Items['+inttostr(i)+'].Description', Description, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxEditRepositoryImageItemTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := (aObj is TcxEditRepositoryImageItem );
end;
function TcxEditRepositoryImageItemTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TcxEditRepositoryImageItem(aObj) do
if Properties<>nil then // TcxCustomImageProperties
with Properties do
Caption := TranslateProp(aObj, TcxDBCheckBox(aObj).Owner.ClassName, Name, 'Properties.Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxEditRepositoryCheckBoxItemTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := (aObj is TcxEditRepositoryCheckBoxItem );
end;
function TcxEditRepositoryCheckBoxItemTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TcxEditRepositoryCheckBoxItem(aObj) do
if Properties<>nil then begin
if Properties.InheritsFrom(TcxCustomCheckBoxProperties) then
with TcxCustomCheckBoxProperties(Properties) do begin
DisplayChecked := TranslateProp(aObj, TcxDBCheckBox(aObj).Owner.ClassName, Name, 'Properties.DisplayChecked', DisplayChecked, Translated);
DisplayGrayed := TranslateProp(aObj, TcxDBCheckBox(aObj).Owner.ClassName, Name, 'Properties.DisplayGrayed', DisplayGrayed, Translated);
DisplayUnchecked := TranslateProp(aObj, TcxDBCheckBox(aObj).Owner.ClassName, Name, 'Properties.DisplayUnchecked', DisplayUnchecked, Translated);
end;
end
end;
// -----------------------------------------------------------------------------
class function TcxGridLevelTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := (aObj is TcxGridLevel );
end;
function TcxGridLevelTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TcxGridLevel(aObj) do
Caption := TranslateProp(aObj, TcxDBCheckBox(aObj).Owner.ClassName, Name, 'Caption', Caption, Translated);
end;
// -----------------------------------------------------------------------------
class function TcxGridDBColumnTranslator.Supports(const aObj: TObject): Boolean;
begin
Result := (aObj is TcxGridDBColumn );
end;
function TcxGridDBColumnTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then
with TcxGridDBColumn(aObj) do begin
Caption := TranslateProp(aObj, TcxDBCheckBox(aObj).Owner.ClassName, Name, 'Caption', Caption, Translated);
if (Properties<>nil) and
(Properties.InheritsFrom(TcxCustomEditProperties)) then
TranslateCustomEditProperties(self, aObj, Properties, Translated)
end;
end;
// -----------------------------------------------------------------------------
function TranslateCustomEditProperties(Sender:TcadCompTranslator; const aObj, aProp: TObject; var Translated:boolean):boolean;
begin
result := true;
Translated := false;
if aObj is TcxCustomCheckBoxProperties then
with TcxCustomCheckBoxProperties(aProp) do begin
DisplayChecked := Sender.TranslateProp( aObj, TcxDBCheckBox(aObj).Owner.ClassName,
TComponent(aObj).Name, 'Properties.DisplayChecked', DisplayChecked, Translated);
DisplayGrayed := Sender.TranslateProp( aObj, TcxDBCheckBox(aObj).Owner.ClassName,
TComponent(aObj).Name, 'Properties.DisplayGrayed', DisplayGrayed, Translated);
DisplayUnchecked := Sender.TranslateProp( aObj, TcxDBCheckBox(aObj).Owner.ClassName,
TComponent(aObj).Name, 'Properties.DisplayUnchecked', DisplayUnchecked, Translated);
end;
if aObj is TcxCustomGroupBoxProperties then begin
// nada
end;
if aObj is TcxCustomImageProperties then begin
with TcxCustomImageProperties(aProp) do
Caption := Sender.TranslateProp(aObj, TcxDBCheckBox(aObj).Owner.ClassName, TComponent(aObj).Name, 'Properties.Caption', Caption, Translated);
end;
if aObj is TcxCustomLabelProperties then begin
// nada
end;
{if aObj is TcxCustomProgressBarProperties then begin
end;
if aObj is TcxCustomTrackBarProperties then begin
end;}
end;
// -----------------------------------------------------------------------------
initialization
RegisterTranslators([ TcxCustomLabelTranslator, TcxButtonTranslator, TcxCustomTextEditTranslator,
TcxCheckBoxTranslator, TcxComboBoxTranslator, TcxTabSheetTranslator,
TcxCustomGridTranslator, TcxNavigatorControlButtonsTranslator,
TcxCustomTabControlTranslator, TcxPageControlTranslator,
TcxEditButtonTranslator, TcxDBEditorRowTranslator, TcxCategoryRowTranslator,
TcxDBComboBoxTranslator, TcxDBCheckBoxTranslator, TcxGridPopupMenuTranslator,
TcxEditRepositoryImageComboBoxItemTranslator,
TcxEditRepositoryImageItemTranslator, TcxEditRepositoryCheckBoxItemTranslator,
TcxGridLevelTranslator, TcxGridDBColumnTranslator
]);
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------}
unit untStdRegComps;
interface
{$DEFINE FD_REGISTER_STD}
{$DEFINE FD_REGISTER_STD_EDITORS}
{$DEFINE FD_REGISTER_DDE}
{$DEFINE FD_REGISTER_DB}
{$DEFINE FD_REGISTER_BDE}
{$DEFINE FD_REGISTER_ADO}
{$DEFINE FD_REGISTER_ECONTROL_SYNTEDIT}
{$DEFINE FD_REGISTER_ECONTROL_FORMDESIGNER}
{.$DEFINE FD_REGISTER_DEVEX_GRIDS}
{.$DEFINE FD_REGISTER_DEVEX_EDITS}
implementation
{$R DclStd.res}
{$R ./dcr/cxGridReg.dcr}
uses
Classes, Graphics, Controls, Forms, Dialogs, ActnList, ComCtrls,
Menus, StdCtrls, ImgList, Buttons, ExtCtrls, Tabs, ExtDlgs, Mask,
Grids, CheckLst, AppEvnts, MPlayer, OleCtnrs, ADODB, DB, DBClient,
StdDsnEditors, DesignEditors, DesignIntf, untEasyGrid, untEasyDBGrid,
cxControls, cxBlobEdit, cxButtonEdit, cxButtons, cxCalc, cxCalendar, cxCheckBox,
cxContainer, cxCurrencyEdit, cxDB, cxDBEdit, cxDBEditRepository, cxDBLookupComboBox,
cxDBNavigator, cxDropDownEdit, cxEditConsts, cxEditRepositoryEditor,
cxEditRepositoryItems, cxGraphics, cxGroupBox, cxHyperLinkEdit, cxImage,
cxImageComboBox, cxLibraryReg, cxListBox, cxLookAndFeels, cxLookupDBGrid,
cxLookupGrid, cxMaskEdit, cxMemo, cxMRUEdit, cxNavigator, cxPropEditors,
cxRadioGroup, cxSpinEdit, cxTextEdit, cxTimeEdit, dxtree, dxDBTree, dxDBTrel,
cxCheckComboBox, cxCheckGroup,
cxCheckGroupStatesEditor, cxCheckListBox, cxClasses, cxColorComboBox,
cxDBCheckComboBox, cxDBCheckGroup, cxDBCheckListBox,
cxDBColorComboBox, cxDBFontNameComboBox, cxDBLabel, cxDBProgressBar,
cxDBRichEdit, cxDBTrackBar, cxEdit,
cxExtEditConsts, cxExtEditRepositoryItems, cxFontNameComboBox, cxHeader, cxHint,
cxHintEditor, cxLabel, cxListView, cxMCListBox, cxProgressBar,
cxRichEdit, cxScrollBar, cxSpinButton, cxSplitter, cxSplitterEditor,
cxTrackBar, cxTreeView, Provider,
cxFilterControl,
cxDBFilterControl, cxEditPropEditors,
dxCore, cxDBShellComboBox,
cxShellBrowserDialog, cxShellComboBox,
cxShellCommon, cxShellEditRepositoryItems, cxShellListView, cxShellTreeView,
cxGrid, cxGridBandedTableView,
cxGridCardView, cxGridCommon, cxGridCustomTableView, cxGridCustomView, cxGridChartView,
cxGridEditor, cxGridLevel, cxGridStrs, cxGridStructureNavigator,
cxGridTableView, cxBandedTableViewEditor, cxCardViewEditor,
cxChartViewEditor, cxGridPredefinedStyles, cxGridStyleSheetsPreview, cxGridExportLink,
cxDBData, cxDBExtLookupComboBox, cxGridDBBandedTableView,
cxGridDBCardView, cxGridDBDataDefinitions, cxGridDBTableView, cxGridDBChartView,
dxLayoutCommon, dxLayoutLookAndFeels, dxLayoutEditForm, dxLayoutControl,
dxLayoutLookAndFeelListDesignForm, dxLayoutSelection, dxLayoutImport,
untStdRegEditors, dxorgchr, dxdborgc, dxorgced, cxGridPopupMenu, cxGridCustomPopUpMenu,
untEasyADOReg, TreeIntf, DiagramSupport, DsnDb,
untEasyDesignerGridPopuMenuReg;
procedure RegisterEditRepositoryItems;
begin
RegisterEditRepositoryItem(TcxEditRepositoryTextItem, scxSEditRepositoryTextItem);
RegisterEditRepositoryItem(TcxEditRepositoryButtonItem, scxSEditRepositoryButtonItem);
RegisterEditRepositoryItem(TcxEditRepositoryImageItem, scxSEditRepositoryImageItem);
RegisterEditRepositoryItem(TcxEditRepositoryComboBoxItem, scxSEditRepositoryComboBoxItem);
RegisterEditRepositoryItem(TcxEditRepositoryMaskItem, scxSEditRepositoryMaskItem);
RegisterEditRepositoryItem(TcxEditRepositoryPopupItem, scxSEditRepositoryPopupItem);
RegisterEditRepositoryItem(TcxEditRepositoryCalcItem, scxSEditRepositoryCalcItem);
RegisterEditRepositoryItem(TcxEditRepositoryDateItem, scxSEditRepositoryDateItem);
RegisterEditRepositoryItem(TcxEditRepositoryCurrencyItem, scxSEditRepositoryCurrencyItem);
RegisterEditRepositoryItem(TcxEditRepositorySpinItem, scxSEditRepositorySpinItem);
RegisterEditRepositoryItem(TcxEditRepositoryMemoItem, scxSEditRepositoryMemoItem);
RegisterEditRepositoryItem(TcxEditRepositoryImageComboBoxItem, scxSEditRepositoryImageComboBoxItem);
RegisterEditRepositoryItem(TcxEditRepositoryBlobItem, scxSEditRepositoryBlobItem);
RegisterEditRepositoryItem(TcxEditRepositoryCheckBoxItem, scxSEditRepositoryCheckBoxItem);
RegisterEditRepositoryItem(TcxEditRepositoryTimeItem, scxSEditRepositoryTimeItem);
RegisterEditRepositoryItem(TcxEditRepositoryMRUItem, scxSEditRepositoryMRUItem);
RegisterEditRepositoryItem(TcxEditRepositoryHyperLinkItem, scxSEditRepositoryHyperLinkItem);
RegisterEditRepositoryItem(TcxEditRepositoryLookupComboBoxItem, scxSEditRepositoryLookupComboBoxItem);
RegisterEditRepositoryItem(TcxEditRepositoryRadioGroupItem, scxSEditRepositoryRadioGroupItem);
end;
procedure StandardRegister;
begin
RegisterComponents('Easy Standard', [{TcxTextEdit, TcxMaskEdit, TcxMemo,
TcxDateEdit, TcxButtonEdit, TcxCheckBox, TcxComboBox, TcxImageComboBox,
TcxSpinEdit, TcxCalcEdit, TcxHyperLinkEdit, TcxTimeEdit, TcxCurrencyEdit,
TcxImage, TcxBlobEdit, TcxMRUEdit, TcxPopupEdit, TcxLookupComboBox,
TcxRadioButton, TcxRadioGroup, TcxListBox, TcxNavigator,
TcxLabel, TcxProgressBar, TcxTrackBar,
TcxCheckListBox, TcxColorComboBox, TcxFontNameComboBox, TcxCheckComboBox,
TcxCheckGroup, TcxRichEdit, TcxExtLookupComboBox}]);
RegisterComponents('Easy DB', [{TcxDBTextEdit, TcxDBMaskEdit, TcxDBMemo,
TcxDBDateEdit, TcxDBButtonEdit, TcxDBCheckBox, TcxDBComboBox, TcxDBImageComboBox,
TcxDBSpinEdit, TcxDBCalcEdit, TcxDBHyperLinkEdit, TcxDBTimeEdit, TcxDBCurrencyEdit,
TcxDBImage, TcxDBBlobEdit, TcxDBMRUEdit, TcxDBPopupEdit, TcxDBLookupComboBox,
TcxDBRadioGroup, TcxDBListBox, TcxDBNavigator,
TcxDBLabel, TcxDBProgressBar, TcxDBTrackBar,
TcxDBCheckListBox, TcxDBColorComboBox, TcxDBFontNameComboBox, TcxDBCheckComboBox,
TcxDBCheckGroup, TcxDBRichEdit, TcxDBExtLookupComboBox}]);
RegisterComponents('Easy Utilities', [{TcxButton, TcxGroupBox,
TcxHintStyleController, TcxSpinButton,
TcxMCListBox, TcxListView, TcxTreeView, TcxHeader, TcxSplitter}]);
RegisterComponents('Easy Filter', [TcxFilterControl, TcxDBFilterControl]);
RegisterComponents('Easy Shell', [TcxShellComboBox, TcxDBShellComboBox,
TcxShellListView, TcxShellTreeView, TcxShellBrowserDialog]);
RegisterComponentEditor(TcxShellBrowserDialog, TcxShellBrowserEditor);
RegisterPropertyEditor(TypeInfo(Boolean), TcxDragDropSettings, 'Scroll', nil);
RegisterPropertyEditor(TypeInfo(Boolean), TcxCustomShellTreeView, 'RightClickSelect', nil);
// RegisterComponents('Easy TreeView', [TdxTreeView, TdxDBTreeView, TdxTreeViewEdit,
// TdxDBTreeViewEdit, TdxLookUpTreeView, TdxDBLookUpTreeView]);
//Grid
RegisterComponents('Easy Grid', [ TEasyStringGrid, TEasyDBGrid]);
//ADO
// Restrict these components to only be used with VCL components.
GroupDescendentsWith(TADOConnection, Controls.TControl);
GroupDescendentsWith(TADOCommand, Controls.TControl);
GroupDescendentsWith(TCustomADODataSet, Controls.TControl);
GroupDescendentsWith(TRDSConnection, Controls.TControl);
RegisterComponents('Easy dbGo', [TADOConnection, TADOQuery, TADOTable, TADOCommand,
TADODataSet, TADOStoredProc, TDataSource, TClientDataSet,
TDataSetProvider]);
RegisterPropertyEditor(TypeInfo(WideString), TADOConnection, 'Provider', TProviderProperty);
RegisterPropertyEditor(TypeInfo(WideString), TADOConnection, 'ConnectionString', TConnectionStringProperty);
RegisterPropertyEditor(TypeInfo(WideString), TADOCommand, 'ConnectionString', TConnectionStringProperty);
RegisterPropertyEditor(TypeInfo(WideString), TCustomADODataSet, 'ConnectionString', TConnectionStringProperty);
RegisterPropertyEditor(TypeInfo(WideString), TADODataSet, 'CommandText', TCommandTextProperty);
RegisterPropertyEditor(TypeInfo(WideString), TADOCommand, 'CommandText', TCommandTextProperty);
RegisterPropertyEditor(TypeInfo(WideString), TADOTable, 'TableName', TTableNameProperty);
RegisterPropertyEditor(TypeInfo(WideString), TADOStoredProc, 'ProcedureName', TProcedureNameProperty);
RegisterPropertyEditor(TypeInfo(TParameters), TCustomADODataSet, 'Parameters', TParametersProperty);
RegisterPropertyEditor(TypeInfo(TParameters), TADOCommand, 'Parameters', TParametersProperty);
RegisterPropertyEditor(TypeInfo(string), TCustomADODataSet, 'IndexName', TADOIndexNameProperty);
RegisterComponentEditor(TADOConnection, TADOConnectionEditor);
RegisterComponentEditor(TADOCommand, TADOCommandEditor);
RegisterComponentEditor(TADODataSet, TADODataSetEditor);
RegisterPropertyEditor(TypeInfo(string), TADODataSet, 'MasterFields', TADODataSetFieldLinkProperty);
RegisterPropertyEditor(TypeInfo(string), TADOTable, 'MasterFields', TADOTableFieldLinkProperty);
RegisterPropertiesInCategory(sDatabaseCategoryName, TADOConnection,
['Attributes','Command*','Connect*','DefaultDatabase','IsolationLevel',
'LoginPrompt','Mode','Provider']);
RegisterPropertiesInCategory(sDatabaseCategoryName, TADOCommand,
['Command*','Connect*','Cursor*','ExecuteOptions','Param*','Prepared']);
RegisterPropertiesInCategory(sDatabaseCategoryName, TCustomADODataSet,
['CacheSize', 'ConnectionString', 'ExecuteOptions', 'MarshalOptions',
'MaxRecords', 'Prepared', 'ProcedureName', 'Command*']);
RegisterSprigType(TADOConnection, TADOConnectionSprig);
RegisterSprigType(TRDSConnection, TRDSConnectionSprig);
RegisterSprigType(TADOCommand, TADOCommandSprig);
RegisterSprigType(TCustomADODataSet, TCustomADODataSetSprig);
RegisterSprigType(TADODataSet, TADODataSetSprig);
RegisterSprigType(TADOTable, TADOTableSprig);
RegisterSprigType(TADOStoredProc, TADOStoredProcSprig);
RegisterSprigType(TADOQuery, TADOQuerySprig);
RegisterIslandType(TADOCommandSprig, TADOCommandIsland);
RegisterIslandType(TCustomADODataSetSprig, TCustomADODataSetIsland);
RegisterIslandType(TADODataSetSprig, TADODataSetIsland);
RegisterIslandType(TADOTableSprig, TADOTableIsland);
RegisterIslandType(TADOQuerySprig, TADOQueryIsland);
RegisterBridgeType(TDataSetIsland, TADODataSetIsland, TADODataSetMasterDetailBridge);
RegisterBridgeType(TDataSetIsland, TADOTableIsland, TADOTableMasterDetailBridge);
RegisterBridgeType(TDataSetIsland, TADOQueryIsland, TADOQueryMasterDetailBridge);
RegisterComponents('Easy LayOut', []);
RegisterComponents('Easy OrgChart', [TdxOrgChart, TdxDbOrgChart]);
RegisterComponentEditor(TdxOrgChart,TdxOrgChartEditor);
RegisterPropertyEditor(TypeInfo(String),TdxDbOrgChart,'KeyFieldName',TFieldProperty);
RegisterPropertyEditor(TypeInfo(String),TdxDbOrgChart,'ParentFieldName',TFieldProperty);
RegisterPropertyEditor(TypeInfo(String),TdxDbOrgChart,'TextFieldName',TFieldProperty);
RegisterPropertyEditor(TypeInfo(String),TdxDbOrgChart,'OrderFieldName',TFieldProperty);
RegisterPropertyEditor(TypeInfo(String),TdxDbOrgChart,'ImageFieldName',TFieldProperty);
RegisterComponentEditor(TdxDBOrgChart,TdxDBOrgChartEditor);
// RegisterNoIcon([TcxGridLevel,
// TcxGridTableView, {$IFNDEF NONDB}TcxGridDBTableView,{$ENDIF}
// TcxGridBandedTableView, {$IFNDEF NONDB}TcxGridDBBandedTableView,{$ENDIF}
// TcxGridCardView{$IFNDEF NONDB}, TcxGridDBCardView{$ENDIF}]);
// RegisterNoIcon([
// TcxGridColumn, {$IFNDEF NONDB}TcxGridDBColumn,{$ENDIF}
// TcxGridBandedColumn, {$IFNDEF NONDB}TcxGridDBBandedColumn,{$ENDIF}
// TcxGridCardViewRow{$IFNDEF NONDB}, TcxGridDBCardViewRow{$ENDIF}]);
// RegisterNoIcon([TcxGridTableViewStyleSheet, TcxGridBandedTableViewStyleSheet, TcxGridCardViewStyleSheet]);
//
//标准控件
RegisterComponents('Standard', [TMainMenu, TPopupMenu, TLabel, TEdit,
TMemo, TButton, TCheckBox, TRadioButton, TListBox, TComboBox, TScrollBar,
TGroupBox, TRadioGroup, TPanel, TActionList]);
RegisterNoIcon([TMenuItem]);
RegisterComponents('Additional', [TBitBtn, TSpeedButton, TMaskEdit, TStringGrid,
TDrawGrid, TImage, TShape, TBevel, TScrollBox, TCheckListBox, TSplitter,
TStaticText, TControlBar, TApplicationEvents]);
RegisterComponents('Win32', [TTabControl, TPageControl, TImageList, TRichEdit,
TTrackBar, TProgressBar, TUpDown, THotKey, TAnimate, TDateTimePicker,
TMonthCalendar, TTreeView, TListView, THeaderControl, TStatusBar, TToolBar,
TCoolBar, TPageScroller]);
RegisterClasses([TToolButton, TTabSheet]);
RegisterComponents('System', [TTimer, TPaintBox, TMediaPlayer, TOleContainer]);
RegisterComponents('Dialogs', [TOpenDialog, TSaveDialog, TOpenPictureDialog,
TSavePictureDialog, TFontDialog, TColorDialog, TPrintDialog, TPrinterSetupDialog,
TFindDialog, TReplaceDialog]);
RegisterPropertiesInCategory('Action',
['Action', 'Caption', 'Checked', 'Enabled', 'HelpContext', 'Hint', 'ImageIndex',
'ShortCut', 'Visible']);
RegisterPropertiesInCategory('Drag, Drop and Docking',
['Drag*', 'Dock*', 'UseDockManager', 'OnDockOver', 'OnGetSiteInfo', 'OnDragOver', 'On*Drop',
'On*Drag', 'On*Dock']);
RegisterPropertiesInCategory('Help and Hints', ['Help*', '*Help', 'Hint*', '*Hint']);
RegisterPropertiesInCategory('Layout', ['Left', 'Top', 'Width', 'Height', 'TabOrder',
'TabStop', 'Align', 'Anchors', 'Constraints', 'AutoSize', 'AutoScroll', 'Scaled',
'OnResize', 'OnConstrained', 'OnCanResize']);
RegisterPropertiesInCategory('Legacy', ['Ctl3d', 'ParentCtl3d', 'OldCreateOrder']);
RegisterPropertiesInCategory('Linkage', TypeInfo(TComponent), ['']);
RegisterPropertiesInCategory('Linkage', TypeInfo(IInterface), ['']);
RegisterPropertiesInCategory('Visual', ['Left','Top','Width','Height','Visible',
'Enabled','Caption','Align','Alignment','ParentColor','ParentFont','Bevel*',
'Border*','ClientHeight','ClientWidth','Scaled','AutoSize','EditMask','OnShow',
'OnPaint','OnClose','OnCloseQuery','OnResize','OnConstrained','OnActivate',
'OnDeactivate','OnCanResize','OnHide']);
RegisterPropertiesInCategory('Visual', TypeInfo(TFont), ['']);
RegisterPropertiesInCategory('Visual', TypeInfo(TColor), ['']);
RegisterPropertiesInCategory('Visual', TypeInfo(TBrush), ['']);
RegisterPropertiesInCategory('Visual', TypeInfo(TPen), ['']);
RegisterPropertiesInCategory('Visual', TypeInfo(TCursor), ['']);
RegisterPropertiesInCategory('Visual', TypeInfo(TGraphic), ['']);
RegisterPropertiesInCategory('Input', ['AutoScroll','KeyPreview','ReadOnly',
'Enabled','OnClick','OnDblClick','OnShortCut','OnKey*','OnMouse*']);
RegisterPropertiesInCategory('Localizable', ['BiDiMode','Caption','Constraints',
'EditMask','Glyph','Height','Hint','Icon','ImeMode','ImeName','Left',
'ParentBiDiMode','ParentFont','Picture','Text','Top','Width']);
RegisterPropertiesInCategory('Localizable', TCustomForm, ['ClientHeight',
'ClientWidth','HelpFile']);
RegisterPropertiesInCategory('Localizable', THotKey, ['Hotkey']);
RegisterPropertiesInCategory('Localizable', TMainMenu, ['Items']);
RegisterPropertiesInCategory('Localizable', TPopupMenu, ['Hotkey']);
RegisterPropertiesInCategory('Localizable', TSplitter, ['MinSize']);
RegisterPropertiesInCategory('Localizable', TCustomEdit, ['PasswordChar']);
RegisterPropertiesInCategory('Localizable', TStatusBar, ['SimpleText']);
RegisterPropertiesInCategory('Localizable', TMenuItem, ['ShortCut']);
RegisterPropertiesInCategory('Localizable', TSpeedButton, ['Margin','Spacing']);
RegisterPropertiesInCategory('Localizable', TAction, ['Category','ShortCut']);
RegisterPropertiesInCategory('Localizable', TRadioGroup, ['Columns']);
RegisterPropertiesInCategory('Localizable', TToolBar, ['ButtonHeight','ButtonWidth']);
RegisterPropertiesInCategory('Localizable', TCustomMemo, ['Lines']);
RegisterPropertiesInCategory('Localizable', TCustomRadioGroup, ['Items']);
RegisterPropertiesInCategory('Localizable', TCustomComboBox, ['Items']);
RegisterPropertiesInCategory('Localizable', TCustomListBox, ['Items']);
RegisterPropertiesInCategory('Localizable', TCustomTabControl, ['Tabs']);
RegisterPropertiesInCategory('Localizable', TTabSet, ['Tabs']);
RegisterPropertiesInCategory('Localizable', TypeInfo(TListColumns), ['']);
RegisterPropertiesInCategory('Localizable', TypeInfo(TListItems), ['']);
RegisterPropertiesInCategory('Localizable', TypeInfo(TStatusPanels), ['']);
RegisterPropertiesInCategory('Localizable', TypeInfo(TTreeNodes), ['']);
RegisterPropertiesInCategory('Localizable', TypeInfo(THeaderSections), ['']);
RegisterPropertiesInCategory('Localizable', TypeInfo(TImageList), ['']);
RegisterPropertiesInCategory('Localizable', TypeInfo(TSizeConstraints), ['']);
RegisterPropertiesInCategory('Localizable', TypeInfo(TFont), ['']);
RegisterPropertiesInCategory('Localizable', TFindDialog, ['FindText']);
RegisterPropertiesInCategory('Localizable', TReplaceDialog, ['FindText']);
RegisterPropertiesInCategory('Localizable', TReplaceDialog, ['ReplaceText']);
RegisterPropertiesInCategory('Localizable', TOpenDialog, ['Filter']);
RegisterPropertiesInCategory('Localizable', TOpenDialog, ['Title']);
RegisterPropertiesInCategory('Localizable', TSaveDialog, ['Filter']);
RegisterPropertiesInCategory('Localizable', TSaveDialog, ['Title']);
RegisterPropertiesInCategory('Localizable', TOpenPictureDialog, ['Filter']);
RegisterPropertiesInCategory('Localizable', TOpenPictureDialog, ['Title']);
RegisterPropertiesInCategory('Localizable', TSavePictureDialog, ['Filter']);
RegisterPropertiesInCategory('Localizable', TSavePictureDialog, ['Title']);
end;
initialization
StandardRegister;
end.
|
unit eSocial.Views.Styles;
interface
uses
System.UITypes,
eSocial.Views.Styles.Colors;
const
FONT_NAME = 'Tahoma';
FONT_SIZE_H1 = 18;
FONT_SIZE_H2 = 16;
FONT_SIZE_H3 = 14;
FONT_SIZE_H4 = 12;
FONT_SIZE_H5 = 10;
FONT_SIZE_H6 = 8;
FONT_SIZE_H7 = 6;
FONT_SIZE_MEDIUM = 12;
FONT_SIZE_NORMAL = 10;
FONT_SIZE_SMALL = 8;
implementation
end.
|
unit UBarraBotoesItens;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
Data.DB;
type
TFBarraBotoesItens = class(TFrame)
sbBotoes: TScrollBox;
btAnterior: TBitBtn;
btProximo: TBitBtn;
btNovo: TBitBtn;
btAlterar: TBitBtn;
btSalvar: TBitBtn;
btCancelar: TBitBtn;
btExluir: TBitBtn;
dsDadosItens: TDataSource;
procedure dsDadosItensStateChange(Sender: TObject);
procedure btAnteriorClick(Sender: TObject);
procedure btProximoClick(Sender: TObject);
procedure btNovoClick(Sender: TObject);
procedure btAlterarClick(Sender: TObject);
procedure btCancelarClick(Sender: TObject);
private
{ Private declarations }
public
procedure HabilitaDesabilitaBotoes;
end;
implementation
{$R *.dfm}
procedure TFBarraBotoesItens.HabilitaDesabilitaBotoes;
begin
btAnterior.Enabled := (dsDadosItens.DataSet.Active) and
(not (dsDadosItens.DataSet.IsEmpty)) and
(dsDadosItens.DataSet.State = dsBrowse);
btProximo.Enabled := btAnterior.Enabled;
btAlterar.Enabled := btAnterior.Enabled;
btExluir.Enabled := btAnterior.Enabled;
btNovo.Enabled := (dsDadosItens.DataSet.Active) and
(dsDadosItens.DataSet.State = dsBrowse);
btSalvar.Enabled := (dsDadosItens.DataSet.Active) and
(dsDadosItens.DataSet.State in dsEditModes);
btCancelar.Enabled := btSalvar.Enabled;
end;
procedure TFBarraBotoesItens.btAlterarClick(Sender: TObject);
begin
dsDadosItens.DataSet.Edit;
end;
procedure TFBarraBotoesItens.btAnteriorClick(Sender: TObject);
begin
dsDadosItens.DataSet.Prior;
end;
procedure TFBarraBotoesItens.btCancelarClick(Sender: TObject);
begin
dsDadosItens.DataSet.Cancel;
end;
procedure TFBarraBotoesItens.btNovoClick(Sender: TObject);
begin
dsDadosItens.DataSet.Insert;
end;
procedure TFBarraBotoesItens.btProximoClick(Sender: TObject);
begin
dsDadosItens.DataSet.Next;
end;
procedure TFBarraBotoesItens.dsDadosItensStateChange(Sender: TObject);
begin
HabilitaDesabilitaBotoes;
end;
end.
|
{*****************************************************************}
{ This is a component for placing icons in the notification area }
{ of the Windows taskbar (aka. the traybar). }
{ }
{ It is an expanded version of my CoolTrayIcon component, which }
{ you will need to make this work. The expanded features allow }
{ you to easily draw text in the tray icon. }
{ }
{ The component is freeware. Feel free to use and improve it. }
{ I would be pleased to hear what you think. }
{ }
{ Troels Jakobsen - delphiuser@get2net.dk }
{ Copyright (c) 2002 }
{ }
{ Portions by Jouni Airaksinen - mintus@codefield.com }
{*****************************************************************}
unit TextTrayIcon;
interface
uses
CoolTrayIcon, Windows, Graphics, Classes, Controls;
type
TOffsetOptions = class(TPersistent)
private
FOffsetX,
FOffsetY,
FLineDistance: Integer;
FOnChange: TNotifyEvent; // Procedure var.
procedure SetOffsetX(Value: Integer);
procedure SetOffsetY(Value: Integer);
procedure SetLineDistance(Value: Integer);
protected
procedure Changed; dynamic;
published
property OffsetX: Integer read FOffsetX write SetOffsetX;
property OffsetY: Integer read FOffsetY write SetOffsetY;
property LineDistance: Integer read FLineDistance write SetLineDistance;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
TTextTrayIcon = class(TCoolTrayIcon)
private
FFont: TFont;
FColor: TColor;
FInvertTextColor: TColor;
FBorder: Boolean;
FBorderColor: TColor;
FText: String;
FTextBitmap: TBitmap;
FOffsetOptions: TOffsetOptions;
FBackgroundIcon: TIcon;
procedure FontChanged(Sender: TObject);
procedure SplitText(const Strings: TList);
procedure OffsetOptionsChanged(OffsetOptions: TObject);
procedure SetBackgroundIcon(Value: TIcon);
protected
procedure Loaded; override;
function LoadDefaultIcon: Boolean; override;
function LoadDefaultBackgroundIcon: Boolean; virtual;
procedure Paint; virtual;
procedure SetText(Value: String);
procedure SetTextBitmap(Value: TBitmap);
procedure SetFont(Value: TFont);
procedure SetColor(Value: TColor);
procedure SetBorder(Value: Boolean);
procedure SetBorderColor(Value: TColor);
procedure SetOffsetOptions(Value: TOffsetOptions);
function TransparentBitmapToIcon(const Bitmap: TBitmap; const Icon: TIcon;
MaskColor: TColor): Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Draw;
published
property BackgroundIcon: TIcon read FBackgroundIcon write SetBackgroundIcon;
property Text: String read FText write SetText;
property Font: TFont read FFont write SetFont;
property Color: TColor read FColor write SetColor default clBtnFace;
property Border: Boolean read FBorder write SetBorder;
property BorderColor: TColor read FBorderColor write SetBorderColor
default clBlack;
property Options: TOffsetOptions read FOffsetOptions write SetOffsetOptions;
end;
implementation
uses
SysUtils;
{------------------- TOffsetOptions -------------------}
procedure TOffsetOptions.Changed;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
procedure TOffsetOptions.SetOffsetX(Value: Integer);
begin
if Value <> FOffsetX then
begin
FOffsetX := Value;
Changed;
end;
end;
procedure TOffsetOptions.SetOffsetY(Value: Integer);
begin
if Value <> FOffsetY then
begin
FOffsetY := Value;
Changed;
end;
end;
procedure TOffsetOptions.SetLineDistance(Value: Integer);
begin
if Value <> FLineDistance then
begin
FLineDistance := Value;
Changed;
end;
end;
{------------------- TTextTrayIcon --------------------}
constructor TTextTrayIcon.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBackgroundIcon := TIcon.Create;
FTextBitmap := TBitmap.Create;
FFont := TFont.Create;
FFont.OnChange := FontChanged;
FColor := clBtnFace;
FBorderColor := clBlack;
FOffsetOptions := TOffsetOptions.Create;
FOffsetOptions.OnChange := OffsetOptionsChanged;
{ Assign a default bg. icon if BackgroundIcon property is empty.
This will assign a bg. icon to the component when it is created for
the very first time. When the user assigns another icon it will not
be overwritten next time the project loads.
This is similar to the default Icon in parent class CoolTrayIcon. }
{ On second thought: do we really want a default bg. icon? Probably not.
For this reason the class method LoadDefaultBackgroundIcon will
return false. }
if (csDesigning in ComponentState) then
if FBackgroundIcon.Handle = 0 then
if LoadDefaultBackgroundIcon then
begin
FBackgroundIcon.Handle := LoadIcon(0, IDI_WINLOGO);
Draw;
end;
end;
destructor TTextTrayIcon.Destroy;
begin
try
FFont.Free;
FTextBitmap.Free;
FOffsetOptions.Free;
try
if FBackgroundIcon <> nil then
FBackgroundIcon.Free;
except
on Exception do
// Do nothing; the background icon seems to be invalid
end;
finally
inherited Destroy;
end;
end;
procedure TTextTrayIcon.Loaded;
begin
inherited Loaded; // Always call inherited Loaded first
// No extra handling needed
end;
function TTextTrayIcon.LoadDefaultIcon: Boolean;
{ We don't want a default icon, so we override this method inherited
from CoolTrayIcon. }
begin
Result := False; // No thanks, no default icon
end;
function TTextTrayIcon.LoadDefaultBackgroundIcon: Boolean;
{ This method is called to determine whether to assign a default bg. icon
to the component. Descendant classes can override the method to change
this behavior. }
begin
Result := False; // No thanks, no default bg. icon
end;
procedure TTextTrayIcon.FontChanged(Sender: TObject);
{ This method is invoked when user assigns to Font (but not when Font is set
directly to another TFont var.) }
begin
Draw;
end;
procedure TTextTrayIcon.SetText(Value: String);
begin
FText := Value;
Draw;
end;
procedure TTextTrayIcon.SetTextBitmap(Value: TBitmap);
begin
FTextBitmap := Value; // Assign?
Draw;
end;
procedure TTextTrayIcon.SetFont(Value: TFont);
begin
FFont.Assign(Value);
Draw;
end;
procedure TTextTrayIcon.SetColor(Value: TColor);
begin
FColor := Value;
Draw;
end;
procedure TTextTrayIcon.SetBorder(Value: Boolean);
begin
FBorder := Value;
Draw;
end;
procedure TTextTrayIcon.SetBorderColor(Value: TColor);
begin
FBorderColor := Value;
Draw;
end;
procedure TTextTrayIcon.SetOffsetOptions(Value: TOffsetOptions);
{ This method will only be invoked if the user creates a new
TOffsetOptions object. User will probably just set the values
of the existing TOffsetOptions object. }
begin
FOffsetOptions.Assign(Value);
Draw;
end;
procedure TTextTrayIcon.OffsetOptionsChanged(OffsetOptions: TObject);
{ This method will be invoked when the user changes the values of the
existing TOffsetOptions object. }
begin
Draw;
end;
procedure TTextTrayIcon.SetBackgroundIcon(Value: TIcon);
begin
FBackgroundIcon.Assign(Value);
Draw;
end;
procedure TTextTrayIcon.Draw;
var
Ico: TIcon;
rc: Boolean;
begin
CycleIcons := False; // We cannot cycle and draw at the same time
Paint; // Render FTextBitmap
Ico := TIcon.Create;
if (Assigned(FBackgroundIcon)) and not (FBackgroundIcon.Empty) then
// Draw text transparently on background icon
rc := TransparentBitmapToIcon(FTextBitmap, Ico, FColor)
else
begin
// Just draw text; no background icon
if FColor <> clNone then
FInvertTextColor := clNone;
rc := BitmapToIcon(FTextBitmap, Ico, FInvertTextColor);
end;
if rc then
begin
Icon.Assign(Ico);
// Refresh; // Always refresh after icon assignment
Ico.Free;
end;
end;
function TTextTrayIcon.TransparentBitmapToIcon(const Bitmap: TBitmap;
const Icon: TIcon; MaskColor: TColor): Boolean;
{ Render an icon from a 16x16 bitmap. Return false if error.
MaskColor is a color that will be rendered transparently. Use clNone for
no transparency. }
var
BitmapImageList: TImageList;
Bmp: TBitmap;
FInvertColor: TColor;
begin
BitmapImageList := TImageList.CreateSize(16, 16);
try
Result := False;
BitmapImageList.AddIcon(FBackgroundIcon);
Bmp := TBitmap.Create;
if (FColor = clNone) or (FColor = FFont.Color) then
FInvertColor := ColorToRGB(FFont.Color) xor $00FFFFFF
else
FInvertColor := MaskColor;
Bmp.Canvas.Brush.Color := FInvertColor;
BitmapImageList.GetBitmap(0, Bmp);
Bitmap.Transparent := True;
Bitmap.TransParentColor := FInvertTextColor;
Bmp.Canvas.Draw(0, 0, Bitmap);
BitmapImageList.AddMasked(Bmp, FInvertColor);
BitmapImageList.GetIcon(1, Icon);
Bmp.Free;
Result := True;
finally
BitmapImageList.Free;
end;
end;
procedure TTextTrayIcon.Paint;
var
Bitmap: TBitmap;
Left, Top, LinesTop, LineHeight: Integer;
Substr: PChar;
Strings: TList;
I: Integer;
begin
Bitmap := TBitmap.Create;
try
Bitmap.Width := 16;
Bitmap.Height := 16;
// Bitmap.Canvas.TextFlags := 2; // ETO_OPAQUE
// Render background rectangle
if (FColor = clNone) or (FColor = FFont.Color) then
FInvertTextColor := ColorToRGB(FFont.Color) xor $00FFFFFF
else
FInvertTextColor := FColor;
Bitmap.Canvas.Brush.Color := FInvertTextColor;
Bitmap.Canvas.FillRect(Rect(0, 0, 16, 16));
// Render text; check for line breaks
Bitmap.Canvas.Font.Assign(FFont);
Substr := StrPos(PChar(FText), #13);
if Substr = nil then
begin
// No line breaks
Left := (15 - Bitmap.Canvas.TextWidth(FText)) div 2;
if FOffsetOptions <> nil then
Left := Left + FOffsetOptions.OffsetX;
Top := (15 - Bitmap.Canvas.TextHeight(FText)) div 2;
if FOffsetOptions <> nil then
Top := Top + FOffsetOptions.OffsetY;
Bitmap.Canvas.TextOut(Left, Top, FText);
end
else
begin
// Line breaks
Strings := TList.Create;
SplitText(Strings);
LineHeight := Bitmap.Canvas.TextHeight(Substr);
if FOffsetOptions <> nil then
LineHeight := LineHeight + FOffsetOptions.LineDistance;
LinesTop := (15 - (LineHeight * Strings.Count)) div 2;
if FOffsetOptions <> nil then
LinesTop := LinesTop + FOffsetOptions.OffsetY;
for I := 0 to Strings.Count -1 do
begin
Substr := Strings[I];
Left := (15 - Bitmap.Canvas.TextWidth(Substr)) div 2;
if FOffsetOptions <> nil then
Left := Left + FOffsetOptions.OffsetX;
Top := LinesTop + (LineHeight * I);
Bitmap.Canvas.TextOut(Left, Top, Substr);
end;
for I := 0 to Strings.Count -1 do
StrDispose(Strings[I]);
Strings.Free;
end;
// Render border
if FBorder then
begin
Bitmap.Canvas.Brush.Color := FBorderColor;
Bitmap.Canvas.FrameRect(Rect(0, 0, 16, 16));
end;
// Assign the final bitmap
FTextBitmap.Assign(Bitmap);
finally
Bitmap.Free;
end;
end;
procedure TTextTrayIcon.SplitText(const Strings: TList);
function PeekedString(S: String): String;
var
P: Integer;
begin
P := Pos(#13, S);
if P = 0 then
Result := S
else
Result := Copy(S, 1, P-1);
end;
var
Substr: String;
P: Integer;
S: PChar;
begin
Strings.Clear;
Substr := FText;
repeat
P := Pos(#13, Substr);
if P = 0 then
begin
S := StrNew(PChar(Substr));
Strings.Add(S);
end
else
begin
S := StrNew(PChar(PeekedString(Substr)));
Strings.Add(S);
Delete(Substr, 1, P);
end;
until P = 0;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 168 O(N2) Dynamic Method
}
program
FliesDance;
const
MaxN = 240{100};
var
N : Integer;
P, Per : array [0 .. MaxN] of Integer;
PN : Integer;
D : array [0 .. 1, 0 .. MaxN] of Extended;
DN : Integer;
Pt : array [1 .. MaxN, 1 .. MaxN] of Byte;
Ans : Extended;
X, Y : Longint;
I, J, K : Integer;
procedure ReadInput;
begin
Readln(N);
end;
procedure WriteOutput;
var
X : Extended;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
Writeln(N);
for I := 1 to N do
Writeln(I, ' ', Per[I]);
Writeln(Ans : 0 : 0);
Close(Output);
end;
procedure FindPrimes;
begin
P[0] := 1;
for I := 2 to N do
begin
for J := PN downto 0 do
if I mod P[J] = 0 then
Break;
if J = 0 then
begin
Inc(PN);
P[PN] := I;
end;
end;
end;
procedure Dynamic;
begin
D[0, 0] := 1; D[1, 0] := 1;
for I := 1 to N do
D[DN, I] := 1;
for I := 1 to PN do
begin
DN := 1 - DN;
for J := 1 to N do
begin
Pt[I, J] := 0; D[DN, J] := D[1 - DN, J];
K := 1; X := P[I];
while X <= J do
begin
if D[DN, J] < D[1 - DN, J - X] * X then
begin
D[DN, J] := D[1 - DN, J - X] * X;
Pt[I, J] := K;
end;
X := X * P[I]; Inc(K);
end;
end;
end;
end;
procedure CalcPermutation;
begin
for I := 1 to N do
Per[I] := I + 1;
Ans := 0;
for I := 1 to N do
if Ans < D[DN, I] then
begin
Ans := D[DN, I];
J := I;
end;
for I := J + 1 to N do
Per[I] := I;
I := PN;
while I > 0 do
begin
if (J > 1) and (Pt[I, J] <> 0) then
begin
Y := 1;
for K := 1 to Pt[I, J] do
Y := Y * P[I];
Per[J] := J - Y + 1;
J := J - Y;
end;
Dec(I);
end;
if N = 1 then
Per[1] := 1;
end;
begin
ReadInput;
FindPrimes;
Dynamic;
CalcPermutation;
WriteOutput;
end.
|
unit Tecon_Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ScktComp, StdCtrls, Sockets, IdBaseComponent, IdComponent,
IdUDPBase, IdUDPServer, IdSocketHandle, IdUDPClient, IdGlobal;
type
TForm1 = class(TForm)
Memo1: TMemo;
IdUDPServer1: TIdUDPServer;
Button1: TButton;
IdUDPClient1: TIdUDPClient;
CheckBox1: TCheckBox;
Button2: TButton;
Edit1: TEdit;
procedure UdpSocket1Connect(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure ServerSocket1Accept(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocket1ClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocket1GetSocket(Sender: TObject; Socket: Integer;
var ClientSocket: TServerClientWinSocket);
procedure IdUDPServer2Status(ASender: TObject;
const AStatus: TIdStatus; const AStatusText: String);
procedure CheckBox1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
procedure Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses GMGlobals, Devices.Tecon, StrUtils;
{$R *.dfm}
procedure TForm1.UdpSocket1Connect(Sender: TObject);
begin
Memo1.Lines.Add('UPD Connected');
end;
procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle);
var buf: TIdBytes;
bCRC: bool;
n: int;
begin
n := Length(AData);
bCRC := Tecon_CheckCRC(AData, n);
Memo1.Lines.Add('UPD < ' + ArrayToString(AData, n, false, true) + ' - ' + IfThen(bCRC, 'Ok', 'Bad CRC'));
// 68 08 08 68 41 25 1B 02 C0 06 36 06 85 16
if n >= 14 then
begin
SetLength(buf, 9);
buf[0] := $10;
buf[1] := $40;
buf[2] := AData[7];
buf[3] := $1B;
buf[4] := $00;
buf[5] := $00;
buf[6] := $00;
Tecon_CRC(buf, 7);
Memo1.Lines.Add('UPD > ' + ArrayToString(buf, 9, false, true));
ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, buf);
end
else
if AData[0] <> $10 then
begin
SetLength(buf, 9);
buf[0] := $10;
buf[1] := $40;
buf[2] := $08;
buf[3] := $01;
buf[4] := $00;
buf[5] := $F0;
buf[6] := $00;
Tecon_CRC(buf, 7);
Memo1.Lines.Add('UPD > ' + ArrayToString(buf, 9, false, true));
ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, buf);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var buf: array [0..100] of byte;
bufSend, bufRec: TIdBytes;
i, n: int;
l: TStringList;
b: bool;
f: double;
// v: int64;
begin
{ buf[0] := $10;
buf[1] := $40;
buf[2] := $08;
buf[3] := $01;
buf[4] := $00;
buf[5] := $F0;
buf[6] := $00;
Tecon_CRC(buf, 7);
IdUDPClient1.SendBuffer(buf, 9);
Memo1.Lines.Add('UPD > ' + ArrayToString(buf, 9, false, true));
n := IdUDPClient1.ReceiveBuffer(bufRec, Length(bufRec));
Memo1.Lines.Add('UPD < ' + ArrayToString(bufRec, n, false, true) + ' - ' + IfThen(Tecon_CheckCRC(bufRec, n), 'Ok', 'Bad CRC'));
}
l := TStringList.Create();
l.CommaText := Edit1.Text;
n := l.Count;
for i := 0 to n - 1 do
buf[i] := StrToInt('$' + l[i]);
Tecon_CRC(buf, n);
SetLength(bufSend, n + 2);
WriteBuf(bufSend, 0, buf, n + 2);
IdUDPClient1.SendBuffer(bufSend);
Memo1.Lines.Add('UPD > ' + ArrayToString(buf, n + 2, false, true));
SetLength(bufRec, 1024);
n := IdUDPClient1.ReceiveBuffer(bufRec, Length(bufRec));
b := Tecon_CheckCRC(bufRec, n);
Memo1.Lines.Add('UPD < ' + ArrayToString(bufRec, n, false, true) + ' - ' + IfThen(b, 'Ok', 'Bad CRC'));
if b then
begin
f := ReadSingle(bufRec, 6);
Memo1.Lines.Add('Decoding float: ' + FormatFloatToShow(f, 3));
{ f := ReadSingleInv(bufRec, 6);
Memo1.Lines.Add('Decoding float_Inv: ' + FormatFloatToShow(f, 3));
v := ReadUINT(bufRec, 6);
Memo1.Lines.Add('Decoding UINT: ' + IntToStr(v));
v := ReadUINTInv(bufRec, 6);
Memo1.Lines.Add('Decoding UINT_Inv: ' + IntToStr(v));
v := ReadLongInt(bufRec, 6);
Memo1.Lines.Add('Decoding LongInt: ' + IntToStr(v));
v := ReadLongIntInv(bufRec, 6);
Memo1.Lines.Add('Decoding LongInt_Inv: ' + IntToStr(v)); }
end;
Memo1.Lines.Add('');
l.Free();
end;
procedure TForm1.ServerSocket1Accept(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo1.Lines.Add('TCP Accept');
end;
procedure TForm1.ServerSocket1ClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo1.Lines.Add('TCP Connect');
end;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
begin
Memo1.Lines.Add('TCP Read');
end;
procedure TForm1.ServerSocket1GetSocket(Sender: TObject; Socket: Integer;
var ClientSocket: TServerClientWinSocket);
begin
Memo1.Lines.Add('TCP Get');
end;
procedure TForm1.IdUDPServer2Status(ASender: TObject;
const AStatus: TIdStatus; const AStatusText: String);
begin
Memo1.Lines.Add('UDP State');
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
IdUDPServer1.Active := CheckBox1.Checked;
end;
procedure TForm1.Button2Click(Sender: TObject);
var l: TStringList;
r: TSearchRec;
n, nPas, nDfm: int;
begin
l := TStringList.Create();
nPas := 0;
nDfm := 0;
n := FindFirst('D:\Programs\Delphi\Geomer\GMIO\*.*', faAnyFile, r);
while n = 0 do
begin
if ExtractFileExt(r.Name) = '.pas' then
begin
l.LoadFromFile('D:\Programs\Delphi\Geomer\GMIO\' + r.Name);
nPas := nPas + l.Count;
end;
if ExtractFileExt(r.Name) = '.dfm' then
begin
l.LoadFromFile('D:\Programs\Delphi\Geomer\GMIO\' + r.Name);
nDfm := nDfm + l.Count;
end;
n := FindNext(r);
end;
Memo1.Lines.Add('pas - ' + IntToStr(nPas));
Memo1.Lines.Add('dfm - ' + IntToStr(nDfm));
Memo1.Lines.Add('all - ' + IntToStr(nDfm + nPas));
FindClose(r);
l.Free();
end;
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then Button1Click(nil);
end;
procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_DELETE then Memo1.Lines.Clear();
end;
end.
|
unit ActnFld;
interface
uses DBAdapt, WebAdapt, AdaptReq, Classes;
type
TBaseDataSetAdapterActionField = class(TAdapterNamedField, ICheckValueChange, IExecuteValue,
IDataSetAdapterFieldClass)
private
function GetAdapter: TCustomDataSetAdapter;
protected
{ ICheckValueChange }
function CheckValueChange(AActionRequest: IActionRequest; AFieldIndex: Integer): Boolean;
function ImplCheckValueChange(AActionRequest: IActionRequest; AFieldIndex: Integer): Boolean; virtual;
function FullyQualifyInputName: Boolean; override;
property Adapter: TCustomDataSetAdapter read GetAdapter;
{ IExecuteValue }
procedure ExecuteValue(AActionRequest: IActionRequest; AFieldIndex: Integer);
procedure ImplExecuteValue(AActionRequest: IActionRequest; AFieldIndex: Integer); virtual;
{ IWebVariableName, IGetWebFieldValue }
function ImplGetValue: Variant; override;
end;
TCustomDataSetAdapterDeleteRowField = class(TBaseDataSetAdapterActionField)
protected
function LocateKeyParamsOfStrings(
AValues: TStrings): TLocateParamsList;
{ IExecuteValue }
procedure ImplExecuteValue(AActionRequest: IActionRequest; AFieldIndex: Integer); override;
end;
TDataSetAdapterDeleteRowField = class(TCustomDataSetAdapterDeleteRowField)
published
property ViewAccess;
property ModifyAccess;
end;
implementation
uses WebDisp, SysUtils, SiteComp;
{ TBaseDataSetAdapterActionField }
function TBaseDataSetAdapterActionField.ImplGetValue: Variant;
var
Params: IAdapterItemRequestParams;
begin
Params := TAdapterItemRequestParams.Create;
Adapter.EncodeActionParamsFlags(Params, [poLocateParams]);
Result := EncodeParamNameValues(Params.ParamValues);
end;
function TBaseDataSetAdapterActionField.GetAdapter: TCustomDataSetAdapter;
begin
if (inherited Adapter <> nil) and (inherited Adapter is TCustomDataSetAdapter) then
Result := TCustomDataSetAdapter(inherited Adapter)
else
Result := nil;
end;
function TBaseDataSetAdapterActionField.FullyQualifyInputName: Boolean;
begin
Result := (Adapter <> nil) and
((Adapter.MasterAdapter <> nil) or (Adapter.DetailAdapters.Count >= 1));
end;
function TBaseDataSetAdapterActionField.CheckValueChange(
AActionRequest: IActionRequest; AFieldIndex: Integer): Boolean;
begin
Result := ImplCheckValueChange(AActionRequest, AFieldIndex);
end;
function TBaseDataSetAdapterActionField.ImplCheckValueChange(
AActionRequest: IActionRequest; AFieldIndex: Integer): Boolean;
begin
// If sent then updates are needed
Result := True;
end;
procedure TBaseDataSetAdapterActionField.ExecuteValue(
AActionRequest: IActionRequest; AFieldIndex: Integer);
begin
ImplExecuteValue(AActionRequest, AFieldIndex);
end;
procedure TBaseDataSetAdapterActionField.ImplExecuteValue(
AActionRequest: IActionRequest; AFieldIndex: Integer);
begin
// Do nothing
Assert(False); // Descendent must implement
end;
function GetActionFieldValues(AActionRequest: IActionRequest): IActionFieldValues;
begin
if not Supports(AActionRequest, IActionFieldValues, Result) then
Assert(False);
end;
{ TCustomDataSetAdapterDeleteRowField }
function TCustomDataSetAdapterDeleteRowField.LocateKeyParamsOfStrings(AValues: TStrings): TLocateParamsList;
var
I: Integer;
begin
Result := TLocateParamsList.Create;
try
for I := 0 to AValues.Count - 1 do
AddLocateParamsString(Adapter.Name, AValues.Names[I], ExtractStringValue(AValues[I]), Result);
except
Result.Free;
end;
end;
procedure TCustomDataSetAdapterDeleteRowField.ImplExecuteValue(
AActionRequest: IActionRequest; AFieldIndex: Integer);
function DeleteRow: Boolean;
begin
Result := True;
try
Adapter.DataSet.Delete
except
// Add to error list
on E: Exception do
begin
Adapter.Errors.AddError(E);
Result := False;
end;
end;
end;
var
FieldValue: IActionFieldValue;
S: string;
Params: TStrings;
LocateParams: TLocateParamsList;
begin
Assert(Adapter <> nil);
with GetActionFieldValues(AActionRequest) do
FieldValue := Values[AFieldIndex];
if FieldValue.ValueCount > 0 then
begin
if FieldValue.ValueCount = 1 then
begin
S := FieldValue.Values[0];
Params := TStringList.Create;
try
ExtractParamNameValues(S, Params);
LocateParams := LocateKeyParamsOfStrings(Params);
try
Adapter.SilentLocate(LocateParams, False);
DeleteRow;
finally
LocateParams.Free;
end;
finally
Params.Free;
end;
end
else
RaiseMultipleValuesException(FieldName)
end
else if FieldValue.FileCount > 0 then
RaiseFileUploadNotSupported(FieldName);
end;
end.
|
unit MemMap;
interface
uses
Windows, SysUtils, Classes;
{
const
fmCreate = $FFFF;
fmOpenRead = $0000;
fmOpenWrite = $0001;
fmOpenReadWrite = $0002;
fmShareCompat = $0000;
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
fmShareDenyRead = $0030;
fmShareDenyNone = $0040;
}
type
EMMFError = class(Exception);
TMemMapFile = class(TObject)
private
FFileName: string;
FSize: LongInt;
FFileSize: LongInt;
FFileMode: Integer;
FFileHandle: Integer;
FMapHandle: Integer;
FData: PByte;
FMapNow: Boolean;
procedure AllocFileHandle;
procedure AllocFileMapping;
procedure AllocFileView;
function GetSize: LongInt;
public
constructor Create(FileName: string; FileMode: Integer;
Size: Integer; MapNow: Boolean); virtual;
destructor Destroy; override;
procedure FreeMapping;
property Data: PByte read FData;
property Size: LongInt read GetSize;
property FileName: string read FFileName;
property MapHandle: Integer read FMapHandle;
end;
implementation
{ TMemMapFile }
procedure TMemMapFile.AllocFileHandle;
begin
if FFileMode = fmCreate then
FFileHandle := FileCreate(FFileName)
else
FFileHandle := FileOpen(FFileName, FFileMode);
if FFileHandle < 0 then
raise EMMFError.Create('Failed to open or create file');
end;
procedure TMemMapFile.AllocFileMapping;
var ProAttr: DWORD;
begin
if FFileMode = fmOpenRead then
ProAttr := PAGE_READONLY
else
ProAttr := PAGE_READWRITE;
FMapHandle := CreateFileMapping(FFileHandle, nil, ProAttr,
0, FSize, nil);
if FMapHandle = 0 then
raise EMMFError.Create('Failed to create file mapping');
end;
procedure TMemMapFile.AllocFileView;
var Access: LongInt;
begin
if FFileMode = fmOpenRead then
Access := FILE_MAP_READ
else
Access := FILE_MAP_ALL_ACCESS;
FData := MapViewOfFile(FMapHandle, Access, 0, 0, FSize);
if FData = nil then
begin
raise EMMFError.Create('Failed to map view of file');
end;
end;
constructor TMemMapFile.Create(FileName: string; FileMode, Size: Integer;
MapNow: Boolean);
begin
FMapNow := MapNow;
FFileName := FileName;
FFileMode := FileMode;
AllocFileHandle;
FFileSize := GetFileSize(FFileHandle, nil);
FSize := Size;
try
AllocFileMapping;
except
on EMMFError do
begin
CloseHandle(FFileHandle);
FFileHandle := 0;
raise;
end;
end;
if FMapNow then
AllocFileView;
end;
destructor TMemMapFile.Destroy;
begin
FreeMapping;
if FMapHandle <> 0 then
CloseHandle(FMapHandle);
if FFileHandle <> 0 then
CloseHandle(FFileHandle);
FSize := 0;
FFileSize := 0;
inherited;
end;
procedure TMemMapFile.FreeMapping;
begin
if FData <> nil then
begin
UnmapViewOfFile(FData);
FData := nil;
end;
end;
function TMemMapFile.GetSize: LongInt;
begin
if FSize <> 0 then
Result := FSize
else
Result := FFileSize;
end;
end.
|
unit Unit8;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, xThreadUDPSendScreen, jpeg,
Vcl.ExtCtrls;
type
TForm8 = class(TForm)
mmo1: TMemo;
rdgrp1: TRadioGroup;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure rdgrp1Click(Sender: TObject);
private
{ Private declarations }
dc : HDC;
fullCanvas : TCanvas;
Fullscreen:Tbitmap;
AJpeg : TJPEGImage;
/// <summary>
/// 界面截屏
/// </summary>
procedure GetSreen(Sender: TObject);
/// <summary>
/// 窗口截屏
/// </summary>
procedure GetSreen1(Sender: TObject);
public
{ Public declarations }
end;
var
Form8: TForm8;
implementation
{$R *.dfm}
procedure TForm8.FormCreate(Sender: TObject);
begin
UDPSendScreen := TThreadUDPSendScreen.Create(False);
rdgrp1Click(nil);
dc := GetDC(0);
fullCanvas := TCanvas.Create;
fullCanvas.Handle := dc;
Fullscreen:=TBitmap.Create;
AJpeg := TJPEGImage.Create;
end;
procedure TForm8.FormDestroy(Sender: TObject);
begin
UDPSendScreen.Free;
fullCanvas.Free;
Fullscreen.Free;
AJpeg.Free;
ReleaseDC(0, dc);
end;
procedure TForm8.GetSreen(Sender: TObject);
var
SrcRect, DstRect : TRect;
begin
// fullCanvas := TCanvas.Create;
// fullCanvas.Handle := dc;
// Fullscreen:=TBitmap.Create;
Fullscreen.Width:=Self.Width;
Fullscreen.Height:=Self.Height;
SrcRect := Rect(Self.Left,Self.Top,Self.Left+Fullscreen.Width,Self.Top+Fullscreen.Height);
DstRect := Rect(0,0,Fullscreen.Width,Fullscreen.Height);
// AJpeg := TJPEGImage.Create;
Fullscreen.Canvas.CopyRect(DstRect, fullCanvas, SrcRect); //把整个屏幕复制到BITMAP中
Fullscreen.PixelFormat := pfDevice;
AJpeg.Assign( Fullscreen );
TMemoryStream(Sender).Clear;
AJpeg.SaveToStream(TMemoryStream(Sender));
// fullscreen.free;
// AJpeg.Free;
// fullCanvas.Free;
// fullCanvas := TCanvas.Create;
// fullCanvas.Handle := dc;
//
// Fullscreen:=TBitmap.Create;
//
// Fullscreen.Width:=Self.Width;
// Fullscreen.Height:=Self.Height;
//
// SrcRect := Rect(Self.Left,Self.Top,Self.Left+Fullscreen.Width,Self.Top+Fullscreen.Height);
// DstRect := Rect(0,0,Fullscreen.Width,Fullscreen.Height);
//
// AJpeg := TJPEGImage.Create;
// Fullscreen.Canvas.CopyRect(DstRect, fullCanvas, SrcRect); //把整个屏幕复制到BITMAP中
// Fullscreen.PixelFormat := pfDevice;
// AJpeg.Assign( Fullscreen );
//
// TMemoryStream(Sender).Clear;
// AJpeg.SaveToStream(TMemoryStream(Sender));
//
// fullscreen.free;
// AJpeg.Free;
// fullCanvas.Free;
end;
procedure TForm8.GetSreen1(Sender: TObject);
var
// Fullscreen:Tbitmap;
// AJpeg : TJPEGImage;
SrcRect, DstRect : TRect;
begin
// Fullscreen:=TBitmap.Create;
Fullscreen.Width:=Self.Width-15;
Fullscreen.Height:=Self.Height-36;
SrcRect := Rect(0, 0, Fullscreen.Width,Fullscreen.Height);
DstRect := Rect(0, 0, Fullscreen.Width,Fullscreen.Height);
// AJpeg := TJPEGImage.Create;
Fullscreen.Canvas.CopyRect(DstRect, Self.Canvas, SrcRect); //把整个屏幕复制到BITMAP中
Fullscreen.PixelFormat := pfDevice;
AJpeg.Assign( Fullscreen );
TMemoryStream(Sender).Clear;
AJpeg.SaveToStream(TMemoryStream(Sender));
// fullscreen.free;
// AJpeg.Free;
end;
procedure TForm8.rdgrp1Click(Sender: TObject);
begin
if rdgrp1.ItemIndex = 0 then
begin
UDPSendScreen.OnGetScreen := GetSreen;
end
else
begin
UDPSendScreen.OnGetScreen := GetSreen1;
end;
end;
end.
|
program LIST0105;
uses Graph, GrafLib0, CRT;
VAR
radius : REAL;
NumPoints,
GMode : INTEGER;
center : Vector2;
(* ------------------------------------------------------------------- *)
PROCEDURE Circle(r :REAL);
{ Listing 1.5 }
CONST
segments = 100;
VAR
theta,thinc : REAL;
i : INTEGER;
pt : Vector2;
BEGIN
theta := 0;
thinc := 2*pi / segments { thinc := 360/ segments } ;
{ Move to first point }
pt.x := r;
pt.y := 0.0;
moveto(pt);
{ draw edges of segment-gon }
FOR i := 1 TO segments DO
BEGIN
theta := theta + thinc;
pt.x := r*cos(theta);
pt.y := r*sin(theta);
lineto(pt);
END;
END {Circle};
(* ------------------------------------------------------------------- *)
PROCEDURE Spiral(center : Vector2; radius, ang : REAL; n : INTEGER);
{ Listing 1.6 }
CONST
segments = 100;
VAR
theta, thinc, r : REAL;
i, ptnumber : INTEGER;
pt : Vector2;
BEGIN
theta := ang;
thinc := 2*pi/segments;
{ Move to first point }
pt.x := radius;
pt.y := 0.0;
moveto(center);
ptnumber := segments*n;
FOR i := 1 TO ptnumber DO
BEGIN
theta := theta + thinc;
r := radius*i/ptnumber;
pt.x := center.x + r*cos(theta);
pt.y := center.y + r*sin(theta);
lineto(pt);
END;
END {Spiral};
(* ------------------------------------------------------------------- *)
PROCEDURE Twist(center : Vector2; radius, ang : REAL; n : INTEGER);
{ Exercise 1.7 }
VAR
i : INTEGER;
frac : REAL;
BEGIN
frac := 2*pi/n;
Circle(radius);
Center.x := 0; Center.y := 0;
FOR i := 0 TO n-1 DO
Spiral(Center,radius,ang+frac*i,n);
END {Twist};
(* ------------------------------------------------------------------- *)
PROCEDURE PointToPoint(r : REAL; n : INTEGER);
{ listing 1.7 }
VAR
pt : ARRAY[0..100] OF Vector2;
i,j : INTEGER;
theta, thinc : REAL;
BEGIN
theta := 0.0;
thinc := 2*pi/n;
FOR i := 1 TO n DO
BEGIN
pt[i].x := r * cos(theta);
pt[i].y := r * sin(theta);
theta := theta + thinc;
END;
FOR i := 1 TO n-1 DO
FOR j := i+1 TO n DO
BEGIN
MoveTo(pt[i]);
LineTo(pt[j]);
END;
END {PointToPoint};
(* ------------------------------------------------------------------- *)
PROCEDURE BetterPointToPoint(r : REAL; n : INTEGER);
{ doesn't work quite right }
VAR
pt : ARRAY[0..99] OF Vector2;
i,j,k : INTEGER;
theta, thinc : REAL;
BEGIN
theta := 0.0;
thinc := 2*pi/n;
FOR i := 0 TO n DO
BEGIN
pt[i].x := r * cos(theta);
pt[i].y := r * sin(theta);
theta := theta + thinc;
END;
MoveTo(pt[0]);
FOR i := 0 TO abs(n mod 2 - 1) DO (* do twice if n is even *)
BEGIN
j := i;
MoveTo(pt[i]);
FOR k := 0 TO n DIV 2 DO
REPEAT
j := (j + k) MOD n;
LineTo(pt[j]);
Delay(250);
UNTIL j = i;
END;
END {BetterPointToPoint};
(* ------------------------------------------------------------------- *)
(* ------------------------------------------------------------------- *)
BEGIN
(*
Writeln(' Please Type in Radius');
Readln(radius);
Start(0);
Circle(radius);
readln; Erase;
Center.x := 0; Center.y := 0;
Spiral(Center,radius,0.0,6);
readln; Erase;
Twist(Center,radius,0.0,3);
GMode := GetGraphMode;
RestoreCRTMode;
Writeln(' Type in Number Of Points');
Readln(NumPoints);
SetGraphMode(Gmode);
PointToPoint(Radius, NumPoints);
Finish;
END { LIST0105}.
|
unit UMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.XPMan,
Vcl.Menus, Vcl.Imaging.pngimage, Vcl.ExtCtrls, Vcl.ImgList, System.ImageList;
type
TfrmMain = class(TForm)
lvRoms: TListView;
cbSystem: TComboBox;
imgPS: TImage;
MainMenu1: TMainMenu;
imgNES: TImage;
imgN64: TImage;
imgSNES: TImage;
lblNoteEmu: TLabel;
File1: TMenuItem;
Options1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
About1: TMenuItem;
btnOpenEmuFolder: TButton;
btnStart: TButton;
btnRefresh: TButton;
imlIcons: TImageList;
lblFileNameDesc: TLabel;
lblFileName: TLabel;
lblFileSizeDesc: TLabel;
lblFileSize: TLabel;
procedure FormCreate(Sender: TObject);
procedure cbSystemChange(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure lvRomsClick(Sender: TObject);
procedure btnOpenEmuFolderClick(Sender: TObject);
procedure Options1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure btnStartClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses ShellApi, UOptions, IniFiles;
function ProcessAMsg: Boolean;
{ equivalent to TApplication.ProcessMessages }
var
Msg: TMsg;
msg_proc: boolean;
begin
msg_proc := False;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
msg_proc := True;
if Msg.Message <> WM_QUIT then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
ProcessAMsg := msg_proc;
end;
procedure ProcessMessage;
begin
while ProcessAMsg do;
end;
//http://www.delphicorner.f9.co.uk/articles/wapi4.htm
function ExecNewProcess(ProgramName : String; Wait: Boolean; var ProcID:DWord):DWord;
var
StartInfo : TStartupInfo;
ProcInfo : TProcessInformation;
CreateOK : Boolean;
ErrorCode : DWord;
Appdone : DWord;
begin
{ fill with known state }
ErrorCode:=0;
FillChar(StartInfo,SizeOf(TStartupInfo),#0);
FillChar(ProcInfo,SizeOf(TProcessInformation),#0);
StartInfo.cb := SizeOf(TStartupInfo);
CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil,False,
CREATE_NEW_PROCESS_GROUP+IDLE_PRIORITY_CLASS+SYNCHRONIZE,
nil, nil, StartInfo, ProcInfo);
{ check to see if successful }
if CreateOK then
begin
//may or may not be needed. Usually wait for child processes
if Wait then
begin
repeat
Appdone := WaitForSingleObject(ProcInfo.hProcess, INFINITE);
ProcessMessage;
until Appdone <> WAIT_TIMEOUT;
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end
else
begin
procid := ProcInfo.hProcess;
ShowMessage('No emulator defined or wrong path');
end;
GetExitCodeProcess(ProcInfo.hProcess,ErrorCode);
ExecNewProcess := ErrorCode;
end;
end;
//http://stackoverflow.com/questions/1642220/getting-size-of-a-file-in-delphi-2010-or-later
function FileSize(const aFilename: String): Int64;
var
info: TWin32FileAttributeData;
begin
result := -1;
if NOT GetFileAttributesEx(PWideChar(aFileName), GetFileExInfoStandard, @info) then
EXIT;
result := Int64(info.nFileSizeLow) or Int64(info.nFileSizeHigh shl 32);
end;
//http://www.swissdelphicenter.ch/torry/showcode.php?id=421
procedure LV_InsertFiles(strPath: string; FileExt:string; ListView: TListView; ImageList: TImageList);
var
i: Integer;
Icon: TIcon;
SearchRec: TSearchRec;
ListItem: TListItem;
FileInfo: SHFILEINFO;
begin
// Create a temporary TIcon
Icon := TIcon.Create;
ListView.Items.BeginUpdate;
try
// search for the first file
i := FindFirst(strPath + '*.' + FileExt, faAnyFile, SearchRec);
while i = 0 do
begin
with ListView do
begin
// On directories and volumes
if ((SearchRec.Attr and FaDirectory <> FaDirectory) and
(SearchRec.Attr and FaVolumeId <> FaVolumeID)) then
begin
ListItem := ListView.Items.Add;
//Get The DisplayName
SHGetFileInfo(PChar(strPath + SearchRec.Name), 0, FileInfo,
SizeOf(FileInfo), SHGFI_DISPLAYNAME);
Listitem.Caption := FileInfo.szDisplayName;
// Get The TypeName
SHGetFileInfo(PChar(strPath + SearchRec.Name), 0, FileInfo,
SizeOf(FileInfo), SHGFI_TYPENAME);
ListItem.SubItems.Add(FileInfo.szTypeName);
//Get The Icon That Represents The File
SHGetFileInfo(PChar(strPath + SearchRec.Name), 0, FileInfo,
SizeOf(FileInfo), SHGFI_ICON or SHGFI_SMALLICON);
icon.Handle := FileInfo.hIcon;
ListItem.ImageIndex := ImageList.AddIcon(Icon);
// Destroy the Icon
DestroyIcon(FileInfo.hIcon);
end;
end;
i := FindNext(SearchRec);
end;
finally
Icon.Free;
ListView.Items.EndUpdate;
end;
end;
procedure TfrmMain.btnOpenEmuFolderClick(Sender: TObject);
begin
ShellExecute(handle,'open',PChar('.\emulators\'), '','',SW_SHOWNORMAL);
end;
procedure TfrmMain.btnRefreshClick(Sender: TObject);
begin
cbSystemChange(Sender);
end;
procedure TfrmMain.btnStartClick(Sender: TObject);
var procid:dword;
begin
btnStart.Enabled:=false;
case cbSystem.ItemIndex of
0:ExecNewProcess(frmOptions.edtGBA.Text +' ".\games\GB\'+ lvRoms.Selected.Caption+'"',true,procid);
1:ExecNewProcess(frmOptions.edtGBA.Text +' ".\games\GBC\'+ lvRoms.Selected.Caption+'"',true,procid);
2:ExecNewProcess(frmOptions.edtGBA.Text +' ".\games\GBA\'+ lvRoms.Selected.Caption+'"',true,procid);
3:ExecNewProcess(frmOptions.edtNDS.Text +' ".\games\NDS\'+ lvRoms.Selected.Caption+'"',true,procid);
4:ExecNewProcess(frmOptions.edtNES.Text +' ".\games\NES\'+ lvRoms.Selected.Caption+'"',true,procid);
5:ExecNewProcess(frmOptions.edtSNES.Text +' ".\games\SNES\'+ lvRoms.Selected.Caption+'"',true,procid);
6:ExecNewProcess(frmOptions.edtN64.Text +' ".\games\N64\'+ lvRoms.Selected.Caption+'"',true,procid);
7:ExecNewProcess(frmOptions.edtGC.Text +' -b -e ".\games\GC\'+ lvRoms.Selected.Caption+'"',true,procid);
8:ExecNewProcess(frmOptions.edtGC.Text +' -b -e ".\games\WII\'+ lvRoms.Selected.Caption+'"',true,procid);
9:ExecNewProcess(frmOptions.edtPSX.Text +' -nogui -loadbin ".\games\PSX\'+ lvRoms.Selected.Caption+'"',true,procid);
10:ExecNewProcess(frmOptions.edtPS2.Text +' ".\games\PS2\'+ lvRoms.Selected.Caption+'" --nogui',true,procid);
11:ExecNewProcess(frmOptions.edtPSP.Text +' ".\games\PSP\'+ lvRoms.Selected.Caption+'"',true,procid);
end;
btnSTart.Enabled:=true;
end;
procedure TfrmMain.cbSystemChange(Sender: TObject);
const Systems: array[0..11] of String = ('GB','GBC','GBA','NDS','NES','SNES','N64','GC','WII','PSX','PS2','PSP');
const FileExt: array[0..11] of String = ('gb','gbc','gba','nds','nes','s*c','*64','iso','iso','*','*','iso');
var ItemIndex: integer;
begin
ItemIndex:=cbSystem.ItemIndex;
lvRoms.Clear;
LV_InsertFiles('.\games\'+Systems[ItemIndex]+'\',FileExt[ItemIndex],lvRoms,imlIcons);
end;
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
var Ini: TIniFile;
begin
Ini := TIniFile.Create( ChangeFileExt( Application.ExeName, '.ini' ) );
try
ini.WriteString('Paths','nestopia',frmOptions.edtNES.Text);
ini.WriteString('Paths','project64',frmOptions.edtN64.Text);
ini.WriteString('Paths','desmume',frmOptions.edtNDS.Text);
ini.WriteString('Paths','epsxe',frmOptions.edtPSX.Text);
ini.WriteString('Paths','pcsx2',frmOptions.edtPS2.Text);
ini.WriteString('Paths','ppsspp',frmOptions.edtPSP.Text);
ini.WriteString('Paths','zsnes',frmOptions.edtSNES.Text);
ini.WriteString('Paths','vba',frmOptions.edtGBA.Text);
ini.WriteString('Paths','dolphin',frmOptions.edtGC.Text);
finally
Ini.Free;
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
const Systems: array[0..11] of String = ('GB','GBC','GBA','NDS','NES','SNES','N64','GC','WII','PSX','PS2','PSP');
var I:integer;
begin
if not directoryexists('.\games\') then
createdir(PChar('.\games\'));
if not directoryexists('.\emulators\') then
createdir(PChar('.\emulators\'));
for I := 0 to 11 do
begin
if not directoryexists('.\games\'+Systems[I]+'\') then
createdir(PChar('.\games\'+Systems[I]+'\'));
end;
cbSystemChange(Sender);
lvRomsClick(Sender);
end;
procedure TfrmMain.FormShow(Sender: TObject);
var Ini: TIniFile;
begin
Ini := TIniFile.Create( ChangeFileExt( Application.ExeName, '.ini' ) );
try
frmOptions.edtNES.Text:=ini.ReadString('Paths','nestopia','');
frmOptions.edtn64.Text:=ini.ReadString('Paths','project64','');
frmOptions.edtNDS.Text:=ini.ReadString('Paths','desmume','');
frmOptions.edtPSX.Text:=ini.ReadString('Paths','epsxe','');
frmOptions.edtPS2.Text:=ini.ReadString('Paths','pcsx2','');
frmOptions.edtPSP.Text:=ini.ReadString('Paths','ppsspp','');
frmOptions.edtSNES.Text:=ini.ReadString('Paths','zsnes','');
frmOptions.edtGBA.Text:=ini.ReadString('Paths','vba','');
frmOptions.edtGC.Text:=ini.ReadString('Paths','dolphin','');
finally
Ini.Free;
end;
end;
procedure TfrmMain.lvRomsClick(Sender: TObject);
const Systems: array[0..11] of String = ('GB','GBC','GBA','NDS','NES','SNES','N64','GC','WII','PSX','PS2','PSP');
var ItemIndex: integer;
begin
ItemIndex:=cbSystem.ItemIndex;
if lvRoms.ItemIndex = -1 then
begin
btnStart.Enabled := false;
lblFileName.Caption:='';
lblFileSize.Caption:='';
end
else
begin
btnStart.Enabled:=true;
lblFileName.Caption:=lvRoms.Selected.Caption;
lblFileSize.Caption:=inttostr(FileSize('.\games\'+Systems[ItemIndex]+'\'+lvRoms.Selected.Caption))+' Bytes';
end;
end;
procedure TfrmMain.Options1Click(Sender: TObject);
begin
frmOptions.ShowModal;
end;
end.
|
unit fODAuto;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fODBase, StdCtrls, ComCtrls, ExtCtrls, ORFn, ORCtrls,
VA508AccessibilityManager;
type
TfrmODAuto = class(TfrmODBase)
Label1: TLabel;
public
procedure InitDialog; override;
procedure SetupDialog(OrderAction: Integer; const ID: string); override;
procedure Validate(var AnErrMsg: string); override;
end;
var
frmODAuto: TfrmODAuto;
implementation
{$R *.DFM}
uses rODBase, rOrders, fTemplateDialog, uTemplateFields, rTemplates, uConst, uTemplates,
rConsults, uCore, uODBase, rODMeds, fFrame;
procedure TfrmODAuto.InitDialog;
begin
inherited;
// nothing for now
end;
procedure TfrmODAuto.Validate(var AnErrMsg: string);
var
cptn, tmp, DocInfo: string;
TempSL: TStringList;
LType: TTemplateLinkType;
IEN: integer;
HasObjects: boolean;
begin
inherited;
DocInfo := '';
LType := DisplayGroupToLinkType(Responses.DisplayGroup);
tmp := Responses.EValueFor('COMMENT', 1);
ExpandOrderObjects(tmp, HasObjects);
Responses.OrderContainsObjects := Responses.OrderContainsObjects or HasObjects;
if (LType <> ltNone) or HasTemplateField(tmp) then
begin
cptn := 'Reason for Request: ' + Responses.EValueFor('ORDERABLE', 1);
case LType of
ltConsult: IEN := StrToIntDef(GetServiceIEN(Responses.IValueFor('ORDERABLE', 1)),0);
ltProcedure: IEN := StrToIntDef(GetProcedureIEN(Responses.IValueFor('ORDERABLE', 1)),0);
else IEN := 0;
end;
if IEN <> 0 then
ExecuteTemplateOrBoilerPlate(tmp, IEN, LType, nil, cptn, DocInfo)
else
CheckBoilerplate4Fields(tmp, cptn);
if WasTemplateDialogCanceled then AnErrMsg := 'The Auto-Accept Quick Order cannot be saved since the template was cancelled.';
if tmp <> '' then
Responses.Update('COMMENT', 1, TX_WPTYPE, tmp)
else
begin
TempSL := TStringList.Create;
try
TempSL.Text := Responses.EValueFor('COMMENT', 1);
Convert2LMText(TempSL);
Responses.Update('COMMENT', 1, TX_WPTYPE, TempSL.Text);
finally
TempSL.Free;
end;
end;
end;
end;
procedure TfrmODAuto.SetupDialog(OrderAction: Integer; const ID: string);
var
DialogNames: TDialogNames;
DlgOI, AnInstance, IVDsGrp: integer;
DEAFailStr, TX_INFO: string;
InptDlg: Boolean;
begin
inherited; // Responses is already loaded here
DEAFailStr := '';
InptDlg := False;
IVDsGrp := DisplayGroupByName('IV RX');
if DisplayGroup = DisplayGroupByName('UD RX') then InptDlg := TRUE;
if DisplayGroup = DisplayGroupByName('O RX') then InptDlg := FALSE;
if DisplayGroup = DisplayGroupByName('NV RX') then InptDlg := FALSE;
if DisplayGroup = DisplayGroupByName('RX') then InptDlg := OrderForInpatient;
if (not Patient.Inpatient) and (DisplayGroup = IVDsGrp) then //if auto-accept of IV med order on Outpatient (ex: from Copy to New order action)
begin
AnInstance := Responses.NextInstance('ORDERABLE', 0);
while AnInstance > 0 do //perform DEA/schedule check on all solutions before auto-accepting
begin
DlgOI := StrtoIntDef(Responses.IValueFor('ORDERABLE',AnInstance),0);
DEAFailStr := DEACheckFailedForIVOnOutPatient(DlgOI,'S');
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
AbortOrder := True;
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailedForIVOnOutPatient(DlgOI,'S');
end
else
begin
AbortOrder := True;
Exit;
end;
end;
AnInstance := Responses.NextInstance('ORDERABLE', AnInstance);
end;
AnInstance := Responses.NextInstance('ADDITIVE', 0);
while AnInstance > 0 do //perform DEA/schedule check on all additives before auto-accepting
begin
DlgOI := StrtoIntDef(Responses.IValueFor('ADDITIVE',AnInstance),0);
DEAFailStr := DEACheckFailedForIVOnOutPatient(DlgOI,'A');
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
AbortOrder := True;
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailedForIVOnOutPatient(DlgOI,'A');
end
else
begin
AbortOrder := True;
Exit;
end;
end;
AnInstance := Responses.NextInstance('ADDITIVE', AnInstance);
end;
end
else if DisplayGroup <> IVDsGrp then
begin //if auto-accept of unit dose, NON-VA, or Outpatient meds
DlgOI := StrtoIntDef(Responses.IValueFor('ORDERABLE',1),0);
DEAFailStr := DEACheckFailed(DlgOI,InptDlg);
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
AbortOrder := True;
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailed(DlgOI,InptDlg);
end
else
begin
AbortOrder := True;
Exit;
end;
end; //end while
end; //end else
AutoAccept := True;
StatusText('Loading Dialog Definition');
FillerID := FillerIDForDialog(DialogIEN);
IdentifyDialog(DialogNames, DialogIEN);
Responses.Dialog := DialogNames.BaseName; // loads formatting info
Responses.DialogDisplayName := DialogNames.Display;
StatusText('');
end;
end.
|
unit FIToolkit.Config.Manager;
interface
uses
System.SysUtils, System.Rtti,
FIToolkit.Config.Data, FIToolkit.Config.Storage, FIToolkit.Config.Types, FIToolkit.Commons.Types;
type
TConfigManager = class sealed
strict private
FConfigData : TConfigData;
FConfigFile : TConfigFile;
private
function FilterConfigProp(Instance : TObject; Prop : TRttiProperty) : Boolean;
function FindConfigAttribute(Prop : TRttiProperty; out Value : TConfigAttribute) : Boolean;
function GetConfigFileName : TFileName;
function GetConfigPropArrayDelimiter(Prop : TRttiProperty) : String;
function GetPropDefaultValue(Prop : TRttiProperty) : TValue;
function PropHasDefaultValue(Prop : TRttiProperty) : Boolean;
procedure ReadObjectFromConfig(Instance : TObject; const Filter : TObjectPropertyFilter);
procedure SetObjectPropsDefaults(Instance : TObject; const Filter : TObjectPropertyFilter);
procedure WriteObjectToConfig(Instance : TObject; const Filter : TObjectPropertyFilter);
protected
procedure FillDataFromFile;
procedure FillFileFromData;
procedure GenerateDefaultConfig;
procedure SetDefaults(TargetProps : TConfigPropCategory);
public
constructor Create(const ConfigFileName : TFileName; GenerateConfig, Validate : Boolean);
destructor Destroy; override;
property ConfigData : TConfigData read FConfigData;
property ConfigFileName : TFileName read GetConfigFileName;
end;
implementation
uses
System.TypInfo,
FIToolkit.Config.FixInsight, FIToolkit.Config.Defaults,
FIToolkit.Commons.Utils;
{ TConfigManager }
constructor TConfigManager.Create(const ConfigFileName : TFileName; GenerateConfig, Validate : Boolean);
begin
inherited Create;
FConfigData := TConfigData.Create;
FConfigData.Validate := Validate;
FConfigData.FixInsightOptions.Validate := Validate;
FConfigFile := TConfigFile.Create(ConfigFileName, GenerateConfig);
if GenerateConfig then
GenerateDefaultConfig
else
if FConfigFile.HasFile then
begin
SetDefaults(cpcNonSerializable);
FillDataFromFile;
end
else
SetDefaults(cpcAny);
end;
destructor TConfigManager.Destroy;
begin
FreeAndNil(FConfigFile);
FreeAndNil(FConfigData);
inherited Destroy;
end;
procedure TConfigManager.FillDataFromFile;
begin
FConfigFile.Load;
ReadObjectFromConfig(FConfigData,
function (Instance : TObject; Prop : TRttiProperty) : Boolean
begin
Result := (Prop.IsWritable or Prop.PropertyType.IsInstance) and FilterConfigProp(Instance, Prop);
end
);
end;
procedure TConfigManager.FillFileFromData;
begin
WriteObjectToConfig(FConfigData,
function (Instance : TObject; Prop : TRttiProperty) : Boolean
begin
Result := Prop.IsReadable and FilterConfigProp(Instance, Prop);
end
);
FConfigFile.Save;
end;
function TConfigManager.FilterConfigProp(Instance : TObject; Prop : TRttiProperty) : Boolean;
var
CfgAttr : TConfigAttribute;
begin
Result := False;
if FindConfigAttribute(Prop, CfgAttr) then
if CfgAttr.Serializable then
Result := ((Instance is TConfigData) and (CfgAttr is FIToolkitParam)) or
((Instance is TFixInsightOptions) and (CfgAttr is FixInsightParam));
end;
function TConfigManager.FindConfigAttribute(Prop : TRttiProperty; out Value : TConfigAttribute) : Boolean;
var
Attr : TCustomAttribute;
begin
Result := False;
for Attr in Prop.GetAttributes do
if Attr is TConfigAttribute then
begin
Value := TConfigAttribute(Attr);
Exit(True);
end;
end;
procedure TConfigManager.GenerateDefaultConfig;
begin
SetDefaults(cpcSerializable);
FillFileFromData;
end;
function TConfigManager.GetConfigFileName : TFileName;
begin
Result := FConfigFile.FileName;
end;
function TConfigManager.GetConfigPropArrayDelimiter(Prop : TRttiProperty) : String;
var
CfgAttr : TConfigAttribute;
begin
Result := String.Empty;
if FindConfigAttribute(Prop, CfgAttr) then
Result := CfgAttr.ArrayDelimiter;
Assert(not (Prop.PropertyType.IsArray and Result.IsEmpty),
Format('Property %s has an array type but no array delimiter.', [Prop.Name]));
end;
function TConfigManager.GetPropDefaultValue(Prop : TRttiProperty) : TValue;
var
Attr : TCustomAttribute;
begin
Result := TValue.Empty;
for Attr in Prop.GetAttributes do
if Attr is TDefaultValueAttribute then
Exit(TDefaultValueAttribute(Attr).Value);
end;
function TConfigManager.PropHasDefaultValue(Prop : TRttiProperty) : Boolean;
var
Attr : TCustomAttribute;
begin
Result := False;
for Attr in Prop.GetAttributes do
if Attr is TDefaultValueAttribute then
Exit(True);
end;
procedure TConfigManager.ReadObjectFromConfig(Instance : TObject; const Filter : TObjectPropertyFilter); //FI:C103
var
Ctx : TRttiContext;
InstanceType : TRttiInstanceType;
Prop : TRttiProperty;
i : Integer;
V : TValue;
sArray : String;
arrS : TArray<String>;
arrV : TArray<TValue>;
begin //FI:C101
Ctx := TRttiContext.Create;
try
InstanceType := Ctx.GetType(Instance.ClassType) as TRttiInstanceType;
for Prop in InstanceType.GetProperties do
if Filter(Instance, Prop) then
begin
if Prop.PropertyType.IsInstance then
ReadObjectFromConfig(Prop.GetValue(Instance).AsObject, Filter)
else
if Prop.PropertyType.IsString then
Prop.SetValue(Instance, FConfigFile.Config.ReadString(Instance.QualifiedClassName, Prop.Name,
GetPropDefaultValue(Prop).AsVariant))
else
if Prop.PropertyType.IsOrdinal then
begin
i := FConfigFile.Config.ReadInteger(Instance.QualifiedClassName, Prop.Name,
GetPropDefaultValue(Prop).AsVariant);
TValue.Make(@i, Prop.PropertyType.Handle, V);
Prop.SetValue(Instance, V);
end
else
if Prop.PropertyType.IsArray then
begin
sArray := FConfigFile.Config.ReadString(Instance.QualifiedClassName, Prop.Name, String.Empty);
if sArray.IsEmpty then
begin
if FConfigFile.Config.ValueExists(Instance.QualifiedClassName, Prop.Name) then
V := TValue.Empty
else
V := GetPropDefaultValue(Prop);
end
else
if Prop.PropertyType.Handle.TypeData.DynArrElType^.IsString then
begin
arrS := sArray.Split([GetConfigPropArrayDelimiter(Prop)], TStringSplitOptions.ExcludeEmpty);
SetLength(arrV, Length(arrS));
for i := 0 to High(arrV) do
arrV[i] := arrS[i].Trim;
V := TValue.FromArray(Prop.PropertyType.Handle, arrV);
end
else
Assert(False, 'Unhandled array element type while deserializing object from config.');
Prop.SetValue(Instance, V);
end
else
Assert(False, 'Unhandled property type kind while deserializing object from config.');
end;
finally
Ctx.Free;
end;
end;
procedure TConfigManager.SetDefaults(TargetProps : TConfigPropCategory);
var
bValidateCD, bValidateFI : Boolean;
Filter : TObjectPropertyFilter;
begin
bValidateCD := FConfigData.Validate;
bValidateFI := FConfigData.FixInsightOptions.Validate;
try
FConfigData.Validate := False;
FConfigData.FixInsightOptions.Validate := False;
case TargetProps of
cpcAny:
Filter :=
function (Instance : TObject; Prop : TRttiProperty) : Boolean
begin
Result := PropHasDefaultValue(Prop);
end;
cpcSerializable:
Filter :=
function (Instance : TObject; Prop : TRttiProperty) : Boolean
var
CfgAttr : TConfigAttribute;
begin
Result := PropHasDefaultValue(Prop);
if Result and FindConfigAttribute(Prop, CfgAttr) then
Result := CfgAttr.Serializable;
end;
cpcNonSerializable:
Filter :=
function (Instance : TObject; Prop : TRttiProperty) : Boolean
var
CfgAttr : TConfigAttribute;
begin
Result := PropHasDefaultValue(Prop);
if Result and FindConfigAttribute(Prop, CfgAttr) then
Result := not CfgAttr.Serializable;
end;
end;
SetObjectPropsDefaults(FConfigData, Filter);
finally
FConfigData.Validate := bValidateCD;
FConfigData.FixInsightOptions.Validate := bValidateFI;
end;
end;
procedure TConfigManager.SetObjectPropsDefaults(Instance : TObject; const Filter : TObjectPropertyFilter);
var
Ctx : TRttiContext;
InstanceType : TRttiInstanceType;
Prop : TRttiProperty;
begin
Ctx := TRttiContext.Create;
try
InstanceType := Ctx.GetType(Instance.ClassType) as TRttiInstanceType;
for Prop in InstanceType.GetProperties do
if Prop.PropertyType.IsInstance then
SetObjectPropsDefaults(Prop.GetValue(Instance).AsObject, Filter)
else
if Prop.IsWritable and Filter(Instance, Prop) then
Prop.SetValue(Instance, GetPropDefaultValue(Prop));
finally
Ctx.Free;
end;
end;
procedure TConfigManager.WriteObjectToConfig(Instance : TObject; const Filter : TObjectPropertyFilter);
var
Ctx : TRttiContext;
InstanceType : TRttiInstanceType;
Prop : TRttiProperty;
S, sArrDelim : String;
V : TValue;
i : Integer;
begin
Ctx := TRttiContext.Create;
try
InstanceType := Ctx.GetType(Instance.ClassType) as TRttiInstanceType;
for Prop in InstanceType.GetProperties do
if Filter(Instance, Prop) then
begin
if Prop.PropertyType.IsInstance then
WriteObjectToConfig(Prop.GetValue(Instance).AsObject, Filter)
else
if Prop.PropertyType.IsString then
FConfigFile.Config.WriteString(Instance.QualifiedClassName, Prop.Name, Prop.GetValue(Instance).AsVariant)
else
if Prop.PropertyType.IsOrdinal then
FConfigFile.Config.WriteInteger(Instance.QualifiedClassName, Prop.Name, Prop.GetValue(Instance).AsVariant)
else
if Prop.PropertyType.IsArray then
begin
S := String.Empty;
V := Prop.GetValue(Instance);
sArrDelim := GetConfigPropArrayDelimiter(Prop);
for i := 0 to V.GetArrayLength - 1 do
if S.IsEmpty then
S := V.GetArrayElement(i).ToString
else
S := S + sArrDelim + V.GetArrayElement(i).ToString;
FConfigFile.Config.WriteString(Instance.QualifiedClassName, Prop.Name, S);
end
else
Assert(False, 'Unhandled property type kind while serializing object to config.');
end;
finally
Ctx.Free;
end;
end;
end.
|
unit uFuncionarioController;
interface
uses uFuncionario, uDependente, uFuncionarioDAO, Vcl.Forms,
System.Generics.Collections;
type
TFuncionarioController = class
protected
FFuncionarioDAO: TFuncionarioDAO;
FView: TForm;
FViewDependente: TForm;
FLista: TList<TFuncionario>;
public
constructor Create; overload;
destructor Destroy;
procedure SetView(AView: TForm);
procedure SetViewDependente(AView: TForm);
procedure LimparView;
procedure LimparViewDependente;
procedure SalvarCadastro;
function getListaFuncionarios: TList<TFuncionario>;
procedure AdicionarDependente; overload;
procedure AdicionarFuncionario; overload;
procedure AdicionarDependente(const ADependente: TDependente); overload;
procedure AdicionarFuncionario(const AFuncionario: TFuncionario); overload;
function CalcularImpostoIR: Real;
function CalcularImpostoINSS: Real;
end;
implementation
uses
uMain, cadDependente, SysUtils;
const PC_IR= 0.15;
PC_INSS= 0.08;
{ TFuncionarioController }
procedure TFuncionarioController.AdicionarDependente;
var
oDependente: TDependente;
oFuncionario: TFuncionario;
begin
oDependente := TDependente.Create;
oDependente.Nome := ( FViewDependente As TfrmDependente).edtNome.Text;
oDependente.IsCalculaIR := ( FViewDependente As TfrmDependente).cbIR.Checked;
oDependente.IsCalculaINSS := ( FViewDependente As TfrmDependente).cbINSS.Checked;
oDependente.Id_Funcionario := 0;
AdicionarDependente(oDependente);
end;
procedure TFuncionarioController.AdicionarFuncionario;
var
oFuncionario: TFuncionario;
begin
oFuncionario := TFuncionario.Create;
oFuncionario.Nome := (FView as TfrmPrincipal).edtNome.Text;
oFuncionario.CPF := (FView as TfrmPrincipal).edtCPF.Text;
oFuncionario.Salario := StrToFloatDef((FView as TfrmPrincipal)
.edtSalario.Text, 0);
AdicionarFuncionario(oFuncionario);
(FView as TfrmPrincipal).btnAdicionarDependente.Enabled := True;
(FView as TfrmPrincipal).btnCalcImpost.Enabled := True;
(FView as TfrmPrincipal).btnSalvar.Enabled := True;
end;
procedure TFuncionarioController.LimparView;
begin
(FView as TfrmPrincipal).edtNome.Clear;
(FView as TfrmPrincipal).edtCPF.Clear;
(FView as TfrmPrincipal).edtSalario.Clear;
end;
procedure TFuncionarioController.LimparViewDependente;
begin
( FViewDependente As TfrmDependente).edtNome.Clear;
( FViewDependente As TfrmDependente).cbIR.Checked := False;
( FViewDependente As TfrmDependente).cbINSS.Checked := False;
end;
procedure TFuncionarioController.AdicionarFuncionario(
const AFuncionario: TFuncionario);
begin
FLista.Add(AFuncionario);
end;
function TFuncionarioController.CalcularImpostoINSS: Real;
var
oDependente: TDependente;
oFuncionario: TFuncionario;
bINSS: Boolean;
begin
result := 0.0;
if FLista.Last.Dependentes.Count = 0 then
Exit;
bINSS := false;
oFuncionario := FLista.Last;
for oDependente in oFuncionario.Dependentes do
begin
if oDependente.IsCalculaINSS then
bINSS := true;
end;
if not bINSS then
result := 0.0;
result := (oFuncionario.Salario * PC_INSS);
end;
function TFuncionarioController.CalcularImpostoIR: Real;
var
iNumDependentes: Integer;
oDependente: TDependente;
oFuncionario: TFuncionario;
begin
result := 0.0;
if FLista.Last.Dependentes.Count = 0 then
Exit;
oFuncionario := FLista.Last;
if oFuncionario.Salario <= 0 then
Exit;
iNumDependentes := 0;
for oDependente in oFuncionario.Dependentes do
begin
if oDependente.IsCalculaIR then
inc(iNumDependentes);
end;
if iNumDependentes = 0 then
result := 0.0;
result := (oFuncionario.Salario -(iNumDependentes*100)) * PC_IR;
end;
constructor TFuncionarioController.Create;
begin
FFuncionarioDAO := TFuncionarioDAO.Create;
FLista := TList<TFuncionario>.Create();
end;
destructor TFuncionarioController.Destroy;
var
oFuncionario: TFuncionario;
begin
FFuncionarioDAO.Free;
for oFuncionario in FLista do
begin
oFuncionario.Free;
end;
FLista.Free;
FLista := nil;
end;
function TFuncionarioController.getListaFuncionarios: TList<TFuncionario>;
begin
result := FLista;
end;
procedure TFuncionarioController.SalvarCadastro;
var
oFuncionario: TFuncionario;
begin
for oFuncionario in FLista do
begin
FFuncionarioDAO.Salvar(oFuncionario);
end;
end;
procedure TFuncionarioController.SetView(AView: TForm);
begin
FView := AView;
end;
procedure TFuncionarioController.SetViewDependente(AView: TForm);
begin
FViewDependente := AView;
end;
procedure TFuncionarioController.AdicionarDependente(
const ADependente: TDependente);
begin
FLista.Last.Dependentes.Add(ADependente);
end;
end.
|
UNIT Mathunit;
INTERFACE
TYPE
PolyPtr = ^Polynom;
RootStack = ^EachRoot;
Complex = RECORD
Re : DOUBLE;
Im : DOUBLE;
END;
Polynom = RECORD
Link : PolyPtr;
Coeff : Complex;
END;
EachRoot = RECORD
Link : RootStack;
Coeff : Complex;
END;
FUNCTION Floor(X : DOUBLE) : DOUBLE; (* The next lowest integer *)
FUNCTION Ceiling(X : DOUBLE) : DOUBLE; (* The next highest integer *)
FUNCTION Log10(X : DOUBLE) : DOUBLE; (* Base 10 log of x *)
FUNCTION Exp10(X : DOUBLE) : DOUBLE; (* 10 raised to the x power *)
FUNCTION PwrXY(X, Y : DOUBLE) : DOUBLE; (* raise x to the power y *)
FUNCTION QDBV(Volts : DOUBLE) : DOUBLE; (* convert from volts to dB *)
FUNCTION QDBW(Watts : DOUBLE) : DOUBLE; (* convert from watts to dB *)
FUNCTION QWATTS(DB : DOUBLE) : DOUBLE; (* convert from dB to watts *)
FUNCTION QVOLTS(DB : DOUBLE) : DOUBLE; (* convert from dB to volts *)
FUNCTION SINH(X : DOUBLE) : DOUBLE; (* hyperbolic sine *)
FUNCTION COSH(X : DOUBLE) : DOUBLE; (* hyperbolic cosine *)
FUNCTION TANH(X : DOUBLE) : DOUBLE; (* hyperbolic tangent *)
FUNCTION ISINH(X : DOUBLE) : DOUBLE; (* arc hyperbolic sine *)
FUNCTION ICOSH(X : DOUBLE) : DOUBLE; (* arc hyperbolic cosine *)
FUNCTION ITANH(X : DOUBLE) : DOUBLE; (* arc hyperbolic tangent *)
FUNCTION ARCSIN(X : DOUBLE) : DOUBLE; (* arc sine using TP arctan function *)
FUNCTION ARCCOS(X : DOUBLE) : DOUBLE; (* inverse cosine using TP arctan *)
FUNCTION ATAN2(X, Y : DOUBLE) : DOUBLE; (* arctan function with quadrant check
X is real axis value or denominator, Y is imaginary axis value or numerator *)
FUNCTION TAN(X : DOUBLE) : DOUBLE; (* tangent of X *)
FUNCTION GAUSS (Mean, StdDev : DOUBLE) : DOUBLE; (* gaussian random number *)
FUNCTION RESIDUE(Radix, Number : DOUBLE) : DOUBLE; (* remainder of number/radix
*)
FUNCTION MINIMUM(A, B : DOUBLE) : DOUBLE; (* the minimum of a and b *)
FUNCTION MAXIMUM(A, B : DOUBLE) : DOUBLE; (* the maximum of a and b *)
PROCEDURE Cadd(C, D : Complex;
VAR Result : Complex); (* add two complex numbers *)
PROCEDURE Cconj(A : Complex;
VAR Result : Complex); (* complex conjugate *)
PROCEDURE Cdiv(Num, Denom : Complex;
VAR Result : Complex); (* complex division *)
PROCEDURE Cinv(A : Complex;
VAR Result : Complex); (* complex inverse *)
FUNCTION Cmag(C : Complex) : DOUBLE; (* magnitude of a complex number *)
PROCEDURE Cmake(A, B : DOUBLE;
VAR Result : Complex); (* form a complex number *)
PROCEDURE Cmult(C, D : Complex;
VAR Result : Complex); (* multiply two complex numbers *)
PROCEDURE Csub(C, D : Complex;
VAR Result : Complex); (* subtract D from C complex number
*)
PROCEDURE Cexp(A : Complex;
VAR Result : Complex); (* exponential of a complex number *)
PROCEDURE Csqr(A : Complex;
VAR Result : Complex); (* square of a complex number *)
PROCEDURE Csqrt(A : Complex;
VAR Result : Complex); (* sqrt of a complex number *)
PROCEDURE Cln(A : Complex;
VAR Result : Complex); (* natural log of complex A *)
PROCEDURE CpwrXY(X, Y : Complex;
VAR Result : Complex); (* raise X to the Y power *)
PROCEDURE Csinh(A : Complex;
VAR Result : Complex); (* hyperbolic sine of complex A *)
PROCEDURE Ccosh(A : Complex;
VAR Result : Complex); (* hyperbolic cosine of complex A *)
PROCEDURE Ctanh(A : Complex;
VAR Result : Complex); (* hyperbolic tangent of complex A *)
PROCEDURE Csin(A : Complex;
VAR Result : Complex); (* sine of complex A *)
PROCEDURE Ccos(A : Complex;
VAR Result : Complex); (* cosine of complex A *)
PROCEDURE Ctan(A : Complex;
VAR Result : Complex); (* tangent of complex A *)
PROCEDURE Carcsin(A : Complex;
VAR Result : Complex); (* inverse sine of complex A *)
PROCEDURE Carccos(A : Complex;
VAR Result : Complex); (* inverse cosine of complex A *)
PROCEDURE Carctan(A : Complex;
VAR Result : Complex); (* inverse tangent of complex A *)
PROCEDURE PolyAssign(X : PolyPtr; (* generate new polynomial at Y with *)
VAR Y : PolyPtr); (* same coefficients as poly at X *)
PROCEDURE PolyClear(VAR Ptr : PolyPtr); (* remove a polynomial *)
PROCEDURE PolyEval(X : PolyPtr; (* evaluate polynomial X in S *)
S : Complex; (* at complex value S *)
VAR Result : Complex); (* assign to Result *)
PROCEDURE PolyForm(A : RootStack; (* form a polynomial B from the
roots of rootstack A *)
VAR B : PolyPtr);
PROCEDURE PolyMult(Xx, Yy : PolyPtr;
VAR Z : PolyPtr); (* multiply two polynomials *)
PROCEDURE PolyNegate(X : PolyPtr);
FUNCTION PolyOrder(Z : PolyPtr) : BYTE; (* order of a polynomial *)
PROCEDURE PolyPower(I : BYTE; (* raise a polynomial X to power I *)
X : PolyPtr;
VAR Y : PolyPtr);
PROCEDURE PolyPrint(X : PolyPtr); (* writeln for polynomial *)
PROCEDURE PolyScale(X : PolyPtr; (* multiply polynomial X by *)
Scalar : Complex); (* complex number Scalar *)
PROCEDURE PolyUnary(X : PolyPtr); (* make the polynomial X unary *)
(* i.e. the leading coef = 1 *)
PROCEDURE RootPush(R : Complex; (* add root R to a rootstack L *)
VAR L : RootStack);
PROCEDURE RootPop(VAR L : RootStack; (* get root from a rootstack L *)
VAR R : Complex);
PROCEDURE RootClear(VAR L : RootStack); (* clear a rootstack L *)
PROCEDURE RootRotate(N : BYTE;VAR L : RootStack);(* rotate rootstack L by N *)
(* so that last moves toward 1st *)
PROCEDURE RootCopy(S : RootStack; (* copy a rootstack from S to D *)
VAR D: RootStack);
CONST
Cone : Complex = (Re : 1.0; Im : 0.0);
Czero: Complex = (Re : 0.0; Im : 0.0);
Ci : Complex = (Re : 0.0; Im : 1.0);
IMPLEMENTATION
VAR
Ln10 : DOUBLE;
FUNCTION Floor (X : DOUBLE) : DOUBLE; (* The next lowest integer *)
(* note that INT will not work when X is a negative number *)
BEGIN
IF X >= 0.0 THEN
Floor := Int(X)
ELSE (* Use int for positive x *)
IF Frac(X) = 0.0 THEN
Floor := X
ELSE (* no shift on exact integer *)
Floor := - Int(1 - X) (* Round away from zero *)
END; (* Floor *)
FUNCTION Ceiling (X : DOUBLE) : DOUBLE; (* The next highest integer *)
BEGIN
IF X <= 0.0 THEN
Ceiling := Int(X)
ELSE (* Use int for negative x *)
IF Frac(X) = 0.0 THEN
Ceiling := X
ELSE (* no shift on exact integer *)
Ceiling := 1 - Int(- X) (* Shift x to negative *)
END; (* Ceiling *)
FUNCTION Log10 (X : DOUBLE) : DOUBLE; (* Base 10 log of x *)
BEGIN (* Ln(10) supplied for speed *)
Log10 := Ln(X) / Ln10 (* Easily derived *)
END; (* Log10 *)
FUNCTION Exp10 (X : DOUBLE) : DOUBLE; (* 10 raised to the x power *)
BEGIN (* Ln(10) supplied for speed *)
Exp10 := Exp(X * Ln10) (* easily derived *)
END; (* Exp10 *)
FUNCTION PwrXY (X, Y : DOUBLE) : DOUBLE; (* raise x to the power y *)
BEGIN
IF (Y = 0.0) THEN
PwrXY := 1.0
ELSE
IF (X <= 0.0) AND (Frac(Y) = 0.0) THEN
IF (Frac(Y / 2)) = 0.0 THEN
PwrXY := Exp(Y * Ln(Abs(X)))
ELSE
PwrXY := - Exp(Y * Ln(Abs(X)))
ELSE
PwrXY := Exp(Y * Ln(X));
END; (* PwrXY *)
FUNCTION QDBV (Volts : DOUBLE) : DOUBLE; (* convert from volts to dB *)
BEGIN
QDBV := 20.0 * Log10(Volts)
END; (* QDBV *)
FUNCTION QDBW (Watts : DOUBLE) : DOUBLE; (* convert from watts to dB *)
BEGIN
QDBW := 10.0 * Log10(Watts)
END; (* QDBW *)
FUNCTION QWATTS (DB : DOUBLE) : DOUBLE; (* convert from dB to watts *)
BEGIN
QWATTS := Exp10(DB / 10.0);
END; (* QWATTS *)
FUNCTION QVOLTS (DB : DOUBLE) : DOUBLE; (* convert from dB to volts *)
BEGIN
QVOLTS := Exp10(DB / 20.0);
END; (* QVOLTS *)
FUNCTION SINH (X : DOUBLE) : DOUBLE; (* hyperbolic sine *)
BEGIN
SINH := 0.5 * (Exp(X) - Exp(- X))
END; (* SINH *)
FUNCTION COSH (X : DOUBLE) : DOUBLE; (* hyperbolic cosine *)
BEGIN
COSH := 0.5 * (Exp(X) + Exp(- X))
END; (* COSH *)
FUNCTION TANH (X : DOUBLE) : DOUBLE; (* hyperbolic tangent *)
BEGIN
X := Exp(2.0 * X);
TANH := (X - 1.0) / (X + 1.0)
END; (* TANH *)
FUNCTION ISINH(X : DOUBLE) : DOUBLE; (* arc hyperbolic sine *)
BEGIN
ISINH := Ln(Sqrt(1.0 + X * X) + X)
END; (* ISINH *)
FUNCTION ICOSH (X : DOUBLE) : DOUBLE; (* arc hyperbolic cosine *)
BEGIN
ICOSH := Ln(X + Sqrt(X * X - 1.0))
END; (* ICOSH *)
FUNCTION ITANH (X : DOUBLE) : DOUBLE; (* arc hyperbolic tangent *)
BEGIN
ITANH := Ln((1.0 + X) / (1.0 - X))
END; (* answer returned in radians *)
FUNCTION ARCSIN (X : DOUBLE) : DOUBLE; (* answer returned in radians *)
BEGIN (* answer returned in radians *)
IF X = 1.0 THEN
ARCSIN := Pi / 2.0
ELSE
IF X = - 1.0 THEN
ARCSIN := Pi / - 2.0
ELSE
ARCSIN := Arctan(X / Sqrt(1.0 - Sqr(X)))
END; (* answer returned in radians *)
FUNCTION ARCCOS (X : DOUBLE) : DOUBLE; (* inverse cosine using TP arctan *)
BEGIN (* answer returned in radians *)
IF X = 0.0 THEN
ARCCOS := Pi / 2.0
ELSE
IF X < 0.0 THEN
ARCCOS := Pi - Arctan(Sqrt(1.0 - Sqr(X)) / Abs(X))
ELSE
ARCCOS := Arctan(Sqrt(1.0 - Sqr(X)) / Abs(X))
END; (* ARCCOS *)
FUNCTION ATAN2(X, Y : DOUBLE) : DOUBLE; (* arctan function with quadrant check
X is real axis value or denominator, Y is imaginary axis value or numerator *)
BEGIN (* answer returned in radians *)
IF Y <> 0.0 THEN
IF X <> 0.0 THEN (* point not on an axis *)
IF X > 0.0 THEN (* 1st or 4th quadrant use std arctan *)
ATAN2 := Arctan(Y / X)
ELSE
IF Y > 0.0 THEN (* 2nd quadrant *)
ATAN2 := Pi + Arctan(Y / X)
ELSE
ATAN2 := Arctan(Y / X) - Pi (* 3rd quadrant *)
ELSE (* point on the Y axis *)
IF Y >= 0.0 THEN
ATAN2 := Pi / 2.0 (* positive Y axis *)
ELSE
ATAN2 := - Pi / 2.0 (* negative Y axis *)
ELSE (* point on the X axis *)
IF X >= 0.0 THEN
ATAN2 := 0.0 (* positive X axis *)
ELSE
ATAN2 := - Pi (* negative X axis *)
END; (* ATAN2 *)
FUNCTION TAN (X : DOUBLE) : DOUBLE; (* tangent of X *)
BEGIN
TAN := Sin(X) / Cos(X)
END; (* TAN *)
FUNCTION GAUSS (Mean, StdDev : DOUBLE) : DOUBLE; (* random number *)
VAR
I : BYTE; (* index for loop *)
T : DOUBLE; (* temporary variable *)
BEGIN (* Based on the central limit theorem *)
T := - 6.0; (* maximum deviation is 6 sigma, remove
the mean first *)
FOR I := 1 TO 12 DO
T := T + Random; (* 12 uniform over 0 to 1 *)
GAUSS := Mean + T * StdDev (* adjust mean and standard deviation *)
END; (* GAUSS *)
FUNCTION RESIDUE (Radix, Number : DOUBLE) : DOUBLE; (* remainder of
radix/number *)
(* uses APL residue definition *)
BEGIN
RESIDUE := Number - Radix * Floor(Number / Radix)
END; (* RESIDUE *)
FUNCTION MINIMUM (A, B : DOUBLE) : DOUBLE; (* the minimum of a and b *)
BEGIN
IF A < B THEN
MINIMUM := A
ELSE
MINIMUM := B
END; (* MINIMUM *)
FUNCTION MAXIMUM (A, B : DOUBLE) : DOUBLE; (* the maximum of a and b *)
BEGIN
IF A < B THEN
MAXIMUM := B
ELSE
MAXIMUM := A
END; (* MAXIMUM *)
PROCEDURE Cmult(C, D : Complex;
VAR Result : Complex); (* multiply two complex numbers *)
BEGIN
Result.Re := C.Re * D.Re - C.Im * D.Im; (* real part *)
Result.Im := C.Re * D.Im + C.Im * D.Re; (* imaginary part *)
END;
PROCEDURE Cadd(C, D : Complex;
VAR Result : Complex); (* add two complex numbers *)
BEGIN
Result.Re := C.Re + D.Re; (* real part *)
Result.Im := C.Im + D.Im; (* imaginary part *)
END;
PROCEDURE Csub(C, D : Complex;
VAR Result : Complex); (* subtract D from C complex number
*)
BEGIN
Result.Re := C.Re - D.Re; (* real part *)
Result.Im := C.Im - D.Im; (* imaginary part *)
END;
FUNCTION Cmag (C : Complex) : DOUBLE; (* magnitude of a complex number *)
BEGIN
Cmag := Sqrt(Sqr(C.Re) + Sqr(C.Im));
END;
PROCEDURE Cmake(A, B : DOUBLE;
VAR Result : Complex); (* form a complex number *)
BEGIN
Result.Re := A;
Result.Im := B;
END;
PROCEDURE Cconj(A : Complex;
VAR Result : Complex); (* complex conjugate *)
BEGIN
Result.Re := A.Re;
Result.Im := - A.Im;
END;
PROCEDURE Cexp(A : Complex;
VAR Result : Complex); (* exponential of a complex number *)
VAR
Magnitude : DOUBLE;
BEGIN (* exp(real+j imag)=exp(real)exp(j imag) *)
Magnitude := Exp(A.Re);
Result.Re := Magnitude * Cos(A.Im); (* Eulers equation *)
Result.Im := Magnitude * Sin(A.Im);
END;
PROCEDURE Csqr(A : Complex;
VAR Result : Complex); (* square of a complex number *)
BEGIN (* sqr(real + j imag) *)
Result.Re := Sqr(A.Re) - Sqr(A.Im);
Result.Im := 2.0 * A.Re * A.Im;
END;
PROCEDURE Csqrt(A : Complex;
VAR Result : Complex); (* sqrt of a complex number *)
VAR
Magnitude, Phase : DOUBLE; (* A to be written as mag*exp(j phase) *)
BEGIN (* solve sqrt(mag)*exp(j .5*phase *)
Phase := 0.5 * Atan2(A.Re, A.Im);
Magnitude := Sqrt(Sqrt(Sqr(A.Re) + Sqr(A.Im)));
Result.Re := Magnitude * Cos(Phase); (* Eulers equation *)
Result.Im := Magnitude * Sin(Phase);
END;
PROCEDURE Cln(A : Complex;
VAR Result : Complex); (* natural log of complex A *)
BEGIN (* A to be written as mag*exp(j phase) *)
Result.Re := 0.5 * Ln(Sqr(A.Re) + Sqr(A.Im));
Result.Im := Atan2(A.Re, A.Im);
END;
PROCEDURE CpwrXY(X, Y : Complex;
VAR Result : Complex); (* raise X to the Y power *)
VAR
Temp : Complex;
BEGIN
IF (X.Re = 0.0) AND (X.Im = 0.0) THEN (* avoid taking log of 0 *)
BEGIN
Result.Re := 0.0;
Result.Im := 0.0;
END
ELSE
BEGIN
Cln(X,Temp);
Cmult(Y,Temp,Temp);
Cexp(Temp,Result);
END
END;
PROCEDURE Csinh(A : Complex;
VAR Result : Complex); (* hyperbolic sine of complex A *)
BEGIN
Result.Re := Cos(A.Im) * Sinh(A.Re);
Result.Im := Sin(A.Im) * Cosh(A.Re);
END;
PROCEDURE Ccosh(A : Complex;
VAR Result : Complex); (* hyperbolic cosine of complex A *)
BEGIN
Result.Re := Cos(A.Im) * Cosh(A.Re);
Result.Im := Sin(A.Im) * Sinh(A.Re);
END;
PROCEDURE Ctanh(A : Complex;
VAR Result : Complex); (* hyperbolic tangent of complex A *)
VAR
Denom : DOUBLE;
BEGIN
Denom := Cos(2.0 * A.Im) + Cosh(2.0 * A.Re);
Result.Re := Sinh(2.0 * A.Re) / Denom;
Result.Im := Sin(2.0 * A.Im) / Denom;
END;
PROCEDURE Csin(A : Complex;
VAR Result : Complex); (* sine of complex A *)
BEGIN
Result.Re := Sin(A.Re) * Cosh(A.Im);
Result.Im := Cos(A.Re) * Sinh(A.Im);
END;
PROCEDURE Ccos(A : Complex;
VAR Result : Complex); (* cosine of complex A *)
BEGIN
Result.Re := Cos(A.Re) * Cosh(A.Im);
Result.Im := - Sin(A.Re) * Sinh(A.Im);
END;
PROCEDURE Ctan(A : Complex;
VAR Result : Complex); (* tangent of complex A *)
VAR
Denom : DOUBLE;
BEGIN
Denom := Cos(2.0 * A.Re) + Cosh(2.0 * A.Im);
Result.Re := Sin(2.0 * A.Re) / Denom;
Result.Im := Sinh(2.0 * A.Im) / Denom;
END;
PROCEDURE Cinv(A : Complex;
VAR Result : Complex); (* complex inverse *)
VAR
Scalar : DOUBLE;
BEGIN
Scalar := Sqr(A.Re) + Sqr(A.Im);
Result.Re := A.Re / Scalar;
Result.Im := - A.Im / Scalar;
END;
PROCEDURE Cdiv(Num, Denom : Complex;
VAR Result : Complex); (* complex division *)
(* returns Num/Denom *)
VAR
Scalar : DOUBLE;
BEGIN
(****************************************************************************)
(* try to avoid overflow by normalizing the denominator *)
(****************************************************************************)
IF (Abs(Denom.Re) > Abs(Denom.Im)) THEN
BEGIN
Scalar := Denom.Re;
Denom.Im := - Denom.Im / Scalar;
(* Denom.Re := 1.0; is implied *)
Scalar := (Sqr(Denom.Im) + 1.0) * Scalar;
Result.Re := (Num.Re - Num.Im * Denom.Im) / Scalar;
Result.Im := (Num.Re * Denom.Im + Num.Im) / Scalar;
END
ELSE
BEGIN
Scalar := Denom.Im;
Denom.Re := Denom.Re / Scalar;
(* Denom.Im := -1.0; is implied *)
Scalar := (Sqr(Denom.Re) + 1.0) * Scalar;
Result.Re := (Num.Re * Denom.Re + Num.Im) / Scalar;
Result.Im := (Num.Im * Denom.Re - Num.Re) / Scalar;
END;
END;
PROCEDURE Carcsin(A : Complex;
VAR Result : Complex); (* inverse sine of complex A *)
VAR
Temp : Complex;
BEGIN
Csqr(A, Temp);
Csub(Cone, Temp, Temp);
Csqrt(Temp, Temp);
Cmult(Ci, A, A);
Csub(Temp, A, Temp);
Cln(Temp, Temp);
Cmult(Ci, Temp, Result)
END;
PROCEDURE Carccos(A : Complex;
VAR Result : Complex); (* inverse cosine of complex A *)
VAR
Temp : Complex;
BEGIN
Csqr(A, Temp);
Csub(Temp, Cone, Temp);
Csqrt(Temp, Temp);
Csub(A, Temp, Temp);
Cln(Temp, Temp);
Cmult(Ci, Temp, Result)
END;
PROCEDURE Carctan(A : Complex;
VAR Result : Complex); (* inverse tangent of complex A *)
VAR
Temp : DOUBLE;
BEGIN
Temp := Sqr(A.Re);
Result.Re := 0.5 * Atan2((1.0 - Temp - Sqr(A.Im)),2.0 * A.Re);
Result.Im := 0.25 * Ln((Sqr(1.0 + A.Im) + Temp) / (Sqr(1.0 - A.Im) + Temp));
END;
PROCEDURE PolyClear(VAR Ptr : PolyPtr); (* remove a polynomial *)
VAR
Tempptr : PolyPtr;
BEGIN
WHILE Ptr <> NIL DO (* for all polynomial coefficients *)
BEGIN
Tempptr := Ptr^.Link; (* store link to the next coefficient *)
Dispose(Ptr); (* free memory at current coefficient *)
Ptr := Tempptr; (* go to next coefficient *)
END;
END;
PROCEDURE PolyNext(VAR Ptr : PolyPtr); (* new linked list element *)
BEGIN
New(Ptr); (* get memory space for a coefficient *)
Ptr^.Coeff := Czero; (* set the coefficient to zero *)
Ptr^.Link := NIL; (* next element in the list is
nonexistant *)
END;
FUNCTION PolyOrder (Z : PolyPtr) : BYTE; (* order of a polynomial *)
VAR
OrderCtr : BYTE; (* maximum order is 255 *)
BEGIN
OrderCtr := 0; (* return 0 for polynomial with one
element *)
WHILE Z^.Link <> NIL DO (* last element in list ? *)
BEGIN
Inc(OrderCtr); (* count number of times through loop *)
Z := Z^.Link; (* go to next coefficient *)
END;
PolyOrder := OrderCtr;
END;
PROCEDURE PolyNew(N : BYTE; (* create a zero polynomial of length N>*)
VAR Z : PolyPtr); (* ** Z must be an existing polynomial **)
VAR
I : BYTE; (* maximum order is 255 *)
Ztemp : PolyPtr; (* to move through coefficient list *)
BEGIN
PolyClear(Z); (* free existing polynomial location *)
PolyNext(Z); (* get zeroth coefficient *)
Ztemp := Z; (* Z stays at first element of list *)
FOR I := 1 TO N DO (* add other coefficients to the list *)
BEGIN
PolyNext(Ztemp^.Link);
Ztemp := Ztemp^.Link;
END;
END;
PROCEDURE PolyAssign(X : PolyPtr; (* generate new polynomial at Y with *)
VAR Y : PolyPtr); (* same coefficients as poly at X *)
VAR
I : BYTE; (* length of polynomial X *)
Ytemp, YtStart : PolyPtr; (* to move through the list *)
(* maximum order is 255 *)
BEGIN
IF X <> NIL THEN
BEGIN
I := PolyOrder(X); (* order of X *)
Ytemp := NIL; (* initialize Ytemp *)
PolyNew(I, Ytemp); (* get new poly of same order *)
YtStart := Ytemp; (* remember first element of list *)
WHILE X <> NIL DO (* go through X *)
BEGIN
Ytemp^.Coeff := X^.Coeff; (* assign X coef to Y coef *)
Ytemp := Ytemp^.Link; (* locate next element of Y *)
X := X^.Link; (* locate next element of X *)
END;
PolyClear(Y); (* in case PolyAssign(P1,P1) *)
Y := YtStart;
END
ELSE PolyClear(Y);
END;
PROCEDURE Root_Poly(Root : Complex; (* form polynomial S-Root *)
VAR Result : PolyPtr);
VAR
ResultTemp : PolyPtr; (* to move through two element list *)
BEGIN
PolyNew(1, Result); (* generate two element list *)
ResultTemp := Result; (* keep Result at 1st element of list *)
ResultTemp^.Coeff.Im := - Root.Im; (* zeroth coefficient *)
ResultTemp^.Coeff.Re := - Root.Re;
ResultTemp := ResultTemp^.Link; (* move to S*1 coefficient *)
ResultTemp^.Coeff := Cone; (* set it equal to 1 + j0 *)
END;
PROCEDURE PolyMult(Xx, Yy : PolyPtr;
VAR Z : PolyPtr);
VAR
X, Y, Ypt, Zpt, Zptsave : PolyPtr;
Result : Complex;
I : BYTE; (* maximum order is 255 *)
BEGIN
X := NIL; (* don't give PolyAssign trash *)
Y := NIL; (* don't give PolyAssign trash *)
PolyAssign(Xx, X); (* copy Xx, in case PolyMult(A,A,A) *)
PolyAssign(Yy, Y); (* copy Yy, in case PolyMult(A,A,A) *)
I := PolyOrder(X) + PolyOrder(Y); (* resultant polynomial order *)
PolyClear(Z); (* release existing Z *)
PolyNew(I, Z); (* make a list of length I *)
Zptsave := Z; (* keep Z at start of the list *)
WHILE X <> NIL DO (* for each element of x *)
BEGIN
Zpt := Zptsave; (* remember start of list 2nd loop *)
Ypt := Y; (* remember start of list 2nd loop *)
WHILE Ypt <> NIL DO (* 2nd loop goes over elements of Y *)
BEGIN (* scale Y polynomial by X coeff *)
Cmult(X^.Coeff, Ypt^.Coeff, Result);
Cadd(Result, Zpt^.Coeff, Zpt^.Coeff);
Ypt := Ypt^.Link; (* next element in Y *)
Zpt := Zpt^.Link; (* next element in Z *)
END;
Zptsave := Zptsave^.Link; (* begin at next higher element in Z *)
X := X^.Link; (* by multiplying by next X element *)
END;
PolyClear(X); (* release X storage *)
PolyClear(Y); (* release Y storage *)
END;
PROCEDURE PolyForm(A : RootStack; (* form a polynomial B from the
roots of rootstack A *)
VAR B : PolyPtr);
VAR
Tply : PolyPtr; (* will hold the 1st order polynomial *)
DupRoots : RootStack; (* get a duplicate rootStack *)
Troot : Complex;
BEGIN
PolyClear(B); (* erase B *)
IF A <> NIL THEN
BEGIN
DupRoots := NIL; (* initialize DupRoots *)
RootCopy(A,DupRoots); (* don't destroy the contents of A *)
RootPop(DupRoots,Troot); (* get first root *)
Root_Poly(Troot,B); (* form 1st order poly *)
Tply := NIL; (* initialize Tply *)
WHILE DupRoots <> NIL DO (* for other each root *)
BEGIN
RootPop(DupRoots,Troot);
Root_Poly(Troot,Tply); (* form 1st order poly *)
PolyMult(Tply,B,B); (* multiply by current B *)
END;
PolyClear(Tply); (* free temporary polynomial *)
RootClear(DupRoots); (* free temporary rootlist *)
END;
END;
PROCEDURE PolyPrint(X : PolyPtr);
BEGIN
WHILE X <> NIL DO
BEGIN
Writeln(X^.Coeff.Re, X^.Coeff.Im);
X := X^.Link;
END;
END;
PROCEDURE PolyPower(I : BYTE; (* raise a polynomial X to power I *)
X : PolyPtr;
VAR Y : PolyPtr); (* assign to polynomial Y *)
VAR
N : BYTE;
Xtemp : PolyPtr;
BEGIN
IF I = 0 THEN (* expression to the 0 power is 1 *)
BEGIN
PolyClear(Y);
PolyNext(Y);
Y^.Coeff.Re := 1.0;
END
ELSE (* not 0 power *)
BEGIN
Xtemp := NIL; (* initialize Xtemp *)
PolyAssign(X, Xtemp); (* in case called PolyPwr(3,A,A) *)
PolyAssign(Xtemp, Y); (* first power *)
N := 1;
WHILE N < I DO (* continuing powers *)
BEGIN
PolyMult(Xtemp, Y, Y); (* multiply by X *)
INC(N); (* current power *)
END; (* WHILE *)
PolyClear(Xtemp);
END (* IF *)
END;
PROCEDURE PolyEval(X : PolyPtr; (* evaluate polynomial X in S *)
S : Complex; (* at complex value S *)
VAR Result : Complex); (* assign to Result *)
VAR
Tempr, Temps : Complex;
BEGIN
Temps := S; (* in generating powers of S *)
IF X <> NIL THEN (* any coefficients in X *)
BEGIN
Result := X^.Coeff; (* add the constant of the polynomial *)
X := X^.Link; (* go to S*1 coefficient *)
WHILE X <> NIL DO (* continue for each coefficient *)
BEGIN
Cmult(X^.Coeff, Temps, Tempr); (* multiply by S*n *)
Cadd(Result, Tempr, Result); (* add to running sum *)
Cmult(S, Temps, Temps); (* form S*(n+1) *)
X := X^.Link; (* next order *)
END; (* while *)
END;
END;
PROCEDURE PolyAdd(X, Y : PolyPtr; (* add polynomials X and Y *)
VAR Z : PolyPtr); (* assign to polynomial Z *)
VAR
Xtemp, Ytemp, Tptr1, Tptr2, Tptr3 : PolyPtr;
BEGIN
Xtemp := NIL; (* Initialize undefined polynomials *)
Ytemp := NIL;
PolyAssign(X, Xtemp); (* temporary working polynomials *)
PolyAssign(Y, Ytemp);
PolyClear(Z); (* in case of PolyAdd(P1,P2,P2) *)
IF PolyOrder(Xtemp) > PolyOrder(Ytemp) THEN (* want to add the smaller to
larger *)
BEGIN (* Z will be same order of the larger *)
Tptr1 := Xtemp;
Tptr2 := Ytemp;
END
ELSE
BEGIN
Tptr1 := Ytemp;
Tptr2 := Xtemp;
END;
PolyAssign(Tptr1, Z); (* Z is 0 + the larger *)
Tptr3 := Z; (* keep Z at start of polynomial *)
WHILE Tptr2 <> NIL DO (* for each coeff of the smaller *)
BEGIN
Cadd(Tptr3^.Coeff, Tptr2^.Coeff, Tptr3^.Coeff); (* Z + smaller *)
Tptr3 := Tptr3^.Link; (* next Z coef *)
Tptr2 := Tptr2^.Link; (* next smaller coef *)
END;
PolyClear(Xtemp); (* free Xtemp and Ytemp storage *)
PolyClear(Ytemp);
END;
PROCEDURE PolyNegate(X : PolyPtr); (* change poly in S to poly in -S *)
VAR
Temp : Complex; (* to be 1+j0 or -1+j0 *)
BEGIN
Temp := Cone; (* initially 1+j0 *)
WHILE X <> NIL DO (* for each coefficient *)
BEGIN
Cmult(X^.Coeff, Temp, X^.Coeff); (* multiply by 1 or -1 *)
Temp.Re := - Temp.Re; (* change 1 to -1 or -1 to 1 *)
X := X^.Link; (* next coefficient *)
END;
END;
PROCEDURE PolyScale(X : PolyPtr; (* multiply polynomial X by *)
Scalar : Complex); (* complex number Scalar *)
BEGIN
WHILE X <> NIL DO (* go through each element of X *)
BEGIN
Cmult(Scalar, X^.Coeff, X^.Coeff); (* scale the coefficient *)
X := X^.Link; (* locate next element of X *)
END;
END;
PROCEDURE PolyUnary(X : PolyPtr); (* make the polynomial X unary *)
(* i.e. the leading coef = 1 *)
VAR
Xtemp : PolyPtr;
Scalar : Complex;
BEGIN
Xtemp := X; (* remember the start of the list *)
WHILE X <> NIL DO (* go through each element of X *)
BEGIN (* to locate last element *)
Scalar := X^.Coeff; (* looking for the last coefficient *)
X := X^.Link; (* locate next element of X *)
END; (* while *)
Cinv(Scalar, Scalar); (* inverse of last element of X *)
PolyScale(Xtemp, Scalar); (* will make last element = 1.0 *)
END;
PROCEDURE PolyDivide(Num, Denom : PolyPtr; (* Synthetic division *)
VAR Quotient, Remainder: PolyPtr);
VAR
TempN, TempD, TempQ, TempR : PolyPtr;
OrderNum, OrderDenom, OrderQuo : BYTE;
LeadingCoef, LeadingCoefD : Complex;
BEGIN
OrderNum := PolyOrder(Num);
OrderDenom := PolyOrder(Denom);
IF OrderNum > OrderDenom THEN
BEGIN
TempN := NIL; (* initialize temporary numerator *)
TempD := NIL; (* initialize temporary denominator *)
PolyAssign(Num,TempN); (* in case PolyDivide(A,B,A,B) *)
PolyAssign(Denom,TempD); (* in case PolyDivide(A,B,A,B) *)
WHILE TempN <> NIL DO (* find the leading coef of the num *)
BEGIN
LeadingCoef := TempN^.Coeff;
TempN := TempN^.Link;
END;
WHILE TempD <> NIL DO (* find the leading coef of the denom *)
BEGIN
LeadingCoefD:= TempD^.Coeff;
TempD := TempD^.Link;
END;
Cdiv(LeadingCoef,LeadingCoefD,LeadingCoef); (* quotient leading coef *)
TempQ := NIL; (* initialize temporary quotient *)
PolyClear(Quotient);
PolyNew((OrderNum-OrderDenom),Quotient);
TempR := NIL; (* initialize temporary remainder *)
PolyClear(Quotient);
PolyClear(Remainder);
END
ELSE (* denominator cannot divide into numerator *)
BEGIN
PolyAssign(Num,Remainder);
PolyClear(Quotient);
END;
END;
PROCEDURE RootPush(R : Complex; (* add root R to a rootstack L *)
VAR L : RootStack);
VAR
NewSpace : RootStack;
BEGIN
New(NewSpace); (* get memory space for new root *)
NewSpace^.Coeff := R; (* set the coefficient to R *)
NewSpace^.Link := L; (* next element in the list is L *)
L := NewSpace; (* new top of stack *)
END;
PROCEDURE RootPop(VAR L : RootStack; (* get root from a rootstack L *)
VAR R : Complex);
VAR
Ltemp : RootStack;
BEGIN
IF L <> NIL THEN
BEGIN
R := L^.Coeff; (* assign R from first stack element *)
Ltemp := L; (* remember top stack element location *)
L := L^.Link; (* move L to second member of stack *)
Dispose(Ltemp); (* free memory at old top of stack *)
END;
END;
PROCEDURE RootClear(VAR L : RootStack); (* clear a rootstack L *)
VAR
Dummy : Complex;
BEGIN
WHILE L <> NIL DO RootPop(L,Dummy); (* pop until empty *)
END;
PROCEDURE RootRotate(N : BYTE;VAR L : RootStack);(* rotate rootstack L by N *)
(* so that last moves toward 1st *)
VAR
MarkTop, Temp : RootStack;
Count : Byte;
BEGIN
IF (L <> NIL) AND (N <> 0) THEN
BEGIN (* make the stack a ring *)
MarkTop := L; (* link to top of L *)
While L <> NIL DO (* search to the end of the list *)
Begin
Temp := L; (* Previous element *)
L := L^.Link;
END;
Temp^.Link := MarkTop; (* wrap the last element to the first *)
Temp := MarkTop; (* move temp back to top of the list *)
(* in the following we locate the bottom of the list which is currently *)
(* linked to the first element of the list. Set the link at the bottom to *)
(* NIL, and its link (being the top) to L *)
FOR Count := 1 to N DO (* will locate bottom of list *)
Temp := Temp^.Link;
L := Temp^.Link; (* pointer to the top of list *)
Temp^.Link := NIL; (* split the ring *)
END;
END;
PROCEDURE RootCopy(S : RootStack; (* copy a rootstack from S to D *)
VAR D: RootStack);
VAR
Dtemp, DtempPrev : RootStack;
BEGIN
If S <> D THEN (* if = then exit *)
BEGIN
IF D <> NIL THEN RootClear(D); (* clear existing stack *)
IF S <> NIL THEN
BEGIN
New(Dtemp); (* first element *)
D := Dtemp; (* is at top of new stack *)
D^.Coeff := S^.Coeff; (* copy the first root *)
D^.Link := NIL; (* don't know if another element *)
S := S^.Link; (* move to second coeff *)
While S <> NIL DO
BEGIN
writeln('rootcopy');
DtempPrev := Dtemp;
New(Dtemp);
Dtemp^.Coeff := S^.Coeff; (* copy the root *)
DtempPrev^.Link := Dtemp; (* tie to previous stack element *)
Dtemp^.Link := NIL;
S := S^.Link;
END; (* while *)
END; (* if *)
END; (* if *)
END; (* RootCopy *)
BEGIN
Randomize;
Ln10 := Ln(10.0)
END; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.