text stringlengths 14 6.51M |
|---|
{13. La tienda de libros Amazon Books está analizando información de algunas editoriales.
Para elloAmazon cuenta con una tabla con las 35 áreas temáticas utilizadas para clasificar los libros (Arte y Cultura,
Historia, Literatura, etc.).
De cada libro se conoce:
su título,
nombre de la editorial,
cantidad de páginas,
año de edición,
cantidad de veces que fue vendido
y código del área temática (1..35).
Realizar un programa que:
A) Invoque a un módulo que lea la información de los libros hasta ingresar el título “Relato de un
náufrago” (que debe procesarse) .
y devuelva en una estructura de datos adecuada para la editorial “Planeta Libros”, con la siguiente información:
- Nombre de la editorial
- Año de edición del libro más antiguo
- Cantidad de libros editados
- Cantidad total de ventas entre todos los libros
- Detalle con título, nombre del área temática y cantidad de páginas de todos los libros con
más de 250 ventas.
B) Invoque a un módulo que reciba la estructura generada en A) e imprima el nombre de la editorial
y el título de cada libro con más de 250 ventas.}
program ejercicios;
const
dimf=35;
type
rango=1..dimf;
str=string[40];
vector =array [rango] of string[20];
detalle=record
titulo_data:str;
nombre_area_tematica:str;
cant_paginas_mas_250_ventas: integer;
end;
lista=^nodo;
nodo=record
elem:detalle;
sig:lista;
end;
libro=record // libros que se leen.
titulo:str;
nombre_editorial:str;
cant_paginas:integer;
anio_edicion:integer;
cant_vendido:integer;
tematic:rango;
end;
editorial=record
nombre_editorial:str;
anio_libro_mas_antiguo: integer;
cant_libros_editados:integer;
total_ventas:integer;
lista_deta: lista ;
end;
//procesos//
procedure leerLibro (var l:libro);
begin
readln (l.titulo);
//if (l.titulo <> 'Relato de un náufrago') then begin
readln (l.nombre_editorial);
readln(l.ant_paginas);
readln(l.anio_edicion);
readln(l.cant_vendido);
readln(l.tematic);
//end;
end;
procedure actualizarMinimo (anio:integer; var min:integer);
begin
if anio < min then
min:=aniol;
end;
end;
procedure agregarAdelante (var lis:lista; l:libro; v:vector)
var
aux:lista;
begin
new(aux);
aux^.detalle.titulo_data:=l.titulo;
aux^.detalle.nombre_area_tematica:=v[l.tematic];
aux^.detalle.cant_paginas_mas_250_ventas:=l.cant_paginas;
aux^.sig:=lis;
lis:=aux;
end;
detalle=record
titulo_data:str;
nombre_area_tematica:str;
cant_paginas_mas_250_ventas: integer;
end;
procedure leerEditorial(var e:editorial; v:vector);
var
l:libro
lis:lista
anio_minimo:integer;
suma:integer;
cant:integer;
begin
lis:=nil
anio_minimo:=9999;
suma:=0;
cant:=0;
repeat
leerLibro (l);
if(l.editorial = 'Planeta Libros')then begin
actualizarMinimo(l.anio_edicion,anio_minimo);
cant:=cant+1;
suma:=suma+l.cant_vendido;
if (l.cant_vendido > 250) then
agregarAdelante(lis,l,v);
end;
until (l.titulo = 'Relato de un náufrago')
e.anio_libro_mas_antiguo := anio_minimo;
e.nombre_editorial:=l.nombre_editorial;
e.cant_libros_editados:=cant;
e.total_ventas:=suma;
e.lista_deta:=lis;
end;
procedure imprimirRegistro(r:detalle)
begin
writeln(r.titulo_data);
//falta imprimir nombre de la editorial
//writeln(r.nombre_area_tematica);
//writeln(r.cant_paginas_mas_250_ventas);
end;
procedure imprimirLista (l:lista);
begin
while l <> nil do begin
imprimirRegistro(l^.elem);
l:=l^.sig;
end;
end;
var
v:vector;
e:editorial;
begin
leerEditorial(e,v);
imprimirLista(e.lista_deta);
end.
{
14. La biblioteca de la Universidad Nacional de La Plata necesita un programa para administrar
información de préstamos de libros efectuados en marzo de 2020. Para ello, se debe leer la información
de los préstamos realizados. De cada préstamo se lee: nro. de préstamo, ISBN del libro prestado, nro. de
socio al que se prestó el libro, día del préstamo (1..31). La información de los préstamos se lee de manera
ordenada por ISBN y finaliza cuando se ingresa el ISBN -1 (que no debe procesarse).
Se pide:
A) Generar una estructura que contenga, para cada ISBN de libro, la cantidad de veces que fue prestado.
Esta estructura debe quedar ordenada por ISBN de libro.
B) Calcular e informar el día del mes en que se realizaron menos préstamos.
C) Calcular e informar el porcentaje de préstamos que poseen nro. de préstamo impar y nro. de socio
par
}
program: ej1;
const
dimF = 31;
type
dias = 1..dimF;
vectorContador = array [dias] of integer;
prestamos = record
prestamo:integer;
isbn:integer;
socio:integer;
dia:dias;
end;
libro = record
isbn:integer;
cant_prestamos:integer;
end;
lista = ^nodo
dato:libro;
sig:lista;
end;
procedure inicializarVector (var v:vector);
var
i:integer;
begin
for i:=1 to dimF do
v[i]:=0;
end;
procedure leer (var p:prestamos);
begin
readln(p.isbn)
if p.isbn <> -1 then begin
readln(p.prestamo);
readln(p.socio);
readln(p.dia);
end;
procedure agregarAdelante (var l:lista; prestamos:integer; act:integer);
var
nue:lista;
begin
new(nue);
nue^.dato.isbn:=act;
nue^.dato.cant_prestamos:=prestamos;
nue^.sig:=l;
l:=nue;
end;
procedure minimo (v:vector);
var
min,i:integer;
dia:dias;
begin
min:=9999;
dia:=-1;
for i:=1 to dimF do begin
if v[i] < min then begin
min := v[i]
dia := i;
end;
end;
writeln (dia);
end;
function cumple (prestamo:integer; socio:integer) : boolean;
var
ok:boolean;
begin
ok:=false
if (prestamo mod 2 <> 0) and (socio mod 2 = 0) then
ok:=true;
cumple:=ok
end;
procesarInformacion (var l:lista; var v:vector);
var
p:prestamos;
act:integer;
cant_prestamos,totalPrestamos,nroImparPrestamoPar:integer;
begin
totalPrestamos:=0;
nroImparPrestamoPar:=0;
leer(p);
while (p.isbn <> -1) do begin
act:=isbn
cant_prestamos:=0
while (p.isbn <> -1) and (act = isbn)do begin
totalPrestamos:=Totalprestamos+1;
if cumple (p.prestamo,p.socio) then
nroImparPrestamoPar:=nroImparPrestamoPar+1
cant_prestamos:=cant_prestamos+1
v[p.dia]:=v[p.dia]+1
leer (p)
end;
agregarAdelante(l,cant_prestamos,act)
end;
minimo (v);
writeln((nroImparPrestamoPar/totalPrestamos)*100:2:2);
end;
var
l:lista; v:vectorContador
begin
l=:nil;
inicializarVector(v);
procesarInformacion(l,v);
end.
{
Evaluación Parcial (2/3/2021)
La Asociación Internacional de Tenis administra la información de sus asociados y necesita disponer de un programa
modularizado que:
A) Lea y almacene la información de los asociados. De cada asociado se conoce: Nro Socio, Apellido, nombre,
categoría (A, B, C, D o E),
monto básico, montos de los premios obtenidos (a lo sumo 10) y fecha de ingreso a la Asociación. La lectura
de la información se lee ordenada
por Nro de socio (de menor a mayor) y finaliza cuando se lee el Nro de Socio -1. La lectura de los montos
de los premios para cada asociado
finaliza al leer monto -1. La información debe quedar ordenada por Nro de socio (de menor a mayor).
B) Una vez leída y almacenada la información:
a. Obtener una lista de “Pagos” con DNI del asociado y pago total al asociado. El pago total se calcula de la
siguiente manera:
- ASOCIADO Categoría A, C, E Monto básico + premios.
- ASOCIADO Categoría B, D Se adiciona, al monto básico + premios, $2000 por cada año de asociado.
b. Informar para cada categoría la cantidad de asociados que cuenta.
c. Eliminar de la lista de “Pagos” el asociado con un Nro de Socio que se lee de teclado, de ser posible.
}
program parcial;
const
dimF = 10;
type
str = string [20];
cat = 'A'..'E';
rangoPremio = 1..dimF;
Tdia = 1..31;
Tmes = 1..12;
vectorPremios = array [rangoPremio] of real;
fecha = record
dia: Tdia;
mes: Tmes;
anio:integer;
end;
asociados = record
num:integer;
apellido:str;
nombre:str;
categoria:cat;
basico:real;
premios:vectorPremios;
ingreso:fecha;
dimL:integer;
end;
listaA = ^nodo;
nodo = record
dato:asociado;
sig:listaA;
end;
pagos = record
dni:integer;
total:real;
end;
listaP = ^elem;
elem = record
info:pagos;
sig:listaP;
end;
vectorContador = array [cat] of integer;
procedure inicializarContador (var vc:vectorContador);
var
i:char;
begin
for i:='a' to 'e' do
v[i]:= 0;
end;
procedure leerFecha (var f:fecha);
begin
readln(f.dia);
readln(f.mes);
readln(f.anio);
end;
procedure leerVectorP (var v:premios;var dimL:integer);
var
monto:real;
begin
realn (monto);
while (dimL < dimF) and (monto <> -1) do begin
dimL:=dimL+1;
v[dimL]:=monto;
readln(monto);
end;
end;
procedure leerAsociado (var a:asociado);
begin
realn(a.num);
if num <> -1 then begin
readln(a.apellido);
readln(a.nombre);
readln(a.categoria);
readln(a.basico);
dimL:=0;
leerVectorP(a.premios,a.dimL);
leerFecha(a.fecha);
end;
procedure agregarAtras (var la:listaA;var ult:ListaA a:asociado);
var
nue:listaA;
begin
new(nue);
nue^.dato:=a;
nue^.sig:=nil;
if(l=nil)then begin
l:=nue;
else
ult^.sig:= nue;
end;
ult:= nue;
end;
end;
procedure cargarListaA ( var la:listaA );
var
a:asociado;
ult:listaA;
begin
ult:=nil;
leerAsociado (a);
while (a.num <> -1) do begin
agregarAtras (la,ult,a);
leerAsociado (a);
end;
end;
function totalVector (v:premios; dimL:integer): real;
var
i:integer;
total:real;
begin
for i:=1 to dimL do
total := total+v[i];
totalVector := total;
end;
procedure agregarLista (var lp:listaP; dni:integer; total:real;)
var
nue:listaP;
begin
new(nue);
nue^.data.dni:=dni
nue^.data.total:=total;
nue^.sig:=lp;
lp:=nue;
end;
procedure cargarVectorContador (var vc:vectorContador;categoria:cat);
begin
vc[categoria]:= vc[categoria] + 1
end;
procedure imprimirVector (vc:vectorContador);
var
i:char;
begin
for i:= 'a' to 'e' do
writeln(vc[i]);
end;
procedure procesarInformacion (var lp:listaP; la:listaA; var vc:vectorContador);
var
total:real;
begin
while (la <> nil) do begin
total:=0
if ((la^.dato.cat = 'a')or (la^.dato.cat = 'c') or (la^.dato.cat = 'e')) then
total = la^.dato.monto + totalVector (la^.dato.premio,la^.dato.dimL);
else
total = la^.dato.monto + totalVector (la^.dato.premio,la^.dato.dimL) + (2000*la^.dato.fecha.anio)
agregarlista (lp,la^.dato.dni,total);
cargarVectorContador (vc,la^.dato.categoria)
la:=la^.sig;
end;
imprimirVector (vc);
end;
function buscarOrdenado(la:listaA; nro:integer):integer;
begin
while (la <> nil) and (la^.dato.num < nro)
la:=la^.sig
if (la <> nil) and (la^.dato.num = nro)
buscarOrdenado:= la^.dato.dni
else
buscarOrdenado:=-1
end;
procedure eliminar (var lp:listaP; dni:integer);
var
ant,act:listaP;
begin
act:=lp;
ant:=lp;
while (act <> nil) and (act^.data.dni <> dni) do begin
ant:=act
act:=act^.sig;
end;
if (act <> nil) then begin
if (act = lp) then
lp:=lp^.sig;
else
ant^.sig:=act^.sig;
dispose (act);
end;
end;
procedure eliminar (var lp:listaP; nro:integer,la:listaA);
var
dni:integer;
begin
dni:=buscarOrdenado(la,nro);
if (dni <> -1) then
eliminar(lp,dni);
writeln ('se elimino el usuario con numero: ',nro);
else
writeln ('no se encontro');
end;
//pp
var
vc:vectorContador;
lp:listaP;
la:listaA;
nro:integer
begin
la=nil;
lp=nil;
inicializarContador (vc);
CargarListaA (la);
ProcesarDatos (lp,la,vc);
readln (nro);
eliminar(lp,nro,la);
end.
{
read(monto)
while(dimL<dimF) and (monto <>-1)
dimL:=diml+1;
vectorMontos[dimL]:=monto
read(monto)
end;
}
///CASOS RAROS DE ACCESOS A ESTRUCTURAS
alumno=record
nombre:string[10]
lista^=nodo
nodo = record
dato: alumno
sig
vector_numeros = array[1..10] of lista;
v[1]^.dato.nombre:='juanito';
dir = record
localidad: stirng[20];
numeroLaCsa:vector_alumnos;
end;
persona = record
direccion: dir;
end;
lista de personas
p:persona
p.direccion.localidad:='city bell';
l^.dato.direccion.numeroLaCsa[1]:=190;
lp^.dato.direccion.numeroLaCsa[1]^.dato.nombre:='pedrito';
//---------------------------------------------------------------
lista_montos=^nodo1;
nodo1 = record
dato: integer;
sig: lista_montos;
end;
obra = record
nombre_obra:String[20];
montos: lista_montos;
end;
vector_obras = array [1..100] of obra;
persona=record
nombre:string[20];
obrasSociales: vector_obras;
end;
lista=^nodo;
nodo = record
dato:persona
sig:lista;
end;
var
l: lista;
//si quiero imprimir un monto de una obra social teniendo la lista de personas por ejemplo:
writeln(l^.dato.obrasSociales[1].montos^.dato)
//si le quiero cambiar el nombre a la obra social
l^.dato.obrasSociales[8].nombre_obra:='un nombre';
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.objects.utils;
interface
uses
Classes,
SysUtils,
Rtti,
DB,
TypInfo,
Math,
StrUtils,
Types,
Variants,
Generics.Collections,
/// orm
dbcbr.mapping.attributes,
dbcbr.mapping.classes,
dbcbr.types.mapping;
type
IRttiSingleton = interface
['{AF40524E-2027-46C3-AAAE-5F4267689CD8}']
function GetRttiType(AClass: TClass): TRttiType;
function RunValidade(AObject: TObject): Boolean;
function Clone(AObject: TObject): TObject;
function CreateObject(ARttiType: TRttiType): TObject;
procedure CopyObject(ASourceObject, ATargetObject: TObject);
end;
TRttiSingleton = class(TInterfacedObject, IRttiSingleton)
private
class var FInstance: IRttiSingleton;
private
FContext: TRttiContext;
constructor CreatePrivate;
protected
constructor Create;
public
{ Public declarations }
destructor Destroy; override;
class function GetInstance: IRttiSingleton;
function GetRttiType(AClass: TClass): TRttiType;
function RunValidade(AObject: TObject): Boolean;
function Clone(AObject: TObject): TObject;
function CreateObject(ARttiType: TRttiType): TObject;
procedure CopyObject(ASourceObject, ATargetObject: TObject);
end;
implementation
uses
dbcbr.mapping.explorer,
dbcbr.rtti.helper,
ormbr.objects.helper;
{ TRttiSingleton }
constructor TRttiSingleton.Create;
begin
raise Exception.Create('Para usar o IRttiSingleton use o método TRttiSingleton.GetInstance()');
end;
constructor TRttiSingleton.CreatePrivate;
begin
inherited;
FContext := TRttiContext.Create;
end;
destructor TRttiSingleton.Destroy;
begin
FContext.Free;
inherited;
end;
function TRttiSingleton.Clone(AObject: TObject): TObject;
var
LRttiType: TRttiType;
LProperty: TRttiProperty;
LCloned: TObject;
LValue: TObject;
LSourceStream: TStream;
LSavedPosition: Int64;
LTargetStream: TStream;
LSourceObject: TObject;
LTargetObject: TObject;
LTargetList: TObjectList<TObject>;
LSourceList: TObjectList<TObject>;
LFor: Integer;
begin
Result := nil;
if not Assigned(AObject) then
Exit;
LRttiType := FContext.GetType(AObject.ClassType);
LCloned := CreateObject(LRttiType);
for LProperty in LRttiType.GetProperties do
begin
if not LProperty.PropertyType.IsInstance then
begin
if LProperty.IsWritable then
LProperty.SetValue(LCloned, LProperty.GetValue(AObject));
end
else
begin
LValue := LProperty.GetNullableValue(AObject).AsObject;
if LValue is TStream then
begin
LSourceStream := TStream(LValue);
LSavedPosition := LSourceStream.Position;
LSourceStream.Position := 0;
if LProperty.GetValue(LCloned).AsType<Variant> = Null then
begin
LTargetStream := TMemoryStream.Create;
LProperty.SetValue(LCloned, LTargetStream);
end
else
LTargetStream := LProperty.GetValue(LCloned).AsObject as TStream;
LTargetStream.Position := 0;
LTargetStream.CopyFrom(LSourceStream, LSourceStream.Size);
LTargetStream.Position := LSavedPosition;
LSourceStream.Position := LSavedPosition;
end
else
if LProperty.IsList then
begin
LSourceList := TObjectList<TObject>(LValue);
if LProperty.GetValue(LCloned).AsType<Variant> = Null then
begin
LTargetList := TObjectList<TObject>.Create;
LProperty.SetValue(LCloned, LTargetList);
end
else
LTargetList := TObjectList<TObject>(LProperty.GetValue(LCloned).AsObject);
for LFor := 0 to LSourceList.Count - 1 do
LTargetList.Add(Clone(LSourceList[LFor]));
end
else
begin
LSourceObject := LValue;
if LProperty.GetValue(LCloned).AsType<Variant> = Null then
begin
LTargetObject := Clone(LSourceObject);
LProperty.SetValue(LCloned, LTargetObject);
end
else
begin
LTargetObject := LProperty.GetValue(LCloned).AsObject;
CopyObject(LSourceObject, LTargetObject);
end;
LProperty.SetValue(LCloned, LTargetObject);
end;
end;
end;
Result := LCloned;
end;
procedure TRttiSingleton.CopyObject(ASourceObject, ATargetObject: TObject);
var
LRttiType: TRttiType;
LProperty: TRttiProperty;
LCloned: TObject;
LValue: TObject;
LSourceStream: TStream;
LSavedPosition: Int64;
LTargetStream: TStream;
LSourceObject: TObject;
LTargetObject: TObject;
LTargetList: TObjectList<TObject>;
LSourceList: TObjectList<TObject>;
LFor: Integer;
begin
if not Assigned(ATargetObject) then
Exit;
LRttiType := FContext.GetType(ASourceObject.ClassType);
LCloned := ATargetObject;
for LProperty in LRttiType.GetProperties do
begin
if not LProperty.PropertyType.IsInstance then
begin
if LProperty.IsWritable then
LProperty.SetValue(LCloned, LProperty.GetValue(ASourceObject));
end
else
begin
LValue := LProperty.GetValue(ASourceObject).AsObject;
if LValue is TStream then
begin
LSourceStream := TStream(LValue);
LSavedPosition := LSourceStream.Position;
LSourceStream.Position := 0;
if LProperty.GetValue(LCloned).AsType<Variant> = Null then
begin
LTargetStream := TMemoryStream.Create;
LProperty.SetValue(LCloned, LTargetStream);
end
else
LTargetStream := LProperty.GetValue(LCloned).AsObject as TStream;
LTargetStream.Position := 0;
LTargetStream.CopyFrom(LSourceStream, LSourceStream.Size);
LTargetStream.Position := LSavedPosition;
LSourceStream.Position := LSavedPosition;
end
else
if LProperty.IsList then
begin
LSourceList := TObjectList<TObject>(LValue);
if LProperty.GetValue(LCloned).AsType<Variant> = Null then
begin
LTargetList := TObjectList<TObject>.Create;
LProperty.SetValue(LCloned, LTargetList);
end
else
LTargetList := TObjectList<TObject>(LProperty.GetValue(LCloned).AsObject);
for LFor := 0 to LSourceList.Count - 1 do
LTargetList.Add(Clone(LSourceList[LFor]));
end
else
begin
LSourceObject := LValue;
if LProperty.GetValue(LCloned).AsType<Variant> = Null then
begin
LTargetObject := Clone(LSourceObject);
LProperty.SetValue(LCloned, LTargetObject);
end
else
begin
LTargetObject := LProperty.GetValue(LCloned).AsObject;
CopyObject(LSourceObject, LTargetObject);
end;
end;
end;
end;
end;
function TRttiSingleton.CreateObject(ARttiType: TRttiType): TObject;
var
Method: TRttiMethod;
metaClass: TClass;
begin
{ First solution, clear and slow }
metaClass := nil;
Method := nil;
for Method in ARttiType.GetMethods do
begin
if not (Method.HasExtendedInfo and Method.IsConstructor) then
Continue;
if Length(Method.GetParameters) > 0 then
Continue;
metaClass := ARttiType.AsInstance.MetaclassType;
Break;
end;
if Assigned(metaClass) then
Result := Method.Invoke(metaClass, []).AsObject
else
raise Exception.Create('Cannot find a propert constructor for ' + ARttiType.ToString);
end;
function TRttiSingleton.GetRttiType(AClass: TClass): TRttiType;
begin
Result := FContext.GetType(AClass);
end;
class function TRttiSingleton.GetInstance: IRttiSingleton;
begin
if not Assigned(FInstance) then
FInstance := TRttiSingleton.CreatePrivate;
Result := FInstance;
end;
function TRttiSingleton.RunValidade(AObject: TObject): Boolean;
var
LColumn: TColumnMapping;
LColumns: TColumnMappingList;
LAttribute: TCustomAttribute;
begin
Result := False;
LColumns := TMappingExplorer.GetMappingColumn(AObject.ClassType);
for LColumn in LColumns do
begin
// Valida se o valor é NULO
LAttribute := LColumn.ColumnProperty.GetNotNullConstraint;
if LAttribute <> nil then
NotNullConstraint(LAttribute)
.Validate(LColumn.ColumnDictionary.ConstraintErrorMessage,
LColumn.ColumnProperty.GetNullableValue(AObject));
// Valida se o valor é menor que ZERO
LAttribute := LColumn.ColumnProperty.GetMinimumValueConstraint;
if LAttribute <> nil then
MinimumValueConstraint(LAttribute)
.Validate(LColumn.ColumnDictionary.ConstraintErrorMessage,
LColumn.ColumnProperty.GetNullableValue(AObject));
// Valida se o valor é menor que ZERO
LAttribute := LColumn.ColumnProperty.GetMaximumValueConstraint;
if LAttribute <> nil then
MaximumValueConstraint(LAttribute)
.Validate(LColumn.ColumnDictionary.ConstraintErrorMessage,
LColumn.ColumnProperty.GetNullableValue(AObject));
// Valida se o valor é vazio
LAttribute := LColumn.ColumnProperty.GetNotEmptyConstraint;
if LAttribute <> nil then
NotEmpty(LAttribute)
.Validate(LColumn.ColumnProperty, AObject);
// Valida se o tamanho da String é válido
LAttribute := LColumn.ColumnProperty.GetSizeConstraint;
if LAttribute <> nil then
Size(LAttribute)
.Validate(LColumn.ColumnProperty, AObject);
end;
Result := True;
end;
end.
|
unit uNetMap;
interface
uses uInterfaces, WinInet, SysUtils, Variants, uModule, uOSMCommon, uMap, uXML;
implementation
uses StrUtils;
const
netMapClassGUID: TGUID = '{A3BB0528-D4AB-493E-A6E3-6B229EBD65F6}';
httpStorageClassGUID: TGUID = '{1C648623-9D76-47AB-88EF-B7000735DC6A}';
type
{$WARNINGS OFF}
THTTPResponce = class(TOSManObject, IHTTPResponce)
protected
fState, fStatus: integer;
fConn, fAddHandle: HInternet;
fReadBuf: array of byte;
fReadBufSize: integer;
procedure grow(const delta: cardinal);
public
constructor create(); override;
destructor destroy(); override;
procedure setStates(const aState, aStatus: integer);
procedure setConnection(const hConnection, hAddHandle: HInternet);
published
//get state of operation.
// 0 - waiting for connect
// 1 - connected
// 2 - sending data to server
// 3 - receiving data from server
// 4 - transfer complete. Success/fail determined by getStatus() call.
function getState(): integer;
//get HTTP-status. It implemented as follows:
// 1.If connection broken or not established in state < 3 then status '503 Service Unavailable' set;
// 2.If connection broken in state=3 then status '504 Gateway Time-out' set;
// 3.If state=3 (transfer operation pending) then status '206 Partial Content' set;
// 4.If state=4 then status set to server-returned status
function getStatus(): integer;
//wait for tranfer completition. On fuction exit all pending
// data send/receive completed and connection closed.
procedure fetchAll();
//maxBufSize: read buffer size
//Readed data in zero-based one dimensional SafeArray of bytes (VT_ARRAY | VT_UI1)
function read(const maxBufSize: integer): OleVariant;
function get_eos(): WordBool;
//"true" if end of stream reached, "false" otherwise
property eos: WordBool read get_eos;
end;
{$WARNINGS ON}
THTTPStorage = class(TOSManObject, IHTTPStorage)
protected
fHostName: WideString;
fTimeout, fMaxRetry: integer;
fInet: HInternet;
public
//property setters-getters
function get_hostName(): WideString;
procedure set_hostName(const aName: WideString);
function get_timeout(): integer;
procedure set_timeout(const aTimeout: integer);
function get_maxRetry(): integer;
procedure set_maxRetry(const aMaxRetry: integer);
constructor create(); override;
destructor destroy(); override;
published
//returns IHTTPResponce for request
function send(const method, location, extraData: WideString): OleVariant;
//hostname for OSM-API server. Official server is api.openstreetmap.org
property hostName: WideString read get_hostName write set_hostName;
//timeout for network operations (in ms). By default 20000ms (20 sec)
property timeout: integer read get_timeout write set_timeout;
//max retries for connection/DNS requests. By default 3.
property maxRetry: integer read get_maxRetry write set_maxRetry;
end;
TNetMap = class(TAbstractMap)
protected
fFetchingResult: boolean;
fResultObj: OleVariant;
//result can be:
//1. 'false' in no objects fetched
//2. mapObject(Node,Way or Relation) if fetched exactly one object
//3. array of mapObjects if fetched more than one object
function fetchObjects(const method, objLocation, extraData: WideString): OleVariant;
function IdArrayToAnsiStr(idArray:Variant):AnsiString;
published
//get node by ID. If no node found returns false
function getNode(const id: int64): OleVariant; override;
//get way by ID. If no way found returns false
function getWay(const id: int64): OleVariant; override;
//get relation by ID. If no relation found returns false
function getRelation(const id: int64): OleVariant; override;
function getNodes(const nodeIdArray: OleVariant): OleVariant; override;
function getWays(const wayIdArray: OleVariant): OleVariant; override;
function getRelations(const relationIdArray: OleVariant): OleVariant; override;
procedure putNode(const aNode: OleVariant); override;
procedure putWay(const aWay: OleVariant); override;
procedure putRelation(const aRelation: OleVariant); override;
procedure putObject(const aObj: OleVariant); override;
//set HTTP-storage (IHTTPStorage). To free system resource set storage to unassigned
//property storage:OleVariant read get_storage write set_storage;
end;
{ TNetMap }
function TNetMap.fetchObjects(const method, objLocation,
extraData: WideString): OleVariant;
procedure raiseError();
begin
raise EInOutError.create(toString() + '.fetchObjects: network problem');
end;
var
hr: OleVariant;
rdr: TOSMReader;
begin
hr := fStorage.send(method, objLocation, extraData);
hr.fetchAll();
fResultObj := false;
if (hr.getState() <> 4) then begin
raiseError();
end
else
//state=4
case (hr.getStatus()) of
404: exit; //not found
410: exit; //deleted
200: ; //continue operation
else
raiseError();
end;
rdr := TOSMReader.create();
fResultObj := unassigned;
try
rdr.setInputStream(hr);
rdr.setOutputMap(self as IDispatch);
fFetchingResult := true;
rdr.read(1);
finally
FreeAndNil(rdr);
fFetchingResult := false;
end;
result := fResultObj;
if varIsEmpty(result) then
result := false;
fResultObj := unassigned;
end;
function TNetMap.getNode(const id: int64): OleVariant;
begin
if not VarIsType(fStorage, varDispatch) then
raise EInOutError.create(toString() + '.getNode: storage not assigned');
result := fetchObjects('GET', '/api/0.6/node/' + inttostr(id), '');
end;
function TNetMap.getNodes(const nodeIdArray: OleVariant): OleVariant;
var
narr: OleVariant;
s: AnsiString;
begin
narr := varFromJsObject(nodeIdArray);
if not VarIsType(fStorage, varDispatch) then
raise EInOutError.create(toString() + '.getNodes: storage not assigned');
if (VarArrayDimCount(narr) <> 1) then
raise EInOutError.create(toString() + '.getNodes: one dimension array expected');
s := 'nodes='+idArrayToAnsiStr(narr);
result := fetchObjects('GET', '/api/0.6/nodes?'+s,'');
if not varIsArray(result) then begin
if varIsType(result,varDispatch) then
result:=varArrayOf([result])
else
result:=varArrayOf([]);
end;
end;
function TNetMap.getRelation(const id: int64): OleVariant;
begin
result := fetchObjects('GET', '/api/0.6/relation/' + inttostr(id), '');
end;
function TNetMap.getRelations(const relationIdArray: OleVariant): OleVariant;
var
narr: OleVariant;
s: AnsiString;
begin
narr := varFromJsObject(relationIdArray);
if not VarIsType(fStorage, varDispatch) then
raise EInOutError.create(toString() + '.getRelations: storage not assigned');
if (VarArrayDimCount(narr) <> 1) then
raise EInOutError.create(toString() + '.getRelations: one dimension array expected');
s := 'relations='+idArrayToAnsiStr(narr);
result := fetchObjects('GET', '/api/0.6/relations?'+s,'');
if not varIsArray(result) then begin
if varIsType(result,varDispatch) then
result:=varArrayOf([result])
else
result:=varArrayOf([]);
end;
end;
function TNetMap.getWay(const id: int64): OleVariant;
begin
result := fetchObjects('GET', '/api/0.6/way/' + inttostr(id), '');
end;
function TNetMap.getWays(const wayIdArray: OleVariant): OleVariant;
var
narr: OleVariant;
s: AnsiString;
begin
narr := varFromJsObject(wayIdArray);
if not VarIsType(fStorage, varDispatch) then
raise EInOutError.create(toString() + '.getWays: storage not assigned');
if (VarArrayDimCount(narr) <> 1) then
raise EInOutError.create(toString() + '.getWays: one dimension array expected');
s := 'ways='+idArrayToAnsiStr(narr);
result := fetchObjects('GET', '/api/0.6/ways?'+s,'');
if not varIsArray(result) then begin
if varIsType(result,varDispatch) then
result:=varArrayOf([result])
else
result:=varArrayOf([]);
end;
end;
function TNetMap.IdArrayToAnsiStr(idArray: Variant): AnsiString;
var
i:integer;
pv:PVariant;
begin
i := varArrayLength(idArray);
pv := VarArrayLock(idArray);
result:='';
try
while i > 0 do begin
dec(i);
result := result + VarAsType(pv^, varOleStr) + IfThen(i = 0, '', ',');
inc(pv);
end;
finally
VarArrayUnlock(idArray);
end;
end;
procedure TNetMap.putNode(const aNode: OleVariant);
begin
putObject(aNode);
end;
procedure TNetMap.putObject(const aObj: OleVariant);
var
h: integer;
o: Variant;
begin
if not fFetchingResult then
raise EInOutError.create(toString() + ': put operations not supported');
varCopyNoInd(o, aObj);
if varIsEmpty(fResultObj) then
fResultObj := o
else if VarIsArray(fResultObj) then begin
h := VarArrayHighBound(fResultObj, 1) + 1;
VarArrayRedim(fResultObj, h);
fResultObj[h] := o;
end
else begin
//not empty and not array - create array now
fResultObj := VarArrayOf([fResultObj, o]);
end;
end;
procedure TNetMap.putRelation(const aRelation: OleVariant);
begin
putObject(aRelation);
end;
procedure TNetMap.putWay(const aWay: OleVariant);
begin
putObject(aWay);
end;
{ THTTPStorage }
constructor THTTPStorage.create;
begin
inherited;
maxRetry := 3;
timeout := 20000;
fInet := nil;
hostName := 'api.openstreetmap.org';
//'api06.dev.openstreetmap.org';
//'jxapi.openstreetmap.org/xapi';
end;
destructor THTTPStorage.destroy;
begin
if assigned(fInet) then begin
InternetCloseHandle(fInet);
fInet := nil;
end;
inherited;
end;
function THTTPStorage.get_hostName: WideString;
begin
result := fHostName;
end;
function THTTPStorage.get_maxRetry: integer;
begin
result := fMaxRetry;
end;
function THTTPStorage.get_timeout: integer;
begin
result := fTimeout;
end;
function THTTPStorage.send(const method, location,
extraData: WideString): OleVariant;
var
rCnt: integer;
hConn, hReq: HInternet;
resp: THTTPResponce;
s, h, l, e: AnsiString;
uc: TURLComponents;
begin
resp := THTTPResponce.create();
result := resp as IDispatch;
fillchar(uc, sizeof(uc), 0);
uc.dwStructSize := sizeof(uc);
s := 'http://' + hostName + location;
setLength(h, length(s));
setLength(l, length(s));
setLength(e, length(s));
uc.dwHostNameLength := length(s);
uc.dwUrlPathLength := length(s);
uc.dwExtraInfoLength := length(s);
uc.lpszHostName := @h[1];
uc.lpszUrlPath := @l[1];
uc.lpszExtraInfo := @e[1];
if not InternetCrackUrlA(pAnsiChar(s), length(s), 0, uc) then begin
resp.setStates(4, 503);
exit;
end;
rCnt := maxRetry;
while (not assigned(fInet)) and (rCnt > 0) do begin
fInet := InternetOpen('OSMan.HTTPStorage.1', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
dec(rCnt);
if (not assigned(fInet)) and (rCnt > 0) then
sleep(fTimeout);
end;
if (not assigned(fInet)) then begin
resp.setStates(4, 503);
exit;
end;
hConn := nil;
hReq := nil;
rCnt := maxRetry;
try
while (not assigned(hConn)) and (rCnt > 0) do begin
hConn := InternetConnectA(fInet, uc.lpszHostName, uc.nPort, nil, nil,
uc.nScheme, 0, 0);
dec(rCnt);
if (not assigned(hConn)) and (rCnt > 0) then
sleep(fTimeout);
end;
if (not assigned(hConn)) then begin
resp.setStates(4, 504);
exit;
end;
rCnt := maxRetry;
while (not assigned(hReq)) and (rCnt > 0) do begin
hReq := HttpOpenRequestA(hConn, pAnsiChar(AnsiString(method)),
pAnsiChar(AnsiString(uc.lpszUrlPath) + AnsiString(uc.lpszExtraInfo)), '1.1', nil, nil, 0,
0);
dec(rCnt);
if (not assigned(hReq)) and (rCnt > 0) then
sleep(fTimeout);
end;
if (not assigned(hReq)) then begin
resp.setStates(4, 504);
exit;
end;
if not HttpSendRequestA(hReq, nil, 0, pAnsiChar(AnsiString(extraData)), length(extraData)) then
begin
resp.setStates(4, 504);
exit;
end;
resp.setConnection(hReq, hConn);
hReq := nil;
hConn := nil;
finally
if assigned(hReq) then
InternetCloseHandle(hReq);
if assigned(hConn) then
InternetCloseHandle(hConn);
end;
end;
procedure THTTPStorage.set_hostName(const aName: WideString);
begin
fHostName := aName;
end;
procedure THTTPStorage.set_maxRetry(const aMaxRetry: integer);
begin
if aMaxRetry < 1 then
fMaxRetry := 1
else
fMaxRetry := aMaxRetry;
end;
procedure THTTPStorage.set_timeout(const aTimeout: integer);
begin
if aTimeout < 0 then
fTimeout := 0
else
fTimeout := aTimeout;
end;
{ THTTPResponce }
procedure THTTPResponce.fetchAll;
var
ba, rd, stt: cardinal;
begin
while true do begin
if not InternetQueryDataAvailable(fConn, ba, 0, 0) then begin
setStates(4, 504);
break;
end;
grow(ba);
if not InternetReadFile(fConn, @fReadBuf[fReadBufSize], ba, rd) then begin
setStates(4, 504);
break;
end;
inc(fReadBufSize, rd);
if rd = 0 then begin
ba := sizeof(stt);
if HttpQueryInfoA(fConn, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @stt, ba, rd) then
setStates(4, stt)
else
setStates(4, 504);
break;
end;
end;
InternetCloseHandle(fConn);
fConn := nil;
end;
function THTTPResponce.get_eos: WordBool;
begin
result := (fReadBufSize = 0) and not assigned(fConn);
end;
function THTTPResponce.getState: integer;
var
ba: cardinal;
begin
result := fState;
if fState <> 3 then
exit;
if InternetQueryDataAvailable(fConn, ba, 0, 0) then begin
if ba > 0 then
fState := 3
else
fState := 4;
end
else begin
setStates(4, 504);
end;
result := fState;
end;
function THTTPResponce.getStatus: integer;
begin
result := fStatus;
end;
function THTTPResponce.read(const maxBufSize: integer): OleVariant;
function min(const a, b: cardinal): cardinal;
begin
if a < b then result := a
else result := b;
end;
var
p: pByte;
reslen, ba, rd: cardinal;
stt: integer;
begin
if not ((fState = 3) or ((fState = 4) and (fStatus = 200))) then begin
raise EInOutError.create(toString() + ': HTTP-connection error');
end;
result := VarArrayCreate([0, maxBufSize - 1], varByte);
p := VarArrayLock(result);
reslen := 0;
try
if fReadBufSize > 0 then begin
reslen := min(maxBufSize, fReadBufSize);
move(fReadBuf[0], p^, reslen);
move(fReadBuf[reslen], fReadBuf[0], fReadBufSize - integer(reslen));
dec(fReadBufSize, reslen);
inc(p, reslen);
end;
while (integer(reslen) < maxBufSize) and not eos do begin
if not InternetQueryDataAvailable(fConn, ba, 0, 0) then begin
setStates(4, 504);
break;
end;
ba := min(maxBufSize - integer(reslen), ba);
if not InternetReadFile(fConn, p, ba, rd) then begin
setStates(4, 504);
break;
end;
inc(reslen, rd);
inc(p, rd);
if rd = 0 then begin
ba := sizeof(stt);
if HttpQueryInfoA(fConn, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @stt, ba, rd)
then
setStates(4, stt)
else
setStates(4, 504);
break;
end;
end;
if (fState = 4) and (assigned(fConn)) then begin
InternetCloseHandle(fConn);
fConn := nil;
end;
finally
VarArrayUnlock(result);
end;
if integer(reslen) < maxBufSize then
VarArrayRedim(result, integer(reslen) - 1);
end;
constructor THTTPResponce.create;
begin
inherited;
fState := 0;
fStatus := 100;
end;
procedure THTTPResponce.setConnection(const hConnection, hAddHandle: HInternet);
begin
fConn := hConnection;
fAddHandle := hAddHandle;
setStates(3, 206);
end;
procedure THTTPResponce.setStates(const aState, aStatus: integer);
begin
fState := aState;
fStatus := aStatus;
end;
destructor THTTPResponce.destroy;
begin
if assigned(fConn) then
InternetCloseHandle(fConn);
fConn := nil;
if assigned(fAddHandle) then
InternetCloseHandle(fAddHandle);
fAddHandle := nil;
inherited;
end;
procedure THTTPResponce.grow(const delta: cardinal);
begin
if (fReadBufSize + integer(delta)) > length(fReadBuf) then
setLength(fReadBuf, (fReadBufSize + integer(delta) + 4 * 1024 - 1) and (-4 * 1024));
end;
initialization
OSManRegister(TNetMap, netMapClassGUID);
OSManRegister(THTTPStorage, httpStorageClassGUID);
end.
|
unit ReadXML;
// Read XML
// Not aware of logic
interface
uses
Classes,
SysUtils,
XMLDoc,
XMLIntf,
EBookingInterfaces;
type
TReadXML = class(TInterfacedObject, IEbooking)
private
fXML: TStringList;
procedure LoadXML(const aXMLfile: string);
public
constructor Create(const aXMLfile: string);
destructor Destroy; override;
function GetRole: String;
end;
implementation
constructor TReadXML.Create(const aXMLfile: string);
begin
inherited Create;
LoadXML(aXMLfile);
end;
destructor TReadXML.Destroy;
begin
fXML.Free;
end;
function TReadXML.GetRole: String;
begin
Result := fXML.Text;
end;
procedure TReadXML.LoadXML(const aXMLfile: string);
begin
fXML := TStringList.Create;
fXML.LoadFromFile(aXMLfile);
end;
end.
|
unit UList;
interface
uses Windows, UxlClasses, UxlWinControl, UxlDragControl, UxlListView, UClientSuper, UxlExtClasses, UTypeDef,
UPageSuper, UxlList, UPageProperty;
type
TListClient = class (TListClientSuper, IOptionObserver, ILangObserver)
private
FWndParent: TxlWincontrol;
FListView: TxlListView;
FSortCol: integer;
FTemprList: TxlStrList;
FSettings: widestring;
FPList: TListProperty;
procedure f_OnContextMenu (index: integer);
procedure f_OnDropEvent (o_dragsource: IDragSource; hidxTarget: integer; b_copy: boolean);
function f_OnEndLabelEdit (index: integer; const newtext: widestring): integer;
procedure f_OnColumnClick (index: integer);
procedure f_OnToolTipDemand (index: integer; const rt: TRect);
function f_GetListItem (o_page: TPageSuper): TListViewItem;
procedure f_OnDeleteItemDemand (Sender: TObject);
protected
procedure Load (value: TPageSuper); override;
procedure UnLoad (); override;
function Items (index: integer): TPageSuper; override;
public
constructor Create (WndParent: TxlWinContainer);
destructor Destroy (); override;
function Control (): TxlControl; override;
procedure OnPageEvent (pct: TPageEvent; id, id2: integer); override;
procedure Save (); override;
function CheckCommand (opr: word): boolean; override;
procedure ExecuteCommand (opr: word); override;
procedure OptionChanged ();
procedure LanguageChanged ();
end;
implementation
uses Messages, UxlWinClasses, UxlStrUtils, UxlCommDlgs, UxlFunctions, Resource, UGlobalObj, UPageStore, UOptionManager,
ULangManager, UPageFactory, UxlMath;
constructor TListClient.Create (WndParent: TxlWinContainer);
begin
FWndParent := WndParent;
FSortCol := -1;
FListView := TxlListview.Create (WndParent);
with FListView do
begin
LargeImages := PageImageList.LargeImages;
SmallImages := PageImageList.SmallImages;
ShowImages := true;
CanDrag := true;
CanDrop := true;
OnDropEvent := f_OnDropEvent;
OnItemDblClick := f_OnItemDblClick;
OnItemReturn := f_OnItemDblClick;
Items.OnSelect := f_OnSelectItem;
OnContextMenu := f_OnContextMenu;
Items.OnEndLabelEdit := f_OnEndLabelEdit;
Cols.OnClick := f_OnColumnClick;
OnToolTipDemand := f_OnToolTipDemand;
OnDeleteItemDemand := f_OnDeleteItemDemand;
end;
FTemprList := TxlStrList.Create;
FTemprList.Separator := #9;
OptionMan.AddObserver(self);
LangMan.AddObserver (self);
end;
destructor TListClient.Destroy ();
begin
LangMan.RemoveObserver (self);
OptionMan.RemoveObserver(self);
FListView.free;
FTemprList.Free;
inherited;
end;
function TListClient.Control (): TxlControl;
begin
result := FListView;
end;
procedure TListClient.OptionChanged ();
begin
FListView.Color := OptionMan.Options.ListColor;
FListView.Font := OptionMan.Options.ListFont; // 需放在setcolor之后,原因不明
end;
procedure TListClient.LanguageChanged ();
begin
FSettings := '';
Refresh;
end;
function TListClient.Items (index: integer): TPageSuper;
begin
result := PageStore[FListView.Items[index].data];
end;
//-----------------------
procedure TListClient.Load (value: TPageSuper);
function f_ListStyle (value: TListProperty): TListViewStyle;
begin
with result do
begin
ViewStyle := TViewType(Ord(value.View));
MultiSelect := true;
FullRowSelect := value.FullRowSelect;
GridLines := value.GridLines;
CheckBoxes := value.CheckBoxes;
EditLabels := ViewStyle <> lvsReport;
ShowHeader := true;
HeaderDragDrop := true;
end;
end;
var o_list: TxlIntList;
o_list2: TxlStrList;
i: integer;
o_item: TListViewItem;
begin
if value = nil then exit;
inherited Load (value);
// initialize and add columns, 并缓存记忆
FPList := value.ListProperty;
o_list2 := TxlStrList.Create;
FPList.Save (o_list2);
if (o_list2.Text <> FSettings) then
begin
FListView.Clear;
FListView.Style := f_ListStyle(FPList);
for i := FPList.ColList.Low to FPList.ColList.High do
FListView.Cols.Add (LangMan.GetItem(FPList.ColList[i]), FPList.widthlist[i]);
FSettings := o_list2.Text;
end;
o_list2.free;
// add items
FListView.items.Clear;
o_list := TxlIntList.Create;
value.GetChildList (o_list);
for i := o_list.Low to o_list.High do
begin
o_item := f_GetListItem (PageStore[o_list[i]]);
FListView.Items.Add (o_item);
end;
o_list.Free;
CommandMan.CheckCommands;
end;
procedure TListClient.UnLoad ();
begin
FListView.Items.Clear;
end;
procedure TListClient.Save ();
var i, i_col: integer;
o_list, o_list2: TxlIntList;
begin
o_list := TxlIntList.Create;
o_list2 := TxlIntLIst.Create();
FListView.Cols.GetHeaderOrder (o_list); // 记忆列头拖放的效果
for i := FPList.ColList.Low to FPList.ColList.High do
o_list2.Add (FPList.ColList[i]);
for i := FPList.ColList.Low to FPList.ColList.High do
begin
i_col := o_list[i];
FPList.ColList[i] := o_list2[i_col];
FPList.WidthList[i] := FListView.Cols.Width[i_col];
end;
for i := FListView.Items.Low to FListView.Items.High do
Items(i).Checked := FListView.Items.Checked[i];
o_list.Free;
o_list2.Free;
end;
function TListClient.f_GetListItem (o_page: TPageSuper): TListViewItem;
var j: integer;
begin
FTemprList.Clear;
for j := FPList.collist.Low to FPList.collist.High do
FTemprList.Add (MultiLineToSingleLine(o_page.GetColText(FPList.collist[j]), true));
with result do
begin
text := FTemprList.Text;
data := o_page.id;
image := o_page.ImageIndex;
state := 0;
checked := o_page.Checked;
selected := false;
end;
end;
procedure TListClient.OnPageEvent (pct: TPageEvent; id, id2: integer);
var o_item: TListViewItem;
i, j: integer;
begin
case pct of
pctFieldModified, pctIcon, pctColor, pctSwitchStatus:
begin
i := FListView.Items.FindByData (id);
if i >= 0 then
FListView.Items[i] := f_GetListItem (PageStore[id]);
end;
pctAddChild:
if id = FPage.id then
begin
o_item := f_GetListItem (PageStore[id2]);
i := FPage.Childs.FindChild (id2);
if i <= FListView.Items.High then
begin
if FListView.Style.ViewStyle in [lvsList, lvsReport] then
FListView.Items.Insert (i, o_item)
else // 对于icon和small icon风格,使用insert不能插入到正确位置,而总是在最后
Refresh;
end
else
FListView.Items.Add (o_item);
for j := FListView.Items.Low to FListView.Items.High do
FListView.Items.Select (j, j = i);
end;
pctRemoveChild:
begin
if not (id = FPage.id) then exit;
i := FListView.Items.FindByData (id2);
if i >= 0 then
FListView.Items.Delete (i);
end;
pctListProperty:
Refresh;
else
inherited OnPageEvent (pct, id, id2);
end
end;
//---------------
function TListClient.CheckCommand (opr: word): boolean;
begin
case opr of
m_clear, m_selectall:
result := FListView.Items.Count > 0;
m_undo, m_redo, m_cut, m_copy, m_paste:
result := false;
m_delete:
if FPage = nil then
result := false
else if FPage.IsVirtualContainer then
result := CommandMan.CheckCommand (m_removeitem)
else
result := CommandMan.CheckCommand (m_deleteitem);
m_wordwrap, m_find, m_subsequentfind, m_highlightmatch, m_texttools, m_insertlink, m_insertcliptext, m_inserttemplate:
result := false;
else
result := true;
end;
end;
procedure TListClient.ExecuteCommand (opr: word);
begin
if not CheckCommand (opr) then exit;
case opr of
m_clear:
begin
// if OptionMan.Options.ConfirmClear then
// if (ShowMessage (LangMan.GetItem(sr_clearprompt), mtQuestion,
// LangMan.GetItem(sr_prompt)) = mrCancel) then exit;
FListView.Items.SelectAll;
CommandMan.ExecuteCommand (m_deleteitem); // 此过程本身会出现提示
end;
m_selectall:
FListView.Items.SelectAll;
m_delete:
if FPage.IsVirtualContainer then
CommandMan.ExecuteCommand (m_removeitem)
else
CommandMan.ExecuteCommand (m_deleteitem);
// else
// inherited ExecuteCommand (opr);
end;
end;
//--------------------------
procedure TListClient.f_OnDropEvent (o_dragsource: IDragSource; hidxTarget: integer; b_copy: boolean);
var i_targetid: integer;
begin
if hidxTarget < 0 then
hidxTarget := FListView.Items.High;
if (hidxTarget >= 0) and assigned (OnDropItems) then
begin
i_targetid := FListView.Items[hidxTarget].data;
OnDropItems (o_dragsource, i_targetid, FPage.id, b_copy);
end;
end;
function TListClient.f_OnEndLabelEdit (index: integer; const newtext: widestring): integer;
begin
if newtext <> '' then
begin
result := 1;
Items(index).name := newtext;
end
else
result := 0;
end;
procedure TListClient.f_OnContextMenu (index: integer);
var i_demand: cardinal;
begin
if index >= 0 then
// begin
// if FPage.PageType = ptFavorite then
// i_demand := FavoriteListContext
// else
i_demand := ListContext
// end
else
i_demand := ListNoSelContext;
EventMan.EventNotify (e_ContextMenuDemand, i_demand);
end;
procedure TListClient.f_OnColumnClick (index: integer);
var b_asc: boolean;
begin
if index = FSortCol then
begin
b_asc := false;
FSortCol := -1;
end
else
begin
b_asc := true;
FSortCol := index;
end;
FListView.Sort (index, b_asc);
end;
procedure TListClient.f_OnToolTipDemand (index: integer; const rt: TRect);
begin
end;
procedure TListClient.f_OnDeleteItemDemand (Sender: TObject);
begin
CommandMan.ExecuteCommand (m_delete);
end;
end.
|
{========================================================================}
{================= TVicHW64 Version 6.0 =================}
{====== Copyright (c) 1997-2004 Victor I.Ishikeev =====}
{========================================================================}
{===== http://www.entechtaiwan.com/tools.htm =======}
{========== mailto:tools@entechtaiwan.com =======}
{========================================================================}
{===== The basic TVicHW6 data declarations =====}
{========================================================================}
unit HW_Types;
{-------} interface {---------}
uses Windows;
type
pMSR_DATA =^TMSR_DATA;
TMSR_DATA = record
MSR_LO: DWORD;
MSR_HI: DWORD;
end;
CPUID_RECORD = record
EAX: DWORD;
EBX: DWORD;
ECX: DWORD;
EDX: DWORD;
end;
pIrqClearRec =^TIrqClearRec;
TIrqClearRec = record
ClearIrq : Byte; // 1 - Irq must be cleared, 0 - not
TypeOfRegister : Byte; // 0 - memory, 1 - port
WideOfRegister : Byte; // 1 - Byte, 2 - Word, 4 - Double Word
ReadOrWrite : Byte; // 0 - read register to clear Irq, 1 - write
RegBaseAddress : DWORD; // Memory or port i/o register base address to clear
RegOffset: DWORD; // Register offset
ValueToWrite : DWORD; // Value to write (if ReadOrWrite=1)
end;
pDmaBufferRequest = ^TDmaBufferRequest;
TDmaBufferRequest = packed record
LengthOfBuffer : DWORD; // Length in Bytes
AlignMask : DWORD; // 0-4K, 1-8K, 3-16K, 7-32K, $0F-64K, $1F-128K
PhysDmaAddress : DWORD; // returned physical address of DMA buffer
LinDmaAddress : Pointer; // returned linear address
DmaMemHandle : THANDLE; // returned memory handle (do not use and keep it!)
Reserved1 : DWORD;
KernelDmaAddress : DWORD; // do not use and keep it!
Reserved2 : DWORD;
end;
pHDDInfo =^THDDInfo;
THDDInfo = packed record
DoubleTransfer : DWORD;
ControllerType : DWORD;
BufferSize : DWORD;
ECCMode : DWORD;
SectorsPerInterrupt : DWORD;
Cylinders : DWORD;
Heads : DWORD;
SectorsPerTrack : DWORD;
Model : array [0..40] of Char;
SerialNumber : array [0..20] of Char;
Revision : array [0..8] of Char;
end;
pPortByteFifo =^TPortByteFifo;
TPortByteFifo = record
PortAddr : DWORD;
NumPorts : DWORD;
Buffer : array[1..2] of Byte;
end;
pPortWordFifo =^TPortWordFifo;
TPortWordFifo = record
PortAddr : DWORD;
NumPorts : DWORD;
Buffer : array[1..2] of Word;
end;
pPortLongFifo =^TPortLongFifo;
TPortLongFifo = record
PortAddr : DWORD;
NumPorts : DWORD;
Buffer : array[1..2] of DWORD;
end;
type
TNonBridge = record
base_address0 : DWORD;
base_address1 : DWORD;
base_address2 : DWORD;
base_address3 : DWORD;
base_address4 : DWORD;
base_address5 : DWORD;
CardBus_CIS : DWORD;
subsystem_vendorID : Word;
subsystem_deviceID : Word;
expansion_ROM : DWORD;
cap_ptr : Byte;
reserved1 : array[1..3] of Byte;
reserved2 : DWORD;
interrupt_line : Byte;
interrupt_pin : Byte;
min_grant : Byte;
max_latency : Byte;
device_specific : array[1..48] of DWORD;
ReservedByVictor : array[1..5] of DWORD;
end;
TBridge = record
base_address0 : DWORD;
base_address1 : DWORD;
primary_bus : Byte;
secondary_bus : Byte;
subordinate_bus : Byte;
secondary_latency : Byte;
IO_base_low : Byte;
IO_limit_low : Byte;
secondary_status : Word;
memory_base_low : Word;
memory_limit_low : Word;
prefetch_base_low : Word;
prefetch_limit_low : Word;
prefetch_base_high : DWORD;
prefetch_limit_high : DWORD;
IO_base_high : Word;
IO_limit_high : Word;
reserved2 : DWORD;
expansion_ROM : DWORD;
interrupt_line : Byte;
interrupt_pin : Byte;
bridge_control : Word;
device_specific : array[1..48] of DWORD;
ReservedByVictor : array[1..5] of DWORD;
end;
type TCardBus = record
ExCa_base : DWORD;
cap_ptr : Byte;
reserved05 : Byte;
secondary_status : Word;
PCI_bus : Byte;
CardBus_bus : Byte;
subordinate_bus : Byte;
latency_timer : Byte;
memory_base0 : DWORD;
memory_limit0 : DWORD;
memory_base1 : DWORD;
memory_limit1 : DWORD;
IObase_0low : Word;
IObase_0high : Word;
IOlimit_0low : Word;
IOlimit_0high : Word;
IObase_1low : Word;
IObase_1high : Word;
IOlimit_1low : Word;
IOlimit_1high : Word;
interrupt_line : Byte;
interrupt_pin : Byte;
bridge_control : Word;
subsystem_vendorID : Word;
subsystem_deviceID : Word;
legacy_baseaddr : DWORD;
cardbus_reserved : array[1..14] of DWORD;
vendor_specific : array[1..32] of DWORD;
ReservedByVictor : array[1..5] of DWORD;
end;
pPciCfg =^TPciCfg;
TPciCfg = record
vendorID : Word;
deviceID : Word;
command_reg : Word;
status_reg : Word;
revisionID : Byte;
progIF : Byte;
subclass : Byte;
classcode : Byte;
cacheline_size : Byte;
latency : Byte;
header_type : Byte;
BIST : Byte;
case Integer of
0 : (NonBridge : TNonBridge);
1 : (Bridge : TBridge);
2 : (CardBus : TCardBus);
end;
TPciRequestRecord = record
cfg_mech : Byte;
bus_number : Byte;
dev_number : Byte;
func_number : Byte;
end;
TOnHWInterrupt = procedure (IRQNumber:WORD); stdcall;
TRing0Function = procedure;// stdcall;
TOnDelphiInterrupt = procedure (TVic : THANDLE; IRQNumber:WORD); stdcall;
TOnKeystroke = procedure (scan_code: Byte); stdcall;
TOnDelphiKeystroke = procedure (TVic : THANDLE; scan_code: Byte); stdcall;
{-------} implementation {--------}
end.
|
unit Lbllist;
interface
Uses SysUtils,StdCtrls,Classes,Buttons,Controls,ExtCtrls,Menus,
Messages,SQLCtrls,DBTables,TSQLCls;
Type TLabelListbox=class(TSQLControl)
protected
BackUp:Integer;
procedure WriteCaption(s:string);
Function ReadCaption:String;
procedure WriteOnClick(s:TNotifyEvent);
Function ReadOnClick:TNotifyEvent;
procedure WriteOnDBlClick(s:TNotifyEvent);
Function ReadOnDblClick:TNotifyEvent;
procedure LLBOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure LLBOnEnter(Sender: TObject);
public
Lbl:TLabel;
ListBox:TListBox;
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure Value(sl:TStringList); override;
procedure SetValue(var q:TQuery); override;
procedure WMSize(var Msg:TMessage); message WM_SIZE;
published
property Caption:String read ReadCaption write WriteCaption;
property OnClick:TNotifyEvent read ReadOnClick write WriteOnClick;
property OnDblClick:TNotifyEvent read ReadOnDblClick write WriteOnDblClick;
property Align;
property DragCursor;
property DragMode;
property Enabled;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
end;
procedure Register;
implementation
Uses WinTypes;
procedure TLabelListBox.Value(sl:TStringList);
begin
if Assigned(fValueEvent) then fValueEvent(self,sl)
else
if (not Visible) or (Listbox.ItemIndex=-1) then
sl.Add('NULL')
else
sl.Add(sql.MakeStr(Listbox.Items[Listbox.ItemIndex]));
end;
procedure TLabelListBox.SetValue(var q:TQuery);
begin
if Assigned(fSetValueEvent) then fSetValueEvent(self,q)
else
Listbox.ItemIndex:=Listbox.Items.IndexOf(q.FieldByName(fFieldName).AsString);
end;
destructor TLabelListBox.Destroy;
begin
Lbl.Free;
ListBox.Free;
inherited Destroy;
end;
constructor TLabelListBox.Create(AOwner:TComponent);
begin
inherited create(AOwner);
Lbl:=TLabel.Create(self);
ListBox:=TListBox.Create(self);
Lbl.Parent:=self;
ListBox.Parent:=self;
Lbl.Left:=0;
Lbl.Top:=0;
ListBox.Left:=0;
ListBox.OnKeyUp:=LLBOnKeyUp;
ListBox.OnEnter:=LLBOnEnter
end;
procedure TLabelListBox.WMSize(var Msg:TMessage);
begin
Lbl.Height:=-Lbl.Font.Height+3;
Lbl.Width:=Msg.LParamLo;
ListBox.Top:=Lbl.Height;
ListBox.Height:=Msg.LParamHi-ListBox.Top;
ListBox.Width:=Msg.LParamLo;
end;
procedure TLabelListBox.WriteCaption(s:String);
begin
Lbl.Caption:=s
end;
function TLabelListBox.ReadCaption:String;
begin
ReadCaption:=Lbl.Caption
end;
procedure TLabelListBox.WriteOnClick(s:TNotifyEvent);
begin
ListBox.OnClick:=s
end;
function TLabelListBox.ReadOnClick:TNotifyEvent;
begin
ReadOnClick:=ListBox.OnClick
end;
procedure TLabelListBox.WriteOnDblClick(s:TNotifyEvent);
begin
ListBox.OnDblClick:=s
end;
function TLabelListBox.ReadOnDblClick:TNotifyEvent;
begin
ReadOnDblClick:=ListBox.OnDblClick
end;
procedure Register;
begin
RegisterComponents('MyOwn',[TLabelListBox])
end;
procedure TLabelListBox.LLBOnEnter(Sender:TObject);
begin
ListBox.SetFocus;
BackUp:=ListBox.ItemIndex
end;
procedure TLabelListBox.LLBOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=VK_ESCAPE then
ListBox.ItemIndex:=BackUp
end;
end.
|
unit globals;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, resource, versiontypes, versionresource;
var
DBType : string ;
DBVersion : integer ;
UserName : string ;
ComputerName : string ;
DNSDomain : string ;
UserAccessLevel : integer ;
ExitApplication : boolean ;
tAccount_ID : integer ;
tOrganization_ID : integer ;
tProject_ID : integer ;
tProjectConfig_ID : integer ;
implementation
FUNCTION resourceVersionInfo: STRING;
(* Unlike most of AboutText (below), this takes significant activity at run- *)
(* time to extract version/release/build numbers from resource information *)
(* appended to the binary. *)
VAR Stream: TResourceStream;
vr: TVersionResource;
fi: TVersionFixedInfo;
BEGIN
RESULT:= '';
TRY
(* This raises an exception if version info has not been incorporated into the *)
(* binary (Lazarus Project -> Project Options -> Version Info -> Version *)
(* numbering). *)
Stream:= TResourceStream.CreateFromID(HINSTANCE, 1, PChar(RT_VERSION));
TRY
vr:= TVersionResource.Create;
TRY
vr.SetCustomRawDataStream(Stream);
fi:= vr.FixedInfo;
RESULT := 'Version ' + IntToStr(fi.FileVersion[0]) + '.' + IntToStr(fi.FileVersion[1]) +
' release ' + IntToStr(fi.FileVersion[2]) + ' build ' + IntToStr(fi.FileVersion[3]) ;
vr.SetCustomRawDataStream(nil)
FINALLY
vr.Free
END
FINALLY
Stream.Free
END
EXCEPT
END
END { resourceVersionInfo } ;
end.
|
var
a, b, x, y: longint;
procedure exgcd(a, b: longint; var x, y: longint);
begin
if b = 0 then
begin
x := 1;
y := 0;
exit;
end;
exgcd(b, a mod b, y, x);
y := y - (a div b) * x;
end;
begin
assign(input, 'main.in'); reset(input);
assign(output, 'main.out'); rewrite(output);
readln(a,b);
exgcd(a, b, x, y);
while x <= 0 do x := x+ b;
writeln(x);
close(input); close(output);
end. |
PROGRAM AverageScore(INPUT, OUTPUT);
CONST
NumberOfScores = 4;
ClassSize = 4;
Radix = 10;
TYPE
Score = 0 .. 100;
VAR
WhichScore: 0..NumberOfScores;
Student: 0..ClassSize;
NextScore: Score;
Ave, TotalScore, ClassTotal: INTEGER;
BEGIN {AverageScore}
ClassTotal := 0;
WRITELN('Student averages:');
Student := 0;
WHILE Student < ClassSize
DO
BEGIN
TotalScore := 0;
WhichScore := 0;
WHILE WhichScore < NumberOfScores
DO
BEGIN
READ(NextScore);
TotalScore := TotalScore + NextScore;
WhichScore := WhichScore + 1;
END;
READLN;
TotalScore := TotalScore * Radix;
Ave := TotalScore DIV NumberOfScores;
IF Ave MOD Radix >= (Radix / 2)
THEN
WRITE('Student ¹', Student + 1:1, ' average: ', Ave DIV Radix + 1)
ELSE
WRITE('Student ¹', Student + 1:1, ' average: ', Ave DIV Radix);
ClassTotal := ClassTotal + TotalScore;
Student := Student + 1;
WRITELN
END;
WRITELN;
WRITELN ('Class average:');
ClassTotal := ClassTotal DIV (ClassSize * NumberOfScores);
WRITELN(ClassTotal DIV Radix, '.', ClassTotal MOD Radix:1)
END. {AverageScore}
|
unit teste.classes.produto;
interface
uses
Windows,
System.classes,
System.Generics.Collections,
System.SysUtils;
type
TprodutoClass = class
Private
Fcodigo: integer;
Fdescricao: string;
Fpreco: double;
public
function ListaProdutos(filtro: string): OleVariant;
procedure Limpar();
procedure Gravar;
procedure Excluir;
constructor create(icodigo: integer);
published
Property Codigo: integer read Fcodigo write Fcodigo;
Property Descricao: string read Fdescricao write Fdescricao;
Property Preco: double read Fpreco write Fpreco;
end;
Tprodutos = TObjectList<TprodutoClass>;
implementation
uses
teste.dao.produto;
{ Tproduto }
{ ------------------------------------------------------------------------- }
constructor TprodutoClass.create(icodigo: integer);
begin
if icodigo > 0 then
begin
Codigo := icodigo;
TdaoProduto.getProduto(self);
end;
end;
{ ------------------------------------------------------------------------- }
procedure TprodutoClass.Excluir;
begin
if TdaoProduto.deleteProduto(self) then
Limpar();
end;
{ ------------------------------------------------------------------------- }
procedure TprodutoClass.Gravar;
begin
TdaoProduto.getProduto(self);
end;
{ ------------------------------------------------------------------------- }
procedure TprodutoClass.Limpar;
begin
Fcodigo := 0;
Fpreco := 0;
Fdescricao := '';
end;
{ ------------------------------------------------------------------------- }
function TprodutoClass.ListaProdutos(filtro: string): OleVariant;
begin
result := TdaoProduto.listarProdutos(filtro);
end;
{ ------------------------------------------------------------------------- }
end.
|
{$include kode.inc}
unit kode_widget_slider;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_canvas,
kode_color,
//kode_const,
kode_flags,
//kode_math,
kode_rect,
kode_widget_value;
type
KWidget_Slider = class(KWidget_Value)
protected
FBarColor : KColor;
FDrawName : Boolean;
public
constructor create(ARect:KRect; AValue:Single; AAlignment:LongWord=kwa_none);
constructor create(ARect:KRect; AName:PChar; AValue:Single; AAlignment:LongWord=kwa_none);
//procedure setBarColor(AColor:KColor);
procedure on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); override;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
//kode_const,
//kode_debug,
kode_math,
kode_utils;
//----------
constructor KWidget_Slider.create(ARect:KRect; AValue:Single; AAlignment:LongWord);
begin
inherited;// create(ARect,AAlignment);
FName := 'KWidget_Slider';
FDrawName := False;
//FValue := AValue;
FBarColor := KWhite;
FCursor := kmc_ArrowUpDown;
end;
//----------
constructor KWidget_Slider.create(ARect:KRect; AName:PChar; AValue:Single; AAlignment:LongWord);
begin
inherited create(ARect,AValue,AAlignment);
FDrawName := True;
FName := AName;//'KWidget_Slider';
//FValue := AValue;
FBarColor := KWhite;
FCursor := kmc_ArrowUpDown;
end;
//----------
{procedure KWidget_Slider.setBarColor(AColor:KColor);
begin
FBarColor := AColor;
end;}
//----------
procedure KWidget_Slider.on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0);
var
//v : single;
w : longint;
nt : PChar; // name
vt : PChar; // value
begin
//if Assigned(FSkin) then
//begin
w := KFloor( FValue * Single(FRect.w) );
if Assigned(FParameter) then
begin
nt := FParameter.getName;
vt := FParameter.getDisplay( FValue )
end
else
begin
nt := FName;
KFloatToString(FTextBuf,FValue);
vt := FTextBuf;
end;
{ bar }
if w > 0 then
begin
ACanvas.setFillColor(FBarColor);
ACanvas.fillRect(FRect.x,FRect.y,FRect.x+w-1,FRect.y2);
{ border }
//ACanvas.setDrawColor(FBorderColor);
//ACanvas.drawRect(FRect.x,FRect.y,FRect.x+w-1,FRect.y2);
end;
{ background }
if w < FRect.w then
begin
ACanvas.setFillColor(FBackColor);
ACanvas.fillRect(FRect.x+w,FRect.y,FRect.x2,FRect.y2);
end;
{ border }
//ACanvas.setDrawColor(FBorderColor);
//ACanvas.drawRect(FRect.x,FRect.y,FRect.x2,FRect.y2);
{ name }
if FDrawName then nt := FName;
ACanvas.setTextColor(FValueColor);
ACanvas.drawText(FRect.x+4,FRect.y,FRect.x2,FRect.y2,nt{FName}, kta_left);
{ value }
ACanvas.setTextColor(FValueColor);
ACanvas.drawText(FRect.x,FRect.y,FRect.x2-4,FRect.y2,vt{FTextBuf}, kta_right{center});
//end;
// inherited
end;
//----------------------------------------------------------------------
end.
|
unit Table;
interface
uses BaseObjects, Registrator, Classes, SysUtils, Forms;
type
TFrameClass = class of TFrame;
TRiccTable = class(TRegisteredIDObject)
private
FRusTableName: string;
FEditorClass: TFrameClass;
FCollection: TIDObjects;
protected
procedure AssignTo(Dest: TPersistent); override;
public
property RusTableName: string read FRusTableName write FRusTableName;
property Collection: TIDObjects read FCollection write FCollection;
property EditorClass: TFrameClass read FEditorClass write FEditorClass;
function Update(ACollection: TIDObjects = nil): integer; override;
function List(AListOption: TListOption = loBrief): string; override;
constructor Create(ACollection: TIDObjects); override;
destructor Destroy; override;
end;
TRICCTables = class(TRegisteredIDObjects)
private
function GetItems(Index: integer): TRICCTable;
public
function RiccTableByName(AName: string): TRiccTable;
procedure BindToCollection(ADictTableName: string; ACollection: TIDObjects; AEditorClass: TFrameClass);
property Items[Index: integer]: TRICCTable read GetItems;
constructor Create; override;
end;
TRICCDicts = class(TRICCTables)
public
procedure Reload; override;
end;
TRICCAttribute = class (TRegisteredIDObject)
private
FRusAttributeName:string;
public
property RusAttributeName:string read FRusAttributeName write FRusAttributeName;
function List(AListOption: TListOption = loBrief): string; override;
constructor Create(ACollection: TIDObjects); override;
end;
TRICCAttributes = class (TRegisteredIDObjects)
private
function GetItems(Index: Integer): TRICCAttribute;
public
property Items[Index: Integer]: TRICCAttribute read GetItems;
constructor Create; override;
end;
implementation
uses Facade, TablePoster;
{ TRiccTable }
procedure TRiccTable.AssignTo(Dest: TPersistent);
begin
inherited;
(Dest as TRiccTable).RusTableName := RusTableName;
end;
constructor TRiccTable.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'таблица РБЦГИ';
end;
destructor TRiccTable.Destroy;
begin
inherited;
end;
function TRiccTable.List(AListOption: TListOption): string;
begin
if trim(RusTableName) <> '' then
Result := RusTableName + '[' + Name + ']'
else
Result := Name;
end;
function TRiccTable.Update(ACollection: TIDObjects): integer;
begin
Result := inherited Update;
end;
{ TRICCTables }
procedure TRICCTables.BindToCollection(ADictTableName: string;
ACollection: TIDObjects; AEditorClass: TFrameClass);
var dict: TRiccTable;
begin
Assert(Assigned(ACollection), 'Для справочника ' + ADictTableName + ' не задана коллекция');
dict := RiccTableByName(ADictTableName);
Assert(Assigned(dict), 'в списке справочников отсутствует искомый справочник ' + ADictTableName);
dict.RusTableName := ADictTableName;
dict.EditorClass := AEditorClass;
dict.Collection := ACollection;
end;
constructor TRICCTables.Create;
begin
inherited;
FObjectClass := TRiccTable;
Poster := TMainFacade.GetInstance.DataPosterByClassType[TRiccTableDataPoster];
end;
function TRICCTables.GetItems(Index: integer): TRICCTable;
begin
Result := inherited Items[Index] as TRiccTable;
end;
function TRICCTables.RiccTableByName(AName: string): TRiccTable;
begin
Result := GetItemByName(AName) as TRiccTable;
end;
{ TRICCDicts }
procedure TRICCDicts.Reload;
begin
Reload('NUM_TABLE_TYPE = 2');
end;
{ TRICCAttribute }
constructor TRICCAttribute.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Аттрибут РЦБГИ';
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TRICCAttributeDataPoster];
end;
function TRICCAttribute.List(AListOption: TListOption): string;
begin
if trim(RusAttributeName) <> '' then
Result := RusAttributeName + '[' + Name + ']'
else
Result := Name;
end;
{ TRICCAttributes }
constructor TRICCAttributes.Create;
begin
inherited;
FObjectClass := TRICCAttribute;
Poster := TMainFacade.GetInstance.DataPosterByClassType[TRICCAttributeDataPoster];
end;
function TRICCAttributes.GetItems(Index: Integer): TRICCAttribute;
begin
Result := inherited Items[Index] as TRICCAttribute;
end;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit dbcbr.database.compare;
interface
uses
SysUtils,
Classes,
dbebr.factory.interfaces,
dbcbr.metadata.db.factory,
dbcbr.database.factory;
type
TDatabaseCompare = class(TDatabaseFactory)
protected
FAutoManager: Boolean;
FConnMaster: IDBConnection;
FConnTarget: IDBConnection;
FMetadataMaster: TMetadataDBAbstract;
FMetadataTarget: TMetadataDBAbstract;
procedure ExtractDatabase; override;
procedure ExecuteDDLCommands; override;
public
constructor Create(AConnMaster, AConnTarget: IDBConnection); overload;
destructor Destroy; override;
end;
implementation
uses
dbcbr.ddl.commands;
{ TDatabaseCompare }
constructor TDatabaseCompare.Create(AConnMaster, AConnTarget: IDBConnection);
begin
FModelForDatabase := False;
FConnMaster := AConnMaster;
FConnMaster.Connect;
if not FConnMaster.IsConnected then
raise Exception.Create('Não foi possivel fazer conexão com o banco de dados Master');
FConnTarget := AConnTarget;
FConnTarget.Connect;
if not FConnTarget.IsConnected then
raise Exception.Create('Não foi possivel fazer conexão com o banco de dados Target');
inherited Create(AConnMaster.GetDriverName);
FMetadataMaster := TMetadataDBFactory.Create(Self, AConnMaster);
FMetadataTarget := TMetadataDBFactory.Create(Self, AConnTarget);
end;
destructor TDatabaseCompare.Destroy;
begin
FMetadataMaster.Free;
FMetadataTarget.Free;
inherited;
end;
procedure TDatabaseCompare.ExecuteDDLCommands;
var
LDDLCommand: TDDLCommand;
LCommand: string;
begin
inherited;
if FCommandsAutoExecute then
FConnTarget.StartTransaction;
try
try
for LDDLCommand in FDDLCommands do
begin
LCommand := LDDLCommand.BuildCommand(FGeneratorCommand);
if Length(LCommand) > 0 then
if FCommandsAutoExecute then
FConnTarget.AddScript(LCommand);
end;
if FConnTarget.InTransaction then
begin
FConnTarget.ExecuteScripts;
FConnTarget.Commit;
end;
except
on E: Exception do
begin
if FConnTarget.InTransaction then
FConnTarget.Rollback;
raise Exception.Create('DBCBr Command : [' + LDDLCommand.Warning + '] - ' + E.Message + sLineBreak +
'Script : "' + LCommand + '"');
end;
end;
finally
FConnMaster.Disconnect;
FConnTarget.Disconnect;
end;
end;
procedure TDatabaseCompare.ExtractDatabase;
begin
inherited;
// Extrai todo metadata com base nos modelos existentes
FMetadataMaster.ExtractMetadata(FCatalogMaster);
// Extrai todo metadata com base banco de dados acessado
FMetadataTarget.ExtractMetadata(FCatalogTarget);
end;
end.
|
unit FHIR.Support.Signatures;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
{
Digital Signature support for FHIR Server
introduction:
This is written to support digital signatures in the FHIR server, but
it can be used elsewhere too. Dependencies:
- Indy 10
- the support library for FHIR Server
It should compile and work under any unicode version of delphi, but
may be very fragile against changes to openXML. It's currently
developed and tested using XE5
About XML:
The hardest part of digital signatures is actually XML canonicalization.
You can't use MS-XML for this - it's too loose with the XML data. Instead,
this source uses the openXML provider. You can't change this here; You
can use ms-xml elsewhere, but not in here. This is why the interface
is entirely binary, and not based on a DOM.
OpenSSL
Tested against openSSL 1.0.1g. These interfaces are stable, but you shouldn't
use anything older than this anyway. note: you must have deployment infrastructure
for keeping up with openSSL bug changes. You have to initialise OpenSSL correctly
before using:
LoadEAYExtensions;
ERR_load_crypto_strings;
OpenSSL_add_all_algorithms;
Since these only need to be done once, this object doesn't do them
Certificates
you have to generate certificates using openSSL or equivalent, and refer
to them here. You have to nominate a method (DSA/RSA) which matches the
certificate you nominate
}
uses
SysUtils, Classes, {$IFNDEF VER260} System.NetEncoding, {$ENDIF}
IdHashSHA, IdGlobal,
FHIR.Support.Utilities, FHIR.Support.Stream,
FHIR.Support.Base, FHIR.Support.Collections,
FHIR.Support.MXml, FHIR.Support.Xml,
IdSSLOpenSSLHeaders, FHIR.Support.Certs, FHIR.Web.Fetcher;
Const
NS_DS = 'http://www.w3.org/2000/09/xmldsig#';
Type
TSignatureMethod = (sdXmlDSASha1, sdXmlRSASha1, sdXmlDSASha256, sdXmlRSASha256);
TDigitalSignatureReference = class (TFslObject)
private
FUrl: String;
FTransforms: TStringList;
FContent: TBytes;
public
constructor Create; override;
destructor Destroy; override;
property url: String read FUrl write FUrl;
property transforms : TStringList read FTransforms;
property content : TBytes read FContent write FContent;
end;
TDigitalSignatureReferenceList = class (TFslObjectList)
private
function getReference(i: integer): TDigitalSignatureReference;
protected
function ItemClass : TFslObjectClass; override;
public
property reference[i : integer] : TDigitalSignatureReference read getReference; default;
end;
TKeyInfo = class (TFslObject)
private
dsa : PDSA;
rsa : PRSA;
function checkSignatureRSA(digest, signature : TBytes; method : TSignatureMethod) : boolean;
function checkSignatureDSA(digest, signature : TBytes; method : TSignatureMethod) : boolean;
function checkSignature(digest, signature : TBytes; method : TSignatureMethod) : boolean;
public
destructor Destroy; override;
end;
TSignatureLocationFinderMethod = reference to function (doc : TMXmlDocument) : TMXmlElement;
TDigitalSigner = class (TFslObject)
private
FPublicKey: AnsiString;
FPrivateKey: AnsiString;
FKeyPassword: AnsiString;
// FCertFile: AnsiString;
// attribute / enum methods
function canoncalizationSet(uri : String) : TXmlCanonicalisationMethodSet;
function signatureMethod(uri : String) : TSignatureMethod;
function digestAlgorithmForMethod(method: TSignatureMethod): String;
function signAlgorithmForMethod(method: TSignatureMethod): String;
// xml routines
function loadXml(source: TBytes) : TMXmlDocument;
function canonicaliseXml(method : TXmlCanonicalisationMethodSet; source : TBytes; var dom : TMXmlDocument) : TBytes; overload;
function canonicaliseXml(method : TXmlCanonicalisationMethodSet; dom : TMXmlElement) : TBytes; overload;
function canonicaliseXml(method : TXmlCanonicalisationMethodSet; dom : TMXmlDocument) : TBytes; overload;
function canonicaliseXml(method : TXmlCanonicalisationMethodSet; source : TBytes) : TBytes; overload;
// digest and signing routine
function digest(source : TBytes; method : TSignatureMethod) : TBytes;
function digestSHA1(source : TBytes) : TBytes;
function digestSHA256(source : TBytes) : TBytes;
procedure checkDigest(ref : TMXmlElement; doc : TMXmlDocument);
function sign(src: TBytes; method: TSignatureMethod): TBytes;
function signDSA(src: TBytes; method: TSignatureMethod): TBytes;
function signRSA(src: TBytes; method: TSignatureMethod): TBytes;
// key/ certificate management routines
function LoadKeyInfo(sig : TMXmlElement) : TKeyInfo;
function loadRSAKey: PRSA;
function loadDSAKey: PDSA;
procedure AddKeyInfo(sig: TMXmlElement; method : TSignatureMethod);
// source content management
function resolveReference(url : string) : TBytes;
public
Constructor Create; override;
// certificate files, for signing
Property PublicKey : AnsiString read FPublicKey write FPublicKey;
Property PrivateKey : AnsiString read FPrivateKey write FPrivateKey;
Property KeyPassword : AnsiString read FKeyPassword write FKeyPassword;
// classic XML Enveloped Signature
function signEnveloped(xml : TBytes; method : TSignatureMethod; keyinfo : boolean) : TBytes; overload;
function signEnveloped(xml : TBytes; finder : TSignatureLocationFinderMethod; method : TSignatureMethod; keyinfo : boolean) : TBytes; overload;
function signDetached(xml : TBytes; refUrl : String; method : TSignatureMethod; canonicalization : string; keyinfo : boolean) : TBytes; overload;
function signExternal(references : TDigitalSignatureReferenceList; method : TSignatureMethod; keyinfo : boolean) : TBytes;
function verifySignature(xml : TBytes) : boolean;
end;
implementation
procedure check(test: boolean; failmsg: string);
begin
if not test then
raise ELibraryException.create(failmsg);
end;
function StripLeadingZeros(bytes : AnsiString) : AnsiString;
var
i : integer;
begin
i := 1;
while (i < length(bytes)) and (bytes[i] = #0) do
inc(i);
result := copy(bytes, i, length(bytes));
end;
function BytesPairToAsn1(bytes : TBytes) : TBytes;
var
r, s : AnsiString;
begin
r := StripLeadingZeros(copy(BytesAsAnsiString(bytes), 1, length(bytes) div 2));
s := StripLeadingZeros(copy(BytesAsAnsiString(bytes), length(bytes) div 2+1, length(bytes) div 2));
if (r[1] >= #$80) then
Insert(#0, r, 1);
if (s[1] >= #$80) then
Insert(#0, s, 1);
result := AnsiStringAsBytes(ansichar($30)+ansichar(4+length(r)+length(s))+ansichar(02)+ansichar(length(r))+r+ansichar(02)+ansichar(length(s))+s);
end;
function asn1SigToBytePair(asn1 : TBytes) : TBytes;
var
sv, r, s : AnsiString;
l : integer;
begin
sv := BytesAsAnsiString(asn1);
if sv[1] <> #$30 then
raise ELibraryException.create('Error 1 reading asn1 DER signature');
if ord(sv[2]) <> length(sv)-2 then
raise ELibraryException.create('Error 2 reading asn1 DER signature');
delete(sv, 1, 2);
if sv[1] <> #$02 then
raise ELibraryException.create('Error 3 reading asn1 DER signature');
r := copy(sv, 3, ord(sv[2]));
delete(sv, 1, length(r)+2);
if sv[1] <> #$02 then
raise ELibraryException.create('Error 4 reading asn1 DER signature');
s := copy(sv, 3, ord(sv[2]));
delete(sv, 1, length(s)+2);
if length(sv) <> 0 then
raise ELibraryException.create('Error 5 reading asn1 DER signature');
if (r[2] >= #$80) and (r[1] = #0) then
delete(r, 1, 1);
if (s[2] >= #$80) and (s[1] = #0) then
delete(s, 1, 1);
if (length(r) <= 20) and (length(s) <= 20) then
l := 20
else
l := 32;
while length(r) < l do
insert(#0, r, 1);
while length(s) < l do
insert(#0, s, 1);
result := AnsiStringAsBytes(r+s);
end;
{ TDigitalSigner }
function TDigitalSigner.canoncalizationSet(uri : String) : TXmlCanonicalisationMethodSet;
begin
if uri = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315' then
result := [xcmCanonicalise]
else if uri = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments' then
result := [xcmCanonicalise, xcmComments]
else
raise ELibraryException.create('Canonicalization Method '+uri+' is not supported');
end;
function TDigitalSigner.canonicaliseXml(method: TXmlCanonicalisationMethodSet; source: TBytes): TBytes;
var
xb : TFslXmlBuilder;
dom : TMXmlDocument;
begin
dom := loadXml(source);
try
xb := TFslXmlBuilder.Create;
try
xb.Canonicalise := method;
xb.Start;
xb.WriteXml(dom.docElement);
xb.Finish;
result := TEncoding.UTF8.GetBytes(xb.Build);
finally
xb.Free;
end;
finally
dom.Free;
end;
end;
function TDigitalSigner.canonicaliseXml(method : TXmlCanonicalisationMethodSet; source: TBytes; var dom : TMXmlDocument): TBytes;
var
xb : TFslXmlBuilder;
begin
dom := loadXml(source);
xb := TFslXmlBuilder.Create;
try
xb.Canonicalise := method;
xb.Start;
xb.WriteXml(dom.docElement);
xb.Finish;
result := TEncoding.UTF8.GetBytes(xb.Build);
finally
xb.Free;
end;
end;
function TDigitalSigner.canonicaliseXml(method : TXmlCanonicalisationMethodSet; dom: TMXmlElement): TBytes;
var
xb : TFslXmlBuilder;
begin
xb := TFslXmlBuilder.Create;
try
xb.Canonicalise := method;
xb.Start;
xb.WriteXml(dom);
xb.Finish;
result := TEncoding.UTF8.GetBytes(xb.Build);
finally
xb.Free;
end;
end;
function TDigitalSigner.canonicaliseXml(method : TXmlCanonicalisationMethodSet; dom: TMXMLDocument): TBytes;
var
xb : TFslXmlBuilder;
begin
xb := TFslXmlBuilder.Create;
try
xb.Canonicalise := method;
xb.Start;
xb.WriteXml(dom);
xb.Finish;
result := TEncoding.UTF8.GetBytes(xb.Build);
finally
xb.Free;
end;
end;
procedure TDigitalSigner.checkDigest(ref: TMXmlElement; doc: TMXMLDocument);
var
bytes, digest : TBytes;
transforms, transform : TMXmlElement;
bEnv : boolean;
i : integer;
begin
//Obtain the data object to be digested. (For example, the signature application may dereference the URI and execute Transforms provided by the signer in the Reference element, or it may obtain the content through other means such as a local cache.)
if ref.attribute['URI'] = '' then
bytes := canonicaliseXml([xcmCanonicalise], doc.docElement)
else
bytes := resolveReference(ref.attribute['URI']);
BytesToFile(bytes, 'c:\temp\cand.xml');
// check the transforms
bEnv := false;
transforms := ref.elementNS(NS_DS, 'Transforms');
if transforms <> nil then
for i := 0 to transforms.Children.Count - 1 do
begin
transform := transforms.Children[i];
if (transform.NodeType = ntElement) and (transform.Name = 'Transform') then
if transform.attribute['Algorithm'] = 'http://www.w3.org/2000/09/xmldsig#enveloped-signature' then
bEnv := true
else
raise ELibraryException.create('Transform '+transform.attribute['Algorithm']+' is not supported');
end;
if (doc <> nil) and not bEnv then
raise ELibraryException.create('Reference Transform is not http://www.w3.org/2000/09/xmldsig#enveloped-signature');
//Digest the resulting data object using the DigestMethod specified in its Reference specification.
if ref.elementNS(NS_DS, 'DigestMethod').attribute['Algorithm'] = 'http://www.w3.org/2000/09/xmldsig#sha1' then
bytes := digestSHA1(bytes)
else if ref.elementNS(NS_DS, 'DigestMethod').attribute['Algorithm'] = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' then
bytes := digestSHA256(bytes)
else
raise ELibraryException.create('Unknown Digest method '+ref.elementNS(NS_DS, 'DigestMethod').attribute['Algorithm']);
digest := decodeBase64(ref.elementNS(NS_DS, 'DigestValue').Text);
//Compare the generated digest value against DigestValue in the SignedInfo Reference; if there is any mismatch, validation fails.
if not SameBytes(bytes, digest) then
raise ELibraryException.create('Digest mismatch on reference '+ref.attribute['URI']);
end;
constructor TDigitalSigner.create;
begin
inherited;
LoadEAYExtensions;
ERR_load_crypto_strings;
OpenSSL_add_all_algorithms;
end;
function TDigitalSigner.verifySignature(xml: TBytes): boolean;
var
doc : TMXmlDocument;
sig, si : TMXmlElement;
can, v : TBytes;
key : TKeyInfo;
i : integer;
begin
doc := loadXml(xml);
try
if (doc.Name = 'Signature') and (doc.NamespaceURI = NS_DS) then
sig := doc.docElement
else
sig := doc.docElement.elementNS(NS_DS, 'Signature');
if (sig = nil) then
raise ELibraryException.create('Signature not found');
si := sig.elementNS(NS_DS, 'SignedInfo');
if (si = nil) then
raise ELibraryException.create('SignedInfo not found');
if (sig <> doc) then
doc.docElement.Children.Remove(sig)
else
doc := nil;
//k. now we follow the method:
// 1. Canonicalize the SignedInfo element based on the CanonicalizationMethod in SignedInfo.
si.Name := '';
si.LocalName := 'SignedInfo';
si.NamespaceURI := NS_DS;
can := canonicaliseXml(canoncalizationSet(si.elementNS(NS_DS, 'CanonicalizationMethod').attribute['Algorithm']), si);
BytesToFile(can, 'c:\temp\can.xml');
// 2. For each Reference in SignedInfo:
for i := 0 to si.children.Count - 1 do
if (si.children[i].NodeType = ntElement) and (si.children[i].Name = 'Reference') then
checkDigest(si.children[i], doc);
// 3. Obtain the keying information from KeyInfo or from an external source.
key := LoadKeyInfo(sig);
try
// 4. Obtain the canonical form of the SignatureMethod using the CanonicalizationMethod and use the result (and previously obtained KeyInfo) to confirm the SignatureValue over the SignedInfo element.
v := decodeBase64(sig.element('SignatureValue').text);
result := key.checkSignature(can, v, signatureMethod(si.elementNS(NS_DS, 'SignatureMethod').attribute['Algorithm']));
finally
key.Free;
end;
finally
doc.free;
end;
end;
function TKeyInfo.checkSignature(digest, signature: TBytes; method: TSignatureMethod) : boolean;
begin
if method in [sdXmlDSASha1, sdXmlDSASha256] then
result := checkSignatureDSA(digest, signature, method)
else
result := checkSignatureRSA(digest, signature, method);
end;
function TKeyInfo.checkSignatureRSA(digest, signature: TBytes; method: TSignatureMethod) : boolean;
var
ctx : EVP_MD_CTX;
e: integer;
pkey: PEVP_PKEY;
begin
pkey := EVP_PKEY_new;
try
check(EVP_PKEY_set1_RSA(pkey, rsa) = 1, 'openSSL EVP_PKEY_set1_RSA failed');
// 2. do the signing
EVP_MD_CTX_init(@ctx);
try
if method = sdXmlRSASha1 then
EVP_VerifyInit(@ctx, EVP_sha1)
else
EVP_VerifyInit(@ctx, EVP_sha256);
check(EVP_VerifyUpdate(@ctx, @digest[0], Length(digest)) = 1, 'openSSL EVP_VerifyUpdate failed');
e := EVP_VerifyFinal(@ctx, @signature[0], length(signature), pKey);
result := e = 1;
finally
EVP_MD_CTX_cleanup(@ctx);
end;
finally
EVP_PKEY_free(pKey);
end;
end;
function TKeyInfo.checkSignatureDSA(digest, signature: TBytes; method: TSignatureMethod) : Boolean;
var
ctx : EVP_MD_CTX;
e: integer;
pkey: PEVP_PKEY;
err : Array [0..250] of ansichar;
m : String;
asn1 : TBytes;
begin
pkey := EVP_PKEY_new;
try
check(EVP_PKEY_set1_DSA(pkey, dsa) = 1, 'openSSL EVP_PKEY_set1_RSA failed');
// 2. do the signing
EVP_MD_CTX_init(@ctx);
try
if method = sdXmlDSASha1 then
EVP_VerifyInit(@ctx, EVP_sha1)
else
EVP_VerifyInit(@ctx, EVP_sha256);
check(EVP_VerifyUpdate(@ctx, @digest[0], Length(digest)) = 1, 'openSSL EVP_VerifyUpdate failed');
asn1 := BytesPairToAsn1(signature);
e := EVP_VerifyFinal(@ctx, @asn1[0], length(asn1), pKey);
if (e = -1) then
begin
m := '';
e := ERR_get_error;
repeat
ERR_error_string(e, @err);
m := m + inttohex(e, 8)+' ('+String(err)+')'+#13#10;
e := ERR_get_error;
until e = 0;
raise ELibraryException.create('OpenSSL Error verifying signature: '+#13#10+m);
end
else
result := e = 1;
finally
EVP_MD_CTX_cleanup(@ctx);
end;
finally
EVP_PKEY_free(pKey);
end;
end;
destructor TKeyInfo.Destroy;
begin
if dsa <> nil then
DSA_Free(dsa);
if rsa <> nil then
RSA_free(rsa);
inherited;
end;
function TDigitalSigner.digest(source: TBytes; method: TSignatureMethod): TBytes;
begin
if method in [sdXmlDSASha256, sdXmlRSASha256] then
result := digestSHA256(source)
else
result := digestSHA1(source);
end;
function TDigitalSigner.digestSHA1(source: TBytes): TBytes;
var
hash : TIdHashSHA1;
begin
hash := TIdHashSHA1.Create;
try
result := idb(hash.HashBytes(idb(source)));
finally
hash.Free;
end;
end;
function TDigitalSigner.digestSHA256(source: TBytes): TBytes;
var
hash : TIdHashSHA256;
b : TIdBytes;
begin
hash := TIdHashSHA256.Create;
try
b := idb(source);
b := hash.HashBytes(b);
result := idb(b);
finally
hash.Free;
end;
end;
function TDigitalSigner.loadRSAKey: PRSA;
var
bp: pBIO;
fn, pp: PAnsiChar;
pk: PRSA;
begin
fn := PAnsiChar(FPrivateKey);
pp := PAnsiChar(FKeyPassword);
bp := BIO_new(BIO_s_file());
BIO_read_filename(bp, fn);
pk := nil;
result := PEM_read_bio_RSAPrivateKey(bp, @pk, nil, pp);
if result = nil then
raise ELibraryException.create('Private key failure.' + GetSSLErrorMessage);
end;
function TDigitalSigner.loadDSAKey: PDSA;
var
bp: pBIO;
fn, pp: PAnsiChar;
pk: PDSA;
begin
fn := PAnsiChar(FPrivateKey);
pp := PAnsiChar(FKeyPassword);
bp := BIO_new(BIO_s_file());
BIO_read_filename(bp, fn);
pk := nil;
result := PEM_read_bio_DSAPrivateKey(bp, @pk, nil, pp);
if result = nil then
raise ELibraryException.create('Private key failure.' + GetSSLErrorMessage);
end;
function TDigitalSigner.sign(src : TBytes; method: TSignatureMethod) : TBytes;
begin
if method in [sdXmlDSASha1, sdXmlDSASha256] then
result := signDSA(src, method)
else
result := signRSA(src, method);
end;
function TDigitalSigner.signDSA(src : TBytes; method: TSignatureMethod) : TBytes;
var
pkey: PEVP_PKEY;
dkey: PDSA;
ctx : EVP_MD_CTX;
len : integer;
asn1 : TBytes;
begin
// 1. Load the RSA private Key from FKey
dkey := loadDSAKey;
try
pkey := EVP_PKEY_new;
try
check(EVP_PKEY_set1_DSA(pkey, dkey) = 1, 'openSSL EVP_PKEY_set1_DSA failed');
// 2. do the signing
SetLength(asn1, EVP_PKEY_size(pkey));
EVP_MD_CTX_init(@ctx);
try
if method = sdXmlDSASha256 then
EVP_SignInit(@ctx, EVP_sha256)
else
EVP_SignInit(@ctx, EVP_sha1);
check(EVP_SignUpdate(@ctx, @src[0], Length(src)) = 1, 'openSSL EVP_SignUpdate failed');
check(EVP_SignFinal(@ctx, @asn1[0], len, pKey) = 1, 'openSSL EVP_SignFinal failed');
SetLength(asn1, len);
result := asn1SigToBytePair(asn1);
finally
EVP_MD_CTX_cleanup(@ctx);
end;
finally
EVP_PKEY_free(pKey);
end;
finally
DSA_free(dkey);
end;
end;
function TDigitalSigner.signRSA(src : TBytes; method: TSignatureMethod) : TBytes;
var
pkey: PEVP_PKEY;
rkey: PRSA;
ctx : EVP_MD_CTX;
keysize : integer;
len : integer;
begin
// 1. Load the RSA private Key from FKey
rkey := loadRSAKey;
try
pkey := EVP_PKEY_new;
try
check(EVP_PKEY_set1_RSA(pkey, rkey) = 1, 'openSSL EVP_PKEY_set1_RSA failed');
// 2. do the signing
keysize := EVP_PKEY_size(pkey);
SetLength(result, keysize);
EVP_MD_CTX_init(@ctx);
try
if method = sdXmlRSASha256 then
EVP_SignInit(@ctx, EVP_sha256)
else
EVP_SignInit(@ctx, EVP_sha1);
check(EVP_SignUpdate(@ctx, @src[0], Length(src)) = 1, 'openSSL EVP_SignUpdate failed');
check(EVP_SignFinal(@ctx, @result[0], len, pKey) = 1, 'openSSL EVP_SignFinal failed');
SetLength(result, len);
finally
EVP_MD_CTX_cleanup(@ctx);
end;
finally
EVP_PKEY_free(pKey);
end;
finally
RSA_free(rkey);
end;
end;
function TDigitalSigner.signAlgorithmForMethod(method : TSignatureMethod) : String;
begin
case method of
sdXmlDSASha1 : result := 'http://www.w3.org/2000/09/xmldsig#dsa-sha1';
sdXmlRSASha1 : result := 'http://www.w3.org/2000/09/xmldsig#rsa-sha1';
sdXmlDSASha256 : result := 'http://www.w3.org/2000/09/xmldsig#dsa-sha256';
sdXmlRSASha256 : result := 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256';
else
raise ELibraryException.create('unknown method');
end;
end;
function TDigitalSigner.signDetached(xml : TBytes; refURL : String; method : TSignatureMethod; canonicalization : string; keyinfo : boolean) : TBytes;
var
can, dig : TBytes;
dom : TMXmlDocument;
sig, si, ref, trns: TMXmlElement;
s : String;
begin
can := canonicaliseXml([xcmCanonicalise], xml);
dom := TMXmlDocument.CreateNS(ntDocument, NS_DS, 'Signature');
try
sig := dom.docElement;
sig.attribute['xmlns'] := NS_DS;
si := sig.addElementNS(NS_DS, 'SignedInfo');
if canonicalization <> '' then
si.addElementNS(NS_DS, 'CanonicalizationMethod').attribute['Algorithm'] := canonicalization
else
si.addElementNS(NS_DS, 'CanonicalizationMethod').attribute['Algorithm'] := 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
si.addElementNS(NS_DS, 'SignatureMethod').attribute['Algorithm'] := signAlgorithmForMethod(method);
ref := si.addElementNS(NS_DS, 'Reference');
if (refUrl <> '') then
ref.attribute['URI'] := refUrl;
trns := ref.addElementNS(NS_DS, 'Transforms');
trns.addElementNS(NS_DS, 'Transform').attribute['Algorithm'] := 'http://www.w3.org/2000/09/xmldsig#enveloped-signature';
ref.addElementNS(NS_DS, 'DigestMethod').attribute['Algorithm'] := digestAlgorithmForMethod(method);
dig := digest(can, method); // the method doesn't actually apply to this, but we figure that if the method specifies sha256, then it should be used here
ref.addElementNS(NS_DS, 'DigestValue').addText(String(EncodeBase64(dig)));
can := canonicaliseXml([xcmCanonicalise],si);
dig := sign(can, method);
s := string(EncodeBase64(dig));
sig.addElementNS(NS_DS, 'SignatureValue').addText(s);
if keyinfo then
AddKeyInfo(sig, method);
s := dom.ToXml(false, true);
result := TEncoding.UTF8.GetBytes(s);
finally
dom.Free;
end;
end;
function TDigitalSigner.digestAlgorithmForMethod(method : TSignatureMethod) : String;
begin
case method of
sdXmlDSASha256 : result := 'http://www.w3.org/2000/09/xmldsig#sha256';
sdXmlRSASha256 : result := 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256';
else
result := 'http://www.w3.org/2000/09/xmldsig#sha1';
end;
end;
function TDigitalSigner.signEnveloped(xml: TBytes; method : TSignatureMethod; keyinfo : boolean): TBytes;
begin
result := signEnveloped(xml, function (doc : TMXmlDocument) : TMXmlElement begin result := doc.docElement end, method, keyInfo);
end;
function TDigitalSigner.signEnveloped(xml: TBytes; finder : TSignatureLocationFinderMethod; method : TSignatureMethod; keyinfo : boolean): TBytes;
var
can, dig : TBytes;
dom : TMXmlDocument;
sig, si, ref, trns: TMXmlElement;
s : String;
begin
can := canonicaliseXml([xcmCanonicalise], xml, dom);
try
sig := finder(dom).addElementNS(NS_DS, 'Signature');
sig.attribute['xmlns'] := NS_DS;
si := sig.addElementNS(NS_DS, 'SignedInfo');
si.addElementNS(NS_DS, 'CanonicalizationMethod').attribute['Algorithm'] := 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
si.addElementNS(NS_DS, 'SignatureMethod').attribute['Algorithm'] := signAlgorithmForMethod(method);
ref := si.addElementNS(NS_DS, 'Reference');
ref.attribute['URI'] := '';
trns := ref.addElementNS(NS_DS, 'Transforms');
trns.addElementNS(NS_DS, 'Transform').attribute['Algorithm'] := 'http://www.w3.org/2000/09/xmldsig#enveloped-signature';
ref.addElementNS(NS_DS, 'DigestMethod').attribute['Algorithm'] := digestAlgorithmForMethod(method);
dig := digest(can, method); // the method doesn't actually apply to this, but we figure that if the method specifies sha256, then it should be used here
ref.addElementNS(NS_DS, 'DigestValue').addText(String(EncodeBase64(dig)));
can := canonicaliseXml([xcmCanonicalise],si);
dig := sign(can, method);
s := string(EncodeBase64(dig));
sig.addElementNS(NS_DS, 'SignatureValue').addText(s);
if keyinfo then
AddKeyInfo(sig, method);
s := dom.ToXml(false, true);
result := TEncoding.UTF8.GetBytes(s);
finally
dom.Free;
end;
end;
function bn2Base64(p : PBigNum) : String;
var
b : TBytes;
begin
setlength(b, BN_num_bytes(p));
BN_bn2bin(p, @b[0]);
result := String(EncodeBase64(b));
end;
procedure TDigitalSigner.AddKeyInfo(sig : TMXmlElement; method : TSignatureMethod);
var
kv: TMXmlElement;
dkey : PDSA;
rkey : PRSA;
begin
if method in [sdXmlDSASha1, sdXmlDSASha256] then
begin
kv := sig.AddElement('KeyInfo').AddElement('KeyValue').AddElement('DSAKeyValue');
dkey := LoadDSAKey;
try
kv.AddElement('P').AddText(bn2Base64(dkey.p));
kv.AddElement('Q').AddText(bn2Base64(dkey.q));
kv.AddElement('G').AddText(bn2Base64(dkey.g));
kv.AddElement('Y').AddText(bn2Base64(dkey.pub_key));
finally
DSA_free(dKey);
end;
end
else
begin
kv := sig.AddElement('KeyInfo').AddElement('KeyValue').AddElement('RSAKeyValue');
rkey := loadRSAKey;
try
kv.AddElement('Modulus').AddText(bn2Base64(rkey.n));
kv.AddElement('Exponent').AddText(bn2Base64(rkey.e));
finally
RSA_free(rkey);
end;
end;
end;
function TDigitalSigner.signExternal(references: TDigitalSignatureReferenceList; method : TSignatureMethod; keyinfo : boolean): TBytes;
var
doc : TMXMLDocument;
sig, si, ref, trns : TMXmlElement;
i : integer;
reference : TDigitalSignatureReference;
s, t : String;
can, dig : TBytes;
begin
doc := TMXMLDocument.Create();
sig := doc.addElementNS(NS_DS, 'Signature');
sig.attribute['xmlns'] := NS_DS;
si := sig.AddElement('SignedInfo');
si.AddElement('CanonicalizationMethod').attribute['Algorithm'] := 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
si.AddElement('SignatureMethod').attribute['Algorithm'] := signAlgorithmForMethod(method);
for i := 0 to references.Count - 1 do
begin
reference := references[i];
ref := si.AddElement('Reference');
ref.attribute['URI'] := reference.URL;
if reference.transforms.count > 0 then
begin
trns := ref.AddElement('Transforms');
for t in reference.transforms do
trns.AddElement('Transform').attribute['Algorithm'] := t;
end;
ref.AddElement('DigestMethod').attribute['Algorithm'] := digestAlgorithmForMethod(method);
dig := digest(reference.content, method);
ref.AddElement('DigestValue').Text := String(EncodeBase64(dig));
end;
can := canonicaliseXml([xcmCanonicalise],si);
dig := sign(can, method);
s := EncodeBase64(dig);
sig.AddElement('SignatureValue').Text := s;
if keyinfo then
AddKeyInfo(sig, method);
result := canonicaliseXml([xcmCanonicalise], sig); // don't need to canonicalise the whole lot, but why not?
end;
function TDigitalSigner.LoadKeyInfo(sig: TMXmlElement): TKeyInfo;
var
ki, kv, kd : TMXmlElement;
v : TBytes;
// p : pansichar;
begin
result := TKeyInfo.Create;
try
ki := sig.elementNS(NS_DS, 'KeyInfo');
if ki = nil then
raise ELibraryException.create('No KeyInfo found in digital signature');
kv := ki.elementNS(NS_DS, 'KeyValue');
if kv = nil then
raise ELibraryException.create('No KeyValue found in digital signature');
kd := kv.elementNS(NS_DS, 'RSAKeyValue');
if kd <> nil then
begin
result.rsa := RSA_new;
v := DecodeBase64(kd.elementNS(NS_DS, 'Modulus').Text);
result.rsa.n := BN_bin2bn(@v[0], length(v), nil);
v := DecodeBase64(kd.elementNS(NS_DS, 'Exponent').Text);
result.rsa.e := BN_bin2bn(@v[0], length(v), nil);
end
else
begin
kd := kv.elementNS(NS_DS, 'DSAKeyValue');
if kd <> nil then
begin
result.dsa := DSA_new;
v := DecodeBase64(kd.elementNS(NS_DS, 'P').Text);
result.dsa.p := BN_bin2bn(@v[0], length(v), nil);
v := DecodeBase64(kd.elementNS(NS_DS, 'Q').Text);
result.dsa.q := BN_bin2bn(@v[0], length(v), nil);
v := DecodeBase64(kd.elementNS(NS_DS, 'G').Text);
result.dsa.g := BN_bin2bn(@v[0], length(v), nil);
v := DecodeBase64(kd.elementNS(NS_DS, 'Y').Text);
result.dsa.pub_key := BN_bin2bn(@v[0], length(v), nil);
// if elementNS(kd, 'X', NS_DS) <> nil then
// begin
// v := DecodeBase64(elementNS(kd, 'X', NS_DS).Text);
// result.dsa.priv_key := BN_bin2bn(@v[0], length(v), nil);
// end;
end
else
raise ELibraryException.create('No Key Info found');
end;
result.Link;
finally
result.Free;
end;
end;
function TDigitalSigner.loadXml(source: TBytes): TMXmlDocument;
begin
result := TMXmlParser.parse(source, [xpResolveNamespaces]);
end;
function TDigitalSigner.resolveReference(url: string): TBytes;
var
fetch : TInternetFetcher;
begin
fetch := TInternetFetcher.Create;
try
fetch.URL := URL;
fetch.Fetch;
result := fetch.Buffer.AsBytes;
finally
fetch.Free;
end;
end;
function TDigitalSigner.signatureMethod(uri: String): TSignatureMethod;
begin
if uri = 'http://www.w3.org/2000/09/xmldsig#dsa-sha1' then
result := sdXmlDSASha1
else if uri = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1' then
result := sdXmlRSASha1
else if uri = 'http://www.w3.org/2000/09/xmldsig#dsa-sha256' then
result := sdXmlDSASha256
else if uri = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' then
result := sdXmlRSASha256
else
raise ELibraryException.create('Unsupported signature method '+uri);
end;
{ TDigitalSignatureReferenceList }
function TDigitalSignatureReferenceList.getReference(i: integer): TDigitalSignatureReference;
begin
result := TDigitalSignatureReference(ObjectByIndex[i]);
end;
function TDigitalSignatureReferenceList.itemClass: TFslObjectClass;
begin
result := TDigitalSignatureReference;
end;
{ TDigitalSignatureReference }
constructor TDigitalSignatureReference.Create;
begin
inherited;
FTransforms := TStringList.Create;
end;
destructor TDigitalSignatureReference.Destroy;
begin
FTransforms.Free;
inherited;
end;
end.
|
program week4_stack;
uses crt;
const
max = 3;
type
stack = record
kode:array[1..max] of string;
judulcd : array [1 .. max] of string;
tahun : array [1 .. max] of integer;
top, bottom : 0 .. max;
end;
var
cd : stack;
i, pil : byte;
// --------- Function ---------------
function isEmpty(x : stack) : boolean;
begin
if x.top = 0 then
isEmpty := true
else
isEmpty := false;
end;
function isFull(x : stack) : boolean;
begin
if x.top = max then
isFull := true
else
isFull := false;
end;
// -------------- Procedure ------------------
procedure pushcd(var x : stack);
var
judulcd,kode : string; tahun : integer;ada:Boolean;
label ulang;
begin
writeln;
ulang:
ada:=false;
writeln('---- Push cd baru ke stack ----');
Write('masukkan kode cd : ');ReadLn(kode);
// validasei kode cd sudah ada atau belum
for i := x.top downto x.bottom do
begin
if kode =x.kode[x.top] then
begin
ada:=true;
WriteLn('kode cd sudah digunakan, ulangi input kode ! ');
ReadLn;
goto ulang;
end;
end;
// jika belum ada maka tambahkan cd
if ada = false then
begin
inc(x.top);
write('Masukan judulcd cd yang akan di push : '); readln(judulcd);
write('masukan tahun dibuat cd yang akan di push : '); readln(tahun);
x.kode[x.top] := kode;
x.judulcd[x.top] := judulcd;
x.tahun[x.top] := tahun;
writeln('cd berhasil di push');
end;
end;
procedure popcd(var x : stack);
var
ya : char;
begin
writeln('---- cd dari stack ----');
writeln('cd diposisi teratas adalah ', x.judulcd[x.top]);
write('yakin akan diambil <y/t> ? '); readln(ya);
if (ya = 'Y') or (ya = 'y') then
begin
writeln('cd dengan judulcd : ', x.judulcd[x.top] ,' diambil');
writeln('Tahun dibuat : ', x.tahun[x.top] ,' diambil');
dec(x.top);
writeln('Pop cd berhasil');
end
else
writeln('cd dengan judulcd : ', x.judulcd[x.top] ,' tahun dibuat ',
x.tahun[x.top] ,' batal diambil');
end;
procedure printcd(var x : stack);
begin
writeln('cd didalam stack');
writeln('------------------------------------------------------');
writeln('Posisi Kode Judulcd Tahun dibuat');
writeln('-------------------------------------------------------');
for i := x.top downto x.bottom do
writeln(i:3 ,' ',x.kode[i],' ', x.judulcd[i]:20 ,' ', x.tahun[i]:20);
writeln('-------------------------------------------------------');
writeln('Jumlah cd di stack = ', x.top ,' buah');
end;
procedure searchcd(x :stack);
var kode,ya:string;ada:Boolean;
label ulang;
begin
ulang:
ada:=False;
clrscr;
write('masukkan kode cd :');ReadLn(kode);
WriteLn;
WriteLn('Hasil Pencarian :');
for i:= x.top downto x.bottom do
begin
if kode = x.kode[i] then
begin
ada:=true;
WriteLn(' kode : ',x.kode[i],' , judul cd : ',x.judulcd[i],' , tahun cd dibuat : ',x.tahun[i]);
end;
end;
if ada=false then WriteLn(' data dengan kode : ',kode,' tidak ditemukan');
WriteLn;
Write('apakah mau mencari lagi ? y/t');readln(ya);
if (ya='y')or(ya='Y') then goto ulang
else WriteLn('keluar menu');
end;
begin
cd.top := 0;
cd.bottom := 1;
repeat
clrscr;
writeln('Stack cd');
writeln('1. Push cd');
writeln('2. Pop cd');
writeln('3. Cetak cd');
writeln('4. Search cd');
writeln('0. Selesai');
write('Pilih menu 0 - 4 : '); readln(pil);
case pil of
1: if isFull(cd) then
writeln('Stack penuh')
else
pushcd(cd);
2: if isEmpty(cd) then
writeln('Stack kosong')
else
popcd(cd);
3: if isEmpty(cd) then
writeln('Stack kosong')
else
printcd(cd);
4: if isEmpty(cd) then
writeln('Stack kosong')
else
searchcd(cd);
0: writeln('Terimakasih')
else
writeln('Pilihan Salah');
end;
readln;
until (pil = 0);
end. |
{$r+}
{$mode delphi}
function binary_search_less(const a:array of integer; v:integer):integer;
var
mid,hi,lo:integer;
begin
lo := -1;
hi := length(a);
while hi-lo > 1 do begin
mid := (lo+hi) div 2;
if a[mid] >= v then
hi:=mid
else
lo:=mid;
end;
exit(lo);
end;
function binary_search_greater(const a:array of integer; v:integer):integer;
var
mid,hi,lo:integer;
begin
lo := -1;
hi := length(a);
while hi-lo > 1 do begin
mid := (lo+hi) div 2;
if a[mid] <= v then
lo:=mid
else
hi:=mid;
end;
exit(hi);
end;
function count_occurrences(const a:array of integer; v:integer): integer;
var
start_index,finish_index:integer;
begin
start_index := binary_search_less(a, v);
finish_index := binary_search_greater(a, v);
exit(finish_index-start_index-1);
end;
var
n,i:integer;
a:array of integer;
begin
readln(n);
setLength(a,n);
for i:=low(a) to high(a) do begin
read(a[i]);
end;
while not seekEof do begin
read(n);
write(count_occurrences(a, n), ' ');
end;
end. |
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [VIEW_TRIBUTACAO_ICMS_CUSTOM]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit ViewTributacaoIcmsCustomVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils;
type
[TEntity]
[TTable('VIEW_TRIBUTACAO_ICMS_CUSTOM')]
TViewTributacaoIcmsCustomVO = class(TVO)
private
FID: Integer;
FDESCRICAO: String;
FORIGEM_MERCADORIA: String;
FUF_DESTINO: String;
FCFOP: Integer;
FCSOSN_B: String;
FCST_B: String;
FMODALIDADE_BC: String;
FALIQUOTA: Extended;
FVALOR_PAUTA: Extended;
FVALOR_PRECO_MAXIMO: Extended;
FMVA: Extended;
FPORCENTO_BC: Extended;
FMODALIDADE_BC_ST: String;
FALIQUOTA_INTERNA_ST: Extended;
FALIQUOTA_INTERESTADUAL_ST: Extended;
FPORCENTO_BC_ST: Extended;
FALIQUOTA_ICMS_ST: Extended;
FVALOR_PAUTA_ST: Extended;
FVALOR_PRECO_MAXIMO_ST: Extended;
public
[TId('ID')]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('DESCRICAO', 'Descricao', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Descricao: String read FDESCRICAO write FDESCRICAO;
[TColumn('ORIGEM_MERCADORIA', 'Origem Mercadoria', 8, [ldGrid, ldLookup, ldCombobox], False)]
property OrigemMercadoria: String read FORIGEM_MERCADORIA write FORIGEM_MERCADORIA;
[TColumn('UF_DESTINO', 'Uf Destino', 16, [ldGrid, ldLookup, ldCombobox], False)]
property UfDestino: String read FUF_DESTINO write FUF_DESTINO;
[TColumn('CFOP', 'Cfop', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Cfop: Integer read FCFOP write FCFOP;
[TColumn('CSOSN_B', 'Csosn B', 24, [ldGrid, ldLookup, ldCombobox], False)]
property CsosnB: String read FCSOSN_B write FCSOSN_B;
[TColumn('CST_B', 'Cst B', 16, [ldGrid, ldLookup, ldCombobox], False)]
property CstB: String read FCST_B write FCST_B;
[TColumn('MODALIDADE_BC', 'Modalidade Bc', 8, [ldGrid, ldLookup, ldCombobox], False)]
property ModalidadeBc: String read FMODALIDADE_BC write FMODALIDADE_BC;
[TColumn('ALIQUOTA', 'Aliquota', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property Aliquota: Extended read FALIQUOTA write FALIQUOTA;
[TColumn('VALOR_PAUTA', 'Valor Pauta', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorPauta: Extended read FVALOR_PAUTA write FVALOR_PAUTA;
[TColumn('VALOR_PRECO_MAXIMO', 'Valor Preco Maximo', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorPrecoMaximo: Extended read FVALOR_PRECO_MAXIMO write FVALOR_PRECO_MAXIMO;
[TColumn('MVA', 'Mva', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property Mva: Extended read FMVA write FMVA;
[TColumn('PORCENTO_BC', 'Porcento Bc', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property PorcentoBc: Extended read FPORCENTO_BC write FPORCENTO_BC;
[TColumn('MODALIDADE_BC_ST', 'Modalidade Bc St', 8, [ldGrid, ldLookup, ldCombobox], False)]
property ModalidadeBcSt: String read FMODALIDADE_BC_ST write FMODALIDADE_BC_ST;
[TColumn('ALIQUOTA_INTERNA_ST', 'Aliquota Interna St', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property AliquotaInternaSt: Extended read FALIQUOTA_INTERNA_ST write FALIQUOTA_INTERNA_ST;
[TColumn('ALIQUOTA_INTERESTADUAL_ST', 'Aliquota Interestadual St', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property AliquotaInterestadualSt: Extended read FALIQUOTA_INTERESTADUAL_ST write FALIQUOTA_INTERESTADUAL_ST;
[TColumn('PORCENTO_BC_ST', 'Porcento Bc St', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property PorcentoBcSt: Extended read FPORCENTO_BC_ST write FPORCENTO_BC_ST;
[TColumn('ALIQUOTA_ICMS_ST', 'Aliquota Icms St', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property AliquotaIcmsSt: Extended read FALIQUOTA_ICMS_ST write FALIQUOTA_ICMS_ST;
[TColumn('VALOR_PAUTA_ST', 'Valor Pauta St', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorPautaSt: Extended read FVALOR_PAUTA_ST write FVALOR_PAUTA_ST;
[TColumn('VALOR_PRECO_MAXIMO_ST', 'Valor Preco Maximo St', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorPrecoMaximoSt: Extended read FVALOR_PRECO_MAXIMO_ST write FVALOR_PRECO_MAXIMO_ST;
end;
implementation
initialization
Classes.RegisterClass(TViewTributacaoIcmsCustomVO);
finalization
Classes.UnRegisterClass(TViewTributacaoIcmsCustomVO);
end.
|
unit Main;
interface
uses
Winapi.Windows,Winapi.Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, Winapi.ShellAPI,JSON, WinApi.WinInet, Vcl.StdCtrls,
IniFiles, Generics.Collections, Generics.Defaults;
type
TForm4 = class(TForm)
function request(host,path:String; AData: AnsiString; blnSSL: Boolean = True): AnsiString;
procedure btnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ReCaption(btn: TButton);
procedure Log(Text:string);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form4: TForm4;
vlogin, vtoken, vdomen:string;
DomenDirectory: TDictionary<string, string>;
implementation
{$R *.dfm}
procedure TForm4.btnClick(Sender: TObject);
var response,temptoken:string;
Site:Pchar;
Params: TStringList;
ParamsStr: string;
JObject: TJSONObject;
JPair: TJSONPair;
i:integer;
MemberName,vsuccess: string;
FJSONObject:TJSONObject;
begin
try
vdomen:=StringReplace(TButton(Sender).Caption,vlogin+'@','',[rfReplaceAll, rfIgnoreCase]);
DomenDirectory.TryGetValue(vDomen,vtoken);
Params:=TStringList.Create;
try
if Length(vdomen)>0 then
Params.Add('domain='+vdomen);
Params.Add('login='+vlogin);
if Params <> nil then
begin
Params.Delimiter := '&';
ParamsStr := Params.DelimitedText;
end;
response:=request('pddimp.yandex.ru','api2/admin/email/get_oauth_token',AnsiString(ParamsStr),true);
response:= StringReplace(response, ' xmlns:xi="http://www.w3.org/2001/XInclude"', '', [rfReplaceAll, rfIgnoreCase]);
FJSONObject:=TJSONObject.ParseJSONValue(response) as TJSONObject;
JObject := (FJSONObject as TJSONObject);//привели значение пары к классу TJSONObject
try
{проходим по каждой паре}
for I := 0 to JObject.Count-1 do
begin
JPair:=JObject.Pairs[i];//получили пару по её индексу
MemberName:=JPair.JsonString.Value;//определили имя
{ищем в какое свойство записывать значение}
if MemberName='oauth-token' then
temptoken:=JPair.JsonValue.Value ;
if MemberName='success' then
vsuccess:=JPair.JsonValue.Value
end;
except
raise Exception.Create('Ошибка разбора JSON');
end;
if vsuccess='ok' then
begin
Site := PChar('https://passport.yandex.ru/passport?mode=oauth&type=trusted-pdd-partner&error_retpath=mail.yandex.ru&access_token='+temptoken);
ShellExecute( Handle, 'open',Site, nil, nil, SW_RESTORE );
end
else
begin
ShowMessage('Не удалось получить доступ к электронной почте!ERROR:'+response);
Log('Не удалось получить доступ к электронной почте!ERROR:'+response);
end;
finally
Params.Free;
end;
Except
on E: Exception do
Log(E.Message);
end;
end;
function TForm4.request(host,path:String; AData: AnsiString; blnSSL: Boolean = True): AnsiString;
var
Header : TStringStream;
pSession : HINTERNET;
pConnection : HINTERNET;
pRequest : HINTERNET;
port : Integer;
bytes, b, pos: Cardinal;
ResponseString: AnsiString;
begin
Result := '';
pSession := InternetOpen(nil, INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if Assigned(pSession) then
try
if blnSSL then
Port := INTERNET_DEFAULT_HTTPS_PORT
else
Port := INTERNET_DEFAULT_HTTP_PORT;
pConnection := InternetConnect(pSession, PChar(host), port, nil, nil, INTERNET_SERVICE_HTTP, 0, 0);
if Assigned(pConnection) then
try
pRequest := HTTPOpenRequest(pConnection, 'POST', PWideChar(path),nil, nil, nil, INTERNET_FLAG_SECURE, 0);
if not Assigned(pRequest) then
raise Exception.Create('Ошибка при выполнении функции HttpOpenRequest' + sLineBreak + SysErrorMessage(GetLastError));
if Assigned(pRequest) then
try
Header := TStringStream.Create('');
try
with Header do
begin
WriteString('Host: ' + host + sLineBreak);
WriteString('Content-type: application/x-www-form-urlencoded'+ SLineBreak);
WriteString('PddToken: '+vtoken+ SlineBreak+SLineBreak);
end;
HttpAddRequestHeaders(pRequest, PChar(Header.DataString), Length(Header.DataString), HTTP_ADDREQ_FLAG_ADD);
if HTTPSendRequest(pRequest, nil, 0, Pointer(AData), Length(AData)) then
begin
pos := 1;
b := 1;
ResponseString := '';
while b > 0 do begin
if not InternetQueryDataAvailable( pRequest, bytes, 0, 0 ) then
raise Exception.Create('Ошибка при выполнении функции InternetQueryDataAvailable' + sLineBreak + SysErrorMessage(GetLastError));
SetLength( ResponseString, Length(ResponseString) + bytes );
InternetReadFile( pRequest, @ResponseString[Pos], bytes, b );
Inc(Pos, b);
end;
Result :=ResponseString;
end;
finally
Header.Free;
end;
finally
InternetCloseHandle(pRequest);
end;
finally
InternetCloseHandle(pConnection);
end;
finally
InternetCloseHandle(pSession);
end;
end;
procedure TForm4.FormCreate(Sender: TObject);
var Buffer: array[0..Pred(MAX_COMPUTERNAME_LENGTH+1)] of Char;
Size: cardinal;
Init1: TIniFile;
i:Integer;
vd,vt: String;
btn:TButton;
dir:String;
begin
try
Size := SizeOf(Buffer);
GetComputerName(Buffer, Size);
if buffer<>'RDP' then
Application.Terminate;
Size := SizeOf(Buffer);
GetUserName(Buffer, Size);
vlogin:=buffer;
//Чтение
FileSetAttr(ExtractFilePath(Application.ExeName)+'Enter2MailBox.ini', faHidden);
Init1:= TIniFile.Create(ExtractFilePath(Application.ExeName)+'Enter2MailBox.ini');
// Создаем справочник
DomenDirectory := TDictionary<string, string>.Create;
for i :=1 to 4 do
begin
vd:= init1.ReadString('Domen info','Domen'+InttoStr(i), '');
vt:= init1.ReadString('Domen info','Token'+InttoStr(i), '');
if vd<>'' then
begin
btn:=TButton.Create(nil);//Задать владельца
btn.Parent:=TForm(Sender);//Задать родителя.
btn.Align:=alTop;
btn.Caption:=vlogin+'@'+vd;
ReCaption(btn);
btn.onClick:=btnClick;
btn.Name:='btn'+InttoStr(i);
if not DomenDirectory.ContainsKey(vd) then
DomenDirectory.add(vd,vt) ;
end;
end;
TForm(Sender).AutoSize:=True;
Except
on E: Exception do
Log(E.Message);
end;
end;
procedure TForm4.Log(Text:string);
var
F : TextFile;
FileName : String;
dt:string;
begin
FileName := ExtractFilePath(Application.ExeName) + 'Log.txt';
AssignFile(F, FileName);
if FileExists(FileName) then
Append(F)
else
Rewrite(F);
dt:=DateToStr(Date);
dt:=dt+' '+TimeToStr(Time);
WriteLn(F, text+': ' +dt);
CloseFile(F);
end;
procedure TForm4.ReCaption(btn: TButton);
var S: string;
begin
S := btn.Caption;
Canvas.Font.Size := btn.Font.Size;
if (Form4.clientwidth < Canvas.TextWidth(s) + 10) then
Form4.clientwidth:= Canvas.TextWidth(s) + 10;
end;
end.
|
unit Compression;
interface
type
HCkBinData = Pointer;
HCkByteData = Pointer;
HCkString = Pointer;
HCkStream = Pointer;
HCkStringBuilder = Pointer;
HCkTask = Pointer;
HCkCompression = Pointer;
function CkCompression_Create: HCkCompression; stdcall;
procedure CkCompression_Dispose(handle: HCkCompression); stdcall;
procedure CkCompression_getAlgorithm(objHandle: HCkCompression; outPropVal: HCkString); stdcall;
procedure CkCompression_putAlgorithm(objHandle: HCkCompression; newPropVal: PWideChar); stdcall;
function CkCompression__algorithm(objHandle: HCkCompression): PWideChar; stdcall;
procedure CkCompression_getCharset(objHandle: HCkCompression; outPropVal: HCkString); stdcall;
procedure CkCompression_putCharset(objHandle: HCkCompression; newPropVal: PWideChar); stdcall;
function CkCompression__charset(objHandle: HCkCompression): PWideChar; stdcall;
procedure CkCompression_getDebugLogFilePath(objHandle: HCkCompression; outPropVal: HCkString); stdcall;
procedure CkCompression_putDebugLogFilePath(objHandle: HCkCompression; newPropVal: PWideChar); stdcall;
function CkCompression__debugLogFilePath(objHandle: HCkCompression): PWideChar; stdcall;
function CkCompression_getDeflateLevel(objHandle: HCkCompression): Integer; stdcall;
procedure CkCompression_putDeflateLevel(objHandle: HCkCompression; newPropVal: Integer); stdcall;
procedure CkCompression_getEncodingMode(objHandle: HCkCompression; outPropVal: HCkString); stdcall;
procedure CkCompression_putEncodingMode(objHandle: HCkCompression; newPropVal: PWideChar); stdcall;
function CkCompression__encodingMode(objHandle: HCkCompression): PWideChar; stdcall;
function CkCompression_getHeartbeatMs(objHandle: HCkCompression): Integer; stdcall;
procedure CkCompression_putHeartbeatMs(objHandle: HCkCompression; newPropVal: Integer); stdcall;
procedure CkCompression_getLastErrorHtml(objHandle: HCkCompression; outPropVal: HCkString); stdcall;
function CkCompression__lastErrorHtml(objHandle: HCkCompression): PWideChar; stdcall;
procedure CkCompression_getLastErrorText(objHandle: HCkCompression; outPropVal: HCkString); stdcall;
function CkCompression__lastErrorText(objHandle: HCkCompression): PWideChar; stdcall;
procedure CkCompression_getLastErrorXml(objHandle: HCkCompression; outPropVal: HCkString); stdcall;
function CkCompression__lastErrorXml(objHandle: HCkCompression): PWideChar; stdcall;
function CkCompression_getLastMethodSuccess(objHandle: HCkCompression): wordbool; stdcall;
procedure CkCompression_putLastMethodSuccess(objHandle: HCkCompression; newPropVal: wordbool); stdcall;
function CkCompression_getVerboseLogging(objHandle: HCkCompression): wordbool; stdcall;
procedure CkCompression_putVerboseLogging(objHandle: HCkCompression; newPropVal: wordbool); stdcall;
procedure CkCompression_getVersion(objHandle: HCkCompression; outPropVal: HCkString); stdcall;
function CkCompression__version(objHandle: HCkCompression): PWideChar; stdcall;
function CkCompression_BeginCompressBytes(objHandle: HCkCompression; data: HCkByteData; outData: HCkByteData): wordbool; stdcall;
function CkCompression_BeginCompressBytesAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_BeginCompressBytesENC(objHandle: HCkCompression; data: HCkByteData; outStr: HCkString): wordbool; stdcall;
function CkCompression__beginCompressBytesENC(objHandle: HCkCompression; data: HCkByteData): PWideChar; stdcall;
function CkCompression_BeginCompressBytesENCAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_BeginCompressString(objHandle: HCkCompression; str: PWideChar; outData: HCkByteData): wordbool; stdcall;
function CkCompression_BeginCompressStringAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_BeginCompressStringENC(objHandle: HCkCompression; str: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkCompression__beginCompressStringENC(objHandle: HCkCompression; str: PWideChar): PWideChar; stdcall;
function CkCompression_BeginCompressStringENCAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_BeginDecompressBytes(objHandle: HCkCompression; data: HCkByteData; outData: HCkByteData): wordbool; stdcall;
function CkCompression_BeginDecompressBytesAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_BeginDecompressBytesENC(objHandle: HCkCompression; str: PWideChar; outData: HCkByteData): wordbool; stdcall;
function CkCompression_BeginDecompressBytesENCAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_BeginDecompressString(objHandle: HCkCompression; data: HCkByteData; outStr: HCkString): wordbool; stdcall;
function CkCompression__beginDecompressString(objHandle: HCkCompression; data: HCkByteData): PWideChar; stdcall;
function CkCompression_BeginDecompressStringAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_BeginDecompressStringENC(objHandle: HCkCompression; str: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkCompression__beginDecompressStringENC(objHandle: HCkCompression; str: PWideChar): PWideChar; stdcall;
function CkCompression_BeginDecompressStringENCAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_CompressBd(objHandle: HCkCompression; binData: HCkBinData): wordbool; stdcall;
function CkCompression_CompressBdAsync(objHandle: HCkCompression; binData: HCkBinData): HCkTask; stdcall;
function CkCompression_CompressBytes(objHandle: HCkCompression; data: HCkByteData; outData: HCkByteData): wordbool; stdcall;
function CkCompression_CompressBytesAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_CompressBytesENC(objHandle: HCkCompression; data: HCkByteData; outStr: HCkString): wordbool; stdcall;
function CkCompression__compressBytesENC(objHandle: HCkCompression; data: HCkByteData): PWideChar; stdcall;
function CkCompression_CompressBytesENCAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_CompressFile(objHandle: HCkCompression; srcPath: PWideChar; destPath: PWideChar): wordbool; stdcall;
function CkCompression_CompressFileAsync(objHandle: HCkCompression; srcPath: PWideChar; destPath: PWideChar): HCkTask; stdcall;
function CkCompression_CompressSb(objHandle: HCkCompression; sb: HCkStringBuilder; binData: HCkBinData): wordbool; stdcall;
function CkCompression_CompressSbAsync(objHandle: HCkCompression; sb: HCkStringBuilder; binData: HCkBinData): HCkTask; stdcall;
function CkCompression_CompressStream(objHandle: HCkCompression; strm: HCkStream): wordbool; stdcall;
function CkCompression_CompressStreamAsync(objHandle: HCkCompression; strm: HCkStream): HCkTask; stdcall;
function CkCompression_CompressString(objHandle: HCkCompression; str: PWideChar; outData: HCkByteData): wordbool; stdcall;
function CkCompression_CompressStringAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_CompressStringENC(objHandle: HCkCompression; str: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkCompression__compressStringENC(objHandle: HCkCompression; str: PWideChar): PWideChar; stdcall;
function CkCompression_CompressStringENCAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_DecompressBd(objHandle: HCkCompression; binData: HCkBinData): wordbool; stdcall;
function CkCompression_DecompressBdAsync(objHandle: HCkCompression; binData: HCkBinData): HCkTask; stdcall;
function CkCompression_DecompressBytes(objHandle: HCkCompression; data: HCkByteData; outData: HCkByteData): wordbool; stdcall;
function CkCompression_DecompressBytesAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_DecompressBytesENC(objHandle: HCkCompression; encodedCompressedData: PWideChar; outData: HCkByteData): wordbool; stdcall;
function CkCompression_DecompressBytesENCAsync(objHandle: HCkCompression; encodedCompressedData: PWideChar): HCkTask; stdcall;
function CkCompression_DecompressFile(objHandle: HCkCompression; srcPath: PWideChar; destPath: PWideChar): wordbool; stdcall;
function CkCompression_DecompressFileAsync(objHandle: HCkCompression; srcPath: PWideChar; destPath: PWideChar): HCkTask; stdcall;
function CkCompression_DecompressSb(objHandle: HCkCompression; binData: HCkBinData; sb: HCkStringBuilder): wordbool; stdcall;
function CkCompression_DecompressSbAsync(objHandle: HCkCompression; binData: HCkBinData; sb: HCkStringBuilder): HCkTask; stdcall;
function CkCompression_DecompressStream(objHandle: HCkCompression; strm: HCkStream): wordbool; stdcall;
function CkCompression_DecompressStreamAsync(objHandle: HCkCompression; strm: HCkStream): HCkTask; stdcall;
function CkCompression_DecompressString(objHandle: HCkCompression; data: HCkByteData; outStr: HCkString): wordbool; stdcall;
function CkCompression__decompressString(objHandle: HCkCompression; data: HCkByteData): PWideChar; stdcall;
function CkCompression_DecompressStringAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_DecompressStringENC(objHandle: HCkCompression; encodedCompressedData: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkCompression__decompressStringENC(objHandle: HCkCompression; encodedCompressedData: PWideChar): PWideChar; stdcall;
function CkCompression_DecompressStringENCAsync(objHandle: HCkCompression; encodedCompressedData: PWideChar): HCkTask; stdcall;
function CkCompression_EndCompressBytes(objHandle: HCkCompression; outData: HCkByteData): wordbool; stdcall;
function CkCompression_EndCompressBytesAsync(objHandle: HCkCompression): HCkTask; stdcall;
function CkCompression_EndCompressBytesENC(objHandle: HCkCompression; outStr: HCkString): wordbool; stdcall;
function CkCompression__endCompressBytesENC(objHandle: HCkCompression): PWideChar; stdcall;
function CkCompression_EndCompressBytesENCAsync(objHandle: HCkCompression): HCkTask; stdcall;
function CkCompression_EndCompressString(objHandle: HCkCompression; outData: HCkByteData): wordbool; stdcall;
function CkCompression_EndCompressStringAsync(objHandle: HCkCompression): HCkTask; stdcall;
function CkCompression_EndCompressStringENC(objHandle: HCkCompression; outStr: HCkString): wordbool; stdcall;
function CkCompression__endCompressStringENC(objHandle: HCkCompression): PWideChar; stdcall;
function CkCompression_EndCompressStringENCAsync(objHandle: HCkCompression): HCkTask; stdcall;
function CkCompression_EndDecompressBytes(objHandle: HCkCompression; outData: HCkByteData): wordbool; stdcall;
function CkCompression_EndDecompressBytesAsync(objHandle: HCkCompression): HCkTask; stdcall;
function CkCompression_EndDecompressBytesENC(objHandle: HCkCompression; outData: HCkByteData): wordbool; stdcall;
function CkCompression_EndDecompressBytesENCAsync(objHandle: HCkCompression): HCkTask; stdcall;
function CkCompression_EndDecompressString(objHandle: HCkCompression; outStr: HCkString): wordbool; stdcall;
function CkCompression__endDecompressString(objHandle: HCkCompression): PWideChar; stdcall;
function CkCompression_EndDecompressStringAsync(objHandle: HCkCompression): HCkTask; stdcall;
function CkCompression_EndDecompressStringENC(objHandle: HCkCompression; outStr: HCkString): wordbool; stdcall;
function CkCompression__endDecompressStringENC(objHandle: HCkCompression): PWideChar; stdcall;
function CkCompression_EndDecompressStringENCAsync(objHandle: HCkCompression): HCkTask; stdcall;
function CkCompression_MoreCompressBytes(objHandle: HCkCompression; data: HCkByteData; outData: HCkByteData): wordbool; stdcall;
function CkCompression_MoreCompressBytesAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_MoreCompressBytesENC(objHandle: HCkCompression; data: HCkByteData; outStr: HCkString): wordbool; stdcall;
function CkCompression__moreCompressBytesENC(objHandle: HCkCompression; data: HCkByteData): PWideChar; stdcall;
function CkCompression_MoreCompressBytesENCAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_MoreCompressString(objHandle: HCkCompression; str: PWideChar; outData: HCkByteData): wordbool; stdcall;
function CkCompression_MoreCompressStringAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_MoreCompressStringENC(objHandle: HCkCompression; str: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkCompression__moreCompressStringENC(objHandle: HCkCompression; str: PWideChar): PWideChar; stdcall;
function CkCompression_MoreCompressStringENCAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_MoreDecompressBytes(objHandle: HCkCompression; data: HCkByteData; outData: HCkByteData): wordbool; stdcall;
function CkCompression_MoreDecompressBytesAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_MoreDecompressBytesENC(objHandle: HCkCompression; str: PWideChar; outData: HCkByteData): wordbool; stdcall;
function CkCompression_MoreDecompressBytesENCAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_MoreDecompressString(objHandle: HCkCompression; data: HCkByteData; outStr: HCkString): wordbool; stdcall;
function CkCompression__moreDecompressString(objHandle: HCkCompression; data: HCkByteData): PWideChar; stdcall;
function CkCompression_MoreDecompressStringAsync(objHandle: HCkCompression; data: HCkByteData): HCkTask; stdcall;
function CkCompression_MoreDecompressStringENC(objHandle: HCkCompression; str: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkCompression__moreDecompressStringENC(objHandle: HCkCompression; str: PWideChar): PWideChar; stdcall;
function CkCompression_MoreDecompressStringENCAsync(objHandle: HCkCompression; str: PWideChar): HCkTask; stdcall;
function CkCompression_SaveLastError(objHandle: HCkCompression; path: PWideChar): wordbool; stdcall;
function CkCompression_UnlockComponent(objHandle: HCkCompression; unlockCode: PWideChar): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkCompression_Create; external DLLName;
procedure CkCompression_Dispose; external DLLName;
procedure CkCompression_getAlgorithm; external DLLName;
procedure CkCompression_putAlgorithm; external DLLName;
function CkCompression__algorithm; external DLLName;
procedure CkCompression_getCharset; external DLLName;
procedure CkCompression_putCharset; external DLLName;
function CkCompression__charset; external DLLName;
procedure CkCompression_getDebugLogFilePath; external DLLName;
procedure CkCompression_putDebugLogFilePath; external DLLName;
function CkCompression__debugLogFilePath; external DLLName;
function CkCompression_getDeflateLevel; external DLLName;
procedure CkCompression_putDeflateLevel; external DLLName;
procedure CkCompression_getEncodingMode; external DLLName;
procedure CkCompression_putEncodingMode; external DLLName;
function CkCompression__encodingMode; external DLLName;
function CkCompression_getHeartbeatMs; external DLLName;
procedure CkCompression_putHeartbeatMs; external DLLName;
procedure CkCompression_getLastErrorHtml; external DLLName;
function CkCompression__lastErrorHtml; external DLLName;
procedure CkCompression_getLastErrorText; external DLLName;
function CkCompression__lastErrorText; external DLLName;
procedure CkCompression_getLastErrorXml; external DLLName;
function CkCompression__lastErrorXml; external DLLName;
function CkCompression_getLastMethodSuccess; external DLLName;
procedure CkCompression_putLastMethodSuccess; external DLLName;
function CkCompression_getVerboseLogging; external DLLName;
procedure CkCompression_putVerboseLogging; external DLLName;
procedure CkCompression_getVersion; external DLLName;
function CkCompression__version; external DLLName;
function CkCompression_BeginCompressBytes; external DLLName;
function CkCompression_BeginCompressBytesAsync; external DLLName;
function CkCompression_BeginCompressBytesENC; external DLLName;
function CkCompression__beginCompressBytesENC; external DLLName;
function CkCompression_BeginCompressBytesENCAsync; external DLLName;
function CkCompression_BeginCompressString; external DLLName;
function CkCompression_BeginCompressStringAsync; external DLLName;
function CkCompression_BeginCompressStringENC; external DLLName;
function CkCompression__beginCompressStringENC; external DLLName;
function CkCompression_BeginCompressStringENCAsync; external DLLName;
function CkCompression_BeginDecompressBytes; external DLLName;
function CkCompression_BeginDecompressBytesAsync; external DLLName;
function CkCompression_BeginDecompressBytesENC; external DLLName;
function CkCompression_BeginDecompressBytesENCAsync; external DLLName;
function CkCompression_BeginDecompressString; external DLLName;
function CkCompression__beginDecompressString; external DLLName;
function CkCompression_BeginDecompressStringAsync; external DLLName;
function CkCompression_BeginDecompressStringENC; external DLLName;
function CkCompression__beginDecompressStringENC; external DLLName;
function CkCompression_BeginDecompressStringENCAsync; external DLLName;
function CkCompression_CompressBd; external DLLName;
function CkCompression_CompressBdAsync; external DLLName;
function CkCompression_CompressBytes; external DLLName;
function CkCompression_CompressBytesAsync; external DLLName;
function CkCompression_CompressBytesENC; external DLLName;
function CkCompression__compressBytesENC; external DLLName;
function CkCompression_CompressBytesENCAsync; external DLLName;
function CkCompression_CompressFile; external DLLName;
function CkCompression_CompressFileAsync; external DLLName;
function CkCompression_CompressSb; external DLLName;
function CkCompression_CompressSbAsync; external DLLName;
function CkCompression_CompressStream; external DLLName;
function CkCompression_CompressStreamAsync; external DLLName;
function CkCompression_CompressString; external DLLName;
function CkCompression_CompressStringAsync; external DLLName;
function CkCompression_CompressStringENC; external DLLName;
function CkCompression__compressStringENC; external DLLName;
function CkCompression_CompressStringENCAsync; external DLLName;
function CkCompression_DecompressBd; external DLLName;
function CkCompression_DecompressBdAsync; external DLLName;
function CkCompression_DecompressBytes; external DLLName;
function CkCompression_DecompressBytesAsync; external DLLName;
function CkCompression_DecompressBytesENC; external DLLName;
function CkCompression_DecompressBytesENCAsync; external DLLName;
function CkCompression_DecompressFile; external DLLName;
function CkCompression_DecompressFileAsync; external DLLName;
function CkCompression_DecompressSb; external DLLName;
function CkCompression_DecompressSbAsync; external DLLName;
function CkCompression_DecompressStream; external DLLName;
function CkCompression_DecompressStreamAsync; external DLLName;
function CkCompression_DecompressString; external DLLName;
function CkCompression__decompressString; external DLLName;
function CkCompression_DecompressStringAsync; external DLLName;
function CkCompression_DecompressStringENC; external DLLName;
function CkCompression__decompressStringENC; external DLLName;
function CkCompression_DecompressStringENCAsync; external DLLName;
function CkCompression_EndCompressBytes; external DLLName;
function CkCompression_EndCompressBytesAsync; external DLLName;
function CkCompression_EndCompressBytesENC; external DLLName;
function CkCompression__endCompressBytesENC; external DLLName;
function CkCompression_EndCompressBytesENCAsync; external DLLName;
function CkCompression_EndCompressString; external DLLName;
function CkCompression_EndCompressStringAsync; external DLLName;
function CkCompression_EndCompressStringENC; external DLLName;
function CkCompression__endCompressStringENC; external DLLName;
function CkCompression_EndCompressStringENCAsync; external DLLName;
function CkCompression_EndDecompressBytes; external DLLName;
function CkCompression_EndDecompressBytesAsync; external DLLName;
function CkCompression_EndDecompressBytesENC; external DLLName;
function CkCompression_EndDecompressBytesENCAsync; external DLLName;
function CkCompression_EndDecompressString; external DLLName;
function CkCompression__endDecompressString; external DLLName;
function CkCompression_EndDecompressStringAsync; external DLLName;
function CkCompression_EndDecompressStringENC; external DLLName;
function CkCompression__endDecompressStringENC; external DLLName;
function CkCompression_EndDecompressStringENCAsync; external DLLName;
function CkCompression_MoreCompressBytes; external DLLName;
function CkCompression_MoreCompressBytesAsync; external DLLName;
function CkCompression_MoreCompressBytesENC; external DLLName;
function CkCompression__moreCompressBytesENC; external DLLName;
function CkCompression_MoreCompressBytesENCAsync; external DLLName;
function CkCompression_MoreCompressString; external DLLName;
function CkCompression_MoreCompressStringAsync; external DLLName;
function CkCompression_MoreCompressStringENC; external DLLName;
function CkCompression__moreCompressStringENC; external DLLName;
function CkCompression_MoreCompressStringENCAsync; external DLLName;
function CkCompression_MoreDecompressBytes; external DLLName;
function CkCompression_MoreDecompressBytesAsync; external DLLName;
function CkCompression_MoreDecompressBytesENC; external DLLName;
function CkCompression_MoreDecompressBytesENCAsync; external DLLName;
function CkCompression_MoreDecompressString; external DLLName;
function CkCompression__moreDecompressString; external DLLName;
function CkCompression_MoreDecompressStringAsync; external DLLName;
function CkCompression_MoreDecompressStringENC; external DLLName;
function CkCompression__moreDecompressStringENC; external DLLName;
function CkCompression_MoreDecompressStringENCAsync; external DLLName;
function CkCompression_SaveLastError; external DLLName;
function CkCompression_UnlockComponent; external DLLName;
end.
|
unit Views.Interfaces.Mensagem;
interface
uses
Services.ComplexTypes;
type
IViewMensagem = interface
['{CB6F35A6-0796-48EA-8719-C34D8746A2CD}']
function Tipo(Value : TTipoMensagem) : IViewMensagem;
function Titulo(Value : String) : IViewMensagem;
function Mensagem(Value : String) : IViewMensagem;
function CallbackProcedure(Value : TCallbackProcedureObject) : IViewMensagem;
procedure &End;
end;
implementation
end.
|
(* @file UTetrominoShape.pas
* @author Willi Schinmeyer
* @date 2011-10-30
*
* The TTetrominoShape type. I put it in its own unit to prevent cyclic dependencies.
*)
unit UTetrominoShape;
interface
uses UVector2i;
type
(* @brief Shape of a tetromino - they always consist of 4 squares, hence the name. *)
TTetrominoShape = array[0..3] of TVector2i;
implementation
begin
end.
|
unit CrossDetailedFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StorageUnit;
type
{ TDetailedFrame }
TDetailedFrame = class(TFrame, IRememberable)
PageControl: TPageControl;
private
FMainFrame: TFrame;
protected
{ IRememberable }
procedure SaveState(Storage: TStorage; const SectionName, Prefix: string);
procedure LoadState(Storage: TStorage; const SectionName, Prefix: string);
public
procedure AfterLink; virtual;
property MainFrame: TFrame read FMainFrame write FMainFrame;
end;
implementation
{$R *.dfm}
{ TDetailedFrame }
procedure TDetailedFrame.AfterLink;
begin
{ do nothing }
end;
{ IRememberable }
procedure TDetailedFrame.SaveState(Storage: TStorage; const SectionName, Prefix: string);
begin
SaveChildState(Self, SectionName, Prefix + Name + '.');
end;
procedure TDetailedFrame.LoadState(Storage: TStorage; const SectionName, Prefix: string);
begin
LoadChildState(Self, SectionName, Prefix + Name + '.');
end;
end.
|
unit PIPX;
(*****************************************************************************
Prozessprogrammierung SS08
Aufgabe: Muehle
Typdefinition fuer IPX-Nachrichten vom Anzeige- zum Prozessrechner.
Autor: Alexander Bertram (B_TInf 2616)
*****************************************************************************)
interface
uses
RTKernel, RTIPX,
Types;
const
Channel = cPIPXChannel;
type
IPXMessageType = TProcessMessage;
IPXMessagePtr = PProcessMessage;
{$I IPX.DEF }
{$I IPX.INT }
implementation
{$I IPX.IMP}
end. |
unit uDependente_imp;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Variants;
Type EParentesco = (epFILHO, epSOBRINHO, epOUTROS);
{ TDependente }
Type TDependente = Class(TComponent)
private
FCpf: String;
FDtNascimento: TDate;
FNome: String;
FParentesco: EParentesco;
procedure SetCpf(AValue: String);
procedure SetDtNascimento(AValue: TDate);
procedure SetNome(AValue: String);
procedure SetParentesco(AValue: EParentesco);
public
function CalculaIdade(): Integer;
published
property Nome: String read FNome write SetNome;
property Cpf: String read FCpf write SetCpf;
property Parentesco: EParentesco read FParentesco write SetParentesco;
property DtNascimento: TDate read FDtNascimento write SetDtNascimento;
end;
implementation
uses
DateUtils;
{ TDependente }
procedure TDependente.SetCpf(AValue: String);
begin
if FCpf = AValue then
Exit;
FCpf := AValue;
end;
procedure TDependente.SetDtNascimento(AValue: TDate);
begin
if FDtNascimento = AValue then
Exit;
FDtNascimento := AValue;
end;
procedure TDependente.SetNome(AValue: String);
begin
if FNome = AValue then
Exit;
FNome := AValue;
end;
procedure TDependente.SetParentesco(AValue: EParentesco);
begin
if FParentesco = AValue then
Exit;
FParentesco := AValue;
end;
function TDependente.CalculaIdade(): Integer;
begin
Result := CurrentYear - YearOf(FDtNascimento);
end;
end.
|
unit MainView;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls,
ActnList, MainViewModel, IdKeyDialog, helpers, entities, ChatView,
vkcmobserver, AbstractViewModel;
type
{ TfMainView }
TfMainView = class(TForm)
CommunitiesImageList: TImageList;
ToolBar1: TToolBar;
procedure FormCreate(Sender: TObject);
procedure PrepareWorkspaceForCommunity(Sender: TObject);
private
FCurrentFrame: TFrame;
FObservable: TVKCMObservable;
FObserver: TVKCMObserver;
FViewModel: IMainViewModel;
procedure SetCurrentFrame(AValue: TFrame);
procedure SetObservable(AValue: TVKCMObservable);
procedure SetObserver(AValue: TVKCMObserver);
procedure SetViewModel(AValue: IMainViewModel);
procedure OnNotify;
public
property ViewModel: IMainViewModel read FViewModel write SetViewModel;
procedure UpdateGUI;
{Creates a button for adding communities}
procedure AddNewCommunityButton;
{Event of "Add new community" button}
procedure AddNewCommunity(Sender: TObject);
property CurrentFrame: TFrame read FCurrentFrame write SetCurrentFrame;
property Observer: TVKCMObserver read FObserver write SetObserver;
property Observable: TVKCMObservable read FObservable write SetObservable;
end;
var
LMainView: TfMainView;
implementation
{$R *.lfm}
{ TfMainView }
procedure TfMainView.PrepareWorkspaceForCommunity(Sender: TObject);
var
Community: TCommunity;
begin
Community := ((Sender as TToolButton).DataObject as TCommunity);
LChatView.Community := Community;
LChatView.UpdateGUI;
if Observable.Observers.IndexOf(LChatView.Observer) = -1 then
LChatView.Observer.Subscribe(Observable);
CurrentFrame := LChatView;
end;
procedure TfMainView.FormCreate(Sender: TObject);
begin
Observer := TVKCMObserver.Create;
Observer.Notify := @OnNotify;
Observable := TVKCMObservable.Create;
end;
procedure TfMainView.SetViewModel(AValue: IMainViewModel);
begin
if FViewModel = AValue then
Exit;
{Unsubscribe old viewmodel}
if (FViewModel is TObserverViewModel) then
Observer.Unsubscribe((FViewModel as TObserverViewModel).Observable);
{Assign and subscribe}
FViewModel := AValue;
if (FViewModel is TObserverViewModel) then
Observer.Subscribe((FViewModel as TObserverViewModel).Observable);
end;
procedure TfMainView.OnNotify;
begin
UpdateGUI;
Observable.NotifyObservers;
end;
procedure TfMainView.SetCurrentFrame(AValue: TFrame);
begin
if Assigned(FCurrentFrame) then
FCurrentFrame.Parent := nil;
AValue.Parent := self;
end;
procedure TfMainView.SetObservable(AValue: TVKCMObservable);
begin
if FObservable = AValue then
Exit;
FObservable := AValue;
end;
procedure TfMainView.SetObserver(AValue: TVKCMObserver);
begin
if FObserver = AValue then
Exit;
FObserver := AValue;
end;
procedure TfMainView.UpdateGUI;
var
i: integer;
NewButton: TToolButton;
Data: TUIData;
begin
{Clean imagelist and toolbar}
CommunitiesImageList.Clear;
while ToolBar1.ControlCount > 0 do
begin
ToolBar1.Controls[0].DataObject.Free;
ToolBar1.Controls[0].Free;
end;
{Fill imagelist}
Data := FViewModel.GetDataForUIUpdate;
CommunitiesImageList.Add(Data.NewCommunityPicture, nil);
for i := 0 to Data.ButtonPictures.Count - 1 do
CommunitiesImageList.Add(Data.ButtonPictures[i], nil);
{1, becuase index 0 stands for new community icon}
for i := 1 to CommunitiesImageList.Count - 1 do
begin
NewButton := TToolButton.Create(ToolBar1);
NewButton.ImageIndex := i;
NewButton.DataObject := Data.Communities[i - 1];
NewButton.Parent := ToolBar1;
NewButton.OnClick := @PrepareWorkspaceForCommunity;
end;
AddNewCommunityButton;
FreeAndNil(Data);
end;
procedure TfMainView.AddNewCommunityButton;
var
NewButton: TToolButton;
begin
NewButton := TToolButton.Create(Toolbar1);
NewButton.ImageIndex := 0;
NewButton.Parent := ToolBar1;
{Hack: NewButton will be always first}
NewButton.Top := -1;
NewButton.OnClick := @AddNewCommunity;
end;
procedure TfMainView.AddNewCommunity(Sender: TObject);
var
Id, AccessKey: string;
begin
Dialog.ShowModal;
if not Dialog.Done then
exit;
Id := Dialog.Id;
AccessKey := Dialog.AccessKey;
try
ViewModel.SaveNewCommunity(AccessKey, Id);
except
on E: Exception do
ShowMessage(E.Message);
end;
UpdateGUI;
end;
end.
|
Unit SendEmail;
Interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
EASendMailObjLib_TLB, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase,
IdSMTP, Vcl.StdCtrls, IdMessage;
Type
TFRMSendEmail = class(TForm)
EDTSendTo: TEdit;
EDTSubject: TEdit;
StaticText2: TStaticText;
StaticText5: TStaticText;
IdSMTP: TIdSMTP;
IdMessage: TIdMessage;
Memo: TMemo;
btMsg: TButton;
StaticText1: TStaticText;
procedure btMsgClick(Sender: TObject);
private
public
Procedure Send(SendTo, Subject, Message: String);
end;
Var
FRMSendEmail: TFRMSendEmail;
Sent: Boolean;
Implementation
{$R *.dfm}
Uses ForgotPassword;
//Procedure using the Hotmail server and authetication to send emails
//to clients through the use of SMTP components.
//The procedure uses the paramemters 'SentTo', 'Subject' and 'Message' to
//send an email to any client with a valid email address containg any message
//choosen by the user.
Procedure TFRMSendEmail.Send(SendTo, Subject, Message: String);
Var IdSMTP : TMail;
Begin
Sent := False;
IdSMTP := TMail.Create(Application);
IdSMTP.LicenseCode := 'TryIt';
// Restaurants Email Address
IdSMTP.FromAddr := 'Comp4project@hotmail.co.uk';
// Recipients email address
IdSMTP.AddRecipientEx( SendTo, 0);
// Email Subject
IdSMTP.Subject := Subject;
// Email Text
IdSMTP.BodyText := Message;
// Hotmail SMTP Server
IdSMTP.ServerAddr := 'smtp.live.com';
// Detect SSL/TLS automatically
IdSMTP.SSL_init();
//Hotmail User authentications
//(Restaurants email details)
IdSMTP.UserName := 'Comp4project@hotmail.co.uk';
IdSMTP.Password := 'Restaurant';
IF IdSMTP.SendMail() = 0
Then Begin
ShowMessage( 'Email sent successfully!' );
Sent := True
End
Else ShowMessage( 'failed to send email with the following error: '
+ IdSMTP.GetLastErrDescription());
End;
Procedure TFRMSendEmail.btMsgClick(Sender: TObject);
Begin
Send(EDTSendTo.Text, EDTSubject.Text, Memo.Lines.Text);
End;
End.
|
// ---------------------------------------------------------------------------//
//
// dgViewport3D
//
// Copyright © 2005-2009 DunconGames. All rights reserved. BSD License. Authors: simsmen
// ---------------------------------------------------------------------------//
//
// ---------------------------------------------------------------------------//
// History:
//
// 2009.01.08 simsmen
// ---------------------------------------------------------------------------//
// Bugs:
//
// ---------------------------------------------------------------------------//
// Future:
//
// on click rotate object
//
// glDepthFunc(DepthFunc2GL[fDepthFunc]);
// glShadeModel(ShadeModel2GL[fShadeModel]);
//
// glLightfv(i,GL_SPOT_DIRECTION,fSpotDirection.Values);
// glLightf (i,GL_SPOT_CUTOFF,fSpotCutOff);
// glLightf (i,GL_SPOT_EXPONENT,fSpotExponent);
(*procedure gluPerspective(fovy, aspect, zNear, zFar: double);
var
xmin,xmax,ymin,ymax:double;
begin
ymax:=zNear*tan(fovy*PI/360);
ymin:=-ymax;
xmin:=ymin*aspect;
xmax:=ymax*aspect;
glFrustum(xmin,xmax,ymin,ymax,zNear,zFar);
end; *)
// ---------------------------------------------------------------------------//
unit dgViewport3D;
{$DEFINE dgAssert}
{$DEFINE dgTrace}
interface
procedure dgInitViewport3D;
implementation
uses
OpenGL,
windows,
dgHeader,
dgTraceCore,
dgCore;
const
cnstUnitName = 'dgViewport3D';
type
TdgNodeData = TdgDrawable;
TdgNodeDataArray = array[0..(Maxint div sizeof(TdgNodeData)) - 1] of TdgNodeData;
PdgNodeDataArray = ^TdgNodeDataArray;
TdgNodeDataList = record
rArray: PdgNodeDataArray;
rCount: integer;
rCapacity: integer;
rIterator: integer;
procedure Create; inline;
procedure Free; inline;
procedure StayBeforeFirst; inline;
function StayOnNext: boolean; inline;
function Data: TdgNodeData; inline;
procedure Append(const aData: TdgNodeData); inline;
procedure ExtractAll; inline;
procedure Extract; inline;
function StayOnData(const aData: TdgNodeData): boolean; inline;
end;
procedure TdgNodeDataList.Create;
begin
rArray := nil;
rCount := 0;
rCapacity := 0;
rIterator := 0;
dgAddCapacity(pointer(rArray), rCapacity, SizeOf(TdgNodeData));
end;
procedure TdgNodeDataList.Free;
var
i: integer;
begin
for i := 0 to rCapacity - 1 do
rArray[i] := nil;
ReallocMem(rArray, 0);
rArray := nil;
end;
procedure TdgNodeDataList.StayBeforeFirst;
begin
rIterator := -1;
end;
function TdgNodeDataList.StayOnNext: boolean;
begin
inc(rIterator);
if rIterator >= rCount then
begin
rIterator := -1;
result := false;
end
else
result := true;
end;
function TdgNodeDataList.Data: TdgNodeData;
begin
{$IFDEF dgAssert}
dgTrace.Assert(rIterator >= 0, '{9F287BDD-C11C-441E-9354-D4603D232E74}', cnstUnitName);
{$ENDIF}
Result := rArray^[rIterator];
end;
procedure TdgNodeDataList.Append(const aData: TdgNodeData);
begin
inc(rCount);
while rCount > rCapacity do
dgAddCapacity(pointer(rArray), rCapacity, SizeOf(TdgNodeData));
rArray^[rCount - 1] := aData;
end;
procedure TdgNodeDataList.ExtractAll;
var
i: integer;
begin
for i := 0 to rCapacity - 1 do
rArray[i] := nil;
rIterator := -1;
rCount := 0;
end;
procedure TdgNodeDataList.Extract;
begin
{$IFDEF dgAssert}
dgTrace.Assert(rIterator >= 0, '{9F287BDD-C11C-441E-9354-D4603D232E74}', cnstUnitName);
{$ENDIF}
Dec(rCount);
rArray^[rIterator] := rArray^[rCount];
rArray^[rCount] := nil;
Dec(rIterator);
end;
function TdgNodeDataList.StayOnData(const aData: TdgNodeData): boolean;
var
i: integer;
begin
result := false;
rIterator := -1;
if aData <> nil then
begin
i := 0;
while (i < rCount) and (rArray[i] <> aData) do
inc(i);
if rArray[i] = aData then
begin
result := true;
rIterator := i;
end;
end;
end;
type
TdgLightData = record
rID: integer;
rLightable: TdgLightable;
end;
TdgLightDataArray = array[0..(Maxint div sizeof(TdgLightData)) - 1] of TdgLightData;
PdgLightDataArray = ^TdgLightDataArray;
TdgLightDataList = record
rArray: PdgLightDataArray;
rCount: integer;
rCapacity: integer;
rIterator: integer;
procedure Create; inline;
procedure Free; inline;
procedure StayBeforeFirst; inline;
function StayOnNext: boolean; inline;
function Data: TdgLightData; inline;
procedure Append(const aData: TdgLightable); inline;
procedure ExtractAll; inline;
procedure Extract; inline;
function StayOnData(const aData: TdgLightable): boolean; inline;
end;
procedure TdgLightDataList.Create;
begin
rArray := nil;
rCount := 0;
rCapacity := 0;
rIterator := 0;
dgAddCapacity(pointer(rArray), rCapacity, SizeOf(TdgLightData));
end;
procedure TdgLightDataList.Free;
var
i: integer;
begin
for i := 0 to rCapacity - 1 do
rArray[i].rLightable := nil;
ReallocMem(rArray, 0);
rArray := nil;
end;
procedure TdgLightDataList.StayBeforeFirst;
begin
rIterator := -1;
end;
function TdgLightDataList.StayOnNext: boolean;
begin
inc(rIterator);
if rIterator >= rCount then
begin
rIterator := -1;
result := false;
end
else
result := true;
end;
function TdgLightDataList.Data: TdgLightData;
begin
{$IFDEF dgAssert}
dgTrace.Assert(rIterator >= 0, '{9F287BDD-C11C-441E-9354-D4603D232E74}', cnstUnitName);
{$ENDIF}
Result := rArray^[rIterator];
end;
procedure TdgLightDataList.Append(const aData: TdgLightable);
begin
inc(rCount);
while rCount > rCapacity do
dgAddCapacity(pointer(rArray), rCapacity, SizeOf(TdgLightData));
rArray^[rCount - 1].rID := aData.ID;
rArray^[rCount - 1].rLightable := aData;
end;
procedure TdgLightDataList.ExtractAll;
var
i: integer;
begin
for i := 0 to rCapacity - 1 do
rArray[i].rLightable := nil;
rIterator := -1;
rCount := 0;
end;
procedure TdgLightDataList.Extract;
begin
{$IFDEF dgAssert}
dgTrace.Assert(rIterator >= 0, '{9F287BDD-C11C-441E-9354-D4603D232E74}', cnstUnitName);
{$ENDIF}
Dec(rCount);
rArray^[rIterator].rID := rArray^[rCount].rID;
rArray^[rIterator].rLightable := rArray^[rCount].rLightable;
rArray^[rCount].rLightable := nil;
Dec(rIterator);
end;
function TdgLightDataList.StayOnData(const aData: TdgLightable): boolean;
var
i: integer;
begin
result := false;
rIterator := -1;
if aData <> nil then
begin
i := 0;
while (i < rCount) and (rArray[i].rLightable <> aData) do
inc(i);
if rArray[i].rLightable = aData then
begin
result := true;
rIterator := i;
end;
end;
end;
type
TdgViewport3D = class(Tdg3DDrawNotifier)
constructor Create;
destructor Destroy; override;
private
fPosition: TdgVector3f;
fDirection: TdgVector3f;
fUp: TdgVector3f;
fFOV: TdgFloat;
fZNear: TdgFloat;
fZFar: TdgFloat;
fAmbient: TdgVector4f;
fLightableList: TdgLightDataList;
fNodeableList: TdgNodeDataList;
fDeltaTime: TdgFloat;
procedure Enable; inline;
procedure Disable; inline;
public
function pDeltaTime: PdgFloat; override;
procedure Render; override;
procedure Attach(const aNode: TdgDrawable); overload; override;
procedure Detach(const aNode: TdgDrawable); overload; override;
procedure Attach(const aNode: TdgLightable); overload; override;
procedure Detach(const aNode: TdgLightable); overload; override;
function GetPosition: TdgVector3f; override;
procedure SetPosition(const aValue: TdgVector3f); override;
function GetDirection: TdgVector3f; override;
procedure SetDirection(const aValue: TdgVector3f); override;
function GetUp: TdgVector3f; override;
procedure SetUp(const aValue: TdgVector3f); override;
function GetFOV: TdgFloat; override;
procedure SetFOV(const aValue: TdgFloat); override;
function GetZNear: TdgFloat; override;
procedure SetZNear(const aValue: TdgFloat); override;
function GetZFar: TdgFloat; override;
procedure SetZFar(const aValue: TdgFloat); override;
function GetAmbient: TdgVector4f; override;
procedure SetAmbient(const aValue: TdgVector4f); override;
function isVisible(const aView: TdgMat4f; const aMinPos, aMaxPos: TdgVector3f): boolean; override;
procedure DetachAllDrawable; override;
end;
constructor TdgViewport3D.Create;
begin
inherited Create;
fPosition := dgVector3f(0.0, 0.0, 0.0);
fDirection := dgVector3f(0.0, 0.0, 0.0);
fUp := dgVector3f(0.0, 0.0, 0.0);
fFOV := 0.0;
fZNear := 0.0;
fZFar := 0.0;
fAmbient := dgVector4f(0.0, 0.0, 0.0, 0.0);
fLightableList.Create;
fNodeableList.Create;
fDeltaTime := 0.0;
{$IFDEF dgTrace}
// dgTrace.Write.Info('Created ...', cnstUnitName);
{$ENDIF}
end;
destructor TdgViewport3D.Destroy;
begin
fLightableList.Free;
fNodeableList.Free;
inherited Destroy;
end;
procedure TdgViewport3D.DetachAllDrawable;
begin
fNodeableList.ExtractAll;
end;
function TdgViewport3D.isVisible(const aView: TdgMat4f; const aMinPos, aMaxPos: TdgVector3f): boolean;
begin
result:=true;
end;
// IdgDrawNotifier = interface
procedure TdgViewport3D.Attach(const aNode: TdgDrawable);
begin
fNodeableList.Append(aNode);
end;
procedure TdgViewport3D.Detach(const aNode: TdgDrawable);
begin
if fNodeableList.StayOnData(aNode) then
fNodeableList.Extract;
end;
procedure TdgViewport3D.Attach(const aNode: TdgLightable);
begin
fLightableList.Append(aNode);
end;
procedure TdgViewport3D.Detach(const aNode: TdgLightable);
begin
if fLightableList.StayOnData(aNode) then
fLightableList.Extract;
end;
function TdgViewport3D.pDeltaTime: PdgFloat;
begin
result := @fDeltaTime;
end;
procedure TdgViewport3D.Render;
var
T: LARGE_INTEGER;
F: LARGE_INTEGER;
Time: TdgFloat;
begin
QueryPerformanceFrequency(Int64(F));
QueryPerformanceCounter(Int64(T));
Time := T.QuadPart / F.QuadPart;
Enable;
fLightableList.StayBeforeFirst;
while fLightableList.StayOnNext do
glEnable(GL_LIGHT0 + fLightableList.Data.rID);
fNodeableList.StayBeforeFirst;
while fNodeableList.StayOnNext do
fNodeableList.Data.Draw;
fLightableList.StayBeforeFirst;
while fLightableList.StayOnNext do
glDisable(GL_LIGHT0 + fLightableList.Data.rID);
Disable;
QueryPerformanceCounter(Int64(T));
fDeltaTime := T.QuadPart / F.QuadPart - Time;
end;
// Idg3DRenderSet = interface
procedure TdgViewport3D.Enable;
begin
glMatrixMode(GL_PROJECTION);
(* if risViewChanged then
begin
glLoadIdentity;
gluPerspective(rFOV, dgWindow.GetAspect, rzNear, rzFar);
gluLookAt(rPosition.X, rPosition.Y, rPosition.Z,
rDirection.X, rDirection.Y, rDirection.Z,
rUp.X, rUp.Y, rUp.Z);
risViewChanged := false;
glGetFloatv(GL_PROJECTION_MATRIX, @rProjectionM4f);
end
else
glLoadMatrixf(@rProjectionM4f);*)
//сравнить с
glLoadIdentity;
gluPerspective(fFOV, dg.Window.GetAspect, fzNear, fzFar);
gluLookAt(fPosition.X, fPosition.Y, fPosition.Z,
fDirection.X, fDirection.Y, fDirection.Z,
fUp.X, fUp.Y, fUp.Z);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glEnable(GL_LIGHTING);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, @fAmbient);
//Операция буффера глубины
//glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
end;
procedure TdgViewport3D.Disable;
begin
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
end;
function TdgViewport3D.GetPosition: TdgVector3f;
begin
result := fPosition;
end;
procedure TdgViewport3D.SetPosition(const aValue: TdgVector3f);
begin
fPosition := aValue;
end;
function TdgViewport3D.GetDirection: TdgVector3f;
begin
result := fDirection;
end;
procedure TdgViewport3D.SetDirection(const aValue: TdgVector3f);
begin
fDirection := aValue;
end;
function TdgViewport3D.GetUp: TdgVector3f;
begin
result := fUp;
end;
procedure TdgViewport3D.SetUp(const aValue: TdgVector3f);
begin
fUp := aValue;
end;
function TdgViewport3D.GetFOV: TdgFloat;
begin
result := fFOV;
end;
procedure TdgViewport3D.SetFOV(const aValue: TdgFloat);
begin
fFOV := aValue;
end;
function TdgViewport3D.GetZNear: TdgFloat;
begin
result := fZNear;
end;
procedure TdgViewport3D.SetZNear(const aValue: TdgFloat);
begin
fZNear := aValue;
end;
function TdgViewport3D.GetZFar: TdgFloat;
begin
result := fZFar;
end;
procedure TdgViewport3D.SetZFar(const aValue: TdgFloat);
begin
fZFar := aValue;
end;
function TdgViewport3D.GetAmbient: TdgVector4f;
begin
result := fAmbient;
end;
procedure TdgViewport3D.SetAmbient(const aValue: TdgVector4f);
begin
fAmbient := aValue;
end;
function dgCreate3DRenderSet: TObject;
begin
result := TdgViewport3D.Create;
end;
procedure dgAssign3DRenderSet(const aSource: TObject; aObject: TObject);
var
cSource: Tdg3DDrawNotifier;
cObject: Tdg3DDrawNotifier;
begin
{$IFDEF dgAssert}
dgTrace.Assert((aSource <> nil) or (aObject <> nil), '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName);
dgTrace.Assert((aSource is Tdg3DDrawNotifier) or (aObject is Tdg3DDrawNotifier), '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName);
{$ENDIF}
cSource := aSource as Tdg3DDrawNotifier;
cObject := aObject as Tdg3DDrawNotifier;
cObject.Position := cSource.Position;
cObject.Direction := cSource.Direction;
cObject.Up := cSource.Up;
cObject.FOV := cSource.FOV;
cObject.ZNear := cSource.ZNear;
cObject.ZFar := cSource.ZFar;
cObject.Ambient := cSource.Ambient;
end;
procedure dgLoad3DRenderSet(const aResource: TdgReadResource; aObject: TObject);
var
cObject: Tdg3DDrawNotifier;
begin
{$IFDEF dgAssert}
dgTrace.Assert(aObject <> nil, '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName);
dgTrace.Assert(aObject is Tdg3DDrawNotifier, '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName);
{$ENDIF}
cObject := aObject as Tdg3DDrawNotifier;
aResource.ReadOpenTag('3DRenderSet');
with cObject do
begin
aResource.ReadInteger('Version');
Position := aResource.ReadVector3f( 'Position');
Direction := aResource.ReadVector3f( 'Direction');
Up := aResource.ReadVector3f( 'Up');
FOV := aResource.ReadFloat('FOV');
ZNear := aResource.ReadFloat('ZNear');
ZFar := aResource.ReadFloat('ZFar');
Ambient := aResource.ReadVector4f('Ambient');
end;
aResource.ReadCloseTag('3DRenderSet');
end;
procedure dgSave3DRenderSet(const aResource: TdgWriteResource; aObject: TObject);
var
cObject: Tdg3DDrawNotifier;
begin
{$IFDEF dgAssert}
dgTrace.Assert(aObject <> nil, '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName);
dgTrace.Assert(aObject is Tdg3DDrawNotifier, '{99D74D65-C954-4CBC-B492-6E73A8975095}', cnstUnitName);
{$ENDIF}
cObject := aObject as Tdg3DDrawNotifier;
aResource.WriteOpenTag('3DRenderSet');
with cObject do
begin
aResource.WriteInteger(20080419, 'Version');
aResource.WriteVector3f(Position, 'Position');
aResource.WriteVector3f(Direction, 'Direction');
aResource.WriteVector3f(Up, 'Up');
aResource.WriteFloat( FOV, 'FOV');
aResource.WriteFloat( ZNear, 'ZNear');
aResource.WriteFloat( ZFar, 'ZFar');
aResource.WriteVector4f(Ambient, 'Ambient');
end;
aResource.WriteCloseTag('3DRenderSet');
end;
procedure dgInitViewport3D;
begin
dg.DrawNotifier.Viewport3D:=dg.CreateOnly.ObjectFactory(@dgSave3DRenderSet, @dgLoad3DRenderSet, @dgCreate3DRenderSet, @dgAssign3DRenderSet);
end;
end.
|
unit SourceTreeDumperVisitor;
interface
uses
Classes, SysUtils, StrUtils,
ParseTreeNode, ParseTreeNodeType,
SourceTreeWalker;
type
TSourceTreeDumperVisitor = class (TInterfacedObject, INodeVisitor)
private
FOutput: TStrings;
function GetNodeDepth(Node: TParseTreeNode): Integer;
protected
property Output: TStrings read FOutput;
public
constructor Create(AOutput: TStrings);
procedure Visit(Node: TParseTreeNode);
end;
implementation
{ TSourceTreeDumperVisitor }
{ Private declarations }
function TSourceTreeDumperVisitor.GetNodeDepth(Node: TParseTreeNode): Integer;
begin
Result := 0;
if Assigned(Node) then
Result := Result + 1 + GetNodeDepth(Node.Parent);
end;
{ Public declarations }
constructor TSourceTreeDumperVisitor.Create(AOutput: TStrings);
begin
inherited Create;
FOutput := AOutput;
end;
procedure TSourceTreeDumperVisitor.Visit(Node: TParseTreeNode);
begin
Output.Add(DupeString(' ', GetNodeDepth(Node)) + Node.Describe);
end;
end. |
unit sPropEditors;
{$I sDefs.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, sConst, ExtCtrls, sPanel, sGraphUtils, acntUtils, ImgList,
Consts, ComStrs, CommCtrl{$IFNDEF ALITE}, sDialogs, sPageControl{$ENDIF} , TypInfo,
{$IFDEF DELPHI6UP}DesignEditors, DesignIntf, VCLEditors,{$ELSE}dsgnintf,{$ENDIF}
sVclUtils, ColnEdit;
type
{$IFNDEF ALITE}
TsHintProperty = class(TCaptionProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetEditLimit: Integer; override;
procedure Edit; override;
end;
TsPageControlEditor = class(TDefaultEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TsFrameBarEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TsTabSheetEditor = class(TDefaultEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TacHintsTemplatesProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TacAlphaHintsEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TsPathDlgEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TacTemplateNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
{$ENDIF}
TacSkinInfoProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TsImageListEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TacImageIndexEditor = class(TIntegerProperty{$IFDEF DELPHI7UP}, ICustomPropertyListDrawing{$ENDIF})
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
function GetMyList:TCustomImageList;
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer);
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
end;
TacImgListItemsProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TsSkinSectionProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TsSkinNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TsDirProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TsInternalSkinsProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TacThirdPartyProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TacSkinManagerEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
procedure Register;
implementation
uses sDefaults, sSkinManager, FileCtrl, sMaskData, sSkinProps,
{$IFNDEF ALITE}
sToolEdit, sComboBoxes, sBitBtn,
sLabel, sStrEdit, acShellCtrls, acRootEdit, acPathDialog, sFrameBar,
sMemo, acAlphaHintsEdit, acNotebook, acAlphaHints,
{$ENDIF}
FiltEdit, sInternalSkins, stdreg, sSpeedButton, sStyleSimply, acAlphaImageList, sImgListEditor
{$IFNDEF BCB}, Notebreg{$ENDIF}, ac3rdPartyEditor, acSkinInfo;
{$IFNDEF ALITE}
{ TsPageControlEditor }
procedure TsPageControlEditor.ExecuteVerb(Index: Integer);
var
NewPage: TsTabSheet;
begin
case Index of
0: begin
NewPage := TsTabSheet.Create(Designer.GetRoot);
NewPage.Parent := (Component as TsPageControl);
NewPage.PageControl := (Component as TsPageControl);
NewPage.Caption := Designer.UniqueName('sTabSheet');
NewPage.Name := NewPage.Caption;
end;
1: begin
NewPage := TsTabSheet((Component as TsPageControl).ActivePage);
NewPage.Free;
end;
2: begin
(Component as TsPageControl).SelectNextPage(True);
end;
3: begin
(Component as TsPageControl).SelectNextPage(False);
end;
end;
if Designer <> nil then Designer.Modified;
end;
function TsPageControlEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: result := 'New Page';
1: result := 'Delete Page';
2: result := 'Next Page';
3: result := 'Previous Page';
end;
end;
function TsPageControlEditor.GetVerbCount: Integer;
begin
result := 4;
end;
{$ENDIF}
procedure Register;
begin
{$IFNDEF ALITE}
RegisterComponentEditor(TsPageControl, TsPageControlEditor);
RegisterComponentEditor(TsTabSheet, TsTabSheetEditor);
RegisterComponentEditor(TsFrameBar, TsFrameBarEditor);
RegisterComponentEditor(TsAlphaHints, TacAlphaHintsEditor);
{$IFNDEF BCB}
RegisterPropertyEditor(TypeInfo(TStrings), TsNotebook, 'Pages', TPageListProperty);
{$ENDIF}
RegisterPropertyEditor(TypeInfo(TsSkinSection), TObject, 'TabSkin', TsSkinSectionProperty);
RegisterPropertyEditor(TypeInfo(TsSkinSection), TObject, 'HeaderSkin', TsSkinSectionProperty);
{$ENDIF}
RegisterComponentEditor(TsAlphaImageList, TsImageListEditor);
RegisterPropertyEditor(TypeInfo(TsSkinSection), TObject, 'MenuLineSkin', TsSkinSectionProperty);
RegisterPropertyEditor(TypeInfo(TsSkinSection), TObject, 'IcoLineSkin', TsSkinSectionProperty);
RegisterPropertyEditor(TypeInfo(TsSkinSection), TObject, 'SkinSection', TsSkinSectionProperty);
RegisterPropertyEditor(TypeInfo(TsSkinSection), TObject, 'TitleSkin', TsSkinSectionProperty);
RegisterPropertyEditor(TypeInfo(TsSkinSection), TObject, 'ButtonSkin', TsSkinSectionProperty);
RegisterPropertyEditor(TypeInfo(TsSkinSection), TObject, 'CaptionSkin', TsSkinSectionProperty);
RegisterPropertyEditor(TypeInfo(TsSkinSection), TObject, 'ProgressSkin', TsSkinSectionProperty);
RegisterPropertyEditor(TypeInfo(TsSkinName), TsSkinManager, 'SkinName', TsSkinNameProperty);
RegisterPropertyEditor(TypeInfo(TsDirectory), TsSkinManager, 'SkinDirectory', TsDirProperty);
RegisterPropertyEditor(TypeInfo(TsStoredSkins), TsSkinManager, 'InternalSkins', TsInternalSkinsProperty);
RegisterPropertyEditor(TypeInfo(ThirdPartyList), TsSkinManager, 'ThirdParty', TacThirdPartyProperty);
RegisterPropertyEditor(TypeInfo(TsImgListItems), TsAlphaImageList, 'Items', TacImgListItemsProperty);
RegisterComponentEditor(TsSkinManager, TacSkinManagerEditor);
RegisterPropertyEditor(TypeInfo(TacSkinInfo), TsSkinManager, 'SkinInfo', TacSkinInfoProperty);
{$IFNDEF ALITE}
RegisterPropertyEditor(TypeInfo(Integer),TsSpeedButton,'ImageIndex',TAcImageIndexEditor);
RegisterPropertyEditor(TypeInfo(Integer),TsBitBtn,'ImageIndex',TAcImageIndexEditor);
RegisterPropertyEditor(TypeInfo(TacStrValue), TsAlphaHints, 'TemplateName', TacTemplateNameProperty);
RegisterPropertyEditor(TypeInfo(TacHintTemplates), TsAlphaHints, 'Templates', TacHintsTemplatesProperty);
{$IFNDEF TNTUNICODE}
RegisterPropertyEditor(TypeInfo(TCaption), TObject, 'Caption', TsHintProperty);
RegisterPropertyEditor(TypeInfo(String), TsMemo, 'Text', TsHintProperty);
{$ENDIF}
RegisterPropertyEditor(TypeInfo(string), TsFileNameEdit, 'Filter', TFilterProperty);
// Shell ctrls
RegisterPropertyEditor(TypeInfo(TacRoot), TsShellListView, 'Root', TacRootProperty);
RegisterPropertyEditor(TypeInfo(TacRoot), TsShellTreeView, 'Root', TacRootProperty);
RegisterPropertyEditor(TypeInfo(TacRoot), TsShellComboBox, 'Root', TacRootProperty);
RegisterPropertyEditor(TypeInfo(TacRoot), TsPathDialog, 'Root', TacRootProperty);
RegisterPropertyEditor(TypeInfo(TacRoot), TsDirectoryEdit, 'Root', TacRootProperty);
RegisterComponentEditor(TsPathDialog, TsPathDlgEditor);
{$ENDIF}
end;
{ TsSkinNameProperty }
function TsSkinNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList, paAutoUpdate];
end;
procedure TsSkinNameProperty.GetValues(Proc: TGetStrProc);
var
i: integer;
FileInfo: TSearchRec;
DosCode: Integer;
s : string;
begin
// Internal skins names loading
if TsSkinManager(GetComponent(0)).InternalSkins.Count > 0 then begin
for i := 0 to TsSkinManager(GetComponent(0)).InternalSkins.Count - 1 do begin
Proc(TsSkinManager(GetComponent(0)).InternalSkins[i].Name);
end;
end;
// External skins names loading
if DirectoryExists(TsSkinManager(GetComponent(0)).GetFullskinDirectory) then begin
s := TsSkinManager(GetComponent(0)).GetFullskinDirectory + '\*.*';
DosCode := FindFirst(s, faVolumeID or faDirectory, FileInfo);
try
while DosCode = 0 do begin
if (FileInfo.Name[1] <> '.') then begin
if {(SkinType in. [stUnpacked, stAllSkins]) and} (FileInfo.Attr and faDirectory = faDirectory) then begin
Proc(FileInfo.Name);
end
else if { (SkinType in [stPacked, stAllSkins]) and} (FileInfo.Attr and faDirectory <> faDirectory) and (ExtractFileExt(FileInfo.Name) = '.' + acSkinExt) then begin
s := ExtractWord(1, FileInfo.Name, ['.']);
Proc(s);
end;
end;
DosCode := FindNext(FileInfo);
end;
finally
FindClose(FileInfo);
end;
end;
end;
{ TsDirProperty }
function TsDirProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paAutoUpdate];
end;
procedure TsDirProperty.Edit;
var
s : string;
begin
s := TsSkinManager(GetComponent(0)).SkinDirectory;
if not directoryExists(s) then s := 'C:\';
{$IFNDEF ALITE}
if TsSkinManager(GetComponent(0)).SkinData.Active then begin
PathDialogForm := TPathDialogForm.Create(Application);
try
PathDialogForm.sShellTreeView1.Path := s;
if PathDialogForm.ShowModal = mrOk then begin
s := PathDialogForm.sShellTreeView1.Path;
if (s <> '') and DirectoryExists(s) then TsSkinManager(GetComponent(0)).SkinDirectory := s;
end;
finally
FreeAndNil(PathDialogForm);
end;
end
else
{$ENDIF}
if SelectDirectory('', '', s) then begin
if (s <> '') and DirectoryExists(s) then TsSkinManager(GetComponent(0)).SkinDirectory := s;
end;
end;
{ TsInternalSkinsProperty }
procedure TsInternalSkinsProperty.Edit;
var
i : integer;
begin
Application.CreateForm(TFormInternalSkins, FormInternalSkins);
FormInternalSkins.ListBox1.Clear;
FormInternalSkins.SkinManager := TsSkinManager(GetComponent(0));
for i := 0 to TsSkinManager(GetComponent(0)).InternalSkins.Count - 1 do begin
FormInternalSkins.ListBox1.Items.Add(TsSkinManager(GetComponent(0)).InternalSkins.Items[i].Name);
end;
if (FormInternalSkins.ShowModal = mrOk) and (Designer <> nil) then Designer.Modified;
if Assigned(FormInternalSkins) then FreeAndNil(FormInternalSkins);
inherited;
end;
function TsInternalSkinsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paAutoUpdate, paReadOnly];
end;
{ TacSkinManagerEditor }
procedure TacSkinManagerEditor.ExecuteVerb(Index: Integer);
var
i : integer;
sm : TsSkinManager;
begin
case Index of
0 : begin
sm := TsSkinManager(Component);
Application.CreateForm(TFormInternalSkins, FormInternalSkins);
FormInternalSkins.ListBox1.Clear;
FormInternalSkins.SkinManager := sm;
for i := 0 to sm.InternalSkins.Count - 1 do begin
FormInternalSkins.ListBox1.Items.Add(sm.InternalSkins.Items[i].Name);
end;
FormInternalSkins.ShowModal;
if Assigned(FormInternalSkins) then FreeAndNil(FormInternalSkins);
if Designer <> nil then Designer.Modified;
end;
1 : begin
Application.CreateForm(TForm3rdPartyEditor, Form3rdPartyEditor);
Form3rdPartyEditor.SM := TsSkinManager(Component);
Form3rdPartyEditor.sListView1.Items.Clear;
Form3rdPartyEditor.Populate;
Form3rdPartyEditor.ShowModal;
if Assigned(Form3rdPartyEditor) then FreeAndNil(Form3rdPartyEditor);
if Designer <> nil then Designer.Modified;
inherited;
end;
end;
inherited;
end;
function TacSkinManagerEditor.GetVerb(Index: Integer): string;
begin
case Index of
0 : Result := '&Internal skins...';
1 : Result := '&Third party controls...';
2 : Result := '-';
end;
end;
function TacSkinManagerEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{$IFNDEF ALITE}
{ TsTabSheetEditor }
procedure TsTabSheetEditor.ExecuteVerb(Index: Integer);
var
NewPage: TsTabSheet;
begin
case Index of
0: begin
NewPage := TsTabSheet.Create(Designer.GetRoot);
NewPage.Parent := TsTabSheet(Component).PageControl;
NewPage.PageControl := TsTabSheet(Component).PageControl;
NewPage.Caption := Designer.UniqueName('sTabSheet');
NewPage.Name := NewPage.Caption;
end;
1: begin
NewPage := TsTabSheet(TsTabSheet(Component).PageControl.ActivePage);
NewPage.Free;
end;
2: begin
TsTabSheet(Component).PageControl.SelectNextPage(True);
end;
3: begin
TsTabSheet(Component).PageControl.SelectNextPage(False);
end;
end;
if Designer <> nil then Designer.Modified;
end;
function TsTabSheetEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: result := 'New Page';
1: result := 'Delete Page';
2: result := 'Next Page';
3: result := 'Previous Page';
end;
end;
function TsTabSheetEditor.GetVerbCount: Integer;
begin
result := 4;
end;
{ TsHintProperty }
procedure TsHintProperty.Edit;
var
Temp: string;
Comp: TPersistent;
sed : TStrEditDlg;
begin
sed := TStrEditDlg.Create(Application);
with sed do try
Comp := GetComponent(0);
if Comp is TComponent then Caption := TComponent(Comp).Name + '.' + GetName else Caption := GetName;
Temp := GetStrValue;
Memo.Text := Temp;
{$IFNDEF TNTUNICODE}
Memo.MaxLength := GetEditLimit;
{$ENDIF}
UpdateStatus(nil);
if ShowModal = mrOk then begin
Temp := Memo.Text;
while (Length(Temp) > 0) and (Temp[Length(Temp)] < ' ') do System.Delete(Temp, Length(Temp), 1);
SetStrValue(Temp);
if Designer <> nil then Designer.Modified;
end;
finally
Free;
end;
end;
function TsHintProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog, paAutoUpdate];
end;
function TsHintProperty.GetEditLimit: Integer;
begin
if GetPropType^.Kind = tkString then Result := GetTypeData(GetPropType)^.MaxLength else Result := 1024;
end;
{ TsPathDlgEditor }
procedure TsPathDlgEditor.ExecuteVerb(Index: Integer);
begin
inherited;
TsPathDialog(Component).Execute;
end;
function TsPathDlgEditor.GetVerb(Index: Integer): string;
begin
case Index of
0 : Result := '&Test dialog...';
1 : Result := '-';
end;
end;
function TsPathDlgEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{ TsFrameBarEditor }
procedure TsFrameBarEditor.ExecuteVerb(Index: Integer);
begin
inherited;
ShowCollectionEditor(Designer, Component, (Component as TsFrameBar).Items, 'Items');
end;
function TsFrameBarEditor.GetVerb(Index: Integer): string;
begin
case Index of
0 : Result := '&Items editor...';
1 : Result := '-';
end;
end;
function TsFrameBarEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{ TacHintsTemplatesProperty }
procedure TacHintsTemplatesProperty.Edit;
begin
if EditHints(TsAlphaHints(GetComponent(0))) and (Designer <> nil) then Designer.Modified;
inherited;
end;
function TacHintsTemplatesProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paAutoUpdate, paReadOnly];
end;
{ TacAlphaHintsEditor }
procedure TacAlphaHintsEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0 : if EditHints(TsAlphaHints(Component)) and (Designer <> nil) then Designer.Modified;
end;
end;
function TacAlphaHintsEditor.GetVerb(Index: Integer): string;
begin
case Index of
0 : Result := '&Hints templates editor...';
end;
end;
function TacAlphaHintsEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{ TacTemplateNameProperty }
function TacTemplateNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
procedure TacTemplateNameProperty.GetValues(Proc: TGetStrProc);
var
i : integer;
begin
inherited;
for i := 0 to TsAlphaHints(GetComponent(0)).Templates.Count - 1 do begin
Proc(TsAlphaHints(GetComponent(0)).Templates[i].Name);
end;
end;
{$ENDIF}
{ TsSkinSectionProperty }
function TsSkinSectionProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList, paAutoUpdate, paMultiSelect];
end;
procedure TsSkinSectionProperty.GetValues(Proc: TGetStrProc);
var
i, l : integer;
begin
inherited;
if Assigned(DefaultManager) and (Length(DefaultManager.gd) > 0) then begin
l := Length(DefaultManager.gd);
for i := 0 to l - 1 do if DefaultManager.gd[i].ClassName <> s_GlobalInfo then Proc(DefaultManager.gd[i].ClassName);
end;
end;
{ TacImageIndexEditor }
function TacImageIndexEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paRevertable];
end;
function TacImageIndexEditor.GetMyList: TCustomImageList;
begin
Result := TCustomImageList(GetObjectProp(GetComponent(0), 'Images', TObject));
end;
procedure TacImageIndexEditor.GetValues(Proc: TGetStrProc);
var
i: Integer;
MyList: TCustomImageList;
begin
MyList := GetMyList;
if Assigned(MyList) then
for i := 0 to MyList.Count-1 do Proc(IntToStr(i));
end;
procedure TacImageIndexEditor.ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
var
MyLeft: Integer;
MyList: TCustomImageList;
begin
ACanvas.FillRect(ARect);
MyList := GetMyList;
MyLeft := ARect.Left + 2;
if Assigned(MyList) then begin
MyList.Draw(ACanvas,MyLeft, ARect.Top + 2, StrToInt(Value));
Inc(MyLeft, MyList.Width);
end;
ACanvas.TextOut(MyLeft + 2, ARect.Top + 1,Value);
end;
procedure TacImageIndexEditor.ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer);
var
MyList: TCustomImageList;
begin
MyList := GetMyList;
AHeight := ACanvas.TextHeight(Value) + 2;
if Assigned(MyList) and (MyList.Height + 4 > AHeight) then AHeight := MyList.Height + 4;
end;
procedure TacImageIndexEditor.ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer);
var
MyList: TCustomImageList;
begin
MyList := GetMyList;
AWidth := ACanvas.TextWidth(Value) + 4;
if Assigned(MyList) then Inc(AWidth, MyList.Width);
end;
{ TacThirdPartyProperty }
procedure TacThirdPartyProperty.Edit;
begin
Application.CreateForm(TForm3rdPartyEditor, Form3rdPartyEditor);
Form3rdPartyEditor.SM := TsSkinManager(GetComponent(0));
Form3rdPartyEditor.sListView1.Items.Clear;
Form3rdPartyEditor.Populate;
Form3rdPartyEditor.ShowModal;
if Assigned(Form3rdPartyEditor) then FreeAndNil(Form3rdPartyEditor);
if Designer <> nil then Designer.Modified;
inherited;
end;
function TacThirdPartyProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paAutoUpdate, paReadOnly];
end;
{ TacImgListItemsProperty }
procedure TacImgListItemsProperty.Edit;
var
Form : TFormImgListEditor;
begin
Application.CreateForm(TFormImgListEditor, Form);
Form.InitFromImgList(TsAlphaImageList(GetComponent(0)));
Form.ShowModal;
FreeAndNil(Form);
if Designer <> nil then Designer.Modified;
end;
function TacImgListItemsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paReadOnly];
end;
{ TacSkinInfoProperty }
procedure TacSkinInfoProperty.Edit;
begin
if TsSkinManager(GetComponent(0)).SkinData.Active then begin
SkinInfoForm := TSkinInfoForm.Create(Application);
SkinInfoForm.sMemo1.Lines.Add('Name : ' + TsSkinManager(GetComponent(0)).SkinName);
SkinInfoForm.sMemo1.Lines.Add('Version : ' + TsSkinManager(GetComponent(0)).SkinInfo);
SkinInfoForm.sMemo1.Lines.Add('Author : ' + TsSkinManager(GetComponent(0)).SkinData.Author);
SkinInfoForm.sMemo1.Lines.Add('Description : ' + TsSkinManager(GetComponent(0)).SkinData.Description);
if TsSkinManager(GetComponent(0)).SkinData.Version < CompatibleSkinVersion then begin
SkinInfoForm.Label1.Visible := True
end;
try
SkinInfoForm.ShowModal;
finally
FreeAndNil(SkinInfoForm);
end;
end
else MessageDlg('Skins are not activated.', mtInformation, [mbOK], 0);
end;
function TacSkinInfoProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paReadOnly, paFullWidthName];
end;
{ TsImageListEditor }
procedure TsImageListEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: begin
Application.CreateForm(TFormImgListEditor, FormImgListEditor);
FormImgListEditor.InitFromImgList(Component as TsAlphaImageList);
FormImgListEditor.ShowModal;
FreeAndNil(FormImgListEditor);
end;
end;
if Designer <> nil then Designer.Modified;
end;
function TsImageListEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: result := '&ImageList editor...';
end;
end;
function TsImageListEditor.GetVerbCount: Integer;
begin
result := 1;
end;
end.
|
{----------------------------------------------------------------------
DEVIUM Content Management System
Copyright (C) 2004 by DEIV Development Team.
http://www.deiv.com/
$Header: /devium/Devium\040CMS\0402/Source/Common/PluginIntf.pas,v 1.2 2004/04/07 10:33:59 paladin Exp $
------------------------------------------------------------------------}
unit PluginIntf;
interface
uses PluginManagerIntf;
const
RegisterPluginName = 'RegisterPlugin';
type
TRegisterPlugin = function(Module: HMODULE; PluginManager: IPluginManager): Boolean;
IPlugin = interface (IInterface)
['{6D5AF092-4AF3-4C1B-8EDC-C76007103B08}']
function GetModule: HMODULE;
function GetName: string;
function Load: Boolean;
function UnLoad: Boolean;
property Module: HMODULE read GetModule;
property Name: string read GetName;
end;
TPlugin = class (TInterfacedObject)
protected
FModule: HMODULE;
FPluginManager: IPluginManager;
public
constructor Create(Module: HMODULE; PluginManager: IPluginManager);
function GetModule: HMODULE;
property Module: HMODULE read GetModule;
end;
implementation
{
*********************************** TPlugin ************************************
}
constructor TPlugin.Create(Module: HMODULE; PluginManager: IPluginManager);
begin
inherited Create;
FModule := Module;
FPluginManager := PluginManager;
end;
function TPlugin.GetModule: HMODULE;
begin
Result := FModule;
end;
end.
|
unit uMainForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ExtDlgs, Spin, Buttons, ComCtrls,
BZClasses, BZStopWatch, BZColors, BZGraphic, BZBitmap, BZBitmapIO;
type
{ TMainForm }
TMainForm = class(TForm)
Panel1 : TPanel;
pnlViewSrc : TPanel;
pnlViewDest : TPanel;
btnOpenImg : TButton;
opd : TOpenPictureDialog;
btnGenerate : TButton;
pnlBottom : TPanel;
lblRayHmax : TLabel;
lblHmax : TLabel;
lblRayAngle : TLabel;
lblOmbre : TLabel;
SpinOmbre : TSpinEdit;
spinRayAngle : TFloatSpinEdit;
spinHmax : TFloatSpinEdit;
spinRayHmax : TFloatSpinEdit;
btnSaveImg : TButton;
Bar : TProgressBar;
chkExpMode : TCheckBox;
chkBlur : TCheckBox;
spinBlurFactor : TFloatSpinEdit;
Label1 : TLabel;
btnLightColor : TColorButton;
spd : TSavePictureDialog;
procedure btnGenerateClick(Sender : TObject);
procedure btnOpenImgClick(Sender : TObject);
procedure FormCloseQuery(Sender : TObject; var CanClose : boolean);
procedure FormClose(Sender : TObject; var CloseAction : TCloseAction);
procedure pnlViewSrcPaint(Sender : TObject);
procedure pnlViewDestPaint(Sender : TObject);
procedure FormShow(Sender : TObject);
procedure btnSaveImgClick(Sender : TObject);
private
FDisplayBufferSrc, FDisplayBufferDst : TBZBitmap;
FBmpSrc, FBmpDst : TBZBitmap;
FStopWatch : TBZStopWatch;
protected
procedure DoLightmap(aSrc, aDst: TBZBitmap; aVO: Byte; aAR, aHR, aHP: Single; ClrLight : TBZColor);
public
end;
var
MainForm : TMainForm;
implementation
{$R *.lfm}
uses
Math,BZMath;
procedure TMainForm.DoLightmap(aSrc, aDst: TBZBitmap; aVO: Byte; aAR, aHR, aHP: Single; ClrLight : TBZColor);
var
pSrcX, pSrcY : PBZColor; //PByte;
pDstX, pDstY : PBZColor;
OutColor, ClrOmbre : TBZColor;
//ClrLight : TBZColor;
x, y, W, H, dZ, Zo, Zr, HR : Integer;
z_step, z_origine, z_rayon: single;
function ControlCouleur(const AC, AX: Byte): Byte; inline;
begin
if (255 - AC) > AX then
Result := (AC + AX)
else
Result := 255;
End;
begin
// dXSrc := aSrc.RawImage.Description.BitsPerPixel div 8;
FStopWatch.Start();
W := aDst.MaxWidth;
H := aDst.MaxHeight;
ClrOmbre.Create(aVo,aVo,aVo);
//ClrLight.Create(79,79,79);
// Calcul du pas en z pour chaque rayon
//z_step := abs(1 / tan(DegToRadian(AAR)));
dz := round( 65280.0*Math.cotan(DegToRadian(aAR))/aHP);
HR := round((65280.0*aHR)/aHP);
aDst.Clear(ClrOmbre);
// Lancement des rayons dans le sens horizontal et de gauche a droite.
Bar.Max := H ;
for y := 0 to H do
begin
Bar.Position := y;
pDstY := aDst.GetScanLine(y);
pSrcY := aSrc.GetScanLine(y);
// Lancements des rayons pour chaque hauteur en remontant suivant l'axe z
//z_origine := 0.0;
Zo := 0;
while Zo < HR do
//while Z_Origine < aHR do
begin // Lancement de rayon.
Zr := Zo;
pSrcX := pSrcY;
pDstX := pDstY;
//z_rayon := z_origine;
for x := 0 to W do
begin
if ((pSrcX^.Red shl 8) >= Zr) then
//if (((pSrcX^.Red * _FloatColorRatio ) * aHP ) >= z_rayon) then
begin
if chkExpMode.Checked then
begin
asm // Exponentielle (mettre ClrLight.int à -1)
mov r8, pDstX // en 1 - e^(-nb_impacts)
pxor xmm0, xmm0
movd xmm2, ClrLight
movd xmm1, [r8]
punpcklbw xmm2, xmm0 // xmm2 = ClrLight en 16 bits
punpcklbw xmm1, xmm0 // xmm1 = pDstXo^ en 16 bits
psubw xmm2, xmm1 // xmm2 = ClrLight-pDstXo^ (par composante)
psraw xmm2, 2 // xmm3 =(ClrLight-pDstXo^)/2^n (par composante)
paddw xmm1, xmm2 // xmm1 = ClrLight+(pDstXo^-ClrLight)/16 (par comp)
packuswb xmm1, xmm0
movd [r8], xmm1
end;
end
else
begin
// Linéaire selon nb_impacts
{$IFDEF WINDOWS}
{$IFDEF CPU32}
asm
push rdx
mov rdx, pDstX
movd xmm2, ClrLight
movd xmm1, [rdx]
paddusb xmm2, xmm1
movd [rdx], xmm2
pop rdx
end;
{$ELSE}
asm
mov r8d, pDstX
movd xmm2, ClrLight
movd xmm1, [r8d]
paddusb xmm2, xmm1
movd [r8d], xmm2
end;
{$ENDIF}
{$ELSE}
OutColor.Red := ControlCouleur(pDstX^.Red, ClrLight.Red);
OutColor.Green := ControlCouleur(pDstX^.Green, ClrLight.Green);
OutColor.Blue := ControlCouleur(pDstX^.Blue, ClrLight.Blue);
OutColor.Alpha := 255;
pDstx^:= OutColor;
{$ENDIF}
end;
break;
End;
inc(pSrcX);
inc(pDstX);
Zr := Zr - dZ;
//z_rayon := z_rayon - z_step;
end;
//z_origine := z_origine + z_step;
Zo := Zo + dZ;
end;
end;
FStopWatch.Stop;
if chkBlur.Checked then FBmpDst.BlurFilter.BoxBlur(Round(spinBlurFactor.Value)); // .GaussianBoxBlur(spinBlurFactor.Value);
pnlViewDest.Invalidate;
Caption := 'Temps : '+FStopWatch.getValueAsMilliSeconds;
Bar.Position := 0;
end;
procedure TMainForm.btnGenerateClick(Sender : TObject);
Var
lc : TBZColor;
begin
lc.Create(btnLightColor.ButtonColor);
DoLightmap(FBmpSrc, FBmpDst, spinOmbre.Value, spinRayAngle.Value, spinRayHmax.Value, spinHmax.Value,lc);
end;
procedure TMainForm.btnOpenImgClick(Sender : TObject);
begin
if opd.Execute then
begin
FBmpSrc.LoadFromFile(opd.FileName);
FBmpDst.SetSize(FBmpSrc.Width, FBmpSrc.Height);
pnlViewSrc.Invalidate;
end;
end;
procedure TMainForm.FormCloseQuery(Sender : TObject; var CanClose : boolean);
begin
FreeAndNil(FStopWatch);
CanClose := True;
end;
procedure TMainForm.FormClose(Sender : TObject; var CloseAction : TCloseAction);
begin
FreeAndNil(FDisplayBufferDst);
FreeAndNil(FDisplayBufferSrc);
FreeAndNil(FBmpDst);
FreeAndNil(FBmpSrc);
end;
procedure TMainForm.pnlViewSrcPaint(Sender : TObject);
begin
FDisplayBufferSrc.Assign(FBmpSrc);
FDisplayBufferSrc.Transformation.Stretch(pnlViewSrc.Width,pnlViewSrc.Height);
FDisplayBufferSrc.DrawToCanvas(pnlViewSrc.Canvas, pnlViewSrc.ClientRect,true,true);
end;
procedure TMainForm.pnlViewDestPaint(Sender : TObject);
begin
FDisplayBufferDst.Assign(FBmpDst);
FDisplayBufferDst.Transformation.Stretch(pnlViewDest.Width,pnlViewDest.Height);
FDisplayBufferDst.DrawToCanvas(pnlViewDest.Canvas, pnlViewDest.ClientRect,true,true);
end;
procedure TMainForm.FormShow(Sender : TObject);
begin
FBmpSrc := TBZBitmap.Create(256,256);
FBmpDst := TBZBitmap.Create(256,256);
FDisplayBufferSrc := TBZBitmap.Create(256,256);
FDisplayBufferDst := TBZBitmap.Create(256,256);
FStopWatch := TBZStopWatch.Create(self);
end;
procedure TMainForm.btnSaveImgClick(Sender : TObject);
var
bmp : TBitmap;
begin
if spd.Execute then
begin
Bmp := FBmpDst.ExportToBitmap;
Bmp.SaveToFile(spd.FileName);
FreeAndNil(Bmp);
end;
end;
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Frustum;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasVulkan.Types,
PasVulkan.Math;
type { TpvFrustum }
TpvFrustum=record
public
const COMPLETE_OUT=0;
PARTIALLY_IN=1;
COMPLETE_IN=2;
type TFrustumSide=
(
Left,
Right,
Top,
Bottom,
Near_,
Far_
);
TPlanes=array[TFrustumSide] of TpvPlane;
TAbsoluteNormals=array[TFrustumSide] of TpvVector3;
TCorners=array[0..7] of TpvVector3;
private
fPlanes:TPlanes;
fAbsoluteNormals:TAbsoluteNormals;
public
procedure Init(const aViewMatrix,aProjectionMatrix:TpvMatrix4x4);
class function ExtractFrustumSphere(const aZNear,aZFar,aFOV,aAspectRatio:TpvScalar;const aPosition,aDirection:TpvVector3):TpvSphere; static;
function AABBInFrustum(const aAABB:TpvAABB):TpvInt32; overload;
function AABBInFrustum(const aAABB:TpvAABB;var aMask:TpvUInt32):TpvInt32; overload;
function SphereInFrustum(const aSphere:TpvSphere;const aRadius:TpvScalar=0.0):TpvInt32;
function PointInFrustum(const aPoint:TpvVector3):boolean;
public
property Planes:TPlanes read fPlanes write fPlanes;
property AbsoluteNormals:TAbsoluteNormals read fAbsoluteNormals write fAbsoluteNormals;
end;
PpvFrustum=^TpvFrustum;
TpvFrustumDynamicArray=array of TpvFrustum;
implementation
function IntersectionPoint(const a,b,c:TpvPlane):TpvVector3;
begin
result:=((b.Normal.Cross(c.Normal)*a.Distance)+
(c.Normal.Cross(a.Normal)*b.Distance)+
(a.Normal.Cross(b.Normal)*c.Distance))/(-a.Normal.Dot(b.Normal.Cross(c.Normal)));
end;
procedure TpvFrustum.Init(const aViewMatrix,aProjectionMatrix:TpvMatrix4x4);
var FrustumSide:TFrustumSide;
ViewProjectionMatrix:TpvMatrix4x4;
begin
ViewProjectionMatrix:=aViewMatrix*aProjectionMatrix;
fPlanes[TFrustumSide.Left]:=TpvPlane.Create(ViewProjectionMatrix.Rows[3]+ViewProjectionMatrix.Rows[0]).Normalize;
fPlanes[TFrustumSide.Right]:=TpvPlane.Create(ViewProjectionMatrix.Rows[3]-ViewProjectionMatrix.Rows[0]).Normalize;
fPlanes[TFrustumSide.Top]:=TpvPlane.Create(ViewProjectionMatrix.Rows[3]-ViewProjectionMatrix.Rows[1]).Normalize;
fPlanes[TFrustumSide.Bottom]:=TpvPlane.Create(ViewProjectionMatrix.Rows[3]+ViewProjectionMatrix.Rows[1]).Normalize;
fPlanes[TFrustumSide.Near_]:=TpvPlane.Create(ViewProjectionMatrix.Rows[2]+ViewProjectionMatrix.Rows[2]).Normalize;
fPlanes[TFrustumSide.Far_]:=TpvPlane.Create(ViewProjectionMatrix.Rows[3]-ViewProjectionMatrix.Rows[2]).Normalize;
for FrustumSide:=Low(TFrustumSide) to High(TFrustumSide) do begin
fAbsoluteNormals[FrustumSide]:=fPlanes[FrustumSide].Normal.Abs;
end;
{fWorldSpaceCorners[0]:=IntersectionPoint(fPlanes[TFrustumSide.Near_],fPlanes[TFrustumSide.Left],fPlanes[TFrustumSide.Top]);
fWorldSpaceCorners[1]:=IntersectionPoint(fPlanes[TFrustumSide.Near_],fPlanes[TFrustumSide.Right],fPlanes[TFrustumSide.Top]);
fWorldSpaceCorners[2]:=IntersectionPoint(fPlanes[TFrustumSide.Near_],fPlanes[TFrustumSide.Right],fPlanes[TFrustumSide.Bottom]);
fWorldSpaceCorners[3]:=IntersectionPoint(fPlanes[TFrustumSide.Near_],fPlanes[TFrustumSide.Left],fPlanes[TFrustumSide.Bottom]);
fWorldSpaceCorners[4]:=IntersectionPoint(fPlanes[TFrustumSide.Far_],fPlanes[TFrustumSide.Left],fPlanes[TFrustumSide.Top]);
fWorldSpaceCorners[5]:=IntersectionPoint(fPlanes[TFrustumSide.Far_],fPlanes[TFrustumSide.Right],fPlanes[TFrustumSide.Top]);
fWorldSpaceCorners[6]:=IntersectionPoint(fPlanes[TFrustumSide.Far_],fPlanes[TFrustumSide.Right],fPlanes[TFrustumSide.Bottom]);
fWorldSpaceCorners[7]:=IntersectionPoint(fPlanes[TFrustumSide.Far_],fPlanes[TFrustumSide.Left],fPlanes[TFrustumSide.Bottom]);}
end;
class function TpvFrustum.ExtractFrustumSphere(const aZNear,aZFar,aFOV,aAspectRatio:TpvScalar;const aPosition,aDirection:TpvVector3):TpvSphere;
var ViewLen,Width,Height:TpvScalar;
begin
ViewLen:=aZFar-aZNear;
Height:=ViewLen*tan(aFOV*0.5);
Width:=Height*aAspectRatio;
result.Radius:=TpvVector3.Create(Width,Height,ViewLen).DistanceTo(TpvVector3.Create(0.0,0.0,aZNear+(ViewLen*0.5)));
result.Center:=aPosition+(aDirection*((ViewLen*0.5)+aZNear));
end;
function TpvFrustum.AABBInFrustum(const aAABB:TpvAABB):TpvInt32;
var FrustumSide:TFrustumSide;
DistanceFromCenter,PlaneAbsoluteNormalDotExtents:TpvScalar;
Center,Extents:TpvVector3;
begin
Center:=(aAABB.Min+aAABB.Max)*0.5;
Extents:=(aAABB.Max-aAABB.Min)*0.5;
result:=COMPLETE_IN;
for FrustumSide:=Low(TFrustumSide) to High(TFrustumSide) do begin
DistanceFromCenter:=fPlanes[FrustumSide].DistanceTo(Center);
PlaneAbsoluteNormalDotExtents:=fAbsoluteNormals[FrustumSide].Dot(Extents);
if (DistanceFromCenter+PlaneAbsoluteNormalDotExtents)<0.0 then begin
result:=COMPLETE_OUT;
exit;
end else if (DistanceFromCenter-PlaneAbsoluteNormalDotExtents)<0.0 then begin
result:=PARTIALLY_IN;
end;
end;
end;
function TpvFrustum.AABBInFrustum(const aAABB:TpvAABB;var aMask:TpvUInt32):TpvInt32;
var FrustumSide:TFrustumSide;
Bit,InMask,OutMask:TpvUInt32;
DistanceFromCenter,PlaneAbsoluteNormalDotExtents:TpvScalar;
Center,Extents:TpvVector3;
begin
Center:=(aAABB.Min+aAABB.Max)*0.5;
Extents:=(aAABB.Max-aAABB.Min)*0.5;
result:=COMPLETE_IN;
InMask:=aMask;
OutMask:=$40000000;
Bit:=1;
for FrustumSide:=Low(TFrustumSide) to High(TFrustumSide) do begin
if (InMask and Bit)<>0 then begin
DistanceFromCenter:=fPlanes[FrustumSide].DistanceTo(Center);
PlaneAbsoluteNormalDotExtents:=fAbsoluteNormals[FrustumSide].Dot(Extents);
if (DistanceFromCenter+PlaneAbsoluteNormalDotExtents)<0.0 then begin
aMask:=0;
result:=COMPLETE_OUT;
exit;
end else if (DistanceFromCenter-PlaneAbsoluteNormalDotExtents)<0.0 then begin
OutMask:=OutMask or (Bit or $80000000);
result:=PARTIALLY_IN;
end;
end;
inc(Bit,Bit);
end;
aMask:=OutMask;
end;
function TpvFrustum.SphereInFrustum(const aSphere:TpvSphere;const aRadius:TpvScalar=0.0):TpvInt32;
var FrustumSide:TFrustumSide;
Count:TpvSizeInt;
Distance,Radius:TpvScalar;
begin
Count:=0;
Radius:=aSphere.Radius+aRadius;
for FrustumSide:=Low(TFrustumSide) to High(TFrustumSide) do begin
Distance:=fPlanes[FrustumSide].DistanceTo(aSphere.Center);
if Distance<=(-Radius) then begin
result:=COMPLETE_OUT;
exit;
end else if Distance>Radius then begin
inc(Count);
end;
end;
if Count=6 then begin
result:=COMPLETE_IN;
end else begin
result:=PARTIALLY_IN;
end;
end;
function TpvFrustum.PointInFrustum(const aPoint:TpvVector3):boolean;
var FrustumSide:TFrustumSide;
begin
result:=true;
for FrustumSide:=Low(TFrustumSide) to High(TFrustumSide) do begin
if fPlanes[FrustumSide].DistanceTo(aPoint)<=0.0 then begin
result:=false;
break;
end;
end;
end;
end.
|
unit fbapiquery;
interface
uses SysUtils, Classes, DB, IB, fbapidatabase, FBMessages;
type
TFbApiQuery = class(TComponent)
private
// FDatabase: TFbApiDatabase;
// FTransaction: TFbApiTransaction;
FStatement: IStatement;
FResultSet: IResultSet;
FSQL: TStrings;
FActive: Boolean;
FParams: TParams;
FResults: IResults;
FOnSQLChanging: TNotifyEvent;
FBOF: Boolean;
FEOF: Boolean;
FMetaData: IMetaData;
FOnSQLChanged: TNotifyEvent;
FRecordCount: Integer;
FSQLParams: ISQLParams;
FParamCheck: Boolean;
FGenerateParamNames: Boolean;
FCaseSensitiveParameterNames: Boolean;
FBase: TIBBase;
FIsTransactionOwner: Boolean;
procedure SetActive(const Value: Boolean);
function GetActive: Boolean;
// function getStatement: IStatement;
procedure SQLChanging(Sender: TObject);
procedure SQLChanged(Sender: TObject);
function GetEOF: Boolean;
function GetFieldCount: Integer;
function GetFieldIndex(FieldName: String): Integer;
function GetFieldMetadata(const Idx: Integer): IColumnMetaData;
function GetFields(const Idx: Integer): ISQLData;
function GetOpen: Boolean;
function GetPlan: String;
function GetPrepared: Boolean;
function GetRecordCount: Integer;
function GetRowsAffected: Integer;
function GetSQLParams: ISQLParams;
function GetSQLStatementType: TIBSQLStatementTypes;
procedure SetDatabase(const Value: TFbApiDatabase);
function GetDatabase: TFbApiDatabase;
function GetTransaction: TFbApiTransaction;
procedure SetTransaction(const Value: TFbApiTransaction);
procedure SetIsTransactionOwner(const Value: Boolean);
// function GetOpen:Boolean;
public
constructor Create(Owner: TComponent); override;
destructor Destroy(); override;
procedure CheckClosed; { raise error if query is not closed. }
procedure CheckOpen; { raise error if query is not open. }
procedure CheckValidStatement; { raise error if statement is invalid. }
procedure Close;
procedure CloseWithTransaction(bCommit: Boolean = True);
procedure ExecQuery;
function HasField(const FieldName: String): Boolean;
{ Note: case sensitive match }
function FieldByName(const FieldName: String): ISQLData;
function ParamByName(const ParamName: String): ISQLParam;
procedure FreeHandle;
function Next: Boolean;
procedure Prepare;
function GetUniqueRelationName: String;
property Bof: Boolean read FBOF;
property Eof: Boolean read GetEOF;
property Current: IResults read FResults;
property Fields[const Idx: Integer]: ISQLData read GetFields; default;
property FieldsMetadata[const Idx: Integer]: IColumnMetaData read GetFieldMetadata;
property FieldIndex[FieldName: String]: Integer read GetFieldIndex;
property FieldCount: Integer read GetFieldCount;
property IsOpen: Boolean read GetOpen;
property Params: ISQLParams read GetSQLParams;
property Plan: String read GetPlan;
property Prepared: Boolean read GetPrepared;
property RecordCount: Integer read GetRecordCount;
property RowsAffected: Integer read GetRowsAffected;
property SQLStatementType: TIBSQLStatementTypes read GetSQLStatementType;
property UniqueRelationName: String read GetUniqueRelationName;
property Statement: IStatement read FStatement;
property MetaData: IMetaData read FMetaData;
property CaseSensitiveParameterNames: Boolean
read FCaseSensitiveParameterNames write FCaseSensitiveParameterNames;
property Database: TFbApiDatabase read GetDatabase write SetDatabase;
property GenerateParamNames: Boolean read FGenerateParamNames
write FGenerateParamNames;
property IsTransactionOwner: Boolean read FIsTransactionOwner
write SetIsTransactionOwner;
property Transaction: TFbApiTransaction read GetTransaction
write SetTransaction;
property Active: Boolean read GetActive write SetActive;
property ParamCheck: Boolean read FParamCheck write FParamCheck;
property SQL: TStrings read FSQL;
property OnSQLChanging: TNotifyEvent read FOnSQLChanging
write FOnSQLChanging;
property OnSQLChanged: TNotifyEvent read FOnSQLChanged write FOnSQLChanged;
end;
implementation
{ TFbApiQuery }
procedure TFbApiQuery.CheckClosed;
begin
if FResultSet <> nil then
IBError(ibxeSQLOpen, [nil]);
end;
procedure TFbApiQuery.CheckOpen;
begin
if FResultSet = nil then
IBError(ibxeSQLClosed, [nil]);
end;
procedure TFbApiQuery.CheckValidStatement;
begin
// FBase.CheckTransaction; ???
if (FStatement = nil) then
IBError(ibxeInvalidStatementHandle, [nil]);
end;
procedure TFbApiQuery.Close;
begin
if FResults <> nil then
FResults.SetRetainInterfaces(false);
FResultSet := nil;
FResults := nil;
FBOF := false;
FEOF := false;
FRecordCount := 0;
{ if (FBase.IsTransactionOwner and Assigned(FTransaction)) then
begin
if FTransaction.Active then
fTransaction.Commit;
FTransaction.Free;
end; }
end;
procedure TFbApiQuery.CloseWithTransaction(bCommit: Boolean);
begin
Close;
if (Transaction.InTransaction) then
begin
if bCommit then
Transaction.Commit
else
Transaction.Rollback;
end;
end;
constructor TFbApiQuery.Create(Owner: TComponent);
begin
inherited;
FSQL := TStringList.Create;
TStringList(FSQL).OnChanging := SQLChanging;
TStringList(FSQL).OnChange := SQLChanged;
FParamCheck := True;
FBase := TIBBase.Create(self);
end;
destructor TFbApiQuery.Destroy;
begin
if ((IsTransactionOwner or FBase.IsTransactionOwner) and
Assigned(FBase.Transaction)) then
begin
if FBase.Transaction.Active then
// FBase.Transaction.Commit;
FBase.Transaction.Close;
end;
FreeAndNil(FSQL);
FreeAndNil(FBase);
inherited;
end;
procedure TFbApiQuery.ExecQuery;
{$IFDEF IBXQUERYSTATS}
var
stats: TPerfCounters;
{$ENDIF}
{$IFDEF IBXQUERYTIME}
var
tmsecs: comp;
{$ENDIF}
begin
CheckClosed;
if not Prepared then
Prepare;
CheckValidStatement;
{$IFDEF IBXQUERYTIME}
tmsecs := TimeStampToMSecs(DateTimeToTimeStamp(Now));
{$ENDIF}
if SQLStatementType = SQLSelect then
begin
FResultSet := FStatement.OpenCursor;
FResults := FResultSet;
FResults.SetRetainInterfaces(True);
FBOF := True;
FEOF := false;
FRecordCount := 0;
// if not (csDesigning in ComponentState) then
// MonitorHook.SQLExecute(Self);
// if FGoToFirstRecordOnExecute then
Next;
end
else
begin
FResults := FStatement.Execute;
// if not (csDesigning in ComponentState) then
// MonitorHook.SQLExecute(Self);
end;
{$IFDEF IBXQUERYTIME}
writeln('Executing ', FStatement.GetSQLText, ' Response time= ',
Format('%f msecs', [TimeStampToMSecs(DateTimeToTimeStamp(Now)) - tmsecs]));
{$ENDIF}
{$IFDEF IBXQUERYSTATS}
if FStatement.GetPerfStatistics(stats) then
writeln('Executing ', FStatement.GetSQLText, ' Elapsed time= ',
FormatFloat('#0.000', stats[psRealTime] / 1000), ' sec');
{$ENDIF}
// FBase.DoAfterExecQuery(self);
end;
function TFbApiQuery.FieldByName(const FieldName: String): ISQLData;
begin
if FResults = nil then
IBError(ibxeNoFieldAccess, [nil]);
Result := FResults.ByName(FieldName);
if Result = nil then
IBError(ibxeFieldNotFound, [FieldName]);
end;
procedure TFbApiQuery.FreeHandle;
begin
if FStatement <> nil then
FStatement.SetRetainInterfaces(false);
Close;
FStatement := nil;
FResults := nil;
FResultSet := nil;
FMetaData := nil;
FSQLParams := nil;
end;
function TFbApiQuery.GetActive: Boolean;
begin
Result := Assigned(FStatement) and Assigned(FResultSet);
end;
function TFbApiQuery.GetDatabase: TFbApiDatabase;
begin
Result := FBase.Database;
end;
function TFbApiQuery.GetEOF: Boolean;
begin
Result := FEOF or (FResultSet = nil);
end;
function TFbApiQuery.GetFieldCount: Integer;
begin
if FResults = nil then
IBError(ibxeNoFieldAccess, [nil]);
Result := FResults.GetCount;
end;
function TFbApiQuery.GetFieldIndex(FieldName: String): Integer;
var
Field: IColumnMetaData;
begin
if FMetaData = nil then
IBError(ibxeNoFieldAccess, [nil]);
Field := FMetaData.ByName(FieldName);
if Field = nil then
Result := -1
else
Result := Field.GetIndex;
end;
function TFbApiQuery.GetFieldMetadata(const Idx: Integer): IColumnMetaData;
var
Field: IColumnMetaData;
begin
if FMetaData = nil then
IBError(ibxeNoFieldAccess, [nil]);
Result := FMetaData.getColumnMetadata(Idx);
end;
function TFbApiQuery.GetFields(const Idx: Integer): ISQLData;
begin
if FResults = nil then
IBError(ibxeNoFieldAccess, [nil]);
if (Idx < 0) or (Idx >= FResults.GetCount) then
IBError(ibxeFieldNotFound, [IntToStr(Idx)]);
Result := FResults[Idx];
end;
function TFbApiQuery.GetOpen: Boolean;
begin
Result := FResultSet <> nil;
end;
function TFbApiQuery.GetPlan: String;
begin
if (not Prepared) or
(not(GetSQLStatementType in [SQLSelect, SQLSelectForUpdate,
{ TODO: SQLExecProcedure, }
SQLUpdate, SQLDelete])) then
Result := ''
else
Result := FStatement.GetPlan;
end;
function TFbApiQuery.GetPrepared: Boolean;
begin
Result := (FStatement <> nil) and FStatement.IsPrepared;
end;
function TFbApiQuery.GetRecordCount: Integer;
begin
Result := FRecordCount;
{ if FResults <> nil then
Result := FResults.GetCount
else
if FMetaData <> nil then
Result := FMetaData.GetCount
else
Result := 0; }
end;
function TFbApiQuery.GetRowsAffected: Integer;
var
SelectCount, InsertCount, UpdateCount, DeleteCount: Integer;
begin
if not Prepared then
Result := -1
else
begin
FStatement.GetRowsAffected(SelectCount, InsertCount, UpdateCount,
DeleteCount);
Result := InsertCount + UpdateCount + DeleteCount;
end;
end;
function TFbApiQuery.GetSQLParams: ISQLParams;
begin
if not Prepared then
Prepare;
Result := Statement.SQLParams;
end;
function TFbApiQuery.GetSQLStatementType: TIBSQLStatementTypes;
begin
if FStatement = nil then
Result := SQLUnknown
else
Result := FStatement.GetSQLStatementType;
end;
{ procedure TFbApiQuery.Open;
begin
if Active then
raise Exception.Create('Statement is open');
if not Statement.IsPrepared then
Statement.Prepare;
FResultSet := Statement.OpenCursor();
end; }
{ function TFbApiQuery.getStatement: IStatement;
var Attachment: IAttachment;
begin
if not (Assigned(FStatement)) or SameText(FStatement.GetSQLText,FSQL.Text) then
begin
if Assigned(FStatement) then
FStatement := nil;
FStatement := Database.Attachment.Prepare(Database.startReadTransaction,
FSQL.Text,Database.params.SqlDialect);
end;
Result := FStatement;
end; }
function TFbApiQuery.GetTransaction: TFbApiTransaction;
begin
Result := FBase.Transaction;
end;
function TFbApiQuery.GetUniqueRelationName: String;
begin
end;
function TFbApiQuery.HasField(const FieldName: String): Boolean;
var
i: Integer;
begin
if MetaData = nil then
IBError(ibxeNoFieldAccess, [nil]);
Result := false;
for i := 0 to MetaData.Count - 1 do
begin
if MetaData.ColMetaData[i].Name = FieldName then
begin
Result := True;
Exit;
end;
end;
end;
function TFbApiQuery.Next: Boolean;
begin
Result := false;
if not FEOF then
begin
CheckOpen;
try
Result := FResultSet.FetchNext;
except
Close;
raise;
end;
if Result then
begin
Inc(FRecordCount);
FBOF := false;
end
else
FEOF := True;
// if not (csDesigning in ComponentState) then
// MonitorHook.SQLFetch(Self);
end;
end;
function TFbApiQuery.ParamByName(const ParamName: String): ISQLParam;
begin
Result := Params.ByName(ParamName);
end;
procedure TFbApiQuery.Prepare;
begin
CheckClosed;
FBase.CheckDatabase;
FBase.CheckTransaction;
Close;
if Prepared then
Exit;
if (FSQL.Text = '') then
IBError(ibxeEmptyQuery, [nil]);
if FStatement <> nil then
FStatement.Prepare(FBase.Transaction.TransactionIntf)
else if not ParamCheck then
FStatement := Database.Attachment.Prepare
(FBase.Transaction.TransactionIntf, SQL.Text)
else
FStatement := Database.Attachment.PrepareWithNamedParameters
(Transaction.TransactionIntf, SQL.Text, GenerateParamNames,
CaseSensitiveParameterNames);
{$IFDEF IBXQUERYSTATS}
FStatement.EnableStatistics(True);
{$ENDIF}
FMetaData := FStatement.GetMetaData;
FSQLParams := FStatement.GetSQLParams;
FStatement.SetRetainInterfaces(True);
// if not (csDesigning in ComponentState) then
// MonitorHook.SQLPrepare(Self);
end;
procedure TFbApiQuery.SetActive(const Value: Boolean);
begin
if (Value <> FActive) then
begin
if (FActive) then
Close
else
ExecQuery;
end;
end;
procedure TFbApiQuery.SetDatabase(const Value: TFbApiDatabase);
begin
if Value = FBase.Database then
Exit;
FBase.Database := Value;
FreeHandle;
end;
procedure TFbApiQuery.SetIsTransactionOwner(const Value: Boolean);
begin
FIsTransactionOwner := Value;
end;
procedure TFbApiQuery.SetTransaction(const Value: TFbApiTransaction);
begin
if FBase.Transaction = Value then
Exit;
FreeHandle;
FBase.Transaction := Value;
end;
procedure TFbApiQuery.SQLChanged(Sender: TObject);
begin
if Assigned(OnSQLChanged) then
OnSQLChanged(self);
end;
procedure TFbApiQuery.SQLChanging(Sender: TObject);
begin
if Assigned(OnSQLChanging) then
OnSQLChanging(self);
FreeHandle;
end;
end.
|
unit uEntryDetailsFrame;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.Sensors,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Ani, FMX.Objects, FMX.Layouts, FMX.Effects,
FMX.Filter.Effects, FMX.Platform, System.Permissions, FMX.Edit, fieldlogger.data
{$IFDEF ANDROID}
, Androidapi.JNI.Os, Androidapi.JNI.JavaTypes, Androidapi.Helpers
{$ENDIF ANDROID}
;
type
TEntryDetailsFrame = class(TFrame)
Image5: TImage;
imgPicture: TImage;
LongitudeRectangle: TRectangle;
Label7: TLabel;
lblLongitude: TLabel;
LatitudeRectangle: TRectangle;
Label9: TLabel;
lblLatitude: TLabel;
ALIRectangle: TRectangle;
Label11: TLabel;
SubThoroughfareRectangle: TRectangle;
Label12: TLabel;
lblSubThoroughfare: TLabel;
ThoroughfareRectangle: TRectangle;
Label14: TLabel;
lblThoroughfare: TLabel;
SubLocalityRectangle: TRectangle;
Label16: TLabel;
lblSubLocality: TLabel;
SubAdminRectangle: TRectangle;
Label18: TLabel;
lblSubAdminArea: TLabel;
ZipRectangle: TRectangle;
Label20: TLabel;
lblZipCode: TLabel;
LocalityRectangle: TRectangle;
Label22: TLabel;
lblLocality: TLabel;
FeatureRectangle: TRectangle;
Label24: TLabel;
lblFeature: TLabel;
CountryRectangle: TRectangle;
Label26: TLabel;
lblCountry: TLabel;
CountryCodeRectangle: TRectangle;
Label28: TLabel;
lblCountryCode: TLabel;
AdminAreaRectangle: TRectangle;
Label30: TLabel;
lblAdminArea: TLabel;
ToolBar3: TToolBar;
ToolBarBackgroundRect: TRectangle;
Label6: TLabel;
btnEntriesBack: TButton;
btnDeleteEntry: TSpeedButton;
VertScrollBox1: TVertScrollBox;
InfoLayout: TLayout;
ImageTitleRect: TRectangle;
Label1: TLabel;
Layout1: TLayout;
Layout2: TLayout;
Circle1: TCircle;
LogoImage: TImage;
Layout3: TLayout;
AddLogEntryCircleBTN: TCircle;
AddButton: TSpeedButton;
ShadowEffect1: TShadowEffect;
MapImage: TImage;
BackgroundRect: TRectangle;
Rectangle1: TRectangle;
Rectangle2: TRectangle;
Label4: TLabel;
Label2: TLabel;
NoteEdit: TEdit;
procedure btnDeleteEntryClick(Sender: TObject);
procedure btnEntriesBackClick(Sender: TObject);
procedure AddLogEntryCircleBTNClick(Sender: TObject);
procedure AddLogEntryCircleBTNMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Single);
private
{ Private declarations }
procedure SetNote(const ANote: String);
public
{ Public declarations }
procedure UpdateDetails(const Address: TCivicAddress);
procedure LoadEntryDetail(LogID: Integer; AProject: TProject);
procedure DownloadStaticMap(const aLocation:String; aHeight, aWidth: Single; aImage: TImage);
end;
implementation
{$R *.fmx}
uses
formMain, uDataModule;
procedure TEntryDetailsFrame.SetNote(const ANote: String);
begin
NoteEdit.Text := ANote;
end;
procedure TEntryDetailsFrame.LoadEntryDetail(LogID: Integer; AProject: TProject);
var
LogData: ILogData;
LogEntries: TArrayOfLogEntry;
Found: integer;
idx: integer;
Bitmap: TBitmap;
begin
// - Init the tab
imgPicture.Bitmap.Clear(TAlphaColorRec.Null);
lblLongitude.Text := '???';
lblLatitude.Text := '???';
lblSubThoroughfare.Text := '???';
lblThoroughfare.Text := '???';
lblSubLocality.Text := '???';
lblSubAdminArea.Text := '???';
lblZipCode.Text := '???';
lblLocality.Text := '???';
lblFeature.Text := '???';
lblCountry.Text := '???';
lblCountryCode.Text := '???';
lblAdminArea.Text := '???';
// - Get data
LogData := TLogData.Create(mainDM.conn);
if not assigned(LogData) then
begin
raise EConnectFailed.Create;
end;
LogData.Read(LogEntries, AProject.ID);
if Length(LogEntries) = 0 then
begin
exit;
end;
// - Loop through and find the log entry we want
frmMain.CurrentLogEntry := 0;
Found := 0;
for idx := 0 to pred(Length(LogEntries)) do
begin
if LogEntries[idx].ID = LogID then
begin
frmMain.CurrentLogEntry := LogEntries[idx].ID;
Found := idx;
break;
end;
end;
if frmMain.CurrentLogEntry = 0 then
begin
exit;
end;
// - Load the entry to the form.
Bitmap := LogEntries[Found].getPicture;
try
imgPicture.Bitmap.SetSize(Bitmap.Width,Bitmap.Height);
imgPicture.Bitmap.CopyFromBitmap(Bitmap);
//imgPicture.Bitmap.Assign(Bitmap);
finally
Bitmap.DisposeOf;
end;
lblLongitude.Text := LogEntries[Found].Longitude.ToString;
lblLatitude.Text := LogEntries[Found].Latitude.ToString;
SetNote(LogEntries[Found].Note);
try
frmMain.ReverseLocation(LogEntries[Found].Latitude, LogEntries[Found].Longitude);
except
end;
DownloadStaticMap(lblLatitude.Text + ',' + lblLongitude.Text, MapImage.Height, MapImage.Width, MapImage);
end;
procedure TEntryDetailsFrame.UpdateDetails(const Address: TCivicAddress);
begin
lblSubThoroughfare.Text := Address.SubThoroughfare;
lblThoroughfare.Text := Address.Thoroughfare;
lblSubLocality.Text := Address.SubLocality;
lblSubAdminArea.Text := Address.SubAdminArea;
lblZipCode.Text := Address.PostalCode;
lblLocality.Text := Address.Locality;
lblFeature.Text := Address.FeatureName;
lblCountry.Text := Address.CountryName;
lblCountryCode.Text := Address.CountryCode;
lblAdminArea.Text := Address.AdminArea;
end;
procedure TEntryDetailsFrame.DownloadStaticMap(const aLocation: String; aHeight, aWidth: Single; aImage: TImage);
begin
frmMain.DownloadStaticMap(aLocation, aHeight, aWidth, aImage);
end;
procedure TEntryDetailsFrame.AddLogEntryCircleBTNClick(Sender: TObject);
begin
frmMain.NewProjectEntry;
end;
procedure TEntryDetailsFrame.AddLogEntryCircleBTNMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
frmMain.MaterialDesignMouseDown(Sender, Button, Shift, X, Y);
end;
procedure TEntryDetailsFrame.btnDeleteEntryClick(Sender: TObject);
var
ASyncService: IFMXDialogServiceASync;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXDialogServiceAsync, IInterface(ASyncService)) then
begin
ASyncService.MessageDialogAsync( 'Delete this Log Entry?', TMsgDlgType.mtConfirmation,
[TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], TMsgDlgBtn.mbNo, 0,
procedure(const AResult: TModalResult)
begin
case AResult of
mrYES: begin
frmMain.DeleteLogEntry;
end;
end;
end);
end;
end;
procedure TEntryDetailsFrame.btnEntriesBackClick(Sender: TObject);
begin
frmMain.SetBackToProjectDetailScreen;
end;
end.
|
unit disassemblerviewlinesunit;
{$MODE Delphi}
interface
uses math,LCLIntf,sysutils, classes,ComCtrls, graphics, CEFuncProc, disassembler,
CEDebugger, debughelper, KernelDebugger, symbolhandler, plugin,
disassemblerComments, SymbolListHandler, ProcessHandlerUnit, tcclib,SynHighlighterCpp
{$ifdef USELAZFREETYPE}
,LazFreeTypeIntfDrawer, EasyLazFreeType
{$endif}, betterControls;
type
TDisassemblerViewColorsState=(csUndefined=-1, csNormal=0, csHighlighted=1, csSecondaryHighlighted=2, csBreakpoint=3, csHighlightedbreakpoint=4, csSecondaryHighlightedbreakpoint=5, csUltimap=6, csHighlightedUltimap=7, csSecondaryHighlightedUltimap=8);
TDisassemblerViewColors=array [csNormal..csSecondaryHighlightedUltimap] of record
backgroundcolor: TColor;
normalcolor: TColor;
registercolor: TColor;
symbolcolor: TColor;
hexcolor: TColor;
end;
PDisassemblerViewColors=^TDisassemblerViewColors;
TDisassemblerLine=class
private
fowner: TObject;
fbitmap: tbitmap;
fCanvas: TCanvas;
fHeaders: THeaderSections;
ftop: integer;
fheight: integer; //height of the line
fDefaultHeight: integer; //the normal height without anything extra
fInstructionCenter: integer; //y position of the center of the disassembled line (so no header)
isselected: boolean;
faddress: ptrUint;
fdescription: string;
fdisassembled: string;
fisJump: boolean;
fjumpcolor: TColor;
fJumpsTo: ptrUint;
fcolors: PDisassemblerViewColors;
addressstring: string;
bytestring: string;
opcodestring: string;
specialstring: string;
specialstrings: tstringlist;
customheaderstrings: tstringlist;
parameterstring: string;
referencedbylineheight: integer;
boldheight: integer;
textheight: integer;
refferencedByStart: integer;
sourcecodestart: integer;
sourcecodestop: integer;
isbp,isultimap: boolean;
focused: boolean;
{$ifdef USELAZFREETYPE}
drawer: TIntfFreeTypeDrawer;
ftfont,ftfontb: TFreeTypeFont;
{$endif}
function truncatestring(s: string; maxwidth: integer; hasSpecialChars: boolean=false): string;
procedure buildReferencedByString(sl: tstringlist);
function DrawTextRectWithColor(const ARect: TRect; X, Y: integer; const Text: string): integer;
procedure renderCCodeLine(x,y: integer; text: string);
public
property instructionCenter: integer read fInstructionCenter;
function isJumpOrCall(var addressitjumpsto: ptrUint): boolean;
function getReferencedByAddress(y: integer):ptruint;
function getSourceCode(y: integer):PLineNumberInfo;
function getHeight: integer;
function getTop: integer;
property description:string read fdescription;
property disassembled:string read fdisassembled;
procedure renderLine(var address: ptrUint; linestart: integer; selected: boolean=false; focused: boolean=false; spaceAboveLines:integer=0; spaceBelowLines:integer=0);
procedure drawJumplineTo(yposition: integer; offset: integer; showendtriangle: boolean=true);
procedure handledisassemblerplugins(addressStringPointer: pointer; bytestringpointer: pointer; opcodestringpointer: pointer; specialstringpointer: pointer; textcolor: PColor);
constructor create(owner: TObject; bitmap: TBitmap; headersections: THeaderSections; colors: PDisassemblerViewColors);
destructor destroy; override;
published
property height: integer read fheight;
property top: integer read fTop;
property defaultHeight: integer read fDefaultHeight;
property Address: ptrUint read faddress;
property Owner: TObject read fowner;
end;
implementation
uses
MemoryBrowserFormUnit, DissectCodeThread,debuggertypedefinitions,
dissectcodeunit, disassemblerviewunit, frmUltimap2Unit, frmcodefilterunit,
BreakpointTypeDef, vmxfunctions, globals, sourcecodehandler, SynHighlighterAA;
resourcestring
rsUn = '(Unconditional)';
rsCon = '(Conditional)';
rsCall = '(Call)';
rsMemory = '(Code/Data)';
rsInvalidDisassembly = 'Invalid disassembly';
var
chighlighter: TSynCppSyn; //the disassemblerview lines highlighter is accessed only from the GUI thread, so can be global
procedure TDisassemblerLine.drawJumplineTo(yposition: integer; offset: integer; showendtriangle: boolean=true);
var
oldpenstyle: Tpenstyle;
oldpenwidth: integer;
oldpencolor, oldbrushcolor: TColor;
jlThickness: integer;
triangleheight: integer;
begin
jlThickness:=TDisassemblerview(owner).jlThickness;
oldpenstyle:=fCanvas.Pen.Style;
oldpenwidth:=fcanvas.pen.Width;
oldpencolor:=fCanvas.Pen.color;
oldbrushcolor:=fCanvas.Brush.color;
fCanvas.Pen.Color:=fjumpcolor;
fCanvas.Pen.Style:=psDot;
fcanvas.Pen.Width:=jlThickness;
fCanvas.PenPos:=point(fHeaders.items[2].Left,instructioncenter);
fCanvas.LineTo(fHeaders.items[2].Left-offset,instructioncenter);
fCanvas.LineTo(fHeaders.items[2].Left-offset,yposition);
fCanvas.LineTo(fHeaders.items[2].Left,yposition);
fCanvas.Pen.Style:=oldpenstyle;
if showendtriangle then
begin
triangleheight:=defaultHeight div 4;
fCanvas.Brush.Style:=bsSolid; //should be the default, but in case something fucked with it (not in the planning, never intended, so even if someone did do it, I'll undo it)
fCanvas.Brush.Color:=fjumpcolor;
fCanvas.Polygon([point(fheaders.items[2].Left-triangleheight,yposition-triangleheight),point(fheaders.items[2].Left,yposition),point(fheaders.items[2].Left-triangleheight,yposition+triangleheight)]);
end;
fCanvas.Brush.Color:=oldbrushcolor;
fCanvas.Pen.Color:=oldpencolor;
end;
function TDisassemblerLine.isJumpOrCall(var addressitjumpsto: ptrUint): boolean;
begin
result:=fisJump;
if result then
addressitjumpsto:=fJumpsTo;
end;
function TDisassemblerLine.getReferencedByAddress(y: integer):ptruint;
//Search the referenced by strings for one with the correct start (if it has one)
var sl: Tstringlist;
p: integer;
a: string;
i: integer;
begin
result:=0;
sl:=TStringList.create;
buildReferencedByString(sl);
if sl.count>0 then
begin
//find the line that matches with this y pos
p:=refferencedByStart-top;
for i:=0 to sl.count-1 do
begin
p:=p+fcanvas.GetTextHeight(sl[i]);
if p>=y then //found it
begin
a:=copy(sl[i], 1, pos('(', sl[i])-1);
result:=StrToQWord('$'+a);
exit;
end;
end;
end;
freeandnil(sl);
end;
function TDisassemblerLine.getSourceCode(y: integer):PLineNumberInfo;
var sci: TSourceCodeInfo;
begin
result:=nil;
//check if y is between sourcecodestart/sourcecodestop, and if so get the sourcecode
if (sourcecodestart<>sourcecodestop) and InRange(top+y,sourcecodestart, sourcecodestop) then
begin
sci:=SourceCodeInfoCollection.getSourceCodeInfo(fAddress);
if sci<>nil then
begin
if sci.processID<>processid then
begin
sci.Free;
exit(nil);
end;
result:=sci.getLineInfo(fAddress);
end;
end;
end;
function TDisassemblerLine.truncatestring(s: string; maxwidth: integer; hasSpecialChars: boolean=false): string;
var
dotsize: integer;
charindexes: array of integer;
original: string;
i,j: integer;
insidecommand: boolean;
begin
setlength(charindexes,0);
if s='' then exit(s);
original:=s;
insidecommand:=false;
if hasSpecialChars then
begin
setlength(charindexes, length(s)+1); //skipping index 0
j:=1;
for i:=1 to length(original) do
begin
case original[i] of
'{':
begin
insidecommand:=true;
continue
end;
'}':
begin
if insidecommand then
begin
insidecommand:=false;
continue;
end;
end;
end;
if insidecommand then continue;
s[j]:=original[i];
charindexes[j]:=i;
inc(j);
end;
setlength(s,j-1);
end;
if fCanvas.TextWidth(s)>maxwidth then
begin
dotsize:=fCanvas.TextWidth('...');
maxwidth:=maxwidth-dotsize;
if maxwidth<=0 then
begin
result:=''; //it's too small for '...'
exit;
end;
while fCanvas.TextWidth(s)>maxwidth do
s:=copy(s,1,length(s)-1);
if hasSpecialChars then
begin
i:=charindexes[length(s)];
result:=copy(original,1,i)+'{U}...';
end
else
result:=s+'...';
end
else
begin
if hasSpecialChars then
result:=original
else
result:=s; //it fits
end;
end;
procedure TdisassemblerLine.buildReferencedByString(sl: tstringlist);
var addresses: tdissectarray;
i: integer;
begin
setlength(addresses,0);
if (dissectcode<>nil) and (dissectcode.done) then
begin
if dissectcode.CheckAddress(address, addresses) then
begin
for i:=0 to length(addresses)-1 do
begin
case addresses[i].jumptype of
jtUnconditional:
sl.Add(inttohex(addresses[i].address, 8)+utf8toansi(rsUn));
jtConditional:
sl.Add(inttohex(addresses[i].address, 8)+utf8toansi(rsCon));
jtCall:
sl.Add(inttohex(addresses[i].address, 8)+utf8toansi(rsCall));
jtMemory:
sl.Add(inttohex(addresses[i].address, 8)+utf8toansi(rsMemory));
end;
end;
end;
end;
end;
procedure TDisassemblerLine.renderLine(var address: ptrUint; linestart: integer; selected: boolean=false; focused: boolean=false; spaceAboveLines:integer=0; spaceBelowLines:integer=0);
var
baseofsymbol: qword;
symbolname: string;
parameters, locations,result: string;
comment, header: string;
refferencedby: string;
refferencedbylinecount: integer;
refferencedbyheight: integer;
refferencedbystrings: tstringlist;
i,j: integer;
paddressstring: pchar;
pbytestring: pchar;
popcodestring: pchar;
pspecialstring: pchar;
textcolor: TColor;
bp: PBreakpoint;
ExtraLineRenderAbove: TRasterImage;
AboveX, AboveY: Integer;
ExtraLineRenderBelow: TRasterImage;
BelowX, BelowY: Integer;
// z: ptrUint;
found :boolean;
extrasymboldata: TExtraSymbolData;
sourcecodeinfo: TSourceCodeInfo;
lni: PLineNumberInfo;
sourcecode: Tstringlist=nil;
sourcecodelineheight: integer;
sourcecodeheight: integer;
sourcecodeindentationstart: integer; //after filename+linenumber
iscurrentinstruction: boolean;
PA: qword;
BO: integer;
b: byte;
inactive: boolean;
{$ifdef USELAZFREETYPE}
w,h: single;
{$endif}
d: TDisassembler;
header0left: integer;
begin
d:=TDisassemblerview(owner).currentDisassembler;
fcanvas.font.style:=[];
iscurrentinstruction:=(memorybrowser.context<>nil) and (memorybrowser.contexthandler<>nil) and (memorybrowser.contexthandler.InstructionPointerRegister^.getValue(MemoryBrowser.context)=address);
self.focused:=focused;
ftop:=linestart;
faddress:=address;
if assigned(TDisassemblerview(fowner).OnExtraLineRender) then
begin
AboveX:=-1000;
AboveY:=-1000;
ExtraLineRenderAbove:=TDisassemblerview(fOwner).OnExtraLineRender(self, faddress, true, selected, AboveX, AboveY);
BelowX:=-1000;
BelowY:=-1000;
ExtraLineRenderBelow:=TDisassemblerview(fOwner).OnExtraLineRender(self, faddress, false, selected, BelowX, BelowY);
end
else
begin
ExtraLineRenderAbove:=nil;
ExtraLineRenderBelow:=nil;
end;
isselected:=selected;
refferencedbystrings:=nil;
fheight:=0;
baseofsymbol:=0;
//z:=address;
symbolname:=symhandler.getNameFromAddress(address,symhandler.showsymbols,symhandler.showmodules,symhandler.showsections, @baseofsymbol, @found, 8,false);
if (faddress=baseofsymbol) and found then
begin
extrasymboldata:=symhandler.getExtraDataFromSymbolAtAddress(address);
end
else
extrasymboldata:=nil;
if iscurrentinstruction then
d.context:=MemoryBrowser.context
else
d.context:=nil;
fdisassembled:=d.disassemble(address,fdescription);
if TDisassemblerview(owner).UseRelativeBase then
addressString:='+'+inttohex(d.LastDisassembleData.address-TDisassemblerview(owner).RelativeBase,8)
else
addressstring:=inttohex(d.LastDisassembleData.address,8);
bytestring:=d.getLastBytestring;
opcodestring:=d.LastDisassembleData.prefix+d.LastDisassembleData.opcode;
parameterstring:=d.LastDisassembleData.parameters+' ';
specialstring:=d.DecodeLastParametersToString;
if iscurrentinstruction and d.LastDisassembleData.isconditionaljump and d.LastDisassembleData.willJumpAccordingToContext then
parameterstring:=parameterstring+' ---> ';
//userdefined comments
if dassemblercomments<>nil then
comment:=dassemblercomments.comments[d.LastDisassembleData.address]
else
comment:='';
if comment<>'' then
begin
try
specialstring:=format(comment,[specialstring]);
except
specialstring:=comment;
end;
end;
if symhandler.showsymbols or symhandler.showmodules then
begin
if TDisassemblerview(owner).UseRelativeBase then
addressString:=addressstring+' ('+symbolname+')'
else
addressString:=symbolname;
end
else
addressString:=truncatestring(addressString, fHeaders.Items[0].Width-2);
//Correction for rendering bug.
if (processhandler.isNetwork=true) and (processhandler.SystemArchitecture=archarm) then
begin
addressstring+=' ';
bytestring+=' ';
opcodestring+=' ';
end;
TDisassemblerview(owner).DoDisassemblerViewLineOverride(address, addressstring, bytestring, opcodestring, parameterstring, specialstring);
//split up into lines
specialstrings.text:=specialstring;
customheaderstrings.text:=dassemblercomments.commentHeader[d.LastDisassembleData.address];
bytestring:=truncatestring(bytestring, fHeaders.Items[1].Width-2, true);
//opcodestring:=truncatestring(opcodestring, fHeaders.Items[2].Width-2, true);
//specialstring:=truncatestring(specialstring, fHeaders.Items[3].Width-2);
if boldheight=-1 then
begin
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (ftfontb<>nil) then
begin
boldheight:=ceil(ftfontb.TextHeight(fdisassembled));
end
else
{$endif}
begin
fcanvas.Font.Style:=[fsbold];
boldheight:=fcanvas.TextHeight(fdisassembled)+1;
fcanvas.Font.Style:=[];
end;
end;
fheight:=fheight+boldheight+1;
fDefaultHeight:=fHeight; //the height without anything special
//calculate how big the comments are. (beyond the default height)
for i:=1 to specialstrings.count-1 do
begin
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (ftfont<>nil) then
inc(fHeight, ceil(ftfont.TextHeight(specialstrings[i])))
else
{$endif}
inc(fHeight, fcanvas.textHeight(specialstrings[i]));
end;
//calculate the custom headersize
for i:=0 to customheaderstrings.count-1 do
begin
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (ftfont<>nil) then
inc(fHeight, ceil(ftfont.TextHeight(customheaderstrings[i])))
else
{$endif}
inc(fheight, fCanvas.TextHeight(customheaderstrings[i]));
end;
inc(fHeight, spaceAboveLines+spaceBelowLines);
if ExtraLineRenderAbove<>nil then
begin
if AboveY=-1000 then //y doesn't care about center...
AboveY:=0;
if AboveX=-1000 then //center
AboveX:=(fHeaders.Items[fHeaders.Count-1].Width div 2) - (ExtraLineRenderAbove.Width div 2);
inc(fheight, AboveY);
inc(fHeight, ExtraLineRenderAbove.Height);
end;
if ExtraLineRenderBelow<>nil then
begin
if BelowY=-1000 then
BelowY:=0;
if BelowX=-1000 then //center
BelowX:=(fHeaders.Items[fHeaders.Count-1].Width div 2) - (ExtraLineRenderBelow.Width div 2);
inc(fheight, BelowY);
inc(fHeight, ExtraLineRenderAbove.Height);
end;
if (baseofsymbol>0) and (faddress=baseofsymbol) then
begin
parameters:='';
if textheight=-1 then
begin
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (ftfont<>nil) then
textheight:=ceil(ftfont.TextHeight(symbolname))
else
{$endif}
textheight:=fcanvas.TextHeight(symbolname);
end;
fheight:=height+textheight+1+10;
if extrasymboldata<>nil then //more space needed for the local vars
fHeight:=fHeight+textheight*extrasymboldata.locals.count;
end;
refferencedbylinecount:=0;
if (dissectcode<>nil) and (dissectcode.done) then
begin
refferencedbystrings:=tstringlist.create;
buildReferencedByString(refferencedbystrings);
if refferencedbystrings.count>0 then
begin
if referencedbylineheight=-1 then
begin
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (ftfontb<>nil) then
begin
referencedbylineheight:=ceil(ftfontb.TextHeight('xxx'));
end
else
{$endif}
begin
fcanvas.Font.Style:=[fsBold];
referencedbylineheight:=fcanvas.textheight('xxx');
fcanvas.Font.Style:=[];
end;
end;
refferencedbylinecount:=refferencedbystrings.count;
refferencedbyheight:=refferencedbylinecount*referencedbylineheight;
fheight:=height+refferencedbyheight;
end;
end;
lni:=nil;
if SourceCodeInfoCollection<>nil then
begin
sourcecodeinfo:=SourceCodeInfoCollection.getSourceCodeInfo(faddress);
if sourcecodeinfo<>nil then
begin
lni:=sourcecodeinfo.getLineInfo(faddress);
if lni<>nil then
begin
sourcecode:=Tstringlist.create;
sourcecode.text:=lni.sourcecode; //sourcecode has newline chars
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (ftfont<>nil) then
begin
sourcecodelineheight:=ceil(ftfont.TextHeight('xxx'));
sourcecodeindentationstart:=ceil(ftfont.TextWidth(sourcecode[0]+' '));
end
else
{$endif}
begin
fcanvas.Font.Style:=[fsItalic];
sourcecodelineheight:=fcanvas.TextHeight('QjgPli');
fcanvas.Font.Style:=[];
sourcecodeindentationstart:=fcanvas.TextWidth(sourcecode[0]+' ');
end;
sourcecodeheight:=sourcecodelineheight*(sourcecode.Count-1); //first line is the file and linenumber
fheight:=height+sourcecodeheight;
end;
end;
end;
fisJump:=d.LastDisassembleData.isjump;
if fisJump then
begin
fisjump:=cefuncproc.isjumporcall(faddress, fJumpsTo);
if d.LastDisassembleData.iscall then
fjumpcolor:= TDisassemblerview(owner).jlCallColor
else
begin
if d.LastDisassembleData.isconditionaljump then
fjumpcolor:=TDisassemblerview(owner).jlConditionalJumpColor
else
fjumpcolor:=TDisassemblerview(owner).jlUnConditionalJumpColor ;
end;
end;
if debuggerthread<>nil then
bp:=debuggerthread.isBreakpoint(faddress,0,true)
else
bp:=nil;
isbp:=(bp<>nil) and (bp.breakpointTrigger=bptExecute) and (bp.active or (bp.breakpointMethod=bpmException) ) and (bp.markedfordeletion=false);
isultimap:=((frmUltimap2<>nil) and frmUltimap2.IsMatchingAddress(faddress)) or ((frmCodeFilter<>nil) and (frmCodeFilter.isBreakpoint(faddress,b) ));
isultimap:=isultimap or dbvm_isBreakpoint(faddress,PA,BO, b); //mark dbvm internal breakpoints with the same color as an ultimap bp
if selected then
begin
if not isbp then
begin
//default
if not focused then
begin
if isultimap then
begin
fcanvas.Brush.Color:=fcolors^[csSecondaryHighlightedUltimap].backgroundcolor;
fcanvas.Font.Color:=fcolors^[csSecondaryHighlightedUltimap].normalcolor;
end
else
begin
fcanvas.Brush.Color:=fcolors^[csSecondaryHighlighted].backgroundcolor;
fcanvas.Font.Color:=fcolors^[csSecondaryHighlighted].normalcolor;
end;
end
else
begin
if isultimap then
begin
fcanvas.Brush.Color:=fcolors^[csHighlightedUltimap].backgroundcolor;
fcanvas.Font.Color:=fcolors^[csHighlightedUltimap].normalcolor;
end
else
begin
fcanvas.Brush.Color:=fcolors^[csHighlighted].backgroundcolor;
fcanvas.Font.Color:=fcolors^[csHighlighted].normalcolor;
end;
end;
end
else
begin
//it's a breakpoint
fcanvas.Brush.Color:=fcolors^[csHighlightedbreakpoint].backgroundcolor;
fcanvas.Font.Color:=fcolors^[csHighlightedbreakpoint].normalcolor;
end;
fcanvas.Refresh;
end
else
begin
//not selected
if isbp then
begin
fCanvas.Brush.Color:=fcolors^[csbreakpoint].backgroundcolor;
fCanvas.font.Color:=fcolors^[csbreakpoint].normalcolor;
end else
begin
if isultimap then
begin
fCanvas.Brush.Color:=fcolors^[csUltimap].backgroundcolor;
fCanvas.font.Color:=fcolors^[csUltimap].normalcolor;
end
else
begin
fCanvas.Brush.Color:=fcolors^[csNormal].backgroundcolor;
fCanvas.font.Color:=fcolors^[csNormal].normalcolor;
end;
end;
fcanvas.Refresh
end;
//height may not change after this
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (drawer<>nil) then
drawer.FillRect(0,top,fbitmap.width,top+height,TColorToFPColor(colortorgb(fcanvas.Brush.Color)))
else
{$endif}
fcanvas.FillRect(rect(0,top,fbitmap.width,top+height));
inc(linestart, spaceAboveLines);
if ExtraLineRenderAbove<>nil then
begin
//render the image above
linestart:=linestart+AboveY;
fcanvas.Draw(abovex, linestart, ExtraLineRenderAbove);
linestart:=linestart+ExtraLineRenderAbove.height;
end;
if (baseofsymbol>0) and (faddress=baseofsymbol) then
begin
parameters:='';
result:='';
if extrasymboldata<>nil then
begin
result:=extrasymboldata.return;
if result<>'' then
result:=result+' ';
locations:='';
parameters:='(';
if extrasymboldata.parameters.count>0 then
begin
for i:=0 to extrasymboldata.parameters.count-1 do
begin
if i=0 then
parameters:=parameters+extrasymboldata.parameters[i].vtype+' '+extrasymboldata.parameters[i].name
else
parameters:=parameters+', '+extrasymboldata.parameters[i].vtype+' '+extrasymboldata.parameters[i].name;
if i=0 then
locations:=' : '+extrasymboldata.parameters[i].name+'='+extrasymboldata.parameters[i].position
else
locations:=locations+' - '+extrasymboldata.parameters[i].name+'='+extrasymboldata.parameters[i].position;
end;
end
else
parameters:=parameters+extrasymboldata.simpleparameters;
parameters:=parameters+')'+locations;
end;
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (drawer<>nil) then
begin
drawer.DrawText(AnsiToUtf8(result+symbolname+parameters), ftfontb,fHeaders.Items[0].Left+5,linestart+5, tcolortofpcolor(colortorgb(fcanvas.Font.color)), [ftaLeft, ftaTop]);
linestart:=linestart+ceil(ftfontb.TextHeight(symbolname))+1+10;
end
else
{$endif}
begin
fcanvas.Font.Style:=[fsbold];
fcanvas.TextOut(fHeaders.Items[0].Left+5,linestart+5,AnsiToUtf8(result+symbolname+parameters));
linestart:=linestart+fcanvas.TextHeight(symbolname)+1+10;
fcanvas.Font.Style:=[];
end;
//render the local vars
if extrasymboldata<>nil then
begin
linestart:=linestart-5; //go back a bit
for i:=0 to extrasymboldata.locals.count-1 do
begin
parameters:=extrasymboldata.locals[i].vtype+' '+extrasymboldata.locals[i].name;
if extrasymboldata.locals[i].position<>'' then
parameters:=parameters+'('+extrasymboldata.locals[i].position+')';
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (drawer<>nil) then
drawer.DrawText(AnsiToUtf8(parameters), ftfont, fHeaders.Items[0].Left+5,linestart,tcolortofpcolor(colortorgb(fcanvas.Font.color)), [ftaLeft, ftaTop])
else
{$endif}
fcanvas.TextOut(fHeaders.Items[0].Left+5,linestart,AnsiToUtf8(parameters));
linestart:=linestart+textheight;
end;
linestart:=linestart+5;
end;
end;
if (refferencedbylinecount>0) then
begin
refferencedByStart:=linestart;
fcanvas.Font.Style:=[fsBold];
for i:=0 to refferencedbylinecount-1 do
begin
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (drawer<>nil) then
drawer.DrawText(AnsiToUtf8(refferencedbystrings[i]), ftfontb, fHeaders.Items[0].Left+5,linestart, tcolortofpcolor(colortorgb(fcanvas.Font.color)), [ftaLeft, ftaTop])
else
{$endif}
fcanvas.TextOut(fHeaders.Items[0].Left+5,linestart,AnsiToUtf8(refferencedbystrings[i]));
linestart:=linestart+fcanvas.TextHeight(refferencedbystrings[i]);
end;
fcanvas.Font.Style:=[];
end;
if lni<>nil then //render sourcecode lines
begin
sourcecodestart:=linestart;
fcanvas.Font.Style:=[fsItalic];
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (drawer<>nil) then
drawer.DrawText(AnsiToUtf8(sourcecode[0]), ftfont, fHeaders.Items[0].Left+5, linestart, tcolortofpcolor(colortorgb(fcanvas.Font.color)), [ftaLeft, ftaTop])
else
{$endif}
fcanvas.TextOut(fHeaders.Items[0].Left+5,linestart,AnsiToUtf8(sourcecode[0]));
for i:=1 to sourcecode.count-1 do
begin
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (drawer<>nil) then
drawer.DrawText(AnsiToUtf8(sourcecode[i]), ftfont, fHeaders.Items[0].Left+5+sourcecodeindentationstart, linestart, tcolortofpcolor(colortorgb(fcanvas.Font.color)), [ftaLeft, ftaTop])
else
{$endif}
begin
renderCCodeLine(fHeaders.Items[2].Left+1,linestart,AnsiToUtf8(sourcecode[i]));
end;
inc(linestart, sourcecodelineheight);
end;
fcanvas.Font.Style:=[];
sourcecodestop:=linestart;
end
else
begin
sourcecodestart:=0;
sourcecodestop:=0;
end;
if customheaderstrings.count>0 then
begin
//render the custom header
for i:=0 to customheaderstrings.count-1 do
begin
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (drawer<>nil) then
drawer.DrawText(AnsiToUtf8(customheaderstrings[i]),ftfont, fHeaders.Items[0].Left,linestart, tcolortofpcolor(colortorgb(fcanvas.Font.color)), [ftaLeft, ftaTop] );
{$endif}
fcanvas.TextOut(fHeaders.Items[0].Left,linestart,AnsiToUtf8(customheaderstrings[i]));
linestart:=linestart+fcanvas.TextHeight(customheaderstrings[i]);
end;
end;
if iscurrentinstruction then
addressString:='>>'+addressString;
//set pointers to strings
paddressstring:=nil;
pbytestring:=nil;
popcodestring:=nil;
pspecialstring:=nil;
if length(addressstring)>0 then
paddressstring:=@addressstring[1];
if length(bytestring)>0 then
pbytestring:=@bytestring[1];
if length(opcodestring)>0 then
popcodestring:=@opcodestring[1];
if length(specialstring)>0 then
pspecialstring:=@specialstring[1];
textcolor:=fcanvas.Font.Color;
handledisassemblerplugins(@paddressString, @pbytestring, @popcodestring, @pspecialstring, @textcolor);
fcanvas.font.color:=textcolor;
DrawTextRectWithColor(rect(fHeaders.Items[0].Left, linestart, fHeaders.Items[0].Right, linestart+height), fHeaders.Items[0].Left+1,linestart, paddressString);
// fcanvas.TextRect(rect(fHeaders.Items[1].Left, linestart, fHeaders.Items[1].Right, linestart+height),fHeaders.Items[1].Left+1,linestart, pbytestring);
DrawTextRectWithColor(rect(fHeaders.Items[1].Left, linestart, fHeaders.Items[1].Right, linestart+height),fHeaders.Items[1].Left+1,linestart, pbytestring);
fcanvas.font.Style:=fcanvas.font.Style+[fsBold];
i:=DrawTextRectWithColor(rect(fHeaders.Items[2].Left, linestart, fHeaders.Items[2].Right, linestart+height),fHeaders.Items[2].Left+1,linestart, popcodestring);
fcanvas.font.Style:=fcanvas.font.Style-[fsBold];
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (ftfont<>nil) then
begin
inc(i, ceil(ftfont.TextWidth(' ')));
j:=ceil(ftfont.TextWidth('XXXXXXX'));
end
else
{$endif}
begin
inc(i, fcanvas.TextWidth(' '));
j:=fcanvas.textwidth('XXXXXXX');
end;
if i>j then
begin
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (ftfont<>nil) then
i:=fHeaders.Items[2].Left+1+i+ceil(ftfont.textwidth(' '))
else
{$endif}
i:=fHeaders.Items[2].Left+1+i+fcanvas.textwidth(' ')
end
else
i:=fHeaders.Items[2].Left+1+j;
DrawTextRectWithColor(rect(fHeaders.Items[2].Left, linestart, fHeaders.Items[2].Right, linestart+height),i,linestart, parameterstring);
fInstructionCenter:=linestart+(fcanvas.TextHeight(opcodestring) div 2);
if specialstrings.Count>0 then
begin
for i:=0 to specialstrings.Count-1 do
begin
fcanvas.TextRect(rect(fHeaders.Items[3].Left, linestart, fHeaders.Items[3].Right, linestart+height),fHeaders.Items[3].Left+1,linestart, specialstrings[i]);
inc(linestart, fcanvas.GetTextHeight(specialstrings[i]));
end;
end
else
inc(linestart, fcanvas.GetTextHeight(parameterstring));
if ExtraLineRenderBelow<>nil then
begin
//render the image below
linestart:=linestart+BelowY;
fcanvas.Draw(belowx, linestart, ExtraLineRenderBelow);
linestart:=linestart+ExtraLineRenderBelow.height; //not really needed as it's the last one
end;
if focused and (tdisassemblerview(fowner).hidefocusrect=false) then
fcanvas.DrawFocusRect(rect(0,top,fbitmap.width,top+height));
if selected then //restore
begin
fCanvas.Brush.Color:=fcolors^[csNormal].backgroundcolor;
fCanvas.font.Color:=fcolors^[csNormal].normalcolor;
fcanvas.Refresh;
end;
if refferencedbystrings<>nil then
freeandnil(refferencedbystrings);
if sourcecode<>nil then
freeandnil(sourcecode);
end;
procedure TDisassemblerLine.renderCCodeLine(x,y: integer; text: string);
var
s: string;
// a: TToken
oldfg: tcolor;
oldstyle: TFontStyles;
w: integer;
begin
if chighlighter=nil then
begin
chighlighter:=TSynCppSyn.Create(nil);
chighlighter.loadFromRegistryDefault;
end;
oldstyle:=fcanvas.font.style;
oldfg:=fcanvas.font.color;
chighlighter.ResetRange;
chighlighter.SetLine(text,0);
while not chighlighter.GetEol do
begin
s:=chighlighter.GetToken;
fcanvas.Font.color:=chighlighter.GetTokenAttribute.Foreground;
fcanvas.Font.style:=chighlighter.GetTokenAttribute.Style;
w:=fcanvas.GetTextWidth(s);
fcanvas.TextOut(x ,y,s);
inc(x,w);
chighlighter.Next;
end;
fcanvas.font.style:=oldstyle;
fcanvas.font.color:=oldfg;
end;
function TDisassemblerLine.DrawTextRectWithColor(const ARect: TRect; X, Y: integer; const Text: string): integer;
var defaultfontcolor, defaultbrushcolor: TColor;
i: integer;
start,startx: integer;
s,s2: string;
colorcode: integer; //0=normal, 1=hex, 2=reg, 3=symbol 4=rgb
bcolorcode: integer; //0=normal, 1=rgb
rgbcolor: integer;
brgbcolor: integer;
colorstate: TDisassemblerViewColorsState;
ts: TTextStyle;
procedure setcolor;
begin
if isselected then
begin
if isbp then
colorstate:=csSecondaryHighlightedbreakpoint
else
if isultimap then
colorstate:=csSecondaryHighlightedUltimap
else
colorstate:=csSecondaryHighlighted;
if focused then
begin
if isbp then
colorstate:=csHighlightedbreakpoint
else
if isultimap then
colorstate:=csHighlightedUltimap
else
colorstate:=csHighlighted;
end;
end
else
begin
if isbp then
colorstate:=csBreakpoint
else
if isultimap then
colorstate:=csUltimap
else
colorstate:=csNormal;
end;
case colorcode of
0: fcanvas.font.color:=fcolors^[colorstate].normalcolor;
1: fcanvas.font.color:=fcolors^[colorstate].hexcolor;
2: fcanvas.font.color:=fcolors^[colorstate].registercolor;
3: fcanvas.font.color:=fcolors^[colorstate].symbolcolor;
4: fcanvas.font.color:=rgbcolor;
end;
case bcolorcode of
0:
begin
ts:=fcanvas.TextStyle;
ts.Opaque:=true;
fcanvas.TextStyle:=ts;
fcanvas.Brush.color:=defaultbrushcolor;
end;
1:
begin
ts:=fcanvas.TextStyle;
ts.Opaque:=true;
fcanvas.TextStyle:=ts;
fcanvas.Brush.color:=brgbcolor;
end;
end;
end;
{$ifdef USELAZFREETYPE}
var fnt: TFreeTypeFont;
{$endif}
begin
{$ifdef USELAZFREETYPE}
if fsbold in fcanvas.Font.style then
fnt:=ftfontb
else
fnt:=ftfont;
{$endif}
defaultbrushcolor:=fcanvas.Brush.color;
defaultfontcolor:=fcanvas.Font.color;
start:=1;
startx:=x;
s:='';
i:=1;
colorcode:=0;
bcolorcode:=0;
if processhandler.SystemArchitecture=archx86 then
begin
while i<=length(text) do
begin
case text[i] of
'{':
begin
setcolor;
s:=copy(text, start,i-start);
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (drawer<>nil) then
begin
drawer.DrawTextWordBreak(AnsiToUtf8(s),fnt,x,y,arect.Width-(x-startx),tcolortofpcolor(colortorgb(fcanvas.Font.Color)),[ftaLeft, ftaTop]);
x:=x+ceil(fnt.TextWidth(s))+1;
end
else
{$endif}
begin
fcanvas.TextRect(ARect,x,y,AnsiToUtf8(s));
x:=x+fcanvas.TextWidth(s)+1;
end;
inc(i);
while i<=length(text) do
begin
case text[i] of
'N':
begin
colorcode:=0;
bcolorcode:=0;
end;
'H': colorcode:=1;
'R': colorcode:=2;
'S': colorcode:=3;
'B': //followed by RRGGBB colorcode
begin
s2:=copy(text, i+1,6);
if trystrtoint('$'+s2, brgbcolor) then bcolorcode:=1;
inc(i,6);
end;
'C': //followed by RRGGBB colorcode
begin
s2:=copy(text, i+1,6);
if trystrtoint('$'+s2, rgbcolor) then colorcode:=4;
inc(i,6);
end;
'}':
begin
inc(i);
break;
end;
//else raise exception.create(rsInvalidDisassembly);
end;
inc(i);
end;
start:=i;
end;
else inc(i);
end;
end;
end
else
i:=length(text)+1;
setcolor;
s:=copy(text, start,i-start);
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (drawer<>nil) then
drawer.DrawTextWordBreak(AnsiToUtf8(s),fnt,x,y,arect.Width-(x-startx),tcolortofpcolor(colortorgb(fcanvas.Font.Color)),[ftaLeft, ftaTop])
else
{$endif}
fcanvas.TextRect(ARect,x,y,AnsiToUtf8(s));
fcanvas.Font.color:=defaultfontcolor;
fcanvas.brush.color:=defaultbrushcolor;
{$ifdef USELAZFREETYPE}
if (not UseOriginalRenderingSystem) and (fnt<>nil) then
x:=x+ceil(fnt.TextWidth(s))
else
{$endif}
x:=x+fcanvas.TextWidth(s);
result:=x-startx;
end;
procedure TDisassemblerLine.handledisassemblerplugins(addressStringPointer: pointer; bytestringpointer: pointer; opcodestringpointer: pointer; specialstringpointer: pointer; textcolor: PColor);
begin
//obsolete
if pluginhandler<>nil then
pluginhandler.handledisassemblerplugins(faddress, addressStringPointer, bytestringpointer, opcodestringpointer, specialstringpointer, textcolor);
end;
function TDisassemblerLine.getHeight: integer;
begin
result:=height;
end;
function TDisassemblerLine.getTop: integer;
begin
result:=ftop;
end;
destructor TDisassemblerLine.destroy;
begin
freeandnil(specialstrings);
inherited destroy;
end;
constructor TDisassemblerLine.create(owner: TObject; bitmap: TBitmap; headersections: THeaderSections; colors: PDisassemblerViewColors);
begin
fowner:=owner;
fCanvas:=bitmap.canvas;
fBitmap:=bitmap;
fheaders:=headersections;
boldheight:=-1; //bypass for memory leak
textheight:=-1;
referencedbylineheight:=-1;
fcolors:=colors;
fheight:=fCanvas.TextHeight('X');
fDefaultHeight:=-1;
specialstrings:=tstringlist.create;
customheaderstrings:=tstringlist.create;
{$ifdef USELAZFREETYPE}
drawer:=TDisassemblerview(owner).drawer;
ftfont:=TDisassemblerview(owner).ftfont;
ftfontb:=TDisassemblerview(owner).ftfontb;
{$endif}
end;
end.
|
unit Cliente;
interface
uses
System.Classes;
type
TClasseAmiga = class
private
Teste : String;
public
procedure TesteDeSoftware;
end;
type
TCliente = class
private
FDataNascimento: TDateTime;
FNome: String;
FTelefone : String;
FEndereco : String;
procedure SetDataNascimento(const Value: TDateTime);
procedure SetNome(const Value: String);
function GetEndereco: String;
procedure SetEndereco(const Value: String);
public
Cidade: String;
UF: String;
Saldo : Currency;
constructor Create;
procedure CadastrarCliente;
procedure CriarFinanceiro;
function Idade : Integer;
property Nome : String read FNome write SetNome;
property DataNascimento : TDateTime read FDataNascimento write SetDataNascimento;
property Telefone : String read FTelefone write FTelefone;
property Endereco: String read GetEndereco write SetEndereco;
end;
implementation
uses
System.SysUtils;
{ TCliente }
procedure TCliente.CadastrarCliente;
var
Lista : TStringList;
begin
Lista := TStringList.Create;
try
Lista.Add('Nome:' + Nome);
Lista.Add('Telefone:' + Telefone);
Lista.Add('Endereço:' + Endereco);
Lista.Add('Cidade:' + Cidade);
Lista.Add('UF:' + UF);
Lista.SaveToFile(Nome + '_Cliente.txt');
finally
Lista.Free;
end;
end;
constructor TCliente.Create;
begin
UF := 'RJ';
Saldo := 1000;
end;
procedure TCliente.CriarFinanceiro;
var
Lista : TStringList;
begin
Lista := TStringList.Create;
try
Lista.Add('Nome:' + Nome);
Lista.Add('Saldo:' + CurrToStr(Saldo));
Lista.SaveToFile(Nome + '_Financeiro.txt');
finally
Lista.Free;
end;
end;
function TCliente.GetEndereco: String;
begin
Result := FEndereco + ' | Rio de Janeiro | Brasil';
end;
function TCliente.Idade: Integer;
begin
Result := Trunc((Now - FDataNascimento) / 365.25);
end;
procedure TCliente.SetDataNascimento(const Value: TDateTime);
begin
FDataNascimento := Value;
end;
procedure TCliente.SetEndereco(const Value: String);
begin
FEndereco := Value;
end;
procedure TCliente.SetNome(const Value: String);
begin
if Value = '' then
raise Exception.Create('Nome não pode ser nulo');
FNome := Value;
end;
{ TClasseAmiga }
procedure TClasseAmiga.TesteDeSoftware;
var
aClasse : TCliente;
begin
//aClasse.
end;
end.
|
unit Form.Main;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.UIConsts,
System.Classes,
System.Math,
System.IOUtils,
FMX.Types,
FMX.Ani,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.InertialMovement,
FMX.Objects,
Lib.Classes;
type
TMainForm = class(TForm)
Rectangle2: TRectangle;
Rectangle1: TRectangle;
Rectangle4: TRectangle;
Rectangle5: TRectangle;
Rectangle6: TRectangle;
ScrollContent: TRectangle;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Rectangle2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure Rectangle2MouseLeave(Sender: TObject);
procedure Rectangle2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
procedure Rectangle2MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure Rectangle2Paint(Sender: TObject; Canvas: TCanvas;
const ARect: TRectF);
procedure Rectangle2Resized(Sender: TObject);
procedure Rectangle2MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; var Handled: Boolean);
procedure Rectangle2Gesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
procedure Rectangle2Click(Sender: TObject);
private const
PhysicsProcessingInterval = 8; // 8 ms for ~120 frames per second
HasPhysicsStretchyScrolling = True;
PICTURES_MARGIN = 10;
private
FAniCalc: TAniCalculations;
FFeedMode: Boolean;
ContentSize: TPointF;
Pictures: TPictureList;
Cache: TPictureList;
PictureReader: TPictureReader;
FCurrentPicture: TPicture;
FLeave: Boolean;
procedure SetCurrentPicture(Value: TPicture);
procedure OnPicturePaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
procedure AniCalcChange(Sender: TObject);
procedure AniCalcStart(Sender: TObject);
procedure AniCalcStop(Sender: TObject);
procedure DoUpdateScrollingLimits;
function GetPicturesPath: string;
procedure LoadPictures;
function GetFiles(const PicturesPath: string): TArray<string>;
function AbsoluteCenterPoint: TPointF;
function AbsolutePressedPoint: TPointF;
procedure AddPicture(const PictureFileName: string);
function PictureOf(PictureIndex: Integer): TPicture;
procedure OnPictureRead(Sender: TObject);
function PictureAt(const AbsolutePoint: TPointF): TPicture;
function TryPictureAt(const AbsolutePoint: TPointF; out Picture: TPicture): Boolean;
function PictureIndexAt(const AbsolutePoint: TPointF): Integer;
procedure ShowText(const Text: string);
procedure ToCache(Picture: TPicture);
procedure PlacementPictures(FeedMode: Boolean);
procedure ScrollToPicture(Picture: TPicture; Immediately: Boolean=False); overload;
procedure ScrollToPicture(PictureIndex: Integer; Immediately: Boolean=False); overload;
property CurrentPicture: TPicture read FCurrentPicture write SetCurrentPicture;
public
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
type
TAniCalculationsAccess = class(TAniCalculations);
procedure TMainForm.FormCreate(Sender: TObject);
begin
PictureReader:=TPictureReader.Create;
PictureReader.Start;
FAniCalc:=TAniCalculations.Create(nil);
FAniCalc.TouchTracking:=[{ttVertical,}ttHorizontal];
FAniCalc.Animation:=True;
FAniCalc.OnChanged:=AniCalcChange;
FAniCalc.Interval:=PhysicsProcessingInterval; // как часто обновлять позицию по таймеру
FAniCalc.OnStart:=AniCalcStart;
FAniCalc.OnStop:=AniCalcStop;
FAniCalc.BoundsAnimation:=HasPhysicsStretchyScrolling; // возможен ли выход за границы min-max (если определены min-max)
FAniCalc.Elasticity:=200; // как быстро возвращать позицию в пределы min-max при выходе за границы (при отпускании пальца/мыши)
FAniCalc.DecelerationRate:=2;//15;//10; // скорость замедления прокрутки после отпускании пальца/мыши
FAniCalc.Averaging:=True;
FAniCalc.AutoShowing:=True;
TAniCalculationsAccess(FAniCalc).Shown:=False;
// TAniCalculationsAccess(FAniCalc).StorageTime:=0.1;//1000;
TAniCalculationsAccess(FAniCalc).DeadZone:=10; // смещение после которого происходит инициация анимации, работает только если Averaging=True
Pictures:=TPictureList.Create;
Cache:=TPictureList.Create;
RequestPermissionsExternalStorage(
procedure(Granted: Boolean)
begin
if Granted then LoadPictures;
end);
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
PictureReader.DoShutDown;
Pictures.Free;
Cache.Free;
FAniCalc.Free;
end;
procedure RepaintControl(Control: TControl);
begin
if Control<>nil then Control.Repaint;
end;
procedure TMainForm.SetCurrentPicture(Value: TPicture);
var P: TPicture;
begin
if Value<>CurrentPicture then
begin
P:=FCurrentPicture;
FCurrentPicture:=Value;
RepaintControl(CurrentPicture);
RepaintControl(P);
end;
end;
procedure TMainForm.ToCache(Picture: TPicture);
begin
if Picture=nil then Exit;
Cache.Remove(Picture);
Cache.Add(Picture);
while (Cache.Count>20) and Cache[0].Loaded do
begin
Cache[0].ReleaseBitmap;
Cache.Delete(0);
end;
end;
procedure TMainForm.OnPictureRead(Sender: TObject);
begin
var Picture:=TPicture(Sender);
//PictureReader.Push(PictureOf(Picture.PictureIndex-1));
PictureReader.Push(Picture);
//PictureReader.Push(PictureOf(Picture.PictureIndex+1));
ToCache(Picture);
end;
procedure TMainForm.OnPicturePaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
var R: TRectF;
begin
var Picture:=TPicture(Sender);
if Picture.Empty then
begin
PictureReader.Push(Picture);
ToCache(Picture);
end;
if Picture=CurrentPicture then
begin
Canvas.Stroke.Kind:=TBrushKind.Solid;
Canvas.Stroke.Thickness:=2;
Canvas.Stroke.Color:=claRed;
R:=ARect;
R.Inflate(-10,-10);
//Canvas.DrawRect(R,0,0,AllCorners,1);
end;
end;
procedure TMainForm.AddPicture(const PictureFileName: string);
var
R: TPicture;
S: TPointF;
begin
S:=TBitmapCodecManager.GetImageSize(PictureFileName);
if (S.X>0) and (S.Y>0) then // is picture file
begin
R:=TPicture.Create(Self);
R.BitmapSize:=S;
R.PictureIndex:=Pictures.Count;
R.PictureFileName:=PictureFileName;
//R.OnRead:=OnPictureRead;
R.OnPaint:=OnPicturePaint;
Pictures.Add(R);
end;
end;
procedure TMainForm.PlacementPictures(FeedMode: Boolean);
var
PaddingRect,PageRect,PageBounds,PictureRect: TRectF;
PageSize: TPointF;
begin
if Pictures=nil then Exit;
FFeedMode:=FeedMode;
PaddingRect:=ScrollContent.Padding.Rect;
PageSize:=Rectangle2.BoundsRect.BottomRight;
ScrollContent.BeginUpdate;
PageRect:=TRectF.Create(PaddingRect.TopLeft,PageSize.X,PageSize.Y-
PaddingRect.Top-PaddingRect.Bottom);
for var Picture in Pictures do
begin
PictureRect:=RectF(0,0,Picture.BitmapSize.X,Picture.BitmapSize.Y).
PlaceInto(PageRect,THorzRectAlign.Center,TVertRectAlign.Center);
if FeedMode then
begin
PictureRect.SetLocation(PageRect.Left,PictureRect.Top);
PageBounds:=PageRect.CenterAt(PictureRect);
PageRect.SetLocation(PictureRect.Right+PICTURES_MARGIN,PageRect.Top);
end else begin
PageBounds:=PageRect;
PageRect.Offset(PageRect.Width+PICTURES_MARGIN,0)
end;
Picture.BoundsRect:=PictureRect.SnapToPixel(0);
Picture.PageBounds:=PageBounds;
ScrollContent.AddObject(Picture);
end;
ScrollContent.Size.Size:=PointF(PageRect.Left-PICTURES_MARGIN,PageRect.Bottom)+
PaddingRect.BottomRight;
ScrollContent.EndUpdate;
DoUpdateScrollingLimits;
AniCalcChange(nil);
end;
function TMainForm.GetFiles(const PicturesPath: string): TArray<string>;
begin
Result:=TDirectory.GetFiles(PicturesPath);
for var Directory in TDirectory.GetDirectories(PicturesPath,
function(const Path: string; const SearchRec: TSearchRec): Boolean
begin
Result:=not string(SearchRec.Name).StartsWith('.');
end)
do Result:=Result+GetFiles(Directory);
end;
function TMainForm.GetPicturesPath: string;
begin
{$IFDEF ANDROID}
Result:=System.IOUtils.TPath.GetSharedPicturesPath;
{$ELSE}
Result:=System.IOUtils.TPath.GetPicturesPath;
{$ENDIF}
end;
procedure TMainForm.LoadPictures;
begin
for var F in GetFiles(GetPicturesPath) do AddPicture(F);
Rectangle2.RecalcSize;
ScrollToPicture(0);
end;
function TMainForm.AbsoluteCenterPoint: TPointF;
begin
Result:=Rectangle2.LocalToAbsolute(Rectangle2.BoundsRect.CenterPoint);
end;
function TMainForm.AbsolutePressedPoint: TPointF;
begin
Result:=Rectangle2.LocalToAbsolute(Rectangle2.PressedPosition);
end;
function TMainForm.PictureOf(PictureIndex: Integer): TPicture;
begin
if InRange(PictureIndex,0,Pictures.Count-1) then
Result:=Pictures[PictureIndex]
else
Result:=nil;
end;
function TMainForm.PictureAt(const AbsolutePoint: TPointF): TPicture;
var P: TPointF;
begin
Result:=nil;
P:=ScrollContent.AbsoluteToLocal(AbsolutePoint);
for var Picture in Pictures do
if Picture.BoundsRect.Contains(P) then Exit(Picture);
end;
function TMainForm.TryPictureAt(const AbsolutePoint: TPointF; out Picture: TPicture): Boolean;
begin
Picture:=PictureAt(AbsolutePoint);
Result:=Assigned(Picture);
end;
function DistanceRect(const R: TRectF; const P: TPointF): Single;
begin
if R.Contains(P) then
Result:=0
else
Result:=R.CenterPoint.Distance(P)-R.Width/2;
end;
function TMainForm.PictureIndexAt(const AbsolutePoint: TPointF): Integer;
var
P: TPointF;
D,Distance: Single;
begin
Result:=-1;
P:=ScrollContent.AbsoluteToLocal(AbsolutePoint);
for var I:=0 to Pictures.Count-1 do
begin
Distance:=DistanceRect(Pictures[I].BoundsRect,P);
if (I=0) or (Distance<D) then Result:=I;
D:=Distance;
end;
end;
procedure TMainForm.ScrollToPicture(Picture: TPicture; Immediately: Boolean);
var A: TAniCalculations.TTarget;
begin
if Picture=nil then Exit;
CurrentPicture:=Picture;
A.TargetType:=TAniCalculations.TTargetType.Other;
A.Point:=Picture.PageBounds.TopLeft;
TAniCalculationsAccess(FAniCalc).MouseTarget:=A;
if Immediately then FAniCalc.UpdatePosImmediately(True);
end;
procedure TMainForm.ScrollToPicture(PictureIndex: Integer; Immediately: Boolean);
begin
ScrollToPicture(PictureOf(PictureIndex),Immediately);
end;
procedure TMainForm.ShowText(const Text: string);
begin
SetCaptured(nil); // fmx bug
ShowMessage(Text);
end;
procedure TMainForm.Rectangle2Resized(Sender: TObject);
begin
PlacementPictures(Rectangle2.Width>Rectangle2.Height*1.5);
ScrollToPicture(CurrentPicture,True);
end;
procedure TMainForm.Rectangle2Click(Sender: TObject);
var Picture: TPicture;
begin
if not FAniCalc.Moved then
if TryPictureAt(AbsolutePressedPoint,Picture) then
begin
ScrollToPicture(Picture);
FLeave:=True;
ShowText(Picture.ToString);
end;
end;
procedure TMainForm.Rectangle2Gesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
var P: TPointF;
begin
// if Assigned(FAniCalc) then
// if EventInfo.GestureID=260 then
// if TInteractiveGestureFlag.gfBegin in EventInfo.Flags then
// begin
// P:=Rectangle2.AbsoluteToLocal(EventInfo.Location);
// FAniCalc.MouseDown(P.X,P.Y);
// TAniCalculationsAccess(FAniCalc).Shown := True;
// Handled:=True;
// end;
end;
procedure TMainForm.Rectangle2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
//DoUpdateScrollingLimits;
//DoUpdateScrollingLimits2;
// if (FAniCalc <> nil) and FAniCalc.Animation then
// begin
// FAniCalc.Averaging := ssTouch in Shift;
// FAniCalc.MouseUp(X, Y);
// FAniCalc.Animation := False;
// end;
if Assigned(FAniCalc) then
begin
FLeave:=False;
//FAniCalc.Averaging := ssTouch in Shift;
FAniCalc.MouseDown(X,Y);
TAniCalculationsAccess(FAniCalc).Shown:=True;
end;
end;
procedure TMainForm.Rectangle2MouseLeave(Sender: TObject);
begin
if (FAniCalc<>nil) and FAniCalc.Down then
begin
FAniCalc.MouseLeave;
TAniCalculationsAccess(FAniCalc).Shown:=False;
if not FLeave then ScrollToPicture(PictureIndexAt(AbsoluteCenterPoint));
FLeave:=True;
end;
end;
procedure TMainForm.Rectangle2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
begin
// if FAniCalc <> nil then
// begin
// FAniCalc.Averaging := ssTouch in Shift;
// FAniCalc.Animation := True;
// FAniCalc.MouseDown(X, Y);
// end;
//
// if (FAniCalc <> nil) and FAniCalc.Animation then
// begin
// FAniCalc.Averaging := ssTouch in Shift;
// FAniCalc.MouseUp(X, Y);
// FAniCalc.Animation := False;
// end;
if (FAniCalc<>nil) and FAniCalc.Down then
FAniCalc.MouseMove(X,Y);
end;
procedure TMainForm.Rectangle2MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
var PictureIndex: Integer;
begin
if FAniCalc <> nil then
begin
FAniCalc.MouseUp(X, Y);
if not FFeedMode then
begin
if Abs(FAniCalc.CurrentVelocity.X)<100 then
PictureIndex:=PictureIndexAt(AbsoluteCenterPoint)
else
// if Abs(FAniCalc.CurrentVelocity.X)>2000 then
// I:=PictureIndexAt(Rectangle2.LocalToAbsolute(PointF(X+FAniCalc.CurrentVelocity.X/2,Y)))
// else
if FAniCalc.CurrentVelocity.X<0 then
PictureIndex:=CurrentPicture.PictureIndex-1
else
PictureIndex:=CurrentPicture.PictureIndex+1;
ScrollToPicture(EnsureRange(PictureIndex,0,Pictures.Count-1));
end;
end;
end;
procedure TMainForm.Rectangle2MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; var Handled: Boolean);
begin
TAniCalculationsAccess(FAniCalc).Shown:=True;
FAniCalc.MouseWheel(-WheelDelta/2,0);
Handled:=True;
end;
procedure TMainForm.Rectangle2Paint(Sender: TObject; Canvas: TCanvas;
const ARect: TRectF);
begin
Canvas.Stroke.Kind:=TBrushKind.Solid;
Canvas.Stroke.Thickness:=0.5;
Canvas.Stroke.Color:=claRed;
Canvas.DrawLine(PointF(ARect.CenterPoint.X,ARect.Top),PointF(ARect.CenterPoint.X,ARect.Bottom),0.5);
//
// for var I:=1 to 20 do
// Canvas.DrawLine(PointF(I*40-0.5,ARect.Top),PointF(I*40-0.5,ARect.Bottom),0.3);
//
// for var I:=1 to 20 do
// Canvas.DrawLine(PointF(ARect.Left,I*40-0.5),PointF(ARect.Right,I*40-0.5),0.3);
// Canvas.DrawLine(Rectangle2.PressedPosition,Rectangle2.PressedPosition-FAniCalc.ViewportPositionF,1);
end;
procedure TMainForm.AniCalcChange(Sender: TObject);
var
NewViewPos, MaxScrollViewPos: Single;
begin
// NewViewPos := FAniCalc.ViewportPosition.Y;
ScrollContent.Position.Point:=-FAniCalc.ViewportPositionF;
Rectangle4.Height:=Max(100,Rectangle1.Height*Rectangle2.Height/ScrollContent.Height);
Rectangle4.Position.Y:=(Rectangle1.Height-Rectangle4.Height)*(FAniCalc.ViewportPositionF.Y/ContentSize.Y);
Rectangle1.Opacity:=FAniCalc.Opacity;
Rectangle6.Width:=Max(100,Rectangle5.Width*Rectangle2.Width/ScrollContent.Width);
Rectangle6.Position.X:=(Rectangle5.Width-Rectangle6.Width)*(FAniCalc.ViewportPositionF.X/ContentSize.X);
Rectangle5.Opacity:=FAniCalc.Opacity;
// Rectangle2.InvalidateRect(TRectF.Create(Rectangle2.PressedPosition,Rectangle2.PressedPosition-FAniCalc.ViewportPositionF));
//Rectangle2.Repaint;
// MaxScrollViewPos := GetMaxScrollViewPos;
//
// if NewViewPos < 0 then
// UpdateScrollStretchStrength(NewViewPos)
// else if NewViewPos > MaxScrollViewPos then
// UpdateScrollStretchStrength(NewViewPos - MaxScrollViewPos)
// else
// UpdateScrollStretchStrength(0);
//
// if not HasStretchyScrolling then
// NewViewPos := EnsureRange(NewViewPos, 0, MaxScrollViewPos);
//
// if (not SameValue(NewViewPos, FScrollViewPos, TEpsilon.Vector)) and
// (TStateFlag.NeedsScrollBarDisplay in FStateFlags) then
// begin
// FScrollBar.StopPropertyAnimation('Opacity');
// FScrollBar.Opacity := 1;
//
// Exclude(FStateFlags, TStateFlag.NeedsScrollBarDisplay);
// end;
//
// if TStateFlag.ScrollingActive in FStateFlags then
// begin
// UpdateScrollViewPos(NewViewPos);
// UpdateSearchEditPos;
// UpdateDeleteButtonLayout;
// UpdateScrollBar;
// end;
end;
procedure TMainForm.AniCalcStart(Sender: TObject);
begin
// if IsRunningOnDesktop then
// DisableHitTestForControl(FScrollBar);
//
(Self as IScene).ChangeScrollingState(Rectangle2, True);
//
// FStateFlags := FStateFlags + [TStateFlag.NeedsScrollBarDisplay, TStateFlag.ScrollingActive];
end;
procedure TMainForm.AniCalcStop(Sender: TObject);
var
ScrollPixelAlign: Boolean;
begin
// ScrollPixelAlign := TStateFlag.ScrollingActive in FStateFlags;
// Exclude(FStateFlags, TStateFlag.ScrollingActive);
// TAnimator.AnimateFloat(FScrollBar, 'Opacity', 0, 0.2);
//
if not FLeave and FFeedMode then
CurrentPicture:=PictureOf(PictureIndexAt(AbsoluteCenterPoint));
TAniCalculationsAccess(FAniCalc).Shown:=False;
(Self as IScene).ChangeScrollingState(nil,False);
//
// if ScrollPixelAlign and (FScrollScale > TEpsilon.Scale) then
// SetScrollViewPos(Round(FScrollViewPos * FScrollScale) / FScrollScale);
end;
procedure TMainForm.DoUpdateScrollingLimits;
var
Targets: array of TAniCalculations.TTarget;
W,H: Single;
begin
if FAniCalc <> nil then
begin
SetLength(Targets, 2);
ContentSize.X:=Max(0,ScrollContent.Width-Rectangle2.Width);
ContentSize.Y:=Max(0,ScrollContent.Height-Rectangle2.Height);
Targets[0].TargetType:=TAniCalculations.TTargetType.Min;
Targets[0].Point:=TPointD.Create(0,0);
Targets[1].TargetType:=TAniCalculations.TTargetType.Max;
Targets[1].Point:=ContentSize;
FAniCalc.SetTargets(Targets);
end;
// if not HasTouchTracking then
// UpdateScrollBar;
end;
end.
|
(*
Category: SWAG Title: DOS & ENVIRONMENT ROUTINES
Original name: 0041.PAS
Description: Disk Ready?
Author: DESCLIN JEAN
Date: 01-27-94 12:01
*)
{
some days ago, Bryan Ellis (gt6918b@prism.gatech.edu)
asked how one could, in TP, check whether a disk in a
drive is formatted or not. I did not see any answer on
this posted to the list, so here comes an 'extract' from
code of mine which might help. }
{ The following two procedures were extracted from old file
copy programs of mine; Therefore they should be 'cleaned-up'
and fixed up before being included in somebody's code.
The purpose of the first one is to ensure that:
a) the target disk (to be written to) is indeed
present in the drive;
b) the target disk is a formatted one. If it is
not, then opportunity is provided for formatting by
shelling to DOS (rather clumsy, but you get the idea ;-)).
The purpose of the second procedure is partly redundant
with that of the first one. It checks whether the disk
is present in the drive, and it also warns when the disk
is write protected.
Calls to ancillary procedures for putting the cursor onto
the right column and row on the screen, or to clean up
the display, save and restore the screen, or warning noises
etc., were removed, which explains the somewhat desultory
code, which I had no time to rewrite :-( }
{ Note: checked in 2018 with FreePascal:
"CheckDriv" returns TRUE for non-existing drives,
so it seems not to work properly }
uses DOS,CRT;
Procedure CheckDriv(driv : string; var OK:boolean;
var cc:char );
{* driv is the string holding the letter of the drive; *}
{* OK is a global boolean var which must be true in order for *}
{* the rest of the program to proceed. *}
{* cc : checks input by the user *}
{***************************************************************}
var IOR : integer;
jk,dr : char;
S : string;
CmdLine: PathStr;
begin
OK := TRUE;
IOR := 0;
{$I-}
ChDir(driv); { make the target drive current }
{ the original current drive letter should be saved in order}
{ to be restored afterwards }
dr := upcase(driv[1]);
IOR := IOresult;
if IOR = 152 then begin
OK := FALSE;
writeln('No disk in ',copy(driv,1,2));
writeln(' (Insert a disk or press ESC)');
repeat until keypressed;
cc := readkey
end
else
if IOR = 162 then begin
OK := FALSE;
writeln('Unformatted disk in ',copy(driv,1,2));
writeln('Press ESC to cancel...');
writeln('...or press ''*'' to format...');
repeat until keypressed;
cc := readkey;
{ here, for security sake, only drives A and B were taken
into account for writing }
if ((cc = '*') AND ((dr = 'A') OR (dr = 'B'))) then
begin
cc := chr(27);
{ now, your Format.com file had better be in the path! }
S := FSearch('FORMAT.COM', GetEnv('PATH'));
S := FExpand(S);
CmdLine := copy(driv,1,2);
SwapVectors;
Exec(S,CmdLine);
SwapVectors;
If DosError <> 0 then
write('Dos error #',DosError)
else
write('Press any key...');
repeat until keypressed;
jk := readkey;
end
end
end;
{$I+}
Procedure CheckWrite(var FF: file;
var OK: boolean;
var cc: char);
{* Tests for presence of disk in drive and write protect tab, *}
{* to allow opening of untyped file for write: this file has *}
{* of course been assigned before, elsewhere in the program *}
{****************************************************************}
{$I-}
var riteprot : boolean;
DiskAbsent : boolean;
error : integer;
begin
riteprot := TRUE;
DiskAbsent := TRUE;
rewrite(FF);
error := IOResult;
riteprot := error = 150;
DiskAbsent := error = 152;
if riteprot then begin
writeln('Disk is write protected!');
writeln('Correct the situation and press any key...');
repeat until keypressed;
cc := readkey
end;
if DiskAbsent then begin
writeln('No disk in the drive!');
writeln('Insert disk into drive, then press any key...');
repeat until keypressed;
cc := readkey
end;
OK := (Not(riteprot)) AND (Not(DiskAbsent))
end;
{$I+}
var
isItOk: boolean;
letter: char;
begin
writeln('Checking if D:\ is formatted...');
CheckDriv('D:\', isItOk, letter);
writeln(isItOk);
end.
|
function isPInt(s: string): boolean;
var
i,l: integer;
res: boolean;
begin
res:=true;
l:= length(s); i:=1;
while((i<=l) and res) do begin
if((s[i]<'0') or (s[i]>'9')) then res:=false;
inc(i);
end;
isPInt:=res;
end;
function BigIntToStr(s: string; n: integer): array of shortint;
var
i,l: integer;
res: array of shortint;
begin
l:=length(s);
SetLength(res,n);
if((n>=l) and isPInt(s)) then begin
for i:= l downto 1 do res[i+n-l-1]:=ord(s[i])-ord('0');
for i:= 0 to n-l-1 do res[i]:=0;
BigIntToStr:=res;
end else BigIntToStr:=BigIntToStr('0',n);
end;
procedure disp(a: array of shortint; n: integer);
var
i: integer;
begin
for i:= 0 to n-1 do write(a[i]);
end;
function subtract(a,b: array of shortint; n: integer): array of shortint;
// a MUST be >= b and both MUST be >0
var
i,k: integer;
r: array of shortint;
begin
SetLength(r,n);
k:=0;
while(a[k]=0) do inc(k);
for i:= n-1 downto k+1 do if(a[i]<b[i]) then begin
a[i-1]-=1;
a[i]+=10;
end;
for i:= n-1 downto 0 do r[i]:=a[i]-b[i];
subtract:=r;
end;
function isZero(a: array of shortint; n: integer): boolean;
var
r: boolean;
i: integer;
begin
r:=true;
i:=n-1;
while((i>=0) and r) do begin
if(a[i]<>0) then r:=false;
dec(i);
end;
isZero:=r;
end;
function minimize(a: array of shortint; n: integer; var k: integer): array of shortint;
var
i: integer;
r: array of shortint;
begin
k:=0;
if(isZero(a,n)) then k:=n-1
else while(a[k]=0) do inc(k);
SetLength(r,n-k);
for i:= n-k-1 downto 0 do r[i]:=a[k+i];
k:=n-k;
minimize:=r;
end;
var
s1,s2: string;
a,b: array of shortint;
n,k1,k2,k3: integer;
begin
readln(s1);
readln(s2);
n:= max(length(s1),length(s2));
a:=BigIntToStr(s1,n);
b:=BigIntToStr(s2,n);
disp(minimize(a,n,k1),k1);
writeln;
writeln('-');
disp(minimize(b,n,k2),k2);
writeln;
writeln('=');
disp(minimize(subtract(a,b,n),n,k3),k3);
end.
|
unit uSavePoint;
interface
uses uGlobals, Classes;
type
TRecord = record
key: string;
value: string;
deleted: boolean;
sync_record: boolean;
end;
TRecords = array of TRecord;
TSavePoint = class
private
us_id: integer;
mwindow: string;
rec: TRecords;
sql: TStringList;
function exists(const key : string; out index: integer): boolean;
public
property Window: string read mWindow;
procedure addValue(const key, value: string);
procedure addFloatValue(const key: string; value: double);
procedure addIntValue(const key: string; value: integer);
procedure addResultMask(const key: string; value: TResultMask);
function asString(const key: string): string;
function asInteger(const key: string): integer;
function asFloat(const key: string): double;
function asResultMask(const key: string): TResultMask;
function count(): integer;
class procedure fromCSV(delimChar: Char; const dataList: TStringList);
procedure Clear;
procedure Delete(const key: string);
procedure Save;
procedure Load();
constructor Create(user: integer; AWindow: string);
procedure Free;
end;
implementation
uses SysUtils, uData, SQLite3, SQLiteTable3, uUser;
{ TSavePoint }
procedure TSavePoint.addResultMask(const key: string; value: TResultMask);
var i : integer;
s: string;
begin
s := '';
for i := 0 to length(value) - 1 do
s := s + intToStr(integer(value[i]));
addValue(key, s);
end;
procedure TSavePoint.addFloatValue(const key: string; value: double);
begin
addValue(key, formatFloat('0.00000', value));
end;
procedure TSavePoint.addIntValue(const key: string; value: integer);
begin
addValue(key, intToStr(value));
end;
procedure TSavePoint.addValue(const key, value: string);
var i: integer;
begin
if exists(key, i) then
begin
rec[i].key := key;
rec[i].value := value;
rec[i].deleted := false;
end
else begin
setLength(rec, length(rec) + 1);
rec[high(rec)].key := key;
rec[high(rec)].value := value;
rec[high(rec)].deleted := false;
end;
end;
function TSavePoint.asResultMask(const key: string):TResultMask;
var i,j: integer;
begin
result := nil;
for i := 0 to length(rec) - 1 do
begin
if (key = rec[i].key) then
begin
setLength(result, length(rec[i].value));
for j := 0 to length(result) - 1 do
result[j] := boolean(strToInt(rec[i].value[j + 1]));
exit;
end;
end;
end;
function TSavePoint.asFloat(const key: string): double;
var i: integer;
begin
result := 0;
for i := 0 to length(rec) - 1 do
if (key = rec[i].key) then exit(strToFloatEx((rec[i].value)))
end;
function TSavePoint.asInteger(const key: string): integer;
var i: integer;
begin
result := -1;
for i := 0 to length(rec) - 1 do
if (key = rec[i].key) then exit(strToInt(rec[i].value))
end;
function TSavePoint.asString(const key: string): string;
var i: integer;
begin
result := '';
for i := 0 to length(rec) - 1 do
if (key = rec[i].key) then exit(rec[i].value)
end;
procedure TSavePoint.Clear;
begin
us_id := 0;
mWindow := '';
rec := nil;
end;
function TSavePoint.count: integer;
begin
result := length(rec);
end;
constructor TSavePoint.Create(user: integer; AWindow: string);
begin
sql := TStringList.Create;
us_id := user;
mwindow := AWindow;
end;
procedure TSavePoint.Delete(const key: string);
var i: integer;
begin
for i := 0 to length(rec) - 1 do
begin
if(rec[i].key = key) then
begin
rec[i].deleted := true;
sql.Clear;
sql.Add(format(
'DELETE FROM SAVEPOINT WHERE ' +
'US_ID = %d AND WINDOW = "%s" AND ' +
'KEY_FIELD = "%s"', [us_id, mwindow, key])
);
dm.sqlite.ExecSQL(ansistring(sql.Text));
exit
end;
end;
end;
function TSavePoint.exists(const key: string; out index: integer): boolean;
var i: integer;
begin
result := false;
for i := 0 to length(rec)- 1 do
if(rec[i].key = key) then
begin index := i; exit(true) end;
end;
procedure TSavePoint.Free;
begin
sql.Free;
end;
class procedure TSavePoint.fromCSV(delimChar: Char; const dataList: TStringList);
var i: integer;
csvList: TStringList;
sp: TSavePoint;
key, value: string;
begin
sp := nil;
csvList := TStringList.Create;
sp := TSavePoint.Create(0, '');
try
csvList.Delimiter := delimChar;
csvList.StrictDelimiter := true;
for i := 0 to dataList.Count - 1 do
begin
sp.Clear;
csvList.Clear;
csvList.DelimitedText := trim(dataList.Strings[i]);
key := trim(csvList.Strings[3]);
value := trim(csvList.Strings[4]);
sp.us_id := strToInt(trim(csvList.Strings[0]));
sp.mWindow := trim(csvList.Strings[2]);
sp.addValue(key, value);
sp.Save;
end;
finally
freeAndNil(sp);
csvList.Free;
end;
end;
procedure TSavePoint.Load();
var i, cnt: integer; table: TSQLiteUniTable;
begin
sql.Clear;
sql.Add(format(
'SELECT COUNT(*)FROM SAVEPOINT ' +
'WHERE US_ID = %d AND WINDOW = "%s"', [us_id, mwindow])
);
try
table := TSQLiteUniTable.Create(dm.sqlite, ansiString(sql.Text));
cnt := table.FieldAsInteger(0);
finally
freeAndNil(table);
end;
if (cnt = 0) then exit;
setLength(rec, cnt);
sql.Clear;
sql.Add(format(
'SELECT KEY_FIELD, VALUE_FIELD FROM SAVEPOINT ' +
'WHERE US_ID = %d AND WINDOW = "%s"', [us_id, mwindow]));
try
table := TSQLiteUniTable.Create(dm.sqlite, ansiString(sql.Text));
for i := 0 to cnt - 1 do
begin
rec[i].key := table.FieldAsString(0);
rec[i].value := table.FieldAsString(1);
table.Next;
end;
finally
freeAndNil(table)
end;
// dm.LoadSavePoint(us_id, window, rec);
end;
procedure TSavePoint.Save;
var i, cnt: integer; table: TSQLiteUniTable;
begin
for i := 0 to length(rec) - 1 do
begin
if rec[i].deleted then continue;
sql.Clear;
sql.Add(format(
'SELECT COUNT(*)FROM SAVEPOINT ' +
'WHERE US_ID = %d AND WINDOW = "%s" AND KEY_FIELD = "%s"',
[us_id, mwindow, rec[i].key])
);
try
table := TSQLiteUniTable.Create(dm.sqlite, ansiString(sql.Text));
cnt := table.FieldAsInteger(0);
finally
freeAndNil(table)
end;
sql.Clear;
if cnt = 0 then
begin
sql.Add(format(
'INSERT INTO SAVEPOINT(US_ID, WINDOW, KEY_FIELD, VALUE_FIELD) ' +
'VALUES(%d, "%s", "%s", "%s")',
[us_id, mwindow, rec[i].key, rec[i].value])
);
end
else begin
sql.Add(format(
'UPDATE SAVEPOINT ' +
'SET VALUE_FIELD = "%s" ' +
'WHERE US_ID = %d AND WINDOW = "%s" AND KEY_FIELD = "%s"',
[rec[i].value, us_id, mwindow, rec[i].key])
);
end;
dm.sqlite.ExecSQL(ansistring(sql.Text));
end;
end;
end.
|
unit USourceInfo;
interface
uses
TeeGenericTree, Classes, System.Generics.Collections, Data.DBXJSON, System.JSON, UUtilsJSON;
type
TStringTree = TNode<String>;
TSourceInfoType = (sitUnknown, sitString, sitPPT, sitFileName, sitTemplate, sitBook);
TSourceInfo = class(TJSONPersistent)
private
FFileName: string;
FContentTypeOverride: boolean;
FShapeName: string;
FDescription: string;
FText: string;
FSlideName: string;
FSourceType: TSourceInfoType;
FRemark: string;
protected
function GetAsJSonObject: TJSONObject; override;
procedure SetAsJSonObject(const Value: TJSONObject); override;
public
property SourceType: TSourceInfoType read FSourceType write FSourceType;
property Description: string read FDescription write FDescription;
property Remark: string read FRemark write FRemark;
property Text: string read FText write FText;
property FileName: string read FFileName write FFileName;
property SlideName: string read FSlideName write FSlideName;
property ShapeName: string read FShapeName write FShapeName;
property ContentTypeOverride: boolean read FContentTypeOverride write FContentTypeOverride;
constructor Create; overload; virtual;
constructor Create(strJSON: string); overload; virtual;
constructor Create(json: TJSONObject); overload; virtual;
function DeepCopy: TSourceInfo;
procedure ClearAsString;
constructor CreateAsString(strText: string; blnContentTypeOverride: boolean = false); virtual;
constructor CreateAsTemplate(strTemplateName: string; blnContentTypeOverride: boolean = false); virtual;
constructor CreateAsPPT(strFilename, strSlide, strShape: string; blnContentTypeOverride: boolean = false); virtual;
constructor CreateAsFileName(strFileName: string; blnContentTypeOverride: boolean = false); virtual;
constructor CreateAsBook(strBook, strChapter, strVerse: string; blnContentTypeOverride: boolean = false); virtual;
end;
TSourceInfos = class(TObjectList<TSourceInfo>)
public
function DeepCopy: TSourceInfos;
end;
function SourceInfoToString(sourceinfo: TSourceInfo; blnDoImplode: boolean = true): string;
function SourceInfoFromString(source: string): TSourceInfo;
function SourceInfoToMemoText(sourceinfo: TSourceInfo): string;
function SourceInfoFromMemoText(strText: string): TSourceInfo;
procedure SortSourceInfoStrings(slStrings: TStrings);
procedure SortStrings(slStrings: TStringList);
implementation
uses
System.SysUtils,
USettings, UUtilsStrings, UStringLogicalComparer;
function SourceInfoToString(sourceinfo: TSourceInfo; blnDoImplode: boolean = true): string;
begin
Assert(sourceinfo.SourceType <> sitUnknown);
if blnDoImplode then begin
sourceinfo.FileName := GetSettings.DirImplode(sourceinfo.FileName);
end;
Result := sourceinfo.AsJSon;
end;
function SourceInfoFromString(source: string): TSourceInfo;
begin
Result := TSourceInfo.Create(source);
Assert(Result.SourceType <> sitUnknown);
end;
const
CTEMPLATEID = '#template:';
function SourceInfoToMemoText(sourceinfo: TSourceInfo): string;
begin
case sourceinfo.SourceType of
sitString: Result := sourceinfo.Text;
sitPPT: ;
sitFileName: ;
sitTemplate: Result := CTEMPLATEID + sourceinfo.Text + '#';
else
Result := '';
end;
end;
function SourceInfoFromMemoText(strText: string): TSourceInfo;
var
iPosTemplateStart, iPosTemplateEnd: integer;
strTemplate: string;
begin
iPosTemplateStart := pos(CTEMPLATEID, strText);
if iPosTemplateStart > 0 then begin
iPosTemplateEnd := PosIEx('#', strText, iPosTemplateStart + Length(CTEMPLATEID));
iPosTemplateStart := iPosTemplateStart + Length(CTEMPLATEID);
strTemplate := copy(strText, iPosTemplateStart, iPosTemplateEnd - iPosTemplateStart);
Result := TSourceInfo.CreateAsTemplate(strTemplate);
end else begin
Result := TSourceInfo.CreateAsString(strText);
end;
end;
function SortItem(List: TStringList; Index1, Index2: Integer): Integer;
var
src1, src2: TSourceInfo;
begin
src1 := nil;
src2 := nil;
try
src1 := SourceInfoFromString(List[Index1]);
src2 := SourceInfoFromString(List[Index2]);
Result := CompareNatural(src1.Description, src2.Description);
finally
src1.Free;
src2.Free;
end;
end;
function SortStringsItem(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := CompareNatural(List[Index1], List[Index2]);
end;
procedure SortSourceInfoStrings(slStrings: TStrings);
var
slItems: TStringList;
begin
slItems := TStringList.Create;
try
slItems.Assign(slStrings);
slItems.CustomSort(SortItem);
slStrings.Assign(slItems);
finally
slItems.Free;
end;
end;
procedure SortStrings(slStrings: TStringList);
begin
slStrings.CustomSort(SortStringsItem);
end;
{ TSourceInfo }
procedure TSourceInfo.ClearAsString;
begin
SourceType := sitString;
Description := '';
Text := '';
FileName := '';
SlideName := '';
ShapeName := '';
ContentTypeOverride := false;
end;
constructor TSourceInfo.Create(strJSON: string);
begin
Create;
SetAsJSon(strJSON);
end;
constructor TSourceInfo.Create(json: TJSONObject);
begin
Create;
SetAsJSonObject(json);
end;
constructor TSourceInfo.Create;
begin
//
end;
constructor TSourceInfo.CreateAsBook(strBook, strChapter, strVerse: string;
blnContentTypeOverride: boolean);
begin
SourceType := sitBook;
Description := '';
Remark := '';
Text := '';
FileName := strBook;
SlideName := strChapter;
ShapeName := strVerse;
ContentTypeOverride := blnContentTypeOverride;
end;
constructor TSourceInfo.CreateAsFileName(strFileName: string;
blnContentTypeOverride: boolean);
begin
SourceType := sitFileName;
Description := '';
Remark := '';
Text := '';
FileName := strFileName;
SlideName := '';
ShapeName := '';
ContentTypeOverride := blnContentTypeOverride;
end;
constructor TSourceInfo.CreateAsPPT(strFilename, strSlide, strShape: string;
blnContentTypeOverride: boolean);
begin
SourceType := sitPPT;
Description := '';
Remark := '';
Text := '';
FileName := strFilename;
SlideName := strSlide;
ShapeName := strShape;
ContentTypeOverride := blnContentTypeOverride;
end;
constructor TSourceInfo.CreateAsString(strText: string;
blnContentTypeOverride: boolean);
begin
ClearAsString;
Text := strText;
ContentTypeOverride := blnContentTypeOverride;
end;
constructor TSourceInfo.CreateAsTemplate(strTemplateName: string;
blnContentTypeOverride: boolean);
begin
SourceType := sitTemplate;
Description := '';
Remark := '';
Text := strTemplateName;
FileName := '';
SlideName := '';
ShapeName := '';
ContentTypeOverride := blnContentTypeOverride;
end;
function TSourceInfo.DeepCopy: TSourceInfo;
begin
Result := TSourceInfo.Create;
Result.SourceType := SourceType;
Result.Description := Description;
Result.Remark := Remark;
Result.Text := Text;
Result.FileName := GetSettings.DirExplode(FileName);
Result.SlideName := SlideName;
Result.ShapeName := ShapeName;
Result.ContentTypeOverride := ContentTypeOverride;
end;
function TSourceInfo.GetAsJSonObject: TJSONObject;
var
strFileName: string;
begin
Result := inherited GetAsJSonObject;
Assert(FSourceType <> sitUnknown);
strFileName := GetSettings.DirImplode(FFileName);
Result.AddPair('SourceType', TJSONNumber.Create(ord(FSourceType)));
Result.AddPair('Description', EscapeString(FDescription));
Result.AddPair('Remark', EscapeString(FRemark));
Result.AddPair('Text', EscapeString(FText));
Result.AddPair('FileName', EscapeString(strFileName));
Result.AddPair('SlideName', EscapeString(FSlideName));
Result.AddPair('ShapeName', EscapeString(FShapeName));
Result.AddPair(CreateBoolPair('ContentTypeOverride', FContentTypeOverride));
end;
procedure TSourceInfo.SetAsJSonObject(const Value: TJSONObject);
begin
inherited SetAsJSonObject(Value);
FSourceType := TSourceInfoType(UUtilsJSON.GetAsInteger(Value, 'SourceType', 0));
FDescription := UUtilsJSON.GetAsString(Value, 'Description');
FRemark := UUtilsJSON.GetAsString(Value, 'Remark');
FText := UUtilsJSON.GetAsString(Value, 'Text');
FFileName := GetSettings.DirExplode(UUtilsJSON.GetAsString(Value, 'FileName'));
FSlideName := UUtilsJSON.GetAsString(Value, 'SlideName');
FShapeName := UUtilsJSON.GetAsString(Value, 'ShapeName');
FContentTypeOverride := UUtilsJSON.GetAsBoolean(Value, 'ContentTypeOverride');
end;
{ TSourceInfos }
function TSourceInfos.DeepCopy: TSourceInfos;
var
i: Integer;
begin
Result := TSourceInfos.Create;
for i := 0 to Count -1 do begin
Result.Add(Items[i].DeepCopy);
end;
end;
end.
|
/// <summary>
/// PageView é adapter para gerar controller para PageViews Abstract
/// </summary>
unit MVCBr.PageView;
{ *************************************************************************** }
{ }
{ MVCBr é o resultado de esforços de um grupo }
{ }
{ Copyright (C) 2017 MVCBr }
{ }
{ amarildo lacerda }
{ http://www.tireideletra.com.br }
{ }
{ }
{ *************************************************************************** }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{ *************************************************************************** }
interface
uses {$IFDEF FMX} FMX.Forms, {$ELSE} VCL.Forms, {$ENDIF}
System.Classes, System.SysUtils, MVCBr.Interf, MVCBr.Controller,
System.JSON,
MVCBr.Component, MVCBr.FormView;
type
TPageView = class;
TCustomPageViewFactory = class;
IPageView = interface
['{FCAA865A-3ED1-46B2-AFCA-627F511B3A2C}']
function This: TPageView;
procedure Remove;
procedure SetTab(const Value: TObject);
function GetTab: TObject;
property Tab: TObject read GetTab write SetTab;
end;
IPageViews = interface(IModel)
['{60605589-283D-4403-B434-D32A024BB049}']
procedure SetPageContainer(const Value: TComponent);
function GetPageContainer: TComponent;
property PageContainer: TComponent read GetPageContainer
write SetPageContainer;
function GetItems(idx: Integer): IPageView;
procedure SetItems(idx: Integer; const Value: IPageView);
function Count: Integer;
property Items[idx: Integer]: IPageView read GetItems write SetItems;
function FindViewByID(Const AID: String): IPageView;
function AddView(AView: IView): IPageView; overload;
function AddView(Const AController: TGuid): IPageView; overload;
function FindView(Const AGuid: TGuid): IPageView; overload;
function FindView(Const AView: IView): IPageView; overload;
function IndexOf(Const AGuid: TGuid): Integer;
end;
/// TPageControllerView - Atributos para o PageView
TPageView = class(TMVCFactoryAbstract, IPageView)
private
FOwner: TCustomPageViewFactory;
FText: string;
FTab: TObject;
FID: String;
FView: IView;
FController:IController;
procedure SetText(const Value: string);
function GetText: string;
procedure SetTab(const Value: TObject);
function GetTab: TObject;
procedure SetView(const Value: IView);
protected
FClassType: TClass;
procedure SetID(const Value: String); override;
public
Destructor Destroy;override;
function GetOwner: TCustomPageViewFactory;
function This: TPageView;
property Text: string read GetText write SetText;
property Tab: TObject read GetTab write SetTab;
property ID: String read FID write SetID;
property View: IView read FView write SetView;
procedure Remove; virtual;
end;
/// Adaptador para associar a lista de View com o TPageControl ativo
/// Cada View é mostrado em uma aba do PageControl
TCustomPageViewFactory = class(TComponentFactory, IModel)
private
FActivePageIndex: Integer;
FAfterViewCreate: TNotifyEvent;
function GetItems(idx: Integer): IPageView;
procedure SetItems(idx: Integer; const Value: IPageView);
procedure SetActivePageIndex(const Value: Integer);
procedure SetAfterViewCreate(const Value: TNotifyEvent);
protected
FPageContainer: TComponent;
FList: IInterfaceList; // TMVCInterfacedList<IPageView>;
procedure SetPageContainer(const Value: TComponent); virtual;
function GetPageContainer: TComponent; virtual;
/// ligação para o PageControl component
property PageContainer: TComponent read GetPageContainer
write SetPageContainer;
procedure Init(APageView: IPageView); virtual;
procedure Remove(APageView: IPageView); virtual;
Procedure DoQueryClose(const APageView: IPageView;
var ACanClose: Boolean); virtual;
Procedure DoViewCreate(Sender: TObject); virtual;
procedure Notification(AComponent: TComponent;
AOperation: TOperation); override;
public
destructor Destroy; override;
procedure AfterConstruction; override;
function NewTab(APageView: IPageView): TObject; virtual;
function GetPageTabClass: TComponentClass; virtual;
function GetPageContainerClass: TComponentClass; virtual;
function Count: Integer;
function ActivePage: IPageView; virtual;
procedure SetActivePage(Const Tab: TObject); virtual;
property ActivePageIndex: Integer read FActivePageIndex
write SetActivePageIndex;
property Items[idx: Integer]: IPageView read GetItems write SetItems;
function PageViewIndexOf(APageView: IPageView): Integer;
function NewItem(Const ACaption: string): IPageView; virtual;
function AddView(AView: IView): IPageView; overload; virtual;
function AddView(Const AController: TGuid): IPageView; overload; virtual;
function AddView(Const AController: TGuid; ABeforeShow: TProc<IView>)
: IPageView; overload; virtual;
function AddForm(AClass: TFormClass): IPageView; virtual;
function FindViewByID(Const AID: String): IPageView; virtual;
function FindViewByClassName(const AClassName: String): IPageView; virtual;
function FindView(Const AGuid: TGuid): IPageView; overload; virtual;
function FindView(Const AView: IView): IPageView; overload; virtual;
procedure ViewEvent(AMessage: TJsonValue);overload;virtual;
procedure ViewEvent(AMessage: String);overload;virtual;
function IndexOf(Const AGuid: TGuid): Integer;
property AfterViewCreate: TNotifyEvent read FAfterViewCreate
write SetAfterViewCreate;
end;
implementation
{ TPageControllerView }
destructor TPageView.Destroy;
begin
//FView := nil;
//FController := nil;
inherited;
end;
function TPageView.GetOwner: TCustomPageViewFactory;
begin
result := FOwner;
end;
function TPageView.GetTab: TObject;
begin
result := FTab;
end;
function TPageView.GetText: string;
begin
result := FText;
end;
procedure TPageView.Remove;
begin
if assigned(FOwner) then
FOwner.Remove(self);
end;
procedure TPageView.SetID(const Value: String);
begin
FID := Value;
end;
procedure TPageView.SetTab(const Value: TObject);
begin
FTab := Value;
end;
procedure TPageView.SetText(const Value: string);
begin
FText := Value;
end;
procedure TPageView.SetView(const Value: IView);
begin
FView := Value;
FID := Value.GetID;
end;
function TPageView.This: TPageView;
begin
result := self;
end;
{ TPageControlFactory }
function TCustomPageViewFactory.AddView(AView: IView): IPageView;
begin
result := NewItem(AView.Title);
result.This.View := AView;
result.this.FController := AView.GetController;
DoViewCreate(AView.This);
Init(result);
end;
function TCustomPageViewFactory.ActivePage: IPageView;
begin
result := FList.Items[FActivePageIndex] as IPageView;
end;
function TCustomPageViewFactory.AddForm(AClass: TFormClass): IPageView;
var
ref: TForm;
vw: IView;
begin
// checa se o formulario ja esta carregao e reutiliza
result := FindViewByClassName(AClass.ClassName);
if assigned(result) then
begin
SetActivePage(result.This.FTab);
exit;
end;
// instancia novo formulario
ref := AClass.Create(self);
if supports(ref, IView, vw) then
begin
result := AddView(vw);
exit;
end;
// usa um stub para embeded de uma formulario como (sem IVIEW)
result := AddView(TViewFactoryAdapter.New(ref, false));
end;
function TCustomPageViewFactory.AddView(Const AController: TGuid): IPageView;
begin
result := AddView(AController, nil);
end;
function TCustomPageViewFactory.AddView(const AController: TGuid;
ABeforeShow: TProc<IView>): IPageView;
var
LController: IController;
LView: IView;
begin
result := nil;
LController := ResolveController(AController);
assert(assigned(LController), 'Parâmetro não é um controller');
// checa se já existe uma aba para a mesma view
LView := LController.GetView;
if LView.GetController = nil then
LView.SetController(LController);
if not assigned(LView) then
exit;
result := FindView(LView);
if assigned(result) then
begin
Init(result);
exit;
end;
// criar nova aba
if assigned(ABeforeShow) then
ABeforeShow(LView);
result := AddView(LView);
end;
procedure TCustomPageViewFactory.AfterConstruction;
begin
inherited;
FList := TMVCInterfacedList<IPageView>.Create;
end;
procedure TCustomPageViewFactory.DoQueryClose(const APageView: IPageView;
var ACanClose: Boolean);
begin
ACanClose := true;
end;
procedure TCustomPageViewFactory.DoViewCreate(Sender: TObject);
begin
if assigned(FAfterViewCreate) then
FAfterViewCreate(Sender);
end;
function TCustomPageViewFactory.Count: Integer;
begin
result := FList.Count;
end;
destructor TCustomPageViewFactory.Destroy;
begin
FList := nil; // .DisposeOf;
inherited;
end;
function TCustomPageViewFactory.IndexOf(const AGuid: TGuid): Integer;
var
i: Integer;
begin
result := -1;
for i := 0 to Count - 1 do
if supports(Items[i].This, AGuid) then
begin
result := i;
exit;
end;
end;
procedure TCustomPageViewFactory.Init(APageView: IPageView);
begin
end;
function TCustomPageViewFactory.FindView(const AGuid: TGuid): IPageView;
var
i: Integer;
begin
result := nil;
i := IndexOf(AGuid);
if i >= 0 then
result := Items[i];
end;
function TCustomPageViewFactory.FindView(const AView: IView): IPageView;
var
i: Integer;
begin
result := nil;
try
for i := 0 to Count - 1 do
if supports(Items[i].This, IPageView) then
if Items[i].This.View = AView then
begin
result := Items[i];
exit;
end;
except
end;
end;
function TCustomPageViewFactory.FindViewByClassName(const AClassName: String)
: IPageView;
var
i: Integer;
frm: TObject;
begin
result := nil;
for i := 0 to Count - 1 do
begin
if not assigned(Items[i].This.FView) then
continue;
if Items[i].This.View.This.InheritsFrom(TViewFactoryAdapter) then
frm := TViewFactoryAdapter(Items[i].This.View.This).Form
else
frm := Items[i].This.FView.This;
if sametext(frm.ClassName, AClassName) then
begin
result := Items[i];
exit;
end;
end;
end;
function TCustomPageViewFactory.FindViewByID(const AID: String): IPageView;
var
i: Integer;
begin
result := nil;
for i := 0 to FList.Count - 1 do
if sametext(AID, (FList.Items[i] as IPageView).This.ID) then
begin
result := FList.Items[i] as IPageView;
exit;
end;
end;
function TCustomPageViewFactory.GetItems(idx: Integer): IPageView;
begin
result := FList.Items[idx] as IPageView;
end;
function TCustomPageViewFactory.GetPageContainer: TComponent;
begin
result := FPageContainer;
end;
function TCustomPageViewFactory.GetPageContainerClass: TComponentClass;
begin
raise Exception.Create('Error: implements in inherited class');
end;
function TCustomPageViewFactory.GetPageTabClass: TComponentClass;
begin
raise Exception.Create('Error: implements in inherited class');
end;
function TCustomPageViewFactory.NewItem(const ACaption: string): IPageView;
var
obj: TPageView;
begin
obj := TPageView.Create;
FList.Add(obj);
obj.FOwner := self;
obj.Text := ACaption;
obj.Tab := NewTab(obj);
if obj.Tab <> nil then
obj.FClassType := obj.Tab.ClassType;
result := obj;
end;
function TCustomPageViewFactory.NewTab(APageView: IPageView): TObject;
begin
result := GetPageTabClass.Create(nil);
end;
procedure TCustomPageViewFactory.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
inherited;
if AOperation = TOperation.opRemove then
if AComponent = FPageContainer then
FPageContainer := nil;
end;
function TCustomPageViewFactory.PageViewIndexOf(APageView: IPageView): Integer;
var
i: Integer;
begin
result := -1;
if not assigned(APageView) then
exit;
for i := 0 to FList.Count - 1 do
begin
if APageView.Tab.Equals(Items[i].Tab) then
begin
result := i;
exit;
end;
end;
end;
procedure TCustomPageViewFactory.Remove(APageView: IPageView);
var
i: Integer;
begin
if assigned(FList) then
for i := FList.Count - 1 downto 0 do
if APageView.This.ID = (FList.Items[i] as IPageView).This.ID then
begin
FList.Delete(i);
exit;
end;
end;
procedure TCustomPageViewFactory.SetActivePage(const Tab: TObject);
begin
// implementar na class herdada;
end;
procedure TCustomPageViewFactory.SetActivePageIndex(const Value: Integer);
begin
FActivePageIndex := Value;
end;
procedure TCustomPageViewFactory.SetAfterViewCreate(const Value: TNotifyEvent);
begin
FAfterViewCreate := Value;
end;
procedure TCustomPageViewFactory.SetItems(idx: Integer; const Value: IPageView);
begin
FList.Items[idx] := Value;
end;
procedure TCustomPageViewFactory.SetPageContainer(const Value: TComponent);
begin
FPageContainer := Value;
end;
procedure TCustomPageViewFactory.ViewEvent(AMessage: String);
var
i: Integer;
LHandled: Boolean;
begin
for i := 0 to Count - 1 do
begin
Items[i].This.FView.ViewEvent(AMessage, LHandled);
if LHandled then
exit;
end;
end;
procedure TCustomPageViewFactory.ViewEvent(AMessage: TJsonValue);
var
i: Integer;
LHandled: Boolean;
begin
for i := 0 to Count - 1 do
begin
Items[i].This.FView.ViewEvent(AMessage, LHandled);
if LHandled then
exit;
end;
end;
end.
|
unit TextEditor.CodeFolding.Hint.Colors;
interface
uses
System.Classes, System.UITypes;
type
TTextEditorCodeFoldingHintColors = class(TPersistent)
strict private
FBackground: TColor;
FBorder: TColor;
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
published
property Background: TColor read FBackground write FBackground default TColors.SysWindow;
property Border: TColor read FBorder write FBorder default TColors.SysBtnFace;
end;
implementation
constructor TTextEditorCodeFoldingHintColors.Create;
begin
inherited;
FBackground := TColors.SysWindow;
FBorder := TColors.SysBtnFace;
end;
procedure TTextEditorCodeFoldingHintColors.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorCodeFoldingHintColors) then
with ASource as TTextEditorCodeFoldingHintColors do
begin
Self.FBackground := FBackground;
Self.FBorder := FBorder;
end
else
inherited Assign(ASource);
end;
end.
|
unit ModifyPassword;
interface
uses
Classes, Controls, Forms, StdCtrls, DB, SysUtils,
ADODB, Buttons, Dialogs;
type
TModifyPasswordForm = class(TForm)
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
EdtOld: TEdit;
EdtNew: TEdit;
EdtRenew: TEdit;
procedure BitBtn1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ModifyPasswordForm: TModifyPasswordForm;
implementation
uses QueryDM, Main, CommonUtil;
{$R *.dfm}
procedure TModifyPasswordForm.BitBtn1Click(Sender: TObject);
begin
Close;
end;
procedure TModifyPasswordForm.FormShow(Sender: TObject);
begin
Label1.Caption := Label1.Caption + MainForm.CurrentUser;
end;
procedure TModifyPasswordForm.BitBtn2Click(Sender: TObject);
var OldPassword, NewPassword: string;
begin
with QueryDataModule.ADOQUser do
begin
Close;
SQL.Clear;
SQL.Add('select 密码 from 用户信息 where 用户名=:user');
Parameters.ParamByName('user').Value := MainForm.CurrentUser;
Open;
OldPassword := FieldByName('密码').AsString;
if UpperCase(TCommonUtil.md5(EdtOld.Text)) <> UpperCase(OldPassword) then
begin
MessageDlg('旧密码不正确', mtWarning, [mbOK], 0);
EdtOld.Text := '';
EdtOld.SetFocus;
Exit
end;
if EdtNew.Text <> EdtRenew.Text then
begin
MessageDlg('两次新密码输入不一致,请重新输入!', mtWarning, [mbOK], 0);
EdtNew.Text := '';
EdtRenew.Text := '';
EdtNew.SetFocus;
Exit
end;
NewPassword := UpperCase(TCommonUtil.Md5(EdtNew.Text));
SQL.Clear;
SQL.Add('update 用户信息 set 密码=:newpass where 用户名=:user');
Parameters.ParamByName('newpass').Value := NewPassword;
Parameters.ParamByName('user').Value := MainForm.CurrentUser;
ExecSQL;
MessageDlg('密码修改成功', mtInformation, [mbOK], 0);
Self.Close
end
end;
end.
|
unit cController;
interface
uses
API_DB,
API_MVC_VCLDB,
eMediaFile,
eVideoMovie,
mDefineMediaFiles,
mGetSearchResPics,
mKinopoiskParser;
type
TController = class(TControllerVCLDB)
private
FEditableLibList: TMediaLibList;
FMediaFileList: TMediaFileList;
FMovieList: TVideoList;
procedure InitDB(var aDBEngineClass: TDBEngineClass; out aConnectParams: TConnectParams;
out aConnectOnCreate: Boolean); override;
protected
procedure AfterCreate; override;
procedure BeforeDestroy; override;
published
procedure AddFiles;
procedure AssignKPSource;
procedure EditMovie;
procedure GetSearchResultPics;
procedure GetSearchResults;
procedure OnCaptchaRequest(aModel: TModelKPSearchParser);
procedure OnMediaFileAdded(aModel: TModelDefineMediaFiles);
procedure OnModelDefineMediaFilesDone(aModel: TModelDefineMediaFiles);
procedure OnModelDefineMediaFilesInit(aModel: TModelDefineMediaFiles);
procedure OnModelGetSearchResPicsInit(aModel: TModelGetSearchResPics);
procedure OnModelKPMovieParserDone(aModel: TModelKPMovieParser);
procedure OnModelKPMovieParserInit(aModel: TModelKPMovieParser);
procedure OnModelKPSearchParserDone(aModel: TModelKPSearchParser);
procedure OnModelKPSearchParserInit(aModel: TModelKPSearchParser);
procedure OnSearchResPicLoaded(aModel: TModelGetSearchResPics);
procedure OnViewEditClosed;
procedure PerformCaptchaReplay;
procedure PullFiles;
procedure PullMovieList;
procedure ServiceDB;
procedure SwitchDB;
procedure Test;
end;
var
DBEngine: TDBEngine;
implementation
uses
API_DB_SQLite,
eAudioAlbum,
eAudioArtist,
eAudioFile,
eAudioTrack,
eExtLink,
eVideoFile,
mMoveFiles,
System.Classes,
System.SysUtils,
Vcl.Controls,
vCaptchaInput,
vEdit,
vMain;
procedure TController.ServiceDB;
begin
DBEngine.ExecSQL('delete from video_movies');
DBEngine.ExecSQL('delete from video_genres');
(DBEngine as TSQLiteEngine).Service([soVacuum, soClearSeq]);
end;
procedure TController.SwitchDB;
begin
if Assigned(DBEngine) then
begin
DBEngine.CloseConnection;
DBEngine.Free;
end;
if ViewMain.DBAliasName = 'local_test' then
FConnectParams.DataBase := 'D:\Git\SmartMediaLib\DB\local_test.db'
else
if ViewMain.DBAliasName = 'local_real' then
FConnectParams.DataBase := 'D:\Git\SmartMediaLib\DB\local_real.db';
DBEngine := CreateDBEngine;
AfterCreate;
PullMovieList;
end;
procedure TController.PerformCaptchaReplay;
var
Model: TModelKPSearchParser;
begin
Model := GetRunningModel<TModelKPSearchParser>(0);
Model.PerformCaptchaReplay(ViewCaptchaInput.CaptchaRep);
end;
procedure TController.OnCaptchaRequest(aModel: TModelKPSearchParser);
begin
ViewCaptchaInput := VCL.CreateView<TViewCaptchaInput>;
ViewCaptchaInput.RenderCaptchaPic(aModel.outCaptchaPicData);
if ViewCaptchaInput.ShowModal = mrOK then
begin
end;
end;
procedure TController.AssignKPSource;
begin
CallModel<TModelKPMovieParser>;
end;
procedure TController.OnModelKPSearchParserDone(aModel: TModelKPSearchParser);
begin
TThread.Synchronize(nil, procedure()
begin
ViewEdit.RenderSearchRes(aModel.outSearchResultArr);
end
);
end;
procedure TController.GetSearchResults;
begin
CallModel<TModelKPSearchParser>;
end;
procedure TController.OnSearchResPicLoaded(aModel: TModelGetSearchResPics);
begin
ViewEdit.RenderSearchResPic(aModel.outPicData, aModel.outSearchResID);
end;
procedure TController.OnModelGetSearchResPicsInit(aModel: TModelGetSearchResPics);
begin
aModel.inSearchArr := ViewEdit.SelectedSearchResArr;
end;
procedure TController.GetSearchResultPics;
begin
CallModel<TModelGetSearchResPics>;
end;
procedure TController.OnViewEditClosed;
begin
StopModel<TModelDefineMediaFiles>;
end;
procedure TController.OnModelDefineMediaFilesDone(aModel: TModelDefineMediaFiles);
begin
FEditableLibList := aModel.outLibList;
FMediaFileList := aModel.outMediaFileList;
end;
procedure TController.OnModelKPSearchParserInit(aModel: TModelKPSearchParser);
begin
aModel.inSearchString := ViewEdit.SelectedMovie.Title;
aModel.inAltSearchString := ViewEdit.SelectedMovie.TitleOrig;
aModel.inPageNum := 1;
aModel.inCookiesPath := GetCurrentDir + '\Cookies\cookies.txt';
end;
procedure TController.OnMediaFileAdded(aModel: TModelDefineMediaFiles);
begin
ViewEdit.RenderMediaFile(aModel.outMediaFile);
end;
procedure TController.OnModelDefineMediaFilesInit(aModel: TModelDefineMediaFiles);
begin
aModel.inFileArr := ViewMain.Files;
aModel.inCookiesPath := GetCurrentDir + '\Cookies\cookies.txt';
end;
procedure TController.PullFiles;
begin
CallModel<TModelDefineMediaFiles>;
end;
procedure TController.AddFiles;
var
VideoReleaseTypeList: TVideoReleaseTypeList;
begin
VideoReleaseTypeList := TVideoReleaseTypeList.Create(['*'], ['NAME']);
ViewEdit := VCL.CreateView<TViewEdit>;
ViewEdit.RenderVideoReleaseTypes(VideoReleaseTypeList);
try
if ViewEdit.ShowModal = mrOK then
begin
FEditableLibList.VideoList.Store;
FMediaFileList.PrepareMoveAction;
end;
finally
VideoReleaseTypeList.Free;
FEditableLibList.Free;
FMediaFileList.Free;
end;
CallModel<TModelMoveFiles>;
end;
procedure TController.EditMovie;
begin
ViewEdit := VCL.CreateView<TViewEdit>;
ViewEdit.ShowModal;
end;
procedure TController.BeforeDestroy;
begin
FMovieList.Free;
end;
procedure TController.OnModelKPMovieParserDone(aModel: TModelKPMovieParser);
var
Movie: TMovie;
MovieExtLink: TMovieExtLink;
sGenre: string;
begin
Movie := ViewEdit.SelectedMovie;
Movie.Title := aModel.outTitle;
Movie.TitleOrig := aModel.outTitleOrig;
Movie.Year := aModel.outYear;
Movie.Storyline := aModel.outStoryline;
for sGenre in aModel.outGenreArr do
Movie.GenreRels.AddGenre(sGenre);
MovieExtLink := TMovieExtLink.Create;
MovieExtLink.ExtLink.ExtSourceID := 1;
MovieExtLink.ExtLink.Link := ViewEdit.SelectedSearchResult.Link;
Movie.ExtLinks.Add(MovieExtLink);
end;
procedure TController.OnModelKPMovieParserInit(aModel: TModelKPMovieParser);
begin
aModel.inURL := ViewEdit.SelectedSearchResult.Link;
end;
procedure TController.PullMovieList;
begin
ViewMain.RenderMovieList(FMovieList);
end;
procedure TController.Test;
begin
CallModel<TModelMoveFiles>;
end;
procedure TController.AfterCreate;
begin
cController.DBEngine := Self.DBEngine;
if Assigned(FMovieList) then
FMovieList.Free;
FMovieList := TVideoList.Create(['*'], ['TITLE']);
end;
procedure TController.InitDB(var aDBEngineClass: TDBEngineClass; out aConnectParams: TConnectParams;
out aConnectOnCreate: Boolean);
begin
aDBEngineClass := TSQLiteEngine;
aConnectOnCreate := True;
aConnectParams.DataBase := 'D:\Git\SmartMediaLib\DB\local_test.db';
end;
end.
|
unit sDialogs;
{$I sDefs.inc}
interface
uses
Windows, Dialogs, Forms, Classes, SysUtils, Graphics, ExtDlgs, Controls, sConst, FileCtrl
{$IFDEF TNTUNICODE} ,TntDialogs, TntExtDlgs, TntFileCtrl, MultiMon {$ENDIF};
type
{$IFNDEF NOTFORHELP}
TsZipShowing = (zsAsFolder, zsAsFile);
{$ENDIF} // NOTFORHELP
{ TsOpenDialog }
{$IFDEF TNTUNICODE}
TsOpenDialog = class(TTntOpenDialog)
{$else}
TsOpenDialog = class(TOpenDialog)
{$ENDIF}
private
FZipShowing: TsZipShowing;
{$IFNDEF NOTFORHELP}
public
constructor Create(AOwner: TComponent); override;
{$ENDIF} // NOTFORHELP
published
property ZipShowing: TsZipShowing read FZipShowing write FZipShowing default zsAsFolder;
end;
{ TsOpenPictureDialog }
{$IFDEF TNTUNICODE}
TsOpenPictureDialog = class(TTntOpenPictureDialog)
{$else}
TsOpenPictureDialog = class(TOpenPictureDialog)
{$ENDIF}
{$IFNDEF NOTFORHELP}
private
FPicture: TPicture;
function IsFilterStored: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoSelectionChange; override;
procedure DoShow; override;
published
property Filter stored IsFilterStored;
{$ENDIF} // NOTFORHELP
end;
{ TsSaveDialog }
{$IFDEF TNTUNICODE}
TsSaveDialog = class(TTntSaveDialog)
{$else}
TsSaveDialog = class(TSaveDialog)
{$ENDIF}
{$IFNDEF NOTFORHELP}
public
{$ENDIF} // NOTFORHELP
end;
{ TsSavePictureDialog }
{$IFDEF TNTUNICODE}
TsSavePictureDialog = class(TTntSavePictureDialog)
{$else}
TsSavePictureDialog = class(TSavePictureDialog)
{$ENDIF}
{$IFNDEF NOTFORHELP}
private
FPicture: TPicture;
function IsFilterStored: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Filter stored IsFilterStored;
{$ENDIF} // NOTFORHELP
end;
TsColorDialog = class(TColorDialog)
{$IFNDEF NOTFORHELP}
private
FMainColors: TStrings;
FStandardDlg : boolean;
procedure SetMainColors(const Value: TStrings);
public
function Execute: Boolean; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoShow; override;
procedure DoClose; override;
published
property Options default [cdFullOpen];
{$ENDIF} // NOTFORHELP
property MainColors: TStrings read FMainColors write SetMainColors;
property StandardDlg : boolean read FStandardDlg write FStandardDlg default False;
end;
TsPathDialog = class(TComponent)
{$IFNDEF NOTFORHELP}
private
FPath: TsDirectory;
FRoot: TacRoot;
FCaption: acString;
FNoChangeDir: Boolean;
FShowRootBtns: Boolean;
FOptions: TSelectDirOpts;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{$ENDIF} // NOTFORHELP
function Execute: Boolean;
published
property Path : TsDirectory read FPath write FPath;
property Root : TacRoot read FRoot write FRoot;
property Caption : acString read FCaption write FCaption;
property NoChangeDir : Boolean read FNoChangeDir write FNoChangeDir default False;
property ShowRootBtns : boolean read FShowRootBtns write FShowRootBtns default False;
{$IFNDEF NOTFORHELP}
property DialogOptions: TSelectDirOpts read FOptions write FOptions default [sdAllowCreate, sdPerformCreate, sdPrompt];
{$ENDIF} // NOTFORHELP
end;
{$IFNDEF NOTFORHELP}
{ Message dialog }
function sCreateMessageDialog(const Title, Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons): TForm;
{$ENDIF} // NOTFORHELP
// Overloaded versions added RS 31/10/05 to allow title and message
function sMessageDlg(const Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt): Integer; overload;
function sMessageDlg(const Title, Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt): Integer; overload;
function sMessageDlgPos(const Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt; X, Y: Integer): Integer; overload;
function sMessageDlgPos(const Title, Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt; X, Y: Integer): Integer; overload;
function sMessageDlgPosHelp(const Title, Msg: acString; DlgType: TMsgDlgType; Buttons:
TMsgDlgButtons; HelpCtx: LongInt; X, Y: Integer; const HelpFileName: acString): Integer;
procedure sShowMessage(const Msg: acString); overload;
procedure sShowMessage(const Title, Msg: acString); overload;
procedure sShowMessageFmt(const Msg: acString; const Params: array of const); overload;
procedure sShowMessageFmt(const Title, Msg: acString; const Params: array of const); overload;
procedure sShowMessagePos(const Msg: acString; X, Y: Integer); overload;
procedure sShowMessagePos(const Title, Msg: acString; X, Y: Integer); overload;
{ Input dialog }
function sInputBox(const ACaption, APrompt, ADefault: acString): acString;
function sInputQuery(const ACaption, APrompt: acString; var Value: acString): Boolean;
{$IFDEF TNTUNICODE}
function Application_MessageBoxW(const Text, Caption: PWideChar; Flags: Longint): Integer;
{$ENDIF}
implementation
uses
Consts, sColorDialog, acPathDialog, acShellCtrls, sSkinManager, ShlObj, acDials,
acntUtils;
var
{.$IFNDEF D2006
Captions: array[TMsgDlgType] of Pointer = (@SMsgDlgWarning, @SMsgDlgError, @SMsgDlgInformation, @SMsgDlgConfirm, nil);
$ELSE}
Captions: array[TMsgDlgType] of acString = ('Warning', 'Error', 'Information', 'Confirm', '');
{.$ENDIF}
function sCreateMessageDialog(const Title, Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons): TForm;
begin
{$IFDEF TNTUNICODE}
Result := WideCreateMessageDialog(Msg, DlgType, Buttons);
{$else}
Result := CreateMessageDialog(Msg, DlgType, Buttons);
{$ENDIF}
end;
function sMessageDlg(const Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt): Integer;
begin
Result := sMessageDlgPosHelp('', Msg, DlgType, Buttons, HelpCtx, -1, -1, '');
end;
function sMessageDlg(const Title, Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt): Integer;
begin
Result := sMessageDlgPosHelp(Title, Msg, DlgType, Buttons, HelpCtx, -1, -1, '');
end;
function sMessageDlgPos(const Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt; X, Y: Integer): Integer;
begin
Result := sMessageDlgPosHelp('', Msg, DlgType, Buttons, HelpCtx, X, Y, '');
end;
function sMessageDlgPos(const Title, Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt; X, Y: Integer): Integer;
begin
Result := sMessageDlgPosHelp(Title, Msg, DlgType, Buttons, HelpCtx, X, Y, '');
end;
{$IFDEF TNTUNICODE}
function Application_MessageBoxW(const Text, Caption: PWideChar; Flags: Longint): Integer;
var
ActiveWindow, TaskActiveWindow: HWnd;
WindowList: Pointer;
MBMonitor, AppMonitor: HMonitor;
MonInfo: TMonitorInfo;
Rect: TRect;
FocusState: TFocusState;
begin
with Application do begin
{$IFDEF D2006}
ActiveWindow := ActiveFormHandle;
{$ELSE}
ActiveWindow := GetActiveWindow;
{$ENDIF}
if ActiveWindow = 0 then
TaskActiveWindow := Handle
else
TaskActiveWindow := ActiveWindow;
MBMonitor := MonitorFromWindow(ActiveWindow, MONITOR_DEFAULTTONEAREST);
AppMonitor := MonitorFromWindow(Handle, MONITOR_DEFAULTTONEAREST);
if MBMonitor <> AppMonitor then
begin
MonInfo.cbSize := Sizeof(TMonitorInfo);
GetMonitorInfo(MBMonitor, @MonInfo);
GetWindowRect(Handle, Rect);
SetWindowPos(Handle, 0,
MonInfo.rcMonitor.Left + ((MonInfo.rcMonitor.Right - MonInfo.rcMonitor.Left) div 2),
MonInfo.rcMonitor.Top + ((MonInfo.rcMonitor.Bottom - MonInfo.rcMonitor.Top) div 2),
0, 0, SWP_NOACTIVATE or SWP_NOREDRAW or SWP_NOSIZE or SWP_NOZORDER);
end;
WindowList := DisableTaskWindows(ActiveWindow);
FocusState := SaveFocusState;
if UseRightToLeftReading then Flags := Flags or MB_RTLREADING;
try
{$IFDEF DELPHI7UP}
Application.ModalStarted;
{$ENDIF}
Result := MessageBoxW(TaskActiveWindow, Text, Caption, Flags);
{$IFDEF DELPHI7UP}
Application.ModalFinished;
{$ENDIF}
finally
if MBMonitor <> AppMonitor then
SetWindowPos(Handle, 0,
Rect.Left + ((Rect.Right - Rect.Left) div 2),
Rect.Top + ((Rect.Bottom - Rect.Top) div 2),
0, 0, SWP_NOACTIVATE or SWP_NOREDRAW or SWP_NOSIZE or SWP_NOZORDER);
EnableTaskWindows(WindowList);
SetActiveWindow(ActiveWindow);
RestoreFocusState(FocusState);
end;
end;
end;
{$ENDIF}
procedure MsgBoxCallback(var lpHelpInfo: THelpInfo); stdcall;
begin
if lpHelpInfo.dwContextId <> 0 then Application.HelpContext(lpHelpInfo.dwContextId);
end;
function sMessageDlgPosHelp(const Title, Msg: acString; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: LongInt; X, Y: Integer; const HelpFileName: acString): Integer;
const
MB_HELP = $4000;
MB_YESTOALL = $A000;
var
Flags : Cardinal;
Caption : acString;
{$IFDEF TNTUNICODE}
mParams : TMsgBoxParamsW;
{$ELSE}
mParams : TMsgBoxParams;
{$ENDIF}
begin
case DlgType of
mtWarning : Flags := MB_ICONWARNING;
mtError : Flags := MB_ICONERROR;
mtInformation : Flags := MB_ICONINFORMATION;
mtConfirmation : Flags := MB_ICONQUESTION
else Flags := 0;
end;
// Flags := Flags or MB_SYSTEMMODAL;
if Title = '' then Caption := Captions[DlgType] else Caption := Title;
if mbOk in Buttons then begin
if mbCancel in Buttons then Flags := Flags or MB_OKCANCEL else Flags := Flags or MB_OK;
end
else if (mbAbort in Buttons) or (mbIgnore in Buttons) then Flags := Flags or MB_ABORTRETRYIGNORE
else if (mbYes in Buttons) or (mbNo in Buttons) then begin
if mbCancel in Buttons then Flags := Flags or MB_YESNOCANCEL else Flags := Flags or MB_YESNO;
end
else if mbRetry in Buttons then Flags := Flags or MB_RETRYCANCEL;
if mbHelp in Buttons then Flags := Flags or MB_HELP;
DlgLeft := X; DlgTop := Y;
{$IFDEF DELPHI7UP}
Application.ModalStarted;
{$ENDIF}
FillChar(mParams, SizeOf(mParams), 0);
mParams.cbSize := SizeOf(mParams);
mParams.dwContextHelpId := HelpCtx;
mParams.dwStyle := Flags;
mParams.lpszCaption := PacChar(Caption);
mParams.lpszText := PacChar(Msg);
mParams.hwndOwner := Application.Handle;
{$T-}
mParams.lpfnMsgBoxCallback := @MsgBoxCallback;
{$T+}
{$IFDEF TNTUNICODE}
Result := integer(MessageBoxIndirectW(mParams));
{$ELSE}
Result := integer(MessageBoxIndirect(mParams));
{$ENDIF}
(*
if GetActiveWindow = 0 then begin // Application will not be set foreground if haven't actve window still
{$IFDEF TNTUNICODE}
Result := MessageBoxW(Application.Handle, PWideChar(Msg), PWideChar(Caption), Flags);
{$ELSE}
Result := MessageBox(Application.Handle, PacChar(Msg), PacChar(Caption), Flags);
{$ENDIF}
end
else begin
{$IFDEF TNTUNICODE}
Result := Application_MessageBoxW(PWideChar(Msg), PWideChar(Caption), Flags);
{$ELSE}
Result := Application.MessageBox(PacChar(Msg), PacChar(Caption), Flags);
{$ENDIF}
end;
*)
{$IFDEF DELPHI7UP}
Application.ModalFinished;
{$ENDIF}
DlgLeft := -1; DlgTop := -1;
end;
procedure sShowMessage(const Msg: acString);
begin
sShowMessagePos(Msg, -1, -1);
end;
procedure sShowMessage(const Title, Msg: acString);
begin
sShowMessagePos(Title, Msg, -1, -1);
end;
procedure sShowMessageFmt(const Msg: acString; const Params: array of const);
begin
sShowMessage(Format(Msg, Params));
end;
procedure sShowMessageFmt(const Title, Msg: acString; const Params: array of const);
begin
sShowMessage(Title, Format(Msg, Params));
end;
procedure sShowMessagePos(const Msg: acString; X, Y: Integer);
begin
sMessageDlgPos(Msg, mtCustom, [mbOK], 0, X, Y);
end;
procedure sShowMessagePos(const Title, Msg: acString; X, Y: Integer);
begin
sMessageDlgPos(Title, Msg, mtCustom, [mbOK], 0, X, Y);
end;
{ Input dialog }
function sInputQuery(const ACaption, APrompt: acString; var Value: acString): Boolean;
begin
{$IFDEF TNTUNICODE}
Result := WideInputQuery(ACaption, APrompt, Value);
{$ELSE}
Result := InputQuery(ACaption, APrompt, Value);
{$ENDIF}
end;
function sInputBox(const ACaption, APrompt, ADefault: acString): acString;
begin
Result := ADefault;
sInputQuery(ACaption, APrompt, Result);
end;
{ TsOpenDialog }
constructor TsOpenDialog.Create(AOwner: TComponent);
begin
inherited;
FZipShowing := zsAsFolder;
end;
{ TsOpenPictureDialog }
constructor TsOpenPictureDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Filter := GraphicFilter(TGraphic);
end;
destructor TsOpenPictureDialog.Destroy;
begin
if Assigned(FPicture) then FreeAndNil(FPicture);
inherited;
end;
procedure TsOpenPictureDialog.DoSelectionChange;
begin
if csDestroying in ComponentState then Exit;
inherited DoSelectionChange;
end;
procedure TsOpenPictureDialog.DoShow;
begin
inherited DoShow;
end;
function TsOpenPictureDialog.IsFilterStored: Boolean;
begin
Result := not (Filter = GraphicFilter(TGraphic));
end;
{ TsSavePictureDialog }
constructor TsSavePictureDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Filter := GraphicFilter(TGraphic);
end;
destructor TsSavePictureDialog.Destroy;
begin
if Assigned(FPicture) then FreeAndNil(FPicture);
inherited;
end;
function TsSavePictureDialog.IsFilterStored: Boolean;
begin
Result := not (Filter = GraphicFilter(TGraphic));
end;
{ TsColorDialog }
constructor TsColorDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMainColors := TStringList.Create;
FStandardDlg := False;
Options := [cdFullOpen];
end;
destructor TsColorDialog.Destroy;
begin
FreeAndNil(FMainColors);
inherited Destroy;
end;
procedure TsColorDialog.DoClose;
begin
inherited;
end;
procedure TsColorDialog.DoShow;
begin
inherited;
end;
function TsColorDialog.Execute: Boolean;
const
MaxWidth = 545;
MinWidth = 235;
begin
if not FStandardDlg and Assigned(DefaultManager) then begin
sColorDialogForm := TsColorDialogForm.Create(Application);
sColorDialogForm.InitLngCaptions;
sColorDialogForm.Owner := Self;
if CustomColors.Count > 0 then begin
sColorDialogForm.AddPal.Colors.Assign(CustomColors);
sColorDialogForm.AddPal.GenerateColors;
end;
if MainColors.Count > 0 then begin
sColorDialogForm.MainPal.Colors.Assign(MainColors);
sColorDialogForm.MainPal.GenerateColors;
end;
sColorDialogForm.ModalResult := mrCancel;
sColorDialogForm.BorderStyle := bsSingle;
sColorDialogForm.sBitBtn4.Enabled := not (cdFullOpen in Options);
if sColorDialogForm.sBitBtn4.Enabled then sColorDialogForm.Width := MinWidth else sColorDialogForm.Width := MaxWidth;
if (cdPreventFullOpen in Options) then
sColorDialogForm.sBitBtn4.Enabled := False;
sColorDialogForm.sBitBtn5.Visible := (cdShowHelp in Options);
sColorDialogForm.sSkinProvider1.PrepareForm;
sColorDialogForm.SelectedPanel.Brush.Color := Color;
sColorDialogForm.ShowModal;
Result := sColorDialogForm.ModalResult = mrOk;
CustomColors.Assign(sColorDialogForm.AddPal.Colors);
DoClose;
if Result then Color := sColorDialogForm.SelectedPanel.Brush.Color;
if sColorDialogForm <> nil then sColorDialogForm.Free;
end
else Result := inherited Execute;
end;
procedure TsColorDialog.SetMainColors(const Value: TStrings);
begin
FMainColors.Assign(Value);
end;
{ TsPathDialog }
constructor TsPathDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FRoot := SRFDesktop;
FNoChangeDir := False;
FShowRootBtns := False;
FOptions := [sdAllowCreate, sdPerformCreate, sdPrompt];
end;
destructor TsPathDialog.Destroy;
begin
inherited;
end;
function TsPathDialog.Execute: Boolean;
var
s: acString;
bw : integer;
begin
Result := False;
s := Path;
if not acDirExists(s) or (s = '.') then s := '';
if not NoChangeDir and (s <> '') then acSetCurrentDir(s);
PathDialogForm := TPathDialogForm.Create(Application);
PathDialogForm.InitLngCaptions;
PathDialogForm.sBitBtn3.Visible := sdAllowCreate in DialogOptions;
if ShowRootBtns then begin
PathDialogForm.sScrollBox1.Visible := True;
PathDialogForm.sLabel1.Visible := True;
bw := GetSystemMetrics(SM_CXSIZEFRAME);
PathDialogForm.sShellTreeView1.Left := PathDialogForm.sShellTreeView1.Left + PathDialogForm.sScrollBox1.Width + 4;
PathDialogForm.sBitBtn1.Left := PathDialogForm.sBitBtn1.Left + PathDialogForm.sScrollBox1.Width + 4;
PathDialogForm.sBitBtn2.Left := PathDialogForm.sBitBtn2.Left + PathDialogForm.sScrollBox1.Width + 4;
PathDialogForm.Width := PathDialogForm.Width + PathDialogForm.sScrollBox1.Width + 4 + bw;
PathDialogForm.GenerateButtons;
end
else begin
PathDialogForm.sScrollBox1.Visible := False;
PathDialogForm.sLabel1.Visible := False;
end;
PathDialogForm.UpdateAnchors;
try
PathDialogForm.sShellTreeView1.BoundLabel.Caption := Caption;
PathDialogForm.sShellTreeView1.Root := FRoot;
if (s = '') then begin
if PathDialogForm.sShellTreeView1.Items.Count > 0 then PathDialogForm.sShellTreeView1.Items[0].Selected := True;
end
else begin
PathDialogForm.sShellTreeView1.Path := s;
end;
if PathDialogForm.ShowModal = mrOk then begin
s := PathDialogForm.sShellTreeView1.Path;
if (s <> '') and acDirExists(s) then Path := s;
Result := True
end;
finally
FreeAndNil(PathDialogForm);
end;
end;
end.
|
program RecursiveFibonacci;
var
i: integer;
function fibonacci(n: integer): integer;
begin
if n = 1 then
fibonacci := 0
else if n = 2 then
fibonacci := 1
else
fibonacci := fibonacci(n - 1) + fibonacci(n - 2);
end;
begin
for i := 1 to 10 do
write(fibonacci(i), ' ');
end. |
unit FormatterUnit;
interface
uses
MacOSAll, HashTableUnit;
function PascalFormatter(teRec: AnsiString): AnsiString;
function PascalCRFormatter(teRec: AnsiString):AnsiString;
implementation
// Hash tables for color coding
var
pascalHashTable: HashRec;
const
kFunctionToken = 1; // function, procedure
kBeginEndToken = 2; // begin/end/if/else/case/of - anything that affects structure)
kReservedToken = 3; // Reserved words that do NOT affect structure analysis
kKnownTypeToken = 4; // Integer, Longint, Real...
kCommentToken = 5; // {} (* *) // Can span several rows!
kStringToken = 6; // 'string' "c"
kSpecialToken = 7; // ( ) * / + - etc
kSingleCharToken = 8; // Any unknown token (identifiers etc)
kOtherToken = 9; // Any unknown token (identifiers etc)
kPreprocessorToken = 10;// For the C parser
kStartParenToken = 11; // For the C parser
kEndParenToken = 12; // For the Java parser
kClassToken = 13; // For the Java parser
kLibraryToken = 14; // For Library functions
kCarbonToken = 15; // For Apple Carbon functions
kCocoaToken = 16; // For Apple Cocoa functions
kCompilerDirectiveToken = 17; // For compiler directives
kCRLFToken = 18; // At this time only used in code formatter
//For PascalCRFormatter
kBeginToken =19; // begin, else, var, type, const
kFunctionModifier = 20; // override, overload, cdecl, register, message
kCRafterTV =21; // then, try, repeat, except, finally, do, of, record, uses
//For PascalFormatter
kRecordToken = 22; // record, class, begin
kUntilToken = 23; //end, end., until
kCaseToken = 24; // case, try, repeat
kForToken = 25; //for, with, while
kIfElseToken = 26; //if, else
kVarToken = 27; // var, type, const
kImplementationToken =28; //Implementation
const
CR = Char(13);
LF = Char(10);
TAB = Char(9);
{------------------------ PASCAL COLOR CODER ----------------------------}
procedure InitColorCodingTable;
begin
HashAddEntry(pascalHashTable, 'begin', kBeginToken);
HashAddEntry(pascalHashTable, 'else', kBeginToken);
HashAddEntry(pascalHashTable, 'var', kBeginToken);
HashAddEntry(pascalHashTable, 'type', kBeginToken);
HashAddEntry(pascalHashTable, 'const', kBeginToken);
HashAddEntry(pascalHashTable, 'override', kFunctionModifier);
HashAddEntry(pascalHashTable, 'overload', kFunctionModifier);
HashAddEntry(pascalHashTable, 'cdecl', kFunctionModifier);
HashAddEntry(pascalHashTable, 'register', kFunctionModifier);
HashAddEntry(pascalHashTable, 'message', kFunctionModifier);
HashAddEntry(pascalHashTable, 'then', kCRafterTV);
HashAddEntry(pascalHashTable, 'try', kCRafterTV);
HashAddEntry(pascalHashTable, 'repeat', kCRafterTV);
HashAddEntry(pascalHashTable, 'except', kCRafterTV);
HashAddEntry(pascalHashTable, 'finally', kCRafterTV);
HashAddEntry(pascalHashTable, 'do', kCRafterTV);
HashAddEntry(pascalHashTable, 'of', kCRafterTV);
HashAddEntry(pascalHashTable, 'record', kCRafterTV);
HashAddEntry(pascalHashTable, 'uses', kCRafterTV);
HashAddEntry(pascalHashTable, 'program', kReservedToken);
HashAddEntry(pascalHashTable, 'library', kReservedToken); // 110311
HashAddEntry(pascalHashTable, 'exports', kReservedToken); // 110311
HashAddEntry(pascalHashTable, 'array', kReservedToken);
HashAddEntry(pascalHashTable, 'unit', kReservedToken);
HashAddEntry(pascalHashTable, 'interface', kReservedToken);
HashAddEntry(pascalHashTable, 'implementation', kReservedToken);
HashAddEntry(pascalHashTable, 'initialization', kReservedToken); // Ingemar 090629
HashAddEntry(pascalHashTable, 'finalization', kReservedToken); // Ingemar 110424
HashAddEntry(pascalHashTable, 'const', kReservedToken);
HashAddEntry(pascalHashTable, 'type', kReservedToken);
HashAddEntry(pascalHashTable, 'var', kReservedToken);
HashAddEntry(pascalHashTable, 'record', kReservedToken);
HashAddEntry(pascalHashTable, 'object', kReservedToken);
HashAddEntry(pascalHashTable, 'uses', kReservedToken);
HashAddEntry(pascalHashTable, 'of', kReservedToken);
HashAddEntry(pascalHashTable, 'set', kReservedToken);
HashAddEntry(pascalHashTable, 'variant', kReservedToken);
HashAddEntry(pascalHashTable, 'packed', kReservedToken);
HashAddEntry(pascalHashTable, 'overload', kReservedToken);
HashAddEntry(pascalHashTable, 'class', kClassToken);
HashAddEntry(pascalHashTable, 'objcclass', kClassToken);
HashAddEntry(pascalHashTable, 'procedure', kFunctionToken);
HashAddEntry(pascalHashTable, 'function', kFunctionToken);
HashAddEntry(pascalHashTable, 'operator', kFunctionToken); // 110314
HashAddEntry(pascalHashTable, 'constructor', kFunctionToken);
HashAddEntry(pascalHashTable, 'destructor', kFunctionToken);
HashAddEntry(pascalHashTable, 'begin', kBeginEndToken);
HashAddEntry(pascalHashTable, 'end', kBeginEndToken);
HashAddEntry(pascalHashTable, 'end.', kBeginEndToken);
HashAddEntry(pascalHashTable, 'if', kBeginEndToken);
HashAddEntry(pascalHashTable, 'then', kBeginEndToken);
HashAddEntry(pascalHashTable, 'else', kBeginEndToken);
HashAddEntry(pascalHashTable, 'case', kBeginEndToken);
HashAddEntry(pascalHashTable, 'otherwise', kBeginEndToken);
HashAddEntry(pascalHashTable, 'with', kBeginEndToken);
HashAddEntry(pascalHashTable, 'downto', kBeginEndToken);
HashAddEntry(pascalHashTable, 'for', kBeginEndToken);
HashAddEntry(pascalHashTable, 'to', kBeginEndToken);
HashAddEntry(pascalHashTable, 'do', kBeginEndToken);
HashAddEntry(pascalHashTable, 'while', kBeginEndToken);
HashAddEntry(pascalHashTable, 'repeat', kBeginEndToken);
HashAddEntry(pascalHashTable, 'until', kBeginEndToken);
HashAddEntry(pascalHashTable, 'goto', kBeginEndToken);
HashAddEntry(pascalHashTable, 'try', kBeginEndToken); // Ingemar 090629
HashAddEntry(pascalHashTable, 'except', kBeginEndToken); // Ingemar 090629
end;
var
previousTokenType: Longint; {Ett steg tillbaka}
previousTokenValue: AnsiString;
lastpreviousTokenValue:AnsiString;
changePreviousTokenValue: Boolean;
type formatterSnapshot = record
pos: LongInt;
end;
procedure GetFormatToken(data: AnsiString; {bufferLength: Longint;} var pos, tokenStart, tokenEnd, tokenType: Longint; var tokenValue: AnsiString);
var
s: ansistring;
bufferLength: Longint;
begin
// MSTE G
RAS OM!
// Reagera p CRLF som egen token.
// Egen hash med formatspecifika saker; begin end var const type record...
// Kommentarparsern mste vara kvar! ven strngparsern. Drmed nstan samma!
bufferLength:= Length(data);
if changePreviousTokenValue then
begin
previousTokenValue:= lastPreviousTokenValue;;
changePreviousTokenValue:=false;
end
else
previousTokenValue:= tokenValue;
previousTokenType:= tokenType;
while (data[pos] in [TAB, ' ']) and (pos < bufferLength) do pos := pos + 1;
tokenStart := pos;
if data[pos] in ['a'..'z', 'A'..'Z', '0'..'9', '_'] then
begin
{Change 070326: Added '.' so Object Pascal code will get methods nicely listed in the function menu}
while (data[pos] in ['a'..'z', 'A'..'Z', '0'..'9', '_', '.']) and (pos < bufferLength) do pos := pos + 1;
tokenEnd := pos - 1;
{Find out what alphanumerical symbol it is by looking it up in the hash table!}
//SetLength(s, pos - tokenStart);
//BlockMove(@data[tokenStart], @s[1], pos - tokenStart); // MoveBytes - should be a Copy
//s:= Copy(data, 1, tokenStart-1);
s := Copy(data, tokenStart, pos - tokenStart);
s := LowerCase(s);
tokenType := HashLookUpInteger(pascalHashTable, s);
tokenValue := s;
//Writeln('s: ', s);
end
else
begin {strings, comments, compiler directives, math operators, brackets, & other singletons }
if data[pos] in [CR, LF] then
begin
// WriteLn('CRLF token');
// Jag vill bara ha den SISTA - flera i rad r ointressanta
while (data[pos] in [CR, LF]) and (pos < bufferLength) do begin {Writeln('pos: ', pos, 'CR or LF: ', data[pos]);} pos := pos + 1; end;
tokenEnd := pos-1;
tokenType := kCRLFToken;
tokenValue := data[pos-1];
// pos := pos + 1;
end
else
if (data[pos] = '{') and (data[pos+1] = '$') then // compiler directive
begin
pos := pos + 2;
while (data[pos] <> '}') and (pos < bufferLength) do pos := pos + 1; //why is it here?
tokenEnd := pos;
pos := pos+1;
tokenType := kCompilerDirectiveToken;
//tokenValue:= '{$'
end
else
if data[pos] = '{' then // Bracket-comment
begin
while (data[pos] <> '}') and (pos < bufferLength) do pos := pos + 1;
pos := pos+1;
tokenEnd := pos-1;
tokenType := kCommentToken;
tokenValue:= 'Comment';
// pos := pos + 1; // Test, try to avoid the last character to be caught by someone else
// NOTE! This is most likely needed for other cases!
end
else
if (data[pos] = '/') and (data[pos+1] = '/') then // Line-comment
begin
while not (data[pos] in [CR, LF]) and (pos < bufferLength) do pos := pos + 1;
//pos:=pos+1;
tokenEnd := pos - 1;
tokenType := kCommentToken;
tokenValue:= 'Comment';
end
else
if (data[pos] = '(') and (data[pos+1] = '*') then // Block-comment
begin
pos := pos + 2;
while ((data[pos-1] <> '*') or (data[pos] <> ')')) and (pos < bufferLength) do pos := pos + 1;
pos := pos+1;
tokenEnd := pos-1;
tokenType := kCommentToken;
tokenValue:= 'Comment';
// pos := pos + 1; // Test, try to avoid the last character to be caught by someone else
// NOTE! This is most likely needed for other cases!
end
else
if (data[pos] = '''') then // String
begin
pos := pos + 1;
while not (data[pos] in ['''', CR, LF]) and (pos < bufferLength) do
pos := pos + 1;
tokenEnd := pos;
pos := pos + 1; // Skip '
tokenType := kStringToken;
// Should we set tokenValue here?
end
else
begin
// Otherwise skip the symbol
tokenEnd := tokenStart;
tokenType := kSingleCharToken;
tokenValue := data[pos]; // Ord(data[pos]);
pos := pos + 1;
//while not (dataPtr in ['a'..'z', 'A'..'Z', '0'..'9', '_', CR, LF, ' ']) do pos := pos + 1;
end;
end;
end;
var
waitingForSemicolon: array of Boolean;
waitingForCR: array of Boolean;
//elseFlag: Boolean;
ifWOBegin: array of Boolean;
elseWOBegin: array of Boolean;
elseWithBegin: array of Boolean;
loopWOBegin: array of Boolean;
function FormatIFElse(level : Longint):Boolean;
begin
FormatIFElse:= false;
if (ifWOBegin[level] xor (elseWOBegin[level] or elseWithBegin[level])) then
if not (elseWithBegin[level]) then
begin
FormatIFElse:= true;
end;
if loopWOBegin[level] then
FormatIFElse:= true;
end;
const
kDefaultFlagArraySize = 30;
kLevelMargin = 10;
// Make sure that level doesn't go out of bounds! Expand arrays if it goes up too far.
procedure CheckLevel(var level: Longint);
begin
if level < 0 then
level := 0
else
if level > High(waitingForSemicolon) - kLevelMargin then
begin
SetLength(waitingForSemicolon, Length(waitingForSemicolon)*2);
SetLength(waitingForCR, Length(waitingForCR)*2);
SetLength(ifWOBegin, Length(ifWOBegin)*2);
SetLength(elseWOBegin, Length(elseWOBegin)*2);
SetLength(elseWithBegin, Length(elseWithBegin)*2);
SetLength(loopWOBegin, Length(loopWOBegin)*2);
end;
end;
procedure IndentOnCRLF(var chars, caseChars: AnsiString; var bufferLength, pos: Longint; level: Longint);
//Replace bufferlength with length(chars)
var
pos1, diff: Longint;
tokenStart, tokenEnd, tokenType: Longint;
tokenValue: AnsiString;
begin
//WriteLn('Indent ', pos, ' to level ', level);
// Vad r nsta token?
pos1 := pos;
//diff:=0
GetFormatToken(chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
//If tokenValue='end' then tokenType:= 2;
if tokenType = kBeginEndToken then
begin
if (tokenValue = 'end') or (tokenValue = 'end.') or (tokenValue = 'until') or (tokenValue = 'except') or (tokenValue = 'finally')
{or (tokenValue = 'private') or (tokenValue = 'public')} then
begin
//writeln('Level down', level, ' in Indent due to ', tokenValue);
level-=1;
end;
if (tokenValue = 'else') then
begin
if elseWithBegin[level+1] then
begin
level-=1;
//writeln('IFELSE level down in IndentCRLF becoz of elseWithBegin and level ',level);
end;
end;
// level -= 1; // Local modification only - only if within one-line if!
// "except" och "finally" borde ha samma? else?
end;
//Writeln('LEVEL: ', level);
{for i:=0 to level do
begin
writeln('ifWOBegin ', i, ' ', ifWOBegin[i]);
writeln('elseWOBegin ', i, ' ', elseWOBegin[i]);
writeln('elseWithBegin ', i, ' ', elseWithBegin[i]);
writeln('loopWOBegin ', i, ' ', loopWOBegin[i]);
end;}
if level < 0 then
level := 0;
CheckLevel(level);
// Vad r nsta? Redan kollat, detta r CRFL som EJ fljs av CRLF
pos1 := pos;
//Writeln('tokenValue in IndentOnCRLF: ', tokenValue);
// Hitta slut p indentering
while (chars[pos1] in [' ', TAB]) and (pos1 < bufferLength) do pos1 := pos1 + 1;
diff := level - (pos1-pos);
//WriteLn('Diff at CRLF: ', diff, ' at level ', level);
if diff <= 0 then // mindre data - kopiera frst, korta sedan - take away uneccessary space/tab
begin
chars:= Copy(chars, 1, pos - 1)+ Copy(#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9, 1, level) + Copy(chars, pos1, bufferLength-pos1+1);
bufferLength += diff;
end;
if diff>0 then // mer data - lng frst, kopiera sedan - add more spaces/tabs
begin
chars:= Copy(chars, 1, pos-1) + Copy(#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9#9, 1, level) + Copy(chars, pos1, bufferLength-pos1+1);
bufferLength += (diff-1);
end;
bufferLength := Length(chars);
end;
procedure ResetFlags(var level:LongInt);
begin
ifWOBegin[level]:=false;
elseWOBegin[level]:=false;
loopWOBegin[level]:=false;
elseWithBegin[level+1]:=false;
end;
function PascalFormatter(teRec: AnsiString{HaldaPtr; editIndex: Integer}):AnsiString;
var
bufferLength: Longint;
//err: OSErr;
chars, caseChars: AnsiString;
pos, tokenStart, tokenEnd, tokenType: Longint;
tokenValue: AnsiString;
// hasSeenProgram, hasSeenUnit, hasSeenInterface, hasSeenImplementation: Boolean;
// secondPreviousTokenType: Longint; {Tv steg tillbaka}
// secondPreviousTokenValue: AnsiString;
level, pos1: Longint;
i: Longint;
// waitingForSemicolon: array of Boolean;
secondWaitForCR, pauseSecondWaitForCR: Boolean;
//predictElse: Boolean;
begin
// WriteLn('ENTER FORMATTER');
SetLength(waitingForSemicolon, kDefaultFlagArraySize);
SetLength(waitingForCR, kDefaultFlagArraySize);
SetLength(ifWOBegin, kDefaultFlagArraySize);
SetLength(elseWOBegin, kDefaultFlagArraySize);
SetLength(elseWithBegin, kDefaultFlagArraySize);
SetLength(loopWOBegin, kDefaultFlagArraySize);
//SetLength(offset, 20);
// SetLength(elseFlag, 20);
for i := 0 to High(waitingForSemicolon) do
begin
waitingForSemicolon[i] := false;
waitingForCR[i] := false;
ifWOBegin[i]:= false;
elseWOBegin[i]:= false;
elseWithBegin[i]:= false;
loopWOBegin[i]:= false;
//offset[i] := 0;
end;
secondWaitForCR:= false;
pauseSecondWaitForCR:=false;
//elseFlag := false;
// Get the text from the text field
chars := teRec;//^.text;
caseChars := chars;
// Change chars to lower case
LowerCase(chars);
bufferLength := Length(chars);
pos := 0;
level := 0;
repeat
GetFormatToken(chars, pos, tokenStart, tokenEnd, tokenType, tokenValue);
//Writeln('tV: ',tokenValue, ' tT: ', tokenType, ' pos: ', pos);
case tokenType of
kBeginEndToken: //kBeginEndToken=2
begin
if {(tokenType=kRecordToken )} (tokenValue = 'begin') or (tokenValue = 'record') or (tokenValue = 'class') {or (tokenValue = 'case')} then
begin
level += 1;
ResetFlags(level);
//writeln('Level Up: ', level, ' in kBiginToken due to: ', tokenValue);
end;
if {(tokenType = kUntilToken)} (tokenValue = 'end') or (tokenValue = 'end.') or (tokenValue = 'until') then
begin
level -= 1;
//writeln('Level down: ', level, ' in kBiginToken due to: ', tokenValue);
end;
if {(tokenType = kCaseToken)} (tokenValue = 'case') or (tokenValue = 'try') or (tokenValue = 'repeat') then // Anything that will lead to "end"
begin
level += 1;
ResetFlags(level);
end;
if {( (tokenType = kIfElseToken) or (tokenType = kForToken) )} (tokenValue = 'if') or (tokenValue = 'for') or (tokenValue = 'else') or (tokenValue = 'with') or (tokenValue = 'while') then // + "on"
// Dessa borde INTE indentera om det fljs av begin... men det lter jobbigt att parsa efter
begin
// Fr if, sk "then"
pos1 := pos;
if tokenValue = 'if' then
begin
//predictElse:=false;
//Parse until CR followed by 'then', Even user missed CR after 'then', CRFormatter adds CR after 'then'.
repeat
GetFormatToken({dataPtr} chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
//writeln('IN IF LOOP: ', 'tokenValue: ', tokenValue, ' pos1: ', pos1);
until (tokenType = kCRLFToken) or (pos1 >= bufferLength);
pos:=pos1-1;
// Sk frsta efter (efter "then" fr "if", 'for', 'while', 'with'), r det "begin"?
repeat
GetFormatToken({dataPtr} chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
//writeln('IN IF LOOP1: ', 'tokenValue: ', tokenValue, 'pos1: ', pos1);
until (not (tokenType in [kCRLFToken, kCommentToken])) or (pos1 >= bufferLength);
//writeln('**TV**', tokenValue);
//If 'if', 'for', 'while', 'with' followed by 'if..then' then do not set waitForCR, which make level down. Use pauseSecondWaitForCR for postpone that.
if ( (tokenValue = 'if') or (tokenValue = 'for') or (tokenValue = 'while') or (tokenValue = 'with') or (tokenValue = 'case') ) then
begin
pauseSecondWaitForCR:= true;
//Writeln('pauseSecondWaitForCR: ', pauseSecondWaitForCR);
end
else
begin
pauseSecondWaitForCR:= false;
//Writeln('pauseSecondWaitForCR: ', pauseSecondWaitForCR);
end;
// Om inte, intendera enbart nsta sats
if tokenValue <> 'begin' then
begin
level += 1;
ResetFlags(level);
ifWOBegin[level]:= true;
//writeln('IN IF LOOP, LEVEL UP: ', level, ' DUE TO ', tokenValue);
//IndentOnCRLF(chars, caseChars, bufferLength, pos, level);
if not (pauseSecondWaitForCR) then
begin
CheckLevel(level);
waitingForCR[level] := true;
end;
{if level >= 0 then
begin
if level > High(waitingForCR) then
SetLength(waitingForCR, level*2 + 10);
waitingForCR[level] := true;
writeln('***level***', level );
end;}
end;
//If elseFlag is true, and begin then no need to level down because the case is 'else followed by if begin'
{if ((tokenValue='begin') and elseFlag) then
begin
elseFlag := False;
predictElse:=true;
Writeln('elseFlag: ', elseFlag, ' due to if begin');
end;}
end
else if {(tokenType=kForToken)} (tokenValue = 'for') or (tokenValue='while') or (tokenValue = 'with') then
begin
pos1 := pos;
repeat GetFormatToken({dataPtr} chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue)
until (tokenValue = 'do') or (pos1 >= bufferLength);
// Sk frsta efter (efter "then" fr "if"), r det "begin"?
repeat GetFormatToken({dataPtr} chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue)
until (not (tokenType in [kCRLFToken, kCommentToken])) or (pos1 >= bufferLength);
//writeln('TOKEN VALUE: ', tokenValue);
//If 'if', 'for', 'while', 'with' followed by 'for, or while, or with ...do ' then do not set waitingForSemicolon. Use pauseSecondWaitForCR for postpone that.
if ( (tokenValue = 'if') or (tokenValue = 'for') or (tokenValue = 'while') or (tokenValue = 'with') or (tokenValue = 'case') ) then
begin
pauseSecondWaitForCR:= true;
//Writeln('pauseSecondWaitForCR: ', pauseSecondWaitForCR);
end
else
begin
pauseSecondWaitForCR:= false;
//Writeln('pauseSecondWaitForCR: ', pauseSecondWaitForCR);
end;
// Om inte, intendera enbart nsta sats
if tokenValue <> 'begin' then
begin
level+=1;
ResetFlags(level);
loopWOBegin[level]:=true;
{if level>0 then
begin
offset[level]:= offset[level-1]+1;
//offset[level]+=1;
offset[level-1]:=0;
end;}
if not (pauseSecondWaitForCR) then
begin
CheckLevel(level);
waitingForSemicolon[level] := true;
end;
{if level >= 0 then
begin
if level > High(waitingForSemicolon) then
SetLength(waitingForSemicolon, level*2 + 10);
waitingForSemicolon[level] := true;
writeln('wfs in kBeginToken for loop: ', waitingForSemicolon[level]);
end;}
end;
{if (tokenValue = 'if') then
begin
elseFlag:=true;
Writeln('elseFlag: ', elseFlag, ' due to after for/while/with if');
end;}
end
else if (tokenValue = 'else') then
begin
//if (previousTokenValue='end') then
//begin
if elseWithBegin[level+1] then
begin
level-=1;
//writeln('IFELSE level down in kBeginEndToken becoz of elseWithBegin and level ',level);
//pos1:= pos- length(tokenValue);
IndentOnCRLF(chars, caseChars, bufferLength, pos, level);
end;
//end;
pos1:=pos;
repeat GetFormatToken({dataPtr} chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue)
until (not (tokenType in [kCRLFToken, kCommentToken])) or (pos1 >= bufferLength);
//Writeln('tokenValue after else: ', tokenValue);
//If 'if', 'for', 'while', 'with' followed by 'for, or while, or with ...do ' then do not set waitingForSemicolon. Use pauseSecondWaitForCR for postpone that.
if ( (tokenValue = 'if') or (tokenValue = 'for') or (tokenValue = 'while') or (tokenValue = 'with') or (tokenValue = 'case') ) then
begin
pauseSecondWaitForCR:= true;
//Writeln('pauseSecondWaitForCR: ', pauseSecondWaitForCR);
end
else
begin
pauseSecondWaitForCR:= false;
//Writeln('pauseSecondWaitForCR: ', pauseSecondWaitForCR);
end;
// Om inte, intendera enbart nsta sats
if tokenValue <> 'begin' then
begin
level+=1;
ResetFlags(level);
elseWOBegin[level]:= true;
if not (pauseSecondWaitForCR) then
begin
CheckLevel(level);
//Set both waitingForSemicolon and waitingForCR. One of them will be used and the other will be reset.
waitingForSemicolon[level] := true;
waitingForCR[level] := true;
end;
{if level >= 0 then
begin
if level > High(waitingForSemicolon) then
SetLength(waitingForSemicolon, level*2 + 10);
waitingForSemicolon[level] := true;
end;}
end
else
begin
if (tokenValue = 'begin') then
elseWithBegin[level+1]:= true;
end;
//Else flag was used while 'if' followed by 'else, for, while, with'.
{if (tokenValue = 'if') then
begin
elseFlag:=true;
Writeln('elseFlag: ', elseFlag, ' due to after else if');
end
else //No 'if' after 'else'
if ( (predictElse) and (tokenValue <> 'begin') ) then // we will think about this later, It may be skipped.
begin
elseFlag:= true;
predictElse:=false;
end;}
end;
end;
end;
kReservedToken: //kReservedToken=3
// var type const record unit...
begin
// if (tokenValue = 'var') or (tokenValue = 'type') or (tokenValue = 'const') or (tokenValue = 'uses') then
if tokenValue = 'uses' then
begin
// Duger inte fr var/const/type som kan vara flera i rad
level += 1;
IndentOnCRLF(chars, caseChars, bufferLength, pos, level);
CheckLevel(level);
waitingForSemicolon[level] := true;
{if level >= 0 then
begin
if level > High(waitingForSemicolon) then
SetLength(waitingForSemicolon, level*2 + 10);
waitingForSemicolon[level] := true;
end;}
end;
if {(tokenType=kVarToken)}(tokenValue = 'var') or (tokenValue = 'type') or (tokenValue = 'const') then
begin
level+=1;
//WriteLn('block starter temporary level ', level);
// Parse to ";", process CR or LF followed by anything else
// or record - parsed as part of the block
// Then test the next token to see if there is more.
// Men if, for, while... och repeat...until mste ju ocks fungera! case!
// VARJE rad skall ha +1 tills semikolon kommer!
// Const och var kommer att f problem med records, som har semikolon. Processa parenteser?
// type kan innehlla class! Krver waitingForSemicolon?
// och type kan innehlla record!
// Borde inte alla dessa lsas med waitingForSemiColon?
repeat
repeat
GetFormatToken(chars, pos, tokenStart, tokenEnd, tokenType, tokenValue);
//Writeln('In Type Loop: ', tokenValue, ' pos: ', pos);
if tokenType = kCRLFToken then
IndentOnCRLF(chars, caseChars, bufferLength, pos, level);
if ( (tokenType = kReservedToken) or (tokenType = kClassToken) ) then
begin
//Writeln('*******Entered kReservedToken******');
// record statement - parse until end
if (tokenValue = 'record') or (tokenValue = 'object') then // inside "var" or "type"
begin
level+=1;
//WriteLn('record start');
repeat
GetFormatToken({dataPtr} chars, pos, tokenStart, tokenEnd, tokenType, tokenValue);
if tokenType = kCRLFToken then
IndentOnCRLF(chars, caseChars, bufferLength, pos, level);
until (tokenType = kBeginEndToken) or (pos >= bufferLength);
level-= 1;
//WriteLn('record end at ', tokenValue);
end
else
// class statement - parse until end
if ( {tokenType = kClassToken} (tokenValue = 'class') or (tokenValue = 'objcclass') ) then // inside "var" or "type"
begin
level += 1;
//WriteLn('class starts');
pos1:=pos;
repeat
GetFormatToken(chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
//writeln('IN CLASS LOOP: ', 'TOKENVALUE: ', tokenValue, ' POS1: ', pos1);
if tokenType = kCRLFToken then
IndentOnCRLF(chars, caseChars, bufferLength, pos1, level);
until (tokenValue = 'end') or (pos1 >= bufferLength);
level-= 1;
pos:=pos1;
end;
end;
until (tokenValue = ';') or (pos >= bufferLength);//second until
pos1 := pos;
repeat
GetFormatToken({dataPtr} chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
until (not (tokenType in [kCommentToken, kCompilerDirectiveToken, kCRLFToken])) or (pos1 >= bufferLength);
until ( {tokenType in [kVarToken, kImplementationToken, kFunctionToken]}(tokenvalue= 'type') or (tokenvalue= 'var') or (tokenvalue= 'begin') or (tokenvalue= 'const') or (tokenvalue= 'procedure') or
(tokenvalue= 'function') or (tokenvalue= 'implementation') or (tokenValue = 'constructor') )or (pos >= bufferLength);//first until
level-= 1;
end;
end;
kSingleCharToken: //kSingleCharToken=8
begin
if tokenValue = ';' then
if level <= High(waitingForSemicolon) then
begin
if waitingForSemicolon[level] then
begin
//If waitingForCR[level] is true then no need to level at wiatingforCR.
if waitingForCR[level] then
waitingForCR[level]:=false;
waitingForSemicolon[level] := false;
ResetFlags(level);
{ifWOBegin[level]:=false;
elseWOBegin[level]:=false;
loopWOBegin[level]:=false;
elseWithBegin[level+1]:=false;}
level -= 1;
//Writeln('Level down due to wFsemicolon: ', level);
{if elseFlag then
begin
waitingForSemicolon[level] := false;
ifWOBegin[level]:=false;
elseWOBegin[level]:=false;
loopWOBegin[level]:=false;
level-=1;
Writeln('Level down: ', level, 'due to elseFlag ', elseFlag );
elseFlag:= False;
end;}
end;
//If 'secondWaitForCR' is true, make it false, bcoz FormatIFELSE will level down bcoz of ';' found. 'secondWaitForCR' should only applicable while no ';' after if..then (if..then statement else ...)
if secondWaitForCR then
secondWaitForCR:=false;
//Reset elseWithBegin[level+1] when end followed by ';'. Its no more usefull
if previousTokenValue='end' then
if elseWithBegin[level+1] then
elseWithBegin[level+1]:=false;
if FormatIFElse(level) then
begin
repeat
if FormatIFElse(level) then
begin
ifWOBegin[level]:=false;
elseWOBegin[level]:=false;
loopWOBegin[level]:=false;
elseWithBegin[level+1]:=false;
level-=1;
//writeln('IFELSE level down in kSingleCharToken and level ',level);
end;
until not FormatIFElse(level);
end;
end;
end;
kCRLFToken:// kCRLFToken=18 , calls for every line
begin
//writeln('**Level:**', level, ' waitForCR[level]: ', waitingForCR[level], 'pauseSecondWaitForCR: ', pauseSecondWaitForCR);
if secondWaitForCR then
begin
pos1 := pos;
repeat
GetFormatToken({dataPtr} chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
until (not (tokenType in [kCommentToken, kCRLFToken])) or (pos1 >= bufferLength);
if tokenValue='else' then
if elseWOBegin[level] then
begin
waitingForSemicolon[level]:=false; // Reset waitForSemicolon as it is level down here.
level-=1;
end;
level-=1;
//Writeln('Level down due to secondWaitForCR: ', level);
secondWaitForCR:=false;
IndentOnCRLF(chars, caseChars, bufferLength, pos, level);
end;
if level <= High(waitingForCR) then
begin
if waitingForCR[level] then
begin
waitingForCR[level] := false;
secondWaitForCR:= true;
//level -= 1;
end;
IndentOnCRLF(chars, caseChars, bufferLength, pos, level);
end;
end;
// IndentOnCRLF(CharsHandle(chars), dataPtr, bufferLength, pos, level);
kCommentToken:
IndentOnCRLF(chars, caseChars, bufferLength, pos, level);
end; // case
until pos >= bufferLength;
PascalFormatter:= chars;
// Stt tillbaka markering
// Markeringen br justeras av ndringar!
// WriteLn('EXIT FORMATTER');
end;
function AddCR(chars: AnsiString; pos: LongInt; tokenValue: AnsiString):AnsiString;
var
bufferLength: LongInt;
begin
bufferLength:= Length(chars);
AddCR := Copy(chars, 1, pos-length(tokenValue)-1)+ #13 + Copy(chars, pos-length(tokenValue), bufferLength+1);
end;
function PascalCRFormatter(teRec: AnsiString):AnsiString;
var
bufferLength: Longint;
//err: OSErr;
chars: AnsiString;
pos, tokenStart, tokenEnd, tokenType: Longint;
tokenValue: AnsiString;
// hasSeenProgram, hasSeenUnit, hasSeenInterface, hasSeenImplementation: Boolean;
// secondPreviousTokenType: Longint; {Tv steg tillbaka}
// secondPreviousTokenValue: AnsiString;
pos1: Longint;
// elseFlag: Boolean=false;
bracketFlag: Boolean =true;
quitProcedure: boolean=false;
bracketFound: Boolean;
typeParsing: Boolean = false;
// procedureFlag:Boolean;
lastSemicolon:Longint;
begin
// WriteLn('ENTER CR FORMATTER');
// Get the text from the text field
chars := teRec;//^.text;
// caseChars := chars;
// Change chars to lower case
LowerCase(chars);
bufferLength := Length(chars);
pos := 0;
// level := 0;
repeat
//Writeln('previousTokenValue: ',previousTokenValue);
GetFormatToken(chars, pos, tokenStart, tokenEnd, tokenType, tokenValue);
//Writeln('tV: ',tokenValue, ' tT: ', tokenType, ' pos: ', pos);
//Add CR after tokenValue
if ( ((previousTokenValue=';') or {(previousTokenType= kBeginToken)} (previousTokenValue='begin') or (previousTokenValue='else') or (previousTokenValue='var') or (previousTokenValue='type') or (previousTokenValue='const') or
{Only after} {(previousTokenType= kCRafterTV)} (previousTokenValue='then') or (previousTokenValue='try') or (previousTokenValue='repeat') or (previousTokenValue='except') or
(previousTokenValue='finally') or (previousTokenValue='do') or (previousTokenValue='of') or (previousTokenValue='record') or (previousTokenValue='uses') )
and (not (tokenValue= #13)) ) then
begin
//Writeln('previousTokenValue: ',previousTokenValue, ' tokenValue: ', tokenValue, 'tokenType: ', tokenType,' pos: ', pos);
//Writeln('Add CR Here due to, ', previousTokenValue);
if not (tokenType=kCommentToken) then
begin
chars := AddCR(chars, pos, tokenValue);
pos:=pos-length(TokenValue);
bufferLength+=1;
//Writeln('new pos: ', pos);
//Writeln('Add CR after TV due to pTV, ', previousTokenValue );
end;
end
//Add CR before tokenValue
else
if ((not (previousTokenValue=#13)) and ( {(tokenType= kBeginToken)} (tokenValue='begin') or (tokenValue='else') or (tokenValue='var') or (tokenValue='type') or (tokenValue='const') or
{only before} {(tokenType= kFunctionToken)} (tokenValue='procedure') or (tokenValue='function') or (tokenValue = 'constructor') )) then
begin
//Writeln('previousTokenValue: ',previousTokenValue, ' tokenValue: ', tokenValue, ' pos: ', pos);
//While type parsing, no need insert CR before token Value (certainlybefore procedure in type). It only needs to add CR after ';'
if not typeParsing then
begin
chars := AddCR(chars, pos, tokenValue);
pos:=pos-length(TokenValue);
//Writeln('Add CR before TV due to tV, ', tokenValue );
//Writeln('new pos: ', pos);
bufferLength+=1;
end;
// Writeln('new pos: ', pos);
end;
//Special Cases: procedure, function, array, type, ;,
if ( tokenType= kFunctionToken {(tokenValue= 'procedure') or (tokenValue= 'function')} ) then
begin
pos1:=pos;
bracketFound:= False;
quitProcedure:= False;
bracketFlag:= true;
//writeln('Entered procedure or function loop: tokenValue: ', tokenValue);
//Parse function with / without parameters
repeat GetFormatToken(chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
//writeln('In procedure loop: tokenValue: ', tokenValue, ' pos1: ', pos1);
//If user used '(', and missed to use ')', then the formatter keeps parsing to look for ')', perhaps it make IDE wheel rolling forever.
//ToDO: It can released when formatter finds 'begin' as most likely 'begin' or 'var' is expected after procedure or function.
if tokenValue='(' then
begin
bracketFound:= true;
//bracketFlag:= true;
//writeln('bracketFlag: ', bracketFlag);
end;
if tokenValue = ';' then // this is the case, when ';' . It's either in brackets of procedure or function or end of function without brackets
if not bracketFound then // To make sure no brackets found so that quit loop as its end.
begin
quitProcedure:= true;
//pos1-=1;
end;
if tokenValue=')' then
bracketFlag:= false;
until (quitProcedure) or not (bracketFlag) or (pos1 >= bufferLength);
//Continue to parse function after brackets
if not quitProcedure then // If not quitProcedure means It has brackets or parameters in other words
begin
repeat GetFormatToken(chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
// writeln('TOKENVALUE IN PROCEDURE OR FUNCTION LOOP2: ', tokenValue, 'pos1: ', pos1);
//procedureFlag:= true;
//writeln('procedureFlag: ', procedureFlag);
if tokenValue=';' then
begin
//Set procedureFlag and keep parsing until last ';' in function
//Save position of ';' and It's previousTokenValue in order to parse from ';', If it is the latest one.
//TODO: Perhaps should save previousTokenType too
lastSemicolon:=pos1;
lastPreviousTokenValue:= previousTokenValue;
end;
(* else
if tokenValue=':' then
begin
GetFormatToken(chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue); // To get the data type of function, eg; function test():LongInt; Here 'LongInt'
//writeln('TOKENVALUE IN PROCEDURE OR FUNCTION LOOP2: ', tokenValue, 'pos1: ', pos1);
end
else // Get out from the loop, If the token value is not one of the following function modifier
if ( {(tokenType= kFunctionModifier) or} not ( (tokenValue = 'override') or (tokenValue = 'overload') or (tokenValue = 'cdecl') or (tokenValue = 'register') or (tokenValue = 'message') ) ) then
begin
procedureFlag:=false;
//writeln('procedureFlag: ', procedureFlag);
end;*)
until ( {(procedureFlag)} ( (tokenValue = 'var') or(tokenValue = 'type') or(tokenValue = 'const') or(tokenValue = 'begin') or(tokenValue = 'procedure') or
(tokenValue = 'function') or(tokenValue = 'implementation') or (tokenValue = 'constructor') or (tokenValue = 'end') ) or (pos1 >= bufferLength) );
//GetFormatToken(chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
pos1:= lastSemicolon-1;
changePreviousTokenValue:=true;
//previousTokenValue:= lastpreviousTokenValue;
end;
pos:=pos1;
end;
if (tokenValue= 'array') then
begin
pos1:=pos;
//writeln('Entered array loop: tokenValue: ', tokenValue);
repeat GetFormatToken(chars, pos1, tokenStart, tokenEnd, tokenType, tokenValue);
until (tokenValue = ';') or (pos1 >= bufferLength);
pos:=pos1;
end;
if ( (typeParsing) and (tokenValue = 'end') ) then
typeParsing:= false;
if (tokenValue= 'type') then
typeParsing:= true;
until pos >= bufferLength;
PascalCRFormatter:= chars;
end;
procedure HashInit;
begin
// Must be done SOMEWHERE
HashInitTable(pascalHashTable, kOtherToken, 'FAIL');
InitColorCodingTable;
end;
begin
HashInit;
end. |
unit UNumToText;
interface
uses SysUtils, dialogs;
type
TArrString2to9 = array [2..9] of string;
TArrString0to19 = array [0..19] of string;
TArrString1to9 = array [1..9] of string;
TNumToText = class(TObject)
public function convert(D: string): string;//D represents a number as d1d2d3...dn
private function convert2Digit(D: string): string;//D represents d1d2
private function simpleFigure(D:string): string;
private function tens(d:string):string;
private function tensAnd(d:string):string;
private function hundreds(d:string):string;
private function hundredsAnd(d:string):string;
private function convert2DigitAdv(D:string): string;
private function convert3Digit(D:string): string;//D represents d1d2d3
private function convert6Digit(D:string): string;//D represents d1d2d3d4d5d6
protected procedure validate(num:integer);virtual;
protected function THOUSANDS:string;virtual;
protected function THOUSANDS_AND:string;virtual;
protected function CTens:TArrString2to9;virtual;
protected function CTensAnd:TArrString2to9;virtual;
protected function CFigures:TArrString0to19;virtual;
protected function CHundreds:TArrString1to9;virtual;
protected function CHundredsAnd:TArrString1to9;virtual;
protected function CDivider:string;virtual;
end;
implementation
{ TNumToText }
function TNumToText.convert(D: string): string;
var n, D_Int:integer;
begin
D_Int:=strtoint(D);
validate(D_Int);
D:=inttostr(D_Int);
n:=length(D);
if n<=2 then result:=convert2Digit(D)//0..99
else if n=3 then result:=convert3Digit(D)//100..999
else if ((n>3)and(n<=6)) then result:=convert6Digit(D)//1000..9999
else raise Exception.Create('خارج از محدوده');
end;
function TNumToText.convert2Digit(D: string): string;
var n:integer;
begin
n:=strtoint(D);
if n<=19 then result:=simpleFigure(D)//0..19
else result:=convert2DigitAdv(D);//20..99
end;
function TNumToText.convert2DigitAdv(D: string): string;
var n:integer;
begin
n:=strtoint(D[2]);
if n=0 then result:=tens(D[1])//20,30,...,90
else result:=tensAnd(D[1])+CDivider+simpleFigure(D[2]);//21,22,...,29,31,32,...,99
end;
function TNumToText.convert3Digit(D: string): string;
var n:integer;
begin
n:=strtoint(D[2]+D[3]);
if (n=0) then result:=hundreds(D[1])//100,200,300,...,900
else result:=hundredsAnd(D[1])+CDivider+convert2Digit(D[2]+D[3]);//101,102,103,...,199,201,202,...,999
end;
//Note that D can be 1,000 or 12,000 or 123,000 which means that it not necessarily 6 digits
function TNumToText.convert6Digit(D: string): string;
var lowest3Digits, highest3Digits:string;
begin
lowest3Digits:=copy(D, length(D)-2, 3);//d4d5d6
highest3Digits:=copy(D, 1, length(D)-3);//d1d2d3
if strtoint(lowest3Digits)=0 then
result:=convert(highest3Digits)+CDivider+THOUSANDS//1000,2000,...,9000
else
//1001,1002,1003,...,1999,2001,2002,...,9999
result:=convert(highest3Digits)+CDivider+THOUSANDS_AND+CDivider+convert(lowest3Digits);
end;
function TNumToText.hundreds(d: string): string;
var n:integer;
begin
n:=strtoint(D);
result:=CHundreds[n];
end;
function TNumToText.hundredsAnd(d: string): string;
var n:integer;
begin
n:=strtoint(D);
result:=CHundredsAnd[n];
end;
function TNumToText.simpleFigure(D: string): string;
var n:integer;
begin
n:=strtoint(D);
result:=CFigures[n];
end;
function TNumToText.tens(d:string): string;
var n:integer;
begin
n:=strtoint(D);
result:=CTens[n];
end;
function TNumToText.tensAnd(d: string): string;
var n:integer;
begin
n:=strtoint(D);
result:=CTensAnd[n];
end;
//Constant functions for returning the text or voice files
function TNumToText.THOUSANDS: string;
begin
result:='هزار';
end;
function TNumToText.THOUSANDS_AND: string;
begin
result:='هزار و';
end;
function TNumToText.CTens: TArrString2to9;
const ARR: TArrString2to9 = ('بيست','سي','چهل','پنجاه','شصت','هفتاد',
'هشتاد','نود');
begin
result:=ARR;
end;
function TNumToText.CTensAnd: TArrString2to9;
const ARR: TArrString2to9 = ('بيست و','سي و','چهل و','پنجاه و','شصت و','هفتاد و',
'هشتاد و','نود و');
begin
result:=ARR;
end;
function TNumToText.CFigures: TArrString0to19;
const ARR: TArrString0to19 = ('صفر','يک','دو','سه','چهار','پنج',
'شش','هفت','هشت','نه','ده','يازده','دوازده','سيزده',
'چهارده','پانزده','شانزده','هفده','هيجده','نوزده');
begin
result:=ARR;
end;
function TNumToText.CHundreds: TArrString1to9;
const ARR: TArrString1to9 = ('يکصد','دويست','سيصد','چهارصد','پانصد','ششصد',
'هفتصد','هشتصد', 'نهصد');
begin
result:=ARR;
end;
function TNumToText.CHundredsAnd: TArrString1to9;
const ARR: TArrString1to9 = ('يکصد و','دويست و','سيصد و','چهارصد و','پانصد و',
'ششصد و','هفتصد و','هشتصد و', 'نهصد و');
begin
result:=ARR;
end;
function TNumToText.CDivider: string;
begin
result:=' ';
end;
procedure TNumToText.validate(num: integer);
begin
if ((num<0)or(num>999999)) then
raise Exception.Create('عدد بايستي بين 1 تا 999999 باشد');
end;
end.
|
unit xe_WORA3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, System.Math, System.StrUtils,
Dialogs, IniFiles, MSXML2_TLB, ShellAPI, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus,
Vcl.ComCtrls, dxCore, cxDateUtils, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxNavigator, Data.DB, cxDBData, cxLabel, cxCurrencyEdit,
cxClasses, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridBandedTableView, cxGridDBBandedTableView, cxGridCustomView, cxGrid,
cxTextEdit, cxDropDownEdit, cxMaskEdit, cxCalendar, Vcl.StdCtrls, cxButtons,
cxGroupBox, Vcl.ExtCtrls, dxSkinsCore, dxSkinDevExpressStyle,
dxSkinscxPCPainter;
type
TFrm_WORA3 = class(TForm)
PnlMain: TPanel;
cxGroupBox1: TcxGroupBox;
btnSearchA3: TcxButton;
cxLabel54: TcxLabel;
lblSosokNameA3: TcxLabel;
Shape1: TShape;
Shape2: TShape;
Shape5: TShape;
cxLabel30: TcxLabel;
cxLabel26: TcxLabel;
cxDtStartA3: TcxDateEdit;
cxLabel28: TcxLabel;
cxDtEndA3: TcxDateEdit;
cxLabel29: TcxLabel;
cbSelList: TcxComboBox;
cxEdtSelText: TcxTextEdit;
cxLabel27: TcxLabel;
RbButton1: TcxButton;
cxGridA3: TcxGrid;
cxgWkAttend: TcxGridDBBandedTableView;
cxgWkAttendColumn1: TcxGridDBBandedColumn;
cxgWkAttendColumn2: TcxGridDBBandedColumn;
cxgWkAttendColumn3: TcxGridDBBandedColumn;
cxgWkAttendColumn4: TcxGridDBBandedColumn;
cxgWkAttendColumn5: TcxGridDBBandedColumn;
cxgWkAttendColumn6: TcxGridDBBandedColumn;
cxgWkAttendColumn7: TcxGridDBBandedColumn;
cxgWkAttendColumn8: TcxGridDBBandedColumn;
cxgWkAttendColumn9: TcxGridDBBandedColumn;
cxgWkAttendColumn10: TcxGridDBBandedColumn;
cxgWkAttendColumn11: TcxGridDBBandedColumn;
cxgWkAttendColumn12: TcxGridDBBandedColumn;
cxgWkAttendColumn13: TcxGridDBBandedColumn;
cxgWkAttendColumn14: TcxGridDBBandedColumn;
cxGridA3Level1: TcxGridLevel;
Shape3: TShape;
pmWkMenuA3: TPopupMenu;
N29: TMenuItem;
MenuItem24: TMenuItem;
MenuItem35: TMenuItem;
MenuItem36: TMenuItem;
MenuItem37: TMenuItem;
MenuItem38: TMenuItem;
pop_dateA3: TPopupMenu;
MenuItem6: TMenuItem;
MenuItem7: TMenuItem;
MenuItem8: TMenuItem;
MenuItem9: TMenuItem;
MenuItem10: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure N29Click(Sender: TObject);
procedure pmWkMenuA3Popup(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure RbButton1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure MenuItem6Click(Sender: TObject);
procedure btnSearchA3Click(Sender: TObject);
procedure MenuItem7Click(Sender: TObject);
procedure MenuItem8Click(Sender: TObject);
procedure MenuItem9Click(Sender: TObject);
procedure MenuItem10Click(Sender: TObject);
procedure cxgWkAttendCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure cxgWkAttendBands0HeaderClick(Sender: TObject);
procedure cxgWkAttendBands1HeaderClick(Sender: TObject);
procedure cxgWkAttendBands2HeaderClick(Sender: TObject);
procedure cxgWkAttendBands3HeaderClick(Sender: TObject);
procedure cxgWkAttendBands5HeaderClick(Sender: TObject);
procedure cxgWkAttendBands6HeaderClick(Sender: TObject);
procedure cxgWkAttendBands8HeaderClick(Sender: TObject);
procedure cxgWkAttendBands9HeaderClick(Sender: TObject);
procedure cxgWkAttendBands11HeaderClick(Sender: TObject);
procedure cxgWkAttendBands12HeaderClick(Sender: TObject);
procedure cxgWkAttendBands13HeaderClick(Sender: TObject);
procedure cxgWkAttendBands15HeaderClick(Sender: TObject);
procedure cxgWkAttendBands16HeaderClick(Sender: TObject);
private
{ Private declarations }
FExcelDownBeach : string;
function func_Search_Phone(sWkSabun: string): string;
procedure proc_Wk_Tel(sWkPhone: string);
procedure proc_FamilyBrChange;
procedure proc_WkAttend;
procedure proc_WkAttend_Search;
public
{ Public declarations }
procedure proc_init;
// 전문 응답 처리
procedure proc_recieve(slList: TStringList);
function func_BrTelSearch(sBrNo: string): string;
end;
var
Frm_WORA3: TFrm_WORA3;
implementation
{$R *.dfm}
uses xe_GNL, xe_xml, xe_Func, xe_Dm, xe_Msg, Main, xe_gnl3, xe_Query, xe_gnl2,
xe_Lib, xe_WOR03, xe_WOR04, xe_WOR01, xe_COM02, xe_SMS01, xe_Flash;
procedure TFrm_WORA3.proc_init;
var
i, iRow: Integer;
sTabCap: string;
begin
try
cxDtStartA3.Date := StrToDate(Copy(startDateTime('yyyy-mm-dd hh:nn:ss'), 1, 10));
cxDtEndA3.Date := cxDtStartA3.Date + 1;
for i := 0 to cxgWkAttend.ColumnCount - 1 do
cxgWkAttend.Columns[i].DataBinding.ValueType := 'Integer';
cxgWkAttend.Columns[1].DataBinding.ValueType := 'String';
cxgWkAttend.Columns[2].DataBinding.ValueType := 'String';
cxgWkAttend.Columns[3].DataBinding.ValueType := 'String';
cxgWkAttend.Columns[10].DataBinding.ValueType := 'Currency';
cxgWkAttend.Columns[11].DataBinding.ValueType := 'Currency';
cxgWkAttend.Columns[12].DataBinding.ValueType := 'Currency';
cxgWkAttend.Columns[13].DataBinding.ValueType := 'String';
lblSosokNameA3.Caption := GetSosokInfo;
cbSelList.ItemIndex := 0;
cxEdtSelText.Text := '';
except
end;
btnSearchA3Click(btnSearchA3);
end;
procedure TFrm_WORA3.proc_recieve(slList: TStringList);
var
xdom: msDomDocument;
ls_ClientKey, ls_Msg_Err, sTemp, sBrName, sMessage, sSCnt, sFCnt, sWkSabun,
sWkName: string;
lst_Result: IXMLDomNodeList;
ls_Rcrd: TStringList;
i, j, iRow, iBrNo, iRowNum, iSum, iCash, iCol, iwk_name, iwkSabun, iNo, iSort: Integer;
iwkTitle: array[0..53] of integer;
ls_rxxml: WideString;
nYear, nDay, nAge : Integer;
y, m, d : word;
begin
try
xdom := ComsDomDocument.Create;
Screen.Cursor := crHourGlass;
try
ls_rxxml := slList[0];
if not xdom.loadXML(ls_rxxml) then
begin
btnSearchA3.Enabled := True;
Screen.Cursor := crDefault;
Exit;
end;
ls_MSG_Err := GetXmlErrorCode(ls_rxxml);
if ('0000' = ls_MSG_Err) then
begin
ls_ClientKey := GetXmlClientKey(ls_rxxml);
if Copy(ls_ClientKey, 1, 5) = 'WOR00' then
begin
ls_ClientKey := Copy(ls_ClientKey, 6, Length(ls_ClientKey) - 5);
if StrToIntDef(ls_ClientKey, 1) <> 1 then
case StrToIntDef(ls_ClientKey, 1) of
2:
begin
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
cxgWkAttend.BeginUpdate;
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
if StrToIntDef(ls_Rcrd[4], -1) = -1 then ls_Rcrd[4] := '0';
if StrToIntDef(ls_Rcrd[5], -1) = -1 then ls_Rcrd[5] := '0';
if StrToIntDef(ls_Rcrd[6], -1) = -1 then ls_Rcrd[6] := '0';
if StrToIntDef(ls_Rcrd[7], -1) = -1 then ls_Rcrd[7] := '0';
if StrToIntDef(ls_Rcrd[8], -1) = -1 then ls_Rcrd[8] := '0';
if StrToIntDef(ls_Rcrd[9], -1) = -1 then ls_Rcrd[9] := '0';
if ls_Rcrd[10] = '' then ls_Rcrd[10] := '0';
if ls_Rcrd[11] = '' then ls_Rcrd[11] := '0';
if ls_Rcrd[12] = '' then ls_Rcrd[12] := '0';
ls_Rcrd.Insert(0, IntToStr(i + 1));
iRow := cxgWkAttend.DataController.AppendRecord;
cxgWkAttend.DataController.Values[iRow, 0] := ls_Rcrd[0];
cxgWkAttend.DataController.Values[iRow, 1] := ls_Rcrd[1] + '[' + ls_Rcrd[2] + ']';
cxgWkAttend.DataController.Values[iRow, 2] := ls_Rcrd[4];
cxgWkAttend.DataController.Values[iRow, 3] := ls_Rcrd[3];
cxgWkAttend.DataController.Values[iRow, 4] := ls_Rcrd[5];
cxgWkAttend.DataController.Values[iRow, 5] := ls_Rcrd[6];
cxgWkAttend.DataController.Values[iRow, 6] := ls_Rcrd[7];
cxgWkAttend.DataController.Values[iRow, 7] := ls_Rcrd[8];
cxgWkAttend.DataController.Values[iRow, 8] := ls_Rcrd[9];
cxgWkAttend.DataController.Values[iRow, 9] := ls_Rcrd[10];
cxgWkAttend.DataController.Values[iRow, 10] := ls_Rcrd[11];
cxgWkAttend.DataController.Values[iRow, 11] := ls_Rcrd[12];
cxgWkAttend.DataController.Values[iRow, 12] := ls_Rcrd[13];
cxgWkAttend.DataController.Values[iRow, 13] := ls_Rcrd[2];
end;
finally
ls_Rcrd.Free;
end;
cxgWkAttend.EndUpdate;
end;
btnSearchA3.Enabled := True;
end;
5:
begin
if ( Not Assigned(Frm_WOR03) ) Or ( Frm_WOR03 = NIl ) then Frm_WOR03 := TFrm_WOR03.Create(Nil);
frm_WOR03.cxgWkCashHis.DataController.SetRecordCount(0);
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
frm_WOR03.cxgWkCashHis.BeginUpdate;
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
ls_Rcrd.Insert(0, InttoStr(i + 1));
if ls_Rcrd[3] = '' then
ls_Rcrd[3] := '0';
if ls_Rcrd[4] = '' then
ls_Rcrd[4] := '0';
if ls_Rcrd[6] = '' then
ls_Rcrd[6] := '0';
if Length(ls_Rcrd[1]) = 18 then
ls_Rcrd[1] := Copy(ls_Rcrd[1], 1, 10) + ' ' + Copy(ls_Rcrd[1], 11, 8);
iRow := frm_WOR03.cxgWkCashHis.DataController.AppendRecord;
frm_WOR03.cxgWkCashHis.DataController.Values[iRow, 0] := ls_Rcrd[0];
frm_WOR03.cxgWkCashHis.DataController.Values[iRow, 1] := ls_Rcrd[1];
frm_WOR03.cxgWkCashHis.DataController.Values[iRow, 2] := ls_Rcrd[2];
frm_WOR03.cxgWkCashHis.DataController.Values[iRow, 3] := ls_Rcrd[3];
frm_WOR03.cxgWkCashHis.DataController.Values[iRow, 4] := ls_Rcrd[4];
frm_WOR03.cxgWkCashHis.DataController.Values[iRow, 5] := ls_Rcrd[5];
frm_WOR03.cxgWkCashHis.DataController.Values[iRow, 6] := ls_Rcrd[6];
frm_WOR03.cxgWkCashHis.DataController.Values[iRow, 7] := ls_Rcrd[7];
frm_WOR03.cxgWkCashHis.DataController.Values[iRow, 8] := ls_Rcrd[8];
end;
finally
ls_Rcrd.Free;
end;
frm_WOR03.cxgWkCashHis.EndUpdate;
btnSearchA3.Enabled := True;
end;
if frm_WOR03.cxgWkCashHis.DataController.RecordCount > 0 then
frm_WOR03.Show;
end;
8:
begin
if ( Not Assigned(Frm_WOR04) ) Or ( Frm_WOR04 = NIl ) then Frm_WOR04 := TFrm_WOR04.Create(Nil);
Frm_WOR04.cxgWkAttend.DataController.SetRecordCount(0);
Frm_WOR04.cxgWkAttend.BeginUpdate;
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
iRow := frm_WOR04.cxgWkAttend.DataController.AppendRecord;
// 1 Record 추가
if Length(ls_Rcrd[2]) = 18 then
ls_Rcrd[2] := Copy(ls_Rcrd[2], 1, 10) + ' ' + Copy(ls_Rcrd[2], 11, 8);
if ls_Rcrd[12] = '/' then
ls_Rcrd[12] := '';
if ls_Rcrd[13] = '/' then
ls_Rcrd[13] := '';
if ls_Rcrd[14] = '' then
ls_Rcrd[14] := '0';
if ls_Rcrd[15] = '' then
ls_Rcrd[15] := '0';
if ls_Rcrd[16] = '' then
ls_Rcrd[16] := '0';
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 0] := ls_Rcrd[0];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 1] := ls_Rcrd[4];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 2] := strtocall(ls_Rcrd[11]);
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 3] := ls_Rcrd[2];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 4] := ls_Rcrd[10];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 5] := ls_Rcrd[7];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 6] := ls_Rcrd[12];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 7] := ls_Rcrd[13];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 8] := ls_Rcrd[14];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 9] := ls_Rcrd[15];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 10] := ls_Rcrd[16];
Frm_WOR04.cxgWkAttend.DataController.Values[iRow, 11] := ls_Rcrd[1];
end;
finally
ls_Rcrd.Free;
end;
end;
Frm_WOR04.cxgWkAttend.EndUpdate;
if Frm_WOR04.cxgWkAttend.DataController.RecordCount > 0 then
begin
Frm_WOR04.Show;
end;
end;
end;
end else
if Copy(ls_ClientKey, 1, 5) = 'WOR01' then
begin
Frm_WOR01.proc_recieve(ls_rxxml);
end else
if Copy(ls_ClientKey, 1, 5) = 'WOR05' then
begin
//- frm_WOR05.proc_recieve(ls_rxxml);
end else
if Copy(ls_ClientKey, 1, 5) = 'WOR06' then
begin
//- frm_WOR06.proc_recieve(ls_rxxml);
end else
if Copy(ls_ClientKey, 1, 5) = 'WOR07' then
begin
//- frm_WOR07.proc_recieve(ls_rxxml);
end else
if Copy(ls_ClientKey, 1, 5) = 'WOR08' then
begin
//- frm_WOR08.proc_recieve(ls_rxxml);
end else
if Copy(ls_ClientKey, 1, 5) = 'WOR09' then
begin
//- frm_WOR09.proc_recieve(ls_rxxml);
end;
end else
begin
btnSearchA3.Enabled := True;
Screen.Cursor := crDefault;
GMessagebox(MSG012 + CRLF + ls_MSG_Err, CDMSE);
end;
finally
btnSearchA3.Enabled := True;
Screen.Cursor := crDefault;
xdom := Nil;
end;
except
btnSearchA3.Enabled := True;
end;
end;
procedure TFrm_WORA3.FormCreate(Sender: TObject);
var
i : Integer;
begin
try
// 날짜형식이 'yy/mm/dd'일경우 오류 발생 가능성으로 인해 자체 Display 포맷 변경
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TcxDateEdit then
begin
(Components[i] as TcxDateEdit).Properties.DisplayFormat := 'yyyy/mm/dd';
(Components[i] as TcxDateEdit).Properties.EditFormat := 'yyyy/mm/dd';
end;
end;
except
end;
proc_init;
if (TCK_USER_PER.WOR_MngModify = '1') then
begin
N29.Visible := True;
end else
begin
N29.Visible := False;
end;
end;
procedure TFrm_WORA3.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrm_WORA3.btnSearchA3Click(Sender: TObject);
begin
if (GT_SEL_BRNO.GUBUN = '0') and (not Check_ALLHD(GT_SEL_BRNO.HDNO)) then
begin
GMessagebox('해당본사에 대한 전체 권한이 없습니다.' + #13#10 + '지사를 선택하여 주십시오.', CDMSI);
exit;
end;
cxgWkAttend.DataController.SetRecordCount(0);
proc_WkAttend;
end;
procedure TFrm_WORA3.N29Click(Sender: TObject);
var
iWkSabun, iRow, iBrNo: Integer;
sWkSabun, sBrNo, sWkPhone, sKeyNum: string;
begin
sWkPhone := '';
iWkSabun := 2;
iBrNo := 13;
iRow := cxgWkAttend.DataController.FocusedRecordIndex;
if iRow < 0 then
exit;
sWkSabun := cxgWkAttend.DataController.Values[iRow, iWkSabun];
sBrNo := cxgWkAttend.DataController.Values[iRow, iBrNo];
case TMenuItem(Sender).Tag of
0:
begin
if Not Assigned(Frm_WOR01) Or (Frm_WOR01 = Nil) then Frm_WOR01 := TFrm_WOR01.Create(Nil);
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
proc_FamilyBrChange;
if GS_PRJ_AREA = 'O' then
begin
frm_WOR01.proc_wk_Search(sWkSabun);
frm_WOR01.Show;
end else
begin
Frm_WOR01.proc_init;
Frm_WOR01.gWOR19Mode := 'UPDATE';
Frm_WOR01.Show;
Frm_WOR01.proc_wk_Search(sWkSabun);
end;
end;
1:
begin
if ( Not Assigned(Frm_COM02) ) Or ( Frm_COM02 = NIl ) then Frm_COM02 := TFrm_COM02.Create(Nil);
Frm_COM02.proc_wk_Search(sWkSabun);
Frm_COM02.Show;
end;
2:
begin
sWkPhone := func_Search_Phone(sWkSabun);
if sWkPhone = '' then
exit;
proc_Wk_Tel(sWkPhone);
end;
3:
begin
sWkPhone := func_Search_Phone(sWkSabun);
if sWkPhone = '' then Exit;
sKeyNum := func_BrTelSearch(sBrNo);
if ( Not Assigned(Frm_SMS01) ) Or ( Frm_SMS01 = NIl ) then Frm_SMS01 := TFrm_SMS01.Create(Nil);
Frm_SMS01.mm_message.Text := '';
Frm_SMS01.ed_send.Text := sKeyNum;
Frm_SMS01.ls_sms.Items.Clear;
Frm_SMS01.ls_sms.Items.Add(sWkPhone);
Frm_SMS01.Proc_Init;
Frm_SMS01.Show;
end;
4:
begin
if cxgWkAttend.DataController.RecordCount = 0 then
begin
GMessagebox('자료가 없습니다.', CDMSI);
exit;
end;
if GT_USERIF.Excel_Use = 'n' then
begin
GMessagebox('[엑셀다운로드허용] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.', CDMSI);
Exit;
end;
if TCK_USER_PER.WOR_ExcelDown <> '1' then
begin
ShowMessage('[엑셀다운로드[기사메뉴]] 권한이 없습니다. 관리자에게 문의(권한요청) 바랍니다.');
Exit;
end;
Frm_Main.sgExcel := '기사배차현황.xls';
Frm_Main.sgRpExcel := Format('기사>기사배차현황]%s건/%s', [GetMoneyStr(cxgWkAttend.DataController.RecordCount), FExcelDownBeach]);
Frm_Main.cxGridExcel := cxGridA3;
Frm_Main.proc_excel(0);
end;
end;
end;
function TFrm_WORA3.func_Search_Phone(sWkSabun: string): string;
var
ls_TxLoad, sNode, rv_str: string;
ls_rxxml: WideString;
xdom: msDomDocument;
lst_Node: IXMLDOMNodeList;
lst_Result: IXMLDomNodeList;
ls_Msg_Err, sWkHp, sWkPhone: string;
ls_Rcrd: TStringList;
slReceive: TStringList;
ErrCode: integer;
begin
Result := '';
ls_rxxml := GTx_UnitXmlLoad('SEL04.XML');
xdom := ComsDomDocument.Create;
try
if (not xdom.loadXML(ls_rxxml)) then
begin
Screen.Cursor := crDefault;
ShowMessage('전문 Error입니다. 다시조회하여주십시요.');
Exit;
end;
sNode := '/cdms/header/UserID';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Value').Text := En_Coding(GT_USERIF.ID);
sNode := '/cdms/header/ClientVer';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Value').Text := VERSIONINFO;
sNode := '/cdms/header/ClientKey';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Value').Text := 'WOR0013';
sNode := '/cdms/Service/Data/Query';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Key').Text := 'WKSEARCH03';
sNode := '/cdms/Service/Data/Query/Param';
lst_Node := xdom.documentElement.selectNodes(sNode);
lst_Node.item[0].attributes.getNamedItem('Seq').Text := '1';
lst_Node.item[0].attributes.getNamedItem('Value').Text := sWkSabun;
ls_TxLoad := '<?xml version="1.0" encoding="euc-kr"?>' + #13#10 + xDom.documentElement.xml;
slReceive := TStringList.Create;
try
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False) then
begin
rv_str := slReceive[0];
if rv_str <> '' then
begin
ls_rxxml := rv_str;
Application.ProcessMessages;
if not xdom.loadXML(ls_rxxml) then
begin
Screen.Cursor := crDefault;
ShowMessage('전문 Error입니다. 다시조회하여주십시요.');
exit;
end;
ls_MSG_Err := GetXmlErrorCode(ls_rxxml);
if ('0000' = ls_MSG_Err) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
GetTextSeperationEx('│', lst_Result.item[0].attributes.getNamedItem('Value').Text, ls_Rcrd);
sWkHp := ls_Rcrd[0];
sWkPhone := ls_Rcrd[1];
if (Copy(sWkPhone, 1, 2) = '01') and (Length(sWkPhone) in [10, 11]) then
Result := sWkPhone
else
Result := sWkHp;
finally
ls_Rcrd.Free;
end;
end
else
begin
Screen.Cursor := crDefault;
GMessagebox(MSG012 + CRLF + ls_MSG_Err, CDMSE);
end;
end;
end;
finally
FreeAndNil(slReceive);
end;
finally
xdom := Nil;
end;
end;
procedure TFrm_WORA3.pmWkMenuA3Popup(Sender: TObject);
begin
if GT_OCX <> '' then
MenuItem35.Visible := True
else
MenuItem35.Visible := False;
end;
procedure TFrm_WORA3.proc_Wk_Tel(sWkPhone: string);
var
sCustTel : string;
begin
sCustTel := StringReplace(sWkPhone, '-', '', [rfReplaceAll]);
Log('기사배차 기사전화걸기 ' + sCustTel, LOGDATAPATHFILE);
Frm_Main.pCallingCID(sCustTel, GT_POSS_KEYNUM);
end;
procedure TFrm_WORA3.RbButton1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
pop_dateA3.Popup(Mouse.CursorPos.X, Mouse.CursorPos.y);
end;
function TFrm_WORA3.func_BrTelSearch(sBrNo: string): string;
var
i: Integer;
sTmp: string;
begin
Result := '';
try
for i := 0 to GT_BR_KN_CNT do
begin
if GSL_HD_LIST[i, 0] = sBrNo then
begin
Result := GSL_HD_LIST[i, 7];
break;
end;
end;
except
on e: Exception do
begin
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands0HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 0) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[0].SortOrder = soNone) or
(cxgWkAttend.Columns[0].SortOrder =
soDescending) then
cxgWkAttend.Columns[0].SortOrder := soAscending
else
if cxgWkAttend.Columns[0].SortOrder = soAscending then
cxgWkAttend.Columns[0].SortOrder := soDescending;
cxgWkAttend.Columns[0].SortIndex := 0;
cxgWkAttend.DataController.FocusedRowIndex := 0;
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands0]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands11HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 8) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[8].SortOrder = soNone) or
(cxgWkAttend.Columns[8].SortOrder =
soDescending) then
cxgWkAttend.Columns[8].SortOrder := soAscending
else
if cxgWkAttend.Columns[8].SortOrder = soAscending then
cxgWkAttend.Columns[8].SortOrder := soDescending;
cxgWkAttend.Columns[8].SortIndex := 8;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands8]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands12HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 9) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[9].SortOrder = soNone) or
(cxgWkAttend.Columns[9].SortOrder =
soDescending) then
cxgWkAttend.Columns[9].SortOrder := soAscending
else
if cxgWkAttend.Columns[9].SortOrder = soAscending then
cxgWkAttend.Columns[9].SortOrder := soDescending;
cxgWkAttend.Columns[9].SortIndex := 9;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands9]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands13HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 10) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[10].SortOrder = soNone) or
(cxgWkAttend.Columns[10].SortOrder =
soDescending) then
cxgWkAttend.Columns[10].SortOrder := soAscending
else
if cxgWkAttend.Columns[10].SortOrder = soAscending then
cxgWkAttend.Columns[10].SortOrder := soDescending;
cxgWkAttend.Columns[10].SortIndex := 10;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands10]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands15HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 11) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[11].SortOrder = soNone) or
(cxgWkAttend.Columns[11].SortOrder =
soDescending) then
cxgWkAttend.Columns[11].SortOrder := soAscending
else
if cxgWkAttend.Columns[11].SortOrder = soAscending then
cxgWkAttend.Columns[11].SortOrder := soDescending;
cxgWkAttend.Columns[11].SortIndex := 11;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands11]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands16HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 12) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[12].SortOrder = soNone) or
(cxgWkAttend.Columns[12].SortOrder =
soDescending) then
cxgWkAttend.Columns[12].SortOrder := soAscending
else
if cxgWkAttend.Columns[12].SortOrder = soAscending then
cxgWkAttend.Columns[12].SortOrder := soDescending;
cxgWkAttend.Columns[12].SortIndex := 12;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
GMessagebox(PChar('frmWOR[cxgWkAttendBands12]Error:' + e.Message), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands1HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 1) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[1].SortOrder = soNone) or
(cxgWkAttend.Columns[1].SortOrder =
soDescending) then
cxgWkAttend.Columns[1].SortOrder := soAscending
else
if cxgWkAttend.Columns[1].SortOrder = soAscending then
cxgWkAttend.Columns[1].SortOrder := soDescending;
cxgWkAttend.Columns[1].SortIndex := 1;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands1]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands2HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 2) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[2].SortOrder = soNone) or
(cxgWkAttend.Columns[2].SortOrder =
soDescending) then
cxgWkAttend.Columns[2].SortOrder := soAscending
else
if cxgWkAttend.Columns[2].SortOrder = soAscending then
cxgWkAttend.Columns[2].SortOrder := soDescending;
cxgWkAttend.Columns[2].SortIndex := 2;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands2]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands3HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 3) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[3].SortOrder = soNone) or
(cxgWkAttend.Columns[3].SortOrder =
soDescending) then
cxgWkAttend.Columns[3].SortOrder := soAscending
else
if cxgWkAttend.Columns[3].SortOrder = soAscending then
cxgWkAttend.Columns[3].SortOrder := soDescending;
cxgWkAttend.Columns[3].SortIndex := 3;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands3]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands5HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 4) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[4].SortOrder = soNone) or
(cxgWkAttend.Columns[4].SortOrder =
soDescending) then
cxgWkAttend.Columns[4].SortOrder := soAscending
else
if cxgWkAttend.Columns[4].SortOrder = soAscending then
cxgWkAttend.Columns[4].SortOrder := soDescending;
cxgWkAttend.Columns[4].SortIndex := 4;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands4]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands6HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 5) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[5].SortOrder = soNone) or
(cxgWkAttend.Columns[5].SortOrder =
soDescending) then
cxgWkAttend.Columns[5].SortOrder := soAscending
else
if cxgWkAttend.Columns[5].SortOrder = soAscending then
cxgWkAttend.Columns[5].SortOrder := soDescending;
cxgWkAttend.Columns[5].SortIndex := 5;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands5]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands8HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 6) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[6].SortOrder = soNone) or
(cxgWkAttend.Columns[6].SortOrder =
soDescending) then
cxgWkAttend.Columns[6].SortOrder := soAscending
else
if cxgWkAttend.Columns[6].SortOrder = soAscending then
cxgWkAttend.Columns[6].SortOrder := soDescending;
cxgWkAttend.Columns[6].SortIndex := 6;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands6]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendBands9HeaderClick(Sender: TObject);
var
i: Integer;
sTemp: string;
begin
try
for i := 0 to cxgWkAttend.ColumnCount - 1 do
begin
if (i <> 7) then
begin
cxgWkAttend.Columns[i].SortIndex := -1;
cxgWkAttend.Columns[i].SortOrder := soNone;
end;
end;
if (cxgWkAttend.Columns[7].SortOrder = soNone) or
(cxgWkAttend.Columns[7].SortOrder =
soDescending) then
cxgWkAttend.Columns[7].SortOrder := soAscending
else
if cxgWkAttend.Columns[7].SortOrder = soAscending then
cxgWkAttend.Columns[7].SortOrder := soDescending;
cxgWkAttend.Columns[7].SortIndex := 7;
cxgWkAttend.DataController.FocusedRowIndex := 0;
gfSetIndexNo(cxgWkAttend, GS_SortNoChange);
except
on e: Exception do
begin
sTemp := 'frmWOR[cxgWkAttendBands7]Error:' + e.Message;
GMessagebox(PChar(sTemp), CDMSE);
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_WORA3.cxgWkAttendCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
begin
proc_WkAttend_Search;
end;
procedure TFrm_WORA3.proc_WkAttend_Search;
var
ls_TxQry, ls_TxLoad, sDt1, sDt2, sWkSabun, sQueryTemp : string; // XML File Load
iRow, iwkSabun: Integer;
slReceive: TStringList;
ErrCode: integer;
begin
iRow := cxgWkAttend.DataController.FocusedRecordIndex;
if iRow < 0 then
exit;
iwkSabun := cxgWkAttend.GetColumnByFieldName('기사사번').Index;
sWkSabun := cxgWkAttend.DataController.Values[iRow, iWkSabun];
if (cxDtStartA3.Text = '') or (cxDtEndA3.Text = '') then
begin
cxDtStartA3.Date := StrToDate(Copy(startDateTime('yyyy-mm-dd'), 1, 10));
cxDtEndA3.Date := cxDtStartA3.Date + 1;
end;
sDt1 := FormatDateTime('yyyymmdd', cxDtStartA3.Date) + '090000';
sDt2 := FormatDateTime('yyyymmdd', cxDtEndA3.Date) + '090000';
ls_TxLoad := GTx_UnitXmlLoad('SEL01.XML');
fGet_BlowFish_Query(GSQ_WK_ATTENT_SEARCH, sQueryTemp);
ls_TxQry := Format(sQueryTemp, [sWkSabun, sDt1, sDt2]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString',
En_Coding(GT_USERIF.ID),
[rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO,
[rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', 'WOR008',
[rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry,
[rfReplaceAll]);
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
procedure TFrm_WORA3.FormDestroy(Sender: TObject);
begin
Frm_WORA3 := Nil;
end;
procedure TFrm_WORA3.MenuItem10Click(Sender: TObject);
begin
SetDateControl(cxDtStartA3, cxDtEndA3, tdStartMonth);
end;
procedure TFrm_WORA3.MenuItem6Click(Sender: TObject);
begin
SetDateControl(cxDtStartA3, cxDtEndA3, tdToday);
end;
procedure TFrm_WORA3.MenuItem7Click(Sender: TObject);
begin
SetDateControl(cxDtStartA3, cxDtEndA3, tdYesterday);
end;
procedure TFrm_WORA3.MenuItem8Click(Sender: TObject);
begin
SetDateControl(cxDtStartA3, cxDtEndA3, tdOneWeek);
end;
procedure TFrm_WORA3.MenuItem9Click(Sender: TObject);
begin
SetDateControl(cxDtStartA3, cxDtEndA3, tdOneMonth);
end;
procedure TFrm_WORA3.proc_FamilyBrChange;
var
i : Integer;
HdCd, HdCd_Old : String;
begin
try
frm_WOR01.FBrNoList.Clear;
frm_WOR01.FTakList.Clear;
frm_WOR01.cboBranch.Properties.Items.Clear;
HdCd_Old := '';
for I := 0 to scb_FamilyBrName.Count - 1 do
begin
HdCd :='';
HdCd := frm_Main.func_search_hdNo(scb_FamilyBrCode[I]);
if HdCd <> HdCd_Old then
begin
frm_WOR01.RequestDataHeadInfo(HdCd);
HdCd_Old := HdCd;
end;
frm_WOR01.cboBranch.Properties.Items.Add('(' + HdCd + ',' + scb_FamilyBrCode[I] +')' + scb_FamilyBrName[I] + '/' + frm_WOR01.Gs_HdNm );
frm_WOR01.FBrNoList.Add(scb_FamilyBrCode[I]);
frm_WOR01.FTakList.Add(scb_FamilyTaksong[I]);
end;
except
end;
end;
procedure TFrm_WORA3.proc_WkAttend;
var
ls_TxQry, ls_TxLoad, sDt1, sDt2, sWhere, sHdNo, sQueryTemp: string;
slReceive: TStringList;
ErrCode: integer;
begin
if (GT_USERIF.LV = '10') and ((GT_SEL_BRNO.GUBUN <> '1') or (GT_SEL_BRNO.BrNo <> GT_USERIF.BR)) then
begin
GMessagebox('상담원 권한은 소속 지사만 조회할수 있습니다.', CDMSI);
Exit;
end;
if fGetChk_Search_HdBrNo('기사배차현황') then Exit;
if cxgWkAttend.DataController.RecordCount = 0 then
begin
//////////////////////////////////////////////////////////////////////////////
// 기사>기사배차현황]1000건/콜센터(통합)/기간:XXXX~XXXX
FExcelDownBeach := Format('%s/기간:%s~%s',
[
GetSelBrInfo
, cxDtStartA3.Text, cxDtEndA3.Text
]);
//////////////////////////////////////////////////////////////////////////////
sWhere := '';
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
sHdNo := GT_SEL_BRNO.HDNO
else
sHdNo := GT_USERIF.HD;
if (cxDtStartA3.Text = '') or (cxDtEndA3.Text = '') then
begin
cxDtStartA3.Date := StrToDate(Copy(startDateTime('yyyy-mm-dd'), 1, 10));
cxDtEndA3.Date := cxDtStartA3.Date + 1;
end;
sDt1 := FormatDateTime('yyyymmdd', cxDtStartA3.Date) + '090000';
sDt2 := FormatDateTime('yyyymmdd', cxDtEndA3.Date) + '090000';
if GT_USERIF.LV <> '60' then
sWhere := 'AND WK_BRCH = ''' + GT_USERIF.BR + ''' '
else if GT_SEL_BRNO.GUBUN = '1' then
sWhere := 'AND WK_BRCH = ''' + GT_SEL_BRNO.BrNo + ''' ';
if cxEdtSelText.Text <> '' then
begin
if cbSelList.ItemIndex = 0 then
sWhere := sWhere + ' AND CONF_WK_SABUN = ''' + Param_Filtering(cxEdtSelText.Text) + ''' '
else
if cbSelList.ItemIndex = 1 then
sWhere := sWhere + ' AND CONF_WORKER LIKE ''%' + Param_Filtering(cxEdtSelText.Text) + '%'' ';
end;
ls_TxLoad := GTx_UnitXmlLoad('SEL01.XML');
fGet_BlowFish_Query(GSQ_WK_ATTEND, sQueryTemp);
ls_TxQry := Format(sQueryTemp, [sDt1, sDt2, sHdNo, sWhere]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', En_Coding(GT_USERIF.ID), [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', 'WOR002', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
Screen.Cursor := crHourGlass;
slReceive := TStringList.Create;
try
frm_Main.proc_SocketWork(False);
if dm.SendSock(ls_TxLoad, slReceive, ErrCode, False, 30000) then
begin
Application.ProcessMessages;
proc_recieve(slReceive);
end;
finally
frm_Main.proc_SocketWork(True);
FreeAndNil(slReceive);
Screen.Cursor := crDefault;
Frm_Flash.Hide;
end;
end;
end;
end.
|
{
定义文字编辑和艺术字的接口
}
unit PCSText;
interface
uses
Windows, TextDef, Image;
//#include "TextDef.h"
//#include "Image.h"
//typedef struct tagARTTEXTINFO
//{
// HANDLE hInst;
// wchar_t szArtID[64];
// UINT uBmpID;
// DWORD dwReserve;
//}ARTTEXTINFO, * LPARTTEXTINFO;
//typedef struct tagTEXTTRANSFORM
//{
// POINT ptLeftTop;
// POINT ptLeftBottom;
// POINT ptRightTop;
// POINT ptRightBottom;
//}TEXTTRANSFORM, * LPTEXTTRANSFORM;
type
ARTTEXTINFO = record
hInst : THandle;
szArtID : array[0..63] of WCHAR;
uBmpID: UINT;
dwReserve: DWORD;
end;
LPARTTEXTINFO = ^ARTTEXTINFO;
TEXTTRANSFORM = record
ptLeftTop : TPoint;
ptLeftBottom : TPoint;
ptRightTop : TPoint ;
ptRightBottom : TPoint ;
end;
LPTEXTTRANSFORM = ^TEXTTRANSFORM ;
// void __stdcall TextInit();
function TextInit() : void; stdcall;
// 关闭GDI+
// void __stdcall TextUninit();
function TextUninit() : void; stdcall;
//int __stdcall GetSupportFontCount();
function GetSupportFontCount() : Integer; stdcall;
//bool __stdcall GetSupportFontName(int nIndex, wchar_t * pFontName);
function GetSupportFontName(nIndex: Integer; pFontName: PWideChar): Boolean; stdcall;
//bool __stdcall SetNormalTransform(LPTEXTTRANSFORM lp);
//function SetNormalTransform(lp : LPTEXTTRANSFORM) : Boolean; stdcall;
//bool __stdcall GenerateNormalText(HDIBIMAGE hImage, const LPTEXTITEM pItem, HDIBIMAGE hImageTexture = NULL);
//function GenerateNormalText(hImage: HDIBIMAGE; pItem: LPTEXTITEM; hImageTexture : HDIBIMAGE = nil): Boolean; stdcall;
//HDIBIMAGE __stdcall GenerateNormalText(const LPTEXTITEM pItem, LPTEXTTRANSFORM lpTextTransform, HDIBIMAGE hImageTexture = NULL);
function GenerateNormalText(const pItem: LPTEXTITEM; lpTextTransform: LPTEXTTRANSFORM; hImageTexture: HDIBIMAGE = NIL): HDIBIMAGE; stdcall;
//HDIBIMAGE __stdcall GenerateNormalTextEx(const LPTEXTITEM pItem, int width = 0, int height = 0, HDIBIMAGE hImageTexture = NULL);
function GenerateNormalTextEx(const pItem: LPTEXTITEM; width: Integer = 0; height: Integer = 0; hImageTexture: HDIBIMAGE = NIL): HDIBIMAGE; stdcall;
//int __stdcall GetArtTextCount();
function GetArtTextCount: Integer; stdcall;
//bool __stdcall GetArtTextInfo(int nIndex, LPARTTEXTINFO pInfo);
function GetArtTextInfo(nIndex: Integer; pInfo: LPARTTEXTINFO) : Boolean; stdcall;
//int __stdcall GetIndexFromID(wchar_t * pArtID);
function GetIndexFromID(pArtID : PWideChar): Integer; stdcall;
//bool __stdcall SetArtTransform(LPTEXTTRANSFORM lp);
//function SetArtTransform(lp: LPTEXTTRANSFORM) : Boolean; stdcall;
//bool __stdcall GenerateArtText(HDIBIMAGE hImage, LPARTTEXTITEM pArtItem);
//function GenerateArtText(hImage: HDIBIMAGE; pArtItem: LPARTTEXTITEM): Boolean; stdcall;
//HDIBIMAGE __stdcall GenerateArtText(LPARTTEXTITEM pArtItem, LPTEXTTRANSFORM lpTextTransform);
function GenerateArtText(pArtItem: LPARTTEXTITEM; lpTextTransform: LPTEXTTRANSFORM) : HDIBIMAGE; stdcall;
//HDIBIMAGE __stdcall GenerateArtTextEx(LPARTTEXTITEM pArtItem, int width, int height);
function GenerateArtText(pArtItem: LPARTTEXTITEM; width: Integer; height: Integer) : HDIBIMAGE; stdcall;
implementation
const
DLL_NAME = 'WS_Text.dll' ;
//function SetNormalTransform ; external DLL_NAME name 'SetNormalTransform' ;
//function SetArtTransform ; external DLL_NAME name 'SetArtTransform' ;
function TextInit ; external DLL_NAME name 'TextInit';
function TextUninit ; external DLL_NAME name 'TextUninit';
function GenerateNormalText ; external DLL_NAME name 'GenerateNormalText' ;
function GenerateNormalTextEx ; external DLL_NAME name 'GenerateNormalTextEx' ;
function GetArtTextCount ; external DLL_NAME name 'GetArtTextCount' ;
function GetArtTextInfo ; external DLL_NAME name 'GetArtTextInfo' ;
function GenerateArtText ; external DLL_NAME name 'GenerateArtText' ;
function GenerateArtTextEx ; external DLL_NAME name 'GenerateArtTextEx' ;
function GetSupportFontCount ; external DLL_NAME name 'GetSupportFontCount';
function GetSupportFontName ; external DLL_NAME name 'GetSupportFontName' ;
function GetIndexFromID ; external DLL_NAME name 'GetIndexFromID' ;
end. |
unit uFr_CadastroMetaIQF;
interface
uses
System.IOUtils,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinOffice2013White,
dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit,
cxNavigator, Data.DB, cxDBData, cxImageComboBox, cxCheckBox, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
cxGridCustomView, cxGrid, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Comp.Client,
cxContainer, cxLabel, dxGDIPlusClasses, Vcl.ExtCtrls, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, cxColorComboBox,
FireDAC.Comp.DataSet, cxCalendar;
type
TFr_CadastroMetaIQF = class(TForm)
cxGridIQF_Metas: TcxGrid;
cxTableViewIQF_Metas: TcxGridDBTableView;
cxGridLevelIQF_Metas: TcxGridLevel;
FDConnection: TFDConnection;
PanelSQLSplashScreen: TPanel;
ImageSQLSplashScreen: TImage;
cxLabelMensagem: TcxLabel;
DataSourceTIQF_Meta: TDataSource;
FDQueryTIQF_Meta: TFDQuery;
FDQueryTIQF_MetaTIQF_METACOD: TFDAutoIncField;
FDQueryTIQF_MetaVALOR: TBCDField;
FDQueryTIQF_MetaDATA_INICIO: TSQLTimeStampField;
FDQueryTIQF_MetaDATA_FIM: TSQLTimeStampField;
cxTableViewIQF_MetasVALOR: TcxGridDBColumn;
cxTableViewIQF_MetasDATA_INICIO: TcxGridDBColumn;
cxTableViewIQF_MetasDATA_FIM: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
procedure Mensagem( pMensagem: String );
{ Private declarations }
public
{ Public declarations }
procedure AbrirDataset;
procedure LoadGridCustomization;
end;
var
Fr_CadastroMetaIQF: TFr_CadastroMetaIQF;
implementation
{$R *.dfm}
uses uUtils, uBrady;
procedure TFr_CadastroMetaIQF.AbrirDataset;
begin
if not FDConnection.Connected then
begin
Mensagem( 'Abrindo conex„o...' );
try
FDConnection.Params.LoadFromFile( MyDocumentsPath + '\DB.ini' );
FDConnection.Open;
Mensagem( 'Obtendo dados (IQF Metas)...' );
FDQueryTIQF_Meta.Open;
finally
Mensagem( EmptyStr );
end;
end;
end;
procedure TFr_CadastroMetaIQF.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
FDConnection.Close;
Fr_CadastroMetaIQF := nil;
Action := caFree;
end;
procedure TFr_CadastroMetaIQF.FormCreate(Sender: TObject);
begin
LoadGridCustomization;
end;
procedure TFr_CadastroMetaIQF.LoadGridCustomization;
begin
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + Name + '_' + cxTableViewIQF_Metas.Name + '.ini' ) then
cxTableViewIQF_Metas.RestoreFromIniFile( MyDocumentsPath + '\' + Name + '_' + cxTableViewIQF_Metas.Name + '.ini' );
end;
procedure TFr_CadastroMetaIQF.Mensagem(pMensagem: String);
begin
cxLabelMensagem.Caption := pMensagem;
PanelSQLSplashScreen.Visible := not pMensagem.IsEmpty;
Update;
Application.ProcessMessages;
end;
end.
|
(*======================================================================*
| GraphFlip unit |
| |
| Simple functions to flip and rotate 24-bit bitmaps |
| |
| Not that these functions *create* copies of the bitmap which must be |
| freed. |
| |
| 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. |
| |
| Copyright © Colin Wilson 2002 All Rights Reserved |
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 1.0 29/08/2002 CPWW Original |
| 10.0 08/03/2006 CPWW Tidied up for BDS 2006 |
| 12.0 09/06/2008 CPWW Tiburonized |
*======================================================================*)
unit GraphFlip;
interface
uses Windows, Classes, Sysutils, Graphics;
function RotateBitmap270 (const bitmap : TBitmap) : TBitmap;
function RotateBitmap90 (const bitmap : TBitmap) : TBitmap;
function ConvertToGrayscale (const bitmap : TBitmap; TransparentColor : TColor = clNone) : TBitmap;
function ConvertToNegative (const bitmap : TBitmap) : TBitmap;
implementation
(*----------------------------------------------------------------------*
| function BytesPerScanLine : LongInt |
| |
| Returns the bytes required per scanline |
| |
| Parameters: |
| PixelsPerScanline : LongInt The width of the bitmap in pixels |
| BitsPerPixel No. of bits per pixel - eg. 24 |
| Alignment The bitmap byte alignment - eg. 32 |
*----------------------------------------------------------------------*)
function BytesPerScanline(PixelsPerScanline, BitsPerPixel, Alignment: Longint): Longint;
begin
Dec(Alignment);
Result := ((PixelsPerScanline * BitsPerPixel) + Alignment) and not Alignment;
Result := Result div 8;
end;
(*----------------------------------------------------------------------*
| function RotateBitmap270 |
| |
| Rotate a bitmap clockwise through 270 degrees |
| |
| Parameters: |
| bitmap The bitmap to rotate |
| |
| The function creates a rotated copy of the bitmap. |
*----------------------------------------------------------------------*)
function RotateBitmap270 (const bitmap : TBitmap) : TBitmap;
var
x, y : Integer;
ps, ps1, pr, pr1 : PRGBTriple;
bpss, bpsr : Integer;
begin
Assert (bitmap.PixelFormat = pf24Bit, 'Invalid pixel format');
result := TBitmap.Create;
try
result.PixelFormat := bitmap.PixelFormat;
result.Height := bitmap.Width;
result.Width := bitmap.Height;
ps1 := bitmap.ScanLine [0];
pr1 := result.ScanLine [bitmap.Width - 1];
bpss := BytesPerScanLine (bitmap.Width, 24, 32);
bpsr := BytesPerScanLine (result.Width, 24, 32);
for y := 0 to bitmap.Height - 1 do
begin
ps := PRGBTriple (PByte (ps1) - bpss * y);
for x := 0 to bitmap.Width - 1 do
begin
pr := PRGBTriple (PByte (pr1) + bpsr * x);
Inc (pr, y);
pr^ := ps^;
Inc (ps)
end
end;
GDIFlush
except
result.Free;
raise
end
end;
(*----------------------------------------------------------------------*
| function RotateBitmap90 |
| |
| Rotate a bitmap clockwise through 90 degrees |
| |
| Parameters: |
| bitmap The bitmap to rotate |
| |
| The function creates a rotated copy of the bitmap. |
*----------------------------------------------------------------------*)
function RotateBitmap90 (const bitmap : TBitmap) : TBitmap;
var
x, y : Integer;
ps, ps1, pr, pr1 : PRGBTriple;
bpss, bpsr : Integer;
begin
Assert (bitmap.PixelFormat = pf24Bit, 'Invalid pixel format');
result := TBitmap.Create;
try
result.PixelFormat := bitmap.PixelFormat;
result.Height := bitmap.Width;
result.Width := bitmap.Height;
ps1 := bitmap.ScanLine [bitmap.Height - 1];
pr1 := result.ScanLine [0];
bpss := BytesPerScanLine (bitmap.Width, 24, 32);
bpsr := BytesPerScanLine (result.Width, 24, 32);
for y := 0 to bitmap.Height - 1 do
begin
ps := PRGBTriple (PByte (ps1) + bpss * y);
for x := 0 to Bitmap.Width - 1 do
begin
pr := PRGBTriple (PByte (pr1) - bpsr * x);
Inc (pr, y);
pr^ := ps^;
Inc (ps)
end
end;
GDIFlush
except
result.Free;
raise
end;
end;
(*----------------------------------------------------------------------*
| function ConvertToGrayscale |
| |
| Convert a bitmap to it's greyscale equivalent |
| |
| Parameters: |
| bitmap The bitmap to convert |
| |
| The function creates a greyscale copy of the bitmap. |
*----------------------------------------------------------------------*)
function ConvertToGrayscale (const bitmap : TBitmap; TransparentColor : TColor) : TBitmap;
var
x, y : Integer;
ps, ps1, pr, pr1 : PRGBTriple;
bps : Integer;
n : Integer;
transparent : boolean;
transparentTriple : TRGBTriple;
rgb :DWORD;
begin
Assert (bitmap.PixelFormat = pf24Bit, 'Invalid pixel format');
transparent := TransparentColor <> clNone;
if transparent then
begin
rgb := ColorToRGB (TransparentColor);
transparentTriple.rgbtBlue := GetBValue (rgb);
transparentTriple.rgbtGreen := GetGValue (rgb);
transparentTriple.rgbtRed := GetRValue (rgb)
end;
result := TBitmap.Create;
try
result.PixelFormat := bitmap.PixelFormat;
result.Height := bitmap.Height;
result.Width := bitmap.Width;
ps1 := bitmap.ScanLine [0];
pr1 := result.ScanLine [0];
bps := BytesPerScanLine (bitmap.Width, 24, 32);
for y := 0 to bitmap.Height - 1 do
begin
ps := PRGBTriple (PByte (ps1) - bps * y);
pr := PRGBTriple (PByte (pr1) - bps * y);
for x := 0 to Bitmap.Width - 1 do
begin
if not Transparent
or (ps^.rgbtBlue <> transparentTriple.rgbtBlue)
or (ps^.rgbtGreen <> transparentTriple.rgbtGreen)
or (ps^.rgbtRed <> transparentTriple.rgbtRed) then
begin
n := ((DWORD (ps^.rgbtBlue) * 28) + // 11% Blue
(DWORD (ps^.rgbtRed) * 77) + // 30% Red
(DWORD (ps^.rgbtGreen) * 151)) div 256; // 59% Green
pr^.rgbtBlue := n;
pr^.rgbtGreen := n;
pr^.rgbtRed := n;
end
else
pr^ := ps^;
Inc (pr);
Inc (ps)
end
end;
GDIFlush
except
result.Free;
raise
end;
end;
(*----------------------------------------------------------------------*
| function ConvertToNegative |
| |
| Convert a bitmap to it's negative equivalent |
| |
| Parameters: |
| bitmap The bitmap to convert |
| |
| The function creates a negative copy of the bitmap. |
*----------------------------------------------------------------------*)
function ConvertToNegative (const bitmap : TBitmap) : TBitmap;
var
x, y : Integer;
ps, ps1, pr, pr1 : PRGBTriple;
bps : Integer;
begin
Assert (bitmap.PixelFormat = pf24Bit, 'Invalid pixel format');
result := TBitmap.Create;
try
result.PixelFormat := bitmap.PixelFormat;
result.Height := bitmap.Height;
result.Width := bitmap.Width;
ps1 := bitmap.ScanLine [0];
pr1 := result.ScanLine [0];
bps := BytesPerScanLine (bitmap.Width, 24, 32);
for y := 0 to bitmap.Height - 1 do
begin
ps := PRGBTriple (PByte (ps1) - bps * y);
pr := PRGBTriple (PByte (pr1) - bps * y);
for x := 0 to Bitmap.Width - 1 do
begin
pr^.rgbtBlue := 255 - ps^.rgbtBlue;
pr^.rgbtGreen := 255 - ps^.rgbtGreen;
pr^.rgbtRed := 255 - ps^.rgbtRed;
Inc (pr);
Inc (ps)
end
end;
GDIFlush
except
result.Free;
raise
end;
end;
end.
|
unit DebugInterfaces;
{ $DEFINE WRITELN_INTERFACES_QUERY}
{ $DEFINE WRITELN_INTERFACES_REFERENCE_COUNTING}
{ $DEFINE DEBUG_WRITELN_INTERFACES_REFERENCE_COUNTING_STACKTRACE}
{$DEFINE WRITELN_INTERFACES_CONSTRUCTION}
{$DEFINE WRITELN_INTERFACES_DESTRUCTION}
interface
uses
SysUtils,
NiceExceptions;
type
{ IReversibleCOM }
IReversibleCOM = interface(IUnknown) ['{41533565-D461-4D7A-AE4F-32F8D01A4800}']
function Reverse: pointer; stdcall;
end;
IHackableCOM = interface(IReversibleCOM) ['{F0E79C83-4183-474B-ADB7-0D8588BE4980}']
procedure ClearReferenceCounter; stdcall;
end;
{ TInterfaced }
TInterfaced = class(TInterfacedObject, IUnknown, IHackableCOM)
public
constructor Create; virtual;
function QueryInterface(constref iid : tguid; out obj) : longint;{$IFNDEF WINDOWS}cdecl{$ELSE}stdcall{$ENDIF};
function _AddRef : longint;{$IFNDEF WINDOWS}cdecl{$ELSE}stdcall{$ENDIF};
function _Release : longint;{$IFNDEF WINDOWS}cdecl{$ELSE}stdcall{$ENDIF};
function Reverse: pointer; stdcall;
procedure ClearReferenceCounter; stdcall;
destructor Destroy; override;
end;
implementation
{ TInterfaced }
constructor TInterfaced.Create;
begin
inherited Create;
{$IFDEF WRITELN_INTERFACES_CONSTRUCTION}
WriteLN('FACE: Constructing ' + ClassName + '....');
{$ENDIF}
end;
function TInterfaced.QueryInterface(constref iid: tguid; out obj): longint; stdcall;
begin
result := inherited QueryInterface(iid, obj);
{$IFDEF WRITELN_INTERFACES_QUERY}
WriteLN('ID: ' + ClassName + '.Query');
{$ENDIF}
end;
function TInterfaced._AddRef: longint; stdcall;
begin
result := InterLockedIncrement(fRefCount);
{$IFDEF WRITELN_INTERFACES_REFERENCE_COUNTING}
WriteLN('ID: ' + ClassName + '+REFER =' + IntToStr(RefCount));
{$IFDEF DEBUG_WRITELN_INTERFACES_REFERENCE_COUNTING_STACKTRACE}
WriteLN(GetStackTraceText);
{$ENDIF}
{$ENDIF}
end;
function TInterfaced._Release: longint; stdcall;
begin
{$IFDEF WRITELN_INTERFACES_REFERENCE_COUNTING}
WriteLN('ID: ' + ClassName + '-DEREF =' + IntToStr(RefCount - 1));
{$IFDEF DEBUG_WRITELN_INTERFACES_REFERENCE_COUNTING_STACKTRACE}
WriteLN(GetStackTraceText);
{$ENDIF}
{$ENDIF}
result := InterLockedDecrement(fRefCount);
if result = 0 then
Free;
end;
function TInterfaced.Reverse: pointer; stdcall;
begin
result := self;
end;
procedure TInterfaced.ClearReferenceCounter; stdcall;
begin
fRefCount := 0;
end;
destructor TInterfaced.Destroy;
begin
{$IFDEF WRITELN_INTERFACES_DESTRUCTION}
WriteLN('FACE: Destructing ' + ClassName + '...');
{$ENDIF}
inherited Destroy;
end;
end.
|
{******************************************}
{ }
{ FastReport v4.0 }
{ 2DBarcode object }
{ }
{ Copyright (c) 2012 }
{ by LiKejian }
{ QQ 39839655 }
{ }
{******************************************}
unit frx2DBarcode;
interface
{$I frx.inc}
uses
uZintBarcode, uZintInterface,
Windows, Messages, SysUtils, Classes, Graphics, frxClass,frxDsgnIntf
{$IFDEF Delphi6}
, Variants
{$ENDIF};
type
TfrxZintBarcodeDataFormat = (dfANSI, dfUTF8);
Type
TfrxBarcode2DEditor=class(TfrxComponentEditor)
public
//function Edit:Boolean; override;
function Edit:Boolean; override;
function HasEditor:Boolean;override;
function Execute(Tag:Integer; Checked:Boolean):Boolean; override;
procedure GetMenuItems; override;
end;
type
TfrxBarcode2DObject = class(TComponent); // fake component
TfrxBarcode2DView = class(TfrxView)
private
FBarcode : TZintBarcode;//生产条码类
FBitmap : TBitmap;//图片类
FAutoSize:Boolean;
FZoom : Single;
FDataFormat: TfrxZintBarcodeDataFormat;//数据格式
///////////////////
FText: String;
FExpression: String;
function GetType: TZBType;
procedure SetType(const Value: TZBType);
function GetZoom: Single;
procedure SetZoom(const Value: Single);
function GetDataEncoded: Widestring;
procedure SetDataFormat(const Value: TfrxZintBarcodeDataFormat);
function GetExpression:String;
procedure SetExpression(Const Value:String);
protected
procedure BarcodeChanged(Sender: TObject);
//procedure SetHeight(Value: Extended); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Draw(Canvas: TCanvas; ScaleX, ScaleY, OffsetX, OffsetY: Extended); override;
class function GetDescription: String; override;
procedure GetData; override;
published
property AutoSize: Boolean read FAutoSize write FAutoSize;
property AutoSizeZoom: Single read GetZoom write SetZoom;//
property BarcodeType : TZBType read GetType write SetType;//条码类型
property DataFormat: TfrxZintBarcodeDataFormat read FDataFormat write SetDataFormat;//数据格式
property DataField;
property DataSet;
property DataSetName;
property Expression: String read GetExpression write SetExpression;
property Frame;
property Text: String read FText write FText;
end;
Procedure InitializeFastReport;
Procedure FinalizeFastReport;
implementation
uses
frx2DBarcodeRTTI, frxRes, frxUtils;
function TfrxBarcode2DEditor.Edit:Boolean;
var
s: String;
Begin
Result := True;
s:=TfrxBarcode2DView(Component).Expression;
s := TfrxCustomDesigner(Designer).InsertExpression(s);
if s <> '' then
TfrxBarcode2DView(Component).Expression:=s;
End;
function TfrxBarcode2DEditor.HasEditor:Boolean;
Begin
Result:=True;
End;
function TfrxBarcode2DEditor.Execute(Tag:Integer; Checked:Boolean):Boolean;
Begin
Result := True;
End;
procedure TfrxBarcode2DEditor.GetMenuItems;
Begin
AddItem('About', 1, False);
End;
function TfrxBarcode2DView.GetType: TZBType;
Begin
Result:=FBarcode.BarcodeType;
End;
procedure TfrxBarcode2DView.SetType(const Value: TZBType);
Begin
FBarcode.BarcodeType:=Value;
End;
function TfrxBarcode2DView.GetZoom: Single;
Begin
Result:=FZoom;
End;
procedure TfrxBarcode2DView.SetZoom(const Value: Single);
Begin
FZoom:=Value;
BarcodeChanged(self);
Self.Width:=Round(FBitmap.Width);
Self.Height:=Round(FBitmap.Height);
End;
function TfrxBarcode2DView.GetDataEncoded: Widestring;
Begin
case FDataFormat of
dfANSI: Result:=ansistring(FText);
dfUTF8: Result:=UTF8Decode(FText);
end;
End;
procedure TfrxBarcode2DView.SetDataFormat(const Value: TfrxZintBarcodeDataFormat);
var
ws : WideString;
begin
FDataFormat := Value;
ws:=GetDataEncoded;
if ws<>EmptyWideStr then
FBarcode.Data:=ws;
End;
function TfrxBarcode2DView.GetExpression:String;
Begin
Result:=FExpression;
End;
procedure TfrxBarcode2DView.SetExpression(Const Value:String);
Begin
{$IFNDEF NO_EDITORS}
FExpression:=Value;
{$ENDIF}
End;
procedure TfrxBarcode2DView.BarcodeChanged(Sender: TObject);
Begin
FBarcode.OnChanged:=nil;
try
FBarcode.Height:=Round(Self.Height / FZoom / 2);
FBarcode.GetBarcode(FBitmap);
finally
FBarcode.OnChanged:=Self.BarcodeChanged;
end;
End;
constructor TfrxBarcode2DView.Create(AOwner: TComponent);
begin
inherited;
FZoom:=1;
FBitmap:=TBitmap.Create;
FBarcode:=TZintBarcode.Create;
FAutoSize:=True;
BarcodeChanged(nil);
FBarcode.OnChanged:=BarcodeChanged;
FBarcode.BarcodeType:=tBARCODE_QRCODE;
FDataFormat:=dfANSI;
FText:=FBarcode.Data;
Self.Width:=1*32;
Self.Height:=1*32;
end;
destructor TfrxBarcode2DView.Destroy;
Begin
FreeAndNil(FBarcode);
FreeAndNil(FBitmap);
inherited;
End;
class function TfrxBarcode2DView.GetDescription: String;
begin
Result := '2D 条形码对象';
end;
procedure TfrxBarcode2DView.Draw(Canvas: TCanvas; ScaleX, ScaleY, OffsetX,
OffsetY: Extended);
var
ws : WideString;
begin
inherited;
ws:=GetDataEncoded;
if ws<>EmptyWideStr then
FBarcode.Data:=ws;
if FAutoSize then
Begin//自动大小
Canvas.StretchDraw(Rect(FX,
FY,
FX+Round(FBitmap.Width * ScaleX * FZoom),
FY+Round(FBitmap.Height * ScaleY * FZoom)),
FBitmap);
Self.Width:=Round(FBitmap.Width);
Self.Height:=Round(FBitmap.Height);
End Else Begin
BeginDraw(Canvas, ScaleX, ScaleY, OffsetX, OffsetY);
frxDrawGraphic(Canvas, Rect(FX, FY, FX1, FY1), FBitmap, IsPrinting); //, False, False, 0);
End;
end;
procedure TfrxBarcode2DView.GetData;
begin
inherited;
if FExpression <> '' then
FText := VarToStr(Report.Calc(FExpression))
Else if IsDataField then
FText := VarToStr(DataSet.Value[DataField])
end;
Procedure InitializeFastReport;
Begin
frxObjects.RegisterObject1(TfrxBarcode2DView, nil, '', '', 0, 23);
{$IFNDEF NO_EDITORS}
frxComponentEditors.Register(TfrxBarcode2DView,TfrxBarcode2DEditor);
{$ENDIF}
End;
Procedure FinalizeFastReport;
Begin
frxObjects.UnRegister(TfrxBarcode2DView);
{$IFNDEF NO_EDITORS}
frxComponentEditors.UnRegister(TfrxBarcode2DEditor);
{$ENDIF}
End;
initialization
InitializeFastReport;
finalization
FinalizeFastReport
end.
|
{$include kode.inc}
unit fx_gain;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_plugin,
kode_types;
type
myPlugin = class(KPlugin)
private
FLeft : Single;
FRight : Single;
public
procedure on_Create; override;
procedure on_ParameterChange(AIndex:LongWord; AValue:Single); override;
procedure on_ProcessSample(AInputs,AOutputs:PPSingle); override;
end;
KPluginClass = myPlugin;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
_plugin_id,
kode_const,
kode_debug,
kode_flags,
kode_parameter,
kode_utils;
//----------
procedure myPlugin.on_Create;
begin
// config
FName := 'fx_gain';
FAuthor := 'skei.audio';
FProduct := FName;
FVersion := 0;
FUniqueId := KODE_MAGIC + fx_gain_id;
KSetFlag(FFlags,kpf_perSample);
// parameters
appendParameter( KParamFloat.create('left', 1, 0, 2 ) );
appendParameter( KParamFloat.create('right',1, 0, 2 ) );
// plugin
FLeft := 0;
FRight := 0;
end;
//----------
procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single);
begin
case AIndex of
0 : FLeft := AValue;
1 : FRight := AValue;
end;
end;
//----------
procedure myPlugin.on_processSample(AInputs,AOutputs:PPSingle);
begin
AOutputs[0]^ := AInputs[0]^ * FLeft;
AOutputs[1]^ := AInputs[1]^ * FRight;
end;
//----------------------------------------------------------------------
end.
|
unit UFormCopySettings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Spin, ComCtrls, UIconUtil, Math, UFormUtil;
type
TfrmCopySetting = class(TForm)
lvBackupCopy: TListView;
lbBackupCopy: TLabel;
btnOK: TButton;
spCopyCount: TSpinEdit;
procedure FormCreate(Sender: TObject);
procedure lvBackupCopyChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure lvBackupCopyDeletion(Sender: TObject; Item: TListItem);
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
LvBackupCopy_FileCount = 0;
LvBackupCopy_Size = 1;
LvBackupCopy_CopyCount = 2;
var
frmCopySetting: TfrmCopySetting;
implementation
uses UBackupInfoFace, UBackupInfoControl;
{$R *.dfm}
procedure TfrmCopySetting.btnOKClick(Sender: TObject);
var
CopyCount, i : Integer;
ItemData : TLvBackupCopyData;
FullPath : string;
begin
CopyCount := spCopyCount.Value;
for i := 0 to lvBackupCopy.Items.Count - 1 do
if lvBackupCopy.Items[i].Selected then
begin
lvBackupCopy.Items[i].SubItems[ LvBackupCopy_CopyCount ] := IntToStr( CopyCount );
ItemData := lvBackupCopy.Items[i].Data;
FullPath := ItemData.FullPath;
MyBackupFileControl.ReSetBackupCopyCount( FullPath, CopyCount );
end;
end;
procedure TfrmCopySetting.FormCreate(Sender: TObject);
begin
lvBackupCopy.SmallImages := MyIcon.getSysIcon;
ListviewUtil.BindSort( lvBackupCopy );
end;
procedure TfrmCopySetting.lvBackupCopyChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
var
IsSelected : Boolean;
i, MinCount : Integer;
ItemData : TLvBackupCopyData;
begin
IsSelected := lvBackupCopy.Selected <> nil;
lbBackupCopy.Enabled := IsSelected;
spCopyCount.Enabled := IsSelected;
btnOK.Enabled := IsSelected;
if not IsSelected then
Exit;
MinCount := 1000;
for i := 0 to lvBackupCopy.Items.Count - 1 do
if lvBackupCopy.Items[i].Selected then
begin
ItemData := lvBackupCopy.Items[i].Data;
MinCount := Min( ItemData.CopyCount, MinCount );
end;
spCopyCount.Value := MinCount;
end;
procedure TfrmCopySetting.lvBackupCopyDeletion(Sender: TObject;
Item: TListItem);
var
Data : TObject;
begin
Data := Item.Data;
Data.Free;
end;
end.
|
unit MyObjectsU;
interface
type
TPerson = class
private
FFirstName: String;
FLastName: String;
FAge: Integer;
procedure SetFirstName(const Value: String);
procedure SetLastName(const Value: String);
procedure SetAge(const Value: Integer);
public
constructor Create(AFirstName, ALastName: String; AAge: Integer); virtual;
property FirstName: String read FFirstName write SetFirstName;
property LastName: String read FLastName write SetLastName;
property Age: Integer read FAge write SetAge;
end;
implementation
{ TPerson }
constructor TPerson.Create(AFirstName, ALastName: string; AAge: Integer);
begin
inherited Create;
FFirstName := AFirstName;
FLastName := ALastName;
FAge := AAge;
end;
procedure TPerson.SetAge(const Value: Integer);
begin
FAge := Value;
end;
procedure TPerson.SetFirstName(const Value: String);
begin
FFirstName := Value;
end;
procedure TPerson.SetLastName(const Value: String);
begin
FLastName := Value;
end;
end.
|
unit Base.uControllerBase;
interface
uses
Datasnap.DSProviderDataModuleAdapter;
type
TMessage = (tmOK, tmNotFound, tmObjectAlreadyExists, tmUnprocessableEntity, tmUndefinedError);
TControllerBase = class(TDSServerModule)
protected
procedure ConfigurarResponse(pMessage: TMessage);
end;
implementation
uses
Data.DBXPlatform;
{ TControllerBase }
procedure TControllerBase.ConfigurarResponse(pMessage: TMessage);
begin
case pmessage of
tmOK:
begin
GetInvocationMetadata.ResponseCode := 200;
GetInvocationMetadata.ResponseMessage := 'OK!';
end;
tmNotFound:
begin
GetInvocationMetadata.ResponseCode := 400;
GetInvocationMetadata.ResponseMessage := 'Not found!';
end;
tmObjectAlreadyExists:
begin
GetInvocationMetadata.ResponseCode := 400;
GetInvocationMetadata.ResponseMessage := 'Object already exists!';
end;
tmUnprocessableEntity:
begin
GetInvocationMetadata.ResponseCode := 422;
GetInvocationMetadata.ResponseMessage := 'Unprocessable entity!';
end;
tmUndefinedError:
begin
GetInvocationMetadata.ResponseCode := 400;
GetInvocationMetadata.ResponseMessage := 'Undefined error!';
end;
end;
end;
end.
|
unit uWordy;
interface
uses System.SysUtils, RegularExpressions, System.Generics.Collections;
type
EInvalidProblem = Class(Exception);
TWordy = Class
private
type
TParsedProblem = record
X: integer;
Operation1: string;
Y: integer;
Operation2: string;
Z: integer;
constructor create(parsedGroups: TGroupCollection);
end;
class var Operations: TDictionary<string, TFunc<integer, integer, integer>>;
class var VariableAndOperatorGroupsRegex: TRegex;
class procedure buildOperations;
class procedure buildVariableAndOperatorGroupsRegex;
class function ParseProblem(aProblem: string): TParsedProblem;
public
class function Answer(aQuestion: string): integer;
end;
implementation
uses Math;
{ TWordy }
class function TWordy.Answer(aQuestion: string): integer;
var ParsedProblem: TParsedProblem;
Operation: TFunc<integer, integer, integer>;
firstPass: integer;
begin
if not assigned(Operations) then
begin
buildOperations;
buildVariableAndOperatorGroupsRegex;
end;
ParsedProblem := ParseProblem(aQuestion);
Operation := Operations[ParsedProblem.Operation1];
firstPass := Operation(ParsedProblem.X, ParsedProblem.Y);
if ParsedProblem.Operation2.IsEmpty then
result := firstPass
else
begin
Operation := Operations[ParsedProblem.Operation2];
result := Operation(firstPass, ParsedProblem.Z);
end;
end;
class procedure TWordy.BuildOperations;
begin
Operations := TDictionary<string, TFunc<integer, integer, integer>>.Create;
Operations.Add('plus',
function(X: integer; Y: integer): integer
begin
result := X + Y;
end);
Operations.Add('minus',
function(X: integer; Y: integer): integer
begin
result := X - Y;
end);
Operations.Add('multiplied by',
function(X: integer; Y: integer): integer
begin
result := X * Y;
end);
Operations.Add('divided by',
function(X: integer; Y: integer): integer
begin
result := X div Y;
end);
end;
class procedure TWordy.buildVariableAndOperatorGroupsRegex;
begin
VariableAndOperatorGroupsRegex := TRegex.Create(format('%0:s %1:s %0:s\s*%1:s*\s*%0:s*',
['(-?\d+)','(plus|minus|multiplied by|divided by)']));
end;
class function TWordy.ParseProblem(aProblem: string): TParsedProblem;
var Match: TMatch;
begin
Match := VariableAndOperatorGroupsRegex.Match(aProblem);
if Match.Groups.Count = 0 then
raise EInvalidProblem.Create('Invalid Problem');
result := TParsedProblem.create(Match.Groups);
end;
{ TWordy.TParsedProblem }
constructor TWordy.TParsedProblem.create(parsedGroups: TGroupCollection);
var i: integer;
parsedItems: TList<string>;
parsedItemsArray: TArray<string>;
begin
parsedItems := TList<string>.Create;
for i := 1 to parsedGroups.Count - 1 do
begin
if parsedGroups[i].Success then
parsedItems.Add(parsedGroups[i].Value)
else
parsedItems.Add('');
end;
parsedItemsArray := parsedItems.ToArray;
Setlength(parsedItemsArray, 5);
X := parsedItemsArray[0].ToInteger;
Operation1 := parsedItemsArray[1];
Y := parsedItemsArray[2].ToInteger;
Operation2 := parsedItemsArray[3];
if parsedItemsArray[4] <> '' then
Z := parsedItemsArray[4].ToInteger
else
Z := 0;
end;
end.
|
unit uMain;
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.Controls.Presentation, FMX.Layouts,
FMX.ListBox;
type
TFormMain = class(TForm)
lbListInfo: TListBox;
ToolBar1: TToolBar;
Label1: TLabel;
sbLoadInfo: TSpeedButton;
procedure sbLoadInfoClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FPermissionReadPhoneState: string;
procedure AddListItem(const AText, ADetail: string);
procedure AddListHeader(const AText: string);
procedure LoadInfo;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
uses
System.Permissions, Androidapi.Helpers, Androidapi.JNI.JavaTypes, Androidapi.JNI.Os, Androidapi.JNI.Provider,
Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI, Androidapi.JNI.Bluetooth;
procedure TFormMain.AddListHeader(const AText: string);
var
ListBoxGroupHeader: TListBoxGroupHeader;
begin
ListBoxGroupHeader := TListBoxGroupHeader.Create(lbListInfo);
ListBoxGroupHeader.Text := AText;
lbListInfo.AddObject(ListBoxGroupHeader);
end;
procedure TFormMain.AddListItem(const AText, ADetail: string);
var
ListBoxItem: TListBoxItem;
begin
ListBoxItem := TListBoxItem.Create(lbListInfo);
ListBoxItem.Text := AText;
ListBoxItem.ItemData.Detail := ADetail;
lbListInfo.AddObject(ListBoxItem);
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
FPermissionReadPhoneState := JStringToString(TJManifest_permission.JavaClass.READ_PHONE_STATE);
end;
procedure TFormMain.LoadInfo;
var
SDK_INT, I, J, K: Integer;
DeviceName: JString;
BTAdapter: JBluetoothAdapter;
SUPPORTED_32_BIT_ABIS, SUPPORTED_64_BIT_ABIS, SUPPORTED_ABIS: TJavaObjectArray<JString>;
StrSUPPORTED_32, StrSUPPORTED_64, StrSUPPORTED_ABIS: string;
begin
SDK_INT := TJBuild_VERSION.JavaClass.SDK_INT;
if SDK_INT < 17 then
DeviceName := TJSettings_System.JavaClass.getString(TAndroidHelper.ContentResolver, StringToJstring('device_name'))
else
DeviceName := TJSettings_Global.JavaClass.getString(TAndroidHelper.ContentResolver, StringToJstring('device_name'));
if DeviceName = nil then
begin
// android.Manifest.permission.BLUETOOTH
BTAdapter := TJBluetoothAdapter.JavaClass.getDefaultAdapter;
DeviceName := BTAdapter.getName;
end;
lbListInfo.Clear;
lbListInfo.BeginUpdate;
AddListHeader('Settings API');
AddListItem('DEVICE_NAME', JStringToString(DeviceName));
AddListHeader('Build API');
AddListItem('BOARD', JStringToString(TJBuild.JavaClass.BOARD)); // API 1
AddListItem('BOOTLOADER', JStringToString(TJBuild.JavaClass.BOOTLOADER)); // API 8
AddListItem('BRAND', JStringToString(TJBuild.JavaClass.BRAND)); // API 1
if SDK_INT <= 21 then
begin
AddListItem('CPU_ABI', JStringToString(TJBuild.JavaClass.CPU_ABI)); // API 4 - Depr. API 21 (Use SUPPORTED_ABIS)
AddListItem('CPU_ABI2', JStringToString(TJBuild.JavaClass.CPU_ABI2)); // API 8 - Depr. API 21 (Use SUPPORTED_ABIS)
end;
AddListItem('DEVICE', JStringToString(TJBuild.JavaClass.DEVICE)); // API 1
AddListItem('DISPLAY', JStringToString(TJBuild.JavaClass.DISPLAY)); // API 3
AddListItem('FINGERPRINT', JStringToString(TJBuild.JavaClass.FINGERPRINT)); // API 1
AddListItem('HARDWARE', JStringToString(TJBuild.JavaClass.HARDWARE)); // API 8
AddListItem('ID', JStringToString(TJBuild.JavaClass.ID)); // API 1
AddListItem('MANUFACTURER', JStringToString(TJBuild.JavaClass.MANUFACTURER)); // API 4
AddListItem('MODEL', JStringToString(TJBuild.JavaClass.MODEL)); // API 1
AddListItem('PRODUCT', JStringToString(TJBuild.JavaClass.PRODUCT)); // API 1
if SDK_INT <= 15 then
AddListItem('RADIO', JStringToString(TJBuild.JavaClass.RADIO)) // API 8 - Deprecated API 15 (Use getRadioVersion())
else
AddListItem('RADIO', JStringToString(TJBuild.JavaClass.getRadioVersion));
if SDK_INT <= 26 then
AddListItem('SERIAL', JStringToString(TJBuild.JavaClass.SERIAL)) // API 9 - Deprecated API 26 (Use getSerial())
else
// android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE
AddListItem('SERIAL', JStringToString(TJBuild.JavaClass.getSerial));
if SDK_INT >= 21 then
begin
SUPPORTED_32_BIT_ABIS := TJBuild.JavaClass.SUPPORTED_32_BIT_ABIS; // API 21
SUPPORTED_64_BIT_ABIS := TJBuild.JavaClass.SUPPORTED_64_BIT_ABIS; // API 21
SUPPORTED_ABIS := TJBuild.JavaClass.SUPPORTED_ABIS; // API 21
StrSUPPORTED_32 := '';
for I := 0 to SUPPORTED_32_BIT_ABIS.Length - 1 do
StrSUPPORTED_32 := StrSUPPORTED_32 + JStringToString(SUPPORTED_32_BIT_ABIS.Items[I]) + ' ';
StrSUPPORTED_64 := '';
for J := 0 to SUPPORTED_64_BIT_ABIS.Length - 1 do
StrSUPPORTED_64 := StrSUPPORTED_64 + JStringToString(SUPPORTED_64_BIT_ABIS.Items[J]) + ' ';
StrSUPPORTED_ABIS := '';
for K := 0 to SUPPORTED_ABIS.Length - 1 do
StrSUPPORTED_ABIS := StrSUPPORTED_ABIS + JStringToString(SUPPORTED_ABIS.Items[K]) + ' ';
AddListItem('SUPPORTED_32_BIT_ABIS', StrSUPPORTED_32);
AddListItem('SUPPORTED_64_BIT_ABIS', StrSUPPORTED_64);
AddListItem('SUPPORTED_ABIS', StrSUPPORTED_ABIS);
end;
AddListItem('TAGS', JStringToString(TJBuild.JavaClass.TAGS)); // API 1
AddListItem('TIME', TJBuild.JavaClass.TIME.ToString); // API 1
AddListItem('TYPE', JStringToString(TJBuild.JavaClass.&TYPE)); // API 1
AddListItem('USER', JStringToString(TJBuild.JavaClass.USER)); // API 1
AddListHeader('Build.VERSION API');
if SDK_INT >= 23 then
AddListItem('BASE_OS', JStringToString(TJBuild_VERSION.JavaClass.BASE_OS)); // API 23
AddListItem('CODENAME', JStringToString(TJBuild_VERSION.JavaClass.CODENAME)); // API 4
AddListItem('INCREMENTAL', JStringToString(TJBuild_VERSION.JavaClass.INCREMENTAL)); // API 1
if SDK_INT >= 23 then
AddListItem('PREVIEW_SDK_INT', TJBuild_VERSION.JavaClass.PREVIEW_SDK_INT.ToString); // API 23
AddListItem('RELEASE', JStringToString(TJBuild_VERSION.JavaClass.RELEASE)); // API 1
if SDK_INT <= 15 then
AddListItem('SDK', JStringToString(TJBuild_VERSION.JavaClass.SDK)); // API 1 - Deprecated API 15 (Use SDK_INT)
AddListItem('SDK_INT', TJBuild_VERSION.JavaClass.SDK_INT.ToString); // API 4
if SDK_INT >= 23 then
AddListItem('SECURITY_PATCH', JStringToString(TJBuild_VERSION.JavaClass.SECURITY_PATCH)); // API 23
lbListInfo.EndUpdate;
end;
procedure TFormMain.sbLoadInfoClick(Sender: TObject);
begin
PermissionsService.RequestPermissions([FPermissionReadPhoneState],
procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>)
begin
if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
LoadInfo
else
ShowMessage('Permission Denied');
end);
end;
end.
|
unit App1MainControllerU;
interface
{$I dmvcframework.inc}
uses MVCFramework,
MVCFramework.Logger,
MVCFramework.Commons,
Web.HTTPApp;
type
[MVCPath('/')]
TApp1MainController = class(TMVCController)
public
[MVCPath('/')]
[MVCHTTPMethod([httpGET])]
procedure Index;
[MVCPath('/hello')]
[MVCHTTPMethod([httpGET])]
procedure HelloWorld;
[MVCPath('/hello')]
[MVCHTTPMethod([httpPOST])]
procedure HelloWorldPost;
[MVCPath('/div/($par1)/($par2)')]
[MVCHTTPMethod([httpGET])]
procedure RaiseException(par1, par2: string);
end;
implementation
uses
System.SysUtils,
MVCFramework.SystemJSONUtils,
MVCFramework.TypesAliases;
{ TApp1MainController }
procedure TApp1MainController.HelloWorld;
begin
Render('Hello World called with GET');
if Context.Request.ThereIsRequestBody then
Log.Info('Body:' + Context.Request.Body, 'basicdemo');
end;
procedure TApp1MainController.HelloWorldPost;
var
JSON: TJSONObject;
begin
JSON := TSystemJSON.StringAsJSONObject(Context.Request.Body);
try
JSON.AddPair('modified', 'from server');
Render(JSON, false);
finally
JSON.Free;
end;
Log.Info('Hello world called with POST', 'basicdemo');
end;
procedure TApp1MainController.Index;
begin
Redirect('index.html');
end;
procedure TApp1MainController.RaiseException(par1, par2: string);
var
R: Extended;
begin
Log.Info('Parameter1=' + QuotedStr(par1), 'basicdemo');
Log.Info('Parameter2=' + QuotedStr(par2), 'basicdemo');
R := StrToInt(par1) / StrToInt(par2);
Render(TJSONObject.Create(TJSONPair.Create('result', TJSONNumber.Create(R))));
end;
end.
|
{*******************************************************************************
作者: dmzn 2009-11-28
描述: 动画编辑器
*******************************************************************************}
unit UFrameAnimate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
UMovedItems, UFrameBase, ULibFun, GIFImage, StdCtrls, ImgList, ComCtrls,
Dialogs, ToolWin, ExtCtrls, Buttons;
type
TfFrameAnimate = class(TfFrameBase)
Group2: TGroupBox;
ListInfo: TListBox;
OpenDialog1: TOpenDialog;
BtnOpen: TSpeedButton;
Image1: TImage;
Bevel1: TBevel;
EditSpeed: TComboBox;
Label1: TLabel;
Check1: TCheckBox;
procedure BtnOpenClick(Sender: TObject);
procedure EditSpeedChange(Sender: TObject);
procedure Check1Click(Sender: TObject);
protected
{ Private declarations }
FAnimateItem: TAnimateMovedItem;
{*待编辑对象*}
procedure UpdateWindow; override;
{*更新窗口*}
procedure DoCreate; override;
procedure DoDestroy; override;
{*基类动作*}
procedure OnItemDBClick(Sender: TObject);
{*组件双击*}
procedure LoadAnimateInfo;
{*动画信息*}
public
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
USysConst, UMgrLang;
//------------------------------------------------------------------------------
procedure TfFrameAnimate.DoCreate;
begin
inherited;
end;
//Desc: 释放资源
procedure TfFrameAnimate.DoDestroy;
begin
inherited;
end;
//Desc: 更新窗口信息
procedure TfFrameAnimate.UpdateWindow;
var nIdx: integer;
begin
inherited;
FMovedItem.OnDblClick := OnItemDBClick;
FAnimateItem := TAnimateMovedItem(FMovedItem);
Check1.Checked := FAnimateItem.Reverse;
EditSpeed.Clear;
for nIdx:=1 to 16 do EditSpeed.Items.Add(IntToStr(nIdx));
LoadAnimateInfo;
end;
//------------------------------------------------------------------------------
//Desc: 插入图片
procedure TfFrameAnimate.BtnOpenClick(Sender: TObject);
var nStr: string;
begin
with TOpenDialog.Create(Application) do
begin
Title := ML('选择动画', sMLFrame);
Filter := ML('动画图片(*.gif)|*.gif');
if Execute then nStr := FileName else nStr := '';
Free;
end;
if FileExists(nStr) then
begin
FAnimateItem.ImageFile := nStr;
LoadAnimateInfo;
FAnimateItem.Invalidate;
end;
end;
//Desc: 图片信息
procedure TfFrameAnimate.LoadAnimateInfo;
begin
if not EditSpeed.Focused then
Image1.Visible := False;
ListInfo.Clear;
with FAnimateItem,ListInfo do
if PicNum > 0 then
begin
gMultiLangManager.SectionID := sMLFrame;
Items.Add(Format(ML('动画来源: %s'), [ImageFile]));
Items.Add(Format(ML('有效帧数: %d'), [PicNum]));
Items.Add(Format(ML('播放速度: %d帧/秒'), [Speed]));
Items.Add(Format(ML('原始大小: %d x %d'), [ImageWH.Right, ImageWH.Bottom]));
EditSpeed.ItemIndex := EditSpeed.Items.IndexOf(IntToStr(Speed));
Image1.Picture.LoadFromFile(ImageFile);
Image1.Visible := True;
end;
end;
procedure TfFrameAnimate.EditSpeedChange(Sender: TObject);
begin
if EditSpeed.ItemIndex > -1 then
begin
FAnimateItem.Speed := StrToInt(EditSpeed.Text);
LoadAnimateInfo;
end;
end;
procedure TfFrameAnimate.OnItemDBClick(Sender: TObject);
begin
BtnOpenClick(nil);
end;
procedure TfFrameAnimate.Check1Click(Sender: TObject);
begin
FAnimateItem.Reverse := Check1.Checked;
end;
end.
|
{ File : SaveBMP2.pas
Author : Deniz Oezmen, based on work by Christian Klaessen and Tobias Post
Created: 1999-12-11
Changed: 2005-10-01
Library providing various functions to export data as a standard Windows
bitmap file.
}
unit SaveBMP2;
interface
const
Version = $0501;
Build = $0000;
Author = 'T. Post, C. Klaessen and D. Oezmen, 1999-2005';
type
TColor = packed record
B, G, R, A: Byte
end;
TColor3 = packed record
B, G, R: Byte;
end;
TPalette = packed array[0..255] of TColor;
TPalette3 = packed array[0..255] of TColor3;
TBitmapFileHeader = packed record
bfType : Word; {UINT : Erkennungsstring = 'BM'}
bfSize : Longint; {DWORD : GrӇe der Bitmapdatei}
bfReserved1, {UINT : Reserviert1 = 0}
bfReserved2: Word; {UINT : Reserviert2 = 0}
bfOffBits : Longint {DWORD : Beginn (Offset) der Bilddaten}
end;
TBitmapInfoHeader = packed record
biSize, {DWORD : GrӇe des BMIH}
biWidth, {LONG : Breite des Bildes}
biHeight : Longint; {LONG : H”he des Bildes}
biPlanes, {WORD : Bildebenen? = 1}
biBitCount : Word; {WORD : Bits pro Pixel = 1/4/8/24}
biCompression, {DWORD : Komprimierung = 0/1}
biSizeImage, {DWORD : GrӇe der Bilddaten}
biXPelsPerMeter, {LONG : X-Pixelanzahl pro Meter}
biYPelsPerMeter, {LONG : Y-Pixelanzahl pro Meter}
biClrUsed, {DWORD : Farbanzahl in Farbpalette}
biClrImportant : Longint {DWORD : Bits Pro Pixel des Grafiktreibers}
END;
TBMPFile = packed record
BMPFile : file;
FileHeader: TBitmapFileHeader;
InfoHeader: TBitmapInfoHeader
end;
procedure OpenBMP(var BMP: TBMPFile; BMPName: string; XRes, YRes: Longint);
procedure WritePixelToBMP(BMP: TBMPFile; x, y: Longint; R, G, B: Byte);
procedure CloseBMP(BMP: TBMPFile);
procedure Dump8BitBMP(BMPName: string; XRes, YRes: Longint; Palette: TPalette;
Content: Pointer); overload;
procedure Dump8BitBMP(BMPName: string; XRes, YRes: Longint;
Palette3: TPalette3; Content: Pointer); overload;
implementation
procedure PrepareBMP(var BMP: TBMPFile; BMPName: string; XRes, YRes: Longint;
Bits: Word);
var
ScanX,
ScanY : Longint;
begin
Assign(BMP.BMPFile, BMPName);
Rewrite(BMP.BMPFile, 1);
ScanX := XRes;
ScanY := YRes;
ScanX := (ScanX div 4 + Byte(ScanX mod 4 > 0)) * 4;
with BMP.FileHeader do
begin
bfType := Ord('B') + Ord('M') * 256;
bfSize := SizeOf(BMP.FileHeader) + SizeOf(BMP.InfoHeader) +
3 * ScanX * ScanY;
bfReserved1 := $00;
bfReserved2 := $00;
bfOffBits := SizeOf(BMP.FileHeader) + SizeOf(BMP.InfoHeader)
end;
with BMP.InfoHeader do
begin
biSize := SizeOf(BMP.InfoHeader);
biWidth := XRes;
biHeight := YRes;
biPlanes := $01;
biBitCount := Bits;
biCompression := $0000;
biSizeImage := 3 * ScanX * ScanY;
biXPelsPerMeter := $0000;
biYPelsPerMeter := $0000;
biClrUsed := $0000;
biClrImportant := $0000
end;
BlockWrite(BMP.BMPFile, BMP.FileHeader, SizeOf(BMP.FileHeader));
BlockWrite(BMP.BMPFile, BMP.InfoHeader, SizeOf(BMP.InfoHeader))
end;
procedure Prepare8BitBMP(var BMP: TBMPFile; BMPName: string;
XRes, YRes: Longint; Bits: Word);
var
ScanX,
ScanY : Longint;
begin
Assign(BMP.BMPFile, BMPName);
Rewrite(BMP.BMPFile, 1);
ScanX := XRes;
ScanY := YRes;
ScanX := (ScanX div 4 + Byte(ScanX mod 4 > 0)) * 4;
with BMP.FileHeader do
begin
bfType := Ord('B') + Ord('M') * 256;
bfSize := SizeOf(BMP.FileHeader) + SizeOf(BMP.InfoHeader) +
SizeOf(TPalette) + ScanX * ScanY;
bfReserved1 := $00;
bfReserved2 := $00;
bfOffBits := SizeOf(BMP.FileHeader) + SizeOf(BMP.InfoHeader) +
SizeOf(TPalette);
end;
with BMP.InfoHeader do
begin
biSize := SizeOf(BMP.InfoHeader);
biWidth := XRes;
biHeight := YRes;
biPlanes := $01;
biBitCount := Bits;
biCompression := $0000;
biSizeImage := 3 * ScanX * ScanY;
biXPelsPerMeter := $0000;
biYPelsPerMeter := $0000;
biClrUsed := $0000;
biClrImportant := $0000
end;
BlockWrite(BMP.BMPFile, BMP.FileHeader, SizeOf(BMP.FileHeader));
BlockWrite(BMP.BMPFile, BMP.InfoHeader, SizeOf(BMP.InfoHeader))
end;
procedure FillBMP(BMP: TBMPFile);
var
i : Longint;
Buffer: array[0..10239] of Byte;
begin
for i := 0 to SizeOf(Buffer) - 1 do
Buffer[i] := 0;
for i := 1 to BMP.InfoHeader.biSizeImage div SizeOf(Buffer) do
BlockWrite(BMP.BMPFile, Buffer, SizeOf(Buffer));
BlockWrite(BMP.BMPFile, Buffer,
BMP.InfoHeader.biSizeImage mod SizeOf(Buffer))
end;
procedure OpenBMP(var BMP: TBMPFile; BMPName: string; XRes, YRes: Longint);
begin
PrepareBMP(BMP, BMPName, XRes, YRes, 24);
FillBMP(BMP)
end;
procedure Dump8BitBMP(BMPName: string; XRes, YRes: Longint; Palette: TPalette;
Content: Pointer);
var
BMP : TBMPFile;
Line : Pointer;
y,
Width: Word;
begin
Prepare8BitBMP(BMP, BMPName, XRes, YRes, 8);
BlockWrite(BMP.BMPFile, Palette, SizeOf(Palette));
Width := BMP.InfoHeader.biWidth;
Width := (Width div 4 + Byte(Width mod 4 > 0)) * 4;
GetMem(Line, Width);
FillChar(Line^, Width, 0);
for y := BMP.InfoHeader.biHeight - 1 downto 0 do
begin
Move(Pointer(Longint(Content) + (y * BMP.InfoHeader.biWidth))^,
Line^, BMP.InfoHeader.biWidth);
BlockWrite(BMP.BMPFile, Line^, Width)
end;
FreeMem(Line, Width);
CloseBMP(BMP)
end;
procedure ConvertPalette3toPalette(Palette3: TPalette3; var Palette: TPalette);
var
i: Byte;
begin
for i := 0 to 255 do
begin
Palette[i].B := Palette3[i].B;
Palette[i].G := Palette3[i].G;
Palette[i].R := Palette3[i].R;
Palette[i].A := 200
end
end;
procedure Dump8BitBMP(BMPName: string; XRes, YRes: Longint; Palette3: TPalette3;
Content: Pointer);
var
Palette: TPalette;
begin
ConvertPalette3ToPalette(Palette3, Palette);
Dump8BitBMP(BMPName, XRes, YRes, Palette, Content)
end;
procedure WritePixelToBMP(BMP: TBMPFile; x, y: Longint; R, G, B: Byte);
var
Color: record
B, G, R: Byte
end;
XRes,
YRes : Longint;
begin
Color.R := R;
Color.G := G;
Color.B := B;
XRes := Longint(BMP.InfoHeader.biWidth);
YRes := Longint(BMP.InfoHeader.biHeight);
Seek(BMP.BMPFile, $0036 + (YRes - y - 1) * 3 * XRes +
(YRes - y - 1) * (XRes mod 4) + 3 * x);
BlockWrite(BMP.BMPFile, Color, SizeOf(Color))
end;
procedure CloseBMP(BMP : TBMPFile);
begin
Close(BMP.BMPFile)
end;
begin
end.
|
{
图片状态,从上向下,从中间拉伸
}
unit uJxdGpCommon;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, GDIPAPI, GDIPOBJ, uJxdGpStyle, uJxdGpBasic;
type
TOnSubItem = procedure(const Ap: PDrawInfo) of object;
{$M+}
TxdGpCommon = class(TxdGraphicsBasic)
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
protected
//子类实现
procedure DrawGraphics(const AGh: TGPGraphics); override;
procedure DoControlStateChanged(const AOldState, ANewState: TxdGpUIState; const ACurPt: TPoint); override;
{Common类一般实现}
procedure DrawCaption(const AGh: TGPGraphics);
{子类可能需要去重新实现的函数}
function DoGetDrawState(const Ap: PDrawInfo): TxdGpUIState; virtual;
{使用 DrawImageCommon 函数来绘制,需要实现的几个事件, DoGetDrawState}
function DoIsDrawSubItem(const Ap: PDrawInfo): Boolean; virtual;
procedure DoDrawSubItemText(const AGh: TGPGraphics; const AText: string; const AR: TGPRectF; const AItemState: TxdGpUIState); virtual;
procedure DoChangedSrcBmpRect(const AState: TxdGpUIState; var ASrcBmpRect: TGPRect); virtual;
{自定义绘制方法动作事件}
procedure DoSubItemMouseDown(const Ap: PDrawInfo); virtual;
procedure DoSubItemMouseUp(const Ap: PDrawInfo); virtual;
{对象改变}
procedure DoObjectChanged(Sender: TObject); virtual;
//AItemTag: < 0 表示不区别层
function GetGpRectItem(const AItemTag: Integer): PDrawInfo;
function CurActiveSubItem: PDrawInfo; inline;
{消息}
procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;
private
FCurActiveSubItem: PDrawInfo;
FImageInfo: TImageInfo;
FFontInfo: TFontInfo;
FCaptionPosition: TPositionInfo;
FImgDrawMethod: TDrawMethod;
FOnSubItemMouseDown: TOnSubItem;
FOnSubItemMouseUp: TOnSubItem;
FAutoSizeByImage: Boolean;
FHandleMouseMoveOnDrawByInfo: Boolean;
procedure SetImageInfo(const Value: TImageInfo);
procedure SetFontInfo(const Value: TFontInfo);
procedure SetCaptionPosition(const Value: TPositionInfo);
procedure SetImgDrawMethod(const Value: TDrawMethod);
procedure SetAutoSizeByImage(const Value: Boolean);
published
property HandleMouseMoveOnDrawByInfo: Boolean read FHandleMouseMoveOnDrawByInfo write FHandleMouseMoveOnDrawByInfo;
property AutoSizeByImage: Boolean read FAutoSizeByImage write SetAutoSizeByImage;
property ImageInfo: TImageInfo read FImageInfo write SetImageInfo; //图像属性
property ImageDrawMethod: TDrawMethod read FImgDrawMethod write SetImgDrawMethod; //图像绘制方式
property FontInfo: TFontInfo read FFontInfo write SetFontInfo; //字体信息
property CaptionPosition: TPositionInfo read FCaptionPosition write SetCaptionPosition; //Caption的位置信息
property OnSubItemMouseDown: TOnSubItem read FOnSubItemMouseDown write FOnSubItemMouseDown;
property OnSubItemMouseUp: TOnSubItem read FOnSubItemMouseUp write FOnSubItemMouseUp;
end;
{$M-}
implementation
uses
uJxdGpSub;
{ TUICoreCommon }
constructor TxdGpCommon.Create(AOwner: TComponent);
begin
inherited;
FCurActiveSubItem := nil;
FAutoSizeByImage := False;
FHandleMouseMoveOnDrawByInfo := True;
FImageInfo := TImageInfo.Create;
FFontInfo := TFontInfo.Create;
FCaptionPosition := TPositionInfo.Create;
FImgDrawMethod := TDrawMethod.Create;
FImageInfo.OnChange := DoObjectChanged;
FFontInfo.OnChange := DoObjectChanged;
FCaptionPosition.OnChange := DoObjectChanged;
FImgDrawMethod.OnChange := DoObjectChanged;
end;
destructor TxdGpCommon.Destroy;
begin
FreeAndNil( FImageInfo );
FreeAndNil( FFontInfo );
FreeAndNil( FImgDrawMethod );
inherited;
end;
procedure TxdGpCommon.DoChangedSrcBmpRect(const AState: TxdGpUIState; var ASrcBmpRect: TGPRect);
begin
end;
procedure TxdGpCommon.DoControlStateChanged(const AOldState, ANewState: TxdGpUIState; const ACurPt: TPoint);
begin
if FImgDrawMethod.DrawStyle = dsDrawByInfo then
begin
case ANewState of
uiNormal:
begin
if Assigned(FCurActiveSubItem) then
begin
InvalidateRect( FCurActiveSubItem^.FDestRect );
FCurActiveSubItem := nil;
end;
end;
uiActive:
begin
if AOldState = uiDown then
begin
if Assigned(FCurActiveSubItem) then
begin
InvalidateRect( FCurActiveSubItem^.FDestRect );
DoSubItemMouseUp( FCurActiveSubItem );
end;
end;
end;
uiDown:
begin
if Assigned(FCurActiveSubItem) then
begin
InvalidateRect( FCurActiveSubItem^.FDestRect );
DoSubItemMouseDown( FCurActiveSubItem );
end;
end;
end;
end
else
Invalidate;
end;
function TxdGpCommon.DoIsDrawSubItem(const Ap: PDrawInfo): Boolean;
begin
Result := True;
end;
procedure TxdGpCommon.DoDrawSubItemText(const AGh: TGPGraphics; const AText: string; const AR: TGPRectF; const AItemState: TxdGpUIState);
begin
AGh.DrawString( AText, -1, FFontInfo.Font, AR, FFontInfo.Format, FFontInfo.FontBrush );
end;
function TxdGpCommon.DoGetDrawState(const Ap: PDrawInfo): TxdGpUIState;
begin
Result := GetCurControlState;
if Assigned(Ap) then
begin
if FCurActiveSubItem <> Ap then
Result := uiNormal;
end;
end;
procedure TxdGpCommon.DoObjectChanged(Sender: TObject);
begin
if FAutoSizeByImage and Assigned(FImageInfo.Image) then
begin
Width := FImageInfo.Image.GetWidth;
Height := Integer(FImageInfo.Image.GetHeight) div FImageInfo.ImageCount;
end;
Invalidate;
end;
procedure TxdGpCommon.DoSubItemMouseDown(const Ap: PDrawInfo);
begin
// OutputDebugString( PChar( 'DoSubItemMouseDown: ' + Ap^.FText) );
if Assigned(OnSubItemMouseDown) then
OnSubItemMouseDown( Ap );
end;
procedure TxdGpCommon.DoSubItemMouseUp(const Ap: PDrawInfo);
begin
// OutputDebugString( PChar( 'DoSubItemMouseUp: ' + Ap^.FText) );
if Assigned(OnSubItemMouseUp) then
OnSubItemMouseUp( Ap );
end;
procedure TxdGpCommon.DrawCaption(const AGh: TGPGraphics);
var
R: TGPRectF;
begin
if Caption <> '' then
begin
R.X :=FCaptionPosition.Left;
R.Y := FCaptionPosition.Top;
if FCaptionPosition.Width <= 0 then
R.Width := Width
else
R.Width := FCaptionPosition.Width;
if FCaptionPosition.Height <= 0 then
R.Height := Height
else
R.Height := FCaptionPosition.Height;
AGh.DrawString( Caption, -1, FFontInfo.Font, R, FFontInfo.Format, FFontInfo.FontBrush );
end;
end;
procedure TxdGpCommon.DrawGraphics(const AGh: TGPGraphics);
begin
// OutputDebugString( PChar('FCurActiveSubItem: ' + IntToStr( Integer(FCurActiveSubItem))) );
DrawImageCommon( AGh, MakeRect(0, 0, Width, Height), FImageInfo, FImgDrawMethod,
DoGetDrawState, DoIsDrawSubItem, DoDrawSubItemText, DoChangedSrcBmpRect );
DrawCaption( AGh );
end;
function TxdGpCommon.CurActiveSubItem: PDrawInfo;
begin
Result := FCurActiveSubItem;
end;
function TxdGpCommon.GetGpRectItem(const AItemTag: Integer): PDrawInfo;
var
i: Integer;
p: PDrawInfo;
begin
Result := nil;
for i := 0 to FImgDrawMethod.CurDrawInfoCount - 1 do
begin
p := FImgDrawMethod.GetDrawInfo( i );
if p^.FItemTag = AItemTag then
begin
Result := p;
Break;
end;
end;
end;
procedure TxdGpCommon.SetAutoSizeByImage(const Value: Boolean);
begin
if FAutoSizeByImage <> Value then
begin
FAutoSizeByImage := Value;
if FAutoSizeByImage and Assigned(FImageInfo.Image) then
begin
Width := FImageInfo.Image.GetWidth;
Height := Integer(FImageInfo.Image.GetHeight) div FImageInfo.ImageCount;
end;
end;
end;
procedure TxdGpCommon.SetCaptionPosition(const Value: TPositionInfo);
begin
FCaptionPosition.Assign( Value );
end;
procedure TxdGpCommon.SetFontInfo(const Value: TFontInfo);
begin
FFontInfo.Assign( Value );
end;
procedure TxdGpCommon.SetImageInfo(const Value: TImageInfo);
begin
FImageInfo.Assign( Value );
end;
procedure TxdGpCommon.SetImgDrawMethod(const Value: TDrawMethod);
begin
FImgDrawMethod.Assign( Value );
end;
procedure TxdGpCommon.WMMouseMove(var Message: TWMMouseMove);
var
i: Integer;
p, pTemp: PDrawInfo;
bFind: Boolean;
begin
inherited;
if DoGetDrawState(nil) = uiDown then Exit;
if FImgDrawMethod.DrawStyle = dsDrawByInfo then
begin
//从顶层向最后一层进行查找
// if Assigned(FCurActiveSubItem) then
// if PtInGpRect(Message.XPos, Message.YPos, FCurActiveSubItem^.FDestRect) then Exit;
bFind := False;
for i := FImgDrawMethod.CurDrawInfoCount - 1 downto 0 do
begin
p := FImgDrawMethod.GetDrawInfo( i );
if Assigned(p) and PtInGpRect(Message.XPos, Message.YPos, p^.FDestRect) then
begin
if FCurActiveSubItem <> p then
begin
if Assigned(FCurActiveSubItem) then
begin
pTemp := FCurActiveSubItem;
FCurActiveSubItem := nil;
if HandleMouseMoveOnDrawByInfo then
InvalidateRect( pTemp^.FDestRect );
end;
FCurActiveSubItem := p;
if HandleMouseMoveOnDrawByInfo then
InvalidateRect( FCurActiveSubItem^.FDestRect );
end;
bFind := True;
Break;
end;
end;
if not bFind then
begin
if Assigned(FCurActiveSubItem) then
begin
if HandleMouseMoveOnDrawByInfo then
InvalidateRect( FCurActiveSubItem^.FDestRect );
FCurActiveSubItem := nil;
end;
end;
end;
end;
end.
|
unit ucategoriamodel;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TCategoriaModel = class
private
{ private declarations }
fId : integer;
fCodigo : integer;
fNome : string;
fStatus : string;
fCriado : string;
fAtualizado : string;
function getId() : integer;
function getCodigo() : integer;
function getNome() : string;
function getStatus() : string;
function getCriado() : string;
function getAtualizado() : string;
procedure setId( id : integer );
procedure setCodigo( codigo: integer );
procedure setNome( nome : string );
procedure setStatus( status : string );
procedure setCriado( data : string );
procedure setAtualizado( data : string );
public
{ public declarations}
property Id : integer read getId write setId;
property Codigo : integer read getCodigo write setCodigo;
property Nome : string read getNome write setNome;
property Status : string read getStatus write setStatus;
property Criado : string read getCriado write setCriado;
property Atualizado : string read getAtualizado write setCriado;
end;
implementation
{ TODO -oRodrigo Soares -cCRUD : Desenvolver as implentações dos getters e setters }
function TCategoriaModel.getId() : integer;
begin
Result := fId;
end;
function TCategoriaModel.getCodigo() : integer;
begin
Result := fCodigo;
end;
function TCategoriaModel.getNome() : string;
begin
Result := fNome;
end;
function TCategoriaModel.getStatus() : string;
begin
Result := fStatus;
end;
function TCategoriaModel.getCriado() : string;
begin
Result := fCriado;
end;
function TCategoriaModel.getAtualizado() : string;
begin
Result := fAtualizado;
end;
procedure TCategoriaModel.setId( id : integer);
begin
fId := id;
end;
procedure TCategoriaModel.setCodigo( codigo : integer );
begin
fCodigo := codigo;
end;
procedure TCategoriaModel.setNome( nome : string );
begin
fNome := nome;
end;
procedure TCategoriaModel.setStatus( status : string );
begin
fStatus := status;
end;
procedure TCategoriaModel.setCriado( data : string );
begin
fCriado := data;
end;
procedure TCategoriaModel.setAtualizado( data : string );
begin
fAtualizado := data;
end;
end.
|
unit Orders;
interface
uses System.Generics.Collections, Order;
type
TOrders = class
private
FList: TList<TOrder>;
public
constructor Create;
destructor Destroy; override;
function GetAllOrders: TList<TOrder>;
procedure AddOrder(AOrder: TOrder);
procedure DeleteOrder(const AOrder: TOrder);
end;
implementation
uses System.SysUtils;
{ TOrders }
constructor TOrders.Create;
var
O: TOrder;
begin
inherited;
FList := TList<TOrder>.Create;
O := TOrder.Create;
O.Text := 'Order No. 1';
O.FullPrice := Random;
O.DiscountedPrice := Random;
AddOrder(O);
O := TOrder.Create;
O.Text := 'Order No. 2';
O.FullPrice := Random;
O.DiscountedPrice := Random;
AddOrder(O);
end;
destructor TOrders.Destroy;
var
O: TOrder;
begin
for O in FList do
O.Free;
FreeAndNil(FList);
inherited;
end;
function TOrders.GetAllOrders: TList<TOrder>;
begin
Result := FList;
end;
procedure TOrders.AddOrder(AOrder: TOrder);
begin
FList.Add(AOrder);
end;
procedure TOrders.DeleteOrder(const AOrder: TOrder);
begin
FList.Remove(AOrder);
end;
end.
|
{
ID: ndchiph1
PROG: rect1
LANG: PASCAL
}
uses math;
const
maxR = 10000;
type
rect = record
x,y,u,v,colr: longint;
end;
var
fi,fo: text;
a,b,n: longint;
s: array[0..1,0..maxR] of rect;
len: array[0..1] of longint;
res: array[1..2500] of longint;
procedure input;
begin
readln(fi,a,b,n);
end;
procedure add(var rec: rect; i,j,k,t,col: longint);
begin
with rec do
begin
x:= i;
y:= j;
u:= k;
v:= t;
colr:= col;
end;
end;
procedure process2(pr,ne: longint);
var
r,p: rect;
i: longint;
begin
len[ne]:= 0;
with r do
begin
readln(fi,x,y,u,v,colr);
for i:= 1 to len[pr] do
begin
p:= s[pr,i];
if (u < p.x) or (x > p.u) or (v < p.y) or (y > p.v) then
begin
inc(len[ne]);
s[ne,len[ne]]:= p;
continue;
end;
if (x > p.x) then
begin
inc(len[ne]);
add(s[ne,len[ne]],p.x,max(y,p.y),x,p.v,p.colr);
end;
if (y > p.y) then
begin
inc(len[ne]);
add(s[ne,len[ne]],p.x,p.y,min(u,p.u),y,p.colr);
end;
if (u < p.u) then
begin
inc(len[ne]);
add(s[ne,len[ne]],u,p.y,p.u,min(v,p.v),p.colr);
end;
if (v < p.v) then
begin
inc(len[ne]);
add(s[ne,len[ne]],max(x,p.x),v,p.u,p.v,p.colr);
end;
end;
end;
inc(len[ne]);
s[ne,len[ne]]:= r;
end;
procedure process;
var
p: rect;
i,k: longint;
begin
len[0]:= 1; add(s[0,1],0,0,a,b,1);
for i:= 0 to n-1 do process2(i mod 2, 1 - i mod 2);
k:= n mod 2;
for i:= 1 to len[k] do
begin
p:= s[k,i];
res[p.colr]:= res[p.colr] + (p.u - p.x) * (p.v - p.y);
end;
for i:= 1 to 2500 do
if (res[i] > 0) then writeln(fo,i,' ',res[i]);
end;
begin
assign(fi,'rect1.in'); reset(fi);
assign(fo,'rect1.out'); rewrite(fo);
//
input;
process;
//
close(fi);
close(fo);
end.
|
program PrinterOutputFilter;
{ Printer filters read input from the IDE by way of StdIn (by using Read
or ReadLn). It then converts the syntax highlight codes inserted into
the text into appropriate printer command codes. This converted text is
then output Lst (which defaults to LPT1).
The syntax highlight codes are in the form of <ESC>#, where '#' is an
ASCII digit from 1($31) to 8($38). The last code sent remains in effect
until another code is found. The following is a list of the codes and
what type of text they represent:
1 - Whitespace (space, tab)
2 - Comment
3 - Reserved word (begin, end, procedure, etc...)
4 - Identifier (Writeln, Reset, etc...)
5 - Symbol (;, :, ., etc...)
6 - String ('string', #32, #$30)
7 - Number (24, $56)
8 - Assembler (asm mov ax,5 end;)
The following printers are supported:
EPSON and compatibles
HP LaserJet II, III, IIP, IID, IIID, IIISi and compatibles
(Italics are available on IIIx, IIP)
ADOBE(R) PostScript(R)
ASCII (simply strips the highlight codes before sending to Lst)
Command line options:
/EPSON - Output EPSON printer codes
/HP - Output HP LaserJet codes
/PS - Output PostScript
/ASCII - Strip highlight codes (Default)
/Lxx - Lines per page (Default 55)
/Txx - Tabsize (Default 8)
/O[file] - Output to file or device (Default LPT1)
}
{$M 2048, 0, 0}
{$I-,S-,X+}
Const MaxAttributes=8;
Type
TPCharArray=Array[0..16380]of PChar;
PPCharArray=^TPCharArray;
PPrinterCodes=^TPrinterCodes;
TPrinterCodes=Record
{ Number of preamble strings in the Preamble array. }
PreambleCount: Byte;
{ Pointer to an array of PChars that define the preamble sequence for
this printer. Sent at the start of a print job. }
Preamble: PPCharArray;
{ Pointer to an array of PChars that define the code sequences for
changing the current attribute. }
CodeArray: PPCharArray;
{ Array of indexes into the CodeArray corresponing to attributes
supported for this printer. }
Attributes: array[0..MaxAttributes - 1] of Byte;
{ Codes sent at the start of a page. }
StartPage: PChar;
{ Codes sent at the end of a page. }
EndPage: PChar;
{ Codes sent at the end of a line. }
EndLine: PChar;
{ Codes sent at the end of the print job. }
Postamble: PChar;
end;
Const
{EPSON Printer code definition}
EpsonItalic = #27'4';
EpsonNoItalic = #27'5';
EpsonBold = #27'E';
EpsonNoBold = #27'F';
EpsonULine = #27'-'#1;
EpsonNoULine = #27'-'#0;
EpsonCodeArray:Array[0..7]of PChar=(
EpsonBold,
EpsonNoBold,
EpsonItalic,
EpsonNoItalic,
EpsonULine,
EpsonNoULine,
EpsonBold+EpsonItalic,
EpsonNoBold+EpsonNoItalic);
EpsonCodes:TPrinterCodes=(
PreambleCount:0;
Preamble:NIL;
CodeArray:@EpsonCodeArray;
Attributes:(
0, { Whitespace }
2, { Comment }
1, { Reserved word }
0, { Identifier }
0, { Symbol }
4, { String }
0, { Number }
1); { Assembler }
StartPage: '';
EndPage: #12;
EndLine: #13#10;
Postamble: ''
);
{HP LaserJet code definition}
HPInit = #27'E'#27'(10U'#27'&k0S'#27'(s3T';
HPItalic = #27'(s1S';
HPNoItalic = #27'(s0S';
HPBold = #27'(s3B';
HPNoBold = #27'(s0B';
HPULine = #27'&dD';
HPNoULine = #27'&d@';
HPCodeArray:Array[0..7]of PChar=(
HPBold,
HPNoBold,
HPItalic,
HPNoItalic,
HPULine,
HPNoULine,
HPBold+HPItalic,
HPNoBold+HPNoItalic);
LaserJetPreamble:PChar=HPInit;
LaserJetCodes:TPrinterCodes=(
PreambleCount:1;
Preamble:@LaserJetPreamble;
CodeArray:@HPCodeArray;
Attributes:(
0, { Whitespace }
2, { Comment }
1, { Reserved word }
0, { Identifier }
0, { Symbol }
4, { String }
0, { Number }
1); { Assembler }
StartPage:'';
EndPage:#12;
EndLine:#13#10;
Postamble:#12
);
{ Raw ASCII definition }
AsciiCodes:TPrinterCodes=(
PreambleCount:0;
Preamble:NIL;
CodeArray:NIL;
Attributes: (
0, { Whitespace }
0, { Comment }
0, { Reserved word }
0, { Identifier }
0, { Symbol }
0, { String }
0, { Number }
0); { Assembler }
StartPage:'';
EndPage:#12;
EndLine:#13#10;
Postamble:''
);
{PostScript code definition}
PSPreamble0=#4'%!PS-Adobe-3.0'#13#10'initgraphics'#13#10;
PSPreamble1='/fnr /Courier findfont 10 scalefont def'#13#10;
PSPreamble2='/fni /Courier-Oblique findfont 10 scalefont def'#13#10;
PSPreamble3='/fnb /Courier-Bold findfont 10 scalefont def'#13#10;
PSPreamble4='/fnbi /Courier-BoldOblique findfont 10 scalefont def'#13#10;
PSPreamble5='/newl {20 currentpoint exch pop 12 sub moveto} def'#13#10+
'/newp {20 765 moveto} def'#13#10+
'fnr setfont'#13#10;
PSNormal='fnr setfont'#13#10;
PSItalic='fni setfont'#13#10;
PSBold='fnb setfont'#13#10;
PSBoldItalic='fnbi setfont'#13#10;
PSCodeArray:Array[0..5]of PChar=(
PSBold,
PSNormal,
PSItalic,
PSNormal,
PSBoldItalic,
PSNormal);
PSPreamble:Array[0..5]of PChar=(
PSPreamble0,
PSPreamble1,
PSPreamble2,
PSPreamble3,
PSPreamble4,
PSPreamble5);
PSCodes:TPrinterCodes=(
PreambleCount:High(PSPreamble)-Low(PSPreamble)+1;
Preamble:@PSPreamble;
CodeArray:@PSCodeArray;
Attributes:(
0, { Whitespace }
2, { Comment }
1, { Reserved word }
0, { Identifier }
0, { Symbol }
3, { String }
0, { Number }
1); { Assembler }
StartPage: 'newp'#13#10;
EndPage: 'showpage'#13#10;
EndLine: 'newl'#13#10;
Postamble: #4
);
{ Special case printer modes. This facilitates indicating a special case
printer such as PostScript }
pmNormal=$0001;
pmPostScript=$0002;
PrintMode:Word=pmNormal;
LinesPerPage:Word=55;
ToFile:Boolean=False;
TabSize:Word=8;
Var
C,LineCount,TabCount:Integer;
Line,OutputLine:String;
InputBuffer:Array[0..4095]of Char;
PrinterCodes:PPrinterCodes;
CurCode,NewCode:Byte;
AKey:Word;
Lst:Text;
Procedure UpStr(Var S:String);Var I:Integer;Begin
For I:=1to Length(S)do S[I]:=UpCase(S[I]);
End;
{ Checks whether or not the Text file is a device. If so, it is forced to
"raw" mode }
Procedure SetDeviceRaw(Var T:Text);Assembler;ASM
LES DI,T
MOV BX,WORD PTR ES:[DI]
MOV AX,4400H
INT 21H
TEST DX,0080H
JZ @@1
OR DL,20H
MOV DH,DH
MOV AX,4401H
INT 21H
@@1:
END;
{ Process the command line. If any new printers are to be supported, simply
add a command line switch here. }
Procedure ProcessCommandLine;Var Param:String;I:Integer;
Function ParamVal(Var P:String;Default:Word):Word;Var N,E:Integer;Begin
Delete(P,1,1);
Val(P,N,E);
If E=0Then ParamVal:=N else ParamVal:=Default;
End;
Begin
PrinterCodes:=@AsciiCodes;
For I:=1to(ParamCount)do Begin
Param:=ParamStr(I);
If(Length(Param)>=2)and(Param[1]in['/','-'])Then Begin
Delete(Param,1,1);
UpStr(Param);
If Param='EPSON'Then PrinterCodes:=@EpsonCodes else
If Param='HP'Then PrinterCodes:=@LaserJetCodes else
If Param='ASCII'Then PrinterCodes:=@AsciiCodes else
If Param='PS'Then Begin;PrinterCodes:=@PSCodes;PrintMode:=pmPostScript;End else
If Param[1]='L'Then LinesPerPage:=ParamVal(Param,LinesPerPage)else
If Param[1]='T'Then TabSize:=ParamVal(Param,TabSize)else
If Param[1]='O'Then Begin
Delete(Param,1,1);
Assign(Lst,Param);
Rewrite(Lst);
ToFile:=True;
SetDeviceRaw(Lst);
End;
End;
End;
If Not(ToFile)Then Begin
Assign(Lst,'LPT1');
Rewrite(Lst);
SetDeviceRaw(Lst);
End;
End;
{ Flush the currently assembled string to the output }
Procedure PurgeOutputBuf;Begin
If OutputLine=''Then Exit;
Case(PrintMode)of
pmNormal:Write(Lst,OutputLine);
pmPostScript:Write(Lst,'(',OutputLine,') show'#13#10);
End;
OutputLine:='';
If IOResult<>0Then Halt(1);
End;
{ Add the chracter to the output string. Process special case characters
and tabs, purging the output buffer when nessesary }
Procedure AddToOutputBuf(AChar:Char);Var I:Integer;Begin
Case(AChar)of
'(',')','\':Case(PrintMode)of
pmPostScript:Begin
If Length(OutputLine)>253Then PurgeOutputBuf;
Inc(OutputLine[0]);
OutputLine[Length(OutputLine)]:='\';
End;
End;
#9:Begin
If Length(OutputLine)>(255-TabSize)Then PurgeOutputBuf;
For I:=1to TabSize-(TabCount mod TabSize)do Begin Inc(OutputLine[0]);
OutputLine[Length(OutputLine)]:=' ';
End;
Inc(TabCount,TabSize-(TabCount mod TabSize));
Exit;
End;
End;
If Length(OutputLine)>254Then PurgeOutputBuf;
Inc(OutputLine[0]);
OutputLine[Length(OutputLine)]:=AChar;
Inc(TabCount);
End;
{ End the current page and start a new one }
Procedure NewPage(Const PCodes:TPrinterCodes);Begin
PurgeOutputBuf;
Write(Lst,PCodes.EndPage);
Write(Lst,PCodes.StartPage);
LineCount:=0;TabCount:=0;
End;
{ End the current line }
Procedure NewLine(Const PCodes:TPrinterCodes);Begin
PurgeOutputBuf;
Write(Lst,PCodes.EndLine);
Inc(LineCount);TabCount:=0;
If(LineCount>LinesPerPage)Then NewPage(PCodes);
End;
{ Check for the presence of a keypressed and return it if available }
Function GetKey(Var Key:Word):Boolean;Assembler;ASM
MOV AH,1
INT 16H
MOV AL,0
JE @@1
XOR AH,AH
INT 16H
LES DI,Key
MOV WORD PTR ES:[DI],AX
MOV AL,1
@@1:
END;
BEGIN
SetTextBuf(Input,InputBuffer);
ProcessCommandLine;
LineCount:=0;
With PrinterCodes^do Begin
If PreambleCount>0Then For C:=0to PreambleCount-1do Write(Lst,Preamble^[C]);
If IOResult<>0Then Halt(1);
LineCount:=0;CurCode:=$FF;TabCount:=0;
Write(Lst,StartPage);
Line:='';
While(True)do Begin
If(Line='')and(Eof)Then Begin
PurgeOutputBuf;
Break;
End;
ReadLn(Line);
If GetKey(AKey)and(AKey=$011B)Then Halt(1);
C:=1;
While C<=Length(Line)do Begin
Case Line[C]of
#27:If(Line[C+1]>='1')and(Line[C+1]<='8')Then Begin
NewCode:=Attributes[Byte(Line[C+1])-$31];
If(NewCode<>CurCode)Then Begin
PurgeOutputBuf;
If(CurCode>0)and(CurCode<MaxAttributes)Then Write(Lst,CodeArray^[(CurCode-1)*2+1]);
If(NewCode>0)and(NewCode<MaxAttributes)Then Write(Lst,CodeArray^[(NewCode-1)*2]);
CurCode:=NewCode;
End;
Inc(C);
End;
#12:NewPage(PrinterCodes^);
else AddToOutputBuf(Line[C]);
End;
Inc(C);
End;
NewLine(PrinterCodes^);
End;
If LineCount>0Then Write(Lst,EndPage);
Write(Lst,Postamble);
End;
Close(Lst);
END.
|
Unit DrawKr;
INTERFACE
Uses Systex,Isatex;
Function ChoiceRGBColor(Var Q:RGB):Boolean;
Procedure DWBrightnessContrast(Var Q:DrawEditApp);
Procedure DWChannelMixer(Var Q:DrawEditApp);
Procedure DWLoadPalette(Var Q:DrawEditApp);
IMPLEMENTATION
Uses
Adele,Video,Systems,Math,Dialex,DialPlus,Restex,ResServI,DrawEdit,Dials;
{ Cette proc‚dure permet d'ajuster le luminosit‚ et la contraste d'une
image du programme de dessin.
}
Procedure DWBrightnessContrast(Var Q:DrawEditApp);
Var
FormBrightnessContrast:Record
Brightness:MScrollBar; { Luminosit‚ }
Contrast:MScrollBar; { Contraste }
End;
Tab:Array[0..255]of Byte;
Procedure ComputeContrast;
Var
I:Integer;
X,Y:Word;
Begin
X:=FormBrightnessContrast.Contrast.Position shr 5;
For I:=0to Q.Canvas.Res.NumPal-1do Begin
Y:=((I shr X)shl X)+FormBrightnessContrast.Brightness.Position;
If Y>255Then Y:=255;
Tab[I]:=Y;
End;
End;
Procedure ComputePalette256;
Var
I:Integer;
Begin
If(Q.Canvas.PaletteRGB<>NIL)Then Begin
For I:=0to Q.Canvas.Res.NumPal-1do Begin
Q.Canvas.PaletteRGB^[I].R:=Tab[Q.Canvas.PaletteRGB^[I].R];
Q.Canvas.PaletteRGB^[I].G:=Tab[Q.Canvas.PaletteRGB^[I].G];
Q.Canvas.PaletteRGB^[I].B:=Tab[Q.Canvas.PaletteRGB^[I].B];
End;
XSetAbsRec(Q.Canvas.Image,SizeOf(ImageHeaderRes)+
Mul2Word(Q.Canvas.Res.BytesPerLine,Q.Canvas.Res.NumYPixels),
Q.Canvas.Res.NumPal*3,Q.Canvas.PaletteRGB^);
End;
End;
Procedure Compute16;
Var
I,J:Integer;
Buffer:Array[0..2047]of Word;
Color:RGB;
P:LongInt;
X:Word;
Begin
If Q.Canvas.Res.BytesPerLine<=SizeOf(Buffer)Then Begin
P:=SizeOf(ImageHeaderRes);
For J:=0to(Q.Canvas.Res.NumYPixels)do Begin
XGetAbsRec(Q.Canvas.Image,P,Q.Canvas.Res.BytesPerLine,Buffer);
For I:=0to Q.Canvas.Res.NumXPixels-1do Begin
_Color2RGB(Buffer[I],Q.Canvas.Res.BitsPerPixel,Color);
Color.R:=Tab[Color.R];
Color.G:=Tab[Color.G];
Color.B:=Tab[Color.B];
Buffer[I]:=_RGB2Color(Q.Canvas.Res.BitsPerPixel,Color.R,Color.G,Color.B);
End;
XSetAbsRec(Q.Canvas.Image,P,Q.Canvas.Res.BytesPerLine,Buffer);
Inc(P,Q.Canvas.Res.BytesPerLine);
End;
End;
End;
Begin
FillClr(FormBrightnessContrast,SizeOf(FormBrightnessContrast));
If ExecuteAppDPU(119,FormBrightnessContrast)Then Begin
ComputeContrast;
Case(Q.Canvas.Res.BitsPerPixel)of
8:ComputePalette256;
15,16:Compute16;
End;
XFreeMem(Q.Canvas.Miroir);
RIMakeDoublon(Q.Canvas.Image,rmAllResSteady,False,Q.Canvas);
DWRefresh(Q);
End;
End;
{ Cette proc‚dure permet d'ajuster de mixer les couleurs RVB en fonction
des valeurs RVB attribu‚ … chacune.
}
Procedure DWChannelMixer(Var Q:DrawEditApp);
Var
FormChannelMixer:Record
R:Record
R,G,B:MScrollBar;
End;
G:Record
R,G,B:MScrollBar;
End;
B:Record
R,G,B:MScrollBar;
End;
End;
Procedure ComputePalette256;
Var
I:Integer;
T:Record
R,G,B:Integer;
End;
Begin
If(Q.Canvas.PaletteRGB<>NIL)Then Begin
For I:=0to Q.Canvas.Res.NumPal-1do Begin
T.R:=((Q.Canvas.PaletteRGB^[I].R*FormChannelMixer.R.R.Position)shr 8)+
((Q.Canvas.PaletteRGB^[I].G*FormChannelMixer.R.G.Position)shr 8)+
((Q.Canvas.PaletteRGB^[I].B*FormChannelMixer.R.B.Position)shr 8);
T.G:=((Q.Canvas.PaletteRGB^[I].R*FormChannelMixer.G.R.Position)shr 8)+
((Q.Canvas.PaletteRGB^[I].G*FormChannelMixer.G.G.Position)shr 8)+
((Q.Canvas.PaletteRGB^[I].B*FormChannelMixer.G.B.Position)shr 8);
T.B:=((Q.Canvas.PaletteRGB^[I].R*FormChannelMixer.B.R.Position)shr 8)+
((Q.Canvas.PaletteRGB^[I].G*FormChannelMixer.B.G.Position)shr 8)+
((Q.Canvas.PaletteRGB^[I].B*FormChannelMixer.B.B.Position)shr 8);
If T.R>255Then T.R:=255;
If T.G>255Then T.G:=255;
If T.B>255Then T.B:=255;
Q.Canvas.PaletteRGB^[I].R:=T.R;
Q.Canvas.PaletteRGB^[I].G:=T.G;
Q.Canvas.PaletteRGB^[I].B:=T.B;
End;
XSetAbsRec(Q.Canvas.Image,SizeOf(ImageHeaderRes)+
Mul2Word(Q.Canvas.Res.BytesPerLine,Q.Canvas.Res.NumYPixels),
Q.Canvas.Res.NumPal*3,Q.Canvas.PaletteRGB^);
End;
End;
Procedure Compute16;
Var
I,J:Integer;
Buffer:Array[0..2047]of Word;
Color:RGB;
P:LongInt;
X:Word;
T:Record
R,G,B:Integer;
End;
Begin
If Q.Canvas.Res.BytesPerLine<=SizeOf(Buffer)Then Begin
P:=SizeOf(ImageHeaderRes);
For J:=0to(Q.Canvas.Res.NumYPixels)do Begin
XGetAbsRec(Q.Canvas.Image,P,Q.Canvas.Res.BytesPerLine,Buffer);
For I:=0to Q.Canvas.Res.NumXPixels-1do Begin
_Color2RGB(Buffer[I],Q.Canvas.Res.BitsPerPixel,Color);
T.R:=((Color.R*FormChannelMixer.R.R.Position)shr 8)+
((Color.G*FormChannelMixer.R.G.Position)shr 8)+
((Color.B*FormChannelMixer.R.B.Position)shr 8);
T.G:=((Color.R*FormChannelMixer.G.R.Position)shr 8)+
((Color.G*FormChannelMixer.G.G.Position)shr 8)+
((Color.B*FormChannelMixer.G.B.Position)shr 8);
T.B:=((Color.R*FormChannelMixer.B.R.Position)shr 8)+
((Color.G*FormChannelMixer.B.G.Position)shr 8)+
((Color.B*FormChannelMixer.B.B.Position)shr 8);
If T.R>255Then T.R:=255;
If T.G>255Then T.G:=255;
If T.B>255Then T.B:=255;
Buffer[I]:=_RGB2Color(Q.Canvas.Res.BitsPerPixel,T.R,T.G,T.B);
End;
XSetAbsRec(Q.Canvas.Image,P,Q.Canvas.Res.BytesPerLine,Buffer);
Inc(P,Q.Canvas.Res.BytesPerLine);
End;
End;
End;
Begin
FillClr(FormChannelMixer,SizeOf(FormChannelMixer));
FormChannelMixer.R.R.Position:=255;
FormChannelMixer.G.G.Position:=255;
FormChannelMixer.B.B.Position:=255;
If ExecuteAppDPU(120,FormChannelMixer)Then Begin
Case(Q.Canvas.Res.BitsPerPixel)of
8:ComputePalette256;
15,16:Compute16;
End;
XFreeMem(Q.Canvas.Miroir);
RIMakeDoublon(Q.Canvas.Image,rmAllResSteady,False,Q.Canvas);
DWRefresh(Q);
End;
End;
Procedure DWLoadPalette(Var Q:DrawEditApp);
Var
Path:String;
S:String;
P:LongInt;
I:Integer;
J:Byte;
N:Byte; { Num‚ro de palette }
Handle:Hdl;
NumPal:Word;
Begin
If Q.Canvas.Res.BitsPerPixel<=8Then Begin
Path:=OpenWin(MaltePath+'DRAW\PALETTES\*.PAL','Choisissez une palette');
If Path<>''Then Begin
Handle:=FileOpen(Path,fmRead);
If(Handle<>errHdl)Then Begin
P:=0;
__GetAbsFileTxtLn(Handle,P,Path);
If Path='JASC-PAL'Then Begin
__GetAbsFileTxtLn(Handle,P,Path);
__GetAbsFileTxtLn(Handle,P,Path);
NumPal:=StrToInt(Path);
If(NumPal>Q.Canvas.Res.NumPal)Then NumPal:=Q.Canvas.Res.NumPal;
__GetAbsFileTxtLn(Handle,P,Path);
For I:=0to NumPal-1do Begin
__GetAbsFileTxtLn(Handle,P,Path);
S:='';N:=0;
For J:=1to Length(Path)do Begin
If Path[J]=' 'Then Begin
Case(N)of
0:Q.Canvas.PaletteRGB^[I].R:=StrToWord(S);
1:Q.Canvas.PaletteRGB^[I].G:=StrToWord(S);
2:Q.Canvas.PaletteRGB^[I].B:=StrToWord(S);
End;
Inc(N);
S:='';
End
Else
IncStr(S,Path[J]);
End;
End;
End;
FileClose(Handle);
XSetAbsRec(Q.Canvas.Image,SizeOf(ImageHeaderRes)+
Mul2Word(Q.Canvas.Res.BytesPerLine,Q.Canvas.Res.NumYPixels),
Q.Canvas.Res.NumPal*3,Q.Canvas.PaletteRGB^);
XFreeMem(Q.Canvas.Miroir);
RIMakeDoublon(Q.Canvas.Image,rmAllResSteady,False,Q.Canvas);
DWRefresh(Q);
End;
End;
End
Else
ErrNoMsgOk(errPaletteNotSupported);
End;
Type
SpecialRGBRec=Record
R,G,B:MScrollBar;
H:ScrollBarWordRec;
S,V:MScrollBar;
ColorCube:ColorCubeData;
End;
Procedure OnMoveColorX(Var R:ResourceWindow;Var Context);Far;
Var
Data:SpecialRGBRec Absolute Context;
H,S,V:Real;
Begin
WEPutFillBox(R.W,1shl 3,GetRawY(16),R.W.MaxX shl 3,GetRawY(18)-1,
RGB2Color(Data.R.Position,Data.G.Position,Data.B.Position));
Data.ColorCube.Color.R:=Data.R.Position;
Data.ColorCube.Color.G:=Data.G.Position;
Data.ColorCube.Color.B:=Data.B.Position;
RGB2HSV(Data.ColorCube.Color,H,S,V);
Data.H.Value:=Trunc(H);
Data.S.Position:=Trunc(S*100);
Data.V.Position:=Trunc(V*256);
End;
Procedure OnMoveColorXHSV(Var R:ResourceWindow;Var Context);Far;
Var
Data:SpecialRGBRec Absolute Context;
Target:RGB;
Begin
HSV2RGB(Data.H.Value,Data.S.Position/100,Data.V.Position/256,Target);
WEPutFillBox(R.W,1shl 3,GetRawY(16),R.W.MaxX shl 3,GetRawY(18)-1,
RGB2Color(Target.R,Target.G,Target.B));
Data.ColorCube.Color.R:=Target.R;
Data.ColorCube.Color.G:=Target.G;
Data.ColorCube.Color.B:=Target.B;
Data.R.Position:=Data.ColorCube.Color.R;
Data.G.Position:=Data.ColorCube.Color.G;
Data.B.Position:=Data.ColorCube.Color.B;
End;
Procedure OnMoveColorXCube(Var R:ResourceWindow;Var Context);Far;
Var
Data:SpecialRGBRec Absolute Context;
Begin
WEPutFillBox(R.W,1shl 3,GetRawY(16),R.W.MaxX shl 3,GetRawY(18)-1,
RGB2Color(Data.ColorCube.Color.R,Data.ColorCube.Color.G,Data.ColorCube.Color.B));
Data.R.Position:=Data.ColorCube.Color.R;
Data.G.Position:=Data.ColorCube.Color.G;
Data.B.Position:=Data.ColorCube.Color.B;
End;
Function ChoiceRGBColor(Var Q:RGB):Boolean;
Var
Data:SpecialRGBRec;
H,S,V:Real;
Begin
ChoiceRGBColor:=False;
FillClr(Data,SizeOf(Data));
Data.R.OnScroll:=OnMoveColorX;
Data.R.OnScrollContext:=@Data;
Data.G.OnScroll:=OnMoveColorX;
Data.G.OnScrollContext:=@Data;
Data.B.OnScroll:=OnMoveColorX;
Data.B.OnScrollContext:=@Data;
Data.H.OnMove:=OnMoveColorXHSV;
Data.H.Context:=@Data;
Data.S.OnScroll:=OnMoveColorXHSV;
Data.S.OnScrollContext:=@Data;
Data.V.OnScroll:=OnMoveColorXHSV;
Data.V.OnScrollContext:=@Data;
Data.ColorCube.OnClick:=OnMoveColorXCube;
Data.ColorCube.Context:=@Data;
Data.B.Position:=Q.B;
Data.G.Position:=Q.G;
Data.R.Position:=Q.R;
RGB2HSV(Q,H,S,V);
Data.H.Value:=Trunc(H);
Data.S.Position:=Trunc(S*100);
Data.V.Position:=Trunc(V*256);
If ExecuteAppDPU(80,Data)Then Begin
Q.B:=Data.B.Position;
Q.G:=Data.G.Position;
Q.R:=Data.R.Position;
ChoiceRGBColor:=True;
End;
End;
END. |
unit Generic2DArray;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
NiceExceptions;
type
{ T2Array }
generic T2Array<T> = class
public
constructor Create(const aWidth, aHeight: integer);
constructor Create;
public type
TColumn = array of T;
TMatrix = array of TColumn;
PT = ^T;
private
fMatrix: TMatrix;
fWidth, fHeight: integer;
procedure Allocate;
function GetCellExists(const aX, aY: integer): boolean;
procedure Deallocate;
public
property Width: integer read fWidth;
property Height: integer read fHeight;
property Matrix: TMatrix read fMatrix;
procedure Reallocate(const aWidth, aHeight: integer);
property CellExists[const x, y: integer]: boolean read GetCellExists;
function AccessCell(const x, y: integer): PT;
end;
implementation
{ T2Array }
constructor T2Array.Create(const aWidth, aHeight: integer);
begin
inherited Create;
fWidth := aWidth;
fHeight := aHeight;
Allocate;
end;
constructor T2Array.Create;
begin
Create(0, 0);
end;
procedure T2Array.Allocate;
var
x: integer;
begin
SetLength(fMatrix, Width);
for x := 0 to Width - 1 do
SetLength(fMatrix[x], Height);
end;
function T2Array.GetCellExists(const aX, aY: integer): boolean;
begin
result := (aX >= 0) and (aY >= 0) and (aX < Width) and (aY < Height);
end;
procedure T2Array.Deallocate;
var
x: integer;
begin
if not Assigned(fMatrix) then
exit; // nothing to deallocate
for x := 0 to Width - 1 do
SetLength(fMatrix[x], 0);
SetLength(fMatrix, 0);
fWidth := 0;
fHeight := 0;
end;
procedure T2Array.Reallocate(const aWidth, aHeight: integer);
begin
Deallocate;
fWidth := aWidth;
fHeight := aHeight;
Allocate;
end;
function T2Array.AccessCell(const x, y: integer): PT;
begin
result := nil;
if CellExists[x, y] then
result := @( Matrix[x, y] );
end;
end.
|
unit tests.driver.zeos;
{$mode objfpc}{$H+}
interface
uses
DB,
Classes, SysUtils, fpcunit, testutils, testregistry,
ZConnection,
dbebr.factory.interfaces;
type
{ TTestDBEBrZeos }
TTestDBEBrZeos= class(TTestCase)
strict private
FConnection: TZConnection;
FDBConnection: IDBConnection;
FDBQuery: IDBQuery;
FDBResultSet: IDBResultSet;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConnect;
procedure TestDisconnect;
procedure TestExecuteDirect;
procedure TestExecuteDirectParams;
procedure TestExecuteScript;
procedure TestAddScript;
procedure TestExecuteScripts;
procedure TestIsConnected;
procedure TestInTransaction;
procedure TestCreateQuery;
procedure TestCreateResultSet;
procedure TestExecuteSQL;
procedure TestStartTransaction;
procedure TestCommit;
procedure TestRollback;
end;
implementation
uses
dbebr.factory.zeos,
Tests.Consts;
procedure TTestDBEBrZeos.TestConnect;
begin
FDBConnection.Connect;
AssertEquals('FConnection.IsConnected = true', True, FDBConnection.IsConnected);
end;
procedure TTestDBEBrZeos.TestDisconnect;
begin
FDBConnection.Disconnect;
AssertEquals('FConnection.IsConnected = false', False, FDBConnection.IsConnected);
end;
procedure TTestDBEBrZeos.TestExecuteDirect;
var
LValue: String;
LRandon: String;
begin
LRandon := IntToStr( Random(9999) );
FDBConnection.ExecuteDirect( Format(cSQLUPDATE, [QuotedStr(cDESCRIPTION + LRandon), '1']) );
FDBQuery := FDBConnection.CreateQuery;
FDBQuery.CommandText := Format(cSQLSELECT, ['1']);
LValue := FDBQuery.ExecuteQuery.FieldByName('CLIENT_NAME').AsString;
AssertEquals(LValue + ' <> ' + cDESCRIPTION + LRandon, LValue, cDESCRIPTION + LRandon);
end;
procedure TTestDBEBrZeos.TestExecuteDirectParams;
var
LParams: TParams;
LRandon: String;
LValue: String;
begin
LRandon := IntToStr( Random(9999) );
LParams := TParams.Create(nil);
try
with LParams.Add as TParam do
begin
Name := 'CLIENT_NAME';
DataType := ftString;
Value := cDESCRIPTION + LRandon;
ParamType := ptInput;
end;
with LParams.Add as TParam do
begin
Name := 'CLIENT_ID';
DataType := ftInteger;
Value := 1;
ParamType := ptInput;
end;
FDBConnection.ExecuteDirect(cSQLUPDATEPARAM, LParams);
FDBResultSet := FDBConnection.CreateResultSet(Format(cSQLSELECT, ['1']));
LValue := FDBResultSet.FieldByName('CLIENT_NAME').AsString;
AssertEquals(LValue + ' <> ' + cDESCRIPTION + LRandon, LValue, cDESCRIPTION + LRandon);
finally
LParams.Free;
end;
end;
procedure TTestDBEBrZeos.TestExecuteScript;
begin
end;
procedure TTestDBEBrZeos.TestAddScript;
begin
end;
procedure TTestDBEBrZeos.TestExecuteScripts;
begin
end;
procedure TTestDBEBrZeos.TestIsConnected;
begin
AssertEquals('FConnection.IsConnected = false', false, FDBConnection.IsConnected);
end;
procedure TTestDBEBrZeos.TestInTransaction;
begin
FDBConnection.Connect;
FDBConnection.StartTransaction;
AssertEquals('FConnection.InTransaction <> FFDConnection.InTransaction', FDBConnection.InTransaction, FConnection.InTransaction);
FDBConnection.Rollback;
FDBConnection.Disconnect;
end;
procedure TTestDBEBrZeos.TestCreateQuery;
var
LValue: String;
LRandon: String;
begin
LRandon := IntToStr( Random(9999) );
FDBQuery := FDBConnection.CreateQuery;
FDBQuery.CommandText := Format(cSQLUPDATE, [QuotedStr(cDESCRIPTION + LRandon), '1']);
FDBQuery.ExecuteDirect;
FDBQuery.CommandText := Format(cSQLSELECT, ['1']);
LValue := FDBQuery.ExecuteQuery.FieldByName('CLIENT_NAME').AsString;
AssertEquals(LValue + ' <> ' + cDESCRIPTION + LRandon, LValue, cDESCRIPTION + LRandon);
end;
procedure TTestDBEBrZeos.TestCreateResultSet;
begin
FDBResultSet := FDBConnection.CreateResultSet(Format(cSQLSELECT, ['1']));
AssertEquals('FDBResultSet.RecordCount = ' + IntToStr(FDBResultSet.RecordCount), 1, FDBResultSet.RecordCount);
end;
procedure TTestDBEBrZeos.TestExecuteSQL;
begin
FDBResultSet := FDBConnection.ExecuteSQL( Format(cSQLSELECT, ['1']) );
AssertEquals('FDBResultSet.RecordCount = ' + IntToStr(FDBResultSet.RecordCount), 1, FDBResultSet.RecordCount);
end;
procedure TTestDBEBrZeos.TestStartTransaction;
begin
FDBConnection.StartTransaction;
AssertEquals('FConnection.InTransaction = true', True, FDBConnection.InTransaction);
end;
procedure TTestDBEBrZeos.TestCommit;
begin
TestStartTransaction;
FDBConnection.Commit;
AssertEquals('FConnection.InTransaction = false', False, FDBConnection.InTransaction);
end;
procedure TTestDBEBrZeos.TestRollback;
begin
TestStartTransaction;
FDBConnection.Rollback;
AssertEquals('FConnection.InTransaction = false', False, FDBConnection.InTransaction);
end;
procedure TTestDBEBrZeos.SetUp;
begin
FConnection := TZConnection.Create(nil);
FConnection.LoginPrompt := False;
FConnection.Protocol := 'sqlite';
FConnection.Database := 'database.db3';
FDBConnection := TFactoryUniDAC.Create(FConnection, dnSQLite);
end;
procedure TTestDBEBrZeos.TearDown;
begin
if Assigned(FConnection) then
FreeAndNil(FConnection);
end;
initialization
RegisterTest(TTestDBEBrZeos);
end.
|
unit Model.SortResults;
interface
uses
System.TimeSpan;
type
TSortResults = class { todo: guard na property }
private
FSwapCounter: Integer;
FName: string;
FDataSize: Integer;
FElapsedTime: TTimeSpan;
public
property DataSize: Integer read FDataSize write FDataSize;
property Name: string read FName write FName;
property SwapCounter: Integer read FSwapCounter write FSwapCounter;
property ElapsedTime: TTimeSpan read FElapsedTime write FElapsedTime;
end;
implementation
end.
|
unit uOperations;
interface
uses
System.SysUtils,
System.Math;
type
TOperations = class
private
function Sort(Const pWord: string): string;
public
function SortLetters(Const pWord: string): string;
function CountOccurrences(Const pWord, pLetter: string): integer;
function RemoveAccents(Const pWord: string): string;
end;
EWordIsEmpty = Class(Exception);
ELetterIsEmpty = Class(Exception);
ENoAlphaNumeric = Class(Exception);
implementation
{ TOperations }
function TOperations.CountOccurrences(const pWord, pLetter: string): integer;
var
vLetter: string;
begin
if pWord.Trim.IsEmpty then
raise EWordIsEmpty.Create('Word is empty');
if pLetter.Trim.IsEmpty then
raise ELetterIsEmpty.Create('Letter is empty');
Result := ZeroValue;
for vLetter in pWord do
if LowerCase(vLetter) = LowerCase(pLetter) then
Inc(Result);
end;
function TOperations.RemoveAccents(const pWord: string): string;
type
USAscii20127 = type AnsiString(20127);
const
cCharsValid = ['0'..'9', 'a'..'z', 'A'..'Z'];
var
vLetter: char;
begin
Result := string(USAscii20127(pWord));
for vLetter in Result do
if not CharInSet(vLetter, cCharsValid) then
raise ENoAlphaNumeric.Create('Word invalid');
end;
function TOperations.SortLetters(const pWord: string): string;
begin
Result := Self.Sort(pWord);
end;
function TOperations.Sort(Const pWord: string): string;
var
vIndexA: integer;
vIndexB: integer;
vWord: string;
vTemp: char;
begin
vWord := pWord;
for vIndexA := PositiveValue to Pred(pWord.Length) do
begin
for vIndexB := Succ(vIndexA) to pWord.Length do
begin
if LowerCase(vWord[vIndexA]) > LowerCase(vWord[vIndexB]) then
begin
vTemp := vWord[vIndexA];
vWord[vIndexA] := vWord[vIndexB];
vWord[vIndexB] := vTemp;
end;
end;
end;
Result := vWord;
end;
end.
|
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä
Msg : 393 of 473
From : Hagen Lehmann 2:244/59.1 12 Apr 93 14:00
To : Timothy Glenn
Subj : Search procedure
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
Hi Timothy,
> TG> Can someone help me make a search procedure that will read
> TG> from a record format, from the disk!!!
The easiest way to search a record in a file is to read the records from file
and compare them with the record that is to be searched.
If you simply want to search for a string then I've got something for you. ;-)
Look at this function: }
Function Search(SearchFor : String;
FileName : String) : LongInt;
Var F : File;
Pos,Dummy : LongInt;
BufSize,ReadNum : Word;
Buffer : ^Byte;
Found : Boolean;
Function SearchString(Var Data;
Size : Word;
Str : String) : LongInt;
Var S : String;
Loop : LongInt;
Found : Boolean;
L : Byte ABSOLUTE Str;
Begin
Loop := -1;
Found := False;
If L>0 Then { I don't search for empty strings, I'm not crazy }
Repeat
Inc(Loop);
Move(Mem[Seg(Data):Loop], { convert buffer into string }
Mem[Seg(S):Ofs(S)+1],L+1);
S[0] := Char(L);
If S=Str Then Found := True; { search for string }
Until Found Or (Loop=Size-L);
If Found Then SearchString := Loop { that's the file position }
Else SearchString := -1; { I couldn't find anything }
End;
Begin
Search := -1;
If MaxAvail>65535 Then BufSize := 65535 { check available heap }
Else BufSize := MaxAvail;
If (BufSize>0) And (BufSize>Length(SearchFor)) Then
Begin
GetMem(Buffer,BufSize); { reserve heap for buffer }
Assign(F,FileName);
Reset(F,1); { open file }
If IOResult=0 Then
Begin
Pos := 0;
Found := False;
Repeat
BlockRead(F,Buffer^,BufSize,ReadNum); { read buffer }
If ReadNum>0 Then { anything ok? }
Begin
Dummy := SearchString(Buffer^,ReadNum,SearchFor);
If Dummy<>-1 Then { string has been found }
Begin
Found := True; { set found flag }
Inc(Pos,Dummy);
End
Else
Begin
Inc(Pos,ReadNum-Length(SearchFor));
Seek(F,Pos); { set new file position }
End;
End;
Until Found Or (ReadNum<>BufSize);
If Found Then Search := Pos { string has been found }
Else Search := -1; { string hasn't been found }
Close(F);
End;
Release(Buffer); { release reserved heap }
End;
End; |
{ ******************************************************* }
{ }
{ Framework Menus }
{ }
{ Copyright (C) 2014 DR2G SISTEMAS }
{ }
{ ******************************************************* }
UNIT DanFW.Menus;
INTERFACE
USES System.Classes, Winapi.Windows, Vcl.Menus, Vcl.controls, Vcl.ImgList,
Vcl.Graphics, Vcl.GraphUtil;
PROCEDURE SetMenu_AlignLeft(MainMenu: TMenu; MenuItem: TMenuItem);
PROCEDURE SetMenu_TagVisible(MainMenu: TMenu; Tag: NativeInt;
Value: Boolean = true);
FUNCTION DisableImagelist(AImageList: TCustomImageList): TImageList;
// Type
// { procedimientos para temas de menus }
// TMenuDrawItem = procedure(Sender: TObject; ACanvas: TCanvas; ARect: TRect;
// Selected: Boolean) of object;
// TMenuMeasureItem = procedure(Sender: TObject; ACanvas: TCanvas;
// var Width, Height: Integer) of object;
{ procedimientos para menues }
type
TMenuDrawEvents = class
class procedure MenuDrawItem(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; Selected: Boolean);
class procedure MenuMeasureItem(Sender: TObject; ACanvas: TCanvas;
var Width, Height: Integer);
end;
// procedure SetMenuItemsDrawItem(AMenu: TMenu);
// procedure SetMenuItemsMeasureItem(AMenu: TMenu);
// procedure DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean);
// procedure MeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer);
IMPLEMENTATION
const RICHMENU_MARG_X = 4; RICHMENU_MARG_Y = 2; RICHMENU_SEPARATOR_LEADING = 6;
RICHMENU_GUTTER_WIDTH = 26;
RICHMENU_SEPARATOR_BACKGROUND_COLOR = $00EEE7DD;
RICHMENU_SEPARATOR_LINE_COLOR = $00C5C5C5; RICHMENU_GUTTER_COLOR = $00EEEEE9;
RICHMENU_ITEM_BACKGROUND_COLOR = $00FAFAFA;
RICHMENU_ITEM_SELECTED_COLOR = $00E6D5CB; RICHMENU_FONT_COLOR = $006E1500;
RICHMENU_FONT_DISABLED_COLOR = $00DEC5D8;
RICHMENU_GRADIENT_START1 = $00EFE8E4; RICHMENU_GRADIENT_END1 = $00DEC5B8;
RICHMENU_GRADIENT_START2 = $00D8BAAB; RICHMENU_GRADIENT_END2 = $00EFE8E4;
///
PROCEDURE SetMenu_AlignLeft(MainMenu: TMenu; MenuItem: TMenuItem);
VAR mm: HMENU; mii: tmenuiteminfo; buffer: ARRAY [0 .. 79] OF char;
BEGIN
mm := MainMenu.Handle;
// GET Help Menu Item Info
mii.cbsize := sizeof(mii);
mii.fmask := miim_type;
mii.dwtypedata := buffer;
mii.cch := sizeof(buffer);
getmenuiteminfo(mm, MenuItem.command, false, mii);
// SET Help Menu Item Info
mii.ftype := mii.ftype OR mft_rightjustify;
setmenuiteminfo(mm, MenuItem.command, false, mii);
UpdateWindow(MainMenu.Handle);
END;
PROCEDURE SetMenu_TagVisible(MainMenu: TMenu; Tag: NativeInt;
Value: Boolean = true);
VAR m: TMenuItem;
BEGIN
FOR m IN MainMenu.Items DO BEGIN
IF m.Tag = Tag THEN m.Visible := Value;
END;
END;
FUNCTION DisableImagelist(AImageList: TCustomImageList): TImageList;
CONST
// MaskColor = 5757;
MaskColor = $00EAEAEA;
VAR ImgList: TImageList; ABitmap: TBitmap; i: Integer;
FUNCTION ConvertColor(AColor: TColor): TColor;
VAR PixelColor, NewColor: Integer;
BEGIN
PixelColor := ColorToRGB(AColor);
NewColor := Round((((PixelColor SHR 16) + ((PixelColor SHR 8) AND $00FF) +
(PixelColor AND $0000FF)) DIV 3)) DIV 2 + 125; // 96;
Result := RGB(NewColor, NewColor, NewColor);
END;
PROCEDURE ConvertColors(ABitmap: TBitmap);
VAR x, y: Integer;
BEGIN
FOR x := 0 TO ABitmap.Width - 1 DO
FOR y := 0 TO ABitmap.Height - 1 DO BEGIN
ABitmap.Canvas.Pixels[x, y] :=
ConvertColor(ABitmap.Canvas.Pixels[x, y]);
END;
END;
BEGIN
ABitmap := TBitmap.Create;
TRY
ImgList := TImageList.Create(NIL);
ImgList.Width := AImageList.Width;
ImgList.Height := AImageList.Height;
ImgList.Clear;
FOR i := 0 TO AImageList.Count - 1 DO BEGIN
ABitmap.Canvas.Brush.Color := MaskColor;
ABitmap.Canvas.FillRect(rect(0, 0, AImageList.Width, AImageList.Height));
AImageList.GetBitmap(i, ABitmap);
ConvertColors(ABitmap);
ImgList.AddMasked(ABitmap, ConvertColor(MaskColor));
END;
Result := ImgList;
FINALLY ABitmap.Free;
END;
END;
{ TMenuDrawEvents }
class procedure TMenuDrawEvents.MenuDrawItem(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; Selected: Boolean);
var hintStr: string; item: TMenuItem; r: TRect; hasGutter: Boolean;
begin
item := TMenuItem(Sender);
hasGutter := item.GetImageList <> nil;
// Background:
ACanvas.Brush.Style := bsSolid;
ACanvas.Brush.Color := RICHMENU_SEPARATOR_BACKGROUND_COLOR;
ACanvas.FillRect(ARect);
// Lines:
ACanvas.Pen.Color := RICHMENU_SEPARATOR_LINE_COLOR;
ACanvas.Polyline([point(ARect.Left, ARect.Bottom - 2), point(ARect.Right,
ARect.Bottom - 2)]);
ACanvas.Pen.Color := RICHMENU_ITEM_BACKGROUND_COLOR;
ACanvas.Polyline([point(ARect.Left, ARect.Bottom - 1), point(ARect.Right,
ARect.Bottom - 1)]);
// Text
hintStr := item.Hint;
if hintStr <> '' then begin
// Text:
ACanvas.Brush.Style := bsClear;
ACanvas.Font.Style := [fsBold];
ACanvas.Font.Color := RICHMENU_FONT_COLOR;
r.Left := ARect.Left + RICHMENU_MARG_X;
if hasGutter then inc(r.Left, RICHMENU_SEPARATOR_LEADING);
r.Right := ARect.Right - RICHMENU_MARG_X;
r.Top := ARect.Top;
r.Bottom := ARect.Bottom;
DrawText(ACanvas.Handle, PChar(hintStr), length(hintStr), r,
DT_LEFT or DT_EXTERNALLEADING or DT_SINGLELINE or DT_VCENTER);
end else if hasGutter then begin
// Gutter
ACanvas.Brush.Style := bsSolid;
ACanvas.Brush.Color := RICHMENU_GUTTER_COLOR;
r := ARect;
r.Right := RICHMENU_GUTTER_WIDTH;
ACanvas.FillRect(r);
ACanvas.Pen.Color := RICHMENU_SEPARATOR_LINE_COLOR;
ACanvas.Polyline([point(r.Right, r.Top), point(r.Right, r.Bottom)]);
end;
{ }
end;
class procedure TMenuDrawEvents.MenuMeasureItem(Sender: TObject;
ACanvas: TCanvas; var Width, Height: Integer);
begin
{ }
end;
END.
|
{ Subroutine STRING_CMLINE_END_ABORT
*
* Print appropriate message and abort if there are any more unread tokens left
* on the command line.
}
module string_CMLINE_END_ABORT;
define string_cmline_end_abort;
%include 'string2.ins.pas';
procedure string_cmline_end_abort; {abort if unread tokens left on command line}
var
token: string_var32_t; {for trying to read next command line token}
stat: sys_err_t;
msg_parms: {references parameters passed to message}
array[1..1] of sys_parm_msg_t;
begin
token.max := sizeof(token.str); {init var string}
string_cmline_token (token, stat); {try to read next command line token}
if string_eos(stat) then return; {really did hit end of command line ?}
sys_error_abort (stat, 'string', 'cmline_opt_err', nil, 0); {some other error ?}
sys_msg_parm_vstr (msg_parms[1], token);
sys_message_parms ('string', 'cmline_extra_token', msg_parms, 1);
sys_bomb;
end;
|
program usingVariantType;
{
Free Pascal autolinks the "variant" unit.
But depending on the compiler you might have to link it yourself.
with
uses variatns;
}
type
PrimaryColor = (red, green, blue);
var
{ variant types accept any other simple type }
{ and type is determined during runtime }
v : variant;
i : integer;
r : real;
c : PrimaryColor;
as : ansistring;
begin
i := 100;
v := i; { assigning an integer }
writeln('variant as integer: ', v);
r := 123.345;
v := r; { assigning a real }
writeln('varian as real: ', v);
c := red;
v := c; { assinging enum type PrimaryColor }
writeln('variant as enum data: ', v);
as := 'this is an AnsiString';
v := as;
writeln('variant as AnsiString: ', v);
writeln;
end.
|
unit DServicos;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ADPadrao, Db, DBTables, DBClient, Grids;
type
TPosicionaCamposFServicos = (
pcFServicosNenhum,
pcFServicosCODServico,
pcFServicosDesServico,
pcFServicosCODFarmaceutico,
pcFServicosCODPaciente);
TPosicionaCamposFServicosItem = (
pcFServicosItemNenhum,
pcFServicosItemCodMedicamento,
pcFServicosItemVlrMedicamento);
TServicoItem = class(TCollectionItem)
private
FIteMedicamento: Integer;
FCodMedicamento: Integer;
FDesMedicamento: String;
FVlrMedicamento: Extended;
FObsMedicamento: String;
procedure SetIteMedicamento(const Value: Integer);
procedure SetCodMedicamento(const Value: Integer);
procedure SetDesMedicamento(const Value: String);
procedure SetVlrMedicamento(const Value: Extended);
procedure SetObsMedicamento(const Value: String);
{ private declarations }
protected
{ protected declarations }
public
property IteMedicamento: Integer read FIteMedicamento write SetIteMedicamento;
property CodMedicamento: Integer read FCodMedicamento write SetCodMedicamento;
property DesMedicamento: String read FDesMedicamento write SetDesMedicamento;
property VlrMedicamento: Extended read FVlrMedicamento write SetVlrMedicamento;
property ObsMedicamento: String read FObsMedicamento write SetObsMedicamento;
{ public declarations }
published
{ published declarations }
end;
TListaServicoItem = class(TCollection)
private
FStgServicoItem: TStringGrid;
procedure SetStgServicoItem(const Value: TStringGrid);
procedure AtualizaSequenciaIteMedicamento;
{ private declarations }
protected
{ protected declarations }
public
procedure InicializaCabecalhoStg(vptStgServicoItem: TStringGrid);
procedure RefreshStgServicoItem;
property StgServicoItem: TStringGrid read FStgServicoItem write SetStgServicoItem;
procedure Delete(Index: Integer);
{ public declarations }
published
{ published declarations }
end;
TDmServicos = class(TADmPadrao)
QryCadastroCODSERVICO: TIntegerField;
QryCadastroDESSERVICO: TStringField;
QryCadastroDATSERVICO: TDateTimeField;
QryCadastroCODFARMACEUTICO: TIntegerField;
QryCadastroCODPACIENTE: TIntegerField;
QryCadastroNUMPRESSAO1: TIntegerField;
QryCadastroNUMPRESSAO2: TIntegerField;
QryCadastroNUMGLICEMIA: TIntegerField;
QryCadastroVLRTOTAL: TFloatField;
QryCadastroNOMFARMACEUTICO: TStringField;
QryCadastroNOMPACIENTE: TStringField;
QryCadastroNUMTEMPERATURA: TFloatField;
QryCadastroTIPATENCAODOMICILIAR: TStringField;
QryCadastroOBSSERVICO: TStringField;
procedure QryCadastroBeforePost(DataSet: TDataSet);
procedure QryCadastroAfterPost(DataSet: TDataSet);
procedure QryCadastroCalcFields(DataSet: TDataSet);
procedure QryCadastroNewRecord(DataSet: TDataSet);
procedure DmPadraoDestroy(Sender: TObject);
procedure QryCadastroAfterScroll(DataSet: TDataSet);
procedure QryCadastroBeforeCancel(DataSet: TDataSet);
procedure QryCadastroBeforeDelete(DataSet: TDataSet);
private
FPosicionaCamposFServicos: TPosicionaCamposFServicos;
FListaServicoItem: TListaServicoItem;
FPosicionaCamposFServicosItem: TPosicionaCamposFServicosItem;
function GetListaServicoItem: TListaServicoItem;
procedure ValidaCampos(DataSet: TDataSet);
procedure SetPosicionaCamposFServicos(
const Value: TPosicionaCamposFServicos);
procedure SetPosicionaCamposFServicosItem(
const Value: TPosicionaCamposFServicosItem);
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
procedure GravaTodasTabelas;
property PosicionaCamposFServicos: TPosicionaCamposFServicos
read FPosicionaCamposFServicos write SetPosicionaCamposFServicos;
property PosicionaCamposFServicosItem: TPosicionaCamposFServicosItem
read FPosicionaCamposFServicosItem write SetPosicionaCamposFServicosItem;
procedure PopulaCodFarmaceutico(vpsCod: String);
procedure PopulaCodPaciente(vpsCod: String);
procedure EditServico;
function Pesquisa(vpsChaveDeBusca: String;
vptBtnCadastro: TObject = nil): String;
property ListaServicoItem: TListaServicoItem read GetListaServicoItem;
procedure ListaServicoItemFree;
procedure AtualizaValorTotal;
function ValidaCamposServicoItem(
vpsConteudo: String;
vptPosicionaCamposFServicosItem: TPosicionaCamposFServicosItem): String;
procedure AlteraServicoItem(
vpiIteServico: Integer;
vpsCodMedicamento,
vpsDesMedicamento,
vpsVlrMedicamento,
vpsObsMedicamento: String);
procedure AdicionaServicoItem(
vpsCodMedicamento,
vpsDesMedicamento,
vpsVlrMedicamento,
vpsObsMedicamento: String;
vptStgServicoItem: TStringGrid);
procedure PopulaCampos(
vpiItemIndex: Integer;
var vpsCodMedicamento: String;
var vpsDesMedicamento: String;
var vpsVlrMedicamento: String;
var vpsObsMedicamento: String);
procedure GravaListaServicoItem;
procedure PopulaListaServicoItem;
procedure DeletaListaServicoItem;
{ Public declarations }
end;
var
DmServicos: TDmServicos;
implementation
uses
UFerramentas, UFerramentasB, DConexao, SPesquisa, DGeral;
{$R *.DFM}
constructor TDmServicos.Create(AOwner: TComponent);
begin
NomeEntidade := 'Serviço';
NomeCampoChave := 'CodServico';
inherited Create(AOwner);
end;
procedure TDmServicos.DmPadraoDestroy(Sender: TObject);
begin
inherited;
ListaServicoItemFree;
end;
procedure TDmServicos.ListaServicoItemFree;
//var
// vli1: Integer;
begin
if Assigned(FListaServicoItem) then
begin
//for vli1 := 0 to FListaServicoItem.Count -1 do
// FListaServicoItem.Items[vli1].Free;
FListaServicoItem.Free;
FListaServicoItem := nil;
end
end;
function TDmServicos.GetListaServicoItem: TListaServicoItem;
begin
if not Assigned(FListaServicoItem) then
FListaServicoItem := TListaServicoItem.Create(TServicoItem);
Result := FListaServicoItem;
end;
procedure TDmServicos.QryCadastroBeforePost(DataSet: TDataSet);
begin
inherited;
ValidaCampos(DataSet);
end;
procedure TDmServicos.ValidaCampos(DataSet: TDataSet);
begin
PosicionaCamposFServicos := pcFServicosNenhum;
if (DataSet.State in [dsEdit]) then
begin
if DataSet.FieldByName('CodServico').AsString = '' then
begin
PosicionaCamposFServicos := pcFServicosCodServico;
raise Exception.Create('O código do Serviço é obrigatório! ');
end;
end;
if DataSet.FieldByName('DesServico').AsString = '' then
begin
PosicionaCamposFServicos := pcFServicosDesServico;
raise Exception.Create('O Descrição do Serviço é obrigatório! ');
end;
if DataSet.FieldByName('CodFarmaceutico').AsString = '' then
begin
PosicionaCamposFServicos := pcFServicosCodFarmaceutico;
raise Exception.Create('O código do farmaceutico é obrigatório! ');
end;
if DataSet.FieldByName('CodPaciente').AsString = '' then
begin
PosicionaCamposFServicos := pcFServicosCodPaciente;
raise Exception.Create('O código do paciente é obrigatório! ');
end;
end;
procedure TDmServicos.GravaTodasTabelas;
begin
if (QryCadastro.State in [dsEdit, dsInsert]) then
QryCadastro.Post;
Atualizar;
end;
procedure TDmServicos.SetPosicionaCamposFServicos(
const Value: TPosicionaCamposFServicos);
begin
FPosicionaCamposFServicos := Value;
end;
procedure TDmServicos.QryCadastroAfterPost(DataSet: TDataSet);
begin
try
BeginTransaction;
inherited;
GravaListaServicoItem;
CommitTransaction;
except
RollbackTransaction;
raise;
end;
QryCadastro.Last;
end;
procedure TDmServicos.EditServico;
begin
if not (QryCadastro.State in [dsEdit, dsInsert]) then
QryCadastro.Edit;
end;
procedure TDmServicos.PopulaCodFarmaceutico(vpsCod: String);
var
vltQry: TQuery;
begin
if vpsCod = QryCadastroCODFARMACEUTICO.AsString then
Exit;
if vpsCod = '' then
begin
EditServico;
QryCadastroCODFARMACEUTICO.Clear;
Exit;
end;
vltQry := TQuery.Create(nil);
try
try
vltQry.Close;
vltQry.Databasename := DmConexao.DbsConexao.DatabaseName;
vltQry.Sql.Text :=
'SELECT * '+#13+
'FROM Farmaceutico '+#13+
'WHERE CODFarmaceutico = :CODFarmaceutico '+#13;
vltQry.ParamByName('CODFarmaceutico').AsString := vpsCod;
vltQry.Open;
if vltQry.IsEmpty then
raise Exception.Create(
'Farmaceutico [' + vpsCod + '] inexistente! ');
EditServico;
QryCadastroCODFarmaceutico.AsString :=
vltQry.FieldByName('CODFarmaceutico').AsString;
except
on E: Exception do
raise Exception.Create(
'Erro na pesquisa! ' + #13 + #13 +
'[' + E.Message + ']!');
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
procedure TDmServicos.PopulaCodPaciente(vpsCod: String);
var
vltQry: TQuery;
begin
if vpsCod = QryCadastroCODPaciente.AsString then
Exit;
if vpsCod = '' then
begin
EditServico;
QryCadastroCODPaciente.Clear;
Exit;
end;
vltQry := TQuery.Create(nil);
try
try
vltQry.Close;
vltQry.Databasename := DmConexao.DbsConexao.DatabaseName;
vltQry.Sql.Text :=
'SELECT * '+#13+
'FROM Paciente '+#13+
'WHERE CODPaciente = :CODPaciente '+#13;
vltQry.ParamByName('CODPaciente').AsString := vpsCod;
vltQry.Open;
if vltQry.IsEmpty then
raise Exception.Create(
'Paciente [' + vpsCod + '] inexistente! ');
EditServico;
QryCadastroCODPaciente.AsString :=
vltQry.FieldByName('CODPaciente').AsString;
except
on E: Exception do
raise Exception.Create(
'Erro na pesquisa! ' + #13 + #13 +
'[' + E.Message + ']!');
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
procedure TDmServicos.QryCadastroCalcFields(DataSet: TDataSet);
var
vltQry: TQuery;
begin
inherited;
vltQry := TQuery.Create(nil);
try
try
vltQry.Close;
vltQry.Databasename := DmConexao.DbsConexao.DatabaseName;
vltQry.Sql.Text :=
'SELECT * '+#13+
'FROM Farmaceutico '+#13+
'WHERE CODFarmaceutico = ' + IntToStr(QryCadastroCODFarmaceutico.AsInteger) + ' '+#13;
vltQry.Open;
QryCadastroNOMFARMACEUTICO.AsString := '';
if not vltQry.IsEmpty then
QryCadastroNOMFARMACEUTICO.AsString := vltQry.FieldByName('NOMFARMACEUTICO').AsString;
except
on E: Exception do
raise Exception.Create(
'Erro ao localizar registros no CalcFields! ' + #13 + #13 +
'[' + vltQry.Sql.Text + '] ' + #13 + #13 +
'[' + E.Message + ']!');
end;
try
vltQry.Close;
vltQry.Databasename := DmConexao.DbsConexao.DatabaseName;
vltQry.Sql.Text :=
'SELECT * '+#13+
'FROM Paciente '+#13+
'WHERE CODPaciente = ' + IntToStr(QryCadastroCODPACIENTE.AsInteger) + ' '+#13;
vltQry.Open;
QryCadastroNOMPACIENTE.AsString := '';
if not vltQry.IsEmpty then
QryCadastroNOMPACIENTE.AsString := vltQry.FieldByName('NOMPACIENTE').AsString;
except
on E: Exception do
raise Exception.Create(
'Erro ao localizar registros no CalcFields! ' + #13 + #13 +
'[' + vltQry.Sql.Text + '] ' + #13 + #13 +
'[' + E.Message + ']!');
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
procedure TDmServicos.QryCadastroNewRecord(DataSet: TDataSet);
begin
inherited;
QryCadastroDESSERVICO.AsString := 'Consulta ' + DateTimeToStr(DataHoraAtual);
QryCadastroTIPATENCAODOMICILIAR.AsString := 'N';
QryCadastroDATSERVICO.Value := DataHoraAtual;
end;
function TDmServicos.Pesquisa(vpsChaveDeBusca: String; vptBtnCadastro: TObject = nil): String;
begin
try
Result :=
FNCPesquisa(
vptBtnCadastro,
'Cadastro dos serviços',
vpsChaveDeBusca,
'CODServico AS Codigo',
DmConexao.DbsConexao.DatabaseName,
'Servico, Paciente ',
'Servico.CODServico AS Codigo',
'Servico.DesServico AS Nome',
'Servico.DatServico as Data',
'paciente.nompaciente as Paciente',
'Servico.VlrTotal as Total',
'Servico.codpaciente = paciente.codpaciente');
except
on E: Exception do
raise Exception.Create(
'Erro na pesquisa! ' + #13 + #13 +
'[' + E.Message + ']!');
end;
end;
procedure TDmServicos.AlteraServicoItem(
vpiIteServico: Integer;
vpsCodMedicamento,
vpsDesMedicamento,
vpsVlrMedicamento,
vpsObsMedicamento: String);
var
vli1: Integer;
begin
for vli1 := 0 to ListaServicoItem.Count -1 do
begin
if TServicoItem(ListaServicoItem.Items[vli1]).IteMedicamento = vpiIteServico then
begin
TServicoItem(ListaServicoItem.Items[vli1]).CodMedicamento :=
StrToInt(ValidaCamposServicoItem(vpsCodMedicamento, pcFServicosItemCodMedicamento));
TServicoItem(ListaServicoItem.Items[vli1]).DesMedicamento := vpsDesMedicamento;
TServicoItem(ListaServicoItem.Items[vli1]).VlrMedicamento :=
StrToFloat(ValidaCamposServicoItem(vpsVlrMedicamento, pcFServicosItemVlrMedicamento));
TServicoItem(ListaServicoItem.Items[vli1]).ObsMedicamento := vpsObsMedicamento;
Break;
end;
end;
ListaServicoItem.RefreshStgServicoItem;
AtualizaValorTotal;
end;
procedure TDmServicos.AtualizaValorTotal;
var
vli1: Integer;
vleValorTotal: Extended;
begin
if not (QryCadastro.State in [dsEdit, dsInsert]) then
Exit;
vleValorTotal := 0.0;
for vli1 := 0 to ListaServicoItem.Count -1 do
vleValorTotal := vleValorTotal + TServicoItem(ListaServicoItem.Items[vli1]).VlrMedicamento;
QryCadastroVLRTOTAL.Value := vleValorTotal;
end;
function TDmServicos.ValidaCamposServicoItem(
vpsConteudo: String;
vptPosicionaCamposFServicosItem: TPosicionaCamposFServicosItem): String;
begin
case vptPosicionaCamposFServicosItem of
pcFServicosItemCodMedicamento:
begin
try
Result := TDmGeral(DmlG).DmlMedicamentos.ValidaExisteRegistro(vpsConteudo);
except
on E: Exception do
begin
PosicionaCamposFServicosItem := vptPosicionaCamposFServicosItem;
raise Exception.Create(E.Message);
end;
end;
end;
pcFServicosItemVlrMedicamento:
begin
Result := vpsConteudo;
Result := DeletaCharAlfanumerico(Result, ',');
if not ContemNumeros(Result) then
Result := '0.00';
end
else
Result := vpsConteudo;
end;
end;
procedure TDmServicos.AdicionaServicoItem(
vpsCodMedicamento,
vpsDesMedicamento,
vpsVlrMedicamento,
vpsObsMedicamento: String;
vptStgServicoItem: TStringGrid);
var
vltServicoItem: TServicoItem;
begin
vltServicoItem := TServicoItem.Create(ListaServicoItem);
vltServicoItem.CodMedicamento := StrToInt(ValidaCamposServicoItem(vpsCodMedicamento, pcFServicosItemCodMedicamento));
vltServicoItem.DesMedicamento := TDmGeral(DmlG).DmlMedicamentos.QryCadastroDESMEDICAMENTO.AsString;
vltServicoItem.VlrMedicamento := StrToFloat(ValidaCamposServicoItem(vpsVlrMedicamento, pcFServicosItemVlrMedicamento));
vltServicoItem.ObsMedicamento := vpsObsMedicamento;
ListaServicoItem.AtualizaSequenciaIteMedicamento;
ListaServicoItem.StgServicoItem := vptStgServicoItem;
ListaServicoItem.RefreshStgServicoItem;
AtualizaValorTotal;
end;
procedure TDmServicos.PopulaCampos(
vpiItemIndex: Integer;
var vpsCodMedicamento: String;
var vpsDesMedicamento: String;
var vpsVlrMedicamento: String;
var vpsObsMedicamento: String);
begin
if (vpiItemIndex < 0)
or (ListaServicoItem.Count = 0) then
Exit;
vpsCodMedicamento := IntToStr(TServicoItem(ListaServicoItem.Items[vpiItemIndex]).CodMedicamento);
vpsDesMedicamento := TServicoItem(ListaServicoItem.Items[vpiItemIndex]).DesMedicamento;
vpsVlrMedicamento := FormatFloat('#,##0.00', TServicoItem(ListaServicoItem.Items[vpiItemIndex]).VlrMedicamento);
vpsObsMedicamento := TServicoItem(ListaServicoItem.Items[vpiItemIndex]).ObsMedicamento;
end;
{ TServicoItem }
procedure TServicoItem.SetCodMedicamento(const Value: Integer);
begin
FCodMedicamento := Value;
end;
procedure TServicoItem.SetVlrMedicamento(const Value: Extended);
begin
FVlrMedicamento := Value;
end;
procedure TServicoItem.SetObsMedicamento(const Value: String);
begin
FObsMedicamento := Value;
end;
procedure TServicoItem.SetDesMedicamento(const Value: String);
begin
FDesMedicamento := Value;
end;
procedure TServicoItem.SetIteMedicamento(const Value: Integer);
begin
FIteMedicamento := Value;
end;
{ TListaServicoItem }
procedure TListaServicoItem.RefreshStgServicoItem;
var
vli1: Integer;
vliQtdCol: Integer;
function QtdCol(vpbSomaCol: Boolean = True): Integer;
begin
if vpbSomaCol then
vliQtdCol := vliQtdCol + 1;
Result := vliQtdCol;
end;
begin
if StgServicoItem = nil then
Exit;
InicializaCabecalhoStg(StgServicoItem);
if Self.Count = 0 then
Exit;
StgServicoItem.RowCount := Self.Count + 1;
for vli1 := 0 to Self.Count -1 do
begin
vliQtdCol := 0;
StgServicoItem.Cells[QtdCol, vli1+1] := IntToStr(TServicoItem(Self.Items[vli1]).IteMedicamento);
StgServicoItem.Cells[QtdCol, vli1+1] := IntToStr(TServicoItem(Self.Items[vli1]).CodMedicamento);
StgServicoItem.Cells[QtdCol, vli1+1] := TServicoItem(Self.Items[vli1]).DesMedicamento;
StgServicoItem.Cells[QtdCol, vli1+1] := FormatFloat('#,##0.00', TServicoItem(Self.Items[vli1]).VlrMedicamento);
StgServicoItem.Cells[QtdCol, vli1+1] := TServicoItem(Self.Items[vli1]).ObsMedicamento;
end;
StgServicoItem.ColCount := QtdCol;
end;
procedure TListaServicoItem.InicializaCabecalhoStg(vptStgServicoItem: TStringGrid);
var
vliQtdCol: Integer;
function QtdCol(vpbSomaCol: Boolean = True): Integer;
begin
if vpbSomaCol then
vliQtdCol := vliQtdCol + 1;
Result := vliQtdCol;
end;
begin
if vptStgServicoItem = nil then
Exit;
StgServicoItem := vptStgServicoItem;
vliQtdCol := 0;
StgServicoItem.ColWidths[QtdCol(False)] := 10;
StgServicoItem.Cells[QtdCol, 0] := 'Item';
StgServicoItem.Cells[QtdCol(false), 1] := '';
StgServicoItem.ColWidths[QtdCol(False)] := 30;
StgServicoItem.Cells[QtdCol, 0] := 'Código';
StgServicoItem.Cells[QtdCol(false), 1] := '';
StgServicoItem.ColWidths[QtdCol(False)] := 40;
StgServicoItem.Cells[QtdCol, 0] := 'Descrição';
StgServicoItem.Cells[QtdCol(false), 1] := '';
StgServicoItem.ColWidths[QtdCol(False)] := 150;
StgServicoItem.Cells[QtdCol, 0] := 'Valor';
StgServicoItem.Cells[QtdCol(false), 1] := '';
StgServicoItem.ColWidths[QtdCol(False)] := 70;
StgServicoItem.Cells[QtdCol, 0] := 'Observação';
StgServicoItem.Cells[QtdCol(false), 1] := '';
StgServicoItem.ColWidths[QtdCol(False)] := 210;
StgServicoItem.ColCount := QtdCol;
StgServicoItem.RowCount := 2;
end;
procedure TListaServicoItem.SetStgServicoItem(const Value: TStringGrid);
begin
FStgServicoItem := Value;
end;
procedure TListaServicoItem.Delete(Index: Integer);
begin
if Self.Count = 0 then
Exit;
inherited;
AtualizaSequenciaIteMedicamento;
RefreshStgServicoItem;
end;
procedure TListaServicoItem.AtualizaSequenciaIteMedicamento;
var
vli1: Integer;
begin
for vli1 := 0 to Self.Count -1 do
TServicoItem(Self.Items[vli1]).IteMedicamento := vli1 + 1;
end;
procedure TDmServicos.GravaListaServicoItem;
//------------------------------------------------------------------------------
procedure _SalvaListaServicoItem;
var
vli1: Integer;
vltQry: TQuery;
vliCodServico: Integer;
begin
if QryCadastroCODSERVICO.AsInteger = 0 then
vliCodServico := UltimoGeneratorCriado('Servico')
else
vliCodServico := QryCadastroCODSERVICO.AsInteger;
vltQry := TQuery.Create(nil);
try
for vli1 := 0 to ListaServicoItem.Count -1 do
begin
try
vltQry.Close;
vltQry.Databasename := DmConexao.DbsConexao.DatabaseName;
vltQry.Sql.Text :=
'INSERT INTO SERVICOITEM '+#13+
'( CODSERVICO, '+#13+
' ITESERVICO, '+#13+
' CODMEDICAMENTO, '+#13+
' VLRMEDICAMENTO, '+#13+
' OBSMEDICAMENTO) '+#13+
'VALUES '+#13+
'( ' + IntToStr(vliCodServico) + ', '+#13+
' ' + IntToStr(TServicoItem(ListaServicoItem.Items[vli1]).IteMedicamento) + ', '+#13+
' ' + IntToStr(TServicoItem(ListaServicoItem.Items[vli1]).CodMedicamento) + ', '+#13+
' :VLRMEDICAMENTO, '+#13+
' ''' + TServicoItem(ListaServicoItem.Items[vli1]).ObsMedicamento + ''') '+#13;
vltQry.ParamByName('VLRMEDICAMENTO').AsFloat := TServicoItem(ListaServicoItem.Items[vli1]).VlrMedicamento;
vltQry.ExecSql;
except
on E: Exception do
raise Exception.Create(
'Erro ao salvar os itens do serviço! ' + #13 + #13 +
'[' + vltQry.Sql.Text + ']!' + #13 + #13 +
'[' + E.Message + ']!');
end;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
//------------------------------------------------------------------------------
//procedure TDmServicos.GravaListaServicoItem
//------------------------------------------------------------------------------
begin
if QryCadastroCODSERVICO.AsInteger <> 0 then
DeletaListaServicoItem;
if ListaServicoItem.Count > 0 then
_SalvaListaServicoItem;
end;
procedure TDmServicos.QryCadastroAfterScroll(DataSet: TDataSet);
begin
inherited;
PopulaListaServicoItem;
end;
procedure TDmServicos.PopulaListaServicoItem;
var
vltQry: TQuery;
begin
ListaServicoItem.Clear;
ListaServicoItem.InicializaCabecalhoStg(ListaServicoItem.StgServicoItem);
if QryCadastroCODSERVICO.AsInteger = 0 then
Exit;
vltQry := TQuery.Create(nil);
try
try
vltQry.Close;
vltQry.Databasename := DmConexao.DbsConexao.DatabaseName;
vltQry.Sql.Text :=
'SELECT '+#13+
' SERVICOITEM.CodMedicamento, '+#13+
' MEDICAMENTO.DesMedicamento, '+#13+
' SERVICOITEM.VlrMedicamento, '+#13+
' SERVICOITEM.ObsMedicamento '+#13+
'FROM SERVICOITEM '+#13+
'JOIN MEDICAMENTO '+#13+
' ON MEDICAMENTO.CODMEDICAMENTO = SERVICOITEM.CODMEDICAMENTO '+#13+
'WHERE CODSERVICO = ' + QryCadastroCODSERVICO.AsString + ' '+#13+
'ORDER BY CODSERVICO, ITESERVICO '+#13;
vltQry.Open;
except
on E: Exception do
raise Exception.Create(
'Erro ao selecionar os itens do serviço! ' + #13 + #13 +
'[' + vltQry.Sql.Text + ']!' + #13 + #13 +
'[' + E.Message + ']!');
end;
if not vltQry.IsEmpty then
begin
vltQry.First;
while not vltQry.Eof do
begin
AdicionaServicoItem(
vltQry.FieldByName('CodMedicamento').AsString,
vltQry.FieldByName('DesMedicamento').AsString,
FormatFloat('#,##0.00', vltQry.FieldByName('VlrMedicamento').AsFloat),
vltQry.FieldByName('ObsMedicamento').AsString,
ListaServicoItem.StgServicoItem);
vltQry.Next;
end;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
procedure TDmServicos.QryCadastroBeforeCancel(DataSet: TDataSet);
begin
inherited;
PopulaListaServicoItem;
end;
procedure TDmServicos.DeletaListaServicoItem;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
try
vltQry.Close;
vltQry.Databasename := DmConexao.DbsConexao.DatabaseName;
vltQry.Sql.Text :=
'DELETE FROM SERVICOITEM '+#13+
'WHERE CODSERVICO = ' + QryCadastroCODSERVICO.AsString + ' '+#13;
vltQry.ExecSql;
except
on E: Exception do
raise Exception.Create(
'Erro ao excluir os itens do serviço! ' + #13 + #13 +
'[' + vltQry.Sql.Text + ']!' + #13 + #13 +
'[' + E.Message + ']!');
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
procedure TDmServicos.QryCadastroBeforeDelete(DataSet: TDataSet);
begin
inherited;
DeletaListaServicoItem;
end;
procedure TDmServicos.SetPosicionaCamposFServicosItem(
const Value: TPosicionaCamposFServicosItem);
begin
FPosicionaCamposFServicosItem := Value;
end;
end.
|
unit SSLSupportWinshoes;
{
1999-Jan-05 - Kudzu
-Dynamic loading of DLLs made automatic
-Small changes and clean up of code
-Created TWinshoeSSLOptions class
1999-Jan-04 - Kudzu
-This unit created from code written by Gregor Ibic
---
-Original SSL code by Gregor Ibic
}
interface
uses
Classes,
MySSLWinshoe,
WinsockIntf;
type
TSSLVersion = (sslvSSLv2, sslvSSLv23, sslvSSLv3, sslvTLSv1);
TSSLMode = (sslmUnassigned, sslmClient, sslmServer, sslmBoth);
TWinshoeSSLOptions = class(TPersistent)
protected
fsRootCertFile, fsServerCertFile, fsKeyFile: String;
published
property RootCertFile: String read fsRootCertFile write fsRootCertFile;
property ServerCertFile: String read fsServerCertFile write fsServerCertFile;
property KeyFile: String read fsKeyFile write fsKeyFile;
end;
TWinshoeSSLContext = class(TObject)
protected
fMethod: TSSLVersion;
fMode: TSSLMode;
fsRootCertFile, fsServerCertFile, fsKeyFile: String;
fContext: PSSL_CTX;
//
procedure DestroyContext;
function InternalGetMethod: PSSL_METHOD;
function LoadOpenSLLibrary: Boolean;
procedure SetMode(const Value: TSSLMode);
procedure UnLoadOpenSLLibrary;
public
constructor Create;
destructor Destroy; override;
function LoadRootCert: Boolean;
function LoadServerCert: Boolean;
function LoadKey: Boolean;
published
property Method: TSSLVersion read fMethod write fMethod;
property Mode: TSSLMode read fMode write SetMode;
property RootCertFile: String read fsRootCertFile write fsRootCertFile;
property ServerCertFile: String read fsServerCertFile write fsServerCertFile;
property KeyFile: String read fsKeyFile write fsKeyFile;
end;
TWinshoeSSLSocket = class(TObject)
public
fSSL: PSSL;
//
procedure Accept(const pHandle: TSocket; fSSLContext: TWinshoeSSLContext);
procedure Connect(const pHandle: TSocket; fSSLContext: TWinshoeSSLContext);
destructor Destroy; override;
end;
implementation
uses
Winshoes,
SysUtils;
var
DLLLoadCount: Integer = 0;
function PasswordCallback(buf:PChar; size:Integer; rwflag:Integer; userdata: Pointer):Integer; cdecl;
var
Password: String;
begin
Password := 'aaaa' + #0; // Staticaly assigned password
// I use 'aaaa' for now.
// This procedure should call
// some metod to get the password
size := Length(Password) + 1;
StrLCopy(buf, @Password[1], size);
Result := StrLen(buf);
end;
constructor TWinshoeSSLContext.Create;
begin
inherited;
if DLLLoadCount = 0 then begin
if not LoadOpenSLLibrary then begin
raise Exception.Create('Could not load SSL library.');
end;
end;
Inc(DLLLoadCount);
fMethod := sslvSSLv2;
fMode := sslmUnassigned;
end;
destructor TWinshoeSSLContext.Destroy;
begin
DestroyContext;
Dec(DLLLoadCount);
if DLLLoadCount = 0 then begin
UnLoadOpenSLLibrary;
end;
inherited;
end;
procedure TWinshoeSSLContext.DestroyContext;
begin
if fContext <> nil then begin
f_SSL_CTX_free(fContext);
fContext := nil;
end;
end;
function TWinshoeSSLContext.InternalGetMethod: PSSL_METHOD;
begin
if fMode = sslmUnassigned then begin
raise exception.create('Mode has not been set.');
end;
case fMethod of
sslvSSLv2:
case fMode of
sslmServer : Result := f_SSLv2_server_method;
sslmClient : Result := f_SSLv2_client_method;
sslmBoth : Result := f_SSLv2_method;
else
Result := f_SSLv2_method;
end;
sslvSSLv23:
case fMode of
sslmServer : Result := f_SSLv23_server_method;
sslmClient : Result := f_SSLv23_client_method;
sslmBoth : Result := f_SSLv23_method;
else
Result := f_SSLv23_method;
end;
sslvSSLv3:
case fMode of
sslmServer : Result := f_SSLv3_server_method;
sslmClient : Result := f_SSLv3_client_method;
sslmBoth : Result := f_SSLv3_method;
else
Result := f_SSLv3_method;
end;
sslvTLSv1:
case fMode of
sslmServer : Result := f_TLSv1_server_method;
sslmClient : Result := f_TLSv1_client_method;
sslmBoth : Result := f_TLSv1_method;
else
Result := f_TLSv1_method;
end;
else
raise Exception.Create('Error geting SSL method.');
end;
end;
function TWinshoeSSLContext.LoadRootCert: Boolean;
var
pStr: PChar;
error: Integer;
begin
pStr := StrNew(PChar(RootCertFile));
error := f_SSL_CTX_load_verify_locations(
fContext,
pStr,
nil);
if error <= 0 then begin
Result := False
end else begin
Result := True;
end;
StrDispose(pStr);
end;
function TWinshoeSSLContext.LoadServerCert: Boolean;
var
pStr: PChar;
error: Integer;
begin
pStr := StrNew(PChar(ServerCertFile));
error := f_SSL_CTX_use_certificate_file(
fContext,
pStr,
SSL_FILETYPE_PEM);
if error <= 0 then
Result := False
else
Result := True;
StrDispose(pStr);
end;
function TWinshoeSSLContext.LoadKey: Boolean;
var
pStr: PChar;
error: Integer;
begin
Result := True;
pStr := StrNew(PChar(fsKeyFile));
error := f_SSL_CTX_use_certificate_file(
fContext,
pStr,
SSL_FILETYPE_PEM);
if error <= 0 then begin
Result := False;
end;
error := f_SSL_CTX_use_PrivateKey_file(
fContext,
pStr,
SSL_FILETYPE_PEM);
if error <= 0 then begin
Result := False;
end else begin
error := f_SSL_CTX_check_private_key(fContext);
if error <= 0 then begin
Result := False;
end;
end;
StrDispose(pStr);
end;
destructor TWinshoeSSLSocket.Destroy;
begin
if fSSL <> nil then begin
f_SSL_set_shutdown(fSSL, SSL_SENT_SHUTDOWN);
f_SSL_shutdown(fSSL);
f_SSL_free(fSSL);
fSSL := nil;
end;
end;
procedure TWinshoeSSLSocket.Accept(const pHandle: TSocket; fSSLContext: TWinshoeSSLContext);
var
err: Integer;
begin
fSSL := f_SSL_new(fSSLContext.fContext);
if fSSL = nil then exit;
f_SSL_set_fd(fSSL, pHandle);
err := f_SSL_accept(fSSL);
if err <= 0 then exit;
end;
procedure TWinshoeSSLSocket.Connect(const pHandle: TSocket; fSSLContext: TWinshoeSSLContext);
var
error: Integer;
begin
fSSL := f_SSL_new(fSSLContext.fContext);
if fSSL = nil then exit;
f_SSL_set_fd(fSSL, pHandle);
error := f_SSL_connect(fSSL);
if error <= 0 then begin
raise EWinshoeException.Create('Error connecting with SSL.');
end;
end;
function TWinshoeSSLContext.LoadOpenSLLibrary: Boolean;
// Load the OpenSSL library which is wrapped by MySSL
begin
if not MySSLWinshoe.Load then begin
Result := False;
Exit;
end;
f_SSL_load_error_strings;
// Successful loading if true
result := f_SSLeay_add_ssl_algorithms > 0;
end;
procedure TWinshoeSSLContext.SetMode(const Value: TSSLMode);
var
method: PSSL_METHOD;
error: Integer;
begin
if fMode = Value then begin
exit;
end;
fMode := Value;
// Destroy the context first
DestroyContext;
if fMode <> sslmUnassigned then begin
// get SSL method constant
method := InternalGetMethod;
// create new SSL context
fContext := f_SSL_CTX_new(method);
if fContext = nil then begin
raise Exception.Create('Error creating SSL context.');
end;
// assign a password lookup routine
f_SSL_CTX_set_default_passwd_cb(fContext, @PasswordCallback);
// load CA certificate file
{TODO Not sure when exceptions should be raised. Gregor?}
if not LoadRootCert then begin
raise Exception.Create('Could not load root certificate.');
end else if not LoadServerCert then begin
raise Exception.Create('Could not load server certificate.');
end else if not LoadKey then begin
// raise Exception.Create('Could not load key.');
end;
error := f_SSL_CTX_set_cipher_list(fContext, 'ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP');
if error <= 0 then begin
raise Exception.Create('SetCipher failed.');
end;
end;
end;
procedure TWinshoeSSLContext.UnLoadOpenSLLibrary;
begin
MySSLWinshoe.Unload;
end;
end.
|
(*
* 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.
*
* Contributor(s):
* Jody Dawkins <jdawkins@delphixtreme.com>
*)
unit dSpecUtils;
interface
function CallerAddr: Pointer; assembler;
function GetImplementingObjectFor(AInterface : IInterface) : TObject;
function IsNumeric(const s : string) : Boolean;
function IsAlpha(const s : string) : Boolean;
function IsAlphaNumeric(const s : string) : Boolean;
function IsPrime(N: Integer): Boolean;
function GetValueName(Value : Variant; const PreferredName : string) : string;
implementation
uses Variants;
function IsBadPointer(P: Pointer):boolean; register;
begin
try
Result := (p = nil)
or ((Pointer(P^) <> P) and (Pointer(P^) = P));
except
Result := true;
end
end;
function CallerAddr: Pointer; assembler;
{
This code is straight from the DUnit souce.
TestFramework.pas
}
const
CallerIP = $4;
asm
mov eax, ebp
call IsBadPointer
test eax,eax
jne @@Error
mov eax, [ebp].CallerIP
sub eax, 5 // 5 bytes for call
push eax
call IsBadPointer
test eax,eax
pop eax
je @@Finish
@@Error:
xor eax, eax
@@Finish:
end;
function GetImplementingObjectFor(AInterface : IInterface) : TObject;
{
This code is straight from Chee Wee's productivity experts.
WelcomePageIntf.pas
}
const
AddByte = $04244483;
AddLong = $04244481;
type
PAdjustSelfThunk = ^TAdjustSelfThunk;
TAdjustSelfThunk = packed record
case AddInstruction: longint of
AddByte : (AdjustmentByte: shortint);
AddLong : (AdjustmentLong: longint);
end;
PInterfaceMT = ^TInterfaceMT;
TInterfaceMT = packed record
QueryInterfaceThunk: PAdjustSelfThunk;
end;
TInterfaceRef = ^PInterfaceMT;
var
QueryInterfaceThunk: PAdjustSelfThunk;
begin
Result := Pointer(AInterface);
if Assigned(Result) then
try
QueryInterfaceThunk := TInterfaceRef(AInterface)^. QueryInterfaceThunk;
case QueryInterfaceThunk.AddInstruction of
AddByte: Inc(PChar(Result), QueryInterfaceThunk.AdjustmentByte);
AddLong: Inc(PChar(Result), QueryInterfaceThunk.AdjustmentLong);
else
Result := nil;
end;
except
Result := nil;
end;
end;
function IsNumeric(const s : string) : Boolean;
var
c: Integer;
begin
Result := False;
for c := 1 to Length(s) do
if not (s[c] in ['0'..'9']) then
Exit;
Result := True;
end;
function IsAlpha(const s : string) : Boolean;
var
c: Integer;
begin
Result := False;
for c := 1 to Length(s) do
if not (s[c] in [' '..'/', 'A'..'Z', 'a'..'z']) then
Exit;
Result := True;
end;
function IsAlphaNumeric(const s : string) : Boolean;
var
c: Integer;
begin
Result := False;
for c := 1 to Length(s) do
if not (s[c] in [' '..'/', '0'..'9', 'A'..'Z', 'a'..'z']) then
Exit;
Result := True;
end;
function IsPrime(N: Integer): Boolean;
var
Z: Real;
Max: LongInt;
Divisor: LongInt;
begin
Result := False;
if (N and 1) = 0 then Exit;
Z := Sqrt(N);
Max := Trunc(Z) + 1;
Divisor := 3;
while Max > Divisor do begin
if (N mod Divisor) = 0 then
Exit;
Inc(Divisor, 2);
if (N mod Divisor) = 0 then
Exit;
Inc(Divisor, 4);
end;
Result := True;
end;
function GetValueName(Value : Variant; const PreferredName : string) : string;
var
DataType: TVarType;
begin
if PreferredName <> '' then begin
Result := PreferredName;
Exit;
end;
DataType := VarType(Value);
Result := VarTypeAsText(DataType);
end;
end.
|
unit Plus.Vcl.Form;
interface
uses
System.Classes,
Vcl.ExtCtrls,
Vcl.AppEvnts,
Vcl.Forms;
type
TFormPlus = class(TForm)
private
FFirstTime: boolean;
FApplicationEvents: Vcl.AppEvnts.TApplicationEvents;
procedure OnApplicationIdle(Sender: TObject; var Done: Boolean);
protected
procedure FormReady; virtual; abstract;
procedure FormIdle; virtual; abstract;
public
constructor Create (Owner: TComponent); override;
end;
implementation
{ TFormWithReadyEvent }
constructor TFormPlus.Create(Owner: TComponent);
begin
inherited;
FFirstTime := True;
FApplicationEvents := TApplicationEvents.Create(Self);
FApplicationEvents.OnIdle := OnApplicationIdle;
end;
procedure TFormPlus.OnApplicationIdle(Sender: TObject; var Done: Boolean);
begin
try
if FFirstTime then
FormReady;
FormIdle();
finally
FFirstTime := False;
Done := True;
end;
end;
end.
|
{******************************************************************************
GolezTrol Big Visual Component Library
Copyright (c) 2006-2008 Jos Visser
*******************************************************************************
The contents of this file are distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied.
The Original Code is released Jan 09, 2009.
*******************************************************************************
TBigProcHook allows to override a given function with another by inserting a
JMP to the new function. In the new function you can disable the hook to call
the old function again.
******************************************************************************}
unit BigProcHook;
interface
uses
Windows, sysUtils;
type
PHack = ^THook;
THook = packed record
OpCodeCall : Byte;
OFFTo : Integer;
OpCodeRet : Byte;
end;
TBackup = THook;
TBigProcHook = class
private
FOldProc, FNewProc: Pointer;
FBackupped: Boolean;
FHooked: Boolean;
FOriginal: TBackup;
procedure SetHooked(const Value: Boolean);
protected
procedure InstallHook(Hook: THook);
procedure OverwriteProc;
public
constructor Create(AOldProc, ANewProc: Pointer; Install: Boolean = True);
property Hooked: Boolean read FHooked write SetHooked;
end;
implementation
{ TBigProcHook }
constructor TBigProcHook.Create(AOldProc, ANewProc: Pointer;
Install: Boolean);
begin
inherited Create;
FOldProc := AOldProc;
FNewProc := ANewProc;
if Install then
SetHooked(True);
end;
procedure TBigProcHook.InstallHook(Hook: THook);
var
OldProtect: Cardinal;
begin
// Change protection of oldproc memory
if VirtualProtect(FOldProc, SizeOf(THook), PAGE_EXECUTE_READWRITE, OldProtect) then
try
if not FBackupped then
begin
Move(FOldProc^, FOriginal, SizeOf(THook));
FBackupped := True;
end;
// Overwrite the old procedure
Move(Hook, FOldProc^, SizeOf(THook));
finally
VirtualProtect(FOldProc, SizeOf(THook), OldProtect, OldProtect);
end
else
begin
RaiseLastOSError;
end;
end;
procedure TBigProcHook.OverwriteProc;
// Overwrites the first few calls of OldProc with a call to NewProc and a Ret.
var
Hook: THook;
begin
// Create a tiny little redirection
with Hook do begin
OpCodeCall := $E8; // = CALL}
OFFTo := PAnsiChar(FNewProc) - PAnsiChar(FOldProc) - 5;
OpCodeRet := $C3; // = RET
end;
InstallHook(Hook);
end;
procedure TBigProcHook.SetHooked(const Value: Boolean);
begin
// Toggle hook.
if FHooked <> Value then
if Value then
OverwriteProc
else
InstallHook(FOriginal);
FHooked := Value;
end;
initialization
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
uses
synsock, blcksock, synautil;
{$R *.lfm}
type
{ TUDPDaemon }
TUDPDaemon = class(TThread)
private
Sock: TUDPBlockSocket;
LogData: string;
procedure AddLog;
public
constructor Create;
destructor Destroy; override;
procedure Execute; override;
end;
var
Daemon: TUDPDaemon;
MyIPAddr: string;
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.Lines.Clear;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
sock: TUDPBlockSocket;
begin
sock := TUDPBlockSocket.Create;
try
sock.Family := SF_IP4;
sock.CreateSocket();
sock.Bind('0.0.0.0', '0');
sock.MulticastTTL := 1;
sock.Connect('234.5.6.7', '22401');
if sock.LastError = 0 then
sock.SendString('Hello World! I am ' + MyIPAddr);
finally
sock.Free;
end;
end;
{ TUDPDaemon }
constructor TUDPDaemon.Create;
begin
Sock := TUDPBlockSocket.Create;
Sock.Family := SF_IP4;
FreeOnTerminate := False;
Priority := tpNormal;
inherited Create(False);
end;
destructor TUDPDaemon.Destroy;
begin
Sock.Free;
inherited Destroy;
end;
procedure TUDPDaemon.Execute;
begin
try
Sock.CreateSocket();
Sock.EnableReuse(True);
// better to use MyIP(not to use INADDR_ANY). Because a problem occurs in Windows7.
Sock.Bind(MyIPAddr, '22401');
Sock.AddMulticast('234.5.6.7', MyIPAddr);
while not Terminated do
begin
LogData := Sock.RecvPacket(1000);
LogData := Sock.GetRemoteSinIP + ': ' + LogData;
if Sock.LastError = 0 then
Synchronize(@AddLog);
end;
finally
end;
end;
procedure TUDPDaemon.AddLog;
begin
if Assigned(Form1) then
begin
Form1.Memo1.Lines.BeginUpdate;
try
Form1.Memo1.Lines.Add(LogData);
finally
Form1.Memo1.Lines.EndUpdate;
end;
end;
LogData := '';
end;
procedure _Init;
var
sock: TBlockSocket;
begin
sock := TBlockSocket.Create;
try
sock.Family := SF_IP4;
MyIPAddr := sock.ResolveName(sock.LocalName);
finally
sock.Free;
end;
Daemon := TUDPDaemon.Create;
end;
procedure _Fin;
begin
if Assigned(Daemon) then
begin
Daemon.Terminate;
Daemon.WaitFor;
FreeAndNil(Daemon);
end;
end;
initialization
_Init;
finalization
_Fin;
end.
|
{------------------------------------
功能说明:实现系统信息
创建日期:2008/11/12
作者:wzw
版权:wzw
-------------------------------------}
unit ImpSysInfoIntf;
interface
uses sysUtils, SysInfoIntf, uConst, SysFactory, SvcInfoIntf;
type
TSysInfoObj = class(TInterfacedObject, ISysInfo, ISvcInfo)
private
FLoginUserInfo: TLoginUserInfo;
protected
{ISysInfo}
function RegistryFile: string;//注册表文件
function AppPath: string;//程序目录
function ErrPath: string;//错误日志目录
{ISvcInfo}
function GetModuleName: String;
function GetTitle: String;
function GetVersion: String;
function GetComments: String;
function LoginUserInfo: PLoginUserInfo;
public
end;
implementation
uses IniFiles;
{ TSysInfoIntfObj }
function TSysInfoObj.AppPath: string;
begin
Result := ExtractFilePath(Paramstr(0));
end;
function TSysInfoObj.ErrPath: string;
begin
Result := AppPath + 'error';
if not DirectoryExists(Result) then
ForceDirectories(Result);
end;
function TSysInfoObj.GetComments: String;
begin
Result := '通过它可以取得系统一些信息,比如错误日志保存目录,注册表文件名以及当前登录用户等。';
end;
function TSysInfoObj.GetModuleName: String;
begin
Result := ExtractFileName(SysUtils.GetModuleName(HInstance));
end;
function TSysInfoObj.GetTitle: String;
begin
Result := '系统信息接口(ISysInfo)';
end;
function TSysInfoObj.GetVersion: String;
begin
Result := '20100421.001';
end;
function TSysInfoObj.LoginUserInfo: PLoginUserInfo;
begin
Result := @FLoginUserInfo;
end;
function TSysInfoObj.RegistryFile: string;
var IniFile: string;
ini: TIniFile;
begin
IniFile := self.AppPath + 'Root.ini';
ini := TiniFile.Create(IniFile);
try
Result := self.AppPath + ini.ReadString('Default', 'Reg', '');
finally
ini.Free;
end;
end;
function CreateSysInfoObj(param: Integer): TObject;
begin
Result := TSysInfoObj.Create;
end;
initialization
TSingletonFactory.Create(ISysInfo, @CreateSysInfoObj);
finalization
end.
|
(*--------------------------------------------------------------------------*)
(* NRand --- Return normally-distributed random number *)
(*--------------------------------------------------------------------------*)
FUNCTION NRand( Mean : REAL; StdDev : REAL ) : REAL;
(*--------------------------------------------------------------------------*)
(* *)
(* Function: NRand *)
(* *)
(* Purpose: Returns normally distributed random number. *)
(* *)
(* Calling sequence: *)
(* *)
(* Ran := NRand( Mean : REAL; StdDev : REAL ) : REAL; *)
(* *)
(* Mean --- Mean of normal distribution *)
(* StdDev --- Standard deviation of normal distribution *)
(* Ran --- Resultant random number *)
(* *)
(* Method: *)
(* *)
(* The Box-Muller transformation is used to get two normal(0,1)- *)
(* distributed values. The given mean and standard deviation are *)
(* used to scale the results to (Mean, StdDev). The first random *)
(* number is returned by this call, and the second random number *)
(* by the next call. *)
(* *)
(*--------------------------------------------------------------------------*)
(* STATIC VARIABLES *) CONST
NRand_Available : BOOLEAN = FALSE (* If number already available -- *);
Saved_NRand : REAL = 0.0 (* saved from last time through. *);
VAR
V1 : REAL;
V2 : REAL;
R : REAL;
Fac: REAL;
BEGIN (* NRand *)
(* Return 2nd random number calculated *)
(* last time through here. *)
IF NRand_Available THEN
BEGIN
NRand := Saved_NRand * StdDev + Mean;
NRand_Available := FALSE;
END
ELSE
BEGIN (* Calculate two new random numbers *)
(* using Box-Muller transformation *)
REPEAT
V1 := 2.0 * RANDOM - 1.0;
V2 := 2.0 * RANDOM - 1.0;
R := SQR( V1 ) + SQR( V2 );
UNTIL ( R < 1.0 );
(* Return 1st number this time, and *)
(* save second one for next time *)
(* through. *)
Fac := SQRT( -2.0 * LN( R ) / R );
NRand := V1 * Fac * StdDev + Mean;
Saved_NRand := V2 * Fac;
NRand_Available := TRUE;
END;
END (* NRand *);
|
{$include kode.inc}
unit syn_thesis_env;
{
attack
decay
release
Start
Peak
susten
End
attack.start :
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_const;
const
{ envelope stages }
env_stage_off = 0;
env_stage_attack = 1;
env_stage_decay = 2;
env_stage_sustain = 3;
env_stage_release = 4;
env_stage_finished = 5;
env_stage_count = 6;
env_stage_threshold = 0.001;//KODE_TINY;//KODE_EPSILON;
type
syn_thesis_envstage = record
FTarget : Single;
FSpeed : Single;
end;
//----------
KSynThesis_Env = class
public // private
FStage : LongInt;
FValue : Single;
FStages : array[0..env_stage_count-1] of syn_thesis_envstage; // -,a,d,s,r
public
constructor create;
function getStage : LongInt;
function getValue : Single;
procedure setValue(AValue:Single);
function finished : Boolean;
procedure setStage(AStage:LongInt; ATarget,ASpeed:Single);
procedure setADSR(a,d,s,r:Single);
procedure setAttack(AValue:Single);
procedure setDecay(AValue:Single);
procedure setSustain(AValue:Single);
procedure setRelease(AValue:Single);
procedure noteOn({%H-}ANote,AVel:Single);
procedure noteOff({%H-}ANote,AVel:Single);
function process : Single;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_debug,
kode_math,
kode_memory;
//----------
constructor KSynThesis_Env.create;
begin
inherited;
FStage := env_stage_off;
FValue := 0;
setADSR(1,1,1,1);
end;
//----------
function KSynThesis_Env.getStage : LongInt;
begin
result := FStage;
end;
//----------
function KSynThesis_Env.getValue : Single;
begin
result := FValue;
end;
//----------
procedure KSynThesis_Env.setValue(AValue:Single);
begin
FValue := AValue;;
end;
//----------
function KSynThesis_Env.finished : Boolean;
begin
if FStage = env_stage_finished then Result := True
else result := False;
end;
//----------
procedure KSynThesis_Env.setStage(AStage:LongInt; ATarget,ASpeed:Single);
begin
FStages[AStage].FTarget := ATarget;
FStages[AStage].FSpeed := ASpeed;
end;
//----------
procedure KSynThesis_Env.setADSR(a,d,s,r:Single);
begin
setStage(env_stage_attack, 1,a);
setStage(env_stage_decay, s,d);
setStage(env_stage_sustain,s,1);
setStage(env_stage_release,0,r);
end;
//----------
procedure KSynThesis_Env.setAttack(AValue:Single);
begin
FStages[env_stage_attack].FSpeed := AValue;
end;
//----------
procedure KSynThesis_Env.setDecay(AValue:Single);
begin
FStages[env_stage_decay].FSpeed := AValue;
end;
//----------
procedure KSynThesis_Env.setSustain(AValue:Single);
begin
FStages[env_stage_decay].FTarget := AValue;
FStages[env_stage_sustain].FTarget := AValue;
end;
//----------
procedure KSynThesis_Env.setRelease(AValue:Single);
begin
FStages[env_stage_release].FSpeed := AValue;
end;
//----------
//procedure KSynThesis_Env.attack(AVel:Single=1);
//begin
// //FStages[env_stage_attack].FTarget := FStages[env_stage_attack].FTarget * AVel;
//end;
//----------
procedure KSynThesis_Env.noteOn(ANote,AVel:Single);
begin
FStage := env_stage_attack;
end;
//----------
procedure KSynThesis_Env.noteOff(ANote,AVel:Single);
begin
FStage := env_stage_release;
end;
//----------
function KSynThesis_Env.process : Single;
var
speed,target : single;
begin
if FStage = env_stage_off then exit(0);
if FStage = env_stage_finished then exit(0);
speed := FStages[FStage].FSpeed;
target := FStages[FStage].FTarget;
if FStage = env_stage_sustain then exit(FValue{target});
result := FValue; // return initial value
FValue += ((target-FValue) * speed);
if abs(target-FValue) <= env_stage_threshold then FStage += 1;
end;
//----------------------------------------------------------------------
end.
|
unit eVideoStream;
interface
uses
API_ORM,
eCommon;
type
TVideoStream = class(TEntity)
private
FBitDepth: Integer;
FBitRate: Integer;
FCodec: string;
FCodecID: string;
FHeight: Integer;
FSize: Int64;
FVideoFileID: Integer;
FWidth: Integer;
public
class function GetStructure: TSructure; override;
published
property BitDepth: Integer read FBitDepth write FBitDepth;
property BitRate: Integer read FBitRate write FBitRate;
property Codec: string read FCodec write FCodec;
property CodecID: string read FCodecID write FCodecID;
property Height: Integer read FHeight write FHeight;
property Size: Int64 read FSize write FSize;
property VideoFileID: Integer read FVideoFileID write FVideoFileID;
property Width: Integer read FWidth write FWidth;
end;
TVideoStreamList = TEntityList<TVideoStream>;
implementation
uses
eVideoFile;
class function TVideoStream.GetStructure: TSructure;
begin
Result.TableName := 'VIDEO_STREAMS';
AddForeignKey(Result.ForeignKeyArr, 'VIDEO_FILE_ID', TVideoFile, 'ID');
end;
end.
|
{************************************************}
{ }
{ UNIT XVIEWS A collection of new Views }
{ Copyright (c) 1994-97 by Tom Wellige }
{ Donated as FREEWARE }
{ }
{ Ortsmuehle 4, 44227 Dortmund, GERMANY }
{ EMail: wellige@itk.de }
{ }
{************************************************}
(*
Some few words on this unit:
----------------------------
- This units works fine with Turbo Pascal 6 or higher. If you use
TP/BP 7 you can use the "inherited" command as shown in the
comment lines on each line where it is possible.
- This unit defines first of all a basic object (TXView) for status views
which are updateable via messages (send from the applications Idle
methode). All inheritances only have to override the abstract methode
UPDATE and place the information to display in a string. In this manner
there are a ClockView, a DateView and an HeapView as examples
implemented. The usage of these objects (TClock, TDate and THeap) will
be demonstrated in the programs XTEST1 and XTEST2.
- There is also a 7-segment view implemented in this unit (T7Segment)
capable of displaying all numbers from 0 to 9 and the characters
"A" "b" "c" "d" "E" "F" and "-". The usage of this object is also
demonstrated in this unit by the object TBigClock which is a clock
in "hh:mm:ss" format. How to use this clock is demonstrated in the
XTEST3 program.
*)
unit xviews;
interface
uses dos, objects, drivers, views;
const
cmGetData = 5000; { Request data string from TXView object }
cmChange7Segment = 5001; { Set new value to display in T7Segment }
cmChangeBack = 5002; { Change Background of T7Segment }
type
PXView = ^TXView; (* Basic status view object *)
TXView = object(TView)
Data: string;
procedure HandleEvent(var Event: TEvent); virtual;
procedure Update; virtual;
procedure Draw; virtual;
function GetString: PString; virtual;
end;
PClock = ^TClock; (* Displays current time *)
TClock = object(TXView)
procedure Update; virtual;
end;
PDate = ^TDate; (* Displays current date *)
TDate = object(TXView)
procedure Update; virtual;
end;
PHeap = ^THeap; (* Displays free bytes on the heap *)
THeap = object(TXView)
procedure Update; virtual;
end;
PInfoView = ^TInfoView; (* Show all "actual" datas *)
TInfoView = object(TView)
procedure Draw; virtual;
end;
PInfoWindow = ^TInfoWindow; (* Window holding TInfoView *)
TInfoWindow = object(TWindow)
constructor Init(var Bounds: TRect);
end;
TSegment = array[1..13] of byte; (* Buffer for T7Sgement *)
P7Segment = ^T7Segment; (* 7 Segment View (7x5) *)
T7Segment = object(TView)
Segment: TSegment;
Number: word;
{ 16 -> segm_ = "-", >=17 -> segmBlank = " " }
BackGround: boolean;
{ not active segment visible (gray) ? }
constructor Init(Top: TPoint; ABackGround: boolean; ANumber: word);
{ Top: upper left corner of segment
ABackGround: not active segments visible (gray) ?
ANumber: default value to be displayed }
procedure HandleEvent(var Event: TEvent); virtual;
procedure Draw; virtual;
procedure UpdateSegments;
end;
PBigClock = ^TBigClock;
TBigClock = object(TGroup)
Seg: Array[1..6] of P7Segment;
constructor Init(Top: TPoint; BackGround: boolean);
{ Top: upper left corner of clock
BackGround: will passed to each T7Segment: not active segments
visible (gray) ? }
procedure HandleEvent(var Event: TEvent); virtual;
procedure Update;
end;
const
Date : PDate = nil;
Clock: PClock = nil;
Heap : PHeap = nil;
implementation
{***********************************************************************}
{** TXView **}
{***********************************************************************}
procedure TXView.HandleEvent(var Event: TEvent);
begin
{ TP/BP7: inherited HandleEvent(Event); }
TView.HandleEvent(Event);
if Event.What = evBroadCast then
if Event.Command = cmGetData then
begin
ClearEvent(Event);
Event.InfoPtr:= GetString;
end;
end;
procedure TXView.Update;
begin
Abstract;
end;
procedure TXView.Draw;
var
Buf: TDrawBuffer;
C: word;
begin
C:= GetColor(2); (* Application -> "Menu normal" *)
(* Window -> "Frame active" *)
MoveChar(Buf, ' ', C, Size.X);
MoveStr(Buf, Data, C);
WriteLine(0, 0, Size.X, 1, Buf);
end;
function TXView.GetString: PString;
begin
GetString:= PString(@Data);
end;
{***********************************************************************}
{** TClock **}
{***********************************************************************}
procedure TClock.Update;
type
Rec = record
hh, mm, ss: longint; end;
var
DataRec: Rec;
hh, mm, ss, hs: word;
begin
GetTime(hh, mm, ss, hs);
DataRec.hh:= hh;
DataRec.mm:= mm;
DataRec.ss:= ss;
FormatStr(Data, '%2d:%2d:%2d', DataRec);
if hh < 10 then Data[1]:= '0';
if mm < 10 then Data[4]:= '0';
if ss < 10 then Data[7]:= '0';
DrawView;
end;
{***********************************************************************}
{** TDate **}
{***********************************************************************}
procedure TDate.Update;
type
Rec = record
dd, mm, yy: longint; end;
var
DataRec: Rec;
dd, mm, yy, dw: word;
begin
GetDate(yy, mm, dd, dw);
DataRec.dd:= dd;
DataRec.mm:= mm;
DataRec.yy:= yy;
FormatStr(Data, '%2d.%2d.%4d', DataRec);
if dd < 10 then Data[1]:= '0';
if mm < 10 then Data[4]:= '0';
DrawView;
end;
{***********************************************************************}
{** THeap **}
{***********************************************************************}
procedure THeap.Update;
var
Mem: longint;
begin
Mem:= MemAvail;
FormatStr(Data, '%d Bytes', Mem);
DrawView;
end;
{***********************************************************************}
{** TInfoView **}
{***********************************************************************}
procedure TInfoView.Draw;
var
Buf: TDrawBuffer;
C: word;
s: string;
begin
C:= GetColor(2); (* Application -> "Menu normal" *)
(* Window -> "Frame active" *)
s:= 'Date : ';
if assigned(Date) then
s:= s + PString(Message(Date, evBroadCast, cmGetData, nil))^ else
s:= s + 'not accessable';
MoveChar(Buf, ' ', C, Size.X);
MoveStr(Buf, s, C);
WriteLine(0, 0, Size.X, 1, Buf);
s:= 'Time : ';
if assigned(Clock) then
s:= s + PString(Message(Clock, evBroadCast, cmGetData, nil))^ else
s:= s + 'not accessable';
MoveChar(Buf, ' ', C, Size.X);
MoveStr(Buf, s, C);
WriteLine(0, 1, Size.X, 1, Buf);
s:= 'Memory : ';
if assigned(Heap) then
s:= s + PString(Message(Heap, evBroadCast, cmGetData, nil))^ else
s:= s + 'not accessable';
MoveChar(Buf, ' ', C, Size.X);
MoveStr(Buf, s, C);
WriteLine(0, 2, Size.X, 1, Buf);
end;
{***********************************************************************}
{** TInfoWindow **}
{***********************************************************************}
constructor TInfoWindow.Init(var Bounds: TRect);
var R: TRect;
begin
{ TP/BP7: inherited Init(Bounds, 'Systeminfo', 0); }
TWindow.Init(Bounds, 'Systeminfo', 0);
Palette:= wpCyanWindow;
Flags:= Flags and not (wfClose + wfZoom + wfGrow);
GetExtent(R);
R.Grow(-2, -2);
Insert(New(PInfoView, Init(R)));
end;
{***********************************************************************}
{** T7Segment **}
{***********************************************************************}
const { 1 2 3 4 5 6 7 8 9 A B C D }
segm0: TSegment = (1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1);
segm1: TSegment = (0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1);
segm2: TSegment = (1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1);
segm3: TSegment = (1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1);
segm4: TSegment = (1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1);
segm5: TSegment = (1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1);
segm6: TSegment = (1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1);
segm7: TSegment = (1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1);
segm8: TSegment = (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
segm9: TSegment = (1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1);
segmA: TSegment = (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1);
segmB: TSegment = (1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1);
segmC: TSegment = (1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1);
segmD: TSegment = (0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1);
segmE: TSegment = (1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1);
segmF: TSegment = (1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0);
segm_: TSegment = (0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0);
segmBlank: TSegment =
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
constructor T7Segment.Init(Top: TPoint; ABackGround: boolean; ANumber: word);
var R: TRect;
begin
R.Assign(Top.X, Top.Y, Top.X+7, Top.Y+5);
{ TP/BP7: inherited Init(R); }
TView.Init(R);
BackGround:= ABackGround;
Number:= ANumber;
UpdateSegments;
end;
procedure T7Segment.HandleEvent(var Event: TEvent);
begin
{ TP/BP7: inherited HandleEvent(Event); }
TView.HandleEvent(Event);
if Event.What = evBroadCast then
case Event.Command of
cmChange7Segment: begin
Number:= Word(Event.InfoPtr^);
UpdateSegments;
DrawView;
ClearEvent(Event);
end;
cmChangeBack : begin
if BackGround then BackGround:= false
else BackGround:= true;
DrawView;
end;
end;
end;
procedure T7Segment.Draw;
var
Buf: TDrawBuffer;
Front, Back: byte;
function SetColor(w: word; c: byte): word;
begin
w:= w and $00FF;
w:= swap(w);
w:= w or c;
w:= swap(w);
SetColor:= w;
end;
procedure SetBufColor(var B: TDrawBuffer; C: word);
var i: integer;
begin
for i:= 0 to Size.X do
Buf[i]:= SetColor(Buf[i], C);
end;
begin
if BackGround then Back:= $8 else Back:= $0;
Front:= $F;
{ Segment 1,2,3 }
SetBufColor(Buf, $0);
MoveStr (Buf, ' þþþþþ', Back);
if Segment[1] = 1 then
Buf[1]:= SetColor(Buf[1], Front);
if Segment[2] = 1 then begin
Buf[2]:= SetColor(Buf[2], Front);
Buf[3]:= SetColor(Buf[3], Front);
Buf[4]:= SetColor(Buf[4], Front); end;
if Segment[3] = 1 then
Buf[5]:= SetColor(Buf[5], Front);
WriteLine(0, 0, Size.X, 1, Buf);
{ Segment 4,5 }
SetBufColor(Buf, $0);
MoveStr (Buf, ' Û Û', Back);
if Segment[4] = 1 then
Buf[1]:= SetColor(Buf[1], Front);
if Segment[5] = 1 then
Buf[5]:= SetColor(Buf[5], Front);
WriteLine(0, 1, Size.X, 1, Buf);
{ Segment 6,7,8 }
SetBufColor(Buf, $0);
MoveStr (Buf, ' þþþþþ', Back);
if Segment[6] = 1 then
Buf[1]:= SetColor(Buf[1], Front);
if Segment[7] = 1 then begin
Buf[2]:= SetColor(Buf[2], Front);
Buf[3]:= SetColor(Buf[3], Front);
Buf[4]:= SetColor(Buf[4], Front); end;
if Segment[8] = 1 then
Buf[5]:= SetColor(Buf[5], Front);
WriteLine(0, 2, Size.X, 1, Buf);
{ Segment 9,10 }
SetBufColor(Buf, $0);
MoveStr (Buf, ' Û Û', Back);
if Segment[9] = 1 then
Buf[1]:= SetColor(Buf[1], Front);
if Segment[10] = 1 then
Buf[5]:= SetColor(Buf[5], Front);
WriteLine(0, 3, Size.X, 1, Buf);
{ Segment 11,12,13 }
SetBufColor(Buf, $0);
MoveStr (Buf, ' þþþþþ', Back);
if Segment[11] = 1 then
Buf[1]:= SetColor(Buf[1], Front);
if Segment[12] = 1 then begin
Buf[2]:= SetColor(Buf[2], Front);
Buf[3]:= SetColor(Buf[3], Front);
Buf[4]:= SetColor(Buf[4], Front); end;
if Segment[13] = 1 then
Buf[5]:= SetColor(Buf[5], Front);
WriteLine(0, 4, Size.X, 1, Buf);
end;
procedure T7Segment.UpdateSegments;
begin
case Number of
0: Segment:= segm0;
1: Segment:= segm1;
2: Segment:= segm2;
3: Segment:= segm3;
4: Segment:= segm4;
5: Segment:= segm5;
6: Segment:= segm6;
7: Segment:= segm7;
8: Segment:= segm8;
9: Segment:= segm9;
10: Segment:= segmA;
11: Segment:= segmB;
12: Segment:= segmC;
13: Segment:= segmD;
14: Segment:= segmE;
15: Segment:= segmF;
16: Segment:= segm_;
else
Segment:= segmBlank;
end;
end;
{***********************************************************************}
{** TBigClock **}
{***********************************************************************}
type
PBlackView = ^TBlackView; (* black background for TBigClock *)
TBlackView = object(TView)
procedure Draw; virtual;
end;
procedure TBlackView.Draw;
var
Buf : TDrawBuffer;
Color: word;
i : integer;
begin
Color:= $0F;
for i:= 0 to Size.Y do
begin
MoveChar(Buf, ' ', Color, Size.X);
if (i = 2) or (i = 4) then
begin
Buf[16]:= $0FFE;
Buf[33]:= $0FFE;
end;
WriteLine(0, i, Size.X, 1, Buf);
end;
end;
constructor TBigClock.Init(Top: TPoint; BackGround: boolean);
const
XPos : Array [1..6] of word = (1, 8, 18, 25, 35, 42);
var
R: TRect;
P: TPoint;
i: integer;
begin
R.Assign(Top.X, Top.Y, Top.X+50, Top.Y+7);
{ TP/BP7: inherited Init(R); }
TGroup.Init(R);
R.Assign(0, 0, Size.X, Size.Y);
Insert(new(PBlackView, Init(R)));
for i:= 1 to 6 do
begin
P.X:= XPos[i]; P.Y:= 1;
Seg[i]:= new(P7Segment, Init(P, BackGround, 0));
insert(Seg[i]);
end;
end;
procedure TBigClock.HandleEvent(var Event: TEvent);
var i: integer;
begin
{ TP/BP7: inherited HandleEvent(Event); }
TGroup.HandleEvent(Event);
if Event.What = evBroadCast then
if Event.Command = cmChangeBack then
begin
for i:= 1 to 6 do
Message(Seg[i], evBroadCast, cmChangeBack, nil);
end;
end;
procedure TBigClock.Update;
var
w, h, m, s, hs: word;
begin
GetTime(h, m, s, hs);
w:= h div 10;
Message(Seg[1], evBroadCast, cmChange7Segment, @w); (* Hours - 10^1 *)
w:= h mod 10;
Message(Seg[2], evBroadCast, cmChange7Segment, @w); (* Hours - 10^0 *)
w:= m div 10;
Message(Seg[3], evBroadCast, cmChange7Segment, @w); (* Minutes - 10^1 *)
w:= m mod 10;
Message(Seg[4], evBroadCast, cmChange7Segment, @w); (* Minutes - 10^0 *)
w:= s div 10;
Message(Seg[5], evBroadCast, cmChange7Segment, @w); (* Seconds - 10^1 *)
w:= s mod 10;
Message(Seg[6], evBroadCast, cmChange7Segment, @w); (* Seconds - 10^0 *)
end;
end.
|
{
Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit DataGrabber.ConnectionProfiles;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics,
DataGrabber.ConnectionSettings;
type
TConnectionProfiles = class;
TConnectionProfile = class(TCollectionItem)
private
FName : string;
FProfileColor : TColor;
FConnectionSettings : TConnectionSettings;
protected
{$REGION 'property access methods'}
procedure SetCollection(const Value: TConnectionProfiles); reintroduce;
function GetCollection: TConnectionProfiles;
procedure SetDisplayName(const Value: string); override;
function GetDisplayName: string; override;
{$ENDREGION}
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
{ Collection that owns the instance of current TConnectionProfile item. }
property Collection: TConnectionProfiles
read GetCollection write SetCollection;
published
{ The name displayed in the collection editor at design time. }
property Name: string
read FName write SetDisplayName;
{ The name as shown in the user interface. }
property DisplayName: string
read GetDisplayName write SetDisplayName;
property ProfileColor: TColor
read FProfileColor write FProfileColor default clWhite;
property ConnectionSettings: TConnectionSettings
read FConnectionSettings write FConnectionSettings;
end;
TConnectionProfileClass = class of TConnectionProfile;
{ TConnectionProfiles inherits from TOwnedCollection to show the items in
the Object Treeview of the Delphi IDE at designtime. }
TConnectionProfiles = class(TOwnedCollection)
protected
function GetItem(Index: Integer): TConnectionProfile;
procedure SetItem(Index: Integer; const Value: TConnectionProfile);
procedure SetItemName(Item: TCollectionItem); override;
procedure Update(AItem: TCollectionItem); override;
procedure Notify(Item: TCollectionItem; Action: TCollectionNotification);
override;
function FindUniqueName(const Name: string): string;
public
constructor Create(AOwner : TPersistent);
function Add: TConnectionProfile;
function Insert(Index: Integer): TConnectionProfile;
function Owner: TComponent; reintroduce;
function IndexOf(const AName: string): Integer; virtual;
function FindItemID(ID: Integer): TConnectionProfile;
function Find(const AName: string): TConnectionProfile;
{ The TCollectionItem decendant class of the collection items. }
property ItemClass;
{ Provides indexed access to the list of collection items. }
property Items[Index: Integer]: TConnectionProfile
read GetItem write SetItem; default;
end;
implementation
{$REGION 'TConnectionProfiles'}
{$REGION 'construction and destruction'}
constructor TConnectionProfiles.Create(AOwner: TPersistent);
begin
inherited Create(AOwner, TConnectionProfile);
end;
{$ENDREGION}
{$REGION 'property access methods'}
function TConnectionProfiles.GetItem(Index: Integer): TConnectionProfile;
begin
Result := inherited Items[Index] as TConnectionProfile;
end;
procedure TConnectionProfiles.SetItem(Index: Integer; const Value: TConnectionProfile);
begin
Items[Index].Assign(Value);
end;
{$ENDREGION}
{$REGION 'protected methods'}
function TConnectionProfiles.FindUniqueName(const Name: string): string;
var
I : Integer;
S : string;
begin
I := 0;
S := Name;
while Assigned(Find(S)) do
begin
Inc(I);
S := Format('%s%d', [Name, I]);
end;
Result := S;
end;
{ Overridden method from TCollection to make any necessary changes when the
items in the collection change. This method is called automatically when an
update is issued.
Item = Item that changed. If the Item parameter is nil, then the change
affects more than one item in the collection }
procedure TConnectionProfiles.Update(AItem: TCollectionItem);
begin
// Make necessary adjustments when items in the collection change
// Update gets called from TCollection.Changed.
end;
{ Responds when items are added to or removed from the collection. }
procedure TConnectionProfiles.Notify(Item: TCollectionItem; Action: TCollectionNotification);
begin
// The actions that can be used to respond to are:
// - cnAdded : an item was just added to the collection
// - cnExtracting : an item is about to be removed from the collection (but
// not freed)
// - cnDeleting : an item is about to be removed from the collection and
// then freed
end;
{$ENDREGION}
{$REGION 'public methods'}
{ Adds a new TConnectionProfile instance to the TConnectionProfiles
collection. }
function TConnectionProfiles.Add: TConnectionProfile;
begin
Result := inherited Add as TConnectionProfile;
end;
{ Inserts a new TConnectionProfile instance to the TConnectionProfiles
collection before position specified with Index. }
function TConnectionProfiles.Insert(Index: Integer): TConnectionProfile;
begin
Result := inherited Insert(Index) as TConnectionProfile;
end;
{ Constructs a unique itemname for a new collection item. }
procedure TConnectionProfiles.SetItemName(Item: TCollectionItem);
var
S : string;
begin
S := Copy(Item.ClassName, 2, Length(Item.ClassName));
TConnectionProfile(Item).Name := FindUniqueName(S);
end;
function TConnectionProfiles.Owner: TComponent;
var
AOwner: TPersistent;
begin
AOwner := inherited Owner;
if AOwner is TComponent then
Result := TComponent(AOwner)
else
Result := nil;
end;
function TConnectionProfiles.IndexOf(const AName: string): Integer;
begin
for Result := 0 to Pred(Count) do
if AnsiCompareText((Items[Result]).Name, AName) = 0 then
Exit;
Result := -1;
end;
{ The FindItemID method returns the item in the collection whose ID property
is passed to it as a parameter. If no item has the specified ID, FindItemID
returns nil. }
function TConnectionProfiles.FindItemID(ID: Integer): TConnectionProfile;
begin
Result := inherited FindItemID(ID) as TConnectionProfile;
end;
function TConnectionProfiles.Find(const AName: string): TConnectionProfile;
var
I : Integer;
begin
I := IndexOf(AName);
if I < 0 then
Result := nil
else
Result := Items[I];
end;
{$ENDREGION}
{$ENDREGION}
{$REGION 'TConnectionProfile'}
{$REGION 'construction and destruction'}
constructor TConnectionProfile.Create(Collection: TCollection);
begin
inherited Create(Collection);
FConnectionSettings := TConnectionSettings.Create;
FProfileColor := clWhite;
end;
destructor TConnectionProfile.Destroy;
begin
FreeAndNil(FConnectionSettings);
inherited Destroy;
end;
{$ENDREGION}
{$REGION 'property access methods'}
function TConnectionProfile.GetCollection: TConnectionProfiles;
begin
Result := inherited Collection as TConnectionProfiles;
end;
procedure TConnectionProfile.SetCollection(const Value: TConnectionProfiles);
begin
inherited Collection := Value;
end;
function TConnectionProfile.GetDisplayName: string;
begin
Result := FName;
end;
procedure TConnectionProfile.SetDisplayName(const Value: string);
begin
if (Value <> '') and (AnsiCompareText(Value, FName) <> 0) and
(Collection is TConnectionProfiles) and
(TConnectionProfiles(Collection).IndexOf(Value) >= 0) then
raise Exception.CreateFmt('Duplicate name [%s]!', [Value]);
FName := Value;
inherited SetDisplayName(Value);
end;
{$ENDREGION}
{$REGION 'public methods'}
procedure TConnectionProfile.Assign(Source: TPersistent);
var
CP: TConnectionProfile;
begin
if (Source <> Self) and (Source is TConnectionProfile) then
begin
CP := TConnectionProfile(Source);
if Assigned(Collection) then
Collection.BeginUpdate;
try
ProfileColor := CP.ProfileColor;
ConnectionSettings.Assign(CP.ConnectionSettings);
finally
if Assigned(Collection) then
Collection.EndUpdate;
end;
end
else
inherited Assign(Source);
end;
{$ENDREGION}
{$ENDREGION}
end.
|
Unit VGA256;
Interface
Uses DOS, crt, graph;
Const
Mode320X200X256 = 0;
Mode640X400X256 = 1;
Mode640X480X256 = 2;
Mode800X600X256 = 3;
Mode1024X768X256 = 4;
GraphMode: Integer = Mode800X600X256;
Var
GraphDriver: Integer;
(*
*
* SVGA.inc
*
*)
type DacPalette256 = array[0..255] of array[0..2] of Byte;
(* These are the currently supported modes *)
const
SVGA320x200x256 = 0; (* 320x200x256 Standard VGA *)
SVGA640x400x256 = 1; (* 640x400x256 Svga *)
SVGA640x480x256 = 2; (* 640x480x256 Svga *)
SVGA800x600x256 = 3; (* 800x600x256 Svga *)
SVGA1024x768x256 = 4; (* 1024x768x256 Svga *)
TRANS_COPY_PIX = 8;
Function GetMode: Integer;
Procedure setmode (Mode: Integer);
Procedure grafikein;
Procedure grafikaus;
procedure SetVGAPalette256(PalBuf : DacPalette256);
Implementation
{$F+}
Function GetMode: Integer; Begin GetMode := GraphMode End;
{$F+}
procedure SetMode; begin GraphMode:= Mode end;
Procedure grafikein;
Var
fname: String;
Begin
fname := GetEnv ( 'BGIPATH' ) + '\' + 'SVGA256';
writeln(fname);
GraphDriver := InstallUserDriver ( fname, @GetMode);
GraphDriver := Detect;
InitGraph ( GraphDriver, GraphMode, '' );
End;
Procedure grafikaus;
Begin
CloseGraph;
End;
(* Setvgapalette sets the entire 256 color palette *)
(* PalBuf contains RGB values for all 256 colors *)
(* R,G,B values range from 0 to 63 *)
procedure SetVGAPalette256(PalBuf : DacPalette256);
var
Reg : Registers;
begin
reg.ax := $1012;
reg.bx := 0;
reg.cx := 256;
reg.es := Seg(PalBuf);
reg.dx := Ofs(PalBuf);
intr($10,reg);
end;
Begin
End. |
{ Private insert file for TYPE1 routines.
}
%include 'ray2.ins.pas';
%include 'ray_type1.ins.pas';
const
mem_block_size = 100000; {number of bytes in mem block}
max_mem_index = mem_block_size - 1; {max index into mem block}
type
stats_tri_t = record {triangle object statistics}
isect_ray: sys_int_machine_t; {number of ray/triangle intersect checks}
hit_ray: sys_int_machine_t; {ray/tri intersections found}
isect_box: sys_int_machine_t; {number of box/triangle intersect checks}
hit_box: sys_int_machine_t; {box/tri intersections found}
end;
stats_oct_t = record {octree object statistics}
n_parent: sys_int_machine_t; {number of parent octree nodes}
n_leaf: sys_int_machine_t; {number of leaf node octree voxels}
mem: sys_int_adr_t; {total memory allocated for octree overhead}
end;
{
*********************************************************************************
*
* Common block for all TYPE1 routines.
}
var (ray_type1)
mem: array[0..max_mem_index] of char; {scratch area for DAG path and hit blocks}
next_mem: sys_int_adr_t {MEM index of start of free area}
:= 0; {init to all of MEM is free area}
stats_tri: stats_tri_t; {triangle primitive statistics}
stats_oct: stats_oct_t; {octree object statistics}
|
unit model.Especialidade;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants;
type
TEspecialidade = class(TObject)
private
aCodigo : Integer;
aDescricao : String;
procedure SetDescricao(const Value: String);
public
constructor Create; overload;
property Codigo : Integer read aCodigo write aCodigo;
property Descricao : String read aDescricao write SetDescricao;
function ToString : String; override;
end;
TEspecialidades = Array of TEspecialidade;
implementation
{ TEspecialidade }
constructor TEspecialidade.Create;
begin
inherited Create;
aCodigo := 0;
aDescricao := EmptyStr;
end;
procedure TEspecialidade.SetDescricao(const Value: String);
begin
aDescricao := Trim(Value);
end;
function TEspecialidade.ToString: String;
begin
Result := aDescricao;
end;
end.
|
// ----------------------------------------------------------------------------
// Unit : PxBase.pas - a part of PxLib
// Author : Matthias Hryniszak
// Date : 2004-10-18
// Version : 1.0
// Description : Base definitions
// Changes log : 2004-10-18 - Initial version
// 2005-03-11 - Removed dependencies to GNUGetText unit and
// switched to PxGetText.
// ToDo : Testing.
// ----------------------------------------------------------------------------
unit PxBase;
{$I PxDefines.inc}
interface
uses
{$IFDEF VER130}
PxDelphi5,
{$ENDIF}
Windows, Classes, SysUtils;
type
//
// Base types
//
Int8 = type ShortInt;
Int16 = type SmallInt;
Int32 = type Integer;
// Int64 = type System.Int64; //- already defined in System.dcu
UInt8 = type Byte;
UInt16 = type Word;
UInt32 = type LongWord;
Float32 = type Single;
Float48 = type Real48;
Float64 = type Double;
Float80 = type Extended;
Float = Float64;
//
// This class enebles the use of interfaces for standard delphi
// classes. The objects MUST be manually disposed therefore
// they can be stored in a standard container like TList.
//
// You have to remeamber, that class instances have to be createrd
// first and disposed last. If any interface variables contain the
// pointer to an interface implemented by this class there will come
// an "Invalid pointer operation" exception what means, that not all
// interface variables are done with this object yet.
//
TPxBaseObject = class (TInterfacedObject)
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
//
// This is a list of objects above
//
TPxBaseObjectList = class (TList)
private
function GetItem(Index: Integer): TPxBaseObject;
public
function IndexOf(Item: TPxBaseObject): Integer;
procedure Add(Item: TPxBaseObject);
procedure Remove(Item: TPxBaseObject);
property Items[Index: Integer]: TPxBaseObject read GetItem; default;
end;
//
// An GetText/WideString-enabled exception object
//
EPxException = class (Exception)
constructor Create(const Msg: WideString);
constructor CreateFmt(const Msg: WideString; const Args: array of const);
constructor CreateRes(ResStringRec: PResStringRec);
constructor CreateResFmt(ResStringRec: PResStringRec; const Args: array of const);
end;
//
// Returns an IUnknown from an object if this object implements the IUnknown interface.
// Most common use of this function should be
//
// SomeProc(GetInterface(my_object) as IMyInterface)
//
// and in SomeProc should be checked if this what has come is <> nil
//
function GetInterface(Obj: TObject): IUnknown;
//
// Checks if given object implements a given interface.
// Can be used together with the GetInterface function like this:
//
// if Implements(my_object, IMyInterface) then
// SomeProc(GetInterface(my_object) as IMyInterface);
//
function Implements(Obj: TObject; IID: TGUID): Boolean;
//
// Import routines from kernel32.dll
//
function InterlockedIncrement(var Addend: Integer): Integer; stdcall;
function InterlockedDecrement(var Addend: Integer): Integer; stdcall;
var
ProgramPath: WideString = '';
implementation
//uses
// PxGetText;
{ TBaseObject }
{ Public declarations }
procedure TPxBaseObject.AfterConstruction;
begin
inherited AfterConstruction;
// make this instance auto-disposal proof
InterlockedIncrement(FRefCount);
end;
procedure TPxBaseObject.BeforeDestruction;
begin
// this instance is auto-disposal proof so we need to
// manualy decrement the reference counter
InterlockedDecrement(FRefCount);
inherited BeforeDestruction;
end;
{ TPxList }
{ Private declarations }
function TPxBaseObjectList.GetItem(Index: Integer): TPxBaseObject;
begin
Result := TObject(Get(Index)) as TPxBaseObject;
end;
{ Public declarations }
function TPxBaseObjectList.IndexOf(Item: TPxBaseObject): Integer;
begin
Result := inherited IndexOf(Item);
end;
procedure TPxBaseObjectList.Add(Item: TPxBaseObject);
begin
inherited Add(Item);
end;
procedure TPxBaseObjectList.Remove(Item: TPxBaseObject);
begin
inherited Remove(Item);
end;
{ EPxException }
constructor EPxException.Create(const Msg: WideString);
begin
inherited Create(Msg);
end;
constructor EPxException.CreateFmt(const Msg: WideString; const Args: array of const);
begin
inherited Create(WideFormat(Msg, Args));
end;
constructor EPxException.CreateRes(ResStringRec: PResStringRec);
begin
// inherited Create(LoadResStringW(ResStringRec));
inherited Create(LoadResString(ResStringRec));
end;
constructor EPxException.CreateResFmt(ResStringRec: PResStringRec; const Args: array of const);
begin
// inherited Create(WideFormat(LoadResStringW(ResStringRec), Args));
inherited Create(WideFormat(LoadResString(ResStringRec), Args));
end;
{ *** }
function InterlockedIncrement(var Addend: Integer): Integer; stdcall;
external 'kernel32.dll' name 'InterlockedIncrement';
function InterlockedDecrement(var Addend: Integer): Integer; stdcall;
external 'kernel32.dll' name 'InterlockedDecrement';
function GetInterface(Obj: TObject): IUnknown;
begin
if not (Assigned(Obj) and Obj.GetInterface(IUnknown, Result)) then
Result := nil;
end;
function Implements(Obj: TObject; IID: TGUID): Boolean;
begin
Result := Assigned(Obj) and Obj.GetInterface(IID, Result)
end;
{ *** }
procedure Initialize;
begin
ProgramPath := ExtractFilePath(ParamStr(0));
end;
procedure Finalize;
begin
end;
initialization
Initialize;
finalization
Finalize;
end.
|
unit ViewModel;
interface
uses
cwCollections
, DataModel
;
type
/// <summary>
/// This provides access to the collections which represent the
/// end-points for out game.
/// </summary>
IViewModel = interface
['{B3C6E9B2-EDE2-4FD6-A99A-E987F06A3538}']
procedure CleanUp;
procedure UpdateUserPing( const UserID: string );
/// <summary>
/// Returns a collection of public games waiting for users to join.
/// </summary>
function getPublicGames: string;
/// <summary>
/// Create a new game based on the json parameters provided. As a
/// minimum, the following parameters must be provided. <br /><br />{ <br />
/// "sessionName": "My new game", <br />"langID": "GB", <br />} <br /><br />
/// Optionally provide "minUsers", "maxUsers" and the "sessionPassword:"
/// parameter may be set to the keyword "Generate" in order to make this
/// game private.
/// </summary>
function CreateGame( const json: string ): string;
/// <summary>
/// <para>
/// This method creates a new entry in the users table for a
/// specified game.
/// </para>
/// <para>
/// required json:
/// </para>
/// <para>
/// "Name": "John Smith" <br />"sessionID": "<GUID>" <br /><br />
/// The game will be loaded based on either the GUID or Password,
/// and if the user successfully joins, their GUID is returned as
/// part of the user record. <br />
/// </para>
/// </summary>
function JoinGame( const json: string ): string;
/// <summary>
///
/// </summary>
function getUsers( const AuthToken: string ): string;
/// <summary>
/// Progress the game state.
/// </summary>
function setGameState( AuthToken: string; const json: string ): string;
function getCurrentGame( AuthToken : String) : IGameData;
/// <summary>
/// Get current turn data for user specified by auth token
/// </summary>
function getCurrentTurn( AuthToken: string ): string;
/// <summary>
/// Set current turn data form user specified by auth token
/// </summary>
function setCurrentTurn( AuthToken: string;Const json : String ): string;
end;
implementation
end.
|
unit uConcreteFlyweight;
interface
uses
Classes, ExtCtrls, uFlyweight, PNGImage;
type
{ Concrete Flyweight - classe base }
TCartao = class(TInterfacedObject, ICartao)
protected
PNGArquivo: TPNGImage;
Mensagem: TStringList;
FCaminhoImagens: string;
FNomeLeitor: string;
procedure SetNomeLeitor(const NomeLeitor: string);
public
constructor Create;
destructor Destroy; override;
procedure Exportar;
property NomeLeitor: string write SetNomeLeitor;
end;
{ Concrete Flyweight - classe herdada }
TCartaoEspanha = class(TCartao)
public
constructor Create;
end;
{ Concrete Flyweight - classe herdada }
TCartaoEUA = class(TCartao)
public
constructor Create;
end;
{ Concrete Flyweight - classe herdada }
TCartaoBrasil = class(TCartao)
constructor Create;
end;
{ Concrete Flyweight - classe herdada }
TCartaoItalia = class(TCartao)
constructor Create;
end;
implementation
uses
SysUtils, Graphics;
{ TCartao }
constructor TCartao.Create;
begin
// cria o objeto da classe TStringList para armazenar a mensagem do cartão
Mensagem := TStringList.Create;
// cria o objeto da classe TPNGObject para exportar o arquivo
PNGArquivo := TPNGImage.Create;
PNGArquivo.Canvas.Font.Name := 'Verdana';
PNGArquivo.Canvas.Font.Size := 11;
PNGArquivo.Canvas.Font.Style := [fsBold];
// armazena o caminho da pasta de exportações
FCaminhoImagens := Format('%s\cartoes\', [ExtractFilePath(ParamStr(0))]);
end;
destructor TCartao.Destroy;
begin
// libera os objetos da memória
FreeAndNil(Mensagem);
FreeAndNil(PNGArquivo);
inherited;
end;
procedure TCartao.Exportar;
begin
// escreve o texto por cima da imagem
PNGArquivo.Canvas.TextOut(5, 10, StringReplace(Mensagem[0], '%nome%', FNomeLeitor, []));
PNGArquivo.Canvas.TextOut(5, 70, Mensagem[1]);
PNGArquivo.Canvas.TextOut(5, 95, Mensagem[2]);
PNGArquivo.Canvas.TextOut(5, 120, Mensagem[3]);
// salva o arquivo
PNGArquivo.SaveToFile(Format('%s\Cartao - %s.png', [FCaminhoImagens, FNomeLeitor]));
end;
procedure TCartao.SetNomeLeitor(const NomeLeitor: string);
begin
// armazena o nome do leitor para concatenar no nome do arquivo
FNomeLeitor := NomeLeitor;
end;
{ TCartaoEspanha }
constructor TCartaoEspanha.Create;
begin
inherited;
// carrega a imagem da bandeira da Espanha
PNGArquivo.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'imagens\Espanha.png');
// preenche a mensagem em espanhol
Mensagem.Add('Hola, %nome%!');
Mensagem.Add('Feliz Año Nuevo!');
Mensagem.Add('Siempre visite el blog');
Mensagem.Add('para leer los nuevos artículos! :)');
end;
{ TCartaoBrasil }
constructor TCartaoBrasil.Create;
begin
inherited;
// carrega a imagem da bandeira do Brasil
PNGArquivo.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'imagens\Brasil.png');
// preenche a mensagem em português
Mensagem.Add('Olá, %nome%!');
Mensagem.Add('Feliz Ano Novo!');
Mensagem.Add('Sempre visite o blog');
Mensagem.Add('para ler os novos artigos! :)');
end;
{ TCartaoEUA }
constructor TCartaoEUA.Create;
begin
inherited;
// carrega a imagem da bandeira dos EUA
PNGArquivo.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'imagens\EUA.png');
// preenche a mensagem em inglês
Mensagem.Add('Hello, %nome%!');
Mensagem.Add('Happy New Year!');
Mensagem.Add('Remember to always visit the blog');
Mensagem.Add('to check out the newest posts! :)');
end;
{ TCartaoItalia }
constructor TCartaoItalia.Create;
begin
inherited;
// carrega a imagem da bandeira da Itália
PNGArquivo.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'imagens\Italia.png');
// preenche a mensagem em italiano
Mensagem.Add('Ciao, %nome%!');
Mensagem.Add('Felice Anno Nuovo!');
Mensagem.Add('Sempre visitare il blog');
Mensagem.Add('per leggere i nuovi articoli! :)');
end;
end.
|
unit uJogador;
interface
uses uEnum, System.SysUtils, uException;
type
TJogador = class
private
FNome: STring;
FSimbolo: tSimbolo;
function getNome: String;
procedure setNome(const Value: String);
function getSimbolo: tSimbolo;
procedure setSimbolo(const Value: tSimbolo);
public
property nome: String read getNome write setNome;
property simbolo: tSimbolo read getSimbolo write setSimbolo;
end;
implementation
{ TJogador }
function TJogador.getNome: String;
begin
Result := FNome;
end;
function TJogador.getSimbolo: tSimbolo;
begin
Result := FSimbolo;
end;
procedure TJogador.setNome(const Value: String);
begin
if Value = EmptyStr then
raise ExceptionNomeNaoInformado.create;
FNome := Value;
end;
procedure TJogador.setSimbolo(const Value: tSimbolo);
begin
FSimbolo := Value;
end;
end.
|
// GLHeightData
{: Classes for height data access.<p>
The components and classes in the unit are the core data providers for
height-based objects (terrain rendering mainly), they are independant
from the rendering stage.<p>
In short: access to raw height data is performed by a THeightDataSource
subclass, that must take care of performing all necessary data access,
cacheing and manipulation to provide THeightData objects. A THeightData
is basicly a square, poxer of two dimensionned raster heightfield, and
holds the data a renderer needs.<p>
<b>History : </b><font size=-1><ul>
<li>04/03/01 - Egg - Added InterpolatedHeight
<li>11/02/01 - Egg - Creation
</ul></font>
}
unit GLHeightData;
interface
uses Windows, Classes, Graphics, Geometry;
type
TByteArray = array [0..MaxInt shr 1] of Byte;
PByteArray = ^TByteArray;
TByteRaster = array [0..MaxInt shr 3] of PByteArray;
PByteRaster = ^TByteRaster;
TWordArray = array [0..MaxInt shr 2] of Word;
PWordArray = ^TWordArray;
TWordRaster = array [0..MaxInt shr 3] of PWordArray;
PWordRaster = ^TWordRaster;
TSingleArray = array [0..MaxInt shr 3] of Single;
PSingleArray = ^TSingleArray;
TSingleRaster = array [0..MaxInt shr 3] of PSingleArray;
PSingleRaster = ^TSingleRaster;
THeightData = class;
THeightDataClass = class of THeightData;
// THeightDataType
//
{: Determines the type of data stored in a THeightData.<p>
There are 3 data types (8 bits, 16 bits and 32 bits) possible, the 8 and
16 bits types are unsigned, the 32 bits type (single) is signed. }
THeightDataType = (hdtByte, hdtWord, hdtSingle);
// THeightDataSource
//
{: Base class for height datasources.<p>
This class is abstract and presents the standard interfaces for height
data retrieval (THeightData objects). The class offers the following
features (that a subclass may decide to implement or not, what follow
is the complete feature set, check subclass doc to see what is actually
supported):<ul>
<li>Pooling / Cacheing (return a THeightData with its "Release" method)
<li>Pre-loading : specify a list of THeightData you want to preload
<li>Multi-threaded preload/queueing : specified list can be loaded in
a background task.
</p> }
THeightDataSource = class (TComponent)
private
{ Private Declarations }
FData : TThreadList; // stores all THeightData, whatever their state/type
FThread : TThread; // queue manager
FMaxThreads : Integer;
FMaxPoolSize : Integer;
FHeightDataClass : THeightDataClass;
protected
{ Protected Declarations }
procedure SetMaxThreads(const val : Integer);
{: Adjust this property in you subclasses. }
property HeightDataClass : THeightDataClass read FHeightDataClass write FHeightDataClass;
{: Access to currently pooled THeightData objects. }
property Data : TThreadList read FData;
{: Looks up the list and returns the matching THeightData, if any. }
function FindMatchInList(xLeft, yTop, size : Integer;
dataType : THeightDataType) : THeightData;
{: Request to start preparing data.<p>
If your subclass is thread-enabled, this is here that you'll create
your thread and fire it (don't forget the requirements), if not,
that'll be here you'll be doing your work.<br>
Either way, you are responsible for adjusting the DataState to
hdsReady when you're done (DataState will be hdsPreparing when this
method will be invoked). }
procedure StartPreparingData(heightData : THeightData); virtual;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{: Empties the Data list, terminating thread if necessary.<p>
If some THeightData are hdsInUse, triggers an exception and does
nothing. }
procedure Clear;
{: Removes less used TDataHeight objects from the pool.<p>
Only removes objects whose state is hdsReady and UseCounter is zero,
starting from the end of the list untill total data size gets below
MaxPoolSize (or nothing can be removed). }
procedure CleanUp;
{: Base THeightData requester method.<p>
Returns (by rebuilding it or from the cache) a THeightData
corresponding to the given area. Size must be a power of two.<p>
Subclasses may choose to publish it or just publish datasource-
specific requester method using specific parameters. }
function GetData(xLeft, yTop, size : Integer;
dataType : THeightDataType) : THeightData; virtual;
{: Preloading request.<p>
See GetData for details. }
function PreLoad(xLeft, yTop, size : Integer;
dataType : THeightDataType) : THeightData; virtual;
{: Notification that the data is no longer used by the renderer.<p>
Default behaviour is just to change DataState to hdsReady (ie. return
the data to the pool) }
procedure Release(aHeightData : THeightData);
{: Maximum number of background threads.<p>
If 0 (zero), multithreading is disabled and StartPreparingData
will be called from the mainthread, and all preload requirements
(queued THeightData objects) will be loaded in sequence from
the main thread.<p>
If 1, basic multithreading and queueing gets enabled,
ie. StartPreparingData will be called from a thread, but from one
thread only (ie. there is no need to implement a THeightDataThread,
just make sure StartPreparingData code is thread-safe).<p>
Other values (2 and more) are relevant only if you implement
a THeightDataThread subclass and fire it in StartPreparingData. }
property MaxThreads : Integer read FMaxThreads write SetMaxThreads;
{: Maximum size of TDataHeight pool in bytes.<p>
The pool (cache) can actually get larger if more data than the pool
can accomodate is used, but as soon as data gets released and returns
to the pool, TDataHeight will be freed untill total pool size gets
below this figure.<br>
The pool manager frees TDataHeight objects who haven't been requested
for the longest time first.<p>
The default value of zero effectively disables pooling. }
property MaxPoolSize : Integer read FMaxPoolSize write FMaxPoolSize;
{: Interpolates height for the given point. }
function InterpolatedHeight(x, y : Single) : Single; virtual;
end;
// THeightDataState
//
{: Possible states for a THeightData.<p>
<ul>
<li>hdsQueued : the data has been queued for loading
<li>hdsPreparing : the data is currently loading or being prepared for use
<li>hdsReady : the data is fully loaded and ready for use
</ul> }
THeightDataState = ( hdsQueued, hdsPreparing, hdsReady);
THeightDataThread = class;
// THeightData
//
{: Base class for height data, stores a height-field raster.<p>
The raster is a square, whose size must be a power of two. Data can be
accessed through a base pointer ("ByteData[n]" f.i.), or through pointer
indirections ("ByteRaster[y][x]" f.i.), this are the fastest way to access
height data (and the most unsecure).<br>
Secure (with range checking) data access is provided by specialized
methods (f.i. "ByteHeight"), in which coordinates (x & y) are always
considered relative (like in raster access).<p>
The class offers conversion facility between the types (as a whole data
conversion), but in any case, the THeightData should be directly requested
from the THeightDataSource with the appropriate format.<p>
Though this class can be instantiated, you will usually prefer to subclass
it in real-world cases, f.i. to add texturing data. }
THeightData = class (TObject)
private
{ Private Declarations }
FOwner : THeightDataSource;
FDataState : THeightDataState;
FSize : Integer;
FXLeft, FYTop : Integer;
FUseCounter : Integer;
FDataType : THeightDataType;
FByteData : PByteArray;
FByteRaster : PByteRaster;
FWordData : PWordArray;
FWordRaster : PWordRaster;
FSingleData : PSingleArray;
FSingleRaster : PSingleRaster;
FObjectTag : TObject;
FTag, FTag2 : Integer;
FOnDestroy : TNotifyEvent;
procedure BuildByteRaster;
procedure BuildWordRaster;
procedure BuildSingleRaster;
procedure ConvertByteToWord;
procedure ConvertByteToSingle;
procedure ConvertWordToByte;
procedure ConvertWordToSingle;
procedure ConvertSingleToByte;
procedure ConvertSingleToWord;
protected
{ Protected Declarations }
FThread : THeightDataThread; // thread used for multi-threaded processing (if any)
procedure SetDataType(const val : THeightDataType);
public
{ Public Declarations }
constructor Create(aOwner : THeightDataSource;
aXLeft, aYTop, aSize : Integer;
aDataType : THeightDataType); virtual;
destructor Destroy; override;
{: The component who created and maintains this data. }
property Owner : THeightDataSource read FOwner;
{: Fired when the object is destroyed. }
property OnDestroy : TNotifyEvent read FOnDestroy write FOnDestroy;
{: Counter for use registration.<p>
A THeightData is not returned to the pool untill this counter reaches
a value of zero. }
property UseCounter : Integer read FUseCounter;
{: Increments UseCounter.<p> }
procedure RegisterUse;
{: Decrements UseCounter.<p>
When the counter reaches zero, notifies the Owner THeightDataSource
that the data is no longer used.<p>
The renderer should call Release when it no longer needs a THeighData,
and never free/destroy the object directly. }
procedure Release;
{: World X coordinate of top left point. }
property XLeft : Integer read FXLeft;
{: World Y coordinate of top left point. }
property YTop : Integer read FYTop;
{: Type of the data.<p>
Assigning a new datatype will result in the data being converted. }
property DataType : THeightDataType read FDataType write SetDataType;
{: Current state of the data. }
property DataState : THeightDataState read FDataState write FDataState;
{: Size of the data square, in data units. }
property Size : Integer read FSize;
{: Memory size of the raw data in bytes. }
function DataSize : Integer;
{: Access to data as a byte array (n = y*Size+x).<p>
If THeightData is not of type hdtByte, this value is nil. }
property ByteData : PByteArray read FByteData;
{: Access to data as a byte raster (y, x).<p>
If THeightData is not of type hdtByte, this value is nil. }
property ByteRaster : PByteRaster read FByteRaster;
{: Access to data as a Word array (n = y*Size+x).<p>
If THeightData is not of type hdtWord, this value is nil. }
property WordData : PWordArray read FWordData;
{: Access to data as a Word raster (y, x).<p>
If THeightData is not of type hdtWord, this value is nil. }
property WordRaster : PWordRaster read FWordRaster;
{: Access to data as a Single array (n = y*Size+x).<p>
If THeightData is not of type hdtSingle, this value is nil. }
property SingleData : PSingleArray read FSingleData;
{: Access to data as a Single raster (y, x).<p>
If THeightData is not of type hdtSingle, this value is nil. }
property SingleRaster : PSingleRaster read FSingleRaster;
{: Height of point x, y as a Byte.<p> }
function ByteHeight(x, y : Integer) : Byte;
{: Height of point x, y as a Word.<p> }
function WordHeight(x, y : Integer) : Word;
{: Height of point x, y as a Single.<p> }
function SingleHeight(x, y : Integer) : Single;
{: Interopolated height of point x, y as a Single.<p> }
function InterpolatedHeight(x, y : Single) : Single;
{: Returns the height as a single, whatever the DataType (slow). }
function Height(x, y : Integer) : Single;
{: Calculates and returns the normal for point x, y.<p>
Sub classes may provide normal cacheing, the default implementation
being rather blunt. }
function Normal(x, y : Integer; const scale : TAffineVector) : TAffineVector; virtual;
{: Reserved for renderer use. }
property ObjectTag : TObject read FObjectTag write FObjectTag;
{: Reserved for renderer use. }
property Tag : Integer read FTag write FTag;
{: Reserved for renderer use. }
property Tag2 : Integer read FTag2 write FTag2;
end;
// THeightDataThread
//
{: A thread specialized for processing THeightData in background.<p>
Requirements:<ul>
<li>must have FreeOnTerminate set to true,
<li>must check and honour Terminated swiftly
</ul> }
THeightDataThread = class (TThread)
protected
{ Protected Declarations }
FHeightData : THeightData;
public
{ Public Declarations }
destructor Destroy; override;
end;
// TGLBitmapHDS
//
{: Bitmap-based Height Data Source.<p>
The image is automatically wrapped if requested data is out of picture size,
or if requested data is larger than the picture.<p>
The internal format is an 8 bit bitmap whose dimensions are a power of two,
if the original image does not comply, it is StretchDraw'ed on a monochrome
(gray) bitmap. }
TGLBitmapHDS = class (THeightDataSource)
private
{ Private Declarations }
FBitmap : TBitmap;
FPicture : TPicture;
protected
{ Protected Declarations }
procedure SetPicture(const val : TPicture);
procedure OnPictureChanged(Sender : TObject);
procedure CreateMonochromeBitmap(size : Integer);
procedure FreeMonochromeBitmap;
procedure StartPreparingData(heightData : THeightData); override;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published Declarations }
{: The picture serving as Height field data reference.<p>
The picture is (if not already) internally converted to a 8 bit
bitmap (grayscale). For better performance and to save memory,
feed it this format! }
property Picture : TPicture read FPicture write SetPicture;
property MaxPoolSize;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils, GLMisc;
// ------------------
// ------------------ THeightDataSourceThread ------------------
// ------------------
type
THeightDataSourceThread = class (TThread)
FOwner : THeightDataSource;
FIdleLoops : Integer;
procedure Execute; override;
end;
// Execute
//
procedure THeightDataSourceThread.Execute;
var
i, n : Integer;
isIdle : Boolean;
begin
while not Terminated do begin
isIdle:=True;
if FOwner.MaxThreads>0 then begin
// current estimated nb threads running
n:=0;
with FOwner.FData.LockList do begin
try
for i:=0 to Count-1 do
if THeightData(Items[i]).FThread<>nil then Inc(n);
i:=0;
while (n<FOwner.MaxThreads) and (i<Count) do begin
if THeightData(Items[i]).DataState=hdsQueued then begin
FOwner.StartPreparingData(THeightData(Items[i]));
isIdle:=False;
Inc(n);
end;
Inc(i);
end;
finally
FOwner.FData.UnlockList;
end;
end;
end;
if isIdle then
Inc(FIdleLoops)
else FIdleLoops:=0;
if FIdleLoops<10 then
Sleep(0) // "fast" mode
else Sleep(10); // "doze" mode
end;
end;
// ------------------
// ------------------ THeightDataSource ------------------
// ------------------
// Create
//
constructor THeightDataSource.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHeightDataClass:=THeightData;
FData:=TThreadList.Create;
FThread:=THeightDataSourceThread.Create(True);
FThread.FreeOnTerminate:=False;
THeightDataSourceThread(FThread).FOwner:=Self;
FThread.Resume;
end;
// Destroy
//
destructor THeightDataSource.Destroy;
begin
FThread.Terminate;
FThread.WaitFor;
FThread.Free;
Clear;
FData.Free;
inherited Destroy;
end;
// Clear
//
procedure THeightDataSource.Clear;
var
i : Integer;
begin
with FData.LockList do begin
try
for i:=0 to Count-1 do
if THeightData(Items[i]).UseCounter>0 then
raise Exception.Create('ERR: HeightData still in use');
for i:=0 to Count-1 do begin
THeightData(Items[i]).FOwner:=nil;
THeightData(Items[i]).Free;
end;
Clear;
finally
FData.UnlockList;
end;
end;
end;
// FindMatchInList
//
function THeightDataSource.FindMatchInList(xLeft, yTop, size : Integer;
dataType : THeightDataType) : THeightData;
var
i : Integer;
hd : THeightData;
begin
Result:=nil;
with FData.LockList do begin
try
for i:=0 to Count-1 do begin
hd:=THeightData(Items[i]);
if (hd.XLeft=xLeft) and (hd.YTop=yTop) and (hd.Size=size) and (hd.DataType=dataType) then begin
Result:=hd;
Break;
end;
end;
finally
FData.UnlockList;
end;
end;
end;
// GetData
//
function THeightDataSource.GetData(xLeft, yTop, size : Integer;
dataType : THeightDataType) : THeightData;
begin
Result:=FindMatchInList(xLeft, yTop, size, dataType);
if not Assigned(Result) then
Result:=PreLoad(xLeft, yTop, size, dataType)
else with FData.LockList do begin
try
Move(IndexOf(Result), 0);
finally
FData.UnlockList;
end;
end;
// got one... can be used ?
while Result.DataState<>hdsReady do Sleep(0);
Result.RegisterUse;
end;
// PreLoad
//
function THeightDataSource.PreLoad(xLeft, yTop, size : Integer;
dataType : THeightDataType) : THeightData;
begin
CleanUp;
Result:=HeightDataClass.Create(Self, xLeft, yTop, size, dataType);
FData.LockList.Insert(0, Result);
FData.UnlockList;
if MaxThreads=0 then
StartPreparingData(Result);
end;
// Release
//
procedure THeightDataSource.Release(aHeightData : THeightData);
begin
CleanUp;
end;
// CleanUp
//
procedure THeightDataSource.CleanUp;
var
i : Integer;
usedMemory : Integer;
begin
with FData.LockList do begin
try
usedMemory:=0;
for i:=0 to Count-1 do
usedMemory:=usedMemory+THeightData(Items[i]).DataSize;
if usedMemory>MaxPoolSize then begin
for i:=Count-1 downto 0 do with THeightData(Items[i]) do begin
if (DataState=hdsReady) and (UseCounter=0) then begin
usedMemory:=usedMemory-DataSize;
FOwner:=nil;
Free;
Delete(i);
if usedMemory<=MaxPoolSize then Break;
end;
end;
end;
finally
FData.UnlockList;
end;
end;
end;
// SetMaxThreads
//
procedure THeightDataSource.SetMaxThreads(const val : Integer);
begin
if val<0 then
FMaxThreads:=0
else FMaxThreads:=val;
end;
// StartPreparingData
//
procedure THeightDataSource.StartPreparingData(heightData : THeightData);
begin
heightData.FDataState:=hdsReady;
end;
// InterpolatedHeight
//
function THeightDataSource.InterpolatedHeight(x, y : Single) : Single;
var
i : Integer;
hd, foundHd : THeightData;
begin
with FData.LockList do begin
try
// first, lookup data list to find if aHeightData contains our point
foundHd:=nil;
for i:=0 to Count-1 do begin
hd:=THeightData(Items[i]);
if (hd.XLeft<=x) and (hd.YTop<=y)
and (hd.XLeft+hd.Size-1>x) and (hd.YTop+hd.Size-1>y) then begin
foundHd:=hd;
Break;
end;
end;
finally
FData.UnlockList;
end;
end;
if foundHd=nil then begin
// not found, request one... slowest mode (should be avoided)
foundHd:=GetData(Trunc(x)-1, Trunc(y)-1, 4, hdtSingle);
end else begin
// request it using "standard" way (takes care of threads)
foundHd:=GetData(foundHd.XLeft, foundHd.YTop, foundHd.Size, foundHd.DataType);
end;
try
Result:=foundHd.InterpolatedHeight(x-foundHd.XLeft, y-foundHd.YTop);
finally
foundHd.Release;
end;
end;
// ------------------
// ------------------ THeightData ------------------
// ------------------
// Create
//
constructor THeightData.Create(aOwner : THeightDataSource;
aXLeft, aYTop, aSize : Integer;
aDataType : THeightDataType);
begin
inherited Create;
FOwner:=aOwner;
FXLeft:=aXLeft;
FYTop:=aYTop;
FSize:=aSize;
FDataType:=aDataType;
FDataState:=hdsQueued;
case DataType of
hdtByte : begin
FByteData:=AllocMem(Size*Size*SizeOf(Byte));
BuildByteRaster;
end;
hdtWord : begin
FWordData:=AllocMem(Size*Size*SizeOf(Word));
BuildWordRaster;
end;
hdtSingle : begin
FSingleData:=AllocMem(Size*Size*SizeOf(Single));
BuildSingleRaster;
end;
else
Assert(False);
end;
end;
// Destroy
//
destructor THeightData.Destroy;
begin
Assert(not Assigned(FOwner), 'You should *not* free a THeightData, use "Release" instead');
if Assigned(FThread) then begin
FThread.Terminate;
FThread.WaitFor;
end;
if Assigned(FOnDestroy) then
FOnDestroy(Self);
case DataType of
hdtByte : begin
FreeMem(FByteData);
FreeMem(FByteRaster);
end;
hdtWord : begin
FreeMem(FWordData);
FreeMem(FWordRaster);
end;
hdtSingle : begin
FreeMem(FSingleData);
FreeMem(FSingleRaster);
end;
else
Assert(False);
end;
inherited Destroy;
end;
// RegisterUse
//
procedure THeightData.RegisterUse;
begin
Inc(FUseCounter);
end;
// Release
//
procedure THeightData.Release;
begin
Dec(FUseCounter);
Assert(FUseCounter>=0);
if FUseCounter=0 then
Owner.Release(Self);
end;
// SetDataType
//
procedure THeightData.SetDataType(const val : THeightDataType);
begin
if val<>FDataType then begin
case FDataType of
hdtByte : case val of
hdtWord : ConvertByteToWord;
hdtSingle : ConvertByteToSingle;
else
Assert(False);
end;
hdtWord : case val of
hdtByte : ConvertWordToByte;
hdtSingle : ConvertWordToSingle;
else
Assert(False);
end;
hdtSingle : case val of
hdtByte : ConvertSingleToByte;
hdtWord : ConvertSingleToWord;
else
Assert(False);
end;
else
Assert(False);
end;
FDataType:=val;
end;
end;
// DataSize
//
function THeightData.DataSize : Integer;
begin
case DataType of
hdtByte : Result:=Size*Size*SizeOf(Byte);
hdtWord : Result:=Size*Size*SizeOf(Word);
hdtSingle : Result:=Size*Size*SizeOf(Single);
else
Result:=0;
Assert(False);
end;
end;
// BuildByteRaster
//
procedure THeightData.BuildByteRaster;
var
i : Integer;
begin
FByteRaster:=AllocMem(Size*SizeOf(PByteArray));
for i:=0 to Size-1 do
FByteRaster[i]:=@FByteData[i*Size]
end;
// BuildWordRaster
//
procedure THeightData.BuildWordRaster;
var
i : Integer;
begin
FWordRaster:=AllocMem(Size*SizeOf(PWordArray));
for i:=0 to Size-1 do
FWordRaster[i]:=@FWordData[i*Size]
end;
// BuildSingleRaster
//
procedure THeightData.BuildSingleRaster;
var
i : Integer;
begin
FSingleRaster:=AllocMem(Size*SizeOf(PSingleArray));
for i:=0 to Size-1 do
FSingleRaster[i]:=@FSingleData[i*Size]
end;
// ConvertByteToWord
//
procedure THeightData.ConvertByteToWord;
var
i : Integer;
begin
FreeMem(FByteRaster);
FByteRaster:=nil;
FWordData:=AllocMem(Size*Size*SizeOf(Word));
for i:=0 to Size*Size-1 do
FWordData[i]:=FByteData[i];
FreeMem(FByteData);
FByteData:=nil;
BuildWordRaster;
end;
// ConvertByteToSingle
//
procedure THeightData.ConvertByteToSingle;
var
i : Integer;
begin
FreeMem(FByteRaster);
FByteRaster:=nil;
FSingleData:=AllocMem(Size*Size*SizeOf(Single));
for i:=0 to Size*Size-1 do
FSingleData[i]:=FByteData[i];
FreeMem(FByteData);
FByteData:=nil;
BuildSingleRaster;
end;
// ConvertWordToByte
//
procedure THeightData.ConvertWordToByte;
var
i : Integer;
begin
FreeMem(FWordRaster);
FWordRaster:=nil;
FByteData:=Pointer(FWordData);
for i:=0 to Size*Size-1 do
FByteData[i]:=FWordData[i];
ReallocMem(FByteData, Size*Size*SizeOf(Byte));
FWordData:=nil;
BuildByteRaster;
end;
// ConvertWordToSingle
//
procedure THeightData.ConvertWordToSingle;
var
i : Integer;
begin
FreeMem(FWordRaster);
FWordRaster:=nil;
FSingleData:=AllocMem(Size*Size*SizeOf(Single));
for i:=0 to Size*Size-1 do
FSingleData[i]:=FWordData[i];
FreeMem(FWordData);
FWordData:=nil;
BuildSingleRaster;
end;
// ConvertSingleToByte
//
procedure THeightData.ConvertSingleToByte;
var
i : Integer;
begin
FreeMem(FSingleRaster);
FSingleRaster:=nil;
FByteData:=Pointer(FSingleData);
for i:=0 to Size*Size-1 do
FByteData[i]:=Round(FSingleData[i]);
ReallocMem(FByteData, Size*Size*SizeOf(Byte));
FSingleData:=nil;
BuildByteRaster;
end;
// ConvertSingleToWord
//
procedure THeightData.ConvertSingleToWord;
var
i : Integer;
begin
FreeMem(FSingleRaster);
FSingleRaster:=nil;
FWordData:=Pointer(FSingleData);
for i:=0 to Size*Size-1 do
FWordData[i]:=Round(FSingleData[i]);
ReallocMem(FWordData, Size*Size*SizeOf(Word));
FSingleData:=nil;
BuildWordRaster;
end;
// ByteHeight
//
function THeightData.ByteHeight(x, y : Integer) : Byte;
begin
Assert((Cardinal(x)<Cardinal(Size)) and (Cardinal(y)<Cardinal(Size)));
Result:=ByteRaster[y][x];
end;
// WordHeight
//
function THeightData.WordHeight(x, y : Integer) : Word;
begin
Assert((Cardinal(x)<Cardinal(Size)) and (Cardinal(y)<Cardinal(Size)));
Result:=WordRaster[y][x];
end;
// SingleHeight
//
function THeightData.SingleHeight(x, y : Integer) : Single;
begin
Assert((Cardinal(x)<Cardinal(Size)) and (Cardinal(y)<Cardinal(Size)));
Result:=SingleRaster[y][x];
end;
// InterpolatedHeight
//
function THeightData.InterpolatedHeight(x, y : Single) : Single;
var
ix, iy : Integer;
h1, h2, h3 : Single;
begin
ix:=Trunc(x); x:=Frac(x);
iy:=Trunc(y); y:=Frac(y);
if x+y<=1 then begin
// top-left triangle
h1:=Height(ix, iy);
h2:=Height(ix+1, iy);
h3:=Height(ix, iy+1);
Result:=h1+(h2-h1)*x+(h3-h1)*y;
end else begin
// bottom-right triangle
h1:=Height(ix+1, iy+1);
h2:=Height(ix, iy+1);
h3:=Height(ix+1, iy);
Result:=h1+(h2-h1)*(1-x)+(h3-h1)*(1-y);
end;
end;
// Height
//
function THeightData.Height(x, y : Integer) : Single;
begin
case DataType of
hdtByte : Result:=ByteHeight(x, y);
hdtWord : Result:=WordHeight(x, y);
hdtSingle : Result:=SingleHeight(x, y);
else
Result:=0;
Assert(False);
end;
end;
// Normal
//
function THeightData.Normal(x, y : Integer; const scale : TAffineVector) : TAffineVector;
var
dx, dy : Single;
begin
if x>0 then
if x<Size-1 then
dx:=(Height(x+1, y)-Height(x-1, y))*scale[0]*scale[2]
else dx:=(Height(x, y)-Height(x-1, y))*scale[0]*scale[2]
else dx:=(Height(x+1, y)-Height(x, y))*scale[0]*scale[2];
if y>0 then
if y<Size-1 then
dy:=(Height(x, y+1)-Height(x, y-1))*scale[1]*scale[2]
else dy:=(Height(x, y)-Height(x, y-1))*scale[1]*scale[2]
else dy:=(Height(x, y+1)-Height(x, y))*scale[1]*scale[2];
Result[0]:=dx;
Result[1]:=dy;
Result[2]:=1;
NormalizeVector(Result);
end;
// ------------------
// ------------------ THeightDataThread ------------------
// ------------------
// Destroy
//
destructor THeightDataThread.Destroy;
begin
if Assigned(FHeightData) then
FHeightData.FThread:=nil;
inherited;
end;
// ------------------
// ------------------ TGLBitmapHDS ------------------
// ------------------
// Create
//
constructor TGLBitmapHDS.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPicture:=TPicture.Create;
FPicture.OnChange:=OnPictureChanged;
end;
// Destroy
//
destructor TGLBitmapHDS.Destroy;
begin
FreeMonochromeBitmap;
FPicture.Free;
inherited Destroy;
end;
// SetPicture
//
procedure TGLBitmapHDS.SetPicture(const val : TPicture);
begin
FPicture.Assign(val);
end;
// OnPictureChanged
//
procedure TGLBitmapHDS.OnPictureChanged(Sender : TObject);
var
oldPoolSize, size : Integer;
begin
// cleanup pool
oldPoolSize:=MaxPoolSize;
MaxPoolSize:=0;
CleanUp;
MaxPoolSize:=oldPoolSize;
// prepare MonoChromeBitmap
FreeMonochromeBitmap;
size:=Picture.Width;
if size>0 then
CreateMonochromeBitmap(size);
end;
// CreateMonochromeBitmap
//
procedure TGLBitmapHDS.CreateMonochromeBitmap(size : Integer);
type
TLogPal = record
lpal : TLogPalette;
pe : Array[0..255] of TPaletteEntry;
end;
var
x : Integer;
logpal : TLogPal;
begin
size:=RoundUpToPowerOf2(size);
FBitmap:=TBitmap.Create;
FBitmap.PixelFormat:=pf8bit;
FBitmap.Width:=size;
FBitmap.Height:=size;
for x:=0 to 255 do with logPal.lpal.palPalEntry[x] do begin
peRed:=x;
peGreen:=x;
peBlue:=x;
peFlags:=0;
end;
with logpal.lpal do begin
palVersion:=$300;
palNumEntries:=256;
end;
FBitmap.Palette:=CreatePalette(logPal.lpal);
FBitmap.Canvas.StretchDraw(Rect(0, 0, size, size), Picture.Graphic);
end;
// FreeMonochromeBitmap
//
procedure TGLBitmapHDS.FreeMonochromeBitmap;
begin
FBitmap.Free;
FBitmap:=nil;
end;
// StartPreparingData
//
procedure TGLBitmapHDS.StartPreparingData(heightData : THeightData);
var
y, x : Integer;
bmpSize, wrapMask : Integer;
bitmapLine, rasterLine : PByteArray;
oldType : THeightDataType;
b : Byte;
begin
if FBitmap=nil then Exit;
bmpSize:=FBitmap.Width;
wrapMask:=bmpSize-1;
// retrieve data
with heightData do begin
oldType:=DataType;
DataType:=hdtByte;
for y:=YTop to YTop+Size-1 do begin
bitmapLine:=FBitmap.ScanLine[y and wrapMask];
rasterLine:=ByteRaster[y-YTop];
// *BIG CAUTION HERE* : Don't remove the intermediate variable here!!!
// or Delphi compiler will "optimize" to 32 bits access with clamping
// resulting in possible reads of stuff beyon bitmapLine length!!!!
for x:=XLeft to XLeft+Size-1 do begin
b:=bitmapLine[x and wrapMask];
rasterLine[x-XLeft]:=b;
end;
end;
if oldType<>hdtByte then
DataType:=oldType;
end;
inherited;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClass(TGLBitmapHDS);
end.
|
unit xe_COM40;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxLookAndFeels, MSXML2_TLB,
cxLookAndFeelPainters, Vcl.Menus, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls,
cxControls, cxContainer, cxEdit, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxNavigator, Data.DB, cxDBData, cxLabel, cxCurrencyEdit,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxClasses, cxGridCustomView, cxGrid, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxGroupBox, dxSkinsCore, dxSkinscxPCPainter, cxRadioGroup,
dxSkinOffice2010Silver, dxDateRanges, dxSkinSharp, dxSkinMetropolisDark, dxSkinOffice2007Silver;
type
TFrm_COM40 = class(TForm)
pnlTitle: TPanel;
btnClose: TcxButton;
Panel1: TPanel;
cxGroupBox1: TcxGroupBox;
cxLabel1: TcxLabel;
curTotal: TcxLabel;
cxLabel2: TcxLabel;
curCurrent: TcxLabel;
cxLabel3: TcxLabel;
curCoupon: TcxLabel;
cxLabel5: TcxLabel;
curPrzCnt: TcxLabel;
cxGroupBox2: TcxGroupBox;
cxLabel4: TcxLabel;
cbbCuProduct: TcxComboBox;
cxLabel15: TcxLabel;
curOutMileMny: TcxCurrencyEdit;
btnMileOut: TcxButton;
cxGroupBox3: TcxGroupBox;
cxLabel6: TcxLabel;
cxLabel7: TcxLabel;
cxLabel8: TcxLabel;
cxCurMileRefresh: TcxCurrencyEdit;
btnMileCharge: TcxButton;
edtAddMileMemo: TcxTextEdit;
cxGroupBox4: TcxGroupBox;
cxGrid1: TcxGrid;
cxgCustMlg: TcxGridDBTableView;
cxgCustMlgColumn1: TcxGridDBColumn;
cxgCustMlgColumn2: TcxGridDBColumn;
cxgCustMlgColumn3: TcxGridDBColumn;
cxgCustMlgColumn4: TcxGridDBColumn;
cxgCustMlgColumn7: TcxGridDBColumn;
cxgCustMlgColumn5: TcxGridDBColumn;
cxgCustMlgColumn8: TcxGridDBColumn;
cxgCustMlgColumn6: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
cxLabel9: TcxLabel;
cxLabel22: TcxLabel;
CB_Gubun: TcxComboBox;
cxBtnTelNESelect: TcxButton;
clbCuSeq: TcxLabel;
edtMileMemo: TcxTextEdit;
cxLabel10: TcxLabel;
grpSetCoupon: TcxGroupBox;
edtCouponHP: TcxTextEdit;
btnCouponSend: TcxButton;
btnCouponClose: TcxButton;
lblCouponDesc: TcxLabel;
Panel2: TPanel;
cxLabel13: TcxLabel;
cxLabel11: TcxLabel;
cxLblActive: TLabel;
curEventCnt: TcxLabel;
grpSetEventView: TcxGroupBox;
cxBtnEvent: TcxButton;
cxLabel12: TcxLabel;
curMileLost: TcxLabel;
Shape17: TShape;
cxBtnEventClose: TcxButton;
cxBtnEventInit: TcxButton;
cxBtnEventSave: TcxButton;
cxEventCnt: TcxCurrencyEdit;
cxFEventCnt: TcxCurrencyEdit;
cxHEventCnt: TcxCurrencyEdit;
cxLabel14: TcxLabel;
cxLabel16: TcxLabel;
cxLabel17: TcxLabel;
cxLabel18: TcxLabel;
edtEventMemo: TcxTextEdit;
rbEventM: TcxRadioButton;
rbEventP: TcxRadioButton;
Shape1: TShape;
Shape2: TShape;
procedure FormCreate(Sender: TObject);
procedure cxBtnTelNESelectClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnCloseClick(Sender: TObject);
procedure btnMileOutClick(Sender: TObject);
procedure btnMileChargeClick(Sender: TObject);
procedure btnCouponCloseClick(Sender: TObject);
procedure btnCouponSendClick(Sender: TObject);
procedure cbbCuProductKeyPress(Sender: TObject; var Key: Char);
procedure curOutMileMnyExit(Sender: TObject);
procedure curOutMileMnyKeyPress(Sender: TObject; var Key: Char);
procedure edtMileMemoKeyPress(Sender: TObject; var Key: Char);
procedure cxCurMileRefreshExit(Sender: TObject);
procedure cxCurMileRefreshKeyPress(Sender: TObject; var Key: Char);
procedure edtAddMileMemoKeyPress(Sender: TObject; var Key: Char);
procedure FormDestroy(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure pnlTitleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cxBtnEventCloseClick(Sender: TObject);
procedure cxBtnEventClick(Sender: TObject);
procedure cxEventCntPropertiesChange(Sender: TObject);
procedure cxBtnEventSaveClick(Sender: TObject);
procedure cxBtnEventInitClick(Sender: TObject);
procedure rbEventMClick(Sender: TObject);
procedure cbbCuProductPropertiesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
procedure Proc_Init;
// 고객 마일리지를 충전 처리 한다.
procedure Proc_CustMileRefresh;
// 고객 마일리지를 즉시차감 처리 한다.
procedure Proc_CustMileDeduct;
procedure RequestMobileCoupone(ACuSeq, AHP: string; ACharge: Integer);
procedure RequestData(AData: string);
procedure ResponseData(AXmlData: string);
function IsUseCoupon(ABrNo: string): Boolean;
function GetPriceFromProduct(AStr: string): Integer;
public
{ Public declarations }
procedure proc_search;
procedure SetCuProduct(AProdName: string; AProdPrice: Integer);
end;
var
Frm_COM40: TFrm_COM40;
implementation
{$R *.dfm}
uses xe_xml, xe_Func, xe_GNL, xe_Dm, Main, xe_Msg, xe_Query, xe_Flash, xe_Lib,
xe_gnl2, xe_gnl3, xe_packet;
procedure TFrm_COM40.btnCloseClick(Sender: TObject);
begin
Close;
end;
function TFrm_COM40.IsUseCoupon(ABrNo: string): Boolean;
var
Idx: Integer;
begin
Result := False;
Idx := scb_BranchCode.IndexOf(ABrNo);
if Idx < 0 then
Exit;
Result := (scb_BranchCoupon[Idx] = 'y');
end;
function TFrm_COM40.GetPriceFromProduct(AStr: string): Integer;
var
Str: string;
begin
Str := Copy(AStr, 1, Pos('원', AStr) - 1);
Str := RemoveComma(Str);
Result := StrToIntDef(Str, 0);
end;
procedure TFrm_COM40.SetCuProduct(AProdName: string; AProdPrice: Integer);
var
Item: TStrings;
begin
cbbCuProduct.Clear;
if IsUseCoupon(Frm_Main.Frm_JON01N[Self.Tag].locBRNO) then
begin
cbbCuProduct.Properties.Items.Text := _PROD_LIST;
cxLabel15.Style.Color := clRed;
cxLabel15.Style.Font.Color := clWhite;
end else
begin
cbbCuProduct.Properties.Items.Text := _PROD_BASE;
cxLabel15.Style.Color := $00FAE1CD;
cxLabel15.Style.Font.Color := $00D1566B;
end;
if AProdName <> '' then
begin
Item := cbbCuProduct.Properties.Items;
Item.Insert(1, AProdName);
if cbbCuProduct.Properties.Items.Count > 1 then
begin
cbbCuProduct.ItemIndex := 2;
AProdPrice := GetPriceFromProduct(cbbCuProduct.Text);
end
else if cbbCuProduct.Properties.Items.Count = 2 then
cbbCuProduct.ItemIndex := 1
else
cbbCuProduct.ItemIndex := -1;
end else
begin
if cbbCuProduct.Properties.Items.Count > 1 then
begin
cbbCuProduct.ItemIndex := 1;
AProdPrice := GetPriceFromProduct(cbbCuProduct.Text);
end else
cbbCuProduct.ItemIndex := -1;
end;
curOutMileMny.Value := AProdPrice;
end;
procedure TFrm_COM40.btnMileOutClick(Sender: TObject);
var
UseMile, TotalMile: Integer;
begin
// 권한 적용 (지호 2008-08-19)
if TCK_USER_PER.COM_CustMlgCharge <> '1' then
begin
GMessagebox('고객에게 상품 지급 권한이 없습니다.', CDMSE);
exit;
end;
if curOutMileMny.Value < 1 then
begin
ShowMessage('지급 할 마일리지 금액을 입력 하세요!');
curOutMileMny.SetFocus;
Exit;
end;
if (clbCuSeq.Caption <> '') then
begin
// 고객 마일리지를 즉시차감 처리 한다.
if Pos('원 주유할인권', cbbCuProduct.Text) > 0 then
begin
UseMile := StrToIntDef(RemoveComma(curOutMileMny.Text), 0);
if UseMile = 0 then
begin
GMessagebox(Format('지급상품권을 다시 선택해주세요.(지급마일리지가 부적절합니다.[%s])', [curOutMileMny.Text]), CDMSE);
Exit;
end;
TotalMile := StrToIntDef(RemoveComma(curCurrent.Caption), 0);
if TotalMile < UseMile then
begin
GMessagebox(Format('사용가능 마일리지가 부족합니다.[현재: %s, 지급: %s]', [
FormatCash(TotalMile), FormatCash(UseMile)]), CDMSE);
Exit;
end;
GrpSetCoupon.Left := 11;
GrpSetCoupon.Top := 35;
edtCouponHP.Text := Frm_Main.Frm_JON01N[Self.Tag].locsCuTel;
GrpSetCoupon.Visible := True;
edtCouponHP.SetFocus;
end else
begin
Proc_CustMileDeduct;
end;
end else
begin
ShowMessage('신규 미등록 고객은 마일리지를 지급할 수 없습니다.');
end;
end;
procedure TFrm_COM40.cbbCuProductKeyPress(Sender: TObject; var Key: Char);
begin
if Ord(Key) = VK_RETURN then
curOutMileMny.SetFocus;
end;
procedure TFrm_COM40.cbbCuProductPropertiesChange(Sender: TObject);
begin
curOutMileMny.Enabled := True;
curOutMileMny.Value := 0;
case TcxComboBox(Sender).ItemIndex of
-1:
TcxComboBox(Sender).Properties.DropDownListStyle := lsEditList;
0:
begin
TcxComboBox(Sender).Properties.DropDownListStyle := lsEditList;
TcxComboBox(Sender).Text := '';
end;
else
TcxComboBox(Sender).Properties.DropDownListStyle := lsFixedList;
if Pos('원 주유할인권', TcxComboBox(Sender).Text) > 0 then
begin
curOutMileMny.Value := GetPriceFromProduct(TcxComboBox(Sender).Text);
curOutMileMny.Enabled := False;
end;
end;
end;
procedure TFrm_COM40.curOutMileMnyExit(Sender: TObject);
begin
if curOutMileMny.Text = '' then
curOutMileMny.Value := 0;
end;
procedure TFrm_COM40.curOutMileMnyKeyPress(Sender: TObject; var Key: Char);
begin
if Ord(Key) = VK_RETURN then
edtMileMemo.SetFocus;
end;
procedure TFrm_COM40.cxBtnEventClick(Sender: TObject);
begin
cxHEventCnt.Text := curEventCnt.Caption;
cxFEventCnt.Value := 0;
cxEventCnt.Value := 0;
GrpSetEventView.Top := cxGroupBox2.Top;
GrpSetEventView.Left := cxGroupBox2.Left;
GrpSetEventView.Visible := True;
end;
procedure TFrm_COM40.cxBtnEventCloseClick(Sender: TObject);
begin
GrpSetEventView.Visible := False;
end;
procedure TFrm_COM40.cxBtnEventInitClick(Sender: TObject);
Var
Param : string;
locHdNo, locBrNo, sEventCnt: string;
XmlData, ErrMsg: string;
ErrCode: integer;
begin
// 권한 적용 (지호 2008-08-19)
if TCK_USER_PER.COM_CustMlgCharge <> '1' then
begin
GMessagebox('고객에게 지급 권한이 없습니다.', CDMSE);
exit;
end;
if (clbCuSeq.Caption <> '') then
begin
try
if Frm_Main.Frm_JON01N[Self.Tag].lcsCu_seq = '' then
begin
ShowMessage('고객 일련번호가 없습니다. 고객정보를 조회 한 다음 [지급] 하세요!');
Exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].cxtCallTelNum.Text = '' then
begin
ShowMessage('고객 전화번호가 없습니다. 고객정보를 조회 한 다음 [지급] 하세요!');
Exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].cxtCallTelNum.Text <> Frm_Main.Frm_JON01N[Self.Tag].cxtCuTel.Text then
begin
ShowMessage('지급 할 고객 전화번호가 조회한 전화번호와 다릅니다. 고객정보를 재조회 한 다음 [지급] 처리 하세요!');
Exit;
end;
if Application.MessageBox('해당 고객의 이벤트횟수를 초기화 하시겠습니까?', 'CDMS', MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2) = IDNO then
begin
Exit;
end;
sEventCnt := FloatToStr(cxEventCnt.Value);
locHdNo := Frm_Main.Frm_JON01N[Self.Tag].Proc_HDNOSearch; // 본사코드 정보를 읽는다.
locBrNo := Frm_Main.Frm_JON01N[Self.Tag].Proc_BRNOSearch; // 지사코드 정보를 읽는다.
Param := En_Coding(Frm_Main.Frm_JON01N[Self.Tag].lcsCu_seq);
Param := Param + '│' + En_Coding(Frm_Main.Frm_JON01N[Self.Tag].cxtCuTel.Text);
Param := Param + '│' + locHdNo;
Param := Param + '│' + locBrNo;
Param := Param + '│' + En_Coding(edtEventMemo.Text);
Param := Param + '│' + En_Coding(sEventCnt);
Param := Param + '│2│1'; // 0.차감,1.충전,2.초기화 || 0.마일리지,1.이벤트횟수
if not RequestBase(GetCallable05('SET_CUST_MILEAGE', 'MNG_CUST.SET_CUST_MILEAGE', Param), XmlData, ErrCode, ErrMsg) then
begin
GMessageBox(Format('[%d] %s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
curEventCnt.Caption := '0';
cxEventCnt.Value := 0;
edtEventMemo.Clear;
ShowMessage('초기화 되었습니다.');
GrpSetEventView.Visible := False;
except
on e: exception do
begin
Assert(False, E.Message);
end;
end;
end else
begin
ShowMessage('신규 미등록 고객은 이벤트 횟수를 저장할 수 없습니다.');
end;
end;
procedure TFrm_COM40.cxBtnEventSaveClick(Sender: TObject);
Var
Param : string;
locHdNo, locBrNo, sEventCnt: string;
XmlData, ErrMsg: string;
ErrCode: integer;
begin
// 권한 적용 (지호 2008-08-19)
if TCK_USER_PER.COM_CustMlgCharge <> '1' then
begin
GMessagebox('고객에게 지급 권한이 없습니다.', CDMSE);
exit;
end;
if (clbCuSeq.Caption <> '') then
begin
try
if Frm_Main.Frm_JON01N[Self.Tag].lcsCu_seq = '' then
begin
ShowMessage('고객 일련번호가 없습니다. 고객정보를 조회 한 다음 [지급] 하세요!');
Exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].cxtCallTelNum.Text = '' then
begin
ShowMessage('고객 전화번호가 없습니다. 고객정보를 조회 한 다음 [지급] 하세요!');
Exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].cxtCallTelNum.Text <> Frm_Main.Frm_JON01N[Self.Tag].cxtCuTel.Text then
begin
ShowMessage('지급 할 고객 전화번호가 조회한 전화번호와 다릅니다. 고객정보를 재조회 한 다음 [지급] 처리 하세요!');
Exit;
end;
if cxEventCnt.Value < 1 then
begin
ShowMessage('이벤트 횟수를 입력 하세요!');
cxEventCnt.SetFocus;
Exit;
end;
sEventCnt := FloatToStr(cxEventCnt.Value);
locHdNo := Frm_Main.Frm_JON01N[Self.Tag].Proc_HDNOSearch; // 본사코드 정보를 읽는다.
locBrNo := Frm_Main.Frm_JON01N[Self.Tag].Proc_BRNOSearch; // 지사코드 정보를 읽는다.
Param := En_Coding(Frm_Main.Frm_JON01N[Self.Tag].lcsCu_seq);
Param := Param + '│' + En_Coding(Frm_Main.Frm_JON01N[Self.Tag].cxtCuTel.Text);
Param := Param + '│' + locHdNo;
Param := Param + '│' + locBrNo;
Param := Param + '│' + En_Coding(edtEventMemo.Text);
Param := Param + '│' + En_Coding(sEventCnt);
if rbEventM.Checked then Param := Param + '│0' else
if rbEventP.Checked then Param := Param + '│1';
Param := Param + '│1'; // 0.차감,1.충전 || 0.마일리지,1.이벤트횟수
if not RequestBase(GetCallable05('SET_CUST_MILEAGE', 'MNG_CUST.SET_CUST_MILEAGE', Param), XmlData, ErrCode, ErrMsg) then
begin
GMessageBox(Format('[%d] %s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
curEventCnt.Caption := FloatToStr(cxFEventCnt.Value);
cxHEventCnt.Value := cxFEventCnt.Value;
cxEventCnt.Value := 0;
edtEventMemo.Clear;
ShowMessage('저장 되었습니다.');
GrpSetEventView.Visible := False;
except
on e: exception do
begin
Assert(False, E.Message);
end;
end;
end else
begin
ShowMessage('신규 미등록 고객은 이벤트 횟수를 저장할 수 없습니다.');
end;
end;
procedure TFrm_COM40.cxBtnTelNESelectClick(Sender: TObject);
begin
proc_search;
end;
procedure TFrm_COM40.cxCurMileRefreshExit(Sender: TObject);
begin
if cxCurMileRefresh.Text = '' then
cxCurMileRefresh.Value := 0;
end;
procedure TFrm_COM40.cxCurMileRefreshKeyPress(Sender: TObject; var Key: Char);
begin
if Ord(Key) = VK_RETURN then
edtAddMileMemo.SetFocus;
end;
procedure TFrm_COM40.cxEventCntPropertiesChange(Sender: TObject);
begin
if rbEventM.Checked then
cxFEventCnt.Value := cxHEventCnt.Value - cxEventCnt.Value
else if rbEventP.Checked then
cxFEventCnt.Value := cxHEventCnt.Value + cxEventCnt.Value;
end;
procedure TFrm_COM40.edtAddMileMemoKeyPress(Sender: TObject; var Key: Char);
begin
if Ord(Key) = VK_RETURN then
btnMileCharge.SetFocus;
end;
procedure TFrm_COM40.edtMileMemoKeyPress(Sender: TObject; var Key: Char);
begin
if Ord(Key) = VK_RETURN then
btnMileOut.SetFocus;
end;
procedure TFrm_COM40.btnCouponCloseClick(Sender: TObject);
begin
GrpSetCoupon.Visible := False;
end;
procedure TFrm_COM40.btnCouponSendClick(Sender: TObject);
var
ErrStr: string;
begin
edtCouponHP.Text := RemovePhone(edtCouponHP.Text);
if not CheckHPType(edtCouponHP.Text, ErrStr) then
begin
GMessagebox(ErrStr, CDMSE);
edtCouponHP.SetFocus;
Exit;
end;
RequestMobileCoupone(Frm_Main.Frm_JON01N[Self.Tag].lcsCu_seq, edtCouponHP.Text, Trunc(curOutMileMny.Value));
end;
procedure TFrm_COM40.btnMileChargeClick(Sender: TObject);
begin
// 고객 마일리지를 충전 처리 한다.
if TCK_USER_PER.COM_CustMlgCharge <> '1' then
begin
GMessagebox('고객에게 마일리지 충전 권한이 없습니다.', CDMSE);
exit;
end;
Proc_CustMileRefresh;
end;
procedure TFrm_COM40.FormActivate(Sender: TObject);
begin
cxLblActive.Color := GS_ActiveColor;
cxLblActive.Visible := True;
end;
procedure TFrm_COM40.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrm_COM40.FormCreate(Sender: TObject);
var
Save: LongInt; // 폼타이틀 제거용.
begin
//====================================================
// 폼 타이틀 제거..
Save := GetWindowLong(Handle, gwl_Style);
if (Save and ws_Caption) = ws_Caption then
begin
case BorderStyle of
bsSingle, bsSizeable:
SetWindowLong(Handle, gwl_Style, Save and (not (ws_Caption)) or
ws_border);
end;
Height := Height - getSystemMetrics(sm_cyCaption);
Refresh;
end;
proc_init;
end;
procedure TFrm_COM40.FormDeactivate(Sender: TObject);
begin
cxLblActive.Visible := False;
end;
procedure TFrm_COM40.FormDestroy(Sender: TObject);
begin
Frm_COM40 := nil;
end;
procedure TFrm_COM40.FormShow(Sender: TObject);
begin
fSetFont(Frm_COM40, GS_FONTNAME);
fSetSkin(Frm_COM40);
end;
procedure TFrm_COM40.Proc_Init;
var
i: integer;
begin
for i := 0 to cxgCustMlg.ColumnCount - 1 do
cxgCustMlg.Columns[i].DataBinding.ValueType := 'String';
cxgCustMlg.Columns[2].DataBinding.ValueType := 'Currency';
cxgCustMlg.Columns[3].DataBinding.ValueType := 'Currency';
cxgCustMlg.Columns[4].DataBinding.ValueType := 'Currency';
cxgCustMlg.DataController.SetRecordCount(0);
CB_Gubun.ItemIndex := 0;
curTotal.Caption := '0';
curCurrent.Caption := '0';
curCoupon.Caption := '0';
curPrzCnt.Caption := '0';
curEventCnt.Caption := '0';
clbCuSeq.Caption := '';
cbbCuProduct.Clear; // 지급상품명
cbbCuProduct.Properties.Items.Text := _PROD_BASE;
curOutMileMny.Enabled := True;
curOutMileMny.Value := 0; // 지급마일리지
cxCurMileRefresh.Value := 0; // 마일리지 충전금액.
edtAddMileMemo.Text := '';
end;
procedure TFrm_COM40.pnlTitleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
ReleaseCapture;
PostMessage(Self.Handle, WM_SYSCOMMAND, $F012, 0);
end;
procedure TFrm_COM40.proc_search;
var
XmlData, Param, ErrMsg, sTemp : string;
xdom: msDomDocument;
lst_Count, lst_Result: IXMLDomNodeList;
ls_Rcrd, slList : TStringList;
I, ErrCode, icnt, j, iRow : Integer;
begin
Param := clbCuSeq.Caption;
Param := Param + '│' + IntToStr(CB_Gubun.ItemIndex);
try
Screen.Cursor := crHourGlass;
slList := TStringList.Create;
try
if not RequestBasePaging(GetSel05('LISTCUSTMILEAGE', 'MNG_CUST.LIST_CUST_MILEAGE', '1000', Param), slList, ErrCode, ErrMsg) then
begin
GMessagebox(Format('조회 중 오류발생'#13#10'[%d]%s', [ErrCode, ErrMsg]), CDMSE);
Screen.Cursor := crDefault;
FreeAndNil(slList);
Exit;
end;
xdom := ComsDomDocument.Create;
try
iCnt := 1;
Frm_Flash.cxPBar1.Properties.Max := slList.Count;
Frm_Flash.cxPBar1.Position := 0;
cxgCustMlg.DataController.SetRecordCount(0);
cxgCustMlg.BeginUpdate;
for j := 0 to slList.Count - 1 do
begin
Frm_Flash.cxPBar1.Position := j + 1;
Frm_Flash.lblCnt.Caption := IntToStr(j + 1) + '/' + IntToStr(slList.Count);
Application.ProcessMessages;
xmlData := slList.Strings[j];
xdom.loadXML(XmlData);
lst_Count := xdom.documentElement.selectNodes('/cdms/Service/Data');
if StrToIntDef(lst_Count.item[0].attributes.getNamedItem('Count').Text,0) > 0 then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
for i := 0 to lst_Result.length - 1 do
begin
GetTextSeperationEx('│', lst_Result.item[i].attributes.getNamedItem('Value').Text, ls_Rcrd);
if i = 0 then
begin
if ls_Rcrd[0] = '' then ls_Rcrd[0] := '0';
if ls_Rcrd[3] = '' then ls_Rcrd[3] := '0';
if ls_Rcrd[4] = '' then ls_Rcrd[4] := '0';
if ls_Rcrd[5] = '' then ls_Rcrd[5] := '0';
curTotal .Caption := FormatFloat('#,', StrToFloatDef(ls_Rcrd[0], 0));
curCurrent .Caption := FormatFloat('#,', StrToFloatDef(ls_Rcrd[3], 0));
curCoupon .Caption := FormatFloat('#,', StrToFloatDef(ls_Rcrd[4], 0));
curEventCnt.Caption := FormatFloat('#,', StrToFloatDef(ls_Rcrd[5], 0));
end else
begin
iRow := cxgCustMlg.DataController.AppendRecord;
ls_Rcrd.Insert(0, IntToStr(i));
if ls_Rcrd[2] = '' then ls_Rcrd[2] := '0';
if ls_Rcrd[3] = '' then ls_Rcrd[3] := '0';
if ls_Rcrd[4] = '' then ls_Rcrd[4] := '0';
sTemp := ls_Rcrd[1];
sTemp := copy(sTemp, 1, 4) + '-' + copy(sTemp, 5, 2) + '-' + copy(sTemp, 7, 2)
+ ' ' + copy(sTemp, 9, 2) + ':' + copy(sTemp, 11, 2) + ':' + copy(sTemp, 13, 2);
cxgCustMlg.DataController.Values[iRow, 0] := ls_Rcrd[0];
cxgCustMlg.DataController.Values[iRow, 1] := sTemp;
cxgCustMlg.DataController.Values[iRow, 2] := ls_Rcrd[2];
cxgCustMlg.DataController.Values[iRow, 3] := ls_Rcrd[3];
cxgCustMlg.DataController.Values[iRow, 4] := ls_Rcrd[4];
cxgCustMlg.DataController.Values[iRow, 5] := ls_Rcrd[5];
cxgCustMlg.DataController.Values[iRow, 6] := ls_Rcrd[7];
cxgCustMlg.DataController.Values[iRow, 7] := ls_Rcrd[6];
end;
end;
finally
ls_Rcrd.Free;
end;
end;
end;
finally
cxgCustMlg.EndUpdate;
xdom := Nil;
end;
finally
Frm_Flash.hide;
Screen.Cursor := crDefault;
FreeAndNil(slList);
end;
except
on E: Exception do
begin
FreeAndNil(slList);
Screen.Cursor := crDefault;
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_COM40.rbEventMClick(Sender: TObject);
begin
cxEventCntPropertiesChange(cxEventCnt);
end;
// 고객 마일리지를 충전 처리 한다.
procedure TFrm_COM40.Proc_CustMileRefresh;
var
Param, XmlData, ErrMsg : string;
sMileMny, sMileMemo, locHdNo, locBrNo : string;
ErrCode, CurMlg : Integer;
begin
try
if TCK_USER_PER.COM_CustMlgCharge <> '1' then
begin
GMessagebox('고객에게 지급 권한이 없습니다.', CDMSE);
exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].lcsCu_seq = '' then
begin
ShowMessage('고객 일련번호가 없습니다. 고객정보를 조회 한 다음 [지급] 하세요!');
Exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].cxtCallTelNum.Text = '' then
begin
ShowMessage('고객 전화번호가 없습니다. 고객정보를 조회 한 다음 [지급] 하세요!');
Exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].cxtCallTelNum.Text <> Frm_Main.Frm_JON01N[Self.Tag].gsCuTelHint then
begin
ShowMessage('마일리지 지급할 고객 전화번호가 조회한 전화번호와 다릅니다. 고객정보를 재조회 한 다음 [지급] 처리 하세요!');
Exit;
end;
if cxCurMileRefresh.Value < 1 then
begin
ShowMessage('충전 할 마일리지 금액을 입력 하세요!');
cxCurMileRefresh.SetFocus;
Exit;
end;
sMileMny := ReplaceAll(cxCurMileRefresh.Text, ',', '');
// 보정/지급/선물시 수정일경우 메모에 접수번호 표시
if (Pos('수정', Frm_Main.Frm_JON01N[Self.Tag].Caption) > 0 ) then
sMileMemo := edtAddMileMemo.Text + '/' + Frm_Main.Frm_JON01N[Self.Tag].cxtJoinNum.Text
else
sMileMemo := edtAddMileMemo.Text;
locHdNo := Frm_Main.Frm_JON01N[Self.Tag].Proc_HDNOSearch; // 본사코드 정보를 읽는다.
locBrNo := Frm_Main.Frm_JON01N[Self.Tag].Proc_BRNOSearch; // 지사코드 정보를 읽는다.
Param := En_Coding(Frm_Main.Frm_JON01N[Self.Tag].lcsCu_seq);
Param := Param + '│' + En_Coding(Frm_Main.Frm_JON01N[Self.Tag].cxtCuTel.Text);
Param := Param + '│' + locHdNo;
Param := Param + '│' + locBrNo;
Param := Param + '│' + En_Coding(sMileMemo);
Param := Param + '│' + En_Coding(sMileMny);
Param := Param + '│1│0'; // 0.차감,1.충전 || 0.마일리지,1.이벤트횟수
Param := Param + '│사용자 직접 수정';
if not RequestBase(GetCallable05('SET_CUST_MILEAGE', 'MNG_CUST.SET_CUST_MILEAGE', Param), XmlData, ErrCode, ErrMsg) then
begin
GMessageBox(Format('[%d] %s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
cxCurMileRefresh.Value := 0;
edtAddMileMemo.Clear;
cxBtnTelNESelect.Click;
ShowMessage('충전 완료 되었습니다.');
CurMlg := StrToIntDef(ReplaceAll(curCurrent.Caption, ',', ''), 0);
curCurrent.Caption := FormatFloat('#,##0', CurMlg + cxCurMileRefresh.Value);
Frm_Main.Frm_JON01N[Self.Tag].lblCuMile.Caption := curCurrent.Caption;
Frm_Main.Frm_JON01N[Self.Tag].SetMileColorChange;
except
on e: exception do
begin
Frm_Main.Frm_JON01N[Self.Tag].Enabled := True;
Screen.Cursor := crDefault;
Assert(False, E.Message);
end;
end;
end;
// 고객 마일리지를 즉시차감 처리 한다.
procedure TFrm_COM40.Proc_CustMileDeduct;
var
Param : string;
locHdNo, locBrNo, sMileMny: string;
XmlData, ErrMsg: string;
ErrCode: integer;
CurMlg, PrizeCnt, PrizeMlg: Integer;
begin
try
if TCK_USER_PER.COM_CustMlgCharge <> '1' then
begin
GMessagebox('고객에게 지급 권한이 없습니다.', CDMSE);
exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].lcsCu_seq = '' then
begin
ShowMessage('고객 일련번호가 없습니다. 고객정보를 조회 한 다음 [지급] 하세요!');
Exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].cxtCallTelNum.Text = '' then
begin
ShowMessage('고객 전화번호가 없습니다. 고객정보를 조회 한 다음 [지급] 하세요!');
Exit;
end;
if Frm_Main.Frm_JON01N[Self.Tag].cxtCallTelNum.Text <> Frm_Main.Frm_JON01N[Self.Tag].cxtCuTel.Text then
begin
ShowMessage('마일리지 지급 할 고객 전화번호가 조회한 전화번호와 다릅니다. 고객정보를 재조회 한 다음 [지급] 처리 하세요!');
Exit;
end;
if curOutMileMny.Value < 1 then
begin
ShowMessage('지급 할 마일리지 금액을 입력 하세요!');
curOutMileMny.SetFocus;
Exit;
end;
sMileMny := FloatToStr(curOutMileMny.Value);
locHdNo := Frm_Main.Frm_JON01N[Self.Tag].Proc_HDNOSearch; // 본사코드 정보를 읽는다.
locBrNo := Frm_Main.Frm_JON01N[Self.Tag].Proc_BRNOSearch; // 지사코드 정보를 읽는다.
Param := En_Coding(Frm_Main.Frm_JON01N[Self.Tag].lcsCu_seq);
Param := Param + '│' + En_Coding(Frm_Main.Frm_JON01N[Self.Tag].cxtCuTel.Text);
Param := Param + '│' + locHdNo;
Param := Param + '│' + locBrNo;
// 보정/지급/선물시 수정일경우 메모에 접수번호 자동저장
if (Pos('수정', Frm_Main.Frm_JON01N[Self.Tag].Caption) > 0 ) then
Param := Param + '│' + En_Coding(edtMileMemo.Text) + '/' + En_Coding(Frm_Main.Frm_JON01N[Self.Tag].cxtJoinNum.Text)
else
Param := Param + '│' + En_Coding(edtMileMemo.Text);
Param := Param + '│' + En_Coding(sMileMny);
Param := Param + '│0│0'; // 0.차감,1.충전 || 0.마일리지,1.이벤트횟수
Param := Param + '│' + En_Coding(cbbCuProduct.Text);
if not RequestBase(GetCallable05('SET_CUST_MILEAGE', 'MNG_CUST.SET_CUST_MILEAGE', Param), XmlData, ErrCode, ErrMsg) then
begin
GMessageBox(Format('[%d] %s', [ErrCode, ErrMsg]), CDMSE);
Exit;
end;
prizeMlg := StrToIntDef(ReplaceAll(curCurrent.Caption, ',', ''), 0);
CurMlg := prizeMlg - StrToIntDef(ReplaceAll(curOutMileMny.Text, ',', ''), 0);
PrizeCnt := StrToIntDef(curPrzCnt.Caption, 0) + 1;
Frm_Main.Frm_JON01N[Self.Tag].lblCuMile.Caption := FormatFloat('#,##0', CurMlg);
Frm_Main.Frm_JON01N[Self.Tag].lblCuMileCnt.Caption := IntToStr(PrizeCnt);
Frm_Main.Frm_JON01N[Self.Tag].SetMileColorChange;
curOutMileMny.Value := 0;
edtMileMemo.Clear;
cxBtnTelNESelect.Click;
ShowMessage('상품이 지급 되었습니다.');
except
on e: exception do
begin
Assert(False, E.Message);
end;
end;
end;
procedure TFrm_COM40.RequestMobileCoupone(ACuSeq, AHP: string;
ACharge: Integer);
var
TxStr: string;
begin
TxStr := GTx_UnitXmlLoad('C067N1.xml');
TxStr := StringReplace(TxStr, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]);
TxStr := StringReplace(TxStr, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
TxStr := StringReplace(TxStr, 'ClientKeyString', 'MobileCpn', [rfReplaceAll]);
TxStr := StringReplace(TxStr, 'CuSeqStr', ACuSeq, [rfReplaceAll]);
TxStr := StringReplace(TxStr, 'HPStr', AHP, [rfReplaceAll]);
TxStr := StringReplace(TxStr, 'ChargeStr', IntToStr(ACharge), [rfReplaceAll]);
RequestData(TxStr);
end;
procedure TFrm_COM40.RequestData(AData: string);
var
ReceiveStr: string;
StrList: TStringList;
ErrCode: integer;
begin
StrList := TStringList.Create;
Screen.Cursor := crHandPoint;
try
if dm.SendSock(AData, StrList, ErrCode, False) then
begin
ReceiveStr := StrList[0];
if trim(ReceiveStr) <> '' then
begin
Application.ProcessMessages;
ResponseData(ReceiveStr);
end;
end;
finally
Frm_Flash.Hide;
Screen.Cursor := crDefault;
StrList.Free
end;
end;
procedure TFrm_COM40.ResponseData(AXmlData: string);
var
xdom: msDomDocument;
ErrorCode, ClientKey: string;
CurMlg, PrizeCnt, PrizeMlg: Integer;
begin
xdom := ComsDomDocument.Create;
Screen.Cursor := crHourGlass;
try
try
if not xdom.loadXML(AXmlData) then Exit;
ErrorCode := GetXmlErrorCode(AXmlData);
if ('0000' = ErrorCode) then
begin
ClientKey := GetXmlClientKey(AXmlData);
if ClientKey = 'MobileCpn' then
begin
prizeMlg := StrToIntDef(ReplaceAll(curCurrent.Caption, ',', ''), 0);
CurMlg := prizeMlg - StrToIntDef(ReplaceAll(curOutMileMny.Text, ',', ''), 0);
PrizeCnt := StrToIntDef(curPrzCnt.Caption, 0) + 1;
curCurrent.Caption := FormatFloat('#,##0', CurMlg);
Frm_Main.Frm_JON01N[Self.Tag].lblCuMile.Caption := curCurrent.Caption;
curPrzCnt.Caption := FormatFloat('#,##0', PrizeCnt);
Frm_Main.Frm_JON01N[Self.Tag].lblCuMileCnt.Caption := IntToStr(PrizeCnt);
Frm_Main.Frm_JON01N[Self.Tag].SetMileColorChange;
GrpSetCoupon.Visible := False;;
GMessagebox('주유할인권을 전송했습니다.', CDMSI);
end;
end else
begin
GMessagebox(MSG012 + CRLF + ErrorCode, CDMSE);
end;
except
end;
finally
Screen.Cursor := crDefault;
xdom := Nil;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.