text stringlengths 14 6.51M |
|---|
program Inmobiliaria;
uses crt, inmuebles;
const COMIENZO_ARRAY = 1;
MAX_SUCURSALES= 255;
MAX_INMUEBLES = 100;
MAT_ESTADISTICA_FILAS = 13;
MAT_ESTADISTICA_COLUMNAS = MAX_SUCURSALES + 1;
LISTARMAX = 20;
VALOR_NO_ENCONTRADO = -1;
PATH_INMUEBLES = 'Inmuebles.dat';
PATH_SUCURSALES = 'sucursales.dat';
FORMATO_CARACTERES_COLUMNA = 15;
POSLOGICA_CORRIMIENTO_SUCURSALES = 1;
MAX_PRECIO_DEPTO = 9999999999;
NONE = 0;
PROCEDENCIA_PRINCIPAL = 'ppal';
PROCEDENCIA_PROCEDIMIENTO = 'proc';
PROCEDENCIA_CANTAMBIENTES = 'cAmb';
PROCEDENCIA_BARRIOS = 'barr';
type
tcodInm = string[5];
tposLogica = longint;
tcodSucursal = integer;
tprocedencia = string[4];
tnomBarrio = string[20];
tstrFecha = string[10];
tstrAnio = string[4];
tstrMes = string [2];
trInmueble = record
codigo : tcodInm;
estado : string[10];
calle : string[20];
altura : word;
ambientes : byte;
descripcion : string[255];
barrio : tnomBarrio;
precio : real;
sucursal : byte;
fechaVenta : tstrFecha;
borrado : boolean;
end;
tNovedad = record
codigo: tcodInm;
tipo_novedad: string[15];
estado: string[10];
calle: string[20];
altura: word;
ambientes: byte;
descripcion: string;
barrio: string[20];
precio: real;
sucursal: byte;
fecha: string[8];
end;
trSucursal = record
codigo : tcodSucursal;
nombre : string[20];
direccion: string[30];
telefono: string[15];
end;
trIndice = record
posLogica: tposLogica;
codigo: tcodInm;
end;
trBuscar = record
codigo : tcodInm;
posLogica : tposLogica;
precio : real;
ambientes : byte;
end;
trBarrio = record
nombre : tnomBarrio;
cantInmuebles : byte;
end;
tarInmuebles = file of trInmueble;
tarNovedades = file of tNovedad;
tarSucursales= file of trSucursal;
tvIndice = array [COMIENZO_ARRAY..MAX_INMUEBLES] of trIndice;
tvBuscar = array [COMIENZO_ARRAY..MAX_INMUEBLES] of trBuscar;
tvBarrios = array [COMIENZO_ARRAY..MAX_INMUEBLES] of trBarrio;
tMatrizEstadistica = array[COMIENZO_ARRAY..MAT_ESTADISTICA_FILAS, COMIENZO_ARRAY..MAT_ESTADISTICA_COLUMNAS] of real;
tvFilasMatrizEstadisticas = array [COMIENZO_ARRAY..MAT_ESTADISTICA_FILAS] of string;
(* mostrarMenu
Autor: Pedro *)
procedure mostrarMenu;
begin
writeln ('Menu principal');
writeln ('Elija una opcion');
writeln; //Espacio para prolijidad
writeln ('1: Listar inmuebles');
writeln ('2: Importar novedades');
writeln ('3: Buscar departamentos');
writeln ('4: Buscar por barrio');
writeln ('5: Calcular estadisticas anuales');
writeln ('6: Salir');
writeln; //Espacio para prolijidad
end;
//Autor: Pedro
procedure menuBusqueda;
begin
writeln('Buscar por:');
writeln; //Espacio para prolijidad
writeln('1: Precio');
writeln('2: Cantidad de ambientes');
writeln('3: Precio y cantidad de ambientes');
writeln('4: Volver');
writeln; //Espacio para prolijidad
end;
(* generarIndice
Autor: Martín
PRE: Archivo "inmuebles" existente y abierto, vector índice vacío, maxLogico = 0
POST: Índice cargado, maxLogico = cantidad de elementos cargados al índice *)
procedure generarIndice(var archInmuebles: tarInmuebles; var vIndice: tvIndice; var maxLogico: tposLogica);
var regInmueble : trInmueble;
begin
maxLogico := 0;
reset(archInmuebles); //Vuelve a posicion 0
while not eof(archInmuebles) and (maxLogico <= MAX_INMUEBLES) do
begin
inc(maxLogico);
vIndice[maxLogico].posLogica := filepos(archInmuebles);
read(archInmuebles, regInmueble);
vIndice[maxLogico].codigo := regInmueble.codigo;
end;
end;
// Autor: Martin
// PRE: Recibe dos registros de tipo trIndice pasados por referencia
// POST: Intercambia los registros entre las dos variables
procedure intercambio(var regActual, regSiguiente : trIndice);
var auxiliar : trIndice;
begin
auxiliar := regSiguiente;
regSiguiente := regActual;
regActual := auxiliar;
end;
// Autor: Martin
// PRE: Recibe un vector indice cargado y un maxLogico para usar de limite
// POST: Devuelve el vector indice ordenado utilizando un algoritmo de burbujeo optimizado
procedure ordenarIndice(var vIndice: tvIndice; maxLogico: tposLogica);
var i, j: tposLogica;
ordenado: boolean;
begin
i := 1; ordenado := false;
while (i < maxLogico) and not(ordenado) do
begin
ordenado := true;
for j := 1 to (maxLogico - i) do
begin
if vIndice[j].codigo > vIndice[j + 1].codigo then
begin
ordenado := false;
intercambio(vIndice[j], vIndice[j + 1]);
end;
end;
inc(i);
end;
end;
// Autor: Martin
// PRE: Recibe un archivo de inmuebles existente, un vector que representa el indice vacío y un maxLogico en 0
// POST: Devuelve el indice cargado Y ordenado y el maxLogico con la cantidad de elementos cargados al indice
procedure cargarIndice(var archInmuebles: tarInmuebles; var vIndice: tvIndice; var maxLogico: tposLogica);
begin
generarIndice(archInmuebles, vIndice, maxLogico);
ordenarIndice(vIndice, maxLogico);
end;
// Autor: Martin
// PRE: Recibe un codigo a buscar, un indice cargado y ordenado y un fin, generalmente el maximo logico
// POST: Devuelve la posicion logica del codigo buscado en el archivo de inmuebles
function obtenerPosLogica(codigo: tcodInm; var tIndice: tvIndice; fin: tposLogica) : tposLogica;
var ini, med : tposLogica;
encontrado : boolean;
begin
ini := COMIENZO_ARRAY;
encontrado := false;
while not(encontrado) and (ini <= fin) do
begin
med := (fin + ini) div 2;
if codigo > tIndice[med].codigo then
ini := med + 1
else if codigo < tIndice[med].codigo then
fin := med - 1
else
encontrado := true;
end;
if encontrado then
obtenerPosLogica := tIndice[med].posLogica
else
obtenerPosLogica := VALOR_NO_ENCONTRADO;
end;
// PRE: Recibe una opcion con un numero a validar que representa una opción del menu
// POST: Devuelve la misma variable pero con un numero entre "minposible" y "maxposible"
procedure validarOpcion (var opcion: byte; minposible : byte; maxposible : byte; procedencia : tprocedencia);
begin
repeat
case procedencia of {Elige cual menu mostrar}
PROCEDENCIA_PRINCIPAL : begin
clrscr;
mostrarMenu;
end;
PROCEDENCIA_PROCEDIMIENTO : begin
clrscr;
menuBusqueda;
end;
PROCEDENCIA_CANTAMBIENTES : writeln ('Ingrese la cantidad de ambientes:');
PROCEDENCIA_BARRIOS : begin
end;
end;
{$I-}
readln (opcion);
{$I+}
until ((IOResult = 0) and (opcion >= minposible) and (opcion <=maxposible));
end;
//Autor: Martin
//PRE: Recibe el registro inmueble y el registro sucursal.
//POST: Muestra la informacion de los inmuebles.
procedure mostrarDatosParaListado(var regInmueble : trInmueble; var regSucursal : trSucursal);
begin
writeln ('Codigo: ', regInmueble.codigo,
', Estado: ', regInmueble.estado,
', Calle: ', regInmueble.calle,
', Altura: ' , regInmueble.altura,
', Barrio: ', regInmueble.barrio,
', Precio: ', regInmueble.precio : 0 : 2,
', Ambientes: ', regInmueble.ambientes,
', Descripcion: ', regInmueble.descripcion,
', Fecha de venta: ', regInmueble.fechaVenta,
', Codigo Sucursal: ', regInmueble.sucursal,
', Nombre Sucursal: ', regSucursal.nombre,
', Direccion Sucursal: ', regSucursal.direccion,
', Telefono Sucursal: ', regSucursal.telefono);
writeln; //Espacio para prolijidad
end;
// Autor: Facundo
// PRE: Recibe un archivo de inmuebles abierto
// POST: Muestra los inmuebles dentro de un archivo
procedure listarInmuebles(var archInmuebles : tarInmuebles; var archSucursales : tarSucursales; var vIndice : tvIndice ; var maxLogico : tposLogica);
var
regInmueble : trInmueble;
regSucursal : trSucursal;
cantPorPag : longint;
posIndice : tposLogica;
begin
posIndice := 1;
while (posIndice <= maxLogico) do
begin
cantPorPag:=1;
while (cantPorPag<=4) and (posIndice <= maxLogico) do
begin
// Leemos el inmueble
seek(archInmuebles, vIndice[posIndice].posLogica);
read(archInmuebles, regInmueble);
// Obtenemos la sucursal asociada al inmueble
seek(archSucursales, (regInmueble.sucursal - POSLOGICA_CORRIMIENTO_SUCURSALES));
read(archSucursales, regSucursal);
if not regInmueble.borrado then
begin
mostrarDatosParaListado(regInmueble, regSucursal);
inc(cantPorPag);
end;
inc(posIndice);
end;
writeln; //Espacio para prolijidad
writeln ('Presione enter para pasar a la siguiente pagina.');
writeln; //Espacio para prolijidad
readln;
end;
writeln ('Fin de lista. Presione enter para continuar.');
readln;
end;
//Autor: Martin
// PRE: Recibe un vector de barrios, el maximo logico relacionado a este, y un nombre de barrio a buscar en el vector
// POST: Ejecuta una busqueda bruta y devuelve el indice del vector en donde se encuentra el barrio o la constante VALOR_NO_ENCONTRADO (-1) si no
function buscarBarrioEnVectorBarrios(var vBarrios : tvBarrios; maxLogicoBarrios : integer; busqueda : tnomBarrio) : integer;
var posicion : integer;
encontrado : boolean;
begin
encontrado := false;
posicion := 0;
// Busqueda bruta: no valía la pena mantener un vector ordenado
while (posicion <= maxLogicoBarrios) and not encontrado do
begin
inc(posicion);
if vBarrios[posicion].nombre = busqueda then
encontrado := true;
end;
if encontrado then
buscarBarrioEnVectorBarrios := posicion
else
buscarBarrioEnVectorBarrios := VALOR_NO_ENCONTRADO;
end;
// Autor: Martin
// PRE: Recibe un vector de barrios vacio, una variable a usar como maximo logico y un archivo de inmuebles de donde leer los datos
// POST: Carga el vector con los barrios encontrados y la cantidad de inmuebles correspondientes a cada uno.
// El maximo logico queda con la cantidad de barrios. Es UN registro por barrio
procedure cargarVectorBarrios(var vBarrios : tvBarrios; var maxLogicoBarrios : integer; var archInmuebles : tarInmuebles);
var regInmueble : trInmueble;
posicionBarrio : integer;
begin
maxLogicoBarrios := 0;
reset(archInmuebles);
while not eof(archInmuebles) do
begin
read(archInmuebles, regInmueble);
if not(regInmueble.borrado) then
begin
posicionBarrio := buscarBarrioEnVectorBarrios(vBarrios, maxLogicoBarrios, regInmueble.barrio);
if (posicionBarrio = VALOR_NO_ENCONTRADO) then
begin
inc(maxLogicoBarrios);
vBarrios[maxLogicoBarrios].nombre := regInmueble.barrio;
vBarrios[maxLogicoBarrios].cantInmuebles := 1;
end
else
begin
inc(vBarrios[posicionBarrio].cantInmuebles);
end;
end;
end;
end;
// Autor: Martin
// PRE: Recibe el archivo de novedades, puede existir o no
// POST: Devuelve true si el archivo existe, false si no
function archNovedadesExiste(var arch : tarNovedades) : boolean;
begin
{$I-}
reset(arch);
{$I+}
if IOResult = 0 then
begin
close(arch);
archNovedadesExiste := true;
end
else
archNovedadesExiste := false;
end;
// Autor: Martin
// PRE: recibe por referencia un archivo de novedades sin asignar
// POST: devuelve el archivo de novedades asignado
procedure solicitarArchivo(var archNovedades : tarNovedades);
var path : string;
begin
repeat
writeln('Ingrese la ruta del archivo de novedades.');
{$I-}
readln(path);
{$I+}
assign(archNovedades, path);
until (path <> '') and (archNovedadesExiste(archNovedades));
end;
// Autor: Martin
// PRE: Recibe el indice, el maximo logico y los datos del nuevo registro a insertar
// POST: Inserta el nuevo registro en el indice de manera que este permanezca ordenado
procedure insertarEnIndice(var vIndice : tvIndice; var maxLogico : tposLogica; nuevaPosicionLogica : tposLogica; nuevoCodigo : tcodInm);
var posActual : tposLogica;
j : tposLogica;
begin
posActual := 1;
{ Buscamos la posicion en donde ubicar el nuevo registro (el indice está ordenado ascendientemente) }
while (posActual <= maxLogico) and (nuevoCodigo > vIndice[posActual].codigo) do
inc(posActual);
{ Si al buscar la posicion no nos pasamos ejecutamos un arrastre para mover todos los elementos desde el final una posicion
adelante, dejando la posicion del nuevo registro libre para ser insertada. }
if posActual < MAX_INMUEBLES then
begin
for j := maxLogico downto posActual do
vIndice[j + 1] := vIndice[j];
vIndice[posActual].codigo := nuevoCodigo;
vIndice[posActual].posLogica := nuevaPosicionLogica;
if maxLogico < MAX_INMUEBLES then inc(maxLogico); { Si no llegamos al limite de inmuebles incrementamos el maximo logico}
end;
end;
// Autor: Anibal
// PRE: Recibe una novedad, un archivo de inmuebles abierto, un indice y un maximo logico
// POST: Si el inmueble asociado a la novedad existe, se modifican los campos no vacios
procedure altaNovedad(var novedad : tNovedad; var archInmuebles : tarInmuebles; var vIndice : tvIndice; var maxLogico : tposLogica);
var posLogica, ultimaPosicion : tposLogica;
rNuevoInmueble : trInmueble;
begin
posLogica := obtenerPosLogica(novedad.codigo, vIndice, maxLogico);
if posLogica = VALOR_NO_ENCONTRADO then
begin
rNuevoInmueble.codigo := novedad.codigo;
rNuevoInmueble.estado := novedad.estado;
rNuevoInmueble.calle := novedad.calle;
rNuevoInmueble.altura := novedad.altura;
rNuevoInmueble.ambientes := novedad.ambientes;
rNuevoInmueble.descripcion := novedad.descripcion;
rNuevoInmueble.barrio := novedad.barrio;
rNuevoInmueble.precio := novedad.precio;
rNuevoInmueble.sucursal := novedad.sucursal;
rNuevoInmueble.fechaVenta := novedad.fecha;
rNuevoInmueble.borrado := False;
ultimaPosicion := filesize(archInmuebles);
seek(archInmuebles, ultimaPosicion);
write(archInmuebles, rNuevoInmueble);
insertarEnIndice(vIndice, maxLogico, ultimaPosicion, rNuevoInmueble.codigo);
writeln('Codigo ', novedad.codigo, ' dado de alta con exito.');
end
else
writeln('El codigo ', novedad.codigo, ' ya se encuentra en el archivo');
end;
// Autor: Anibal
// PRE: Recibe una novedad, un archivo de inmuebles abierto, un indice y un maximo logico
// POST: Si existe, marca el inmueble asociado a la novedad como borrado
procedure bajaNovedad(var novedad : tNovedad; var archInmuebles : tarInmuebles;
var vIndice: tvIndice; var maxLogico: tposLogica);
var
posLogica: tposLogica;
regInmueble : trInmueble;
begin
posLogica := obtenerPosLogica(novedad.codigo, vIndice, maxLogico);
if posLogica > VALOR_NO_ENCONTRADO then
begin
seek(archInmuebles, posLogica);
read(archInmuebles, regInmueble);
regInmueble.borrado:= True;
seek(archInmuebles, posLogica);
write(archInmuebles, regInmueble);
writeln('Codigo ', novedad.codigo, ' dado de baja con exito.');
end
else
writeln('El codigo ', novedad.codigo ,' no se encuentra en el archivo');
end;
// Autor: Anibal
// PRE: Recibe una novedad, un archivo de inmuebles abierto, el indice y su maximo logico asociado
// POST: Efectua las modificaciones sobre el inmueble con el mismo codigo que la novedad. De no existir se avisa al usuario
procedure modificacionNovedad(var novedad : tNovedad; var archInmuebles : tarInmuebles; var vIndice: tvIndice; var maxLogico: tposLogica);
var regInmueble : trInmueble;
posLogica : tposLogica;
begin
posLogica := obtenerPosLogica(novedad.codigo, vIndice, maxLogico);
if posLogica > VALOR_NO_ENCONTRADO then
begin
seek(archInmuebles, posLogica);
read(archInmuebles, regInmueble);
if(novedad.estado <> '') then
regInmueble.estado:=novedad.estado;
if(novedad.calle <> '') then
regInmueble.calle:=novedad.calle;
if(novedad.altura <> 0) then
regInmueble.altura:=novedad.altura;
if(novedad.ambientes <> 0)then
regInmueble.ambientes:=novedad.ambientes;
if(novedad.descripcion <> '')then
regInmueble.descripcion:=novedad.descripcion;
if(novedad.barrio <> '')then
regInmueble.barrio:=novedad.barrio;
if(novedad.precio <> 0)then
regInmueble.precio:=novedad.precio;
if(novedad.sucursal <> 0)then
regInmueble.sucursal:=novedad.sucursal;
if(novedad.Fecha <> '') then
regInmueble.fechaVenta:=novedad.Fecha;
seek(archInmuebles, posLogica);
write(archInmuebles, regInmueble);
writeln('El codigo ', novedad.codigo, ' fue modificado');
end
else
writeln('El codigo ', novedad.codigo,' no se encuentra en el archivo.');
end;
// Autor: Martin y Anibal
// PRE: Recibe un archivo de inmuebles asignado pero no abierto, el indice y el maxLogico asociado al indice
// POST: Procesa el archivo de novedades, dando de alta, baja o modificando los inmuebles dependiendo del tipo de novedad
procedure importarNovedades(var archInmuebles: tarInmuebles; var vIndice: tvIndice; var maxLogico: tposLogica; var vBarrios : tvBarrios; var maxLogicoBarrios : integer);
var archNovedades : tarNovedades;
novedad : tNovedad;
begin
clrscr; // Limpia pantalla
writeln('Importar Novedades');
writeln; //Epacio para prolijidad
solicitarArchivo(archNovedades);
reset(archNovedades); //Vuelve a posición 0
reset(archInmuebles); //Vuelve a posición 0
while not eof(archNovedades) do
begin
read(archNovedades, novedad);
writeln('Procesando codigo ', novedad.codigo, ' (', novedad.tipo_novedad, ')');
case novedad.tipo_novedad of
'Alta': altaNovedad(novedad, archInmuebles, vIndice, maxLogico);
'Baja': bajaNovedad(novedad, archInmuebles, vIndice, maxLogico);
'Modificacion', 'Modificación':
modificacionNovedad(novedad, archInmuebles, vIndice, maxLogico);
end;
writeln(); //espacio para prolijidad
end;
close(archNovedades);
cargarVectorBarrios(vBarrios, maxLogicoBarrios, archInmuebles);
writeln('Presione cualquier tecla para volver al menu.');
readln();
end;
//Autor: Matias
//PRE:
//POST: Muestra los inmuebles por precio.
procedure listarVectorPorPrecio(var vectorBuscar: tvBuscar; var archInmuebles : tarInmuebles; maxLogico : byte);
var pos: byte;
cantPorPag:byte;
reg: trInmueble;
begin
cantPorPag:=1;
pos:=1;
while (pos<=LISTARMAX) and (pos<=maxLogico) do
begin
writeln; //Espacio para prolijidad
while ((pos<=LISTARMAX) and (cantPorPag<=4) and (pos<=maxLogico)) do {cantPorPag<=4 para listar hasta 4 registros por vez}
begin
seek(archInmuebles, vectorBuscar[pos].posLogica);
read(archInmuebles, reg);
writeln('Codigo: ', reg.codigo, ', Estado: ', reg.estado, ', Calle: '
, reg.calle, ', Altura: ' , reg.altura, ', Ambientes: ', reg.ambientes,
', Descripcion: ', reg.descripcion, ', Barrio: ', reg.barrio, ', Precio: ',
reg.precio:0:2, ', Sucursal: ', reg.sucursal, ', Fecha de venta: ', reg.fechaVenta);
writeln;//Espacio para prolijidad
inc(cantPorPag);
inc(pos);
end;
cantPorPag:=1;
writeln; //Espacio para prolijidad
writeln('Pulse enter para continuar.');
readln();
end;
end;
//Autor: Matias
//PRE: Recibe el indice
//POST: Ordena por precio
procedure ordenarVectorPorPrecio (var vectorBuscar: tvBuscar; max : byte);
var pos:byte;
posmovil: byte;
aux: trBuscar;
ordenado: boolean;
begin
pos:=1;
posmovil:= COMIENZO_ARRAY;
ordenado:= false;
while ((posmovil<= max-1) and (not ordenado)) do
begin
ordenado:=true;
for pos := COMIENZO_ARRAY to (max-posmovil) do
if ((vectorBuscar[pos].precio) < (vectorBuscar[pos+1].precio)) then
begin
ordenado:= false;
aux := vectorBuscar[pos];
vectorBuscar[pos]:=vectorBuscar[pos+1];
vectorBuscar[pos+1]:=aux;
end;
posmovil:=posmovil+1;
end;
end;
// Autor: Martin
// PRE: recibe una variable "numero" por referencia que va a contener el valor ingresado, un mensaje para mostrar y un maximo
// y minimo entre los que estara el valor
// POST: la variable numero contiene un valor numerico entre el maximo y minimo
procedure solicitarNumeroReal(var numero : real; mensaje : string; min : real; max : real);
begin
repeat
writeln(mensaje);
{$I-}
readln(numero);
{$I+}
until (IOResult = 0) and (min <= numero) and (numero <= max);
end;
//Autor: Pedro
procedure asignarVectorBuscar (var vectorBuscar : tvBuscar; reg : trInmueble; max : byte; var archInmuebles : tarInmuebles);
begin
vectorBuscar[max].codigo := reg.codigo;
vectorBuscar[max].precio := reg.precio;
vectorBuscar[max].ambientes := reg.ambientes;
vectorBuscar[max].posLogica := filepos(archInmuebles) - 1;
end;
//Autor: Pedro
{Solicitado por EGB para evitar codigo duplicado}
procedure mostrarVectorPorPrecio (var vectorBuscar : tvBuscar; var archInmuebles : tarInmuebles; max : byte);
begin
ordenarVectorPorPrecio(vectorBuscar, max);
listarVectorPorPrecio(vectorBuscar, archInmuebles, max);
end;
//Autores: Pedro
//PRE: el usuario debe ingresar un valor de precio
//POST: verifica si es un valor valido, de lo contrario lo vuelve a pedir.
procedure validacionPrecios (var cantMayor, cantMenor : real);
begin
solicitarNumeroReal(cantMenor, 'Ingrese un valor de precio minimo:', 0, MAX_PRECIO_DEPTO);
writeln;
solicitarNumeroReal(cantMayor, 'Ingrese un valor de precio maximo que sea mayor al minimo:', cantMenor, MAX_PRECIO_DEPTO);
writeln; //Espacio para prolijidad
end;
//Autores: Matias y Pedro
//PRE: Recibe el indice
//POST: Busca los departamentos en el rango de precio ingresado por el usuario.
procedure buscarDepartamentoPorPrecio(var archInmuebles: tarInmuebles; var vectorBuscar : tvBuscar);
var
reg : trInmueble;
cantMayor : real;
cantMenor : real;
max : byte;
begin
validacionPrecios(cantMayor,cantMenor);
max:=0;
reset(archInmuebles); //Vuelve a posición 0
while not eof (archInmuebles) do
begin
read(archInmuebles,reg);
if ((cantMayor>=reg.precio) and (cantMenor<=reg.precio)) then
begin
inc(max);
asignarVectorBuscar(vectorBuscar, reg, max, archInmuebles);
end;
end;
mostrarVectorPorPrecio(vectorBuscar, archInmuebles, max);
writeln('Fin de lista. Enter para continuar');
readln; //Pausa
end;
//Autores: Matias y Pedro
//PRE: El usuario debe ingresar la cantidad de ambientes
//POST: Busca los inmuebles que tienen esa cantidad de ambientes.
procedure buscarDeptoPorAmbientes(var archInmuebles : tarInmuebles; var vectorBuscar : tvBuscar);
var
cantAmb : byte;
reg : trInmueble;
max : byte;
procede : tprocedencia;
begin
procede:= PROCEDENCIA_CANTAMBIENTES;
validarOpcion(cantAmb, 1, 4, procede);
max:= 0;
reset(archInmuebles);
while not eof(archInmuebles) do
begin
read (archInmuebles, reg);
if (cantAmb = reg.ambientes) then
begin
inc(max);
asignarVectorBuscar(vectorBuscar, reg, max, archInmuebles);
end;
end;
mostrarVectorPorPrecio(vectorBuscar, archInmuebles, max);
writeln('Fin de lista. Enter para continuar');
readln; //Pausa
end;
//Autor: Pedro
//PRE: El indice debe estar ordenado
//POST: vectorBuscar con inmuebles de "cantAmb" ambientes ordenado por precio, pantalla imprime primeros 20
procedure buscarCorteControl (var archInmuebles : tarInmuebles; var vectorBuscar : tvBuscar);
var
cantAmb : byte;
cantMayor, cantMenor : real;
reg : trInmueble;
max : byte;
procede : tprocedencia;
begin
procede:=PROCEDENCIA_CANTAMBIENTES;
validarOpcion(cantAmb, 1, 4, procede);
validacionPrecios(cantMayor, cantMenor);
max:=0;
reset(archInmuebles); //Vuelve a posicion 0
while not eof(archInmuebles) do
begin
read (archInmuebles, reg);
if ((reg.ambientes = cantAmb) and (reg.precio >= cantMenor) and (reg.precio <= cantMayor)) then
begin
inc(max);
asignarVectorBuscar(vectorBuscar, reg, max, archInmuebles);
end;
end;
mostrarVectorPorPrecio(vectorBuscar, archInmuebles, max);
end;
//Autor: Pedro
//PRE: vectorBuscar creado
//POST: vectorBuscar con valores nulos
procedure limpiarVectorBuscar(var vectorBuscar : tvBuscar);
var
pos : byte;
begin
for pos:= COMIENZO_ARRAY to LISTARMAX do
begin
vectorBuscar[pos].codigo := '00100';
vectorBuscar[pos].posLogica := NONE;
vectorBuscar[pos].precio := VALOR_NO_ENCONTRADO;
vectorBuscar[pos].ambientes := NONE;
end;
end;
//Autor: Pedro
//PRE:
//POST: Procedimiento por precio, por ambientes o por ambas
procedure buscarPorCategoria(var archInmuebles : tarInmuebles);
var
elegido: byte;
vectorBuscar : tvBuscar;
procede : tprocedencia;
begin
elegido := 0;
procede:=PROCEDENCIA_PROCEDIMIENTO;
while (elegido <> 4) do
begin
limpiarVectorBuscar(vectorBuscar);
validarOpcion(elegido, 1, 4, procede);
case elegido of
1: buscarDepartamentoPorPrecio(archInmuebles, vectorBuscar);
2: buscarDeptoPorAmbientes(archInmuebles, vectorBuscar);
3: buscarCorteControl(archInmuebles, vectorBuscar);
end;
end;
end;
// Autor: Martin
// PRE: Recibe un vector de barrios y su maximo asociado
// POST: Muestra los contenidos del vector en pantalla
procedure mostrarMenuBarrios(var vBarrios : tvBarrios; maxLogicoBarrios : integer);
var i : integer;
begin
clrscr;
writeln('Modulo Buscar Por Barrio');
writeln;
writeln('Seleccione un barrio.');
for i := 1 to maxLogicoBarrios do
writeln(' ', i, ') ',vBarrios[i].nombre, ' - (', vBarrios[i].cantInmuebles, ' inmuebles)');
end;
//Autor: Matias
//PRE: Recibe un barrio ingresado por el ususario y la cantidad de inmuebles en dicho barrio
//POST: Muestra la cantidad de inmuebles que hay en dicho barrio
procedure listarInmueblesPorBarrio(var archInmuebles : tarInmuebles; barrioBuscado : tnomBarrio; cantBusqueda : byte);
var
cantPorPag:byte;
cantInmueblesListados : byte;
regInmueble : trInmueble;
begin
cantPorPag := 1;
cantInmueblesListados := 0;
reset (archInmuebles);
while (cantInmueblesListados<> cantBusqueda) and not eof (archInmuebles) do
begin
read (archInmuebles, regInmueble);
cantPorPag:=1;
while ((cantInmueblesListados <> cantBusqueda) and (cantPorPag <= 4) and (regInmueble.barrio = barrioBuscado)) do {cantPorPag<=4 para listar hasta 4 registros por vez}
begin
writeln('Codigo: ', regInmueble.codigo,
', Estado: ', regInmueble.estado,
', Calle: ' , regInmueble.calle,
', Altura: ' , regInmueble.altura,
', Ambientes: ', regInmueble.ambientes,
', Descripcion: ', regInmueble.descripcion,
', Barrio: ', regInmueble.barrio,
', Precio: ',regInmueble.precio:0:2,
', Sucursal: ', regInmueble.sucursal,
', Fecha de venta: ', regInmueble.fechaVenta);
writeln;//Espacio para prolijidad
inc(cantPorPag);
inc(cantInmueblesListados);
if (cantInmueblesListados <> cantBusqueda) then
read (archInmuebles, regInmueble);
end;
if(cantPorPag =4) then
begin
writeln('Pulse enter para continuar.');
readln;
end;
end;
end;
//Autor: MAtias, Martin y Pedro
//PRE: recibe el archivo inmuebles asignado y abierto, un vector de barrios y un maxlogico asociado al vector de barrios
//POST: llama a los procedimientos necesarios para buscar y listar por barrios.
procedure buscarPorBarrio(var archInmuebles : tarInmuebles; var vBarrios: tvBarrios; maxLogicoBarrios: integer);
var
opcion : integer;
procede : tprocedencia;
max_Byte, opcionByte : byte;
begin
procede:=PROCEDENCIA_BARRIOS;
mostrarMenuBarrios(vBarrios, maxLogicoBarrios);
max_Byte:=maxLogicoBarrios;
opcionByte:=opcion;
validarOpcion(opcionByte, 1, max_Byte, procede);
opcion:=opcionByte;
listarInmueblesPorBarrio(archInmuebles, vBarrios[opcion].nombre, vBarrios[opcion].cantInmuebles);
writeln('Pulse enter para volver.');
readln();
end;
//Autor: MAtias y Facundo
//PRE: solicita al usuario que ingrese un anio
//POST: valida el numero controlando que sea menor a 3000
procedure solicitarAnio(var anio : tstrAnio);
begin
repeat
writeln('Ingrese un anio entre 1950 y 2050');
{$I-}
readln(anio);
{$I+}
until (IOResult = 0) and (anio <> '') and (anio > '1950') and (anio < '2050');
end;
// Autores: Facundo y Matias
//PRE: El usuario debe ingresar un anio en solicitarAnio
//POST: La matriz se carga con las estadisticas de los meses y de las sucursales correspondientes al anio ingresado
procedure cargarMatrizEstadisticas(var archInmuebles : tarInmuebles; anio : tstrAnio; var matEstadisticas : tMatrizEstadistica; maxColumnas : byte);
var
anioEsperado: tstrAnio;
mes: byte;
regInmueble : trInmueble;
errorCode : word;
begin
reset(archInmuebles);
while not eof(archInmuebles) do
begin
read(archInmuebles, regInmueble);
anioEsperado := copy (regInmueble.fechaVenta, 7, 4);
if (anio = anioEsperado) and not(regInmueble.borrado) then
begin
Val(copy(regInmueble.fechaVenta,4,2), mes, errorCode); //Tomamos el mes del string de Fecha (formato DD-MM-YYYY)
// Celda correspondiente
matEstadisticas[mes, regInmueble.sucursal] := matEstadisticas[mes, regInmueble.sucursal] + regInmueble.precio;
// Total por sucursal
matEstadisticas[13, regInmueble.sucursal] := matEstadisticas[13, regInmueble.sucursal] + regInmueble.precio;
// Total por mes
matEstadisticas[mes, maxColumnas] := matEstadisticas[mes, maxColumnas] + regInmueble.precio;
// Total anual
matEstadisticas[13, maxColumnas] := matEstadisticas[13, maxColumnas] +regInmueble.precio;
end;
end;
end;
// Autor: Martin
// PRE: recibe un vector de tipo tvFilasMatrizEstadisticas
// POST: El vector vacío es rellenado con los nombres de los meses y un texto de 'total x suc'
procedure cargarVecFilasMatriz(var vFilas : tvFilasMatrizEstadisticas);
begin
vFilas[1] := 'Enero'; vFilas[2] := 'Febrero'; vFilas[3] := 'Marzo'; vFilas[4] := 'Abril'; vFilas[5] := 'Mayo'; vFilas[6] := 'Junio';
vFilas[7] := 'Julio'; vFilas[8] := 'Agosto'; vFilas[9] := 'Septiembre'; vFilas[10] := 'Octubre'; vFilas[11] := 'Noviembre';
vFilas[12] := 'Diciembre'; vFilas[13] := 'Total x Suc';
end;
// Autor: Martin
// PRE: Recibe un archivo de sucursales asignado y existente, una matriz de estadisticas cargada y el maximo de columnas de esta (coincide con la cantidad de sucursales)
// POST: Muestra la matriz en pantalla
procedure mostrarMatriz(var archSucursales : tarSucursales; var matEstadisticas : tMatrizEstadistica; maxColSucursales : byte);
var regSuc : trSucursal;
vFilasMatEstadisticas : tvFilasMatrizEstadisticas;
mesActual : byte;
colActual : word;
begin
cargarVecFilasMatriz(vFilasMatEstadisticas);
{ Encabezado con nombres de sucursales }
reset(archSucursales);
write('' : FORMATO_CARACTERES_COLUMNA);
while not eof(archSucursales) do
begin
read(archSucursales, regSuc);
write(regSuc.nombre : FORMATO_CARACTERES_COLUMNA);
end;
write('Total x Mes' : FORMATO_CARACTERES_COLUMNA);
writeln;
{ Filas y datos }
for mesActual := COMIENZO_ARRAY to MAT_ESTADISTICA_FILAS do
begin
{ Mes }
write(vFilasMatEstadisticas[mesActual] : FORMATO_CARACTERES_COLUMNA);
{ Datos de la matriz }
colActual := 1;
while colActual <= maxColSucursales do
begin
write(matEstadisticas[mesActual, colActual] : FORMATO_CARACTERES_COLUMNA : 2);
inc(colActual);
end;
writeln;
end;
writeln; //Espacio para prolijidad
writeln ('Presione enter para volver.');
readln;
end;
// Autor: Martin
// PRE: Recibe una matriz de word
// POST: Modifica la matriz de manera que todos los campos sean de valor 0
procedure inicializarMatriz(var matEstadisticas : tMatrizEstadistica);
var i : byte;
j : word;
begin
for i := 1 to MAT_ESTADISTICA_FILAS do
for j := 1 to MAT_ESTADISTICA_COLUMNAS do
matEstadisticas[i, j] := 0;
end;
// Autores: Matias, Martin y Facundo
//PRE: recibe un archivo inmuebles y un archivo sucursales
//POST: Muestra las estadisticas por sucursal y mes de un anio ingresado.
procedure calcularEstadisticasAnuales(var archInmuebles : tarInmuebles; var archSucursales : tarSucursales); //Estadisticas anuales
var anio : tstrAnio;
maxCol : byte;
matEstadisticas : tMatrizEstadistica;
begin
clrscr;
writeln('Modulo estadisticas');
writeln;
inicializarMatriz(matEstadisticas);
maxCol := filesize(archSucursales) + 1;
solicitarAnio(anio);
cargarMatrizEstadisticas(archInmuebles, anio, matEstadisticas, maxCol);
mostrarMatriz(archSucursales, matEstadisticas, maxCol);
end;
// Autor: Martin
// PRE: Recibe una variable que representa el archivo de inmuebles ya asignada
// POST: Genera el archivo de inmuebles si es que este no existe (la variable pasada no puede abrirse)
procedure generarArchivosIniciales(var archInmuebles : tarInmuebles);
begin
{$I-}
reset(archInmuebles);
{$I+}
if IOResult <> 0 then
crear_archivos_iniciales() // Declarada en la unit de inmuebles
else
close(archInmuebles);
end;
var
opcion: byte;
archInmuebles: tarInmuebles;
vIndice: tvIndice;
maxLogico: tposLogica;
archSucursales: tarSucursales;
vBarrios: tvBarrios;
maxLogicoBarrios: integer;
procedeppal: tprocedencia;
begin
opcion := 0;
assign(archInmuebles, PATH_INMUEBLES);
assign(archSucursales,PATH_SUCURSALES);
generarArchivosIniciales(archInmuebles);
reset(archInmuebles);
reset(archSucursales);
cargarIndice(archInmuebles, vIndice, maxLogico);
cargarVectorBarrios(vBarrios, maxLogicoBarrios, archInmuebles);
while (opcion <> 6) do
begin
procedeppal:=PROCEDENCIA_PRINCIPAL;
validarOpcion(opcion, 1, 6, procedeppal);
case opcion of
1: listarInmuebles(archInmuebles, archSucursales, vIndice, maxLogico);
2: importarNovedades(archInmuebles, vIndice, maxLogico, vBarrios, maxLogicoBarrios);
3: buscarPorCategoria(archInmuebles);
4: buscarPorBarrio(archInmuebles,vBarrios,maxLogicoBarrios);
5: calcularEstadisticasAnuales(archInmuebles, archSucursales);
end;
end;
close(archInmuebles);
close(archSucursales);
end.
|
unit DragDropText;
// -----------------------------------------------------------------------------
// Project: Drag and Drop Component Suite.
// Module: DragDropText
// Description: Implements Dragging and Dropping of different text formats.
// Version: 4.0
// Date: 18-MAY-2001
// Target: Win32, Delphi 5-6
// Authors: Anders Melander, anders@melander.dk, http://www.melander.dk
// Copyright © 1997-2001 Angus Johnson & Anders Melander
// -----------------------------------------------------------------------------
interface
uses
DragDrop,
DropTarget,
DropSource,
DragDropFormats,
ActiveX,
Windows,
Classes;
type
////////////////////////////////////////////////////////////////////////////////
//
// TRichTextClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TRichTextClipboardFormat = class(TCustomTextClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
function HasData: boolean; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
property Text;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TUnicodeTextClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TUnicodeTextClipboardFormat = class(TCustomWideTextClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
property Text;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TOEMTextClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TOEMTextClipboardFormat = class(TCustomTextClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
property Text;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TCSVClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TCSVClipboardFormat = class(TCustomStringListClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
property Lines;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TLocaleClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
TLocaleClipboardFormat = class(TCustomDWORDClipboardFormat)
public
function GetClipboardFormat: TClipFormat; override;
function HasData: boolean; override;
function Assign(Source: TCustomDataFormat): boolean; override;
function AssignTo(Dest: TCustomDataFormat): boolean; override;
property Locale: DWORD read GetValueDWORD;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropTextTarget
//
////////////////////////////////////////////////////////////////////////////////
TDropTextTarget = class(TCustomDropMultiTarget)
private
FTextFormat : TTextDataFormat;
protected
function GetText: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Text: string read GetText;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropTextSource
//
////////////////////////////////////////////////////////////////////////////////
TDropTextSource = class(TCustomDropMultiSource)
private
FTextFormat : TTextDataFormat;
protected
function GetText: string;
procedure SetText(const Value: string);
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
published
property Text: string read GetText write SetText;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
////////////////////////////////////////////////////////////////////////////////
//
// Misc.
//
////////////////////////////////////////////////////////////////////////////////
function IsRTF(const s: string): boolean;
function MakeRTF(const s: string): string;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
implementation
uses
SysUtils;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
begin
RegisterComponents(DragDropComponentPalettePage, [TDropTextTarget,
TDropTextSource]);
end;
////////////////////////////////////////////////////////////////////////////////
//
// Utilities
//
////////////////////////////////////////////////////////////////////////////////
function IsRTF(const s: string): boolean;
begin
// This probably isn't a valid test, but it will have to do until I have
// time to research the RTF specifications.
{ TODO -oanme -cImprovement : Need a solid test for RTF format. }
Result := (AnsiStrLIComp(PChar(s), '{\rtf', 5) = 0);
end;
{ TODO -oanme -cImprovement : Needs RTF to text conversion. Maybe ITextDocument can be used. }
function MakeRTF(const s: string): string;
begin
{ TODO -oanme -cImprovement : Needs to escape \ in text to RTF conversion. }
{ TODO -oanme -cImprovement : Needs better text to RTF conversion. }
if (not IsRTF(s)) then
Result := '{\rtf1\ansi ' + s + '}'
else
Result := s;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TRichTextClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_RTF: TClipFormat = 0;
function TRichTextClipboardFormat.GetClipboardFormat: TClipFormat;
begin
// Note: The string 'Rich Text Format', is also defined in the RichEdit
// unit as CF_RTF
if (CF_RTF = 0) then
CF_RTF := RegisterClipboardFormat('Rich Text Format'); // *** DO NOT LOCALIZE ***
Result := CF_RTF;
end;
function TRichTextClipboardFormat.HasData: boolean;
begin
Result := inherited HasData and IsRTF(Text);
end;
function TRichTextClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
begin
if (Source is TTextDataFormat) then
begin
Text := MakeRTF(TTextDataFormat(Source).Text);
Result := True;
end else
Result := inherited Assign(Source);
end;
function TRichTextClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
begin
if (Dest is TTextDataFormat) then
begin
TTextDataFormat(Dest).Text := Text;
Result := True;
end else
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TUnicodeTextClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
function TUnicodeTextClipboardFormat.GetClipboardFormat: TClipFormat;
begin
Result := CF_UNICODETEXT;
end;
function TUnicodeTextClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
begin
if (Source is TTextDataFormat) then
begin
Text := TTextDataFormat(Source).Text;
Result := True;
end else
Result := inherited Assign(Source);
end;
function TUnicodeTextClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
begin
if (Dest is TTextDataFormat) then
begin
TTextDataFormat(Dest).Text := Text;
Result := True;
end else
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TOEMTextClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
function TOEMTextClipboardFormat.GetClipboardFormat: TClipFormat;
begin
Result := CF_OEMTEXT;
end;
function TOEMTextClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
var
OEMText : string;
begin
if (Source is TTextDataFormat) then
begin
// First convert ANSI string to OEM string...
SetLength(OEMText, Length(TTextDataFormat(Source).Text));
CharToOemBuff(PChar(TTextDataFormat(Source).Text), PChar(OEMText),
Length(TTextDataFormat(Source).Text));
// ...then assign OEM string
Text := OEMText;
Result := True;
end else
Result := inherited Assign(Source);
end;
function TOEMTextClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
var
AnsiText : string;
begin
if (Dest is TTextDataFormat) then
begin
// First convert OEM string to ANSI string...
SetLength(AnsiText, Length(Text));
OemToCharBuff(PChar(Text), PChar(AnsiText), Length(Text));
// ...then assign ANSI string
TTextDataFormat(Dest).Text := AnsiText;
Result := True;
end else
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TCSVClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
var
CF_CSV: TClipFormat = 0;
function TCSVClipboardFormat.GetClipboardFormat: TClipFormat;
begin
if (CF_CSV = 0) then
CF_CSV := RegisterClipboardFormat('CSV'); // *** DO NOT LOCALIZE ***
Result := CF_CSV;
end;
function TCSVClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
begin
if (Source is TTextDataFormat) then
begin
Lines.Text := TTextDataFormat(Source).Text;
Result := True;
end else
Result := inherited AssignTo(Source);
end;
function TCSVClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
begin
if (Dest is TTextDataFormat) then
begin
TTextDataFormat(Dest).Text := Lines.Text;
Result := True;
end else
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TLocaleClipboardFormat
//
////////////////////////////////////////////////////////////////////////////////
function TLocaleClipboardFormat.GetClipboardFormat: TClipFormat;
begin
Result := CF_LOCALE;
end;
function TLocaleClipboardFormat.HasData: boolean;
begin
Result := (Locale <> 0);
end;
function TLocaleClipboardFormat.Assign(Source: TCustomDataFormat): boolean;
begin
// So far we have no one to play with...
Result := inherited Assign(Source);
end;
function TLocaleClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean;
begin
// So far we have no one to play with...
Result := inherited AssignTo(Dest);
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropTextTarget
//
////////////////////////////////////////////////////////////////////////////////
constructor TDropTextTarget.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTextFormat := TTextDataFormat.Create(Self);
end;
destructor TDropTextTarget.Destroy;
begin
FTextFormat.Free;
inherited Destroy;
end;
function TDropTextTarget.GetText: string;
begin
Result := FTextFormat.Text;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropTextSource
//
////////////////////////////////////////////////////////////////////////////////
constructor TDropTextSource.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
FTextFormat := TTextDataFormat.Create(Self);
end;
destructor TDropTextSource.Destroy;
begin
FTextFormat.Free;
inherited Destroy;
end;
function TDropTextSource.GetText: string;
begin
Result := FTextFormat.Text;
end;
procedure TDropTextSource.SetText(const Value: string);
begin
FTextFormat.Text := Value;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Initialization/Finalization
//
////////////////////////////////////////////////////////////////////////////////
initialization
// Clipboard format registration
TTextDataFormat.RegisterCompatibleFormat(TUnicodeTextClipboardFormat, 1, csSourceTarget, [ddRead]);
TTextDataFormat.RegisterCompatibleFormat(TRichTextClipboardFormat, 2, csSourceTarget, [ddRead]);
TTextDataFormat.RegisterCompatibleFormat(TOEMTextClipboardFormat, 2, csSourceTarget, [ddRead]);
TTextDataFormat.RegisterCompatibleFormat(TCSVClipboardFormat, 3, csSourceTarget, [ddRead]);
finalization
// Clipboard format unregistration
TUnicodeTextClipboardFormat.UnregisterClipboardFormat;
TRichTextClipboardFormat.UnregisterClipboardFormat;
TOEMTextClipboardFormat.UnregisterClipboardFormat;
TCSVClipboardFormat.UnregisterClipboardFormat;
end.
|
unit Rights;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, Vcl.StdCtrls, RzLabel,
Vcl.ExtCtrls, RzPanel, RzLstBox, RzChkLst, RzCmboBx, System.Rtti, StrUtils;
type
TfrmRights = class(TfrmBaseDocked)
chlRights: TRzCheckList;
lblDate: TLabel;
cmbModule: TRzComboBox;
procedure FormCreate(Sender: TObject);
procedure cmbModuleChange(Sender: TObject);
procedure chlRightsChange(Sender: TObject; Index: Integer;
NewState: TCheckBoxState);
private
{ Private declarations }
FRights: array of string;
procedure GetRights;
procedure PopulateRights;
public
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
Right, SecurityData, DBUtil, IFinanceDialogs;
{ TfrmRights }
procedure TfrmRights.chlRightsChange(Sender: TObject; Index: Integer;
NewState: TCheckBoxState);
var
sql: string;
LRight: TRight;
begin
LRight := chlRights.Items.Objects[Index] as TRight;
// insert
if NewState = cbChecked then
begin
try
sql := 'INSERT INTO SYSPRIVILEGE VALUES (' +
QuotedStr(LRight.Code) + ',' +
QuotedStr(LRight.Name) + ',' +
QuotedStr(LRight.Name) + ',' +
IntToStr(1) +
')';
ExecuteSQL(sql,true);
chlRights.ItemEnabled[Index] := false;
finally
LRight.Free;
end;
end
else // delete
begin
Exit;
if ShowWarningBox('Unchecking this right will delete it from the active rights and will be removed from all ROLES using it. Do you wish to proceed?') = mrYes then
begin
sql := 'DELETE FROM SYSPRIVILEGE WHERE SYSPRIVILEGE_CODE = ' + QuotedStr(LRight.Code);
ExecuteSQL(sql,true);
end;
end;
end;
procedure TfrmRights.cmbModuleChange(Sender: TObject);
begin
inherited;
PopulateRights;
end;
procedure TfrmRights.FormCreate(Sender: TObject);
begin
inherited;
GetRights;
PopulateRights;
end;
procedure TfrmRights.GetRights;
var
len: integer;
begin
with dmSecurity.dstRights do
begin
Open;
while not Eof do
begin
len := Length(FRights);
SetLength(FRights, len + 1);
FRights[len] := FieldByName('privilege_code').AsString;
Next;
end;
Close;
end;
end;
procedure TfrmRights.PopulateRights;
const
// MODULE INDICES
//
// A = Client
// B = Loans
// C = Payment
// S = Administrator functions
// Z = Security
ADMINISTRATOR = 0;
CLIENT = 1;
LOANS = 2;
PAYMENT = 3;
SECURITY = 4;
var
item: string;
LRight: TRight;
sl: TStringList;
module: string;
begin
// clear the list
chlRights.Clear;
case cmbModule.ItemIndex of
ADMINISTRATOR: module := 'ADM';
CLIENT: module := 'CLIENT';
LOANS: module := 'LOAN';
PAYMENT: module := 'PAY';
SECURITY: module := 'SEC';
else module := 'X';
end;
for item in PRIVILEGES do
begin
sl := TStringList.Create;
sl.Delimiter := ';';
sl.DelimitedText := item;
if sl[2] = module then
begin
LRight := TRight.Create;
LRight.Code := sl[0];
LRight.Name := StringReplace(sl[1],'_',' ',[rfReplaceAll]);
chlRights.AddItem(LRight.Name,LRight);
chlRights.ItemChecked[chlRights.Items.Count-1] := MatchStr(LRight.Code,FRights);
chlRights.ItemEnabled[chlRights.Items.Count-1] := not MatchStr(LRight.Code,FRights);
end;
sl.Free;
end;
end;
end.
|
unit MediaStream.Framer.Mp6;
interface
uses Windows,SysUtils,Classes,HHCommon,HHReader, MediaProcessing.Definitions,MediaStream.Framer;
type
TStreamFramerMp6RandomAccess = class;
TStreamFramerMp6 = class (TStreamFramer)
private
FReader: THHReaderMpeg6;
FRandomAccess: TStreamFramerMp6RandomAccess;
FFirstVideoFrameTimeStamp: int64;
FFirstAudioFrameTimeStamp: int64;
FVideoFramesRead: int64;
FAudioFramesRead: int64;
public
constructor Create; override;
destructor Destroy; override;
procedure OpenStream(aStream: TStream); override;
function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal):boolean; override;
function VideoStreamType: TStreamType; override;
function VideoInfo: TVideoInfo; override;
function AudioStreamType: TStreamType; override;
function AudioInfo: TAudioInfo; override;
function StreamInfo: TBytes; override;
property Reader: THHReaderMpeg6 read FReader;
function RandomAccess: TStreamFramerRandomAccess; override;
end;
TStreamFramerMp6RandomAccess = class (TStreamFramerRandomAccess)
private
FOwner: TStreamFramerMp6;
FStreamInfo: TStreamInfo;
FFirstVideoTimeStamp, FLastVideoTimeStamp: int64;
protected
function GetPosition: int64; override;
procedure SetPosition(const Value: int64); override;
public
function StreamInfo: TStreamInfo; override;
function SeekToPrevVideoKeyFrame: boolean; override;
constructor Create(aOwner: TStreamFramerMp6);
end;
implementation
{ TStreamFramerMp6 }
constructor TStreamFramerMp6.Create;
begin
inherited;
FReader:=THHReaderMpeg6.Create;
end;
destructor TStreamFramerMp6.Destroy;
begin
FreeAndNil(FReader);
FreeAndNil(FRandomAccess);
inherited;
end;
function TStreamFramerMp6.GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal): boolean;
var
aH264Data: pointer;
aH264DataSize: cardinal;
begin
Assert(FReader<>nil);
result:=FReader.ReadFrame;
if result then
begin
aOutData:=FReader.CurrentFrame;
aOutDataSize:=FReader.CurrentFrame.nByteNum+sizeof(HV_FRAME_HEAD);
aOutInfo:=@FReader.AVInfo;
aOutInfoSize:=sizeof(FReader.AVInfo);
aOutFormat.Clear;
//aOutFormat.DataSize:=aOutDataSize;
if FReader.CurrentFrame.streamFlag = FRAME_FLAG_A then
begin
aOutFormat.biMediaType:=mtAudio;
aOutFormat.biStreamType:= AudioStreamType;
aOutFormat.biStreamSubType:=FReader.AVInfo.nAudioEncodeType;
aOutFormat.AudioChannels:=FReader.AVInfo.nAudioChannels;
aOutFormat.AudioBitsPerSample:=FReader.AVInfo.nAudioBits;
aOutFormat.AudioSamplesPerSec:=FReader.AVInfo.nAudioSamples;
if (FFirstAudioFrameTimeStamp=0) and (FAudioFramesRead=0) then
FFirstAudioFrameTimeStamp:=FReader.CurrentFrame.nTimestamp;
aOutFormat.TimeStamp:=FReader.CurrentFrame.nTimestamp-FFirstAudioFrameTimeStamp;
inc(FAudioFramesRead);
end
else begin
aOutFormat.biMediaType:=mtVideo;
aOutFormat.biStreamType:= VideoStreamType;
aOutFormat.biStreamSubType:=FReader.AVInfo.nVideoEncodeType;
aOutFormat.VideoWidth:=FReader.AVInfo.nVideoWidth;
aOutFormat.VideoHeight:=FReader.AVInfo.nVideoHeight;
if (FFirstVideoFrameTimeStamp=0) and (FVideoFramesRead=0) then
FFirstVideoFrameTimeStamp:=FReader.CurrentFrame.nTimestamp;
//aOutFormat.biBitCount:=0;
if FReader.CurrentFrame.streamFlag=FRAME_FLAG_VI then
Include(aOutFormat.biFrameFlags,ffKeyFrame);
aOutFormat.TimeStamp:=FReader.CurrentFrame.nTimestamp-FFirstVideoFrameTimeStamp;
if GetH264Data(aOutData,aH264Data,aH264DataSize) then
begin
aOutData:=aH264Data;
aOutDataSize:=aH264DataSize;
aOutInfo:=nil;
aOutInfoSize:=0;
aOutFormat.biStreamType:=stH264;
end;
inc(FVideoFramesRead);
end;
aOutFormat.TimeKoeff:=40;
//if aOutFormat.TimeStamp<0 then
// aOutFormat.TimeStamp:=0; //?? Что делать в случае нарушенных временных меток?
end;
end;
procedure TStreamFramerMp6.OpenStream(aStream: TStream);
begin
FreeAndNil(FRandomAccess);
FReader.Open(aStream);
end;
function TStreamFramerMp6.RandomAccess: TStreamFramerRandomAccess;
begin
result:=FRandomAccess;
if result<>nil then
exit;
if not FReader.Opened then
exit;
FReader.ReadIndexTable;
if FReader.IndexTableExists then
begin
try FReader.IndexTable.CheckTimeStampOrder; except end;
FRandomAccess:=TStreamFramerMp6RandomAccess.Create(self);
end;
result:=FRandomAccess;
end;
function TStreamFramerMp6.StreamInfo: TBytes;
var
aAVInfo: HHAV_INFO;
begin
aAVInfo:=FReader.AVInfo;
SetLength(result,sizeof(aAVInfo));
CopyMemory(result,@aAVInfo,sizeof(aAVInfo));
end;
function TStreamFramerMp6.VideoInfo: TVideoInfo;
begin
result.Width:=FReader.AVInfo.nVideoWidth;
result.Height:=FReader.AVInfo.nVideoHeight;
if result.Width*Result.Height>0 then
result.State:=isOK
else
result.State:=isNotFound;
end;
function TStreamFramerMp6.VideoStreamType: TStreamType;
begin
result:=stHHVI;
end;
function TStreamFramerMp6.AudioInfo: TAudioInfo;
begin
result.Channels:=FReader.AVInfo.nAudioChannels;
result.BitsPerSample:=FReader.AVInfo.nAudioBits;
result.SamplesPerSec:=FReader.AVInfo.nAudioSamples;
if result.Channels>0 then
result.State:=isOK
else
result.State:=isNotFound;
end;
function TStreamFramerMp6.AudioStreamType: TStreamType;
begin
result:=stHHAU;
end;
{ TStreamFramerMp6RandomAccess }
constructor TStreamFramerMp6RandomAccess.Create(aOwner: TStreamFramerMp6);
var
aDelta: int64;
i: integer;
begin
FOwner:=aOwner;
FStreamInfo.VideoFrameCount:=FOwner.FReader.IndexTable.GetVideoFrameCount(FFirstVideoTimeStamp,FLastVideoTimeStamp);
aDelta:=FLastVideoTimeStamp-FFirstVideoTimeStamp;
FStreamInfo.Length:=DeviceTimeStampToMs(aDelta);
i:=FOwner.Reader.IndexTable.FindFirstVideoFrame;
if i<>-1 then
FOwner.FFirstVideoFrameTimeStamp:=FOwner.FReader.IndexTable[i].Timestamp;
i:=FOwner.Reader.IndexTable.FindFirstAudioFrame;
if i<>-1 then
FOwner.FFirstAudioFrameTimeStamp:=FOwner.FReader.IndexTable[i].Timestamp;
end;
function TStreamFramerMp6RandomAccess.GetPosition: int64;
var
// i: integer;
aDelta: int64;
begin
//TODO не учитывается переполнение в счетчике
if FOwner.FReader.LastReadVideoTimestamp<FFirstVideoTimeStamp then
result:=0
else begin
aDelta:= FOwner.FReader.LastReadVideoTimestamp-FFirstVideoTimeStamp;
result:=DeviceTimeStampToMs(aDelta);
end;
(* i:=FOwner.FReader.IndexTable.FindNearestFrame(FOwner.FReader.Position);
if i>=0 then
begin
while (i>=0) and (not (FOwner.FReader.IndexTable[i].StreamFlag in [FRAME_FLAG_VI,FRAME_FLAG_VP])) do
dec(i);
end;
if i>=0 then
begin
end;
*)
end;
function TStreamFramerMp6RandomAccess.StreamInfo: TStreamInfo;
begin
result:=FStreamInfo;
end;
function TStreamFramerMp6RandomAccess.SeekToPrevVideoKeyFrame: boolean;
begin
result:=FOwner.FReader.SeekToPrevIVideoFrame;
end;
procedure TStreamFramerMp6RandomAccess.SetPosition(const Value: int64);
begin
if Value<=0 then
FOwner.FReader.ResetPos
else begin
if FOwner.FReader.SeekToVideoFrameGE(FFirstVideoTimeStamp+MsToDeviceTimeStamp(Value)) then
FOwner.FReader.SeekToPrevIVideoFrame
else
FOwner.FReader.SeekToEnd;
end;
end;
end.
|
unit RadioButtonImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB;
type
TRadioButtonX = class(TActiveXControl, IRadioButtonX)
private
{ Private declarations }
FDelphiControl: TRadioButton;
FEvents: IRadioButtonXEvents;
procedure ClickEvent(Sender: TObject);
procedure DblClickEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_Alignment: TxLeftRight; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_Caption: WideString; safecall;
function Get_Checked: WordBool; safecall;
function Get_Color: OLE_COLOR; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Font: IFontDisp; safecall;
function Get_ParentColor: WordBool; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_ParentFont: WordBool; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure _Set_Font(const Value: IFontDisp); safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_Alignment(Value: TxLeftRight); safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_Caption(const Value: WideString); safecall;
procedure Set_Checked(Value: WordBool); safecall;
procedure Set_Color(Value: OLE_COLOR); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Font(const Value: IFontDisp); safecall;
procedure Set_ParentColor(Value: WordBool); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_ParentFont(Value: WordBool); safecall;
procedure Set_Visible(Value: WordBool); safecall;
end;
implementation
uses ComObj, About24;
{ TRadioButtonX }
procedure TRadioButtonX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_RadioButtonXPage); }
end;
procedure TRadioButtonX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IRadioButtonXEvents;
end;
procedure TRadioButtonX.InitializeControl;
begin
FDelphiControl := Control as TRadioButton;
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnDblClick := DblClickEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
end;
function TRadioButtonX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TRadioButtonX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TRadioButtonX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TRadioButtonX.Get_Alignment: TxLeftRight;
begin
Result := Ord(FDelphiControl.Alignment);
end;
function TRadioButtonX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TRadioButtonX.Get_Caption: WideString;
begin
Result := WideString(FDelphiControl.Caption);
end;
function TRadioButtonX.Get_Checked: WordBool;
begin
Result := FDelphiControl.Checked;
end;
function TRadioButtonX.Get_Color: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.Color);
end;
function TRadioButtonX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TRadioButtonX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TRadioButtonX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TRadioButtonX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TRadioButtonX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TRadioButtonX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TRadioButtonX.Get_Font: IFontDisp;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
function TRadioButtonX.Get_ParentColor: WordBool;
begin
Result := FDelphiControl.ParentColor;
end;
function TRadioButtonX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TRadioButtonX.Get_ParentFont: WordBool;
begin
Result := FDelphiControl.ParentFont;
end;
function TRadioButtonX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TRadioButtonX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TRadioButtonX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TRadioButtonX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TRadioButtonX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TRadioButtonX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TRadioButtonX._Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TRadioButtonX.AboutBox;
begin
ShowRadioButtonXAbout;
end;
procedure TRadioButtonX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TRadioButtonX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TRadioButtonX.Set_Alignment(Value: TxLeftRight);
begin
FDelphiControl.Alignment := TLeftRight(Value);
end;
procedure TRadioButtonX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TRadioButtonX.Set_Caption(const Value: WideString);
begin
FDelphiControl.Caption := TCaption(Value);
end;
procedure TRadioButtonX.Set_Checked(Value: WordBool);
begin
FDelphiControl.Checked := Value;
end;
procedure TRadioButtonX.Set_Color(Value: OLE_COLOR);
begin
FDelphiControl.Color := TColor(Value);
end;
procedure TRadioButtonX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TRadioButtonX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TRadioButtonX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TRadioButtonX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TRadioButtonX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TRadioButtonX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TRadioButtonX.Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TRadioButtonX.Set_ParentColor(Value: WordBool);
begin
FDelphiControl.ParentColor := Value;
end;
procedure TRadioButtonX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TRadioButtonX.Set_ParentFont(Value: WordBool);
begin
FDelphiControl.ParentFont := Value;
end;
procedure TRadioButtonX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TRadioButtonX.ClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClick;
end;
procedure TRadioButtonX.DblClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnDblClick;
end;
procedure TRadioButtonX.KeyPressEvent(Sender: TObject; var Key: Char);
var
TempKey: Smallint;
begin
TempKey := Smallint(Key);
if FEvents <> nil then FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TRadioButtonX,
TRadioButton,
Class_RadioButtonX,
24,
'{695CDB91-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit UnitFormProductData;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UnitFormDataTable, server_data_types,
services, stringgridutils, Vcl.ExtCtrls, Vcl.Menus;
type
TFormProductData = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure PopupMenu1Popup(Sender: TObject);
procedure N2Click(Sender: TObject);
private
{ Private declarations }
FFormDataTable1, FFormDataTable2: TFormDataTable;
FProductID: int64;
procedure SetupColumnsWidth2;
procedure SetupProduct;
public
{ Public declarations }
procedure FetchProductData(productID: int64);
procedure OnProductDataChanged(x: int64);
end;
var
FormProductData: TFormProductData;
implementation
uses dateutils;
{$R *.dfm}
procedure TFormProductData.FormCreate(Sender: TObject);
begin
FFormDataTable1 := TFormDataTable.Create(self);
FFormDataTable2 := TFormDataTable.Create(self);
FFormDataTable2.StringGrid2.PopupMenu := PopupMenu1;
end;
procedure TFormProductData.N1Click(Sender: TObject);
var
ro: integer;
entryID: int64;
Entries: TArray<int64>;
begin
with FFormDataTable2.StringGrid2 do
begin
for ro := Selection.Top to Selection.Bottom do
begin
SetLength(Entries, Length(Entries) + 1);
Entries[Length(Entries) - 1] := StrToInt64(Cells[0, ro]);
end;
end;
TProductsSvc.DeleteEntries(Entries);
SetupProduct;
end;
procedure TFormProductData.N2Click(Sender: TObject);
begin
with FFormDataTable2.StringGrid2 do
TPartySvc.DeleteTestEntries(Cells[2, Row]);
SetupProduct;
end;
procedure TFormProductData.FetchProductData(productID: int64);
begin
FProductID := productID;
SetupProduct;
end;
procedure TFormProductData.SetupProduct;
var
pp: TProductPassport;
begin
pp := TProductsSvc.ProductPassport(FProductID);
Panel1.Caption := Format('ДАФ-М %d №%d партия %d %s',
[FProductID, pp.Serial, pp.PartyID, DateTimeToStr(pp.CreatedAt)]);
Panel1.Top := 0;
with FFormDataTable1 do
begin
Font.Assign(self.Font);
Parent := Panel2;
BorderStyle := bsNone;
Align := alTop;
Top := 100500;
SetTable(pp.T1);
with StringGrid2 do
FFormDataTable1.Height := DefaultRowHeight * RowCount + 20;
Show;
end;
with FFormDataTable2 do
begin
Font.Assign(self.Font);
Parent := Panel2;
BorderStyle := bsNone;
Align := alClient;
SetTable(pp.T2);
SetupColumnsWidth2;
Visible := StringGrid2.RowCount > 1;
end;
end;
procedure TFormProductData.SetupColumnsWidth2;
var
ACol: integer;
begin
with FFormDataTable2.StringGrid2 do
begin
ColWidths[ColCount - 1] := self.Width - 50;
for ACol := 0 to ColCount - 2 do
begin
StringGrid_SetupColumnWidth(FFormDataTable2.StringGrid2, ACol);
ColWidths[ColCount - 1] := ColWidths[ColCount - 1] -
ColWidths[ACol];
end;
end;
end;
procedure TFormProductData.OnProductDataChanged(x: int64);
begin
if FProductID = x then
SetupProduct;
end;
procedure TFormProductData.PopupMenu1Popup(Sender: TObject);
begin
with FFormDataTable2.StringGrid2 do
begin
if Row > 0 then
begin
N2.Caption := 'Удалить записи "' + Cells[2, Row] +
'" для всей партии';
N2.Visible := true;
end
else
begin
N2.Visible := false;
end;
end;
end;
end.
|
unit uFrame1;
interface
uses
System.Generics.Collections,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts,
UI.Standard, UI.Base, UI.Frame, UI.Dialog, UI.ListView, uBaseFrame{Base Frame for project};
type
TDataItem = record
TiTle: string;
Accessory: TViewAccessoryType;
Color: TAlphaColor;
end;
TCustomListDataAdapter = class(TListAdapterBase)
private
[Weak] FList: TList<TDataItem>;
protected
function GetCount: Integer; override;
function ItemDefaultHeight: Single; override;
function GetItem(const Index: Integer): Pointer; override;
function IndexOf(const AItem: Pointer): Integer; override;
function GetView(const Index: Integer; ConvertView: TViewBase;
Parent: TViewGroup): TViewBase; override;
public
constructor Create(const AList: TList<TDataItem>);
end;
TFrame1 = class(TFrame)
LinearLayout1: TLinearLayout;
tvTitle: TTextView;
ListViewEx1: TListViewEx;
procedure ListViewEx1ItemClick(Sender: TObject; ItemIndex: Integer;
const ItemView: TControl);
private
{ Private declarations }
FAdapter: TCustomListDataAdapter;
FList: TList<TDataItem>;
protected
procedure DoCreate(); override;
procedure DoFree(); override;
procedure DoShow(); override;
procedure DoResume; override;
procedure DoPause; override;
public
{ Public declarations }
end;
implementation
{$R *.fmx}
uses
uFrame2;
{ TFrame1 }
procedure TFrame1.DoCreate;
procedure AddItem(ATitle: string; AAccessory: TViewAccessoryType; AColor: TAlphaColor);
var
Item: TDataItem;
begin
Item.Accessory := AAccessory;
Item.TiTle := ATitle;
Item.Color := AColor;
FList.Add(Item);
end;
begin
inherited;
FList := TList<TDataItem>.Create();
FAdapter := TCustomListDataAdapter.Create(FList);
ListViewEx1.Adapter := FAdapter;
AddItem('OnInit', TViewAccessoryType.Pagecurl, TAlphaColorRec.Green);
AddItem('OnReturn', TViewAccessoryType.Refresh, TAlphaColorRec.Blue);
AddItem('OnCallback', TViewAccessoryType.Password, TAlphaColorRec.Black);
AddItem('StatusBar', TViewAccessoryType.Info, TAlphaColorRec.Black);
AddItem('Exit', TViewAccessoryType.Exit, TAlphaColorRec.Crimson);
FAdapter.NotifyDataChanged;
end;
procedure TFrame1.DoFree;
begin
inherited;
ListViewEx1.Adapter := nil;
FAdapter := nil;
FreeAndNil(FList);
end;
procedure TFrame1.DoPause;
begin
Hint('TFrame1.DoPause');
inherited;
end;
procedure TFrame1.DoResume;
begin
inherited;
Hint('TFrame1.DoResume');
end;
procedure TFrame1.DoShow;
begin
inherited;
end;
procedure TFrame1.ListViewEx1ItemClick(Sender: TObject; ItemIndex: Integer;
const ItemView: TControl);
begin
if FList[ItemIndex].TiTle = 'Exit' then begin
Application.MainForm.Close;
end
else if FList[ItemIndex].TiTle = 'OnCallback' then begin
with TFrame2(TFrame2.ShowMainFrame) do begin
Hint('Callback demo, please click the button');
BackColor := FList[ItemIndex].Color;
StatusColor := FList[ItemIndex].Color;
tvTitle.Text := FList[ItemIndex].TiTle;
EnableLogin := True;
OnLogin := procedure (AView: TFrame; AUserName, APassword: string) begin
if (AUserName = '') or (APassword = '') then begin
Hint('Please input all items.');
Exit;
end;
Hint('UserName: %s Password:%s', [AUserName, APassword]);
AView.Finish;
end;
end;
end
else if FList[ItemIndex].TiTle = 'OnReturn' then begin
with TFrame2(TFrame2.ShowMainFrame) do begin
BackColor := FList[ItemIndex].Color;
StatusColor := FList[ItemIndex].Color;
tvTitle.Text := FList[ItemIndex].TiTle;
end;
end
else if FList[ItemIndex].TiTle = 'OnInit' then begin
TFrame2.ShowWithInit(
procedure (View: TFrameView) begin
with TFrame2(View) do begin
BackColor := FList[ItemIndex].Color;
StatusColor := FList[ItemIndex].Color;
tvTitle.Text := FList[ItemIndex].TiTle;
end;
end)
end
else if FList[ItemIndex].TiTle = 'StatusBar' then begin
if BackColor = TAlphaColorRec.Gray then
BackColor := TAlphaColorRec.Whitesmoke
else
BackColor := TAlphaColorRec.Gray;
TFrameView.SetDefaultStatusLight(BackColor <> TAlphaColorRec.Gray);
TFrameView.SetDefaultStatusTransparent(True);
StatusColor := BackColor;
end;
end;
{ TCustomListDataAdapter }
constructor TCustomListDataAdapter.Create(const AList: TList<TDataItem>);
begin
FList := AList;
end;
function TCustomListDataAdapter.GetCount: Integer;
begin
if Assigned(FList) then
Result := FList.Count
else
Result := 0;
end;
function TCustomListDataAdapter.GetItem(const Index: Integer): Pointer;
begin
Result := nil;
end;
function TCustomListDataAdapter.GetView(const Index: Integer;
ConvertView: TViewBase; Parent: TViewGroup): TViewBase;
var
ViewItem: TTextView;
Item: TDataItem;
begin
if (ConvertView = nil) or (not (ConvertView.ClassType = TTextView)) then begin
ViewItem := TTextView.Create(Parent);
with ViewItem do begin
Parent := Parent;
Align := TAlignLayout.Client;
WidthSize := TViewSize.FillParent;
HeightSize := TViewSize.FillParent;
CanFocus := False;
Padding.Left := 8;
Padding.Right := 8;
Padding.Top := 15;
Padding.Bottom := 15;
Drawable.Position := TDrawablePosition.Top;
Drawable.SizeWidth := 40;
Drawable.SizeHeight := 40;
Drawable.Padding := 10;
TextSettings.Gravity := TLayoutGravity.CenterHorizontal;
TextSettings.Font.Size := 11;
with TViewBrushBase(Drawable.ItemDefault) do begin
Kind := TViewBrushKind.AccessoryBitmap;
end;
Size.Width := 80;
Size.Height := 100;
end;
end else
ViewItem := TObject(ConvertView) as TTextView;
Item := FList.Items[Index];
ViewItem.BeginUpdate;
try
with ViewItem do begin
with TViewBrushBase(Drawable.ItemDefault) do begin
Accessory.Accessory := Item.Accessory;
Accessory.Color := Item.Color;
end;
Text := Item.TiTle;
end;
finally
ViewItem.EndUpdate;
end;
Result := TViewBase(ViewItem);
end;
function TCustomListDataAdapter.IndexOf(const AItem: Pointer): Integer;
begin
Result := -1;
end;
function TCustomListDataAdapter.ItemDefaultHeight: Single;
begin
Result := 72;
end;
end.
|
Unit myQueueForTree;
Interface
Uses myDates;
Type pointQueue = ^treeQueue;
treeQueue = record
info: pointTree;
next: pointQueue;
end;
Var headQueue: pointQueue;
Procedure addToQueue(var point: pointQueue; x: pointTree);
Function isEmptyPointQueue(point: pointQueue):boolean;
Function queuePop(var point: pointQueue):pointTree;
Implementation
Procedure initHeadQueue(var point: pointQueue);
begin
new(point);
point^.next:=point;
end;
Procedure addToQueue(var point: pointQueue; x: pointTree);
var y:pointQueue;
begin
point^.info:=x;
new(y);
y^.next:=point^.next;
point^.next:=y;
point:=y;
end;
Function isEmptyPointQueue(point: pointQueue):boolean;
begin
isEmptyPointQueue:=point=point^.next;
end;
Function queuePop(var point: pointQueue):pointTree;
var metk: pointQueue;
info: pointTree;
begin
metk:=point^.next;
info:=metk^.info;
point^.next:=metk^.next;
dispose(metk);
queuePop:=info;
end;
Initialization
initHeadQueue(headQueue);
End. |
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ Internet Application Runtime }
{ }
{ Copyright (C) 1995, 2001 Borland Software Corporation }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ This unit is a pascal wrapper for the Apache interface header files. Those }
{ files were released under the following copyright: }
{ }
{ ==================================================================== }
{ Copyright (c) 1995-2000 The Apache Group. All rights reserved. }
{ }
{ Redistribution and use in source and binary forms, with or without }
{ modification, are permitted provided that the following conditions }
{ are met: }
{ }
{ 1. Redistributions of source code must retain the above copyright }
{ notice, this list of conditions and the following disclaimer. }
{ }
{ 2. 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. }
{ }
{ 3. All advertising materials mentioning features or use of this }
{ software must display the following acknowledgment: }
{ "This product includes software developed by the Apache Group }
{ for use in the Apache HTTP server project http://httpd.apache.org/ }
{ }
{ 4. The names "Apache Server" and "Apache Group" must not be used to }
{ endorse or promote products derived from this software without }
{ prior written permission. For written permission, please contact }
{ apache@apache.org. }
{ }
{ 5. Products derived from this software may not be called "Apache" }
{ nor may "Apache" appear in their names without prior written }
{ permission of the Apache Group. }
{ }
{ 6. Redistributions of any form whatsoever must retain the following }
{ acknowledgment: }
{ "This product includes software developed by the Apache Group }
{ for use in the Apache HTTP server project (http://httpd.apache.org }
{ }
{ THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY }
{ EXPRESSED 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 APACHE GROUP OR }
{ ITS 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. }
{ ==================================================================== }
{ }
{ This software consists of voluntary contributions made by many }
{ individuals on behalf of the Apache Group and was originally based }
{ on public domain software written at the National Center for }
{ Supercomputing Applications, University of Illinois, Urbana-Champaign. }
{ For more information on the Apache Group and the Apache HTTP server }
{ project, please see <http://www.apache.org/>. }
{ }
{ *************************************************************************** }
unit HTTPD;
{ Pull in importlib for ApacheCore.dll }
(*$HPPEMIT '#if defined(__WIN32__)' *)
(*$HPPEMIT '#pragma link "ApacheCore.lib"' *)
(*$HPPEMIT '#endif' *)
(*$HPPEMIT '#if defined(__linux__)' *)
(*$HPPEMIT '#pragma link "libhttpd.so"' *)
(*$HPPEMIT '#endif' *)
(*$HPPEMIT '#include <httpd.h>'*)
(*$HPPEMIT '#include <http_config.h>'*)
(*$HPPEMIT '#include <http_core.h>'*)
(*$HPPEMIT '#include <http_log.h>'*)
(*$HPPEMIT '#include <http_protocol.h>'*)
interface
{$IFDEF MSWINDOWS}
uses WinSock;
{$ENDIF}
{$IFDEF Linux}
uses Libc;
{$ENDIF}
const
//* ----------------------------- config dir ------------------------------ */
//* Define this to be the default server home dir. Most things later in this
//* file with a relative pathname will have this added.
//*
//* The target name of the installed Apache */
{$IFDEF MSWINDOWS}
ApacheCore = 'ApacheCore.dll'; {do not localize}
{$EXTERNALSYM ApacheCore}
// HTTPD_ROOT = '/apache'; {do not localize}
TARGET = 'apache'; {do not localize}
{$EXTERNALSYM TARGET}
{$ENDIF}
{$IFDEF LINUX}
ApacheCore = 'libhttpd.so'; {do not localize}
{$EXTERNALSYM ApacheCore}
// HTTPD_ROOT = '/usr/local/apache'; {do not localize}
TARGET = 'httpd'; {do not localize}
{$EXTERNALSYM TARGET}
{$ENDIF}
//* Default location of documents. Can be overridden by the DocumentRoot directive
// DOCUMENT_LOCATION = HTTPD_ROOT + '/htdocs'; {do not localize}
//* Max. number of dynamically loaded modules */
DYNAMIC_MODULE_LIMIT = 64;
{$EXTERNALSYM DYNAMIC_MODULE_LIMIT}
//* Default administrator's address */
DEFAULT_ADMIN = '[no address given]'; {do not localize}
{$EXTERNALSYM DEFAULT_ADMIN}
//* Initializer for the first few module slots, which are only
// * really set up once we start running. Note that the first two slots
// * provide a version check; this should allow us to deal with changes to
// * the API. The major number should reflect changes to the API handler table
// * itself or removal of functionality. The minor number should reflect
// * additions of functionality to the existing API. (the server can detect
// * an old-format module, and either handle it back-compatibly, or at least
// * signal an error). See src/include/ap_mmn.h for MMN version history.
// */
MODULE_MAGIC_COOKIE = $41503133; ///* "AP13" */
{$EXTERNALSYM MODULE_MAGIC_COOKIE}
MODULE_MAGIC_NUMBER_MAJOR = 19990320;
{$EXTERNALSYM MODULE_MAGIC_NUMBER_MAJOR}
MODULE_MAGIC_NUMBER_MINOR = 6; ///* 0...n */
{$EXTERNALSYM MODULE_MAGIC_NUMBER_MINOR}
MODULE_MAGIC_NUMBER = MODULE_MAGIC_NUMBER_MAJOR; ///* backward compat */
{$EXTERNALSYM MODULE_MAGIC_NUMBER}
// STANDARD_MODULE_STUFF
// must appear in all module records.
// version := MODULE_MAGIC_NUMBER_MAJOR;
// minor_version := MODULE_MAGIC_NUMBER_MINOR;
// module_index := -1;
// name := __FILE__;
// dynamic_load_handle := nil;
// next := nil;
// magic := MODULE_MAGIC_COOKIE;
///* Numeric release version identifier: MMNNFFRBB: major minor fix final beta
// * Always increases along the same track as the source branch.
// * For example, Apache 1.4.2 would be '10402100', 2.5b7 would be '20500007'.
// */
APACHE_RELEASE = 10309100;
{$EXTERNALSYM APACHE_RELEASE}
SERVER_PROTOCOL = 'HTTP/1.1'; {do not localize}
{$EXTERNALSYM SERVER_PROTOCOL}
AP_DECLINED = -1; ///* Module declines to handle */
{$EXTERNALSYM AP_DECLINED}
AP_DONE = -2; ///* Module has served the response completely
{$EXTERNALSYM AP_DONE}
// * - it's safe to die() with no more output
// */
AP_OK = 0; ///* Module has handled this stage. */
{$EXTERNALSYM AP_OK}
// Constants for reading client input
REQUEST_NO_BODY = 0;
{$EXTERNALSYM REQUEST_NO_BODY}
REQUEST_CHUNKED_ERROR = 1;
{$EXTERNALSYM REQUEST_CHUNKED_ERROR}
REQUEST_CHUNKED_DECHUNK = 2;
{$EXTERNALSYM REQUEST_CHUNKED_DECHUNK}
REQUEST_CHUNKED_PASS = 3;
{$EXTERNALSYM REQUEST_CHUNKED_PASS}
///* Methods recognized (but not necessarily handled) by the server.
// * These constants are used in bit shifting masks of size int, so it is
// * unsafe to have more methods than bits in an int. HEAD == M_GET.
// */
M_GET = 0;
{$EXTERNALSYM M_GET}
M_PUT = 1;
{$EXTERNALSYM M_PUT}
M_POST = 2;
{$EXTERNALSYM M_POST}
M_DELETE = 3;
{$EXTERNALSYM M_DELETE}
M_CONNECT = 4;
{$EXTERNALSYM M_CONNECT}
M_OPTIONS = 5;
{$EXTERNALSYM M_OPTIONS}
M_TRACE = 6;
{$EXTERNALSYM M_TRACE}
M_PATCH = 7;
{$EXTERNALSYM M_PATCH}
M_PROPFIND = 8;
{$EXTERNALSYM M_PROPFIND}
M_PROPPATCH = 9;
{$EXTERNALSYM M_PROPPATCH}
M_MKCOL = 10;
{$EXTERNALSYM M_MKCOL}
M_COPY = 11;
{$EXTERNALSYM M_COPY}
M_MOVE = 12;
{$EXTERNALSYM M_MOVE}
M_LOCK = 13;
{$EXTERNALSYM M_LOCK}
M_UNLOCK = 14;
{$EXTERNALSYM M_UNLOCK}
M_INVALID = 15;
{$EXTERNALSYM M_INVALID}
METHODS = 16;
{$EXTERNALSYM METHODS}
REMOTE_HOST = 0;
{$EXTERNALSYM REMOTE_HOST}
REMOTE_NAME = 1;
{$EXTERNALSYM REMOTE_NAME}
REMOTE_NOLOOKUP = 2;
{$EXTERNALSYM REMOTE_NOLOOKUP}
REMOTE_DOUBLE_REV = 3;
{$EXTERNALSYM REMOTE_DOUBLE_REV}
CGI_MAGIC_TYPE = 'application/x-httpd-cgi';
{$EXTERNALSYM CGI_MAGIC_TYPE}
INCLUDES_MAGIC_TYPE = 'text/x-server-parsed-html';
{$EXTERNALSYM INCLUDES_MAGIC_TYPE}
INCLUDES_MAGIC_TYPE3 = 'text/x-server-parsed-html3';
{$EXTERNALSYM INCLUDES_MAGIC_TYPE3}
MAP_FILE_MAGIC_TYPE = 'application/x-type-map';
{$EXTERNALSYM MAP_FILE_MAGIC_TYPE}
ASIS_MAGIC_TYPE = 'httpd/send-as-is';
{$EXTERNALSYM ASIS_MAGIC_TYPE}
DIR_MAGIC_TYPE = 'httpd/unix-directory';
{$EXTERNALSYM DIR_MAGIC_TYPE}
STATUS_MAGIC_TYPE = 'application/x-httpd-status';
{$EXTERNALSYM STATUS_MAGIC_TYPE}
///* ----------------------- HTTP Status Codes ------------------------- */
///* The size of the static array in http_protocol.c for storing
// * all of the potential response status-lines (a sparse table).
// * A future version should dynamically generate the table at startup.
// */
RESPONSE_CODES = 55;
{$EXTERNALSYM RESPONSE_CODES}
HTTP_CONTINUE = 100;
{$EXTERNALSYM HTTP_CONTINUE}
HTTP_SWITCHING_PROTOCOLS = 101;
{$EXTERNALSYM HTTP_SWITCHING_PROTOCOLS}
HTTP_PROCESSING = 102;
{$EXTERNALSYM HTTP_PROCESSING}
HTTP_OK = 200;
{$EXTERNALSYM HTTP_OK}
HTTP_CREATED = 201;
{$EXTERNALSYM HTTP_CREATED}
HTTP_ACCEPTED = 202;
{$EXTERNALSYM HTTP_ACCEPTED}
HTTP_NON_AUTHORITATIVE = 203;
{$EXTERNALSYM HTTP_NON_AUTHORITATIVE}
HTTP_NO_CONTENT = 204;
{$EXTERNALSYM HTTP_NO_CONTENT}
HTTP_RESET_CONTENT = 205;
{$EXTERNALSYM HTTP_RESET_CONTENT}
HTTP_PARTIAL_CONTENT = 206;
{$EXTERNALSYM HTTP_PARTIAL_CONTENT}
HTTP_MULTI_STATUS = 207;
{$EXTERNALSYM HTTP_MULTI_STATUS}
HTTP_MULTIPLE_CHOICES = 300;
{$EXTERNALSYM HTTP_MULTIPLE_CHOICES}
HTTP_MOVED_PERMANENTLY = 301;
{$EXTERNALSYM HTTP_MOVED_PERMANENTLY}
HTTP_MOVED_TEMPORARILY = 302;
{$EXTERNALSYM HTTP_MOVED_TEMPORARILY}
HTTP_SEE_OTHER = 303;
{$EXTERNALSYM HTTP_SEE_OTHER}
HTTP_NOT_MODIFIED = 304;
{$EXTERNALSYM HTTP_NOT_MODIFIED}
HTTP_USE_PROXY = 305;
{$EXTERNALSYM HTTP_USE_PROXY}
HTTP_TEMPORARY_REDIRECT = 307;
{$EXTERNALSYM HTTP_TEMPORARY_REDIRECT}
HTTP_BAD_REQUEST = 400;
{$EXTERNALSYM HTTP_BAD_REQUEST}
HTTP_UNAUTHORIZED = 401;
{$EXTERNALSYM HTTP_UNAUTHORIZED}
HTTP_PAYMENT_REQUIRED = 402;
{$EXTERNALSYM HTTP_PAYMENT_REQUIRED}
HTTP_FORBIDDEN = 403;
{$EXTERNALSYM HTTP_FORBIDDEN}
HTTP_NOT_FOUND = 404;
{$EXTERNALSYM HTTP_NOT_FOUND}
HTTP_METHOD_NOT_ALLOWED = 405;
{$EXTERNALSYM HTTP_METHOD_NOT_ALLOWED}
HTTP_NOT_ACCEPTABLE = 406;
{$EXTERNALSYM HTTP_NOT_ACCEPTABLE}
HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
{$EXTERNALSYM HTTP_PROXY_AUTHENTICATION_REQUIRED}
HTTP_REQUEST_TIME_OUT = 408;
{$EXTERNALSYM HTTP_REQUEST_TIME_OUT}
HTTP_CONFLICT = 409;
{$EXTERNALSYM HTTP_CONFLICT}
HTTP_GONE = 410;
{$EXTERNALSYM HTTP_GONE}
HTTP_LENGTH_REQUIRED = 411;
{$EXTERNALSYM HTTP_LENGTH_REQUIRED}
HTTP_PRECONDITION_FAILED = 412;
{$EXTERNALSYM HTTP_PRECONDITION_FAILED}
HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
{$EXTERNALSYM HTTP_REQUEST_ENTITY_TOO_LARGE}
HTTP_REQUEST_URI_TOO_LARGE = 414;
{$EXTERNALSYM HTTP_REQUEST_URI_TOO_LARGE}
HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
{$EXTERNALSYM HTTP_UNSUPPORTED_MEDIA_TYPE}
HTTP_RANGE_NOT_SATISFIABLE = 416;
{$EXTERNALSYM HTTP_RANGE_NOT_SATISFIABLE}
HTTP_EXPECTATION_FAILED = 417;
{$EXTERNALSYM HTTP_EXPECTATION_FAILED}
HTTP_UNPROCESSABLE_ENTITY = 422;
{$EXTERNALSYM HTTP_UNPROCESSABLE_ENTITY}
HTTP_LOCKED = 423;
{$EXTERNALSYM HTTP_LOCKED}
HTTP_FAILED_DEPENDENCY = 424;
{$EXTERNALSYM HTTP_FAILED_DEPENDENCY}
HTTP_INTERNAL_SERVER_ERROR = 500;
{$EXTERNALSYM HTTP_INTERNAL_SERVER_ERROR}
HTTP_NOT_IMPLEMENTED = 501;
{$EXTERNALSYM HTTP_NOT_IMPLEMENTED}
HTTP_BAD_GATEWAY = 502;
{$EXTERNALSYM HTTP_BAD_GATEWAY}
HTTP_SERVICE_UNAVAILABLE = 503;
{$EXTERNALSYM HTTP_SERVICE_UNAVAILABLE}
HTTP_GATEWAY_TIME_OUT = 504;
{$EXTERNALSYM HTTP_GATEWAY_TIME_OUT}
HTTP_VERSION_NOT_SUPPORTED = 505;
{$EXTERNALSYM HTTP_VERSION_NOT_SUPPORTED}
HTTP_VARIANT_ALSO_VARIES = 506;
{$EXTERNALSYM HTTP_VARIANT_ALSO_VARIES}
HTTP_INSUFFICIENT_STORAGE = 507;
{$EXTERNALSYM HTTP_INSUFFICIENT_STORAGE}
HTTP_NOT_EXTENDED = 510;
{$EXTERNALSYM HTTP_NOT_EXTENDED}
// backward compatibility codes
DOCUMENT_FOLLOWS = HTTP_OK;
{$EXTERNALSYM DOCUMENT_FOLLOWS}
PARTIAL_CONTENT = HTTP_PARTIAL_CONTENT;
{$EXTERNALSYM PARTIAL_CONTENT}
MULTIPLE_CHOICES = HTTP_MULTIPLE_CHOICES;
{$EXTERNALSYM MULTIPLE_CHOICES}
MOVED = HTTP_MOVED_PERMANENTLY;
{$EXTERNALSYM MOVED}
REDIRECT = HTTP_MOVED_TEMPORARILY;
{$EXTERNALSYM REDIRECT}
USE_LOCAL_COPY = HTTP_NOT_MODIFIED;
{$EXTERNALSYM USE_LOCAL_COPY}
BAD_REQUEST = HTTP_BAD_REQUEST;
{$EXTERNALSYM BAD_REQUEST}
AUTH_REQUIRED = HTTP_UNAUTHORIZED;
{$EXTERNALSYM AUTH_REQUIRED}
FORBIDDEN = HTTP_FORBIDDEN;
{$EXTERNALSYM FORBIDDEN}
NOT_FOUND = HTTP_NOT_FOUND;
{$EXTERNALSYM NOT_FOUND}
METHOD_NOT_ALLOWED = HTTP_METHOD_NOT_ALLOWED;
{$EXTERNALSYM METHOD_NOT_ALLOWED}
NOT_ACCEPTABLE = HTTP_NOT_ACCEPTABLE;
{$EXTERNALSYM NOT_ACCEPTABLE}
LENGTH_REQUIRED = HTTP_LENGTH_REQUIRED;
{$EXTERNALSYM LENGTH_REQUIRED}
PRECONDITION_FAILED = HTTP_PRECONDITION_FAILED;
{$EXTERNALSYM PRECONDITION_FAILED}
SERVER_ERROR = HTTP_INTERNAL_SERVER_ERROR;
{$EXTERNALSYM SERVER_ERROR}
NOT_IMPLEMENTED = HTTP_NOT_IMPLEMENTED;
{$EXTERNALSYM NOT_IMPLEMENTED}
BAD_GATEWAY = HTTP_BAD_GATEWAY;
{$EXTERNALSYM BAD_GATEWAY}
VARIANT_ALSO_VARIES = HTTP_VARIANT_ALSO_VARIES;
{$EXTERNALSYM VARIANT_ALSO_VARIES}
// Error Level constants
// APLOG_MARK = __FILE__, __LINE__
APLOG_EMERG = 0; ///* system is unusable */
{$EXTERNALSYM APLOG_EMERG}
APLOG_ALERT = 1; ///* action must be taken immediately */
{$EXTERNALSYM APLOG_ALERT}
APLOG_CRIT = 2; ///* critical conditions */
{$EXTERNALSYM APLOG_CRIT}
APLOG_ERR = 3; ///* error conditions */
{$EXTERNALSYM APLOG_ERR}
APLOG_WARNING = 4; ///* warning conditions */
{$EXTERNALSYM APLOG_WARNING}
APLOG_NOTICE = 5; ///* normal but significant condition */
{$EXTERNALSYM APLOG_NOTICE}
APLOG_INFO = 6; ///* informational */
{$EXTERNALSYM APLOG_INFO}
APLOG_DEBUG = 7; ///* debug-level messages */
{$EXTERNALSYM APLOG_DEBUG}
APLOG_LEVELMASK = 7; ///* mask off the level value */
{$EXTERNALSYM APLOG_LEVELMASK}
APLOG_NOERRNO = (APLOG_LEVELMASK + 1);
{$EXTERNALSYM APLOG_NOERRNO}
APLOG_WIN32ERROR = ((APLOG_LEVELMASK + 1) * 2);
{$EXTERNALSYM APLOG_WIN32ERROR}
type
ap_pchar = pchar; // char *
{$EXTERNALSYM ap_pchar}
ap_ppchar = ^ap_pchar; // char **
ap_constpchar = pchar; // const char *
{$EXTERNALSYM ap_constpchar}
ap_punsignedchar = ^byte; // unsigned char *
ap_short = smallint; // short
{$EXTERNALSYM ap_short}
ap_pshort = ^ap_short; // short *
ap_unsignedshort = word; // unsigned short
{$EXTERNALSYM ap_unsignedshort}
ap_int = integer; // int
{$EXTERNALSYM ap_int}
ap_unsigned = cardinal; // unsigned
{$EXTERNALSYM ap_unsigned}
ap_long = longint; // long
{$EXTERNALSYM ap_long}
ap_unsignedlong = longword; // unsigned long
{$EXTERNALSYM ap_unsignedlong}
ap_pFILE = pointer; // FILE *
{$EXTERNALSYM ap_pFILE}
ap_ppFILE = ^ap_pFILE; // FILE **
ap_pvoid = pointer; // void *
{$EXTERNALSYM ap_pvoid}
// pending ...
Ppool = pointer; // pool *
{$EXTERNALSYM Ppool}
Ptable = pointer; // table *
{$EXTERNALSYM Ptable}
Pserver_addr_rec = pointer; // server_addr_rec *
{$EXTERNALSYM Pserver_addr_rec}
Parray_header = pointer; // array_header *
{$EXTERNALSYM Parray_header}
Pregmatch_t = pointer; // regmatch_t *
{$EXTERNALSYM Pregmatch_t}
Pchild_info = pointer; // child_info *
{$EXTERNALSYM Pchild_info}
AP_PMD5_CTX = pointer; // AP_MD5_CTX *
{$EXTERNALSYM AP_PMD5_CTX}
Ptm = pointer; // tm *
{$EXTERNALSYM Ptm}
uid_t = integer; // system type
{$EXTERNALSYM uid_t}
gid_t = integer; // system type
{$EXTERNALSYM gid_t}
time_t = longint; // system type
{$EXTERNALSYM time_t}
size_t = integer; // system type
{$EXTERNALSYM size_t}
ap_Ppool = Ppool;
{$EXTERNALSYM ap_Ppool}
Phostent = pointer;
{$EXTERNALSYM Phostent}
///* The allowed locations for a configuration directive are the union of
// * those indicated by each set bit in the req_override mask.
// *
// * (req_override & RSRC_CONF) => *.conf outside <Directory> or <Location>
// * (req_override & ACCESS_CONF) => *.conf inside <Directory> or <Location>
// * (req_override & OR_AUTHCFG) => *.conf inside <Directory> or<Location>
// * and .htaccess when AllowOverride AuthConfig
// * (req_override & OR_LIMIT) => *.conf inside <Directory> or <Location>
// * and .htaccess when AllowOverride Limit
// * (req_override & OR_OPTIONS) => *.conf anywhere
// * and .htaccess when AllowOverride Options
// * (req_override & OR_FILEINFO) => *.conf anywhere
// * and .htaccess when AllowOverride FileInfo
// * (req_override & OR_INDEXES) => *.conf anywhere
// * and .htaccess when AllowOverride Indexes
// */
const
OR_NONE = 0;
{$EXTERNALSYM OR_NONE}
OR_LIMIT = 1;
{$EXTERNALSYM OR_LIMIT}
OR_OPTIONS = 2;
{$EXTERNALSYM OR_OPTIONS}
OR_FILEINFO = 4;
{$EXTERNALSYM OR_FILEINFO}
OR_AUTHCFG = 8;
{$EXTERNALSYM OR_AUTHCFG}
OR_INDEXES = 16;
{$EXTERNALSYM OR_INDEXES}
OR_UNSET = 32;
{$EXTERNALSYM OR_UNSET}
ACCESS_CONF = 64;
{$EXTERNALSYM ACCESS_CONF}
RSRC_CONF = 128;
{$EXTERNALSYM RSRC_CONF}
OR_ALL = (OR_LIMIT or OR_OPTIONS or OR_FILEINFO or OR_AUTHCFG or OR_INDEXES);
{$EXTERNALSYM OR_ALL}
type
{$EXTERNALSYM Pstat}
Pstat = ^stat;
{$EXTERNALSYM stat}
stat = packed record
st_dev: Word;
st_ino: Word;
st_mode: Word;
st_nlink: SmallInt;
st_uid: SmallInt;
st_gid: SmallInt;
st_rdev: Word;
st_size: Longint;
st_atime: Longint;
st_mtime: Longint;
st_ctime: Longint;
end;
// Apache data structures ======================================================
Puri_components = ^uri_components;
{$EXTERNALSYM uri_components}
uri_components = packed record
scheme: pchar; ///* scheme ("http"/"ftp"/...) */
hostinfo: pchar; ///* combined [user[:password]@]host[:port] */
user: pchar; ///* user name, as in http://user:passwd@host:port/ */
password: pchar; ///* password, as in http://user:passwd@host:port/ */
hostname: pchar; ///* hostname from URI (or from Host: header) */
port_str: pchar; ///* port string (integer representation is in "port") */
path: pchar; ///* the request path (or "/" if only scheme://host was given) */
query: pchar; ///* Everything after a '?' in the path, if present */
fragment: pchar; ///* Trailing "#fragment" string, if present */
hostent: Phostent;
port: word; ///* The port number, numeric, valid only if port_str != NULL */
is_initialized: cardinal; // = 1;
dns_looked_up: cardinal; // = 1;
dns_resolved: cardinal; // = 1;
end;
///* Things which may vary per file-lookup WITHIN a request ---
// * e.g., state of MIME config. Basically, the name of an object, info
// * about the object, and any other info we may ahve which may need to
// * change as we go poking around looking for it (e.g., overridden by
// * .htaccess files).
// *
// * Note how the default state of almost all these things is properly
// * zero, so that allocating it with pcalloc does the right thing without
// * a whole lot of hairy initialization... so long as we are willing to
// * make the (fairly) portable assumption that the bit pattern of a NULL
// * pointer is, in fact, zero.
// */
///* This represents the result of calling htaccess; these are cached for
// * each request.
// */
Phtaccess_result = ^htaccess_result;
{$EXTERNALSYM htaccess_result}
htaccess_result = packed record
dir: ap_pchar; ///* the directory to which this applies */
override: ap_int; ///* the overrides allowed for the .htaccess file */
htaccess: ap_pvoid; ///* the configuration directives */
///* the next one, or NULL if no more; N.B. never change this */
next: Phtaccess_result;
end;
{$EXTERNALSYM PSPerServer}
PSPerServer = ^SPerServer;
{$EXTERNALSYM SPerServer}
SPerServer = packed record
szServer: ap_pchar;
szTag: ap_pchar;
end;
Pserver_rec = ^server_rec;
{$EXTERNALSYM server_rec}
server_rec = packed record
next: Pserver_rec;
///* description of where the definition came from */
defn_name: ap_constpchar;
defn_line_number: ap_unsigned;
///* Full locations of server config info */
srm_confname: ap_pchar;
access_confname: ap_pchar;
///* Contact information */
server_admin: ap_pchar;
server_hostname: ap_pchar;
port: ap_unsignedshort; ///* for redirects, etc. */
///* Log files --- note that transfer log is now in the modules... */
error_fname: ap_pchar;
error_log: ap_pFILE;
loglevel: ap_int;
///* Module-specific configuration for server, and defaults... */
is_virtual: ap_int; ///* true if this is the virtual server */
module_config: ap_pvoid; ///* Config vector containing pointers to
// * modules' per-server config structures.
// */
lookup_defaults: ap_pvoid; ///* MIME type info, etc., before we start
// * checking per-directory info.
// */
///* Transaction handling */
addrs: Pserver_addr_rec;
timeout: ap_int; ///* Timeout, in seconds, before we give up */
keep_alive_timeout: ap_int; ///* Seconds we'll wait for another request */
keep_alive_max: ap_int; ///* Maximum requests per connection */
keep_alive: ap_int; ///* Use persistent connections? */
send_buffer_size: ap_int; ///* size of TCP send buffer (in bytes) */
path: ap_pchar; ///* Pathname for ServerPath */
pathlen: ap_int; ///* Length of path */
names: Parray_header; ///* Normal names for ServerAlias servers */
wild_names: Parray_header; ///* Wildcarded names for ServerAlias servers */
server_uid: uid_t; ///* effective user id when calling exec wrapper */
server_gid: gid_t; ///* effective group id when calling exec wrapper */
limit_req_line: ap_int; ///* limit on size of the HTTP request line */
limit_req_fieldsize: ap_int; ///* limit on size of any request header field */
limit_req_fields: ap_int; ///* limit on number of request header fields */
end;
{$EXTERNALSYM PSPerDir}
PSPerDir = ^SPerDir;
{$EXTERNALSYM SPerDir}
SPerDir = packed record
szDir: ap_pchar;
szTag: ap_pchar;
end;
{$EXTERNALSYM BUFF}
PBUFF = ^BUFF; // BUFF *
PPBUFF = ^PBUFF; // BUFF **
BUFF = packed record
end;
Pconn_rec = ^conn_rec;
{$EXTERNALSYM conn_rec}
conn_rec = packed record
pool: ap_Ppool;
server: Pserver_rec;
base_server: Pserver_rec; ///* Physical vhost this conn come in on */
vhost_lookup_data: ap_pvoid; ///* used by http_vhost.c */
///* Information about the connection itself */
child_num: integer; ///* The number of the child handling conn_rec */
client: PBUFF; ///* Connection to the guy */
///* Who is the client? */
local_addr: sockaddr_in; ///* local address */
remote_addr: sockaddr_in; ///* remote address */
remote_ip: ap_pchar; ///* Client's IP address */
remote_host: ap_pchar; ///* Client's DNS name, if known.
// * NULL if DNS hasn't been checked,
// * "" if it has and no address was found.
// * N.B. Only access this though
// * get_remote_host() */
remote_logname: ap_pchar; ///* Only ever set if doing rfc1413 lookups.
// * N.B. Only access this through
// * get_remote_logname() */
user: ap_pchar; ///* If an authentication check was made,
// * this gets set to the user name. We assume
// * that there's only one user per connection(!)
// */
ap_auth_type: ap_pchar; ///* Ditto. */
flags: integer;
///* Are we still talking? */
///* Are we using HTTP Keep-Alive?
// * -1 fatal error, 0 undecided, 1 yes */
///* Did we use HTTP Keep-Alive? */
///* have we done double-reverse DNS?
// * -1 yes/failure, 0 not yet, 1 yes/success */
keepalives: integer; ///* How many times have we used it? */
local_ip: ap_pchar; ///* server IP address */
local_host: ap_pchar; ///* used for ap_get_server_name when
// * UseCanonicalName is set to DNS
// * (ignores setting of HostnameLookups) */
end;
Prequest_rec = ^request_rec;
{$EXTERNALSYM request_rec}
request_rec = packed record
pool: ap_Ppool;
connection: Pconn_rec;
server: Pserver_rec;
next: Prequest_rec; ///* If we wind up getting redirected,
// * pointer to the request we redirected to.
// */
prev: Prequest_rec; ///* If this is an internal redirect,
// * pointer to where we redirected *from*.
// */
main: Prequest_rec; ///* If this is a sub_request (see request.h)
// * pointer back to the main request.
// */
///* Info about the request itself... we begin with stuff that only
// * protocol.c should ever touch...
// */
the_request: ap_pchar; ///* First line of request, so we can log it */
backwards: ap_int; ///* HTTP/0.9, "simple" request */
proxyreq: ap_int; ///* A proxy request (calculated during
// * post_read_request or translate_name) */
header_only: ap_int; ///* HEAD request, as opposed to GET */
protocol: ap_pchar; ///* Protocol, as given to us, or HTTP/0.9 */
proto_num: ap_int; ///* Number version of protocol; 1.1 = 1001 */
hostname: ap_constpchar; ///* Host, as set by full URI or Host: */
request_time: time_t; ///* When the request started */
status_line: ap_constpchar; ///* Status line, if set by script */
status: ap_int; ///* In any case */
///* Request method, two ways; also, protocol, etc.. Outside of protocol.c,
// * look, but don't touch.
// */
method: ap_constpchar; ///* GET, HEAD, POST, etc. */
method_number: ap_int; ///* M_GET, M_POST, etc. */
///*
// allowed is a bitvector of the allowed methods.
// A handler must ensure that the request method is one that
// it is capable of handling. Generally modules should DECLINE
// any request methods they do not handle. Prior to aborting the
// handler like this the handler should set r->allowed to the list
// of methods that it is willing to handle. This bitvector is used
// to construct the "Allow:" header required for OPTIONS requests,
// and METHOD_NOT_ALLOWED and NOT_IMPLEMENTED status codes.
// Since the default_handler deals with OPTIONS, all modules can
// usually decline to deal with OPTIONS. TRACE is always allowed,
// modules don't need to set it explicitly.
// Since the default_handler will always handle a GET, a
// module which does *not* implement GET should probably return
// METHOD_NOT_ALLOWED. Unfortunately this means that a Script GET
// handler can't be installed by mod_actions.
//*/
allowed: ap_int; ///* Allowed methods - for 405, OPTIONS, etc */
sent_bodyct: ap_int; ///* byte count in stream is for body */
bytes_sent: ap_long; ///* body byte count, for easy access */
mtime: time_t; ///* Time the resource was last modified */
///* HTTP/1.1 connection-level features */
chunked: ap_int; ///* sending chunked transfer-coding */
byterange: ap_int; ///* number of byte ranges */
boundary: ap_pchar; ///* multipart/byteranges boundary */
range: ap_constpchar; ///* The Range: header */
clength: ap_long; ///* The "real" content length */
remaining: ap_long; ///* bytes left to read */
read_length: ap_long; ///* bytes that have been read */
read_body: ap_int; ///* how the request body should be read */
read_chunked: ap_int; ///* reading chunked transfer-coding */
expecting_100: ap_unsigned; ///* is client waiting for a 100 response? */
///* MIME header environments, in and out. Also, an array containing
// * environment variables to be passed to subprocesses, so people can
// * write modules to add to that environment.
// *
// * The difference between headers_out and err_headers_out is that the
// * latter are printed even on error, and persist across internal redirects
// * (so the headers printed for ErrorDocument handlers will have them).
// *
// * The 'notes' table is for notes from one module to another, with no
// */ other set purpose in mind...
// */
headers_in: Ptable;
headers_out: Ptable;
err_headers_out: Ptable;
subprocess_env: Ptable;
notes: Ptable;
///* content_type, handler, content_encoding, content_language, and all
// * content_languages MUST be lowercased strings. They may be pointers
// * to static strings; they should not be modified in place.
// */
content_type: ap_constpchar; ///* Break these out --- we dispatch on 'em */
handler: ap_constpchar; ///* What we *really* dispatch on */
content_encoding: ap_constpchar;
content_language: ap_constpchar; ///* for back-compat. only -- do not use */
content_languages: Parray_header; ///* array of (char*) */
vlist_validator: ap_pchar; ///* variant list validator (if negotiated) */
no_cache: ap_int;
no_local_copy: ap_int;
///* What object is being requested (either directly, or via include
// * or content-negotiation mapping).
// */
unparsed_uri: ap_pchar; ///* the uri without any parsing performed */
uri: ap_pchar; ///* the path portion of the URI */
filename: ap_pchar;
path_info: ap_pchar;
args: ap_pchar; ///* QUERY_ARGS, if any */
finfo: stat; ///* ST_MODE set to zero if no such file */
parsed_uri: uri_components; ///* components of uri, dismantled */
///* Various other config info which may change with .htaccess files
// * These are config vectors, with one void* pointer for each module
// * (the thing pointed to being the module's business).
// */
per_dir_config: ap_pvoid; ///* Options set in config files, etc. */
request_config: ap_pvoid; ///* Notes on *this* request */
///*
// * a linked list of the configuration directives in the .htaccess files
// * accessed by this request.
// * N.B. always add to the head of the list, _never_ to the end.
// * that way, a sub request's list can (temporarily) point to a parent's list
// */
htaccess: Phtaccess_result; // pointer to constant. * gcm *
///* Things placed at the end of the record to avoid breaking binary
// * compatibility. It would be nice to remember to reorder the entire
// * record to improve 64bit alignment the next time we need to break
// * binary compatibility for some other reason.
// */
end;
///* Note that for all of these except RAW_ARGS, the config routine is
// * passed a freshly allocated string which can be modified or stored
// * or whatever... it's only necessary to do pstrdup() stuff with
// * RAW_ARGS.
// */
{$EXTERNALSYM cmd_how}
cmd_how = (
RAW_ARGS, ///* cmd_func parses command line itself */
TAKE1, ///* one argument only */
TAKE2, ///* two arguments only */
ITERATE, ///* one argument, occuring multiple times
// * (e.g., IndexIgnore)
// */
ITERATE2, ///* two arguments, 2nd occurs multiple times
// * (e.g., AddIcon)
// */
FLAG, ///* One of 'On' or 'Off' */
NO_ARGS, ///* No args at all, e.g. </Directory> */
TAKE12, ///* one or two arguments */
TAKE3, ///* three arguments only */
TAKE23, ///* two or three arguments */
TAKE123, ///* one, two or three arguments */
TAKE13 ///* one or three arguments */
);
TCommandFunc = function : pchar;
{$EXTERNALSYM TCommandFunc}
Pcommand_rec = ^command_rec;
{$EXTERNALSYM command_rec}
command_rec = packed record
name: pchar; ///* Name of this command */
func: TCommandFunc; ///* Function invoked */
cmd_data: pointer; ///* Extra data, for functions which
// * implement multiple commands...
// */
req_override: integer; ///* What overrides need to be allowed to
// * enable this command.
// */
args_how: cmd_how; ///* What the command expects as arguments */
errmsg: pchar; ///* 'usage' message, in case of syntax errors */
end;
///* This structure records the existence of handlers in a module... */
THandlerFunc = function (rr: Prequest_rec): integer; cdecl;
{$EXTERNALSYM THandlerFunc}
Phandler_rec = ^handler_rec;
{$EXTERNALSYM handler_rec}
handler_rec = packed record
content_type: pchar; ///* MUST be all lower case */
handler: THandlerFunc;
end;
Pmodule = ^module_struct;
{$EXTERNALSYM module_struct}
module_struct = packed record
version: integer; ///* API version, *not* module version;
// * check that module is compatible with this
// * version of the server.
// */
minor_version: integer; ///* API minor version. Provides API feature
// * milestones. Not checked during module init
// */
module_index: integer; ///* Index to this modules structures in
// * config vectors.
// */
name: pchar;
dynamic_load_handle: pointer;
next: Pmodule;
magic: integer; ///* Magic Cookie to identify a module structure;
// * It's mainly important for the DSO facility
// * (see also mod_so).
// */
///* init() occurs after config parsing, but before any children are
// * forked.
// * Modules should not rely on the order in which create_server_config
// * and create_dir_config are called.
// */
init: procedure (s: Pserver_rec; p: Ppool); cdecl;
create_dir_config: function (p: Ppool; dir: pchar): pointer; cdecl;
merge_dir_config: function (p: Ppool; base_conf, new_conf: pointer): pointer; cdecl;
create_server_config: function (p: Ppool; s: Pserver_rec): pointer; cdecl;
merge_server_config: function (p: Ppool; base_conf, new_conf: pointer): pointer; cdecl;
cmds: Pcommand_rec;
handlers: Phandler_rec;
///* Hooks for getting into the middle of server ops...
// * translate_handler --- translate URI to filename
// * access_checker --- check access by host address, etc. All of these
// * run; if all decline, that's still OK.
// * check_user_id --- get and validate user id from the HTTP request
// * auth_checker --- see if the user (from check_user_id) is OK *here*.
// * If all of *these* decline, the request is rejected
// * (as a SERVER_ERROR, since the module which was
// * supposed to handle this was configured wrong).
// * type_checker --- Determine MIME type of the requested entity;
// * sets content_type, _encoding and _language fields.
// * logger --- log a transaction.
// * post_read_request --- run right after read_request or internal_redirect,
// * and not run during any subrequests.
// */
translate_handler: THandlerFunc;
ap_check_user_id: THandlerFunc;
auth_checker: THandlerFunc;
access_checker: THandlerFunc;
type_checker: THandlerFunc;
fixer_upper: THandlerFunc;
logger: THandlerFunc;
header_parser: THandlerFunc;
//* Regardless of the model the server uses for managing "units of
// * execution", i.e. multi-process, multi-threaded, hybrids of those,
// * there is the concept of a "heavy weight process". That is, a
// * process with its own memory space, file spaces, etc. This method,
// * child_init, is called once for each heavy-weight process before
// * any requests are served. Note that no provision is made yet for
// * initialization per light-weight process (i.e. thread). The
// * parameters passed here are the same as those passed to the global
// * init method above.
// */
child_init: procedure (s: Pserver_rec; p: Ppool); cdecl;
child_exit: procedure (s: Pserver_rec; p: Ppool); cdecl;
post_read_request: function (r: Prequest_rec): integer; cdecl;
end;
{$EXTERNALSYM module}
module = module_struct;
TCompFunc = function (rec: ap_pvoid; const key, value: ap_pchar): ap_int;
{$EXTERNALSYM TCompFunc}
TCleanupFunc = procedure (p: ap_pvoid);
{$EXTERNALSYM TCleanupFunc}
TSpawnFunc = procedure (p: ap_pvoid; ci: Pchild_info);
{$EXTERNALSYM TSpawnFunc}
TbSpawnFunc = function (p: ap_pvoid; ci: Pchild_info): ap_int;
{$EXTERNALSYM TbSpawnFunc}
Pregex_t = ^regex_t;
{$EXTERNALSYM regex_t}
regex_t = packed record
re_magic: ap_int;
re_nsub: size_t; ///* number of parenthesized subexpressions */
re_endp: ap_pchar; ///* end pointer for REG_PEND */
re_g: pointer; ///* none of your business :-) */
end;
{$EXTERNALSYM kill_conditions}
kill_conditions = (
kill_never, ///* process is never sent any signals */
kill_always, ///* process is sent SIGKILL on pool cleanup */
kill_after_timeout, ///* SIGTERM, wait 3 seconds, SIGKILL */
just_wait, ///* wait forever for the process to complete */
kill_only_once ///* send SIGTERM and then wait */
);
///* Common structure for reading of config files / passwd files etc. */
Pconfigfile_t = ^configfile_t;
{$EXTERNALSYM configfile_t}
configfile_t = packed record
///* a getc()-like function */
getch: function (param: ap_pvoid): integer;
///* a fgets()-like function */
getstr: function (buf: ap_pvoid; bufsiz: size_t; param: ap_pvoid): ap_pvoid;
///* a close hander function */
close: function (param: ap_pvoid): integer;
param: ap_pvoid; ///* the argument passed to getch/getstr/close */
filename: ap_constpchar; ///* the filename / description */
line_number: ap_unsigned; ///* current line number, starting at 1 */
end;
///*
// * This structure is passed to a command which is being invoked,
// * to carry a large variety of miscellaneous data which is all of
// * use to *somebody*...
// */
type
Pcmd_parms = ^cmd_parms;
{$EXTERNALSYM cmd_parms}
cmd_parms = record
info: pointer; ///* Argument to command from cmd_table */
override: ap_int; ///* Which allow-override bits are set */
limited: ap_int; ///* Which methods are <Limit>ed */
config_file: Pconfigfile_t; ///* Config file structure from pcfg_openfile() */
pool: Ppool; ///* Pool to allocate new storage in */
temp_pool: Ppool; ///* Pool for scratch memory; persists during
// * configuration, but wiped before the first
// * request is served...
// */
server: Pserver_rec; ///* Server_rec being configured for */
path: PChar; ///* If configuring for a directory,
// * pathname of that directory.
// * NOPE! That's what it meant previous to the
// * existance of <Files>, <Location> and regex
// * matching. Now the only usefulness that can
// * be derived from this field is whether a command
// * is being called in a server context (path == NULL)
// * or being called in a dir context (path != NULL).
// */
cmd: Pcommand_rec; ///* configuration command */
end_token: PChar; ///* end token required to end a nested section */
context: Pointer; ///* per_dir_config vector passed
// * to handle_command */
end;
// HTTP status info
{$EXTERNALSYM ap_is_HTTP_INFO}
function ap_is_HTTP_INFO(x: ap_int): boolean;
{$EXTERNALSYM ap_is_HTTP_SUCCESS}
function ap_is_HTTP_SUCCESS(x: ap_int): boolean;
{$EXTERNALSYM ap_is_HTTP_REDIRECT}
function ap_is_HTTP_REDIRECT(x: ap_int): boolean;
{$EXTERNALSYM ap_is_HTTP_ERROR}
function ap_is_HTTP_ERROR(x: ap_int): boolean;
{$EXTERNALSYM ap_is_HTTP_CLIENT_ERROR}
function ap_is_HTTP_CLIENT_ERROR(x: ap_int): boolean;
{$EXTERNALSYM ap_is_HTTP_SERVER_ERROR}
function ap_is_HTTP_SERVER_ERROR(x: ap_int): boolean;
{$IFDEF MSWINDOWS}
// Pool functions
{$EXTERNALSYM ap_make_sub_pool}
function ap_make_sub_pool(p: Ppool): Ppool; stdcall;
{$EXTERNALSYM ap_clear_pool}
procedure ap_clear_pool(p: Ppool); stdcall;
{$EXTERNALSYM ap_destroy_pool}
procedure ap_destroy_pool(p: Ppool); stdcall;
{$EXTERNALSYM ap_bytes_in_pool}
function ap_bytes_in_pool(p: Ppool): ap_long; stdcall;
{$EXTERNALSYM ap_bytes_in_free_blocks}
function ap_bytes_in_free_blocks: ap_long; stdcall;
{$EXTERNALSYM ap_palloc}
function ap_palloc(p: Ppool; size: ap_int): ap_pvoid; stdcall;
{$EXTERNALSYM ap_pcalloc}
function ap_pcalloc(p: Ppool; size: ap_int): ap_pvoid; stdcall;
{$EXTERNALSYM ap_pstrdup}
function ap_pstrdup(p: Ppool; const s: ap_pchar): ap_pchar; stdcall;
{$EXTERNALSYM ap_pstrndup}
function ap_pstrndup(p: Ppool; const s: ap_pchar; n: ap_int): ap_pchar; stdcall;
// function ap_pstrcat(p: Ppool; ..): ap_pchar; stdcall;
// Array functions
{$EXTERNALSYM ap_make_array}
function ap_make_array(p: Ppool; nelts, elt_size: ap_int): Parray_header; stdcall;
{$EXTERNALSYM ap_push_array}
function ap_push_array(arr: Parray_header): ap_pvoid; stdcall;
{$EXTERNALSYM ap_array_cat}
procedure ap_array_cat(dst: Parray_header; const src: Parray_header); stdcall;
{$EXTERNALSYM ap_copy_array}
function ap_copy_array(p: Ppool; const arr: Parray_header): Parray_header; stdcall;
{$EXTERNALSYM ap_copy_array_hdr}
function ap_copy_array_hdr(p: Ppool; const arr: Parray_header): Parray_header; stdcall;
{$EXTERNALSYM ap_append_arrays}
function ap_append_arrays(p: Ppool; const first, second: Parray_header): Parray_header; stdcall;
// Table functions
{$EXTERNALSYM ap_make_table}
function ap_make_table(p: Ppool; nelts: ap_int): Ptable; stdcall;
{$EXTERNALSYM ap_copy_table}
function ap_copy_table(p: Ppool; const t: Ptable): Ptable; stdcall;
{$EXTERNALSYM ap_table_elts}
function ap_table_elts(t: Ptable): Parray_header; stdcall;
{$EXTERNALSYM ap_is_empty_table}
function ap_is_empty_table(t: Ptable): ap_int; stdcall;
{$EXTERNALSYM ap_table_set}
procedure ap_table_set(t: Ptable; const key, value: pchar); stdcall;
{$EXTERNALSYM ap_table_setn}
procedure ap_table_setn(t: Ptable; const key, value: pchar); stdcall;
{$EXTERNALSYM ap_table_merge}
procedure ap_table_merge(t: Ptable; const key, value: pchar); stdcall;
{$EXTERNALSYM ap_table_mergen}
procedure ap_table_mergen(t: Ptable; const key, value: pchar); stdcall;
{$EXTERNALSYM ap_table_add}
procedure ap_table_add(t: Ptable; const key, value: pchar); stdcall;
{$EXTERNALSYM ap_table_addn}
procedure ap_table_addn(t: Ptable; const key, value: pchar); stdcall;
{$EXTERNALSYM ap_table_unset}
procedure ap_table_unset(t: Ptable; const key: pchar); stdcall;
{$EXTERNALSYM ap_table_get}
function ap_table_get(t: Ptable; const key: pchar): ap_constpchar; stdcall;
{$EXTERNALSYM ap_table_do}
procedure ap_table_do(comp: TCompFunc; rec: ap_pvoid; const t: Ptable; tag: ap_pchar = nil); stdcall;
{$EXTERNALSYM ap_overlay_tables}
function ap_overlay_tables(p: Ppool; const overlay, base: Ptable): Ptable; stdcall;
{$EXTERNALSYM ap_clear_table}
procedure ap_clear_table(t: Ptable); stdcall;
// Cleanup functions
{$EXTERNALSYM ap_register_cleanup}
procedure ap_register_cleanup(p: Ppool; data: ap_pvoid; plain_cleanup, child_cleanup: TCleanupFunc); stdcall;
{$EXTERNALSYM ap_kill_cleanup}
procedure ap_kill_cleanup(p: Ppool; data: ap_pvoid; plain_cleanup: TCleanupFunc); stdcall;
{$EXTERNALSYM ap_cleanup_for_exec}
procedure ap_cleanup_for_exec; stdcall;
{$EXTERNALSYM ap_note_cleanups_for_fd}
procedure ap_note_cleanups_for_fd(p: Ppool; fd: ap_int); stdcall;
{$EXTERNALSYM ap_kill_cleanups_for_fd}
procedure ap_kill_cleanups_for_fd(p: Ppool; fd: ap_int); stdcall;
{$EXTERNALSYM ap_note_cleanups_for_socket}
procedure ap_note_cleanups_for_socket(p: Ppool; fd: ap_int); stdcall;
{$EXTERNALSYM ap_kill_cleanups_for_socket}
procedure ap_kill_cleanups_for_socket(p: Ppool; fd: ap_int); stdcall;
{$EXTERNALSYM ap_note_cleanups_for_file}
procedure ap_note_cleanups_for_file(p: Ppool; f: ap_pFILE); stdcall;
{$EXTERNALSYM ap_run_cleanup}
procedure ap_run_cleanup(p: Ppool; data: ap_pvoid; cleanup: TCleanupFunc); stdcall;
// File and socket functions
{$EXTERNALSYM ap_popenf}
function ap_popenf(p: Ppool; const name: ap_pchar; flg, mode: ap_int): ap_int; stdcall;
{$EXTERNALSYM ap_pclosef}
function ap_pclosef(p: Ppool; fd: ap_int): ap_int; stdcall;
{$EXTERNALSYM ap_pfopen}
function ap_pfopen(p: Ppool; const name, mode: ap_pchar): ap_pFILE; stdcall;
{$EXTERNALSYM ap_pfdopen}
function ap_pfdopen(p: Ppool; fd: ap_int; const mode: ap_pchar): ap_pFILE; stdcall;
{$EXTERNALSYM ap_pfclose}
function ap_pfclose(p: Ppool; fd: ap_pFILE): ap_int; stdcall;
{$EXTERNALSYM ap_psocket}
function ap_psocket(p: Ppool; domain, _type, protocol: ap_int): ap_int; stdcall;
{$EXTERNALSYM ap_pclosesocket}
function ap_pclosesocket(p: Ppool; sock: ap_int): ap_int; stdcall;
// Regular expression functions
{$EXTERNALSYM ap_pregcomp}
function ap_pregcomp(p: Ppool; const pattern: ap_pchar; cflags: ap_int): Pregex_t; stdcall;
{$EXTERNALSYM ap_pregsub}
function ap_pregsub(p: Ppool; const input, source: ap_pchar; nmatch: size_t; pmatch: Pregmatch_t): ap_pchar; stdcall;
{$EXTERNALSYM ap_pregfree}
procedure ap_pregfree(p: Ppool; reg: Pregex_t); stdcall;
{$EXTERNALSYM ap_os_is_path_absolute}
function ap_os_is_path_absolute(const _file: ap_pchar): ap_int; stdcall;
// Process and CGI functions
{$EXTERNALSYM ap_note_subprocess}
procedure ap_note_subprocess(p: Ppool; pid: ap_int; how: kill_conditions); stdcall;
{$EXTERNALSYM ap_spawn_child}
function ap_spawn_child(p: Ppool; func: TSpawnFunc; data: ap_pvoid; how: kill_conditions; pipe_in, pipe_out, pipe_err: ap_ppFILE): ap_int; stdcall;
{$EXTERNALSYM ap_bspawn_child}
function ap_bspawn_child(p: Ppool; func: TbSpawnFunc; data: ap_pvoid; kill_how: kill_conditions; pipe_in, pipe_out, pipe_err: PPBUFF): ap_int; stdcall;
{$EXTERNALSYM ap_call_exec}
function ap_call_exec(r: Prequest_rec; pinfo: Pchild_info; argv0: ap_pchar; env: ap_ppchar; shellcmd: ap_int): ap_int; stdcall;
{$EXTERNALSYM ap_can_exec}
function ap_can_exec(const finfo: Pstat): ap_int; stdcall;
{$EXTERNALSYM ap_add_cgi_vars}
procedure ap_add_cgi_vars(r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_add_common_vars}
procedure ap_add_common_vars(r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_scan_script_header_err}
function ap_scan_script_header_err(r: Prequest_rec; f: ap_pFILE; buffer: ap_pchar): ap_int; stdcall;
{$EXTERNALSYM ap_scan_script_header_err_buff}
function ap_scan_script_header_err_buff(r: Prequest_rec; f: PBUFF; buffer: ap_pchar): ap_int; stdcall;
{$EXTERNALSYM ap_scan_script_header}
function ap_scan_script_header(r: Prequest_rec; f: ap_pFILE): ap_int; stdcall;
// MD5 functions
{$EXTERNALSYM ap_md5}
function ap_md5(p: Ppool; _string: ap_pchar): pchar; stdcall;
{$EXTERNALSYM ap_md5contextTo64}
function ap_md5contextTo64(a: Ppool; context: AP_PMD5_CTX): ap_pchar; stdcall;
{$EXTERNALSYM ap_md5digest}
function ap_md5digest(p: Ppool; infile: ap_pFILE): ap_pchar; stdcall;
{$EXTERNALSYM ap_MD5Init}
procedure ap_MD5Init(context: AP_PMD5_CTX); stdcall;
{$EXTERNALSYM ap_MD5Final}
procedure ap_MD5Final(digest: ap_pchar; context: AP_PMD5_CTX); stdcall;
{$EXTERNALSYM ap_MD5Update}
procedure ap_MD5Update(context: AP_PMD5_CTX; const input: ap_pchar; inputLen: ap_unsigned); stdcall;
// Time and Date functions
{$EXTERNALSYM ap_get_time}
function ap_get_time: ap_pchar; stdcall;
{$EXTERNALSYM ap_ht_time}
function ap_ht_time(p: Ppool; t: time_t; const fmt: ap_pchar; gmt: ap_int): ap_pchar; stdcall;
{$EXTERNALSYM ap_gm_timestr_822}
function ap_gm_timestr_822(p: Ppool; t: time_t): ap_pchar; stdcall;
{$EXTERNALSYM ap_get_gmtoff}
function ap_get_gmtoff(var tz: ap_long): Ptm; stdcall;
{$EXTERNALSYM ap_tm2sec}
function ap_tm2sec(const t: Ptm): time_t; stdcall;
{$EXTERNALSYM ap_parseHTTPdate}
function ap_parseHTTPdate(const date: ap_pchar): time_t; stdcall;
// Path, Filename, and URL Manipulation Fuctions
{$EXTERNALSYM ap_getparents}
procedure ap_getparents(name: ap_pchar); stdcall;
{$EXTERNALSYM ap_no2slash}
procedure ap_no2slash(name: ap_pchar); stdcall;
{$EXTERNALSYM ap_make_dirstr}
function ap_make_dirstr(p: Ppool; const path: ap_pchar; n: ap_int): ap_pchar; stdcall;
{$EXTERNALSYM ap_make_dirstr_parent}
function ap_make_dirstr_parent(p: Ppool; const s: ap_pchar): ap_pchar; stdcall;
{$EXTERNALSYM ap_make_dirstr_prefix}
function ap_make_dirstr_prefix(d: ap_pchar; const s: ap_pchar; n: ap_int): ap_pchar; stdcall;
{$EXTERNALSYM ap_count_dirs}
function ap_count_dirs(const path: ap_pchar): ap_int; stdcall;
{$EXTERNALSYM ap_chdir_file}
procedure ap_chdir_file(const _file: ap_pchar); stdcall;
{$EXTERNALSYM ap_unescape_url}
function ap_unescape_url(url: ap_pchar): ap_int; stdcall;
{$EXTERNALSYM ap_construct_server}
function ap_construct_server(p: Ppool; const hostname: ap_pchar; port: ap_int; r: Prequest_rec): ap_pchar; stdcall;
{$EXTERNALSYM ap_construct_url}
function ap_construct_url(p: Ppool; const uri: ap_pchar; const r: Prequest_rec): ap_pchar; stdcall;
{$EXTERNALSYM ap_escape_path_segment}
function ap_escape_path_segment(p: Ppool; const segment: ap_pchar): ap_pchar; stdcall;
{$EXTERNALSYM ap_os_escape_path}
function ap_os_escape_path(p: Ppool; const path: ap_pchar; partial: ap_int): ap_pchar; stdcall;
{$EXTERNALSYM ap_is_directory}
function ap_is_directory(const path: ap_pchar): ap_int; stdcall;
{$EXTERNALSYM ap_make_full_path}
function ap_make_full_path(p: Ppool; const path1, path2: ap_pchar): ap_pchar; stdcall;
{$EXTERNALSYM ap_is_url}
function ap_is_url(const url: ap_pchar): ap_int; stdcall;
{$EXTERNALSYM ap_server_root_relative}
function ap_server_root_relative(p: Ppool; _file: ap_pchar): ap_pchar; stdcall;
{$EXTERNALSYM ap_os_canonical_filename}
function ap_os_canonical_filename(p: Ppool; const szfile: ap_pchar): ap_int; stdcall;
// TCP/IP and I/O functions
{$EXTERNALSYM ap_get_virthost_addr}
function ap_get_virthost_addr(const hostname: ap_pchar; ports: ap_pshort): ap_unsignedlong; stdcall;
{$EXTERNALSYM ap_get_local_host}
function ap_get_local_host(p: Ppool): ap_constpchar; stdcall;
{$EXTERNALSYM ap_get_remote_host}
function ap_get_remote_host(conn: Pconn_rec; dir_config: ap_pvoid; _type: ap_int): ap_constpchar; stdcall;
{$EXTERNALSYM ap_send_fd}
function ap_send_fd(f: ap_pFILE; r: Prequest_rec): ap_long; stdcall;
{$EXTERNALSYM ap_send_fd_length}
function ap_send_fd_length(f: ap_pFILE; r: Prequest_rec; length: ap_long): ap_long; stdcall;
{$EXTERNALSYM ap_send_fb}
function ap_send_fb(fb: pBUFF; r: Prequest_rec): ap_long; stdcall;
{$EXTERNALSYM ap_send_fb_length}
function ap_send_fb_length(f: pBUFF; r: Prequest_rec; length: ap_long): ap_long; stdcall;
{$EXTERNALSYM ap_rwrite}
function ap_rwrite(var buf; n_byte: ap_int; r: Prequest_rec): ap_int; stdcall;
{$EXTERNALSYM ap_rputc}
function ap_rputc(c: ap_int; r: Prequest_rec): ap_int; stdcall;
{$EXTERNALSYM ap_rputs}
function ap_rputs(const s: pchar; r: Prequest_rec): ap_int; stdcall;
{$EXTERNALSYM ap_rflush}
function ap_rflush(r: Prequest_rec): ap_int; stdcall;
{$EXTERNALSYM ap_setup_client_block}
function ap_setup_client_block(r: Prequest_rec; read_policy: ap_int): ap_int; stdcall;
{$EXTERNALSYM ap_should_client_block}
function ap_should_client_block(r: Prequest_rec): ap_int; stdcall;
{$EXTERNALSYM ap_get_client_block}
function ap_get_client_block(r: Prequest_rec; buffer: ap_pchar; bufsiz: ap_int): ap_long; stdcall;
{$EXTERNALSYM ap_send_http_header}
procedure ap_send_http_header(r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_send_size}
procedure ap_send_size(size: size_t; r: Prequest_rec); stdcall;
// Request handling functions
{$EXTERNALSYM ap_sub_req_lookup_uri}
function ap_sub_req_lookup_uri(const new_uri: ap_pchar; const r: Prequest_rec): Prequest_rec; stdcall;
{$EXTERNALSYM ap_sub_req_lookup_file}
function ap_sub_req_lookup_file(const new_file: ap_pchar; const r: Prequest_rec): Prequest_rec; stdcall;
{$EXTERNALSYM ap_run_sub_req}
function ap_run_sub_req(r: Prequest_rec): ap_int; stdcall;
{$EXTERNALSYM ap_destroy_sub_req}
procedure ap_destroy_sub_req(r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_internal_redirect}
procedure ap_internal_redirect(const uri: ap_pchar; r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_internal_redirect_handler}
procedure ap_internal_redirect_handler(const uri: ap_pchar; r: Prequest_rec); stdcall;
// Timeout & Alarm functions
{$EXTERNALSYM ap_hard_timeout}
procedure ap_hard_timeout(name: ap_pchar; r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_keepalive_timeout}
procedure ap_keepalive_timeout(name: ap_pchar; r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_soft_timeout}
procedure ap_soft_timeout(name: ap_pchar; r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_reset_timeout}
procedure ap_reset_timeout(r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_kill_timeout}
procedure ap_kill_timeout(r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_block_alarms}
procedure ap_block_alarms; stdcall;
{$EXTERNALSYM ap_unblock_alarms}
procedure ap_unblock_alarms; stdcall;
{$EXTERNALSYM ap_check_alarm}
procedure ap_check_alarm; stdcall;
// Logging functions
{$EXTERNALSYM ap_log_error}
procedure ap_log_error(const filename: pchar; line, level: ap_int; const s: Pserver_rec; const fmt: pchar); stdcall;
{$EXTERNALSYM ap_log_rerror}
procedure ap_log_rerror(const filename: pchar; line, level: ap_int; const s: Prequest_rec; const fmt: pchar); stdcall;
// URI functions
{$EXTERNALSYM ap_parse_uri_components}
function ap_parse_uri_components(p: Ppool; const uri: ap_pchar; uptr: Puri_components): ap_int; stdcall;
{$EXTERNALSYM ap_parse_hostinfo_components}
function ap_parse_hostinfo_components(p: Ppool; const hostinfo: ap_pchar; uptr: Puri_components): ap_int; stdcall;
{$EXTERNALSYM ap_unparse_uri_components}
function ap_unparse_uri_components(p: Ppool; const uptr: Puri_components; flags: ap_unsigned): ap_pchar; stdcall;
{$EXTERNALSYM ap_pgethostbyname}
function ap_pgethostbyname(p: Ppool; const hostname: ap_pchar): Phostent; stdcall;
{$EXTERNALSYM ap_pduphostent}
function ap_pduphostent(p: Ppool; const hp: Phostent): Phostent; stdcall;
// Miscellaneous functions
{$EXTERNALSYM ap_child_terminate}
procedure ap_child_terminate(r: Prequest_rec); stdcall;
{$EXTERNALSYM ap_default_port}
function ap_default_port(r: Prequest_rec): ap_unsignedshort; stdcall;
{$EXTERNALSYM ap_is_default_port}
function ap_is_default_port(port: ap_int; r: Prequest_rec): ap_int; stdcall;
{$EXTERNALSYM ap_default_port_for_scheme}
function ap_default_port_for_scheme(const scheme_str: ap_pchar): ap_unsignedshort; stdcall;
{$EXTERNALSYM ap_http_method}
function ap_http_method(r: Prequest_rec): ap_pchar; stdcall;
{$EXTERNALSYM ap_default_type}
function ap_default_type(r: Prequest_rec): ap_pchar; stdcall;
{$EXTERNALSYM ap_get_basic_auth_pw}
function ap_get_basic_auth_pw(r: Prequest_rec; const pw: ap_ppchar): ap_int; stdcall;
{$EXTERNALSYM ap_get_module_config}
function ap_get_module_config(conf_vector: ap_pvoid; m: Pmodule): ap_pvoid; stdcall;
{$EXTERNALSYM ap_get_remote_logname}
function ap_get_remote_logname(r: Prequest_rec): ap_pchar; stdcall;
{$EXTERNALSYM ap_get_server_name}
function ap_get_server_name(r: Prequest_rec): ap_pchar; stdcall;
{$EXTERNALSYM ap_get_server_port}
function ap_get_server_port(r: Prequest_rec): ap_unsigned; stdcall;
{$EXTERNALSYM ap_is_initial_req}
function ap_is_initial_req(r: Prequest_rec): ap_int; stdcall;
///* Open a configfile_t as FILE, return open configfile_t struct pointer */
function ap_pcfg_openfile(p: Ppool; filename: ap_constpchar): Pconfigfile_t; stdcall;
{$EXTERNALSYM ap_pcfg_openfile}
///* Read one line from open configfile_t, strip LF, increase line number */
function ap_cfg_getline(buf: ap_pchar; bufsize: size_t; cfp: Pconfigfile_t): integer; stdcall;
{$EXTERNALSYM ap_cfg_getline}
///* Read one char from open configfile_t, increase line number upon LF */
function ap_cfg_getc(cfp: Pconfigfile_t): integer; stdcall;
{$EXTERNALSYM ap_cfg_getc}
///* Detach from open configfile_t, calling the close handler */
function ap_cfg_closefile(cfp: Pconfigfile_t): integer; stdcall;
{$EXTERNALSYM ap_cfg_closefile}
function ap_getword(p: Ppool; line: ap_ppchar; stop: char): ap_pchar; stdcall;
{$EXTERNALSYM ap_getword}
{$ENDIF}
{$IFDEF LINUX}
// Pool functions
{$EXTERNALSYM ap_make_sub_pool}
function ap_make_sub_pool(p: Ppool): Ppool; cdecl;
{$EXTERNALSYM ap_clear_pool}
procedure ap_clear_pool(p: Ppool); cdecl;
{$EXTERNALSYM ap_destroy_pool}
procedure ap_destroy_pool(p: Ppool); cdecl;
{$EXTERNALSYM ap_bytes_in_pool}
function ap_bytes_in_pool(p: Ppool): ap_long; cdecl;
{$EXTERNALSYM ap_bytes_in_free_blocks}
function ap_bytes_in_free_blocks: ap_long; cdecl;
{$EXTERNALSYM ap_palloc}
function ap_palloc(p: Ppool; size: ap_int): ap_pvoid; cdecl;
{$EXTERNALSYM ap_pcalloc}
function ap_pcalloc(p: Ppool; size: ap_int): ap_pvoid; cdecl;
{$EXTERNALSYM ap_pstrdup}
function ap_pstrdup(p: Ppool; const s: ap_pchar): ap_pchar; cdecl;
{$EXTERNALSYM ap_pstrndup}
function ap_pstrndup(p: Ppool; const s: ap_pchar; n: ap_int): ap_pchar; cdecl;
// function ap_pstrcat(p: Ppool; ..): ap_pchar; cdecl;
// Array functions
{$EXTERNALSYM ap_make_array}
function ap_make_array(p: Ppool; nelts, elt_size: ap_int): Parray_header; cdecl;
{$EXTERNALSYM ap_push_array}
function ap_push_array(arr: Parray_header): ap_pvoid; cdecl;
{$EXTERNALSYM ap_array_cat}
procedure ap_array_cat(dst: Parray_header; const src: Parray_header); cdecl;
{$EXTERNALSYM ap_copy_array}
function ap_copy_array(p: Ppool; const arr: Parray_header): Parray_header; cdecl;
{$EXTERNALSYM ap_copy_array_hdr}
function ap_copy_array_hdr(p: Ppool; const arr: Parray_header): Parray_header; cdecl;
{$EXTERNALSYM ap_append_arrays}
function ap_append_arrays(p: Ppool; const first, second: Parray_header): Parray_header; cdecl;
// Table functions
{$EXTERNALSYM ap_make_table}
function ap_make_table(p: Ppool; nelts: ap_int): Ptable; cdecl;
{$EXTERNALSYM ap_copy_table}
function ap_copy_table(p: Ppool; const t: Ptable): Ptable; cdecl;
{$EXTERNALSYM ap_table_elts}
function ap_table_elts(t: Ptable): Parray_header; cdecl;
{$EXTERNALSYM ap_is_empty_table}
function ap_is_empty_table(t: Ptable): ap_int; cdecl;
{$EXTERNALSYM ap_table_set}
procedure ap_table_set(t: Ptable; const key, value: pchar); cdecl;
{$EXTERNALSYM ap_table_setn}
procedure ap_table_setn(t: Ptable; const key, value: pchar); cdecl;
{$EXTERNALSYM ap_table_merge}
procedure ap_table_merge(t: Ptable; const key, value: pchar); cdecl;
{$EXTERNALSYM ap_table_mergen}
procedure ap_table_mergen(t: Ptable; const key, value: pchar); cdecl;
{$EXTERNALSYM ap_table_add}
procedure ap_table_add(t: Ptable; const key, value: pchar); cdecl;
{$EXTERNALSYM ap_table_addn}
procedure ap_table_addn(t: Ptable; const key, value: pchar); cdecl;
{$EXTERNALSYM ap_table_unset}
procedure ap_table_unset(t: Ptable; const key: pchar); cdecl;
{$EXTERNALSYM ap_table_get}
function ap_table_get(t: Ptable; const key: pchar): ap_constpchar; cdecl;
{$EXTERNALSYM ap_table_do}
procedure ap_table_do(comp: TCompFunc; rec: ap_pvoid; const t: Ptable; tag: ap_pchar = nil); cdecl;
{$EXTERNALSYM ap_overlay_tables}
function ap_overlay_tables(p: Ppool; const overlay, base: Ptable): Ptable; cdecl;
{$EXTERNALSYM ap_clear_table}
procedure ap_clear_table(t: Ptable); cdecl;
// Cleanup functions
{$EXTERNALSYM ap_register_cleanup}
procedure ap_register_cleanup(p: Ppool; data: ap_pvoid; plain_cleanup, child_cleanup: TCleanupFunc); cdecl;
{$EXTERNALSYM ap_kill_cleanup}
procedure ap_kill_cleanup(p: Ppool; data: ap_pvoid; plain_cleanup: TCleanupFunc); cdecl;
{$EXTERNALSYM ap_cleanup_for_exec}
procedure ap_cleanup_for_exec; cdecl;
{$EXTERNALSYM ap_note_cleanups_for_fd}
procedure ap_note_cleanups_for_fd(p: Ppool; fd: ap_int); cdecl;
{$EXTERNALSYM ap_kill_cleanups_for_fd}
procedure ap_kill_cleanups_for_fd(p: Ppool; fd: ap_int); cdecl;
{$EXTERNALSYM ap_note_cleanups_for_socket}
procedure ap_note_cleanups_for_socket(p: Ppool; fd: ap_int); cdecl;
{$EXTERNALSYM ap_kill_cleanups_for_socket}
procedure ap_kill_cleanups_for_socket(p: Ppool; fd: ap_int); cdecl;
{$EXTERNALSYM ap_note_cleanups_for_file}
procedure ap_note_cleanups_for_file(p: Ppool; f: ap_pFILE); cdecl;
{$EXTERNALSYM ap_run_cleanup}
procedure ap_run_cleanup(p: Ppool; data: ap_pvoid; cleanup: TCleanupFunc); cdecl;
// File and socket functions
{$EXTERNALSYM ap_popenf}
function ap_popenf(p: Ppool; const name: ap_pchar; flg, mode: ap_int): ap_int; cdecl;
{$EXTERNALSYM ap_pclosef}
function ap_pclosef(p: Ppool; fd: ap_int): ap_int; cdecl;
{$EXTERNALSYM ap_pfopen}
function ap_pfopen(p: Ppool; const name, mode: ap_pchar): ap_pFILE; cdecl;
{$EXTERNALSYM ap_pfdopen}
function ap_pfdopen(p: Ppool; fd: ap_int; const mode: ap_pchar): ap_pFILE; cdecl;
{$EXTERNALSYM ap_pfclose}
function ap_pfclose(p: Ppool; fd: ap_pFILE): ap_int; cdecl;
{$EXTERNALSYM ap_psocket}
function ap_psocket(p: Ppool; domain, _type, protocol: ap_int): ap_int; cdecl;
{$EXTERNALSYM ap_pclosesocket}
function ap_pclosesocket(p: Ppool; sock: ap_int): ap_int; cdecl;
// Regular expression functions
{$EXTERNALSYM ap_pregcomp}
function ap_pregcomp(p: Ppool; const pattern: ap_pchar; cflags: ap_int): Pregex_t; cdecl;
{$EXTERNALSYM ap_pregsub}
function ap_pregsub(p: Ppool; const input, source: ap_pchar; nmatch: size_t; pmatch: Pregmatch_t): ap_pchar; cdecl;
{$EXTERNALSYM ap_pregfree}
procedure ap_pregfree(p: Ppool; reg: Pregex_t); cdecl;
{$EXTERNALSYM ap_os_is_path_absolute}
function ap_os_is_path_absolute(const _file: ap_pchar): ap_int; cdecl;
// Process and CGI functions
{$EXTERNALSYM ap_note_subprocess}
procedure ap_note_subprocess(p: Ppool; pid: ap_int; how: kill_conditions); cdecl;
{$EXTERNALSYM ap_spawn_child}
function ap_spawn_child(p: Ppool; func: TSpawnFunc; data: ap_pvoid; how: kill_conditions; pipe_in, pipe_out, pipe_err: ap_ppFILE): ap_int; cdecl;
{$EXTERNALSYM ap_bspawn_child}
function ap_bspawn_child(p: Ppool; func: TbSpawnFunc; data: ap_pvoid; kill_how: kill_conditions; pipe_in, pipe_out, pipe_err: PPBUFF): ap_int; cdecl;
{$EXTERNALSYM ap_call_exec}
function ap_call_exec(r: Prequest_rec; pinfo: Pchild_info; argv0: ap_pchar; env: ap_ppchar; shellcmd: ap_int): ap_int; cdecl;
{$EXTERNALSYM ap_can_exec}
function ap_can_exec(const finfo: Pstat): ap_int; cdecl;
{$EXTERNALSYM ap_add_cgi_vars}
procedure ap_add_cgi_vars(r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_add_common_vars}
procedure ap_add_common_vars(r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_scan_script_header_err}
function ap_scan_script_header_err(r: Prequest_rec; f: ap_pFILE; buffer: ap_pchar): ap_int; cdecl;
{$EXTERNALSYM ap_scan_script_header_err_buff}
function ap_scan_script_header_err_buff(r: Prequest_rec; f: PBUFF; buffer: ap_pchar): ap_int; cdecl;
{$EXTERNALSYM ap_scan_script_header}
function ap_scan_script_header(r: Prequest_rec; f: ap_pFILE): ap_int; cdecl;
// MD5 functions
{$EXTERNALSYM ap_md5}
function ap_md5(p: Ppool; _string: ap_pchar): pchar; cdecl;
{$EXTERNALSYM ap_md5contextTo64}
function ap_md5contextTo64(a: Ppool; context: AP_PMD5_CTX): ap_pchar; cdecl;
{$EXTERNALSYM ap_md5digest}
function ap_md5digest(p: Ppool; infile: ap_pFILE): ap_pchar; cdecl;
{$EXTERNALSYM ap_MD5Init}
procedure ap_MD5Init(context: AP_PMD5_CTX); cdecl;
{$EXTERNALSYM ap_MD5Final}
procedure ap_MD5Final(digest: ap_pchar; context: AP_PMD5_CTX); cdecl;
{$EXTERNALSYM ap_MD5Update}
procedure ap_MD5Update(context: AP_PMD5_CTX; const input: ap_pchar; inputLen: ap_unsigned); cdecl;
// Time and Date functions
{$EXTERNALSYM ap_get_time}
function ap_get_time: ap_pchar; cdecl;
{$EXTERNALSYM ap_ht_time}
function ap_ht_time(p: Ppool; t: time_t; const fmt: ap_pchar; gmt: ap_int): ap_pchar; cdecl;
{$EXTERNALSYM ap_gm_timestr_822}
function ap_gm_timestr_822(p: Ppool; t: time_t): ap_pchar; cdecl;
{$EXTERNALSYM ap_get_gmtoff}
function ap_get_gmtoff(var tz: ap_long): Ptm; cdecl;
{$EXTERNALSYM ap_tm2sec}
function ap_tm2sec(const t: Ptm): time_t; cdecl;
{$EXTERNALSYM ap_parseHTTPdate}
function ap_parseHTTPdate(const date: ap_pchar): time_t; cdecl;
// Path, Filename, and URL Manipulation Fuctions
{$EXTERNALSYM ap_getparents}
procedure ap_getparents(name: ap_pchar); cdecl;
{$EXTERNALSYM ap_no2slash}
procedure ap_no2slash(name: ap_pchar); cdecl;
{$EXTERNALSYM ap_make_dirstr}
function ap_make_dirstr(p: Ppool; const path: ap_pchar; n: ap_int): ap_pchar; cdecl;
{$EXTERNALSYM ap_make_dirstr_parent}
function ap_make_dirstr_parent(p: Ppool; const s: ap_pchar): ap_pchar; cdecl;
{$EXTERNALSYM ap_make_dirstr_prefix}
function ap_make_dirstr_prefix(d: ap_pchar; const s: ap_pchar; n: ap_int): ap_pchar; cdecl;
{$EXTERNALSYM ap_count_dirs}
function ap_count_dirs(const path: ap_pchar): ap_int; cdecl;
{$EXTERNALSYM ap_chdir_file}
procedure ap_chdir_file(const _file: ap_pchar); cdecl;
{$EXTERNALSYM ap_unescape_url}
function ap_unescape_url(url: ap_pchar): ap_int; cdecl;
{$EXTERNALSYM ap_construct_server}
function ap_construct_server(p: Ppool; const hostname: ap_pchar; port: ap_int; r: Prequest_rec): ap_pchar; cdecl;
{$EXTERNALSYM ap_construct_url}
function ap_construct_url(p: Ppool; const uri: ap_pchar; const r: Prequest_rec): ap_pchar; cdecl;
{$EXTERNALSYM ap_escape_path_segment}
function ap_escape_path_segment(p: Ppool; const segment: ap_pchar): ap_pchar; cdecl;
{$EXTERNALSYM ap_os_escape_path}
function ap_os_escape_path(p: Ppool; const path: ap_pchar; partial: ap_int): ap_pchar; cdecl;
{$EXTERNALSYM ap_is_directory}
function ap_is_directory(const path: ap_pchar): ap_int; cdecl;
{$EXTERNALSYM ap_make_full_path}
function ap_make_full_path(p: Ppool; const path1, path2: ap_pchar): ap_pchar; cdecl;
{$EXTERNALSYM ap_is_url}
function ap_is_url(const url: ap_pchar): ap_int; cdecl;
{$EXTERNALSYM ap_server_root_relative}
function ap_server_root_relative(p: Ppool; _file: ap_pchar): ap_pchar; cdecl;
{$EXTERNALSYM ap_os_canonical_filename}
function ap_os_canonical_filename(p: Ppool; const szfile: ap_pchar): ap_int; cdecl;
// TCP/IP and I/O functions
{$EXTERNALSYM ap_get_virthost_addr}
function ap_get_virthost_addr(const hostname: ap_pchar; ports: ap_pshort): ap_unsignedlong; cdecl;
{$EXTERNALSYM ap_get_local_host}
function ap_get_local_host(p: Ppool): ap_constpchar; cdecl;
{$EXTERNALSYM ap_get_remote_host}
function ap_get_remote_host(conn: Pconn_rec; dir_config: ap_pvoid; _type: ap_int): ap_constpchar; cdecl;
{$EXTERNALSYM ap_send_fd}
function ap_send_fd(f: ap_pFILE; r: Prequest_rec): ap_long; cdecl;
{$EXTERNALSYM ap_send_fd_length}
function ap_send_fd_length(f: ap_pFILE; r: Prequest_rec; length: ap_long): ap_long; cdecl;
{$EXTERNALSYM ap_send_fb}
function ap_send_fb(fb: pBUFF; r: Prequest_rec): ap_long; cdecl;
{$EXTERNALSYM ap_send_fb_length}
function ap_send_fb_length(f: pBUFF; r: Prequest_rec; length: ap_long): ap_long; cdecl;
{$EXTERNALSYM ap_rwrite}
function ap_rwrite(var buf; n_byte: ap_int; r: Prequest_rec): ap_int; cdecl;
{$EXTERNALSYM ap_rputc}
function ap_rputc(c: ap_int; r: Prequest_rec): ap_int; cdecl;
{$EXTERNALSYM ap_rputs}
function ap_rputs(const s: pchar; r: Prequest_rec): ap_int; cdecl;
{$EXTERNALSYM ap_rflush}
function ap_rflush(r: Prequest_rec): ap_int; cdecl;
{$EXTERNALSYM ap_setup_client_block}
function ap_setup_client_block(r: Prequest_rec; read_policy: ap_int): ap_int; cdecl;
{$EXTERNALSYM ap_should_client_block}
function ap_should_client_block(r: Prequest_rec): ap_int; cdecl;
{$EXTERNALSYM ap_get_client_block}
function ap_get_client_block(r: Prequest_rec; buffer: ap_pchar; bufsiz: ap_int): ap_long; cdecl;
{$EXTERNALSYM ap_send_http_header}
procedure ap_send_http_header(r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_send_size}
procedure ap_send_size(size: size_t; r: Prequest_rec); cdecl;
// Request handling functions
{$EXTERNALSYM ap_sub_req_lookup_uri}
function ap_sub_req_lookup_uri(const new_uri: ap_pchar; const r: Prequest_rec): Prequest_rec; cdecl;
{$EXTERNALSYM ap_sub_req_lookup_file}
function ap_sub_req_lookup_file(const new_file: ap_pchar; const r: Prequest_rec): Prequest_rec; cdecl;
{$EXTERNALSYM ap_run_sub_req}
function ap_run_sub_req(r: Prequest_rec): ap_int; cdecl;
{$EXTERNALSYM ap_destroy_sub_req}
procedure ap_destroy_sub_req(r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_internal_redirect}
procedure ap_internal_redirect(const uri: ap_pchar; r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_internal_redirect_handler}
procedure ap_internal_redirect_handler(const uri: ap_pchar; r: Prequest_rec); cdecl;
// Timeout & Alarm functions
{$EXTERNALSYM ap_hard_timeout}
procedure ap_hard_timeout(name: ap_pchar; r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_keepalive_timeout}
procedure ap_keepalive_timeout(name: ap_pchar; r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_soft_timeout}
procedure ap_soft_timeout(name: ap_pchar; r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_reset_timeout}
procedure ap_reset_timeout(r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_kill_timeout}
procedure ap_kill_timeout(r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_block_alarms}
procedure ap_block_alarms; cdecl;
{$EXTERNALSYM ap_unblock_alarms}
procedure ap_unblock_alarms; cdecl;
{$EXTERNALSYM ap_check_alarm}
procedure ap_check_alarm; cdecl;
// Logging functions
{$EXTERNALSYM ap_log_error}
procedure ap_log_error(const filename: pchar; line, level: ap_int; const s: Pserver_rec; const fmt: pchar); cdecl;
{$EXTERNALSYM ap_log_rerror}
procedure ap_log_rerror(const filename: pchar; line, level: ap_int; const s: Prequest_rec; const fmt: pchar); cdecl;
// URI functions
{$EXTERNALSYM ap_parse_uri_components}
function ap_parse_uri_components(p: Ppool; const uri: ap_pchar; uptr: Puri_components): ap_int; cdecl;
{$EXTERNALSYM ap_parse_hostinfo_components}
function ap_parse_hostinfo_components(p: Ppool; const hostinfo: ap_pchar; uptr: Puri_components): ap_int; cdecl;
{$EXTERNALSYM ap_unparse_uri_components}
function ap_unparse_uri_components(p: Ppool; const uptr: Puri_components; flags: ap_unsigned): ap_pchar; cdecl;
{$EXTERNALSYM ap_pgethostbyname}
function ap_pgethostbyname(p: Ppool; const hostname: ap_pchar): Phostent; cdecl;
{$EXTERNALSYM ap_pduphostent}
function ap_pduphostent(p: Ppool; const hp: Phostent): Phostent; cdecl;
// Miscellaneous functions
{$EXTERNALSYM ap_child_terminate}
procedure ap_child_terminate(r: Prequest_rec); cdecl;
{$EXTERNALSYM ap_default_port}
function ap_default_port(r: Prequest_rec): ap_unsignedshort; cdecl;
{$EXTERNALSYM ap_is_default_port}
function ap_is_default_port(port: ap_int; r: Prequest_rec): ap_int; cdecl;
{$EXTERNALSYM ap_default_port_for_scheme}
function ap_default_port_for_scheme(const scheme_str: ap_pchar): ap_unsignedshort; cdecl;
{$EXTERNALSYM ap_http_method}
function ap_http_method(r: Prequest_rec): ap_pchar; cdecl;
{$EXTERNALSYM ap_default_type}
function ap_default_type(r: Prequest_rec): ap_pchar; cdecl;
{$EXTERNALSYM ap_get_basic_auth_pw}
function ap_get_basic_auth_pw(r: Prequest_rec; const pw: ap_ppchar): ap_int; cdecl;
{$EXTERNALSYM ap_get_module_config}
function ap_get_module_config(conf_vector: ap_pvoid; m: Pmodule): ap_pvoid; cdecl;
{$EXTERNALSYM ap_get_remote_logname}
function ap_get_remote_logname(r: Prequest_rec): ap_pchar; cdecl;
{$EXTERNALSYM ap_get_server_name}
function ap_get_server_name(r: Prequest_rec): ap_pchar; cdecl;
{$EXTERNALSYM ap_get_server_port}
function ap_get_server_port(r: Prequest_rec): ap_unsigned; cdecl;
{$EXTERNALSYM ap_is_initial_req}
function ap_is_initial_req(r: Prequest_rec): ap_int; cdecl;
///* Open a configfile_t as FILE, return open configfile_t struct pointer */
function ap_pcfg_openfile(p: Ppool; filename: ap_constpchar): Pconfigfile_t; cdecl;
{$EXTERNALSYM ap_pcfg_openfile}
///* Read one line from open configfile_t, strip LF, increase line number */
function ap_cfg_getline(buf: ap_pchar; bufsize: size_t; cfp: Pconfigfile_t): integer; cdecl;
{$EXTERNALSYM ap_cfg_getline}
///* Read one char from open configfile_t, increase line number upon LF */
function ap_cfg_getc(cfp: Pconfigfile_t): integer; cdecl;
{$EXTERNALSYM ap_cfg_getc}
///* Detach from open configfile_t, calling the close handler */
function ap_cfg_closefile(cfp: Pconfigfile_t): integer; cdecl;
{$EXTERNALSYM ap_cfg_closefile}
function ap_getword(p: Ppool; line: ap_ppchar; stop: char): ap_pchar; cdecl;
{$EXTERNALSYM ap_getword}
{$ENDIF}
// http_protocol.h
procedure ap_note_auth_failure(r: Prequest_rec);
{$EXTERNALSYM ap_note_auth_failure}
procedure ap_note_basic_auth_failure(r: Prequest_rec);
{$EXTERNALSYM ap_note_basic_auth_failure}
procedure ap_note_digest_auth_failure(r: Prequest_rec);
{$EXTERNALSYM ap_note_digest_auth_failure}
implementation
function ap_is_HTTP_INFO(x: ap_int): boolean;
begin
result := (x >= 100) and (x < 200);
end;
function ap_is_HTTP_SUCCESS(x: ap_int): boolean;
begin
result := (x >= 200) and (x < 300);
end;
function ap_is_HTTP_REDIRECT(x: ap_int): boolean;
begin
result := (x >= 300) and (x < 400);
end;
function ap_is_HTTP_ERROR(x: ap_int): boolean;
begin
result := (x >= 400) and (x < 600);
end;
function ap_is_HTTP_CLIENT_ERROR(x: ap_int): boolean;
begin
result := (x >= 400) and (x < 500);
end;
function ap_is_HTTP_SERVER_ERROR(x: ap_int): boolean;
begin
result := (x >= 500) and (x < 600);
end;
// Pool functions
function ap_make_sub_pool; external ApacheCore name 'ap_make_sub_pool';
procedure ap_clear_pool; external ApacheCore name 'ap_clear_pool';
procedure ap_destroy_pool; external ApacheCore name 'ap_destroy_pool';
function ap_bytes_in_pool; external ApacheCore name 'ap_bytes_in_pool';
function ap_bytes_in_free_blocks; external ApacheCore name 'ap_bytes_in_free_pool';
function ap_palloc; external ApacheCore name 'ap_palloc';
function ap_pcalloc; external ApacheCore name 'ap_pcalloc';
function ap_pstrdup; external ApacheCore name 'ap_pstrdup';
function ap_pstrndup; external ApacheCore name 'ap_pstrndup';
// function ap_pstrcat; external ApacheCore name 'ap_pstrcat';
// Array functions
function ap_make_array; external ApacheCore name 'ap_make_array';
function ap_push_array; external ApacheCore name 'ap_push_array';
procedure ap_array_cat; external ApacheCore name 'ap_array_cat';
function ap_copy_array; external ApacheCore name 'ap_copy_array';
function ap_copy_array_hdr; external ApacheCore name 'ap_copy_array_hdr';
function ap_append_arrays; external ApacheCore name 'ap_append_arrays';
// Table functions
function ap_make_table; external ApacheCore name 'ap_make_table';
function ap_copy_table; external ApacheCore name 'ap_copy_table';
function ap_table_elts; external ApacheCore name 'ap_table_elts';
function ap_is_empty_table; external ApacheCore name 'ap_is_empty_table';
procedure ap_table_set; external ApacheCore name 'ap_table_set';
procedure ap_table_setn; external ApacheCore name 'ap_table_setn';
procedure ap_table_merge; external ApacheCore name 'ap_table_merge';
procedure ap_table_mergen; external ApacheCore name 'ap_table_mergen';
procedure ap_table_add; external ApacheCore name 'ap_table_add';
procedure ap_table_addn; external ApacheCore name 'ap_table_addn';
procedure ap_table_unset; external ApacheCore name 'ap_table_unset';
function ap_table_get; external ApacheCore name 'ap_table_get';
procedure ap_table_do; external ApacheCore name 'ap_table_do';
function ap_overlay_tables; external ApacheCore name 'ap_overlay_tables';
procedure ap_clear_table; external ApacheCore name 'ap_clear_table';
// Cleanup functions
procedure ap_register_cleanup; external ApacheCore name 'ap_register_cleanup';
procedure ap_kill_cleanup; external ApacheCore name 'ap_kill_cleanup';
procedure ap_cleanup_for_exec; external ApacheCore name 'ap_cleanup_for_exec';
procedure ap_note_cleanups_for_fd; external ApacheCore name 'ap_note_cleanups_for_fd';
procedure ap_kill_cleanups_for_fd; external ApacheCore name 'ap_kill_cleanups_for_fd';
procedure ap_note_cleanups_for_socket; external ApacheCore name 'ap_note_cleanups_for_socket';
procedure ap_kill_cleanups_for_socket; external ApacheCore name 'ap_kill_cleanups_for_socket';
procedure ap_note_cleanups_for_file; external ApacheCore name 'ap_note_cleanups_for_file';
procedure ap_run_cleanup; external ApacheCore name 'ap_run_cleanup';
// File and socket functions
function ap_popenf; external ApacheCore name 'ap_popenf';
function ap_pclosef; external ApacheCore name 'ap_pclosef';
function ap_pfopen; external ApacheCore name 'ap_pfopen';
function ap_pfdopen; external ApacheCore name 'ap_pfdopen';
function ap_pfclose; external ApacheCore name 'ap_pfclose';
function ap_psocket; external ApacheCore name 'ap_psocket';
function ap_pclosesocket; external ApacheCore name 'ap_pclosesocket';
// Regular expression functions
function ap_pregcomp; external ApacheCore name 'ap_pregcomp';
function ap_pregsub; external ApacheCore name 'ap_pregsub';
procedure ap_pregfree; external ApacheCore name 'ap_pregfree';
function ap_os_is_path_absolute; external ApacheCore name 'ap_os_is_path_absolute';
// Process and CGI functions
procedure ap_note_subprocess; external ApacheCore name 'ap_note_subprocess';
function ap_spawn_child; external ApacheCore name 'ap_spawn_child';
function ap_bspawn_child; external ApacheCore name 'ap_bspawn_child';
function ap_call_exec; external ApacheCore name 'ap_call_exec';
function ap_can_exec; external ApacheCore name 'ap_can_exec';
procedure ap_add_cgi_vars; external ApacheCore name 'ap_add_cgi_vars';
procedure ap_add_common_vars; external ApacheCore name 'ap_add_common_vars';
function ap_scan_script_header_err; external ApacheCore name 'ap_scan_script_header_err';
function ap_scan_script_header_err_buff; external ApacheCore name 'ap_scan_script_header_err_buff';
function ap_scan_script_header; external ApacheCore name 'ap_scan_script_header';
// MD5 functions
function ap_md5; external ApacheCore name 'ap_md5';
function ap_md5contextTo64; external ApacheCore name 'ap_md5contextTo64';
function ap_md5digest; external ApacheCore name 'ap_md5digest';
procedure ap_MD5Init; external ApacheCore name 'ap_MD5Init';
procedure ap_MD5Final; external ApacheCore name 'ap_MD5Final';
procedure ap_MD5Update; external ApacheCore name 'ap_MD5Update';
// Time and Date functions
function ap_get_time: ap_pchar; external ApacheCore name 'ap_get_time';
function ap_ht_time; external ApacheCore name 'ap_ht_time';
function ap_gm_timestr_822; external ApacheCore name 'ap_gm_timestr_822';
function ap_get_gmtoff; external ApacheCore name 'ap_get_gmtoff';
function ap_tm2sec; external ApacheCore name 'ap_tm2sec';
function ap_parseHTTPdate; external ApacheCore name 'ap_parseHTTPdate';
// Path, Filename, and URL Manipulation Fuctions
procedure ap_getparents; external ApacheCore name 'ap_getparents';
procedure ap_no2slash; external ApacheCore name 'ap_no2slash';
function ap_make_dirstr; external ApacheCore name 'ap_make_dirstr';
function ap_make_dirstr_parent; external ApacheCore name 'ap_make_dirstr_parent';
function ap_make_dirstr_prefix; external ApacheCore name 'ap_make_dirstr_prefix';
function ap_count_dirs; external ApacheCore name 'ap_count_dirs';
procedure ap_chdir_file; external ApacheCore name 'ap_chdir_file';
function ap_unescape_url; external ApacheCore name 'ap_unescape_url';
function ap_construct_server; external ApacheCore name 'ap_construct_server';
function ap_construct_url; external ApacheCore name 'ap_construct_url';
function ap_escape_path_segment; external ApacheCore name 'ap_escape_path_segment';
function ap_os_escape_path; external ApacheCore name 'ap_os_escape_path';
function ap_is_directory; external ApacheCore name 'ap_is_directory';
function ap_make_full_path; external ApacheCore name 'ap_make_full_path';
function ap_is_url; external ApacheCore name 'ap_is_url';
function ap_server_root_relative; external ApacheCore name 'ap_server_root_relative';
function ap_os_canonical_filename; external ApacheCore name 'ap_os_canonical_filename';
// TCP/IP and I/O functions
function ap_get_virthost_addr; external ApacheCore name 'ap_get_virthost_addr';
function ap_get_local_host; external ApacheCore name 'ap_get_local_host';
function ap_get_remote_host; external ApacheCore name 'ap_get_remote_host';
function ap_send_fd; external ApacheCore name 'ap_send_fd';
function ap_send_fd_length; external ApacheCore name 'ap_send_fd_lentgh';
function ap_send_fb; external ApacheCore name 'ap_send_fb';
function ap_send_fb_length; external ApacheCore name 'ap_send_fb_lentgh';
function ap_rwrite; external ApacheCore name 'ap_rwrite';
function ap_rputc; external ApacheCore name 'ap_rputc';
function ap_rputs; external ApacheCore name 'ap_rputs';
function ap_rflush; external ApacheCore name 'ap_rflush';
function ap_setup_client_block; external ApacheCore name 'ap_setup_client_block';
function ap_should_client_block; external ApacheCore name 'ap_should_client_block';
function ap_get_client_block; external ApacheCore name 'ap_get_client_block';
procedure ap_send_http_header; external ApacheCore name 'ap_send_http_header';
procedure ap_send_size; external ApacheCore name 'ap_send_size';
// Request handling functions
function ap_sub_req_lookup_uri; external ApacheCore name 'ap_sub_req_lookup_uri';
function ap_sub_req_lookup_file; external ApacheCore name 'ap_sub_req_lookup_uri';
function ap_run_sub_req; external ApacheCore name 'ap_run_sub_req';
procedure ap_destroy_sub_req; external ApacheCore name 'ap_destroy_sub_req';
procedure ap_internal_redirect; external ApacheCore name 'ap_internal_redirect';
procedure ap_internal_redirect_handler; external ApacheCore name 'ap_internal_redirect_handler';
// Timeout & Alarm functions
procedure ap_hard_timeout; external ApacheCore name 'ap_hard_timeout';
procedure ap_keepalive_timeout; external ApacheCore name 'ap_keepalive_timeout';
procedure ap_soft_timeout; external ApacheCore name 'ap_soft_timeout';
procedure ap_reset_timeout; external ApacheCore name 'ap_reset_timeout';
procedure ap_kill_timeout; external ApacheCore name 'ap_kill_timeout';
procedure ap_block_alarms; external ApacheCore name 'ap_block_alarms';
procedure ap_unblock_alarms; external ApacheCore name 'ap_unblock_alarms';
procedure ap_check_alarm; external ApacheCore name 'ap_check_alarm';
// Logging functions
procedure ap_log_error; external ApacheCore name 'ap_log_error';
procedure ap_log_rerror; external ApacheCore name 'ap_log_error';
// URI functions
function ap_parse_uri_components; external ApacheCore name 'ap_parse_uri_components';
function ap_parse_hostinfo_components; external ApacheCore name 'ap_parse_hostinfo_components';
function ap_unparse_uri_components; external ApacheCore name 'ap_unparse_uri_components';
function ap_pgethostbyname; external ApacheCore name 'ap_pgethostbyname';
function ap_pduphostent; external ApacheCore name 'ap_pduphostent';
// Miscellaneous functions
procedure ap_child_terminate; external ApacheCore name 'ap_child_terminate';
function ap_default_port; external ApacheCore name 'ap_default_port';
function ap_is_default_port; external ApacheCore name 'ap_is_default_port';
function ap_default_port_for_scheme; external ApacheCore name 'ap_default_port_for_scheme';
function ap_http_method; external ApacheCore name 'ap_http_method';
function ap_default_type; external ApacheCore name 'ap_default_type';
function ap_get_basic_auth_pw; external ApacheCore name 'ap_get_basic_auth_pw';
function ap_get_module_config; external ApacheCore name 'ap_get_module_config';
function ap_get_remote_logname; external ApacheCore name 'ap_get_remote_logname';
function ap_get_server_name; external ApacheCore name 'ap_get_server_name';
function ap_get_server_port; external ApacheCore name 'ap_get_server_port';
function ap_is_initial_req; external ApacheCore name 'ap_is_initial_req';
function ap_pcfg_openfile; external ApacheCore name 'ap_pcfg_openfile';
function ap_cfg_getline; external ApacheCore name 'ap_cfg_getline';
function ap_cfg_getc; external ApacheCore name 'ap_cfg_getc';
function ap_cfg_closefile; external ApacheCore name 'ap_cfg_closefile';
function ap_getword; external ApacheCore name 'ap_getword';
// http_protocol.h
procedure ap_note_auth_failure; external ApacheCore name 'ap_note_auth_failure';
procedure ap_note_basic_auth_failure; external ApacheCore name 'ap_note_basic_auth_failure';
procedure ap_note_digest_auth_failure; external ApacheCore name 'ap_note_digest_auth_failure';
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Spin, ExtCtrls,
StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
MapCalculatorPanel: TPanel;
GridX: TSpinEdit;
GridY: TSpinEdit;
CalculatorResults: TMemo;
procedure DoCalculation();
procedure GridXChange(Sender: TObject);
procedure GridYChange(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.DoCalculation();
begin
CalculatorResults.Clear;
CalculatorResults.Append('Height Map: ' + IntToStr(GridX.Value*64+1) + ' X ' + IntToStr(GridY.Value*64+1));
CalculatorResults.Append('Metal Map: ' + IntToStr(GridX.Value*32) + ' X ' + IntToStr(GridY.Value*32));
CalculatorResults.Append('Diffuse(Texture) Map: ' + IntToStr(GridX.Value*512) + ' X ' + IntToStr(GridY.Value*512));
CalculatorResults.Append('Minimap Map: ' + '1024 X 1024(ALWAYS)');
CalculatorResults.Append('Grass Map: ' + IntToStr(GridX.Value*16) + ' X ' + IntToStr(GridY.Value*16));
end;
procedure TForm1.GridXChange(Sender: TObject);
begin
DoCalculation();
end;
procedure TForm1.GridYChange(Sender: TObject);
begin
DoCalculation();
end;
end.
|
unit TMCmnFunc;
{
Aestan Tray Menu
Made by Onno Broekmans; visit http://www.xs4all.nl/~broekroo/aetraymenu
for more information.
This work is hereby released into the Public Domain. To view a copy of the
public domain dedication, visit:
http://creativecommons.org/licenses/publicdomain/
or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford,
California 94305, USA.
This unit contains some general functions that are mainly used by the
TMConfig unit.
}
{
NOTE:
Lots of code from this unit are based on the Inno Setup source code,
which was written by Jordan Russell (portions by Martijn Laan).
Inno Setup is a great, free installer for Windows; see:
http://www.jrsoftware.org
>>PLEASE DO NOT REMOVE THIS NOTE<<
}
{$WARN UNIT_PLATFORM OFF}
interface
uses
Windows, SysUtils, Classes, Contnrs,
TMStruct;
type
TBreakStringRec = record
ParamName: String;
ParamData: String;
end;
PBreakStringArray = ^TBreakStringArray;
TBreakStringArray = array[0..15] of TBreakStringRec;
TParamInfo = record
Name: PChar;
Flags: set of (piNoEmpty, piNoQuotes);
end;
function AddBackslash(const S: String): String;
function AdjustLength(var S: String; const Res: Cardinal): Boolean;
function ExpandVariables(S: String; Variables: TObjectList): String;
function ExtractFlag(var S: String; const FlagStrs: array of PChar): Integer;
function ExtractStr(var S: String): String;
function FindCmdSwitch(const Switch: String; const Default: String = ''): String;
function GetCmdFileName: String;
function GetCommonFiles: String;
function GetEnv(const EnvVar: String): String;
function GetPathFromRegistry(const Name: PChar): String;
function GetProgramFiles: String;
function GetSystemDir: String;
function GetSystemDrive: String;
function GetTempDir: String;
function GetWinDir: String;
//function InstExec(const Filename, Params: String; WorkingDir: String;
// const ShowCmd: Integer; var ResultCode: Integer): Boolean;
function InstExec (const Filename, Params: String; WorkingDir: String;
const WaitUntilTerminated, WaitUntilIdle: Boolean; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
function InstShellExec(const Filename, Params, Verb: String; WorkingDir: String;
const ShowCmd: Integer; var ErrorCode: Integer): Boolean;
function InternalRegQueryStringValue (H: HKEY; Name: PChar; var ResultStr: String;
Type1, Type2: DWORD): Boolean;
function KillInstance(const ID: String): Boolean;
function RegQueryStringValue(H: HKEY; Name: PChar; var ResultStr: String): Boolean;
function RemoveBackslash(const S: String): String;
function RemoveBackslashUnlessRoot(const S: String): String;
function RemoveQuotes(const S: String): String;
procedure SeparateDirective(const Line: PChar; var Key, Value: String);
procedure StringChange(var S: String; const FromStr, ToStr: String);
implementation
uses ShellApi, JclStrings, StrUtils, FileCtrl, RegStr, Messages;
function RemoveQuotes(const S: String): String;
{ Opposite of AddQuotes; removes any quotes around the string. }
begin
Result := S;
while (Result <> '') and (Result[1] = '"') do
Delete (Result, 1, 1);
while (Result <> '') and (AnsiLastChar(Result)^ = '"') do
SetLength (Result, Length(Result)-1);
end;
procedure SeparateDirective(const Line: PChar; var Key, Value: String);
var
P, P2: PChar;
L: Cardinal;
begin
Key := '';
Value := '';
P := Line;
while (P^ <> #0) and (P^ <= ' ') do
Inc (P);
if P^ = #0 then
Exit;
P2 := P;
while (P2^ <> #0) and (P2^ <> '=') do
Inc (P2);
L := P2 - P;
SetLength (Key, L);
Move (P^, Key[1], Length(Key));
Key := TrimRight(Key);
if P2^ = #0 then
Exit;
P := P2 + 1;
while (P^ <> #0) and (P^ <= ' ') do
Inc (P);
if P^ = #0 then
Exit;
Value := TrimRight(StrPas(P));
end;
function ExtractStr(var S: String): String;
var
I: Integer;
begin
I := Pos(' ', S);
if I = 0 then I := Length(S)+1;
Result := Trim(Copy(S, 1, I-1));
S := Trim(Copy(S, I+1, Maxint));
end;
function ExtractFlag(var S: String; const FlagStrs: array of PChar): Integer;
var
I: Integer;
F: String;
begin
F := ExtractStr(S);
if F = '' then begin
Result := -2;
Exit;
end;
Result := -1;
for I := 0 to High(FlagStrs) do
if StrIComp(FlagStrs[I], PChar(F)) = 0 then begin
Result := I;
Break;
end;
end;
function RemoveBackslash(const S: String): String;
{ Removes the trailing backslash from the string, if one exists }
begin
Result := S;
if (Result <> '') and (AnsiLastChar(Result)^ = '\') then
SetLength (Result, Length(Result)-1);
end;
procedure StringChange(var S: String; const FromStr, ToStr: String);
{ Change all occurrences in S of FromStr to ToStr }
var
StartPos, I: Integer;
label 1;
begin
if FromStr = '' then Exit;
StartPos := 1;
1:for I := StartPos to Length(S)-Length(FromStr)+1 do begin
if Copy(S, I, Length(FromStr)) = FromStr then begin
Delete (S, I, Length(FromStr));
Insert (ToStr, S, I);
StartPos := I + Length(ToStr);
goto 1;
end;
end;
end;
function InstExec (const Filename, Params: String; WorkingDir: String;
const WaitUntilTerminated, WaitUntilIdle: Boolean; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
var
CmdLine: String;
WorkingDirP: PChar;
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
begin
Result := True;
CmdLine := '"' + Filename + '"';
if Params <> '' then
CmdLine := CmdLine + ' ' + Params;
if WorkingDir = '' then
WorkingDir := RemoveBackslashUnlessRoot(ExtractFilePath(Filename));
FillChar (StartupInfo, SizeOf(StartupInfo), 0);
StartupInfo.cb := SizeOf(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := ShowCmd;
if WorkingDir <> '' then
WorkingDirP := PChar(WorkingDir)
else
WorkingDirP := nil;
if not CreateProcess(nil, PChar(CmdLine), nil, nil, False, 0, nil,
WorkingDirP, StartupInfo, ProcessInfo) then begin
Result := False;
ResultCode := GetLastError;
Exit;
end;
with ProcessInfo do begin
{ Don't need the thread handle, so close it now }
CloseHandle (hThread);
if WaitUntilIdle then
WaitForInputIdle (hProcess, INFINITE);
if WaitUntilTerminated then
{ Wait until the process returns, but still process any messages that
arrive. }
repeat
{ Process any pending messages first because MsgWaitForMultipleObjects
(called below) only returns when *new* messages arrive }
if Assigned(ProcessMessagesProc) then
ProcessMessagesProc;
until MsgWaitForMultipleObjects(1, hProcess, False, INFINITE, QS_ALLINPUT) <> WAIT_OBJECT_0+1;
{ Get the exit code. Will be set to STILL_ACTIVE if not yet available }
GetExitCodeProcess(hProcess, DWORD(ResultCode));
{ Then close the process handle }
CloseHandle (hProcess);
end;
end;
function InstShellExec(const Filename, Params, Verb: String; WorkingDir: String;
const ShowCmd: Integer; var ErrorCode: Integer): Boolean;
var
WorkingDirP: PChar;
E: Integer;
begin
if WorkingDir = '' then
WorkingDir := RemoveBackslashUnlessRoot(ExtractFilePath(Filename));
if WorkingDir <> '' then
WorkingDirP := PChar(WorkingDir)
else
WorkingDirP := nil;
E := ShellExecute(0, PChar(Verb), PChar(Filename), PChar(Params), WorkingDirP,
ShowCmd);
Result := E > 32;
if not Result then
ErrorCode := E;
end;
function RemoveBackslashUnlessRoot(const S: String): String;
{ Removes the trailing backslash from the string, if one exists and does
not specify a root directory of a drive (i.e. "C:\"}
var
L: Integer;
begin
Result := S;
L := Length(Result);
if L < 2 then
Exit;
if (AnsiLastChar(Result)^ = '\') and
((Result[L-1] <> ':') or (ByteType(Result, L-1) <> mbSingleByte)) then
SetLength (Result, L-1);
end;
function ExpandVariables(S: String; Variables: TObjectList): String;
var
I: Integer;
begin
if Length(S) = 0 then
begin
Result := '';
Exit;
end;
for I := 0 to Variables.Count - 1 do
with Variables[I] as TVariableBase do
begin
if (vfIsPath in Flags) and (RightStr(Value, 1) = '\') then
StrReplace(S, StrQuote(Name, '%') + '\', StrQuote(Name, '%'),
[rfIgnoreCase, rfReplaceAll]);
if AnsiPos(StrQuote(Name, '%'), S) <> 0 then
StrReplace(S, StrQuote(Name, '%'), Value, [rfIgnoreCase, rfReplaceAll]);
end; //with variables[i]
StrReplace(S, '%%', '%', [rfIgnoreCase, rfReplaceAll]);
Result := S;
end;
function GetWinDir: String;
{ Returns fully qualified path of the Windows directory. Only includes a
trailing backslash if the Windows directory is the root directory. }
var
Buf: array[0..MAX_PATH-1] of Char;
begin
GetWindowsDirectory (Buf, SizeOf(Buf));
Result := StrPas(Buf);
end;
function GetSystemDir: String;
{ Returns fully qualified path of the Windows System directory. Only includes a
trailing backslash if the Windows System directory is the root directory. }
var
Buf: array[0..MAX_PATH-1] of Char;
begin
GetSystemDirectory(Buf, SizeOf(Buf));
Result := StrPas(Buf);
{ DONE 3 : Check, and if necessary fix %System% variable }
end;
function GetTempDir: String;
{ Returns fully qualified path of the temporary directory, with trailing
backslash. This does not use the Win32 function GetTempPath, due to platform
differences.
Gets the temporary file path as follows:
1. The path specified by the TMP environment variable.
2. The path specified by the TEMP environment variable, if TMP is not
defined or if TMP specifies a directory that does not exist.
3. The Windows directory, if both TMP and TEMP are not defined or specify
nonexistent directories.
}
begin
Result := GetEnv('TMP');
if (Result = '') or not DirectoryExists(Result) then
Result := GetEnv('TEMP');
if (Result = '') or not DirectoryExists(Result) then
Result := GetWinDir;
Result := AddBackslash(ExpandFileName(Result));
end;
function GetEnv(const EnvVar: String): String;
{ Gets the value of the specified environment variable. (Just like TP's GetEnv) }
var
Res: DWORD;
begin
SetLength (Result, 255);
repeat
Res := GetEnvironmentVariable(PChar(EnvVar), PChar(Result), Length(Result));
if Res = 0 then begin
Result := '';
Break;
end;
until AdjustLength(Result, Res);
end;
function AddBackslash(const S: String): String;
{ Adds a trailing backslash to the string, if one wasn't there already.
But if S is an empty string, the function returns an empty string. }
begin
Result := S;
if (Result <> '') and (AnsiLastChar(Result)^ <> '\') then
Result := Result + '\';
end;
function AdjustLength(var S: String; const Res: Cardinal): Boolean;
{ Returns True if successful. Returns False if buffer wasn't large enough,
and called AdjustLength to resize it. }
begin
Result := Integer(Res) < Length(S);
SetLength (S, Res);
end;
function GetProgramFiles: String;
{ Gets path of Program Files.
Returns blank string if not found in registry. }
begin
Result := GetPathFromRegistry('ProgramFilesDir');
end;
function GetCommonFiles: String;
{ Gets path of Common Files.
Returns blank string if not found in registry. }
begin
Result := GetPathFromRegistry('CommonFilesDir');
end;
function GetPathFromRegistry(const Name: PChar): String;
var
H: HKEY;
begin
if RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGSTR_PATH_SETUP, 0,
KEY_QUERY_VALUE, H) = ERROR_SUCCESS then begin
if not RegQueryStringValue(H, Name, Result) then
Result := '';
RegCloseKey (H);
end
else
Result := '';
end;
function RegQueryStringValue(H: HKEY; Name: PChar; var ResultStr: String): Boolean;
{ Queries the specified REG_SZ or REG_EXPAND_SZ registry key/value, and returns
the value in ResultStr. Returns True if successful. When False is returned,
ResultStr is unmodified. }
begin
Result := InternalRegQueryStringValue(H, Name, ResultStr, REG_SZ,
REG_EXPAND_SZ);
end;
function InternalRegQueryStringValue(H: HKEY; Name: PChar; var ResultStr: String;
Type1, Type2: DWORD): Boolean;
var
Typ, Size: DWORD;
S: String;
begin
Result := False;
if (RegQueryValueEx(H, Name, nil, @Typ, nil, @Size) = ERROR_SUCCESS) and
((Typ = Type1) or (Typ = Type2)) then begin
if Size < 2 then begin {for the following code to work properly, Size can't be 0 or 1}
ResultStr := '';
Result := True;
end
else begin
SetLength (S, Size-1); {long strings implicity include a null terminator}
if RegQueryValueEx(H, Name, nil, nil, @S[1], @Size) = ERROR_SUCCESS then begin
ResultStr := S;
Result := True;
end;
end;
end;
end;
function GetCmdFileName: String;
begin
if Win32Platform = VER_PLATFORM_WIN32_NT then
Result := AddBackslash(GetSystemDir) + 'cmd.exe'
else
Result := AddBackslash(GetWinDir) + 'COMMAND.COM';
end;
function GetSystemDrive: String;
begin
if Win32Platform = VER_PLATFORM_WIN32_NT then
Result := GetEnv('SystemDrive')
else
Result := '';
if Result = '' then begin
Result := ExtractFileDrive(GetWinDir);
if Result = '' then
{ In some rare case that ExtractFileDrive failed, just default to C }
Result := 'C:';
end;
end;
function FindCmdSwitch(const Switch: String; const Default: String = ''): String;
var
I: Integer;
begin
Result := '';
for I := 1 to ParamCount do
if UpperCase(Copy(ParamStr(I), 1, Length(Switch))) = UpperCase(Switch) then
begin
Result := Copy(ParamStr(I), Length(Switch) + 1, MaxInt);
Exit;
end;
if Result = '' then
Result := Default;
end;
function KillInstance(const ID: String): Boolean;
{ Kills another instance of the aetraymenu application }
var
wndHandle: HWND;
begin
Result := False;
if ID = '' then
Exit; //must specify an id
wndHandle := FindWindow(nil, PChar('AeTrayMenu[' + ID + ']'));
if wndHandle <> 0 then
begin
SendMessage(wndHandle, WM_CLOSE, 0, 0);
Result := True;
end; //if wndhandle <> nil
end;
end.
|
unit DrillDiagram;
interface
uses ExtCtrls,Classes,Graphics,forms,sysutils,Math;
const FIRSTVALUE :double = -10000; //变量初始值
const TITLEVOFF :Integer = 5; //孔口坐标纵向预留高度
const TOPLINEVOFF :integer = 25; //孔口基线纵向预留高度
const BOTTOMLINEVOFF :integer = 10; //孔底基线纵向预留高度
Const TBLINEHLOFF :integer = 0; //基线横向左边预留宽度
const TBLINEHROFF :integer = 50; //基线横向右边预留宽度
const AXISLINEOFF :integer = 25; //轴线向左偏移量
const LTEXTOFF :integer = 90; //左边文字预留宽度
const CDRILLTOP :double = 0; //上基线初始值
const CDRILLBOTTOM :double = 0; //下基线初始值
const BACKGROUNDCOLOR :integer =clWhite; //背景颜色
const TOPBOTTOMLINECOLOR:integer =clFuchsia; //范围线颜色
const TITLECOLOR :integer = clNavy; //标题颜色
const NOTECOLOR :integer = clBlue; //标注颜色
const SHAPECOLOR :integer =clBlack; //图形颜色
const MARKCOLOR :integer = clRed; //标记颜色
type
TDrillDiagram=class
private
m_AxisLine:integer;
m_RegionPixelHeigh:integer;
m_RegionActualHeigh:double;
FImage:TImage;
FDrillTop:double;
FDrillBottom:double;
FDrillStandHeigh:double;
FDrillX:double;
FDrillY:double;
FFirstWaterHeigh:double;
FStableWaterHeigh:double;
FPipeDiameter:double;
FPlanDepth:double;
FFinishDepth:double;
FStratumList:TStrings;
FBMList:TList;
procedure SetImage(aImage:TImage);
procedure SetDrillStandHeigh(aDrillStandHeigh:double);
procedure SetDrillX(aDrillX:double);
procedure SetDrillY(aDrillY:double);
procedure SetFirstWaterHeigh(aFirstWaterHeigh:double);
procedure SetStableWaterHeigh(aStableWaterHeigh:double);
procedure SetPipeDiameter(aPipeDiameter:double);
procedure SetPlanDepth(aPlanDepth:double);
procedure SetFinishDepth(aFinishDepth:double);
procedure SetPubVar;
procedure SetStratumList(aStratumList:TStrings);
procedure SetBMList(aBMList:TList);
public
property Image:TImage read FImage write SetImage;
property DrillTop:double read FDrillTop;
property DrillBottom:double read FDrillBottom;
property DrillStandHeigh:double read FDrillStandHeigh write SetDrillStandHeigh;
property DrillX:double read FDrillX write SetDrillX;
property DrillY:double read FDrillY write SetDrillY;
property FirstWaterHeigh:double read FFirstWaterHeigh write SetFirstWaterHeigh;
property StableWaterHeigh:double read FStableWaterHeigh write SetStableWaterHeigh;
property PipeDiameter:double read FPipeDiameter write SetPipeDiameter;
property PlanDepth:double read FPlanDepth write SetPlanDepth;
property FinishDepth:double read FFinishDepth write SetFinishDepth;
property StratumList:TStrings read FStratumList write SetStratumList;
property BMList:TList read FBMList write SetBMList;
Constructor create;
procedure DrawDrillDiagram(ReGetPixelHeigh:boolean);
procedure SetTopBottom(aTop,aBottom:double;isForceSet:boolean=false);
procedure Clear;
end;
implementation
Constructor TDrillDiagram.create;
begin
inherited Create;
m_AxisLine:=0;
m_RegionPixelHeigh:=40;
m_RegionActualHeigh:=40;
FImage:=nil;
clear;
end;
procedure TDrillDiagram.SetImage(aImage:TImage);
begin
if Assigned(aImage) then
begin
FImage:=aImage;
SetPubVar;
end;
end;
procedure TDrillDiagram.SetDrillStandHeigh(aDrillStandHeigh:double);
begin
if aDrillStandHeigh<>FDrillStandHeigh then FDrillStandHeigh:=aDrillStandHeigh;
if aDrillStandHeigh>FDrillTop then
FDrillTop:=aDrillStandHeigh;
if (FPlanDepth=FIRSTVALUE) and (FFinishDepth=FIRSTVALUE) then
begin
if (FFirstWaterHeigh<>FIRSTVALUE) or (FStableWaterHeigh<>FIRSTVALUE) then
if (FFirstWaterHeigh=FIRSTVALUE) and (FStableWaterHeigh<>FIRSTVALUE) then
begin if FDrillBottom>FDrillStandHeigh-abs(FStableWaterHeigh) then FDrillBottom:=FDrillStandHeigh-abs(FStableWaterHeigh);end
else if (FFirstWaterHeigh<>FIRSTVALUE) and (FStableWaterHeigh=FIRSTVALUE) then
begin if FDrillBottom>FDrillStandHeigh-abs(FFirstWaterHeigh) then FDrillBottom:=FDrillStandHeigh-abs(FFirstWaterHeigh);end
else
begin if FDrillBottom>FDrillStandHeigh-abs(max(FFirstWaterHeigh,FStableWaterHeigh)) then FDrillBottom:=FDrillStandHeigh-abs(max(FFirstWaterHeigh,FStableWaterHeigh));end;
end
else
if (FPlanDepth=FIRSTVALUE) and (FFinishDepth<>FIRSTVALUE) then
begin if FDrillBottom>FDrillStandHeigh-abs(FFinishDepth) then FDrillBottom:=FDrillStandHeigh-abs(FFinishDepth); end
else if (FPlanDepth<>FIRSTVALUE) and (FFinishDepth=FIRSTVALUE) then
begin if FDrillBottom>FDrillStandHeigh-abs(FPlanDepth) then FDrillBottom:=FDrillStandHeigh-abs(FPlanDepth);end
else
begin if FDrillBottom>FDrillStandHeigh-abs(max(FPlanDepth,FFinishDepth)) then FDrillBottom:=FDrillStandHeigh-abs(max(FPlanDepth,FFinishDepth));end;
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.SetDrillX(aDrillX:double);
begin
if aDrillX<>FDrillX then FDrillX:=aDrillX;
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.SetDrillY(aDrillY:double);
begin
if aDrillY<>FDrillY then FDrillY:=aDrillY;
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.SetFirstWaterHeigh(aFirstWaterHeigh:double);
begin
if aFirstWaterHeigh<>FFirstWaterHeigh then FFirstWaterHeigh:=aFirstWaterHeigh;
if FDrillStandHeigh<>FIRSTVALUE then
begin
if (FDrillStandHeigh-abs(aFirstWaterHeigh))<FDrillBottom then
FDrillBottom:=FDrillStandHeigh-abs(aFirstWaterHeigh);
end
else
if (FDrillBottom=FIRSTVALUE)or((FDrillTop-abs(aFirstWaterHeigh))<FDrillBottom) then
FDrillBottom:=FDrillTop-abs(aFirstWaterHeigh);
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.SetStableWaterHeigh(aStableWaterHeigh:double);
begin
if aStableWaterHeigh<>FStableWaterHeigh then FStableWaterHeigh:=aStableWaterHeigh;
if FDrillStandHeigh<>FIRSTVALUE then
begin
if (FDrillStandHeigh-abs(aStableWaterHeigh))<FDrillBottom then
FDrillBottom:=FDrillStandHeigh-abs(aStableWaterHeigh);
end
else
if (FDrillBottom=FIRSTVALUE)or((FDrillTop-abs(aStableWaterHeigh))<FDrillBottom) then
FDrillBottom:=FDrillTop-abs(aStableWaterHeigh);
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.SetPipeDiameter(aPipeDiameter:double);
begin
if aPipeDiameter<>FPipeDiameter then FPipeDiameter:=aPipeDiameter;
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.SetPlanDepth(aPlanDepth:double);
begin
if aPlanDepth<>FPlanDepth then FPlanDepth:=aPlanDepth;
if FDrillStandHeigh<>FIRSTVALUE then
begin
if (FDrillStandHeigh-abs(aPlanDepth))<FDrillBottom then
FDrillBottom:=FDrillStandHeigh-abs(aPlanDepth);
end
else
if (FDrillBottom=FIRSTVALUE)or((FDrillTop-abs(aPlanDepth))<FDrillBottom) then
FDrillBottom:=FDrillTop-abs(aPlanDepth);
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.SetFinishDepth(aFinishDepth:double);
begin
if aFinishDepth<>FFinishDepth then FFinishDepth:=aFinishDepth;
if FDrillStandHeigh<>FIRSTVALUE then
begin
if (FDrillStandHeigh-abs(aFinishDepth))<FDrillBottom then
FDrillBottom:=FDrillStandHeigh-abs(aFinishDepth);
end
else
if (FDrillBottom=FIRSTVALUE)or((FDrillTop-abs(aFinishDepth))<FDrillBottom) then
FDrillBottom:=FDrillTop-abs(aFinishDepth);
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.SetStratumList(aStratumList:TStrings);
begin
FStratumList:=aStratumList;
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.SetBMList(aBMList:TList);
begin
FBMList:=aBMList;
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.DrawDrillDiagram(ReGetPixelHeigh:boolean);
var
aMidPoint,i,j:integer;
aRate:double;
aSitX,aSitY,aSHSitY,aSHSitX,tmpSitY:integer;
aPipeDiameter:double;
aBits:TBits;
aBitMap:TBitMap;
begin
if ReGetPixelHeigh then SetPubVar;
if FDrillBottom<>FDrillTop then m_RegionActualHeigh:=abs(FDrillBottom-FDrillTop);
FImage.Canvas.Brush.Color:=BACKGROUNDCOLOR;
FImage.Canvas.FillRect(Rect(0,0,FImage.Width,FImage.Height));
aMidPoint:=FImage.Width DIV 2;
FImage.Canvas.Font.Color:=TITLECOLOR;
if FDrillX<>FIRSTVALUE then
FImage.Canvas.TextOut(aMidPoint Div 4+2,TITLEVOFF,'X座标:'+formatfloat('0.00',FDrillX))//floattostr(FDrillX))
else
FImage.Canvas.TextOut(aMidPoint Div 4+2,TITLEVOFF,'X座标:');
if FDrillY<>FIRSTVALUE then
FImage.Canvas.TextOut(aMidPoint-aMidPoint Div 4 ,TITLEVOFF,'Y座标:'+formatfloat('0.00',FDrillY))//floattostr(FDrillY))
else
FImage.Canvas.TextOut(aMidPoint-aMidPoint Div 4 ,TITLEVOFF,'Y座标:');
FImage.Canvas.Pen.Color:=TOPBOTTOMLINECOLOR;
FImage.Canvas.MoveTo(TBLINEHLOFF,TOPLINEVOFF);
FImage.Canvas.LineTo(FImage.Width-TBLINEHROFF,TOPLINEVOFF);
FImage.Canvas.MoveTo(TBLINEHLOFF,FImage.Height-BOTTOMLINEVOFF);
FImage.Canvas.LineTo(FImage.Width-TBLINEHROFF,FImage.Height-BOTTOMLINEVOFF);
FImage.Canvas.Pen.Color:=SHAPECOLOR;
FImage.Canvas.TextOut(FImage.Width-TBLINEHROFF+5,TOPLINEVOFF-5,formatfloat('0.00',FDrillTop));
FImage.Canvas.TextOut(FImage.Width-TBLINEHROFF+5,FImage.Height-BOTTOMLINEVOFF-5,formatfloat('0.00',FDrillBottom));
if FPipeDiameter=FIRSTVALUE then
begin
FImage.Canvas.Pen.Style :=psDot;
aPipeDiameter:=40;
end
else
begin
FImage.Canvas.Pen.Style :=psSolid;
aPipeDiameter:=FPipeDiameter;
end;
aSitX:=m_AxisLine-round(aPipeDiameter/2);
aSHSitX:=m_AxisLine+round(aPipeDiameter/2);
aRate:=m_RegionPixelHeigh/m_RegionActualHeigh;
aSitY:=TOPLINEVOFF;
aSHSitY:=TOPLINEVOFF;
FImage.Canvas.Font.Color :=NOTECOLOR;
if FDrillStandHeigh<>FIRSTVALUE then
begin
aSitY:=TOPLINEVOFF+round(abs(FDrillStandHeigh-FDrillTop)*aRate);
FImage.Canvas.MoveTo(aSitX,aSitY);
FImage.Canvas.LineTo(aSHSitX,aSitY);
//FImage.Canvas.TextOut(aSHSitX+5,aSitY-5,'孔口标高('+floattostr(FDrillStandHeigh)+')');
FImage.Canvas.Font.Color :=TITLECOLOR;
FImage.Canvas.TextOut(aMidPoint+aMidPoint Div 4 ,TITLEVOFF,'孔口标高:'+FormatFloat('0.00',FDrillStandHeigh));
FImage.Canvas.Font.Color :=NOTECOLOR;
aSHSitY:=aSitY;
end;
if FStratumList.Count>0 then
begin
if FImage.Canvas.Pen.Style<>psSolid then FImage.Canvas.Pen.Style :=psSolid;
if FDrillStandHeigh=FIRSTVALUE then
begin
FImage.Canvas.MoveTo(aSitX,aSHSitY);
FImage.Canvas.LineTo(aSHSitX,aSHSitY);
end;
aBitMap:=TBitMap.Create ;
aBitMap.Width :=32;
aBitMap.Height :=32;
tmpSitY:=aSHSitY;
for i:=0 to FStratumList.Count-1 do
begin
if FDrillStandHeigh<>FIRSTVALUE then
aSitY:=TOPLINEVOFF+round(abs(strtofloat(FStratumList[i])+(FDrillTop-FDrillStandHeigh))*aRate)
else
aSitY:=TOPLINEVOFF+round(abs(strtofloat(FStratumList[i]))*aRate);
if FBMList.Count>i then
begin
aBits:=TBits(FBMList[i]);
for j:=0 to aBits.Size-1 do
if aBits.Bits[j] then
aBitMap.Canvas.Pixels[j mod 32,j div 32]:=clWhite
else
aBitMap.Canvas.Pixels[j mod 32,j div 32]:=clBlack;
FImage.Canvas.Brush.Style:=bsClear;
FImage.Canvas.Brush.Bitmap :=aBitMap;
FImage.Canvas.FillRect(Rect(aSitX,tmpSitY+1,aSHSitX,aSitY));
FImage.Canvas.Brush.Style:=bsSolid;
FImage.Canvas.Brush.Bitmap :=nil;
end;
if FFinishDepth=FIRSTVALUE then
begin
FImage.Canvas.MoveTo(aSitX,tmpSitY);
FImage.Canvas.LineTo(aSitX,aSitY);
FImage.Canvas.MoveTo(aSHSitX,tmpSitY);
FImage.Canvas.LineTo(aSHSitX,aSitY);
end;
FImage.Canvas.MoveTo(aSitX,aSitY);
FImage.Canvas.LineTo(aSHSitX,aSitY);
if FDrillStandHeigh<>FIRSTVALUE then
if i mod 2=0 then
FImage.Canvas.TextOut(aSHSitX+5,aSitY-5,FStratumList[i]+'('+FormatFloat('0.00',FDrillStandHeigh-strtofloat(FStratumList[i]))+')')
else
FImage.Canvas.TextOut(aSitX-LTEXTOFF,aSitY-5,FStratumList[i]+'('+FormatFloat('0.00',FDrillStandHeigh-strtofloat(FStratumList[i]))+')')
else
if i mod 2=1 then
FImage.Canvas.TextOut(aSHSitX+5,aSitY-5,FStratumList[i]+'('+FormatFloat('0.00',FDrillTop-strtofloat(FStratumList[i]))+')')
else
FImage.Canvas.TextOut(aSitX-LTEXTOFF,aSitY-5,FStratumList[i]+'('+FormatFloat('0.00',FDrillTop-strtofloat(FStratumList[i]))+')');
tmpSitY:=aSitY;
end;
aBitMap.Free ;
end;
if FFirstWaterHeigh<>FIRSTVALUE then
begin
FImage.Canvas.Pen.Color:=MARKCOLOR;
FImage.Canvas.Pen.Style :=psDashDotDot;
if FDrillStandHeigh<>FIRSTVALUE then
aSitY:=TOPLINEVOFF+round(abs(FDrillStandHeigh-FDrillTop-FFirstWaterHeigh)*aRate)
else
aSitY:=TOPLINEVOFF+round(FFirstWaterHeigh*aRate);
FImage.Canvas.MoveTo(aSitX,aSitY);
//FImage.Canvas.LineTo(aSHSitX,aSitY);
FImage.Canvas.LineTo(aSitX+100,aSitY);
{FImage.Canvas.MoveTo(m_AxisLine,aSitY);
FImage.Canvas.LineTo(m_AxisLine+5,aSitY-5);
FImage.Canvas.MoveTo(m_AxisLine+5,aSitY-5);
FImage.Canvas.LineTo(m_AxisLine-5,aSitY-5);
FImage.Canvas.MoveTo(m_AxisLine-5,aSitY-5);
FImage.Canvas.LineTo(m_AxisLine,aSitY);
FImage.Canvas.Pen.Color:=SHAPECOLOR;}
FImage.Canvas.TextOut(aSitX-LTEXTOFF,aSitY-5,'初见水位:'+FormatFloat('0.00',FFirstWaterHeigh));
end;
if FStableWaterHeigh<>FIRSTVALUE then
begin
FImage.Canvas.Pen.Style :=psDashDotDot;
FImage.Canvas.Pen.Color:=MARKCOLOR;
if FDrillStandHeigh<>FIRSTVALUE then
aSitY:=TOPLINEVOFF+round(abs(FDrillStandHeigh-FDrillTop-FStableWaterHeigh)*aRate)
else
aSitY:=TOPLINEVOFF+round(FStableWaterHeigh*aRate);
FImage.Canvas.MoveTo(aSHSitX,aSitY);
//FImage.Canvas.LineTo(aSHSitX,aSitY);
FImage.Canvas.LineTo(aSHSitX-100,aSitY);
{FImage.Canvas.MoveTo(m_AxisLine,aSitY);
FImage.Canvas.LineTo(m_AxisLine+5,aSitY-5);
FImage.Canvas.MoveTo(m_AxisLine+5,aSitY-5);
FImage.Canvas.LineTo(m_AxisLine-5,aSitY-5);
FImage.Canvas.MoveTo(m_AxisLine-5,aSitY-5);
FImage.Canvas.LineTo(m_AxisLine,aSitY);
FImage.Canvas.Pen.Color:=SHAPECOLOR;}
FImage.Canvas.TextOut(aSHSitX+5,aSitY-5,'稳定水位:'+FormatFloat('0.00',FStableWaterHeigh));
end;
if FPlanDepth<>FIRSTVALUE then
begin
FImage.Canvas.Pen.Style :=psDot;
FImage.Canvas.Pen.Color:=MARKCOLOR;
if FDrillStandHeigh<>FIRSTVALUE then
aSitY:=TOPLINEVOFF+round(abs(FDrillStandHeigh-FDrillTop-FPlanDepth)*aRate)
else
aSitY:=TOPLINEVOFF+round(FPlanDepth*aRate);
FImage.Canvas.MoveTo(aSitX,aSitY);
FImage.Canvas.LineTo(aSHSitX,aSitY);
FImage.Canvas.Pen.Color:=SHAPECOLOR;
FImage.Canvas.TextOut(aSitX-LTEXTOFF,aSitY-5,'计划深度:'+FormatFloat('0.00',FPlanDepth));
FImage.Canvas.MoveTo(aSitX,aSHSitY);
FImage.Canvas.LineTo(aSitX,aSitY);
FImage.Canvas.MoveTo(aSHSitX,aSHSitY);
FImage.Canvas.LineTo(aSHSitX,aSitY);
end;
if FFinishDepth<>FIRSTVALUE then
begin
if FImage.Canvas.Pen.Style<>psSolid then FImage.Canvas.Pen.Style :=psSolid;
if FDrillStandHeigh<>FIRSTVALUE then
aSitY:=TOPLINEVOFF+round(abs(FDrillStandHeigh-FDrillTop-FFinishDepth)*aRate)
else
aSitY:=TOPLINEVOFF+round(FFinishDepth*aRate);
FImage.Canvas.Pen.Color:=MARKCOLOR;
FImage.Canvas.MoveTo(aSitX,aSitY);
FImage.Canvas.LineTo(aSHSitX,aSitY);
FImage.Canvas.Pen.Color:=SHAPECOLOR;
FImage.Canvas.TextOut(aSHSitX+5,aSitY-5,'完成深度:'+FormatFloat('0.00',FFinishDepth));
FImage.Canvas.MoveTo(aSitX,aSHSitY);
FImage.Canvas.LineTo(aSitX,aSitY);
FImage.Canvas.MoveTo(aSHSitX,aSHSitY);
FImage.Canvas.LineTo(aSHSitX,aSitY);
end;
if FImage.Canvas.Pen.Style<>psSolid then FImage.Canvas.Pen.Style :=psSolid;
FImage.Canvas.Font.Color :=SHAPECOLOR;
FImage.Canvas.Brush.Style:=bsSolid;
end;
procedure TDrillDiagram.SetPubVar;
begin
if (FImage.Height<=TOPLINEVOFF) or (FImage.Width<=TBLINEHROFF) then
begin
if FImage.Height<=TOPLINEVOFF then FImage.Height:=TOPLINEVOFF+100;
if FImage.Width<=TBLINEHROFF then FImage.Width:=TBLINEHROFF+100;
end;
m_AxisLine:=FImage.Width DIV 2 - AXISLINEOFF;
m_RegionPixelHeigh:=FImage.Height-BOTTOMLINEVOFF-TOPLINEVOFF;
end;
procedure TDrillDiagram.SetTopBottom(aTop,aBottom:double;isForceSet:boolean=false);
var
aTmp:double;
begin
if isForceSet then
begin
FDrillTop:=aTop;
FDrillBottom:=aBottom;
end
else
begin
if aTop<aBottom then
begin
aTmp:=aTop;
aTop:=aBottom;
aBottom:=aTmp;
end;
if FDrillTop<aTop then FDrillTop:=aTop;
if FDrillBottom>aBottom then FDrillBottom:=aBottom;
end;
DrawDrillDiagram(false);
end;
procedure TDrillDiagram.Clear;
begin
FDrillTop:=CDRILLTOP;
FDrillBottom:=CDRILLBOTTOM;
FDrillStandHeigh:=FIRSTVALUE;
FDrillX:=FIRSTVALUE;
FDrillY:=FIRSTVALUE;
FFirstWaterHeigh:=FIRSTVALUE;
FStableWaterHeigh:=FIRSTVALUE;
FPipeDiameter:=FIRSTVALUE;
FPlanDepth:=FIRSTVALUE;
FFinishDepth:=FIRSTVALUE;
if FStratumList<>nil then FStratumList:=nil;
FStratumList:=TStringlist.Create;
if FBMList<>nil then FBMList:=nil;
FBMList:=TList.Create ;
end;
end.
|
unit Right;
interface
const
// REMINDER!!! Every time a new right is added.. be sure to check it gets displayed in the Rights form
//************* PRIVILEGES ****************//
// Client privileges
PRIV_CLIENT_ADD_NEW = 'PRIV_CLIENT_ADD_NEW;Add_new_client;CLIENT';
PRIV_CLIENT_MODIFY = 'PRIV_CLIENT_MODIFY;Modify_client_details;CLIENT';
// Loan privileges
PRIV_LOAN_ADD_NEW = 'PRIV_LOAN_ADD_NEW;Add_new_loan;LOAN';
PRIV_LOAN_ASSESS = 'PRIV_LOAN_ASSESS;Assess_pending_loan;LOAN';
PRIV_LOAN_APPROVE = 'PRIV_LOAN_APPROVE;Approve_loan;LOAN';
PRIV_LOAN_RELEASE = 'PRIV_LOAN_RELEASE;Release_loan;LOAN';
PRIV_LOAN_CANCEL = 'PRIV_LOAN_CANCEL;Cancel_loan;LOAN';
PRIV_LOAN_CLOSE = 'PRIV_LOAN_CLOSE;Close_loan_manually;LOAN';
// Payment privileges
PRIV_PAY_ADD_NEW = 'PRIV_PAY_ADD_NEW;Add_new_payment;PAY';
PRIV_PAY_CANCEL = 'PRIV_PAY_CANCEL;Cancel_payment;PAY';
PRIV_PAY_WD_ADD_NEW = 'PRIV_PAY_WD_ADD_NEW;Add_new_withdrawal;PAY';
PRIV_PAY_WD_MODIFY = 'PRIV_PAY_WD_MODIFY;Edit_withdrawal;PAY';
PRIV_PAY_WD_CANCEL = 'PRIV_PAY_WD_CANCEL;Cancel_withdrawal;PAY';
// Admin-related.. involves maintenance tables
PRIV_ADM_ADD_NEW = 'PRIV_ADM_ADD_NEW;Add_new_lookup_values;ADM';
PRIV_ADM_LC_ADD_NEW = 'PRIV_ADM_LC_ADD_NEW;Create_a_new_loan_classification;ADM';
PRIV_ADM_LC_MODIFY = 'PRIV_ADM_LC_MODIFY;Modify_existing_loan_classification;ADM';
PRIV_ADM_LC_VIEW = 'PRIV_ADM_LC_VIEW;View_loan_classifications;ADM';
PRIV_SETTINGS = 'PRIV_ADM_SETTINGS;View_and_modify_system_settings;ADM';
// Security privileges
PRIV_SEC_ROLE_ADD_NEW = 'PRIV_SEC_ROLE_ADD_NEW;Add_new_role;SEC';
PRIV_SEC_ROLE_MODIFY = 'PRIV_SEC_ROLE_ADD_MODIFY;Modify_roles_including_assigned_rights;SEC';
PRIV_SEC_ROLE_VIEW = 'PRIV_SEC_ROLE_VIEW;View_roles;SEC';
PRIV_SEC_USER_MODIFY = 'PRIV_SEC_USER_MODIFY;Modify_user_credentials_including_assigned_roles;SEC';
PRIV_SEC_USER_VIEW = 'PRIV_SEC_USER_VIEW;View_users;SEC';
// adjust the array size before adding an item
// array size is equal to the number of privileges
PRIVILEGES: array [1..23] of string =
(
PRIV_CLIENT_ADD_NEW,
PRIV_CLIENT_MODIFY,
PRIV_LOAN_ADD_NEW,
PRIV_LOAN_ASSESS,
PRIV_LOAN_APPROVE,
PRIV_LOAN_RELEASE,
PRIV_LOAN_CANCEL,
PRIV_LOAN_CLOSE,
PRIV_PAY_ADD_NEW,
PRIV_PAY_CANCEL,
PRIV_PAY_WD_ADD_NEW,
PRIV_PAY_WD_MODIFY,
PRIV_PAY_WD_CANCEL,
PRIV_ADM_ADD_NEW,
PRIV_ADM_LC_ADD_NEW,
PRIV_ADM_LC_MODIFY,
PRIV_ADM_LC_VIEW,
PRIV_SETTINGS,
PRIV_SEC_ROLE_ADD_NEW,
PRIV_SEC_ROLE_MODIFY,
PRIV_SEC_ROLE_VIEW,
PRIV_SEC_USER_MODIFY,
PRIV_SEC_USER_VIEW
);
//************* PRIVILEGES ****************//
type
TRight = class
strict private
FName: string;
FCode: string;
FAssignedOldValue: boolean;
private
FModified: boolean;
FAssignedNewValue: boolean;
function GetModified: boolean;
public
property Code: string read FCode write FCode;
property Name: string read FName write FName;
property AssignedOldValue: boolean read FAssignedOldValue write FAssignedOldValue;
property AssignedNewValue: boolean read FAssignedNewValue write FAssignedNewValue;
property Modified: boolean read GetModified;
end;
implementation
{ TRight }
function TRight.GetModified: boolean;
begin
Result := FAssignedOldValue <> FAssignedNewValue;
end;
end.
|
unit TRegFunctions;
interface
uses
Windows;
procedure regWrite(writeDir:String);
function regRead(readKey : String) : String;
function regKeyExists(checkingKey : String) : Boolean;
implementation
uses
Registry, strConsts;
///////////////////////////////regWrite////////////////////////////////////
procedure regWrite(writeDir : String);
var
writeRegPath : TRegistry;
begin
writeRegPath := TRegistry.Create();
try
writeRegPath.RootKey := HKEY_CURRENT_USER;
writeRegPath.OpenKey(OPEN_KEY_VALUE, true);
writeRegPath.WriteString(LAST_PATH, writeDir);
finally
writeRegPath.Free;
end;
end;
///////////////////////////////regRead////////////////////////////////////
function regRead(readKey : String) : String;
var
readRegPath : TRegistry;
readPath : String;
begin
readRegPath := TRegistry.Create();
try
readRegPath.RootKey := HKEY_CURRENT_USER;
readRegPath.OpenKey(OPEN_KEY_VALUE, true);
readPath := readRegPath.ReadString(readKey);
Result := readPath;
finally
readRegPath.Free();
end;
end;
///////////////////////////////regKeyExists////////////////////////////////////
function regKeyExists(checkingKey : String) : Boolean;
var
checkKey : TRegistry;
begin
checkKey := TRegistry.Create();
try
checkKey.RootKey := HKEY_CURRENT_USER;
checkKey.OpenKey(OPEN_KEY_VALUE, true);
Result := checkKey.ValueExists(checkingKey)
finally
checkKey.Free();
end;
end;
end.
|
{
Alignement_de_deux_mots.pas
Copyright 2010 tarik User <tarik@ubuntu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
}
// auteur : Djebien Tarik
// date : Mars 2010
// objet : Alignement de deux mots.
PROGRAM Alignement_de_deux_mots;
USES crt;
TYPE
Matrice = array of array of CARDINAL;
VAR
U,V : STRING;
Menu : Boolean;
c : char;
rec,dyn : CARDINAL;
// min(x,y,z) renvoie le plus petit élement
// parmi les trois en parametres.
function min(x,y,z:CARDINAL): CARDINAL;
var min1 : CARDINAL;
begin
if ( x >= y ) then
min1:= y
else
min1:= x;
if (min1 >= z) then
min:= z
else
min:= min1;
end{min};
// Calcule la distance d'edition de deux chaines
// de caracteres.
// VERSION RECURSIVE.
function distance_recursive(u,v:STRING): CARDINAL;
begin
// d(e,v) = |v|
// (on fait |v| insertions )
if ( u = '' ) then
distance_recursive:= length(v)
// d(u,e) = |u|
// (on fait |u| suppressions )
else if ( v = '' ) then
distance_recursive:= length(u)
// d(ua,va) = d(u,v)
else if ( u[length(u)] = v[length(v)] ) then
distance_recursive:= distance_recursive(copy(u,1,length(u)-1),copy(v,1,length(v)-1))
// d(ua,vb) = 1 + min(d(u,v),d(ua,v),d(u,vb))
// (la derniere operation est une substitution de la lettre a en b,
// ou une insertion de la lettre b, ou une suppression de la lettre a.)
else
distance_recursive:= 1 + min(distance_recursive(copy(u,1,length(u)-1),copy(v,1,length(v)-1)),
distance_recursive(u,copy(v,1,length(v)-1)),
distance_recursive(copy(u,1,length(u)-1),v)
);
// ou a et b sont deux lettres quelconques distinctes,
// e est le mot vide et |u| représente la longueur du mot u.
end{distance_recursive};
// Calcule la distance d'edition de deux chaines
// de caracteres.
// VERSION DYNAMIQUE.
function distance_dynamique(u,v:STRING): CARDINAL;
var
table : Matrice;
i,j : CARDINAL;
begin
// table indexee par u'first-1..u'last et v'first-1..v'last.
setlength(table,length(u)+1,length(v)+1);
// d(u,e) = |u|
for i:= 0 to length(u) do
table[i,0]:= i;
// d(e,v) = |v|
for j:= 0 to length(v) do
table[0,j]:= j;
// Parcours de la table
// sens de remplissage
for i:= 1 to length(u) do
for j:= 1 to length(v) do
begin
// d(ua,va) = d(u,v)
if (u[i]= v[j]) then
table[i,j]:= table[i-1,j-1]
else
// d(ua,vb) = 1 + min(d(u,v),d(ua,v),d(u,vb))
table[i,j]:= 1 + min(table[i-1,j],table[i,j-1],table[i-1,j-1]);
end;//for
// le resultat est D(u'last,v'last)
distance_dynamique:= table[length(u),length(v)];
end{distance_dynamique};
// Retourne la table des distances d'editions de deux chaines
// de caracteres apres sa construction par programmation dynamique.
function getTableDynamique(u,v:STRING): Matrice;
var
table : Matrice;
i,j : CARDINAL;
begin
// Meme Algorithme que precedemment
setlength(table,length(u)+1,length(v)+1);
for i:= 0 to length(u) do
table[i,0]:= i;
for j:= 0 to length(v) do
table[0,j]:= j;
for i:= 1 to length(u) do
for j:= 1 to length(v) do
begin
if (u[i]= v[j]) then
table[i,j]:= table[i-1,j-1]
else
table[i,j]:= 1 + min(table[i-1,j],table[i,j-1],table[i-1,j-1]);
end;//for
// On retourne la table construite
getTableDynamique:= table;
end{getTableDynamique};
//procedure d'affichage de notre table dynamique
procedure afficherTableau(const M: Matrice ; const u,v: STRING);
var
i,j: CARDINAL;
begin
writeln('La table dynamique de ',u,' et ',v,' : ');
writeln;
write(' ');
for i:= 1 to length(v) do
write(v[i],' ');writeln;
for i:= 0 to length(v) do
write('---');writeln;
for i:= 0 to length(v) do
write(i,' ');writeln('|');
for i:= 0 to length(v)+2 do
write('---');writeln;
for i:= 0 to length(u) do
begin
for j:= 0 to length(v) do
write(M[i,j],' ');
write('| ',i,' | ');
if i <> 0 then write(u[i]);
writeln;
end;
end{afficherTableau};
procedure afficher(u,v: STRING);
var
t: Matrice;
s1,s2,s3: STRING;
i,j,k: CARDINAL;
begin
// Initialisation
s1:='';
s2:='';
s3:='';
i:=length(u);
j:=length(v);
t:= getTableDynamique(u,v);
while ((i>0) and (j>0)) do begin
// Dans le cas ou :
// On a une identite
if ((t[i][j] = t[i-1][j-1]) and (u[i] = v[j])) then begin
s1:=u[i]+s1;
s2:='|'+s2;
s3:=v[j]+s3;
i:=i-1;
j:=j-1;
end else begin
// On a une substitution
if ((t[i][j] = t[i-1][j-1]+1) and (u[i] <> v[j])) then begin
s1:=u[i]+s1;
s2:=' '+s2;
s3:=v[j]+s3;
i:=i-1;
j:=j-1;
end else begin
// On a une suppression
if (t[i][j]=t[i-1][j]+1) then begin
s1:=u[i]+s1;
s2:=' '+s2;
s3:='-'+s3;
i:=i-1;
end else begin
//si on a une insertion
if (t[i][j]=t[i][j-1]+1) then begin
s1:='-'+s1;
s2:=' '+s2;
s3:=v[j]+s3;
j:=j-1;
end;
end;
end;
end;
end;
// Dans le cas ou i=1 mais j>1
// i.e : le deuxieme mot est plus grand
// => insertion du surplus dans le deuxieme mot
if (i<=0) and (j>0) then begin
for k:=j downto 1 do begin
s1:='-'+s1;
s2:=' '+s2;
s3:=v[k]+s3;
end;
end;
// Dans le cas ou j=1 mais i>1
// i.e : le premier mot est plus grand
// => insertion du surplus dans le premier mot
if (i>0) and (j<=0) then begin
for k:=i downto 1 do begin
s1:=u[k]+s1;
s2:=' '+s2;
s3:='-'+s3;
end;
end;
// Affichage sur la sortie standard
writeln; // Exemple :
writeln(' ',s1);// a l - u m i n i u m
writeln(' ',s2);// | | | | | |
writeln(' ',s3);// a l b u m i n e - -
end{afficher};
(* PROGRAMME PRINCIPAL *)
BEGIN
clrscr;
Menu:= true;
writeln(' Algorithmique et Structure de Donnees');
writeln(' TP3: Programmation dynamique');
writeln(' Exercice 2');
writeln;
repeat
begin
// Saisie des deux mots sur l'entree standard
write('Entrer le premier mot : ');readln(U);
write('Entrer le deuxieme mot : ');readln(V);
writeln;
// Affichage de la Table
afficherTableau(getTableDynamique(U,V),U,V);
writeln;
writeln(' VERSION RECURSIVE : ');writeln;
rec:= distance_recursive(U,V);
writeln('distance_recursive(',U,',',V,') = ',rec);
writeln('La distance d''edition entre ',U,' et ',V,' vaut : ',rec);
writeln;
writeln(' VERSION DYNAMIQUE : ');writeln;
dyn:= distance_dynamique(U,V);
writeln('distance_dynamique(',U,',',V,') = ',dyn);
writeln('La distance d''edition entre ',U,' et ',V,' vaut : ',dyn);
// Affichage de la suite des operations
writeln;
writeln(' Affichage de la suite des operations : ');
writeln;
writeln(' Notation : ');
writeln(' - l''identite, que l''on note | ');
writeln(' - la substitution, que l''on note '' '' ');
writeln(' - l''insertion, que l''on note - sur le mot de depart');
writeln(' - la suppression, que l''on note - sur le mot d''arrivee');
writeln;
writeln('Schema de visualisation des transformations : ');
afficher(U,V);
writeln;
// Nouveau Test
writeln('Souhaiteriez vous reiterer le test ? (Y = oui, N = non )');
write('Reponse : ');readln(c);
if ((c = 'N') or (c = 'n')) then Menu := false else clrscr;
end;
until Menu = false;
writeln;
writeln(' Author : Djebien Tarik ');
writeln;
writeln(' END OF EXECUTION,');
write(' PRESS ANY KEY TO EXIT THIS PROGRAM.');
repeat until keypressed;
clrscr;
END.
|
unit Vigilante.Compilacao.Model.Impl;
interface
uses
System.Generics.Collections, Model.Base.Impl, Vigilante.Aplicacao.SituacaoBuild,
Vigilante.ChangeSetItem.Model, Module.ValueObject.URL, Vigilante.Compilacao.Model;
type
TCompilacaoModel = class(TModelBase, ICompilacaoModel)
private
FNumero: integer;
FChangeSet: TObjectList<TChangeSetItem>;
FSituacao: TSituacaoBuild;
FURL: IURL;
FBuilding: boolean;
FNome: string;
protected
function GetChangeSet: TObjectList<TChangeSetItem>;
function GetNome: string;
function GetNumero: integer;
function GetSituacao: TSituacaoBuild;
function GetURL: string;
function GetBuilding: boolean;
public
constructor Create(const ANumero: integer; const ANome: string;
const AURL: IURL; const ASituacao: TSituacaoBuild;
const ABuilding: boolean; const AChangeSet: TArray<TChangeSetItem>);
destructor Destroy; override;
function Equals(const ACompilacaoModel: ICompilacaoModel): boolean; reintroduce;
end;
implementation
uses
System.SysUtils, System.StrUtils;
constructor TCompilacaoModel.Create(const ANumero: integer; const ANome: string;
const AURL: IURL; const ASituacao: TSituacaoBuild;
const ABuilding: boolean; const AChangeSet: TArray<TChangeSetItem>);
var
i: integer;
begin
inherited Create;
FChangeSet := TObjectList<TChangeSetItem>.Create;
FNumero := ANumero;
FNome := ANome;
FURL := AURL;
FSituacao := ASituacao;
FBuilding := ABuilding;
if not Assigned(AChangeSet) then
Exit;
for i := 0 to Length(AChangeSet) - 1 do
FChangeSet.Add(AChangeSet[i]);
end;
destructor TCompilacaoModel.Destroy;
begin
FreeAndNil(FChangeSet);
inherited;
end;
function TCompilacaoModel.Equals(
const ACompilacaoModel: ICompilacaoModel): boolean;
begin
Result := false;
if not ACompilacaoModel.Numero = Self.FNumero then
Exit;
if not ACompilacaoModel.Nome.Equals(Self.FNome) then
Exit;
if not ACompilacaoModel.URL.Equals(Self.FURL.AsString) then
Exit;
if not ACompilacaoModel.Situacao.Equals(Self.FSituacao) then
Exit;
if not ACompilacaoModel.Building = Self.FBuilding then
Exit;
if not ACompilacaoModel.Id.ToString.Equals(GetId.ToString) then
Exit;
Result := True;
end;
function TCompilacaoModel.GetChangeSet: TObjectList<TChangeSetItem>;
begin
Result := FChangeSet;
end;
function TCompilacaoModel.GetNome: string;
begin
Result := FNome;
end;
function TCompilacaoModel.GetNumero: integer;
begin
Result := FNumero;
end;
function TCompilacaoModel.GetSituacao: TSituacaoBuild;
begin
Result := FSituacao;
end;
function TCompilacaoModel.GetURL: string;
begin
Result := FURL.AsString;
end;
function TCompilacaoModel.GetBuilding: boolean;
begin
Result := FBuilding;
end;
end.
|
{The memory manager benchmark taken from the NexusDB website (www.nexusdb.com).
Two changes: (1) Monitoring of memory usage was added (shouldn't impact scores
much) and (2) lowered max items from 4K to 2K to lower memory consumption so
that the higher thread count tests can be run on computers with 256M RAM.
Changes from the original benchmark are indicated by a "PLR" in the comment}
// RH 17/04/2005
// class function IterationCount in order to have reasonable benchmark execution times
// IterationCount can be defined in each individual benchmark
unit NexusDBBenchmarkUnit;
{$mode delphi}
interface
uses Windows, SysUtils, Classes, BenchmarkClassUnit, Math;
type
TNexusBenchmark = class(TFastcodeMMBenchmark)
protected
FSemaphore: THandle;
public
constructor CreateBenchmark; override;
destructor Destroy; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function NumThreads: integer; virtual; abstract;
class function GetBenchmarkWeight: Double; override;
procedure RunBenchmark; override;
class function GetCategory: TBenchmarkCategory; override;
class function IterationCount: integer; virtual;
end;
TNexusBenchmark1Thread = class(TNexusBenchmark)
public
class function NumThreads: integer; override;
end;
TNexusBenchmark2Threads = class(TNexusBenchmark)
public
class function NumThreads: integer; override;
class function IterationCount: integer; override;
end;
TNexusBenchmark4Threads = class(TNexusBenchmark)
public
class function NumThreads: integer; override;
class function IterationCount: integer; override;
end;
TNexusBenchmark8Threads = class(TNexusBenchmark)
public
class function NumThreads: integer; override;
class function IterationCount: integer; override;
end;
TNexusBenchmark12Threads = class(TNexusBenchmark)
public
class function NumThreads: integer; override;
class function RunByDefault: boolean; override;
end;
TNexusBenchmark16Threads = class(TNexusBenchmark)
public
class function NumThreads: integer; override;
class function RunByDefault: boolean; override;
end;
TNexusBenchmark32Threads = class(TNexusBenchmark)
public
class function NumThreads: integer; override;
class function RunByDefault: boolean; override;
end;
implementation
const
MaxItems = 7;
TestClass : array [1..MaxItems] of TClass =
(TStringlist, TObject, Tlist, TBits, TCollectionItem, TCollection, TStream);
type
TTestThread = class(TThread)
protected
FBenchmark: TNexusBenchmark;
public
procedure Execute; override;
constructor Create(ABenchmark: TNexusBenchmark);
end;
{ TTestThread }
constructor TTestThread.Create(ABenchmark: TNexusBenchmark);
begin
inherited Create(False);
FreeOnTerminate := True;
Priority := tpNormal;
FBenchmark := ABenchmark;
end;
procedure TTestThread.Execute;
var
k : Integer;
i, j : Integer;
p : Pointer;
aString: string;
begin
// direct memory allocation
with TList.Create do
try
for i := 0 to FBenchmark.IterationCount do // RH replaced 1 * 1000 * 1000 by FBenchmark.IterationCount
begin
j:=Random(16*1024);
GetMem(p, j);
k:=0;
while k<j do begin
pchar(p)[k]:=#13;
inc(k,4*1024);
end;
if j>0 then
pchar(p)[j-1]:=#13;
Add(p);
//PLR - Reduced the count from 4K to 2K to lower memory usage
j := Random(2 * 1024);
if j < Count then begin
p := List[j];
Delete(j);
FreeMem(p);
end;
//PLR - Added to measure usage every 64K iterations
if i and $ffff = 0 then
FBenchmark.UpdateUsageStatistics;
end;
for i := Pred(Count) downto 0 do
begin
FreeMem(List[i]);
end;
finally
Free;
end;
// component creation
with TList.Create do
try
for i := 0 to FBenchmark.IterationCount do // RH replaced 1 * 1000 * 1000 by FBenchmark.IterationCount
begin
j := Random(MaxItems);
Add(TestClass[j+1].Create());
//PLR - Reduced the count from 4K to 2K to lower memory usage
j := Random(2 * 1024);
if j < Count then
begin
TComponent(List[j]).Free;
Delete(j);
end;
//PLR - Added to measure usage every 64K iterations
if i and $ffff = 0 then
FBenchmark.UpdateUsageStatistics;
end;
for i := Pred(Count) downto 0 do
begin
TComponent(List[i]).Free;
end;
finally
Free;
end;
// strings and stringlist
with TStringList.Create do
try
for i := 0 to FBenchmark.IterationCount do // RH replaced 1 * 1000 * 1000 by FBenchmark.IterationCount
begin
aString:='';
for j := 0 to Random(250) do
begin // Iterate
aString:=aString+'A';
end; // for
Add(aString);
//PLR - Added to measure usage every 4K iterations
if i and $fff = 0 then
FBenchmark.UpdateUsageStatistics;
//PLR - Reduced the count from 4K to 2K to lower memory usage
j := Random(2 * 1024);
if j < Count then
begin
Delete(j);
end;
end;
finally
Free;
end;
{Notify that the thread is done}
ReleaseSemaphore(FBenchmark.FSemaphore, 1, nil);
end;
{ TNexusBenchmark }
constructor TNexusBenchmark.CreateBenchmark;
begin
inherited;
FSemaphore := CreateSemaphore(nil, 0, 9999, nil);
end;
destructor TNexusBenchmark.Destroy;
begin
CloseHandle(FSemaphore);
inherited;
end;
class function TNexusBenchmark.GetBenchmarkDescription: string;
begin
Result := 'The benchmark taken from www.nexusdb.com. Memory usage was '
+ 'slightly reduced to accommodate machines with 256MB RAM with up to 8 threads.';
end;
class function TNexusBenchmark.GetBenchmarkName: string;
begin
Result := 'NexusDB with ' + IntToStr(NumThreads) + ' thread(s)';
end;
class function TNexusBenchmark.GetBenchmarkWeight: Double;
begin
{The Nexus benchmark is represented four times, so reduce weighting}
Result := 0.5;
end;
class function TNexusBenchmark.GetCategory: TBenchmarkCategory;
begin
Result := bmMultiThreadRealloc;
end;
class function TNexusBenchmark.IterationCount: integer;
begin
Result := 1 * 1000 * 1000;
end;
procedure TNexusBenchmark.RunBenchmark;
var
i : Integer;
begin
{Call the inherited method to reset the peak usage}
inherited;
{Create and start the threads}
for i := 1 to NumThreads do
TTestThread.Create(Self);
{Wait for threads to finish}
for i := 1 to NumThreads do
WaitForSingleObject(FSemaphore, INFINITE);
end;
{ TNexusBenchmark1Thread }
class function TNexusBenchmark1Thread.NumThreads: integer;
begin
Result := 1;
end;
{ TNexusBenchmark2Threads }
class function TNexusBenchmark2Threads.IterationCount: integer;
begin
Result := 500 * 1000; // RH 50% of the original value
end;
class function TNexusBenchmark2Threads.NumThreads: integer;
begin
Result := 2;
end;
{ TNexusBenchmark4Threads }
class function TNexusBenchmark4Threads.IterationCount: integer;
begin
Result := 250 * 1000; // RH 50% of the original value
end;
class function TNexusBenchmark4Threads.NumThreads: integer;
begin
Result := 4;
end;
{ TNexusBenchmark8Threads }
class function TNexusBenchmark8Threads.IterationCount: integer;
begin
Result := 125 * 1000; // RH 25% of the original value
end;
class function TNexusBenchmark8Threads.NumThreads: integer;
begin
Result := 8;
end;
{ TNexusBenchmark12Threads }
class function TNexusBenchmark12Threads.NumThreads: integer;
begin
Result := 12;
end;
class function TNexusBenchmark12Threads.RunByDefault: boolean;
begin
Result := False;
end;
{ TNexusBenchmark16Threads }
class function TNexusBenchmark16Threads.NumThreads: integer;
begin
Result := 16;
end;
class function TNexusBenchmark16Threads.RunByDefault: boolean;
begin
Result := False;
end;
{ TNexusBenchmark32Threads }
class function TNexusBenchmark32Threads.NumThreads: integer;
begin
Result := 32;
end;
class function TNexusBenchmark32Threads.RunByDefault: boolean;
begin
Result := False;
end;
end.
|
unit unt_Excel;
interface
uses
SysUtils, Classes, ComObj, contnrs, unt_ExcelCommonClass, Variants;
function CreateExcelApp: variant;
function CreateWorkBook(ExcelApp: Variant): variant;
function CreateWorksheet(WorkBook: Variant): Variant;
function RefToCell(RowID, ColID: Integer): string;
procedure SaveAsExcelFile(aSheets: TSheets; AFileName: string);
function LoadExcelFile(var aSheets: TSheets; AFileName: string): Variant;
implementation
function CreateExcelApp: variant;
begin
try
Result := CreateOleObject('Excel.Application');
Result.UserControl := True;
Result.DisplayAlerts := False;
Result.Visible := False;
except
//showMessage('Não foi possível abrir o Excel');
Result := varNull;
end;
end;
function CreateWorkBook(ExcelApp: Variant): variant;
begin
try
Result := ExcelApp.Workbooks.Add(xlWBATWorksheet);
except
//showMessage('Não foi possível criar uma nova planilha');
Result := varNull;
end;
end;
function OpenWorkBook(ExcelApp: Variant): variant;
begin
try
Result := ExcelApp.Workbooks.Open(ExcelApp);
except
//showMessage('Não foi possível criar uma nova planilha');
Result := varNull;
end;
end;
function CreateWorksheet(WorkBook: Variant): Variant;
begin
try
Result := WorkBook.WorkSheets.Add;
except
//showMessage('Não foi possível criar uma nova planilha');
Result := varNull;
end;
end;
function RefToCell(RowID, ColID: Integer): string;
var
ACount, APos: Integer;
begin
ACount := ColID div 26;
APos := ColID mod 26;
if APos = 0 then
begin
ACount := ACount - 1;
APos := 26;
end;
if ACount = 0 then
Result := Chr(Ord('A') + ColID - 1) + IntToStr(RowID);
if ACount = 1 then
Result := 'A' + Chr(Ord('A') + APos - 1) + IntToStr(RowID);
if ACount > 1 then
Result := Chr(Ord('A') + ACount - 1) + Chr(Ord('A') + APos - 1) + IntToStr(RowID);
end;
procedure SaveAsExcelFile(aSheets: TSheets; AFileName: string);
var
XLApp, XLWorkbook: OLEVariant;
Sheet: Variant;
Data: TSheet;
i: integer;
begin
XLApp := CreateExcelApp;
XLApp.Visible := False;
XLWorkbook := CreateWorkBook(XLApp);
try
for i := MAXIMO_CAPTURAS downto 1 do
begin
Data := aSheets[i];
if (Trim(Data.Name) <> '') then
begin
CreateWorksheet(XLWorkbook);
Sheet := XLWorkbook.ActiveSheet;
Sheet.Name := Data.Name;
Sheet.Range[RefToCell(1, 1), RefToCell(VarArrayHighBound(Data.Data, 1), VarArrayHighBound(Data.Data, 2))].Value := Data.Data;
Sheet.Range[RefToCell(1, 1), RefToCell(VarArrayHighBound(Data.Data, 1), VarArrayHighBound(Data.Data, 2))].Columns.AutoFit;
end;
end;
if XLApp.WorkBooks[1].Sheets.Count > 1 then
begin
XLApp.WorkBooks[1].Sheets['Plan1'].Select;
XLApp.ActiveWindow.SelectedSheets.Delete;
XLApp.WorkBooks[1].Sheets[1].Select;
end;
finally
XLWorkbook.SaveAs(AFileName);
if not VarIsEmpty(XLApp) then
begin
XLApp.DisplayAlerts := False;
XLApp.Quit;
XLAPP := Unassigned;
Sheet := Unassigned;
end;
end;
end;
function LoadExcelFile(var aSheets: TSheets; AFileName: string): Variant;
var
XLApp, XLWorkbook: OLEVariant;
i: integer;
begin
XLApp := CreateExcelApp;
XLApp.Visible := False;
XLApp.Workbooks.Open(AFileName);
for i := 1 to XLApp.Workbooks.Count do
begin
end;
end;
end.
|
(***********************************************************)
(* xPLRFX *)
(* part of Digital Home Server project *)
(* http://www.digitalhomeserver.net *)
(* info@digitalhomeserver.net *)
(***********************************************************)
unit uxPLRFX_0x19;
interface
Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages;
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray);
implementation
Uses SysUtils;
(*
Type $19 - Blinds1 - RollerTrol, Hasta, A-OK, Raex, Media Mount
Buffer[0] = packetlength = $09;
Buffer[1] = packettype
Buffer[2] = subtype
Buffer[3] = seqnbr
Buffer[4] = id1
Buffer[5] = id2
Buffer[6] = id3
Buffer[7] = unitcode
Buffer[8] = cmnd
Buffer[9] = battery_level:4/rssi:4
Test Strings :
0919040600A21B010280
xPL Schema
control.basic
{
device=0x000001-0xffffff
unit=0-15|all
current=open|close|stop|confirm_pair|set_limit|set_lower_limit|delete_limits|change_direction|left|right
protocol=<blinds0-blinds5>
}
*)
const
// Packet length
PACKETLENGTH = $09;
// Type
BLINDS1 = $19;
// Subtype
BLINDST0 = $00; // Rollertrol, Hasta new
BLINDST1 = $01; // Hasta old
BLINDST2 = $02; // A-OK RF01
BLINDST3 = $03; // A-OK AC114
BLINDST4 = $04; // Raex YR1326
BLINDST5 = $05; // Media Mount
// Commands
COMMAND_OPEN = 'open';
COMMAND_CLOSE = 'close';
COMMAND_STOP = 'stop';
COMMAND_CONFIRM = 'confirm_pair';
COMMAND_SET_LIMIT = 'set_limit';
COMMAND_SET_LOWER_LIMIT = 'set_lower_limit';
COMMAND_DELETE_LIMITS = 'delete_limits';
COMMAND_CHANGE_DIRECTION = 'change_direction';
COMMAND_LEFT = 'left';
COMMAND_RIGHT = 'right';
var
// Lookup table for commands
RFXCommandArray : array[1..10] of TRFXCommandRec =
((RFXCode : $00; xPLCommand : COMMAND_OPEN),
(RFXCode : $01; xPLCommand : COMMAND_CLOSE),
(RFXCode : $02; xPLCommand : COMMAND_STOP),
(RFXCode : $03; xPLCommand : COMMAND_CONFIRM),
(RFXCode : $04; xPLCommand : COMMAND_SET_LIMIT),
(RFXCode : $05; xPLCommand : COMMAND_SET_LOWER_LIMIT),
(RFXCode : $06; xPLCommand : COMMAND_DELETE_LIMITS),
(RFXCode : $07; xPLCommand : COMMAND_CHANGE_DIRECTION),
(RFXCode : $08; xPLCommand : COMMAND_LEFT),
(RFXCode : $09; xPLCommand : COMMAND_RIGHT)
);
SubTypeArray : array[1..6] of TRFXSubTypeRec =
((SubType : BLINDST0; SubTypeString : 'blindst0'),
(SubType : BLINDST1; SubTypeString : 'blindst1'),
(SubType : BLINDST2; SubTypeString : 'blindst2'),
(SubType : BLINDST3; SubTypeString : 'blindst3'),
(SubType : BLINDST4; SubTypeString : 'blindst4'),
(SubType : BLINDST5; SubTypeString : 'blindst5'));
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
var
DeviceID : String;
Current : String;
UnitCode : Integer;
xPLMessage : TxPLMessage;
begin
DeviceID := '0x'+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2)+IntToHex(Buffer[6],2);
Current := GetxPLCommand(Buffer[8],RFXCommandArray);
UnitCode := Buffer[7];
// Create control.basic message
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'control.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+current);
if UnitCode = $10 then
xPLMessage.Body.AddKeyValue('unit=all')
else
xPLMessage.Body.AddKeyValue('unit='+IntToStr(UnitCode));
xPLMessage.Body.AddKeyValue('protocol='+GetSubTypeString(Buffer[2],SubTypeArray));
xPLMessages.Add(xPLMessage.RawXPL);
end;
procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray);
begin
ResetBuffer(Buffer);
Buffer[0] := PACKETLENGTH;
Buffer[1] := BLINDS1; // Type
Buffer[2] := GetSubTypeFromString(aMessage.Body.Strings.Values['protocol'],SubTypeArray);
Buffer[4] := StrToInt('$'+Copy(aMessage.Body.Strings.Values['device'],3,2));
Buffer[5] := StrToInt('$'+Copy(aMessage.Body.Strings.Values['device'],5,2));
Buffer[6] := StrToInt('$'+Copy(aMessage.Body.Strings.Values['device'],7,2));
if CompareText(aMessage.Body.Strings.Values['unit'],'all') = 0 then
Buffer[7] := $10
else
Buffer[7] := StrToInt(aMessage.Body.Strings.Values['unit']);
Buffer[8] := GetRFXCode(aMessage.Body.Strings.Values['current'],RFXCommandArray);
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
const PocetSortov = 6;
type TZoznam = array[1..PocetSortov] of string;
type
THlavneOkno = class(TForm)
PaintBoxBubble: TPaintBox;
PaintBoxQuick: TPaintBox;
TextBubbleSort: TLabel;
TextQuickSort: TLabel;
Bevel1: TBevel;
Bevel2: TBevel;
TlacitkoZacniTriedit: TButton;
EditPocet: TEdit;
Bevel3: TBevel;
PaintBoxSelection: TPaintBox;
TextSelection: TLabel;
Bevel4: TBevel;
PaintBoxShell: TPaintBox;
TextShell: TLabel;
Bevel5: TBevel;
PaintBoxRadix: TPaintBox;
TextRadix: TLabel;
ImageVystup: TImage;
TextVysledky: TLabel;
TextPocetPrvkov: TLabel;
Bevel6: TBevel;
PaintBoxMerge: TPaintBox;
TextMerge: TLabel;
procedure ObnovZoznam( ObnovZoznam : TZoznam );
procedure TlacitkoZacniTrieditClick(Sender: TObject);
procedure ZrusJedenThread( Sender : TObject );
procedure EditPocetExit(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
HlavneOkno: THlavneOkno;
PocetPrvkov : Word;
KohoZrusit : Word;
implementation
Uses Unit2;
var QuickPole : TPole;
BubblePole : TPole;
SelectionPole : TPole;
ShellPole : TPole;
RadixPole : TPole;
MergePole : TPole;
BeziaceSorty : Word;
Vysledky : TZoznam;
const Mena : TZoznam = ('Bubble','Quick','Selection','Shell','Radix','Merge');
{$R *.DFM}
procedure NahodnePole;
var a, c : Word;
begin
for a := 1 to PocetPrvkov do
begin
c := Random( 500 );
QuickPole[ a ] := c;
end;
BubblePole := QuickPole;
SelectionPole := QuickPole;
ShellPole := QuickPole;
RadixPole := QuickPole;
MergePole := QuickPole;
for a := 1 to PocetSortov do
Vysledky[a] := '';
end;
procedure THlavneOkno.ObnovZoznam( ObnovZoznam : TZoznam );
var a : Word;
begin
with ImageVystup.Canvas do
begin
for a := 1 to PocetSortov do
TextOut( ImageVystup.ClientRect.Left + 10 , ImageVystup.ClientRect.Left + ((a-1)*20) ,
ObnovZoznam[ a ] );
end;
end;
procedure THlavneOkno.ZrusJedenThread( Sender : TObject );
begin
Dec( BeziaceSorty );
if BeziaceSorty = 0 then
begin
TlacitkoZacniTriedit.Enabled := True;
EditPocet.Enabled := True;
end;
Vysledky[ PocetSortov-BeziaceSorty ] := IntToStr(PocetSortov-BeziaceSorty) + '. ' + Mena[ KohoZrusit ];
ObnovZoznam( Vysledky );
end;
procedure THlavneOkno.TlacitkoZacniTrieditClick(Sender: TObject);
begin
TlacitkoZacniTriedit.Enabled := False;
EditPocet.Enabled := False;
NahodnePole;
ImageVystup.Canvas.FillRect( ImageVystup.ClientRect );
BeziaceSorty := PocetSortov;
with TBubbleSort.Create( PaintBoxBubble , BubblePole , PocetPrvkov ) do
OnTerminate := ZrusJedenThread;
with TQuickSort.Create( PaintBoxQuick , QuickPole , PocetPrvkov ) do
OnTerminate := ZrusJedenThread;
with TSelectionSort.Create( PaintBoxSelection , SelectionPole , PocetPrvkov ) do
OnTerminate := ZrusJedenThread;
with TShellSort.Create( PaintBoxShell , ShellPole , PocetPrvkov ) do
OnTerminate := ZrusJedenThread;
with TRadixSort.Create( PaintBoxRadix , RadixPole , PocetPrvkov ) do
OnTerminate := ZrusJedenThread;
with TMergeSort.Create( PaintBoxMerge , MergePole , PocetPrvkov ) do
OnTerminate := ZrusJedenThread;
end;
procedure THlavneOkno.EditPocetExit(Sender: TObject);
var Zaloha : Word;
Code : integer;
begin
Zaloha := PocetPrvkov;
Val( EditPocet.Text , PocetPrvkov , Code );
if Code <> 0 then PocetPrvkov := Zaloha;
end;
procedure THlavneOkno.FormCreate(Sender: TObject);
begin
with ImageVystup.Canvas do
begin
Brush.Color := clBtnFace;
Pen.Color := clBlack;
FillRect( ImageVystup.ClientRect );
end;
PocetPrvkov := 100;
end;
end.
|
(* Ejercicio 21
Con el resultado del ejercicio 14 del práctico 1, escriba un programa para
determinar la raíz cuadrada de un número positivo a mediante el cálculo de a^0.5.
La entrada consistirá en una sola línea conteniendo el número real a.
Exhíba a, a^0.5, y sqrt(a) con etiquetas apropiadas.
Ejemplo de entrada : 12.7.
Ejemplo de salida : Valor introducido = 1.2700000000e+00
Raiz cuadrada calculada = 3.5637059362e+00
Raiz cuadrada de Pascal = 3.5637059362e+00. *)
program ejercicio21;
var a, pot, raiz : real;
begin
writeln('Ingrese valor de a.');
read(a);
pot := exp((1/2)*ln(a));
raiz := sqrt(a);
writeln('El introducido = ',a);
writeln('Raiz cuadrada calculada = ',pot);
writeln('Raiz cuadrada de Pascal = ', raiz)
end.
|
unit IdStackConsts;
interface
{This should be the only unit except OS Stack units that reference
Winsock or lnxsock}
uses
{$IFDEF LINUX}
Libc;
{$ELSE}
IdWinsock2;
{$ENDIF}
type
TIdStackSocketHandle = TSocket;
var
Id_SO_True: Integer = 1;
Id_SO_False: Integer = 0;
const
{$IFDEF LINUX}
Id_IP_MULTICAST_TTL = IP_MULTICAST_TTL; // TODO integrate into IdStackConsts
Id_IP_MULTICAST_LOOP = IP_MULTICAST_LOOP; // TODO integrate into IdStackConsts
Id_IP_ADD_MEMBERSHIP = IP_ADD_MEMBERSHIP; // TODO integrate into IdStackConsts
Id_IP_DROP_MEMBERSHIP = IP_DROP_MEMBERSHIP; // TODO integrate into IdStackConsts
{$ELSE}
Id_IP_MULTICAST_TTL = 10; // TODO integrate into IdStackConsts FIX ERROR in IdWinsock
Id_IP_MULTICAST_LOOP = 11; // TODO integrate into IdStackConsts FIX ERROR in IdWinsock
Id_IP_ADD_MEMBERSHIP = 12; // TODO integrate into IdStackConsts FIX ERROR in IdWinsock
Id_IP_DROP_MEMBERSHIP = 13; // TODO integrate into IdStackConsts FIX ERROR in IdWinsock
{$ENDIF}
(*
There seems to be an error in the correct values of multicast values in IdWinsock
The values should be:
ip_options = 1; //* set/get IP options */
ip_hdrincl = 2; //* header is included with data */
ip_tos = 3; //* IP type of service and preced*/
ip_ttl = 4; //* IP time to live */
ip_multicast_if = 9; //* set/get IP multicast i/f */
ip_multicast_ttl = 10; //* set/get IP multicast ttl */
ip_multicast_loop = 11; //*set/get IP multicast loopback */
ip_add_membership = 12; //* add an IP group membership */
ip_drop_membership = 13; //* drop an IP group membership */
ip_dontfragment = 14; //* don't fragment IP datagrams */ {Do not Localize}
*)
{$IFDEF LINUX}
TCP_NODELAY = 1;
{$ENDIF}
// Protocol Family
Id_PF_INET = PF_INET;
// Socket Type
Id_SOCK_STREAM = Integer(SOCK_STREAM);
Id_SOCK_DGRAM = Integer(SOCK_DGRAM);
Id_SOCK_RAW = Integer(SOCK_RAW);
// IP Protocol type
Id_IPPROTO_IP = IPPROTO_IP;
Id_IPPROTO_ICMP = IPPROTO_ICMP;
Id_IPPROTO_IGMP = IPPROTO_IGMP;
Id_IPPROTO_TCP = IPPROTO_TCP;
Id_IPPROTO_UDP = IPPROTO_UDP;
Id_IPPROTO_RAW = IPPROTO_RAW;
Id_IPPROTO_MAX = IPPROTO_MAX;
// Socket Option level
Id_SOL_SOCKET = SOL_SOCKET;
// Socket options
Id_SO_BROADCAST = SO_BROADCAST;
Id_SO_DEBUG = SO_DEBUG;
Id_SO_DONTROUTE = SO_DONTROUTE;
Id_SO_KEEPALIVE = SO_KEEPALIVE;
Id_SO_LINGER = SO_LINGER;
Id_SO_OOBINLINE = SO_OOBINLINE;
Id_SO_RCVBUF = SO_RCVBUF;
Id_SO_REUSEADDR = SO_REUSEADDR;
Id_SO_SNDBUF = SO_SNDBUF;
// Additional socket options
Id_SO_RCVTIMEO = SO_RCVTIMEO;
Id_SO_SNDTIMEO = SO_SNDTIMEO;
Id_IP_TTL = IP_TTL;
//
Id_INADDR_ANY = INADDR_ANY;
Id_INADDR_NONE = INADDR_NONE;
// TCP Options
Id_TCP_NODELAY = TCP_NODELAY;
Id_INVALID_SOCKET = INVALID_SOCKET;
Id_SOCKET_ERROR = SOCKET_ERROR;
//
{$IFDEF LINUX}
// Shutdown Options
Id_SD_Recv = SHUT_RD;
Id_SD_Send = SHUT_WR;
Id_SD_Both = SHUT_RDWR;
Id_SD_Default = Id_SD_Both;
//
Id_WSAEINTR = EINTR;
Id_WSAEBADF = EBADF;
Id_WSAEACCES = EACCES;
Id_WSAEFAULT = EFAULT;
Id_WSAEINVAL = EINVAL;
Id_WSAEMFILE = EMFILE;
Id_WSAEWOULDBLOCK = EWOULDBLOCK;
Id_WSAEINPROGRESS = EINPROGRESS;
Id_WSAEALREADY = EALREADY;
Id_WSAENOTSOCK = ENOTSOCK;
Id_WSAEDESTADDRREQ = EDESTADDRREQ;
Id_WSAEMSGSIZE = EMSGSIZE;
Id_WSAEPROTOTYPE = EPROTOTYPE;
Id_WSAENOPROTOOPT = ENOPROTOOPT;
Id_WSAEPROTONOSUPPORT = EPROTONOSUPPORT;
Id_WSAESOCKTNOSUPPORT = ESOCKTNOSUPPORT;
Id_WSAEOPNOTSUPP = EOPNOTSUPP;
Id_WSAEPFNOSUPPORT = EPFNOSUPPORT;
Id_WSAEAFNOSUPPORT = EAFNOSUPPORT;
Id_WSAEADDRINUSE = EADDRINUSE;
Id_WSAEADDRNOTAVAIL = EADDRNOTAVAIL;
Id_WSAENETDOWN = ENETDOWN;
Id_WSAENETUNREACH = ENETUNREACH;
Id_WSAENETRESET = ENETRESET;
Id_WSAECONNABORTED = ECONNABORTED;
Id_WSAECONNRESET = ECONNRESET;
Id_WSAENOBUFS = ENOBUFS;
Id_WSAEISCONN = EISCONN;
Id_WSAENOTCONN = ENOTCONN;
Id_WSAESHUTDOWN = ESHUTDOWN;
Id_WSAETOOMANYREFS = ETOOMANYREFS;
Id_WSAETIMEDOUT = ETIMEDOUT;
Id_WSAECONNREFUSED = ECONNREFUSED;
Id_WSAELOOP = ELOOP;
Id_WSAENAMETOOLONG = ENAMETOOLONG;
Id_WSAEHOSTDOWN = EHOSTDOWN;
Id_WSAEHOSTUNREACH = EHOSTUNREACH;
Id_WSAENOTEMPTY = ENOTEMPTY;
{$ELSE}
// Shutdown Options
Id_SD_Recv = 0;
Id_SD_Send = 1;
Id_SD_Both = 2;
Id_SD_Default = Id_SD_Send;
//
Id_WSAEINTR = WSAEINTR;
Id_WSAEBADF = WSAEBADF;
Id_WSAEACCES = WSAEACCES;
Id_WSAEFAULT = WSAEFAULT;
Id_WSAEINVAL = WSAEINVAL;
Id_WSAEMFILE = WSAEMFILE;
Id_WSAEWOULDBLOCK = WSAEWOULDBLOCK;
Id_WSAEINPROGRESS = WSAEINPROGRESS;
Id_WSAEALREADY = WSAEALREADY;
Id_WSAENOTSOCK = WSAENOTSOCK;
Id_WSAEDESTADDRREQ = WSAEDESTADDRREQ;
Id_WSAEMSGSIZE = WSAEMSGSIZE;
Id_WSAEPROTOTYPE = WSAEPROTOTYPE;
Id_WSAENOPROTOOPT = WSAENOPROTOOPT;
Id_WSAEPROTONOSUPPORT = WSAEPROTONOSUPPORT;
Id_WSAESOCKTNOSUPPORT = WSAESOCKTNOSUPPORT;
Id_WSAEOPNOTSUPP = WSAEOPNOTSUPP;
Id_WSAEPFNOSUPPORT = WSAEPFNOSUPPORT;
Id_WSAEAFNOSUPPORT = WSAEAFNOSUPPORT;
Id_WSAEADDRINUSE = WSAEADDRINUSE;
Id_WSAEADDRNOTAVAIL = WSAEADDRNOTAVAIL;
Id_WSAENETDOWN = WSAENETDOWN;
Id_WSAENETUNREACH = WSAENETUNREACH;
Id_WSAENETRESET = WSAENETRESET;
Id_WSAECONNABORTED = WSAECONNABORTED;
Id_WSAECONNRESET = WSAECONNRESET;
Id_WSAENOBUFS = WSAENOBUFS;
Id_WSAEISCONN = WSAEISCONN;
Id_WSAENOTCONN = WSAENOTCONN;
Id_WSAESHUTDOWN = WSAESHUTDOWN;
Id_WSAETOOMANYREFS = WSAETOOMANYREFS;
Id_WSAETIMEDOUT = WSAETIMEDOUT;
Id_WSAECONNREFUSED = WSAECONNREFUSED;
Id_WSAELOOP = WSAELOOP;
Id_WSAENAMETOOLONG = WSAENAMETOOLONG;
Id_WSAEHOSTDOWN = WSAEHOSTDOWN;
Id_WSAEHOSTUNREACH = WSAEHOSTUNREACH;
Id_WSAENOTEMPTY = WSAENOTEMPTY;
{$ENDIF}
implementation
end.
|
unit testhermiteunit;
interface
uses Math, Sysutils, Ap, hermite;
function TestHermiteCalculate(Silent : Boolean):Boolean;
function testhermiteunit_test_silent():Boolean;
function testhermiteunit_test():Boolean;
implementation
function TestHermiteCalculate(Silent : Boolean):Boolean;
var
Err : Double;
SumErr : Double;
CErr : Double;
Threshold : Double;
N : AlglibInteger;
MaxN : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
Pass : AlglibInteger;
C : TReal1DArray;
X : Double;
V : Double;
WasErrors : Boolean;
begin
Err := 0;
SumErr := 0;
CErr := 0;
Threshold := 1.0E-9;
WasErrors := False;
//
// Testing Hermite polynomials
//
N := 0;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)-1));
N := 1;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)-2));
N := 2;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)-2));
N := 3;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)+4));
N := 4;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)+20));
N := 5;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)+8));
N := 6;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)-184));
N := 7;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)-464));
N := 11;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)-230848));
N := 12;
Err := Max(Err, AbsReal(HermiteCalculate(N, 1)-280768));
//
// Testing Clenshaw summation
//
MaxN := 10;
SetLength(C, MaxN+1);
Pass:=1;
while Pass<=10 do
begin
X := 2*RandomReal-1;
V := 0;
N:=0;
while N<=MaxN do
begin
C[N] := 2*RandomReal-1;
V := V+HermiteCalculate(N, X)*C[N];
SumErr := Max(SumErr, AbsReal(V-HermiteSum(C, N, X)));
Inc(N);
end;
Inc(Pass);
end;
//
// Testing coefficients
//
HermiteCoefficients(0, C);
CErr := Max(CErr, AbsReal(C[0]-1));
HermiteCoefficients(1, C);
CErr := Max(CErr, AbsReal(C[0]-0));
CErr := Max(CErr, AbsReal(C[1]-2));
HermiteCoefficients(2, C);
CErr := Max(CErr, AbsReal(C[0]+2));
CErr := Max(CErr, AbsReal(C[1]-0));
CErr := Max(CErr, AbsReal(C[2]-4));
HermiteCoefficients(3, C);
CErr := Max(CErr, AbsReal(C[0]-0));
CErr := Max(CErr, AbsReal(C[1]+12));
CErr := Max(CErr, AbsReal(C[2]-0));
CErr := Max(CErr, AbsReal(C[3]-8));
HermiteCoefficients(4, C);
CErr := Max(CErr, AbsReal(C[0]-12));
CErr := Max(CErr, AbsReal(C[1]-0));
CErr := Max(CErr, AbsReal(C[2]+48));
CErr := Max(CErr, AbsReal(C[3]-0));
CErr := Max(CErr, AbsReal(C[4]-16));
HermiteCoefficients(5, C);
CErr := Max(CErr, AbsReal(C[0]-0));
CErr := Max(CErr, AbsReal(C[1]-120));
CErr := Max(CErr, AbsReal(C[2]-0));
CErr := Max(CErr, AbsReal(C[3]+160));
CErr := Max(CErr, AbsReal(C[4]-0));
CErr := Max(CErr, AbsReal(C[5]-32));
HermiteCoefficients(6, C);
CErr := Max(CErr, AbsReal(C[0]+120));
CErr := Max(CErr, AbsReal(C[1]-0));
CErr := Max(CErr, AbsReal(C[2]-720));
CErr := Max(CErr, AbsReal(C[3]-0));
CErr := Max(CErr, AbsReal(C[4]+480));
CErr := Max(CErr, AbsReal(C[5]-0));
CErr := Max(CErr, AbsReal(C[6]-64));
//
// Reporting
//
WasErrors := AP_FP_Greater(Err,Threshold) or AP_FP_Greater(SumErr,Threshold) or AP_FP_Greater(CErr,Threshold);
if not Silent then
begin
Write(Format('TESTING CALCULATION OF THE HERMITE POLYNOMIALS'#13#10'',[]));
Write(Format('Max error %5.3e'#13#10'',[
Err]));
Write(Format('Summation error %5.3e'#13#10'',[
SumErr]));
Write(Format('Coefficients error %5.3e'#13#10'',[
CErr]));
Write(Format('Threshold %5.3e'#13#10'',[
Threshold]));
if not WasErrors then
begin
Write(Format('TEST PASSED'#13#10'',[]));
end
else
begin
Write(Format('TEST FAILED'#13#10'',[]));
end;
end;
Result := not WasErrors;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testhermiteunit_test_silent():Boolean;
begin
Result := TestHermiteCalculate(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testhermiteunit_test():Boolean;
begin
Result := TestHermiteCalculate(False);
end;
end. |
unit pCopyForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FileCtrl, StdCtrls, DB, DBTables, ComCtrls, FastCopy;
type
TFastCopyFileThread = class;
TCopyForm = class(TForm)
btnCopy: TButton;
ProgressBar1: TProgressBar;
lblStatus: TLabel;
GroupBox2: TGroupBox;
Button4: TButton;
edTarget: TEdit;
GroupBox1: TGroupBox;
edSource: TEdit;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
dsreusable1: TDataSource;
qryreusable1: TQuery;
DirectoryListBox1: TDirectoryListBox;
FileListBox1: TFileListBox;
procedure btnCopyClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
fFastCopyFileThread: TFastCopyFileThread;
fFastCopyFileThreadCanceled: Boolean;
procedure ChangeControlsState(State: Boolean);
procedure FastCopyFileProgress(Sender: TObject; FileName: TFileName;
Value: Integer; var CanContinue: Boolean);
procedure FastCopyFileTerminate(Sender: TObject);
public
{ Public declarations }
procedure StartFastCopyThread2;
end;
TFastCopyFileProgressEvent = procedure(Sender: TObject; FileName: TFileName;
Value: Integer; var CanContinue: Boolean) of object;
TFastCopyFileThread = class(TThread)
private
fSourceFileName: TFileName;
fDestinationFileName: TFileName;
fProgress: TFastCopyFileProgressEvent;
fCopyMode: TFastCopyFileMode;
procedure FastCopyFileCallback(const FileName: TFileName;
const CurrentSize, TotalSize: LongWord; var CanContinue: Boolean);
protected
procedure Execute; override;
public
constructor Create; overload;
property SourceFileName: TFileName
read fSourceFileName write fSourceFileName;
property DestinationFileName: TFileName
read fDestinationFileName write fDestinationFileName;
property CopyMode: TFastCopyFileMode read fCopyMode write fCopyMode;
property OnProgress: TFastCopyFileProgressEvent
read fProgress write fProgress;
end;
var
CopyForm: TCopyForm;
cSource,cTarget:string;
implementation
uses pARData;
{$R *.dfm}
procedure TCopyForm.btnCopyClick(Sender: TObject);
var nctr : integer;
begin
for nctr := 0 to FileListBox1.Count-1 do
begin
edSource.text := cSource + FileListBox1.Items[nctr];
edTarget.Text := cTarget + FileListBox1.Items[nctr];
showmessage(filelistbox1.FileName);
StartFastCopyThread2;
end;
end;
procedure TCopyForm.StartFastCopyThread2;
begin
ChangeControlsState(False);
fFastCopyFileThread := TFastCopyFileThread.Create;
with fFastCopyFileThread do
begin
SourceFileName := edSource.Text;
DestinationFileName := edTarget.Text;
CopyMode := TFastCopyFileMode(0);
OnProgress := FastCopyFileProgress;
OnTerminate := FastCopyFileTerminate;
Resume;
end;
end;
procedure tCopyForm.ChangeControlsState(State: Boolean);
begin
{Button1.Enabled := State;
Button2.Enabled := not State;}
if State then
begin
if fFastCopyFileThreadCanceled then
lblStatus.caption := 'Aborted !!!'
else
lblStatus.caption := 'Competed...';
fFastCopyFileThreadCanceled := False;
end;
end;
procedure TCopyForm.FastCopyFileProgress(Sender: TObject; FileName: TFileName;
Value: Integer; var CanContinue: Boolean);
begin
{StatusText := ExtractFileName(FileName);}
ProgressBar1.Position := Value;
end;
procedure TCopyForm.FastCopyFileTerminate(Sender: TObject);
begin
ChangeControlsState(True);
end;
{ TFastCopyFileThread }
constructor TFastCopyFileThread.Create;
begin
inherited Create(True);
FreeOnTerminate := True;
end;
procedure TFastCopyFileThread.Execute;
begin
FastCopyFile(SourceFileName, DestinationFileName, CopyMode,
FastCopyFileCallback);
end;
procedure TFastCopyFileThread.FastCopyFileCallback(const FileName: TFileName;
const CurrentSize, TotalSize: LongWord; var CanContinue: Boolean);
var
ProgressValue: Integer;
begin
CanContinue := not Terminated;
ProgressValue := Round((CurrentSize / TotalSize) * 100);
if Assigned(OnProgress) then
OnProgress(Self, FileName, ProgressValue, CanContinue);
end;
procedure TCopyForm.FormActivate(Sender: TObject);
begin
with dmardata do
begin
qryCompany.close;
qryCompany.sql.clear;
qryCompany.sql.add('select * from Setup');
qrycompany.open;
edSource.text := qryCompany.fieldbyname('SourceDir').asstring;
edTarget.Text := qryCompany.fieldbyname('TargetDir').asstring;
DirectoryListBox1.Directory:= edSource.text;
qryCompany.close;
end;
end;
procedure TCopyForm.Button1Click(Sender: TObject);
begin
qryreusable1.Close;
qryreusable1.SQL.Clear;
qryreusable1.SQL.ADD('ALTER TABLE "CUSTOMER.DB" ADD CurrencyCode CHAR(2) ');
qryreusable1.EXECSQL;
{
Query1.Close;
Query1.SQL.Clear;
Query1.SQL.ADD('ALTER TABLE "MYDB.DB" DROP Myfield');
Query1.EXECSQL;
}
end;
end.
|
{$mode objfpc}{$H+}{$J-}
program showcolor;
// и Graphics и GoogleMapsEngine определяют тип TColor.
uses
Graphics, GoogleMapsEngine;
var
{ Это не сработает, как мы ожидаем, поскольку TColor последний раз
был объявлен в unit-е GoogleMapsEngine. }
// Color: TColor;
{ This works Ok. }
Color: Graphics.TColor;
begin
Color := clYellow;
WriteLn(Red(Color), ' ', Green(Color), ' ', Blue(Color));
end.
|
unit untCadastroProduto;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.DBCtrls, Vcl.Mask, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TfrmCadastroProduto = class(TForm)
pnlRodape: TPanel;
btnNovo: TBitBtn;
btnGravar: TBitBtn;
btnCancelar: TBitBtn;
btnExcluir: TBitBtn;
btnFechar: TBitBtn;
pnlCentro: TPanel;
lblDescricao: TLabel;
lblValorUnit: TLabel;
lblCodigo: TLabel;
btnPesquisar: TBitBtn;
edtDescricao: TDBEdit;
edtCodigo: TEdit;
lblEstoque: TLabel;
edtEstoque: TDBEdit;
edtVlrUnit: TDBEdit;
chkSituacao: TDBCheckBox;
edtUnidade: TDBEdit;
lblUnidade: TLabel;
chkSemen: TDBCheckBox;
procedure btnFecharClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnNovoClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure edtCodigoExit(Sender: TObject);
procedure edtCodigoKeyPress(Sender: TObject; var Key: Char);
procedure edtCodigoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
vID : String;
fNovo : Boolean;
procedure PesquisaBD(vStatus : boolean);
procedure CarregaCampos;
end;
var
frmCadastroProduto: TfrmCadastroProduto;
implementation
{$R *.dfm}
uses untFuncoes, untPesquisa, untPrincipal, untDM;
procedure TfrmCadastroProduto.btnCancelarClick(Sender: TObject);
begin
if edtCodigo.Text <> '' then
begin
if fNovo = False then
begin
dm.qryProduto.UndoLastChange(True);
CarregaCampos;
end
else
begin
edtCodigo.Enabled := true;
edtCodigo.Clear;
CarregaCampos;
btnNovo.Enabled := True;
btnGravar.Enabled := True;
btnExcluir.Enabled := True;
fNovo := False;
end;
end;
end;
procedure TfrmCadastroProduto.btnExcluirClick(Sender: TObject);
begin
if fNovo = False then
begin
if DM.qryProduto.RecordCount > 0 then
begin
frmFuncoes.Botoes('Excluir', DM.qryProduto);
edtCodigo.Clear;
edtCodigo.SetFocus;
end;
end;
end;
procedure TfrmCadastroProduto.btnFecharClick(Sender: TObject);
begin
close;
end;
procedure TfrmCadastroProduto.btnGravarClick(Sender: TObject);
begin
if fNovo = True then
begin
dm.qryProduto.FieldByName('id').AsString := edtCodigo.Text;
end;
dm.qryProduto.FieldByName('alteracao').AsDateTime := Date+time;
dm.qryProduto.FieldByName('usuario').AsInteger := frmPrincipal.vUsuario;
dm.qryProduto.FieldByName('CODEMPRESA').AsInteger := frmPrincipal.vEmpresa; //Versao 1.4 - 14/10/2018
btnNovo.Enabled := True;
btnExcluir.Enabled := True;
edtCodigo.Enabled := True;
try
frmFuncoes.Botoes('Gravar', dm.qryProduto);
frmFuncoes.AutoIncre('PRODUTO', 'Gravar');
PesquisaBD(True);
fNovo := False;
if fNovo = True then //Versao 1.2.0 - 04/07/2018
frmFuncoes.GravaLog('Adição de cadastro de Produto. Codigo: ' + edtCodigo.Text, IntToStr(frmPrincipal.vUsuario)) //Versao 1.2.0 - 04/07/2018
else
frmFuncoes.GravaLog('Alteração de cadastro de Produto. Codigo: ' + edtCodigo.Text, IntToStr(frmPrincipal.vUsuario)); //Versao 1.2.0 - 04/07/2018
Except on E: Exception do
ShowMessage('Erro na gravação. >>>> ' + E.Message);
end;
end;
procedure TfrmCadastroProduto.btnNovoClick(Sender: TObject);
begin
fNovo := True;
dm.qryProduto.Insert;
btnNovo.Enabled := False;
btnGravar.Enabled := True;
btnExcluir.Enabled := False;
edtCodigo.Enabled := False;
edtDescricao.SetFocus;
chkSituacao.Checked := True;
chkSituacao.Field.Value := 'Ativo';
edtVlrUnit.Field.Value := 0;
edtEstoque.Field.Value := 0;
edtCodigo.Text := IntToStr(frmFuncoes.AutoIncre('PRODUTO', 'Novo'));
end;
procedure TfrmCadastroProduto.btnPesquisarClick(Sender: TObject);
begin
if fNovo = False then
PesquisaBD(False);
end;
procedure TfrmCadastroProduto.CarregaCampos;
begin
edtDescricao.DataField := 'DESCRICAO';
edtVlrUnit.DataField := 'VALOR';
edtUnidade.DataField := 'UNIDADE';
edtEstoque.DataField := 'ESTOQUE';
chkSituacao.DataField := 'SITUACAO';
chkSemen.DataField := 'SEMEM';
TFMTBCDField(dm.qryProduto.FieldByName('valor')).DisplayFormat := '###,####,###,##0.00';
end;
procedure TfrmCadastroProduto.edtCodigoExit(Sender: TObject);
begin
if fNovo = False then
begin
if Trim(edtCodigo.Text) <> '' then
PesquisaBD(True);
end;
end;
procedure TfrmCadastroProduto.edtCodigoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F2 then
btnPesquisarClick(Self);
end;
procedure TfrmCadastroProduto.edtCodigoKeyPress(Sender: TObject; var Key: Char);
begin
If not( key in['0'..'9',#08] ) then
key := #0;
end;
procedure TfrmCadastroProduto.FormActivate(Sender: TObject);
begin
vID := '0';
frmFuncoes.ExecutaSQL('Select * from PRODUTO where ID = ' + vID, 'Abrir', DM.qryProduto);
CarregaCampos;
edtCodigo.SetFocus;
end;
procedure TfrmCadastroProduto.FormKeyPress(Sender: TObject; var Key: Char);
begin
If key = #13 then
Begin
Key:= #0;
Perform(Wm_NextDlgCtl,0,0);
end;
end;
procedure TfrmCadastroProduto.PesquisaBD(vStatus: boolean);
begin
if vStatus = True then
begin
if Trim(edtCodigo.Text) <> '' then
begin
frmFuncoes.ExecutaSQL('Select * from PRODUTO where ID = ' + QuotedStr(edtCodigo.Text), 'Abrir', dm.qryProduto);
if dm.qryProduto.RecordCount > 0 then
begin
dm.qryProduto.Edit;
CarregaCampos;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodigo.SetFocus;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'PRODUTO';
frmPesquisa.vComando := 'Select ID, DESCRICAO, UNIDADE, VALOR, ESTOQUE from PRODUTO';
frmPesquisa.vTela := 'CAD_PRODUTO';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
end.
|
unit MarkdownTables;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, MarkdownUtils;
type
{ TTable }
TTable = class
public
class var
Rows:integer;
Cols:integer;
Emitter:TEmitter;
class procedure RowSplit (Input: string; const Strings: TStrings);
class function ProcTable(var L: TLine): string;
class procedure emitTableLines(out_: TStringBuilder; lines: TLine);
class function hasFormatChars(L: Tline): integer;
class function isRow(L: Tline): boolean;
class function ColCount(L: Tline): integer;
class procedure AlignFormat(f: string; sl: TStringList);
end;
implementation
class procedure TTable.RowSplit (Input: string; const Strings: TStrings);
var
i,j:integer;
s:string;
begin
if not Assigned(Strings) then exit;
i:=1;
j:=Length(Input);
if Input[i]='|' then inc(i);
if (Input[j]='|') and (Input[j-1]<>'\') then dec(j);
s:='';
Strings.Clear;
while (i<=j) do
begin
if ((Input[i]='|') and (Input[i-1]<>'\')) then
begin
Strings.Append(s);
s:='';
end else s:=s+Input[i];
inc(i);
end;
Strings.Append(s);
end;
class function TTable.ProcTable(var L: TLine): string;
(*
| First Header | Second Header | Third Header |
| :----------- | :-----------: | -----------: |
| Left | Center | Right |
| Second row | **strong** | *italic* |
*)
var
cell,outs,t,t2:string;
orig:TLine;
first:boolean;
col:integer;
tsl:TStringList;
ColAlign:TStringList;
begin
outs:='';
first:=true;
tsl:=TStringList.Create;
ColAlign:=TStringList.Create;
orig:=L;
while (orig<>nil) and not(orig.isEmpty) do
begin
t:=trim(orig.Value);
t2:='';
RowSplit(t, tsl);
if (first) then // get header
begin
AlignFormat(orig.next.Value,ColAlign); // get format row
col:=0;
for cell in tsl do
begin
t2:=t2+' <th'+ColAlign[col]+trim(cell)+'</th>'#10;
inc(col);
end;
first:=false;
orig:=orig.next; // skip table format row
end else
begin
col:=0;
for cell in tsl do
begin
t2:=t2+' <td'+ColAlign[col]+trim(cell)+'</td>'#10;
inc(col);
end;
end;
if t2<>'' then
begin
outs+=' <tr>'#10+t2+' </tr>'#10;
inc(Rows);
end;
orig:=orig.next;
end;
t:='<table>'#10;
t:=t+outs+'</table>'#10;
tsl.free;
ColAlign.free;
ProcTable:=t;
end;
class procedure TTable.emitTableLines(out_: TStringBuilder; lines: TLine);
var line:TLine;
begin
line := lines;
if Assigned(Emitter) then Emitter.recursiveEmitLine(out_, ProcTable(line), 0, mtNONE);
end;
class function TTable.hasFormatChars(L: Tline): integer;
var
i,j:integer;
begin
result:=0;Cols:=0;
if not Assigned(L) or L.isEmpty then exit(0);
i:=L.leading+1;
j:=Length(L.value)-L.trailing;
if i>4 then exit(0); // more of 4 spaces of identation
if L.value[i]='|' then inc(i);
if L.value[j]='|' then dec(j);
while (i<=j) do
begin
if not(L.value[i] in [' ','|','-',':']) then exit(0);
if L.value[i]='|' then inc(result);
inc(i);
end;
Cols:=result;
end;
class function TTable.isRow(L: Tline): boolean;
var
c:integer;
begin
c:=ColCount(L);
exit((c>0) and (c<=Cols))
end;
class function TTable.ColCount(L: Tline): integer;
var
i,j,r:integer;
begin
if not Assigned(L) or L.isEmpty then exit(0);
r:=0;
i:=L.leading+1;
j:=Length(L.value)-L.trailing;
if i>4 then exit(0); // more of 4 spaces of identation
if L.value[i]='|' then inc(i);
if L.value[j]='|' then dec(j);
while (i<=j) do
begin
if (L.value[i]='|') and (L.value[i-1]<>'\') then inc(r);
inc(i);
end;
exit(r);
end;
class procedure TTable.AlignFormat(f: string; sl: TStringList);
var
i:integer;
begin
f:=trim(f);
if f[1]='|' then f:=Copy(f,2);
if f[length(f)]='|' then f:=Copy(f,1,length(f)-1);
RowSplit(f, sl);
for i:=0 to sl.Count-1 do
begin
if sl[i].Contains(':-') and sl[i].Contains('-:') then sl[i]:=' align="center">'
else if sl[i].Contains(':-') then sl[i]:=' align="left">'
else if sl[i].Contains('-:') then sl[i]:=' align="right">'
else sl[i]:='>';
end;
end;
end.
|
unit JASketch;
{$mode objfpc}{$H+}
{$PACKRECORDS 2} {required for compatibility with various amiga APIs}
{$i JA.inc}
{A Sketch is a collection of Polygons. It is arranged as such so different
coloured/styled polygons can make up a single object while also having a
defined order of rendering, the order of the Polygon array, for controlling
which polygons lie above or below one another, if required.}
interface
uses
JATypes, JAMath, JAList, JAPolygon;
type
TJASketch = record
Polygon : PJAPolygon;
PolygonCapacity : SInt32;
PolygonCount : SInt32;
end;
PJASketch = ^TJASketch;
function JASketchCreate() : PJASketch;
function JASketchDestroy(ASketch : PJASketch) : boolean;
function JASketchClear(ASketch : PJASketch) : boolean;
function JASketchPolygonCreate(ASketch : PJASketch) : PJAPolygon;
function JASketchPolygonDestroy(ASketch : PJASketch; APolygon : PJAPolygon) : boolean;
implementation
function JASketchCreate() : PJASketch;
begin
Result := PJASketch(JAMemGet(SizeOf(TJASketch)));
Result^.Polygon := nil;
Result^.PolygonCapacity := 0;
Result^.PolygonCount := 0;
end;
function JASketchDestroy(ASketch : PJASketch) : boolean;
begin
if (ASketch=nil) then exit(false);
JASketchClear(ASketch);
JAMemFree(ASketch,SizeOf(TJASketch));
Result := true;
end;
function JASketchClear(ASketch : PJASketch) : boolean;
var
I : SInt32;
begin
if (ASketch=nil) then exit(false);
for I := 0 to ASketch^.PolygonCount-1 do
begin
if (ASketch^.Polygon[I].VertexCapacity > 0) then
begin
JAMemFree(ASketch^.Polygon[I].Vertex, SizeOf(TJAVertex) * ASketch^.Polygon[I].VertexCapacity);
JAMemFree(ASketch^.Polygon[I].WorldVertex, SizeOf(TVec2) * ASketch^.Polygon[I].VertexCapacity);
JAMemFree(ASketch^.Polygon[I].WorldVertexI, SizeOf(TVec2SInt16) * ASketch^.Polygon[I].VertexCapacity);
end;
ASketch^.Polygon[I].Vertex := nil;
ASketch^.Polygon[I].VertexCapacity := 0;
ASketch^.Polygon[I].VertexCount := 0;
ASketch^.Polygon[I].WorldVertex := nil;
ASketch^.Polygon[I].WorldVertexI := nil;
if (ASketch^.Polygon[I].IndexCapacity > 0) then
JAMemFree(ASketch^.Polygon[I].Index, SizeOf(UInt32) * ASketch^.Polygon[I].IndexCapacity);
ASketch^.Polygon[I].Index := nil;
ASketch^.Polygon[I].IndexCapacity := 0;
ASketch^.Polygon[I].IndexCount := 0;
end;
if (ASketch^.PolygonCapacity > 0) then
JAMemFree(ASketch^.Polygon, SizeOf(TJAPolygon) * ASketch^.PolygonCapacity);
ASketch^.Polygon := nil;
ASketch^.PolygonCapacity := 0;
ASketch^.PolygonCount := 0;
Result := true;
end;
function JASketchPolygonCreate(ASketch : PJASketch) : PJAPolygon;
var
NewCapacity : SInt32;
begin
NewCapacity := ASketch^.PolygonCapacity;
if (NewCapacity=0) then NewCapacity := JAPool_BlockSize else
if (ASketch^.PolygonCount+1) > NewCapacity then NewCapacity += JAPool_BlockSize;
if NewCapacity<>ASketch^.PolygonCapacity then
begin
if ASketch^.PolygonCapacity=0 then
ASketch^.Polygon := JAMemGet(SizeOf(TJAPolygon)*NewCapacity) else
ASketch^.Polygon := reallocmem(ASketch^.Polygon, SizeOf(TJAPolygon)*NewCapacity);
ASketch^.PolygonCapacity := NewCapacity;
end;
{return pointer to polygon structure}
Result := @ASketch^.Polygon[ASketch^.PolygonCount];
{Set Initial Shadow Array State}
Result^.Shadows := nil;
Result^.ShadowsCount := 0;
Result^.ShadowPenumbra0Fins := nil;
Result^.ShadowPenumbra0FinsCapacity := 0;
Result^.ShadowPenumbra0FinsCount := 0;
Result^.ShadowPenumbra1Fins := nil;
Result^.ShadowPenumbra1FinsCapacity := 0;
Result^.ShadowPenumbra1FinsCount := 0;
{Set Polygon Inital State}
Result^.Vertex := nil;
Result^.WorldVertex := nil;
Result^.WorldVertexI := nil;
Result^.Index := nil;
JAPolygonClear(Result);
ASketch^.PolygonCount += 1;
end;
function JASketchPolygonDestroy(ASketch : PJASketch; APolygon : PJAPolygon) : boolean;
var
I : SInt32;
begin
Result := false;
for I := 0 to ASketch^.PolygonCount-1 do
begin
if (@ASketch^.Polygon[I] = ASketch) then Result := true;
if Result and (I < ASketch^.PolygonCount-1) then
ASketch^.Polygon[I] := ASketch^.Polygon[I+1];
end;
if Result then ASketch^.PolygonCount +=1;
{Something should probably be here}
Result := false;
end;
end.
|
{******************************************************************************}
{ }
{ Gofy - Arkham Horror Card Game }
{ }
{ The contents of this file are subject to the Mozilla Public License Version }
{ 1.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.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, }
{ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for }
{ the specific language governing rights and limitations under the License. }
{ }
{ The Original Code is CommonItemCardDeck.pas. }
{ }
{ Contains logic for handling common card. }
{ }
{ Unit owner: Ronar }
{ Last modified: March 7, 2021 }
{ }
{******************************************************************************}
unit uCommonItemCardDeck;
interface
uses
SysUtils, Classes, uCommon, uCardDeck;
type
TCommonItemCard = record
id: integer;
amt: Integer; // Количество присутсвующих карт в колоде
ccounter: integer; // how many times card was used
ccounter_max: integer; // max times uses
data: string;
cardType: Integer; // Weapon, Tome
exposed: boolean;
hands: integer;
price: integer;
phase_use: integer;
prm: integer;
prm_value: integer;
end;
TCommonItemCardDeck = class(TCardDeck)
private
fCards: array [1..NUMBER_OF_COMMON_CARDS] of TCommonItemCard; // Данные о каждой карте
function GetCardID(i: integer): Integer;
function GetCardData(i: integer): string;
public
constructor Create (CardType: integer);
property card[i: integer]: integer read GetCardID;
function FindCards(file_path: string): integer; override;
function GetCardByID(id: integer): TCommonItemCard;
function IndexOfCard(id: integer): integer;
function DrawCard: Integer; //overload;
function DrawWeaponCard: Integer;
procedure Shuffle(); override;
function CheckAvailability(N: integer): boolean;
procedure IncCounter(indx: integer); // Увеличивает счетчик карты
procedure DecCounter(indx: integer); // Уменьшает счетчик карты
procedure AddCardToDeck(indx: integer);
procedure RemoveCardFromDeck(indx: integer);
//destructor Destroy; override;
end;
implementation
constructor TCommonItemCardDeck.Create(CardType: integer);
var
i: Integer;
begin
fCardType := CardType;
for i := 1 to NUMBER_OF_COMMON_CARDS do
begin
fCards[i].id := 0;
fCards[i].amt := 0;
fCards[i].ccounter := 0; // how many times card was used
fCards[i].ccounter_max := 0; // max times uses
fCards[i].data := '';
fCards[i].cardType := 0; // Weapon, Tome
fCards[i].exposed := False;
fCards[i].hands := 0;
fCards[i].price := 0;
fCards[i].phase_use := 0;
fCards[i].prm := 0;
fCards[i].prm_value := 0;
end;
end;
function TCommonItemCardDeck.GetCardByID(id: integer): TCommonItemCard;
var
i: integer;
begin
for i:= 1 to fCount do
begin
if fCards[i].id = id then
begin
GetCardByID := fCards[i];
break;
end;
end;
end;
function TCommonItemCardDeck.IndexOfCard(id: integer): integer;
var
i: integer;
begin
for i:= 1 to fCount do
begin
if fCards[i].id = id then
begin
IndexOfCard := i;
break;
end;
end;
end;
// Получение ID карты
function TCommonItemCardDeck.GetCardID(i: integer): integer;
begin
GetCardID := fCards[i].id;
end;
// Получение данных карты (указатель на голову связного списка)
function TCommonItemCardDeck.GetCardData(i: integer): string;
begin
GetCardData := fCards[i].data;
end;
function TCommonItemCardDeck.DrawCard: Integer;
begin
Shuffle;
DrawCard := fCards[fCount].id;
end;
function TCommonItemCardDeck.DrawWeaponCard: Integer;
var
i: integer;
begin
Result := 0;
Shuffle;
for i := 1 to fCount do
begin
if fCards[i].cardType = COMMON_ITEM_WEAPON then
begin
Result := fCards[i].id;
Break;
end;
end;
end;
// Поиск файлов в картами
function TCommonItemCardDeck.FindCards(file_path: string): integer;
var
F: TextFile;
SR: TSearchRec; // Поисковая переменная
FindRes: Integer; // Переменная для записи результата поиска
s: string[80];
i: integer;
output_data: TStringList;
procedure SplitData(delimiter: Char; str: string; var output_data: TStringList);
begin
output_data.Clear;
output_data.QuoteChar := '''';
output_data.Delimiter := delimiter;
output_data.DelimitedText := str;
end;
begin
// Задание условий поиска и начало поиска
FindRes := FindFirst(file_path + '*.txt', faAnyFile, SR);
i := 0;
output_data := TStringList.Create;
while FindRes = 0 do // Пока мы находим файлы (каталоги), то выполнять цикл
begin
i := i + 1;
AssignFile (F, file_path + SR.Name);
Reset(F);
readln(F, s);
CloseFile(F);
SplitData('|', s, output_data);
fCards[i].data := s;
//fCards[i].id :=
with fCards[i] do
begin
id := StrToInt(Copy(SR.Name, 1, 4));
amt := StrToInt(Copy(SR.Name, 4, 1));
exposed := False;
fCardType := StrToInt(output_data[0]);
price := StrToInt(output_data[1]);
hands := StrToInt(output_data[3]);
phase_use := StrToInt(output_data[4]);
prm := StrToInt(output_data[5]);
prm_value := StrToInt(output_data[6]);
end;
FindRes := FindNext(SR); // Продолжение поиска по заданным условиям
end;
output_data.Free;
FindClose(SR); // Закрываем поиск
FindCards := i;
fCount := i;
end;
// Тасовка колоды
procedure TCommonItemCardDeck.Shuffle();
var
i, r: integer;
temp: TCommonItemCard;
begin
randomize;
for i := 1 to fCount do
begin
temp := fCards[i];
r := random(fCount);
fCards[i] := fCards[r+1];
fCards[r+1] := temp;
end;
end;
function TCommonItemCardDeck.CheckAvailability(N: integer): boolean;
var
i: Integer;
begin
result := false;
for i := 1 to fCount do
if fCards[i].id = N then
result := true;
end;
procedure TCommonItemCardDeck.IncCounter(indx: integer);
begin
fCards[indx].ccounter := fCards[indx].ccounter + 1;
end;
procedure TCommonItemCardDeck.DecCounter(indx: integer);
begin
fCards[indx].ccounter := fCards[indx].ccounter - 1;
end;
// Добавление карты в колоду (например, при возвращении)
procedure TCommonItemCardDeck.AddCardToDeck(indx: integer);
begin
if fCards[indx].amt < StrToInt(IntToStr(fCards[indx].id)[4]) then
fCards[indx].amt := fCards[indx].amt + 1;
end;
// Удаление карты из колоды (при передаче ее игроку)
procedure TCommonItemCardDeck.RemoveCardFromDeck(indx: integer);
begin
if fCards[indx].amt > 0 then
fCards[indx].amt := fCards[indx].amt - 1;
end;
end.
|
unit ksFormTransitionUI;
interface
{$I ksComponents.inc}
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
ksFormTransition;
type
TfrmFormTransitionUI = class(TForm)
Image1: TImage;
Image2: TImage;
Fade: TRectangle;
private
//function GenerateFormImageExt(AForm: TCommonCustomForm): TBitmap;
procedure Delay;
procedure AnimateImage(AImg: TImage; XY: string; ANewValue: single);
{ Private declarations }
public
procedure Initialise(AFrom, ATo: TCommonCustomForm);
procedure Animate(ATransition: TksTransitionType; APop: Boolean);
{ Public declarations }
end;
implementation
uses ksCommon, System.UIConsts, FMX.Ani, DateUtils, FMX.Platform,
ksLoadingIndicator;
{$R *.fmx}
procedure TfrmFormTransitionUI.Delay;
var
ANow: TDatetime;
begin
ANow := Now;
while MilliSecondsBetween(ANow, Now) < 100 do
Application.ProcessMessages;
end;
procedure TfrmFormTransitionUI.Initialise(AFrom, ATo: TCommonCustomForm);
var
ABmp: TBitmap;
begin
ATo.SetBounds(0, 0, AFrom.Width, AFrom.Height);
//Image1.WrapMode := TImageWrapMode.Original;
//Image2.WrapMode := TImageWrapMode.Original;
Fade.Fill.Kind := TBrushKind.Solid;
Fade.Fill.Color := claBlack;
Fade.Align := TAlignLayout.Client;
Fade.Opacity := 0;
ATo.SetBounds(0, 0, AFrom.Width, AFrom.Height);
ABmp := TBitmap.Create;
try
GenerateFormImageExt(AFrom, ABmp);
Image1.Bitmap := ABmp;
GenerateFormImageExt(ATo, ABmp);
Image2.Bitmap := ABmp;
finally
FreeAndNil(ABmp);
end;
Fade.Opacity := 0;
{$IFDEF MSWINDOWS}
SetBounds(AFrom.Left, AFrom.Top, AFrom.Width, AFrom.Height);
{$ENDIF}
end;
procedure TfrmFormTransitionUI.AnimateImage(AImg: TImage; XY: string; ANewValue: single);
begin
{$IFNDEF ANDROID}
{$IFDEF XE10_2_OR_NEWER}
{$IFDEF FMX_TOKYO_FIX}
TAnimator.AnimateFloat(AImg, 'Position.'+XY, ANewValue, C_TRANSITION_DURATION);
{$ELSE}
TAnimator.AnimateFloatWait(AImg, 'Position.'+XY, ANewValue, C_TRANSITION_DURATION);
{$ENDIF}
{$ENDIF}
{$ELSE}
TAnimator.AnimateFloat(AImg, 'Position.'+XY, ANewValue, C_TRANSITION_DURATION);
{$ENDIF}
end;
procedure TfrmFormTransitionUI.Animate(ATransition: TksTransitionType; APop: Boolean);
var
w,h: single;
begin
w := Image1.Bitmap.Width / GetScreenScale;
h := Image1.Bitmap.Height / GetScreenScale;
if ATransition = ksFtSlideInFromRight then
begin
if APop then
begin
Fade.Opacity := C_FADE_OPACITY;
Image2.AddObject(Fade);
Image2.SetBounds(0-(w/3), 0, w, h);
Image1.SetBounds(0, 0, w, h);
Image1.BringToFront;
Delay;
TAnimator.AnimateFloat(Image1, 'Position.X', w, C_TRANSITION_DURATION);
TAnimator.AnimateFloat(Fade, 'Opacity', 0, C_TRANSITION_DURATION);
AnimateImage(Image2, 'X', 0);
end
else
begin
Fade.Opacity := 0;
Image1.AddObject(Fade);
Image1.SetBounds(0, 0, w, h);
Image2.SetBounds(w, 0, w, h);
Image2.BringToFront;
Delay;
TAnimator.AnimateFloat(Image1, 'Position.X', 0-(w/3), C_TRANSITION_DURATION);
TAnimator.AnimateFloat(Fade, 'Opacity', C_FADE_OPACITY, C_TRANSITION_DURATION);
AnimateImage(Image2, 'X', 0);
end;
end;
if ATransition = ksFtSlideInFromBottom then
begin
if APop then
begin
Fade.Opacity := C_FADE_OPACITY;
Image2.AddObject(Fade);
Image2.SetBounds(0, 0, w, h);
Image1.SetBounds(0, 0, w, h);
Image1.BringToFront;
Delay;
TAnimator.AnimateFloat(Fade, 'Opacity', 0, C_TRANSITION_DURATION);
AnimateImage(Image1, 'Y', h);
end
else
begin
Fade.Opacity := 0;
Image1.AddObject(Fade);
Image1.SetBounds(0, 0, w, h);
Image2.SetBounds(0, h, w, h);
Image2.BringToFront;
Delay;
TAnimator.AnimateFloat(Fade, 'Opacity', C_FADE_OPACITY, C_TRANSITION_DURATION);
AnimateImage(Image2, 'Y', 0);
end;
end;
if ATransition = ksFtSlideInFromLeft then
begin
if APop then
begin
Fade.Opacity := C_FADE_OPACITY;
Image2.AddObject(Fade);
Image2.SetBounds((w/3), 0, w, h);
Image1.SetBounds(0, 0, w, h);
Image1.BringToFront;
Delay;
TAnimator.AnimateFloat(Image1, 'Position.X', 0-w, C_TRANSITION_DURATION);
TAnimator.AnimateFloat(Fade, 'Opacity', 0, C_TRANSITION_DURATION);
AnimateImage(Image2, 'X', 0);
end
else
begin
Fade.Opacity := 0;
Image1.AddObject(Fade);
Image1.SetBounds(0, 0, w, h);
Image2.SetBounds(0-w, 0, w, h);
Image2.BringToFront;
Delay;
TAnimator.AnimateFloat(Image1, 'Position.X', (w/3), C_TRANSITION_DURATION);
TAnimator.AnimateFloat(Fade, 'Opacity', C_FADE_OPACITY, C_TRANSITION_DURATION);
AnimateImage(Image2, 'X', 0);
end;
end;
if ATransition = ksFtSlideInFromTop then
begin
if APop then
begin
Fade.Opacity := C_FADE_OPACITY;
Image2.AddObject(Fade);
Image2.SetBounds(0, 0, w, h);
Image1.SetBounds(0, 0, w, h);
Image1.BringToFront;
Delay;
TAnimator.AnimateFloat(Fade, 'Opacity', 0, C_TRANSITION_DURATION);
AnimateImage(Image1, 'Y', 0-h);
end
else
begin
Fade.Opacity := 0;
Image1.AddObject(Fade);
Image1.SetBounds(0, 0, w, h);
Image2.SetBounds(0, 0-h, w, h);
Image2.BringToFront;
Delay;
TAnimator.AnimateFloat(Fade, 'Opacity', C_FADE_OPACITY, C_TRANSITION_DURATION);
AnimateImage(Image2, 'Y', 0);
end;
end;
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QExtCtrls;
{$S-,W-,R-,H+,X+}
interface
uses
SysUtils, Types, Classes, Qt, QTypes, QControls, QGraphics,
QStdCtrls, QForms, QConsts;
type
TShapeType = (stRectangle, stSquare, stRoundRect, stRoundSquare,
stEllipse, stCircle);
TShape = class(TGraphicControl)
private
FShape: TShapeType;
procedure SetBrush(Value: TBrush);
procedure SetPen(Value: TPen);
procedure SetShape(Value: TShapeType);
function GetBrush: TBrush;
function GetPen: TPen;
protected
procedure ColorChanged; override;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
published
procedure StyleChanged(Sender: TObject);
property Align;
property Anchors;
property Brush: TBrush read GetBrush write SetBrush;
property Color;
property Constraints;
property DragMode;
property Enabled;
property ParentShowHint;
property Pen: TPen read GetPen write SetPen;
property Shape: TShapeType read FShape write SetShape default stRectangle;
property ShowHint;
property Visible;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
TPaintBox = class(TGraphicControl)
private
FOnPaint: TNotifyEvent;
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
property Canvas;
published
property Align;
property Anchors;
property Color;
property Constraints;
property DragMode;
property Enabled;
property Font;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
property OnStartDrag;
end;
TBevelStyle = (bsLowered, bsRaised);
TBevelShape = (bsBox, bsFrame, bsTopLine, bsBottomLine, bsLeftLine,
bsRightLine, bsSpacer);
TBevel = class(TGraphicControl)
private
FStyle: TBevelStyle;
FShape: TBevelShape;
procedure SetStyle(Value: TBevelStyle);
procedure SetShape(Value: TBevelShape);
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
published
property Align;
property Anchors;
property Constraints;
property ParentShowHint;
property Shape: TBevelShape read FShape write SetShape default bsBox;
property ShowHint;
property Style: TBevelStyle read FStyle write SetStyle default bsLowered;
property Visible;
end;
TTimer = class(THandleComponent)
private
FInterval: Cardinal;
FOnTimer: TNotifyEvent;
FEnabled: Boolean;
procedure SetEnabled(Value: Boolean);
procedure SetInterval(Value: Cardinal);
protected
procedure CreateWidget; override;
function GetHandle: QTimerH;
procedure HookEvents; override;
procedure Timer; virtual; cdecl;
public
constructor Create(AOwner: TComponent); override;
property Handle: QTimerH read GetHandle;
published
property Enabled: Boolean read FEnabled write SetEnabled default True;
property Interval: Cardinal read FInterval write SetInterval default 1000;
property OnTimer: TNotifyEvent read FOnTimer write FOnTimer;
end;
TPanelBevel = TBevelCut;
TBevelWidth = 1..MaxInt;
TBorderWidth = 0..MaxInt;
TCustomPanel = class(TCustomControl)
private
FBevelInner: TPanelBevel;
FBevelOuter: TPanelBevel;
FBevelWidth: TBevelWidth;
FBorderWidth: TBorderWidth;
FBorderStyle: TControlBorderStyle;
FAlignment: TAlignment;
FCaption: TCaption;
procedure SetAlignment(const Value: TAlignment);
procedure SetBevelInner(const Value: TPanelBevel);
procedure SetBevelOuter(const Value: TPanelBevel);
procedure SetBevelWidth(const Value: TBevelWidth);
procedure SetBorderWidth(const Value: TBorderWidth);
procedure SetBorderStyle(const Value: TControlBorderStyle);
function GetHandle: QFrameH;
protected
procedure AdjustClientRect(var Rect: TRect); override;
function GetText: TCaption; override;
procedure SetText(const Value: TCaption); override;
procedure CreateWidget; override;
procedure Paint; override;
property Alignment: TAlignment read FAlignment write SetAlignment default taCenter;
property BevelInner: TPanelBevel read FBevelInner write SetBevelInner default bvNone;
property BevelOuter: TPanelBevel read FBevelOuter write SetBevelOuter default bvRaised;
property BevelWidth: TBevelWidth read FBevelWidth write SetBevelWidth default 1;
property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0;
property BorderStyle: TControlBorderStyle read FBorderStyle write SetBorderStyle default bsNone;
property Color default clBtnFace;
property Caption read GetText write SetText;
property Handle: QFrameH read GetHandle;
property ParentColor default True;
public
constructor Create(AOwner: TComponent); override;
procedure Invalidate; override;
end;
TPanel = class(TCustomPanel)
published
property Align default alNone;
property Alignment;
property Anchors;
property BevelInner;
property BevelOuter;
property BevelWidth;
property Bitmap;
property BorderWidth;
property BorderStyle;
property Caption;
property Color default clBackground;
property Constraints;
property DragMode;
property Enabled;
property Font;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop default False;
property Visible;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDrag;
end;
TImage = class(TGraphicControl)
private
FPicture: TPicture;
FOnProgress: TProgressEvent;
FStretch: Boolean;
FCenter: Boolean;
FIncrementalDisplay: Boolean;
FTransparent: Boolean;
FDrawing: Boolean;
FAutoSize: Boolean;
function GetCanvas: TCanvas;
procedure PictureChanged(Sender: TObject);
procedure SetCenter(Value: Boolean);
procedure SetPicture(Value: TPicture);
procedure SetStretch(Value: Boolean);
procedure SetTransparent(Value: Boolean);
procedure SetAutoSize(const Value: Boolean);
protected
procedure DoAutoSize;
function DestRect: TRect;
function DoPaletteChange: Boolean;
procedure Paint; override;
procedure Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: WideString); dynamic;
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Canvas: TCanvas read GetCanvas;
published
property Align;
property Anchors;
property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
property Center: Boolean read FCenter write SetCenter default False;
property Constraints;
property DragMode;
property Enabled;
property IncrementalDisplay: Boolean read FIncrementalDisplay write FIncrementalDisplay default False;
property ParentShowHint;
property Picture: TPicture read FPicture write SetPicture;
property PopupMenu;
property ShowHint;
property Stretch: Boolean read FStretch write SetStretch default False;
property Transparent: Boolean read FTransparent write SetTransparent default False;
property Visible;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnProgress: TProgressEvent read FOnProgress write FOnProgress;
property OnStartDrag;
end;
NaturalNumber = 1..High(Integer);
TCanResizeEvent = procedure(Sender: TObject; var NewSize: Integer;
var Accept: Boolean) of object;
TResizeStyle = (rsNone, rsLine, rsUpdate, rsPattern);
TSplitter = class(TGraphicControl)
private
FOldCur: TCursor;
FActiveControl: TWidgetControl;
FAutoSnap: Boolean;
FBeveled: Boolean;
FBrush: TBrush;
FControl: TControl;
FDownPos: TPoint;
FMinSize: NaturalNumber;
FMaxSize: Integer;
FNewSize: Integer;
FOldKeyDown: TKeyEvent;
FOldSize: Integer;
FResizeStyle: TResizeStyle;
FSplit: Integer;
FOnCanResize: TCanResizeEvent;
FOnMoved: TNotifyEvent;
FOnPaint: TNotifyEvent;
procedure CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer);
procedure DrawLine;
function FindControl: TControl;
procedure FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure SetBeveled(Value: Boolean);
procedure UpdateControlSize;
procedure UpdateSize(X, Y: Integer);
function CanResize(var NewSize: Integer): Boolean;
protected
function DoCanResize(var NewSize: Integer): Boolean; virtual;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
procedure RequestAlign; override;
procedure StopSizing; dynamic;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Canvas;
published
property Align default alLeft;
property Anchors;
property AutoSnap: Boolean read FAutoSnap write FAutoSnap default True;
property Beveled: Boolean read FBeveled write SetBeveled default False;
property Color default clBtnFace;
property Constraints;
property Cursor default crHSplit;
property Height default 22;
property MinSize: NaturalNumber read FMinSize write FMinSize default 30;
property ParentColor default False;
property ParentShowHint;
property ResizeStyle: TResizeStyle read FResizeStyle write FResizeStyle default rsPattern;
property ShowHint;
property Visible;
property Width default 3;
property OnCanResize: TCanResizeEvent read FOnCanResize write FOnCanResize;
property OnMoved: TNotifyEvent read FOnMoved write FOnMoved;
property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
end;
TOrientation = (orVertical, orHorizontal);
TCustomRadioGroup = class(TCustomGroupBox)
private
FItems: TStrings;
FButtons: TList;
FItemIndex: Integer;
FLastIndex: Integer;
FColumns: Integer;
FOrientation: TOrientation;
procedure ClickedHook(Index: Integer); cdecl;
procedure ForceLayout;
function GetHandle: QButtonGroupH;
procedure ItemsChange(Sender: TObject);
procedure SetButtonCount(Value: Integer);
procedure SetColumns(Value: Integer);
procedure SetItemIndex(Value: Integer);
procedure SetItems(Value: TStrings);
procedure UpdateButtons;
procedure SetOrientation(const Value: TOrientation);
protected
function CanModify: Boolean; virtual;
procedure CreateWidget; override;
procedure CursorChanged; override;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
procedure HookEvents; override;
procedure Loaded; override;
procedure RestoreWidgetState; override;
procedure SaveWidgetState; override;
procedure ShowingChanged; override;
function WantKey(Key: Integer; Shift: TShiftState;
const KeyText: WideString): Boolean; override;
property Columns: Integer read FColumns write SetColumns default 1;
property ItemIndex: Integer read FItemIndex write SetItemIndex default -1;
property Items: TStrings read FItems write SetItems;
property Orientation: TOrientation read FOrientation write SetOrientation
default orVertical;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetFocus; override;
property Handle: QButtonGroupH read GetHandle;
end;
TRadioGroup = class(TCustomRadioGroup)
published
property Items;
property Orientation;
property Align default alNone;
property Alignment default taLeftJustify;
property Bitmap;
property Anchors;
property Caption;
property Color default clBackground;
property Columns;
property Constraints;
property DragMode;
property Enabled;
property Font;
property ItemIndex;
property Masked default False;
property ParentColor default True;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint default False;
property TabOrder;
property TabStop default True;
property Visible;
property OnClick;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnStartDrag;
end;
{ TControlBar }
TBandPaintOption = (bpoGrabber, bpoFrame);
TBandPaintOptions = set of TBandPaintOption;
TBandDragEvent = procedure (Sender: TObject; Control: TControl;
var Drag: Boolean) of object;
TBandInfoEvent = procedure (Sender: TObject; Control: TControl;
var Insets: TRect; var PreferredSize, RowCount: Integer) of object;
TBandMoveEvent = procedure (Sender: TObject; Control: TControl;
var ARect: TRect) of object;
TBandPaintEvent = procedure (Sender: TObject; Control: TControl;
Canvas: TCanvas; var ARect: TRect; var Options: TBandPaintOptions) of object;
TRowSize = 1..MaxInt;
TCustomControlBar = class(TCustomControl)
private
FAligning: Boolean;
FAutoDrag: Boolean;
FGrabCursor: TCursor;
FSaveCursor: TCursor;
FDockingControl: TControl;
FDragControl: TControl;
FDragOffset: TPoint;
FDrawing: Boolean;
FItems: TList;
FPicture: TPicture;
FRowSize: TRowSize;
FRowSnap: Boolean;
FOnBandDrag: TBandDragEvent;
FOnBandInfo: TBandInfoEvent;
FOnBandMove: TBandMoveEvent;
FOnBandPaint: TBandPaintEvent;
FOnPaint: TNotifyEvent;
FBevelEdges: TBevelEdges;
FBevelOuter: TBevelCut;
FBevelInner: TBevelCut;
FAutoSize: Boolean;
procedure AdjustSize; reintroduce;
procedure MarkDirty;
procedure DoAlignControl(AControl: TControl);
function FindPos(AControl: TControl): Pointer;
function HitTest2(X, Y: Integer): Pointer;
function HitTest3(X, Y: Integer): TControl;
procedure DockControl(AControl: TControl; const ARect: TRect;
BreakList, IndexList, SizeList: TList; Parent: Pointer;
ChangedPriorBreak: Boolean; Insets: TRect; PreferredSize,
RowCount: Integer; Existing: Boolean);
function EdgeSpacing(Edge: TBevelEdge): Integer;
procedure PictureChanged(Sender: TObject);
procedure SetPicture(const Value: TPicture);
procedure SetRowSize(Value: TRowSize);
procedure SetRowSnap(Value: Boolean);
procedure UnDockControl(AControl: TControl);
function UpdateItems(AControl: TControl): Boolean;
procedure SetBevelEdges(const Value: TBevelEdges);
procedure SetBevelInner(const Value: TBevelCut);
procedure SetBevelOuter(const Value: TBevelCut);
procedure SetAutoSize(const Value: Boolean);
protected
procedure AlignControls(AControl: TControl; var ARect: TRect); override;
procedure ControlsListChanged(Control: TControl; Inserting: Boolean); override;
procedure DoBandMove(Control: TControl; var ARect: TRect); virtual;
procedure DoBandPaint(Control: TControl; Canvas: TCanvas; var ARect: TRect;
var Options: TBandPaintOptions); virtual;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
function DragControl(AControl: TControl; X, Y: Integer;
KeepCapture: Boolean = False): Boolean; virtual;
function GetClientRect: TRect; override;
procedure GetControlInfo(AControl: TControl; var Insets: TRect;
var PreferredSize, RowCount: Integer); virtual;
function HitTest(X, Y: Integer): TControl; reintroduce;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
procedure PaintControlFrame(Canvas: TCanvas; AControl: TControl;
var ARect: TRect); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure FlipChildren(AllLevels: Boolean); override;
procedure StickControls; virtual;
property Picture: TPicture read FPicture write SetPicture;
protected
property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
property GrabCursor: TCursor read FGrabCursor write FGrabCursor default crDefault;
property BevelEdges: TBevelEdges read FBevelEdges write SetBevelEdges
default [beLeft, beTop, beRight, beBottom];
property BevelInner: TBevelCut read FBevelInner write SetBevelInner default bvRaised;
property BevelOuter: TBevelCut read FBevelOuter write SetBevelOuter default bvLowered;
property Color default clBtnFace;
property ParentColor default False;
property RowSize: TRowSize read FRowSize write SetRowSize default 26;
property RowSnap: Boolean read FRowSnap write SetRowSnap default True;
property OnBandDrag: TBandDragEvent read FOnBandDrag write FOnBandDrag;
property OnBandInfo: TBandInfoEvent read FOnBandInfo write FOnBandInfo;
property OnBandMove: TBandMoveEvent read FOnBandMove write FOnBandMove;
property OnBandPaint: TBandPaintEvent read FOnBandPaint write FOnBandPaint;
property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
end;
TControlBar = class(TCustomControlBar)
public
property Canvas;
published
property Align;
property Anchors;
property AutoSize;
property Color;
property Constraints;
property DragMode;
property BevelEdges;
property BevelInner;
property BevelOuter;
property Enabled;
property GrabCursor;
property ParentColor;
property ParentFont;
property ParentShowHint;
property Picture;
property PopupMenu;
property RowSize;
property RowSnap;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnBandDrag;
property OnBandInfo;
property OnBandMove;
property OnBandPaint;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnPaint;
property OnResize;
property OnStartDrag;
end;
procedure Frame3D(Canvas: TCanvas; var Rect: TRect;
TopColor, BottomColor: TColor; Width: Integer);
implementation
{ Utility routines }
procedure Frame3D(Canvas: TCanvas; var Rect: TRect; TopColor, BottomColor: TColor;
Width: Integer);
procedure DoRect;
var
TopRight, BottomLeft: TPoint;
begin
with Canvas, Rect do
begin
TopRight.X := Right;
TopRight.Y := Top;
BottomLeft.X := Left;
BottomLeft.Y := Bottom;
Pen.Color := TopColor;
PolyLine([BottomLeft, TopLeft, TopRight]);
Pen.Color := BottomColor;
Dec(BottomLeft.X);
PolyLine([TopRight, BottomRight, BottomLeft]);
end;
end;
begin
Canvas.Pen.Width := 1;
Dec(Rect.Bottom);
Dec(Rect.Right);
while Width > 0 do
begin
Dec(Width);
DoRect;
InflateRect(Rect, -1, -1);
end;
Inc(Rect.Bottom);
Inc(Rect.Right);
end;
{ TCustomPanel }
function TCustomPanel.GetHandle: QFrameH;
begin
HandleNeeded;
Result := QFrameH(FHandle);
end;
procedure TCustomPanel.SetAlignment(const Value: TAlignment);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
Invalidate;
end;
end;
procedure TCustomPanel.SetBevelWidth(const Value: TBevelWidth);
begin
if FBevelWidth <> Value then
begin
FBevelWidth := Value;
Invalidate;
end;
end;
procedure TCustomPanel.SetBevelInner(const Value: TPanelBevel);
begin
if BevelInner <> Value then
begin
FBevelInner := Value;
Invalidate;
end;
end;
procedure TCustomPanel.SetBevelOuter(const Value: TPanelBevel);
begin
if BevelOuter <> Value then
begin
FBevelOuter := Value;
Invalidate;
end;
end;
procedure TCustomPanel.SetBorderWidth(const Value: TBorderWidth);
begin
if FBorderWidth <> Value then
begin
FBorderWidth := Value;
Realign;
Invalidate;
end;
end;
procedure TCustomPanel.Paint;
const
Alignments: array[TAlignment] of Longint = (Integer(AlignmentFlags_AlignLeft),
Integer(AlignmentFlags_AlignRight),
Integer(AlignmentFlags_AlignHCenter));
cColor: array [Boolean] of Integer = (clBtnShadow, clBtnHighlight);
var
Rect: TRect;
InflateSize: Integer;
begin
Rect := GetClientRect;
if BorderStyle = bsSingle then
begin
Frame3D(Canvas, Rect, clBlack, clBlack, 1);
Inc(Rect.Top);
Inc(Rect.Left);
end;
if BevelOuter <> bvNone then
Frame3D(Canvas, Rect, cColor[not (BevelOuter = bvLowered)],
cColor[BevelOuter = bvLowered], BevelWidth);
if BevelInner <> bvNone then
begin
Frame3D(Canvas, Rect, Color, Color, BorderWidth);
Frame3D(Canvas, Rect, cColor[not (BevelInner = bvLowered)],
cColor[BevelInner = bvLowered], BevelWidth);
end;
with Canvas do
begin
InflateSize := -(BevelWidth div 2);
InflateRect(Rect, InflateSize, InflateSize);
if (Bitmap = nil) or Bitmap.Empty then
begin
Brush.Color := Color;
if Color <> clBackground then
FillRect(Rect)
else
QWidget_erase(Self.Handle, @Rect);
end;
Font := Self.Font;
if Font.Color <> clBlack then { for the caption }
Pen.Color := Font.Color
else
Pen.Color := clText;
TextRect(ClientRect, 0, 0, Caption, Integer(AlignmentFlags_ExpandTabs) or
Integer(AlignmentFlags_AlignVCenter) or
Alignments[FAlignment]);
end;
end;
procedure TCustomPanel.AdjustClientRect(var Rect: TRect);
var
BevelSize: Integer;
begin
inherited AdjustClientRect(Rect);
InflateRect(Rect, -BorderWidth, -BorderWidth);
BevelSize := 0;
if BevelOuter <> bvNone then
Inc(BevelSize, BevelWidth);
if BevelInner <> bvNone then
Inc(BevelSize, BevelWidth);
InflateRect(Rect, -BevelSize, -BevelSize);
end;
procedure TCustomPanel.SetBorderStyle(const Value: TControlBorderStyle);
begin
if FBorderStyle <> Value then
begin
FBorderStyle := Value;
Invalidate;
end;
end;
procedure TCustomPanel.CreateWidget;
begin
FHandle := QFrame_create(ParentWidget, nil, WidgetFlags, False);
end;
constructor TCustomPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents,
csSetCaption, csOpaque, csDoubleClicks, csReplicatable, csNoFocus];
FBevelOuter := bvRaised;
FBevelInner := bvNone;
FBevelWidth := 1;
FAlignment := taCenter;
Height := 41;
Width := 185;
ParentColor := True;
end;
procedure TCustomPanel.Invalidate;
begin
inherited;
InvalidateRect(ClientRect, True);
end;
function TCustomPanel.GetText: TCaption;
begin
Result := FCaption;
end;
procedure TCustomPanel.SetText(const Value: TCaption);
begin
if Caption <> Value then
begin
FCaption := Value;
TextChanged;
Invalidate;
end;
end;
{ TShape }
constructor TShape.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable, csOpaque];
Width := 65;
Height := 65;
Canvas.Pen.Width := 0;
Canvas.Pen.OnChange := StyleChanged;
Canvas.Brush.OnChange := StyleChanged;
ParentColor := False;
end;
procedure TShape.Paint;
var
X, Y, W, H, S: Integer;
begin
with Canvas do
begin
X := Pen.Width div 2;
Y := X;
W := Width - Pen.Width + 1;
H := Height - Pen.Width + 1;
if Pen.Width = 0 then
begin
Dec(W);
Dec(H);
end;
if W < H then S := W else S := H;
if FShape in [stSquare, stRoundSquare, stCircle] then
begin
Inc(X, (W - S) div 2);
Inc(Y, (H - S) div 2);
W := S;
H := S;
end;
case FShape of
stRectangle, stSquare:
Rectangle(X, Y, X + W, Y + H);
stRoundRect, stRoundSquare:
RoundRect(X, Y, X + W, Y + H, S div 4, S div 4);
stCircle, stEllipse:
Ellipse(X, Y, X + W, Y + H);
end;
end;
end;
procedure TShape.StyleChanged(Sender: TObject);
begin
Invalidate;
end;
procedure TShape.SetBrush(Value: TBrush);
begin
Canvas.Brush.Assign(Value);
end;
procedure TShape.SetPen(Value: TPen);
begin
Canvas.Pen.Assign(Value);
end;
procedure TShape.SetShape(Value: TShapeType);
begin
if FShape <> Value then
begin
FShape := Value;
Invalidate;
end;
end;
function TShape.GetBrush: TBrush;
begin
Result := Canvas.Brush;
end;
function TShape.GetPen: TPen;
begin
Result := Canvas.Pen;
end;
procedure TShape.ColorChanged;
begin
Brush.Color := Color;
inherited;
end;
{ TPaintBox }
constructor TPaintBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable];
Width := 105;
Height := 105;
end;
procedure TPaintBox.Paint;
begin
Canvas.Font := Font;
Canvas.Brush.Color := Color;
if csDesigning in ComponentState then
with Canvas do
begin
Pen.Style := psDash;
Brush.Style := bsClear;
Rectangle(0, 0, Width, Height);
end;
if Assigned(FOnPaint) then FOnPaint(Self);
end;
{ TBevel }
constructor TBevel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable];
FStyle := bsLowered;
FShape := bsBox;
Width := 50;
Height := 50;
end;
procedure TBevel.SetStyle(Value: TBevelStyle);
begin
if Value <> FStyle then
begin
FStyle := Value;
Invalidate;
end;
end;
procedure TBevel.SetShape(Value: TBevelShape);
begin
if Value <> FShape then
begin
FShape := Value;
Invalidate;
end;
end;
procedure TBevel.Paint;
var
Color1, Color2: TColor;
Temp: TColor;
procedure BevelRect(const R: TRect);
begin
with Canvas do
begin
Pen.Color := Color1;
PolyLine([Types.Point(R.Left, R.Bottom), Types.Point(R.Left, R.Top),
Types.Point(R.Right, R.Top)]);
Pen.Color := Color2;
PolyLine([Types.Point(R.Right, R.Top), Types.Point(R.Right, R.Bottom),
Types.Point(R.Left, R.Bottom)]);
end;
end;
procedure BevelLine(C: TColor; X1, Y1, X2, Y2: Integer);
begin
with Canvas do
begin
Pen.Color := C;
MoveTo(X1, Y1);
LineTo(X2, Y2);
end;
end;
begin
with Canvas do
begin
if (csDesigning in ComponentState) then
begin
if (FShape = bsSpacer) then
begin
Pen.Style := psDot;
Pen.Mode := pmCopy;
Pen.Color := clBlack;
Brush.Style := bsClear;
Rectangle(0, 0, ClientWidth, ClientHeight);
Exit;
end
else
begin
Pen.Style := psSolid;
Pen.Mode := pmCopy;
Pen.Color := clBlack;
Brush.Style := bsSolid;
end;
end;
Pen.Width := 1;
if FStyle = bsLowered then
begin
Color1 := clBtnShadow;
Color2 := clBtnHighlight;
end
else
begin
Color1 := clBtnHighlight;
Color2 := clBtnShadow;
end;
case FShape of
bsBox: BevelRect(Types.Rect(0, 0, Width - 1, Height - 1));
bsFrame:
begin
Temp := Color1;
Color1 := Color2;
BevelRect(Types.Rect(1, 1, Width - 1, Height - 1));
Color2 := Temp;
Color1 := Temp;
BevelRect(Types.Rect(0, 0, Width - 2, Height - 2));
end;
bsTopLine:
begin
BevelLine(Color1, 0, 0, Width, 0);
BevelLine(Color2, 0, 1, Width, 1);
end;
bsBottomLine:
begin
BevelLine(Color1, 0, Height - 2, Width, Height - 2);
BevelLine(Color2, 0, Height - 1, Width, Height - 1);
end;
bsLeftLine:
begin
BevelLine(Color1, 0, 0, 0, Height);
BevelLine(Color2, 1, 0, 1, Height);
end;
bsRightLine:
begin
BevelLine(Color1, Width - 2, 0, Width - 2, Height);
BevelLine(Color2, Width - 1, 0, Width - 1, Height);
end;
end;
end;
end;
{ TTimer }
constructor TTimer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Interval := 1000;
Enabled := True;
end;
function TTimer.GetHandle: QTimerH;
begin
HandleNeeded;
Result := QTimerH(FHandle);
end;
procedure TTimer.SetEnabled(Value: Boolean);
begin
if Value <> FEnabled then
begin
FEnabled := Value;
if not (csDesigning in ComponentState) then
if Value then
QTimer_start(Handle, Interval, False)
else
QTimer_stop(Handle);
end;
end;
procedure TTimer.SetInterval(Value: Cardinal);
begin
if Value <> FInterval then
begin
FInterval := Value;
if Enabled and not (csDesigning in ComponentState) then
QTimer_changeInterval(Handle, Interval); { starts the timer going again }
end;
end;
procedure TTimer.Timer;
begin
if Assigned(FOnTimer) then
try
FOnTimer(Self);
except
Application.HandleException(Self);
end;
end;
procedure TTimer.HookEvents;
var
Timeout: TMethod;
begin
QTimer_timeout_Event(Timeout) := Timer;
QTimer_hook_hook_timeout(QTimer_hookH(Hooks), Timeout);
inherited HookEvents;
end;
procedure TTimer.CreateWidget;
begin
if not (csDesigning in ComponentState) then
begin
FHandle := QTimer_create(nil, nil);
Hooks := QTimer_hook_create(FHandle);
end;
end;
{ TSplitter }
type
TOpenWidgetControl = class(TWidgetControl);
constructor TSplitter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FResizeStyle := rsPattern;
FAutoSnap := True;
Width := 3;
Height := 22;
Align := alLeft;
Cursor := crHSplit;
FMinSize := 30;
FOldSize := -1;
Color := clBtnFace;
end;
destructor TSplitter.Destroy;
begin
FBrush.Free;
inherited Destroy;
end;
procedure TSplitter.DrawLine;
var
P: TPoint;
Painter: QPainterH;
ParentWidget: QOpenWidgetH;
PaintUnclipped: Boolean;
begin
P := Types.Point(Left, Top);
if Align in [alLeft, alRight] then
P.X := Left + FSplit
else
P.Y := Top + FSplit;
ParentWidget := QOpenWidgetH(Parent.Handle);
PaintUnclipped := QOpenWidget_getWFlags(ParentWidget) and Integer(WidgetFlags_WPaintUnclipped) <> 0;
if not PaintUnclipped then
QOpenWidget_setWFlags(ParentWidget, Integer(WidgetFlags_WPaintUnclipped));
try
Painter := QPainter_create;
try
QPainter_begin(Painter, QWidget_to_QPaintDevice(ParentWidget));
try
QPainter_setRasterOp(Painter, RasterOp_NotXorROP);
if ResizeStyle = rsPattern then
Canvas.Brush.Style := bsDense4
else
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := clForeground;
QPainter_fillRect(Painter, P.X, P.Y, Width, Height, Canvas.Brush.Handle);
finally
QPainter_end(Painter);
end;
finally
QPainter_destroy(Painter);
end;
finally
if not PaintUnclipped then
QOpenWidget_clearWFlags(ParentWidget, Integer(WidgetFlags_WPaintUnclipped));
end;
end;
function TSplitter.FindControl: TControl;
var
P: TPoint;
I: Integer;
R: TRect;
begin
Result := nil;
P := Types.Point(Left, Top);
case Align of
alLeft: Dec(P.X);
alRight: Inc(P.X, Width);
alTop: Dec(P.Y);
alBottom: Inc(P.Y, Height);
else
Exit;
end;
for I := 0 to Parent.ControlCount - 1 do
begin
Result := Parent.Controls[I];
if Result.Visible and Result.Enabled then
begin
R := Result.BoundsRect;
if (R.Right - R.Left) = 0 then
if Align in [alTop, alLeft] then
Dec(R.Left)
else
Inc(R.Right);
if (R.Bottom - R.Top) = 0 then
if Align in [alTop, alLeft] then
Dec(R.Top)
else
Inc(R.Bottom);
if PtInRect(R, P) then
Exit;
end;
end;
Result := nil;
end;
procedure TSplitter.RequestAlign;
begin
inherited RequestAlign;
if (Cursor <> crVSplit) and (Cursor <> crHSplit) then
Exit;
if Align in [alBottom, alTop] then
Cursor := crVSplit
else
Cursor := crHSplit;
end;
procedure TSplitter.Paint;
var
R: TRect;
begin
R := ClientRect;
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := Color;
Canvas.FillRect(R);
if Beveled then
begin
if Align in [alLeft, alRight] then
InflateRect(R, -1, 2)
else
InflateRect(R, 2, -1);
OffsetRect(R, 1, 1);
Canvas.Pen.Width := 2;
Canvas.Pen.Color := clBtnHighlight;
Canvas.MoveTo(R.Left, R.Top);
Canvas.LineTo(R.Left, R.Bottom);
Canvas.MoveTo(R.Right, R.Bottom);
Canvas.LineTo(R.Right, R.Top);
OffsetRect(R, -2, -2);
Canvas.Pen.Color := clBtnShadow;
Canvas.MoveTo(R.Left, R.Top);
Canvas.LineTo(R.Left, R.Bottom);
Canvas.MoveTo(R.Right, R.Bottom);
Canvas.LineTo(R.Right, R.Top);
end;
if csDesigning in ComponentState then
{ Draw outline }
with Canvas do
begin
Pen.Style := psDash;
Brush.Style := bsSolid;
Rectangle(0, 0, Width, Height-1);
end;
if Assigned(FOnPaint) then
FOnPaint(Self);
end;
function TSplitter.DoCanResize(var NewSize: Integer): Boolean;
begin
Result := CanResize(NewSize);
if Result and (NewSize <= MinSize) and FAutoSnap then
NewSize := 0;
end;
function TSplitter.CanResize(var NewSize: Integer): Boolean;
begin
Result := True;
if Assigned(FOnCanResize) then
FOnCanResize(Self, NewSize, Result);
end;
procedure TSplitter.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
I: Integer;
begin
if Button = mbLeft then
begin
FOldCur := Screen.Cursor;
Screen.Cursor := Cursor;
end;
inherited MouseDown(Button, Shift, X, Y);
if Button = mbLeft then
begin
FControl := FindControl;
FDownPos := Types.Point(X, Y);
if Assigned(FControl) then
begin
if Align in [alLeft, alRight] then
begin
FMaxSize := Parent.ClientWidth - FMinSize;
for I := 0 to Parent.ControlCount - 1 do
with Parent.Controls[I] do
if Align in [alLeft, alRight] then
Dec(FMaxSize, Width);
Inc(FMaxSize, FControl.Width);
end
else
begin
FMaxSize := Parent.ClientHeight - FMinSize;
for I := 0 to Parent.ControlCount - 1 do
with Parent.Controls[I] do
if Align in [alTop, alBottom] then
Dec(FMaxSize, Height);
Inc(FMaxSize, FControl.Height);
end;
UpdateSize(X, Y);
with ValidParentForm(Self) do
if ActiveControl <> nil then
begin
FActiveControl := ActiveControl;
FOldKeyDown := TOpenWidgetControl(FActiveControl).OnKeyDown;
TOpenWidgetControl(FActiveControl).OnKeyDown := FocusKeyDown;
end;
if ResizeStyle in [rsLine, rsPattern] then
DrawLine;
end;
end;
end;
procedure TSplitter.UpdateControlSize;
begin
if FNewSize <> FOldSize then
begin
case Align of
alLeft: FControl.Width := FNewSize;
alTop: FControl.Height := FNewSize;
alRight:
begin
Parent.DisableAlign;
try
FControl.Left := FControl.Left + (FControl.Width - FNewSize);
FControl.Width := FNewSize;
finally
Parent.EnableAlign;
end;
end;
alBottom:
begin
Parent.DisableAlign;
try
FControl.Top := FControl.Top + (FControl.Height - FNewSize);
FControl.Height := FNewSize;
finally
Parent.EnableAlign;
end;
end;
end;
Update;
if Assigned(FOnMoved) then FOnMoved(Self);
FOldSize := FNewSize;
end;
end;
procedure TSplitter.CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer);
var
S: Integer;
begin
if Align in [alLeft, alRight] then
Split := X - FDownPos.X
else
Split := Y - FDownPos.Y;
S := 0;
case Align of
alLeft: S := FControl.Width + Split;
alRight: S := FControl.Width - Split;
alTop: S := FControl.Height + Split;
alBottom: S := FControl.Height - Split;
end;
NewSize := S;
if S < FMinSize then
NewSize := FMinSize
else if S > FMaxSize then
NewSize := FMaxSize;
if S <> NewSize then
begin
if Align in [alRight, alBottom] then
S := S - NewSize else
S := NewSize - S;
Inc(Split, S);
end;
end;
procedure TSplitter.UpdateSize(X, Y: Integer);
begin
CalcSplitSize(X, Y, FNewSize, FSplit);
end;
procedure TSplitter.MouseMove(Shift: TShiftState; X, Y: Integer);
var
NewSize, Split: Integer;
begin
inherited MouseMove(Shift, X, Y);
if (ssLeft in Shift) and Assigned(FControl) then
begin
CalcSplitSize(X, Y, NewSize, Split);
if DoCanResize(NewSize) then
begin
if ResizeStyle in [rsLine, rsPattern] then
DrawLine;
FNewSize := NewSize;
FSplit := Split;
if ResizeStyle = rsUpdate then
UpdateControlSize;
if ResizeStyle in [rsLine, rsPattern] then
DrawLine;
end;
end;
end;
procedure TSplitter.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if Button = mbLeft then
Screen.Cursor := FOldCur;
inherited MouseUp(Button, Shift, X, Y);
if Assigned(FControl) then
begin
UpdateControlSize;
StopSizing;
end;
end;
procedure TSplitter.FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = Word(Key_Escape) then
StopSizing
else if Assigned(FOldKeyDown) then
FOldKeyDown(Sender, Key, Shift);
end;
procedure TSplitter.SetBeveled(Value: Boolean);
begin
FBeveled := Value;
Repaint;
end;
procedure TSplitter.StopSizing;
begin
if Assigned(FControl) then
begin
FControl := nil;
if Assigned(FActiveControl) then
begin
TOpenWidgetControl(FActiveControl).OnKeyDown := FOldKeyDown;
FActiveControl := nil;
end;
end;
if Assigned(FOnMoved) then
FOnMoved(Self);
end;
{ TImage }
constructor TImage.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable];
FPicture := TPicture.Create;
FPicture.OnChange := PictureChanged;
FPicture.OnProgress := Progress;
FAutoSize := False;
Height := 105;
Width := 105;
end;
destructor TImage.Destroy;
begin
FPicture.Free;
inherited Destroy;
end;
function TImage.DestRect: TRect;
begin
if Stretch then
Result := ClientRect
else if Center then
Result := Types.Bounds((Width - Picture.Width) div 2, (Height - Picture.Height) div 2,
Picture.Width, Picture.Height)
else
Result := Types.Rect(0, 0, Picture.Width, Picture.Height);
end;
procedure TImage.Paint;
var
Save: Boolean;
begin
Save := FDrawing;
FDrawing := True;
try
with inherited Canvas do
StretchDraw(DestRect, Picture.Graphic);
finally
FDrawing := Save;
end;
if csDesigning in ComponentState then
with inherited Canvas do
begin
Pen.Style := psDash;
Brush.Style := bsClear;
Rectangle(0, 0, Width, Height);
end;
end;
function TImage.DoPaletteChange: Boolean;
var
ParentForm: TCustomForm;
Tmp: TGraphic;
begin
Result := False;
Tmp := Picture.Graphic;
if Visible and (not (csLoading in ComponentState)) and (Tmp <> nil) then
begin
ParentForm := GetParentForm(Self);
if Assigned(ParentForm) and ParentForm.Active and ParentForm.HandleAllocated then
if FDrawing then
else
Result := True;
end;
end;
procedure TImage.Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: WideString);
begin
if FIncrementalDisplay and RedrawNow then
begin
if DoPaletteChange then Update
else Paint;
end;
if Assigned(FOnProgress) then FOnProgress(Sender, Stage, PercentDone, RedrawNow, R, Msg);
end;
function TImage.GetCanvas: TCanvas;
var
Bitmap: TBitmap;
begin
if Picture.Graphic = nil then
begin
Bitmap := TBitmap.Create;
try
Bitmap.Width := Width;
Bitmap.Height := Height;
Picture.Graphic := Bitmap;
finally
Bitmap.Free;
end;
end;
if Picture.Graphic is TBitmap then
Result := TBitmap(Picture.Graphic).Canvas
else
raise EInvalidOperation.CreateRes(@SImageCanvasNeedsBitmap);
end;
procedure TImage.SetAutoSize(const Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
Resize;
end;
end;
procedure TImage.SetCenter(Value: Boolean);
begin
if FCenter <> Value then
begin
FCenter := Value;
PictureChanged(Self);
end;
end;
procedure TImage.SetPicture(Value: TPicture);
begin
FPicture.Assign(Value);
end;
procedure TImage.SetStretch(Value: Boolean);
begin
if Value <> FStretch then
begin
FStretch := Value;
PictureChanged(Self);
end;
end;
procedure TImage.SetTransparent(Value: Boolean);
begin
if Value <> FTransparent then
begin
FTransparent := Value;
PictureChanged(Self);
end;
end;
procedure TImage.PictureChanged(Sender: TObject);
var
G: TGraphic;
begin
if AutoSize and (Picture.Width > 0) and (Picture.Height > 0) then
SetBounds(Left, Top, Picture.Width, Picture.Height);
G := Picture.Graphic;
if G <> nil then
begin
{ if not ((G is TMetaFile) or (G is TIcon)) then }
G.Transparent := FTransparent;
if (not G.Transparent and (not (G is TIcon))) and
(Stretch or (G.Width >= Width) and (G.Height >= Height)) then
ControlStyle := ControlStyle + [csOpaque]
else
ControlStyle := ControlStyle - [csOpaque];
if DoPaletteChange and FDrawing then Update;
end
else ControlStyle := ControlStyle - [csOpaque];
if not FDrawing then Invalidate;
end;
procedure TImage.DoAutoSize;
begin
if Align in [alNone, alLeft, alRight] then
Width := Picture.Width;
if Align in [alNone, alTop, alBottom] then
Height := Picture.Height;
end;
{ TGroupButton }
type
TGroupButton = class(TRadioButton)
private
{ FInClick: Boolean; }
FRadioGroup: TCustomRadioGroup;
protected
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
public
constructor InternalCreate(RadioGroup: TCustomRadioGroup);
destructor Destroy; override;
end;
constructor TGroupButton.InternalCreate(RadioGroup: TCustomRadioGroup);
begin
inherited Create(RadioGroup);
FRadioGroup := RadioGroup;
Parent := RadioGroup;
RadioGroup.FButtons.Add(Self);
Visible := RadioGroup.Visible;
Enabled := RadioGroup.Enabled;
Cursor := RadioGroup.Cursor;
TabStop := False;
InputKeys := [ikArrows];
Masked := True;
end;
destructor TGroupButton.Destroy;
var
RadioGroup: TCustomRadioGroup;
begin
RadioGroup := TCustomRadioGroup(Owner);
if not (csDestroying in RadioGroup.ComponentState) then
QButtonGroup_remove(RadioGroup.Handle, Handle);
RadioGroup.FButtons.Remove(Self);
inherited Destroy;
end;
function TGroupButton.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
if not (csDesigning in ComponentState) and
(QEvent_type(Event) = QEventType_MouseButtonPress) and
(QMouseEvent_button(QMouseEventH(Event)) = ButtonState_LeftButton) then
begin
Result := not TCustomRadioGroup(Parent).CanModify;
end
else
Result := inherited EventFilter(Sender, Event);
end;
procedure TGroupButton.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
if (Key = Key_Down) or (Key = Key_Up) then
if TCustomRadioGroup(Parent).CanModify then
begin
if not Checked then
SetChecked(True);
end
else
Key := 0;
end;
procedure TGroupButton.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
TCustomRadioGroup(Parent).KeyPress(Key);
if (Key = #8) or (Key = #32) then
if not TCustomRadioGroup(Parent).CanModify then Key := #0;
end;
{ TCustomRadioGroup }
procedure TCustomRadioGroup.ClickedHook(Index: Integer);
begin
try
FItemIndex := Index;
if FItemIndex <> FLastIndex then
begin
FLastIndex := FItemIndex;
if (Index >= 0) and (Index < FButtons.Count) then
TWidgetControl(FButtons[Index]).SetFocus;
Click;
end;
except
Application.HandleException(Self);
end;
end;
constructor TCustomRadioGroup.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csClickEvents, csAcceptsControls];
FItems := TStringList.Create;
TStringList(FItems).OnChange := ItemsChange;
FButtons := TList.Create;
FItemIndex := -1;
FLastIndex := -1;
FColumns := 1;
FOrientation := orVertical;
InputKeys := [ikArrows];
TabStop := True;
end;
//const
//Yes, this is intentional. Makes more sense visually.
// OrientMap: array[TOrientation] of Qt.Orientation = (
// Orientation_Vertical, Orientation_Horizontal);
function TCustomRadioGroup.CanModify: Boolean;
begin
Result := True;
end;
procedure TCustomRadioGroup.CreateWidget;
begin
FHandle := QButtonGroup_create(FColumns, Qt.Orientation(FOrientation),
ParentWidget, nil);
Hooks := QButtonGroup_hook_create(Handle);
end;
procedure TCustomRadioGroup.CursorChanged;
var
I: Integer;
begin
inherited CursorChanged;
for I := 0 to FButtons.Count - 1 do
TGroupButton(FButtons[I]).Cursor := Cursor;
end;
destructor TCustomRadioGroup.Destroy;
begin
SetButtonCount(0);
TStringList(FItems).OnChange := nil;
FItems.Free;
FButtons.Free;
inherited Destroy;
end;
function TCustomRadioGroup.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
try
if (QEvent_type(Event) = QEventType_show) then
ForceLayout;
if (QEvent_type(Event) = QEventType_KeyPress) and
(QKeyEvent_key(QKeyEventH(Event)) = Key_Tab) then
Result := False
else
Result := inherited EventFilter(Sender, Event);
except
Application.HandleException(Self);
Result := False;
end;
end;
procedure TCustomRadioGroup.ForceLayout;
begin
QGroupBox_setColumnLayout(Handle, FColumns, Qt.Orientation(FOrientation));
end;
function TCustomRadioGroup.GetHandle: QButtonGroupH;
begin
HandleNeeded;
Result := QButtonGroupH(FHandle);
end;
procedure TCustomRadioGroup.HookEvents;
var
Method: TMethod;
begin
QButtonGroup_clicked_Event(Method) := Self.ClickedHook;
QButtonGroup_hook_hook_clicked(QButtonGroup_hookH(Hooks), Method);
inherited HookEvents;
end;
procedure TCustomRadioGroup.ItemsChange(Sender: TObject);
var
ResizeEvent: QResizeEventH;
Size: TSize;
I: Integer;
begin
UpdateButtons;
ShowingChanged;
for I := 0 to FButtons.Count - 1 do
with TGroupButton(FButtons[I]) do
begin
//calling QRadioButton::resizeEvent will force the button to update it's mask.
//Once QWidget::updateMask is exposed, call that directly.
Size.cx := Width;
Size.cy := Height;
ResizeEvent := QResizeEvent_create(@Size, @Size);
try
QOpenWidget_resizeEvent(QOpenWidgetH(Handle), ResizeEvent);
finally
QResizeEvent_destroy(ResizeEvent);
end;
end;
end;
procedure TCustomRadioGroup.RestoreWidgetState;
var
S: TCaption;
begin
inherited RestoreWidgetState;
UpdateButtons;
S := Caption;
QGroupBox_setTitle(Handle, PWideString(@S));
end;
procedure TCustomRadioGroup.SaveWidgetState;
var
I: Integer;
begin
inherited SaveWidgetState;
for I := FButtons.Count - 1 downto 0 do
TGroupButton(FButtons[I]).Free;
FButtons.Clear;
end;
procedure TCustomRadioGroup.Loaded;
begin
inherited Loaded;
ForceLayout;
end;
procedure TCustomRadioGroup.SetButtonCount(Value: Integer);
begin
while FButtons.Count < Value do TGroupButton.InternalCreate(Self);
while FButtons.Count > Value do TGroupButton(FButtons.Last).Free;
end;
procedure TCustomRadioGroup.SetColumns(Value: Integer);
begin
if (Value > 0) and (FColumns <> Value) then
begin
FColumns := Value;
ForceLayout;
end;
end;
procedure TCustomRadioGroup.SetFocus;
var
BtnIndex: Integer;
begin
if FButtons.Count > 0 then
begin
if FItemIndex < 0 then BtnIndex := 0 else BtnIndex := FItemIndex;
if FButtons.Count > FItemIndex then
TGroupButton(FButtons[BtnIndex]).SetFocus;
end else
inherited SetFocus;
end;
procedure TCustomRadioGroup.SetItemIndex(Value: Integer);
begin
if Value < -1 then Value := -1;
if Value >= FButtons.Count then
Value := FButtons.Count - 1;
if FItemIndex <> Value then
begin
if Value >= 0 then
QButtonGroup_setButton(Handle, Value)
else
TGroupButton(FButtons[FItemIndex]).Checked := False;
FItemIndex := Value;
end;
end;
procedure TCustomRadioGroup.SetItems(Value: TStrings);
begin
FItems.Assign(Value);
end;
procedure TCustomRadioGroup.SetOrientation(const Value: TOrientation);
begin
if FOrientation <> Value then
begin
FOrientation := Value;
ForceLayout;
end;
end;
procedure TCustomRadioGroup.UpdateButtons;
var
I: Integer;
begin
SetButtonCount(FItems.Count);
for I := 0 to FButtons.Count - 1 do
TGroupButton(FButtons[I]).Caption := FItems[I];
if (FItemIndex >= 0) and (FItemIndex < FButtons.Count) then
TGroupButton(FButtons[FItemIndex]).Checked := True;
end;
procedure TCustomRadioGroup.ShowingChanged;
begin
inherited ShowingChanged;
ForceLayout;
end;
function TCustomRadioGroup.WantKey(Key: Integer;
Shift: TShiftState; const KeyText: WideString): Boolean;
var
I: Integer;
begin
if IsAccel(Key, Caption) and CanFocus and (ItemIndex < 0)
and (FButtons.Count > 0) then
begin
TGroupButton(FButtons[0]).Checked := True;
SetFocus;
Click;
Result := True;
Exit
end;
for I := 0 to FButtons.Count - 1 do
begin
Result := TGroupButton(FButtons[I]).WantKey(Key, Shift, KeyText);
if Result then
begin
if FItemIndex <> I then
begin
FItemIndex := I;
Click;
end;
Exit;
end;
end;
Result := inherited WantKey(Key, Shift, KeyText);
end;
{ TCustomControlBar }
type
PDockPos = ^TDockPos;
TDockPos = record
Control: TControl;
Insets: TRect;
Visible: Boolean;
Break: Boolean;
Pos: TPoint;
Width: Integer;
Height: Integer;
RowCount: Integer;
TempRow: Integer;
Parent: PDockPos;
SubItem: PDockPos;
TempBreak: Boolean;
TempPos: TPoint;
TempWidth: Integer;
Dirty: Boolean;
end;
function CreateDockPos(AControl: TControl; Break: Boolean; Visible: Boolean;
const APos: TPoint; AWidth, AHeight: Integer; Parent: PDockPos;
const Insets: TRect; RowCount: Integer): PDockPos;
begin
GetMem(Result, SizeOf(TDockPos));
Result.Control := AControl;
Result.Insets := Insets;
Result.Visible := Visible;
Result.Break := Break;
Result.Pos := APos;
Result.Width := AWidth;
Result.Height := AHeight;
Result.RowCount := RowCount;
Result.TempRow := 1;
Result.TempBreak := Break;
Result.TempPos := APos;
Result.TempWidth := AWidth;
Result.Parent := Parent;
Result.SubItem := nil;
end;
procedure FreeDockPos(Items: TList; DockPos: PDockPos);
var
Tmp: PDockPos;
begin
{ Remove all subitems }
while DockPos <> nil do
begin
Tmp := DockPos;
Items.Remove(DockPos);
DockPos := DockPos.SubItem;
FreeMem(Tmp, SizeOf(TDockPos));
end;
end;
procedure AdjustControlRect(var ARect: TRect; const Insets: TRect);
begin
with Insets do
begin
Dec(ARect.Left, Left);
Dec(ARect.Top, Top);
Inc(ARect.Right, Right);
Inc(ARect.Bottom, Bottom);
end;
end;
constructor TCustomControlBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents,
csDoubleClicks, csOpaque, csNoFocus];
FItems := TList.Create;
FAutoDrag := True;
FPicture := TPicture.Create;
FPicture.OnChange := PictureChanged;
FRowSize := 26;
FRowSnap := True;
FBevelEdges := [beLeft, beTop, beRight, beBottom];
FBevelInner := bvRaised;
FBevelOuter := bvLowered;
Color := clBtnFace;
Width := 100;
Height := 50;
FGrabCursor := crDefault;
FSaveCursor := crNone;
end;
destructor TCustomControlBar.Destroy;
var
I: Integer;
begin
for I := 0 to FItems.Count - 1 do
if FItems[I] <> nil then
FreeMem(PDockPos(FItems[I]), SizeOf(TDockPos));
FItems.Free;
FPicture.Free;
inherited Destroy;
end;
procedure TCustomControlBar.AlignControls(AControl: TControl; var ARect: TRect);
var
I, J, X: Integer;
DockPos: PDockPos;
TotalSize, RowSize, RowSpace, Shift: Integer;
RowHeight, PrevRowHeight: Integer;
MoveBy: Integer;
Pos: TPoint;
CX: Integer;
Control: TControl;
UseTemp: Boolean;
Row: Integer;
RowCount: Integer;
FirstIndex, LastIndex: Integer;
InsertingControl: Boolean;
SelfDirty: Boolean;
R: TRect;
TempRowSize, TempRowSpace: Integer;
AdjustX: Integer;
DockRect: TRect;
PreferredSize: Integer;
TmpDockPos: PDockPos;
Redo: PDockPos;
RedoCount: Integer;
SkipRedo: Boolean;
PaintEvent: QPaintEventH;
function ShouldRedo(DockPos: PDockPos; const Pos: TPoint; Width: Integer): Boolean;
begin
{ Determine whether this subitem has changed and will affect its
parent(s). }
if (DockPos^.Parent <> nil) and ((Pos.X <> DockPos^.Parent^.TempPos.X) or
(Width <> DockPos^.Parent^.TempWidth)) then
begin
DockPos := DockPos^.Parent;
{ Update parents and re-perform align logic }
repeat
DockPos^.TempPos.X := Pos.X;
DockPos^.TempWidth := Width;
Redo := DockPos;
DockPos := DockPos^.Parent;
until DockPos = nil;
Result := True;
end
else
Result := False;
end;
begin
if FAligning then Exit;
FAligning := True;
try
{ Update items }
InsertingControl := UpdateItems(AControl);
if FItems.Count = 0 then Exit;
RowCount := 0;
FirstIndex := 0;
LastIndex := FItems.Count - 1;
{ Find number of rows }
for I := FirstIndex to LastIndex do
begin
DockPos := PDockPos(FItems[I]);
{ First item can't have Break set! }
DockPos^.TempBreak := DockPos^.Break;
if DockPos^.Break then
Inc(RowCount);
end;
Redo := nil;
SkipRedo := False;
RedoCount := 2;
repeat
if Redo <> nil then
begin
SkipRedo := True;
Dec(RedoCount);
end;
if RedoCount = 0 then Exit;
RowHeight := 0;
PrevRowHeight := 0;
Row := 1;
while Row <= RowCount do
begin
if Row = 1 then
RowHeight := ClientRect.Top + EdgeSpacing(beTop);
{ Find first and last index for current row }
if Row = 1 then
FirstIndex := 0
else
FirstIndex := LastIndex + 1;
LastIndex := FItems.Count - 1;
for I := FirstIndex to LastIndex - 1 do
begin
DockPos := PDockPos(FItems[I + 1]);
{ First item can't have Break set }
if DockPos^.Break or DockPos^.TempBreak then
begin
LastIndex := I;
Break;
end;
end;
{ Set temp values for all controls }
TotalSize := ARect.Right - ARect.Left;
RowSize := 0;
RowSpace := 0;
for I := FirstIndex to LastIndex do
begin
DockPos := PDockPos(FItems[I]);
if DockPos^.Break or DockPos^.TempBreak then
begin
RowSize := ClientRect.Left + EdgeSpacing(beLeft);
RowSpace := 0;
UseTemp := False;
if UseTemp then
DockPos^.TempPos.Y := RowHeight else
DockPos^.Pos.Y := RowHeight;
PrevRowHeight := RowHeight;
end
else UseTemp := False;
Control := DockPos^.Control;
if (csDesigning in ComponentState) or Control.Visible then
begin
{ If control was moved/resized, update our info }
if DockPos^.Parent = nil then
begin
PreferredSize := DockPos^.Width;
Dec(PreferredSize, DockPos^.Insets.Left + DockPos^.Insets.Right);
GetControlInfo(Control, DockPos^.Insets, PreferredSize,
DockPos^.RowCount);
DockPos^.Width := PreferredSize + DockPos^.Insets.Left +
DockPos^.Insets.Right;
if not InsertingControl and (DockPos^.Parent = nil) and
(AControl = DockPos^.Control) then
begin
if UseTemp then
begin
DockPos^.TempPos := Point(AControl.Left - ARect.Left -
DockPos^.Insets.Left, AControl.Top - ARect.Top - DockPos^.Insets.Top);
DockPos^.TempWidth := AControl.Width + DockPos^.Insets.Left +
DockPos^.Insets.Right;
DockRect := Bounds(DockPos^.TempPos.X, DockPos^.TempPos.Y,
DockPos^.TempWidth, DockPos^.Height);
end
else
DockRect := Bounds(DockPos^.Pos.X, DockPos^.Pos.Y,
DockPos^.Width, DockPos^.Height);
end;
{ Let user adjust sizes }
if DockPos = Redo then
DockRect := Bounds(DockPos^.TempPos.X, DockPos^.TempPos.Y,
DockPos^.TempWidth, DockPos^.Height)
else
DockRect := Bounds(DockPos^.Pos.X, DockPos^.Pos.Y,
DockPos^.Width, DockPos^.Height);
DoBandMove(Control, DockRect);
DockPos^.TempWidth := DockRect.Right - DockRect.Left;
end
else
begin
{ Use parent's position }
with DockPos^.Parent^ do
begin
DockPos^.Pos := Pos;
DockPos^.TempPos := TempPos;
Inc(DockPos^.Pos.Y, Height);
Inc(DockPos^.TempPos.Y, Height);
DockPos^.Width := Width;
DockPos^.TempWidth := TempWidth;
DockRect := Bounds(DockPos^.TempPos.X, DockPos^.TempPos.Y,
DockPos^.TempWidth, DockPos^.Height);
end;
end;
if DockPos = Redo then
begin
with DockPos^ do
begin
TempPos.X := DockRect.Left;
TempPos.Y := DockRect.Top;
TempWidth := DockRect.Right - DockRect.Left;
Redo := nil;
SkipRedo := False;
end;
end
else
begin
with DockPos^ do
begin
Pos.X := DockRect.Left;
Pos.Y := DockRect.Top;
end;
end;
if UseTemp then
begin
Pos := DockPos^.TempPos;
CX := DockPos^.TempWidth;
end
else
begin
Pos := DockRect.TopLeft;
CX := DockRect.Right - DockRect.Left;
end;
{ Make sure Pos is within bounds }
if Pos.X < RowSize then
begin
{ If a control is being resized/moved then adjust any controls to
its left }
if (RowSpace > 0) then
begin
TempRowSize := Pos.X;
AdjustX := Pos.X;
TempRowSpace := RowSpace;
for J := I - 1 downto FirstIndex do
begin
with PDockPos(FItems[J])^ do
begin
if (csDesigning in ComponentState) or Control.Visible then
begin
if TempPos.X + TempWidth > TempRowSize then
begin
X := TempPos.X + TempWidth - TempRowSize;
{ Calculate adjusted rowspace }
if J < I - 1 then
Dec(TempRowSpace, AdjustX - (TempPos.X + TempWidth));
if X > TempRowSpace then
X := TempRowSpace;
AdjustX := TempPos.X;
Dec(TempPos.X, X);
Dec(TempRowSize, TempWidth);
TmpDockPos := PDockPos(FItems[J]);
if ShouldRedo(TmpDockPos, TmpDockPos^.TempPos,
TmpDockPos^.TempWidth) then
System.Break;
TmpDockPos := SubItem;
while TmpDockPos <> nil do
with TmpDockPos^ do
begin
Pos := PDockPos(FItems[J])^.Pos;
TempPos := PDockPos(FItems[J])^.TempPos;
Inc(Pos.Y, Parent.Height);
Inc(TempPos.Y, Parent.Height);
Width := PDockPos(FItems[J])^.Width;
TempWidth := PDockPos(FItems[J])^.TempWidth;
TmpDockPos := SubItem;
end;
end
else System.Break;
end;
end;
end;
AdjustX := RowSize - Pos.X;
if AdjustX > RowSpace then
AdjustX := RowSpace;
Dec(RowSpace, AdjustX);
Dec(RowSize, AdjustX);
end;
Pos.X := RowSize;
end;
if (Redo <> nil) and not SkipRedo then Break;
if Pos.Y <> PrevRowHeight then
Pos.Y := PrevRowHeight;
if Pos.Y + DockPos^.Height > RowHeight then
RowHeight := Pos.Y + DockPos^.Height;
Inc(RowSpace, Pos.X - RowSize);
Inc(RowSize, Pos.X - RowSize + CX);
if DockPos^.Parent = nil then
begin
DockPos^.TempPos := Pos;
DockPos^.TempWidth := CX;
end
else
begin
if ShouldRedo(DockPos, Pos, CX) then
System.Break
else if not DockPos^.Break and (DockPos^.TempPos.X < Pos.X) then
begin
DockPos^.TempPos := Pos;
DockPos^.TempWidth := CX;
end;
end;
TmpDockPos := DockPos^.SubItem;
while TmpDockPos <> nil do
with TmpDockPos^ do
begin
Pos := DockPos^.Pos;
TempPos := DockPos^.TempPos;
Inc(Pos.Y, Parent.Height);
Inc(TempPos.Y, Parent.Height);
Width := DockPos^.Width;
TempWidth := DockPos^.TempWidth;
TmpDockPos := SubItem;
end;
end;
end;
if (Redo <> nil) and not SkipRedo then Break;
{ Determine whether controls on this row can fit }
Shift := TotalSize - RowSize;
if Shift < 0 then
begin
TotalSize := ARect.Right - ARect.Left;
{ Try to move all controls to fill space }
AdjustX := RowSize;
TempRowSpace := RowSpace;
for I := LastIndex downto FirstIndex do
begin
DockPos := PDockPos(FItems[I]);
Control := DockPos^.Control;
if (csDesigning in ComponentState) or Control.Visible then
begin
if (DockPos^.TempPos.X + DockPos^.TempWidth) > TotalSize then
begin
MoveBy := (DockPos^.TempPos.X + DockPos^.TempWidth) - TotalSize;
if I < LastIndex then
Dec(TempRowSpace, AdjustX - (DockPos^.TempPos.X +
DockPos^.TempWidth));
if MoveBy <= TempRowSpace then
Shift := MoveBy else
Shift := TempRowSpace;
if Shift <= TempRowSpace then
begin
AdjustX := DockPos^.TempPos.X;
Dec(DockPos^.TempPos.X, Shift);
Dec(TotalSize, DockPos^.TempWidth);
if ShouldRedo(DockPos, DockPos^.TempPos, DockPos^.TempWidth) then
Break;
TmpDockPos := DockPos^.SubItem;
while TmpDockPos <> nil do
with TmpDockPos^ do
begin
TempPos := DockPos^.TempPos;
Inc(TempPos.Y, Parent.Height);
TmpDockPos := SubItem;
end;
end
else
Break;
end;
end;
end;
if (Redo <> nil) and not SkipRedo then Break;
{ Try to minimize all controls to fill space }
if TotalSize < 0 then
begin
TotalSize := ARect.Right - ARect.Left;
for I := LastIndex downto FirstIndex do
begin
DockPos := PDockPos(FItems[I]);
Control := DockPos^.Control;
if (csDesigning in ComponentState) or Control.Visible then
begin
if DockPos^.TempPos.X + DockPos^.TempWidth > TotalSize then
begin
{ Try to minimize control, move if it can't be resized }
DockPos^.TempWidth := DockPos^.TempWidth -
((DockPos^.TempPos.X + DockPos^.TempWidth) - TotalSize);
{ if DockPos^.TempWidth < Control.Constraints.MinWidth +
DockPos^.Insets.Left + DockPos^.Insets.Right then
DockPos^.TempWidth := Control.Constraints.MinWidth +
DockPos^.Insets.Left + DockPos^.Insets.Right;}
{ Move control }
if DockPos^.TempPos.X + DockPos^.TempWidth > TotalSize then
begin
Dec(DockPos^.TempPos.X, (DockPos^.TempPos.X +
DockPos^.TempWidth) - TotalSize);
if DockPos^.TempPos.X < ARect.Left then
DockPos^.TempPos.X := ARect.Left;
end;
if ShouldRedo(DockPos, DockPos^.TempPos, DockPos^.TempWidth) then
Break;
TmpDockPos := DockPos^.SubItem;
while TmpDockPos <> nil do
with TmpDockPos^ do
begin
Pos := DockPos^.Pos;
TempPos := DockPos^.TempPos;
Inc(TempPos.Y, Parent.Height);
TempWidth := DockPos^.TempWidth;
TmpDockPos := SubItem;
end;
end;
Dec(TotalSize, DockPos^.TempWidth);
end;
end;
end;
if (Redo <> nil) and not SkipRedo then Break;
{ Done with first pass at minimizing. If we're still cramped for
space then wrap last control if there are more than 1 controls on
this row. }
if (TotalSize < 0) and (FirstIndex <> LastIndex) then
begin
DockPos := PDockPos(FItems[LastIndex]);
DockPos^.TempPos.X := 0;
DockPos^.TempWidth := DockPos^.Width;
DockPos^.TempBreak := True;
Inc(RowCount);
if ShouldRedo(DockPos, DockPos^.TempPos, DockPos^.TempWidth) then
Break;
TmpDockPos := DockPos^.SubItem;
while TmpDockPos <> nil do
with TmpDockPos^ do
begin
TempPos := DockPos^.TempPos;
Inc(TempPos.Y, Parent.Height);
TempWidth := DockPos^.TempWidth;
TmpDockPos := SubItem;
end;
end
else
Inc(Row);
end
else
Inc(Row);
end;
until Redo = nil;
{ Now position controls }
for I := 0 to FItems.Count - 1 do
begin
DockPos := PDockPos(FItems[I]);
with DockPos^ do
if (Parent = nil) and ((csDesigning in ComponentState) or
Control.Visible) then
begin
with Insets do
R := Rect(Left + TempPos.X, Top + TempPos.Y,
TempPos.X + TempWidth - Right,
TempPos.Y + DockPos^.Height - Bottom);
TmpDockPos := SubItem;
while TmpDockPos <> nil do
begin
Inc(R.Bottom, TmpDockPos^.Height);
TmpDockPos := TmpDockPos^.SubItem;
end;
if (R.Left <> Control.Left) or (R.Top <> Control.Top) or
(R.Right - R.Left <> Control.Width) or
(R.Bottom - R.Top <> Control.Height) then
begin
Dirty := True;
SelfDirty := True;
Control.BoundsRect := R;
end;
end;
end;
AdjustSize;
if SelfDirty or (AControl <> nil) then
{$IFDEF MSWINDOWS}
InvalidateRect(ARect, False);
{$ENDIF}
{$IFDEF LINUX}
begin
PaintEvent := QPaintEvent_create(@ARect, False);
QApplication_sendEvent(Handle, PaintEvent);
end;
{$ENDIF}
{ Apply any constraints }
finally
FAligning := False;
end;
end;
const
DefaultInsets: TRect = (Left: 11; Top: 2; Right: 2; Bottom: 2);
function TCustomControlBar.UpdateItems(AControl: TControl): Boolean;
var
I, J, Tmp, RepositionIndex: Integer;
PrevBreak: Boolean;
Control: TControl;
Exists: Boolean;
AddControls: TList;
DockRect, R: TRect;
Dirty: Boolean;
IsVisible: Boolean;
DockPos, TmpDockPos1, TmpDockPos2: PDockPos;
BreakList: TList;
IndexList: TList;
SizeList: TList;
ChangedPriorBreak: Boolean;
procedure AddControl(List: TList; Control: TControl);
var
I: Integer;
begin
for I := 0 to List.Count - 1 do
with TControl(List[I]) do
if (Control.Top < Top) or (Control.Top = Top) and
(Control.Left < Left) then
begin
List.Insert(I, Control);
Exit;
end;
List.Add(Control);
end;
begin
Result := False;
ChangedPriorBreak := False;
AddControls := TList.Create;
BreakList := TList.Create;
IndexList := TList.Create;
SizeList := TList.Create;
try
AddControls.Capacity := ControlCount;
RepositionIndex := -1;
Dirty := False;
for I := 0 to ControlCount - 1 do
begin
Control := Controls[I];
IsVisible := (csDesigning in ComponentState) or Control.Visible;
Exists := False;
for J := 0 to FItems.Count - 1 do
if (PDockPos(FItems[J])^.Parent = nil) and
(PDockPos(FItems[J])^.Control = Control) then
begin
Dirty := Dirty or PDockPos(FItems[J])^.Visible <> IsVisible;
PDockPos(FItems[J])^.Visible := IsVisible;
Exists := True;
Break;
end;
if Exists and (Control = AControl) then
begin
RepositionIndex := J;
DockPos := PDockPos(FItems[J]);
with DockPos^ do
begin
SizeList.Add(TObject(Insets.Top + Insets.Bottom));
if FDragControl <> nil then
DockRect := Rect(Pos.X + Insets.Left, Pos.Y + Insets.Top,
Pos.X + Width - Insets.Right, Pos.Y + Insets.Top + Control.Height)
else
DockRect := Control.BoundsRect;
PrevBreak := Break;
end;
{ If we were starting a row, then update any items to the right to
begin starting the row. }
if PrevBreak and (J + 1 < FItems.Count) then
begin
TmpDockPos1 := FItems[J + 1];
if not TmpDockPos1.Break then
begin
TmpDockPos1.Break := True;
TmpDockPos1.TempBreak := True;
ChangedPriorBreak := True;
end;
end;
{ Remember the state of this item and its subitems }
BreakList.Add(TObject(Ord(PrevBreak)));
IndexList.Add(TObject(J));
TmpDockPos1 := DockPos^.SubItem;
while TmpDockPos1 <> nil do
begin
Tmp := FItems.IndexOf(TmpDockPos1);
BreakList.Add(TObject(Ord(TmpDockPos1.Break)));
IndexList.Add(TObject(Tmp));
with TmpDockPos1^ do
SizeList.Add(TObject(Insets.Top + Insets.Bottom));
{ If we were starting a row, then update any items to the right to
begin starting the row. }
if TmpDockPos1.Break then
begin
if Tmp + 1 < FItems.Count then
begin
TmpDockPos2 := FItems[Tmp + 1];
if not TmpDockPos2.Break then
TmpDockPos2.Break := True;
end;
end;
TmpDockPos1 := TmpDockPos1^.SubItem;
end;
{ Remove this item from consideration in DockControl. It's as if we are
adding a new control. }
FreeDockPos(FItems, DockPos);
end
else if not Exists then
begin
if Control = AControl then Result := True;
AddControl(AddControls, Control);
end;
end;
for I := 0 to AddControls.Count - 1 do
begin
R := TControl(AddControls[I]).BoundsRect;
DockControl(TControl(AddControls[I]), R, BreakList, IndexList, SizeList,
nil, ChangedPriorBreak, DefaultInsets, -1, -1, False);
end;
if RepositionIndex >= 0 then
DockControl(AControl, DockRect, BreakList, IndexList, SizeList, nil,
ChangedPriorBreak, DefaultInsets, -1, -1, True);
// if Dirty then Invalidate;
finally
AddControls.Free;
BreakList.Free;
IndexList.Free;
SizeList.Free;
end;
end;
procedure TCustomControlBar.SetRowSize(Value: TRowSize);
begin
if Value <> RowSize then
begin
FRowSize := Value;
end;
end;
procedure TCustomControlBar.SetRowSnap(Value: Boolean);
begin
if Value <> RowSnap then
begin
FRowSnap := Value;
end;
end;
procedure TCustomControlBar.FlipChildren(AllLevels: Boolean);
begin
{ Do not flip controls }
end;
procedure TCustomControlBar.StickControls;
var
I: Integer;
begin
for I := 0 to FItems.Count - 1 do
if FItems[I] <> nil then
with PDockPos(FItems[I])^ do
begin
if Parent <> nil then
Pos := Point(Parent^.Pos.X, Parent^.Pos.Y + Parent.Height)
else
begin
Pos := Control.BoundsRect.TopLeft;
Dec(Pos.X, Insets.Left);
Dec(Pos.Y, Insets.Top);
end;
Width := Control.Width + Insets.Left + Insets.Right;
Break := TempBreak;
end;
end;
procedure TCustomControlBar.DockControl(AControl: TControl;
const ARect: TRect; BreakList, IndexList, SizeList: TList; Parent: Pointer;
ChangedPriorBreak: Boolean; Insets: TRect; PreferredSize, RowCount: Integer;
Existing: Boolean);
var
I, InsPos, Size, TotalSize: Integer;
DockPos: PDockPos;
MidPoint: TPoint;
NewControlRect, ControlRect: TRect;
IsVisible, DockBreak: Boolean;
PrevBreak: Boolean;
PrevIndex: Integer;
NewHeight, PrevInsetHeight: Integer;
NewLine: Boolean;
procedure AddItem;
var
DockPos: PDockPos;
H: Integer;
begin
if InsPos = 0 then DockBreak := True;
if (PrevIndex <> InsPos) or ChangedPriorBreak then
begin
if DockBreak and (InsPos < FItems.Count) then
begin
DockPos := FItems[InsPos];
if not NewLine and DockPos^.Break then
begin
DockPos^.Break := False;
DockPos^.TempBreak := False;
end;
end;
end;
if RowSnap then
H := RowSize else
H := NewControlRect.Bottom - NewControlRect.Top;
DockPos := CreateDockPos(AControl, DockBreak, IsVisible,
NewControlRect.TopLeft, NewControlRect.Right - NewControlRect.Left,
H, Parent, Insets, RowCount);
if Parent <> nil then
PDockPos(Parent).SubItem := DockPos;
FItems.Insert(InsPos, DockPos);
{ If we're adding an item that spans more than one row, we need to add
pseudo items which are linked to this item. }
if RowCount > 1 then
begin
Dec(RowCount);
Inc(NewControlRect.Top, RowSize);
DockControl(AControl, NewControlRect, BreakList, IndexList, SizeList,
DockPos, False, Insets, PreferredSize, RowCount, False);
end;
end;
begin
FDockingControl := AControl;
if BreakList.Count > 0 then
begin
PrevBreak := Boolean(BreakList[0]);
BreakList.Delete(0);
end
else
PrevBreak := False;
if IndexList.Count > 0 then
begin
PrevIndex := Integer(IndexList[0]);
IndexList.Delete(0);
end
else
PrevIndex := -1;
if SizeList.Count > 0 then
begin
PrevInsetHeight := Integer(SizeList[0]);
SizeList.Delete(0);
end
else
PrevInsetHeight := -1;
InsPos := 0;
Size := -MaxInt;
TotalSize := -MaxInt;
NewControlRect := ARect;
if RowCount < 0 then
with AControl do
begin
PreferredSize := ARect.Right - ARect.Left;
Insets := DefaultInsets;
if PrevInsetHeight < 0 then
PrevInsetHeight := Insets.Top + Insets.Bottom;
{ Try to fit control into row size }
NewHeight := PrevInsetHeight + NewControlRect.Bottom - NewControlRect.Top;
if RowSnap then
begin
RowCount := NewHeight div RowSize;
if RowCount = 0 then
Inc(RowCount);
if Existing and (NewHeight > RowSize * RowCount) then
Inc(RowCount);
end
else
RowCount := 1;
GetControlInfo(AControl, Insets, PreferredSize, RowCount);
if RowCount = 0 then RowCount := 1;
if RowSnap and Existing and (NewHeight > RowSize * RowCount) then
RowCount := NewHeight div RowSize + 1;
NewControlRect.Right := NewControlRect.Left + PreferredSize;
AdjustControlRect(NewControlRect, Insets);
if RowSnap then
NewControlRect.Bottom := NewControlRect.Top + RowSize * RowCount;
end;
IsVisible := (csDesigning in Self.ComponentState) or AControl.Visible;
MidPoint.Y := NewControlRect.Top + RowSize div 2;
DockBreak := False;
NewLine := False;
for I := 0 to FItems.Count - 1 do
begin
DockPos := PDockPos(FItems[I]);
ControlRect := Rect(DockPos^.Pos.X, DockPos^.Pos.Y, DockPos^.Pos.X +
DockPos^.Width, DockPos^.Pos.Y + DockPos^.Height );
with ControlRect do
begin
if Bottom - Top > Size then
Size := Bottom - Top;
if Bottom > TotalSize then
TotalSize := Bottom;
if (NewControlRect.Left > Left) and (MidPoint.Y > Top) then
begin
DockBreak := False;
InsPos := I + 1;
end;
end;
if (I = FItems.Count - 1) or ((I + 1 = PrevIndex) and (PrevBreak)) or
PDockPos(FItems[I + 1])^.Break then
begin
if MidPoint.Y < TotalSize then
begin
NewLine := (InsPos = 0) and (MidPoint.Y < ControlRect.Top);
AddItem;
Exit;
end
else
begin
DockBreak := (ControlRect.Left > NewControlRect.Left) or
((DockPos^.SubItem = nil));
InsPos := I + 1;
end;
if RowSnap then
Size := RowSize else
Size := 0;
end;
end;
AddItem;
end;
procedure TCustomControlBar.UnDockControl(AControl: TControl);
var
I: Integer;
DockPos: PDockPos;
begin
FDockingControl := AControl;
for I := 0 to FItems.Count - 1 do
begin
DockPos := PDockPos(FItems[I]);
if DockPos^.Control = AControl then
begin
if DockPos^.Break and (I < FItems.Count - 1) then
PDockPos(FItems[I + 1])^.Break := True;
FreeDockPos(FItems, DockPos);
Break;
end;
end;
end;
procedure TCustomControlBar.GetControlInfo(AControl: TControl; var Insets: TRect;
var PreferredSize, RowCount: Integer);
begin
if RowCount = 0 then RowCount := 1;
if Assigned(FOnBandInfo) then FOnBandInfo(Self, AControl, Insets,
PreferredSize, RowCount);
end;
procedure TCustomControlBar.PaintControlFrame(Canvas: TCanvas; AControl: TControl;
var ARect: TRect);
const
Offset = 3;
var
R: TRect;
Options: TBandPaintOptions;
procedure DrawGrabber;
begin
with Canvas, R do
begin
Pen.Color := clBtnHighlight;
MoveTo(R.Left+2, R.Top);
LineTo(R.Left, R.Top);
LineTo(R.Left, R.Bottom+1);
Pen.Color := clBtnShadow;
MoveTo(R.Right, R.Top);
LineTo(R.Right, R.Bottom);
LineTo(R.Left, R.Bottom);
end;
end;
begin
Options := [bpoGrabber, bpoFrame];
DoBandPaint(AControl, Canvas, ARect, Options);
with Canvas do
begin
if not Assigned(Picture.Graphic) then
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(ARect);
end;
if bpoFrame in Options then
DrawEdge(Canvas, ARect, esRaised, esNone, ebRect);
if bpoGrabber in Options then
begin
R := Rect(ARect.Left + Offset, ARect.Top + 2, ARect.Left + Offset + 2,
ARect.Bottom - 3);
DrawGrabber;
end;
end;
end;
procedure TCustomControlBar.Paint;
const
EdgeMap: array[TBevelCut] of TEdgeStyle = (esNone, esLowered, esRaised);
var
I: Integer;
DockPos: PDockPos;
Control: TControl;
R: TRect;
Save: Boolean;
Rgn, Rgn1: QRegionH;
begin
with Canvas do
begin
R := ClientRect;
Rgn := QRegion_create(@R, QRegionRegionType_rectangle);
for I := 0 to FItems.Count - 1 do
begin
DockPos := PDockPos(FItems[I]);
Control := DockPos^.Control;
if (DockPos^.Parent = nil) and ((csDesigning in ComponentState) or
Control.Visible) then
begin
R := Control.BoundsRect;
if (not DockPos.Dirty) and MouseCapture then
with DockPos^.Insets do //include the control frame in clipping region.
begin
Dec(R.Left, Left);
Dec(R.Top, Top);
Inc(R.Right, Right);
Inc(R.Bottom, Bottom);
Rgn1 := QRegion_create(@R, QRegionRegionType_Rectangle);
QRegion_subtract(Rgn, Rgn, Rgn1);
QRegion_destroy(Rgn1);
end;
end;
end;
QPainter_setClipRegion(Canvas.Handle, Rgn);
R := ClientRect;
if Picture.Graphic <> nil then
begin
Save := FDrawing;
FDrawing := True;
try
// Tile image across client area
Canvas.TiledDraw(R, Picture.Graphic);
finally
FDrawing := Save;
end;
end
else begin
Brush.Color := Color;
Brush.Style := bsSolid;
FillRect(R);
end;
QPainter_setClipping(Canvas.Handle, False);
QRegion_destroy(Rgn);
if Assigned(FOnPaint) then FOnPaint(Self);
{ Draw grabbers and frames for each control }
for I := 0 to FItems.Count - 1 do
begin
DockPos := PDockPos(FItems[I]);
Control := DockPos^.Control;
if (DockPos^.Parent = nil) and ((csDesigning in ComponentState) or
Control.Visible) then
begin
R := Control.BoundsRect;
with DockPos^.Insets do
begin
Dec(R.Left, Left);
Dec(R.Top, Top);
Inc(R.Right, Right);
Inc(R.Bottom, Bottom);
end;
if DockPos.Dirty or not MouseCapture then
PaintControlFrame(Canvas, Control, R);
DockPos.Dirty := False;
end;
end;
R := Rect(0, 0, Width, Height);
DrawEdge(Canvas, R, EdgeMap[FBevelInner], EdgeMap[FBevelOuter],
TEdgeBorders(FBevelEdges));
end;
end;
function TCustomControlBar.HitTest(X, Y: Integer): TControl;
var
DockPos: PDockPos;
begin
DockPos := HitTest2(X, Y);
if DockPos <> nil then
Result := DockPos^.Control else
Result := nil;
end;
function TCustomControlBar.HitTest2(X, Y: Integer): Pointer;
var
I: Integer;
R: TRect;
begin
for I := 0 to FItems.Count - 1 do
begin
Result := PDockPos(FItems[I]);
with PDockPos(Result)^ do
if (Parent = nil) and ((csDesigning in ComponentState) or
Control.Visible) then
begin
R := Control.BoundsRect;
with Insets do
begin
Dec(R.Left, Left);
Dec(R.Top, Top);
Inc(R.Right, Right);
Inc(R.Bottom, Bottom);
end;
if PtInRect(R, Point(X, Y)) then Exit;
end;
end;
Result := nil;
end;
function TCustomControlBar.HitTest3(X, Y: Integer): TControl;
var
R: TRect;
DockPos: PDockPos;
begin
Result := nil;
DockPos := HitTest2(X, Y);
if DockPos <> nil then
begin
R := DockPos.Control.BoundsRect;
R.Right := R.Left;
Dec(R.Left, DockPos.Insets.Left);
if PtInRect(R, Point(X, Y)) then
Result := DockPos.Control;
end;
end;
procedure TCustomControlBar.DoAlignControl(AControl: TControl);
var
Rect: TRect;
begin
if not HandleAllocated or (csDestroying in ComponentState) then Exit;
DisableAlign;
try
Rect := GetClientRect;
AlignControls(AControl, Rect);
finally
ControlState := ControlState - [csAlignmentNeeded];
EnableAlign;
end;
end;
procedure TCustomControlBar.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
DockPos: PDockPos;
procedure ResetDockItems;
var
I: Integer;
begin
for I := FItems.Count - 1 downto 0 do
FreeMem(PDockPos(FItems[I]), SizeOf(TDockPos));
FItems.Clear;
FDragControl := nil;
FDockingControl := nil;
DoAlignControl(nil);
end;
begin
inherited MouseDown(Button, Shift, X, Y);
if MouseCapture then
begin
ResetDockItems;
if FDragControl <> nil then
DockPos := FindPos(FDragControl) else
DockPos := HitTest2(X, Y);
if (DockPos <> nil) and (not (ssDouble in Shift) or not (FAutoDrag or
(ssDouble in Shift)) or (csDesigning in ComponentState) or
not DragControl(DockPos^.Control, X, Y, False)) then
begin
FDragControl := DockPos^.Control;
if FDockingControl = FDragControl then
FDockingControl := nil
else
StickControls;
FDragOffset := Point(DockPos^.TempPos.X - X, DockPos^.TempPos.Y - Y);
end;
end;
end;
procedure TCustomControlBar.MouseMove(Shift: TShiftState; X, Y: Integer);
var
DockPos: PDockPos;
Delta: Integer;
AControl: TControl;
begin
inherited MouseMove(Shift, X, Y);
AControl := HitTest3(X, Y);
if (AControl <> nil) then
begin
if FSaveCursor = crNone then
begin
FSaveCursor := Cursor;
Cursor := FGrabCursor;
end
end
else if (FSaveCursor <> crNone) and not MouseCapture then
begin
Cursor := FSaveCursor;
FSaveCursor := crNone;
end;
if MouseCapture then
begin
if FDragControl <> nil then
begin
DockPos := FindPos(FDragControl);
if DockPos <> nil then
with DockPos^ do
begin
Pos.X := X + FDragOffset.X;
Pos.Y := Y + FDragOffset.Y;
TempPos := Pos;
TempWidth := Control.Width + Insets.Left + Insets.Right;
{ Detect a float operation }
if not (csDesigning in ComponentState) and FAutoDrag then
begin
Delta := Control.Height;
if (Pos.X < -Delta) or (Pos.Y < -Delta) or
(Pos.X > ClientWidth + Delta) or (Pos.Y > ClientHeight + Delta) then
begin
if DragControl(Control, X, Y, True) then Exit;
end;
end;
DoAlignControl(Control);
end;
end;
end;
end;
procedure TCustomControlBar.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
Control: TControl;
begin
if FDragControl <> nil then
begin
Control := FDragControl;
FDragControl := nil;
if FDockingControl = Control then
FDockingControl := nil
else
StickControls;
end;
Control := HitTest3(X, Y);
if (Control <> nil) then
begin
if FSaveCursor = crNone then
begin
FSaveCursor := Cursor;
Cursor := FGrabCursor;
end
end
else if (FSaveCursor <> crNone) then
begin
Cursor := FSaveCursor;
FSaveCursor := crNone;
end;
inherited MouseUp(Button, Shift, X, Y);
end;
function TCustomControlBar.FindPos(AControl: TControl): Pointer;
var
I: Integer;
begin
for I := 0 to FItems.Count - 1 do
with PDockPos(FItems[I])^ do
begin
if (Parent = nil) and (Control = AControl) then
begin
Result := FItems[I];
Exit;
end;
end;
Result := nil;
end;
function TCustomControlBar.DragControl(AControl: TControl; X, Y: Integer;
KeepCapture: Boolean): Boolean;
begin
Result := True;
if (AControl <> nil) and Assigned(FOnBandDrag) then
FOnBandDrag(Self, AControl, Result);
end;
procedure TCustomControlBar.DoBandMove(Control: TControl; var ARect: TRect);
begin
if Assigned(FOnBandMove) then FOnBandMove(Self, Control, ARect);
end;
procedure TCustomControlBar.DoBandPaint(Control: TControl; Canvas: TCanvas;
var ARect: TRect; var Options: TBandPaintOptions);
begin
if Assigned(FOnBandPaint) then FOnBandPaint(Self, Control, Canvas, ARect, Options);
end;
procedure TCustomControlBar.SetPicture(const Value: TPicture);
begin
FPicture.Assign(Value);
end;
procedure TCustomControlBar.PictureChanged(Sender: TObject);
begin
if Picture.Graphic <> nil then
if FDrawing then Update;
if not FDrawing then Invalidate;
end;
procedure TCustomControlBar.ControlsListChanged(Control: TControl; Inserting: Boolean);
begin
inherited;
if not Inserting then
begin
if Control = FDragControl then
FDragControl := nil;
UnDockControl(Control);
end;
AdjustSize;
Repaint;
end;
procedure TCustomControlBar.SetBevelEdges(const Value: TBevelEdges);
begin
FBevelEdges := Value;
Invalidate;
end;
procedure TCustomControlBar.SetBevelInner(const Value: TBevelCut);
begin
FBevelInner := Value;
Invalidate;
end;
procedure TCustomControlBar.SetBevelOuter(const Value: TBevelCut);
begin
FBevelOuter := Value;
Invalidate;
end;
function TCustomControlBar.EdgeSpacing(Edge: TBevelEdge): Integer;
begin
Result := 0;
if (Edge in FBevelEdges) then
begin
if FBevelInner in [bvRaised, bvLowered] then Inc(Result);
if FBevelOuter in [bvRaised, bvLowered] then Inc(Result);
end;
end;
function TCustomControlBar.GetClientRect: TRect;
begin
Result.Left := EdgeSpacing(beLeft);
Result.Right := Width - EdgeSpacing(beRight);
Result.Top := EdgeSpacing(beTop);
Result.Bottom := Height - EdgeSpacing(beBottom);
end;
procedure TCustomControlBar.AdjustSize;
var
I,
Dim,
NewDim: Integer;
Resized: Boolean;
begin
if FAutoSize and (FItems.Count > 0) then
begin
Resized := False;
NewDim := 0;
case Align of
alTop, alBottom, alNone:
begin
for I := 0 to FItems.Count - 1 do
with PDockPos(FItems[I])^ do
begin
Dim := Control.Top + Control.Height + Insets.Bottom;
if Dim > NewDim then
NewDim := Dim + EdgeSpacing(beBottom);
end;
if NewDim <> Height then
begin
Height := NewDim;
Resized := True;
end;
end;
alLeft, alRight:
begin
for I := 0 to FItems.Count -1 do
with PDockPos(FItems[I])^ do
begin
Dim := Control.Left + Control.Width + Insets.Right;
if Dim > NewDim then
NewDim := Dim + EdgeSpacing(beLeft);
end;
if NewDim <> Width then
begin
Width := NewDim;
Resized := True;
end;
end;
end;
if Resized then
begin
MarkDirty;
Invalidate;
end;
end;
end;
procedure TCustomControlBar.SetAutoSize(const Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
AdjustSize;
end;
end;
procedure TCustomControlBar.MarkDirty;
var
I: Integer;
begin
for I := 0 to FItems.Count - 1 do
PDockPos(FItems[I]).Dirty := True;
end;
function TCustomControlBar.EventFilter(Sender: QObjectH;
Event: QEventH): Boolean;
begin
{$IFDEF LINUX}
if (QEvent_type(Event) = QEventtype_paint)
and (not FAligning and MouseCapture) then
Result := True
else
{$ENDIF}
Result := inherited EventFilter(Sender, Event);
end;
procedure TImage.Resize;
begin
if FAutoSize then DoAutoSize;
inherited Resize;
end;
initialization
StartClassGroup(TControl);
GroupDescendentsWith(TTimer, QControls.TControl);
finalization
end.
|
object MapRangeSelectDialog: TMapRangeSelectDialog
Left = 234
Top = 105
ActiveControl = StartValueEdit
BorderStyle = bsDialog
Caption = 'Select Map Ranges'
ClientHeight = 453
ClientWidth = 331
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
OldCreateOrder = False
Position = poScreenCenter
PixelsPerInch = 96
TextHeight = 16
object OKButton: TBitBtn
Left = 130
Top = 416
Width = 86
Height = 33
Caption = 'OK'
TabOrder = 0
OnClick = OKButtonClick
Glyph.Data = {
DE010000424DDE01000000000000760000002800000024000000120000000100
0400000000006801000000000000000000001000000000000000000000000000
80000080000000808000800000008000800080800000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333
3333333333333333333333330000333333333333333333333333F33333333333
00003333344333333333333333388F3333333333000033334224333333333333
338338F3333333330000333422224333333333333833338F3333333300003342
222224333333333383333338F3333333000034222A22224333333338F338F333
8F33333300003222A3A2224333333338F3838F338F33333300003A2A333A2224
33333338F83338F338F33333000033A33333A222433333338333338F338F3333
0000333333333A222433333333333338F338F33300003333333333A222433333
333333338F338F33000033333333333A222433333333333338F338F300003333
33333333A222433333333333338F338F00003333333333333A22433333333333
3338F38F000033333333333333A223333333333333338F830000333333333333
333A333333333333333338330000333333333333333333333333333333333333
0000}
NumGlyphs = 2
end
object CancelButton: TBitBtn
Left = 239
Top = 416
Width = 86
Height = 33
TabOrder = 1
OnClick = CancelButtonClick
Kind = bkCancel
end
object Panel1: TPanel
Left = 4
Top = 4
Width = 322
Height = 410
BevelInner = bvRaised
BevelOuter = bvLowered
TabOrder = 2
object StartValueLabel: TLabel
Left = 10
Top = 123
Width = 75
Height = 16
Caption = 'Start Value:'
end
object EndValueLabel: TLabel
Left = 10
Top = 157
Width = 69
Height = 16
Caption = 'End Value:'
end
object StartColorShape: TShape
Left = 91
Top = 221
Width = 65
Height = 25
end
object IncrementsLabel: TLabel
Left = 10
Top = 191
Width = 45
Height = 16
Caption = 'Levels:'
end
object Label4: TLabel
Left = 10
Top = 225
Width = 72
Height = 16
Caption = 'Start Color:'
end
object EndColorShape: TShape
Left = 91
Top = 256
Width = 65
Height = 25
end
object Label5: TLabel
Left = 10
Top = 260
Width = 66
Height = 16
Caption = 'End Color:'
end
object ValueRangeHeaderLabel: TLabel
Left = 15
Top = 3
Width = 282
Height = 50
AutoSize = False
Caption =
'Please enter the starting and ending value of the range and the ' +
'increment for each range break.'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
WordWrap = True
end
object ValueRangeHeaderLabel2: TLabel
Left = 15
Top = 66
Width = 282
Height = 50
AutoSize = False
Caption =
'Also please enter the starting and ending colors - the colors in' +
' between will be automatically calculated.'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
WordWrap = True
end
object StartYearLabel: TLabel
Left = 10
Top = 294
Width = 67
Height = 16
Caption = 'Start Year:'
Visible = False
end
object EndYearLabel: TLabel
Left = 173
Top = 294
Width = 61
Height = 16
Caption = 'End Year:'
Visible = False
end
object CodeRangeHeaderLabel: TLabel
Left = 15
Top = 13
Width = 282
Height = 84
AutoSize = False
Caption =
'Since the colors displayed are based on a list of codes rather t' +
'han a value range, only a color range must be entered. After yo' +
'u click OK below, you will get to choose which codes you want to' +
' display.'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
Visible = False
WordWrap = True
end
object Label1: TLabel
Left = 138
Top = 192
Width = 145
Height = 14
Caption = '(How many color breaks?)'
Font.Charset = DEFAULT_CHARSET
Font.Color = clGreen
Font.Height = -11
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
end
object StartValueEdit: TEdit
Left = 91
Top = 119
Width = 121
Height = 24
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 0
end
object EndValueEdit: TEdit
Left = 91
Top = 153
Width = 121
Height = 24
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 1
end
object LevelsEdit: TEdit
Left = 91
Top = 187
Width = 34
Height = 24
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 2
end
object StartColorButton: TButton
Left = 156
Top = 221
Width = 25
Height = 25
Caption = '...'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 3
OnClick = SetColorButtonClick
end
object EndColorButton: TButton
Left = 156
Top = 256
Width = 25
Height = 25
Caption = '...'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 4
OnClick = SetColorButtonClick
end
object StartYearEdit: TMaskEdit
Left = 91
Top = 290
Width = 75
Height = 24
TabOrder = 5
Visible = False
end
object EndYearEdit: TMaskEdit
Left = 238
Top = 290
Width = 75
Height = 24
TabOrder = 6
Visible = False
end
object MapSizeRadioGroup: TRadioGroup
Left = 10
Top = 317
Width = 304
Height = 64
Caption = ' Map Size: '
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -12
Font.Name = 'Arial'
Font.Style = [fsBold]
ItemIndex = 0
Items.Strings = (
'Search in the current map extent.'
'Search in the whole map.')
ParentFont = False
TabOrder = 7
end
object DisplayLabelsCheckBox: TCheckBox
Left = 10
Top = 386
Width = 185
Height = 17
Alignment = taLeftJustify
Caption = 'Display Labels on Parcels'
TabOrder = 8
end
end
object ColorDialog: TColorDialog
Ctl3D = True
Options = [cdFullOpen]
Left = 199
Top = 235
end
end
|
unit MediaStream.Filer;
interface
uses SysUtils,Classes, Windows, SyncObjs, MediaProcessing.Definitions;
type
TStreamFiler = class
protected
FStream: TFileStream;
FStreamLock: TCriticalSection;
procedure CheckOpened;
procedure DoWriteData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); virtual; abstract;
public
constructor Create; overload; virtual;
constructor Create(const aFileName: string); overload;
destructor Destroy; override;
procedure Open(const aFileName: string); virtual;
procedure Close; virtual;
function Opened: boolean;
function FileName: string;
procedure WriteData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal);
class function DefaultExt: string; virtual; abstract;
end;
implementation
{ TStreamFiler }
procedure TStreamFiler.CheckOpened;
begin
if not Opened then
raise Exception.Create('Файл для записи не открыт');
end;
procedure TStreamFiler.Close;
begin
FreeAndNil(FStream);
end;
constructor TStreamFiler.Create(const aFileName: string);
begin
Create;
Open(aFileName);
end;
destructor TStreamFiler.Destroy;
begin
Close;
FreeAndNil(FStreamLock);
inherited;
end;
function TStreamFiler.FileName: string;
begin
CheckOpened;
result:=FStream.FileName;
end;
constructor TStreamFiler.Create;
begin
FStreamLock:=TCriticalSection.Create;
end;
procedure TStreamFiler.Open(const aFileName: string);
begin
Close;
FStreamLock.Enter;
try
FStream:=TFileStream.Create(aFileName,fmCreate or fmShareDenyWrite);
finally
FStreamLock.Leave;
end;
end;
function TStreamFiler.Opened: boolean;
begin
result:=FStream<>nil;
end;
procedure TStreamFiler.WriteData(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal);
begin
FStreamLock.Enter;
try
CheckOpened;
DoWriteData(aFormat,aData,aDataSize,aInfo,aInfoSize);
finally
FStreamLock.Leave;
end;
end;
end.
|
{####################################################################################################################
TINJECT - Componente de comunicação WhatsApp (Não Oficial WhatsApp)
www.tinject.com.br
Novembro de 2019
####################################################################################################################
Owner.....: Daniel Oliveira Rodrigues - Dor_poa@hotmail.com - +55 51 9.9155-9228
Developer.: Joathan Theiller - jtheiller@hotmail.com -
Mike W. Lustosa - mikelustosa@gmail.com - +55 81 9.9630-2385
Robson André de Morais - robinhodemorais@gmail.com
####################################################################################################################
Obs:
- Código aberto a comunidade Delphi, desde que mantenha os dados dos autores e mantendo sempre o nome do IDEALIZADOR
Mike W. Lustosa;
- Colocar na evolução as Modificação juntamente com as informaçoes do colaborador: Data, Nova Versao, Autor;
- Mantenha sempre a versao mais atual acima das demais;
- Todo Commit ao repositório deverá ser declarado as mudança na UNIT e ainda o Incremento da Versão de
compilação (último digito);
####################################################################################################################
Evolução do Código
####################################################################################################################
Autor........:
Email........:
Data.........:
Identificador:
Modificação..:
####################################################################################################################
}
unit uTInject.ExePath;
interface
{$WARN SYMBOL_PLATFORM OFF}
uses
System.Classes, SysUtils, Windows,
{$IFDEF DESIGNER_COMP}
ToolsAPI,
{$ENDIF}
uTInject.Constant;
Type
TDadosApp = Class(TComponent)
Private
FLocalEXE: String;
FIniProc: Cardinal;
FLocalProject: String;
Procedure TrazNomeJs;
{$IFDEF DESIGNER_COMP}
function GetPathProject: IOTAProject;
{$ENDIF}
Function FindInterno(ADirRoot: String; PFile:String):String;
Public
constructor Create(Owner: TComponent); override;
Function FindDirs(ADirRoot: String; PFile:String):String;
Property LocalEXE: String Read FLocalEXE;
Property LocalProject: String Read FLocalProject;
End;
implementation
uses
Vcl.Forms, Vcl.Dialogs, uTInject.Diversos;
{ TDadosApp }
function TDadosApp.FindDirs(ADirRoot, PFile: String): String;
begin
FIniProc := GetTickCount;
Result := FindInterno(ADirRoot, PFile);
end;
Function TDadosApp.FindInterno(ADirRoot: String; PFile:String): String;
var
LArquivos: TSearchRec;
begin
Result := '';
ADirRoot := IncludeTrailingPathDelimiter(ADirRoot);
if FindFirst(ADirRoot + '*.*', faDirectory + faArchive, LArquivos) = 0 then
begin
Try
Repeat
//Segurança contra TRAVADAS se estiuver um um local com muitos arquivos!!
if (FIniProc - GetTickCount) >= MsMaxFindJSinDesigner then
Begin
if (csDesigning in Owner.ComponentState) then
Begin
if (FIniProc - GetTickCount) < MsMaxFindJSinDesigner * 10 then
WarningDesenv(PFile + ' -> Timeout do Search IDE atingido (' + IntToStr(MsMaxFindJSinDesigner) + ') / ' + IntToStr(FIniProc - GetTickCount));
End;
Exit;
End;
If (LArquivos.Name <> '.') and (LArquivos.Name <> '..') then
begin
If (LArquivos.Attr = fadirectory) or (LArquivos.Attr = 48) then
begin
result := FindInterno(ADirRoot + LArquivos.Name, PFile);
if result <> '' then
Exit;
end;
If (LArquivos.Attr in [faArchive, faNormal]) or (LArquivos.Attr = 8224) then
Begin
if AnsiLowerCase(LArquivos.Name) = AnsiLowerCase(PFile) then
begin
Result := ADirRoot + LArquivos.Name;
exit;
end;
end;
end;
until FindNext(LArquivos) <> 0;
finally
SysUtils.FindClose(LArquivos)
end;
end;
end;
constructor TDadosApp.Create;
begin
//Se estiver em modo DESIGNER tem que catar o local
//Esta rodando a APLICAção
//Entao vai valer o que esta configurado no DPR...
// LocalEXE := ExtractFilePath(Application.exename);
FIniProc := GetTickCount;
Inherited Create(Owner);
TrazNomeJs;
end;
procedure TDadosApp.TrazNomeJs;
var
LpastaRaiz: String;
begin
//Agora tem que varrer para achar!!
LpastaRaiz := ExtractFilePath(Application.exename);
FIniProc := GetTickCount; //rotina de segurança de TIMEOUT
FLocalEXE := FindDirs(ExtractFilePath(LpastaRaiz), NomeArquivoInject);
{$IFDEF DESIGNER_COMP}
LpastaRaiz := ExtractFilePath(GetPathProject.FileName);
{$ENDIF}
FLocalProject := LpastaRaiz;
end;
{$IFDEF DESIGNER_COMP}
function TDadosApp.GetPathProject: IOTAProject;
var
LServico: IOTAModuleServices;
LModulo: IOTAModule;
LProjeto: IOTAProject;
LGrupo: IOTAProjectGroup;
i: Integer;
begin
Result := nil;
try
LServico := BorlandIDEServices as IOTAModuleServices;
for i := 0 to LServico.ModuleCount - 1 do
begin
LModulo := LServico.Modules[i];
if Supports(LModulo, IOTAProjectGroup, LGrupo) then
begin
Result := LGrupo.ActiveProject;
Exit;
end else
Begin
if Supports(LModulo, IOTAProject, LProjeto) then
begin
if Result = nil then
Result := LProjeto;
end;
End;
end;
finally
FIniProc := GetTickCount;
end;
end;
{$ENDIF}
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.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. }
{ }
{***************************************************************************}
//TODO : way too much code in this unit.. get it working then refactor!
unit DPM.IDE.EditorViewFrame;
interface
{$I ..\DPMIDE.inc}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ImgList,
Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Menus, SVGInterfaces,
Vcl.Themes,
DPM.Controls.ButtonedEdit,
DPM.Controls.GroupButton,
VSoftVirtualListView,
ToolsApi,
Spring.Collections,
Spring.Container,
VSoft.Awaitable,
DPM.IDE.Types,
DPM.IDE.IconCache,
DPM.IDE.Options,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Dependency.Interfaces,
DPM.IDE.Logger,
DPM.Core.Configuration.Interfaces,
DPM.Core.Options.Search,
DPM.Core.Package.Interfaces,
DPM.Core.Project.Interfaces,
DPM.IDE.ProjectTreeManager,
{$IF CompilerVersion >= 24.0 }
{$LEGACYIFEND ON}
System.Actions,
{$IFEND}
{$IF CompilerVersion >= 30.0 }
System.ImageList,
{$IFEND}
Vcl.ActnList, DPM.IDE.PackageDetailsFrame;
type
TRowLayout = record
RowWidth : integer;
IconRect : TRect;
TitleRect : TRect;
VersionRect : TRect;
InstalledVersionRect : TRect;
DescriptionRect : TRect;
procedure Update(const ACanvas : TCanvas; const rowRect : TRect; const showSelect : Boolean);
end;
TDPMEditViewFrame = class(TFrame, IPackageSearcher)
lblProject : TLabel;
DPMEditorViewImages : TImageList;
pnlSearchPanel : TPanel;
txtSearch : TButtonedEdit;
btnRefresh : TButton;
chkIncludePrerelease : TCheckBox;
ContentPanel : TPanel;
Splitter2 : TSplitter;
chkIncludeCommercial : TCheckBox;
btnSettings : TButton;
btnAbout : TButton;
lblSources : TLabel;
cbSources : TComboBox;
pnlButtonBar : TPanel;
chkIncludeTrial : TCheckBox;
searchDebounceTimer : TTimer;
PackageListPanel : TPanel;
PackageDetailsFrame : TPackageDetailsFrame;
platformChangeDetectTimer : TTimer;
procedure txtSearchKeyDown(Sender : TObject; var Key : Word; Shift : TShiftState);
procedure btnAboutClick(Sender : TObject);
procedure btnSettingsClick(Sender : TObject);
procedure tabMainChange(Sender : TObject);
procedure searchDebounceTimerTimer(Sender : TObject);
procedure btnRefreshClick(Sender : TObject);
procedure chkIncludePrereleaseClick(Sender : TObject);
procedure platformChangeDetectTimerTimer(Sender : TObject);
procedure txtSearchChange(Sender : TObject);
procedure txtSearchRightButtonClick(Sender : TObject);
private
//controls
FInstalledButton : TDPMGroupButton;
FUpdatesButton : TDPMGroupButton;
FSearchButton : TDPMGroupButton;
FConflictsButton : TDPMGroupButton;
FScrollList : TVSoftVirtualListView;
//controls
//contains layout rects for the list view
FRowLayout : TRowLayout;
//dpm core stuff
FContainer : TContainer;
FLogger : IDPMIDELogger;
FProjectTreeManager : IDPMProjectTreeManager;
FConfigurationManager : IConfigurationManager;
FConfiguration : IConfiguration;
FConfigIsLocal : boolean;
FDPMIDEOptions : IDPMIDEOptions;
//RS IDE Stuff
FProjectGroup : IOTAProjectGroup;
FProject : IOTAProject;
FCurrentPlatform : TDPMPlatform;
FIDEStyleServices : TCustomStyleServices;
//request stuff
FCancelTokenSource : ICancellationTokenSource;
FRequestInFlight : boolean;
FClosing : boolean;
FSearchHistFile : string;
FCurrentTab : TCurrentTab;
FIconCache : TDPMIconCache;
//all installed packages, direct and transitive
FAllInstalledPackages : IList<IPackageSearchResultItem>;
//directly installed packages, might be fitered.
FInstalledPackages : IList<IPackageSearchResultItem>;
FSearchResultPackages : IList<IPackageSearchResultItem>;
FConflictPackages : IList<IPackageSearchResultItem>;
FGotConflicts : boolean;
FPackageReferences : IGraphNode;
FSearchOptions : TSearchOptions;
FSearchSkip : integer;
FSearchTake : integer;
FUpdates : IList<IPackageSearchResultItem>;
//true when we first load the view
FFirstView : boolean;
FHasSources : boolean;
procedure FilterAndLoadInstalledPackages(const searchTxt : string);
protected
procedure SwitchTabs(const currentTab : TCurrentTab; const refresh : boolean);
procedure txtSearchChanged(Sender : TObject);
procedure ScrollListPaintRow(const Sender : TObject; const ACanvas : TCanvas; const itemRect : TRect; const index : Int64; const state : TPaintRowState);
procedure ScrollListPaintNoRows(const Sender : TObject; const ACanvas : TCanvas; const paintRect : TRect);
procedure ScrollListChangeRow(const Sender : TObject; const newRowIndex : Int64; const direction : TScrollDirection; const delta : Int64);
procedure RequestPackageIcon(const index : integer; const package : IPackageSearchResultItem);
function IsProjectGroup : boolean;
function CurrentList : IList<IPackageSearchResultItem>;
procedure AddDefaultSearchHistory;
procedure LoadList(const list : IList<IPackageSearchResultItem>);
procedure SwitchedToInstalled(const refresh : boolean);
procedure SwitchedToUpdates(const refresh : boolean);
procedure SwitchedToSearch(const refresh : boolean);
procedure SwitchedToConflicts(const refresh : boolean);
function GetInstalledPackages : IAwaitable<IList<IPackageSearchResultItem>>;
function GetUpdatedPackages : IAwaitable<IList<IPackageSearchResultItem>>;
function GetConflictingPackages : IAwaitable<IList<IPackageSearchResultItem>>;
function GetPackageIdsFromReferences(const platform : TDPMPlatform) : IList<IPackageId>;
procedure ReloadSourcesCombo;
//IPackageSearcher
function GetSearchOptions : TSearchOptions;
function SearchForPackagesAsync(const options : TSearchOptions) : IAwaitable<IList<IPackageSearchResultItem>>;
function SearchForPackages(const options : TSearchOptions) : IList<IPackageSearchResultItem>;
function GetCurrentPlatform : string;
procedure PackageInstalled(const package : IPackageSearchResultItem);
procedure PackageUninstalled(const package : IPackageSearchResultItem);
procedure SaveBeforeChange;
//Create Ui elements at runtime - uses controls that are not installed, saves dev needing
//to install controls before they can work in this.
procedure CreateControls(AOwner : TComponent);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
//called from the EditorView
procedure Configure(const projectOrGroup : IOTAProject; const container : TContainer; const projectTreeManager : IDPMProjectTreeManager);
procedure ViewSelected;
procedure ViewDeselected;
procedure Closing;
procedure ProjectReloaded;
procedure ThemeChanged;
end;
implementation
{$R *.dfm}
uses
System.Types,
Xml.XMLIntf,
System.Diagnostics,
DPM.Core.Constants,
DPM.Core.Options.Common,
DPM.Core.Utils.Config,
DPM.Core.Utils.Numbers,
DPM.Core.Utils.Strings,
DPM.Core.Project.Editor,
DPM.Core.Package.Icon,
DPM.Core.Package.SearchResults,
DPM.Core.Repository.Interfaces,
DPM.IDE.AboutForm,
DPM.IDE.AddInOptionsHostForm;
const
cDMPSearchHistoryFile = 'packagesearch.txt';
{ TDPMEditViewFrame }
procedure TDPMEditViewFrame.AddDefaultSearchHistory;
begin
//some commonly used open source libs to get people started.
txtSearch.ACStrings.Add('Spring4D.Core');
txtSearch.ACStrings.Add('Spring4D.Base');
txtSearch.ACStrings.Add('VSoft');
txtSearch.ACStrings.Add('VSoft.DUnitX');
txtSearch.ACStrings.Add('VSoft.DelphiMocks');
txtSearch.ACStrings.Add('Gabr42.OmniThreadLibrary');
end;
procedure TDPMEditViewFrame.btnAboutClick(Sender : TObject);
var
aboutForm : TDPMAboutForm;
begin
aboutForm := TDPMAboutForm.Create(nil);
try
aboutForm.ShowModal;
finally
aboutForm.Free;
end;
end;
procedure TDPMEditViewFrame.btnRefreshClick(Sender : TObject);
begin
if FSearchResultPackages <> nil then
FSearchResultPackages.Clear;
//also called by the include checkboxes.
case FCurrentTab of
TCurrentTab.Installed : SwitchedToInstalled(true);
TCurrentTab.Updates : SwitchedToUpdates(true);
TCurrentTab.Search : SwitchedToSearch(true);
TCurrentTab.Conflicts : SwitchedToConflicts(true);
end;
end;
procedure TDPMEditViewFrame.btnSettingsClick(Sender : TObject);
var
bReload : boolean;
optionsHost : TDPMOptionsHostForm;
begin
optionsHost := TDPMOptionsHostForm.Create(Self, FConfigurationManager, FLogger, FDPMIDEOptions, FSearchOptions.ConfigFile);
try
bReload := optionsHost.ShowModal = mrOk;
finally
optionsHost.Free;
end;
if bReload then
begin
FConfiguration := FConfigurationManager.LoadConfig(FSearchOptions.ConfigFile);
PackageDetailsFrame.Init(FContainer, FIconCache, FConfiguration, Self, FProject.FileName);
//populate the sources combo.
ReloadSourcesCombo;
end;
end;
procedure TDPMEditViewFrame.chkIncludePrereleaseClick(Sender : TObject);
begin
PackageDetailsFrame.IncludePreRelease := chkIncludePrerelease.Checked;
btnRefreshClick(Sender);
end;
procedure TDPMEditViewFrame.Closing;
begin
FClosing := true;
PackageDetailsFrame.ViewClosing;
//cancel any pending requests asap. Needs to return quickly or the IDE will hang.
FCancelTokenSource.Cancel;
//allow the cancellation to happen.
//if we don't do this we will get an excepion in the await or cancellation callbacks
while FRequestInFlight do
Application.ProcessMessages;
end;
constructor TDPMEditViewFrame.Create(AOwner : TComponent);
{$IFDEF THEMESERVICES}
var
ideThemeSvc : IOTAIDEThemingServices;
{$ENDIF}
begin
inherited;
FIconCache := TDPMIconCache.Create;
//not published in older versions, so get removed when we edit in older versions.
{$IFDEF STYLEELEMENTS}
StyleElements := [seFont, seClient, seBorder];
{$ENDIF}
//todo - check when the IOTAIDEThemingServices was added
{$IFDEF THEMESERVICES}
ideThemeSvc := (BorlandIDEServices as IOTAIDEThemingServices);
ideThemeSvc.ApplyTheme(Self);
FIDEStyleServices := ideThemeSvc.StyleServices;
{$ELSE}
FIDEStyleServices := Vcl.Themes.StyleServices;
{$ENDIF}
CreateControls(AOwner);
ThemeChanged;
FFirstView := true;
txtSearch.ACEnabled := true;
txtSearch.ACOptions := [acAutoAppend, acAutoSuggest, acUseArrowKey];
txtSearch.ACSource := acsList;
FSearchHistFile := TConfigUtils.GetDefaultDMPFolder + '\' + cDMPSearchHistoryFile;
if FileExists(FSearchHistFile) then
txtSearch.ACStrings.LoadFromFile(FSearchHistFile)
else
//some common packages to help with the search
AddDefaultSearchHistory;
FSearchOptions := TSearchOptions.Create;
//hard code our compiler version here since when we are running in the IDE we are only working with the IDE version
FSearchOptions.CompilerVersion := IDECompilerVersion;
// FSearchOptions.Take := 5; //just for testing.
FSearchSkip := 0;
FSearchTake := 0;
FRowLayout.RowWidth := -1;
FCurrentTab := TCurrentTab.Installed;
PackageDetailsFrame.Configure(FCurrentTab, chkIncludePrerelease.Checked);
FProjectGroup := nil;
FProject := nil;
FCurrentPlatform := TDPMPlatform.UnknownPlatform;
FCancelTokenSource := TCancellationTokenSourceFactory.Create;
FRequestInFlight := false;
end;
procedure TDPMEditViewFrame.CreateControls(AOwner : TComponent);
begin
FInstalledButton := TDPMGroupButton.Create(Self);
FUpdatesButton := TDPMGroupButton.Create(Self);
FSearchButton := TDPMGroupButton.Create(Self);
FConflictsButton := TDPMGroupButton.Create(Self);
FSearchButton.Top := 10;
FSearchButton.Left := 20;
FSearchButton.Caption := 'Search';
FSearchButton.Tag := 0;
FSearchButton.Parent := pnlButtonBar;
FInstalledButton.Top := 10;
FInstalledButton.Left := FSearchButton.Left + FSearchButton.Width + 20;
FInstalledButton.Caption := 'Installed';
FInstalledButton.Tag := 1;
FInstalledButton.Active := true;
FInstalledButton.Parent := pnlButtonBar;
FUpdatesButton.Top := 10;
FUpdatesButton.Left := FInstalledButton.Left + FInstalledButton.Width + 20;
FUpdatesButton.Caption := 'Updates';
FUpdatesButton.Tag := 2;
FUpdatesButton.Parent := pnlButtonBar;
FConflictsButton.Top := 10;
FConflictsButton.Left := FUpdatesButton.Left + FUpdatesButton.Width + 20;
FConflictsButton.Caption := 'Conflicts';
FConflictsButton.Tag := 3;
FConflictsButton.Visible := false;
FConflictsButton.Parent := pnlButtonBar;
FInstalledButton.OnClick := tabMainChange;
FUpdatesButton.OnClick := tabMainChange;
FSearchButton.OnClick := tabMainChange;
FConflictsButton.OnClick := tabMainChange;
FScrollList := TVSoftVirtualListView.Create(Self);
{$IFDEF STYLEELEMENTS}
FScrollList.StyleElements := [seFont, seBorder];
{$ENDIF}
FScrollList.Align := alClient;
FScrollList.BorderStyle := bsNone;
FScrollList.BevelEdges := [];
FScrollList.BevelOuter := bvNone;
FScrollList.BevelInner := bvNone;
FScrollList.BevelKind := bkNone;
FScrollList.RowHeight := 75;
FScrollList.RowCount := 0;
FScrollList.OnPaintRow := Self.ScrollListPaintRow;
FScrollList.OnPaintNoRows := Self.ScrollListPaintNoRows;
FScrollList.OnRowChange := Self.ScrollListChangeRow;
FScrollList.Constraints.MinWidth := 400;
FScrollList.DoubleBuffered := false;
FScrollList.ParentDoubleBuffered := false;
FScrollList.ParentBackground := false;
FScrollList.ParentColor := false;
FScrollList.Parent := PackageListPanel;
end;
function TDPMEditViewFrame.CurrentList : IList<IPackageSearchResultItem>;
begin
case FCurrentTab of
TCurrentTab.Installed : result := FInstalledPackages;
TCurrentTab.Updates : result := FUpdates;
TCurrentTab.Search : result := FSearchResultPackages;
TCurrentTab.Conflicts : result := FConflictPackages;
end;
end;
destructor TDPMEditViewFrame.Destroy;
begin
FSearchOptions.Free;
FIconCache.Free;
FLogger.Debug('DPMIDE : View Destroying');
inherited;
end;
function TDPMEditViewFrame.GetConflictingPackages : IAwaitable<IList<IPackageSearchResultItem>>;
var
lSearchTerm : string;
lProjectFile : string;
begin
//local for capture
lSearchTerm := txtSearch.Text;
if IsProjectGroup then
lProjectFile := FProjectGroup.FileName
else
lProjectFile := FProject.FileName;
result := TAsync.Configure < IList<IPackageSearchResultItem> > (
function(const cancelToken : ICancellationToken) : IList<IPackageSearchResultItem>
var
filter : string;
begin
filter := lSearchTerm;
result := TCollections.CreateList<IPackageSearchResultItem>;
if not IsProjectGroup then
begin
exit;
end;
//simulating long running.
WaitForSingleObject(cancelToken.Handle, 3000);
end, FCancelTokenSource.Token);
end;
function FindPackageRef(const references : IGraphNode; const platform : TDPMPlatform; const searchItem : IPackageSearchResultItem) : IGraphNode;
var
ref : IGraphNode;
begin
result := nil;
if (references = nil) or (not references.HasChildren) then
exit;
for ref in references.ChildNodes do
begin
if ref.Platform <> platform then
continue;
if SameText(ref.Id, searchItem.Id) then
Exit(ref);
if ref.HasChildren then
begin
result := FindPackageRef(ref, platform, searchItem);
if result <> nil then
Exit(result);
end;
end;
end;
function TDPMEditViewFrame.GetCurrentPlatform : string;
begin
//todo : change this.
result := DPMPlatformToString(FCurrentPlatform);
end;
function TDPMEditViewFrame.GetInstalledPackages : IAwaitable<IList<IPackageSearchResultItem>>;
var
lProjectFile : string;
repoManager : IPackageRepositoryManager;
options : TSearchOptions;
begin
//local for capture
if IsProjectGroup then
lProjectFile := FProjectGroup.FileName
else
lProjectFile := FProject.FileName;
repoManager := FContainer.Resolve<IPackageRepositoryManager>;
options := FSearchOptions.Clone;
//we want all packages for installed as we don't know what types we might have
options.Prerelease := true;
options.Commercial := true;
options.Trial := true;
options.SearchTerms := txtSearch.Text;
if not IsProjectGroup then
options.Platforms := [FCurrentPlatform];
result := TAsync.Configure < IList<IPackageSearchResultItem> > (
function(const cancelToken : ICancellationToken) : IList<IPackageSearchResultItem>
var
packageRef : IGraphNode;
item : IPackageSearchResultItem;
begin
result := TCollections.CreateList<IPackageSearchResultItem>;
if IsProjectGroup then
begin
//TODO : Figure out how to work with project groups!
exit;
end
else
begin
FLogger.Debug('DPMIDE : Got Installed package references, fetching metadata...');
result := repoManager.GetInstalledPackageFeed(cancelToken, options, GetPackageIdsFromReferences(ProjectPlatformToDPMPlatform(FProject.CurrentPlatform)), FConfiguration);
for item in result do
begin
if FPackageReferences <> nil then
begin
packageRef := FindPackageRef(FPackageReferences, FCurrentPlatform, item);
if packageRef <> nil then
item.IsTransitive := packageRef.IsTransitive;
end;
end;
FLogger.Debug('DPMIDE : Got Installed package metadata.');
end;
end, FCancelTokenSource.Token);
end;
function TDPMEditViewFrame.GetPackageIdsFromReferences(const platform : TDPMPlatform) : IList<IPackageId>;
var
lookup : IDictionary<string, IPackageId>;
packageRef : IGraphNode;
procedure AddPackageIds(const value : IGraphNode);
var
childRef : IGraphNode;
begin
if not (value.Platform = platform) then
exit;
if not lookup.ContainsKey(Lowercase(value.Id)) then
lookup[Lowercase(value.Id)] := value;
for childRef in value.ChildNodes do
AddPackageIds(childRef);
end;
begin
lookup := TCollections.CreateDictionary < string, IPackageId > ;
result := TCollections.CreateList<IPackageId>;
if FPackageReferences <> nil then
begin
for packageRef in FPackageReferences.ChildNodes do
begin
AddPackageIds(packageRef);
end;
result.AddRange(lookup.Values);
end;
end;
function TDPMEditViewFrame.GetUpdatedPackages : IAwaitable<IList<IPackageSearchResultItem>>;
begin
result := TAsync.Configure < IList<IPackageSearchResultItem> > (
function(const cancelToken : ICancellationToken) : IList<IPackageSearchResultItem>
begin
result := TCollections.CreateList<IPackageSearchResultItem>;
//simulating long running.
//WaitForSingleObject(cancelToken.Handle, 3000);
end, FCancelTokenSource.Token);
end;
function TDPMEditViewFrame.IsProjectGroup : boolean;
begin
result := FProjectGroup <> nil;
end;
procedure TDPMEditViewFrame.LoadList(const list : IList<IPackageSearchResultItem>);
begin
if list = nil then
begin
FScrollList.RowCount := 0;
exit;
end;
FScrollList.CurrentRow := -1;
if FScrollList.RowCount = list.Count then
FScrollList.Invalidate //doing this because if the rowcount is the same it doesn't invalidate.
else
FScrollList.RowCount := list.Count;
if list.Count > 0 then
FScrollList.CurrentRow := 0;
end;
procedure TDPMEditViewFrame.PackageInstalled(const package : IPackageSearchResultItem);
var
packageSearchResult : IPackageSearchResultItem;
begin
package.Installed := true;
package.InstalledVersion := package.Version;
FAllInstalledPackages := nil;
FInstalledPackages := nil;
//if it's in the search results, update the installed version.
if FSearchResultPackages <> nil then
begin
packageSearchResult := FSearchResultPackages.FirstOrDefault(
function(const value : IPackageSearchResultItem) : boolean
begin
result := SameText(value.Id,
package.Id) and (value.Version = package.Version);
end);
if packageSearchResult <> nil then
begin
packageSearchResult.Installed := true;
packageSearchResult.InstalledVersion := package.Version;
end;
end;
if FAllInstalledPackages = nil then
begin
FAllInstalledPackages :=
TCollections.CreateList<IPackageSearchResultItem>;
FAllInstalledPackages.Add(package);
end
else
begin
packageSearchResult := FAllInstalledPackages.FirstOrDefault(
function(const value : IPackageSearchResultItem) : boolean
begin
result := SameText(value.Id,
package.Id) and (value.Version = package.Version);
end);
if packageSearchResult <> nil then
begin
packageSearchResult.Installed := true;
packageSearchResult.InstalledVersion := package.Version;
end
else
FAllInstalledPackages.Add(packageSearchResult);
end;
if FCurrentTab = TCurrentTab.Installed then
FilterAndLoadInstalledPackages(txtSearch.Text);
//Tell the IDE to reload the project as we have just modified it on disk.
FProject.Refresh(true);
//force the project tree to update after installing package.
FProjectTreeManager.NotifyEndLoading();
end;
procedure TDPMEditViewFrame.PackageUninstalled(const package : IPackageSearchResultItem);
var
packageSearchResult : IPackageSearchResultItem;
begin
package.Installed := false;
package.InstalledVersion := '';
//if it's in the search results, update the installed version.
//might be nil if we haven't switched to the tab yet.
if FSearchResultPackages <> nil then
begin
packageSearchResult := FSearchResultPackages.FirstOrDefault(
function(const value : IPackageSearchResultItem) : boolean
begin
result := SameText(value.Id,
package.Id) and (value.Version = package.Version);
end);
if packageSearchResult <> nil then
begin
packageSearchResult.Installed := false;
packageSearchResult.InstalledVersion := '';
end;
end;
//shouldn't be nil
if FAllInstalledPackages <> nil then
begin
packageSearchResult := FAllInstalledPackages.FirstOrDefault(
function(const value : IPackageSearchResultItem) : boolean
begin
result := SameText(value.Id,
package.Id) and (value.Version = package.Version);
end);
if packageSearchResult <> nil then
begin
FAllInstalledPackages.Remove(packageSearchResult);
if FInstalledPackages <> nil then
FInstalledPackages.Remove(packageSearchResult);
if FCurrentTab = TCurrentTab.Installed then
SwitchedToInstalled(False);
// FilterAndLoadInstalledPackages(txtSearch.Text);
end;
end;
//Tell the IDE to reload the project
FProject.Refresh(true);
//force the project tree to update after installing package.
FProjectTreeManager.NotifyEndLoading();
end;
procedure TDPMEditViewFrame.platformChangeDetectTimerTimer(Sender : TObject);
var
projectEditor : IProjectEditor;
projectPlatform : TDPMPlatform;
begin
// since the tools api provides no notifications about active platform change
// we have to resort to this ugly hack.
platformChangeDetectTimer.Enabled := false;
if FProject <> nil then
begin
projectPlatform := ProjectPlatformToDPMPlatform(FProject.CurrentPlatform);
if projectPlatform = TDPMPlatform.UnknownPlatform then
raise Exception.Create('FProject.CurrentPlatform : ' + FProject.CurrentPlatform);
if FCurrentPlatform <> projectPlatform then
begin
FCurrentPlatform := projectPlatform;
projectEditor := TProjectEditor.Create(FLogger, FConfiguration, IDECompilerVersion);
projectEditor.LoadProject(FProject.FileName);
FPackageReferences := projectEditor.GetPackageReferences(FCurrentPlatform); //NOTE : Can return nil. Will change internals to return empty root node.
//TODO : need to do this more safely as it may interrup another operation.
FInstalledPackages := nil; //force refresh as we always need to update the installed packages.
FAllInstalledPackages := nil;
FSearchResultPackages := nil;
FUpdates := nil;
PackageDetailsFrame.SetPlatform(FCurrentPlatform);
PackageDetailsFrame.SetPackage(nil);
FScrollList.CurrentRow := -1;
case FCurrentTab of
TCurrentTab.Search : SwitchedToSearch(true);
TCurrentTab.Installed : SwitchedToInstalled(true);
TCurrentTab.Updates : SwitchedToUpdates(true);
TCurrentTab.Conflicts : SwitchedToConflicts(True);
end;
end;
end;
platformChangeDetectTimer.Enabled := true;
end;
procedure TDPMEditViewFrame.ProjectReloaded;
begin
FLogger.Debug('DPMIDE : EditViewReloaded');
FCurrentPlatform := TDPMPlatform.UnknownPlatform;
platformChangeDetectTimerTimer(platformChangeDetectTimer);
end;
procedure TDPMEditViewFrame.ReloadSourcesCombo;
var
sCurrent : string;
source : ISourceConfig;
idx : integer;
begin
if cbSources.Items.Count > 0 then
sCurrent := cbSources.Items[cbSources.ItemIndex];
cbSources.Clear;
cbSources.Items.Add('All');
if FConfiguration.Sources.Any then
begin
for source in FConfiguration.Sources do
begin
if source.IsEnabled then
begin
cbSources.Items.Add(source.Name);
FHasSources := true;
end;
end;
end
else
FHasSources := false;
if sCurrent <> '' then
begin
idx := cbSources.Items.IndexOf(sCurrent);
if idx <> -1 then
cbSources.ItemIndex := idx
else
cbSources.ItemIndex := 0;
end;
end;
procedure TDPMEditViewFrame.RequestPackageIcon(const index : integer; const package : IPackageSearchResultItem);
var
platform : TDPMPlatform;
id : string;
version : string;
source : string;
repoManager : IPackageRepositoryManager;
config : IConfiguration;
stopWatch : TStopWatch;
begin
stopWatch.Start;
//we need a platform to pass to the repo, because the directory repo needs to construct a filename
//we just get the first plaform in the set, doesn't matter which one.
for platform in package.Platforms do
break;
//local for capture for use in the anonymous methods below.
id := package.Id;
version := package.Version;
source := package.SourceName;
FLogger.Debug('DPMIDE : Requesting icon for [' + id + '.' + version + ']');
repoManager := FContainer.Resolve<IPackageRepositoryManager>;
config := FConfiguration;
TAsync.Configure<IPackageIcon>(
function(const cancelToken : ICancellationToken) : IPackageIcon
begin
result := repoManager.GetPackageIcon(cancelToken, source, id, version,
IDECompilerVersion, platform, FConfiguration);
end, FCancelTokenSource.Token)
.OnException(
procedure(const e : Exception)
begin
if FClosing then
exit;
FLogger.Error(e.Message);
end)
.Await(
procedure(const theResult : IPackageIcon)
var
icon : IPackageIconImage;
begin
if FClosing then
exit;
//the result can be nil if there is no icon found
if theResult <> nil then
try
icon := TPackageIconImage.Create(theResult);
except
icon := nil;
FLogger.Debug('DPMIDE : INVALID icon for [' + id + '.' + version + ']');
end;
//we will cache nil to stop future pointeless requests.
FIconCache.Cache(id, icon);
stopWatch.Stop;
if icon <> nil then
FLogger.Debug('DPMIDE : Got icon for [' + id + '.' + version + '] in ' + IntToStr(stopWatch.ElapsedMilliseconds) + 'ms');
if icon <> nil then
//TODO : Instead request repaint of row.
FScrollList.Invalidate;
end);
end;
procedure TDPMEditViewFrame.SaveBeforeChange;
begin
(BorlandIDEServices as IOTAModuleServices).SaveAll;
end;
procedure TDPMEditViewFrame.ScrollListChangeRow(const Sender : TObject; const newRowIndex : Int64; const direction : TScrollDirection; const delta : Int64);
var
item : IPackageSearchResultItem;
list : IList<IPackageSearchResultItem>;
begin
list := CurrentList;
if list = nil then
begin
PackageDetailsFrame.SetPackage(nil);
exit;
end;
item := nil;
if (newRowIndex >= 0) and (newRowIndex < list.Count) then
item := list[newRowIndex];
PackageDetailsFrame.SetPackage(item);
end;
procedure TDPMEditViewFrame.ScrollListPaintNoRows(const Sender : TObject; const ACanvas : TCanvas; const paintRect : TRect);
begin
ACanvas.Font.Assign(Self.Font);
ACanvas.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
if FRequestInFlight then
ACanvas.TextOut(20, 20, 'Loading....')
else
begin
if FHasSources then
ACanvas.TextOut(20, 20, 'No Packages found')
else
ACanvas.TextOut(20, 20, 'No enabled package sources, add a package source in DPM settings.')
end;
end;
procedure TDPMEditViewFrame.ScrollListPaintRow(const Sender : TObject; const ACanvas : TCanvas; const itemRect : TRect; const index : Int64; const state : TPaintRowState);
var
item : IPackageSearchResultItem;
list : IList<IPackageSearchResultItem>;
titleRect : TRect;
reservedRect : TRect;
title : string;
fontSize : integer;
backgroundColor : TColor;
// foregroundColor : TColor;
icon : IPackageIconImage;
extent : TSize;
oldTextAlign : UINT;
focusRect : TRect;
begin
list := CurrentList;
if (list = nil) or (not list.Any) then
begin
FScrollList.RowCount := 0; //will force a repaint.
//ScrollListPaintNoRows(Sender, ACanvas, FScrollList.ClientRect);
exit;
end;
if (index >= 0) and (index < list.Count) then
item := list[index]
else
exit;
FRowLayout.Update(ACanvas, itemRect, false);
fontSize := ACanvas.Font.Size;
try
if (state in [rsFocusedSelected, rsFocusedHot, rsHot]) then
begin
{$IF CompilerVersion < 32.0}
backgroundColor := $00FFF0E9; // StyleServices.GetSystemColor(clHighlight);
ACanvas.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
{$ELSE}
backgroundColor := FIDEStyleServices.GetStyleColor(TStyleColor.scButtonHot);
ACanvas.Font.Color := FIDEStyleServices.GetSystemColor(clHighlightText);
{$IFEND}
end
else
begin
backgroundColor := FIDEStyleServices.GetSystemColor(clWindow);
ACanvas.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
end;
//row background
ACanvas.Brush.Color := backgroundColor;
ACanvas.FillRect(itemRect);
icon := nil;
if item.Icon <> '' then
begin
//first query will add nil to avoid multiple requests
if not FIconCache.Query(item.Id) then
//fetch the icon async
RequestPackageIcon(index, item)
else
//this might return nil if the request hasn't completed
//or it failed to find the icon.
icon := FIconCache.Request(item.Id);
end;
if icon = nil then
icon := FIconCache.Request('missing_icon');
icon.PaintTo(ACanvas, FRowLayout.IconRect);
//ACanvas.StretchDraw(FRowLayout.IconRect, icon );
//TODO : this all feels super hacky, revisit when IDE supports high dpi/scaling.
// leaving here as it's usefull for debugging layout
// ACanvas.Brush.Color := clRed;
// ACanvas.FillRect(FRowLayout.TitleRect);
// ACanvas.Brush.Color := backgroundColor;
//make text of different font sizes align correctly.
oldTextAlign := SetTextAlign(ACanvas.Handle, TA_BASELINE);
fontSize := ACanvas.Font.Size;
try
//Draw the package Name.
titleRect := FRowLayout.TitleRect;
title := item.Id;
ACanvas.Font.Size := fontSize + 2;
ACanvas.Font.Style := [fsBold];
extent := ACanvas.TextExtent(title);
ExtTextOut(ACanvas.Handle, titleRect.Left, titleRect.Bottom - 6, ETO_CLIPPED, titleRect, title, Length(title), nil);
titleRect.Left := titleRect.Left + extent.cx + 4;
ACanvas.Font.Size := fontSize;
ACanvas.Font.Style := [];
//if there is room and the prefix is reserved, paint the reserved icon
if item.IsReservedPrefix and ((FRowLayout.VersionRect.Left - titleRect.Right) > 16) then
begin
reservedRect.Left := titleRect.Right + 2;
reservedRect.Top := titleRect.Top + 4;
reservedRect.Width := 16;
reservedRect.Height := 16;
DPMEditorViewImages.Draw(ACanvas, reservedRect.Left, reservedRect.Top, 4, TDrawingStyle.dsTransparent, TImageType.itImage);
titleRect.Left := reservedRect.Right + 4;
titleRect.Right := FRowLayout.TitleRect.Right;
end;
title := ' by ' + item.Authors;
if item.Downloads > 0 then
title := title + ', ';
extent := ACanvas.TextExtent(title);
ExtTextOut(ACanvas.Handle, titleRect.Left, titleRect.Bottom - 6, ETO_CLIPPED, titleRect, title, Length(title), nil);
titleRect.Left := titleRect.Left + extent.cx;
if item.Downloads > 0 then
begin
title := TIntegerUtils.InToStringAbbr(item.Downloads);
ACanvas.Font.Style := [fsBold];
extent := ACanvas.TextExtent(title);
ExtTextOut(ACanvas.Handle, titleRect.Left, titleRect.Bottom - 6, ETO_CLIPPED, titleRect, title, Length(title), nil);
titleRect.Left := titleRect.Left + extent.cx + 4;
ACanvas.Font.Style := [];
title := ' downloads';
extent := ACanvas.TextExtent(title);
ExtTextOut(ACanvas.Handle, titleRect.Left, titleRect.Bottom - 6, ETO_CLIPPED, titleRect, title, Length(title), nil);
end;
finally
//this is important
SetTextAlign(ACanvas.Handle, oldTextAlign);
end;
//version
if item.Installed and (item.Version <> item.InstalledVersion) then
title := 'v' + item.InstalledVersion
else
title := 'v' + item.Version;
ACanvas.TextRect(FRowLayout.VersionRect, title, [tfSingleLine, tfVerticalCenter, tfRight]);
if item.Installed and (item.Version <> item.InstalledVersion) then
begin
title := 'v' + item.Version;
ACanvas.TextRect(FRowLayout.InstalledVersionRect, title, [tfSingleLine, tfVerticalCenter, tfRight]);
end;
//description
title := item.Description;
ACanvas.TextRect(FRowLayout.DescriptionRect, title, [tfEndEllipsis, tfWordBreak]);
if (state in [rsFocusedSelected, rsSelected]) then
begin
focusRect := itemRect;
InflateRect(focusRect, -3, -3);
ACanvas.DrawFocusRect(focusRect);
end;
finally
ACanvas.Font.Style := [];
ACanvas.Font.Size := fontSize;
end;
end;
procedure TDPMEditViewFrame.searchDebounceTimerTimer(Sender : TObject);
begin
searchDebounceTimer.Enabled := false;
if FRequestInFlight then
FCancelTokenSource.Cancel;
while FRequestInFlight do
Application.ProcessMessages;
FCancelTokenSource.Reset;
case FCurrentTab of
TCurrentTab.Installed :
begin
//todo : apply filter to installed
SwitchedToInstalled(true);
end;
TCurrentTab.Updates :
begin
SwitchedToUpdates(true);
end;
TCurrentTab.Search :
begin
SwitchedToSearch(true);
end;
TCurrentTab.Conflicts :
begin
end;
end;
end;
function TDPMEditViewFrame.GetSearchOptions : TSearchOptions;
begin
result := FSearchOptions.Clone;
end;
function TDPMEditViewFrame.SearchForPackagesAsync(const options : TSearchOptions) : IAwaitable<IList<IPackageSearchResultItem>>;
var
repoManager : IPackageRepositoryManager;
begin
//local for capture
repoManager := FContainer.Resolve<IPackageRepositoryManager>;
result := TAsync.Configure < IList<IPackageSearchResultItem> > (
function(const cancelToken : ICancellationToken) : IList<IPackageSearchResultItem>
begin
result := repoManager.GetPackageFeed(cancelToken, options, FConfiguration);
//simulating long running.
end, FCancelTokenSource.Token);
end;
function TDPMEditViewFrame.SearchForPackages(const options : TSearchOptions) : IList<IPackageSearchResultItem>;
var
repoManager : IPackageRepositoryManager;
begin
repoManager := FContainer.Resolve<IPackageRepositoryManager>;
result := repoManager.GetPackageFeed(FCancelTokenSource.Token, options, FConfiguration);
end;
procedure TDPMEditViewFrame.SwitchedToConflicts(const refresh : boolean);
begin
if FGotConflicts and (not refresh) then
LoadList(FConflictPackages)
else
begin
FScrollList.RowCount := 0;
FRequestInFlight := true;
FCancelTokenSource.Reset;
FLogger.Debug('DPMIDE : Searching for conflicting packages');
GetConflictingPackages
.OnException(
procedure(const e : Exception)
begin
FRequestInFlight := false;
if FClosing then
exit;
FLogger.Error(e.Message);
end)
.OnCancellation(
procedure
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('DPMIDE : Cancelled getting conflicting packages.');
end)
.Await(
procedure(const theResult : IList<IPackageSearchResultItem>)
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('DPMIDE : Got conflicting packages.');
FConflictPackages := theResult;
FGotConflicts := true;
LoadList(FConflictPackages);
end);
end;
end;
procedure TDPMEditViewFrame.FilterAndLoadInstalledPackages(const searchTxt : string);
begin
FInstalledPackages := TCollections.CreateList<IPackageSearchResultItem>(FAllInstalledPackages.Where(
function(const pkg : IPackageSearchResultItem) : boolean
begin
result := not pkg.IsTransitive;
if result and (searchTxt <> '') then
begin
result := TStringUtils.Contains(pkg.Id, searchTxt, true);
end;
end));
LoadList(FInstalledPackages);
end;
type
TFilterProc = procedure(const searchTxt : string) of object;
procedure TDPMEditViewFrame.SwitchedToInstalled(const refresh : boolean);
var
searchTxt : string;
filterProc : TFilterProc;
//filter the list to only show directly installed packages, and on the search term
begin
FLogger.Debug('DPMIDE : SwitchToInstalled');
searchTxt := txtSearch.Text;
chkIncludePrerelease.Visible := true;
chkIncludeCommercial.Visible := false;
chkIncludeTrial.Visible := false;
filterProc := FilterAndLoadInstalledPackages;
if (not refresh) and (FAllInstalledPackages <> nil) and FAllInstalledPackages.Any then
filterProc(searchTxt)
else
begin
FRequestInFlight := true;
FCancelTokenSource.Reset;
FAllInstalledPackages := nil;
FInstalledPackages := nil;
FScrollList.RowCount := 0;
FLogger.Debug('DPMIDE : Getting Installed Packages..');
GetInstalledPackages
.OnException(
procedure(const e : Exception)
begin
FRequestInFlight := false;
if FClosing then
exit;
FLogger.Error(e.Message);
end)
.OnCancellation(
procedure
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('DPMIDE : Cancelled getting installed packages.');
end)
.Await(
procedure(const theResult : IList<IPackageSearchResultItem>)
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('DPMIDE : Got installed packages.');
FAllInstalledPackages := theResult;
filterProc(searchTxt);
end);
end;
end;
procedure TDPMEditViewFrame.SwitchedToSearch(const refresh : boolean);
begin
chkIncludePrerelease.Visible := true;
chkIncludeCommercial.Visible := true;
chkIncludeTrial.Visible := true;
if (not refresh) and (FSearchResultPackages <> nil) and FSearchResultPackages.Any then
LoadList(FSearchResultPackages)
else
begin
FRequestInFlight := true;
FCancelTokenSource.Reset;
FLogger.Debug('DPMIDE : Searching for Packages..');
FSearchOptions.SearchTerms := Trim(txtSearch.Text);
FSearchOptions.Prerelease := chkIncludePrerelease.Checked;
FSearchOptions.Commercial := chkIncludeCommercial.Checked;
FSearchOptions.Trial := chkIncludeTrial.Checked;
FSearchOptions.Platforms := [FCurrentPlatform];
SearchForPackagesAsync(FSearchOptions)
.OnException(
procedure(const e : Exception)
begin
FRequestInFlight := false;
if FClosing then
exit;
FLogger.Error(e.Message);
end)
.OnCancellation(
procedure
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('DPMIDE : Cancelled searching for packages.');
end)
.Await(
procedure(const theResult : IList<IPackageSearchResultItem>)
var
item : IPackageSearchResultItem;
packageRef : IGraphNode;
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('DPMIDE : Got search results.');
FSearchResultPackages := theResult;
for item in FSearchResultPackages do
begin
packageRef := FindPackageRef(FPackageReferences, FCurrentPlatform, item);
item.Installed := (packageRef <> nil) and (not packageRef.IsTransitive);
if item.Installed then
item.InstalledVersion := packageRef.Version.ToStringNoMeta;
end;
FScrollList.RowCount := FSearchResultPackages.Count;
LoadList(FSearchResultPackages);
end);
end;
end;
procedure TDPMEditViewFrame.SwitchedToUpdates(const refresh : boolean);
begin
chkIncludePrerelease.Visible := true;
chkIncludeCommercial.Visible := false;
chkIncludeTrial.Visible := false;
if (not refresh) and (FUpdates <> nil) and FUpdates.Any then
LoadList(FUpdates)
else
begin
FScrollList.RowCount := 0;
FRequestInFlight := true;
FCancelTokenSource.Reset;
FLogger.Debug('DPMIDE : Getting Updated Packages..');
GetUpdatedPackages
.OnException(
procedure(const e : Exception)
begin
FRequestInFlight := false;
if FClosing then
exit;
FLogger.Error(e.Message);
end)
.OnCancellation(
procedure
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('DPMIDE : Cancelled getting updated packages.');
end)
.Await(
procedure(const theResult : IList<IPackageSearchResultItem>)
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('DPMIDE : Got updated packages.');
FUpdates := theResult;
LoadList(FUpdates);
end);
end;
end;
procedure TDPMEditViewFrame.SwitchTabs(const currentTab : TCurrentTab; const
refresh : boolean);
var
doRefresh : boolean;
begin
if FRequestInFlight then
FCancelTokenSource.Cancel;
while FRequestInFlight do
Application.ProcessMessages;
FCancelTokenSource.Reset;
FCurrentTab := currentTab;
FScrollList.RowCount := 0;
PackageDetailsFrame.SetPackage(nil);
PackageDetailsFrame.Configure(FCurrentTab, chkIncludePrerelease.Checked);
doRefresh := refresh or (txtSearch.Text <> '');
case FCurrentTab of
TCurrentTab.Search : SwitchedToSearch(doRefresh);
TCurrentTab.Installed : SwitchedToInstalled(doRefresh);
TCurrentTab.Updates : SwitchedToUpdates(doRefresh);
TCurrentTab.Conflicts : SwitchedToConflicts(doRefresh);
end;
end;
procedure TDPMEditViewFrame.Configure(const projectOrGroup : IOTAProject; const container : TContainer; const projectTreeManager : IDPMProjectTreeManager);
var
sConfigFile : string;
begin
FContainer := container;
FProjectTreeManager := projectTreeManager;
if not Supports(projectOrGroup, IOTAProjectGroup, FProjectGroup) then
begin
lblProject.Caption := 'DPM : ' + ChangeFileExt(ExtractFileName(projectOrGroup.FileName), '');
FProject := projectOrGroup;
FConflictsButton.Visible := false;
end
else
begin
FConflictsButton.Visible := true;
FProject := nil;
lblProject.Caption := 'DPM : Project Group';
end;
FLogger := FContainer.Resolve<IDPMIDELogger>;
FDPMIDEOptions := FContainer.Resolve<IDPMIDEOptions>;
//if there is a project specific config file then that is what we should use.
sConfigFile := IncludeTrailingPathDelimiter(ExtractFilePath(projectOrGroup.FileName)) + cDPMConfigFileName;
if FileExists(sConfigFile) then
begin
FSearchOptions.ConfigFile := sConfigFile;
FConfigIsLocal := true; //noting this so we can and tell what to do when the settings button is clicked.
end;
// This ensures that the default config file is uses if a project one doesn't exist.
FSearchOptions.ApplyCommon(TCommonOptions.Default);
//load our dpm configuration
FConfigurationManager := FContainer.Resolve<IConfigurationManager>;
FConfigurationManager.EnsureDefaultConfig;
FConfiguration := FConfigurationManager.LoadConfig(FSearchOptions.ConfigFile);
PackageDetailsFrame.Init(FContainer, FIconCache, FConfiguration, Self, FProject.FileName);
//populate the sources combo.
ReloadSourcesCombo;
end;
procedure TDPMEditViewFrame.tabMainChange(Sender : TObject);
var
tab : TCurrentTab;
begin
tab := TCurrentTab(TDPMGroupButton(Sender).Tag);
SwitchTabs(tab, txtSearch.Text <> '');
end;
procedure TDPMEditViewFrame.ThemeChanged;
{$IF CompilerVersion >=32.0}
var
ideThemeSvc : IOTAIDEThemingServices;
{$IFEND}
begin
{$IF CompilerVersion >=32.0}
ideThemeSvc := (BorlandIDEServices as IOTAIDEThemingServices);
ideThemeSvc.ApplyTheme(Self);
FIDEStyleServices := ideThemeSvc.StyleServices;
ideThemeSvc.ApplyTheme(pnlButtonBar);
ideThemeSvc.ApplyTheme(pnlSearchPanel);
ideThemeSvc.ApplyTheme(Splitter2);
{$ELSE}
FIDEStyleServices := Vcl.Themes.StyleServices;
{$IFEND}
//
pnlButtonBar.Color := FIDEStyleServices.GetSystemColor(clBtnFace);
pnlButtonBar.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
pnlSearchPanel.Color := FIDEStyleServices.GetSystemColor(clBtnFace);
pnlSearchPanel.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
Splitter2.Color := FIDEStyleServices.GetSystemColor(clBtnFace);
FSearchButton.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
FInstalledButton.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
FUpdatesButton.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
FConflictsButton.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
FScrollList.Color := FIDEStyleServices.GetSystemColor(clWindow);
FScrollList.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
PackageDetailsFrame.Color := FIDEStyleServices.GetSystemColor(clWindow);
PackageDetailsFrame.ThemeChanged;
// Self.Invalidate;
end;
procedure TDPMEditViewFrame.txtSearchChange(Sender : TObject);
begin
txtSearch.RightButton.Visible := txtSearch.Text <> '';
end;
procedure TDPMEditViewFrame.txtSearchChanged(Sender : TObject);
begin
end;
procedure TDPMEditViewFrame.txtSearchKeyDown(Sender : TObject; var Key : Word; Shift : TShiftState);
var
i : integer;
begin
searchDebounceTimer.Enabled := false;
case key of
VK_RETURN :
begin
i := txtSearch.ACStrings.IndexOf(txtSearch.Text);
if i = -1 then
txtSearch.ACStrings.Insert(0, txtSearch.Text)
else
txtSearch.ACStrings.Move(i, 0);
try
txtSearch.ACStrings.SaveToFile(FSearchHistFile);
except
//ignore the error, not much we can do?
//perhaps log it?
end;
end;
VK_ESCAPE :
begin
txtSearch.Text := '';
searchDebounceTimerTimer(searchDebounceTimer);
end
else
searchDebounceTimer.Enabled := true;
end;
end;
procedure TDPMEditViewFrame.txtSearchRightButtonClick(Sender : TObject);
begin
txtSearch.Text := '';
FSearchResultPackages := nil;
FInstalledPackages := FAllInstalledPackages;
FUpdates := nil;
searchDebounceTimerTimer(searchDebounceTimer);
end;
procedure TDPMEditViewFrame.ViewDeselected;
begin
// The view tab was deselected.
FLogger.Debug('DPMIDE : View Deselected');
platformChangeDetectTimer.Enabled := false;
end;
procedure TDPMEditViewFrame.ViewSelected;
begin
//For some reason this get's called twice for each time the view is selected.
platformChangeDetectTimer.Enabled := true;
FLogger.Debug('DPMIDE : View Selected');
//The first time the view is opened we want to switch to the installed packages tab
if FFirstView then
begin
FFirstView := false;
platformChangeDetectTimerTimer(platformChangeDetectTimer);
//SwitchedToInstalled(true);
end;
end;
{ TRowLayout }
procedure TRowLayout.Update(const ACanvas : TCanvas; const rowRect : TRect; const showSelect : Boolean);
var
bUpdateLayout : boolean;
begin
bUpdateLayout := rowRect.Width <> RowWidth;
if bUpdateLayout then
begin
IconRect.Top := rowRect.Top + 5;
IconRect.Left := rowRect.Left + 10;
IconRect.Width := 32;
IconRect.Height := 32;
VersionRect.Top := IconRect.Top;
VersionRect.Right := rowRect.Right - 50;
VersionRect.Height := Abs(ACanvas.Font.Height) + 10;
//TODO : Figure out a better way to ensure this will be correct
VersionRect.Left := rowRect.Right - ACanvas.TextExtent('1.100.100-aplha123aaaaa').Width - 10;
InstalledVersionRect.Top := VersionRect.Bottom + 10;
InstalledVersionRect.Right := rowRect.Right - 50;
InstalledVersionRect.Height := Abs(ACanvas.Font.Height) + 10;
//TODO : Figure out a better way to ensure this will be correct
InstalledVersionRect.Left := VersionRect.Left;
TitleRect.Top := IconRect.Top;
TitleRect.Height := Abs(ACanvas.Font.Height) * 2;
TitleRect.Left := rowRect.Left + 10 + 32 + 10;
TitleRect.Right := VersionRect.Left - 5;
DescriptionRect.Top := TitleRect.Bottom + 4;
DescriptionRect.Left := TitleRect.Left;
DescriptionRect.Bottom := rowRect.Bottom - 6;
DescriptionRect.Right := VersionRect.Left - 5;
RowWidth := rowRect.Width;
end
else
begin
//just update top and bottom of rects.
IconRect.Top := rowRect.Top + 5;
IconRect.Height := 32;
VersionRect.Top := IconRect.Top;
VersionRect.Height := Abs(ACanvas.Font.Height) + 10;
InstalledVersionRect.Top := VersionRect.Bottom + 10;
InstalledVersionRect.Height := Abs(ACanvas.Font.Height) + 10;
TitleRect.Top := IconRect.Top;
TitleRect.Height := Abs(ACanvas.Font.Height) * 2;
DescriptionRect.Top := TitleRect.Bottom + 4;
DescriptionRect.Bottom := rowRect.Bottom - 5;
end;
end;
end.
|
unit uBD;
interface
uses
classes,IBQuery,SqlExpr,SysUtils,Contnrs,
URegistro, UConexaoFB;
// O exemplo de singleton em /Exemplo1/uDadosRegistroDB.pas é muito mais simples ,
// mas´não funciona no D7 só a partir do Delphi 2009
type
TBD = class
// strict private no D7 não tem strict
private
// Não funciona no D7 class var FInstancia: TBD;
// Variavel estática para armazenar a unica instancia
FBD: TBD;
// Construtor privado para que possamos criar
// o objeto somente dentro da propria classe
constructor Create;
public
class function GetInstancia : TBD;
function Inserir (oRegistro : TRegistro ) : Boolean;
function Excluir (oRegistro : TRegistro ) : Boolean;
function GeraId (Gerador : string ) : Integer;
function Procurar (oRegistro : TRegistro ) : TRegistro;
function Todos (oRegistro : TRegistro ) : TObjectList;
end;
implementation
uses UEmpresa, UEmpresaBD,
uRegistroBD;
var FInstancia:TBD = nil;
{ TBD }
constructor TBD.Create;
begin
// criar o objeto que será fornecida para todos.
FInstancia := create;
end;
function TBD.Excluir(oRegistro: TRegistro): Boolean;
begin
end;
function TBD.GeraId(Gerador: string): Integer;
var
Qry:TIBQuery;
begin
result := 0;
Qry := TIBQuery.Create(nil);
Qry.Database := TConexaoFB.GetObjetoConexao().conexao;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT GEN_ID('+GERADOR+',1) as ID FROM rdb$database');
try
Qry.Open;
result := Qry.FieldByName('ID').AsInteger;
except
on e:Exception do begin
Qry.Close;
Qry.Free;
raise exception.Create('Gerador inexistente: ' + Gerador);
end;
end;
Qry.Close;
Qry.Free;
end;
class function TBD.GetInstancia: TBD;
begin
if (not Assigned(FInstancia)) then begin
FInstancia := create;
end;
result := FInstancia;
end;
function TBD.Inserir(oRegistro: TRegistro): Boolean;
var
fBD : TRegistroBD;
begin
// poderia ter um TList especialista para isto ao invez de um if
// no initialization poderia registrar todas as Classes + ClassesDB no mesmo
// e aqui realizar um loop para descobri, fica "on the fly" - não precisa mais alterar o
// metodo que se tornaria generico.
//
// For in ListClassesRegistrada
// ClasseRegistrada.Inserir(aRegistro);
if oRegistro is TMedico then begin
fBD := TMedicoBD.Create;
TMedico(oRegistro).ID := GeraId('medico');
end;
fBD.Inserir(oRegistro);
end;
function TBD.Procurar(oRegistro: TRegistro): TRegistro;
var
fBD : TRegistroBD;
begin
if oRegistro is TMedico then begin
fBD := TMedicoBD.Create;
end;
result := fBD.Procurar(oRegistro);
end;
function TBD.Todos(oRegistro: TRegistro): TObjectList;
var
fBD : TRegistroBD;
begin
if oRegistro is TEspecialidade then begin
fBD := TEspecialidadeBD.Create;
end;
result := fBD.Todos(oRegistro);
end;
end.
|
unit SMS_Queue;
interface
uses Classes, AdGSM, AdPort, SyncObjs, SIP_RingList;
type
TSMSQueue=class(TThread)
private
ComPort:TApdComPort;
GSM:TApdGSMPhone;
SMSList:TThreadList;
Event:TEvent;
FSIPApp:TObject;
protected
FPort,FBits,FBaud,FStopBits:Integer;
FParity:String;
procedure Execute;override;
public
constructor Create(const Port,Bits,Baud,StopBits:Integer;Parity:String;App:TObject);
destructor Destroy;override;
procedure Add(const Name,Phone,Msg:String;Address:TSIPAddress;QueueID:Cardinal);
end;
implementation
uses SysUtils,Windows, Logger, SIP_Monitor, SIP_App, SIP_QueueManager;
type
TSMS=class(TObject)
Name,
Phone:String;
Msg:String;
Address:TSIPAddress;
QueueID:Cardinal;
end;
{ TSMSQueue }
procedure TSMSQueue.Add(const Name, Phone, Msg: String;Address:TSIPAddress;QueueID:Cardinal);
var S:TSMS;
begin
S:=TSMS.Create;
S.Name:=Name;
S.Phone:=Phone;
S.Msg:=Msg;
S.Address:=Address;
S.QueueID:=QueueID;
TSIPApp(FSIPApp).SIPQueueManager.StartSMS(Address,QueueID);
SMSList.Add(S);
Event.SetEvent;
end;
constructor TSMSQueue.Create;
begin
FSIPApp:=App;
FPort:=Port;
FBits:=Bits;
FBaud:=Baud;
FStopBits:=StopBits;
FParity:=Parity;
Event:=TEvent.Create(nil,True,False,'',False);
SMSList:=TThreadList.Create;
inherited Create(False);
end;
destructor TSMSQueue.Destroy;
begin
Terminate;
Event.SetEvent;
inherited;
FreeAndNil(GSM);
FreeAndNil(ComPort);
FreeAndNil(SMSList);
FreeAndNil(Event);
end;
procedure TSMSQueue.Execute;
var
S:TSMS;
L:TList;
begin
if FPort<=0 then Exit;
ComPort:=TApdComPort.Create(nil);
ComPort.ComNumber:=FPort;
ComPort.DataBits:=FBits;
ComPort.Baud:=FBaud;
ComPort.StopBits:=FStopBits;
ComPort.HWFlowOptions:=[hwfUseRTS,hwfRequireCTS];
ComPort.SWFlowOptions:=swfNone;
ComPort.LogName:='GSM.log';
ComPort.Logging:=tlOn;
ComPort.TraceName:='GSMTrace.log';
ComPort.Tracing:=tlOn;
if SameText(FParity,'odd') then
ComPort.Parity:=pOdd
else
if SameText(FParity,'even') then
ComPort.Parity:=pEven
else
if SameText(FParity,'mark') then
ComPort.Parity:=pMark
else
if SameText(FParity,'space') then
ComPort.Parity:=pSpace
else
ComPort.Parity:=pNone;
GSM:=TApdGSMPhone.Create(nil);
GSM.QuickConnect:=True;
GSM.ComPort:=ComPort;
GSM.GSMMode:=gmText;
//GSM.SMSCenter:='+35988000301';
GSM.Connect;
while not Terminated do
begin
S:=nil;
try
GSM.Diagnose;
SIPMonitor.Status_GSM:=GetTick64;
SIPMonitor.GSM_Registration:=GSM.Registration;
except
SIPMonitor.GSM_Registration:='';
end;
if SIPMonitor.GSM_Registration<>'' then
begin
L:=SMSList.LockList;
try
SIPMonitor.Count_GSM:=L.Count;
if L.Count>0 then
begin
S:=L[0];
L.Delete(0);
end;
if (L.Count<=0) then Event.ResetEvent;
finally
SMSList.UnlockList;
end;
end;
if S<>nil then
begin
try
GSM.SMSAddress:=S.Phone;
GSM.SMSMessage:=S.Msg;
if Log<>nil then Log.Info('SMS('+S.Phone+')'+StringReplace(StringReplace(S.Msg,#13,'<CR>',[rfReplaceAll]),#10,'<LF>',[rfReplaceAll]));
try
//s.Address.Status:='изпращане на SMS';
GSM.SendMessage;
//Sleep(2000);
SIPMonitor.Status_GSM:=GetTick64;
s.Address.AddReport('Успешно изпратен SMS('+S.Name+') към '+s.Phone);
TSIPApp(FSIPApp).SIPQueueManager.Succeed(s.Address,s.QueueID,pkSMS);
except
on E:Exception do
begin
s.Address.AddReport('Неуспешно изпращане на SMS('+S.Name+') към '+s.Phone+' : '+E.Message);
TSIPApp(FSIPApp).SIPQueueManager.Fail(s.Address,s.QueueID,pkSMS);
if Log<>nil then Log.Error('Грешка при изпращане към "'+s.Phone+'" на SMS "'+s.Msg+'" : '+E.Message);
end;
end;
finally
FreeAndNil(S);
end;
end;
if not Terminated then Event.WaitFor(2000);
end;
end;
end.
|
unit LanctoPagtoPrestServico;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Padrao1, Servidor_frme, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxGroupBox,
StdCtrls, Buttons, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage,
DB, cxDBData, cxCheckBox, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, cxDBEdit, FMTBcd,
SqlExpr, Provider, DBClient, Menus, cxRadioGroup, Evento_frme, cxCalendar,
fmeEvento, fmePrestServico, cxLabel, fmeUnidOrcamentaria, dxSkinsCore,
dxSkinsDefaultPainters, dxSkinscxPCPainter, ExtCtrls, frxClass, frxDBSet,
frxDesgn, frxExportPDF, frxRich;
type
TfrmLanctoPagtoPrestServico = class(TfrmPadrao1)
dsPagtoPrestServ: TDataSource;
cdsPagtoPrestServ: TClientDataSet;
dspPagtoPrestServ: TDataSetProvider;
sdsPagtoPrestServ: TSQLDataSet;
PopupMenu1: TPopupMenu;
Novo1: TMenuItem;
Alterar1: TMenuItem;
Exluir1: TMenuItem;
N1: TMenuItem;
Sair1: TMenuItem;
gbUnidOrcament: TcxGroupBox;
btnOk: TBitBtn;
frmeUnidOrcament1: TfrmeUnidOrcament;
cxLabel1: TcxLabel;
rbRecbIndiv: TcxRadioButton;
rbRecbTodos: TcxRadioButton;
rbRecbColet: TcxRadioButton;
sdsPagtoPrestServID: TIntegerField;
sdsPagtoPrestServID_PREST_SERVICO: TIntegerField;
sdsPagtoPrestServDATA_PAGTO: TDateField;
sdsPagtoPrestServANO_MES: TStringField;
sdsPagtoPrestServID_ORDEM: TIntegerField;
sdsPagtoPrestServID_UNID_ORCAMENT: TIntegerField;
sdsPagtoPrestServVALOR_BRUTO: TFMTBCDField;
sdsPagtoPrestServALIQUOTA_ISS: TFMTBCDField;
sdsPagtoPrestServVALOR_ISS: TFMTBCDField;
sdsPagtoPrestServDEDUZ_ISS_B_CALC_IRRF: TStringField;
sdsPagtoPrestServBASE_CALC_PREVID: TFMTBCDField;
sdsPagtoPrestServVALOR_PREVID: TFMTBCDField;
sdsPagtoPrestServBASE_CALC_IRRF: TFMTBCDField;
sdsPagtoPrestServQTD_DEPEND_IRRF: TIntegerField;
sdsPagtoPrestServVALOR_IRRF: TFMTBCDField;
sdsPagtoPrestServVALOR_LIQUIDO: TFMTBCDField;
sdsPagtoPrestServVALOR_MAO_OBRA: TFMTBCDField;
sdsPagtoPrestServHISTORICO: TStringField;
sdsPagtoPrestServRECIBO_INDIVIDUAL: TStringField;
sdsPagtoPrestServNOME_PREST_SERVICO: TStringField;
sdsPagtoPrestServTIPO_PESSOA: TStringField;
sdsPagtoPrestServCPF_CNPJ: TStringField;
cdsPagtoPrestServID: TIntegerField;
cdsPagtoPrestServID_PREST_SERVICO: TIntegerField;
cdsPagtoPrestServDATA_PAGTO: TDateField;
cdsPagtoPrestServANO_MES: TStringField;
cdsPagtoPrestServID_ORDEM: TIntegerField;
cdsPagtoPrestServID_UNID_ORCAMENT: TIntegerField;
cdsPagtoPrestServVALOR_BRUTO: TFMTBCDField;
cdsPagtoPrestServALIQUOTA_ISS: TFMTBCDField;
cdsPagtoPrestServVALOR_ISS: TFMTBCDField;
cdsPagtoPrestServDEDUZ_ISS_B_CALC_IRRF: TStringField;
cdsPagtoPrestServBASE_CALC_PREVID: TFMTBCDField;
cdsPagtoPrestServVALOR_PREVID: TFMTBCDField;
cdsPagtoPrestServBASE_CALC_IRRF: TFMTBCDField;
cdsPagtoPrestServQTD_DEPEND_IRRF: TIntegerField;
cdsPagtoPrestServVALOR_IRRF: TFMTBCDField;
cdsPagtoPrestServVALOR_LIQUIDO: TFMTBCDField;
cdsPagtoPrestServVALOR_MAO_OBRA: TFMTBCDField;
cdsPagtoPrestServHISTORICO: TStringField;
cdsPagtoPrestServRECIBO_INDIVIDUAL: TStringField;
cdsPagtoPrestServNOME_PREST_SERVICO: TStringField;
cdsPagtoPrestServTIPO_PESSOA: TStringField;
cdsPagtoPrestServCPF_CNPJ: TStringField;
Panel: TPanel;
edPesquisa: TcxTextEdit;
lblTitColPesquisa: TcxLabel;
cxLabel3: TcxLabel;
btnAdd: TBitBtn;
btnEdit: TBitBtn;
btnDel: TBitBtn;
btnLimpar: TButton;
btnFechar: TBitBtn;
dbg1: TcxGrid;
GridDBTableView1: TcxGridDBTableView;
cxGridDBColumn1: TcxGridDBColumn;
cxGridDBColumn5: TcxGridDBColumn;
cxGridDBColumn2: TcxGridDBColumn;
cxGridDBColumn3: TcxGridDBColumn;
cxGridDBColumn4: TcxGridDBColumn;
cxGridDBColumn6: TcxGridDBColumn;
cxGridDBColumn7: TcxGridDBColumn;
cxGridDBColumn8: TcxGridDBColumn;
GridDBTableView1Column1: TcxGridDBColumn;
GridDBTableView1Column2: TcxGridDBColumn;
cxGridLevel1: TcxGridLevel;
btnRecibo: TBitBtn;
btnGPS: TBitBtn;
frxReport1: TfrxReport;
frxRichObject1: TfrxRichObject;
frxPDFExport1: TfrxPDFExport;
frxDesigner1: TfrxDesigner;
frxRecibo: TfrxDBDataset;
qryConfigOrgao: TSQLQuery;
qryConfigOrgaoID: TIntegerField;
qryConfigOrgaoRAZAO_SOCIAL: TStringField;
qryConfigOrgaoSIGLA: TStringField;
qryConfigOrgaoCNPJ: TStringField;
qryConfigOrgaoTIPO_ORGAO: TIntegerField;
qryConfigOrgaoENDER_LOGRAD: TStringField;
qryConfigOrgaoENDER_NUM: TStringField;
qryConfigOrgaoENDER_BAIRRO: TStringField;
qryConfigOrgaoENDER_CIDADE: TStringField;
qryConfigOrgaoENDER_CEP: TStringField;
qryConfigOrgaoENDER_UF: TStringField;
qryConfigOrgaoTELEFONE: TStringField;
qryConfigOrgaoNOME_DIR_DRH: TStringField;
qryConfigOrgaoCOD_CNAE: TIntegerField;
qryConfigOrgaoCOD_FPAS: TIntegerField;
qryConfigOrgaoCOD_NATUREZA_JURIDICA: TIntegerField;
qryConfigOrgaoCOD_MUNICIPIO_RAIS: TIntegerField;
qryConfigOrgaoCOD_MUNICIPIO_TCM: TIntegerField;
qryConfigOrgaoBRASAO: TBlobField;
qryConfigOrgaoLOGO_ADMIN: TBlobField;
qryConfigOrgaoVER_EXE: TStringField;
qryConfigOrgaoDT_VER_EXE: TDateField;
qryConfigOrgaoNOME_PASTA_ATUALIZA_EXE: TStringField;
qryConfigOrgaoTIPO_CONTRA_CHEQUE: TStringField;
qryConfigOrgaoDESCR_TIPO_ORGAO: TStringField;
sdsPagtoPrestServPIS_PASEP: TStringField;
sdsPagtoPrestServENDER_LOGRAD: TStringField;
sdsPagtoPrestServENDER_NUM: TStringField;
sdsPagtoPrestServENDER_BAIRRO: TStringField;
sdsPagtoPrestServENDER_CIDADE: TStringField;
sdsPagtoPrestServENDER_UF: TStringField;
cdsPagtoPrestServPIS_PASEP: TStringField;
cdsPagtoPrestServENDER_LOGRAD: TStringField;
cdsPagtoPrestServENDER_NUM: TStringField;
cdsPagtoPrestServENDER_BAIRRO: TStringField;
cdsPagtoPrestServENDER_CIDADE: TStringField;
cdsPagtoPrestServENDER_UF: TStringField;
mTbRecibo: TClientDataSet;
mTbReciboVAL_BRUTO: TStringField;
mTbReciboVAL_ISS: TStringField;
mTbReciboVAL_PREVID: TStringField;
mTbReciboVAL_IRRF: TStringField;
mTbReciboVAL_LIQUIDO: TStringField;
mTbReciboVAL_LIQ_EXTENSO: TStringField;
mTbReciboDESCR_TIPO_ORGAO: TStringField;
mTbReciboHISTORICO: TStringField;
mTbReciboFAVORECIDO: TStringField;
mTbReciboCPF_CNPJ: TStringField;
mTbReciboENDER_LOGRAD: TStringField;
mTbReciboENDER_CIDADE: TStringField;
mTbReciboDESCR_TIPO_ORGAO_TIT: TStringField;
mTbReciboNOME_ORGAO: TStringField;
mTbReciboCNPJ_ORGAO: TStringField;
mTbReciboDT_PAGTO_EXTENSO: TStringField;
mTbReciboENDER_ORGAO: TStringField;
frxConfigOrgao: TfrxDBDataset;
GridDBTableView1Column3: TcxGridDBColumn;
procedure FormShow(Sender: TObject);
procedure btnLimparClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Novo1Click(Sender: TObject);
procedure btnDelClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure edPesquisaPropertiesChange(Sender: TObject);
procedure GridDBTableView1ColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure rbRecbTodosClick(Sender: TObject);
procedure cdsPagtoPrestServAfterApplyUpdates(Sender: TObject;
var OwnerData: OleVariant);
procedure btnGPSClick(Sender: TObject);
procedure btnReciboClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
pv_sPathRel: widestring;
Procedure HabilitaBotoes(lHabilita1,lHabilita2: Boolean);
Procedure ExecutaFiltro;
public
{ Public declarations }
end;
var
frmLanctoPagtoPrestServico: TfrmLanctoPagtoPrestServico;
implementation
uses udmPrincipal, gsLib, UtilsDb, VarGlobais, AddEditLanctoPagtoPrestServico,
udmRelFinanceiros, ConverteNumEmExtenso;
{$R *.dfm}
procedure TfrmLanctoPagtoPrestServico.btnGPSClick(Sender: TObject);
begin
dmRelFinanceiros := TdmRelFinanceiros.Create(Nil);
dmRelFinanceiros.RelGPS2(cdsPagtoPrestServID.Value,True);
FreeAndNil(dmRelFinanceiros);
end;
procedure TfrmLanctoPagtoPrestServico.btnAddClick(Sender: TObject);
Var
iAddEdit: Integer;
begin
if TButton(Sender).Tag = 1 then
begin
iAddEdit := frmAddEditLanctoPagtoPrestServico.Executa(Self.Name,0,
StrToInt(Trim(frmeUnidOrcament1.edId.Text)),1,True);
end else
begin
if cdsPagtoPrestServ.RecordCount = 0 then exit;
iAddEdit := frmAddEditLanctoPagtoPrestServico.Executa(Self.Name,
cdsPagtoPrestServID.Value,0,1,False);
end;
if iAddEdit > 0 then
gsRefreshClient(cdsPagtoPrestServ,'ID',iAddEdit);
end;
procedure TfrmLanctoPagtoPrestServico.btnDelClick(Sender: TObject);
begin
if not Confirma('Deseja realmente EXCLUIR esse Pagamento ?') then exit;
ExcluiRegistro(cdsPagtoPrestServ);
end;
procedure TfrmLanctoPagtoPrestServico.btnLimparClick(Sender: TObject);
begin
cdsPagtoPrestServ.Close;
HabilitaBotoes(False,True);
frmeUnidOrcament1.edId.Text := '';
frmeUnidOrcament1.edId.SetFocus;
end;
procedure TfrmLanctoPagtoPrestServico.btnOkClick(Sender: TObject);
begin
//frmeUnidOrcament1.edIdExit(Nil);
cdsPagtoPrestServ.Close;
sdsPagtoPrestServ.ParamByName('pUnidOrcament').Value:= StrToInt(Trim(frmeUnidOrcament1.edId.Text));
sdsPagtoPrestServ.ParamByName('pAnoMes').Value := glb_sAnoMesTrab;
cdsPagtoPrestServ.Open;
ExecutaFiltro;
cdsPagtoPrestServ.IndexFieldNames:= GridDBTableView1.Columns[2].DataBinding.FieldName;
GridDBTableView1.Columns[2].SortOrder := soAscending;
//lblTitColPesquisa.Caption:= '&Pesquisar p/ '+GridDBTableView1.Columns[2].Caption+':';
HabilitaBotoes(True,False);
cdsPagtoPrestServ.First;
dbg1.SetFocus;
end;
procedure TfrmLanctoPagtoPrestServico.btnReciboClick(Sender: TObject);
begin
mTbRecibo.Edit;
mTbReciboVAL_BRUTO.Value := FormatCurr('0,0.00',
cdsPagtoPrestServVALOR_BRUTO.AsCurrency);
mTbReciboVAL_ISS.Value := FormatCurr('0,0.00',
cdsPagtoPrestServVALOR_ISS.AsCurrency);
mTbReciboVAL_PREVID.Value := FormatCurr('0,0.00',
cdsPagtoPrestServVALOR_PREVID.AsCurrency);
mTbReciboVAL_IRRF.Value := FormatCurr('0,0.00',
cdsPagtoPrestServVALOR_IRRF.AsCurrency);
mTbReciboVAL_LIQUIDO.Value := FormatCurr('0,0.00',
cdsPagtoPrestServVALOR_LIQUIDO.AsCurrency);
mTbReciboDESCR_TIPO_ORGAO.Value := qryConfigOrgaoDESCR_TIPO_ORGAO.Value;
mTbReciboVAL_LIQ_EXTENSO.Value := Trim(NumeroEmExtenso(
cdsPagtoPrestServVALOR_BRUTO.AsCurrency));
mTbReciboHISTORICO.Value := Trim(cdsPagtoPrestServHISTORICO.Value);
mTbReciboFAVORECIDO.Value:= cdsPagtoPrestServNOME_PREST_SERVICO.Value;
if cdsPagtoPrestServTIPO_PESSOA.Value = 'F' then
mTbReciboCPF_CNPJ.Value := FormatString('999.999.999-99',
cdsPagtoPrestServCPF_CNPJ.Value)
else
mTbReciboCPF_CNPJ.Value := FormatString('99.999.999/9999-99',
cdsPagtoPrestServCPF_CNPJ.Value);
mTbReciboENDER_LOGRAD.Value := cdsPagtoPrestServENDER_LOGRAD.Value+','+
cdsPagtoPrestServENDER_BAIRRO.Value;
mTbReciboENDER_CIDADE.Value := cdsPagtoPrestServENDER_CIDADE.Value+'-'+
cdsPagtoPrestServENDER_UF.Value;
if qryConfigOrgaoTIPO_ORGAO.Value = 1 then
mTbReciboDESCR_TIPO_ORGAO_TIT.Value := 'Poder Executivo Municipal'
else
if qryConfigOrgaoTIPO_ORGAO.Value = 2 then
mTbReciboDESCR_TIPO_ORGAO_TIT.Value := 'Secretaria Municipal'
else
if qryConfigOrgaoTIPO_ORGAO.Value = 3 then
mTbReciboDESCR_TIPO_ORGAO_TIT.Value := 'Poder Legislativo Municipal'
else
if qryConfigOrgaoTIPO_ORGAO.Value = 1 then
mTbReciboDESCR_TIPO_ORGAO_TIT.Value := 'Autarquia Municipal'
else
mTbReciboDESCR_TIPO_ORGAO_TIT.Value := ' ... nada ...';
mTbReciboNOME_ORGAO.Value := Criptografa(
qryConfigOrgaoRAZAO_SOCIAL.Value,'2',60);
mTbReciboCNPJ_ORGAO.Value := FormatString('99.999.999/9999-99',
Criptografa(qryConfigOrgaoCNPJ.Value,'2',14));
mTbReciboENDER_ORGAO.Value := qryConfigOrgaoENDER_LOGRAD.Value+','+
qryConfigOrgaoENDER_NUM.Value+' - '+
qryConfigOrgaoENDER_BAIRRO.Value+ ' - CEP: '+
FormatString('99.999-999',qryConfigOrgaoENDER_CEP.Value)+' - '+
qryConfigOrgaoENDER_CIDADE.Value +'-'+
qryConfigOrgaoENDER_UF.Value;
mTbReciboDT_PAGTO_EXTENSO.Value := qryConfigOrgaoENDER_CIDADE.Value+'-'+
qryConfigOrgaoENDER_UF.Value+', '+
DataExtenso(cdsPagtoPrestServDATA_PAGTO.AsString);
frxReport1.LoadFromFile(pv_sPathRel+'ReciboPagtoPrestServicos.fr3');
frxReport1.ShowReport();
end;
procedure TfrmLanctoPagtoPrestServico.cdsPagtoPrestServAfterApplyUpdates(
Sender: TObject; var OwnerData: OleVariant);
begin
dmPrincipal.GeraLog(cdsPagtoPrestServ,'3','PAGTO_PREST_SERVICO',Self.Name,'');
end;
procedure TfrmLanctoPagtoPrestServico.GridDBTableView1ColumnHeaderClick(
Sender: TcxGridTableView; AColumn: TcxGridColumn);
begin
lblTitColPesquisa.Enabled:= (GridDBTableView1.Columns[AColumn.Index].Tag = 1);
edPesquisa.Enabled := lblTitColPesquisa.Enabled;
cdsPagtoPrestServ.IndexFieldNames := GridDBTableView1.
Columns[AColumn.Index].DataBinding.FieldName
end;
procedure TfrmLanctoPagtoPrestServico.edPesquisaPropertiesChange(Sender: TObject);
begin
if cdsPagtoPrestServ.RecordCount = 0 then exit;
PesquisaIncremental(TcxTextEdit(Sender).Text,cdsPagtoPrestServ);
end;
procedure TfrmLanctoPagtoPrestServico.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
mTbRecibo.Close;
qryConfigOrgao.Close;
end;
procedure TfrmLanctoPagtoPrestServico.FormCreate(Sender: TObject);
begin
inherited;
Position := poDesigned;
Top := 70;
Left := 11;
Application.ProcessMessages;
qryConfigOrgao.Open;
mTbRecibo.CreateDataSet;
mTbRecibo.Open;
frmAddEditLanctoPagtoPrestServico := TfrmAddEditLanctoPagtoPrestServico.
Create(Self);
end;
procedure TfrmLanctoPagtoPrestServico.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(frmAddEditLanctoPagtoPrestServico);
end;
procedure TfrmLanctoPagtoPrestServico.FormShow(Sender: TObject);
begin
inherited;
Caption := 'LANÇAMENTOS DE PAGAMENTOS À PRESTADORES DE SERVIÇOS ...';
HabilitaBotoes(False,True);
frmeUnidOrcament1.edId.SetFocus;
pv_sPathRel := GetPathRel();
end;
Procedure TfrmLanctoPagtoPrestServico.HabilitaBotoes(lHabilita1,lHabilita2: Boolean);
begin
btnAdd.Enabled := lHabilita1;
btnEdit.Enabled:= lHabilita1;
btnDel.Enabled := lHabilita1;
btnLimpar.Enabled := lHabilita1;
frmeUnidOrcament1.edId.Enabled := lHabilita2;
frmeUnidOrcament1.sbUnidOrcament.Enabled:= lHabilita2;
btnOk.Enabled := lHabilita2;
end;
procedure TfrmLanctoPagtoPrestServico.Novo1Click(Sender: TObject);
begin
if TMenuItem(Sender).Tag = 1 then
btnAdd.Click
else
btnEdit.Click;
end;
procedure TfrmLanctoPagtoPrestServico.rbRecbTodosClick(Sender: TObject);
begin
ExecutaFiltro;
end;
procedure TfrmLanctoPagtoPrestServico.ExecutaFiltro;
begin
cdsPagtoPrestServ.DisableControls;
if rbRecbTodos.Checked then
cdsPagtoPrestServ.Filtered := False
else
begin
if rbRecbIndiv.Checked then
cdsPagtoPrestServ.Filter := 'RECIBO_INDIVIDUAL = '+QuotedStr('S')
else
cdsPagtoPrestServ.Filter := 'RECIBO_INDIVIDUAL = '+QuotedStr('N');
cdsPagtoPrestServ.Filtered := True;
end;
cdsPagtoPrestServ.EnableControls;
end;
end.
|
{
Version 12
Copyright (c) 2011-2012 by Bernd Gabriel
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.
Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS
are covered by separate copyright notices located in those modules.
}
{$I htmlcons.inc}
unit HtmlViewer;
interface
uses
Windows, Graphics, Messages, SysUtils, Classes, Controls, ExtCtrls,
//
HtmlBoxes,
HtmlDocument,
HtmlElements,
HtmlImages,
HtmlRenderer,
StyleTypes;
type
//------------------------------------------------------------------------------
// TCustomHtmlViewer is base class for THtmlViewer 12
//------------------------------------------------------------------------------
// It is the hood of both framed and single HTML document visualizations.
//------------------------------------------------------------------------------
THtmlViewerOptions = set of (
voOwnsDocument
);
THtmlViewerState = set of (
vsDocumentChanged,
vsViewChanged
);
TCustomHtmlViewer = class(TWinControl)
private
FState: THtmlViewerState;
FOptions: THtmlViewerOptions;
FDocument: THtmlDocument;
FControlMap: THtmlControlOfElementMap; // remember the controls per element
FImageCache: ThtImageCache;
FView: THtmlBox; // the hook for the boxes to show.
FScale: Double;
procedure SetDocument(const Value: THtmlDocument);
procedure SetViewerOptions(const Value: THtmlViewerOptions);
procedure SetViewerState(const Value: THtmlViewerState);
procedure SetScale(const Value: Double);
protected
procedure UpdateDocument;
procedure UpdateView;
procedure Resize; override;
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
procedure AddView(const Value: THtmlBox);
procedure ClearView;
property HtmlDocument: THtmlDocument read FDocument write SetDocument;
property HtmlView: THtmlBox read FView;
property Scale: Double read FScale write SetScale;
property ViewerOptions: THtmlViewerOptions read FOptions write SetViewerOptions;
property ViewerState: THtmlViewerState read FState write SetViewerState;
end;
THtmlViewer12 = class(TCustomHtmlViewer)
published
property Align;
property Anchors;
property BiDiMode;
property Color;
property Constraints;
property Ctl3D;
property DoubleBuffered;
property Enabled;
property Font;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property ViewerOptions;
property Visible;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('HtmlViewer', [THtmlViewer12]);
end;
{ TCustomHtmlViewer }
//-- BG ---------------------------------------------------------- 05.04.2011 --
procedure TCustomHtmlViewer.AddView(const Value: THtmlBox);
begin
FView.Children.Add(Value);
Include(FState, vsViewChanged);
Invalidate;
end;
//-- BG ---------------------------------------------------------- 25.04.2011 --
procedure TCustomHtmlViewer.AfterConstruction;
begin
inherited;
FControlMap := THtmlControlOfElementMap.Create;
FImageCache := ThtImageCache.Create;
FView := THtmlBox.Create;
end;
//-- BG ---------------------------------------------------------- 25.04.2011 --
procedure TCustomHtmlViewer.BeforeDestruction;
begin
SetDocument(nil);
FView.Free;
FControlMap.Free;
FImageCache.Free;
inherited;
end;
//-- BG ---------------------------------------------------------- 25.04.2011 --
procedure TCustomHtmlViewer.ClearView;
begin
FView.Children.Clear;
end;
//-- BG ---------------------------------------------------------- 04.04.2011 --
procedure TCustomHtmlViewer.Resize;
begin
inherited;
Include(FState, vsDocumentChanged);
UpdateDocument;
end;
//-- BG ---------------------------------------------------------- 04.04.2011 --
procedure TCustomHtmlViewer.SetDocument(const Value: THtmlDocument);
begin
if FDocument <> Value then
begin
if FDocument <> nil then
if voOwnsDocument in FOptions then
FDocument.Free;
FControlMap.Clear;
FDocument := Value;
Include(FState, vsDocumentChanged);
UpdateDocument;
UpdateView;
Invalidate;
end;
end;
//-- BG ---------------------------------------------------------- 25.04.2011 --
procedure TCustomHtmlViewer.SetScale(const Value: Double);
begin
if FScale <> Value then
begin
FScale := Value;
FView.Rescaled(Value);
Invalidate;
end;
end;
//-- BG ---------------------------------------------------------- 04.04.2011 --
procedure TCustomHtmlViewer.SetViewerOptions(const Value: THtmlViewerOptions);
begin
if FOptions <> Value then
begin
FOptions := Value;
Include(FState, vsViewChanged);
Invalidate;
end;
end;
//-- BG ---------------------------------------------------------- 04.04.2011 --
procedure TCustomHtmlViewer.SetViewerState(const Value: THtmlViewerState);
begin
if FState <> Value then
begin
FState := Value;
Invalidate;
end;
end;
//-- BG ---------------------------------------------------------- 04.04.2011 --
procedure TCustomHtmlViewer.UpdateDocument;
// Rebuild internal representation after document/structure or client rect has changed.
var
Renderer: THtmlVisualRenderer;
begin
if vsDocumentChanged in FState then
try
FView.Children.Clear;
if FDocument <> nil then
begin //TODO -1 -oBG, 02.05.2011: Defaultfont parameter
FView.BoundsRect := ClientRect;
// setting bounds rect may have called Resize and thus has updated the document already.
if vsDocumentChanged in FState then
begin
Renderer := THtmlVisualRenderer.Create(FDocument, FControlMap, FImageCache, mtScreen, nil, ClientWidth, ClientHeight);
try
Renderer.MediaCapabilities := [mcFrames];
Renderer.RenderDocument(Self, FView);
finally
Include(FState, vsViewChanged);
Renderer.Free;
end;
end;
end;
finally
Exclude(FState, vsDocumentChanged);
end;
end;
//-- BG ---------------------------------------------------------- 04.04.2011 --
procedure TCustomHtmlViewer.UpdateView;
// Update internal representation after visually relevant parameters have changed.
begin
if vsViewChanged in FState then
begin
Exclude(FState, vsViewChanged);
//TODO -1 -oBG, 04.04.2011: update display structure after any visually relevant changes except document changes.
end;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
procedure TCustomHtmlViewer.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
if FView.Children.IsEmpty then
// fill background as long as there is no box to show.
inherited
else
// avoid flickering, if there is a box.
Message.Result := 1;
end;
end.
|
unit Ex2Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TMyLongThread = class(TThread)
private
procedure DoUsefullTask; // Процедура для имитации полезной работы
public
procedure Execute; override;
end;
TForm1 = class(TForm)
btnRunParallelThread: TButton;
procedure btnRunParallelThreadClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
MyThread: TMyLongThread;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnRunParallelThreadClick(Sender: TObject);
begin
// Запускает параллельный поток
if MyThread = nil then
MyThread := TMyLongThread.Create(False)
else
raise Exception.Create('Дополнительный поток уже запущен!');
end;
{ TMyLongThread }
procedure TMyLongThread.DoUsefullTask;
begin
// Реальный поток может выполнять какую угодно полезную работу
// В учебных целях делаем паузу 5 секунд для имитации задержки, которая
// может возникнуть при выполнении полезной работы
Sleep(5000);
end;
procedure TMyLongThread.Execute;
procedure WaitTimeout(ATimeOut: Integer);
begin
Sleep(ATimeOut);
end;
begin
while not Terminated do
begin
DoUsefullTask;
WaitTimeout(10000); // Ожидаем таймаут 10 сек.
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
// При закрытии программы необходимо завершить работу потока
// и уничтожить объект потока MyThread
if MyThread <> nil then
MyThread.Free;
end;
end.
|
unit k03_kel3_md5;
{Hashing dengan metode MD5}
{REFERENSI : https://en.wikipedia.org/wiki/MD5#Algorithm
https://tr.opensuse.org/MD5
https://rosettacode.org/wiki/MD5/Implementation
.. dan masih banyak lagi}
{!! DISCLAIMER : saya hanya mengikuti pseudocode yang ada di wikipedia !!
!! dengan bantuan google dan stackoverflow, bukan berarti !!
!! saya paham masing-masing barisnya !!}
interface
{PUBLIC VARIABLE, CONST, ADT}
uses
k03_kel3_utils;
{PUBLIC FUNCTION, PROCEDURE}
function hashMD5(str: string): string;
implementation
function leftrotate(x, c: Cardinal): Cardinal;
{DESKRIPSI : merotasi 32 bit yang merepresentasikan 1 chunk string}
{PARAMETER : integer (cardinal) yang ingin dirotate dan seberapa banyak (jumlah bit nya)}
{RETURN : integer (cardinal) yang sudah dirotate}
begin
leftrotate := (x shl c) or (x shr (32-c));
end;
{$asmmode intel}
function Swap32(ALong: Cardinal): Cardinal; Assembler;
{DESKRIPSI : menukar isi memori 32 bit}
{PARAMETER : 32 bit unsigned integer (Cardinal)}
{RETURN : assembler untuk menukar 2 cardinal}
asm
BSWAP eax
end;
function hashMD5(str: string): string;
{DESKRIPSI : melakukan hashing pada string, terutama password}
{PARAMETER : string yang ingin dihash}
{RETURN : string hasil hash}
{!! DISCLAIMER : PSEUDOCODE ADA DI WIKIPEDIA !!}
{KAMUS LOKAL}
const
{s : jumlah shift tiap 'round'}
s: array[0..63] of Cardinal = (
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 );
{K[i] : floor(2^32 × abs(sin(i + 1)))}
K: array[0..63] of Cardinal = (
$d76aa478, $e8c7b756, $242070db, $c1bdceee,
$f57c0faf, $4787c62a, $a8304613, $fd469501,
$698098d8, $8b44f7af, $ffff5bb1, $895cd7be,
$6b901122, $fd987193, $a679438e, $49b40821,
$f61e2562, $c040b340, $265e5a51, $e9b6c7aa,
$d62f105d, $02441453, $d8a1e681, $e7d3fbc8,
$21e1cde6, $c33707d6, $f4d50d87, $455a14ed,
$a9e3e905, $fcefa3f8, $676f02d9, $8d2a4c8a,
$fffa3942, $8771f681, $6d9d6122, $fde5380c,
$a4beea44, $4bdecfa9, $f6bb4b60, $bebfbc70,
$289b7ec6, $eaa127fa, $d4ef3085, $04881d05,
$d9d4d039, $e6db99e5, $1fa27cf8, $c4ac5665,
$f4292244, $432aff97, $ab9423a7, $fc93a039,
$655b59c3, $8f0ccc92, $ffeff47d, $85845dd1,
$6fa87e4f, $fe2ce6e0, $a3014314, $4e0811a1,
$f7537e82, $bd3af235, $2ad7d2bb, $eb86d391 );
var
a0, b0, c0, d0 : Cardinal; {4 chunk 32bit yang akan diubah jadi hexadecimal}
a, b, c, d : Cardinal;
f, g, dTemp : Cardinal;
len, i : integer;
msg : array[0..63] of Char;
{array M menyimpan 16 32-bit unsigned integer yang merepresentasikan string tsb}
M : array[0..15] of Cardinal absolute msg;
{ALGORITMA}
begin
{INISIASI}
a0 := $67452301;
b0 := $efcdab89;
c0 := $98badcfe;
d0 := $10325476;
len := length(Str);
fillChar(msg, 64, 0);
for i:=1 to len do begin
msg[i-1] := Str[i];
end;
//append "1" bit to message
msg[len] := chr(128);
//append original length in bits mod (2 pow 64) to message
msg[63-7] := chr(8*Len);
//Process each 512-bit chunk of message- 1 only have 1 chunk
//Initialize hash value for this chunk:
A := a0;
B := b0;
C := c0;
D := d0;
//Main loop:
{!! DISCLAIMER : PSEUDOCODE ADA DI WIKIPEDIA !!}
for i := 0 to 63 do begin
if (i >= 0) and (i <= 15) then begin
F := (B and C) or ((not B) and D);
g := i;
end else if (i >= 16) and (i <= 31) then begin
F := (D and B) or ((not D) and C);
g := (5*i + 1) mod 16;
end else if (i >= 32) and (i <= 47) then begin
F := B xor C xor D;
g := (3*i + 5) mod 16;
end else if (i >= 48) and (i <= 63) then begin
F := C xor (B or (not D));
g := (7*i) mod 16;
end;
dTemp := D;
D := C;
C := B;
B := B + leftrotate((A + F + K[i] + M[g]), s[i]);
A := dTemp;
end;
a0 := Swap32(a0 + A);
b0 := Swap32(b0 + B);
c0 := Swap32(c0 + C);
d0 := Swap32(d0 + D);
hashMD5 := (IntToHex(a0) + IntToHex(b0) + IntToHex(c0) + IntToHex(d0));
end;
end. |
unit main1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ExtCtrls, JvCreateProcess, windows, lazUTF8, SynEdit;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
JvCreateProcess1: TJvCreateProcess;
Memo1: TMemo;
Panel1: TPanel;
SynEdit1: TSynEdit;
procedure Button1Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure JvCreateProcess1Read(Sender: TObject; const S: string;
const StartsOnNewLine: Boolean);
procedure JvCreateProcess1Terminate(Sender: TObject; ExitCode: DWORD);
//procedure JvCreateProcess1Terminate(Sender: TObject; ExitCode: DWORD);
private
procedure ChangeLastLine(const S: string);
function FormatForDisplay(const S: string): string;
//procedure JvCreateProcess1Read(Sender: TObject; const S: string;const StartsOnNewLine: Boolean);
public
procedure AddNewLine(const S: string);
procedure ClearScreen;
procedure InitCommand(cmd:string);
end;
const
PREFIX='D:\lazarus3\stuff\Arduino\';
AVR_CPP=PREFIX+'hardware\tools\avr\bin\avr-c++.exe';
AVR_GCC=PREFIX+'hardware\tools\avr\bin\avr-gcc.exe';
var
Form1: TForm1;
implementation
uses
JclSysInfo, JclStrings, JvDSADialogs;
{$R *.lfm}
resourcestring
sProcessTerminated = 'Process "%s" terminated, ExitCode: %.8x';
procedure Tform1.InitCommand(cmd:string);
var CommandLine:string;
begin
{ Retrieve the command processor name }
if not JclSysInfo.GetEnvironmentVar('COMSPEC', CommandLine) or (Length(CommandLine) = 0) then
{ Paranoid }
CommandLine := 'COMMAND.EXE';
//CommandLine:=cmd;
JvCreateProcess1.CommandLine := CommandLine;
{ Redirect console output, we'll receive the output via the OnRead event }
JvCreateProcess1.ConsoleOptions := JvCreateProcess1.ConsoleOptions + [coRedirect];
{ Hide the console window }
JvCreateProcess1.StartupInfo.ShowWindow := swHide;
JvCreateProcess1.StartupInfo.DefaultWindowState := False;
{ And start the console }
JvCreateProcess1.Run;
end;
function Tform1.FormatForDisplay(const S: string): string;
begin
Result := StrReplaceChar(S, #255, ' ');
end;
procedure Tform1.ClearScreen;
begin
memo1.Clear;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
self.JvCreateProcess1.WriteLn(ansistring('makeCore.bat'));
end;
procedure TForm1.FormActivate(Sender: TObject);
begin
self.InitCommand('INIT');
self.SynEdit1.Lines.LoadFromFile(getCurrentDir()+'/ino/default.ino');
end;
procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
self.JvCreateProcess1.WriteLn(ansistring('exit'));
end;
procedure TForm1.JvCreateProcess1Read(Sender: TObject; const S: string;
const StartsOnNewLine: Boolean);
begin
// $0C is the Form Feed char.
if S = #$C then
ClearScreen
else
if StartsOnNewLine then
AddNewLine(S)
else
ChangeLastLine(S);
end;
procedure TForm1.JvCreateProcess1Terminate(Sender: TObject; ExitCode: DWORD);
begin
AddNewLine(Format(sProcessTerminated, [JvCreateProcess1.CommandLine, ExitCode]));
end;
procedure Tform1.ChangeLastLine(const S: string);
begin
with memo1 do
begin
if lines.Count > 0 then
Lines[lines.Count - 1] := FormatForDisplay(S)
else
AddNewLine(S);
//ItemIndex := Count - 1;
end;
end;
procedure Tform1.AddNewLine(const S: string);
begin
with memo1 as Tmemo do
begin
Lines.Add(FormatForDisplay(S));
//ItemIndex := Count - 1;
end;
end;
end.
|
unit fGMV_EnteredInError;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 1 $ $Modtime: 8/11/09 3:56p $
* Developer: ddomain.user@domain.ext/doma.user@domain.ext
* Site: Hines OIFO
*
* Description: Utility for marking vitals in error.
*
* Notes:
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSDATAENTRY/fGMV_EnteredInError.pas $
*
* $History: fGMV_EnteredInError.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:38p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/14/07 Time: 10:29a
* Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:43p
* Created in $/Vitals/VITALS-5-0-18/VitalsDataEntry
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:33p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsDataEntry
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 3:35p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, No CCOW) - Delphi 6/VitalsDataEntry
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 4/16/04 Time: 4:20p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/26/04 Time: 1:08p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, Delphi7)/V5031-D7/VitalsUser
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 10/29/03 Time: 4:15p
* Created in $/Vitals503/Vitals User
* Version 5.0.3
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 5/22/03 Time: 10:16a
* Updated in $/Vitals GUI Version 5.0/VitalsUserNoCCOW
* Preparation to CCOW
* MessageDLG changed to MessageDLGS
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 5/21/03 Time: 1:46p
* Updated in $/Vitals GUI Version 5.0/VitalsUserNoCCOW
* Version 5.0.1.5
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/21/03 Time: 1:18p
* Created in $/Vitals GUI Version 5.0/VitalsUserNoCCOW
* Pre CCOW Version of Vitals User
*
* ***************** Version 5 *****************
* User: Zzzzzzandria Date: 12/20/02 Time: 3:02p
* Updated in $/Vitals GUI Version 5.0/Vitals User
*
* ***************** Version 4 *****************
* User: Zzzzzzandria Date: 10/11/02 Time: 6:21p
* Updated in $/Vitals GUI Version 5.0/Vitals User
* Version vT32_1
*
* ***************** Version 3 *****************
* User: Zzzzzzpetitd Date: 6/20/02 Time: 9:33a
* Updated in $/Vitals GUI Version 5.0/Vitals User
* t27 Build
*
* ***************** Version 2 *****************
* User: Zzzzzzpetitd Date: 6/06/02 Time: 11:14a
* Updated in $/Vitals GUI Version 5.0/Vitals User
* Roll-up to 5.0.0.27
*
* ***************** Version 1 *****************
* User: Zzzzzzpetitd Date: 4/04/02 Time: 11:58a
* Created in $/Vitals GUI Version 5.0/Vitals User
*
*
================================================================================
}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
ExtCtrls,
StdCtrls,
Buttons,
CheckLst,
MFunStr,
uGMV_Common,
ComCtrls;
type
TfrmGMV_EnteredInError = class(TForm)
GroupBox1: TGroupBox;
rgReason: TRadioGroup;
dtpDate: TDateTimePicker;
pnlButtons: TPanel;
btnCancel: TButton;
btnOK: TButton;
lvVitals: TListView;
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
procedure DateChange(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OkToProceed(Sender: TObject);
procedure ClearList;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lvVitalsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure FormResize(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lvVitalsCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
procedure FormDestroy(Sender: TObject);
private
FPatientIEN: string;
{ Private declarations }
public
{ Public declarations }
end;
function EnterVitalsInError(DFN: string): Integer;
function EnteredInErrorByDate(DFN: string;aDate:TDateTime): Integer;
implementation
uses uGMV_FileEntry, uGMV_User, uGMV_Engine, fGMV_PtInfo, system.UITypes
;
const
kwVitals = 'Vitals';
kwCliO = 'CliO';
{$R *.DFM}
function EnterVitalsInError(DFN: string): Integer;
var
TimeToStart: TDateTime;
begin
TimeToStart := getServerWDateTime;
TimeToStart := Trunc(TimeToStart)+1 - 1/(3600*24);
Result := EnteredInErrorByDate(DFN,TimeToStart);
end;
function EnteredInErrorByDate(DFN: string;aDate:TDateTime): Integer;
begin
with TfrmGMV_EnteredInError.Create(Application) do
try
FPatientIEN := DFN;
dtpDate.Date := aDate;
if dtpDate.Date = 0 then
dtpDate.Date := Now;
DateChange(nil);
Result := ShowModal;
finally
free;
end;
end;
procedure TfrmGMV_EnteredInError.FormCreate(Sender: TObject);
begin
ClearList;
dtpDate.Date := getServerWDateTime;
if dtpDate.Date = 0 then
begin
dtpDate.Date := Now;
end;
end;
procedure TfrmGMV_EnteredInError.FormDestroy(Sender: TObject);
begin
ClearList;
end;
procedure TfrmGMV_EnteredInError.DateChange(Sender: TObject);
var
sSource,
s: String;
dt: Double;
i: integer;
RetList : TStrings;
function DataSource(aValue:String):String;
begin
Result := kwVitals;
if pos('{',trim(aValue)) = 1 then
Result := kwClio;
end;
begin
ClearList;
dt := WindowsDateToFMDate(dtpDate.Date);
RetList := getGMVRecord(FPatientIEN + '^' + FloatToStr(dt) + '^^' + FloatToStr(dt));
if (RetList.Count > 0) and (Piece(RetList[0], '^', 1) <> '0') then
for i := 0 to RetList.Count - 1 do
if Copy(RetList[i], 1, 1) <> ' ' then
with lvVitals.Items.Add do
begin
s := RetList[i];
Caption := Piece(Piece(RetList[i], '^', 2), ' ', 1);
sSource := DataSource(s);
s := trim(Copy(RetList[i], Pos(' ', RetList[i]), 255));
SubItems.Add(piece(s,'_',1));
SubItems.Add(piece(s,'_',2));
SubItems.Add(sSource);
Data := TGMV_FileEntry.CreateFromRPC('120.51;' + RetList[i]);
end;
RetList.Free;
lvVitals.Invalidate;
end;
procedure TfrmGMV_EnteredInError.ClearList;
begin
lvVitals.Items.BeginUpdate;
while lvVitals.Items.Count > 0 do
begin
if lvVitals.Items[0].Data <> nil then
TGMV_FileEntry(lvVitals.Items[0].Data).Free;
lvVitals.Items.Delete(0);
end;
lvVitals.Items.EndUpdate;
btnOK.Enabled := False;
rgReason.Enabled := False;
rgReason.ItemIndex := -1;
end;
procedure TfrmGMV_EnteredInError.OkButtonClick(Sender: TObject);
var
i: integer;
sReason,
sVitals,sClio,
sDUZ,
s: String;
RetList:TStrings;
iVitals,iExternal:Integer;
function WarningString(aClio:Integer):String;
begin
Result := 'Are you sure you want to mark ' +
IntToStr(iVitals)+' vitals sign records as ' + sReason+'?';
if aClio <> 0 then
Result := Result +#13#13+
'NOTE: some of the selected records are stored outside of the Vitals package'+#13+
'and could not be marked as "Entered in Error" by the Vitals application';
end;
begin
if rgReason.ItemIndex < 0 then
MessageDlg('No reason has been selected.', mtError, [mbok], 0)
else
begin
s := '';
sVitals := '';
sCliO := '';
iVitals := 0;
iExternal := 0;
sReason := rgReason.Items[rgReason.ItemIndex];
for i := 0 to lvVitals.Items.Count - 1 do
if lvVitals.Items[i].Selected then
begin
s := s + lvVitals.Items[i].Caption +' ' + lvVitals.Items[i].SubItems[0] + #13;
if lvVitals.Items[i].SubItems[2] = kwVitals then
begin
sVitals := sVitals + lvVitals.Items[i].Caption +' ' + lvVitals.Items[i].SubItems[0] + #13;
inc(iVitals);
end
else
begin
sCliO := sCliO + lvVitals.Items[i].Caption +' ' + lvVitals.Items[i].SubItems[0] + #13;
inc(iExternal);
end;
end;
// if MessageDlg('Are you sure you want to mark '+IntToStr(j)+' vitals sign records as '
// + sReason+'?', mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
// Exit;
if iVitals = 0 then
begin
MessageDlg('Selected records are not stored in the Vitals package.'+#13+
'Please use the Flowsheets application to update them.', mtInformation, [mbOk], 0);
exit;
end;
if MessageDlg(WarningString(iExternal), mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
Exit;
sDUZ := getUserDUZString;
for i := 0 to lvVitals.Items.Count - 1 do
if lvVitals.Items[i].Selected and (lvVitals.Items[i].SubItems[2] = kwVitals)
then
with TGMV_FileEntry(lvVitals.Items[i].Data) do
begin
RetList := setGMVErrorRecord(IEN + '^' + sDUZ + '^' + IntToStr(rgReason.ItemIndex + 1));
RetList.Free;
end;
// MessageDlg('Vitals:'+#13#10#13#10+s+#13#10#13#10+'marked as ' + rgReason.Items[rgReason.ItemIndex],mtInformation,[mbOk],0);
// ShowInfo('Entered In Error Result','Vitals:'+#13#10#13#10+s+#13#10#13#10+'marked as ' + rgReason.Items[rgReason.ItemIndex]);
ModalResult := mrOK;
end;
end;
procedure TfrmGMV_EnteredInError.OkToProceed(Sender: TObject);
begin
btnOK.Enabled := (rgReason.ItemIndex > -1)
and (lvVitals.SelCount > 0) and (rgReason.ItemIndex >= 0);
end;
procedure TfrmGMV_EnteredInError.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ClearList;
end;
procedure TfrmGMV_EnteredInError.lvVitalsChange(Sender: TObject;
Item: TListItem; Change: TItemChange);
begin
rgReason.Enabled := (lvVitals.ItemFocused <> nil) or (lvVitals.SelCount > 0);
end;
procedure TfrmGMV_EnteredInError.FormResize(Sender: TObject);
var
i,iLen:Integer;
begin
// lvVitals.Columns[1].Width := lvVitals.Width - lvVitals.Columns[0].Width - lvVitals.Columns[2].Width- 4;
iLen := lvVitals.Width - 20;
for i := 0 to lvVitals.Columns.Count - 1 do
if i <> 1 then
iLen := iLen - lvVitals.Columns[i].Width;
lvVitals.Columns[1].Width := iLen;
end;
procedure TfrmGMV_EnteredInError.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
ModalResult := mrCancel;
end;
procedure TfrmGMV_EnteredInError.lvVitalsCustomDrawItem(
Sender: TCustomListView; Item: TListItem; State: TCustomDrawState;
var DefaultDraw: Boolean);
begin
if Item.SubItems.Count >= 2 then begin
if Item.SubItems[2] = kwClio then
lvVitals.Canvas.Font.Color := clGray
else
lvVitals.Canvas.Font.Color := clWindowText;
end;
end;
end.
|
unit gMouseGesture;
{
Mouse Gesture Component for Delphi
written by Wolfy(http://hp.vector.co.jp/authors/VA024591/)
license BSD
modified 2002/10/12
thanks to OpenJane, i had written.
}
{$IFDEF VER130}
{$ELSE}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN UNIT_PLATFORM OFF}
{$ENDIF}
interface
uses
Windows, Messages, SysUtils, Classes,forms,controls;
type
TMouseGestureType = (mgUp,mgDown,mgLeft,mgRight,
mgLeftClick,mgWheelClick,mgWheelUp,mgWheelDown,
mgSide1,mgSide2,mgSide1R,mgSide2R);
TMouseGestureArray = array of TMouseGestureType;
TMouseGestureExecuteEvent = procedure(Sender: TObject; Gestures: TMouseGestureArray) of object;
TMouseGestureNotifyEvent = procedure(Sender: TObject; Gesture: TMouseGestureType) of object;
TAppMessageHook = class(TComponent)
private
FOldMessageEvent: TMessageEvent;
protected
procedure DoMessage(var Msg: TMsg; var Handled: Boolean); virtual;
procedure Loaded; override;
public
destructor Destroy; override;
end;
TgMouseGesture = class(TAppMessageHook)
private
FPrevPoint: TPoint;
FClickGestureStandby: Boolean;
FMargin: Integer;
FTempMoveGestures: TMouseGestureArray;
FEnabled: Boolean;
FTempControl: TWinControl;
FTempWndMethod: TWndMethod;
FRightClickSelect: Boolean;
FOnMouseGestureExecute: TMouseGestureExecuteEvent;
FOnMouseGestureNotify: TMouseGestureNotifyEvent;
FOnMouseGestureNotifyMove: TMouseGestureExecuteEvent;
protected
procedure DoMessage(var Msg: TMsg; var Handled: Boolean); override;
procedure DoMouseGesture(var Msg: TMsg; var Handled: Boolean); virtual;
procedure MoveGesture(pt: TPoint);
procedure GestureExecute(Gestures: TMouseGestureArray);
function AddGesture(Gesture: TMouseGestureType; Ary: TMouseGestureArray = nil): TMouseGestureArray;
procedure SubClassMessageHook(var Message: TMessage); virtual;
procedure ResetSubClass;
procedure SetSubClass(Handle: HWND);
procedure Notification(AComponent: TComponent; Operation: TOperation);override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
//マウス移動を認識する距離
property Margin: Integer read FMargin write FMargin;
//有効/無効
property Enabled: Boolean read FEnabled write FEnabled;
//ListView,TreeViewでの右クリック選択を有効
property RightClickSelect: Boolean read FRightClickSelect write FRightClickSelect;
property OnMouseGestureExecute: TMouseGestureExecuteEvent read FOnMouseGestureExecute write FOnMouseGestureExecute;
property OnMouseGestureNotify: TMouseGestureNotifyEvent read FOnMouseGestureNotify write FOnMouseGestureNotify;
property OnMouseGestureNotifyMove: TMouseGestureExecuteEvent read FOnMouseGestureNotifyMove write FOnMouseGestureNotifyMove;
end;
function MouseGestureToString(Gesture: TMouseGestureType): String;
function MouseGestureArrayToString(Gestures: TMouseGestureArray): String;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Main1', [TgMouseGesture]);
end;
const
CRLF = sLineBreak;
WM_CONTROLRECREATED = WM_USER + 020103;
WM_XBUTTONDOWN = $020B;
WM_XBUTTONUP = $020C;
WM_XBUTTONDBLCLK = $020D;
MK_XBUTTON1 = $0001;
MK_XBUTTON2 = $0002;
function MouseGestureToString(Gesture: TMouseGestureType): String;
begin
case Gesture of
mgUp: Result := '↑';
mgDown: Result := '↓';
mgLeft: Result := '←';
mgRight: Result := '→';
mgLeftClick: Result := 'LeftClick';
mgWheelClick: Result := 'WheelClick';
mgWheelUp: Result := 'WheelUp';
mgWheelDown: Result := 'WheelDown';
mgSide1: Result := 'Side1';
mgSide2: Result := 'Side2';
mgSide1R: Result := 'Side1R';
mgSide2R: Result := 'Sede2R';
end;
end;
function MouseGestureArrayToString(Gestures: TMouseGestureArray): String;
var
i: Integer;
g: TMouseGestureType;
begin
for i := 0 to Length(Gestures) - 1 do
begin
g := Gestures[i];
case g of
mgUp,mgDown,mgLeft,mgRight:
Result := Result + MouseGestureToString(g);
else
if Result = '' then
Result := MouseGestureToString(g)
else
Result := Result + CRLF + MouseGestureToString(g);
end;
end;
end;
{ TAppMessageHook }
destructor TAppMessageHook.Destroy;
//破棄
begin
//終わり
if Assigned(FOldMessageEvent) then
Application.OnMessage := FOldMessageEvent;
FOldMessageEvent := nil;
inherited;
end;
procedure TAppMessageHook.DoMessage(var Msg: TMsg; var Handled: Boolean);
//本来のメソッドを実行
begin
if Assigned(FOldMessageEvent) then
FOldMessageEvent(Msg,Handled);
end;
procedure TAppMessageHook.Loaded;
//開始前準備
begin
inherited;
//イベントを入れ替え
FOldMessageEvent := Application.OnMessage;
Application.OnMessage := DoMessage;
end;
{ TgMouseGesture }
function TgMouseGesture.AddGesture(
Gesture: TMouseGestureType; Ary: TMouseGestureArray): TMouseGestureArray;
//ジェスチャーを加える
begin
Result := Ary;
if Length(Result) = 0 then
begin
//作成する
SetLength(Result,1);
Result[0] := Gesture;
end
else begin
//追加する
if Result[High(Result)] <> Gesture then
begin
SetLength(Result,Length(Result) + 1);
Result[High(Result)] := Gesture;
end;
end;
end;
constructor TgMouseGesture.Create(AOwner: TComponent);
begin
inherited;
FMargin := 5;
FEnabled := True;
FRightClickSelect := False;
end;
destructor TgMouseGesture.Destroy;
begin
ResetSubClass;
inherited;
end;
procedure TgMouseGesture.DoMessage(var Msg: TMsg; var Handled: Boolean);
begin
if FEnabled then
DoMouseGesture(Msg,Handled);
inherited;
end;
procedure TgMouseGesture.DoMouseGesture(var Msg: TMsg;
var Handled: Boolean);
//マウスジェスチャー
begin
case Msg.message of
WM_RBUTTONDOWN: //開始
begin
FTempMoveGestures := nil;
FPrevPoint := Msg.pt;
//右クリック選択を有効にする
if FRightClickSelect then
begin
Handled := False;
//サブクラス
SetSubClass(Msg.hwnd);
end
else
Handled := True;
end;
WM_RBUTTONUP: //実行
begin
if (Length(FTempMoveGestures) > 0) and (Msg.wParam = 0) then
begin
GestureExecute(FTempMoveGestures);
Handled := True;
end
else
Handled := False;
FClickGestureStandby := False;
//リセット
ResetSubClass;
end;
WM_MOUSEMOVE: //ジェスチャーをチェック
if Msg.wParam = MK_RBUTTON then
begin
MoveGesture(Msg.pt);
Handled := True;
end;
WM_LBUTTONUP: //左ボタン
if FClickGestureStandby then
begin
FClickGestureStandby := False;
Handled := True;
GestureExecute(AddGesture(mgLeftClick));
end;
WM_MBUTTONUP: //ホイールボタン
if FClickGestureStandby then
begin
FClickGestureStandby := False;
Handled := True;
GestureExecute(AddGesture(mgWheelClick));
end;
WM_XBUTTONUP: //横ボタン
if FClickGestureStandby then
begin
FClickGestureStandby := False;
Handled := True;
if (GetKeyState(VK_RBUTTON) < 0) then
case HiWord(Msg.wParam) of
MK_XBUTTON1: GestureExecute(AddGesture(mgSide1R));
MK_XBUTTON2: GestureExecute(AddGesture(mgSide2R));
end
else begin
case HiWord(Msg.wParam) of
MK_XBUTTON1: GestureExecute(AddGesture(mgSide1));
MK_XBUTTON2: GestureExecute(AddGesture(mgSide2));
end;
end;
end;
WM_LBUTTONDOWN:
if Msg.wParam = (MK_RBUTTON + MK_LBUTTON) then
begin
FClickGestureStandby := True;
Handled := True;
end;
WM_MBUTTONDOWN:
if Msg.wParam = (MK_RBUTTON + MK_MBUTTON) then
begin
FClickGestureStandby := True;
Handled := True;
end;
WM_XBUTTONDOWN:
if (HiWord(Msg.wParam) = MK_XBUTTON1) or
(HiWord(Msg.wParam) = MK_XBUTTON2) then
begin
FClickGestureStandby := True;
Handled := (GetKeyState(VK_RBUTTON) < 0);
end;
WM_MOUSEWHEEL:
if LoWord(Msg.wParam) = MK_RBUTTON then
begin
if (Msg.wParam > 0) then
GestureExecute(AddGesture(mgWheelUp))
else
GestureExecute(AddGesture(mgWheelDown));
Handled := True;
end;
end;
end;
procedure TgMouseGesture.GestureExecute(Gestures: TMouseGestureArray);
//実行する
begin
if Assigned(FOnMouseGestureExecute) then
FOnMouseGestureExecute(Self,Gestures);
end;
procedure TgMouseGesture.MoveGesture(pt: TPoint);
//ジェスチャーをチェック
var
temp: Extended;
distance: TPoint;
arrow: TMouseGestureType;
len: Integer;
begin
distance.X := Abs(pt.X - FPrevPoint.X);
distance.Y := Abs(pt.Y - FPrevPoint.Y);
if (distance.X > FMargin) or
(distance.Y > FMargin) then
begin
temp := distance.Y / (distance.X + 0.001);
if temp >= 1 then
begin
if pt.Y > FPrevPoint.Y then
arrow := mgDown
else
arrow := mgUp;
end else
begin
if pt.X > FPrevPoint.X then
arrow := mgRight
else
arrow := mgLeft;
end;
len := Length(FTempMoveGestures);
FTempMoveGestures := AddGesture(arrow,FTempMoveGestures);
if len <> Length(FTempMoveGestures) then
begin
//イベント
if Assigned(FOnMouseGestureNotify) then
FOnMouseGestureNotify(Self,arrow);
if Assigned(FOnMouseGestureNotifyMove) then
FOnMouseGestureNotifyMove(Self,FTempMoveGestures);
end;
FPrevPoint := pt;
end;
end;
procedure TgMouseGesture.Notification(AComponent: TComponent;
Operation: TOperation);
//サブクラスの終了通知
begin
if Operation = opRemove then
ResetSubClass;
inherited;
end;
procedure TgMouseGesture.ResetSubClass;
//初期化する
begin
if Assigned(FTempControl) then
begin
//元に戻す
FTempControl.WindowProc := FTempWndMethod;
FTempControl.RemoveFreeNotification(Self);
FTempControl := nil;
FTempWndMethod := nil;
end;
end;
procedure TgMouseGesture.SetSubClass(Handle: HWND);
//新しいWndProcをセット
begin
//前のをリセット
ResetSubClass;
//コントロールを得る
FTempControl := FindControl(Handle);
if Assigned(FTempControl) then
begin
//終了通知を要求
FTempControl.FreeNotification(Self);
//WndPrco入れ替え
FTempWndMethod := FTempControl.WindowProc;
FTempControl.WindowProc := SubClassMessageHook;
end;
end;
procedure TgMouseGesture.SubClassMessageHook(var Message: TMessage);
//サブクラス
begin
case Message.Msg of
WM_CONTEXTMENU: //無効化する
if (GetKeyState(VK_RBUTTON) < 0) then
Message.Result := 1;
end;
if Assigned(FTempWndMethod) then
FTempWndMethod(Message);
end;
end.
|
unit simple_func_call_1;
interface
implementation
var
G: Int32;
function GetFive: Int32;
begin
Result := 5;
end;
initialization
G := GetFive;
finalization
Assert(G = 5);
end. |
program
SisBiblioteca;
uses
crt, sysutils, DOS;
// ------------- ALUNO --------------------
type listISBNLivros = array[1..2, 1..3] of string;
type Aluno = record //Registro de Aluno
nome : string[30];
mat : integer;
isbnLivros : listISBNLivros;
sexo: char;
curso : string[20];
end;
type returnVerifMatricula = record //Criado para guardar dados da mattrícula
nome : string[30];
mat : integer;
isbnLivros : listISBNLivros;
pos: integer;
sexo : char;
curso : string[20];
end;
tableAlunos = file of Aluno; //Arquivo do tipo Aluno
// ----------- LIVRO ---------------------
type Livro = record
nome : string[30];
autor : string[30];
editora : string[20];
isbn: string[13];
quant: integer;
end;
type r_infLivro = record
nome : string[30];
isbn : string[13];
autor : string[30];
editora : string[20];
quant: integer;
pos: integer;
end;
tableLivros = file of Livro;
const MAXLVR = 6;
type array_inforLivro = array[1..MAXLVR+1] of r_infLivro;
//--------------------------------- Funções------------------------------------
//===================== Aluno ======================
{Funcao para verificar a existencia de um arquivo}
function ExisteTabelaAluno(var f : tableAlunos): boolean;
begin
{$I-}
Reset(f);
if IOResult = 0 then
ExisteTabelaAluno := true
else ExisteTabelaAluno := false;
{$I+}
end;
function ExtArqTextAlunos(var f : text): boolean;
begin
{$I-}
Reset(f);
if IOResult = 0 then
ExtArqTextAlunos := true
else ExtArqTextAlunos := false;
{$I+}
end;
function verificaMatricula(var f : tableAlunos; matricula:integer; r: Aluno): returnVerifMatricula;
var infor : returnVerifMatricula;
begin
infor.nome := '';
infor.mat := -1;
infor.pos := -1;
// Aqui irei tribuir -1 para o nome do livro, -1 para a data de emprestimo e -1 para
// a data de devolução
//======== Livro 1, isbn, emprestimo e devolução
infor.isbnLivros[1,1] := '-1' ;//isbn
infor.isbnLivros[1,2] := '-1' ;// data emprestimo
infor.isbnLivros[1,3] := '-1' ;// data devolução
//======== Livro 1, isbn, emprestimo e devolução
infor.isbnLivros[2,1] := '-1' ; //isbn
infor.isbnLivros[2,2] := '-1' ;//data emprestimo
infor.isbnLivros[2,3] := '-1' ;// data devolução
infor.curso := '';
verificaMatricula := infor;
Reset(f);
read(f,r);
while (not Eof(f)) and (r.mat <> matricula) do
read(f,r);
if r.mat = matricula then
begin
with r do
infor.nome := r.nome;
infor.mat := r.mat;
infor.pos := FilePos(f);
infor.curso := r.curso;
infor.isbnLivros[1,1] := r.isbnLivros[1,1] ;//isbn
infor.isbnLivros[1,2] := r.isbnLivros[1,2] ;// data emprestimo
infor.isbnLivros[1,3] := r.isbnLivros[1,3] ;// data devolução
//======== Livro 1, isbn, emprestimo e devolução
infor.isbnLivros[2,1] := r.isbnLivros[2,1] ; //isbn
infor.isbnLivros[2,2] := r.isbnLivros[2,2] ;//data emprestimo
infor.isbnLivros[2,3] := r.isbnLivros[2,3] ;// data devolução
infor.sexo := r.sexo;
verificaMatricula := infor;
end
else
begin
infor.nome := '';
infor.mat := -1;
infor.pos := -1;
// Aqui irei tribuir -1 para o nome do livro, -1 para a data de emprestimo e -1 para
// a data de devolução
//======== Livro 1, isbn, emprestimo e devolução
infor.isbnLivros[1,1] := '-1' ;//isbn
infor.isbnLivros[1,2] := '-1' ;// data emprestimo
infor.isbnLivros[1,3] := '-1' ;// data devolução
//======== Livro 1, isbn, emprestimo e devolução
infor.isbnLivros[2,1] := '-1' ; //isbn
infor.isbnLivros[2,2] := '-1' ;//data emprestimo
infor.isbnLivros[2,3] := '-1' ;// data devolução
infor.curso := '';
verificaMatricula := infor;
end;
end;
// ========================== Livros ===================================
function ExisteTabelaLivros(var f : tableLivros): boolean;
begin
{$I-}
Reset(f);
if IOResult = 0 then
ExisteTabelaLivros := true
else ExisteTabelaLivros := false;
{$I+}
end;
function ExtArqTextLivros(var f : text): boolean;
begin
{$I-}
Reset(f);
if IOResult = 0 then
ExtArqTextLivros := true
else ExtArqTextLivros := false;
{$I+}
end;
function verificaISBN(var f : tableLivros; isbn:string[13]; r: Livro): r_infLivro;
var inforLivro : r_infLivro;
begin
inforLivro.nome := '';
inforLivro.isbn := '';
inforLivro.autor := '';
inforLivro.editora :='';
inforLivro.quant := -1;
inforLivro.pos := -1;
verificaISBN := inforLivro;
Reset(f);
read(f,r);
while (not Eof(f)) and (r.isbn <> isbn) do
read(f,r);
if r.isbn = isbn then
begin
with r do
inforLivro.nome := r.nome;
inforLivro.isbn := r.isbn;
inforLivro.autor := r.autor;
inforLivro.editora := r.editora;
inforLivro.quant := r.quant;
inforLivro.pos := FilePos(f);
verificaISBN := inforLivro;
end
else
begin
inforLivro.nome := '';
inforLivro.isbn := '';
inforLivro.autor := '';
inforLivro.editora :='';
inforLivro.quant := -1;
inforLivro.pos := -1;
verificaISBN := inforLivro;
end;
end;
function buscaPor(var f : tableLivros; campo: string[30] ;escolha: string; r: Livro): array_inforLivro;
var arrayInforLivro : array_inforLivro;
i : integer;
begin
i := 0;
Reset(f);
while (not Eof(f)) do
begin
read(f,r);
if escolha = 'N' then
begin
if r.nome = campo then
begin
i := i+1;
arrayInforLivro[i].isbn := r.isbn;
arrayInforLivro[i].autor := r.autor;
arrayInforLivro[i].editora := r.editora;
arrayInforLivro[i].quant := r.quant;
arrayInforLivro[i].pos := 0;
end;
end
else if escolha = 'A' then
begin
if r.autor = campo then
begin
i := i+1;
arrayInforLivro[i].nome := r.nome;
arrayInforLivro[i].isbn := r.isbn;
arrayInforLivro[i].editora := r.editora;
arrayInforLivro[i].quant := r.quant;
arrayInforLivro[i].pos := 0;
end;
end
else if escolha = 'E' then
begin
if r.editora = campo then
begin
i := i+1;
arrayInforLivro[i].nome := r.nome;
arrayInforLivro[i].isbn := r.isbn;
arrayInforLivro[i].autor := r.autor;
arrayInforLivro[i].quant := r.quant;
arrayInforLivro[i].pos := 0;
end;
end;
end;
i := i+1 ;
arrayInforLivro[i].pos := -1;
i := 0;
buscaPor := arrayInforLivro;
end;
//================================ Time
function obterDataAtual(comBarra:string):string;
Var
Dia,
Mes,
Ano ,
Dia_Semana,
Hora,
Minuto,
Segundo,
Dec_Segundo : Word; {O tipo das variáveis deve ser WORD
pois até agora não vi data negativa...}
d1, m1, a1 : integer;
d, m, a : string;
begin
GetDate(Ano, Mes, Dia, Dia_Semana);
GetTime(Hora, Minuto, Segundo, Dec_Segundo);
//Writeln(Hora, ':', Minuto, ':', Segundo); {Escreve a hora}
d1 := Dia;
m1 := Mes;
a1 := Ano;
if upCase(comBarra) = 'S' then
begin
Str(d1, d);
Str(m1, m);
Str(a1, a);
obterDataAtual := concat(d, '/',m, '/', a, '/'); {Escreve a data}
end
else
begin
obterDataAtual := concat(d,'',m,'',a,''); {Escreve a data}
end;
end;
function obter(data, get :string):integer;
var dia, mes, ano, i : integer;
begin
for i := 1 to length(data) do
begin
if data[i] = '/' then
begin
Val(Copy(data,1,i-1), dia);
Delete(data,1,i);
break;
end;
end;
for i := 1 to length(data) do
begin
if data[i] = '/' then
begin
Val(Copy(data,1,i-1), mes);
Delete(data,1,i);
break;
end;
end;
Val(Copy(data,1,LENGTH(data)), ano);
if upCase(get) = 'DIA' then
begin
obter := dia;
end
else if upCase(get) = 'MES' then
begin
obter := mes;
end
else if upCase(get) = 'ANO' then
begin
obter := ano;
end;
end;
function quantDias(diaInicial, mesInicial, diaFinal, mesFinal, ano:integer):integer;
const mesesDias : array [1 .. 2, 1 ..12] of integer = ((1,2,3,4,5,6,7,8,9,10,11,12),(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
var i,quantD : integer;
bissexto : boolean;
begin
bissexto := false;
//Bissexto --------------------------------------------------------------
IF ((ano mod 4 = 0) AND ((ano mod 400 = 0) or (ano mod 100 <> 0))) THEN
BEGIN
bissexto := true;
END
ELSE
BEGIN
bissexto := false;
END;
//-----------------------------------------------------------------------
IF bissexto = true THEN
BEGIN
mesesDias[2, 2] := 29;
END
ELSE
BEGIN
mesesDias[2, 2] := 28;
END;
if mesInicial <> mesFinal then
begin
for i := mesInicial to mesFinal do
BEGIN
IF (i = mesInicial) THEN
BEGIN
quantD := mesesDias[2, mesInicial] - diaInicial;
END
else IF (i = mesFinal) THEN
BEGIN
quantD := quantD + diaFinal;
END
else
BEGIN
quantD := quantD+mesesDias[2,i];
END;
quantDias := quantD;
END;
end
else
begin
quantDias := diaFinal - diaInicial;
end;
end;
// =========================== Aluno Livro ================
function verifPendencia(dataEmp, dataDev:string):boolean;
begin
if (quantDias(obter(dataEmp, 'DIA'), obter(dataEmp, 'MES'), obter(dataDev, 'DIA'), obter(dataDev, 'MES'), obter(dataDev, 'ANO'))) > 7 then
begin
verifPendencia := true;
end
else
begin
verifPendencia := false;
end;
end;
var
opcao: integer;
//################### Alunos
tabelaAlunos : tableAlunos;
regAluno : Aluno;
arquivoTextAluno:Text;
buscaMatricula : integer;
//################## Livros
tabelaLivros : tableLivros;
regLivro : Livro;
aquivoTextLivros:Text;
full: boolean;
campo: string;
i, contReg:integer;
inforLivro : r_infLivro;
listaLivros : array_inforLivro;
//############## Outras ...
escolha : char;
buscaISBN : string[13];
n, n1, local :integer;
nome : string;
contSacola : integer;
ok, inseriu : boolean;
//############### Data
dataEmp, dataDev : string;
Dia,
Mes,
Ano ,
Dia_Semana,
Hora,
Minuto,
Segundo,
Dec_Segundo : Word;
d1, m1, a1 : integer;
d, m, a : string;
//#################################
begin
//+++++++++++++++++ Alunos +++++++++++++++++
assign(tabelaAlunos, 'Alunos.arq');
assign(arquivoTextAluno, 'Alunos.txt');
// +++++++++++++++++++++ Livros +++++++++++++
assign(tabelaLivros, 'Biblioteca.arq');
assign(aquivoTextLivros, 'Biblioteca.txt');
//Irei deixar separado a principio depois analisar e juntar ...
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Alunooooooo
if not ExtArqTextAlunos(arquivoTextAluno) OR ExisteTabelaAluno(tabelaAlunos) then
begin
//Atenção! Verificar quando for cadastrar sem os arquivos criados.
rewrite(arquivoTextAluno);
close(arquivoTextAluno);
end;
//~~~~~~~~~~~~~~~~~ AS:130907
if not ExtArqTextLivros(aquivoTextLivros) OR ExisteTabelaLivros(tabelaLivros) then
begin
//Atenção! Verificar quando for cadastrar sem os arquivos criados.
rewrite(aquivoTextLivros);
close(aquivoTextLivros);
end;
full := false;
i := 1;
contReg := 0;
ok := true;
inseriu := false;
local := 0;
repeat
clrscr;
writeln(' SISBiblioteca ');
writeln;
writeln(' 1. Cadastrar Aluno(s)');
writeln(' 2. Cadastrar Livro(s)');
writeln(' 3. Consultar Livro(s)');
writeln(' 4. Consulta de pendencia de aluno');
writeln(' 5. Pedido de emprestimo/devolucoes de livros');
writeln(' 6. Listar Aluno(s)');
writeln(' 7. Encerrar');
writeln;
write(' Digite a opcao desejada: ');
readln(opcao);
case opcao of
1:
begin
clrscr;
writeln(' SISBiblioteca - Cadastro de Aluno(s)');
writeln;
write(' Nome: ');
readln(regAluno.nome);
write(' Matricula: ');
readln(regAluno.mat);
write(' Sexo: ');
readln(regAluno.sexo);
write(' Curso: ');
readln(regAluno.curso);
// Aqui irei tribuir -1 para o nome do livro, -1 para a data de emprestimo e -1 para
// a data de devolução
//======== Livro 1, isbn, emprestimo e devolução
regAluno.isbnLivros[1,1] := '-1' ;//isbn
regAluno.isbnLivros[1,2] := '-1' ;// data emprestimo
regAluno.isbnLivros[1,3] := '-1' ;// data devolução
//======== Livro 1, isbn, emprestimo e devolução
regAluno.isbnLivros[2,1] := '-1' ; //isbn
regAluno.isbnLivros[2,2] := '-1' ;//data emprestimo
regAluno.isbnLivros[2,3] := '-1' ;// data devolução
if not ExisteTabelaAluno(tabelaAlunos) then
begin
rewrite(tabelaAlunos);
write(tabelaAlunos, regAluno);
close(tabelaAlunos);
write('Cadastrado com sucesso. Pressione ENTER para retornar ao menu.');
readln;
end
else
begin
Reset(tabelaAlunos);
buscaMatricula := regAluno.mat;
n := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).pos;
if n = -1 then
begin
Seek(tabelaAlunos, FileSize(tabelaAlunos));
write(tabelaAlunos, regAluno);
close(tabelaAlunos);
writeln;
write('Cadastrado com sucesso. Pressione ENTER para retornar ao menu.');
readln;
end
else
begin
nome := verificaMatricula(tabelaAlunos, regAluno.mat, regAluno).nome;
writeln('Aluno(a) ', nome , ' ja cadastrado(a). ');
write(' Deseja atualizar os dados deste aluno? S/N: ');
readln(escolha);
if upCase(escolha) = 'S' then
begin
clrscr;
Reset(tabelaAlunos);
writeln(' SISBiblioteca - Atualizacao dados do(a) aluno(a) ', nome);
writeln;
write('Digite o novo nome: ');
readln(regAluno.nome);
write('Digite o novo sexo: ');
readln(regAluno.sexo);
write('Digite o novo curso: ');
readln(regAluno.curso);
regAluno.isbnLivros[1,1] := verificaMatricula(tabelaAlunos, regAluno.mat, regAluno).isbnLivros[1,1];
regAluno.isbnLivros[2,1] := verificaMatricula(tabelaAlunos, regAluno.mat, regAluno).isbnLivros[2,1];
regAluno.isbnLivros[1,2] := verificaMatricula(tabelaAlunos, regAluno.mat, regAluno).isbnLivros[1,2];
regAluno.isbnLivros[2,2] := verificaMatricula(tabelaAlunos, regAluno.mat, regAluno).isbnLivros[2,2];
regAluno.isbnLivros[1,3] := verificaMatricula(tabelaAlunos, regAluno.mat, regAluno).isbnLivros[1,3];
regAluno.isbnLivros[2,3] := verificaMatricula(tabelaAlunos, regAluno.mat, regAluno).isbnLivros[2,3];
Seek(tabelaAlunos, n-1);
write(tabelaAlunos, regAluno);
writeln;
write('Usuario atualizado com sucesso. Pressione ENTER para retornar ao menu.');
end
else
begin
clrscr;
write('Cancelado pelo usuario. Pressione ENTER para retornar ao menu.');
end;
readln;
end;
end;
end;
2: //Cadastro de Livros;
begin
clrscr;
writeln(' SISBiblioteca - Cadastro de Livros');
writeln;
write(' Nome: ');
readln(regLivro.nome);
write(' Autor: ');
readln(regLivro.autor);
write(' Editora: ');
readln(regLivro.editora);
write(' ISBN: ');
readln(regLivro.isbn);
write(' Quantidade em estoque: ');
readln(regLivro.quant);
if not ExisteTabelaLivros(tabelaLivros) then
begin
rewrite(tabelaLivros);
write(tabelaLivros, regLivro);
close(tabelaLivros);
write('Cadastrado com sucesso. Pressione ENTER para retornar ao menu.');
readln;
end
else
begin
Reset(tabelaLivros);
if FileSize(tabelaLivros) = MAXLVR then
begin
full := true;
end
else
begin
full := false;
end;
buscaISBN := regLivro.isbn;
n := verificaISBN(tabelaLivros, buscaISBN, regLivro).pos;
if (n = -1) and (full = false) then
begin
Seek(tabelaLivros, FileSize(tabelaLivros));
write(tabelaLivros, regLivro);
close(tabelaLivros);
writeln;
write('Cadastrado com sucesso. Pressione ENTER para retornar ao menu.');
readln;
end
else if ( ((n <> -1) and (full = true)) OR ((n <> -1) and (full = false)) ) then
begin
inforLivro := verificaISBN(tabelaLivros, regLivro.isbn, regLivro);
nome := inforLivro.nome;
clrscr;
writeln('Livro(a) ', nome , ' ja cadastrado(a). ');
write(' Deseja atualizar o estoque? S/N: ');
readln(escolha);
if upCase(escolha) = 'S' then
begin
clrscr;
Reset(tabelaLivros);
writeln(' SISBiblioteca - Atualizacao do livro ', nome);
writeln;
regLivro.nome := inforLivro.nome;
regLivro.autor := inforLivro.autor;
regLivro.editora := inforLivro.editora;
regLivro.isbn := inforLivro.isbn;
write('Digite a nova quantidade: ');
read(regLivro.quant);
Seek(tabelaLivros, n-1);
write(tabelaLivros, regLivro);
writeLN('Estoque atualizado com sucesso. Pressione ENTER para retornar ao menu.');
end
else
begin
clrscr;
write('Cancelado pelo usuario. Pressione ENTER para retornar ao menu.');
readln;
end;
end
else
begin
write('Novo registro nao sera inserido. So eh permitido atualizacao!');
readln;
end;
end;
readln;
end;
3:
begin
clrscr;
writeln(' SISBiblioteca - Consulta de Livros');
writeln;
writeln(' Digite por qual informacao sera efetuada a busca ');
writeln;
writeLN(' N - Nome A - Autor E - Editora ou Qualquer Letra para exibir todos');
readln(escolha);
case UPCASE(escolha) of
'N':
begin
writeln('Digite o nome do livro para efetuar a busca: ');
readln(campo);
listaLivros := buscaPor(tabelaLivros, campo ,escolha, regLivro);
while (listaLivros[i].pos <> -1) do
begin
writeln('Autor : ', listaLivros[i].autor);
writeln('Editora: ', listaLivros[i].editora);
writeln('ISBN: ', listaLivros[i].isbn);
writeln('Quant. Estoque: ', listaLivros[i].quant);
writeln('');
i:=i+1;
end;
writeln('----------------------------------------------');
writeln('Busca concluida, total de registros: ', i - 1);
i := 1;
readln;
end;
'A':
begin
writeln('Digite o nome do autor para efetuar a busca: ');
readln(campo);
listaLivros := buscaPor(tabelaLivros, campo ,escolha, regLivro);
while (listaLivros[i].pos <> -1) do
begin
writeln('Nome: : ', listaLivros[i].nome);
writeln('Editora: ', listaLivros[i].editora);
writeln('ISBN: ', listaLivros[i].isbn);
writeln('Quant. Estoque: ', listaLivros[i].quant);
writeln('');
i:=i+1;
end;
writeln('----------------------------------------------');
writeln('Busca concluida, total de registros: ', i - 1);
i := 1;
readln;
end;
'E':
begin
writeln('Digite o nome da editora para efetuar a busca: ');
readln(campo);
listaLivros := buscaPor(tabelaLivros, campo ,escolha, regLivro);
while (listaLivros[i].pos <> -1) do
begin
writeln('Nome: : ', listaLivros[i].nome);
writeln('Autor: ', listaLivros[i].autor);
writeln('ISBN: ', listaLivros[i].isbn);
writeln('Quant. Estoque: ', listaLivros[i].quant);
writeln('');
i:=i+1;
end;
writeln('----------------------------------------------');
writeln('Busca concluida, total de registros: ', i - 1);
i := 1;
readln;
end
else // lista todos
begin
Reset(tabelaLivros);
rewrite(aquivoTextLivros);
while not Eof(tabelaLivros) do
begin
contReg := contReg + 1;
read(tabelaLivros, regLivro);
writeln('Nome: ', regLivro.nome);
writeln('Autor : ', regLivro.autor);
writeln('Editora: ', regLivro.editora);
writeln('ISBN: ', regLivro.isbn);
writeln('Quant. Estoque: ', regLivro.quant);
writeln('');
if not ExtArqTextLivros(aquivoTextLivros) then
begin
rewrite(aquivoTextLivros);
end
else
begin
Append(aquivoTextLivros);
end;
writeln(aquivoTextLivros, 'Nome: ', regLivro.nome);
writeln(aquivoTextLivros, 'Autor : ', regLivro.autor);
writeln(aquivoTextLivros, 'Editora: ', regLivro.editora);
writeln(aquivoTextLivros, 'ISBN: ', regLivro.isbn);
writeln(aquivoTextLivros, 'Quant. Estoque: ', regLivro.quant);
writeln(aquivoTextLivros, '');
close(aquivoTextLivros);
end;
writeln('----------------------------------------------');
writeln(' Total de registros: ', contReg);
if not ExtArqTextLivros(aquivoTextLivros) then
begin
rewrite(aquivoTextLivros);
end
else
begin
Append(aquivoTextLivros);
end;
writeln(aquivoTextLivros, '----------------------------------------------');
writeln(aquivoTextLivros, ' Total de registros: ', contReg);
close(aquivoTextLivros);
contReg := 0;
end;
readln;
end;
end;
4: //excluirAluno;
begin
clrscr;
writeln(' SISBiblioteca - Consulta de pendencia de alunos');
writeln;
write(' Digite a matricula do aluno: ');
readln(buscaMatricula);
Reset(tabelaAlunos);
if verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).pos <> -1 then
begin
writeln(' Nome: ',verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).nome);
writeln(' Curso: ',verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).curso);
for contSacola := 1 to 2 do
begin
//verificarPrazoEntrega
dataEmp := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[contSacola,2];
dataDev := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[contSacola,3];
if verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[contSacola,1] <> '-1' then
begin
GetDate(Ano, Mes, Dia, Dia_Semana);
d1 := Dia;
m1 := Mes;
a1 := Ano;
Str(d1, d);
Str(m1, m);
Str(a1, a);
if (quantDias(obter(dataEmp, 'DIA'), obter(dataEmp, 'MES'), d1, m1, ano )) > 7 then
begin
write(' O livro ', verificaISBN(tabelaLivros, verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[contSacola,1] , regLivro).nome, ' esta com prazo vencido!');
writeln;
end
else
begin
write(' O livro ', verificaISBN(tabelaLivros, verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[contSacola,1] , regLivro).nome, ' esta em dia!');
writeln;
end;
end
else
begin
writeln(' Espaco livre!');
end;
end;
readln;
end
else
begin
write(' Matricula inexistente. Pressione ENTER para retornar ao menu');
readln;
end;
end;
5:
begin
clrscr;
writeln(' SISBiblioteca - Pedido de emprestimo/devolucoes de livros');
writeln;
write(' Escolha [E - Emprestimo] ou [D - Devolucoes]');
readln(escolha);
if upcase(escolha) = 'E' then
begin
writeln(' Menu: Emprestimo ');
writeln(' ----------------- ');
write(' Digite a matricula do aluno: ');
readln(buscaMatricula);
Reset(tabelaAlunos);
if verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).pos <> -1 then
begin
for contSacola := 1 to 2 do
begin
//verificarPrazoEntrega
dataEmp := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[contSacola,2];
dataDev := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[contSacola,3];
if dataEmp <> '-1' then
begin
if verifPendencia(dataEmp, dataDev) = true then
begin
ok := false;
end
else
begin
ok := true;
end;
end;
end;
if ok = true then
begin
write(' Digite o ISBN do livro para efetuar o emprestimo: ');
readln(buscaISBN);
Reset(tabelaLivros);
n1 := verificaISBN(tabelaLivros, buscaISBN, regLivro).pos;
if n1 <> -1 then
begin
//Se houver estoque
if verificaISBN(tabelaLivros, buscaISBN, regLivro).quant > 0 then
begin
write(' Digite a da para devolucao (Considere 7 dias, formato DD/MM/AAAA) : ');
readln(dataDev);
for contSacola := 1 to 2 do
begin
if (verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[contSacola,1] = '-1') then
begin
local := contSacola;
break;
end
else
begin
local := 0;
end;
end;
GetDate(Ano, Mes, Dia, Dia_Semana);
d1 := Dia;
m1 := Mes;
a1 := Ano;
Str(d1, d);
Str(m1, m);
Str(a1, a);
if local = 1 then
begin
regAluno.nome := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).nome;
regAluno.curso := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).curso;
regAluno.mat:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).mat;
regAluno.sexo:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).sexo;
regAluno.isbnLivros[1,1] := buscaISBN;
regAluno.isbnLivros[1,2] := concat(d,'/',m,'/',a);
regAluno.isbnLivros[1,3] := dataDev;
regAluno.isbnLivros[2,1] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,1];
regAluno.isbnLivros[2,2] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,2];
regAluno.isbnLivros[2,3] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,3];
Reset(tabelaAlunos);
n := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).pos;
Seek(tabelaAlunos, n-1);
write(tabelaAlunos, regAluno);
writeln;
inseriu := true;
end
else if local = 2 then
begin
regAluno.nome := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).nome;
regAluno.curso := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).curso;
regAluno.mat:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).mat;
regAluno.isbnLivros[1,1] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,1];
regAluno.isbnLivros[1,2] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,2];
regAluno.isbnLivros[1,3] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,3];
regAluno.sexo:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).sexo;
regAluno.isbnLivros[2,1] := buscaISBN;
regAluno.isbnLivros[2,2] := concat(d,'/',m,'/',a);
regAluno.isbnLivros[2,3] := dataDev;
Reset(tabelaAlunos);
n := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).pos;
Seek(tabelaAlunos, n-1);
write(tabelaAlunos, regAluno);
writeln;
inseriu := true;
end
else
begin
inseriu := false;
end;
if inseriu = true then
begin
inforLivro := verificaISBN(tabelaLivros, buscaISBN, regLivro);
Reset(tabelaLivros);
regLivro.nome := inforLivro.nome;
regLivro.autor := inforLivro.autor;
regLivro.editora := inforLivro.editora;
regLivro.isbn := inforLivro.isbn;
regLivro.quant := inforLivro.quant - 1;
Seek(tabelaLivros, n1 - 1);
write(tabelaLivros, regLivro);
writeln(' Adicionado com sucesso.');
readln;
end
else
begin
inseriu := false;
writeln(' Erro ao adicionar ');
readln;
end;
end
else
begin
inseriu := false;
writeln(' Quantidade nao disponivel! ');
readln;
end;
end
else
begin
inseriu := false;
writeln(' ISBN invalido! ');
readln;
end;
end
else
begin
writeln(' Existem pendencias para o aluno ', verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).nome);
readln;
end;
end
else
begin
write(' Matricula inexistente. Pressione ENTER para retornar ao menu');
readln;
end;
end
else if upcase(escolha) = 'D' then
begin
writeln(' Menu: Devolucoes ');
writeln(' ---------------- ');
write(' Digite a matricula do aluno: ');
readln(buscaMatricula);
Reset(tabelaAlunos);
if verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).pos <> -1 then
begin
Reset(tabelaLivros);
/////////////////////////////////////////////////////////////////////////
writeln(' Livros em posse do aluno : [', verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).nome, ']');
if verificaISBN(tabelaLivros, verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,1], regLivro).pos <> -1 then
writeln(' Nome livro [1]: ', verificaISBN(tabelaLivros, verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,1], regLivro).nome, '- ISBN: ' , verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,1]);
if verificaISBN(tabelaLivros, verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,1], regLivro).pos <> -1 then
writeln(' Nome Livro [2]: ', verificaISBN(tabelaLivros, verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,1], regLivro).nome, ' - ISBN: ', verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,1] );
writeln(' Deseja devolver todos [T] ou um livro [U]: ');
readln(escolha);
if upcase(escolha) = 'T' then
begin
inforLivro := verificaISBN(tabelaLivros, verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,1], regLivro);
regLivro.nome := inforLivro.nome;
regLivro.autor := inforLivro.autor;
regLivro.editora := inforLivro.editora;
regLivro.isbn := inforLivro.isbn;
regLivro.quant := inforLivro.quant + 1;
Seek(tabelaLivros, inforLivro.pos - 1);
write(tabelaLivros, regLivro);
inforLivro := verificaISBN(tabelaLivros, verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,1], regLivro);
Reset(tabelaLivros);
regLivro.nome := inforLivro.nome;
regLivro.autor := inforLivro.autor;
regLivro.editora := inforLivro.editora;
regLivro.isbn := inforLivro.isbn;
regLivro.quant := inforLivro.quant + 1;
Seek(tabelaLivros, inforLivro.pos - 1);
write(tabelaLivros, regLivro);
regAluno.nome := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).nome;
regAluno.curso := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).curso;
regAluno.mat:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).mat;
regAluno.sexo:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).sexo;
regAluno.isbnLivros[1,1] := '-1';
regAluno.isbnLivros[1,2] := '-1';
regAluno.isbnLivros[1,3] := '-1';
regAluno.isbnLivros[2,1] := '-1';
regAluno.isbnLivros[2,2] := '-1';
regAluno.isbnLivros[2,3] := '-1';
Reset(tabelaAlunos);
n := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).pos;
Seek(tabelaAlunos, n-1);
write(tabelaAlunos, regAluno);
writeln(' Devolvido com sucesso.');
readln;
end
else if upcase(escolha) = 'U' then
begin
write(' Digite o ISBN do livro a ser devolvido: ');
readln(buscaISBN);
Reset(tabelaAlunos);
Reset(tabelaLivros);
n1 := verificaISBN(tabelaLivros, buscaISBN, regLivro).pos;
if n1 <> -1 then
begin
inseriu := false;
for contSacola := 1 to 2 do
begin
if (verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[contSacola,1] = buscaISBN) then
begin
local := contSacola;
break;
end
else
begin
local := 0;
end;
end;
if local = 1 then
begin
regAluno.nome := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).nome;
regAluno.curso := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).curso;
regAluno.mat:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).mat;
regAluno.sexo:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).sexo;
regAluno.isbnLivros[1,1] := '-1';
regAluno.isbnLivros[1,2] := '-1';
regAluno.isbnLivros[1,3] := '-1';
regAluno.isbnLivros[2,1] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,1];
regAluno.isbnLivros[2,2] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,2];
regAluno.isbnLivros[2,3] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[2,3];
Reset(tabelaAlunos);
n := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).pos;
Seek(tabelaAlunos, n-1);
write(tabelaAlunos, regAluno);
writeln;
inseriu := true;
end
else if local = 2 then
begin
regAluno.nome := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).nome;
regAluno.curso := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).curso;
regAluno.mat:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).mat;
regAluno.isbnLivros[1,1] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,1];
regAluno.isbnLivros[1,2] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,2];
regAluno.isbnLivros[1,3] := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).isbnLivros[1,3];
regAluno.sexo:= verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).sexo;
regAluno.isbnLivros[2,1] := '-1';
regAluno.isbnLivros[2,2] := '-1';
regAluno.isbnLivros[2,3] := '-1';
Reset(tabelaAlunos);
n := verificaMatricula(tabelaAlunos, buscaMatricula, regAluno).pos;
Seek(tabelaAlunos, n-1);
write(tabelaAlunos, regAluno);
writeln;
inseriu := true;
end
else
begin
inseriu := false;
end;
if inseriu = true then
begin
inforLivro := verificaISBN(tabelaLivros, buscaISBN, regLivro);
Reset(tabelaLivros);
regLivro.nome := inforLivro.nome;
regLivro.autor := inforLivro.autor;
regLivro.editora := inforLivro.editora;
regLivro.isbn := inforLivro.isbn;
regLivro.quant := inforLivro.quant + 1;
Seek(tabelaLivros, n1 - 1);
write(tabelaLivros, regLivro);
writeln(' Devolvido com sucesso.');
readln;
end
else
begin
inseriu := false;
writeln(' Erro ao Devolver ');
readln;
end;
end
else
begin
writeln(' ISBN Invalido ');
readln;
end;
end
else
begin
writeln(' Invalida ');
readln;
end;
end;
end;
end;
6: //Lista de Aluno;
begin
clrscr;
writeln(' SISBiblioteca - Listar de Aluno(s)');
writeln;
try
Reset(tabelaAlunos);
rewrite(arquivoTextAluno);
while not Eof(tabelaAlunos) do
begin
read(tabelaAlunos, regAluno);
writeln(' Nome: ', regAluno.nome);
writeln(' Matricula : ', regAluno.mat);
writeln(' Sexo: ', regAluno.sexo);
writeln(' Curso: ', regAluno.curso);
writeln(' Livros em sua posse: ' );
if regAluno.isbnLivros[1,1] = '-1' then
begin
writeln(' 1. - ' );
end
else
begin
writeln(' 1. ', regAluno.isbnLivros[1,1] );
end;
if regAluno.isbnLivros[1,2] = '-1' then
begin
writeln(' Data de Emprestimo: - ');
end
else
begin
writeln(' Data de Emprestimo:', regAluno.isbnLivros[1,2]);
end;
if regAluno.isbnLivros[1,3] = '-1' then
begin
writeln(' Data de Devolucao: - ');
end
else
begin
writeln(' Data de Devolucao:', regAluno.isbnLivros[1,3]);
end;
if regAluno.isbnLivros[2,1] = '-1' then
begin
writeln(' 2. - ');
end
else
begin
writeln(' 2. ', regAluno.isbnLivros[2,1]);
end;
if regAluno.isbnLivros[2,2] = '-1' then
begin
writeln(' Data de Emprestimo: - ');
end
else
begin
writeln(' Data de Emprestimo:', regAluno.isbnLivros[2,2]);
end;
if regAluno.isbnLivros[2,3] = '-1' then
begin
writeln(' Data de Devolucao: - ');
end
else
begin
writeln(' Data de Devolucao:', regAluno.isbnLivros[2,3]);
end;
writeln('');
if not ExtArqTextAlunos(arquivoTextAluno) then
begin
rewrite(arquivoTextAluno);
end
else
begin
Append(arquivoTextAluno);
end;
writeln(arquivoTextAluno, 'Nome: ', regAluno.nome);
writeln(arquivoTextAluno,' Matricula : ', regAluno.mat);
writeln(arquivoTextAluno,' Sexo: ', regAluno.sexo);
writeln(arquivoTextAluno,' Curso: ', regAluno.curso);
writeln(arquivoTextAluno,' Livros em sua posse: ' );
if regAluno.isbnLivros[1,1] = '-1' then
begin
writeln(arquivoTextAluno,' 1. - ' );
end
else
begin
writeln(arquivoTextAluno,' 1. ', regAluno.isbnLivros[1,1] );
end;
if regAluno.isbnLivros[1,2] = '-1' then
begin
writeln(arquivoTextAluno,' Data de Emprestimo: - ');
end
else
begin
writeln(arquivoTextAluno,' Data de Emprestimo:', regAluno.isbnLivros[1,2]);
end;
if regAluno.isbnLivros[1,3] = '-1' then
begin
writeln(arquivoTextAluno,' Data de Devolucao: - ');
end
else
begin
writeln(arquivoTextAluno,' Data de Devolucao:', regAluno.isbnLivros[1,3]);
end;
if regAluno.isbnLivros[2,1] = '-1' then
begin
writeln(arquivoTextAluno,' 2. - ');
end
else
begin
writeln(arquivoTextAluno,' 2. ', regAluno.isbnLivros[2,1]);
end;
//
if regAluno.isbnLivros[2,2] = '-1' then
begin
writeln(arquivoTextAluno,' Data de Emprestimo: - ');
end
else
begin
writeln(arquivoTextAluno,' Data de Emprestimo:', regAluno.isbnLivros[2,2]);
end;
//
if regAluno.isbnLivros[2,3] = '-1' then
begin
writeln(arquivoTextAluno,' Data de Devolucao: - ');
end
else
begin
writeln(arquivoTextAluno,' Data de Devolucao:', regAluno.isbnLivros[2,3]);
end;
//
writeln;
close(arquivoTextAluno);
end;
readln;
except
on e: EInOutError do
begin
writeln('Ocorreu um erro ao ler alunos. Verifique se existem alunos cadastrados. \n Detalhes: '+ e.ClassName+'/'+ e.Message);
readln;
end;
end;
end;
7:
begin
writeln;
write(' Encerrando...');
readln;
end
else
begin
writeln;
write(' Opcao invalida!');
readln;
end
end;
until opcao = 7;
end.
|
unit ExecSQLFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, RzStatus, RzPanel, ExtCtrls, StdCtrls, RzButton, ImgList,
DBAccess, MSAccess, RzLabel, DB, MemDS, Grids, DBGridEh, RzTabs, Mask,
RzEdit, GridsEh, DBGridEhGrouping;
type
TFmeExecSQL = class(TFrame)
lblCaption: TRzLabel;
MySQL: TMSSQL;
RzToolbar1: TRzToolbar;
ImageList1: TImageList;
BtnExecute: TRzToolButton;
RzPanel1: TRzPanel;
meSQL: TMemo;
Splitter1: TSplitter;
RzPanel2: TRzPanel;
RzStatusBar1: TRzStatusBar;
Status: TRzStatusPane;
RzPageControl1: TRzPageControl;
TabSheet1: TRzTabSheet;
meResult: TMemo;
TabSheet2: TRzTabSheet;
DBGridEh1: TDBGridEh;
MyQuery: TMSQuery;
MySource: TDataSource;
dlgOpenFile: TOpenDialog;
RzSpacer1: TRzSpacer;
BtnOpenFile: TRzToolButton;
BtnCheck: TRzToolButton;
RzSpacer2: TRzSpacer;
BtnClear: TRzToolButton;
RzSpacer3: TRzSpacer;
RzToolButton1: TRzToolButton;
TabSheet3: TRzTabSheet;
MD: TMSMetadata;
dsMetaData: TDataSource;
DBGridEh2: TDBGridEh;
edtName: TRzEdit;
procedure BtnExecuteClick(Sender: TObject);
procedure meSQLExit(Sender: TObject);
procedure MySQLAfterExecute(Sender: TObject; Result: Boolean);
procedure BtnOpenFileClick(Sender: TObject);
procedure BtnCheckClick(Sender: TObject);
procedure BtnClearClick(Sender: TObject);
procedure RzToolButton1Click(Sender: TObject);
procedure edtNameChange(Sender: TObject);
private
{ Private declarations }
public
procedure Init;
end;
implementation
uses DataModule, MainForm;
{$R *.dfm}
{ TFrame1 }
procedure TFmeExecSQL.Init;
begin
//meSQL.Clear;
RzPageControl1.ActivePage:=TabSheet1;
end;
procedure TFmeExecSQL.BtnExecuteClick(Sender: TObject);
begin
MySQL.SQL := meSQL.Lines;
Status.Caption := 'Выполнение...';
MySQL.Execute;
MyQuery.SQL := meSQL.Lines;
try
MyQuery.Open;
except
end;
end;
procedure TFmeExecSQL.meSQLExit(Sender: TObject);
begin
MySQL.SQL := meSQL.Lines;
end;
procedure TFmeExecSQL.MySQLAfterExecute(Sender: TObject; Result: Boolean);
var
i:integer;
begin
if Result then begin
Status.Caption := 'Успешно' + ' (' + IntToStr(MySQL.RowsAffected) +
' строк обработано)';
meResult.Lines.Clear;
for i := 0 to MySQL.Params.Count-1 do begin
meResult.Lines.Add(MySQL.Params[i].Name + ' = ' +
MySQL.Params[i].AsString);
end;
end
else
Status.Caption := 'Ошибка';
MessageBeep(MB_OK);
end;
procedure TFmeExecSQL.BtnOpenFileClick(Sender: TObject);
begin
dlgOpenFile.Execute;
meSQL.Lines.LoadFromFile(dlgOpenFile.FileName);
end;
procedure TFmeExecSQL.BtnCheckClick(Sender: TObject);
Var
i:integer;
begin
for i:=0 to meSQl.Lines.Count-1 do
if CompareText('Go',meSQl.Lines.Strings[i])=0 then
meSQl.Lines.Strings[i]:=' ';
end;
procedure TFmeExecSQL.BtnClearClick(Sender: TObject);
begin
meSQl.Clear;
end;
procedure TFmeExecSQL.RzToolButton1Click(Sender: TObject);
begin
FrmMain.pgcWork.ActivePage:=FrmMain.TabWelcome;
end;
procedure TFmeExecSQL.edtNameChange(Sender: TObject);
begin
MD.TableName:=edtName.Text;
MD.Active:=True;
end;
end.
|
unit MySetsUnit;
interface
type
TMySet = array of string;
TMySets = class
public
function StrToSet(InputString: String; Delimiter: String = ', '): TMySet;
function SetToStr(InputArray: TMySet; Delimiter: String = ', '): String;
function CellExists(Cell: String; InputSet: TMySet): Boolean;
function SubSet(SubSet, InputSet: TMySet): Boolean;
function Equal(ASet, BSet: TMySet): Boolean;
function GetUnion(ASet, BSet: TMySet): TMySet;
function GetIntersection(ASet, BSet: TMySet): TMySet;
function GetDifference(ASet, BSet: TMySet): TMySet;
function GetSymmetricDifference(ASet, BSet: TMySet): TMySet;
end;
implementation
function TMySets.StrToSet(InputString: String;
Delimiter: String = ', '): TMySet;
var Len, sPartLen: Integer;
begin
Len := 0;
sPartLen := Length(Delimiter);
if InputString = '' then Exit;
while Pos(Delimiter, InputString) <> 0 do
begin
Inc(Len);
SetLength(Result, Len);
Result[Len - 1] := Copy(InputString, 0, Pos(Delimiter, InputString) - 1);
Delete(InputString, 1, Pos(Delimiter, InputString) + sPartLen - 1);
end;
SetLength(Result, Len + 1);
Result[Len] := InputString;
end;
function TMySets.SetToStr(InputArray: TMySet; Delimiter: String = ', '): String;
var
I, Len: Integer;
begin
Len := Length(InputArray);
if Len = 0 then Exit
else
if Len = 1 then Result := InputArray[0]
else
begin
for I := 0 to Len - 2 do Result := Result + InputArray[I] + Delimiter;
Result := Result + InputArray[Len - 1];
end;
end;
function TMySets.CellExists(Cell: String; InputSet: TMySet): Boolean;
var I: Integer;
begin
Result := False;
for I := Low(InputSet) to High(InputSet) do
if Cell = InputSet[I] then
begin
Result := True;
Break;
end;
end;
function TMySets.SubSet(SubSet, InputSet: TMySet): Boolean;
var I: Integer;
begin
Result := True;
for I := Low(SubSet) to High(SubSet) do
if not CellExists(SubSet[I], InputSet) then
begin
Result := False;
Break;
end;
end;
function TMySets.Equal(ASet, BSet: TMySet): Boolean;
begin
if SubSet(ASet, BSet) and (Length(ASet) = Length(BSet))
then Result := True
else Result := False;
end;
function TMySets.GetUnion(ASet, BSet: TMySet): TMySet;
var
I, Len: Integer;
begin
Len := Length(ASet);
SetLength(Result, Len);
Result := ASet;
for I := Low(BSet) to High(BSet) do
if not CellExists(BSet[I], ASet) then
begin
Inc(Len);
SetLength(Result, Len);
Result[Len-1] := BSet[I];
end;
end;
function TMySets.GetIntersection(ASet, BSet: TMySet): TMySet;
var
I, Len: Integer;
begin
Len := 0;
for I := Low(ASet) to High(ASet) do
if CellExists(ASet[I], BSet) then
begin
Inc(Len);
SetLength(Result, Len);
Result[Len-1] := ASet[I];
end;
end;
function TMySets.GetDifference(ASet, BSet: TMySet): TMySet;
var
I, Len: Integer;
begin
Len := 0;
for I := Low(ASet) to High(ASet) do
if not CellExists(ASet[I], BSet) then
begin
Inc(Len);
SetLength(Result, Len);
Result[Len-1] := ASet[I];
end;
end;
function TMySets.GetSymmetricDifference(ASet, BSet: TMySet): TMySet;
begin
Result := GetUnion(
GetDifference(ASet, BSet),
GetDifference(BSet, ASet)
);
end;
end.
|
unit LinkedListBenchmark;
{$mode delphi}
interface
uses
Classes, BenchmarkClassUnit, Math;
const
cNB_LIST_ITEMS = 128*1024;
type
TLinkedListBench = class(TFastcodeMMBenchmark)
public
constructor CreateBenchmark; override;
destructor Destroy; override;
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetSpeedWeight: Double; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
{ TSmallResizeBench }
constructor TLinkedListBench.CreateBenchmark;
begin
inherited;
end;
destructor TLinkedListBench.Destroy;
begin
inherited;
end;
class function TLinkedListBench.GetBenchmarkDescription: string;
begin
Result:= 'Allocates a linked list containers and then navigates back and '
+'forth through it multiple times.';
end;
class function TLinkedListBench.GetBenchmarkName: string;
begin
Result := 'Linked-list container benchmark';
end;
class function TLinkedListBench.GetCategory: TBenchmarkCategory;
begin
Result := bmMemoryAccessSpeed;
end;
class function TLinkedListBench.GetSpeedWeight: Double;
begin
{Speed is of the essence here}
Result := 0.8;
end;
type
TExternalRefObject1 = class
Padding : array [0..50] of Integer;
end;
TExternalRefObject2 = class(TExternalRefObject1)
Padding2 : array [0..50] of Integer;
end;
TExternalRefObject3 = class(TExternalRefObject2)
Padding3 : array [0..50] of Integer;
end;
TExternalRefObject4 = class(TExternalRefObject3)
Padding4 : array [0..50] of Integer;
end;
PLinkedListItem = ^TLinkedListItem;
TLinkedListItem = record
Next, Prev : PLinkedListItem;
List : TList;
ExternalRef : TExternalRefObject1;
end;
TLinkedList = class
First, Last : PLinkedListItem;
end;
procedure Dummy;
begin
end;
procedure TLinkedListBench.RunBenchmark;
var
i : Integer;
list : TLinkedList;
current : PLinkedListItem;
begin
inherited;
// allocate the list
list:=TLinkedList.Create;
New(current);
current.Next:=nil;
current.Prev:=nil;
current.ExternalRef:=TExternalRefObject1.Create;
list.First:=current;
list.Last:=list.First;
RandSeed:=0;
for i:=2 to cNB_LIST_ITEMS do begin
New(current);
current.Next:=nil;
list.Last.Next:=current;
current.Prev:=list.Last;
list.Last:=current;
case Random(4) of // allocate randomly from a small variety of external refs
0 : current.ExternalRef:=TExternalRefObject1.Create;
1 : current.ExternalRef:=TExternalRefObject2.Create;
2 : current.ExternalRef:=TExternalRefObject3.Create;
3 : current.ExternalRef:=TExternalRefObject4.Create;
end;
end;
// peak usage reached now
UpdateUsageStatistics;
// do the bench
for i:=1 to 100 do begin
current:=list.First;
while current<>nil do begin
if current.ExternalRef.Padding[0]=-1 then Dummy; // access the ExternalRef
current:=current.Next;
end;
current:=list.Last;
while current<>nil do begin
if current.ExternalRef.Padding[0]=-1 then Dummy; // access the ExternalRef
current:=current.Prev;
end;
end;
// cleanup
current:=list.First;
while current<>nil do begin
list.First:=current.Next;
current.ExternalRef.Free;
Dispose(current);
current:=list.First;
end;
list.Free;
end;
end.
|
unit DockForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus,
ExtCtrls, StdCtrls;
type
TDockableForm = class(TForm)
Memo1: TMemo;
procedure FormDockOver(Sender: TObject; Source: TDragDockObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
function ComputeDockingRect(var DockRect: TRect; MousePos: TPoint): TAlign;
procedure CMDockClient(var Message: TCMDockClient); message CM_DOCKCLIENT;
public
end;
implementation
{$R *.DFM}
uses ComCtrls, TabHost, ConjoinHost, Main;
procedure TDockableForm.FormDockOver(Sender: TObject;
Source: TDragDockObject; X, Y: Integer; State: TDragState;
var Accept: Boolean);
var
ARect: TRect;
begin
Accept := (Source.Control is TDockableForm);
//Draw dock preview depending on where the cursor is relative to our client area
if Accept and (ComputeDockingRect(ARect, Point(X, Y)) <> alNone) then
Source.DockRect := ARect;
end;
function TDockableForm.ComputeDockingRect(var DockRect: TRect; MousePos: TPoint): TAlign;
var
DockTopRect,
DockLeftRect,
DockBottomRect,
DockRightRect,
DockCenterRect: TRect;
begin
Result := alNone;
//divide form up into docking "Zones"
DockLeftRect.TopLeft := Point(0, 0);
DockLeftRect.BottomRight := Point(ClientWidth div 5, ClientHeight);
DockTopRect.TopLeft := Point(ClientWidth div 5, 0);
DockTopRect.BottomRight := Point(ClientWidth div 5 * 4, ClientHeight div 5);
DockRightRect.TopLeft := Point(ClientWidth div 5 * 4, 0);
DockRightRect.BottomRight := Point(ClientWidth, ClientHeight);
DockBottomRect.TopLeft := Point(ClientWidth div 5, ClientHeight div 5 * 4);
DockBottomRect.BottomRight := Point(ClientWidth div 5 * 4, ClientHeight);
DockCenterRect.TopLeft := Point(ClientWidth div 5, ClientHeight div 5);
DockCenterRect.BottomRight := Point(ClientWidth div 5 * 4, ClientHeight div 5 * 4);
//Find out where the mouse cursor is, to decide where to draw dock preview.
if PtInRect(DockLeftRect, MousePos) then
begin
Result := alLeft;
DockRect := DockLeftRect;
DockRect.Right := ClientWidth div 2;
end
else
if PtInRect(DockTopRect, MousePos) then
begin
Result := alTop;
DockRect := DockTopRect;
DockRect.Left := 0;
DockRect.Right := ClientWidth;
DockRect.Bottom := ClientHeight div 2;
end
else
if PtInRect(DockRightRect, MousePos) then
begin
Result := alRight;
DockRect := DockRightRect;
DockRect.Left := ClientWidth div 2;
end
else
if PtInRect(DockBottomRect, MousePos) then
begin
Result := alBottom;
DockRect := DockBottomRect;
DockRect.Left := 0;
DockRect.Right := ClientWidth;
DockRect.Top := ClientHeight div 2;
end
else
if PtInRect(DockCenterRect, MousePos) then
begin
Result := alClient;
DockRect := DockCenterRect;
end;
if Result = alNone then Exit;
//DockRect is in screen coordinates.
DockRect.TopLeft := ClientToScreen(DockRect.TopLeft);
DockRect.BottomRight := ClientToScreen(DockRect.BottomRight);
end;
procedure TDockableForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
//the action taken depends on how the form is docked.
if (HostDockSite is TConjoinDockHost) then
begin
//remove the form's caption from the conjoin dock host's caption list
TConjoinDockHost(HostDockSite).UpdateCaption(Self);
//if we're the last visible form on a conjoined form, hide the form
if HostDockSite.VisibleDockClientCount <= 1 then
HostDockSite.Hide;
end;
//if docked to a panel, tell the panel to hide itself. If there are other
//visible dock clients on the panel, it ShowDockPanel won't allow it to
//be hidden
if (HostDockSite is TPanel) then
MainForm.ShowDockPanel(HostDockSite as TPanel, False, nil);
Action := caHide;
end;
procedure TDockableForm.CMDockClient(var Message: TCMDockClient);
var
ARect: TRect;
DockType: TAlign;
Host: TForm;
Pt: TPoint;
begin
//Overriding this message allows the dock form to create host forms
//depending on the mouse position when docking occurs. If we don't override
//this message, the form will use VCL's default DockManager.
//NOTE: the only time ManualDock can be safely called during a drag
//operation is we override processing of CM_DOCKCLIENT.
if Message.DockSource.Control is TDockableForm then
begin
//Find out how to dock (Using a TAlign as the result of ComputeDockingRect)
Pt.x := Message.MousePos.x;
Pt.y := Message.MousePos.y;
DockType := ComputeDockingRect(ARect, Pt);
//if we are over a dockable form docked to a panel in the
//main window, manually dock the dragged form to the panel with
//the correct orientation.
if (HostDockSite is TPanel) then
begin
Message.DockSource.Control.ManualDock(HostDockSite, nil, DockType);
Exit;
end;
//alClient => Create a TabDockHost and manually dock both forms to the PageControl
//owned by the TabDockHost.
if DockType = alClient then
begin
Host := TTabDockHost.Create(Application);
Host.BoundsRect := Self.BoundsRect;
Self.ManualDock(TTabDockHost(Host).PageControl1, nil, alClient);
Message.DockSource.Control.ManualDock(TTabDockHost(Host).PageControl1, nil, alClient);
Host.Visible := True;
end
//if DockType <> alClient, create the ConjoinDockHost and manually dock both
//forms to it. Be sure to make dockable forms non-dockable when hosted by
// ConjoinDockForm, since it is using the VCL default DockManager.
else begin
Host := TConjoinDockHost.Create(Application);
Host.BoundsRect := Self.BoundsRect;
Self.ManualDock(Host, nil, alNone);
Self.DockSite := False;
Message.DockSource.Control.ManualDock(Host, nil, DockType);
TDockableForm(Message.DockSource.Control).DockSite := False;
Host.Visible := True;
end;
end;
end;
procedure TDockableForm.FormShow(Sender: TObject);
begin
if HostDockSite is TConjoinDockHost then
TConjoinDockHost(HostDockSite).UpdateCaption(nil);
end;
end.
|
unit morphutils;
interface
uses Classes,opengl, SysUtils,morphmath;
const
cMaxArray = (MaxInt shr 4);
type
TIntegerVector = array[0..cMaxArray] of integer;
TFloatVector = array[0..cMaxArray] of Single;
TSingleArray = array of Single;
PFloatVector = ^TFloatVector;
PFloatArray = PFloatVector;
PSingleArray = PFloatArray;
TSingleArrayList = array [0..MaxInt shr 4] of Single;
PSingleArrayList = ^TSingleArrayList;
TIntegerArray = array [0..MaxInt shr 3] of Integer;
PIntegerArray = ^TIntegerArray;
PInteger = ^Integer;
TSmallIntArray = array [0..MaxInt shr 2] of SmallInt;
PSmallIntArray = ^TSmallIntArray;
PSmallInt = ^SmallInt;
TShortIntArray = array [0..MaxInt shr 2] of ShortInt;
PShortIntArray = ^TShortIntArray;
PShortInt = ^ShortInt;
TSingleList = class
private
FItemSize : Integer;
FCount : Integer;
FCapacity : Integer;
FGrowthDelta : Integer;
FBufferItem : PByteArray;
FList : PSingleArrayList;
protected
procedure SetCount(val : Integer);
function Get(Index: Integer) : Single;
procedure Put(Index: Integer; const item : Single);
procedure SetCapacity(NewCapacity: Integer);
public
constructor Create;
procedure Delete(index: Integer);
function Add(const item : Single) : Integer;
procedure Push(const val : Single);
function Pop : Single;
function push_back(v:single):integer;
procedure Flush;
procedure Clear;
procedure Insert(Index : Integer; const item : Single);
property Items[Index: Integer] : Single read Get write Put; default;
property List : PSingleArrayList read FList;
property Count : Integer read FCount write SetCount;
property Capacity : Integer read FCapacity write SetCapacity;
property GrowthDelta : Integer read FGrowthDelta write FGrowthDelta;
end;
TIntegerList = class
private
FItemSize : Integer;
FCount : Integer;
FCapacity : Integer;
FGrowthDelta : Integer;
FBufferItem : PByteArray;
FList : PIntegerArray;
protected
procedure SetCount(val : Integer);
function Get(Index: Integer) : Integer;
procedure Put(Index: Integer; const item : Integer);
procedure SetCapacity(NewCapacity: Integer);
public
constructor Create;
procedure Delete(index: Integer);
function Add(const item : Integer) : Integer;
procedure Push(const val : Integer);
function Pop : Integer;
procedure Flush;
procedure Clear;
function push_back(v:integer):integer;
procedure Insert(Index : Integer; const item : Integer);
property Items[Index: Integer] : Integer read Get write Put; default;
property List : PIntegerArray read FList;
property Count : Integer read FCount write SetCount;
property Capacity : Integer read FCapacity write SetCapacity;
property GrowthDelta : Integer read FGrowthDelta write FGrowthDelta;
end;
implementation
// ------------------
// ------------------ TSingleList ------------------
// ------------------
// Create
//
constructor TSingleList.Create;
begin
FItemSize:=SizeOf(Single);
FGrowthDelta:=16;
inherited Create;
end;
procedure TSingleList.SetCount(val : Integer);
begin
Assert(val>=0);
if val>FCapacity then SetCapacity(val);
// if (val>FCount) then
// FillChar(FList[FItemSize*FCount], (val-FCount)*FItemSize, 0);
//if (val>FCount) and (bloSetCountResetsMemory in FOptions) then
// FillChar(FBaseList[FItemSize*FCount], (val-FCount)*FItemSize, 0);
FCount:=val;
end;
// Add
//
function TSingleList.Add(const item : Single): Integer;
begin
Result:=FCount;
if Result=FCapacity then SetCapacity(FCapacity+FGrowthDelta);
FList[Result]:=Item;
Inc(FCount);
end;
function TSingleList.push_back(v:single):integer;
begin
result:=add(v);
end;
// Get
//
function TSingleList.Get(Index : Integer) : Single;
begin
{$IFOPT R+}
Assert(Cardinal(Index)<Cardinal(FCount));
{$endif}
Result := FList[Index];
end;
// Insert
//
procedure TSingleList.Insert(Index : Integer; const Item : Single);
begin
{$IFOPT R+}
Assert(Cardinal(Index)<Cardinal(FCount));
{$ENDIF}
if FCount=FCapacity then SetCapacity(FCapacity+FGrowthDelta);
if Index<FCount then
System.Move(FList[Index], FList[Index + 1],
(FCount-Index)*SizeOf(Single));
FList[Index]:=Item;
Inc(FCount);
end;
procedure TSingleList.Flush;
begin
if Assigned(Self) then begin
SetCount(0);
end;
end;
// Clear
//
procedure TSingleList.Clear;
begin
if Assigned(Self) then begin
SetCount(0);
SetCapacity(0);
end;
end;
// Put
//
procedure TSingleList.Put(Index : Integer; const Item : Single);
begin
{$IFOPT R+}
Assert(Cardinal(Index)<Cardinal(FCount));
{$ENDIF}
FList[Index] := Item;
end;
// SetCapacity
//
procedure TSingleList.SetCapacity(NewCapacity : Integer);
begin
inherited;
// FList:=PSingleArrayList(NewCapacity);
ReallocMem(FList, newCapacity*FItemSize);
FCapacity:=newCapacity;
end;
// Push
//
procedure TSingleList.Push(const val : Single);
begin
Add(val);
end;
procedure TSingleList.Delete(index: Integer);
begin
{$IFOPT R+}
Assert(Cardinal(index)<Cardinal(FCount));
{$ENDIF}
Dec(FCount);
if index<FCount then
System.Move(FList[(index+1)*FItemSize],
FList[index*FItemSize],
(FCount-index)*FItemSize);
end;
// Pop
//
function TSingleList.Pop : Single;
begin
if FCount>0 then begin
Result:=Get(FCount-1);
Delete(FCount-1);
end else Result:=0;
end;
// ------------------
// ------------------ TIntegerList ------------------
// ------------------
// Create
//
constructor TIntegerList.Create;
begin
FItemSize:=SizeOf(Single);
FGrowthDelta:=16;
inherited Create;
end;
procedure TIntegerList.SetCount(val : Integer);
begin
Assert(val>=0);
if val>FCapacity then SetCapacity(val);
// if (val>FCount) then
// FillChar(FList[FItemSize*FCount], (val-FCount)*FItemSize, 0);
//if (val>FCount) and (bloSetCountResetsMemory in FOptions) then
// FillChar(FBaseList[FItemSize*FCount], (val-FCount)*FItemSize, 0);
FCount:=val;
end;
// Add
//
function TIntegerList.Add(const item : integer): Integer;
begin
Result:=FCount;
if Result=FCapacity then SetCapacity(FCapacity+FGrowthDelta);
FList[Result]:=Item;
Inc(FCount);
end;
// Get
//
function TIntegerList.Get(Index : Integer) : integer;
begin
{$IFOPT R+}
Assert(Cardinal(Index)<Cardinal(FCount));
{$endif}
Result := FList[Index];
end;
// Insert
//
procedure TIntegerList.Insert(Index : Integer; const Item : integer);
begin
{$IFOPT R+}
Assert(Cardinal(Index)<Cardinal(FCount));
{$ENDIF}
if FCount=FCapacity then SetCapacity(FCapacity+FGrowthDelta);
if Index<FCount then
System.Move(FList[Index], FList[Index + 1],
(FCount-Index)*SizeOf(Single));
FList[Index]:=Item;
Inc(FCount);
end;
// Put
//
procedure TIntegerList.Put(Index : Integer; const Item : integer);
begin
{$IFOPT R+}
Assert(Cardinal(Index)<Cardinal(FCount));
{$ENDIF}
FList[Index] := Item;
end;
// SetCapacity
//
procedure TIntegerList.SetCapacity(NewCapacity : Integer);
begin
inherited;
// FList:=PSingleArrayList(NewCapacity);
ReallocMem(FList, newCapacity*FItemSize);
FCapacity:=newCapacity;
end;
// Push
//
procedure TIntegerList.Push(const val : integer);
begin
Add(val);
end;
procedure TIntegerList.Delete(index: Integer);
begin
{$IFOPT R+}
Assert(Cardinal(index)<Cardinal(FCount));
{$ENDIF}
Dec(FCount);
if index<FCount then
System.Move(FList[(index+1)*FItemSize],
FList[index*FItemSize],
(FCount-index)*FItemSize);
end;
procedure TIntegerList.Flush;
begin
if Assigned(Self) then begin
SetCount(0);
end;
end;
// Clear
//
procedure TIntegerList.Clear;
begin
if Assigned(Self) then begin
SetCount(0);
SetCapacity(0);
end;
end;
function TIntegerList.push_back(v:integer):integer;
begin
result:=add(v);
end;
// Pop
//
function TIntegerList.Pop : integer;
begin
if FCount>0 then
begin
Result:=Get(FCount-1);
Delete(FCount-1);
end else Result:=0;
end;
end.
|
{
GMRectangle unit
ES: contiene las clases bases necesarias para mostrar rectángulos en un mapa de
Google Maps mediante el componente TGMMap
EN: includes the base classes needed to show rectangles on Google Map map using
the component TGMMap
=========================================================================
MODO DE USO/HOW TO USE
ES: poner el componente en el formulario, linkarlo a un TGMMap y poner los
rectángulos a mostrar
EN: put the component into a form, link to a TGMMap and put the rectangles to
show
=========================================================================
History:
ver 1.0.0
ES:
cambio: el método TCustomRectangle.GetCenter pasa a ser un procedure.
nuevo: TCustomRectangle -> ZoomToPoints, establece el zoom óptimo para visualizar
el rectánglo.
EN:
change: TCustomRectangle.GetCenter method becomes a procedure.
new: TCustomRectangle -> ZoomToPoints, sets the optimal zoom to display the rectangle.
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
EN:
new: documentation
new: now compatible with FireMonkey
ver 0.1.7
ES:
cambio: modificados métodos Set y ShowElement para que usen el nuevo método
ChangeProperties heredado de TLinkedComponent
EN:
change: modified all Set and ShowElements methods to use the new method
ChangeProperties inherited from TLinkedComponent
ver 0.1.5
ES:
nuevo: TRectangle -> añadido método GetCenter
EN:
new: TRectangle -> GetCenter method added
ver 0.1.4
ES:
cambio: cambio en el JavaScript de algunos métodos Set
EN:
change: JavaScript changed from some Set methods
ver 0.1.3
ES: primera versión
EN: first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2012, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
The GMRectangle unit includes the base classes needed to show rectangles on Google Map map using the component TGMMap.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La unit GMRectangle contiene las clases bases necesarias para mostrar rectángulos en un mapa de Google Maps mediante el componente TGMMap
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
unit GMRectangle;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
GMLinkedComponents, GMClasses, GMConstants;
type
{*------------------------------------------------------------------------------
Base class for rectangles.
More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#Rectangle
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para los rectángulos.
Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#Rectangle
-------------------------------------------------------------------------------}
TCustomRectangle = class(TLinkedComponent)
private
{*------------------------------------------------------------------------------
If this rectangle is visible on the map.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si el rectángulo está visible en el mapa.
-------------------------------------------------------------------------------}
FVisible: Boolean;
{*------------------------------------------------------------------------------
The rectangle bounds.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Límites del rectángulo.
-------------------------------------------------------------------------------}
FBounds: TLatLngBounds;
{*------------------------------------------------------------------------------
The stroke width in pixels.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Anchura del trazo en píxeles.
-------------------------------------------------------------------------------}
FStrokeWeight: Integer;
{*------------------------------------------------------------------------------
The fill opacity between 0.0 and 1.0.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Opacidad del relleno con valores entre 0.0 y 1.0.
-------------------------------------------------------------------------------}
FFillOpacity: Real;
{*------------------------------------------------------------------------------
Indicates whether this rectangle handles mouse events.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Indica si este rentángulo recivirá eventos del ratón.
-------------------------------------------------------------------------------}
FClickable: Boolean;
{*------------------------------------------------------------------------------
The stroke opacity between 0.0 and 1.0.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Opacidad del trazo con valores entre 0.0 y 1.0.
-------------------------------------------------------------------------------}
FStrokeOpacity: Real;
{*------------------------------------------------------------------------------
If set to true, the user can edit this rectangle by dragging the control points shown at the corners and on each edge.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece a true, el usuario puede editar este rectángulo desplazando el control mediantes los puntos mostrados en las esquinas y en cada lado.
-------------------------------------------------------------------------------}
FEditable: Boolean;
FIsBoundsUpdt: Boolean;
procedure SetClickable(const Value: Boolean);
procedure SetEditable(const Value: Boolean);
procedure SetFillOpacity(const Value: Real);
procedure SetStrokeOpacity(const Value: Real);
procedure SetStrokeWeight(const Value: Integer);
procedure SetVisible(const Value: Boolean);
procedure OnChangeBounds(Sender: TObject);
protected
{*------------------------------------------------------------------------------
This method returns the assigned color to the FillColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad FillColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetFillColor: string; virtual; abstract;
{*------------------------------------------------------------------------------
This method returns the assigned color to the StrokeColor property defined into its descendents.
@return String with the color in RGB format
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Método que devuelve el color asignado a la propiedad StrokeColor definida en los descendientes.
@return Cadena con el color en formato RGB
-------------------------------------------------------------------------------}
function GetStrokeColor: string; virtual; abstract;
function ChangeProperties: Boolean; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
{*------------------------------------------------------------------------------
Sets the optimal zoom to display the rectangle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Establece el zoom óptimo para visualizar el rectángulo.
-------------------------------------------------------------------------------}
procedure ZoomToPoints;
{*------------------------------------------------------------------------------
Converts to string the four points of the rectangle. The points are separated by semicolon (;) and the coordinates (lat/lng) by a pipe (|).
@return String with conversion.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Convierte en una cadena los cuatro puntos del rectángulo. Los puntos están separados por punto y coma (;) y las coordenadas (lat/lng) separados por una barra vertical (|).
@return Cadena con la conversión.
-------------------------------------------------------------------------------}
function GetStrPath: string;
{*------------------------------------------------------------------------------
Returns the area of a closed path. The computed area uses the same units as the Radius. The radius defaults to the Earth's radius in meters, in which case the area is in square meters.
@param Radius Radius to use.
@return Area.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve el area de una ruta cerrada. El area calculada usa las mismas unidades que Radius. El radio por defecto es el radio de la Tierra en metros, en cuyo caso el área es en metros cuadrados.
@param Radius Radio a usar.
@return Area.
-------------------------------------------------------------------------------}
function ComputeArea(Radius: Real = -1): Real;
{*------------------------------------------------------------------------------
Returns the center of the rectangle.
@param LL TLatLng with the center of the rectangle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve el centro del rectángulo.
@param LL TLatLng con el centro del rectángulo.
-------------------------------------------------------------------------------}
procedure GetCenter(LL: TLatLng);
procedure CenterMapTo; override;
published
property Bounds: TLatLngBounds read FBounds write FBounds;
property Clickable: Boolean read FClickable write SetClickable default True;
property Editable: Boolean read FEditable write SetEditable default False;
property FillOpacity: Real read FFillOpacity write SetFillOpacity; // 0 to 1
property StrokeOpacity: Real read FStrokeOpacity write SetStrokeOpacity; // 0 to 1
property StrokeWeight: Integer read FStrokeWeight write SetStrokeWeight default 2; // 1 to 10
property Visible: Boolean read FVisible write SetVisible default True;
{*------------------------------------------------------------------------------
InfoWindows associated object.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
InfoWindows asociado al objeto.
-------------------------------------------------------------------------------}
property InfoWindow;
{*------------------------------------------------------------------------------
This property is used, if applicable, to establish the name that appears in the collection editor.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Esta propiedad se usa, si procede, para establecer el nombre que aparece en el editor de la colección.
-------------------------------------------------------------------------------}
property Text;
end;
{*------------------------------------------------------------------------------
Base class for rectangles collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para la colección de rectángulos.
-------------------------------------------------------------------------------}
TCustomRectangles = class(TLinkedComponents)
private
procedure SetItems(I: Integer; const Value: TCustomRectangle);
function GetItems(I: Integer): TCustomRectangle;
protected
function GetOwner: TPersistent; override;
public
function Add: TCustomRectangle;
function Insert(Index: Integer): TCustomRectangle;
{*------------------------------------------------------------------------------
Lists the rectangles in the collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de rectángulos en la colección.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TCustomRectangle read GetItems write SetItems; default;
end;
{*------------------------------------------------------------------------------
Base class for GMRectangle component.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para el componente GMRectangle.
-------------------------------------------------------------------------------}
TCustomGMRectangle = class(TGMLinkedComponent)
private
{*------------------------------------------------------------------------------
This event is fired when the rectangle's StrokeColor property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad StrokeColor de un rectángulo.
-------------------------------------------------------------------------------}
FOnStrokeColorChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when a rectangle is right-clicked on.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando en un rectángulo se pulsa el botón derecho del ratón.
-------------------------------------------------------------------------------}
FOnRightClick: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired for a mousedown on the rectangle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara al pulsar en el rentángulo.
-------------------------------------------------------------------------------}
FOnMouseDown: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the rectangle's Visible property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad Visible de un rectángulo.
-------------------------------------------------------------------------------}
FOnVisibleChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when mousemove on the rectangle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el ratón se mueve por encima del rectángulo.
-------------------------------------------------------------------------------}
FOnMouseMove: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the rectangle's StrokeWeight property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad StrokeWeight de un rectángulo.
-------------------------------------------------------------------------------}
FOnStrokeWeightChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired for a mouseup on the rectangle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara al soltar el rectángulo.
-------------------------------------------------------------------------------}
FOnMouseUp: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the rectangle's FillOpacity property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad FillOpacity de un rectángulo.
-------------------------------------------------------------------------------}
FOnFillOpacityChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the rectangle's Clickable property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad Clickable de un rectángulo.
-------------------------------------------------------------------------------}
FOnClickableChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired on rectangle mouseout.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el ratón sale del rectángulo.
-------------------------------------------------------------------------------}
FOnMouseOut: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the rectangle's StrokeOpacity property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad StrokeOpacity de un rectángulo.
-------------------------------------------------------------------------------}
FOnStrokeOpacityChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the rectangle's Editable property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad Editable de un rectángulo.
-------------------------------------------------------------------------------}
FOnEditableChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event is fired when the rectangle's bounds are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambian los límites de un rectángulo.
-------------------------------------------------------------------------------}
FOnBoundsChanged: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event occurs when the user double-clicks a rectangle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando el usuario hace doble click un rectángulo.
-------------------------------------------------------------------------------}
FOnDblClick: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the mouse enters the area of the rectangle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento se dispara cuando el ratón entra en el área del rectángulo.
-------------------------------------------------------------------------------}
FOnMouseOver: TLatLngIdxEvent;
{*------------------------------------------------------------------------------
This event is fired when the rectangle's FillColor property are changed.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando cambia la propiedad FillColor de un rectángulo.
-------------------------------------------------------------------------------}
FOnFillColorChange: TLinkedComponentChange;
{*------------------------------------------------------------------------------
This event occurs when the user click a rectangle.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Este evento ocurre cuando el usuario pulsa un rectángulo.
-------------------------------------------------------------------------------}
FOnClick: TLatLngIdxEvent;
protected
function GetAPIUrl: string; override;
function GetItems(I: Integer): TCustomRectangle;
procedure EventFired(EventType: TEventType; Params: array of const); override;
function GetCollectionItemClass: TLinkedComponentClass; override;
function GetCollectionClass: TLinkedComponentsClass; override;
public
{*------------------------------------------------------------------------------
Creates a new TCustomRectangle instance and adds it to the Items array.
@param SWLat The rectangle's southwest latitude
@param SWLng The rectangle's southwest longitude
@param NELat The rectangle's northeast latitude
@param NELng The rectangle's northeast longitude
@return A new instance of TCustomRectangle
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea una nueva instancia de TCustomRectangle y la añade en el array de Items.
@param SWLat Latitud suroeste del rectángulo
@param SWLng Longitud suroeste del rectángulo
@param NELat Latitud noreste del rectángulo
@param NELng Longitud noreste del rectángulo
@return Una nueva instancia de TCustomRectangle
-------------------------------------------------------------------------------}
function Add(SWLat: Real = 0; SWLng: Real = 0; NELat: Real = 0; NELng: Real = 0): TCustomRectangle;
{*------------------------------------------------------------------------------
Array with the collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con la colección de elementos.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TCustomRectangle read GetItems; default;
published
{*------------------------------------------------------------------------------
Collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Colección de elementos.
-------------------------------------------------------------------------------}
property VisualObjects;
// eventos
// events
// both (map and properties)
property OnBoundsChanged: TLinkedComponentChange read FOnBoundsChanged write FOnBoundsChanged;
// from map
property OnClick: TLatLngIdxEvent read FOnClick write FOnClick;
property OnDblClick: TLatLngIdxEvent read FOnDblClick write FOnDblClick;
property OnMouseDown: TLatLngIdxEvent read FOnMouseDown write FOnMouseDown;
property OnMouseMove: TLatLngIdxEvent read FOnMouseMove write FOnMouseMove;
property OnMouseOut: TLatLngIdxEvent read FOnMouseOut write FOnMouseOut;
property OnMouseOver: TLatLngIdxEvent read FOnMouseOver write FOnMouseOver;
property OnMouseUp: TLatLngIdxEvent read FOnMouseUp write FOnMouseUp;
property OnRightClick: TLatLngIdxEvent read FOnRightClick write FOnRightClick;
// from properties
property OnClickableChange: TLinkedComponentChange read FOnClickableChange write FOnClickableChange;
property OnEditableChange: TLinkedComponentChange read FOnEditableChange write FOnEditableChange;
property OnFillColorChange: TLinkedComponentChange read FOnFillColorChange write FOnFillColorChange;
property OnFillOpacityChange: TLinkedComponentChange read FOnFillOpacityChange write FOnFillOpacityChange;
property OnStrokeColorChange: TLinkedComponentChange read FOnStrokeColorChange write FOnStrokeColorChange;
property OnStrokeOpacityChange: TLinkedComponentChange read FOnStrokeOpacityChange write FOnStrokeOpacityChange;
property OnStrokeWeightChange: TLinkedComponentChange read FOnStrokeWeightChange write FOnStrokeWeightChange;
property OnVisibleChange: TLinkedComponentChange read FOnVisibleChange write FOnVisibleChange;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.SysUtils,
{$ELSE}
SysUtils,
{$ENDIF}
Lang, GMFunctions;
{ TCustomGMRectangle }
function TCustomGMRectangle.Add(SWLat, SWLng, NELat, NELng: Real): TCustomRectangle;
begin
Result := TCustomRectangle(inherited Add);
Result.Bounds.SW.Lat := SWLat;
Result.Bounds.SW.Lng := SWLng;
Result.Bounds.NE.Lat := NELat;
Result.Bounds.NE.Lng := NELng;
end;
procedure TCustomGMRectangle.EventFired(EventType: TEventType;
Params: array of const);
var
LL: TLatLng;
OldEvent: TNotifyEvent;
begin
inherited;
if EventType = etInfoWinCloseClick then Exit;
if EventType = etRectangleBoundsChange then
begin
if High(Params) <> 4 then
raise Exception.Create(GetTranslateText('Número de parámetros incorrecto', Map.Language));
if (Params[1].VType <> vtExtended) or (Params[2].VType <> vtExtended) or
(Params[3].VType <> vtExtended) or (Params[4].VType <> vtExtended) then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[0].VType <> vtInteger then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[0].VInteger > VisualObjects.Count - 1 then
raise Exception.Create(GetTranslateText('Valor de parámetro incorrecto', Map.Language));
if Items[Params[0].VInteger].FIsBoundsUpdt then
begin
Items[Params[0].VInteger].FIsBoundsUpdt := False;
Exit;
end;
OldEvent := Items[Params[0].VInteger].Bounds.NE.OnChange;
Items[Params[0].VInteger].Bounds.NE.OnChange := nil;
Items[Params[0].VInteger].Bounds.SW.OnChange := nil;
Items[Params[0].VInteger].Bounds.NE.Lat := ControlPrecision(Params[1].VExtended^, GetMapPrecision);
Items[Params[0].VInteger].Bounds.NE.Lng := ControlPrecision(Params[2].VExtended^, GetMapPrecision);
Items[Params[0].VInteger].Bounds.SW.Lat := ControlPrecision(Params[3].VExtended^, GetMapPrecision);
Items[Params[0].VInteger].Bounds.SW.Lng := ControlPrecision(Params[4].VExtended^, GetMapPrecision);
if Assigned(FOnBoundsChanged) then FOnBoundsChanged(Self, Params[0].VInteger, Items[Params[0].VInteger]);
Items[Params[0].VInteger].Bounds.NE.OnChange := OldEvent;
Items[Params[0].VInteger].Bounds.SW.OnChange := OldEvent;
Exit;
end;
if High(Params) <> 2 then
raise Exception.Create(GetTranslateText('Número de parámetros incorrecto', Map.Language));
if (Params[0].VType <> vtExtended) or (Params[1].VType <> vtExtended) then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[2].VType <> vtInteger then
raise Exception.Create(GetTranslateText('Tipo de parámetro incorrecto', Map.Language));
if Params[2].VInteger > VisualObjects.Count - 1 then
raise Exception.Create(GetTranslateText('Valor de parámetro incorrecto', Map.Language));
LL := TLatLng.Create(ControlPrecision(Params[0].VExtended^, GetMapPrecision),
ControlPrecision(Params[1].VExtended^, GetMapPrecision));
try
case EventType of
etRectangleClick: if Assigned(FOnClick) then FOnClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etRectangleDblClick: if Assigned(FOnDblClick) then FOnDblClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etRectangleMouseDown: if Assigned(FOnMouseDown) then FOnMouseDown(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etRectangleMouseMove: if Assigned(FOnMouseMove) then FOnMouseMove(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etRectangleMouseOut: if Assigned(FOnMouseOut) then FOnMouseOut(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etRectangleMouseOver: if Assigned(FOnMouseOver) then FOnMouseOver(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etRectangleMouseUp: if Assigned(FOnMouseUp) then FOnMouseUp(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
etRectangleRightClick: if Assigned(FOnRightClick) then FOnRightClick(Self, LL, Params[2].VInteger, Items[Params[2].VInteger]);
end;
finally
FreeAndNil(LL);
end;
end;
function TCustomGMRectangle.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference?hl=en#Rectangle';
end;
function TCustomGMRectangle.GetCollectionClass: TLinkedComponentsClass;
begin
Result := TCustomRectangles;
end;
function TCustomGMRectangle.GetCollectionItemClass: TLinkedComponentClass;
begin
Result := TCustomRectangle;
end;
function TCustomGMRectangle.GetItems(I: Integer): TCustomRectangle;
begin
Result := TCustomRectangle(inherited Items[i]);
end;
{ TCustomRectangles }
function TCustomRectangles.Add: TCustomRectangle;
begin
Result := TCustomRectangle(inherited Add);
end;
function TCustomRectangles.GetItems(I: Integer): TCustomRectangle;
begin
Result := TCustomRectangle(inherited Items[I]);
end;
function TCustomRectangles.GetOwner: TPersistent;
begin
Result := TCustomGMRectangle(inherited GetOwner);
end;
function TCustomRectangles.Insert(Index: Integer): TCustomRectangle;
begin
Result := TCustomRectangle(inherited Insert(Index));
end;
procedure TCustomRectangles.SetItems(I: Integer; const Value: TCustomRectangle);
begin
inherited SetItem(I, Value);
end;
{ TCustomRectangle }
procedure TCustomRectangle.Assign(Source: TPersistent);
begin
inherited;
if Source is TCustomRectangle then
begin
Bounds.Assign(TCustomRectangle(Source).Bounds);
Clickable := TCustomRectangle(Source).Clickable;
Editable := TCustomRectangle(Source).Editable;
FillOpacity := TCustomRectangle(Source).FillOpacity;
StrokeOpacity := TCustomRectangle(Source).StrokeOpacity;
StrokeWeight := TCustomRectangle(Source).StrokeWeight;
Visible := TCustomRectangle(Source).Visible;
end;
end;
procedure TCustomRectangle.CenterMapTo;
var
LL: TLatLng;
begin
inherited;
if Assigned(Collection) and (Collection is TCustomRectangles) and
Assigned(TCustomRectangles(Collection).FGMLinkedComponent) and
Assigned(TCustomRectangles(Collection).FGMLinkedComponent.Map) then
begin
LL := TLatLng.Create;
try
GetCenter(LL);
TCustomRectangles(Collection).FGMLinkedComponent.Map.SetCenter(LL.Lat, LL.Lng);
finally
if Assigned(LL) then FreeAndNil(LL);
end;
end;
end;
function TCustomRectangle.ChangeProperties: Boolean;
const
StrParams = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s';
var
Params: string;
begin
inherited;
Result := False;
if not Assigned(Collection) or not(Collection is TCustomRectangles) or
not Assigned(TCustomRectangles(Collection).FGMLinkedComponent) or
//not TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).AutoUpdate or
not Assigned(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).Map) or
(csDesigning in TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).ComponentState) then
Exit;
Params := Format(StrParams, [
IntToStr(IdxList),
LowerCase(TCustomTransform.GMBoolToStr(Clickable, True)),
LowerCase(TCustomTransform.GMBoolToStr(Editable, True)),
QuotedStr(GetFillColor),
StringReplace(FloatToStr(FillOpacity), ',', '.', [rfReplaceAll]),
QuotedStr(GetStrokeColor),
StringReplace(FloatToStr(StrokeOpacity), ',', '.', [rfReplaceAll]),
IntToStr(StrokeWeight),
LowerCase(TCustomTransform.GMBoolToStr(Visible, True)),
Bounds.SW.LatToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.SW.LngToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.NE.LatToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.NE.LngToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
IntToStr(Index),
QuotedStr(InfoWindow.GetConvertedString),
LowerCase(TCustomTransform.GMBoolToStr(InfoWindow.DisableAutoPan, True)),
IntToStr(InfoWindow.MaxWidth),
IntToStr(InfoWindow.PixelOffset.Height),
IntToStr(InfoWindow.PixelOffset.Width),
LowerCase(TCustomTransform.GMBoolToStr(InfoWindow.CloseOtherBeforeOpen, True))
]);
Result := TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).ExecuteScript('MakeRectangle', Params);
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).ErrorControl;
end;
function TCustomRectangle.ComputeArea(Radius: Real): Real;
begin
Result := TGeometry.ComputeArea(TCustomRectangles(Collection).FGMLinkedComponent.Map, GetStrPath, Radius);
end;
constructor TCustomRectangle.Create(Collection: TCollection);
begin
inherited;
FBounds := TLatLngBounds.Create;
Bounds.NE.OnChange := OnChangeBounds;
Bounds.SW.OnChange := OnChangeBounds;
FClickable := True;
FEditable := False;
FFillOpacity := 0.5;
FStrokeOpacity := 1;
FStrokeWeight := 2;
FVisible := True;
FIsBoundsUpdt := False;
end;
destructor TCustomRectangle.Destroy;
begin
if Assigned(FBounds) then FreeAndNil(FBounds);
inherited;
end;
procedure TCustomRectangle.GetCenter(LL: TLatLng);
const
StrParams = '%s,%s';
var
Params: string;
begin
if not Assigned(LL) then Exit;
if not Assigned(Collection) or not (Collection is TCustomRectangles) or
not Assigned(TCustomRectangles(Collection).FGMLinkedComponent) or
not Assigned(TCustomRectangles(Collection).FGMLinkedComponent.Map) then
Exit;
Params := Format(StrParams, [IntToStr(IdxList), IntToStr(Index)]);
if not TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).ExecuteScript('RectangleGetCenter', Params) then
Exit;
LL.Lat := TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetFloatField(RectangleForm, RectangleFormLat);
LL.Lng := TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetFloatField(RectangleForm, RectangleFormLng);
end;
function TCustomRectangle.GetStrPath: string;
const
Tmp = '%s|%s;%s|%s;%s|%s;%s|%s';
begin
Result := Format(Tmp, [
Bounds.NE.LatToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.NE.LngToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.NE.LatToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.SW.LngToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.SW.LatToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.SW.LngToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.SW.LatToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision),
Bounds.NE.LngToStr(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).GetMapPrecision)
]);
end;
procedure TCustomRectangle.OnChangeBounds(Sender: TObject);
begin
ChangeProperties;
if Assigned(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnBoundsChanged) then
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnBoundsChanged(
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomRectangle.SetClickable(const Value: Boolean);
begin
if FClickable = Value then Exit;
FClickable := Value;
ChangeProperties;
if Assigned(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnClickableChange) then
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnClickableChange(
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomRectangle.SetEditable(const Value: Boolean);
begin
if FEditable = Value then Exit;
FEditable := Value;
SetProperty('SetEditable', 'OnEditableChange', FEditable);
{ ChangeProperties;
if Assigned(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnEditableChange) then
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnEditableChange(
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent),
Index,
Self);}
end;
procedure TCustomRectangle.SetFillOpacity(const Value: Real);
begin
if FFillOpacity = Value then Exit;
FFillOpacity := Value;
if FFillOpacity < 0 then FFillOpacity := 0;
if FFillOpacity > 1 then FFillOpacity := 1;
FFillOpacity := Trunc(FFillOpacity * 100) / 100;
ChangeProperties;
if Assigned(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnFillOpacityChange) then
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnFillOpacityChange(
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomRectangle.SetStrokeOpacity(const Value: Real);
begin
if FStrokeOpacity = Value then Exit;
FStrokeOpacity := Value;
if FStrokeOpacity < 0 then FStrokeOpacity := 0;
if FStrokeOpacity > 1 then FStrokeOpacity := 1;
FStrokeOpacity := Trunc(FStrokeOpacity * 100) / 100;
ChangeProperties;
if Assigned(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnStrokeOpacityChange) then
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnStrokeOpacityChange(
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomRectangle.SetStrokeWeight(const Value: Integer);
begin
if FStrokeWeight = Value then Exit;
FStrokeWeight := Value;
if FStrokeWeight < 1 then FStrokeWeight := 1;
if FStrokeWeight > 10 then FStrokeWeight := 10;
ChangeProperties;
if Assigned(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnStrokeWeightChange) then
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnStrokeWeightChange(
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomRectangle.SetVisible(const Value: Boolean);
begin
if FVisible = Value then Exit;
FVisible := Value;
ChangeProperties;
if Assigned(TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnVisibleChange) then
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent).FOnVisibleChange(
TCustomGMRectangle(TCustomRectangles(Collection).FGMLinkedComponent),
Index,
Self);
end;
procedure TCustomRectangle.ZoomToPoints;
var
Points: array of TLatLng;
begin
if not Assigned(Collection) or not (Collection is TCustomRectangles) or
not Assigned(TCustomRectangles(Collection).FGMLinkedComponent) or
not Assigned(TCustomRectangles(Collection).FGMLinkedComponent.Map) then
Exit;
SetLength(Points, 2);
Points[0] := Bounds.SW;
Points[1] := Bounds.NE;
TCustomRectangles(Collection).FGMLinkedComponent.Map.ZoomToPoints(Points);
end;
end.
|
unit fTimeout;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fAutoSz, ExtCtrls, StdCtrls, ORFn, VA508AccessibilityManager;
type
TfrmTimeout = class(TfrmAutoSz)
timCountDown: TTimer;
pnlTop: TPanel;
Label1: TStaticText;
Label2: TStaticText;
pnlBottom: TPanel;
btnClose: TButton;
cmdContinue: TButton;
lblCount: TStaticText;
pnlWarning: TPanel;
imgWarning: TImage;
lblWarning: TLabel;
lblWarningMultiple: TLabel;
lblWarningContinue: TLabel;
lblWarningPatient: TLabel;
procedure FormCreate(Sender: TObject);
procedure cmdContinueClick(Sender: TObject);
procedure timCountDownTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
{ Private declarations }
FContinue: Boolean;
FCount: Integer;
end;
function AllowTimeout: Boolean;
implementation
{$R *.DFM}
uses uCore;
function AllowTimeout: Boolean;
var
frmTimeout: TfrmTimeout;
begin
frmTimeout := TfrmTimeout.Create(Application);
try
ResizeFormToFont(TForm(frmTimeout));
frmTimeout.ShowModal;
Result := not frmTimeout.FContinue;
finally
frmTimeout.Release;
end;
end;
procedure TfrmTimeout.FormCreate(Sender: TObject);
begin
inherited;
Application.Restore;
Application.BringToFront;
MessageBeep(MB_ICONASTERISK);
FCount := User.CountDown;
lblCount.Caption := IntToStr(FCount);
end;
procedure TfrmTimeout.FormShow(Sender: TObject);
begin
inherited;
SetForegroundWindow(Handle);
lblWarningPatient.Caption := Patient.Name;
lblWarning.Font.Size := lblWarningPatient.Font.Size + 4;
if CPRSInstances < 2 then
begin
pnlWarning.Visible := false;
Height := Height - pnlWarning.Height;
end;
end;
procedure TfrmTimeout.btnCloseClick(Sender: TObject);
begin
inherited;
FContinue := False;
Close;
end;
procedure TfrmTimeout.cmdContinueClick(Sender: TObject);
begin
inherited;
FContinue := True;
Close;
end;
procedure TfrmTimeout.timCountDownTimer(Sender: TObject);
begin
inherited;
if FCount = User.CountDown then
begin
MessageBeep(MB_ICONASTERISK);
timCountDown.Enabled := False;
timCountDown.Interval := 1000;
timCountDown.Enabled := True;
end;
Dec(FCount);
lblCount.Caption := IntToStr(FCount);
if FCount < 1 then
begin
timCountDown.Enabled := False;
Close;
end;
end;
end.
|
unit NtUtils.Objects;
interface
{$WARN SYMBOL_PLATFORM OFF}
uses
Winapi.WinNt, Ntapi.ntdef, Ntapi.ntobapi, NtUtils.Exceptions,
DelphiUtils.AutoObject;
type
IHandle = DelphiUtils.AutoObject.IHandle;
TAutoHandle = class(TCustomAutoHandle, IHandle)
destructor Destroy; override;
end;
TObjectBasicInformaion = Ntapi.ntobapi.TObjectBasicInformaion;
TObjectTypeInfo = record
TypeName: String;
Other: TObjectTypeInformation;
end;
// Close a handle safely and set it to zero
function NtxSafeClose(var hObject: THandle): NTSTATUS;
// Duplicate handle to an object. Supports MAXIMUM_ALLOWED.
function NtxDuplicateObject(SourceProcessHandle: THandle;
SourceHandle: THandle; TargetProcessHandle: THandle;
out TargetHandle: THandle; DesiredAccess: TAccessMask;
HandleAttributes: Cardinal; Options: Cardinal): TNtxStatus;
// Duplicate a handle from a process
function NtxDuplicateObjectFrom(hProcess: THandle; hRemoteHandle: THandle;
out hxLocalHandle: IHandle; HandleAttributes: Cardinal = 0): TNtxStatus;
// Duplicate a handle to a process
function NtxDuplicateObjectTo(hProcess: THandle; hLocalHandle: THandle;
out hRemoteHandle: THandle; HandleAttributes: Cardinal = 0): TNtxStatus;
// Duplicate a local handle
function NtxDuplicateObjectLocal(SourceHandle: THandle;
out hxNewHandle: IHandle; DesiredAccess: TAccessMask;
HandleAttributes: Cardinal = 0): TNtxStatus;
// Closes a handle in a process
function NtxCloseRemoteHandle(hProcess: THandle; hObject: THandle): TNtxStatus;
// Query name of an object
function NtxQueryNameObject(hObject: THandle; out Name: String): TNtxStatus;
// Query basic information about an object
function NtxQueryBasicInfoObject(hObject: THandle;
out Info: TObjectBasicInformaion): TNtxStatus;
// Query object type information
function NtxQueryTypeObject(hObject: THandle;
out Info: TObjectTypeInfo): TNtxStatus;
// Wait for an object to enter signaled state
function NtxWaitForSingleObject(hObject: THandle; Timeout: Int64 = NT_INFINITE;
Alertable: Boolean = False): TNtxStatus;
// Wait for any/all objects to enter a signaled state
function NtxWaitForMultipleObjects(Objects: TArray<THandle>; WaitType:
TWaitType; Timeout: Int64 = NT_INFINITE; Alertable: Boolean = False)
: TNtxStatus;
implementation
uses
Ntapi.ntstatus, Ntapi.ntpsapi, System.SysUtils;
destructor TAutoHandle.Destroy;
begin
if FAutoRelease then
NtxSafeClose(FHandle);
inherited;
end;
function NtxSafeClose(var hObject: THandle): NTSTATUS;
begin
if hObject > MAX_HANDLE then
Exit(STATUS_INVALID_HANDLE);
Result := STATUS_UNSUCCESSFUL;
try
// NtClose can raise errors, we should capture them
Result := NtClose(hObject);
except
on E: EExternalException do
if Assigned(E.ExceptionRecord) then
Result := E.ExceptionRecord.ExceptionCode;
end;
// Log failed close attempts
if not NT_SUCCESS(Result) then
ENtError.Report(Result, 'NtClose 0x' + IntToHex(hObject, 0));
// Prevent future use
hObject := 0;
end;
function NtxDuplicateObject(SourceProcessHandle: THandle;
SourceHandle: THandle; TargetProcessHandle: THandle;
out TargetHandle: THandle; DesiredAccess: TAccessMask;
HandleAttributes: Cardinal; Options: Cardinal): TNtxStatus;
var
hSameAccess, hTemp: THandle;
objInfo: TObjectBasicInformaion;
handleInfo: TObjectHandleFlagInformation;
bit: Integer;
label
MaskExpandingDone;
begin
// NtDuplicateObject does not support MAXIMUM_ALLOWED (it returns zero
// access instead). We will implement this feature by probing additional
// access masks.
Result.Location := 'NtDuplicateObject';
Result.LastCall.Expects(PROCESS_DUP_HANDLE, @ProcessAccessType);
if (DesiredAccess = MAXIMUM_ALLOWED) and
(Options and DUPLICATE_SAME_ACCESS = 0) then
begin
// To prevent race conditions we duplicate the handle to the current process
// with the same access and attributes to perform all further probing on it.
// This operation might close the source handle if DUPLICATE_CLOSE_SOURCE is
// specified.
Result.Status := NtDuplicateObject(SourceProcessHandle, SourceHandle,
NtCurrentProcess, hSameAccess, 0, HandleAttributes,
Options or DUPLICATE_SAME_ACCESS);
// If we can't do it we are finished
if not Result.IsSuccess then
Exit;
// Start probing. Try full access first.
DesiredAccess := STANDARD_RIGHTS_ALL or SPECIFIC_RIGHTS_ALL;
Result.Status := NtDuplicateObject(NtCurrentProcess, hSameAccess,
NtCurrentProcess, hTemp, DesiredAccess, 0, 0);
// Was the guess correct?
if Result.IsSuccess then
begin
NtxSafeClose(hTemp);
goto MaskExpandingDone;
end;
// Did something else happen?
if Result.Status <> STATUS_ACCESS_DENIED then
Exit;
// Query what access we already have based on DUPLICATE_SAME_ACCESS flag
if NT_SUCCESS(NtQueryObject(hSameAccess, ObjectBasicInformation, @objInfo,
SizeOf(objInfo), nil)) then
DesiredAccess := objInfo.GrantedAccess and not ACCESS_SYSTEM_SECURITY
else
DesiredAccess := 0;
// Try each one standard or specific access right that is not granted yet
for bit := 0 to 31 do
if ((STANDARD_RIGHTS_ALL or SPECIFIC_RIGHTS_ALL) and (1 shl bit)
and not DesiredAccess) <> 0 then
if NT_SUCCESS(NtDuplicateObject(NtCurrentProcess, hSameAccess,
NtCurrentProcess, hTemp, (1 shl bit), 0, 0)) then
begin
// Yes, this access can be granted, add it
DesiredAccess := DesiredAccess or (1 shl bit);
NtxSafeClose(hTemp);
end;
// Finally, duplicate the handle to the target process with the requested
// attributes and expanded maximum access
MaskExpandingDone:
Result.Status := NtDuplicateObject(NtCurrentProcess, hSameAccess,
TargetProcessHandle, TargetHandle, DesiredAccess, HandleAttributes,
Options and not DUPLICATE_CLOSE_SOURCE);
// Make sure our copy is closable by clearing protection
if (Options and DUPLICATE_SAME_ATTRIBUTES <> 0) or
(HandleAttributes and OBJ_PROTECT_CLOSE <> 0) then
begin
handleInfo.Inherit := False;
handleInfo.ProtectFromClose := False;
NtSetInformationObject(hSameAccess, ObjectHandleFlagInformation,
@handleInfo, SizeOf(handleInfo));
end;
// Close local copy
NtxSafeClose(hSameAccess);
end
else
begin
// Usual case
Result.Status := NtDuplicateObject(SourceProcessHandle, SourceHandle,
TargetProcessHandle, TargetHandle, DesiredAccess, HandleAttributes,
Options);
end;
end;
function NtxDuplicateObjectFrom(hProcess: THandle; hRemoteHandle: THandle;
out hxLocalHandle: IHandle; HandleAttributes: Cardinal): TNtxStatus;
var
hLocalHandle: THandle;
begin
Result := NtxDuplicateObject(hProcess, hRemoteHandle, NtCurrentProcess,
hLocalHandle, 0, HandleAttributes, DUPLICATE_SAME_ACCESS);
if Result.IsSuccess then
hxLocalHandle := TAutoHandle.Capture(hLocalHandle);
end;
function NtxDuplicateObjectTo(hProcess: THandle; hLocalHandle: THandle;
out hRemoteHandle: THandle; HandleAttributes: Cardinal): TNtxStatus;
begin
Result := NtxDuplicateObject(NtCurrentProcess, hLocalHandle, hProcess,
hRemoteHandle, 0, HandleAttributes, DUPLICATE_SAME_ACCESS);
end;
function NtxDuplicateObjectLocal(SourceHandle: THandle;
out hxNewHandle: IHandle; DesiredAccess: TAccessMask;
HandleAttributes: Cardinal): TNtxStatus;
var
hNewHandle: THandle;
begin
Result := NtxDuplicateObject(NtCurrentProcess, SourceHandle, NtCurrentProcess,
hNewHandle, DesiredAccess, HandleAttributes, 0);
if Result.IsSuccess then
hxNewHandle := TAutoHandle.Capture(hNewHandle);
end;
function NtxCloseRemoteHandle(hProcess: THandle; hObject: THandle): TNtxStatus;
begin
Result.Location := 'NtDuplicateObject';
Result.LastCall.Expects(PROCESS_DUP_HANDLE, @ProcessAccessType);
Result.Status := NtDuplicateObject(hProcess, hObject, 0, THandle(nil^), 0, 0,
DUPLICATE_CLOSE_SOURCE);
end;
function NtxQueryNameObject(hObject: THandle; out Name: String): TNtxStatus;
var
Buffer: PUNICODE_STRING;
BufferSize, Required: Cardinal;
begin
Result.Location := 'NtQueryObject';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(ObjectNameInformation);
Result.LastCall.InfoClassType := TypeInfo(TObjectInformationClass);
// No special handle access required
BufferSize := 0;
repeat
Buffer := AllocMem(BufferSize);
Required := 0;
Result.Status := NtQueryObject(hObject, ObjectNameInformation, Buffer,
BufferSize, @Required);
if not Result.IsSuccess then
FreeMem(Buffer);
until not NtxExpandBuffer(Result, BufferSize, Required);
if not Result.IsSuccess then
Exit;
Name := Buffer.ToString;
FreeMem(Buffer);
end;
function NtxQueryBasicInfoObject(hObject: THandle;
out Info: TObjectBasicInformaion): TNtxStatus;
begin
Result.Location := 'NtQueryObject';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(ObjectBasicInformation);
Result.LastCall.InfoClassType := TypeInfo(TObjectInformationClass);
// No special handle access required
Result.Status := NtQueryObject(hObject, ObjectBasicInformation, @Info,
SizeOf(Info), nil);
end;
function NtxQueryTypeObject(hObject: THandle;
out Info: TObjectTypeInfo): TNtxStatus;
var
Buffer: PObjectTypeInformation;
BufferSize, Required: Cardinal;
begin
Result.Location := 'NtQueryObject';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(ObjectTypeInformation);
Result.LastCall.InfoClassType := TypeInfo(TObjectInformationClass);
// No special handle access required
BufferSize := 0;
repeat
Buffer := AllocMem(BufferSize);
Required := 0;
Result.Status := NtQueryObject(hObject, ObjectTypeInformation, Buffer,
BufferSize, @Required);
if not Result.IsSuccess then
FreeMem(Buffer);
until not NtxExpandBuffer(Result, BufferSize, Required);
if not Result.IsSuccess then
Exit;
if BufferSize >= SizeOf(TObjectTypeInformation) then
begin
// Copy the structure and fix string reference
Info.TypeName := Buffer.TypeName.ToString;
Info.Other := Buffer^;
Info.Other.TypeName.Buffer := PWideChar(Info.TypeName);
end
else
begin
Result.Location := 'NtxQueryTypeObject';
Result.Status := STATUS_INFO_LENGTH_MISMATCH;
end;
FreeMem(Buffer);
end;
function NtxWaitForSingleObject(hObject: THandle; Timeout: Int64;
Alertable: Boolean): TNtxStatus;
begin
Result.Location := 'NtWaitForSingleObject';
Result.LastCall.Expects(SYNCHRONIZE, @NonSpecificAccessType);
Result.Status := NtWaitForSingleObject(hObject, Alertable,
Int64ToLargeInteger(Timeout));
end;
function NtxWaitForMultipleObjects(Objects: TArray<THandle>; WaitType:
TWaitType; Timeout: Int64; Alertable: Boolean): TNtxStatus;
begin
Result.Location := 'NtWaitForMultipleObjects';
Result.LastCall.Expects(SYNCHRONIZE, @NonSpecificAccessType);
Result.Status := NtWaitForMultipleObjects(Length(Objects), Objects,
WaitType, Alertable, Int64ToLargeInteger(Timeout));
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.DlgPushWhereU;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.JSON, FMX.StdCtrls, FMX.Layouts, FMX.ListBox,
System.Generics.Collections, FMX.ListView.Types, FMX.ListView,
FMX.ListView.Appearances,
RSSetUp.QueryU, FMX.Controls.Presentation, FMX.ListView.Adapters.Base;
type
TDlgPushWhere = class(TForm)
GroupBox1: TGroupBox;
RadioButtonAll: TRadioButton;
RadioButtonIOS: TRadioButton;
RadioButtonAndroid: TRadioButton;
GroupBox2: TGroupBox;
CheckBoxAllDevices: TCheckBox;
ButtonOK: TButton;
ButtonCancel: TButton;
ListView1: TListView;
Layout1: TLayout;
procedure ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure RadioButtonAllChange(Sender: TObject);
procedure CheckBoxAllDevicesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
public type
TDevice = record
DeviceToken: string;
DeviceType: string;
Channels: TArray<string>;
public
constructor Create(const ADeviceToken, ADeviceType: string;
const AChannels: TArray<string>);
end;
TDevices = TArray<TDevice>;
private
FChecking: Boolean;
FDevices: TDevices;
FDeviceTokens: TDictionary<string, Boolean>;
FFilters: TFilters;
procedure ListCheckDeviceTokens;
procedure CheckDeviceType(const ADeviceType: string);
procedure SetDevices(const Value: TDevices);
procedure ListDevices;
// procedure UpdateDeviceTokens(const AArray: TJSONArray); overload;
procedure UpdateDeviceTokens(const AArray: TArray<string>); overload;
procedure UpdateCheckBoxAllDevices;
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Load(const AJSONQuery: TJSONObject);
procedure Save(const AJSONQuery: TJSONObject);
property Devices: TDevices write SetDevices;
end;
var
DlgPushWhere: TDlgPushWhere;
implementation
{$R *.fmx}
uses System.Rtti;
const
sDeviceType = 'deviceType';
sDeviceToken = 'deviceToken';
sWhere = 'where';
sIOS = 'ios';
sAndroid = 'android';
procedure TDlgPushWhere.ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
var
I: Integer;
begin
I := AItem.Tag;
FDeviceTokens[FDevices[I].DeviceToken] := AItem.Checked;
if ListView1.Items.AnyChecked(True) then
CheckBoxAllDevices.IsChecked := False
else
CheckBoxAllDevices.IsChecked := True;
end;
procedure TDlgPushWhere.Load(const AJSONQuery: TJSONObject);
var
LWhere: TJSONObject;
I: Integer;
LStrings: TArray<string>;
LValue: TValue;
LSimpleFilter: TSimpleFilter;
LInFilter: TInFilter;
begin
FChecking := True;
try
FFilters := TFilters.Create;
if AJSONQuery.TryGetValue<TJSONObject>('where', LWhere) then
begin
TJSONFilterParser.Parse(LWhere, FFilters, 0);
for I := 0 to FFilters.Count - 1 do
begin
LSimpleFilter := nil;
LInFilter := nil;
if FFilters.Items[I] is TSimpleFilter then
LSimpleFilter := TSimpleFilter(FFilters.Items[I])
else if FFilters.Items[I] is TInFilter then
LInFilter := TInFilter(FFilters.Items[I]);
if (LSimpleFilter <> nil) and (LSimpleFilter.Op = TSimpleFilter.TOperator.eq) then
begin
if LSimpleFilter.Attribute = sDeviceType then
CheckDeviceType(LSimpleFilter.Value.AsString);
if LSimpleFilter.Attribute = sDeviceToken then
UpdateDeviceTokens(TArray<string>.Create(LSimpleFilter.Value.AsString));
end
else if (LInFilter <> nil) then
begin
if LInFilter.Attribute = 'deviceToken' then
begin
LStrings := nil;
for LValue in TInFilter(FFilters.Items[I]).Values do
LStrings := LStrings + [LValue.AsString];
UpdateDeviceTokens(LStrings);
end;
end;
end;
end
else
RadioButtonAll.IsChecked := True;
UpdateCheckBoxAllDevices;
finally
FChecking := False;
end;
end;
procedure TDlgPushWhere.UpdateCheckBoxAllDevices;
begin
FChecking := True;
try
CheckBoxAllDevices.IsChecked := not ListView1.Items.AnyChecked;
finally
FChecking := False;
end;
end;
procedure TDlgPushWhere.RadioButtonAllChange(Sender: TObject);
begin
if not FChecking then
begin
ListDevices;
ListCheckDeviceTokens;
UpdateCheckBoxAllDevices;
end;
end;
procedure TDlgPushWhere.Save(const AJSONQuery: TJSONObject);
var
LJSONWhere: TJSONObject;
LPair: TPair<string, Boolean>;
I: Integer;
LAttribute: string;
LSimpleFilter: TSimpleFilter;
LInFilter: TInFilter;
LValues: TList<TValue>;
begin
for I := FFilters.Count - 1 downto 0 do
begin
LSimpleFilter := nil;
LInFilter := nil;
if FFilters.Items[I] is TSimpleFilter then
LSimpleFilter := TSimpleFilter(FFilters.Items[I])
else if FFilters.Items[I] is TInFilter then
LInFilter := TInFilter(FFilters.Items[I]);
if LSimpleFilter <> nil then
LAttribute := LSimpleFilter.Attribute
else if LInFilter <> nil then
LAttribute := LInFilter.Attribute
else
continue;
if LAttribute = sDeviceType then
FFilters.Delete(I)
else if LAttribute = sDeviceToken then
FFilters.Delete(I);
end;
if RadioButtonIOS.IsChecked then
begin
LSimpleFilter := TSimpleFilter.Create;
FFilters.Add(LSimpleFilter);
LSimpleFilter.Attribute := sDeviceType;
LSimpleFilter.Op := TSimpleFilter.TOperator.eq;
LSimpleFilter.Value := sIOS;
end
else if RadioButtonAndroid.IsChecked then
begin
LSimpleFilter := TSimpleFilter.Create;
FFilters.Add(LSimpleFilter);
LSimpleFilter.Attribute := sDeviceType;
LSimpleFilter.Op := TSimpleFilter.TOperator.eq;
LSimpleFilter.Value := sAndroid;
end;
if not CheckBoxAllDevices.IsChecked then
begin
LInFilter := TInFilter.Create;
FFilters.Add(LInFilter);
LInFilter.Attribute := sDeviceToken;
LInFilter.Op := TInFilter.TOperator.inop;
LValues := TList<TValue>.Create;
try
for LPair in FDeviceTokens do
if LPair.Value then
LValues.Add(LPair.Key);
LInFilter.Values := LValues.ToArray;
finally
LValues.Free;
end;
end;
AJSONQuery.RemovePair(sWhere);
LJSONWhere := TJSONObject.Create;
AJSONQuery.AddPair(sWhere, LJSONWhere);
TQueryToJSON.WriteFilters(FFilters, LJSONWhere);
end;
procedure TDlgPushWhere.SetDevices(const Value: TDevices);
var
LDevice: TDevice;
begin
FDevices := Value;
for LDevice in Value do
FDeviceTokens.Add(LDevice.DeviceToken, False);
ListDevices;
end;
procedure TDlgPushWhere.ListDevices;
var
LDevice: TDevice;
LAdd: Boolean;
I: Integer;
begin
ListView1.BeginUpdate;
try
ListView1.Items.Clear;
I := 0;
for LDevice in FDevices do
begin
if RadioButtonIOS.IsChecked then
LAdd := LDevice.DeviceType = sIOS
else if RadioButtonAndroid.IsChecked then
LAdd := LDevice.DeviceType = sAndroid
else
LAdd := True;
if LAdd then
with ListView1.Items.Add do
begin
Text := LDevice.DeviceToken;
Tag := I;
end;
Inc(I);
end;
finally
ListView1.EndUpdate;
end;
end;
procedure TDlgPushWhere.CheckDeviceType(const ADeviceType: string);
begin
RadioButtonIOS.IsChecked := ADeviceType = sIOS;
RadioButtonAndroid.IsChecked := ADeviceType = sAndroid;
RadioButtonAll.IsChecked := (not RadioButtonIOS.IsChecked) and
(not RadioButtonAndroid.IsChecked);
end;
constructor TDlgPushWhere.Create(AOwner: TComponent);
begin
inherited;
FFilters := TFilters.Create;
FDeviceTokens := TDictionary<string, Boolean>.Create;
end;
destructor TDlgPushWhere.Destroy;
begin
FDeviceTokens.Free;
FFilters.Free;
inherited;
end;
procedure TDlgPushWhere.FormShow(Sender: TObject);
begin
if not FChecking then
begin
ListDevices;
ListCheckDeviceTokens;
UpdateCheckBoxAllDevices;
end;
end;
// procedure TDlgPushWhere.UpdateDeviceTokens(const AArray: TJSONArray);
// var
// LValue: TJSONValue;
// S: string;
// begin
// for S in FDeviceTokens.Keys do
// FDeviceTokens[S] := False;
// for LValue in AArray do
// FDeviceTokens[LValue.Value] := True;
// ListCheckDeviceTokens;
// end;
procedure TDlgPushWhere.UpdateDeviceTokens(const AArray: TArray<string>);
var
S: string;
begin
for S in FDeviceTokens.Keys do
FDeviceTokens[S] := False;
for S in AArray do
FDeviceTokens[S] := True;
ListCheckDeviceTokens;
end;
procedure TDlgPushWhere.CheckBoxAllDevicesChange(Sender: TObject);
var
S: string;
begin
if not FChecking then
begin
if CheckBoxAllDevices.IsChecked then
begin
for S in FDeviceTokens.Keys do
FDeviceTokens[S] := False;
ListCheckDeviceTokens;
end;
CheckBoxAllDevices.IsChecked := not ListView1.Items.AnyChecked;
end
end;
procedure TDlgPushWhere.ListCheckDeviceTokens;
var
LItem: TListViewItem;
I: Integer;
begin
for LItem in ListView1.Items do
begin
I := LItem.Tag;
LItem.Checked := FDeviceTokens[FDevices[I].DeviceToken];
end;
end;
{ TDlgPushWhere.TDevice }
constructor TDlgPushWhere.TDevice.Create(const ADeviceToken,
ADeviceType: string; const AChannels: TArray<string>);
begin
DeviceToken := ADeviceToken;
DeviceType := ADeviceType;
Channels := AChannels;
end;
end.
|
unit FC.StockChart.UnitTask.Indicator.Duplicate;
interface
{$I Compiler.inc}
uses
SysUtils,Classes, BaseUtils, Serialization, Dialogs, StockChart.Definitions.Units,StockChart.Definitions,
FC.Definitions, FC.Singletons,
FC.StockChart.UnitTask.Base;
implementation
type
TStockUnitTaskIndicatorDuplicate = class(TStockUnitTaskBase)
public
function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override;
procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override;
end;
{ TStockUnitTaskIndicatorDuplicate }
function TStockUnitTaskIndicatorDuplicate.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean;
begin
result:=true;
if result then
aOperationName:='Duplicate';
end;
procedure TStockUnitTaskIndicatorDuplicate.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition);
var
aIndicatorInfo : ISCIndicatorInfo;
aCopy: ISCIndicator;
i: integer;
aSrcProp,aDstProp: ISCIndicatorProperty;
begin
aIndicatorInfo:=IndicatorFactory.GetIndicatorInfo(aIndicator.GetIID);
aCopy:=aStockChart.CreateIndicator(aIndicatorInfo,false);
for i := 0 to aIndicator.GetProperties.Count - 1 do
begin
aSrcProp:=aIndicator.GetProperties.Items[i];
aDstProp:=aCopy.GetProperties.Items[i];
Assert(aSrcProp.GetName=aDstProp.GetName);
aDstProp.Value:=aSrcProp.Value;
end;
end;
initialization
StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskIndicatorDuplicate.Create);
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{ *************************************************************************** }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit Web.WebReq;
interface
uses
System.SyncObjs, System.SysUtils, System.Classes, Web.HTTPApp, System.Generics.Collections;
type
TRequestNotification = (rnActivateModule, rnDeactivateModule, rnCreateModule, rnFreeModule,
rnStartRequest, rnFinishRequest);
TWebRequestHandler = class(TComponent)
private
FCriticalSection: TCriticalSection;
FActiveWebModules: TObjectList<TComponent>;
FAddingActiveModules: Integer;
FInactiveWebModules: TObjectList<TComponent>;
FMaxConnections: Integer;
FCacheConnections: Boolean;
FWebModuleClass: TComponentClass;
function GetActiveCount: Integer;
function GetInactiveCount: Integer;
procedure SetCacheConnections(Value: Boolean);
protected
function ActivateWebModules: TComponent;
procedure DeactivateWebModules(WebModules: TComponent);
function HandleRequest(Request: TWebRequest; Response: TWebResponse): Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure FreeModules; virtual;
procedure HandleException(Sender: TObject);
property WebModuleClass: TComponentClass read FWebModuleClass write FWebModuleClass;
property ActiveCount: Integer read GetActiveCount;
property CacheConnections: Boolean read FCacheConnections write SetCacheConnections;
property InactiveCount: Integer read GetInactiveCount;
property MaxConnections: Integer read FMaxConnections write FMaxConnections;
end;
function WebRequestHandler: TWebRequestHandler;
procedure FreeWebModules;
var
WebRequestHandlerProc: function: TWebRequestHandler = nil;
implementation
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
Web.BrkrConst, Web.WebConst, System.Types;
procedure FreeWebModules;
begin
if Assigned(WebRequestHandlerProc) and (WebRequestHandlerProc <> nil) then
WebRequestHandlerProc.FreeModules;
end;
function WebRequestHandler: TWebRequestHandler;
begin
if Assigned(WebRequestHandlerProc) then
Result := WebRequestHandlerProc
else
Result := nil;
end;
{ TWebRequestHandler }
constructor TWebRequestHandler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCriticalSection := TCriticalSection.Create;
FActiveWebModules := TObjectList<TComponent>.Create(True); // Owns
FInactiveWebModules := TObjectList<TComponent>.Create(True); // Owns
FMaxConnections := 32;
FCacheConnections := True;
end;
destructor TWebRequestHandler.Destroy;
begin
FreeModules;
FActiveWebModules.Free;
FInactiveWebModules.Free;
FCriticalSection.Free;
inherited Destroy;
end;
procedure TWebRequestHandler.FreeModules;
begin
FCriticalSection.Enter;
try
FActiveWebModules.Clear;
FInactiveWebModules.Clear;
finally
FCriticalSection.Leave;
end;
end;
function IsUniqueGlobalWebComponentName(const Name: string): Boolean;
begin
// Prevent rename of data modules
Result := True;
end;
function TWebRequestHandler.ActivateWebModules: TComponent;
begin
if (FMaxConnections > 0) and (FAddingActiveModules >= FMaxConnections) then
raise EWebBrokerException.CreateRes(@sTooManyActiveConnections);
FCriticalSection.Enter;
try
FAddingActiveModules := FActiveWebModules.Count + 1;
try
Result := nil;
if (FMaxConnections > 0) and (FActiveWebModules.Count >= FMaxConnections) then
raise EWebBrokerException.CreateRes(@sTooManyActiveConnections);
if FInactiveWebModules.Count > 0 then
begin
Result := FInactiveWebModules[0];
FInactiveWebModules.Extract(Result);
FActiveWebModules.Add(Result);
end
else
begin
if WebModuleClass <> nil then
begin
Result := WebModuleClass.Create(nil);
FActiveWebModules.Add(Result);
end
else
raise EWebBrokerException.CreateRes(@sNoDataModulesRegistered);
end;
finally
FAddingActiveModules := 0;
end;
finally
FCriticalSection.Leave;
end;
end;
procedure TWebRequestHandler.DeactivateWebModules(WebModules: TComponent);
begin
FCriticalSection.Enter;
try
if FCacheConnections then
begin
FActiveWebModules.Extract(WebModules);
FInactiveWebModules.Add(WebModules);
end
else
FActiveWebModules.Remove(WebModules);
finally
FCriticalSection.Leave;
end;
end;
function TWebRequestHandler.GetActiveCount: Integer;
begin
FCriticalSection.Enter;
try
Result := FActiveWebModules.Count;
finally
FCriticalSection.Leave;
end;
end;
function TWebRequestHandler.GetInactiveCount: Integer;
begin
FCriticalSection.Enter;
try
Result := FInactiveWebModules.Count;
finally
FCriticalSection.Leave;
end;
end;
function TWebRequestHandler.HandleRequest(Request: TWebRequest;
Response: TWebResponse): Boolean;
var
I: Integer;
LWebModule: TComponent;
LWebAppServices: IWebAppServices;
LGetWebAppServices: IGetWebAppServices;
LComponent: TComponent;
begin
Result := False;
LWebModule := ActivateWebModules;
if Assigned(LWebModule) then
try
try
if Supports(IInterface(LWebModule), IGetWebAppServices, LGetWebAppServices) then
LWebAppServices := LGetWebAppServices.GetWebAppServices;
if LWebAppServices = nil then
for I := 0 to LWebModule.ComponentCount - 1 do
begin
LComponent := LWebModule.Components[I];
if Supports(LComponent, IWebAppServices, LWebAppServices) then
if LWebAppServices.Active then
break
else
LWebAppServices := nil;
end;
if LWebAppServices = nil then
LWebAppServices := TDefaultWebAppServices.Create;
LWebAppServices.InitContext(LWebModule, Request, Response);
try
try
Result := LWebAppServices.HandleRequest;
except
ApplicationHandleException(LWebAppServices.ExceptionHandler);
end;
finally
LWebAppServices.FinishContext;
end;
if Result and not Response.Sent then
Response.SendResponse;
except
ApplicationHandleException(LWebAppServices.ExceptionHandler);
end;
finally
DeactivateWebModules(LWebModule);
end;
end;
procedure TWebRequestHandler.SetCacheConnections(Value: Boolean);
begin
if Value <> FCacheConnections then
begin
FCacheConnections := Value;
if not Value then
begin
FCriticalSection.Enter;
try
FInactiveWebModules.Clear;
finally
FCriticalSection.Leave;
end;
end;
end;
end;
procedure TWebRequestHandler.HandleException(Sender: TObject);
var
Handled: Boolean;
Intf: IWebExceptionHandler;
begin
Handled := False;
if ExceptObject is Exception and
Supports(Sender, IWebExceptionHandler, Intf) then
try
Intf.HandleException(Exception(ExceptObject), Handled);
except
Handled := True;
System.SysUtils.ShowException(ExceptObject, ExceptAddr);
end;
if (not Handled) then
System.SysUtils.ShowException(ExceptObject, ExceptAddr);
end;
function ImplGetModuleFileName: string;
begin
Result := GetModuleName(hinstance);
end;
initialization
if not Assigned(GetModuleFileNameProc) then
GetModuleFileNameProc := ImplGetModuleFileName;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://hpw-chorafarma-test.hes.it/sms/sms.asmx?wsdl
// >Import : http://hpw-chorafarma-test.hes.it/sms/sms.asmx?wsdl>0
// Encoding : utf-8
// Version : 1.0
// (16/07/2015 11:25:46 - - $Rev: 76228 $)
// ************************************************************************ //
unit sms;
interface
uses Soap.InvokeRegistry, Soap.SOAPHTTPClient, System.Types, Soap.XSBuiltIns;
const
IS_OPTN = $0001;
IS_UNBD = $0002;
IS_NLBL = $0004;
IS_REF = $0080;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Embarcadero types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"[Gbl]
// !:int - "http://www.w3.org/2001/XMLSchema"[Gbl]
StatusItem = class; { "http://secure-services.hes.it/SMSway.Web.Service/"[GblCplx] }
MessageItem = class; { "http://secure-services.hes.it/SMSway.Web.Service/"[GblCplx] }
SMSRecv = class; { "http://secure-services.hes.it/SMSway.Web.Service/"[GblCplx] }
ArrayOfStatusItem = array of StatusItem; { "http://secure-services.hes.it/SMSway.Web.Service/"[GblCplx] }
ArrayOfString = array of string; { "http://secure-services.hes.it/SMSway.Web.Service/"[GblCplx] }
// ************************************************************************ //
// XML : StatusItem, global, <complexType>
// Namespace : http://secure-services.hes.it/SMSway.Web.Service/
// ************************************************************************ //
StatusItem = class(TRemotable)
private
FMessageID: string;
FMessageID_Specified: boolean;
FStatus: string;
FStatus_Specified: boolean;
FDate: string;
FDate_Specified: boolean;
FError: string;
FError_Specified: boolean;
procedure SetMessageID(Index: Integer; const Astring: string);
function MessageID_Specified(Index: Integer): boolean;
procedure SetStatus(Index: Integer; const Astring: string);
function Status_Specified(Index: Integer): boolean;
procedure SetDate(Index: Integer; const Astring: string);
function Date_Specified(Index: Integer): boolean;
procedure SetError(Index: Integer; const Astring: string);
function Error_Specified(Index: Integer): boolean;
published
property MessageID: string Index (IS_OPTN) read FMessageID write SetMessageID stored MessageID_Specified;
property Status: string Index (IS_OPTN) read FStatus write SetStatus stored Status_Specified;
property Date: string Index (IS_OPTN) read FDate write SetDate stored Date_Specified;
property Error: string Index (IS_OPTN) read FError write SetError stored Error_Specified;
end;
// ************************************************************************ //
// XML : MessageItem, global, <complexType>
// Namespace : http://secure-services.hes.it/SMSway.Web.Service/
// ************************************************************************ //
MessageItem = class(TRemotable)
private
FMessageID: string;
FMessageID_Specified: boolean;
FPriority: string;
FPriority_Specified: boolean;
FAddress: string;
FAddress_Specified: boolean;
FBody: string;
FBody_Specified: boolean;
FValPeriod: string;
FValPeriod_Specified: boolean;
FEncoding: string;
FEncoding_Specified: boolean;
FSmsClass: string;
FSmsClass_Specified: boolean;
FTimetosend: string;
FTimetosend_Specified: boolean;
procedure SetMessageID(Index: Integer; const Astring: string);
function MessageID_Specified(Index: Integer): boolean;
procedure SetPriority(Index: Integer; const Astring: string);
function Priority_Specified(Index: Integer): boolean;
procedure SetAddress(Index: Integer; const Astring: string);
function Address_Specified(Index: Integer): boolean;
procedure SetBody(Index: Integer; const Astring: string);
function Body_Specified(Index: Integer): boolean;
procedure SetValPeriod(Index: Integer; const Astring: string);
function ValPeriod_Specified(Index: Integer): boolean;
procedure SetEncoding(Index: Integer; const Astring: string);
function Encoding_Specified(Index: Integer): boolean;
procedure SetSmsClass(Index: Integer; const Astring: string);
function SmsClass_Specified(Index: Integer): boolean;
procedure SetTimetosend(Index: Integer; const Astring: string);
function Timetosend_Specified(Index: Integer): boolean;
published
property MessageID: string Index (IS_OPTN) read FMessageID write SetMessageID stored MessageID_Specified;
property Priority: string Index (IS_OPTN) read FPriority write SetPriority stored Priority_Specified;
property Address: string Index (IS_OPTN) read FAddress write SetAddress stored Address_Specified;
property Body: string Index (IS_OPTN) read FBody write SetBody stored Body_Specified;
property ValPeriod: string Index (IS_OPTN) read FValPeriod write SetValPeriod stored ValPeriod_Specified;
property Encoding: string Index (IS_OPTN) read FEncoding write SetEncoding stored Encoding_Specified;
property SmsClass: string Index (IS_OPTN) read FSmsClass write SetSmsClass stored SmsClass_Specified;
property Timetosend: string Index (IS_OPTN) read FTimetosend write SetTimetosend stored Timetosend_Specified;
end;
ArrayOfMessageItem = array of MessageItem; { "http://secure-services.hes.it/SMSway.Web.Service/"[GblCplx] }
ArrayOfSMSRecv = array of SMSRecv; { "http://secure-services.hes.it/SMSway.Web.Service/"[GblCplx] }
// ************************************************************************ //
// XML : SMSRecv, global, <complexType>
// Namespace : http://secure-services.hes.it/SMSway.Web.Service/
// ************************************************************************ //
SMSRecv = class(TRemotable)
private
Fid: Integer;
Foriginator: string;
Foriginator_Specified: boolean;
Fbody: string;
Fbody_Specified: boolean;
Fdaterecv: string;
Fdaterecv_Specified: boolean;
Fdateinsert: string;
Fdateinsert_Specified: boolean;
Fencoding: Integer;
procedure Setoriginator(Index: Integer; const Astring: string);
function originator_Specified(Index: Integer): boolean;
procedure Setbody(Index: Integer; const Astring: string);
function body_Specified(Index: Integer): boolean;
procedure Setdaterecv(Index: Integer; const Astring: string);
function daterecv_Specified(Index: Integer): boolean;
procedure Setdateinsert(Index: Integer; const Astring: string);
function dateinsert_Specified(Index: Integer): boolean;
published
property id: Integer read Fid write Fid;
property originator: string Index (IS_OPTN) read Foriginator write Setoriginator stored originator_Specified;
property body: string Index (IS_OPTN) read Fbody write Setbody stored body_Specified;
property daterecv: string Index (IS_OPTN) read Fdaterecv write Setdaterecv stored daterecv_Specified;
property dateinsert: string Index (IS_OPTN) read Fdateinsert write Setdateinsert stored dateinsert_Specified;
property encoding: Integer read Fencoding write Fencoding;
end;
// ************************************************************************ //
// Namespace : http://secure-services.hes.it/SMSway.Web.Service/
// soapAction: http://secure-services.hes.it/SMSway.Web.Service/%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : document
// use : literal
// binding : SmsSoap
// service : Sms
// port : SmsSoap
// URL : http://hpw-chorafarma-test.hes.it/sms/sms.asmx
// ************************************************************************ //
SmsSoap = interface(IInvokable)
['{C58BA232-4395-4828-CB3B-636ECA59E087}']
function RecvStatusPolling(const username: string; const password: string; const MessageId: ArrayOfString): ArrayOfStatusItem; stdcall;
function RecvPolling(const username: string; const password: string): ArrayOfSMSRecv; stdcall;
function SendEx(const username: string; const password: string; const priority: string; const sender: string; const address: string; const body: string;
const valperiod: string; const encoding: string; const smsclass: string; const timetosend: string; const messageid: string
): string; stdcall;
function SendMultiple(const username: string; const password: string; const defaultPriority: string; const defaultAddress: string; const defaultBody: string; const defaultValPeriod: string;
const defaultEncoding: string; const defaultSmsClass: string; const defaultTimetosend: string; const messageitems: ArrayOfMessageItem): ArrayOfStatusItem; stdcall;
end;
function GetSmsSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): SmsSoap;
implementation
uses System.SysUtils;
function GetSmsSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): SmsSoap;
const
defWSDL = 'http://hpw-chorafarma-test.hes.it/sms/sms.asmx?wsdl';
defURL = ''; //'http://hpw-chorafarma-test.hes.it/sms/sms.asmx';
defSvc = 'Sms';
defPrt = 'SmsSoap';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as SmsSoap);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
procedure StatusItem.SetMessageID(Index: Integer; const Astring: string);
begin
FMessageID := Astring;
FMessageID_Specified := True;
end;
function StatusItem.MessageID_Specified(Index: Integer): boolean;
begin
Result := FMessageID_Specified;
end;
procedure StatusItem.SetStatus(Index: Integer; const Astring: string);
begin
FStatus := Astring;
FStatus_Specified := True;
end;
function StatusItem.Status_Specified(Index: Integer): boolean;
begin
Result := FStatus_Specified;
end;
procedure StatusItem.SetDate(Index: Integer; const Astring: string);
begin
FDate := Astring;
FDate_Specified := True;
end;
function StatusItem.Date_Specified(Index: Integer): boolean;
begin
Result := FDate_Specified;
end;
procedure StatusItem.SetError(Index: Integer; const Astring: string);
begin
FError := Astring;
FError_Specified := True;
end;
function StatusItem.Error_Specified(Index: Integer): boolean;
begin
Result := FError_Specified;
end;
procedure MessageItem.SetMessageID(Index: Integer; const Astring: string);
begin
FMessageID := Astring;
FMessageID_Specified := True;
end;
function MessageItem.MessageID_Specified(Index: Integer): boolean;
begin
Result := FMessageID_Specified;
end;
procedure MessageItem.SetPriority(Index: Integer; const Astring: string);
begin
FPriority := Astring;
FPriority_Specified := True;
end;
function MessageItem.Priority_Specified(Index: Integer): boolean;
begin
Result := FPriority_Specified;
end;
procedure MessageItem.SetAddress(Index: Integer; const Astring: string);
begin
FAddress := Astring;
FAddress_Specified := True;
end;
function MessageItem.Address_Specified(Index: Integer): boolean;
begin
Result := FAddress_Specified;
end;
procedure MessageItem.SetBody(Index: Integer; const Astring: string);
begin
FBody := Astring;
FBody_Specified := True;
end;
function MessageItem.Body_Specified(Index: Integer): boolean;
begin
Result := FBody_Specified;
end;
procedure MessageItem.SetValPeriod(Index: Integer; const Astring: string);
begin
FValPeriod := Astring;
FValPeriod_Specified := True;
end;
function MessageItem.ValPeriod_Specified(Index: Integer): boolean;
begin
Result := FValPeriod_Specified;
end;
procedure MessageItem.SetEncoding(Index: Integer; const Astring: string);
begin
FEncoding := Astring;
FEncoding_Specified := True;
end;
function MessageItem.Encoding_Specified(Index: Integer): boolean;
begin
Result := FEncoding_Specified;
end;
procedure MessageItem.SetSmsClass(Index: Integer; const Astring: string);
begin
FSmsClass := Astring;
FSmsClass_Specified := True;
end;
function MessageItem.SmsClass_Specified(Index: Integer): boolean;
begin
Result := FSmsClass_Specified;
end;
procedure MessageItem.SetTimetosend(Index: Integer; const Astring: string);
begin
FTimetosend := Astring;
FTimetosend_Specified := True;
end;
function MessageItem.Timetosend_Specified(Index: Integer): boolean;
begin
Result := FTimetosend_Specified;
end;
procedure SMSRecv.Setoriginator(Index: Integer; const Astring: string);
begin
Foriginator := Astring;
Foriginator_Specified := True;
end;
function SMSRecv.originator_Specified(Index: Integer): boolean;
begin
Result := Foriginator_Specified;
end;
procedure SMSRecv.Setbody(Index: Integer; const Astring: string);
begin
Fbody := Astring;
Fbody_Specified := True;
end;
function SMSRecv.body_Specified(Index: Integer): boolean;
begin
Result := Fbody_Specified;
end;
procedure SMSRecv.Setdaterecv(Index: Integer; const Astring: string);
begin
Fdaterecv := Astring;
Fdaterecv_Specified := True;
end;
function SMSRecv.daterecv_Specified(Index: Integer): boolean;
begin
Result := Fdaterecv_Specified;
end;
procedure SMSRecv.Setdateinsert(Index: Integer; const Astring: string);
begin
Fdateinsert := Astring;
Fdateinsert_Specified := True;
end;
function SMSRecv.dateinsert_Specified(Index: Integer): boolean;
begin
Result := Fdateinsert_Specified;
end;
initialization
{ SmsSoap }
InvRegistry.RegisterInterface(TypeInfo(SmsSoap), 'http://secure-services.hes.it/SMSway.Web.Service/', 'utf-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(SmsSoap), 'http://secure-services.hes.it/SMSway.Web.Service/%operationName%');
InvRegistry.RegisterInvokeOptions(TypeInfo(SmsSoap), ioDocument);
{ SmsSoap.RecvStatusPolling }
InvRegistry.RegisterMethodInfo(TypeInfo(SmsSoap), 'RecvStatusPolling', '',
'[ReturnName="RecvStatusPollingResult"]', IS_OPTN);
InvRegistry.RegisterParamInfo(TypeInfo(SmsSoap), 'RecvStatusPolling', 'MessageId', '',
'[ArrayItemName="string"]');
InvRegistry.RegisterParamInfo(TypeInfo(SmsSoap), 'RecvStatusPolling', 'RecvStatusPollingResult', '',
'[ArrayItemName="StatusItem"]');
{ SmsSoap.RecvPolling }
InvRegistry.RegisterMethodInfo(TypeInfo(SmsSoap), 'RecvPolling', '',
'[ReturnName="RecvPollingResult"]', IS_OPTN);
InvRegistry.RegisterParamInfo(TypeInfo(SmsSoap), 'RecvPolling', 'RecvPollingResult', '',
'[ArrayItemName="SMSRecv"]');
{ SmsSoap.SendEx }
InvRegistry.RegisterMethodInfo(TypeInfo(SmsSoap), 'SendEx', '',
'[ReturnName="SendExResult"]', IS_OPTN);
{ SmsSoap.SendMultiple }
InvRegistry.RegisterMethodInfo(TypeInfo(SmsSoap), 'SendMultiple', '',
'[ReturnName="SendMultipleResult"]', IS_OPTN);
InvRegistry.RegisterParamInfo(TypeInfo(SmsSoap), 'SendMultiple', 'messageitems', '',
'[ArrayItemName="MessageItem"]');
InvRegistry.RegisterParamInfo(TypeInfo(SmsSoap), 'SendMultiple', 'SendMultipleResult', '',
'[ArrayItemName="StatusItem"]');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfStatusItem), 'http://secure-services.hes.it/SMSway.Web.Service/', 'ArrayOfStatusItem');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfString), 'http://secure-services.hes.it/SMSway.Web.Service/', 'ArrayOfString');
RemClassRegistry.RegisterXSClass(StatusItem, 'http://secure-services.hes.it/SMSway.Web.Service/', 'StatusItem');
RemClassRegistry.RegisterXSClass(MessageItem, 'http://secure-services.hes.it/SMSway.Web.Service/', 'MessageItem');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfMessageItem), 'http://secure-services.hes.it/SMSway.Web.Service/', 'ArrayOfMessageItem');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfSMSRecv), 'http://secure-services.hes.it/SMSway.Web.Service/', 'ArrayOfSMSRecv');
RemClassRegistry.RegisterXSClass(SMSRecv, 'http://secure-services.hes.it/SMSway.Web.Service/', 'SMSRecv');
end. |
unit Connection.TCP;
interface
uses Windows, SysUtils, GMConst, GMGlobals, Connection.Base, StrUtils, blcksock, System.Classes;
type
TConnectionObjectTCP = class(TConnectionObjectBase)
private
FSocket: TTCPBlockSocket;
function ReadFromSocket(): TCheckCOMResult;
protected
FLastError: string;
function OpenSocket(): int; virtual;
procedure HandleException(e: Exception; const source: string);
function MakeExchange(etAction: TExchangeType): TCheckCOMResult; override;
function GetLastConnectionError: string; override;
function ExceptionLogInfo(e: Exception): string; virtual;
public
property Socket: TTCPBlockSocket read FSocket write FSocket;
end;
TConnectionObjectTCP_IncomingSocket = class (TConnectionObjectTCP)
protected
function ConnectionEquipmentInitialized(): bool; override;
function LogSignature: string; override;
end;
TConnectionObjectTCP_OwnSocket = class (TConnectionObjectTCP)
private
FHost: string;
FPort: int;
protected
function LogSignature: string; override;
function OpenSocket(): int; override;
function ExceptionLogInfo(e: Exception): string; override;
public
constructor Create(); override;
destructor Destroy(); override;
property Host: string read FHost write FHost;
property Port: int read FPort write FPort;
procedure FreePort; override;
end;
TBlockSocketHelper = class helper for TBlockSocket
public
function IsWaitDataSocketError(): bool;
end;
implementation
{ TConnectionObjectTCP }
uses ProgramLogFile, Winapi.WinSock, synautil;
function TConnectionObjectTCP.ExceptionLogInfo(e: Exception): string;
begin
Result := '';
end;
procedure TConnectionObjectTCP.HandleException(e: Exception; const source: string);
begin
ProgramLog().AddException(ClassName() + '.' + source + ' - ' + e.Message + ExceptionLogInfo(e));
FLastError := e.Message;
FreePort();
end;
function TConnectionObjectTCP.ReadFromSocket(): TCheckCOMResult;
var
s: AnsiString;
ms: ISmartPointer<TMemoryStream>;
begin
try
buffers.NumberOfBytesRead := 0;
ms := TSmartPointer<TMemoryStream>.Create();
s := Socket.RecvPacket(WaitFirst);
case Socket.LastError of
0:
begin
WriteStrToStream(ms, s);
Result := ccrBytes;
end;
WSAETIMEDOUT:
Exit(ccrEmpty);
else
Exit(ccrError);
end;
if not CheckGetAllData() then
while true do
begin
s := Socket.RecvPacket(WaitNext);
if Socket.LastError = 0 then
begin
WriteStrToStream(ms, s);
if CheckGetAllData() then
break;
end
else
break;
Sleep(10);
end;
ms.Seek(0, soFromBeginning);
buffers.NumberOfBytesRead := ms.Size;
CopyMemory(@buffers.BufRec, ms.Memory, ms.Size);
except
on e: Exception do
begin
HandleException(e, 'ReadFromSocket');
Result := ccrError;
end;
end;
end;
function TConnectionObjectTCP.GetLastConnectionError: string;
begin
Result := FLastError;
end;
function TConnectionObjectTCP.OpenSocket(): int;
begin
Result := 0;
end;
function TConnectionObjectTCP.MakeExchange(etAction: TExchangeType): TCheckCOMResult;
var
res: int;
begin
Result := ccrError;
try
res := OpenSocket();
if res <> 0 then
begin
ProgramLog().AddError(GetGoodLastError(res));
Exit;
end;
if etAction in [etSenRec, etSend] then
Socket.SendBuffer(@buffers.BufSend, buffers.LengthSend);
if etAction in [etSenRec, etRec] then
Result := ReadFromSocket()
else
Result := ccrEmpty;
except
on e: Exception do
HandleException(e, 'MakeExchange');
end;
end;
{ TConnectionObjectTCP_OwnSocket }
constructor TConnectionObjectTCP_OwnSocket.Create;
begin
inherited Create();
FSocket := TTCPBlockSocket.Create();
end;
destructor TConnectionObjectTCP_OwnSocket.Destroy;
begin
inherited Destroy; // здесь вызывается FreePort, где закрывается FSocket, поэтому очистим FSocket после inherited
FSocket.Free();
end;
function TConnectionObjectTCP_OwnSocket.ExceptionLogInfo(e: Exception): string;
begin
if FSocket <> nil then
Result := Format(' (host = %s, port = %d)', [FHost.QuotedString(), FPort])
else
Result := '';
end;
procedure TConnectionObjectTCP_OwnSocket.FreePort;
begin
inherited FreePort;
FSocket.CloseSocket();
end;
function TConnectionObjectTCP_OwnSocket.LogSignature: string;
begin
Result := IfThen(LogPrefix <> '', LogPrefix, 'TCP');
if FSocket <> nil then
Result := Result + ' ' + FHost + ' ' + IntToStr(FPort);
end;
function TConnectionObjectTCP_OwnSocket.OpenSocket: int;
begin
Result := inherited OpenSocket;
if Result <> 0 then
Exit;
if FSocket.Socket <> INVALID_SOCKET then
Exit;
FSocket.Connect(FHost, IntToStr(FPort));
Result := FSocket.LastError;
end;
{ TConnectionObjectTCP_ExternalSocket }
function TConnectionObjectTCP_IncomingSocket.ConnectionEquipmentInitialized: bool;
begin
Result := FSocket <> nil;
end;
function TConnectionObjectTCP_IncomingSocket.LogSignature: string;
begin
Result := IfThen(LogPrefix <> '', LogPrefix, 'TCP Incoming');
end;
{ TBlockSocketHelper }
function TBlockSocketHelper.IsWaitDataSocketError: bool;
begin
Result := (LastError <> 0) and (LastError <> WSAETIMEDOUT);
end;
end.
|
unit TextPrint;
interface
uses
Classes, WinTypes, WinProcs, SysUtils, Db, Dialogs, Utilits;
type
TTextPrintManager = class(TComponent)
private
FNumberOfBytesWritten: DWORD;
FHandle: THandle;
FPrinterOpen: Boolean;
FErrorString: PChar;
FCommands, FParams, FSetStrings: TStringList;
FDataSet: TDataSet;
FLeftMarg: Integer;
procedure SetErrorString;
protected
function DecodeTag(CS: string; ManageLevel: Byte): string;
procedure PrintFileOrList(var F: TextFile; AList: TStringList);
public
property NumberOfBytesWritten: DWORD read FNumberOfBytesWritten;
property Commands: TStringList read FCommands;
property Params: TStringList read FParams;
property SetStrings: TStringList read FSetStrings;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function InitPort(APort: PChar; ToEnd: Boolean): Boolean;
procedure DonePort;
procedure Send(const Str: string);
procedure SendLn(const Str: string);
function LoadCommands(FN: TFileName): Boolean;
function PrintForm(FN: TFileName; DS: TDataSet; LeftMarg: Integer;
FormFeed: Boolean): Boolean;
function GetCommand(Index: Integer): string;
function InitParam(N: string): Boolean;
function GetParam(AMask: string; Len: Integer; OneLine: Boolean; Align: Byte): string;
end;
implementation
const
pcInit = 0;
pcPica = 1;
pcElite = 2;
pcCondensed = 3;
pcUnderlineOn = 4;
pcUnderlineOff = 5;
pcBoldOn = 6;
pcBoldOff = 7;
pcItalicOn = 8;
pcItalicOff = 9;
constructor TTextPrintManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCommands := TStringList.Create;
FParams := TStringList.Create;
FSetStrings := TStringList.Create;
end;
destructor TTextPrintManager.Destroy;
begin
DonePort;
FSetStrings.Free;
FParams.Free;
FCommands.Free;
inherited Destroy;
end;
function TTextPrintManager.InitPort(APort: PChar; ToEnd: Boolean): Boolean;
var
DesiredAccess, ShareMode, CreationDistribution: DWORD;
begin
DonePort;
DesiredAccess := {GENERIC_READ or} GENERIC_WRITE;
ShareMode := {FILE_SHARE_READ or} FILE_SHARE_WRITE;
CreationDistribution := {OPEN_EXISTING CREATE_NEW} OPEN_ALWAYS;
FHandle := CreateFile(APort, DesiredAccess, ShareMode, nil,
CreationDistribution, 0, 0);
Result := FHandle <> INVALID_HANDLE_VALUE;
if not Result then
begin
SetErrorString;
raise Exception.Create('Ошибка открытия порта принтера'+#13#10
+FErrorString+#13#10+APort);
end
else begin
FPrinterOpen := True;
if ToEnd then
SetFilePointer(FHandle, 0, nil, FILE_END);
end;
end;
procedure TTextPrintManager.SetErrorString;
begin
if FErrorString <> nil then
LocalFree(Integer(FErrorString));
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM,
nil, GetLastError(), LANG_USER_DEFAULT, @FErrorString, 0, nil);
end;
function TTextPrintManager.GetCommand(Index: Integer): string;
begin
if (Index>=0) and (Index<Commands.Count) then
Result := Commands[Index]
else
Result := '';
end;
procedure TTextPrintManager.Send(const Str: string);
var
OEMStr: PChar;
NumberOfBytesToWrite: DWord;
begin
if not FPrinterOpen then
Exit;
NumberOfBytesToWrite := Length(Str);
OEMStr := PChar(LocalAlloc(LMEM_FIXED, NumberOfBytesToWrite + 1));
try
{CharToOem(PChar(Str), OEMStr);}
StrPCopy(OEMStr, Str);
if not WriteFile(FHandle, OEMStr^, NumberOfBytesToWrite,
FNumberOfBytesWritten, nil) then
begin
SetErrorString;
raise Exception.Create(FErrorString);
end;
finally
LocalFree(Integer(OEMStr));
end;
end;
procedure TTextPrintManager.SendLn(const Str: string);
begin
Send(Str);
Send(#13#10);
end;
procedure TTextPrintManager.DonePort;
begin
CloseHandle(FHandle);
if FErrorString <> nil then
LocalFree(Integer(FErrorString));
end;
function TTextPrintManager.LoadCommands(FN: TFileName): Boolean;
var
F: TextFile;
S: string;
begin
AssignFile(F, FN);
FileMode := 0;
{$I-} Reset(F); {$I+}
Result := IOResult=0;
if Result then
begin
Commands.Clear;
while not Eof(F) do
begin
ReadLn(F, S);
if (Length(S)>0) and (S[1]<>';') then
Commands.Add(S);
end;
CloseFile(F);
end;
end;
const
ComCount = 7;
ComNames: array[1..ComCount] of PChar =
('K', 'V', 'F', 'B', 'S', 'L', 'LM');
function GetCommandIndex(C: string): Integer;
begin
C := UpperCase(C);
Result := 1;
while (Result<=ComCount) and (StrComp(PChar(C), ComNames[Result])<>0) do
Inc(Result);
if Result>ComCount then
Result := -1;
end;
function TTextPrintManager.InitParam(N: string): Boolean;
const
MesTitle: PChar = 'Инициализация параметра';
var
T: array[0..1023] of Char;
begin
Result := FDataSet=nil;
if Result then
MessageBox(ParentWnd, 'База не указана', MesTitle, MB_OK or MB_ICONERROR)
else begin
StrPLCopy(T, DecodeFieldMask(FDataSet, N), SizeOf(T));
WinToDos(T);
Params.Add(N + '=' + T);
end;
end;
function TTextPrintManager.GetParam(AMask: string; Len: Integer; OneLine: Boolean;
Align: Byte): string;
function GetParamLoc(N: string): string;
var
I, J, K, L: Integer;
S: string;
begin
I := Params.IndexOfName(N);
if I>=0 then
begin
Result := Params.Strings[I];
K := Pos('=', Result);
if K>0 then
Delete(Result, 1, K);
if OneLine then
begin
S := '';
J := Length(Result);
K := 1; {разбиение по CR или перенос}
while (K<=J) and ((Len<=0) or (K<=Len)) and (Result[K]<>#13)
and (Result[K]<>#10) do Inc(K);
if K<=J then
begin {нужно отрзать начальный кусок строки}
if (Len>0) and (K>Len) then {найдем пробел, если нету - режем по слову}
begin
while (K>0) and (Result[K]<>' ') and (Result[K]<>#13)
and (Result[K]<>#10) and (Result[K]<>'.')
and (Result[K]<>',') and (Result[K]<>';')
do Dec(K);
if K<=0 then
K := Len;
end;
L := K+1;
while (L<=J) and ((Result[L]=' ') or (Result[L]=#13) or (Result[L]=#10))
do Inc(L);
S := S + Copy(Result, L, Length(Result)-L+1);
while (K>0) and ((Result[K]=' ') or (Result[K]=#13) or (Result[K]=#10))
do Dec(K);
Result := Copy(Result, 1, K);
end;
if Length(S)>0 then
Params.Strings[I] := N + '=' + S
else
Params.Delete(I);
end
else
Params.Delete(I);
end
else begin
{MessageBox(ParentWnd, PChar('Параметр не инициализирован ['+N+']'),
'Взятие параметра', MB_OK or MB_ICONERROR);}
Result := '';
end;
end;
var
V: string;
I, J, ErrCode: Integer;
AField: TField;
begin
Result:='';
repeat
I := Pos('+',AMask);
if I>0 then
begin
V := Copy(AMask,1,I-1);
Delete(AMask,1,I)
end
else begin
V := AMask;
AMask := ''
end;
I := 0;
while (I<Length(V)) and (V[I+1]=' ') do Inc(I);
if I>0 then
Delete(V,1,I);
I := Length(V);
while (I>1) and (V[I]=' ') do Dec(I);
V := Copy(V,1,I);
if (V[1]='"') or (V[1]='''') or (V[1]='[') then
begin
if V[1]='[' then I:=1
else I:=0;
V := Copy(V,2,Length(V)-2);
end
else begin
I := 2;
V := GetParamLoc(V);
end;
Result := Result + V;
until Length(AMask)<=0;
if Len>0 then {выравнивание}
begin
I := Length(Result);
if I<Len then
begin
I := Len-I;
case Align of
1:
for J := 1 to I do
Result := ' '+Result;
2:
begin
Len := I div 2;
for J := 1 to Len do
Result := ' '+Result;
Dec(I, Len);
for J := 1 to I do
Result := Result+' ';
end;
else
for J := 1 to I do
Result := Result+' ';
end;
end
else
if I>Len then
Result := Copy(Result, 1, Len);
end;
end;
function TTextPrintManager.DecodeTag(CS: string; ManageLevel: Byte): string;
const
MesTitle: PChar = 'Расшифровка команд';
var
F: TextFile;
I,J,Err: Integer;
C,P: string;
Align: Byte;
begin
Result := '';
while Length(CS)>0 do
begin
if ManageLevel<=0 then
I := Pos(';', CS)
else
I := 0;
if I>0 then
begin
C := Copy(CS, 1, I-1);
System.Delete(CS, 1, I);
end
else begin
C := CS;
CS := ''
end;
I := Pos(':', C);
if I>0 then
begin
P := Copy(C, I+1, Length(C)-I);
C := Copy(C, 1, I-1);
end
else
P := '';
C := TruncStr(C);
I := GetCommandIndex(C);
case I of
1: {K - команда}
begin
Val(P, J, Err);
if Err=0 then
Result := Result + GetCommand(J)
else begin
MessageBox(ParentWnd, PChar('Параметр команды K должен быть числом ['+P+']'),
MesTitle, MB_OK or MB_ICONERROR);
Result := Result + C;
end;
end;
2: {V - взятие параметра из базы}
InitParam(P);
3: {F - заполнение поля формы}
begin
if Length(P)>0 then
begin
Align := 0;
J := Pos('#', P);
if J>0 then
begin
C := Copy(P, J+1, Length(P)-J);
P := Copy(P, 1, J-1);
if Length(C)>0 then
begin
if (C[1]<'0') or (C[1]>'9') then
begin
case C[1] of
'R': Align := 1;
'C': Align := 2;
end;
Delete(C, 1, 1);
end;
Val(C, J, Err);
if Err<>0 then
J := 0
end
else
J := 0;
end;
if P[1]='@' then
Result := Result + GetParam(Copy(P, 2, Length(P)-1), J, True, Align)
else
Result := Result + GetParam(P, J, False, Align);
end;
end;
4: {B - отображение символов}
begin
Val(P, J, Err);
if Err=0 then
Result := Result + Chr(J)
else begin
MessageBox(ParentWnd, PChar('Параметр команды B должен быть числом ['
+P+']'), MesTitle, MB_OK or MB_ICONERROR);
Result := Result + C;
end;
end;
5: {S - установка шаблона}
begin
SetStrings.Clear;
SetStrings.Add(P);
end;
6: {L - цикл по шаблону}
begin
Val(P, J, Err);
if Err=0 then
begin
if FDataSet<>nil then
begin
with FDataSet do
begin
case J of
1: First;
end;
while not EoF do
begin
PrintFileOrList(F, SetStrings);
Next;
end;
end;
end;
end
else begin
MessageBox(ParentWnd, PChar('Параметр команды L должен быть числом ['
+P+']'), MesTitle, MB_OK or MB_ICONERROR);
Result := Result + C;
end;
end;
7: {LM - левая граница}
begin
Val(P, J, Err);
if Err=0 then
FLeftMarg := J
else begin
MessageBox(ParentWnd, PChar('Параметр команды LM должен быть числом ['
+P+']'), MesTitle, MB_OK or MB_ICONERROR);
Result := Result + C;
end;
end;
else begin
MessageBox(ParentWnd, PChar('В форме неизвестная команда ['+C+']'),
MesTitle, MB_OK or MB_ICONERROR);
Result := Result + C;
end;
end;
end;
end;
procedure TTextPrintManager.PrintFileOrList(var F: TextFile; AList: TStringList);
var
EndOfList: Boolean;
I, P: Integer;
S, PS, CS, SS: string;
ManageLevel: Byte;
Manage: Boolean;
begin
CS := '';
PS := '';
ManageLevel := 0;
Manage := False;
if AList=nil then
EndOfList := Eof(F)
else begin
I := 0;
EndOfList := I>=AList.Count;
end;
while not EndOfList do
begin
if AList=nil then
ReadLn(F, S)
else
S := AList.Strings[I];
while Length(S)>0 do
begin
if Manage then
begin
SS := '}';
for P := 1 to ManageLevel do
SS := '$'+SS;
P := Pos(SS, S);
if P>0 then
Inc(P, ManageLevel);
end
else begin
P := Pos('{', S);
ManageLevel := 0;
if P>0 then
while (P+ManageLevel<Length(S)) and (S[P+ManageLevel+1]='$') do
Inc(ManageLevel);
end;
if P>0 then
begin
if Manage then
begin
CS := CS + Copy(S, 1, P-1);
if ManageLevel>0 then
CS := Copy(CS, ManageLevel+1, Length(CS)-2*ManageLevel);
PS := PS + DecodeTag(CS, ManageLevel);
CS := '';
end
else
PS := PS + Copy(S, 1, P-1);
System.Delete(S, 1, P);
Manage := not Manage;
end
else begin
if Manage then
CS := CS+S
else
PS := PS+S;
S := '';
end;
end;
if not Manage then
begin
for P := 1 to FLeftMarg do
PS := ' '+PS;
SendLn(PS);
PS := '';
end;
if AList=nil then
EndOfList := Eof(F)
else begin
Inc(I);
EndOfList := I>=AList.Count;
end;
end;
end;
function TTextPrintManager.PrintForm(FN: TFileName; DS: TDataSet;
LeftMarg: Integer; FormFeed: Boolean): Boolean;
var
F: TextFile;
begin
AssignFile(F, FN);
FileMode := 0;
{$I-} Reset(F); {$I+}
Result := IOResult=0;
if Result then
begin
try
Params.Clear;
FLeftMarg := LeftMarg;
FDataSet := DS;
PrintFileOrList(F, nil);
if FormFeed then
Send(#12);
finally
CloseFile(F);
end;
end;
end;
end.
|
unit rhlRotating;
interface
uses
rhlCore;
type
{ TrhlRotating }
TrhlRotating = class(TrhlHash)
private
m_hash: DWord;
protected
procedure UpdateBytes(const ABuffer; ASize: LongWord); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlRotating }
procedure TrhlRotating.UpdateBytes(const ABuffer; ASize: LongWord);
var
b: PByte;
begin
b := @ABuffer;
while ASize > 0 do
begin
m_hash := (m_hash shl 4) xor (m_hash shr 28) xor b^;
Inc(b);
Dec(ASize);
end;
end;
constructor TrhlRotating.Create;
begin
HashSize := 4;
BlockSize := 1;
end;
procedure TrhlRotating.Init;
begin
inherited Init;
m_hash := 0;
end;
procedure TrhlRotating.Final(var ADigest);
begin
Move(m_hash, ADigest, 4);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Xml.XmlTransform;
interface
uses
System.Classes, System.SysUtils, Xml.Xmldom;
type
TranslateException = class(Exception);
{ TXMLTransform }
TTranslateEvent = procedure(Sender: TObject; Id: string;
SrcNode: IDOMNode; var Value: string; DestNode: IDOMNode) of object;
TRowEvent = procedure(Sender: TObject; Id: string;
SrcNode: IDOMNode; DestNode: IDOMNode) of object;
TXMLTransform = class(TComponent)
private
FEncoding: string;
FEncodingTrans: string;
FDirectionToCds: Boolean;
FVersion: string;
FSourceXmlFile: string;
FSourceXmlDocument: IDOMDocument;
FSourceXml: string;
FTransformationFile: string;
FTransformationDocument: IDOMDocument;
FEmptyDestinationDocument: IDOMDocument; //Insert into this, if present
FResultDocument: IDOMDocument;
FResultString: string;
FOnTranslate: TTranslateEvent;
FBeforeEachRow: TRowEvent;
FAfterEachRow: TRowEvent;
FBeforeEachRowSet: TRowEvent;
FAfterEachRowSet: TRowEvent;
protected
procedure Translate(const Id: string; const SrcNode: IDOMNode;
var SrcValue: string; const DestNode: IDOMNode); dynamic;
function DoTransform(const XMLSrc, XMLExtract, XMLOut: IDOMDocument): string;
procedure Transform(TransNode, SrcNode, DestNode: IDOMNode;
Count: Integer; InFromList, InDestList, InIdStrList, InValueList,
InOptionalList, InDateFormatList, InDateFormatTypeList,
InMapValuesList: TStringList);
function GetData: string;
function GetResultString: string;
public
function TransformXML(const SourceXml: string;
const ATransformationFile: string = ''): string;
property Data: string read GetData ;
property Encoding: string read FEncoding;
property EncodingTrans: string read FEncodingTrans;
property SourceXmlDocument: IDOMDocument read FSourceXmlDocument write FSourceXmlDocument;
property SourceXmlFile: string read FSourceXmlFile write FSourceXmlFile;
property SourceXml: string read FSourceXml write FSourceXml;
property TransformationDocument: IDOMDocument read FTransformationDocument write FTransformationDocument;
property EmptyDestinationDocument: IDOMDocument read FEmptyDestinationDocument write FEmptyDestinationDocument;
property ResultDocument: IDOMDocument read FResultDocument;
property ResultString: string read GetResultString;
published
property TransformationFile: string read FTransformationFile write FTransformationFile;
property OnTranslate: TTranslateEvent read FOnTranslate write FOnTranslate;
property BeforeEachRow: TRowEvent read FBeforeEachRow write FBeforeEachRow;
property AfterEachRow: TRowEvent read FAfterEachRow write FAfterEachRow;
property BeforeEachRowSet: TRowEvent read FBeforeEachRowSet write FBeforeEachRowSet;
property AfterEachRowSet: TRowEvent read FAfterEachRowSet write FAfterEachRowSet;
end;
implementation
uses
Xml.XMLConst, Xml.xmlutil;
procedure TransformError(const Msg: string);
begin
raise TranslateException.Create(Msg);
end;
{ TXMLTransform }
procedure TXMLTransform.Translate(const Id: string; const SrcNode: IDOMNode;
var SrcValue: string; const DestNode: IDOMNode);
begin
if Assigned(FOnTranslate) then
FOnTranslate(Self, Id, SrcNode, SrcValue, DestNode);
end;
function TXMLTransform.GetData: string;
var
FSrcDom: IDOMDocument;
FTransDom: IDOMDocument;
begin
if FSourceXMLFile = '' then
begin
if FSourceXml <> '' then
FSrcDom := LoadDocFromString(FSourceXml)
else if FSourceXmlDocument = nil then
TransformError(SMissingSourceFile)
else
FSrcDom := FSourceXmlDocument;
end
else
FSrcDom := LoadDocFromFile(FSourceXMLFile);
if FTransformationFile = '' then
begin
if FTransformationDocument = nil then
TransformError(SMissingTransform)
else
FTransDom := FTransformationDocument;
end
else
FTransDom := LoadDocFromFile(FTransformationFile);
Result := DoTransform(FSrcDom, FTransDom, FEmptyDestinationDocument);
end;
function TXMLTransform.GetResultString: string;
begin
if (FResultString = '') and (FResultDocument <> nil) then
FResultString := (FResultDocument as IDOMPersist).xml;
Result := FResultString;
end;
function TXMLTransform.TransformXML (const SourceXML: string;
const ATransformationFile: string = ''): string;
var
SrcDom: IDOMDocument;
TransDom: IDOMDocument;
begin
Result := '';
TransDom := nil;
SrcDom := nil;
if SourceXml <> '' then
SrcDom := LoadDocFromString(SourceXML);
if ATransformationFile <> '' then
TransDom := LoadDocFromFile(ATransformationFile)
else
if FTransformationFile <> '' then
TransDom := LoadDocFromFile(FTransformationFile)
else
TransformError(SMissingTransform);
if (TransDom <> nil) and (SrcDom <> nil) then
Result := DoTransForm(SrcDom, TransDom, FEmptyDestinationDocument);
end;
function TXMLTransform.DoTransform(const XMLSrc, XMLExtract, XMLOut: IDOMDocument): string;
var
TransRoot: IDOMNode;
SrcRoot, DestRoot, DestRootClone, Node, TransformNode: IDOMNode;
I: Integer;
cdata_skeleton: string;
Skeleton: IDOMDocument;
Direction: string;
MajorVersion, MinorVersion: string;
begin
FResultDocument := nil;
FResultString := '';
FEncoding := GetEncoding(XMLSrc);
TransRoot := XMLExtract.documentElement;
SrcRoot := XMLSrc.documentElement;
if XMLOut <> nil then
DestRootClone := XMLOut.documentElement
else
begin
FVersion := GetAttribute(TransRoot, mx_Version);
if FVersion <> '' then
begin
MajorVersion := Head(FVersion, '.', MinorVersion);
if StrToInt(MajorVersion) < 1 then
TransformError(SOldVersion);
end;
TransformNode := SelectNode(TransRoot, mx_Root + '\'+ mx_Transform);
FEncodingTrans := GetAttribute(TransformNode, mx_DataEncoding);
Direction := GetAttribute(TransformNode, mx_Direction);
FDirectionToCds := (Direction = mx_ToCds);
DestRoot := SelectNode(TransRoot,mx_Root+'\'+mx_Skeleton);
if DestRoot.ChildNodes.item[0].nodeType = ELEMENT_NODE then
DestRootClone := DestRoot.CloneNode(True)
else if DestRoot.ChildNodes.item[0].nodeType = CDATA_SECTION_NODE then
begin
cdata_skeleton := DestRoot.ChildNodes.item[0].nodeValue;
Skeleton := LoadDocFromString(cdata_skeleton);
DestRootClone := Skeleton.documentElement;
end;
end;
Node := SelectNode(TransRoot, mx_Root + '\' + mx_Transform);
if Node <> nil then
for I := 0 to Node.childNodes.length-1 do
Transform(Node.childNodes.item[I], SrcRoot, DestRootClone,
0, nil, nil, nil, nil, nil, nil, nil, nil);
if XmlOut <> nil then
begin
FResultDocument := XMLOut;
Result := (DestRootClone as IDOMNodeEx).xml;
end
else
begin
if Skeleton = nil then
Result := (DestRootClone.childNodes.item[0] as IDOMPersist).xml
else
begin
FResultDocument := Skeleton;
Result := (Skeleton as IDOMPersist).xml;
end;
end;
FResultString := Result;
end;
procedure TXMLTransform.Transform(TransNode, SrcNode, DestNode: IDOMNode;
Count: Integer; InFromList, InDestList, InIdStrList, InValueList,
InOptionalList, InDateFormatList, InDateFormatTypeList,
InMapValuesList: TStringList);
var
I, J: Integer;
From, Dest: string;
Value, AttrName: string;
IdStr, RepeatName: string;
Optional, Map_Values: string;
DefaultValue, DateFormat, DateFormatType: string;
More, BeforeEachRowSet: Boolean;
RepeatDestNode, AttrNode, TmpNode: IDOMNode;
FromList, DestList, IdStrList, ValueList, OptionalList: TStringList;
DateFormatList, DateFormatTypeList, MapValuesList: TStringList;
begin
if TransNode.NodeName = mx_TranslateEach then
begin
AttrNode := TransNode.attributes.getNamedItem(mx_FROM);
if AttrNode <> nil then From := AttrNode.nodeValue else From := '';
AttrNode := TransNode.attributes.getNamedItem(mx_DEST);
if AttrNode <> nil then Dest := AttrNode.nodeValue else Dest := '';
AttrNode := TransNode.attributes.getNamedItem(mx_ID);
if AttrNode <> nil then IdStr := AttrNode.nodeValue else IdStr := '';
SrcNode := SelectNode(SrcNode, From);
if SrcNode <> nil then
begin
RepeatName := SrcNode.nodeName;
DestNode := SelectCreateNode(DestNode, Dest, AttrName);
end
else
begin
RepeatName := '';
DestNode := SelectCreateNode(DestNode, Dest, AttrName);
if (DestNode <> nil) and (DestNode.parentNode <> nil) then
begin
TmpNode := DestNode;
DestNode := DestNode.parentNode;
DestNode.removeChild(TmpNode);
end;
end;
if (SrcNode <> nil) and (DestNode <> nil) then
begin
More := True;
BeforeEachRowSet := True;
RepeatDestNode := DestNode.cloneNode(True);
end
else
begin
More := False;
BeforeEachRowSet := False;
RepeatDestNode := nil;
end;
if More and Assigned(FBeforeEachRowSet) then
FBeforeEachRowSet(Self, IdStr, SrcNode, DestNode);
FromList := TStringList.Create;
DestList := TStringList.Create;
IdStrList := TStringList.Create;
ValueList := TStringList.Create;
OptionalList := TStringList.Create;
DateFormatList := TStringList.Create;
DateFormatTypeList := TStringList.Create;
MapValuesList := TStringList.Create;
try
while More do
begin
if Assigned(FBeforeEachRow) then
FBeforeEachRow(Self, IdStr, SrcNode, DestNode);
for I := 0 to TransNode.childNodes.length-1 do
TransForm(TransNode.childNodes.item[i], SrcNode, DestNode,
I, FromList, DestList, IdStrList, ValueList, OptionalList,
DateFormatList, DateFormatTypeList, MapValuesList);
if Assigned(FAfterEachRow) then
FAfterEachRow(Self, IdStr, SrcNode, DestNode);
while More do
begin
SrcNode := SrcNode.nextSibling;
if SrcNode = nil then
More := False
else
begin
if SrcNode.nodeName = RepeatName then
begin //found next\
DestNode := SelectCreateSibling(DestNode, RepeatDestNode);
if DestNode = nil then More := False;
Break;
end;
end;
end;
end; //while More
if BeforeEachRowSet and Assigned(FAfterEachRowSet) then
FAfterEachRowSet(Self, IdStr, SrcNode, DestNode);
{We don't have any items, but must keep List.Count = Count}
if InFromList <> nil then
begin
InFromList.Add(EmptyStr);
InDestList.Add(EmptyStr);
InIdStrList.Add(EmptyStr);
InValueList.Add(EmptyStr);
InOptionalList.Add(EmptyStr);
InDateFormatList.Add(EmptyStr);
InDateFormatTypeList.Add(EmptyStr);
InMapValuesList.Add(EmptyStr);
end;
finally
FromList.Free;
DestList.Free;
IdStrList.Free;
ValueList.Free ;
OptionalList.Free;
DateFormatList.Free;
DateFormatTypeList.Free;
MapValuesList.Free;
end;
end // TransNode.NodeName = mx_TranslateEach
else if TransNode.NodeName = mx_Translate then //Field-translation
begin
if (InFromList = nil) or (Count >= InFromList.Count) then
begin
From := ''; Dest := ''; IdStr := ''; Value := ''; Optional := '';
DateFormat := ''; DateFormatType := ''; Map_Values := '';
for J := 0 to TransNode.attributes.length-1 do
begin
TmpNode := TransNode.attributes.item[J];
if TmpNode.NodeName = mx_FROM then
From := TmpNode.nodeValue
else if TmpNode.NodeName = mx_DEST then
Dest := TmpNode.nodeValue
else if TmpNode.NodeName = mx_VALUE then
Value := TmpNode.nodeValue
else if TmpNode.NodeName = mx_OPTIONAL then
Optional := TmpNode.nodeValue
else if TmpNode.NodeName = mx_ID then
Idstr := TmpNode.nodeValue
else if TmpNode.NodeName = mx_DEFAULT then
DefaultValue := TmpNode.nodeValue
else if (TmpNode.NodeName = mx_DATETIMEFORMAT) or
(TmpNode.NodeName = mx_DATEFORMAT) or
(TmpNode.NodeName = mx_TIMEFORMAT) then
begin
DateFormat := TmpNode.NodeValue;
DateFormatType := TmpNode.NodeName;
end
else if TmpNode.NodeName = mx_MAPVALUES then
Map_Values := TmpNode.NodeValue;
end; // for
if InFromList <> nil then
begin
InFromList.Add(From);
InDestList.Add(Dest);
InIdStrList.Add(IdStr);
InValueList.Add(Value);
InOptionalList.Add(Optional);
InDateFormatList.Add(DateFormat);
InDateFormatTypeList.Add(DateFormatType);
InMapValuesList.Add(Map_Values);
end;
end // if (InFromList = nil) ...
else
begin
From := InFromList[Count];
Dest := InDestList[Count];
IdStr := InIdStrList[Count];
Value := InValueList[Count];
Optional := InOptionalList[Count];
DateFormat := InDateFormatList[Count];
DateFormatType := InDateFormatTypeList[Count];
Map_Values := InMapValuesList[Count];
end;
SrcNode := SelectNode(SrcNode, From);
if SrcNode <> nil then
begin
if Value = '' then
begin
if SrcNode.nodeType = ELEMENT_NODE then
Value := (SrcNode as IDOMNodeEx).Text
else
Value := SrcNode.nodeValue;
end;
if (IdStr <> '') and Assigned(FOnTranslate) then
FOnTranslate(Self, IdStr, SrcNode, Value, DestNode);
end;
if Value = '' then
if DefaultValue <> '' then
Value := DefaultValue;
if Value <> '' then
begin
if Map_Values <> '' then
Value := MapValues(Map_Values, Value);
if Value = '' then
if DefaultValue <> '' then
Value := DefaultValue;
if DateFormatType <> '' then
Value := MapDateTime(DateFormatType, DateFormat, Value, FDirectionToCds);
if (Optional = '') or (Value <> '') then
PutValue(DestNode, Dest, Value);
end
else if Optional = '' then // = '1'
PutValue(DestNode, Dest, '');
if (Optional <> '') and (Value = '') and
(Dest <> '') and (Dest[1] <> '@') then
begin
TmpNode := SelectNode(DestNode, Dest);
if TmpNode <> nil then
TmpNode.parentNode.removeChild(TmpNode);
end;
end; // else if TransNode.NodeName = mx_Translate
end;
end.
|
{ * ------------------------------------------------------------------------
* ♥ Akademia BSC © 2019 ♥
* ----------------------------------------------------------------------- * }
unit TestBoard;
interface
uses
System.Generics.Collections, System.SysUtils, System.Classes,
TestFramework,
Model.Board;
type
TestTBoard = class(TTestCase)
strict private
FBoard: TBoard;
private
public
procedure SetUp; override;
procedure TearDown; override;
published
// TBoard.Generate
procedure TestGenerate10Data;
procedure TestGenerateZeroData;
procedure TestGenerateNegativeNumberOfData;
// TBorad.Swap:
procedure TestSwapZeroAndOne;
procedure TestSwapTwoLastValues;
procedure TestSwapNegativeIndexes;
procedure TestSwapOutOfRangeIndex;
// TBorad.SortBubble:
procedure TestSortBubble_123;
procedure TestSortBubble_312;
procedure TestSortBubble_111;
procedure TestSortBubble_EmptyData;
procedure TestSortBubble_50Random_Range1ToMax;
// TBorad.Sort... :
procedure TestSortInsertion_321;
procedure TestSortQuick_321;
end;
implementation
procedure TestTBoard.SetUp;
begin
FBoard := TBoard.Create;
end;
procedure TestTBoard.TearDown;
begin
FBoard.Free;
FBoard := nil;
end;
procedure TestTBoard.TestGenerate10Data;
begin
FBoard.GenerateData(10);
CheckEquals(10, FBoard.Count, 'Nieodpowiednia liczba danych');
(*
Self.CheckEquals (expected, actual, msg)
- sprawdza czy actual = expected i jeśli nie jest to zwraca negatywny
wynik testu
- tylko w przyapdku negatywnego wyniku wyświetalny jest komunikat msg
*)
end;
procedure TestTBoard.TestGenerateZeroData;
begin
// TODO: [TeamA] Zweyfikuj działanie grerate dla 0
// TODO: [TeamD] j.w. = takie same zadanie
(*
Kroki:
1. Generate(n), gdzie n>=1 - wypełnij dowolną liczbą danych
2. Gerate(0) - wypełniż zero elementów
3. Zweryfikuj czy Count = 0
4. Zweryfikuj czy Length(Data)=0
*)
end;
procedure TestTBoard.TestGenerateNegativeNumberOfData;
begin
// TODO: [TeamC] Wpełnić FBoard ujemną liczbą danych
(*
Użyj fukcji Self.StartExpectingException oraz Self.StopExpectingException
Zobacz w żródłach: TestFramework.pas
*)
end;
procedure TestTBoard.TestSwapZeroAndOne;
begin
// TODO: [TeamA] Zweryfkować swap indeksów 0 i 1
// Uwaga! Najpierw trzeba wypełnić dane
end;
procedure TestTBoard.TestSwapTwoLastValues;
begin
// TODO: [TeamA] Zweryfkować swap dwóch ostatnich indeksów max-2 oraz max-1
// Uwaga! Trzeba wypełnić dane przynajmiej 3 elementami
end;
procedure TestTBoard.TestSwapNegativeIndexes;
begin
// TODO: [TeamC] Zweryfkować czy swap dwóch ujemnych indeksów rzuca wyjątkiem
end;
procedure TestTBoard.TestSwapOutOfRangeIndex;
begin
// TODO: [TeamD] Zweryfkować czy swap dwóch indeksów dodatkich z poza zakresu
// rzuca wyjątkiem
end;
procedure TestTBoard.TestSortBubble_123;
begin
// TODO: [TeamA] wypełnij tablicę danymi [1, 2, 3] uruchom sortowanie
// bąbelkowe oraz zweryfikuj czy dane wynikowe są posortowanie
end;
procedure TestTBoard.TestSortBubble_312;
begin
// TODO: [TeamC] wypełnij tablicę danymi [1, 2, 3] uruchom sortowanie
// bąbelkowe oraz zweryfikuj czy dane wynikowe są posortowanie
end;
procedure TestTBoard.TestSortBubble_111;
begin
// TODO: [TeamD] wypełnij tablicę danymi [1, 1, 1] uruchom sortowanie
// bąbelkowe oraz zweryfikuj czy dane wynikowe są posortowanie
end;
procedure TestTBoard.TestSortBubble_EmptyData;
begin
// [TeamC] Sprawdź czy sortowanie zadziała poprawnie dla pustego
// zbioru danych. Weryfikacja ma sprawdzić czy nie poawił się wyjątek
end;
procedure TestTBoard.TestSortBubble_50Random_Range1ToMax;
begin
// TODO: [TeamA] Sprawdź czy sortowanie zadziała poprawnie dla pustego
// TODO: [TeamD] j.w. = takie same zadanie
end;
procedure TestTBoard.TestSortInsertion_321;
begin
// TODO: [TeamA] Sprawdzić sortowanie InsertionSort na danych [3, 2, 1]
// TODO: [TeamC] j.w.
// TODO: [TeamD] j.w.
end;
procedure TestTBoard.TestSortQuick_321;
begin
// TODO: [TeamA] Sprawdzić sortowanie QuickSort na danych [3, 2, 1]
// TODO: [TeamC] j.w.
// TODO: [TeamD] j.w.
end;
initialization
RegisterTest(TestTBoard.Suite);
end.
|
unit main04;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids,
Generics.Collections, Ap, mlpbase;
type
TForm2 = class(TForm)
Image1: TImage;
edInputText: TEdit;
Label1: TLabel;
sgResults: TStringGrid;
procedure FormShow(Sender: TObject);
procedure edInputTextChange(Sender: TObject);
private
{ Private declarations }
FBitmap: TBitmap;
FCharList: TList<char>;
lXY: TReal2DArray;
lNetwork: MultiLayerPerceptron;
procedure PrintChar(aCanvas: TCanvas; const aStr: string);
procedure SetBitmapDefaultProps(aBitmap: TBitmap);
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
uses calc_utils;
{$R *.dfm}
const
ImageSizeW = 20;
ImageSizeH = 25;
ImagePixelCount = ImageSizeW * ImageSizeH;
procedure TForm2.edInputTextChange(Sender: TObject);
var
i: Integer;
lX, lY: TReal1DArray;
begin
if Length(edInputText.Text) > 1 then
edInputText.Text := copy(edInputText.Text, 0, 1);
PrintChar(Image1.Picture.Bitmap.Canvas, edInputText.Text);
SetLength(lX, ImagePixelCount);
SetLength(lY, FCharList.Count);
Get1DArrayFromImage(Image1.Picture.Bitmap.Canvas, ImageSizeW, ImageSizeH, lX);
MLPProcess(lNetwork, lX, lY);
sgResults.RowCount := FCharList.Count + 1;
for i := 0 to FCharList.Count - 1 do
begin
sgResults.Cells[0, i + 1] := FCharList[i];
sgResults.Cells[1, i + 1] := FloatToStr(lY[i]);
end;
SetLength(lX, 0);
SetLength(lY, 0);
end;
const cReservedCharsCount = 2;
procedure TForm2.FormShow(Sender: TObject);
var
i: Integer;
ch: char;
begin
SetBitmapDefaultProps(Image1.Picture.Bitmap);
FBitmap := TBitmap.Create;
SetBitmapDefaultProps(FBitmap);
// добавим все используемые символы
FCharList := TList<char>.Create;
for ch := 'A' to 'Z' do
FCharList.Add(ch);
for ch := 'А' to 'Я' do
FCharList.Add(ch);
FCharList.Add(#0000);
FCharList.Add(#0001);
// формируем нейросеть
NewEmptyMatrix(ImagePixelCount + 1, FCharList.Count, lXY);
for i := 0 to FCharList.Count - 1 - cReservedCharsCount do
begin
PrintChar(FBitmap.Canvas, FCharList[i]);
PutImageToArrayLine(i, i, FBitmap.Canvas, ImageSizeW, ImageSizeH, lXY);
end;
// добавим зарезервированные варианты, которые должны дать 0
for i := FCharList.Count - cReservedCharsCount to FCharList.Count - 1 do
begin
PrintChar(FBitmap.Canvas, FCharList[i]);
PutImageToArrayLine(i, -1, FBitmap.Canvas, ImageSizeW, ImageSizeH, lXY);
end;
// обучение нейросети
// для задачи с символами количество слоёв не важно. Важнее количество вариантов
CalcNeuroMatrix(True, 1, ImagePixelCount, FCharList.Count - cReservedCharsCount, lXY, lNetwork);
// отобразим букву
edInputText.Text := 'W';
end;
procedure TForm2.PrintChar(aCanvas: TCanvas; const aStr: string);
begin
aCanvas.Lock;
if (aStr[1] in [#0000, #0001]) then
begin
if (aStr[1] = #0000) then
aCanvas.Brush.Color := clBlack
else if (aStr[1] = #0001) then
aCanvas.Brush.Color := clWhite;
aCanvas.Rectangle(0, 0, ImageSizeW, ImageSizeH);
end
else
begin
aCanvas.Brush.Color := clWhite;
aCanvas.Rectangle(0, 0, ImageSizeW, ImageSizeH);
aCanvas.TextOut(0, 0, aStr);
end;
aCanvas.Unlock;
end;
procedure TForm2.SetBitmapDefaultProps(aBitmap: TBitmap);
begin
// set image params
aBitmap.SetSize(ImageSizeW, ImageSizeH);
aBitmap.Canvas.Brush.Color := clWhite;
aBitmap.Canvas.Brush.Style := bsSolid;
aBitmap.Canvas.Pen.Color := clWhite;
aBitmap.Canvas.Font.Size := 14;
end;
end.
|
unit Vigilante.Controller.Mediator.Impl;
interface
uses
System.Generics.Collections, Module.ValueObject.URL,
Vigilante.Controller.Base, Vigilante.Controller.Mediator;
type
TControllerMediator = class(TInterfacedObject, IControllerMediator)
private
FControllers: TDictionary<TTipoController, IBaseController>;
public
constructor Create;
destructor Destroy; override;
procedure AdicionarController(const AController: IBaseController;
const ATipoController: TTipoController);
procedure AdicionarURL(const ATipoController: TTipoController;
const AURL: IURL);
procedure RemoverController(const ATipoController: TTipoController);
end;
implementation
uses
System.SysUtils;
constructor TControllerMediator.Create;
begin
FControllers := TDictionary<TTipoController, IBaseController>.Create;
end;
destructor TControllerMediator.Destroy;
begin
FControllers.Clear;
FreeAndNil(FControllers);
inherited;
end;
procedure TControllerMediator.AdicionarController(
const AController: IBaseController; const ATipoController: TTipoController);
begin
FControllers.AddOrSetValue(ATipoController, AController);
end;
procedure TControllerMediator.AdicionarURL(
const ATipoController: TTipoController; const AURL: IURL);
begin
FControllers.Items[ATipoController].AdicionarNovaURL(AURL);
end;
procedure TControllerMediator.RemoverController(
const ATipoController: TTipoController);
begin
FControllers.Remove(ATipoController);
end;
end.
|
unit class_ctor_1;
interface
uses System;
type
TC1 = class
a, b, c: int32;
constructor Create;
end;
implementation
var
C: TC1;
GA, GB, GC: Int32;
constructor TC1.Create;
begin
a := 11;
b := 22;
c := 33;
end;
procedure Test;
begin
C := TC1.Create();
GA := C.a;
GB := C.b;
GC := C.c;
end;
initialization
Test();
finalization
Assert(GA = 11);
Assert(GB = 22);
Assert(GC = 33);
end. |
UNIT cmdLineParseUtil;
INTERFACE
USES sysutils;
TYPE
T_extendedParameter=record
isFile:boolean;
leadingSign:char;
cmdString:string;
intParam:array of longint;
floatParam:array of double;
stringSuffix:string;
end;
T_commandAbstraction=record
isFile:boolean;
leadingSign:char;
cmdString:string;
paramCount:longint;
end;
FUNCTION extendedParam(index:longint):T_extendedParameter;
FUNCTION extendedParam(s:string ):T_extendedParameter;
FUNCTION matches(ep:T_extendedParameter; ca:T_commandAbstraction):boolean;
FUNCTION matchingCmdIndex(ep:T_extendedParameter; cmdList: array of T_commandAbstraction):longint;
FUNCTION gotParam(cmd:T_commandAbstraction):boolean;
FUNCTION getParam(cmd:T_commandAbstraction):T_extendedParameter;
IMPLEMENTATION
FUNCTION extendedParam(s:string):T_extendedParameter;
VAR i:longint;
begin
setLength(result.intParam,0);
setLength(result.floatParam,0);
result.stringSuffix:='';
result.leadingSign:=s[1];
if result.leadingSign in ['.','a'..'z','A'..'Z','_','0'..'9'] then begin
result.isFile:=true;
result.cmdString:=s;
result.stringSuffix:=s;
end else begin
result.isFile:=false;
s:=copy(s,2,length(s)-1); //remove leading '-'
result.cmdString:='';
i:=1;
while (s[i] in ['a'..'z','A'..'Z']) and (i<=length(s)) do begin
result.cmdString:=result.cmdString+s[i];
inc(i);
end;
s:=copy(s,i,length(s));
if (length(s)>0) and (s[1] in [':',',']) then s:=copy(s,2,length(s)-1);
result.stringSuffix:=s;
while length(s)>0 do begin
i:=1;
while (i<=length(s)) and (not(s[i] in ['x',',',':','='])) do inc(i);
with result do begin
setLength(floatParam,length(floatParam)+1);
setLength(intParam ,length(intParam)+1);
floatParam[length(floatParam)-1]:=strToFloatDef(copy(s,1,i-1),0);
intParam [length(intParam) -1]:=strToIntDef (copy(s,1,i-1),0);
end;
s:=copy(s,i+1,length(s));
end;
end;
end;
FUNCTION extendedParam(index:longint):T_extendedParameter;
begin
result:=extendedParam(paramStr(index));
end;
FUNCTION matches(ep:T_extendedParameter; ca:T_commandAbstraction):boolean;
begin
result:=(ep.isFile) and (ca.isFile) or
not(ep.isFile) and
not(ca.isFile) and
(ep.leadingSign=ca.leadingSign) and
(ep.cmdString=ca.cmdString) and
((ca.paramCount=-1) or (length(ep.floatParam)=ca.paramCount));
end;
FUNCTION matchingCmdIndex(ep:T_extendedParameter; cmdList: array of T_commandAbstraction):longint;
begin
result:=low(cmdList);
while (result<=high(cmdList)) and not(matches(ep,cmdList[result])) do inc(result);
end;
FUNCTION gotParam(cmd:T_commandAbstraction):boolean;
VAR i:longint;
begin
result:=false;
for i:=1 to paramCount do result:=result or matches(extendedParam(i),cmd);
end;
FUNCTION getParam(cmd:T_commandAbstraction):T_extendedParameter;
VAR i:longint;
begin
i:=1;
while (i<=paramCount) and not(matches(extendedParam(i),cmd)) do inc(i);
if i<=paramCount then result:=extendedParam(i);
end;
INITIALIZATION
DefaultFormatSettings.DecimalSeparator:='.';
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 65520,0,200000}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 118 Backtrack Method with Many Bounds
}
program
RectangularCover;
const
MaxNum = 20 + 1;
MaxRect = MaxNum * MaxNum;
type
Arr1 = array [0 .. MaxNum + 1, 0 .. MaxNum + 1] of Integer;
Arr4 = array [0 .. MaxNum * MaxNum] of Record I, J : Integer; end;
Arr6 = array [0 .. MaxRect] of Integer;
Arr7 = array [0 .. MaxNum * MaxNum] of Integer;
Arr2 = array [0 .. MaxRect, 1 .. 4] of Integer;
PArr = ^ Arr3;
Arr3 = array [1 .. MaxNum, 1 .. MaxNum, 1 .. MaxNum] of Integer;
Arr5 = array [1 .. MaxRect] of Integer;
var
M, N, RecN : Integer;
Mat : Arr1;
Index : Arr4;
Ans, BestAns : Arr5;
Mark : Arr6;
Mark2 : Arr7;
Num, BestNum : Integer;
Rects : Arr2;
InRectsN : Arr1;
InRects : PArr;
I, J, P, Q, R, S, O : Integer;
Flag, Flag2 : Boolean;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
ReadLn(M, N);
for I := 1 to M do
for J := 1 to N do
Read(Mat[I, J]);
Close(Input);
end;
procedure WriteOutput;
begin
Assign(Output, 'output.txt');
ReWrite(Output);
if BestNum < MaxInt then
begin
Writeln(BestNum);
for I := 1 to BestNum do
Writeln(Rects[BestAns[I], 1], ' ', Rects[BestAns[I], 2], ' ',
Rects[BestAns[I], 3], ' ', Rects[BestAns[I], 4]);
end;
Close(Output);
end;
procedure FindRects;
begin
for I := 1 to M do
for P := I to M do
begin
J := 1;
while J <= N do
begin
Flag := False;
for R := I to P do
if Mat[R, J - 1] = 0 then
begin Flag := True; Break; end;
if not Flag then Continue;
Q := J - 1;
while Flag = True do
begin
Inc(Q);
for R := I to P do
if Mat[R, Q] = 0 then
begin Flag := False; Break; end;
end;
Dec(Q);
if Q >= J then
begin
Flag := False;
for R := J to Q do
if Mat[I - 1, R] = 0 then
begin Flag := True; Break; end;
if Flag then
begin
Flag := False;
for R := J to Q do
if Mat[P + 1, R] = 0 then
begin Flag := True; Break; end;
if Flag then
begin Inc(RecN); Rects[RecN, 1] := I; Rects[RecN, 2] := J; Rects[RecN, 3] := P; Rects[RecN, 4] := Q; end;
end;
end;
J := Q + 2;
end;
end;
end;
procedure SortRects;
procedure QSort(l, r: Integer);
function s(o : Integer) : Integer;
begin s := (rects[o,3] - rects[o,1]{ + 1}) * (rects[o,4] - rects[o,2]{ + 1}); end;
var
i, j, x : integer;
begin
i := l; j := r; x := s((l+r) DIV 2);
repeat
while s(i) > x do i := i + 1;
while x > s(j) do j := j - 1;
if i <= j then
begin
rects[0] := rects[i]; rects[i] := rects[j]; rects[j] := rects[0];
i := i + 1; j := j - 1;
end;
until i > j;
if l < j then QSort(l, j);
if i < r then QSort(i, r);
end;
begin
QSort(1, RecN);
end;
procedure AssignRects;
begin
for P := 1 to RecN do
for I := Rects[P, 1] to Rects[P, 3] do
for J := Rects[P, 2] to Rects[P, 4] do
begin Inc(InRectsN[I, J]); InRects^[I, J, InRectsN[I, J]] := P; end;
end;
procedure SortIndexes;
procedure QSort(l, r: Integer);
var
i, j, x : integer;
begin
i := l; j := r; x := InRectsN[Index[(l+r) DIV 2].I,Index[(l+r) DIV 2].J];
repeat
while InRectsN[Index[i].I,Index[i].J] > x do i := i + 1;
while x > InRectsN[Index[j].I,Index[j].J] do j := j - 1;
if i <= j then
begin
index[0] := index[i]; index[i] := index[j]; index[j] := index[0];
i := i + 1; j := j - 1;
end;
until i > j;
if l < j then QSort(l, j);
if i < r then QSort(i, r);
end;
begin
P := 0;
for I := 1 to M do
for J := 1 to N do
if Mat[I, J] = 1 then begin Inc(P); Index[P].I := I; Index[P].J := J; end;
QSort(1, P);
end;
procedure Init;
begin
New(InRects);
Mark2[0] := 0;
RecN := 0;
Num := 0;
BestNum := MaxInt;
FindRects;
SortRects;
AssignRects;
SortIndexes;
end;
procedure Found;
begin
BestNum := Num;
Move(Ans, BestAns, Num shl 1 + 4);
end;
procedure BackTrack (L : Integer);
var
I, TTTT : Integer;
procedure Put;
begin
Ans[Num] := TTTT;
for P := Rects[Ans[Num], 1] to Rects[Ans[Num], 3] do
for Q := Rects[Ans[Num], 2] to Rects[Ans[Num], 4] do
Dec(Mat[P, Q]);
end;
procedure Pick;
begin
for P := Rects[Ans[Num], 1] to Rects[Ans[Num], 3] do
for Q := Rects[Ans[Num], 2] to Rects[Ans[Num], 4] do
Inc(Mat[P, Q]);
end;
function FindNextPoint : Boolean;
begin
O := L - 1;
while (Mat[Index[O].I, Index[O].J] <= 0) and (O > 0) do
Dec(O);
FindNextPoint := O > 0;
end;
begin {BackTrack}
If Num < BestNum - 1 then
begin
Inc(Num);
Mark2[L] := 1;
for I := 1 to InRectsN[Index[L].I, Index[L].J] do
begin
TTTT := InRects^[Index[L].I, Index[L].J, I];
if (Mark2[Mark[TTTT]] = 0) or (Mark[TTTT] = L) then
begin
Mark[TTTT] := L;
Put;
if FindNextPoint then
BackTrack(O)
else
begin
Found;
Pick;
Break;
end;
Pick;
end;
end;
Mark2[L] :=0;
Dec(Num);
end
end;
procedure Solve;
begin
Init;
if P > 0 then
BackTrack(P)
else
BestNum := 0;
end;
begin
ReadInput;
Solve;
WriteOutput;
end. |
unit URepositorioTodasVacinas;
interface
uses
UTodasVacinas
, UEntidade
, URepositorioDB
, SqlExpr
;
type
TRepositorioTodasVacinas = class(TRepositorioDB<TTODASVACINAS>)
private
public
constructor Create;
//destructor Destroy; override;
procedure AtribuiDBParaEntidade(const coTODASVACINAS: TTODASVACINAS); override;
procedure AtribuiEntidadeParaDB(const coTODASVACINAS: TTODASVACINAS;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
, SysUtils
, StrUtils
;
{ TRepositorioCoren }
constructor TRepositorioTODASVACINAS.Create;
begin
inherited Create(TTODASVACINAS, TBL_TODAS_VACINAS, FLD_ENTIDADE_ID, STR_TODAS_VACINAS);
end;
procedure TRepositorioTODASVACINAS.AtribuiDBParaEntidade(const coTODASVACINAS: TTODASVACINAS);
begin
inherited;
with FSQLSelect do
begin
coTODASVACINAS.NOME_VACINA := FieldByName(FLD_NOME_VACINA ).AsString ;
coTODASVACINAS.DESCRICAO := FieldByName(FLD_DESCRICAO ).AsString ;
coTODASVACINAS.IDADE_INDICADA := FieldByName(FLD_IDADE_INDICADA).AsString;
coTODASVACINAS.TOTAL_DOSES := FieldByName(FLD_TOTAL_DOSES).AsString;
coTODASVACINAS.RESTRICAO := FieldByName(FLD_RESTRICAO).AsString;
end;
end;
procedure TRepositorioTODASVACINAS.AtribuiEntidadeParaDB(const coTODASVACINAS: TTODASVACINAS;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_NOME_VACINA).AsString := coTODASVACINAS.NOME_VACINA;
ParamByName(FLD_DESCRICAO).AsString := coTODASVACINAS.DESCRICAO ;
ParamByName(FLD_IDADE_INDICADA).AsString := coTODASVACINAS.IDADE_INDICADA ;
ParamByName(FLD_TOTAL_DOSES).AsString := coTODASVACINAS.TOTAL_DOSES ;
ParamByName(FLD_RESTRICAO).AsString := coTODASVACINAS.RESTRICAO;
end;
end;
end.
|
{**********************************************}
{ TAxisMaxMin Dialog Editor }
{ Copyright (c) 1996-2004 David Berneda }
{**********************************************}
unit TeeAxMaxMin;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls,
{$ENDIF}
Classes, SysUtils;
type
TAxisMaxMin = class(TForm)
BitBtn1: TButton;
BitBtn2: TButton;
EMaximum: TEdit;
EMinimum: TEdit;
Label1: TLabel;
Label2: TLabel;
procedure FormShow(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
IsDateTime : Boolean;
MaxMin : Double;
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeProcs, TeeConst, TeeAxisIncr;
procedure TAxisMaxMin.FormShow(Sender: TObject);
begin
if IsDateTime then
Begin
if MaxMin>=1 then EMaximum.Text:=DateToStr(MaxMin)
else
Begin
Label1.Visible:=False;
EMaximum.Visible:=False;
end;
EMinimum.Text:=TimeToStr(MaxMin);
end
else
begin
EMaximum.Hint:='';
EMinimum.Hint:='';
Label1.Caption:='Value:'; // <-- do not translate
EMaximum.Text:=FloatToStr(MaxMin);
Label2.Visible:=False;
EMinimum.Visible:=False;
end;
end;
procedure TAxisMaxMin.BitBtn1Click(Sender: TObject);
begin
try
if IsDateTime then
begin
if EMaximum.Visible then
MaxMin:=StrToDateTime(EMaximum.Text+' '+EMinimum.Text)
else
MaxMin:=StrToTime(EMinimum.Text);
end
else MaxMin:=StrToFloat(EMaximum.Text);
ModalResult:=mrOk;
except
on E:Exception do TeeShowIncorrect(E.Message);
end;
end;
procedure TAxisMaxMin.FormCreate(Sender: TObject);
begin
BorderStyle:=TeeBorderStyle;
end;
end.
|
unit hmackecc;
{HMAC-Keccak unit}
interface
(*************************************************************************
DESCRIPTION : HMAC (hash message authentication) unit for Keccak
REQUIREMENTS : TP5-7, D1-D7/D9-D12, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : - HMAC: Keyed-Hashing for Message Authentication
(http://tools.ietf.org/html/rfc2104)
- The Keyed-Hash Message Authentication Code (HMAC)
http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf
- US Secure Hash Algorithms (SHA and HMAC-SHA)
(http://tools.ietf.org/html/rfc4634)
- Keccak sponge function family main document, sections 4.2.3 and 4.2.1
http://keccak.noekeon.org/Keccak-main-2.1.pdf
- David Ireland's "Test vectors for HMAC-SHA-3" from
http://www.di-mgt.com.au/hmac_sha3_testvectors.html
REMARKS : Provisional HMAC-Keccak routines (as for SHA3 there is no
official specification). Using D. Ireland's parameters, the
input block length used in the HMAC algorithm is state.rate.
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.01 09.11.12 W.Ehrhardt Initial version
0.02 10.11.12 we Use context.Err
0.03 11.11.12 we BIT API
0.04 13.11.12 we removed context.DigLen
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2012 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
uses
BTypes,keccak_n;
type
THMACKec_Context = record
hashctx: THashState;
hmacbuf: array[0..143] of byte;
BlkLen : integer;
Err : integer;
end;
procedure hmac_keccak_init(var ctx: THMACKec_Context; hashbitlen: integer; key: pointer; klen: word);
{-Initialize HMAC context for Keccak with hashbitlen (224, 256, 384, or 512) }
{ and klen key bytes from and key^}
procedure hmac_keccak_inits(var ctx: THMACKec_Context; hashbitlen: integer; skey: Str255);
{-Initialize HMAC context for Keccak with hashbitlen (224, 256, 384, or 512) and key from skey}
procedure hmac_keccak_update(var ctx: THMACKec_Context; data: pointer; dlen: word);
{-HMAC data input, may be called more than once}
procedure hmac_keccak_updateXL(var ctx: THMACKec_Context; data: pointer; dlen: longint);
{-HMAC data input, may be called more than once}
procedure hmac_keccak_final(var ctx: THMACKec_Context; var mac: TKeccakMaxDigest);
{-End data input and calculate HMAC digest}
procedure hmac_keccak_finalbits(var ctx: THMACKec_Context; var mac: TKeccakMaxDigest; BData: byte; bitlen: integer);
{-End data input with bitlen bits from BData and calculate HMAC digest}
implementation
{---------------------------------------------------------------------------}
procedure hmac_keccak_init(var ctx: THMACKec_Context; hashbitlen: integer; key: pointer; klen: word);
{-Initialize HMAC context for Keccak with hashbitlen (224, 256, 384, or 512) }
{ and klen key bytes from and key^}
var
k: integer;
begin
fillchar(ctx, sizeof(ctx),0);
with ctx do begin
Err := Init(ctx.hashctx, hashbitlen);
if Err<>0 then exit;
BlkLen := hashctx.rate div 8;
if klen > BlkLen then begin
{Hash if key length > block length}
Err := Update(ctx.hashctx, key, klen*8);
if Err=0 then Err := Final(ctx.hashctx, @ctx.hmacbuf);
end
else move(key^, hmacbuf, klen);
if Err=0 then begin
{XOR with ipad}
for k:=0 to BlkLen-1 do hmacbuf[k] := hmacbuf[k] xor $36;
{start inner hash}
Err := Init(hashctx, hashbitlen);
if Err=0 then Err := Update(hashctx, @hmacbuf, BlkLen*8);
end;
end;
end;
{---------------------------------------------------------------------------}
procedure hmac_keccak_inits(var ctx: THMACKec_Context; hashbitlen: integer; skey: Str255);
{-Initialize HMAC context for Keccak with hashbitlen (224, 256, 384, or 512) and key from skey}
begin
hmac_keccak_init(ctx, hashbitlen, @skey[1], length(skey));
end;
{---------------------------------------------------------------------------}
procedure hmac_keccak_update(var ctx: THMACKec_Context; data: pointer; dlen: word);
{-HMAC data input, may be called more than once}
begin
with ctx do begin
if Err=0 then Err := Update(hashctx, data, longint(dlen)*8);
end;
end;
{---------------------------------------------------------------------------}
procedure hmac_keccak_updateXL(var ctx: THMACKec_Context; data: pointer; dlen: longint);
{-HMAC data input, may be called more than once}
begin
with ctx do begin
if Err=0 then Err := Update(hashctx, data, longint(dlen)*8);
end;
end;
{---------------------------------------------------------------------------}
procedure hmac_keccak_finalbits(var ctx: THMACKec_Context; var mac: TKeccakMaxDigest; BData: byte; bitlen: integer);
{-End data input with bitlen bits from BData and calculate HMAC digest}
var
i: integer;
begin
with ctx do if Err=0 then begin
{append the final bits from BData}
if (bitlen>0) and (bitlen<=7) then Err := Update(hashctx, @BData, bitlen);
{complete inner hash}
if Err=0 then Err := Final(hashctx, @mac);
{remove ipad from buf, XOR opad}
if Err=0 then begin
for i:=0 to ctx.BlkLen-1 do ctx.hmacbuf[i] := ctx.hmacbuf[i] xor ($36 xor $5c);
{outer hash}
i := hashctx.fixedOutputLength;
Err := Init(hashctx, i);
if Err=0 then Err := Update(hashctx, @hmacbuf, BlkLen*8);
if Err=0 then Err := Update(hashctx, @mac, i);
if Err=0 then Err := Final(hashctx, @mac);
end;
end;
end;
{---------------------------------------------------------------------------}
procedure hmac_keccak_final(var ctx: THMACKec_Context; var mac: TKeccakMaxDigest);
{-End data input and calculate HMAC digest}
begin
hmac_keccak_finalbits(ctx, mac, 0, 0);
end;
end.
|
unit fUserData;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ToolWin, Ex_Grid, Ex_Inspector, ActnList, ImgList,
FlexBase, FlexProps;
type
TfmUserData = class(TForm)
tbMain: TToolBar;
tbNew: TToolButton;
tbDelete: TToolButton;
imgToolIcons: TImageList;
ToolButton3: TToolButton;
tbMoveUp: TToolButton;
tbMoveDown: TToolButton;
alMain: TActionList;
acUserPropAdd: TAction;
acUserPropDelete: TAction;
acUserPropMoveUp: TAction;
acUserPropMoveDown: TAction;
grUserProps: TExInspector;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure grUserPropsGetCellText(Sender: TObject; Cell: TGridCell;
var Value: String);
procedure grUserPropsSetEditText(Sender: TObject; Cell: TGridCell;
var Value: String);
procedure grUserPropsChange(Sender: TObject; Cell: TGridCell;
Selected: Boolean);
procedure tbNewClick(Sender: TObject);
procedure tbDeleteClick(Sender: TObject);
procedure tbMoveUpClick(Sender: TObject);
procedure tbMoveDownClick(Sender: TObject);
private
{ Private declarations }
FActiveFlex: TFlexPanel;
FLastControl: TFlexControl;
procedure CheckTools;
procedure SetActiveFlex(const Value: TFlexPanel);
function GetSelControl: TFlexControl;
procedure DrawCell(Sender: TObject; Cell: TGridCell;
var Rect: TRect; var DefaultDrawing: Boolean);
public
{ Public declarations }
property ActiveFlex: TFlexPanel read FActiveFlex write SetActiveFlex;
property SelControl: TFlexControl read GetSelControl;
procedure UpdateData;
end;
var
fmUserData: TfmUserData;
implementation
uses ToolMngr;
{$R *.DFM}
procedure TfmUserData.FormCreate(Sender: TObject);
begin
RegisterToolForm(Self);
with grUserProps do begin
Columns[0].ReadOnly := False;
Columns[0].TabStop := True;
Columns[0].Width := 80;
Fixed.Count := 0;
OnDrawCell := DrawCell;
//AlwaysEdit := false;
end;
CheckTools;
end;
procedure TfmUserData.FormDestroy(Sender: TObject);
begin
UnRegisterToolForm(Self);
end;
procedure TfmUserData.CheckTools;
var DataExists: boolean;
Control: TFlexControl;
begin
Control := SelControl;
if Assigned(Control)
then DataExists := Control.UserData.LinesCount > 0
else DataExists := False;
tbNew.Enabled := Assigned(Control);
tbDelete.Enabled := DataExists;
if DataExists then begin
tbMoveUp.Enabled := grUserProps.CellFocused.Row > 0;
tbMoveDown.Enabled :=
grUserProps.CellFocused.Row < Control.UserData.LinesCount-1;
end else begin
tbMoveUp.Enabled := False;
tbMoveDown.Enabled := False;
end;
end;
procedure TfmUserData.UpdateData;
var Control: TFlexControl;
begin
Control := SelControl;
with grUserProps do begin
if Assigned(FLastControl) and (FLastControl <> Control) then Editing := False;
if Assigned(Control) then begin
Rows.Count := Control.UserData.LinesCount;
if Editing then Edit.Text := Cells[EditCell.Col, EditCell.Row];
if EditCell.Row >= 0 then begin
AlwaysEdit := False;
Editing := False;
AlwaysEdit := True;
end;
end else begin
Rows.Count := 0;
AlwaysEdit := False;
Editing := False;
AlwaysEdit := True;
end;
Invalidate;
end;
CheckTools;
FLastControl := Control;
end;
function TfmUserData.GetSelControl: TFlexControl;
begin
if Assigned(FActiveFlex) and (FActiveFlex.SelectedCount = 1)
then Result := FActiveFlex.Selected[0]
else Result := Nil;
end;
procedure TfmUserData.SetActiveFlex(const Value: TFlexPanel);
begin
if Value = FActiveFlex then exit;
if not Assigned(Value) then FLastControl := Nil;
FActiveFlex := Value;
UpdateData;
end;
procedure TfmUserData.DrawCell(Sender: TObject; Cell: TGridCell;
var Rect: TRect; var DefaultDrawing: Boolean);
begin
DefaultDrawing := true;
if Cell.Col = 0 then with TGridView(grUserProps).Canvas do begin
Pen.Color := clBtnShadow;
Pen.Width := 1;
MoveTo(Rect.Right - 2, Rect.Top - 1);
LineTo(Rect.Right - 2, Rect.Bottom);
Pen.Color := clBtnHighlight;
MoveTo(Rect.Right - 1, Rect.Bottom - 1);
LineTo(Rect.Right - 1, Rect.Top - 1);
dec(Rect.Right, 2);
end;
end;
procedure TfmUserData.grUserPropsGetCellText(Sender: TObject;
Cell: TGridCell; var Value: String);
var Control: TFlexControl;
begin
Control := SelControl;
if Assigned(Control) then
case Cell.Col of
0: Value := Control.UserData.Names[Cell.Row];
1: Value := Control.UserData.ValuesByIndex[Cell.Row];
end;
end;
procedure TfmUserData.grUserPropsSetEditText(Sender: TObject;
Cell: TGridCell; var Value: String);
begin
if Assigned(FLastControl) then
if Cell.Col = 0
then FLastControl.UserData.Names[Cell.Row] := Value
else FLastControl.UserData.ValuesByIndex[Cell.Row] := Value;
grUserProps.InvalidateCell(Cell);
end;
procedure TfmUserData.grUserPropsChange(Sender: TObject; Cell: TGridCell;
Selected: Boolean);
begin
CheckTools;
end;
procedure TfmUserData.tbNewClick(Sender: TObject);
var Control: TFlexControl;
begin
Control := SelControl;
if Assigned(Control) then begin
grUserProps.Editing := False;
Control.UserData.Add('');
UpdateData;
grUserProps.CellFocused := GridCell(0, grUserProps.Rows.Count-1);
end;
end;
procedure TfmUserData.tbDeleteClick(Sender: TObject);
var Control: TFlexControl;
begin
Control := SelControl;
if Assigned(Control) then begin
Control.UserData.Delete(grUserProps.CellFocused.Row);
UpdateData;
end;
end;
procedure TfmUserData.tbMoveUpClick(Sender: TObject);
var Control: TFlexControl;
s1, s2: string;
begin
Control := SelControl;
if Assigned(Control) then with Control.UserData, grUserProps do begin
Editing := False;
s1 := Lines[CellFocused.Row-1];
s2 := Lines[CellFocused.Row];
Lines[CellFocused.Row-1] := s2;
Lines[CellFocused.Row] := s1;
UpdateData;
CellFocused := GridCell(CellFocused.Col, CellFocused.Row-1);
end;
end;
procedure TfmUserData.tbMoveDownClick(Sender: TObject);
var Control: TFlexControl;
s1, s2: string;
begin
Control := SelControl;
if Assigned(Control) then with Control.UserData, grUserProps do begin
Editing := False;
s1 := Lines[CellFocused.Row];
s2 := Lines[CellFocused.Row+1];
Lines[CellFocused.Row] := s2;
Lines[CellFocused.Row+1] := s1;
UpdateData;
CellFocused := GridCell(CellFocused.Col, CellFocused.Row+1);
end;
end;
end.
|
unit uDrawingEvent;
interface
uses uEventModel, uGraphicPrimitive, Graphics, uDrawingCommand, uVarArrays,
uExceptions, Variants;
const
EVENT_PLEASE_REPAINT = 'PLEASE_REPAINT';
EVENT_BACKGROUND_COLOR = 'BACKGROUND_COLOR';
type
TDrawingCommandData = class
public
class function CreateData( const aPrimitiveID: string; const aData : Variant ) : Variant; overload;
class function CreateData( const aPrimitiveID: string; const aData : array of variant ) : Variant; overload;
class function ExtractPrimitiveID( const aData : Variant ) : string;
class function ExtractColor( const aData : Variant ) : TColor;
end;
implementation
class function TDrawingCommandData.CreateData(
const aPrimitiveID: string; const aData: Variant): Variant;
begin
if aPrimitiveID = '' then ContractFailure;
Result := VA_Of( [ aPrimitiveID, aData ] );
end;
class function TDrawingCommandData.CreateData(
const aPrimitiveID: string; const aData: array of variant): Variant;
var
R : Variant;
begin
R := VA_Of( [ aPrimitiveID ] );
VA_AddOf( R, aData );
Result := R;
end;
class function TDrawingCommandData.ExtractColor(const aData: Variant): TColor;
begin
Result := TColor( VA_Get( aData, 1, clRed ) );
end;
class function TDrawingCommandData.ExtractPrimitiveID(
const aData: Variant): string;
begin
Result := VA_Get( aData, 0, 0 );
end;
end.
|
unit URepositorioPaciente;
interface
uses
UPaciente
, UEntidade
, URepositorioDB
, SqlExpr
;
type
TRepositorioPaciente = class(TRepositorioDB<TPACIENTE>)
private
public
constructor Create;
//destructor Destroy; override;
procedure AtribuiDBParaEntidade(const coPACIENTE: TPACIENTE); override;
procedure AtribuiEntidadeParaDB(const coPACIENTE: TPACIENTE;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
, SysUtils
, StrUtils
;
{ TRepositorioPACIENTE }
constructor TRepositorioPACIENTE.Create;
begin
Inherited Create(TPACIENTE, TBL_PACIENTE, FLD_ENTIDADE_ID, STR_PACIENTE);
end;
{destructor TRepositorioAeroporto.Destroy;
begin
FreeAndNil(FRepositorioCidade);
inherited;
end; }
procedure TRepositorioPACIENTE.AtribuiDBParaEntidade(
const coPACIENTE: TPACIENTE);
begin
inherited;
with FSQLSelect do
begin
coPACIENTE.CODIGO_SUS := FieldByName(FLD_CODIGO_SUS).AsString;
coPACIENTE.NOME := FieldByName(FLD_NOME).AsString;
coPACIENTE.NASCIMENTO := FieldByName(FLD_NASCIMENTO).AsDateTime;
coPACIENTE.SEXO := FieldByName(FLD_SEXO).AsString;
coPACIENTE.CPF := FieldByName(FLD_CPF).AsString;
coPACIENTE.RG := FieldByName(FLD_RG).AsInteger;
coPACIENTE.UF := FieldByName(FLD_UF).AsString;
coPACIENTE.CIDADE := FieldByName(FLD_CIDADE).AsString;
coPACIENTE.ENDERECO := FieldByName(FLD_ENDERECO).AsString;
coPACIENTE.TEL_FIXO := FieldByName(FLD_TEL_FIXO).AsString;
coPACIENTE.CELULAR := FieldByName(FLD_CELULAR).AsString;
coPACIENTE.PAI := FieldByName(FLD_PAI).AsString;
coPACIENTE.MAE := FieldByName(FLD_MAE).AsString;
coPACIENTE.ESTADO_CIVIL := FieldByName(FLD_ESTADO_CIVIL).AsString;
coPACIENTE.ORGAO_EMISSOR := FieldByName(FLD_ORGAO_EMISSOR).AsString;
coPACIENTE.DATA_EMISSAO := FieldByName(FLD_DATA_EMISSAO).AsDateTime;
coPACIENTE.BAIRRO := FieldByName(FLD_BAIRRO).AsString;
coPACIENTE.REFERENCIA := FieldByName(FLD_REFERENCIA).AsString;
coPACIENTE.TEL_COMERCIAL := FieldByName(FLD_TEL_COMERCIAL).AsString;
coPACIENTE.TIPO_SANGUE := FieldByName(FLD_TIPO_SANGUE).AsString;
coPACIENTE.PESSOA_RECADO := FieldByName(FLD_PESSOA_RECADO).AsString;
end;
end;
procedure TRepositorioPACIENTE.AtribuiEntidadeParaDB(
const coPACIENTE: TPACIENTE; const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_CODIGO_SUS).AsString := coPACIENTE.CODIGO_SUS;
ParamByName(FLD_NOME).AsString := coPACIENTE.NOME;
ParamByName(FLD_NASCIMENTO).AsDate := coPACIENTE.NASCIMENTO;
ParamByName(FLD_SEXO).AsString := coPACIENTE.SEXO;
ParamByName(FLD_CPF).AsString := coPACIENTE.CPF;
ParamByName(FLD_RG).AsInteger := coPACIENTE.RG;
ParamByName(FLD_UF).AsString := coPACIENTE.UF;
ParamByName(FLD_CIDADE).AsString := coPACIENTE.CIDADE;
ParamByName(FLD_ENDERECO).AsString := coPACIENTE.ENDERECO;
ParamByName(FLD_TEL_FIXO).AsString := coPACIENTE.TEL_FIXO;
ParamByName(FLD_CELULAR).AsString := coPACIENTE.CELULAR;
ParamByName(FLD_PAI).AsString := coPACIENTE.PAI;
ParamByName(FLD_MAE).AsString := coPACIENTE.MAE;
ParamByName(FLD_ESTADO_CIVIL).AsString := coPACIENTE.ESTADO_CIVIL;
ParamByName(FLD_ORGAO_EMISSOR).AsString := coPACIENTE.ORGAO_EMISSOR;
ParamByName(FLD_DATA_EMISSAO).AsDate := coPACIENTE.DATA_EMISSAO;
ParamByName(FLD_BAIRRO).AsString := coPACIENTE.BAIRRO;
ParamByName(FLD_REFERENCIA).AsString := coPACIENTE.REFERENCIA;
ParamByName(FLD_TEL_COMERCIAL).AsString := coPACIENTE.TEL_COMERCIAL;
ParamByName(FLD_TIPO_SANGUE).AsString := coPACIENTE.TIPO_SANGUE;
ParamByName(FLD_PESSOA_RECADO).AsString := coPACIENTE.PESSOA_RECADO;
end;
end;
end.
|
{******************************************}
{ TeeChart }
{ TColoredForm Example }
{ Copyright (c) 1995-2001 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit ucolor;
interface
uses
Wintypes,WinProcs, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Teengine, Series, ExtCtrls, Chart, StdCtrls, Buttons, teeprocs;
type
TColoredForm = class(TForm)
Chart1: TChart;
Panel1: TPanel;
CheckBox1: TCheckBox;
BitBtn2: TBitBtn;
LineSeries1: TLineSeries;
PointSeries1: TPointSeries;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
procedure TColoredForm.FormCreate(Sender: TObject);
Procedure AddColors(Series:TChartSeries);
var step:Double;
t:Longint;
begin
With Series,GetVertAxis do
begin
step:=(Maximum-Minimum)/10.0;
for t:=0 to Count-1 do
ValueColor[t]:=GetDefaultColor( Trunc((YValue[t]-Minimum)/step) );
end;
end;
begin
LineSeries1.FillSampleValues(100);
PointSeries1.FillSampleValues(100);
Chart1.LeftAxis.AdjustMaxMin;
AddColors(LineSeries1);
AddColors(PointSeries1);
end;
procedure TColoredForm.CheckBox1Click(Sender: TObject);
begin
Chart1.LeftAxis.Inverted:=CheckBox1.Checked;
end;
end.
|
unit Support.Plextor;
interface
uses
SysUtils,
Support, Device.SMART.List;
type
TPlextorNSTSupport = class sealed(TNSTSupport)
private
InterpretingSMARTValueList: TSMARTValueList;
function IsNinja: Boolean;
function IsM3Series: Boolean;
function IsM5Series: Boolean;
function IsProductOfPlextor: Boolean;
function GetFullSupport: TSupportStatus;
function GetTotalWrite: TTotalWrite;
function IsM3SeriesWithOldUnit: Boolean;
function IsM3PWithOldUnit: Boolean;
function IsM3WithOldUnit: Boolean;
function IsM3AndNotM3P: Boolean;
function IsM3128WithOldUnit: Boolean;
function IsM3256WithOldUnit: Boolean;
function IsM3512WithOldUnit: Boolean;
function IsM364WithOldUnit: Boolean;
public
function GetSupportStatus: TSupportStatus; override;
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; override;
end;
implementation
{ TPlextorNSTSupport }
function TPlextorNSTSupport.IsM5Series: Boolean;
begin
result := (Pos('PLEXTOR', Identify.Model) > 0) and (Pos('M5', Identify.Model) > 0);
end;
function TPlextorNSTSupport.IsM3Series: Boolean;
begin
result := (Pos('PLEXTOR', Identify.Model) > 0) and (Pos('M3', Identify.Model) > 0);
end;
function TPlextorNSTSupport.IsM3AndNotM3P: Boolean;
begin
result := (Copy(Identify.Model, Length(Identify.Model) - 2, 2) = 'M3');
end;
function TPlextorNSTSupport.IsM364WithOldUnit: Boolean;
const
OldUnit = 1.06;
begin
result :=
(Pos('64', Identify.Model) > 0) and (StrToFloat(Identify.Firmware) < OldUnit);
end;
function TPlextorNSTSupport.IsM3128WithOldUnit: Boolean;
const
OldUnit = 1.07;
begin
result :=
(Pos('128', Identify.Model) > 0) and (StrToFloat(Identify.Firmware) < OldUnit);
end;
function TPlextorNSTSupport.IsM3256WithOldUnit: Boolean;
const
OldUnit = 1.07;
begin
result :=
(Pos('256', Identify.Model) > 0) and (StrToFloat(Identify.Firmware) < OldUnit);
end;
function TPlextorNSTSupport.IsM3512WithOldUnit: Boolean;
const
OldUnit = 1.06;
begin
result :=
(Pos('512', Identify.Model) > 0) and (StrToFloat(Identify.Firmware) < OldUnit);
end;
function TPlextorNSTSupport.IsM3WithOldUnit: Boolean;
begin
result :=
IsM3AndNotM3P and
(IsM364WithOldUnit or IsM3128WithOldUnit or
IsM3256WithOldUnit or IsM3512WithOldUnit or
IsM3512WithOldUnit);
end;
function TPlextorNSTSupport.IsM3PWithOldUnit: Boolean;
const
OldUnit = 1.06;
begin
result :=
(Pos('M3P', Identify.Model) > 0) and (StrToFloat(Identify.Firmware) < OldUnit);
end;
function TPlextorNSTSupport.IsM3SeriesWithOldUnit: Boolean;
begin
result := IsM3Series and
(IsM3PWithOldUnit or IsM3WithOldUnit);
end;
function TPlextorNSTSupport.IsNinja: Boolean;
begin
result := Pos('NINJA', Identify.Model) > 0;
end;
function TPlextorNSTSupport.IsProductOfPlextor: Boolean;
begin
result := IsNinja or IsM3Series or IsM5Series;
end;
function TPlextorNSTSupport.GetFullSupport: TSupportStatus;
begin
result.Supported := Supported;
result.FirmwareUpdate := true;
result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue;
end;
function TPlextorNSTSupport.GetSupportStatus: TSupportStatus;
begin
result.Supported := NotSupported;
if IsProductOfPlextor then
result := GetFullSupport;
end;
function TPlextorNSTSupport.GetTotalWrite: TTotalWrite;
const
OldPlextorUnit = 64;
NewPlextorUnit = 128;
IDOfPlextorNANDWrite = 177;
var
RAWValue: UInt64;
begin
result.InValue.TrueHostWriteFalseNANDWrite := false;
RAWValue :=
InterpretingSMARTValueList.GetRAWByID(IDOfPlextorNANDWrite);
if IsM3SeriesWithOldUnit then
result.InValue.ValueInMiB := RAWValue * OldPlextorUnit
else
result.InValue.ValueInMiB := RAWValue * NewPlextorUnit;
end;
function TPlextorNSTSupport.GetSMARTInterpreted(
SMARTValueList: TSMARTValueList): TSMARTInterpreted;
const
IDOfEraseError = 182;
IDOfReplacedSector = 5;
IDofUsedHour = 9;
ReplacedSectorThreshold = 25;
EraseErrorThreshold = 10;
begin
InterpretingSMARTValueList := SMARTValueList;
result.TotalWrite := GetTotalWrite;
result.UsedHour :=
InterpretingSMARTValueList.GetRAWByID(IDOfUsedHour);
result.ReadEraseError.TrueReadErrorFalseEraseError := false;
result.ReadEraseError.Value :=
InterpretingSMARTValueList.GetRAWByID(IDOfEraseError);
result.SMARTAlert.ReadEraseError :=
result.ReadEraseError.Value >= EraseErrorThreshold;
result.ReplacedSectors :=
InterpretingSMARTValueList.GetRAWByID(IDOfReplacedSector);
result.SMARTAlert.ReplacedSector :=
result.ReplacedSectors >= ReplacedSectorThreshold;
end;
end.
|
unit Rx.Observable.FlatMap;
interface
uses Rx, SyncObjs, Rx.Subjects, Rx.Implementations, Generics.Collections;
type
TConcurrencyCondVar = class
strict private
FCriSection: TCriticalSection;
FCondVar: TConditionVariableCS;
FLimit: Integer;
FCurrent: Integer;
public
constructor Create(Limit: Integer);
destructor Destroy; override;
procedure Enter;
procedure Leave;
procedure SetLimit(Value: Integer);
end;
TFromConcurrentSbscriptionImpl<T> = class(TFromSbscriptionImpl<T>)
type
TOnNext = TOnNext<T>;
strict private
FConcurrency: TConcurrencyCondVar;
public
constructor Create(Observable: IObservable<T>; Concurrency: TConcurrencyCondVar;
const OnNext: TOnNext=nil; const OnError: TOnError = nil;
const OnCompleted: TOnCompleted=nil);
procedure OnNext(const A: T); override;
end;
TInputSubscription<T> = class(TSubscriptionImpl, IFromSubscription<T>)
type
TOnNext = TOnNext<T>;
strict private
[Weak] FObservable: IObservable<T>;
FOnNext: TOnNext;
FOnError: TOnError;
FConcurrency: TConcurrencyCondVar;
protected
procedure UnsubscribeInterceptor; override;
public
constructor Create(Observable: IObservable<T>; Concurrency: TConcurrencyCondVar;
const OnNext: TOnNext=nil; const OnError: TOnError = nil);
procedure Lock;
procedure Unlock;
procedure OnNext(const A: T);
procedure OnError(E: IThrowable);
procedure OnCompleted;
function GetObservable: IObservable<T>;
end;
TFlatMap<X, Y> = class(TObservableImpl<X>, IObservable<Y>, IFlatMapObservable<X, Y>)
type
TFlatMap = Rx.TFlatMap<X,Y>;
TFlatMapStatic = Rx.TFlatMapStatic<X,Y>;
IFromYSubscription = IFromSubscription<Y>;
strict private
FStreams: TList<IObservable<Y>>;
FSpawns: TList<TFlatMap>;
FSpawnsStatic: TList<TFlatMapStatic>;
FLock: TCriticalSection;
FDest: TPublishSubject<Y>;
FInputs: TList<IFromYSubscription>;
FConcurrency: TConcurrencyCondVar;
procedure OnDestSubscribe(Subscriber: IObserver<Y>);
procedure OnInputError(E: IThrowable);
public
constructor Create(Source: IObservable<X>; const MaxConcurrent: Integer=0);
destructor Destroy; override;
procedure Spawn(const Routine: TFlatMap); overload;
procedure Spawn(const Routine: TFlatMapStatic); overload;
procedure SetMaxConcurrency(Value: Integer);
function Subscribe(const OnNext: TOnNext<Y>): ISubscription; overload;
function Subscribe(const OnNext: TOnNext<Y>; const OnError: TOnError): ISubscription; overload;
function Subscribe(const OnNext: TOnNext<Y>; const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription; overload;
function Subscribe(const OnNext: TOnNext<Y>; const OnCompleted: TOnCompleted): ISubscription; overload;
function Subscribe(const OnError: TOnError): ISubscription; overload;
function Subscribe(const OnCompleted: TOnCompleted): ISubscription; overload;
function Subscribe(A: ISubscriber<Y>): ISubscription; overload;
procedure OnNext(const Data: Y); reintroduce; overload;
procedure OnNext(const Data: X); overload; override;
procedure OnError(E: IThrowable); override;
procedure OnCompleted; override;
end;
TFlatMapIterableImpl<T> = class(TFlatMap<T, T>, IFlatMapIterableObservable<T>)
strict private
class threadvar CurRoutine: TFlatMapIterable<T>;
class threadvar CurRoutineStatic: TFlatMapIterableStatic<T>;
function RoutineDecorator(const Data: T): IObservable<T>;
public
procedure Spawn(const Routine: TFlatMapIterable<T>); overload;
procedure Spawn(const Routine: TFlatMapIterableStatic<T>); overload;
end;
TOnceSubscriber<X, Y> = class(TInterfacedObject, ISubscriber<X>)
strict private
FRoutine: Rx.TFlatMap<X, Y>;
FStream: IObserver<Y>;
FOnError: TOnError;
FConcurrency: TConcurrencyCondVar;
procedure OnYNext(const Data: Y);
public
constructor Create(Stream: IObserver<Y>; Concurrency: TConcurrencyCondVar;
const Routine: Rx.TFlatMap<X, Y>);
destructor Destroy; override;
procedure OnNext(const A: X);
procedure OnError(E: IThrowable);
procedure OnCompleted;
procedure Unsubscribe;
function IsUnsubscribed: Boolean;
procedure SetProducer(P: IProducer);
end;
implementation
uses Rx.Observable.Map;
{ TFlatMap<X, Y> }
constructor TFlatMap<X, Y>.Create(Source: IObservable<X>; const MaxConcurrent: Integer);
begin
inherited Create;
FLock := TCriticalSection.Create;
FStreams := TList<IObservable<Y>>.Create;
FSpawns := TList<TFlatMap>.Create;
FSpawnsStatic := TList<TFlatMapStatic>.Create;
FDest := TPublishSubject<Y>.Create(OnDestSubscribe);
FInputs := TList<IFromYSubscription>.Create;
FConcurrency := TConcurrencyCondVar.Create(MaxConcurrent);
inherited Merge(Source);
end;
destructor TFlatMap<X, Y>.Destroy;
begin
FStreams.Free;
FSpawns.Free;
FSpawnsStatic.Free;
FInputs.Free;
FDest.Free;
FConcurrency.Free;
FLock.Free;
inherited;
end;
procedure TFlatMap<X, Y>.OnNext(const Data: Y);
begin
// nothing
end;
procedure TFlatMap<X, Y>.OnCompleted;
begin
FDest.OnCompleted
end;
procedure TFlatMap<X, Y>.OnDestSubscribe(Subscriber: IObserver<Y>);
var
Decorator: ISubscriber<X>;
Routine: Rx.TFlatMap<X,Y>;
begin
for Routine in FSpawns do begin
Decorator := TOnceSubscriber<X, Y>.Create(Subscriber, FConcurrency, Routine);
try
Inputs[0].GetObservable.Subscribe(Decorator)
finally
Decorator.Unsubscribe
end;
end;
end;
procedure TFlatMap<X, Y>.OnError(E: IThrowable);
begin
FDest.OnError(E);
end;
procedure TFlatMap<X, Y>.OnInputError(E: IThrowable);
var
Contract: TObservableImpl<Y>.IContract;
begin
for Contract in FDest.Freeze do
FDest.Scheduler.Invoke(TOnErrorAction<Y>.Create(E, Contract))
end;
procedure TFlatMap<X, Y>.OnNext(const Data: X);
var
O: IObservable<Y>;
Routine: TFlatMap;
RoutineStatic: TFlatMapStatic;
S: IFromYSubscription;
I: Integer;
List: TList<IObservable<Y>>;
begin
List := TList<IObservable<Y>>.Create;
try
for Routine in FSpawns do begin
O := Routine(Data);
List.Add(O)
end;
for RoutineStatic in FSpawnsStatic do begin
O := RoutineStatic(Data);
List.Add(O)
end;
FLock.Acquire;
try
for O in List do begin
if not FStreams.Contains(O) then begin
S := TInputSubscription<Y>.Create(O, FConcurrency, FDest.OnNext, Self.OnInputError);
FInputs.Add(S);
O.Subscribe(S);
end;
end;
for I := FInputs.Count-1 downto 0 do
if FInputs[I].IsUnsubscribed then
FInputs.Delete(I);
finally
FLock.Release;
end;
finally
List.Free;
end;
end;
procedure TFlatMap<X, Y>.Spawn(const Routine: TFlatMap);
begin
FLock.Acquire;
try
FSpawns.Add(Routine)
finally
FLock.Release;
end;
end;
function TFlatMap<X, Y>.Subscribe(const OnNext: TOnNext<Y>;
const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription;
begin
Result := FDest.Subscribe(OnNext, OnError, OnCompleted);
end;
function TFlatMap<X, Y>.Subscribe(const OnNext: TOnNext<Y>;
const OnError: TOnError): ISubscription;
begin
Result := FDest.Subscribe(OnNext, OnError);
end;
function TFlatMap<X, Y>.Subscribe(const OnNext: TOnNext<Y>): ISubscription;
begin
Result := FDest.Subscribe(OnNext);
end;
function TFlatMap<X, Y>.Subscribe(const OnNext: TOnNext<Y>;
const OnCompleted: TOnCompleted): ISubscription;
begin
Result := FDest.Subscribe(OnNext, OnCompleted);
end;
procedure TFlatMap<X, Y>.SetMaxConcurrency(Value: Integer);
begin
FConcurrency.SetLimit(Value);
end;
procedure TFlatMap<X, Y>.Spawn(const Routine: TFlatMapStatic);
begin
FLock.Acquire;
try
FSpawnsStatic.Add(Routine)
finally
FLock.Release;
end;
end;
function TFlatMap<X, Y>.Subscribe(A: ISubscriber<Y>): ISubscription;
begin
Result := FDest.Subscribe(A);
end;
function TFlatMap<X, Y>.Subscribe(
const OnCompleted: TOnCompleted): ISubscription;
begin
Result := FDest.Subscribe(OnCompleted);
end;
function TFlatMap<X, Y>.Subscribe(const OnError: TOnError): ISubscription;
begin
Result := FDest.Subscribe(OnError);
end;
{ TInputSubscription<T> }
constructor TInputSubscription<T>.Create(Observable: IObservable<T>;
Concurrency: TConcurrencyCondVar; const OnNext: TOnNext; const OnError: TOnError);
begin
inherited Create;
FObservable := Observable;
FOnNext := OnNext;
FOnError := OnError;
FConcurrency := Concurrency;
end;
function TInputSubscription<T>.GetObservable: IObservable<T>;
begin
Lock;
Result := FObservable;
Unlock;
end;
procedure TInputSubscription<T>.Lock;
begin
FLock.Acquire;
end;
procedure TInputSubscription<T>.OnCompleted;
begin
Unsubscribe
end;
procedure TInputSubscription<T>.OnError(E: IThrowable);
begin
Lock;
try
if not IsUnsubscribed and Assigned(FOnError) then begin
FOnError(E);
Unsubscribe;
end;
finally
Unlock;
end;
end;
procedure TInputSubscription<T>.OnNext(const A: T);
begin
Lock;
try
if not IsUnsubscribed and Assigned(FOnNext) then begin
FConcurrency.Enter;
try
FOnNext(A)
finally
FConcurrency.Leave;
end;
end;
finally
Unlock;
end;
end;
procedure TInputSubscription<T>.Unlock;
begin
FLock.Release;
end;
procedure TInputSubscription<T>.UnsubscribeInterceptor;
begin
FObservable := nil;
end;
{ TFlatMapIterableImpl<T> }
function TFlatMapIterableImpl<T>.RoutineDecorator(
const Data: T): IObservable<T>;
begin
if Assigned(CurRoutine) then
Result := CurRoutine(Data)
else
Result := CurRoutineStatic(Data)
end;
procedure TFlatMapIterableImpl<T>.Spawn(const Routine: TFlatMapIterable<T>);
begin
CurRoutine := Routine;
CurRoutineStatic := nil;
inherited Spawn(RoutineDecorator)
end;
procedure TFlatMapIterableImpl<T>.Spawn(
const Routine: TFlatMapIterableStatic<T>);
begin
CurRoutine := nil;
CurRoutineStatic := Routine;
inherited Spawn(RoutineDecorator)
end;
{ TOnceSubscriber<X, Y> }
constructor TOnceSubscriber<X, Y>.Create(Stream: IObserver<Y>;
Concurrency: TConcurrencyCondVar; const Routine: Rx.TFlatMap<X, Y>);
begin
FRoutine := Routine;
FStream := Stream;
FConcurrency := Concurrency;
end;
destructor TOnceSubscriber<X, Y>.Destroy;
begin
FStream := nil;
inherited;
end;
function TOnceSubscriber<X, Y>.IsUnsubscribed: Boolean;
begin
Result := FStream = nil
end;
procedure TOnceSubscriber<X, Y>.OnCompleted;
begin
//Unsubscribe
end;
procedure TOnceSubscriber<X, Y>.OnError(E: IThrowable);
begin
if not IsUnsubscribed and Assigned(FOnError) then begin
FOnError(E);
//Unsubscribe;
end;
end;
procedure TOnceSubscriber<X, Y>.OnNext(const A: X);
var
O: IObservable<Y>;
InternalSubscr: IFromSubscription<Y>;
begin
if not IsUnsubscribed then begin
O := FRoutine(A);
InternalSubscr := TFromConcurrentSbscriptionImpl<Y>.Create(O, FConcurrency,
OnYNext, OnError, OnCompleted);
try
O.Subscribe(InternalSubscr)
finally
InternalSubscr.Unsubscribe;
end;
end;
end;
procedure TOnceSubscriber<X, Y>.OnYNext(const Data: Y);
begin
FStream.OnNext(Data)
end;
procedure TOnceSubscriber<X, Y>.SetProducer(P: IProducer);
begin
// nothing
end;
procedure TOnceSubscriber<X, Y>.Unsubscribe;
begin
FStream := nil;
end;
{ TConcurrencyCondVar }
constructor TConcurrencyCondVar.Create(Limit: Integer);
begin
FCriSection := TCriticalSection.Create;
FCondVar := TConditionVariableCS.Create;
FLimit := Limit
end;
destructor TConcurrencyCondVar.Destroy;
begin
FCriSection.Free;
FCondVar.Free;
inherited;
end;
procedure TConcurrencyCondVar.Enter;
begin
FCriSection.Acquire;
if FLimit <= 0 then begin
FCriSection.Release;
Exit;
end;
if FCurrent < FLimit then begin
Inc(FCurrent);
FCriSection.Release;
Exit;
end
else begin
repeat
FCondVar.WaitFor(FCriSection);
FCriSection.Acquire;
until FCurrent < FLimit;
FCriSection.Release;
end;
end;
procedure TConcurrencyCondVar.Leave;
begin
FCriSection.Acquire;
Dec(FCurrent);
FCriSection.Release;
FCondVar.Release;
end;
procedure TConcurrencyCondVar.SetLimit(Value: Integer);
var
Grow: Integer;
begin
FCriSection.Acquire;
if Value = 0 then
Grow := MaxInt
else
Grow := Value - FLimit;
FLimit := Value;
FCriSection.Release;
if Grow > 0 then
FCondVar.ReleaseAll;
end;
{ TFromConcurrentSbscriptionImpl<T> }
constructor TFromConcurrentSbscriptionImpl<T>.Create(Observable: IObservable<T>;
Concurrency: TConcurrencyCondVar; const OnNext: TOnNext;
const OnError: TOnError; const OnCompleted: TOnCompleted);
begin
inherited Create(Observable, OnNext, OnError, OnCompleted);
FConcurrency := Concurrency;
end;
procedure TFromConcurrentSbscriptionImpl<T>.OnNext(const A: T);
begin
FConcurrency.Enter;
try
inherited;
finally
FConcurrency.Leave;
end;
end;
end.
|
unit Unit5;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
DbCtrls;
type
{ TOperacje }
TOperacje = class(TForm)
Button1: TButton;
Button2: TButton;
DBMemo1: TDBMemo;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Zamknij: TButton;
Label1: TLabel;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ZamknijClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Operacje: TOperacje;
klikniety:Boolean;
implementation
uses unit1;
{ TOperacje }
procedure TOperacje.ZamknijClick(Sender: TObject);
begin
Operacje.Enabled:=False;
Operacje.Visible:=False;
end;
procedure TOperacje.FormShow(Sender: TObject);
var
dodawanie, mnozenie, odejmowanie: Int64;
dzielenie: double;
ch_1: string;
begin
dodawanie:=Unit1.dodawanie;
str(dodawanie, ch_1);
Label2.Caption:='Wynik z operacji dodawania: '+ch_1;
odejmowanie:=Unit1.odejmowanie;
str(odejmowanie, ch_1);
Label3.Caption:='Wynik z operacji odejmowania: '+ch_1;
mnozenie:=Unit1.mnozenie;
str(mnozenie, ch_1);
Label4.Caption:='Wynik z operacji mnozenia: '+ch_1;
dzielenie:=Unit1.dzielenie;
if Unit1.dzielenie<>-1 then
begin
str(round(dzielenie), ch_1);
Label5.Caption:='Wynik z operacji dzielenia: '+ch_1;
end
else
begin
Label5.Caption:='Wynik z operacji dzielenia: Błąd, nie można dzielić przez 0!';
Operacje.Width:=650;
end;
end;
procedure TOperacje.Button1Click(Sender: TObject);
var
file_src: string;
i,wybor: Byte;
begin
i:=0;
if (Unit1.matrix_size>=9) then
begin
wybor:=Application.MessageBox('Plik będzie zbyt duży aby wczytać go do programu, jednak można zapisać go na dysku, proszę podać ściężkę do zapisu.','Uwaga!',($00000004+$00000030));
if wybor=6 then // TAK
if Unit1.MainForm.SaveDialog.Execute then
file_src:=Unit1.MainForm.SaveDialog.Filename;
Unit1.sortuj_rosn(file_src);
klikniety:=True;
end;
repeat
begin
if (Unit1.matrix_size>=3) then
begin
file_src:='tmp3.txt';
Unit1.sortuj_rosn(file_src);
Operacje.DBMemo1.Lines.Clear;
Unit5.Operacje.DBMemo1.Lines.LoadFromFile(file_src);
klikniety:=True;
end;
inc(i);
end;
until i=2;
end;
procedure TOperacje.Button2Click(Sender: TObject);
var
i,wybor:byte;
file_src:string;
begin
i:=0;
if (Unit1.matrix_size>=9) then
begin
wybor:=Application.MessageBox('Plik będzie zbyt duży aby wczytać go do programu, jednak można zapisać go na dysku, proszę podać ściężkę do zapisu.','Uwaga!',($00000004+$00000030));
if wybor=6 then // TAK
if Unit1.MainForm.SaveDialog.Execute then
file_src:=Unit1.MainForm.SaveDialog.Filename;
Unit1.sortuj_mal(file_src);
klikniety:=True;
end;
repeat
begin
if (Unit1.matrix_size>=3) then
begin
Unit1.sortuj_mal(file_src);
file_src:='tmp3.txt';
Operacje.DBMemo1.Lines.LoadFromFile(file_src);
klikniety:=True;
end;
inc(i);
end;
until i=2;
end;
{$R *.lfm}
end.
|
unit SMCnst;
interface
{Hungarian strings}
const
strMessage = 'Nyomtatás...';
strSaveChanges = 'A változásokat valóban tárolni akarod az adatbázis szerveren?';
strErrSaveChanges = 'Az adatokat nem lehet menteni! Ellenőrizd a szerver kapcsolatot vagy az adatot!';
strDeleteWarning = 'Valóban törölni akarod a(z) %s táblát?';
strEmptyWarning = 'Valóban üríteni akarod a(z) %s táblát?';
const
PopUpCaption: array [0..22] of string[44] =
('Új rekord',
'Rekord beszúrás',
'Rekord javítás',
'Rekord törlés',
'-',
'Nyomtatás ...',
'Export ...',
'-',
'Javítások mentése',
'Javítások elhagyása',
'Frissítés',
'-',
'Rekordok kijelölése',
'Rekord jelölése',
'Minden rekord jelölése',
'-',
'A rekord jelölés megszüntetése',
'Az összes rekord jelölés megszüntetése',
'-',
'Az oszlop helyzetének mentése',
'Az oszlop helyzetének visszaállítása',
'-',
'Beállítás...');
const //for TSMSetDBGridDialog
SgbTitle = ' Cím ';
SgbData = ' Adat ';
STitleCaption = 'Felirat:';
STitleAlignment = 'Kijelölés:';
STitleColor = 'Háttér:';
STitleFont = 'Betű:';
SWidth = 'Szélesség:';
SWidthFix = 'karakter';
SAlignLeft = 'bal';
SAlignRight = 'jobb';
SAlignCenter = 'közép';
// added Varga Zoltán varga.zoltan@nml.hu
SApplyAll ='Mindre';
const //for TSMDBFilterDialog
strEqual = '= egyenlő';
strNonEqual = '<> nem egyenlő';
strNonMore = 'nem nagyobb';
strNonLess = 'nem kisebb';
strLessThan = '< kisebb';
strLargeThan = '> nagyobb';
strExist = 'üres';
strNonExist = 'nem üres';
strIn = 'listában';
strBetween = 'között';
strOR = 'VAGY';
strAND = 'ÉS';
strField = 'Mező';
strCondition = 'Feltétel';
strValue = 'Érték';
strAddCondition = ' A következő feltétel megadása:';
strSelection = ' A rekord kijelölése a következő feltétel szerint:';
strAddToList = 'Hozzáadás a listához';
strEditInList = 'Lista szerkesztése';
strDeleteFromList = 'Törlés a listából';
strTemplate = 'Szürő dialógus';
strFLoadFrom = 'Betölt...';
strFSaveAs = 'Mentés más néven..';
strFDescription = 'Lerás';
strFFileName = 'Állomány név';
strFCreate = 'Létrehozva: %s';
strFModify = 'Módosítva: %s';
strFProtect = 'Írásvédett';
strFProtectErr = 'Védett állomány!';
const //for SMDBNavigator
SFirstRecord = 'Első rekord';
SPriorRecord = 'Előző rekord';
SNextRecord = 'Következő rekord';
SLastRecord = 'Utolsó rekord';
SInsertRecord = 'Rekord beszúrása';
SCopyRecord = 'Rekord másolása';
SDeleteRecord = 'Rekord törlése';
SEditRecord = 'Rekord javítása';
SFilterRecord = 'Szűrő feltétel';
SFindRecord = 'Rekord keresés';
SPrintRecord = 'Rekord nyomtsatás';
SExportRecord = 'Rekord exportálása';
SPostEdit = 'Változások mentése';
SCancelEdit = 'Változások elhagyása';
SRefreshRecord = 'Adatok frissítése';
SChoice = 'Rekord kijelölés';
SClear = 'Rekord kijelölés megszüntetése';
SDeleteRecordQuestion = 'Törlöd a rekordot?';
SDeleteMultipleRecordsQuestion = 'Valóban törölni akarod a kijelölt rekordokat?';
SRecordNotFound = 'nincs találat';
SFirstName = 'Első';
SPriorName = 'Előző';
SNextName = 'Következő';
SLastName = 'Utolsó';
SInsertName = 'Beszúr';
SCopyName = 'Másol';
SDeleteName = 'Töröl';
SEditName = 'Javít';
SFilterName = 'Szűrő';
SFindName = 'Keres';
SPrintName = 'Nyomtat';
SExportName = 'Export';
SPostName = 'Ment';
SCancelName = 'Elhagy';
SRefreshName = 'Frissít';
SChoiceName = 'Választ';
SClearName = 'Töröl';
SBtnOk = '&OK';
SBtnCancel = '&Elhagy';
SBtnLoad = 'Tölt';
SBtnSave = 'Ment';
SBtnCopy = 'Másol';
SBtnPaste = 'Beilleszt';
SBtnClear = 'Töröl';
SRecNo = ' # ';
SRecOf = ' / ';
const //for EditTyped
etValidNumber = 'érvényes szám';
etValidInteger = 'érvényes egész szám';
etValidDateTime = 'érvényes dátum/idő';
etValidDate = 'érvényes dátum';
etValidTime = 'érvényes idő';
etValid = 'érvényes';
etIsNot = 'nem egy';
etOutOfRange = 'Az érték %s az értékhatáron kívül esik %s..%s';
dbanOf = '';
implementation
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,655360}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 65 O(N2)
}
program
Lines;
uses
Graph;
const
MaxN = 50;
type
LSeg = array[0 .. 1] of PointType;
Arr = array [0 .. MaxN] of LSeg;
var
N : Integer;
GM, GD : integer;
P : Arr;
BestLine : LSeg;
BestCross : Integer;
I, J, K, L : integer;
D1, D2 : Byte;
TT1, T1, T2 : Integer;
TT2 : Real;
Cross : Integer;
procedure ReadInput;
begin
Assign(Input, 'input.txt');
Reset(Input);
Readln(N);
for I := 1 to N do
Readln(P[I,0].X, P[I,0].Y, P[I,1].X, P[I,1].Y);
Close(Input);
Assign(Input, '');
Reset(Input);
end;
function F (L : Integer; D : Integer) : Integer;
begin
if TT1 = 0 then
F := P[L, D].X - P[I, D1].X
else
F := Trunc(TT2 * (P[L, D].X - P[I, D1].X)) + P[I, D1].Y;
end;
procedure Solve;
begin
BestCross:=0;
for I := 1 to N do
for J := I to N do
for K := 0 to 3 do
begin
D1 := K and 1;
D2 := K shr 1;
if I = J then
begin
D1 := 0;
D2 := 1;
K := 3;
end;
TT1 := P[J,D2].X - P[I,D1].X;
if TT1 <> 0 then
TT2 := (P[J,D2].Y - P[I,D1].Y) / TT1;
Cross := 0;
for L := 1 to N do
begin
if (L = I) or (L = J) then
begin
Inc(Cross);
Continue;
end;
T1 := P[L, 0].Y - F(L, 0);
T2 := P[L, 1].Y - F(L, 1);
if (T1 < 0) and (T2 > 0) then Inc(Cross)
else if (T1 > 0) and (T2 < 0) then Inc(Cross)
else if (T1 = 0) or (T2 = 0) then Inc(Cross);
end;
if Cross > BestCross then
begin
BestCross := Cross;
BestLine[0].X := I;
BestLine[0].Y := D1;
BestLine[1].X := J;
BestLine[1].Y := D2;
end;
end;
end;
procedure Draw;
begin
GM := Detect;
InitGraph(Gm, Gd, '');
Writeln(BestCross);
for I := 1 to N do
Line(P[I,0].X, P[I,0].Y, P[I,1].X, P[I,1].Y);
SetColor(12);
I := BestLine[0].X;
D1 := BestLine[0].Y;
J := BestLine[1].X;
D2 := BestLine[1].Y;
TT1 := (P[J, D2].X - P[I, D1].X);
if TT1 <> 0 then
begin
TT2 := (P[J, D2].Y - P[I, D1].Y) / TT1;
P[0, 0].X := 0;
P[0, 1].X := 639;
Line(0, F(0, 0), 639, F(0, 1));
end
else
Line(P[J,D2].X,0,P[J,D2].X,479);
Readln;
CloseGraph;
end;
begin
ReadInput;
Solve;
Draw;
end. |
unit BillQuery2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap, BillQuery, BaseEventsQuery;
type
TBillW2 = class(TBillW)
private
FStorehouseId: TParamWrap;
public
constructor Create(AOwner: TComponent); override;
property StorehouseId: TParamWrap read FStorehouseId;
end;
TQryBill2 = class(TQueryBaseEvents)
private
FW: TBillW2;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
procedure SearchByStoreHouse(AStoreHouseID: Integer);
property W: TBillW2 read FW;
{ Public declarations }
end;
implementation
uses
BaseQuery;
{$R *.dfm}
constructor TQryBill2.Create(AOwner: TComponent);
begin
inherited;
FW := TBillW2.Create(FDQuery);
end;
procedure TQryBill2.SearchByStoreHouse(AStoreHouseID: Integer);
begin
Assert(AStoreHouseID > 0);
SearchEx([TParamRec.Create(W.StorehouseId.FullName, AStoreHouseID)]);
end;
constructor TBillW2.Create(AOwner: TComponent);
begin
inherited;
// Параметр SQL запроса
FStorehouseId := TParamWrap.Create(Self, 'bc.StorehouseId');
end;
end.
|
unit ControleUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, DBCtrls, Grids, DBGrids, DB, DBTables, StdCtrls, Buttons;
type
TControleForm = class(TForm)
TableCracha: TTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
DBNavigator1: TDBNavigator;
StartPoolingButton: TButton;
Add5000SpeedButton: TSpeedButton;
Add100SpeedButton: TSpeedButton;
Timer1: TTimer;
Memo1: TMemo;
TableCrachaNmerodoCrach: TStringField;
TableCrachaCatracaPermitida: TIntegerField;
TableCrachaHabilitado: TBooleanField;
StopPoolingButton: TButton;
Label1: TLabel;
Label2: TLabel;
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Add5000SpeedButtonClick(Sender: TObject);
procedure StartPoolingButtonClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure StopPoolingButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ControleForm: TControleForm;
implementation
{$R *.DFM}
procedure ActiveDll; stdcall; external 'Online.dll';
procedure DeactiveDll; stdcall; external 'Online.dll';
function InsertTerminal (Terminal: LongInt): LongInt; stdcall; external 'Online.dll';
function DeleteTerminal (Terminal: LongInt): LongInt; stdcall; external 'Online.dll';
function EnableTerminal (Terminal: LongInt): LongInt; stdcall; external 'Online.dll';
function DisableTerminal (Terminal: LongInt): LongInt; stdcall; external 'Online.dll';
procedure SetPoolingIntervalTime(IntervalTime: LongInt); stdcall; external 'Online.dll';
procedure SetTerminalResponseTime(Time: LongInt); stdcall; external 'Online.dll';
procedure StartPooling; stdcall; external 'Online.dll';
procedure StopPooling; stdcall; external 'Online.dll';
procedure SetComm(CommPort: LongInt); stdcall; external 'Online.dll';
procedure SetBaudRate(BaudRate: LongInt); stdcall; external 'Online.dll';
procedure SetCommShow; stdcall; external 'Online.dll';
function OpenComm: LongInt; stdcall; external 'Online.dll';
procedure CloseComm; stdcall; external 'Online.dll';
procedure SetDateTime (Terminal: LongInt; CurrentDateTime: PChar); stdcall; external 'Online.dll';
procedure SetTerminalTimeOut (Terminal, TimeOut: LongInt); stdcall; external 'Online.dll';
procedure SetConditionAfterTimeOut (Terminal, Condition: LongInt); stdcall; external 'Online.dll';
procedure SendMessage (Terminal, TimeMessage: LongInt; PersonalMessage: PChar); stdcall; external 'Online.dll';
function Question: PChar; stdcall; external 'Online.dll';
procedure Answer(Terminal: LongInt; Badge, Position, Status: PChar; TimeMessage: LongInt; PersonalMessage: PChar); stdcall; external 'Online.dll';
procedure TControleForm.FormActivate(Sender: TObject);
begin
TableCracha.Open;
ActiveDll; // ativa a DLL
SetComm(2); // configura a porta serial e a velocidade de comunicação
SetBaudRate(4800);
OpenComm; // abre a porta serial
SetPoolingIntervalTime(100); // configura o intervalo do pooling = 50ms (milisegundos)
SetTerminalResponseTime(500); // configura o tempo de aguardo da resposta pelo computador
InsertTerminal(1); // insere o terminal 1
DisableTerminal(1); // desabilita momentaneamente o terminal recentemente inserido
// InsertTerminal(2); // insere o terminal 1
// DisableTerminal(2); // desabilita momentaneamente o terminal recentemente inserido
// InsertTerminal(3); // insere o terminal 1
// DisableTerminal(3); // desabilita momentaneamente o terminal recentemente inserido
// InsertTerminal(4); // insere o terminal 1
// DisableTerminal(4); // desabilita momentaneamente o terminal recentemente inserido
// InsertTerminal(5); // insere o terminal 1
// DisableTerminal(5); // desabilita momentaneamente o terminal recentemente inserido
// InsertTerminal(6); // insere o terminal 1
// DisableTerminal(6); // desabilita momentaneamente o terminal recentemente inserido
// InsertTerminal(7); // insere o terminal 1
// DisableTerminal(7); // desabilita momentaneamente o terminal recentemente inserido
// InsertTerminal(8); // insere o terminal 1
// DisableTerminal(8); // desabilita momentaneamente o terminal recentemente inserido
EnableTerminal(1); // habilita o terminal
// EnableTerminal(2); // habilita o terminal
// EnableTerminal(3); // habilita o terminal
// EnableTerminal(4); // habilita o terminal
// EnableTerminal(5); // habilita o terminal
// EnableTerminal(6); // habilita o terminal
// EnableTerminal(7); // habilita o terminal
// EnableTerminal(8); // habilita o terminal
Randomize;
Label2.Caption := IntToStr(TableCracha.RecordCount);
end;
procedure TControleForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
TableCracha.Close;
CloseComm;
DeactiveDll;
end;
procedure TControleForm.Add5000SpeedButtonClick(Sender: TObject);
var
mI,mQuantidade: Integer;
begin
TableCracha.DisableControls;
if Sender = Add5000SpeedButton then
mQuantidade := 5000
else
mQuantidade := 100;
for mI := 1 to mQuantidade do
begin
TableCracha.Append;
TableCrachaNMERODOCRACH.Value := Format('%.10d',[Random(1000000)]);
TableCrachaCATRACAPERMITIDA.Value := Random(6);
TableCrachaHABILITADO.Value := Random(2) = Random(2);
try
TableCracha.Post;
except on exception do
TableCracha.Cancel;
end;
end;
TableCracha.EnableControls;
Label2.Caption := IntToStr(TableCracha.RecordCount);
end;
procedure TControleForm.StartPoolingButtonClick(Sender: TObject);
begin
SetTerminalTimeOut(1,2000); // configura o tempo de aguardo da resposta do terminal
SetConditionAfterTimeOut(1,0); // configura o procedimento a ser tomado pelo terminal após decorrido o tempo de aguardo
SetDateTime(1,PChar(FormatDateTime('dd/mm/yyyy hh:nn:ss',Now))); // configura o calendário e o relógio do terminal
SendMessage(1,1000,PChar('Terminal 1 inicializado... ')); // envia uma mensagem ao terminal afim de confirmar sua participaçãp no pooling
// SetTerminalTimeOut(2,2000); // configura o tempo de aguardo da resposta do terminal
// SetConditionAfterTimeOut(2,0); // configura o procedimento a ser tomado pelo terminal após decorrido o tempo de aguardo
// SetDateTime(2,PChar(FormatDateTime('dd/mm/yyyy hh:nn:ss',Now))); // configura o calendário e o relógio do terminal
// SendMessage(2,1000,PChar('Terminal 2 inicializado... ')); // envia uma mensagem ao terminal afim de confirmar sua participaçãp no pooling
// SetTerminalTimeOut(3,2000); // configura o tempo de aguardo da resposta do terminal
// SetConditionAfterTimeOut(3,0); // configura o procedimento a ser tomado pelo terminal após decorrido o tempo de aguardo
// SetDateTime(3,PChar(FormatDateTime('dd/mm/yyyy hh:nn:ss',Now))); // configura o calendário e o relógio do terminal
// SendMessage(3,1000,PChar('Terminal 3 inicializado... ')); // envia uma mensagem ao terminal afim de confirmar sua participaçãp no pooling
// SetTerminalTimeOut(4,2000); // configura o tempo de aguardo da resposta do terminal
// SetConditionAfterTimeOut(4,0); // configura o procedimento a ser tomado pelo terminal após decorrido o tempo de aguardo
// SetDateTime(4,PChar(FormatDateTime('dd/mm/yyyy hh:nn:ss',Now))); // configura o calendário e o relógio do terminal
// SendMessage(4,1000,PChar('Terminal 4 inicializado... ')); // envia uma mensagem ao terminal afim de confirmar sua participaçãp no pooling
// SetTerminalTimeOut(5,2000); // configura o tempo de aguardo da resposta do terminal
// SetConditionAfterTimeOut(5,0); // configura o procedimento a ser tomado pelo terminal após decorrido o tempo de aguardo
// SetDateTime(5,PChar(FormatDateTime('dd/mm/yyyy hh:nn:ss',Now))); // configura o calendário e o relógio do terminal
// SendMessage(5,1000,PChar('Terminal 5 inicializado... ')); // envia uma mensagem ao terminal afim de confirmar sua participaçãp no pooling
// SetTerminalTimeOut(6,2000); // configura o tempo de aguardo da resposta do terminal
// SetConditionAfterTimeOut(6,0); // configura o procedimento a ser tomado pelo terminal após decorrido o tempo de aguardo
// SetDateTime(6,PChar(FormatDateTime('dd/mm/yyyy hh:nn:ss',Now))); // configura o calendário e o relógio do terminal
// SendMessage(6,1000,PChar('Terminal 6 inicializado... ')); // envia uma mensagem ao terminal afim de confirmar sua participaçãp no pooling
// SetTerminalTimeOut(7,2000); // configura o tempo de aguardo da resposta do terminal
// SetConditionAfterTimeOut(7,0); // configura o procedimento a ser tomado pelo terminal após decorrido o tempo de aguardo
// SetDateTime(7,PChar(FormatDateTime('dd/mm/yyyy hh:nn:ss',Now))); // configura o calendário e o relógio do terminal
// SendMessage(7,1000,PChar('Terminal 7 inicializado... ')); // envia uma mensagem ao terminal afim de confirmar sua participaçãp no pooling
// SetTerminalTimeOut(8,2000); // configura o tempo de aguardo da resposta do terminal
// SetConditionAfterTimeOut(8,0); // configura o procedimento a ser tomado pelo terminal após decorrido o tempo de aguardo
// SetDateTime(8,PChar(FormatDateTime('dd/mm/yyyy hh:nn:ss',Now))); // configura o calendário e o relógio do terminal
// SendMessage(8,1000,PChar('Terminal 8 inicializado... ')); // envia uma mensagem ao terminal afim de confirmar sua participaçãp no pooling
Timer1.Enabled := True;
StartPooling;
end;
procedure TControleForm.StopPoolingButtonClick(Sender: TObject);
begin
Timer1.Enabled := False;
StopPooling;
end;
procedure TControleForm.Timer1Timer(Sender: TObject);
var
mCatraca: Integer;
mAA, mDado, mEstado, mCracha, mMsg: string;
begin
Timer1.Enabled := False;
mDado := StrPas(Question);
if mDado <> '' then
begin
mCatraca := StrToInt(Copy(mDado,1,2));
mCracha := Copy(mDado,4,10);
if (TableCracha.FindKey([mCracha])) and (TableCrachaHABILITADO.Value) then
begin
mEstado := 'S';
mMsg := 'Liberado';
mAA := Copy(mDado,1,2)+' '+Copy(mDado,4,10)+' '+Copy(mDado,15,1)+'Liberado ';
end
else
begin
mEstado := 'N';
mMsg := 'Não liberado';
mAA := Copy(mDado,1,2)+' '+Copy(mDado,4,10)+' '+Copy(mDado,15,1)+'Bloqueado ';
end;
Answer(mCatraca, PChar(mCracha), PChar(Copy(mDado,15,1)), PChar(mEstado), 2000, PChar(mAA));
Memo1.Lines.Add('Catraca:'+Copy(mDado,1,2)+' Crachá:'+ Copy(mDado,4,10)+'Sentido: '+Copy(mDado,15,1)+' -> '+mMsg);
end;
Timer1.Enabled := True;
end;
end.
|
unit HCFloatBarCodeItem;
interface
uses
Windows, Classes, Controls, SysUtils, Graphics, HCStyle, HCCustomData, HCXml,
HCItem, HCCustomFloatItem, HCCode128B, HCCommon;
type
THCFloatBarCodeItem = class(THCCustomFloatItem)
private
FAutoSize, FShowText: Boolean;
FPenWidth: Byte;
FText: string;
protected
function GetText: string; override;
procedure SetText(const Value: string); override;
public
constructor Create(const AOwnerData: THCCustomData); override;
procedure Assign(Source: THCCustomItem); override;
procedure DoPaint(const AStyle: THCStyle; const ADrawRect: TRect;
const ADataDrawTop, ADataDrawBottom, ADataScreenTop, ADataScreenBottom: Integer;
const ACanvas: TCanvas; const APaintInfo: TPaintInfo); override;
procedure SaveToStream(const AStream: TStream; const AStart, AEnd: Integer); override;
procedure LoadFromStream(const AStream: TStream; const AStyle: THCStyle; const AFileVersion: Word); override;
procedure ToXml(const ANode: IHCXMLNode); override;
procedure ParseXml(const ANode: IHCXMLNode); override;
property PenWidth: Byte read FPenWidth write FPenWidth;
property AutoSize: Boolean read FAutoSize write FAutoSize;
property ShowText: Boolean read FShowText write FShowText;
end;
implementation
{ THCFloatBarCodeItem }
procedure THCFloatBarCodeItem.Assign(Source: THCCustomItem);
begin
inherited Assign(Source);
FText := (Source as THCFloatBarCodeItem).Text;
end;
constructor THCFloatBarCodeItem.Create(const AOwnerData: THCCustomData);
begin
inherited Create(AOwnerData);
Self.StyleNo := Ord(THCStyle.FloatBarCode);
FAutoSize := True;
FShowText := True;
FPenWidth := 2;
Width := 80;
Height := 60;
SetText('0000');
end;
procedure THCFloatBarCodeItem.DoPaint(const AStyle: THCStyle;
const ADrawRect: TRect; const ADataDrawTop, ADataDrawBottom, ADataScreenTop,
ADataScreenBottom: Integer; const ACanvas: TCanvas; const APaintInfo: TPaintInfo);
var
vCode128B: THCCode128B;
vBitmap: TBitmap;
begin
vBitmap := TBitmap.Create;
try
vCode128B := THCCode128B.Create;
try
vCode128B.Margin := 2;
vCode128B.PenWidth := FPenWidth;
vCode128B.CodeKey := FText;
vCode128B.ShowCodeKey := FShowText;
if not FAutoSize then
vCode128B.Height := Height;
vBitmap.SetSize(vCode128B.Width, vCode128B.Height);
vCode128B.PaintToEx(vBitmap.Canvas);
ACanvas.StretchDraw(ADrawRect, vBitmap);
finally
FreeAndNil(vCode128B);
end;
finally
vBitmap.Free;
end;
inherited DoPaint(AStyle, ADrawRect, ADataDrawTop, ADataDrawBottom, ADataScreenTop,
ADataScreenBottom, ACanvas, APaintInfo);
end;
function THCFloatBarCodeItem.GetText: string;
begin
Result := FText;
end;
procedure THCFloatBarCodeItem.LoadFromStream(const AStream: TStream;
const AStyle: THCStyle; const AFileVersion: Word);
begin
inherited LoadFromStream(AStream, AStyle, AFileVersion);
HCLoadTextFromStream(AStream, FText, AFileVersion);
if AFileVersion > 34 then
begin
AStream.ReadBuffer(FAutoSize, SizeOf(FAutoSize));
AStream.ReadBuffer(FShowText, SizeOf(FShowText));
AStream.ReadBuffer(FPenWidth, SizeOf(FPenWidth));
end;
end;
procedure THCFloatBarCodeItem.ParseXml(const ANode: IHCXMLNode);
begin
inherited ParseXml(ANode);
FText := ANode.Text;
if ANode.HasAttribute('autosize') then
FAutoSize := ANode.Attributes['autosize']
else
FAutoSize := True;
if ANode.HasAttribute('showtext') then
FShowText := ANode.Attributes['showtext']
else
FShowText := True;
if ANode.HasAttribute('penwidth') then
FPenWidth := ANode.Attributes['penwidth']
else
FPenWidth := 2;
end;
procedure THCFloatBarCodeItem.SaveToStream(const AStream: TStream; const AStart,
AEnd: Integer);
begin
inherited SaveToStream(AStream, AStart, AEnd);
HCSaveTextToStream(AStream, FText);
AStream.WriteBuffer(FAutoSize, SizeOf(FAutoSize));
AStream.WriteBuffer(FShowText, SizeOf(FShowText));
AStream.WriteBuffer(FPenWidth, SizeOf(FPenWidth));
end;
procedure THCFloatBarCodeItem.SetText(const Value: string);
var
vBarCode: THCCode128B;
begin
if FText <> Value then
begin
FText := Value;
if FAutoSize then
begin
vBarCode := THCCode128B.Create;
try
vBarCode.Margin := 2;
vBarCode.PenWidth := FPenWidth;
vBarCode.CodeKey := FText;
vBarCode.ShowCodeKey := FShowText;
Width := vBarCode.Width;
finally
vBarCode.Free;
end;
end;
end;
end;
procedure THCFloatBarCodeItem.ToXml(const ANode: IHCXMLNode);
begin
inherited ToXml(ANode);
ANode.Text := FText;
ANode.Attributes['autosize'] := FAutoSize;
ANode.Attributes['showtext'] := FShowText;
ANode.Attributes['penwidth'] := FPenWidth;
end;
end.
|
unit U_VECTOR_CONTROL;
interface
uses Classes, SysUtils, U_VECTOR_LIEN_INFO, Graphics, Windows, XMLIntf, msxmldom,
XMLDoc,Variants, Forms, Dialogs, GDIPAPI, GDIPOBJ, System.Types;
type
TVECTOR_CONTROL = class
private
FVectorList: TStringList;
XMLDocument1: TXMLDocument;
FRect: TRect;
FCanvas: TCanvas;
FBackColor: TColor;
function GetVectorInfo(nIndex: Integer): TVECTOR_LIEN_INFO;
procedure SetVectorStr(const Value: string);
function GetVectorStr: string;
public
/// <summary>
/// 设置全部向量处在不选择状态
/// </summary>
procedure SetNoSelect;
/// <summary>
/// 添加向量
/// </summary>
function AddVector : TVECTOR_LIEN_INFO;
/// <summary>
/// 删除向量
/// </summary>
procedure DelVector(nVectorID : Integer);
/// <summary>
/// 背景图
/// </summary>
property BackColor : TColor read FBackColor write FBackColor;
/// <summary>
/// 获取点所在向量图,如果没有返回nil
/// </summary>
function PointInVLine(APoint : TPoint): TVECTOR_LIEN_INFO;
/// <summary>
/// 鼠标移动
/// </summary>
function MouseMove(APoint : TPoint): TVECTOR_LIEN_INFO;
/// <summary>
/// 删除选择向量
/// </summary>
procedure DelSelect;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 向量列表
/// </summary>
property VectorList : TStringList read FVectorList write FVectorList;
property VectorInfo[nIndex : Integer] : TVECTOR_LIEN_INFO read GetVectorInfo;
procedure ClearList;
/// <summary>
/// 向量图描述
/// </summary>
property VectorStr : string read GetVectorStr write SetVectorStr;
/// <summary>
/// 画布 必须赋值
/// </summary>
property Canvas : TCanvas read FCanvas write FCanvas;
/// <summary>
/// 绘制区域 必须赋值
/// </summary>
property Rect : TRect read FRect write FRect;
/// <summary>
/// 绘制
/// </summary>
procedure Draw;
end;
var
AVectorControl : TVECTOR_CONTROL;
implementation
{ TVECTOR_CONTROL }
function TVECTOR_CONTROL.AddVector: TVECTOR_LIEN_INFO;
function GetMaxID : Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to FVectorList.Count - 1 do
begin
if VectorInfo[i].VID > Result then
Result := VectorInfo[i].VID;
end;
end;
begin
Result := TVECTOR_LIEN_INFO.Create;
Result.VID := GetMaxID + 1;
FVectorList.AddObject('', Result);
end;
procedure TVECTOR_CONTROL.ClearList;
var
i: Integer;
begin
for i := 0 to FVectorList.Count - 1 do
FVectorList.Objects[i].Free;
FVectorList.Clear;
end;
constructor TVECTOR_CONTROL.Create;
begin
XMLDocument1:= TXMLDocument.Create(Application);
FVectorList:= TStringList.Create;
FBackColor := clBlack;
end;
procedure TVECTOR_CONTROL.DelSelect;
var
i: Integer;
AVLInfo : TVECTOR_LIEN_INFO;
begin
for i := FVectorList.Count - 1 downto 0 do
begin
AVLInfo := VectorInfo[i];
if AVLInfo.IsSelected then
begin
AVLInfo.Free;
FVectorList.Delete(i);
end;
end;
end;
procedure TVECTOR_CONTROL.DelVector(nVectorID: Integer);
var
i: Integer;
AVLineInfo : TVECTOR_LIEN_INFO;
begin
for i := FVectorList.Count - 1 downto 0 do
begin
AVLineInfo := VectorInfo[i];
if Assigned(AVLineInfo) then
begin
if AVLineInfo.VID = nVectorID then
begin
AVLineInfo.Free;
FVectorList.Delete(i);
end;
end;
end;
end;
destructor TVECTOR_CONTROL.Destroy;
begin
ClearList;
FVectorList.Free;
XMLDocument1.Free;
inherited;
end;
procedure TVECTOR_CONTROL.Draw;
function GetScale : Double;
begin
if (FRect.Right - FRect.Left)/430 > (FRect.Bottom - FRect.Top)/350 then
begin
Result := (FRect.Bottom - FRect.Top)/350
end
else
begin
Result := (FRect.Right - FRect.Left)/430
end;
end;
var
AVector : TVECTOR_LIEN_INFO;
i: Integer;
g: TGPGraphics;
p: TGPPen;
ACenterPoint : TPoint;
sb: TGPSolidBrush;
dScale : Double;
begin
if not Assigned(FCanvas) then
Exit;
// 计算放大倍数
dScale := GetScale;
// 画背景
g := TGPGraphics.Create(FCanvas.Handle);
g.SetSmoothingMode(TSmoothingMode(1));
with FRect do
begin
ACenterPoint := Point(Round((Left + Right)/2), Round((Top + Bottom)/2));
sb := TGPSolidBrush.Create(ColorRefToARGB(FBackColor));
g.FillRectangle(sb, Left ,top,Right-Left,Bottom-top);
p := TGPPen.Create(MakeColor(192,192,192), 1);
p.SetDashStyle(DashStyleDash);
g.DrawLine(p, Left+1 ,Top+1,Right-2,Top+1);
g.DrawLine(p, Right-2 ,Top+1,Right-2,Bottom-2);
g.DrawLine(p, Left+1 ,Top+1,Left+1,Bottom-2);
g.DrawLine(p, Left+1 ,Bottom-2,Right-2,Bottom-2);
g.DrawLine(p, Left ,ACenterPoint.Y,Right,ACenterPoint.y);
g.DrawLine(p, ACenterPoint.x ,Top,ACenterPoint.x,Bottom);
end;
g.Free;
p.Free;
// 辅助向量
for i := 0 to 2 do
begin
AVector := TVECTOR_LIEN_INFO.Create;
AVector.CenterPoint := ACenterPoint;
AVector.Canvas := FCanvas;
AVector.Scale := dScale;
// AVector.VName := 'U' + Char(ord('a') + i);
AVector.VName := '';
AVector.VColor := clSilver;
AVector.VValue := 220;
AVector.VAngle := 90 + 120*i;
AVector.Draw;
AVector.Free;
end;
// 画向量图
for i := 0 to FVectorList.Count - 1 do
begin
AVector := VectorInfo[i];
AVector.CenterPoint := ACenterPoint;
AVector.Canvas := FCanvas;
AVector.Scale := dScale;
AVector.Draw;
end;
end;
function TVECTOR_CONTROL.GetVectorInfo(nIndex: Integer): TVECTOR_LIEN_INFO;
begin
if (nIndex >= 0) and (nIndex < FVectorList.Count) then
begin
Result := TVECTOR_LIEN_INFO(FVectorList.Objects[nIndex]);
end
else
Result := nil;
end;
function TVECTOR_CONTROL.GetVectorStr: string;
const
C_XML = '<LineInfo VID ="%d" VName ="%s" VType="%s" VColor="%d" VValue="%f" VAngle="%f" VDrawPoint="%s">%s</LineInfo>';
var
i: Integer;
begin
Result := '<?xml version="1.0" encoding="gb2312"?>' + #13#10;
Result := Result + '<VectorMap>' + #13#10;
Result := Result + '<VectorLine>' + #13#10;
for i := 0 to FVectorList.Count - 1 do
begin
with VectorInfo[i] do
begin
Result := Result + Format(C_XML, [VID, VName, VTypeStr, VColor, VValue, VAngle,BoolToStr(IsDrawPoint), VName ]) + #13#10;
end;
end;
Result := Result + '</VectorLine>' + #13#10;
Result := Result + '</VectorMap>' + #13#10;
end;
function TVECTOR_CONTROL.MouseMove(APoint: TPoint): TVECTOR_LIEN_INFO;
var
i: Integer;
AVLInfo : TVECTOR_LIEN_INFO;
begin
Result := nil;
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
AVLInfo.IsOver := False;
end;
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
if AVLInfo.IsInLine(APoint) then
begin
Result := AVLInfo;
Result.IsOver := True;
Break;
end;
end;
end;
function TVECTOR_CONTROL.PointInVLine(APoint: TPoint): TVECTOR_LIEN_INFO;
var
i: Integer;
AVLInfo : TVECTOR_LIEN_INFO;
begin
Result := nil;
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
if AVLInfo.IsInLine(APoint) then
begin
Result := AVLInfo;
Break;
end;
end;
end;
procedure TVECTOR_CONTROL.SetNoSelect;
var
i: Integer;
AVLInfo : TVECTOR_LIEN_INFO;
begin
for i := 0 to FVectorList.Count - 1 do
begin
AVLInfo := VectorInfo[i];
AVLInfo.IsSelected := False;
AVLInfo.IsMainSelect := False;
end;
end;
procedure TVECTOR_CONTROL.SetVectorStr(const Value: string);
function GetStrValue(sValue : string; Anode:IXMLNode) : string;
var
oValue : OleVariant;
begin
oValue := Anode.Attributes[sValue];
if oValue <> null then
Result := oValue
else
Result := '';
end;
function GetIntValue(sValue : string; Anode:IXMLNode) : Integer;
var
oValue : OleVariant;
begin
oValue := Anode.Attributes[sValue];
if oValue <> null then
Result := oValue
else
Result := 0;
end;
function GetFloatValue(sValue : string; Anode:IXMLNode) : Double;
var
oValue : OleVariant;
begin
oValue := Anode.Attributes[sValue];
if oValue <> null then
Result := oValue
else
Result := 0;
end;
function GetBoolValue(sValue : string; Anode:IXMLNode) : Boolean;
var
oValue : OleVariant;
begin
oValue := Anode.Attributes[sValue];
if oValue <> null then
Result := oValue
else
Result := True;
end;
var
node, nodeInfo: IXMLNode;
i: Integer;
j: Integer;
AVLInfo : TVECTOR_LIEN_INFO;
begin
ClearList;
XMLDocument1.XML.Text := Value;
XMLDocument1.Active := True;
for i := 0 to XMLDocument1.DocumentElement.ChildNodes.Count - 1 do
begin
node := XMLDocument1.DocumentElement.ChildNodes[i];
if node.NodeName = 'VectorLine' then
begin
for j := 0 to node.ChildNodes.Count - 1 do
begin
nodeInfo := node.ChildNodes[j];
AVLInfo := AddVector;
AVLInfo.VID := GetIntValue('VID', nodeInfo);
AVLInfo.VName := GetStrValue('VName', nodeInfo);
AVLInfo.VTypeStr := GetStrValue('VType', nodeInfo);
AVLInfo.VColor := GetIntValue('VColor', nodeInfo);
AVLInfo.VValue := GetFloatValue('VValue', nodeInfo);
AVLInfo.VAngle := GetFloatValue('VAngle', nodeInfo);
AVLInfo.IsDrawPoint := GetBoolValue('VDrawPoint', nodeInfo);
end;
end;
end;
Draw;
end;
end.
|
{===============================================================================
串口通讯基类
===============================================================================}
unit xSerialBase;
interface
uses xCommBase, System.Types, xTypes, System.Classes, xFunction,
{$IFDEF MSWINDOWS}
SPComm,
{$ENDIF}
system.SysUtils, Forms;
type
TSerialBase = class(TCommBase)
private
// 串口对象
{$IFDEF MSWINDOWS}
FCommPort: TComm;
{$ENDIF}
FBaudRate: string;
FParity: string;
FPortSN: Byte;
FStopBits: string;
FPortName: string;
FFlowControl: string;
FDataBits: string;
procedure SetBaudRate(const Value: string);
procedure SetDataBits(const Value: string);
procedure SetFlowControl(const Value: string);
procedure SetParity(const Value: string);
procedure SetPortName(const Value: string);
procedure SetPortSN(const Value: Byte);
procedure SetStopBits(const Value: string);
{$IFDEF MSWINDOWS}
/// <summary>
/// 串口接收
/// </summary>
procedure ReceiveData(Sender: TObject; Buffer: Pointer; BufferLength: Word);
{$ENDIF}
protected
/// <summary>
///真实发送 串口或以太网发送
/// </summary>
function RealSend(APacks: TArray<Byte>; sParam1: string = ''; sParam2 : string=''): Boolean; override;
/// <summary>
/// 真实连接
/// </summary>
function RealConnect : Boolean; override;
/// <summary>
/// 真实断开连接
/// </summary>
procedure RealDisconnect; override;
public
constructor Create; override;
destructor Destroy; override;
/// <summary>
/// 串口名称
/// </summary>
property PortName: string read FPortName write SetPortName;
/// <summary>
/// 串口号
/// </summary>
property PortSN: Byte read FPortSN write SetPortSN;
/// <summary>
/// 波特率
/// </summary>
property BaudRate: string read FBaudRate write SetBaudRate;
/// <summary>
/// 数据位 5 6 7 8
/// </summary>
property DataBits: string read FDataBits write SetDataBits;
/// <summary>
/// 停止位 1 1.5 2
/// </summary>
property StopBits: string read FStopBits write SetStopBits;
/// <summary>
/// 校验位 None Odd Even Mark Space
/// </summary>
property Parity: string read FParity write SetParity;
/// <summary>
/// 数据流控制 Hardware Software None Custom
/// </summary>
property FlowControl : string read FFlowControl write SetFlowControl;
end;
implementation
{ TSerialBase }
constructor TSerialBase.Create;
begin
inherited;
// Coinitialize(nil);
{$IFDEF MSWINDOWS}
FCommPort:= TComm.Create(application);
FCommPort.OnReceiveData := ReceiveData;
FCommPort.Outx_XonXoffFlow := False;
{$ENDIF}
BaudRate := '9600';
DataBits := '8';
StopBits := '1';
Parity := 'None';
PortSN := 0;
end;
destructor TSerialBase.Destroy;
begin
inherited;
end;
function TSerialBase.RealConnect: Boolean;
begin
inherited;
Result := False;
try
if (FPortSN > 0) then
begin
{$IFDEF MSWINDOWS}
FCommPort.StartComm;
{$ENDIF}
Result := True;
end;
except
CommError(PortSNToName(FPortSN) + '打开失败!');
end;
end;
procedure TSerialBase.RealDisconnect;
begin
inherited;
{$IFDEF MSWINDOWS}
FCommPort.StopComm; //关闭端口
{$ENDIF}
end;
function TSerialBase.RealSend(APacks: TArray<Byte>; sParam1, sParam2 : string): Boolean;
var
sStr : string;
begin
Result := False;
try
if Active then
begin
sStr := PacksToStr(aPacks);
{$IFDEF MSWINDOWS}
// Result := FCommPort.WriteCommData(PAnsiChar(AnsiString(sStr)), Length(aPacks));
Result := FCommPort.WriteCommData(@aPacks[0], Length(aPacks));
{$ENDIF}
end
else
begin
Result := False;
CommError('串口未打开,发送失败!');
end;
except
end;
end;
{$IFDEF MSWINDOWS}
procedure TSerialBase.ReceiveData(Sender: TObject; Buffer: Pointer;
BufferLength: Word);
var
// sData : string;
APacks: TArray<Byte>;
begin
APacks := TBytes(Buffer);
SetLength(APacks, BufferLength);
// sData := string(PAnsiChar(Buffer));
RevStrData(PacksToStr(APacks));
RevPacksData(APacks)
end;
{$ENDIF}
procedure TSerialBase.SetBaudRate(const Value: string);
var
s : string;
n : Integer;
begin
s := Trim(Value);
if (s = '110') or
(s = '300') or
(s = '600') or
(s = '1200') or
(s = '2400') or
(s = '4800') or
(s = '9600') or
(s = '14400') or
(s = '19200') or
(s = '38400') or
(s = '56000') or
(s = '57600') or
(s = '115200') or
(s = '128000') or
(s = '256000') then
begin
FBaudRate := Value;
TryStrToInt(FBaudRate, n);
{$IFDEF MSWINDOWS}
FCommPort.BaudRate := n;
{$ENDIF}
end
else
CommError('设置波特率不合法!');
end;
procedure TSerialBase.SetDataBits(const Value: string);
{$IFDEF MSWINDOWS}
function GetByteSize(sData : string) : TByteSize;
begin
if sData = '5' then
Result := _5
else if sData = '6' then
Result := _6
else if sData = '7' then
Result := _7
else
Result := _8;
end;
{$ENDIF}
var
s: string;
begin
s := Trim(Value);
if (s = '5') or (s = '6') or (s = '7') or (s = '8') then
begin
FDataBits := Value;
{$IFDEF MSWINDOWS}
FCommPort.ByteSize := GetByteSize(FDataBits);
{$ENDIF}
end
else
CommError('设置数据位不合法!');
end;
procedure TSerialBase.SetFlowControl(const Value: string);
var
s: string;
begin
s := Trim(Value);
if (s='None') or (s='Hardware') or (s='Software') or (s='Custom') then
begin
FFlowControl := Value;
end
else
CommError('设置数据流控制不合法!');
end;
procedure TSerialBase.SetParity(const Value: string);
{$IFDEF MSWINDOWS}
function GetParity(sParity : string) : TParity;
begin
if sParity = 'None' then
Result := TParity.None
else if sParity = 'Odd' then
Result := Odd
else if sParity = 'Even' then
Result := Even
else if sParity = 'Mark' then
Result := Mark
else
Result := Space;
end;
{$ENDIF}
var
s: string;
begin
s := Trim(Value);
if (s='None') or (s='Odd') or (s='Even') or (s='Mark') or (s='Space') then
begin
FParity := s;
{$IFDEF MSWINDOWS}
FCommPort.Parity := GetParity(s);
{$ENDIF}
end
else
CommError('设置校验位不合法!');
end;
procedure TSerialBase.SetPortName(const Value: string);
begin
if Pos('COM', Value) > 0 then
begin
FPortSN := PortNameToSN(Value);
FPortName := PortSNToName(FPortSN);
{$IFDEF MSWINDOWS}
FCommPort.CommName := FPortName;
{$ENDIF}
end
else
begin
CommError('串口名称不合法!');
end;
end;
procedure TSerialBase.SetPortSN(const Value: Byte);
begin
FPortSN := Value;
PortName := PortSNToName(FPortSN);
end;
procedure TSerialBase.SetStopBits(const Value: string);
{$IFDEF MSWINDOWS}
function GetStopBits(sStop : string) : TStopBits;
begin
if sStop = '1' then
Result := _1
else if sStop = '1.5' then
Result := _1_5
else
Result := _2;
end;
{$ENDIF}
var
s: string;
begin
s := Trim(Value);
if (s = '1') or (s = '1.5') or (s = '2')then
begin
FStopBits := s;
{$IFDEF MSWINDOWS}
FCommPort.StopBits := GetStopBits(s);
{$ENDIF}
end
else
CommError('设置停止位不合法!');
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_RecastRegion;
interface
uses
Math, SysUtils, System.Generics.Collections,
RN_Helper, RN_Recast;
/// Builds the distance field for the specified compact heightfield.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in,out] chf A populated compact heightfield.
/// @returns True if the operation completed successfully.
function rcBuildDistanceField(ctx: TrcContext; chf: PrcCompactHeightfield): Boolean;
/// Builds region data for the heightfield using watershed partitioning.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in,out] chf A populated compact heightfield.
/// @param[in] borderSize The size of the non-navigable border around the heightfield.
/// [Limit: >=0] [Units: vx]
/// @param[in] minRegionArea The minimum number of cells allowed to form isolated island areas.
/// [Limit: >=0] [Units: vx].
/// @param[in] mergeRegionArea Any regions with a span count smaller than this value will, if possible,
/// be merged with larger regions. [Limit: >=0] [Units: vx]
/// @returns True if the operation completed successfully.
function rcBuildRegions(ctx: TrcContext; chf: PrcCompactHeightfield;
const borderSize, minRegionArea, mergeRegionArea: Integer): Boolean;
/// Builds region data for the heightfield by partitioning the heightfield in non-overlapping layers.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in,out] chf A populated compact heightfield.
/// @param[in] borderSize The size of the non-navigable border around the heightfield.
/// [Limit: >=0] [Units: vx]
/// @param[in] minRegionArea The minimum number of cells allowed to form isolated island areas.
/// [Limit: >=0] [Units: vx].
/// @returns True if the operation completed successfully.
{function rcBuildLayerRegions(ctx: TrcContext; chf: PrcCompactHeightfield;
const borderSize, minRegionArea: Integer): Boolean;}
/// Builds region data for the heightfield using simple monotone partitioning.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in,out] chf A populated compact heightfield.
/// @param[in] borderSize The size of the non-navigable border around the heightfield.
/// [Limit: >=0] [Units: vx]
/// @param[in] minRegionArea The minimum number of cells allowed to form isolated island areas.
/// [Limit: >=0] [Units: vx].
/// @param[in] mergeRegionArea Any regions with a span count smaller than this value will, if possible,
/// be merged with larger regions. [Limit: >=0] [Units: vx]
/// @returns True if the operation completed successfully.
{function rcBuildRegionsMonotone(ctx: TrcContext; chf: PrcCompactHeightfield;
const borderSize, minRegionArea, mergeRegionArea: Integer): Boolean;}
implementation
uses RN_RecastAlloc, RN_RecastHelper;
procedure calculateDistanceField(const chf: PrcCompactHeightfield; src: PWord; out maxDist: Word);
var w,h,i,x,y: Integer; c: PrcCompactCell; s,as1: PrcCompactSpan; area: Byte; nc,dir,ax,ay,ai,aax,aay,aai: Integer;
begin
w := chf.width;
h := chf.height;
// Init distance and points.
for i := 0 to chf.spanCount - 1 do
src[i] := $ffff;
// Mark boundary cells.
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
s := @chf.spans[i];
area := chf.areas[i];
nc := 0;
for dir := 0 to 3 do
begin
if (rcGetCon(s, dir) <> RC_NOT_CONNECTED) then
begin
ax := x + rcGetDirOffsetX(dir);
ay := y + rcGetDirOffsetY(dir);
ai := chf.cells[ax+ay*w].index + rcGetCon(s, dir);
if (area = chf.areas[ai]) then
Inc(nc);
end;
end;
if (nc <> 4) then
src[i] := 0;
end;
end;
end;
// Pass 1
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
s := @chf.spans[i];
if (rcGetCon(s, 0) <> RC_NOT_CONNECTED) then
begin
// (-1,0)
ax := x + rcGetDirOffsetX(0);
ay := y + rcGetDirOffsetY(0);
ai := chf.cells[ax+ay*w].index + rcGetCon(s, 0);
as1 := @chf.spans[ai];
if (src[ai]+2 < src[i]) then
src[i] := src[ai]+2;
// (-1,-1)
if (rcGetCon(as1, 3) <> RC_NOT_CONNECTED) then
begin
aax := ax + rcGetDirOffsetX(3);
aay := ay + rcGetDirOffsetY(3);
aai := chf.cells[aax+aay*w].index + rcGetCon(as1, 3);
if (src[aai]+3 < src[i]) then
src[i] := src[aai]+3;
end;
end;
if (rcGetCon(s, 3) <> RC_NOT_CONNECTED) then
begin
// (0,-1)
ax := x + rcGetDirOffsetX(3);
ay := y + rcGetDirOffsetY(3);
ai := chf.cells[ax+ay*w].index + rcGetCon(s, 3);
as1 := @chf.spans[ai];
if (src[ai]+2 < src[i]) then
src[i] := src[ai]+2;
// (1,-1)
if (rcGetCon(as1, 2) <> RC_NOT_CONNECTED) then
begin
aax := ax + rcGetDirOffsetX(2);
aay := ay + rcGetDirOffsetY(2);
aai := chf.cells[aax+aay*w].index + rcGetCon(as1, 2);
if (src[aai]+3 < src[i]) then
src[i] := src[aai]+3;
end;
end;
end;
end;
end;
// Pass 2
for y := h-1 downto 0 do
begin
for x := w-1 downto 0 do
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
s := @chf.spans[i];
if (rcGetCon(s, 2) <> RC_NOT_CONNECTED) then
begin
// (1,0)
ax := x + rcGetDirOffsetX(2);
ay := y + rcGetDirOffsetY(2);
ai := chf.cells[ax+ay*w].index + rcGetCon(s, 2);
as1 := @chf.spans[ai];
if (src[ai]+2 < src[i]) then
src[i] := src[ai]+2;
// (1,1)
if (rcGetCon(as1, 1) <> RC_NOT_CONNECTED) then
begin
aax := ax + rcGetDirOffsetX(1);
aay := ay + rcGetDirOffsetY(1);
aai := chf.cells[aax+aay*w].index + rcGetCon(as1, 1);
if (src[aai]+3 < src[i]) then
src[i] := src[aai]+3;
end;
end;
if (rcGetCon(s, 1) <> RC_NOT_CONNECTED) then
begin
// (0,1)
ax := x + rcGetDirOffsetX(1);
ay := y + rcGetDirOffsetY(1);
ai := chf.cells[ax+ay*w].index + rcGetCon(s, 1);
as1 := @chf.spans[ai];
if (src[ai]+2 < src[i]) then
src[i] := src[ai]+2;
// (-1,1)
if (rcGetCon(as1, 0) <> RC_NOT_CONNECTED) then
begin
aax := ax + rcGetDirOffsetX(0);
aay := ay + rcGetDirOffsetY(0);
aai := chf.cells[aax+aay*w].index + rcGetCon(as1, 0);
if (src[aai]+3 < src[i]) then
src[i] := src[aai]+3;
end;
end;
end;
end;
end;
maxDist := 0;
for i := 0 to chf.spanCount - 1 do
maxDist := rcMax(src[i], maxDist);
end;
function boxBlur(chf: PrcCompactHeightfield; thr: Integer;
src,dst: PWord): PWord;
var w,h,i,x,y: Integer; c: PrcCompactCell; s,as1: PrcCompactSpan; cd: Word; dir,dir2: Integer; d,ax,ay,ai,ax2,ay2,ai2: Integer;
begin
w := chf.width;
h := chf.height;
thr := thr*2;
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
s := @chf.spans[i];
cd := src[i];
if (cd <= thr) then
begin
dst[i] := cd;
continue;
end;
d := cd;
for dir := 0 to 3 do
begin
if (rcGetCon(s, dir) <> RC_NOT_CONNECTED) then
begin
ax := x + rcGetDirOffsetX(dir);
ay := y + rcGetDirOffsetY(dir);
ai := chf.cells[ax+ay*w].index + rcGetCon(s, dir);
Inc(d, src[ai]);
as1 := @chf.spans[ai];
dir2 := (dir+1) and $3;
if (rcGetCon(as1, dir2) <> RC_NOT_CONNECTED) then
begin
ax2 := ax + rcGetDirOffsetX(dir2);
ay2 := ay + rcGetDirOffsetY(dir2);
ai2 := chf.cells[ax2+ay2*w].index + rcGetCon(as1, dir2);
Inc(d, src[ai2]);
end
else
begin
d := d + cd;
end;
end
else
begin
d := d + cd*2;
end;
end;
dst[i] := Trunc((d+5)/9);
end;
end;
end;
Result := dst;
end;
function floodRegion(x, y, i: Integer;
level,r: Word;
chf: PrcCompactHeightfield;
srcReg, srcDist: PWord;
stack: PrcIntArray): Boolean;
var w,dir: Integer; area: Byte; cs,as1: PrcCompactSpan; lev,ar,nr: Word; count,ci,cx,cy,ax,ay,ai,ax2,ay2,ai2,dir2,nr2: Integer;
begin
w := chf.width;
area := chf.areas[i];
// Flood fill mark region.
stack.resize(0);
stack.push(x);
stack.push(y);
stack.push(i);
srcReg[i] := r;
srcDist[i] := 0;
if level >= 2 then lev := level-2 else lev := 0;
count := 0;
while (stack.size > 0) do
begin
ci := stack.pop();
cy := stack.pop();
cx := stack.pop();
cs := @chf.spans[ci];
// Check if any of the neighbours already have a valid region set.
ar := 0;
for dir := 0 to 3 do
begin
// 8 connected
if (rcGetCon(cs, dir) <> RC_NOT_CONNECTED) then
begin
ax := cx + rcGetDirOffsetX(dir);
ay := cy + rcGetDirOffsetY(dir);
ai := chf.cells[ax+ay*w].index + rcGetCon(cs, dir);
if (chf.areas[ai] <> area) then
continue;
nr := srcReg[ai];
if (nr and RC_BORDER_REG) <> 0 then// Do not take borders into account.
continue;
if (nr <> 0) and (nr <> r) then
begin
ar := nr;
break;
end;
as1 := @chf.spans[ai];
dir2 := (dir+1) and $3;
if (rcGetCon(as1, dir2) <> RC_NOT_CONNECTED) then
begin
ax2 := ax + rcGetDirOffsetX(dir2);
ay2 := ay + rcGetDirOffsetY(dir2);
ai2 := chf.cells[ax2+ay2*w].index + rcGetCon(as1, dir2);
if (chf.areas[ai2] <> area) then
continue;
nr2 := srcReg[ai2];
if (nr2 <> 0) and (nr2 <> r) then
begin
ar := nr2;
break;
end;
end;
end;
end;
if (ar <> 0) then
begin
srcReg[ci] := 0;
//C++ seems to be doing loop increase, so do we
continue;
end;
Inc(count);
// Expand neighbours.
for dir := 0 to 3 do
begin
if (rcGetCon(cs, dir) <> RC_NOT_CONNECTED) then
begin
ax := cx + rcGetDirOffsetX(dir);
ay := cy + rcGetDirOffsetY(dir);
ai := chf.cells[ax+ay*w].index + rcGetCon(cs, dir);
if (chf.areas[ai] <> area) then
continue;
if (chf.dist[ai] >= lev) and (srcReg[ai] = 0) then
begin
srcReg[ai] := r;
srcDist[ai] := 0;
stack.push(ax);
stack.push(ay);
stack.push(ai);
end;
end;
end;
end;
Result := count > 0;
end;
function expandRegions(maxIter: Integer; level: Word;
chf: PrcCompactHeightfield;
srcReg, srcDist,
dstReg, dstDist: PWord;
stack: PrcIntArray;
fillStack: Boolean): PWord;
var w,h,i,j,x,y: Integer; c: PrcCompactCell; s: PrcCompactSpan; iter,failed,dir: Integer; r,d2: Word; area: Byte; ax,ay,ai: Integer;
begin
w := chf.width;
h := chf.height;
if (fillStack) then
begin
// Find cells revealed by the raised level.
stack.resize(0);
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
if (chf.dist[i] >= level) and (srcReg[i] = 0) and (chf.areas[i] <> RC_NULL_AREA) then
begin
stack.push(x);
stack.push(y);
stack.push(i);
end;
end;
end;
end;
end
else // use cells in the input stack
begin
// mark all cells which already have a region
//for (int j=0; j<stack.size(); j+=3)
for j := 0 to stack.size div 3 - 1 do
begin
i := stack^[j*3+2];
if (srcReg[i] <> 0) then
stack^[j*3+2] := -1;
end;
end;
iter := 0;
while (stack.size > 0) do
begin
failed := 0;
Move(srcReg^, dstReg^, sizeof(Word)*chf.spanCount);
Move(srcDist^, dstDist^, sizeof(Word)*chf.spanCount);
//for (int j = 0; j < stack.size(); j += 3)
for j := 0 to stack.size div 3 - 1 do
begin
x := stack^[j*3+0];
y := stack^[j*3+1];
i := stack^[j*3+2];
if (i < 0) then
begin
Inc(failed);
continue;
end;
r := srcReg[i];
d2 := $ffff;
area := chf.areas[i];
s := @chf.spans[i];
for dir := 0 to 3 do
begin
if (rcGetCon(s, dir) = RC_NOT_CONNECTED) then continue;
ax := x + rcGetDirOffsetX(dir);
ay := y + rcGetDirOffsetY(dir);
ai := chf.cells[ax+ay*w].index + rcGetCon(s, dir);
if (chf.areas[ai] <> area) then continue;
if (srcReg[ai] > 0) and ((srcReg[ai] and RC_BORDER_REG) = 0) then
begin
if (srcDist[ai]+2 < d2) then
begin
r := srcReg[ai];
d2 := srcDist[ai]+2;
end;
end;
end;
if (r <> 0) then
begin
stack^[j*3+2] := -1; // mark as used
dstReg[i] := r;
dstDist[i] := d2;
end
else
begin
Inc(failed);
end;
end;
// rcSwap source and dest.
rcSwap(Pointer(srcReg), Pointer(dstReg));
rcSwap(Pointer(srcDist), Pointer(dstDist));
if (failed*3 = stack.size) then
break;
if (level > 0) then
begin
Inc(iter);
if (iter >= maxIter) then
break;
end;
end;
Result := srcReg;
end;
procedure sortCellsByLevel(startLevel: Word;
chf: PrcCompactHeightfield;
srcReg: PWord;
nbStacks: Integer; const stacks: TArrayOfTrcIntArray;
loglevelsPerStack: Word); // the levels per stack (2 in our case) as a bit shift
var w,h,i,j,x,y: Integer; c: PrcCompactCell; level,sId: Integer;
begin
w := chf.width;
h := chf.height;
startLevel := startLevel shr loglevelsPerStack;
for j := 0 to nbStacks - 1 do
stacks[j].resize(0);
// put all cells in the level range into the appropriate stacks
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
if (chf.areas[i] = RC_NULL_AREA) or (srcReg[i] <> 0) then
continue;
level := chf.dist[i] shr loglevelsPerStack;
sId := startLevel - level;
if (sId >= nbStacks) then
continue;
if (sId < 0) then
sId := 0;
stacks[sId].push(x);
stacks[sId].push(y);
stacks[sId].push(i);
end;
end;
end;
end;
procedure appendStacks(srcStack, dstStack: PrcIntArray;
srcReg: PWord);
var i,j: Integer;
begin
for j := 0 to srcStack.size div 3 - 1 do
begin
i := srcStack^[j*3+2];
if ((i < 0) or (srcReg[i] <> 0)) then
continue;
dstStack.push(srcStack^[j*3]);
dstStack.push(srcStack^[j*3+1]);
dstStack.push(srcStack^[j*3+2]);
end;
end;
type
TrcRegion = record
spanCount: Integer; // Number of spans belonging to this region
id: Word; // ID of the region
areaType: Byte; // Are type.
remap: Boolean;
visited: Boolean;
overlap: Boolean;
connectsToBorder: Boolean;
ymin, ymax: Word;
connections: TrcIntArray;
floors: TrcIntArray;
end;
PrcRegion = ^TrcRegion;
function rcRegion(i: Word): TrcRegion;
begin
with Result do
begin
spanCount := 0;
id := i;
areaType := 0;
remap := false;
visited := false;
overlap := false;
connectsToBorder := false;
ymin := $ffff;
ymax := 0;
connections.Create(0);
floors.Create(0);
end;
end;
// Delphi: Manually dispose of allocated memory within TrcIntArray;
procedure rcRegionFree(r: TrcRegion);
begin
r.connections.Free;
r.floors.Free;
end;
procedure removeAdjacentNeighbours(reg: PrcRegion);
var i,j,ni: Integer;
begin
// Remove adjacent duplicates.
//for (int i := 0; i < reg.connections.size() and reg.connections.size() > 1; )
i := 0;
while(i < reg.connections.size) and (reg.connections.size > 1) do
begin
ni := (i+1) mod reg.connections.size;
if (reg.connections[i] = reg.connections[ni]) then
begin
// Remove duplicate
for j := i to reg.connections.size-1-1 do
reg.connections[j] := reg.connections[j+1];
reg.connections.pop();
end
else
Inc(i);
end;
end;
procedure replaceNeighbour(reg: PrcRegion; oldId, newId: Word);
var neiChanged: Boolean; i: Integer;
begin
neiChanged := false;
for i := 0 to reg.connections.size - 1 do
begin
if (reg.connections[i] = oldId) then
begin
reg.connections[i] := newId;
neiChanged := true;
end;
end;
for i := 0 to reg.floors.size - 1 do
begin
if (reg.floors[i] = oldId) then
reg.floors[i] := newId;
end;
if (neiChanged) then
removeAdjacentNeighbours(reg);
end;
function canMergeWithRegion(const rega, regb: PrcRegion): Boolean;
var n,i: Integer;
begin
if (rega.areaType <> regb.areaType) then
Exit(false);
n := 0;
for i := 0 to rega.connections.size - 1 do
begin
if (rega.connections[i] = regb.id) then
Inc(n);
end;
if (n > 1) then
Exit(false);
for i := 0 to rega.floors.size - 1 do
begin
if (rega.floors[i] = regb.id) then
Exit(false);
end;
Result := true;
end;
procedure addUniqueFloorRegion(reg: PrcRegion; n: Integer);
var i: Integer;
begin
for i := 0 to reg.floors.size - 1 do
if (reg.floors[i] = n) then
Exit;
reg.floors.push(n);
end;
function mergeRegions(rega, regb: PrcRegion): Boolean;
var aid,bid: Word; acon: TrcIntArray; bcon: PrcIntArray; i,j,ni,insa,insb: Integer;
begin
aid := rega.id;
bid := regb.id;
// Duplicate current neighbourhood.
acon.create(rega.connections.size);
for i := 0 to rega.connections.size - 1 do
acon[i] := rega.connections[i];
bcon := @regb.connections;
// Find insertion point on A.
insa := -1;
for i := 0 to acon.size - 1 do
begin
if (acon[i] = bid) then
begin
insa := i;
break;
end;
end;
if (insa = -1) then
Exit(false);
// Find insertion point on B.
insb := -1;
for i := 0 to bcon.size - 1 do
begin
if (bcon^[i] = aid) then
begin
insb := i;
break;
end;
end;
if (insb = -1) then
Exit(false);
// Merge neighbours.
rega.connections.resize(0);
//for (int i := 0, ni := acon.size(); i < ni-1; ++i)
i := 0;
ni := acon.size;
while (i < ni-1) do
begin
rega.connections.push(acon[(insa+1+i) mod ni]);
Inc(i);
end;
//for ( int i := 0, ni := bcon.size(); i < ni-1; ++i)
i := 0;
ni := bcon.size;
while (i < ni-1) do
begin
rega.connections.push(bcon^[(insb+1+i) mod ni]);
Inc(i);
end;
removeAdjacentNeighbours(rega);
for j := 0 to regb.floors.size - 1 do
addUniqueFloorRegion(rega, regb.floors[j]);
rega.spanCount := rega.spanCount + regb.spanCount;
regb.spanCount := 0;
regb.connections.resize(0);
// Delphi: Manually release record and buffer it holds within
acon.Free;
Result := true;
end;
function isRegionConnectedToBorder(reg: PrcRegion): Boolean;
var i: Integer;
begin
// Region is connected to border if
// one of the neighbours is null id.
for i := 0 to reg.connections.size - 1 do
begin
if (reg.connections[i] = 0) then
Exit(true);
end;
Result := false;
end;
function isSolidEdge(chf: PrcCompactHeightfield; srcReg: PWord;
x,y,i,dir: Integer): Boolean;
var s: PrcCompactSpan; r: Word; ax,ay,ai: Integer;
begin
s := @chf.spans[i];
r := 0;
if (rcGetCon(s, dir) <> RC_NOT_CONNECTED) then
begin
ax := x + rcGetDirOffsetX(dir);
ay := y + rcGetDirOffsetY(dir);
ai := chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
r := srcReg[ai];
end;
if (r = srcReg[i]) then
Exit(false);
Result := true;
end;
procedure walkContour(x, y, i, dir: Integer;
chf: PrcCompactHeightfield;
srcReg: PWord;
cont: PrcIntArray);
var startDir,starti: Integer; s,ss: PrcCompactSpan; curReg,r: Word; ax,ay,ai: Integer; iter: Integer; ni,nx,ny: Integer;
nc: PrcCompactCell; j,nj,k: Integer;
begin
startDir := dir;
starti := i;
ss := @chf.spans[i];
curReg := 0;
if (rcGetCon(ss, dir) <> RC_NOT_CONNECTED) then
begin
ax := x + rcGetDirOffsetX(dir);
ay := y + rcGetDirOffsetY(dir);
ai := chf.cells[ax+ay*chf.width].index + rcGetCon(ss, dir);
curReg := srcReg[ai];
end;
cont.push(curReg);
iter := 0;
while (iter < 40000) do
begin
Inc(iter);
s := @chf.spans[i];
if (isSolidEdge(chf, srcReg, x, y, i, dir)) then
begin
// Choose the edge corner
r := 0;
if (rcGetCon(s, dir) <> RC_NOT_CONNECTED) then
begin
ax := x + rcGetDirOffsetX(dir);
ay := y + rcGetDirOffsetY(dir);
ai := chf.cells[ax+ay*chf.width].index + rcGetCon(s, dir);
r := srcReg[ai];
end;
if (r <> curReg) then
begin
curReg := r;
cont.push(curReg);
end;
dir := (dir+1) and $3; // Rotate CW
end
else
begin
ni := -1;
nx := x + rcGetDirOffsetX(dir);
ny := y + rcGetDirOffsetY(dir);
if (rcGetCon(s, dir) <> RC_NOT_CONNECTED) then
begin
nc := @chf.cells[nx+ny*chf.width];
ni := nc.index + rcGetCon(s, dir);
end;
if (ni = -1) then
begin
// Should not happen.
Exit;
end;
x := nx;
y := ny;
i := ni;
dir := (dir+3) and $3; // Rotate CCW
end;
if (starti = i) and (startDir = dir) then
begin
break;
end;
end;
// Remove adjacent duplicates.
if (cont.size > 1) then
begin
//for (int j = 0; j < cont.size(); )
j := 0;
while (j < cont.size) do
begin
nj := (j+1) mod cont.size;
if (cont^[j] = cont^[nj]) then
begin
for k := j to cont.size-1 - 1 do
cont^[k] := cont^[k+1];
cont.pop();
end
else
Inc(j);
end;
end;
end;
function mergeAndFilterRegions(ctx: TrcContext; minRegionArea, mergeRegionSize: Integer;
maxRegionId: PWord;
chf: PrcCompactHeightfield;
srcReg: PWord; overlaps: PrcIntArray): Boolean;
var w,h,nreg,i,j,ni,ndir,dir,x,y: Integer; regions: PrcRegion; c: PrcCompactCell; r: Word; reg,creg,neireg,mreg,target: PrcRegion;
floorId: Word; stack,trace: TrcIntArray; connectsToBorder: Boolean; spanCount,ri: Integer; mergeCount,smallest: Integer;
mergeId, oldId, regIdGen, newId: Word;
begin
w := chf.width;
h := chf.height;
nreg := maxRegionId^+1;
GetMem(regions, sizeof(TrcRegion)*nreg);
// Construct regions
for i := 0 to nreg - 1 do
regions[i] := rcRegion(i);
// Find edge of a region and find connections around the contour.
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
c := @chf.cells[x+y*w];
ni := (c.index+c.count);
for i := c.index to ni - 1 do
begin
r := srcReg[i];
if (r = 0) or (r >= nreg) then
continue;
reg := @regions[r];
Inc(reg.spanCount);
// Update floors.
for j := c.index to ni - 1 do
begin
if (i = j) then continue;
floorId := srcReg[j];
if (floorId = 0) or (floorId >= nreg) then
continue;
if (floorId = r) then
reg.overlap := true;
addUniqueFloorRegion(reg, floorId);
end;
// Have found contour
if (reg.connections.size > 0) then
continue;
reg.areaType := chf.areas[i];
// Check if this cell is next to a border.
ndir := -1;
for dir := 0 to 3 do
begin
if (isSolidEdge(chf, srcReg, x, y, i, dir)) then
begin
ndir := dir;
break;
end;
end;
if (ndir <> -1) then
begin
// The cell is at border.
// Walk around the contour to find all the neighbours.
walkContour(x, y, i, ndir, chf, srcReg, @reg.connections);
end;
end;
end;
end;
// Remove too small regions.
stack.Create(32);
trace.Create(32);
for i := 0 to nreg - 1 do
begin
reg := @regions[i];
if (reg.id = 0) or (reg.id and RC_BORDER_REG <> 0) then
continue;
if (reg.spanCount = 0) then
continue;
if (reg.visited) then
continue;
// Count the total size of all the connected regions.
// Also keep track of the regions connects to a tile border.
connectsToBorder := false;
spanCount := 0;
stack.resize(0);
trace.resize(0);
reg.visited := true;
stack.push(i);
while (stack.size <> 0) do
begin
// Pop
ri := stack.pop();
creg := @regions[ri];
Inc(spanCount, creg.spanCount);
trace.push(ri);
for j := 0 to creg.connections.size - 1 do
begin
if (creg.connections[j] and RC_BORDER_REG) <> 0 then
begin
connectsToBorder := true;
continue;
end;
neireg := @regions[creg.connections[j]];
if (neireg.visited) then
continue;
if (neireg.id = 0) or (neireg.id and RC_BORDER_REG <> 0) then
continue;
// Visit
stack.push(neireg.id);
neireg.visited := true;
end;
end;
// If the accumulated regions size is too small, remove it.
// Do not remove areas which connect to tile borders
// as their size cannot be estimated correctly and removing them
// can potentially remove necessary areas.
if (spanCount < minRegionArea) and (not connectsToBorder) then
begin
// Kill all visited regions.
for j := 0 to trace.size - 1 do
begin
regions[trace[j]].spanCount := 0;
regions[trace[j]].id := 0;
end;
end;
end;
// Delphi: Manually release record and buffer it holds within
stack.Free;
trace.Free;
// Merge too small regions to neighbour regions.
mergeCount := 0;
repeat
mergeCount := 0;
for i := 0 to nreg - 1 do
begin
reg := @regions[i];
if (reg.id = 0) or (reg.id and RC_BORDER_REG <> 0) then
continue;
if (reg.overlap) then
continue;
if (reg.spanCount = 0) then
continue;
// Check to see if the region should be merged.
if (reg.spanCount > mergeRegionSize) and isRegionConnectedToBorder(reg) then
continue;
// Small region with more than 1 connection.
// Or region which is not connected to a border at all.
// Find smallest neighbour region that connects to this one.
smallest := $fffffff;
mergeId := reg.id;
for j := 0 to reg.connections.size - 1 do
begin
if (reg.connections[j] and RC_BORDER_REG <> 0) then continue;
mreg := @regions[reg.connections[j]];
if (mreg.id = 0) or (mreg.id and RC_BORDER_REG <> 0) or (mreg.overlap) then continue;
if (mreg.spanCount < smallest) and
canMergeWithRegion(reg, mreg) and
canMergeWithRegion(mreg, reg) then
begin
smallest := mreg.spanCount;
mergeId := mreg.id;
end;
end;
// Found new id.
if (mergeId <> reg.id) then
begin
oldId := reg.id;
target := @regions[mergeId];
// Merge neighbours.
if (mergeRegions(target, reg)) then
begin
// Fixup regions pointing to current region.
for j := 0 to nreg - 1 do
begin
if (regions[j].id = 0) or (regions[j].id and RC_BORDER_REG <> 0) then continue;
// If another region was already merged into current region
// change the nid of the previous region too.
if (regions[j].id = oldId) then
regions[j].id := mergeId;
// Replace the current region with the new one if the
// current regions is neighbour.
replaceNeighbour(@regions[j], oldId, mergeId);
end;
Inc(mergeCount);
end;
end;
end;
until (mergeCount <= 0);
// Compress region Ids.
for i := 0 to nreg - 1 do
begin
regions[i].remap := false;
if (regions[i].id = 0) then continue; // Skip nil regions.
if (regions[i].id and RC_BORDER_REG <> 0) then continue; // Skip external regions.
regions[i].remap := true;
end;
regIdGen := 0;
for i := 0 to nreg - 1 do
begin
if (not regions[i].remap) then
continue;
oldId := regions[i].id;
Inc(regIdGen);
newId := regIdGen;
for j := i to nreg - 1 do
begin
if (regions[j].id = oldId) then
begin
regions[j].id := newId;
regions[j].remap := false;
end;
end;
end;
maxRegionId^ := regIdGen;
// Remap regions.
for i := 0 to chf.spanCount - 1 do
begin
if ((srcReg[i] and RC_BORDER_REG) = 0) then
srcReg[i] := regions[srcReg[i]].id;
end;
// Return regions that we found to be overlapping.
for i := 0 to nreg - 1 do
if (regions[i].overlap) then
overlaps.push(regions[i].id);
for i := 0 to nreg - 1 do
rcRegionFree(regions[i]);
FreeMem(regions);
Result := true;
end;
procedure addUniqueConnection(reg: PrcRegion; n: Integer);
var i: Integer;
begin
for i := 0 to reg.connections.size - 1 do
if (reg.connections[i] = n) then
Exit;
reg.connections.push(n);
end;
{function mergeAndFilterLayerRegions(ctx: TrcContext; int minRegionArea,
unsigned short& maxRegionId,
chf: TrcCompactHeightfield;,
unsigned short* srcReg, rcIntArray& overlaps): Boolean;
var w,h,i,x,y: Integer; c: PrcCompactCell; s: PrcCompactSpan;
begin
w := chf.width;
h := chf.height;
const int nreg := maxRegionId+1;
rcRegion* regions := (rcRegion*)rcAlloc(sizeof(rcRegion)*nreg, RC_ALLOC_TEMP);
if (!regions)
begin
ctx.log(RC_LOG_ERROR, 'mergeAndFilterLayerRegions: Out of memory 'regions' (%d).', nreg);
return false;
end;
// Construct regions
for (int i := 0; i < nreg; ++i)
new(®ions[i]) rcRegion((unsigned short)i);
// Find region neighbours and overlapping regions.
rcIntArray lregs(32);
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
c := @chf.cells[x+y*w];
lregs.resize(0);
for i := c.index to Integer(c.index+c.count) - 1 do
begin
s := @chf.spans[i];
const unsigned short ri := srcReg[i];
if (ri = 0 or ri >= nreg) continue;
rcRegion& reg := regions[ri];
reg.spanCount++;
reg.ymin := rcMin(reg.ymin, s.y);
reg.ymax := rcMax(reg.ymax, s.y);
// Collect all region layers.
lregs.push(ri);
// Update neighbours
for dir := 0 to 3 do
begin
if (rcGetCon(s, dir) <> RC_NOT_CONNECTED)
begin
const int ax := x + rcGetDirOffsetX(dir);
const int ay := y + rcGetDirOffsetY(dir);
const int ai := chf.cells[ax+ay*w].index + rcGetCon(s, dir);
const unsigned short rai := srcReg[ai];
if (rai > 0 and rai < nreg and rai <> ri)
addUniqueConnection(reg, rai);
if (rai & RC_BORDER_REG)
reg.connectsToBorder := true;
end;
end;
end;
// Update overlapping regions.
for (int i := 0; i < lregs.size()-1; ++i)
begin
for (int j := i+1; j < lregs.size(); ++j)
begin
if (lregs[i] <> lregs[j])
begin
rcRegion& ri := regions[lregs[i]];
rcRegion& rj := regions[lregs[j]];
addUniqueFloorRegion(ri, lregs[j]);
addUniqueFloorRegion(rj, lregs[i]);
end;
end;
end;
end;
end;
// Create 2D layers from regions.
unsigned short layerId := 1;
for (int i := 0; i < nreg; ++i)
regions[i].id := 0;
// Merge montone regions to create non-overlapping areas.
rcIntArray stack(32);
for (int i := 1; i < nreg; ++i)
begin
rcRegion& root := regions[i];
// Skip already visited.
if (root.id <> 0)
continue;
// Start search.
root.id := layerId;
stack.resize(0);
stack.push(i);
while (stack.size() > 0)
begin
// Pop front
rcRegion& reg := regions[stack[0]];
for (int j := 0; j < stack.size()-1; ++j)
stack[j] := stack[j+1];
stack.resize(stack.size()-1);
const int ncons := (int)reg.connections.size();
for (int j := 0; j < ncons; ++j)
begin
const int nei := reg.connections[j];
rcRegion& regn := regions[nei];
// Skip already visited.
if (regn.id <> 0)
continue;
// Skip if the neighbour is overlapping root region.
bool overlap := false;
for (int k := 0; k < root.floors.size(); k++)
begin
if (root.floors[k] = nei)
begin
overlap := true;
break;
end;
end;
if (overlap)
continue;
// Deepen
stack.push(nei);
// Mark layer id
regn.id := layerId;
// Merge current layers to root.
for (int k := 0; k < regn.floors.size(); ++k)
addUniqueFloorRegion(root, regn.floors[k]);
root.ymin := rcMin(root.ymin, regn.ymin);
root.ymax := rcMax(root.ymax, regn.ymax);
root.spanCount += regn.spanCount;
regn.spanCount := 0;
root.connectsToBorder := root.connectsToBorder or regn.connectsToBorder;
end;
end;
layerId++;
end;
// Remove small regions
for (int i := 0; i < nreg; ++i)
begin
if (regions[i].spanCount > 0 and regions[i].spanCount < minRegionArea and !regions[i].connectsToBorder)
begin
unsigned short reg := regions[i].id;
for (int j := 0; j < nreg; ++j)
if (regions[j].id = reg)
regions[j].id := 0;
end;
end;
// Compress region Ids.
for (int i := 0; i < nreg; ++i)
begin
regions[i].remap := false;
if (regions[i].id = 0) continue; // Skip nil regions.
if (regions[i].id & RC_BORDER_REG) continue; // Skip external regions.
regions[i].remap := true;
end;
unsigned short regIdGen := 0;
for (int i := 0; i < nreg; ++i)
begin
if (!regions[i].remap)
continue;
unsigned short oldId := regions[i].id;
unsigned short newId := ++regIdGen;
for (int j := i; j < nreg; ++j)
begin
if (regions[j].id = oldId)
begin
regions[j].id := newId;
regions[j].remap := false;
end;
end;
end;
maxRegionId := regIdGen;
// Remap regions.
for for i := 0 to chf.spanCount - 1 do
begin
if ((srcReg[i] & RC_BORDER_REG) = 0)
srcReg[i] := regions[srcReg[i]].id;
end;
for (int i := 0; i < nreg; ++i)
regions[i].~rcRegion();
rcFree(regions);
return true;
end;}
/// @par
///
/// This is usually the second to the last step in creating a fully built
/// compact heightfield. This step is required before regions are built
/// using #rcBuildRegions or #rcBuildRegionsMonotone.
///
/// After this step, the distance data is available via the rcCompactHeightfield::maxDistance
/// and rcCompactHeightfield::dist fields.
///
/// @see rcCompactHeightfield, rcBuildRegions, rcBuildRegionsMonotone
function rcBuildDistanceField(ctx: TrcContext; chf: PrcCompactHeightfield): Boolean;
var maxDist: Word; src,dst: PWord;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_BUILD_DISTANCEFIELD);
if (chf.dist <> nil) then
begin
FreeMem(chf.dist);
chf.dist := nil;
end;
GetMem(src, SizeOf(Word) * chf.spanCount);
GetMem(dst, SizeOf(Word) * chf.spanCount);
maxDist := 0;
ctx.startTimer(RC_TIMER_BUILD_DISTANCEFIELD_DIST);
calculateDistanceField(chf, src, maxDist);
chf.maxDistance := maxDist;
ctx.stopTimer(RC_TIMER_BUILD_DISTANCEFIELD_DIST);
ctx.startTimer(RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
// Blur
if (boxBlur(chf, 1, src, dst) <> src) then
rcSwap(Pointer(src), Pointer(dst));
// Store distance.
chf.dist := src;
ctx.stopTimer(RC_TIMER_BUILD_DISTANCEFIELD_BLUR);
ctx.stopTimer(RC_TIMER_BUILD_DISTANCEFIELD);
FreeMem(dst);
Result := true;
end;
procedure paintRectRegion(minx, maxx, miny, maxy: Integer; regId: Word;
chf: PrcCompactHeightfield; srcReg: PWord);
var w,i,x,y: Integer; c: PrcCompactCell;
begin
w := chf.width;
for y := miny to maxy - 1 do
begin
for x := minx to maxx - 1 do
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
if (chf.areas[i] <> RC_NULL_AREA) then
srcReg[i] := regId;
end;
end;
end;
end;
const RC_NULL_NEI = $ffff;
type
TcSweepSpan = record
rid: Word; // row id
id: Word; // region id
ns: Word; // number samples
nei: Word; // neighbour id
end;
/// @par
///
/// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour.
/// Contours will form simple polygons.
///
/// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be
/// re-assigned to the zero (null) region.
///
/// Partitioning can result in smaller than necessary regions. @p mergeRegionArea helps
/// reduce unecessarily small regions.
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// The region data will be available via the rcCompactHeightfield::maxRegions
/// and rcCompactSpan::reg fields.
///
/// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions.
///
/// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig
{function rcBuildRegionsMonotone(ctx: TrcContext; chf: PrcCompactHeightfield;
const borderSize, minRegionArea, mergeRegionArea: Integer): Boolean;
var w,h,i,x,y: Integer; c: PrcCompactCell; s: PrcCompactSpan;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_BUILD_REGIONS);
w := chf.width;
h := chf.height;
unsigned short id := 1;
rcScopedDelete<unsigned short> srcReg := (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
if (!srcReg)
begin
ctx.log(RC_LOG_ERROR, 'rcBuildRegionsMonotone: Out of memory 'src' (%d).', chf.spanCount);
return false;
end;
memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
const int nsweeps := rcMax(chf.width,chf.height);
rcScopedDelete<rcSweepSpan> sweeps := (rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP);
if (!sweeps)
begin
ctx.log(RC_LOG_ERROR, 'rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).', nsweeps);
return false;
end;
// Mark border regions.
if (borderSize > 0)
begin
// Make sure border will not overflow.
const int bw := rcMin(w, borderSize);
const int bh := rcMin(h, borderSize);
// Paint regions
paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++;
chf.borderSize := borderSize;
end;
rcIntArray prev(256);
// Sweep one line at a time.
for (int y := borderSize; y < h-borderSize; ++y)
begin
// Collect spans from this row.
prev.resize(id+1);
memset(&prev[0],0,sizeof(int)*id);
unsigned short rid := 1;
for (int x := borderSize; x < w-borderSize; ++x)
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
s := @chf.spans[i];
if (chf.areas[i] = RC_NULL_AREA) continue;
// -x
unsigned short previd := 0;
if (rcGetCon(s, 0) <> RC_NOT_CONNECTED)
begin
const int ax := x + rcGetDirOffsetX(0);
const int ay := y + rcGetDirOffsetY(0);
const int ai := chf.cells[ax+ay*w].index + rcGetCon(s, 0);
if ((srcReg[ai] & RC_BORDER_REG) = 0 and chf.areas[i] = chf.areas[ai])
previd := srcReg[ai];
end;
if (!previd)
begin
previd := rid++;
sweeps[previd].rid := previd;
sweeps[previd].ns := 0;
sweeps[previd].nei := 0;
end;
// -y
if (rcGetCon(s,3) <> RC_NOT_CONNECTED)
begin
const int ax := x + rcGetDirOffsetX(3);
const int ay := y + rcGetDirOffsetY(3);
const int ai := chf.cells[ax+ay*w].index + rcGetCon(s, 3);
if (srcReg[ai] and (srcReg[ai] & RC_BORDER_REG) = 0 and chf.areas[i] = chf.areas[ai])
begin
unsigned short nr := srcReg[ai];
if (!sweeps[previd].nei or sweeps[previd].nei = nr)
begin
sweeps[previd].nei := nr;
sweeps[previd].ns++;
prev[nr]++;
end;
else
begin
sweeps[previd].nei := RC_NULL_NEI;
end;
end;
end;
srcReg[i] := previd;
end;
end;
// Create unique ID.
for (int i := 1; i < rid; ++i)
begin
if (sweeps[i].nei <> RC_NULL_NEI and sweeps[i].nei <> 0 and
prev[sweeps[i].nei] = (int)sweeps[i].ns)
begin
sweeps[i].id := sweeps[i].nei;
end;
else
begin
sweeps[i].id := id++;
end;
end;
// Remap IDs
for (int x := borderSize; x < w-borderSize; ++x)
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
if (srcReg[i] > 0 and srcReg[i] < rid)
srcReg[i] := sweeps[srcReg[i]].id;
end;
end;
end;
ctx.startTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Merge regions and filter out small regions.
rcIntArray overlaps;
chf.maxRegions := id;
if (!mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, chf.maxRegions, chf, srcReg, overlaps))
return false;
// Monotone partitioning does not generate overlapping regions.
ctx.stopTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Store the result out.
for for i := 0 to chf.spanCount - 1 do
chf.spans[i].reg := srcReg[i];
ctx.stopTimer(RC_TIMER_BUILD_REGIONS);
return true;
end;}
/// @par
///
/// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour.
/// Contours will form simple polygons.
///
/// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be
/// re-assigned to the zero (null) region.
///
/// Watershed partitioning can result in smaller than necessary regions, especially in diagonal corridors.
/// @p mergeRegionArea helps reduce unecessarily small regions.
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// The region data will be available via the rcCompactHeightfield::maxRegions
/// and rcCompactSpan::reg fields.
///
/// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions.
///
/// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig
function rcBuildRegions(ctx: TrcContext; chf: PrcCompactHeightfield;
const borderSize, minRegionArea, mergeRegionArea: Integer): Boolean;
const LOG_NB_STACKS = 3;
const NB_STACKS = 1 shl LOG_NB_STACKS;
const expandIters = 8;
var w,h,i,j,x,y: Integer; buf: PWord; lvlStacks: TArrayOfTrcIntArray;
stack,visited,overlaps: TrcIntArray; srcReg,srcDist,dstReg,dstDist: PWord; regionId,level: Word; bw,bh: Integer; sId: Integer;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_BUILD_REGIONS);
w := chf.width;
h := chf.height;
GetMem(buf, sizeOf(Word)*chf.spanCount*4);
ctx.startTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
SetLength(lvlStacks, NB_STACKS);
for i := 0 to NB_STACKS - 1 do
lvlStacks[i].Create(1024);
stack.Create(1024);
visited.Create(1024);
srcReg := buf;
srcDist := buf + chf.spanCount;
dstReg := buf + chf.spanCount*2;
dstDist := buf + chf.spanCount*3;
FillChar(srcReg[0], sizeof(Word)*chf.spanCount, 0);
FillChar(srcDist[0], sizeof(Word)*chf.spanCount, 0);
regionId := 1;
level := (chf.maxDistance+1) and not 1;
// TODO: Figure better formula, expandIters defines how much the
// watershed 'overflows' and simplifies the regions. Tying it to
// agent radius was usually good indication how greedy it could be.
// const int expandIters := 4 + walkableRadius * 2;
//const int expandIters := 8;
if (borderSize > 0) then
begin
// Make sure border will not overflow.
bw := rcMin(w, borderSize);
bh := rcMin(h, borderSize);
// Paint regions
paintRectRegion(0, bw, 0, h, regionId or RC_BORDER_REG, chf, srcReg); Inc(regionId);
paintRectRegion(w-bw, w, 0, h, regionId or RC_BORDER_REG, chf, srcReg); Inc(regionId);
paintRectRegion(0, w, 0, bh, regionId or RC_BORDER_REG, chf, srcReg); Inc(regionId);
paintRectRegion(0, w, h-bh, h, regionId or RC_BORDER_REG, chf, srcReg); Inc(regionId);
chf.borderSize := borderSize;
end;
sId := -1;
while (level > 0) do
begin
level := IfThen(level >= 2, level-2, 0);
sId := (sId+1) and (NB_STACKS-1);
// ctx.startTimer(RC_TIMER_DIVIDE_TO_LEVELS);
if (sId = 0) then
sortCellsByLevel(level, chf, srcReg, NB_STACKS, lvlStacks, 1)
else
appendStacks(@lvlStacks[sId-1], @lvlStacks[sId], srcReg); // copy left overs from last level
// ctx.stopTimer(RC_TIMER_DIVIDE_TO_LEVELS);
ctx.startTimer(RC_TIMER_BUILD_REGIONS_EXPAND);
// Expand current regions until no empty connected cells found.
if (expandRegions(expandIters, level, chf, srcReg, srcDist, dstReg, dstDist, @lvlStacks[sId], false) <> srcReg) then
begin
rcSwap(Pointer(srcReg), Pointer(dstReg));
rcSwap(Pointer(srcDist), Pointer(dstDist));
end;
ctx.stopTimer(RC_TIMER_BUILD_REGIONS_EXPAND);
ctx.startTimer(RC_TIMER_BUILD_REGIONS_FLOOD);
// Mark new regions with IDs.
for j := 0 to lvlStacks[sId].size div 3 - 1 do
begin
x := lvlStacks[sId][j*3];
y := lvlStacks[sId][j*3+1];
i := lvlStacks[sId][j*3+2];
if (i >= 0) and (srcReg[i] = 0) then
begin
if (floodRegion(x, y, i, level, regionId, chf, srcReg, srcDist, @stack)) then
Inc(regionId);
end;
end;
ctx.stopTimer(RC_TIMER_BUILD_REGIONS_FLOOD);
end;
// Expand current regions until no empty connected cells found.
if (expandRegions(expandIters*8, 0, chf, srcReg, srcDist, dstReg, dstDist, @stack, true) <> srcReg) then
begin
rcSwap(Pointer(srcReg), Pointer(dstReg));
rcSwap(Pointer(srcDist), Pointer(dstDist));
end;
ctx.stopTimer(RC_TIMER_BUILD_REGIONS_WATERSHED);
ctx.startTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Merge regions and filter out smalle regions.
overlaps.Create(0);
chf.maxRegions := regionId;
if (not mergeAndFilterRegions(ctx, minRegionArea, mergeRegionArea, @chf.maxRegions, chf, srcReg, @overlaps)) then
Exit(false);
// If overlapping regions were found during merging, split those regions.
if (overlaps.size > 0) then
begin
ctx.log(RC_LOG_ERROR, Format('rcBuildRegions: %d overlapping regions.', [overlaps.size]));
end;
ctx.stopTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Write the result out.
for i := 0 to chf.spanCount - 1 do
chf.spans[i].reg := srcReg[i];
FreeMem(buf);
// Delphi: Manually release record and buffer it holds within
for i := 0 to NB_STACKS - 1 do
lvlStacks[i].Free;
stack.Free;
visited.Free;
ctx.stopTimer(RC_TIMER_BUILD_REGIONS);
Result := true;
end;
{function rcBuildLayerRegions(ctx: TrcContext; chf: PrcCompactHeightfield;
const borderSize, minRegionArea: Integer): Boolean;
var w,h,i,x,y: Integer; c: PrcCompactCell; s: PrcCompactSpan;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_BUILD_REGIONS);
w := chf.width;
h := chf.height;
unsigned short id := 1;
rcScopedDelete<unsigned short> srcReg := (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
if (!srcReg)
begin
ctx.log(RC_LOG_ERROR, 'rcBuildRegionsMonotone: Out of memory 'src' (%d).', chf.spanCount);
return false;
end;
memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
const int nsweeps := rcMax(chf.width,chf.height);
rcScopedDelete<rcSweepSpan> sweeps := (rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP);
if (!sweeps)
begin
ctx.log(RC_LOG_ERROR, 'rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).', nsweeps);
return false;
end;
// Mark border regions.
if (borderSize > 0)
begin
// Make sure border will not overflow.
const int bw := rcMin(w, borderSize);
const int bh := rcMin(h, borderSize);
// Paint regions
paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++;
paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++;
chf.borderSize := borderSize;
end;
rcIntArray prev(256);
// Sweep one line at a time.
for (int y := borderSize; y < h-borderSize; ++y)
begin
// Collect spans from this row.
prev.resize(id+1);
memset(&prev[0],0,sizeof(int)*id);
unsigned short rid := 1;
for (int x := borderSize; x < w-borderSize; ++x)
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
s := @chf.spans[i];
if (chf.areas[i] = RC_NULL_AREA) continue;
// -x
unsigned short previd := 0;
if (rcGetCon(s, 0) <> RC_NOT_CONNECTED)
begin
const int ax := x + rcGetDirOffsetX(0);
const int ay := y + rcGetDirOffsetY(0);
const int ai := chf.cells[ax+ay*w].index + rcGetCon(s, 0);
if ((srcReg[ai] & RC_BORDER_REG) = 0 and chf.areas[i] = chf.areas[ai])
previd := srcReg[ai];
end;
if (!previd)
begin
previd := rid++;
sweeps[previd].rid := previd;
sweeps[previd].ns := 0;
sweeps[previd].nei := 0;
end;
// -y
if (rcGetCon(s,3) <> RC_NOT_CONNECTED)
begin
const int ax := x + rcGetDirOffsetX(3);
const int ay := y + rcGetDirOffsetY(3);
const int ai := chf.cells[ax+ay*w].index + rcGetCon(s, 3);
if (srcReg[ai] and (srcReg[ai] & RC_BORDER_REG) = 0 and chf.areas[i] = chf.areas[ai])
begin
unsigned short nr := srcReg[ai];
if (!sweeps[previd].nei or sweeps[previd].nei = nr)
begin
sweeps[previd].nei := nr;
sweeps[previd].ns++;
prev[nr]++;
end;
else
begin
sweeps[previd].nei := RC_NULL_NEI;
end;
end;
end;
srcReg[i] := previd;
end;
end;
// Create unique ID.
for i := 1 to rid - 1 do
begin
if (sweeps[i].nei <> RC_NULL_NEI) and (sweeps[i].nei <> 0) and
(prev[sweeps[i].nei] = sweeps[i].ns) then
begin
sweeps[i].id := sweeps[i].nei;
end;
else
begin
sweeps[i].id := id;
Inc(id);
end;
end;
// Remap IDs
for x := borderSize to w-borderSize - 1 do
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
if (srcReg[i] > 0) and (srcReg[i] < rid) then
srcReg[i] := sweeps[srcReg[i]].id;
end;
end;
end;
ctx.startTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Merge monotone regions to layers and remove small regions.
rcIntArray overlaps;
chf.maxRegions := id;
if (not mergeAndFilterLayerRegions(ctx, minRegionArea, chf.maxRegions, chf, srcReg, overlaps)) then
Exit(false);
ctx.stopTimer(RC_TIMER_BUILD_REGIONS_FILTER);
// Store the result out.
for i := 0 to chf.spanCount - 1 do
chf.spans[i].reg := srcReg[i];
ctx.stopTimer(RC_TIMER_BUILD_REGIONS);
Result := true;
end;}
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC InterBase/Firebird Call Interface }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.IBCli;
interface
uses
System.SysUtils,
FireDAC.Stan.Intf;
// ---------------------------------------------------------------------------
// Basic data types
// ---------------------------------------------------------------------------
type
intptr_t = NativeInt;
uintptr_t = NativeUInt;
// IB: api_handle_t=Pointer, FB: api_handle_t=Integer
api_handle_t = Pointer;
ISC_UCHAR = Byte;
ISC_SCHAR = ShortInt;
ISC_SHORT = Smallint;
ISC_USHORT = Word;
ISC_SSHORT = Smallint;
ISC_LONG = Integer;
ISC_ULONG = Cardinal;
ISC_SLONG = Integer;
ISC_INT64 = Int64;
ISC_UINT64 = UInt64;
ISC_BOOLEAN = WordBool;
ISC_STATUS = intptr_t;
TISCStatusVector = array[0..19] of ISC_STATUS;
TISCEventCounts = array[0..19] of ISC_ULONG;
SQUAD = record
high: ISC_SLONG;
low: ISC_ULONG;
end;
GDS_QUAD = record
gds_quad_high: ISC_SLONG;
gds_quad_low: ISC_ULONG;
end;
ISC_QUAD = GDS_QUAD;
vary = record
vary_length: ISC_USHORT;
vary_string: array [0..0] of ISC_UCHAR;
end;
lstring = record
lstr_length: ISC_ULONG;
lstr_allocated: ISC_ULONG;
lstr_address: ^ISC_UCHAR;
end;
PISC_UCHAR = ^ISC_UCHAR;
PISC_SCHAR = ^ISC_SCHAR;
PPISC_SCHAR = ^PISC_SCHAR;
PISC_SHORT = ^ISC_SHORT;
PISC_LONG = ^ISC_LONG;
PISC_ULONG = ^ISC_ULONG;
PISC_BOOLEAN = ^ISC_BOOLEAN;
PISC_STATUS = ^ISC_STATUS;
PGDS_QUAD = ^GDS_QUAD;
PISC_QUAD = ^ISC_QUAD;
Pvary = ^vary;
Plstring = ^lstring;
const
ISC_TRUE = 1;
ISC_FALSE = 0;
DSQL_close = 1;
DSQL_drop = 2;
DSQL_cancel = 4;
DSQL_unprepare = 4;
METADATALENGTH_V2 = 68;
METADATALENGTH_V1 = 32;
const
FB_SQLSTATE_SIZE = 6;
type
FB_SQLSTATE_STRING = array [0 .. FB_SQLSTATE_SIZE-1] of ISC_SCHAR;
// ---------------------------------------------------------------------------
// Time & Date Support
// ---------------------------------------------------------------------------
ISC_DATE = ISC_LONG;
PISC_DATE = ^ISC_DATE;
ISC_TIME = ISC_ULONG;
PISC_TIME = ^ISC_TIME;
PISC_TIMESTAMP = ^ISC_TIMESTAMP;
ISC_TIMESTAMP = record
timestamp_date: ISC_DATE;
timestamp_time: ISC_TIME;
end;
// C Date/Time Structure
TCTimeStructure = record
tm_sec: Integer; // Seconds
tm_min: Integer; // Minutes
tm_hour: Integer; // Hour (0--23)
tm_mday: Integer; // Day of month (1--31)
tm_mon: Integer; // Month (0--11)
tm_year: Integer; // Year (calendar year minus 1900)
tm_wday: Integer; // Weekday (0--6) Sunday = 0)
tm_yday: Integer; // Day of year (0--365)
tm_isdst: Integer; // 0 if daylight savings time is not in effect)
{$IFNDEF MSWINDOWS}
tm_gmtoff: LongInt;// Seconds east of UTC
rm_zone: PByte; // Timezone abbreviation
{$ENDIF}
end;
PCTimeStructure = ^TCTimeStructure;
const
ISC_TIME_SECONDS_PRECISION = 10000;
ISC_TIME_SECONDS_PRECISION_SCALE = -4;
// ---------------------------------------------------------------------------
// Blob and array structures
// ---------------------------------------------------------------------------
type
PISC_ARRAY_BOUND = ^ISC_ARRAY_BOUND;
ISC_ARRAY_BOUND = record
array_bound_lower: ISC_SHORT;
array_bound_upper: ISC_SHORT;
end;
PISC_ARRAY_BOUNDs = ^TISC_ARRAY_BOUNDs;
TISC_ARRAY_BOUNDs = array [0..15] of ISC_ARRAY_BOUND;
PISC_ARRAY_DESC = Pointer;
PISC_BLOB_DESC = Pointer;
PISC_ARRAY_DESC_V1 = ^ISC_ARRAY_DESC_V1;
ISC_ARRAY_DESC_V1 = record
array_desc_dtype: ISC_UCHAR;
array_desc_scale: ISC_SCHAR;
array_desc_length: ISC_USHORT;
array_desc_field_name: array [0..METADATALENGTH_V1 - 1] of ISC_SCHAR;
array_desc_relation_name: array [0..METADATALENGTH_V1 - 1] of ISC_SCHAR;
array_desc_dimensions: ISC_SHORT;
array_desc_flags: ISC_SHORT;
array_desc_bounds: TISC_ARRAY_BOUNDs;
end;
PISC_BLOB_DESC_V1 = ^ISC_BLOB_DESC_V1;
ISC_BLOB_DESC_V1 = record
blob_desc_subtype: ISC_SHORT;
blob_desc_charset: ISC_SHORT;
blob_desc_segment_size: ISC_SHORT;
blob_desc_field_name: array [0..METADATALENGTH_V1 - 1] of ISC_UCHAR;
blob_desc_relation_name: array [0..METADATALENGTH_V1 - 1] of ISC_UCHAR;
end;
PISC_ARRAY_DESC_V2 = ^ISC_ARRAY_DESC_V2;
ISC_ARRAY_DESC_V2 = record
array_desc_version: ISC_SHORT;
array_desc_dtype: ISC_UCHAR;
array_desc_subtype: ISC_UCHAR;
array_desc_scale: ISC_SCHAR;
array_desc_length: ISC_USHORT;
array_desc_field_name: array [0..METADATALENGTH_V2 - 1] of ISC_SCHAR;
array_desc_relation_name: array [0..METADATALENGTH_V2 - 1] of ISC_SCHAR;
array_desc_dimensions: ISC_SHORT;
array_desc_flags: ISC_SHORT;
array_desc_bounds: TISC_ARRAY_BOUNDs;
end;
PISC_BLOB_DESC_V2 = ^ISC_BLOB_DESC_V2;
ISC_BLOB_DESC_V2 = record
blob_desc_version: ISC_SHORT;
blob_desc_subtype: ISC_SHORT;
blob_desc_charset: ISC_SHORT;
blob_desc_segment_size: ISC_SHORT;
blob_desc_field_name: array [0..METADATALENGTH_V2 - 1] of ISC_UCHAR;
blob_desc_relation_name: array [0..METADATALENGTH_V2 - 1] of ISC_UCHAR;
end;
const
ARR_DESC_VERSION2 = 2;
BLB_DESC_VERSION2 = 2;
ARR_DESC_VERSION1 = 1;
BLB_DESC_VERSION1 = 1;
// ---------------------------------------------------------------------------
// Blob control structure
// ---------------------------------------------------------------------------
type
PISC_BLOB_CTL = ^ISC_BLOB_CTL;
TISCStatusFn = function(Action: Word; Control: PISC_BLOB_CTL): ISC_STATUS; cdecl;
ISC_BLOB_CTL = record
ctl_source: TISCStatusFn; // Source filter
ctl_source_handle: PISC_BLOB_CTL; // Argument to pass to source filter
ctl_to_sub_type: Smallint; // Target type
ctl_from_sub_type: Smallint; // Source type
ctl_buffer_length: Word; // Length of buffer
ctl_segment_length: Word; // Length of current segment
ctl_bpb_length: Word; // Length of blob parameter block
ctl_bpb: PISC_SCHAR; // Address of blob parameter block
ctl_buffer: PISC_UCHAR; // Address of segment buffer
ctl_max_segment: ISC_LONG; // Length of longest segment
ctl_number_segments: ISC_LONG; // Total number of segments
ctl_total_length: ISC_LONG; // Total length of blob
ctl_status: PISC_STATUS; // Address of status vector
ctl_data: array [0..7] of NativeInt; // Application specific data
end;
// ---------------------------------------------------------------------------
// Blob stream definitions
// ---------------------------------------------------------------------------
PBSTREAM = ^BSTREAM;
BSTREAM = record
bstr_blob: api_handle_t; // Blob handle
bstr_buffer: PISC_SCHAR; // Address of buffer
bstr_ptr: PISC_SCHAR; // Next character
bstr_length: Smallint; // Length of buffer
bstr_cnt: Smallint; // Characters in buffer
bstr_mode: ISC_SCHAR; // (mode) ? OUTPUT : INPUT
end;
// ---------------------------------------------------------------------------
// CVC: Public blob interface definition held in val.h.
// For some unknown reason, it was only documented in langRef
// and being the structure passed by the engine to UDFs it never
// made its way into this public definitions file.
// Being its original name "blob", I renamed it blobcallback here.
// I did the full definition with the proper parameters instead of
// the weak C declaration with any number and type of parameters.
// Since the first parameter -BLB- is unknown outside the engine,
// it's more accurate to use void* than int* as the blob pointer
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Blob passing structure
// ---------------------------------------------------------------------------
const
// This enum applies to parameter "mode" in blob_lseek
blb_seek_relative = 1;
blb_seek_from_tail = 2;
// This enum applies to the value returned by blob_get_segment
blb_got_fragment = -1;
blb_got_eof = 0;
blb_got_full_segment = 1;
type
TBlobGetSegmentFn = function(hnd: Pointer; buffer: PISC_UCHAR; buf_size: ISC_USHORT;
var result_len: ISC_USHORT): Smallint; stdcall;
TBlobPutSegmentFn = procedure(hnd: Pointer; buffer: PISC_UCHAR; buf_size: ISC_USHORT); stdcall;
TBlobLSeekFn = function(hnd: Pointer; mode: ISC_USHORT; offset: ISC_LONG): ISC_LONG; stdcall;
PBLOBCALLBACK = ^BLOBCALLBACK;
BLOBCALLBACK = record
blob_get_segment: TBlobGetSegmentFn;
blob_handle: Pointer;
blob_number_segments: ISC_LONG;
blob_max_segment: ISC_LONG;
blob_total_length: ISC_LONG;
blob_put_segment: TBlobPutSegmentFn;
blob_lseek: TBlobLSeekFn;
end;
// ---------------------------------------------------------------------------
// CVC: Public descriptor interface held in dsc.h.
// We need it documented to be able to recognize NULL in UDFs.
// Being its original name "dsc", I renamed it paramdsc here.
// Notice that I adjust to the original definition: contrary to
// other cases, the typedef is the same struct not the pointer.
// I included the enumeration of dsc_dtype possible values.
// Ultimately, dsc.h should be part of the public interface.
// ---------------------------------------------------------------------------
// This is the famous internal descriptor that UDFs can use, too.
PPARAMDSC_V1 = ^PARAMDSC_V1;
PARAMDSC_V1 = record
dsc_dtype: ISC_UCHAR;
dsc_scale: ShortInt;
dsc_length: ISC_USHORT;
dsc_sub_type: Smallint;
dsc_flags: ISC_USHORT;
dsc_address: PISC_UCHAR;
end;
PPARAMDSC_V2 = ^PARAMDSC_V2;
PARAMDSC_V2 = record
dsc_version: Byte;
dsc_dtype: Byte;
dsc_scale: ShortInt;
dsc_precision: ShortInt;
dsc_length: Word;
dsc_sub_type: SmallInt;
dsc_flags: Word;
dsc_address: PByte;
end;
// This is a helper struct to work with varchars.
PPARAMVARY = ^PARAMVARY;
PARAMVARY = record
vary_length: ISC_USHORT;
vary_string: array [0..0] of ISC_UCHAR;
end;
// values for dsc_flags
// Note: DSC_null is only reliably set for local variables (blr_variable)
const
DSC_null = 1;
DSC_no_subtype = 2; // dsc has no sub type specified
DSC_nullable = 4; // not stored. instead, is derived
// from metadata primarily to flag
// SQLDA (in DSQL) *)
// ---------------------------------------------------------------------------
// Note that dtype_null actually means that we do not yet know the
// dtype for this descriptor. A nice cleanup item would be to globally
// change it to dtype_unknown. --chrisj 1999-02-17
// ---------------------------------------------------------------------------
dtype_unknown = 0;
dtype_null = 0;
dtype_text = 1;
dtype_cstring = 2;
dtype_varying = 3;
dtype_packed = 6;
dtype_byte = 7;
dtype_short = 8;
dtype_long = 9;
dtype_quad = 10;
dtype_real = 11;
dtype_double = 12;
dtype_d_float = 13;
dtype_sql_date = 14;
dtype_sql_time = 15;
dtype_timestamp = 16;
dtype_blob = 17;
dtype_array = 18;
dtype_int64 = 19;
dtype_dbkey = 20;
// FB 3.0
dtype_boolean = 21;
DTYPE_TYPE_MAX = 22;
// ---------------------------------------------------------------------------
// Dynamic SQL definitions
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Declare the extended SQLDA
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Older and obsolete XSQLVAR, ISC_BLOB_DESC, ISC_ARRAY_DESC strucutres.
// NOTE:These structure will no longer be available in future releases.
// This is kept only for backward compatability.
// Please refrain from using these old structures.
// It is strongly recomended to use the newer SQLDA version
// and related XSQLVAR, ISC_BLOB_DESC, ISC_ARRAY_DESC structures.
// ---------------------------------------------------------------------------
type
PXSQLVAR_V1 = ^XSQLVAR_V1;
XSQLVAR_V1 = record
sqltype: ISC_SHORT; // datatype of field
sqlscale: ISC_SHORT; // scale factor
sqlsubtype: ISC_SHORT; // datatype subtype
sqllen: ISC_SHORT; // length of data area
sqldata: PISC_SCHAR; // address of data
sqlind: PISC_SHORT; // address of indicator variable
sqlname_length: ISC_SHORT; // length of sqlname field
sqlname: array [0..METADATALENGTH_V1 - 1] of ISC_SCHAR; // name of field, name length + space for NULL
relname_length: ISC_SHORT; // length of relation name
relname: array [0..METADATALENGTH_V1 - 1] of ISC_SCHAR; // field's relation name + space for NULL
ownname_length: ISC_SHORT; // length of owner name
ownname: array [0..METADATALENGTH_V1 - 1] of ISC_SCHAR; // relation's owner name + space for NULL
aliasname_length: ISC_SHORT; // length of alias name
aliasname: array [0..METADATALENGTH_V1 - 1] of ISC_SCHAR; // relation's alias name + space for NULL
end;
PXSQLDA_V1 = ^XSQLDA_V1;
XSQLDA_V1 = record
version: ISC_SHORT; // version of this XSQLDA
sqldaid: array [0..7] of ISC_SCHAR; // XSQLDA name field -> RESERVED
sqldabc: ISC_LONG; // length in bytes of SQLDA -> RESERVED
sqln: ISC_SHORT; // number of fields allocated
sqld: ISC_SHORT; // actual number of fields
sqlvar: array [0..0] of XSQLVAR_V1; // first field address
end;
PXSQLVAR_V2 = ^XSQLVAR_V2;
PPXSQLVAR_V2 = ^PXSQLVAR_V2;
XSQLVAR_V2 = record
sqltype: Smallint; // datatype of field
sqlscale: Smallint; // scale factor
sqlprecision: Smallint; // precision : Reserved for future
sqlsubtype: Smallint; // datatype subtype
sqllen: Smallint; // length of data area
sqldata: PByte; // address of data
sqlind: PSmallint; // address of indicator variable
sqlname_length: Smallint; // length of sqlname field
sqlname: array [0..METADATALENGTH_V2 - 1] of ISC_SCHAR; // name of field, name length + space for NULL
relname_length: Smallint; // length of relation name
relname: array [0..METADATALENGTH_V2 - 1] of ISC_SCHAR; // field's relation name + space for NULL
ownname_length: Smallint; // length of owner name
ownname: array [0..METADATALENGTH_V2 - 1] of ISC_SCHAR; // relation's owner name + space for NULL
aliasname_length: Smallint; // length of alias name
aliasname: array [0..METADATALENGTH_V2 - 1] of ISC_SCHAR;// relation's alias name + space for NULL
end;
PXSQLDA_V2 = ^XSQLDA_V2;
XSQLDA_V2 = record
version: Smallint; // version of this XSQLDA
sqldaid: array [0..7] of ISC_SCHAR; // XSQLDA name field -> RESERVED
sqldabc: ISC_LONG; // length in bytes of SQLDA -> RESERVED
sqln: Smallint; // number of fields allocated
sqld: Smallint; // actual number of fields
sqlvar: array [0..0] of XSQLVAR_V2; // first field address
end;
PXSQLDA = Pointer;
PXSQLVar = Pointer;
function XSQLDA_LENGTH_V1(n: Integer): Integer;
function XSQLDA_LENGTH_V2(n: Integer): Integer;
function XSQLVAR_LENGTH(num_rows, num_vars: Integer): Integer;
const
SQLDA_VERSION1 = 1;
SQLDA_VERSION2 = 2; // IB7 and higher
SQL_DIALECT_V5 = 1; // meaning is same as DIALECT_xsqlda.
SQL_DIALECT_V6_TRANSITION = 2; // flagging anything that is delimited
// by double quotes as an error and
// flagging keyword DATE as an error
SQL_DIALECT_V6 = 3; // supports SQL delimited identifier,
// SQLDATE/DATE, TIME, TIMESTAMP,
// CURRENT_DATE, CURRENT_TIME,
// CURRENT_TIMESTAMP, and 64-bit exact
// numeric type
SQLIND_NULL = 1 shl 15; // IB XE7
SQLIND_INSERT = 1 shl 0;
SQLIND_UPDATE = 1 shl 1;
SQLIND_DELETE = 1 shl 2;
SQLIND_CHANGE = 1 shl 3;
SQLIND_TRUNCATE = 1 shl 4; // IB 2017
SQLIND_CHANGE_VIEW = 1 shl 5;
// ---------------------------------------------------------------------------
// InterBase Handle Definitions
// ---------------------------------------------------------------------------
type
isc_att_handle = api_handle_t;
Pisc_att_handle = ^isc_att_handle;
isc_blob_handle = api_handle_t;
Pisc_blob_handle = ^isc_blob_handle;
isc_db_handle = api_handle_t;
Pisc_db_handle = ^isc_db_handle;
isc_form_handle = api_handle_t;
Pisc_form_handle = ^isc_form_handle;
isc_req_handle = api_handle_t;
Pisc_req_handle = ^isc_req_handle;
isc_stmt_handle = api_handle_t;
Pisc_stmt_handle = ^isc_stmt_handle;
isc_svc_handle = api_handle_t;
Pisc_svc_handle = ^isc_svc_handle;
isc_tr_handle = api_handle_t;
Pisc_tr_handle = ^isc_tr_handle;
isc_callback = procedure;
isc_resv_handle = ISC_LONG;
Pisc_resv_handle = ^isc_resv_handle;
// ---------------------------------------------------------------------------
// OSRI database functions
// ---------------------------------------------------------------------------
type
// Parameter for transaction on multiple Database, see
PISCTEB = ^TISCTEB;
TISCTEB = record
Handle: Pisc_db_handle;
Len: Integer;
Address: PByte;
end;
// ---------------------------------------------------------------------------
// Security Functions and structures
// ---------------------------------------------------------------------------
const
sec_uid_spec = $01;
sec_gid_spec = $02;
sec_server_spec = $04;
sec_password_spec = $08;
sec_group_name_spec = $10;
sec_first_name_spec = $20;
sec_middle_name_spec = $40;
sec_last_name_spec = $80;
sec_dba_user_name_spec = $100;
sec_dba_password_spec = $200;
sec_protocol_tcpip = 1;
sec_protocol_netbeui = 2;
sec_protocol_spx = 3;
sec_protocol_local = 4;
type
USER_SEC_DATA = record
sec_flags: Smallint; // which fields are specified
uid: Integer; // the user's id
gid: Integer; // the user's group id
protocol: Integer; // protocol to use for connection
server: PISC_SCHAR; // server to administer
user_name: PISC_SCHAR; // the user's name
password: PISC_SCHAR; // the user's password
group_name: PISC_SCHAR; // the group name
first_name: PISC_SCHAR; // the user's first name
middle_name: PISC_SCHAR; // the user's middle name
last_name: PISC_SCHAR; // the user's last name
dba_user_name: PISC_SCHAR; // the dba user name
dba_password: PISC_SCHAR; // the dba password
end;
PUSER_SEC_DATA = ^USER_SEC_DATA;
// ---------------------------------------------------------------------------
// Service manager functions
// ---------------------------------------------------------------------------
procedure ADD_SPB_LENGTH(var p: PISC_UCHAR; length: Integer);
procedure ADD_SPB_NUMERIC(var p: PISC_UCHAR; data: Integer);
// ---------------------------------------------------------------------------
// Actions to pass to the blob filter (ctl_source)
// ---------------------------------------------------------------------------
const
isc_blob_filter_open = 0;
isc_blob_filter_get_segment = 1;
isc_blob_filter_close = 2;
isc_blob_filter_create = 3;
isc_blob_filter_put_segment = 4;
isc_blob_filter_alloc = 5;
isc_blob_filter_free = 6;
isc_blob_filter_seek = 7;
// ---------------------------------------------------------------------------
// Blr definitions
// ---------------------------------------------------------------------------
blr_text = 14;
blr_text2 = 15;
blr_short = 7;
blr_long = 8;
blr_quad = 9;
blr_int64 = 16;
blr_float = 10;
blr_double = 27;
blr_d_float = 11;
blr_timestamp = 35;
blr_varying = 37;
blr_varying2 = 38;
blr_blob = 261;
blr_cstring = 40;
blr_cstring2 = 41;
blr_blob_id = 45;
blr_sql_date = 12;
blr_sql_time = 13;
// Interbase
blr_boolean_dtype_ib = 17;
// Firebird
blr_blob2 = 17;
blr_domain_name = 18;
blr_domain_name2 = 19;
blr_not_nullable = 20;
blr_column_name = 21;
blr_column_name2 = 22;
blr_bool_fb = 23;
// Historical alias for pre V6 applications
blr_date = blr_timestamp;
blr_inner = 0;
blr_left = 1;
blr_right = 2;
blr_full = 3;
blr_gds_code = 0;
blr_sql_code = 1;
blr_exception = 2;
blr_trigger_code = 3;
blr_default_code = 4;
blr_immediate = 0;
blr_deferred = 1;
blr_restrict = 0;
blr_cascade = 1;
blr_raise = 5;
blr_exception_msg = 6;
blr_exception_params = 7;
blr_version4 = 4;
blr_version5 = 5;
blr_eoc = 76;
blr_end = 255; // note: defined as -1 in gds.h
blr_assignment = 1;
blr_begin = 2;
blr_dcl_variable = 3; // added from gds.h
blr_message = 4;
blr_erase = 5;
blr_fetch = 6;
blr_for = 7;
blr_if = 8;
blr_loop = 9;
blr_modify = 10;
blr_handler = 11;
blr_receive = 12;
blr_select = 13;
blr_send = 14;
blr_store = 15;
blr_truncate = 16;
blr_label = 17;
blr_leave = 18;
blr_store2 = 19;
blr_post = 20;
blr_literal = 21;
blr_dbkey = 22;
blr_field = 23;
blr_fid = 24;
blr_parameter = 25;
blr_variable = 26;
blr_average = 27;
blr_count = 28;
blr_maximum = 29;
blr_minimum = 30;
blr_total = 31;
// count 2
// define blr_count2 32
blr_add = 34;
blr_subtract = 35;
blr_multiply = 36;
blr_divide = 37;
blr_negate = 38;
blr_concatenate = 39;
blr_substring = 40;
blr_parameter2 = 41;
blr_from = 42;
blr_via = 43;
blr_parameter2_old = 44; // Confusion
blr_user_name = 44; // added from gds.h
blr_null = 45;
blr_equiv = 46;
blr_eql = 47;
blr_neq = 48;
blr_gtr = 49;
blr_geq = 50;
blr_lss = 51;
blr_leq = 52;
blr_containing = 53;
blr_matching = 54;
blr_starting = 55;
blr_between = 56;
blr_or = 57;
blr_and = 58;
blr_not = 59;
blr_any = 60;
blr_missing = 61;
blr_unique = 62;
blr_like = 63;
blr_stream = 65; // added from gds.h
blr_set_index = 66; // added from gds.h
blr_rse = 67;
blr_first = 68;
blr_project = 69;
blr_sort = 70;
blr_boolean = 71;
blr_ascending = 72;
blr_descending = 73;
blr_relation = 74;
blr_rid = 75;
blr_union = 76;
blr_map = 77;
blr_group_by = 78;
blr_aggregate = 79;
blr_join_type = 80;
blr_rows = 81;
// sub parameters for blr_rows
blr_ties = 0;
blr_percent = 1;
blr_agg_count = 83;
blr_agg_max = 84;
blr_agg_min = 85;
blr_agg_total = 86;
blr_agg_average = 87;
blr_parameter3 = 88; // same as Rdb definition
blr_run_max = 89;
blr_run_min = 90;
blr_run_total = 91;
blr_run_average = 92;
blr_agg_count2 = 93;
blr_agg_count_distinct = 94;
blr_agg_total_distinct = 95;
blr_agg_average_distinct = 96;
blr_function = 100;
blr_gen_id = 101;
blr_prot_mask = 102;
blr_upcase = 103;
blr_lock_state = 104;
blr_value_if = 105;
blr_matching2 = 106;
blr_index = 107;
blr_ansi_like = 108;
blr_bookmark = 109;
blr_crack = 110;
blr_force_crack = 111;
blr_seek = 112;
blr_find = 113;
blr_scrollable = 109;
// these indicate directions for blr_seek and blr_find
blr_continue = 0;
blr_forward = 1;
blr_backward = 2;
blr_bof_forward = 3;
blr_eof_backward = 4;
blr_lock_relation = 114;
blr_lock_record = 115;
blr_set_bookmark = 116;
blr_get_bookmark = 117;
blr_run_count = 118; // changed from 88 to avoid conflict with blr_parameter3
blr_rs_stream = 119;
blr_exec_proc = 120;
blr_begin_range = 121;
blr_end_range = 122;
blr_delete_range = 123;
blr_procedure = 124;
blr_pid = 125;
blr_exec_pid = 126;
blr_singular = 127;
blr_abort = 128;
blr_block = 129;
blr_error_handler = 130;
blr_cast = 131;
blr_release_lock = 132;
blr_release_locks = 133;
blr_start_savepoint = 134;
blr_end_savepoint = 135;
blr_find_dbkey = 136;
blr_range_relation = 137;
blr_delete_ranges = 138;
blr_pid2 = 132;
blr_procedure2 = 133;
blr_plan = 139; // access plan items
blr_merge = 140;
blr_join = 141;
blr_sequential = 142;
blr_navigational = 143;
blr_indices = 144;
blr_retrieve = 145;
blr_relation2 = 146;
blr_rid2 = 147;
blr_reset_stream = 148;
blr_release_bookmark = 149;
blr_set_generator = 150;
blr_ansi_any = 151; // required for NULL handling
blr_exists = 152; // required for NULL handling
blr_cardinality = 153;
blr_record_version = 154; // get tid of record
blr_stall = 155; // fake server stall
blr_seek_no_warn = 156;
blr_find_dbkey_version = 157; // find dbkey with record version
blr_ansi_all = 158; // required for NULL handling
blr_extract = 159;
// sub parameters for blr_extract
blr_extract_year = 0;
blr_extract_month = 1;
blr_extract_day = 2;
blr_extract_hour = 3;
blr_extract_minute = 4;
blr_extract_second = 5;
blr_extract_weekday = 6;
blr_extract_yearday = 7;
blr_current_date = 160;
blr_current_timestamp = 161;
blr_current_time = 162;
// FB1 specific BLR
blr_current_role = 174;
blr_skip = 175;
// These verbs were added in 7.0 for BOOLEAN dtype support
blr_boolean_true = 174;
blr_boolean_false = 175;
// These verbs were added in 7.1 for SQL savepoint support
blr_start_savepoint2 = 176;
blr_release_savepoint = 177;
blr_rollback_savepoint = 178;
// FB 1.5 specific BLR
blr_exec_sql = 176;
blr_internal_info = 177;
blr_nullsfirst = 178;
blr_writelock = 179;
blr_nullslast = 180;
// This codes reuse BLR code space
blr_post_arg = 163;
blr_exec_into = 164;
blr_user_savepoint = 165;
// FB 2.0 specific BLR
blr_lowcase = 181;
blr_strlen = 182;
blr_strlen_bit = 0;
blr_strlen_char = 1;
blr_strlen_octet = 2;
blr_trim = 183;
blr_trim_both = 0;
blr_trim_leading = 1;
blr_trim_trailing = 2;
blr_trim_spaces = 0;
blr_trim_characters = 1;
blr_dcl_cursor = 166;
blr_cursor_stmt = 167;
blr_current_timestamp2 = 168;
blr_current_time2 = 169;
blr_agg_list = 170;
blr_agg_list_distinct = 171;
blr_modify2 = 172;
// These codes are actions for user-defined savepoints
// FB 1.5 specific
blr_savepoint_set = 0;
blr_savepoint_release = 1;
blr_savepoint_undo = 2;
blr_savepoint_release_single = 3;
// FB 2.0 specific
blr_cursor_open = 0;
blr_cursor_close = 1;
blr_cursor_fetch = 2;
blr_cursor_fetch_scroll = 3;
// scroll options
blr_scroll_forward = 0;
blr_scroll_backward = 1;
blr_scroll_bof = 2;
blr_scroll_eof = 3;
blr_scroll_absolute = 4;
blr_scroll_relative = 5;
// FB 3.0 specific BLR
blr_procedure3 = 192;
blr_exec_proc2 = 193;
blr_function2 = 194;
blr_window = 195;
blr_partition_by = 196;
blr_continue_loop = 197;
blr_procedure4 = 198;
blr_agg_function = 199;
blr_substring_similar = 200;
blr_bool_as_value = 201;
blr_coalesce = 202;
blr_decode = 203;
// ---------------------------------------------------------------------------
// Database parameter block stuff
// ---------------------------------------------------------------------------
isc_dpb_version1 = 1;
isc_dpb_version2 = 2;
isc_dpb_cdd_pathname = 1;
isc_dpb_allocation = 2;
isc_dpb_journal = 3;
isc_dpb_page_size = 4;
isc_dpb_num_buffers = 5;
isc_dpb_buffer_length = 6;
isc_dpb_debug = 7;
isc_dpb_garbage_collect = 8;
isc_dpb_verify = 9;
isc_dpb_sweep = 10;
isc_dpb_enable_journal = 11;
isc_dpb_disable_journal = 12;
isc_dpb_dbkey_scope = 13;
isc_dpb_number_of_users = 14;
isc_dpb_trace = 15;
isc_dpb_no_garbage_collect = 16;
isc_dpb_damaged = 17;
isc_dpb_license = 18;
isc_dpb_sys_user_name = 19;
isc_dpb_encrypt_key = 20;
isc_dpb_activate_shadow = 21;
isc_dpb_sweep_interval = 22;
isc_dpb_delete_shadow = 23;
isc_dpb_force_write = 24;
isc_dpb_begin_log = 25;
isc_dpb_quit_log = 26;
isc_dpb_no_reserve = 27;
isc_dpb_user_name = 28;
isc_dpb_password = 29;
isc_dpb_password_enc = 30;
isc_dpb_sys_user_name_enc = 31;
isc_dpb_interp = 32;
isc_dpb_online_dump = 33;
isc_dpb_old_file_size = 34;
isc_dpb_old_num_files = 35;
isc_dpb_old_file = 36;
isc_dpb_old_start_page = 37;
isc_dpb_old_start_seqno = 38;
isc_dpb_old_start_file = 39;
isc_dpb_drop_walfile = 40;
isc_dpb_old_dump_id = 41;
isc_dpb_wal_backup_dir = 42;
isc_dpb_wal_chkptlen = 43;
isc_dpb_wal_numbufs = 44;
isc_dpb_wal_bufsize = 45;
isc_dpb_wal_grp_cmt_wait = 46;
isc_dpb_lc_messages = 47;
isc_dpb_lc_ctype = 48;
isc_dpb_cache_manager = 49;
isc_dpb_shutdown = 50;
isc_dpb_online = 51;
isc_dpb_shutdown_delay = 52;
isc_dpb_reserved = 53;
isc_dpb_overwrite = 54;
isc_dpb_sec_attach = 55;
isc_dpb_disable_wal = 56;
isc_dpb_connect_timeout = 57;
isc_dpb_dummy_packet_interval = 58;
isc_dpb_gbak_attach = 59;
isc_dpb_sql_role_name = 60;
isc_dpb_set_page_buffers = 61;
isc_dpb_working_directory = 62;
isc_dpb_sql_dialect = 63;
isc_dpb_set_db_readonly = 64;
isc_dpb_set_db_sql_dialect = 65;
isc_dpb_gfix_attach = 66;
isc_dpb_gstat_attach = 67;
// IB65 or YF867
isc_dpb_gbak_ods_version = 68;
isc_dpb_gbak_ods_minor_version = 69;
// YF867
isc_dpb_numeric_scale_reduction = 70;
isc_dpb_sec_flags = 91;
isc_dpb_sec_type = 92;
isc_dpb_sec_principal = 93;
isc_dpb_sec_srv_name = 94;
// IB70
isc_dpb_set_group_commit = 70;
// IB71
isc_dpb_gbak_validate = 71;
// IB75
isc_dpb_client_interbase_var = 72;
isc_dpb_admin_option = 73;
isc_dpb_flush_interval = 74;
// IB2007
isc_dpb_instance_name = 75;
isc_dpb_old_overwrite = 76;
isc_dpb_archive_database = 77;
isc_dpb_archive_journals = 78;
isc_dpb_archive_sweep = 79;
isc_dpb_archive_dumps = 80;
isc_dpb_archive_recover = 81;
isc_dpb_recover_until = 82;
isc_dpb_force = 83;
// IBXE
isc_dpb_preallocate = 84;
isc_dpb_sys_encrypt_password = 85;
// IBXE3
isc_dpb_eua_user_name = 86;
// IBXE7
isc_dpb_transaction = 87; // accepts up to int64 type value
// FB103
isc_dpb_set_db_charset = 68;
// FB20
isc_dpb_gsec_attach = 69;
isc_dpb_address_path = 70;
// FB21
isc_dpb_process_id = 71;
isc_dpb_no_db_triggers = 72;
isc_dpb_trusted_auth = 73;
isc_dpb_process_name = 74;
// FB25
isc_dpb_trusted_role = 75;
isc_dpb_org_filename = 76;
isc_dpb_utf8_filename = 77;
isc_dpb_ext_call_depth = 78;
// FB30
isc_dpb_auth_block = 79;
// FB30x
isc_dpb_client_version = 80;
isc_dpb_remote_protocol = 81;
isc_dpb_host_name = 82;
isc_dpb_os_user = 83;
isc_dpb_specific_auth_data = 84;
isc_dpb_auth_plugin_list = 85;
isc_dpb_auth_plugin_name = 86;
isc_dpb_config = 87;
isc_dpb_nolinger = 88;
isc_dpb_reset_icu = 89;
isc_dpb_map_attach = 90;
isc_dpb_Max_Value_IB650 = 69;
isc_dpb_Max_Value_IB700 = 70;
isc_dpb_Max_Value_IB710 = 71;
isc_dpb_Max_Value_IB750 = 74;
isc_dpb_Max_Value_IB2007 = 83;
isc_dpb_Max_Value_IBXE = 85;
isc_dpb_Max_Value_IBXE3 = 86;
isc_dpb_Max_Value_FB103 = 68;
isc_dpb_Max_Value_FB150 = 68;
isc_dpb_Max_Value_FB200 = 70;
isc_dpb_Max_Value_FB210 = 74;
isc_dpb_Max_Value_FB250 = 78;
isc_dpb_Max_Value_FB300 = 79;
isc_dpb_Max_Value_FB30x = 90;
isc_dpb_Max_Value_YF867 = 70;
// ---------------------------------------------------------------------------
// clumplet tags used inside isc_dpb_address_path
// ---------------------------------------------------------------------------
(* Format of this clumplet is the following:
<address-path-clumplet> ::=
isc_dpb_address_path <byte-clumplet-length> <address-stack>
<address-stack> ::=
<address-descriptor> |
<address-stack> <address-descriptor>
<address-descriptor> ::=
isc_dpb_address <byte-clumplet-length> <address-elements>
<address-elements> ::=
<address-element> |
<address-elements> <address-element>
<address-element> ::=
isc_dpb_addr_protocol <byte-clumplet-length> <protocol-string> |
isc_dpb_addr_endpoint <byte-clumplet-length> <remote-endpoint-string>
<protocol-string> ::=
"TCPv4" |
"TCPv6" |
"XNET" |
"WNET" |
....
<remote-endpoint-string> ::=
<IPv4-address> | // such as "172.20.1.1"
<IPv6-address> | // such as "2001:0:13FF:09FF::1"
<xnet-process-id> | // such as "17864"
...
*)
isc_dpb_address = 1;
isc_dpb_addr_protocol = 1;
isc_dpb_addr_endpoint = 2;
// ---------------------------------------------------------------------------
// isc_dpb_verify specific flags
// ---------------------------------------------------------------------------
isc_dpb_pages = 1;
isc_dpb_records = 2;
isc_dpb_indices = 4;
isc_dpb_transactions = 8;
isc_dpb_no_update = 16;
isc_dpb_repair = 32;
isc_dpb_ignore = 64;
// ---------------------------------------------------------------------------
// isc_dpb_shutdown specific flags
// ---------------------------------------------------------------------------
isc_dpb_shut_cache = $1;
isc_dpb_shut_attachment = $2;
isc_dpb_shut_transaction = $4;
isc_dpb_shut_force = $8;
// FB20
isc_dpb_shut_mode_mask = $70;
isc_dpb_shut_default = $00;
isc_dpb_shut_normal = $10;
isc_dpb_shut_multi = $20;
isc_dpb_shut_single = $30;
isc_dpb_shut_full = $40;
// YF867
// ---------------------------------------------------------------------------
// isc_dpb_sec_flags specific flags
// ---------------------------------------------------------------------------
isc_dpb_sec_delegation = 1;
isc_dpb_sec_mutual_auth = 2;
isc_dpb_sec_replay = 4;
isc_dpb_sec_sequence = 8;
isc_dpb_sec_confidentiality = 16;
isc_dpb_sec_integrity = 32;
isc_dpb_sec_anonymous = 64;
isc_dpb_sec_transport = $08000000; // use transport security if supported by underlying protocol
// ---------------------------------------------------------------------------
// Bit assignments in RDB$SYSTEM_FLAG
// ---------------------------------------------------------------------------
RDB_system = 1;
RDB_id_assigned = 2;
// ---------------------------------------------------------------------------
// Transaction parameter block stuff
// ---------------------------------------------------------------------------
isc_tpb_version1 = 1;
isc_tpb_version3 = 3;
isc_tpb_consistency = 1;
isc_tpb_concurrency = 2;
isc_tpb_shared = 3;
isc_tpb_protected = 4;
isc_tpb_exclusive = 5;
isc_tpb_wait = 6;
isc_tpb_nowait = 7;
isc_tpb_read = 8;
isc_tpb_write = 9;
isc_tpb_lock_read = 10;
isc_tpb_lock_write = 11;
isc_tpb_verb_time = 12;
isc_tpb_commit_time = 13;
isc_tpb_ignore_limbo = 14;
isc_tpb_read_committed = 15;
isc_tpb_autocommit = 16;
isc_tpb_rec_version = 17;
isc_tpb_no_rec_version = 18;
isc_tpb_restart_requests = 19;
isc_tpb_no_auto_undo = 20;
// IB75
isc_tpb_no_savepoint = 21;
// FB20
isc_tpb_lock_timeout = 21;
// IB2017
isc_tpb_exclusivity = 22;
isc_tpb_wait_time = 23;
// ---------------------------------------------------------------------------
// Blob Parameter Block
// ---------------------------------------------------------------------------
isc_bpb_Max_Value = 6;
isc_bpb_version1 = 1;
isc_bpb_source_type = 1;
isc_bpb_target_type = 2;
isc_bpb_type = 3;
isc_bpb_source_interp = 4;
isc_bpb_target_interp = 5;
isc_bpb_filter_parameter = 6;
isc_bpb_target_relation_name = 7;
isc_bpb_target_field_name = 8;
isc_bpb_type_segmented = 0;
isc_bpb_type_stream = 1;
// ---------------------------------------------------------------------------
// Service parameter block stuff
// ---------------------------------------------------------------------------
isc_spb_version1 = 1;
isc_spb_version3 = 3;
isc_spb_current_version = 2;
isc_spb_version = isc_spb_current_version;
isc_spb_user_name = isc_dpb_user_name;
isc_spb_sys_user_name = isc_dpb_sys_user_name;
isc_spb_sys_user_name_enc = isc_dpb_sys_user_name_enc;
isc_spb_password = isc_dpb_password;
isc_spb_password_enc = isc_dpb_password_enc;
isc_spb_connect_timeout = isc_dpb_connect_timeout;
isc_spb_dummy_packet_interval = isc_dpb_dummy_packet_interval;
isc_spb_sql_role_name = isc_dpb_sql_role_name;
isc_spb_instance_name = isc_dpb_instance_name;
isc_spb_command_line = 105;
isc_spb_dbname = 106;
isc_spb_verbose = 107;
isc_spb_options = 108;
// IB75
isc_spb_user_dbname = 109;
isc_spb_auth_dbname = 110;
// IBXE
isc_spb_sys_encrypt_password = isc_dpb_sys_encrypt_password;
// FB20
isc_spb_address_path = 109;
// FB25
isc_spb_process_id = 110;
isc_spb_trusted_auth = 111;
isc_spb_process_name = 112;
isc_spb_trusted_role = 113;
// FB30
isc_spb_verbint = 114;
isc_spb_auth_block = 115;
// FB30x
isc_spb_auth_plugin_name = 116;
isc_spb_auth_plugin_list = 117;
isc_spb_utf8_filename = 118;
isc_spb_client_version = 119;
isc_spb_remote_protocol = 120;
isc_spb_host_name = 121;
isc_spb_os_user = 122;
isc_spb_config = 123;
isc_spb_expected_db = 124;
// ---------------------------------------------------------------------------
// Information call declarations
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Common, structural codes
// ---------------------------------------------------------------------------
isc_info_end = 1;
isc_info_truncated = 2;
isc_info_error = 3;
isc_info_data_not_ready = 4;
isc_info_flag_end = 127;
// ---------------------------------------------------------------------------
// Database information items
// ---------------------------------------------------------------------------
isc_info_db_id = 4;
isc_info_reads = 5;
isc_info_writes = 6;
isc_info_fetches = 7;
isc_info_marks = 8;
isc_info_implementation = 11;
isc_info_isc_version = 12;
isc_info_base_level = 13;
// IB71
isc_info_svr_maj_ver = isc_info_base_level;
isc_info_page_size = 14;
isc_info_num_buffers = 15;
isc_info_limbo = 16;
isc_info_current_memory = 17;
isc_info_max_memory = 18;
isc_info_window_turns = 19;
isc_info_license = 20;
isc_info_allocation = 21;
isc_info_attachment_id = 22;
isc_info_read_seq_count = 23;
isc_info_read_idx_count = 24;
isc_info_insert_count = 25;
isc_info_update_count = 26;
isc_info_delete_count = 27;
isc_info_backout_count = 28;
isc_info_purge_count = 29;
isc_info_expunge_count = 30;
isc_info_sweep_interval = 31;
isc_info_ods_version = 32;
isc_info_ods_minor_version = 33;
isc_info_no_reserve = 34;
isc_info_logfile = 35;
isc_info_cur_logfile_name = 36;
isc_info_cur_log_part_offset = 37;
isc_info_num_wal_buffers = 38;
isc_info_wal_buffer_size = 39;
isc_info_wal_ckpt_length = 40;
isc_info_wal_cur_ckpt_interval = 41;
isc_info_wal_prv_ckpt_fname = 42;
isc_info_wal_prv_ckpt_poffset = 43;
isc_info_wal_recv_ckpt_fname = 44;
isc_info_wal_recv_ckpt_poffset = 45;
isc_info_wal_grpc_wait_usecs = 47;
isc_info_wal_num_io = 48;
isc_info_wal_avg_io_size = 49;
isc_info_wal_num_commits = 50;
isc_info_wal_avg_grpc_size = 51;
isc_info_forced_writes = 52;
isc_info_user_names = 53;
isc_info_page_errors = 54;
isc_info_record_errors = 55;
isc_info_bpage_errors = 56;
isc_info_dpage_errors = 57;
isc_info_ipage_errors = 58;
isc_info_ppage_errors = 59;
isc_info_tpage_errors = 60;
isc_info_set_page_buffers = 61;
isc_info_db_sql_dialect = 62;
isc_info_db_read_only = 63;
isc_info_db_size_in_pages = 64;
// IB70
isc_info_db_reads = 65;
isc_info_db_writes = 66;
isc_info_db_fetches = 67;
isc_info_db_marks = 68;
isc_info_db_group_commit = 69;
// IB71
isc_info_att_charset = 70;
isc_info_svr_min_ver = 71;
// IB75
isc_info_ib_env_var = 72;
isc_info_server_tcp_port = 73;
// IBXE
isc_info_db_preallocate = 74;
isc_info_db_encrypted = 75;
isc_info_db_encryptions = 76;
isc_info_db_sep_external = 77;
// IBXE3
isc_info_db_eua_active = 78;
// FB102 OR YF867
frb_info_att_charset = 101;
isc_info_db_class = 102;
isc_info_firebird_version = 103;
isc_info_oldest_transaction = 104;
isc_info_oldest_active = 105;
isc_info_oldest_snapshot = 106;
isc_info_next_transaction = 107;
isc_info_db_provider = 108;
isc_info_active_transactions = 109;
// FB20
isc_info_active_tran_count = 110;
isc_info_creation_date = 111;
isc_info_db_file_size = 112;
fb_info_page_contents = 113;
// FB30
fb_info_implementation = 114;
fb_info_pages_used = 124;
fb_info_pages_free = 125;
// FB30x
fb_info_crypt_state = 126;
isc_info_version = isc_info_isc_version;
// ---------------------------------------------------------------------------
// Database information return values
// ---------------------------------------------------------------------------
isc_info_db_impl_rdb_vms = 1;
isc_info_db_impl_rdb_eln = 2;
isc_info_db_impl_rdb_eln_dev = 3;
isc_info_db_impl_rdb_vms_y = 4;
isc_info_db_impl_rdb_eln_y = 5;
isc_info_db_impl_jri = 6;
isc_info_db_impl_jsv = 7;
isc_info_db_impl_isc_apl_68K = 25;
isc_info_db_impl_isc_vax_ultr = 26;
isc_info_db_impl_isc_vms = 27;
isc_info_db_impl_isc_sun_68k = 28;
isc_info_db_impl_isc_os2 = 29;
isc_info_db_impl_isc_sun4 = 30;
isc_info_db_impl_isc_hp_ux = 31;
isc_info_db_impl_isc_sun_386i = 32;
isc_info_db_impl_isc_vms_orcl = 33;
isc_info_db_impl_isc_mac_aux = 34;
isc_info_db_impl_isc_rt_aix = 35;
isc_info_db_impl_isc_mips_ult = 36;
isc_info_db_impl_isc_xenix = 37;
isc_info_db_impl_isc_dg = 38;
isc_info_db_impl_isc_hp_mpexl = 39;
isc_info_db_impl_isc_hp_ux68K = 40;
isc_info_db_impl_isc_sgi = 41;
isc_info_db_impl_isc_sco_unix = 42;
isc_info_db_impl_isc_cray = 43;
isc_info_db_impl_isc_imp = 44;
isc_info_db_impl_isc_delta = 45;
isc_info_db_impl_isc_next = 46;
isc_info_db_impl_isc_dos = 47;
// IB65
isc_info_db_impl_isc_winnt = 48;
isc_info_db_impl_isc_epson_IB65 = 49;
// FB102 OR YF867
isc_info_db_impl_m88K = 48;
isc_info_db_impl_unixware = 49;
isc_info_db_impl_isc_winnt_x86 = 50;
isc_info_db_impl_isc_epson_FB102 = 51;
isc_info_db_impl_alpha_osf = 52;
isc_info_db_impl_alpha_vms = 53;
isc_info_db_impl_netware_386 = 54;
isc_info_db_impl_win_only = 55;
isc_info_db_impl_ncr_3000 = 56;
isc_info_db_impl_winnt_ppc = 57;
isc_info_db_impl_dg_x86 = 58;
isc_info_db_impl_sco_ev = 59;
isc_info_db_impl_i386 = 60;
isc_info_db_impl_freebsd = 61;
isc_info_db_impl_netbsd = 62;
isc_info_db_impl_darwin = 63;
// FB102
isc_info_db_impl_sinixz = 64;
// FB15
isc_info_db_impl_linux_sparc = 65;
isc_info_db_impl_linux_amd64 = 66; // FB151
// FB20
isc_info_db_impl_freebsd_amd64 = 67;
isc_info_db_impl_winnt_amd64 = 68;
isc_info_db_impl_linux_ppc = 69;
isc_info_db_impl_darwin_x86 = 70;
isc_info_db_impl_linux_mipsel = 71;
isc_info_db_impl_linux_mips = 72;
isc_info_db_impl_darwin_x64 = 73;
isc_info_db_impl_sun_amd64 = 74;
isc_info_db_impl_linux_arm = 75;
isc_info_db_impl_linux_ia64 = 76;
isc_info_db_impl_darwin_ppc64 = 77;
isc_info_db_impl_linux_s390x = 78;
isc_info_db_impl_linux_s390 = 79;
isc_info_db_impl_linux_sh = 80;
isc_info_db_impl_linux_sheb = 81;
isc_info_db_impl_isc_a = isc_info_db_impl_isc_apl_68K;
isc_info_db_impl_isc_u = isc_info_db_impl_isc_vax_ultr;
isc_info_db_impl_isc_v = isc_info_db_impl_isc_vms;
isc_info_db_impl_isc_s = isc_info_db_impl_isc_sun_68k;
isc_info_db_class_access = 1;
isc_info_db_class_y_valve = 2;
isc_info_db_class_rem_int = 3;
isc_info_db_class_rem_srvr = 4;
isc_info_db_class_pipe_int = 7;
isc_info_db_class_pipe_srvr = 8;
isc_info_db_class_sam_int = 9;
isc_info_db_class_sam_srvr = 10;
isc_info_db_class_gateway = 11;
isc_info_db_class_cache = 12;
// FB 102 OR YF867
isc_info_db_class_classic_access = 13;
isc_info_db_class_server_access = 14;
// FB102 OR YF867
isc_info_db_code_rdb_eln = 1;
isc_info_db_code_rdb_vms = 2;
isc_info_db_code_interbase = 3;
isc_info_db_code_firebird = 4;
// ---------------------------------------------------------------------------
// Request information items
// ---------------------------------------------------------------------------
isc_info_number_messages = 4;
isc_info_max_message = 5;
isc_info_max_send = 6;
isc_info_max_receive = 7;
isc_info_state = 8;
isc_info_message_number = 9;
isc_info_message_size = 10;
isc_info_request_cost = 11;
isc_info_access_path = 12;
isc_info_req_select_count = 13;
isc_info_req_insert_count = 14;
isc_info_req_update_count = 15;
isc_info_req_delete_count = 16;
// ---------------------------------------------------------------------------
// Access path items
// ---------------------------------------------------------------------------
isc_info_rsb_end = 0;
isc_info_rsb_begin = 1;
isc_info_rsb_type = 2;
isc_info_rsb_relation = 3;
isc_info_rsb_plan = 4;
// ---------------------------------------------------------------------------
// Rsb types
// ---------------------------------------------------------------------------
isc_info_rsb_unknown = 1;
isc_info_rsb_indexed = 2;
isc_info_rsb_navigate = 3;
isc_info_rsb_sequential = 4;
isc_info_rsb_cross = 5;
isc_info_rsb_sort = 6;
isc_info_rsb_first = 7;
isc_info_rsb_boolean = 8;
isc_info_rsb_union = 9;
isc_info_rsb_aggregate = 10;
isc_info_rsb_merge = 11;
isc_info_rsb_ext_sequential = 12;
isc_info_rsb_ext_indexed = 13;
isc_info_rsb_ext_dbkey = 14;
isc_info_rsb_left_cross = 15;
isc_info_rsb_select = 16;
isc_info_rsb_sql_join = 17;
isc_info_rsb_simulate = 18;
isc_info_rsb_sim_cross = 19;
isc_info_rsb_once = 20;
isc_info_rsb_procedure = 21;
// FB20
isc_info_rsb_skip = 22;
// FB25
isc_info_rsb_virt_sequential = 23;
isc_info_rsb_recursive = 24;
// FB30
isc_info_rsb_window = 25;
isc_info_rsb_singular = 26;
isc_info_rsb_writelock = 27;
isc_info_rsb_buffer = 28;
isc_info_rsb_hash = 29;
// ---------------------------------------------------------------------------
// Bitmap expressions
// ---------------------------------------------------------------------------
isc_info_rsb_and = 1;
isc_info_rsb_or = 2;
isc_info_rsb_dbkey = 3;
isc_info_rsb_index = 4;
isc_info_req_active = 2;
isc_info_req_inactive = 3;
isc_info_req_send = 4;
isc_info_req_receive = 5;
isc_info_req_select = 6;
isc_info_req_sql_stall = 7;
// ---------------------------------------------------------------------------
// Blob information items
// ---------------------------------------------------------------------------
isc_info_blob_num_segments = 4;
isc_info_blob_max_segment = 5;
isc_info_blob_total_length = 6;
isc_info_blob_type = 7;
// ---------------------------------------------------------------------------
// Transaction information items
// ---------------------------------------------------------------------------
isc_info_tra_id = 4;
// FB
isc_info_tra_oldest_interesting = 5;
isc_info_tra_oldest_snapshot = 6;
isc_info_tra_oldest_active = 7;
isc_info_tra_isolation = 8;
isc_info_tra_access = 9;
isc_info_tra_lock_timeout = 10;
// FB30
fb_info_tra_dbpath = 11;
// ---------------------------------------------------------------------------
// Service action items
// ---------------------------------------------------------------------------
isc_action_svc_backup = 1; // Starts database backup process on the server
isc_action_svc_restore = 2; // Starts database restore process on the server
isc_action_svc_repair = 3; // Starts database repair process on the server
isc_action_svc_add_user = 4; // Adds a new user to the security database
isc_action_svc_delete_user = 5; // Deletes a user record from the security database
isc_action_svc_modify_user = 6; // Modifies a user record in the security database
isc_action_svc_display_user = 7; // Displays a user record from the security database
isc_action_svc_properties = 8; // Sets database properties
isc_action_svc_add_license = 9; // Adds a license to the license file
isc_action_svc_remove_license = 10; // Removes a license from the license file
isc_action_svc_db_stats = 11; // Retrieves database statistics
isc_action_svc_get_ib_log = 12; // Retrieves the InterBase log file from the server
// IB75
isc_action_svc_add_db_alias = 13; // Adds a new database alias
isc_action_svc_delete_db_alias = 14; // Deletes an existing database alias
isc_action_svc_display_db_alias = 15;// Displays an existing database alias
// IBXE3
isc_action_svc_dump = 16; // Starts database dump process on the server
// FB20
isc_action_svc_nbak = 20; // Incremental nbackup
isc_action_svc_nrest = 21;
isc_action_svc_trace_start = 22;
isc_action_svc_trace_stop = 23;
isc_action_svc_trace_suspend = 24;
isc_action_svc_trace_resume = 25;
isc_action_svc_trace_list = 26;
// FB25
isc_action_svc_set_mapping = 27;
isc_action_svc_drop_mapping = 28;
// FB30
isc_action_svc_display_user_adm = 29;
isc_action_svc_validate = 30;
// ---------------------------------------------------------------------------
// Service information items
// ---------------------------------------------------------------------------
// Retrieves the number of attachments and databases
isc_info_svc_svr_db_info = 50;
// Retrieves all license keys and IDs from the license file
isc_info_svc_get_license = 51;
// Retrieves a bitmask representing licensed options on the server
isc_info_svc_get_license_mask = 52;
// Retrieves the parameters and values for IB_CONFIG
isc_info_svc_get_config = 53;
// Retrieves the version of the services manager
isc_info_svc_version = 54;
// Retrieves the version of the InterBase server
isc_info_svc_server_version = 55;
// Retrieves the implementation of the InterBase server
isc_info_svc_implementation = 56;
// Retrieves a bitmask representing the server's capabilities
isc_info_svc_capabilities = 57;
// Retrieves the path to the security database in use by the server
isc_info_svc_user_dbpath = 58;
// Retrieves the setting of $INTERBASE
isc_info_svc_get_env = 59;
// Retrieves the setting of $INTERBASE_LCK
isc_info_svc_get_env_lock = 60;
// Retrieves the setting of $INTERBASE_MSG
isc_info_svc_get_env_msg = 61;
// Retrieves 1 line of service output per call
isc_info_svc_line = 62;
// Retrieves as much of the server output as will fit in the supplied buffer
isc_info_svc_to_eof = 63;
// Sets / signifies a timeout value for reading service information
isc_info_svc_timeout = 64;
// Retrieves the number of users licensed for accessing the server
isc_info_svc_get_licensed_users = 65;
// Retrieve the limbo transactions
isc_info_svc_limbo_trans = 66;
// Checks to see if a service is running on an attachment
isc_info_svc_running = 67;
// Returns the user information from isc_action_svc_display_users
isc_info_svc_get_users = 68;
// Returns the database alias information from isc_action_svc_display_db_alias
isc_info_svc_get_db_alias = 69;
// IBXE3
// Returns embedding application's product identifier, if present in license
isc_info_svc_product_identifier = 70;
// ---------------------------------------------------------------------------
// Parameters for isc_action_{add|delete|modify)_user
// ---------------------------------------------------------------------------
isc_spb_sec_userid = 5;
isc_spb_sec_groupid = 6;
isc_spb_sec_username = 7;
isc_spb_sec_password = 8;
isc_spb_sec_groupname = 9;
isc_spb_sec_firstname = 10;
isc_spb_sec_middlename = 11;
isc_spb_sec_lastname = 12;
// ---------------------------------------------------------------------------
// Parameters for isc_action_{add|delete|display)_db_alias
// ---------------------------------------------------------------------------
isc_spb_sec_db_alias_name = 20;
isc_spb_sec_db_alias_dbpath = 21;
// ---------------------------------------------------------------------------
// Parameters for isc_action_svc_(add|remove)_license,
// isc_info_svc_get_license
// ---------------------------------------------------------------------------
isc_spb_lic_key = 5;
isc_spb_lic_id = 6;
isc_spb_lic_desc = 7;
// ---------------------------------------------------------------------------
// Parameters for isc_action_svc_properties
// ---------------------------------------------------------------------------
isc_spb_prp_page_buffers = 5;
isc_spb_prp_sweep_interval = 6;
isc_spb_prp_shutdown_db = 7;
isc_spb_prp_deny_new_attachments = 9;
isc_spb_prp_deny_new_transactions = 10;
isc_spb_prp_reserve_space = 11;
isc_spb_prp_write_mode = 12;
isc_spb_prp_access_mode = 13;
isc_spb_prp_set_sql_dialect = 14;
// IBXE7
isc_spb_prp_archive_dumps = 42;
isc_spb_prp_archive_sweep = 43;
isc_spb_prp_activate = $0100;
isc_spb_prp_db_online = $0200;
// ---------------------------------------------------------------------------
// Parameters for isc_spb_prp_reserve_space
// ---------------------------------------------------------------------------
isc_spb_prp_res_use_full = 35;
isc_spb_prp_res = 36;
// ---------------------------------------------------------------------------
// Parameters for isc_spb_prp_write_mode
// ---------------------------------------------------------------------------
isc_spb_prp_wm_async = 37;
isc_spb_prp_wm_sync = 38;
isc_spb_prp_wm_direct = 41;
// ---------------------------------------------------------------------------
// Parameters for isc_spb_prp_access_mode
// ---------------------------------------------------------------------------
isc_spb_prp_am_readonly = 39;
isc_spb_prp_am_readwrite = 40;
// ---------------------------------------------------------------------------
// Parameters for isc_action_svc_repair
// ---------------------------------------------------------------------------
isc_spb_rpr_commit_trans = 15;
isc_spb_rpr_rollback_trans = 34;
isc_spb_rpr_recover_two_phase = 17;
isc_spb_tra_id = 18;
isc_spb_single_tra_id = 19;
isc_spb_multi_tra_id = 20;
isc_spb_tra_state = 21;
isc_spb_tra_state_limbo = 22;
isc_spb_tra_state_commit = 23;
isc_spb_tra_state_rollback = 24;
isc_spb_tra_state_unknown = 25;
isc_spb_tra_host_site = 26;
isc_spb_tra_remote_site = 27;
isc_spb_tra_db_path = 28;
isc_spb_tra_advise = 29;
isc_spb_tra_advise_commit = 30;
isc_spb_tra_advise_rollback = 31;
isc_spb_tra_advise_unknown = 33;
isc_spb_rpr_validate_db = $01;
isc_spb_rpr_sweep_db = $02;
isc_spb_rpr_mend_db = $04;
isc_spb_rpr_list_limbo_trans = $08;
isc_spb_rpr_check_db = $10;
isc_spb_rpr_ignore_checksum = $20;
isc_spb_rpr_kill_shadows = $40;
isc_spb_rpr_full = $80;
// ---------------------------------------------------------------------------
// Parameters for isc_action_svc_backup
// ---------------------------------------------------------------------------
isc_spb_bkp_file = 5;
isc_spb_bkp_factor = 6;
isc_spb_bkp_length = 7;
// IB2009
isc_spb_bkp_preallocate = 13;
isc_spb_bkp_encrypt_name = 14;
// FB30
isc_spb_bkp_stat = 15;
// flags
isc_spb_bkp_ignore_checksums = $01;
isc_spb_bkp_ignore_limbo = $02;
isc_spb_bkp_metadata_only = $04;
isc_spb_bkp_no_garbage_collect = $08;
isc_spb_bkp_old_descriptions = $10;
isc_spb_bkp_non_transportable = $20;
isc_spb_bkp_convert = $40;
isc_spb_bkp_expand = $80;
// IBXE7
// standalone options for Archive backup operation
isc_spb_bkp_archive_database = $010000;
isc_spb_bkp_archive_journals = $020000;
// ---------------------------------------------------------------------------
// FB20, Parameters for isc_action_svc_nbak
// ---------------------------------------------------------------------------
isc_spb_nbk_level = 5;
isc_spb_nbk_file = 6;
isc_spb_nbk_direct = 7;
// Flags
isc_spb_nbk_no_triggers = $01;
// ---------------------------------------------------------------------------
// Parameters for isc_action_svc_restore
// ---------------------------------------------------------------------------
isc_spb_res_buffers = 9;
isc_spb_res_page_size = 10;
isc_spb_res_length = 11;
isc_spb_res_access_mode = 12;
// FB25
isc_spb_res_fix_fss_data = 13;
isc_spb_res_fix_fss_metadata = 14;
isc_spb_res_metadata_only = isc_spb_bkp_metadata_only;
// FB30
isc_spb_res_stat = isc_spb_bkp_stat;
// IB2009
isc_spb_res_decrypt_password = 16;
isc_spb_res_eua_user_name = 17;
// IBXE3
isc_spb_res_eua_password = 18;
isc_spb_res_write_mode = 19;
isc_spb_res_starting_trans = 21; // requires 64bit integer value
isc_spb_res_ods_version_major = 22;
// IBXE7
isc_spb_res_archive_recover_until = 23;
isc_spb_res_deactivate_idx = $0100;
isc_spb_res_no_shadow = $0200;
isc_spb_res_no_validity = $0400;
isc_spb_res_one_at_a_time = $0800;
isc_spb_res_replace = $1000;
isc_spb_res_create = $2000;
isc_spb_res_use_all_space = $4000;
// IB71
isc_spb_res_validate = $8000;
// IBXE7
// standalone options for Archive recover operation
isc_spb_res_archive_recover = $040000;
// FB30
isc_spb_val_tab_incl = 1;
isc_spb_val_tab_excl = 2;
isc_spb_val_idx_incl = 3;
isc_spb_val_idx_excl = 4;
isc_spb_val_lock_timeout = 5;
// ---------------------------------------------------------------------------
// Parameters for isc_action_svc_dump
// ---------------------------------------------------------------------------
isc_spb_dmp_file = isc_spb_bkp_file;
isc_spb_dmp_length = isc_spb_bkp_length;
isc_spb_dmp_overwrite = 20;
// IBXE7
// standalone options for dump operation
isc_spb_dmp_create = $080000;
// ---------------------------------------------------------------------------
// Parameters for isc_spb_res_access_mode
// ---------------------------------------------------------------------------
isc_spb_res_am_readonly = isc_spb_prp_am_readonly;
isc_spb_res_am_readwrite = isc_spb_prp_am_readwrite;
// ---------------------------------------------------------------------------
// Parameters for isc_spb_res_write_mode
// ---------------------------------------------------------------------------
isc_spb_res_wm_async = isc_spb_prp_wm_async;
isc_spb_res_wm_sync = isc_spb_prp_wm_sync;
isc_spb_res_wm_direct = isc_spb_prp_wm_direct;
// ---------------------------------------------------------------------------
// Parameters for isc_info_svc_svr_db_info
// ---------------------------------------------------------------------------
isc_spb_num_att = 5;
isc_spb_num_db = 6;
// ---------------------------------------------------------------------------
// Parameters for isc_info_svc_db_stats
// ---------------------------------------------------------------------------
isc_spb_sts_data_pages = $01;
isc_spb_sts_db_log = $02;
isc_spb_sts_hdr_pages = $04;
isc_spb_sts_idx_pages = $08;
isc_spb_sts_sys_relations = $10;
// IB70
isc_spb_sts_record_versions_IB70 = $20;
isc_spb_sts_table_IB70 = $40;
// IB65 OR YF867
isc_spb_sts_record_versions_IB65 = $12;
isc_spb_sts_table_IB65 = $14;
// FB15
isc_spb_sts_record_versions_FB15 = $20;
isc_spb_sts_table_FB15 = $40;
// FB20
isc_spb_sts_nocreation= $80;
// ---------------------------------------------------------------------------
// FB20, Parameters for isc_action_svc_trace_xxxx
// ---------------------------------------------------------------------------
isc_spb_trc_id = 1;
isc_spb_trc_name = 2;
isc_spb_trc_cfg = 3;
// ---------------------------------------------------------------------------
// SQL information items
// ---------------------------------------------------------------------------
isc_info_sql_select = 4;
isc_info_sql_bind = 5;
isc_info_sql_num_variables = 6;
isc_info_sql_describe_vars = 7;
isc_info_sql_describe_end = 8;
isc_info_sql_sqlda_seq = 9;
isc_info_sql_message_seq = 10;
isc_info_sql_type = 11;
isc_info_sql_sub_type = 12;
isc_info_sql_scale = 13;
isc_info_sql_length = 14;
isc_info_sql_null_ind = 15;
isc_info_sql_field = 16;
isc_info_sql_relation = 17;
isc_info_sql_owner = 18;
isc_info_sql_alias = 19;
isc_info_sql_sqlda_start = 20;
isc_info_sql_stmt_type = 21;
isc_info_sql_get_plan = 22;
isc_info_sql_records = 23;
isc_info_sql_batch_fetch = 24;
// FB20
isc_info_sql_relation_alias = 25;
// IB71
isc_info_sql_precision = 25;
// FB30
isc_info_sql_explain_plan = 26;
// ---------------------------------------------------------------------------
// SQL information return values
// ---------------------------------------------------------------------------
isc_info_sql_stmt_select = 1;
isc_info_sql_stmt_insert = 2;
isc_info_sql_stmt_update = 3;
isc_info_sql_stmt_delete = 4;
isc_info_sql_stmt_ddl = 5;
isc_info_sql_stmt_get_segment = 6;
isc_info_sql_stmt_put_segment = 7;
isc_info_sql_stmt_exec_procedure = 8;
isc_info_sql_stmt_start_trans = 9;
isc_info_sql_stmt_commit = 10;
isc_info_sql_stmt_rollback = 11;
isc_info_sql_stmt_select_for_upd = 12;
isc_info_sql_stmt_set_generator = 13;
// FB15
isc_info_sql_stmt_savepoint = 14;
// IBXE3
isc_info_sql_stmt_set_password = 14;
// IBXE7
isc_info_sql_stmt_set_subscription = 15;
// IB2017
isc_info_sql_stmt_truncate = 16;
// ---------------------------------------------------------------------------
// Server configuration key values
// ---------------------------------------------------------------------------
// NOT FOR FB15
ISCCFG_LOCKMEM_KEY = 0;
ISCCFG_LOCKSEM_KEY = 1;
ISCCFG_LOCKSIG_KEY = 2;
ISCCFG_EVNTMEM_KEY = 3;
ISCCFG_DBCACHE_KEY = 4;
ISCCFG_PRIORITY_KEY = 5;
ISCCFG_IPCMAP_KEY = 6;
ISCCFG_MEMMIN_KEY = 7;
ISCCFG_MEMMAX_KEY = 8;
ISCCFG_LOCKORDER_KEY = 9;
ISCCFG_ANYLOCKMEM_KEY = 10;
ISCCFG_ANYLOCKSEM_KEY = 11;
ISCCFG_ANYLOCKSIG_KEY = 12;
ISCCFG_ANYEVNTMEM_KEY = 13;
ISCCFG_LOCKHASH_KEY = 14;
ISCCFG_DEADLOCK_KEY = 15;
ISCCFG_LOCKSPIN_KEY = 16;
ISCCFG_CONN_TIMEOUT_KEY = 17;
ISCCFG_DUMMY_INTRVL_KEY = 18;
ISCCFG_TRACE_POOLS_KEY = 19; // Internal Use only
ISCCFG_REMOTE_BUFFER_KEY = 20;
// FB102
ISCCFG_CPU_AFFINITY_KEY = 21;
// IB65
// ISCCFG_CPU_AFFINITY_KEY = 21;
ISCCFG_SWEEP_QUANTUM_KEY = 22;
ISCCFG_USER_QUANTUM_KEY = 23;
ISCCFG_SLEEP_TIME_KEY = 24;
// IB70
ISCCFG_MAX_THREADS_KEY = 25;
ISCCFG_ADMIN_DB_KEY = 26;
// IB71
ISCCFG_USE_SANCTUARY_KEY = 27;
ISCCFG_ENABLE_HT_KEY = 28;
// IB75
ISCCFG_USE_ROUTER_KEY = 29;
ISCCFG_SORTMEM_BUFFER_SIZE_KEY = 30;
// IBXE3
ISCCFG_SQL_CMP_RECURSION_KEY = 31;
ISCCFG_SOL_BOUND_THREADS_KEY = 32;
ISCCFG_SOL_SYNC_SCOPE_KEY = 33;
ISCCFG_IDX_RECNUM_MARKER_KEY = 34;
ISCCFG_IDX_GARBAGE_COLLECTION_KEY = 35;
ISCCFG_WIN_LOCAL_CONNECT_RETRIES_KEY = 36;
ISCCFG_EXPAND_MOUNTPOINT_KEY = 37;
ISCCFG_LOOPBACK_CONNECTION_KEY = 38;
ISCCFG_THREAD_STACK_SIZE_KEY = 39;
ISCCFG_MAX_DB_VIRMEM_USE_KEY = 40;
ISCCFG_MAX_ASSISTANTS_KEY = 41;
ISCCFG_APPDATA_DIR_KEY = 42;
ISCCFG_MEMORY_RECLAMATION_KEY = 43;
ISCCFG_PAGE_CACHE_EXPANSION_KEY = 44;
ISCCFG_STARTING_TRANSACTION_ID_KEY = 45; // Used internally to test 64-bit transaction ID
ISCCFG_DATABASE_ODS_VERSION_KEY = 46; // Used internally to test creating databases with older ODS versions
// YF867
// ISCCFG_CPU_AFFINITY_KEY = 21;
// ISCCFG_SWEEP_QUANTUM_KEY = 22;
// ISCCFG_USER_QUANTUM_KEY = 23;
ISCCFG_REJECT_AMBIGUITY_KEY = 24;
ISCCFG_SQZ_BLOCK_KEY = 25;
ISCCFG_LOCK_TIMEOUT_KEY = 26;
ISCCFG_YAFFIL_ODS_KEY = 27;
ISCCFG_CONSTRAINT_INDEX_NAME_KEY = 28;
ISCCFG_NO_NAGLE_KEY = 29;
ISCCFG_WIN32_DISABLEFILECACHE_KEY = 30;
ISCCFG_LOCKMEM_RES_KEY = 31;
ISCCFG_FORCERESHEDULE_KEY = 32;
ISCCFG_LEGACY_DIALECT1_KEY = 33;
// ---------------------------------------------------------------------------
// Dynamic Data Definition Language operators
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Version number
// ---------------------------------------------------------------------------
isc_dyn_version_1 = 1;
isc_dyn_eoc = 255;
// ---------------------------------------------------------------------------
// Operations (may be nested)
// ---------------------------------------------------------------------------
isc_dyn_begin = 2;
isc_dyn_end = 3;
isc_dyn_if = 4;
isc_dyn_def_database = 5;
isc_dyn_def_global_fld = 6;
isc_dyn_def_local_fld = 7;
isc_dyn_def_idx = 8;
isc_dyn_def_rel = 9;
isc_dyn_def_sql_fld = 10;
isc_dyn_def_view = 12;
isc_dyn_def_trigger = 15;
isc_dyn_def_security_class = 120;
isc_dyn_def_dimension = 140;
isc_dyn_def_generator = 24;
isc_dyn_def_function = 25;
isc_dyn_def_filter = 26;
isc_dyn_def_function_arg = 27;
isc_dyn_def_shadow = 34;
isc_dyn_def_trigger_msg = 17;
isc_dyn_def_file = 36;
// IB75
isc_dyn_def_user = 225;
isc_dyn_mod_database = 39;
isc_dyn_mod_rel = 11;
isc_dyn_mod_global_fld = 13;
isc_dyn_mod_idx = 102;
isc_dyn_mod_local_fld = 14;
isc_dyn_mod_sql_fld = 216;
isc_dyn_mod_view = 16;
isc_dyn_mod_security_class = 122;
isc_dyn_mod_trigger = 113;
isc_dyn_mod_trigger_msg = 28;
// IB75
isc_dyn_mod_user = 226;
isc_dyn_delete_database = 18;
isc_dyn_delete_rel = 19;
isc_dyn_delete_global_fld = 20;
isc_dyn_delete_local_fld = 21;
isc_dyn_delete_idx = 22;
isc_dyn_delete_security_class = 123;
isc_dyn_delete_dimensions = 143;
isc_dyn_delete_trigger = 23;
isc_dyn_delete_trigger_msg = 29;
isc_dyn_delete_filter = 32;
isc_dyn_delete_function = 33;
// ---------------------------------------------------------------------------
// Generators again
// ---------------------------------------------------------------------------
// FB20 or IB71
isc_dyn_delete_generator = 217;
// FB20
// New for comments in objects.
isc_dyn_mod_function = 224;
isc_dyn_mod_filter = 225;
isc_dyn_mod_generator = 226;
isc_dyn_mod_sql_role = 227;
isc_dyn_mod_charset = 228;
isc_dyn_mod_collation = 229;
isc_dyn_mod_prc_parameter = 230;
// ---------------------------------------------------------------------------
// collation values
// ---------------------------------------------------------------------------
// FB20
isc_dyn_def_collation = 231;
isc_dyn_coll_for_charset = 232;
isc_dyn_coll_from = 233;
isc_dyn_coll_attribute = 234;
isc_dyn_coll_specific_attributes_charset = 235;
isc_dyn_coll_specific_attributes = 236;
isc_dyn_del_collation = 237;
isc_dyn_delete_shadow = 35;
// IB75
isc_dyn_delete_user = 227;
isc_dyn_grant = 30;
isc_dyn_revoke = 31;
isc_dyn_def_primary_key = 37;
isc_dyn_def_foreign_key = 38;
isc_dyn_def_unique = 40;
isc_dyn_def_procedure = 164;
isc_dyn_delete_procedure = 165;
isc_dyn_def_parameter = 135;
isc_dyn_delete_parameter = 136;
isc_dyn_mod_procedure = 175;
// not for FB20
// deprecated
isc_dyn_def_log_file = 176;
isc_dyn_def_cache_file = 180;
isc_dyn_def_exception = 181;
isc_dyn_mod_exception = 182;
isc_dyn_del_exception = 183;
// not for FB20
// deprecated
isc_dyn_drop_log = 194;
isc_dyn_drop_cache = 195;
isc_dyn_def_default_log = 202;
// FB20
isc_dyn_def_difference = 220;
isc_dyn_drop_difference = 221;
isc_dyn_begin_backup = 222;
isc_dyn_end_backup = 223;
// ---------------------------------------------------------------------------
// View specific stuff
// ---------------------------------------------------------------------------
isc_dyn_view_blr = 43;
isc_dyn_view_source = 44;
isc_dyn_view_relation = 45;
isc_dyn_view_context = 46;
isc_dyn_view_context_name = 47;
// ---------------------------------------------------------------------------
// Generic attributes
// ---------------------------------------------------------------------------
isc_dyn_rel_name = 50;
isc_dyn_fld_name = 51;
isc_dyn_new_fld_name = 215;
isc_dyn_idx_name = 52;
isc_dyn_description = 53;
isc_dyn_security_class = 54;
isc_dyn_system_flag = 55;
isc_dyn_update_flag = 56;
isc_dyn_prc_name = 166;
isc_dyn_prm_name = 137;
isc_dyn_sql_object = 196;
isc_dyn_fld_character_set_name = 174;
// IB75
isc_dyn_restrict_or_cascade = 220;
// ---------------------------------------------------------------------------
// Relation specific attributes
// ---------------------------------------------------------------------------
isc_dyn_rel_dbkey_length = 61;
isc_dyn_rel_store_trig = 62;
isc_dyn_rel_modify_trig = 63;
isc_dyn_rel_erase_trig = 64;
isc_dyn_rel_store_trig_source = 65;
isc_dyn_rel_modify_trig_source = 66;
isc_dyn_rel_erase_trig_source = 67;
isc_dyn_rel_ext_file = 68;
isc_dyn_rel_sql_protection = 69;
isc_dyn_rel_constraint = 162;
isc_dyn_delete_rel_constraint = 163;
// IB75
isc_dyn_rel_sql_scope = 218;
isc_dyn_rel_sql_on_commit = 219;
// ---------------------------------------------------------------------------
// Global field specific attributes
// ---------------------------------------------------------------------------
isc_dyn_fld_type = 70;
isc_dyn_fld_length = 71;
isc_dyn_fld_scale = 72;
isc_dyn_fld_sub_type = 73;
isc_dyn_fld_segment_length = 74;
isc_dyn_fld_query_header = 75;
isc_dyn_fld_edit_string = 76;
isc_dyn_fld_validation_blr = 77;
isc_dyn_fld_validation_source = 78;
isc_dyn_fld_computed_blr = 79;
isc_dyn_fld_computed_source = 80;
isc_dyn_fld_missing_value = 81;
isc_dyn_fld_default_value = 82;
isc_dyn_fld_query_name = 83;
isc_dyn_fld_dimensions = 84;
isc_dyn_fld_not_null = 85;
isc_dyn_fld_precision = 86;
isc_dyn_fld_char_length = 172;
isc_dyn_fld_collation = 173;
isc_dyn_fld_default_source = 193;
isc_dyn_del_default = 197;
isc_dyn_del_validation = 198;
isc_dyn_single_validation = 199;
isc_dyn_fld_character_set = 203;
// ---------------------------------------------------------------------------
// Local field specific attributes
// ---------------------------------------------------------------------------
isc_dyn_fld_source = 90;
isc_dyn_fld_base_fld = 91;
isc_dyn_fld_position = 92;
isc_dyn_fld_update_flag = 93;
// ---------------------------------------------------------------------------
// Index specific attributes
// ---------------------------------------------------------------------------
isc_dyn_idx_unique = 100;
isc_dyn_idx_inactive = 101;
isc_dyn_idx_type = 103;
isc_dyn_idx_foreign_key = 104;
isc_dyn_idx_ref_column = 105;
isc_dyn_idx_statistic = 204;
// ---------------------------------------------------------------------------
// Trigger specific attributes
// ---------------------------------------------------------------------------
isc_dyn_trg_type = 110;
isc_dyn_trg_blr = 111;
isc_dyn_trg_source = 112;
isc_dyn_trg_name = 114;
isc_dyn_trg_sequence = 115;
isc_dyn_trg_inactive = 116;
isc_dyn_trg_msg_number = 117;
isc_dyn_trg_msg = 118;
// ---------------------------------------------------------------------------
// Security Class specific attributes
// ---------------------------------------------------------------------------
isc_dyn_scl_acl = 121;
isc_dyn_grant_user = 130;
isc_dyn_grant_proc = 186;
isc_dyn_grant_trig = 187;
isc_dyn_grant_view = 188;
isc_dyn_grant_options = 132;
isc_dyn_grant_user_group = 205;
// FB102 OR YF867
isc_dyn_grant_role = 218;
isc_dyn_grant_user_explicit = 219;
// ---------------------------------------------------------------------------
// Dimension specific information
// ---------------------------------------------------------------------------
isc_dyn_dim_lower = 141;
isc_dyn_dim_upper = 142;
// ---------------------------------------------------------------------------
// File specific attributes
// ---------------------------------------------------------------------------
isc_dyn_file_name = 125;
isc_dyn_file_start = 126;
isc_dyn_file_length = 127;
isc_dyn_shadow_number = 128;
isc_dyn_shadow_man_auto = 129;
isc_dyn_shadow_conditional = 130;
// ---------------------------------------------------------------------------
// Log file specific attributes
// ---------------------------------------------------------------------------
// not for FB20
// deprecated
isc_dyn_log_file_sequence = 177;
isc_dyn_log_file_partitions = 178;
isc_dyn_log_file_serial = 179;
isc_dyn_log_file_overflow = 200;
isc_dyn_log_file_raw = 201;
// ---------------------------------------------------------------------------
// Log specific attributes
// ---------------------------------------------------------------------------
// not for FB20
// deprecated
isc_dyn_log_group_commit_wait = 189;
isc_dyn_log_buffer_size = 190;
isc_dyn_log_check_point_length = 191;
isc_dyn_log_num_of_buffers = 192;
// ---------------------------------------------------------------------------
// Function specific attributes
// ---------------------------------------------------------------------------
isc_dyn_function_name = 145;
isc_dyn_function_type = 146;
isc_dyn_func_module_name = 147;
isc_dyn_func_entry_point = 148;
isc_dyn_func_return_argument = 149;
isc_dyn_func_arg_position = 150;
isc_dyn_func_mechanism = 151;
isc_dyn_filter_in_subtype = 152;
isc_dyn_filter_out_subtype = 153;
isc_dyn_description2 = 154;
isc_dyn_fld_computed_source2 = 155;
isc_dyn_fld_edit_string2 = 156;
isc_dyn_fld_query_header2 = 157;
isc_dyn_fld_validation_source2 = 158;
isc_dyn_trg_msg2 = 159;
isc_dyn_trg_source2 = 160;
isc_dyn_view_source2 = 161;
isc_dyn_xcp_msg2 = 184;
// ---------------------------------------------------------------------------
// Generator specific attributes
// ---------------------------------------------------------------------------
isc_dyn_generator_name = 95;
isc_dyn_generator_id = 96;
// ---------------------------------------------------------------------------
// Procedure specific attributes
// ---------------------------------------------------------------------------
isc_dyn_prc_inputs = 167;
isc_dyn_prc_outputs = 168;
isc_dyn_prc_source = 169;
isc_dyn_prc_blr = 170;
isc_dyn_prc_source2 = 171;
// ---------------------------------------------------------------------------
// Parameter specific attributes
// ---------------------------------------------------------------------------
isc_dyn_prm_number = 138;
isc_dyn_prm_type = 139;
// ---------------------------------------------------------------------------
// Relation specific attributes
// ---------------------------------------------------------------------------
isc_dyn_xcp_msg = 185;
// ---------------------------------------------------------------------------
// Cascading referential integrity values
// ---------------------------------------------------------------------------
isc_dyn_foreign_key_update = 205;
isc_dyn_foreign_key_delete = 206;
isc_dyn_foreign_key_cascade = 207;
isc_dyn_foreign_key_default = 208;
isc_dyn_foreign_key_null = 209;
isc_dyn_foreign_key_none = 210;
// ---------------------------------------------------------------------------
// SQL role values
// ---------------------------------------------------------------------------
isc_dyn_def_sql_role = 211;
isc_dyn_sql_role_name = 212;
isc_dyn_grant_admin_options = 213;
isc_dyn_del_sql_role = 214;
// 215 & 216 are used some lines above.
// ---------------------------------------------------------------------------
// Generators again
// ---------------------------------------------------------------------------
// FB15 OR YF867
gds_dyn_delete_generator = 217;
// ---------------------------------------------------------------------------
// ADMIN OPTION values
// ---------------------------------------------------------------------------
// IB75
isc_dyn_add_admin = 221;
isc_dyn_drop_admin = 222;
isc_dyn_admin_active = 223;
isc_dyn_admin_inactive = 224;
// ---------------------------------------------------------------------------
// User specific attributes
// ---------------------------------------------------------------------------
// IB75
isc_dyn_user_sys_name = 11;
isc_dyn_user_grp_name = 12;
isc_dyn_user_uid = 13;
isc_dyn_user_gid = 14;
isc_dyn_user_password = 15;
isc_dyn_user_active = 16;
isc_dyn_user_inactive = 17;
isc_dyn_user_description = 18;
isc_dyn_user_first_name = 19;
isc_dyn_user_middle_name = 20;
isc_dyn_user_last_name = 21;
isc_dyn_user_default_role = 22;
// ---------------------------------------------------------------------------
// Database specific attributes
// ---------------------------------------------------------------------------
// IB75
isc_dyn_db_page_cache = 41;
isc_dyn_db_proc_cache = 42;
isc_dyn_db_rel_cache = 43;
isc_dyn_db_trig_cache = 44;
isc_dyn_db_flush_int = 45;
isc_dyn_db_linger_int = 46;
isc_dyn_db_reclaim_int = 47;
isc_dyn_db_sweep_int = 48;
isc_dyn_db_group_commit = 49;
// ---------------------------------------------------------------------------
// Last $dyn value assigned
// ---------------------------------------------------------------------------
isc_dyn_last_dyn_value_FB102 = 219;
isc_dyn_last_dyn_value_FB103 = 219;
isc_dyn_last_dyn_value_FB150 = 219;
isc_dyn_last_dyn_value_FB200 = 223;
isc_dyn_last_dyn_value_IB650 = 216;
isc_dyn_last_dyn_value_IB710 = 217;
isc_dyn_last_dyn_value_IB750 = 227;
// ---------------------------------------------------------------------------
// Array slice description language (SDL)
// ---------------------------------------------------------------------------
isc_sdl_version1 = 1;
isc_sdl_eoc = 255;
isc_sdl_relation = 2;
isc_sdl_rid = 3;
isc_sdl_field = 4;
isc_sdl_fid = 5;
isc_sdl_struct = 6;
isc_sdl_variable = 7;
isc_sdl_scalar = 8;
isc_sdl_tiny_integer = 9;
isc_sdl_short_integer = 10;
isc_sdl_long_integer = 11;
isc_sdl_literal = 12;
isc_sdl_add = 13;
isc_sdl_subtract = 14;
isc_sdl_multiply = 15;
isc_sdl_divide = 16;
isc_sdl_negate = 17;
isc_sdl_eql = 18;
isc_sdl_neq = 19;
isc_sdl_gtr = 20;
isc_sdl_geq = 21;
isc_sdl_lss = 22;
isc_sdl_leq = 23;
isc_sdl_and = 24;
isc_sdl_or = 25;
isc_sdl_not = 26;
isc_sdl_while = 27;
isc_sdl_assignment = 28;
isc_sdl_label = 29;
isc_sdl_leave = 30;
isc_sdl_begin = 31;
isc_sdl_end = 32;
isc_sdl_do3 = 33;
isc_sdl_do2 = 34;
isc_sdl_do1 = 35;
isc_sdl_element = 36;
// ---------------------------------------------------------------------------
// International text interpretation values
// ---------------------------------------------------------------------------
isc_interp_eng_ascii = 0;
isc_interp_jpn_sjis = 5;
isc_interp_jpn_euc = 6;
// ---------------------------------------------------------------------------
// SQL definitions
// ---------------------------------------------------------------------------
SQL_TEXT = 452; // Array of char
SQL_VARYING = 448;
SQL_SHORT = 500;
SQL_LONG = 496;
SQL_INT64 = 580;
SQL_FLOAT = 482;
SQL_DOUBLE = 480;
SQL_D_FLOAT = 530;
SQL_TYPE_TIME = 560;
SQL_TYPE_DATE = 570;
SQL_TIMESTAMP = 510;
SQL_BLOB = 520;
SQL_ARRAY = 540;
SQL_QUAD = 550;
// IB7
SQL_BOOLEAN_IB = 590;
// FB25
SQL_NULL = 32766;
// FB30
SQL_BOOLEAN_FB = 32764;
// Historical alias for pre V6 applications
SQL_DATE = SQL_TIMESTAMP;
// ---------------------------------------------------------------------------
// Blob Subtypes
// ---------------------------------------------------------------------------
// types less than zero are reserved for customer use
isc_blob_untyped = 0;
// internal subtypes
isc_blob_text = 1;
isc_blob_blr = 2;
isc_blob_acl = 3;
isc_blob_ranges = 4;
isc_blob_summary = 5;
isc_blob_format = 6;
isc_blob_tra = 7;
isc_blob_extfile = 8;
// FB20
isc_blob_max_predefined_subtype = 9;
// the range 20-30 is reserved for dBASE and Paradox types
isc_blob_formatted_memo = 20;
isc_blob_paradox_ole = 21;
isc_blob_graphic = 22;
isc_blob_dbase_ole = 23;
isc_blob_typed_binary = 24;
// ---------------------------------------------------------------------------
// FB 2.5
// ---------------------------------------------------------------------------
// fb_shutdown reasons
fb_shutrsn_svc_stopped = -1;
fb_shutrsn_no_connection = -2;
fb_shutrsn_app_stopped = -3;
fb_shutrsn_device_removed = -4;
fb_shutrsn_signal = -5;
fb_shutrsn_services = -6;
fb_shutrsn_exit_called = -7;
type
FB_SHUTDOWN_CALLBACK_FUNC = function (reason: Integer; mask: Integer;
arg: Pointer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
const
// fb_cancel_operation options
fb_cancel_disable = 1;
fb_cancel_enable = 2;
fb_cancel_raise = 3;
fb_cancel_abort = 4;
// ---------------------------------------------------------------------------
// ISC Error Codes
// ---------------------------------------------------------------------------
const
ISC_MASK = $14000000; // Defines the code as a valid ISC code
FAC_MASK = $00FF0000; // Specifies the facility where the code is located
CODE_MASK = $0000FFFF; // Specifies the code in the message file
CLASS_MASK = $F0000000; // Defines the code as warning, error, info, or other
// Note: Perhaps a debug level could be interesting !!!
CLASS_ERROR = 0; // Code represents an error
CLASS_WARNING = 1; // Code represents a warning
CLASS_INFO = 2; // Code represents an information msg
FAC_JRD = 0; // In Use
FAC_QLI = 1;
FAC_GDEF = 2;
FAC_GFIX = 3; // In Use
FAC_GPRE = 4;
FAC_GLTJ = 5;
FAC_GRST = 6;
FAC_DSQL = 7; // In Use
FAC_DYN = 8; // In Use
FAC_FRED = 9;
FAC_INSTALL = 10;
FAC_TEST = 11;
FAC_GBAK = 12; // In Use
FAC_SQLERR = 13;
FAC_SQLWARN = 14;
FAC_JRD_BUGCHK = 15;
FAC_GJRN = 16;
FAC_ISQL = 17;
FAC_GSEC = 18; // In Use
FAC_LICENSE = 19; // In Use
FAC_DOS = 20;
FAC_GSTAT = 21; // In Use
const
isc_facility = 20;
isc_base = 335544320;
isc_factor = 1;
isc_arg_end = 0; // end of argument list
isc_arg_gds = 1; // generic DSRI status value
isc_arg_string = 2; // string argument
isc_arg_cstring = 3; // count & string argument
isc_arg_number = 4; // numeric argument (long)
isc_arg_interpreted = 5; // interpreted status code (string)
isc_arg_vms = 6; // VAX/VMS status code (long)
isc_arg_unix = 7; // UNIX error code
isc_arg_domain = 8; // Apollo/Domain error code
isc_arg_dos = 9; // MSDOS/OS2 error code
isc_arg_mpexl = 10; // HP MPE/XL error code
isc_arg_mpexl_ipc = 11; // HP MPE/XL IPC error code
isc_arg_next_mach = 15; // NeXT/Mach error code
isc_arg_netware = 16; // NetWare error code
isc_arg_win32 = 17; // Win32 error code
isc_arg_warning = 18; // warning argument
isc_arg_sql = 19;
isc_arith_except = 335544321;
isc_bad_dbkey = 335544322;
isc_bad_db_format = 335544323;
isc_bad_db_handle = 335544324;
isc_bad_dpb_content = 335544325;
isc_bad_dpb_form = 335544326;
isc_bad_req_handle = 335544327;
isc_bad_segstr_handle = 335544328;
isc_bad_segstr_id = 335544329;
isc_bad_tpb_content = 335544330;
isc_bad_tpb_form = 335544331;
isc_bad_trans_handle = 335544332;
isc_bug_check = 335544333;
isc_convert_error = 335544334;
isc_db_corrupt = 335544335;
isc_deadlock = 335544336;
isc_excess_trans = 335544337;
isc_from_no_match = 335544338;
isc_infinap = 335544339;
isc_infona = 335544340;
isc_infunk = 335544341;
isc_integ_fail = 335544342;
isc_invalid_blr = 335544343;
isc_io_error = 335544344;
isc_lock_conflict = 335544345;
isc_metadata_corrupt = 335544346;
isc_not_valid = 335544347;
isc_no_cur_rec = 335544348;
isc_no_dup = 335544349;
isc_no_finish = 335544350;
isc_no_meta_update = 335544351;
isc_no_priv = 335544352;
isc_no_recon = 335544353;
isc_no_record = 335544354;
isc_no_segstr_close = 335544355;
isc_obsolete_metadata = 335544356;
isc_open_trans = 335544357;
isc_port_len = 335544358;
isc_read_only_field = 335544359;
isc_read_only_rel = 335544360;
isc_read_only_trans = 335544361;
isc_read_only_view = 335544362;
isc_req_no_trans = 335544363;
isc_req_sync = 335544364;
isc_req_wrong_db = 335544365;
isc_segment = 335544366;
isc_segstr_eof = 335544367;
isc_segstr_no_op = 335544368;
isc_segstr_no_read = 335544369;
isc_segstr_no_trans = 335544370;
isc_segstr_no_write = 335544371;
isc_segstr_wrong_db = 335544372;
isc_sys_request = 335544373;
isc_stream_eof = 335544374;
isc_unavailable = 335544375;
isc_unres_rel = 335544376;
isc_uns_ext = 335544377;
isc_wish_list = 335544378;
isc_wrong_ods = 335544379;
isc_wronumarg = 335544380;
isc_imp_exc = 335544381;
isc_random = 335544382;
isc_fatal_conflict = 335544383;
isc_badblk = 335544384;
isc_invpoolcl = 335544385;
isc_nopoolids = 335544386;
isc_relbadblk = 335544387;
isc_blktoobig = 335544388;
isc_bufexh = 335544389;
isc_syntaxerr = 335544390;
isc_bufinuse = 335544391;
isc_bdbincon = 335544392;
isc_reqinuse = 335544393;
isc_badodsver = 335544394;
isc_relnotdef = 335544395;
isc_fldnotdef = 335544396;
isc_dirtypage = 335544397;
isc_waifortra = 335544398;
isc_doubleloc = 335544399;
isc_nodnotfnd = 335544400;
isc_dupnodfnd = 335544401;
isc_locnotmar = 335544402;
isc_badpagtyp = 335544403;
isc_corrupt = 335544404;
isc_badpage = 335544405;
isc_badindex = 335544406;
isc_dbbnotzer = 335544407;
isc_tranotzer = 335544408;
isc_trareqmis = 335544409;
isc_badhndcnt = 335544410;
isc_wrotpbver = 335544411;
isc_wroblrver = 335544412;
isc_wrodpbver = 335544413;
isc_blobnotsup = 335544414;
isc_badrelation = 335544415;
isc_nodetach = 335544416;
isc_notremote = 335544417;
isc_trainlim = 335544418;
isc_notinlim = 335544419;
isc_traoutsta = 335544420;
isc_connect_reject = 335544421;
isc_dbfile = 335544422;
isc_orphan = 335544423;
isc_no_lock_mgr = 335544424;
isc_ctxinuse = 335544425;
isc_ctxnotdef = 335544426;
isc_datnotsup = 335544427;
isc_badmsgnum = 335544428;
isc_badparnum = 335544429;
isc_virmemexh = 335544430;
isc_blocking_signal = 335544431;
isc_lockmanerr = 335544432;
isc_journerr = 335544433;
isc_keytoobig = 335544434;
isc_nullsegkey = 335544435;
isc_sqlerr = 335544436;
isc_wrodynver = 335544437;
isc_funnotdef = 335544438;
isc_funmismat = 335544439;
isc_bad_msg_vec = 335544440;
isc_bad_detach = 335544441;
isc_noargacc_read = 335544442;
isc_noargacc_write = 335544443;
isc_read_only = 335544444;
isc_ext_err = 335544445;
isc_non_updatable = 335544446;
isc_no_rollback = 335544447;
isc_bad_sec_info = 335544448;
isc_invalid_sec_info = 335544449;
isc_misc_interpreted = 335544450;
isc_update_conflict = 335544451;
isc_unlicensed = 335544452;
isc_obj_in_use = 335544453;
isc_nofilter = 335544454;
isc_shadow_accessed = 335544455;
isc_invalid_sdl = 335544456;
isc_out_of_bounds = 335544457;
isc_invalid_dimension = 335544458;
isc_rec_in_limbo = 335544459;
isc_shadow_missing = 335544460;
isc_cant_validate = 335544461;
isc_cant_start_journal = 335544462;
isc_gennotdef = 335544463;
isc_cant_start_logging = 335544464;
isc_bad_segstr_type = 335544465;
isc_foreign_key = 335544466;
isc_high_minor = 335544467;
isc_tra_state = 335544468;
isc_trans_invalid = 335544469;
isc_buf_invalid = 335544470;
isc_indexnotdefined = 335544471;
isc_login = 335544472;
isc_invalid_bookmark = 335544473;
isc_bad_lock_level = 335544474;
isc_relation_lock = 335544475;
isc_record_lock = 335544476;
isc_max_idx = 335544477;
isc_jrn_enable = 335544478;
isc_old_failure = 335544479;
isc_old_in_progress = 335544480;
isc_old_no_space = 335544481;
isc_no_wal_no_jrn = 335544482;
isc_num_old_files = 335544483;
isc_wal_file_open = 335544484;
isc_bad_stmt_handle = 335544485;
isc_wal_failure = 335544486;
isc_walw_err = 335544487;
isc_logh_small = 335544488;
isc_logh_inv_version = 335544489;
isc_logh_open_flag = 335544490;
isc_logh_open_flag2 = 335544491;
isc_logh_diff_dbname = 335544492;
isc_logf_unexpected_eof = 335544493;
isc_logr_incomplete = 335544494;
isc_logr_header_small = 335544495;
isc_logb_small = 335544496;
isc_wal_illegal_attach = 335544497;
isc_wal_invalid_wpb = 335544498;
isc_wal_err_rollover = 335544499;
isc_no_wal = 335544500;
isc_drop_wal = 335544501;
isc_stream_not_defined = 335544502;
isc_wal_subsys_error = 335544503;
isc_wal_subsys_corrupt = 335544504;
isc_no_archive = 335544505;
isc_shutinprog = 335544506;
isc_range_in_use = 335544507;
isc_range_not_found = 335544508;
isc_charset_not_found = 335544509;
isc_lock_timeout = 335544510;
isc_prcnotdef = 335544511;
isc_prcmismat = 335544512;
isc_wal_bugcheck = 335544513;
isc_wal_cant_expand = 335544514;
isc_codnotdef = 335544515;
isc_xcpnotdef = 335544516;
isc_except = 335544517;
isc_cache_restart = 335544518;
isc_bad_lock_handle = 335544519;
isc_jrn_present = 335544520;
isc_wal_err_rollover2 = 335544521;
isc_wal_err_logwrite = 335544522;
isc_wal_err_jrn_comm = 335544523;
isc_wal_err_expansion = 335544524;
isc_wal_err_setup = 335544525;
isc_wal_err_ww_sync = 335544526;
isc_wal_err_ww_start = 335544527;
isc_shutdown = 335544528;
isc_existing_priv_mod = 335544529;
isc_primary_key_ref = 335544530;
isc_primary_key_notnull = 335544531;
isc_ref_cnstrnt_notfound = 335544532;
isc_foreign_key_notfound = 335544533;
isc_ref_cnstrnt_update = 335544534;
isc_check_cnstrnt_update = 335544535;
isc_check_cnstrnt_del = 335544536;
isc_integ_index_seg_del = 335544537;
isc_integ_index_seg_mod = 335544538;
isc_integ_index_del = 335544539;
isc_integ_index_mod = 335544540;
isc_check_trig_del = 335544541;
isc_check_trig_update = 335544542;
isc_cnstrnt_fld_del = 335544543;
isc_cnstrnt_fld_rename = 335544544;
isc_rel_cnstrnt_update = 335544545;
isc_constaint_on_view = 335544546;
isc_invld_cnstrnt_type = 335544547;
isc_primary_key_exists = 335544548;
isc_systrig_update = 335544549;
isc_not_rel_owner = 335544550;
isc_grant_obj_notfound = 335544551;
isc_grant_fld_notfound = 335544552;
isc_grant_nopriv = 335544553;
isc_nonsql_security_rel = 335544554;
isc_nonsql_security_fld = 335544555;
isc_wal_cache_err = 335544556;
isc_shutfail = 335544557;
isc_check_constraint = 335544558;
isc_bad_svc_handle = 335544559;
isc_shutwarn = 335544560;
isc_wrospbver = 335544561;
isc_bad_spb_form = 335544562;
isc_svcnotdef = 335544563;
isc_no_jrn = 335544564;
isc_transliteration_failed = 335544565;
isc_start_cm_for_wal = 335544566;
isc_wal_ovflow_log_required = 335544567;
isc_text_subtype = 335544568;
isc_dsql_error = 335544569;
isc_dsql_command_err = 335544570;
isc_dsql_constant_err = 335544571;
isc_dsql_cursor_err = 335544572;
isc_dsql_datatype_err = 335544573;
isc_dsql_decl_err = 335544574;
isc_dsql_cursor_update_err = 335544575;
isc_dsql_cursor_open_err = 335544576;
isc_dsql_cursor_close_err = 335544577;
isc_dsql_field_err = 335544578;
isc_dsql_internal_err = 335544579;
isc_dsql_relation_err = 335544580;
isc_dsql_procedure_err = 335544581;
isc_dsql_request_err = 335544582;
isc_dsql_sqlda_err = 335544583;
isc_dsql_var_count_err = 335544584;
isc_dsql_stmt_handle = 335544585;
isc_dsql_function_err = 335544586;
isc_dsql_blob_err = 335544587;
isc_collation_not_found = 335544588;
isc_collation_not_for_charset = 335544589;
isc_dsql_dup_option = 335544590;
isc_dsql_tran_err = 335544591;
isc_dsql_invalid_array = 335544592;
isc_dsql_max_arr_dim_exceeded = 335544593;
isc_dsql_arr_range_error = 335544594;
isc_dsql_trigger_err = 335544595;
isc_dsql_subselect_err = 335544596;
isc_dsql_crdb_prepare_err = 335544597;
isc_specify_field_err = 335544598;
isc_num_field_err = 335544599;
isc_col_name_err = 335544600;
isc_where_err = 335544601;
isc_table_view_err = 335544602;
isc_distinct_err = 335544603;
isc_key_field_count_err = 335544604;
isc_subquery_err = 335544605;
isc_expression_eval_err = 335544606;
isc_node_err = 335544607;
isc_command_end_err = 335544608;
isc_index_name = 335544609;
isc_exception_name = 335544610;
isc_field_name = 335544611;
isc_token_err = 335544612;
isc_union_err = 335544613;
isc_dsql_construct_err = 335544614;
isc_field_aggregate_err = 335544615;
isc_field_ref_err = 335544616;
isc_order_by_err = 335544617;
isc_return_mode_err = 335544618;
isc_extern_func_err = 335544619;
isc_alias_conflict_err = 335544620;
isc_procedure_conflict_error = 335544621;
isc_relation_conflict_err = 335544622;
isc_dsql_domain_err = 335544623;
isc_idx_seg_err = 335544624;
isc_node_name_err = 335544625;
isc_table_name = 335544626;
isc_proc_name = 335544627;
isc_idx_create_err = 335544628;
isc_wal_shadow_err = 335544629;
isc_dependency = 335544630;
isc_idx_key_err = 335544631;
isc_dsql_file_length_err = 335544632;
isc_dsql_shadow_number_err = 335544633;
isc_dsql_token_unk_err = 335544634;
isc_dsql_no_relation_alias = 335544635;
isc_indexname = 335544636;
isc_no_stream_plan = 335544637;
isc_stream_twice = 335544638;
isc_stream_not_found = 335544639;
isc_collation_requires_text = 335544640;
isc_dsql_domain_not_found = 335544641;
isc_index_unused = 335544642;
isc_dsql_self_join = 335544643;
isc_stream_bof = 335544644;
isc_stream_crack = 335544645;
isc_db_or_file_exists = 335544646;
isc_invalid_operator = 335544647;
isc_conn_lost = 335544648;
isc_bad_checksum = 335544649;
isc_page_type_err = 335544650;
isc_ext_readonly_err = 335544651;
isc_sing_select_err = 335544652;
isc_psw_attach = 335544653;
isc_psw_start_trans = 335544654;
isc_invalid_direction = 335544655;
isc_dsql_var_conflict = 335544656;
isc_dsql_no_blob_array = 335544657;
isc_dsql_base_table = 335544658;
isc_duplicate_base_table = 335544659;
isc_view_alias = 335544660;
isc_index_root_page_full = 335544661;
isc_dsql_blob_type_unknown = 335544662;
isc_req_max_clones_exceeded = 335544663;
isc_dsql_duplicate_spec = 335544664;
isc_unique_key_violation = 335544665;
isc_srvr_version_too_old = 335544666;
isc_drdb_completed_with_errs = 335544667;
isc_dsql_procedure_use_err = 335544668;
isc_dsql_count_mismatch = 335544669;
isc_blob_idx_err = 335544670;
isc_array_idx_err = 335544671;
isc_key_field_err = 335544672;
isc_no_delete = 335544673;
isc_del_last_field = 335544674;
isc_sort_err = 335544675;
isc_sort_mem_err = 335544676;
isc_version_err = 335544677;
isc_inval_key_posn = 335544678;
isc_no_segments_err = 335544679;
isc_crrp_data_err = 335544680;
isc_rec_size_err = 335544681;
isc_dsql_field_ref = 335544682;
isc_req_depth_exceeded = 335544683;
isc_no_field_access = 335544684;
isc_no_dbkey = 335544685;
isc_jrn_format_err = 335544686;
isc_jrn_file_full = 335544687;
isc_dsql_open_cursor_request = 335544688;
isc_ib_error = 335544689;
isc_cache_redef = 335544690;
isc_cache_too_small = 335544691;
isc_log_redef = 335544692;
isc_log_too_small = 335544693;
isc_partition_too_small = 335544694;
isc_partition_not_supp = 335544695;
isc_log_length_spec = 335544696;
isc_precision_err = 335544697;
isc_scale_nogt = 335544698;
isc_expec_short = 335544699;
isc_expec_long = 335544700;
isc_expec_ushort = 335544701;
isc_like_escape_invalid = 335544702;
isc_svcnoexe = 335544703;
isc_net_lookup_err = 335544704;
isc_service_unknown = 335544705;
isc_host_unknown = 335544706;
isc_grant_nopriv_on_base = 335544707;
isc_dyn_fld_ambiguous = 335544708;
isc_dsql_agg_ref_err = 335544709;
isc_complex_view = 335544710;
isc_unprepared_stmt = 335544711;
isc_expec_positive = 335544712;
isc_dsql_sqlda_value_err = 335544713;
isc_invalid_array_id = 335544714;
isc_extfile_uns_op = 335544715;
isc_svc_in_use = 335544716;
isc_err_stack_limit = 335544717;
isc_invalid_key = 335544718;
isc_net_init_error = 335544719;
isc_loadlib_failure = 335544720;
isc_network_error = 335544721;
isc_net_connect_err = 335544722;
isc_net_connect_listen_err = 335544723;
isc_net_event_connect_err = 335544724;
isc_net_event_listen_err = 335544725;
isc_net_read_err = 335544726;
isc_net_write_err = 335544727;
isc_integ_index_deactivate = 335544728;
isc_integ_deactivate_primary = 335544729;
isc_cse_not_supported = 335544730;
isc_tra_must_sweep = 335544731;
isc_unsupported_network_drive = 335544732;
isc_io_create_err = 335544733;
isc_io_open_err = 335544734;
isc_io_close_err = 335544735;
isc_io_read_err = 335544736;
isc_io_write_err = 335544737;
isc_io_delete_err = 335544738;
isc_io_access_err = 335544739;
isc_udf_exception = 335544740;
isc_lost_db_connection = 335544741;
isc_no_write_user_priv = 335544742;
isc_token_too_long = 335544743;
isc_max_att_exceeded = 335544744;
isc_login_same_as_role_name = 335544745;
isc_reftable_requires_pk = 335544746;
isc_usrname_too_long = 335544747;
isc_password_too_long = 335544748;
isc_usrname_required = 335544749;
isc_password_required = 335544750;
isc_bad_protocol = 335544751;
isc_dup_usrname_found = 335544752;
isc_usrname_not_found = 335544753;
isc_error_adding_sec_record = 335544754;
isc_error_modifying_sec_record = 335544755;
isc_error_deleting_sec_record = 335544756;
isc_error_updating_sec_db = 335544757;
isc_sort_rec_size_err = 335544758;
isc_bad_default_value = 335544759;
isc_invalid_clause = 335544760;
isc_too_many_handles = 335544761;
isc_optimizer_blk_exc = 335544762;
isc_invalid_string_constant = 335544763;
isc_transitional_date = 335544764;
isc_read_only_database = 335544765;
isc_must_be_dialect_2_and_up = 335544766;
isc_blob_filter_exception = 335544767;
isc_exception_access_violation = 335544768;
isc_exception_datatype_missalignment = 335544769;
isc_exception_array_bounds_exceeded = 335544770;
isc_exception_float_denormal_operand = 335544771;
isc_exception_float_divide_by_zero = 335544772;
isc_exception_float_inexact_result = 335544773;
isc_exception_float_invalid_operand = 335544774;
isc_exception_float_overflow = 335544775;
isc_exception_float_stack_check = 335544776;
isc_exception_float_underflow = 335544777;
isc_exception_integer_divide_by_zero = 335544778;
isc_exception_integer_overflow = 335544779;
isc_exception_unknown = 335544780;
isc_exception_stack_overflow = 335544781;
isc_exception_sigsegv = 335544782;
isc_exception_sigill = 335544783;
isc_exception_sigbus = 335544784;
isc_exception_sigfpe = 335544785;
isc_ext_file_delete = 335544786;
isc_ext_file_modify = 335544787;
isc_adm_task_denied = 335544788;
isc_extract_input_mismatch = 335544789;
isc_insufficient_svc_privileges = 335544790;
isc_file_in_use = 335544791;
isc_service_att_err = 335544792;
isc_ddl_not_allowed_by_db_sql_dial = 335544793;
isc_cancelled = 335544794;
isc_unexp_spb_form = 335544795;
isc_sql_dialect_datatype_unsupport = 335544796;
isc_svcnouser = 335544797;
isc_depend_on_uncommitted_rel = 335544798;
isc_svc_name_missing = 335544799;
isc_too_many_contexts = 335544800;
isc_datype_notsup = 335544801;
isc_dialect_reset_warning = 335544802;
isc_dialect_not_changed = 335544803;
isc_database_create_failed = 335544804;
isc_inv_dialect_specified = 335544805;
isc_valid_db_dialects = 335544806;
isc_sqlwarn = 335544807;
isc_dtype_renamed = 335544808;
isc_extern_func_dir_error = 335544809;
isc_date_range_exceeded = 335544810;
isc_inv_client_dialect_specified = 335544811;
isc_valid_client_dialects = 335544812;
isc_optimizer_between_err = 335544813;
isc_service_not_supported = 335544814;
// FB102 OR YF867
isc_generator_name = 335544815;
isc_udf_name = 335544816;
isc_bad_limit_param = 335544817;
isc_bad_skip_param = 335544818;
isc_io_32bit_exceeded_err = 335544819;
// FB15
isc_invalid_savepoint = 335544820;
isc_dsql_column_pos_err = 335544821;
isc_dsql_agg_where_err = 335544822;
isc_dsql_agg_group_err = 335544823;
isc_dsql_agg_column_err = 335544824;
isc_dsql_agg_having_err = 335544825;
isc_dsql_agg_nested_err = 335544826;
isc_exec_sql_invalid_arg = 335544827;
isc_exec_sql_invalid_req = 335544828;
isc_exec_sql_invalid_var = 335544829;
isc_exec_sql_max_call_exceeded = 335544830;
isc_conf_access_denied = 335544831;
// FB20
isc_wrong_backup_state = 335544832;
isc_wal_backup_err = 335544833;
isc_cursor_not_open = 335544834;
isc_bad_shutdown_mode = 335544835;
isc_concat_overflow = 335544836;
isc_bad_substring_offset = 335544837;
isc_foreign_key_target_doesnt_exist = 335544838;
isc_foreign_key_references_present = 335544839;
isc_no_update = 335544840;
isc_cursor_already_open = 335544841;
isc_stack_trace = 335544842;
isc_ctx_var_not_found = 335544843;
isc_ctx_namespace_invalid = 335544844;
isc_ctx_too_big = 335544845;
isc_ctx_bad_argument = 335544846;
isc_identifier_too_long = 335544847;
isc_except2 = 335544848;
isc_malformed_string = 335544849;
isc_prc_out_param_mismatch = 335544850;
isc_command_end_err2 = 335544851;
isc_partner_idx_incompat_type = 335544852;
isc_bad_substring_length = 335544853;
isc_charset_not_installed = 335544854;
isc_collation_not_installed = 335544855;
isc_att_shutdown = 335544856;
isc_blobtoobig = 335544857;
isc_must_have_phys_field = 335544858;
isc_invalid_time_precision = 335544859;
isc_blob_convert_error = 335544860;
isc_array_convert_error = 335544861;
isc_record_lock_not_supp = 335544862;
isc_partner_idx_not_found = 335544863;
// IB71
isc_savepoint_err = 335544815;
isc_generator_name_2 = 335544816;
isc_udf_name_2 = 335544817;
// IB2017
isc_table_truncated = 335544860;
isc_dyn_delete_subscribers_failed = 336068869;
isc_dyn_subscribers_exist = 336068870;
isc_dyn_delete_subscription_failed = 336068871;
isc_gfix_db_name = 335740929;
isc_gfix_invalid_sw = 335740930;
isc_gfix_incmp_sw = 335740932;
isc_gfix_replay_req = 335740933;
isc_gfix_pgbuf_req = 335740934;
isc_gfix_val_req = 335740935;
isc_gfix_pval_req = 335740936;
isc_gfix_trn_req = 335740937;
isc_gfix_full_req = 335740940;
isc_gfix_usrname_req = 335740941;
isc_gfix_pass_req = 335740942;
isc_gfix_subs_name = 335740943;
isc_gfix_wal_req = 335740944;
isc_gfix_sec_req = 335740945;
isc_gfix_nval_req = 335740946;
isc_gfix_type_shut = 335740947;
isc_gfix_retry = 335740948;
isc_gfix_retry_db = 335740951;
isc_gfix_exceed_max = 335740991;
isc_gfix_corrupt_pool = 335740992;
isc_gfix_mem_exhausted = 335740993;
isc_gfix_bad_pool = 335740994;
isc_gfix_trn_not_valid = 335740995;
isc_gfix_unexp_eoi = 335741012;
isc_gfix_recon_fail = 335741018;
isc_gfix_trn_unknown = 335741036;
isc_gfix_mode_req = 335741038;
isc_gfix_opt_SQL_dialect = 335741039;
// FB20
isc_gfix_pzval_req = 335741042;
// IB7
isc_gfix_commits_opt = 335741041;
isc_dsql_dbkey_from_non_table = 336003074;
isc_dsql_transitional_numeric = 336003075;
isc_dsql_dialect_warning_expr = 336003076;
isc_sql_db_dialect_dtype_unsupport = 336003077;
isc_isc_sql_dialect_conflict_num = 336003079;
isc_dsql_warning_number_ambiguous = 336003080;
isc_dsql_warning_number_ambiguous1 = 336003081;
isc_dsql_warn_precision_ambiguous = 336003082;
isc_dsql_warn_precision_ambiguous1 = 336003083;
isc_dsql_warn_precision_ambiguous2 = 336003084;
// FB102 OR YF867
isc_dsql_ambiguous_field_name = 336003085;
isc_dsql_udf_return_pos_err = 336003086;
// FB15
isc_dsql_invalid_label = 336003087;
isc_dsql_datatypes_not_comparable = 336003088;
// FB20
isc_dsql_cursor_invalid = 336003089;
isc_dsql_cursor_redefined = 336003090;
isc_dsql_cursor_not_found = 336003091;
isc_dsql_cursor_exists = 336003092;
isc_dsql_cursor_rel_ambiguous = 336003093;
isc_dsql_cursor_rel_not_found = 336003094;
isc_dsql_cursor_not_open = 336003095;
isc_dsql_type_not_supp_ext_tab = 336003096;
// IB65
isc_dsql_rows_ties_err = 336003085;
// IB75
isc_dsql_cursor_stmt_err = 336003086;
isc_dsql_on_commit_invalid = 336003087;
isc_dsql_gen_cnstrnt_ref_temp = 336003088;
isc_dsql_persist_cnstrnt_ref_temp = 336003089;
isc_dsql_temp_cnstrnt_ref_persist = 336003090;
isc_dsql_persist_refs_temp = 336003091;
isc_dsql_temp_refs_persist = 336003092;
isc_dsql_temp_refs_mismatch = 336003093;
isc_dsql_usrname_lower = 336003094;
// FB30
isc_dyn_filter_not_found = 336068645;
isc_dyn_func_not_found = 336068649;
isc_dyn_index_not_found = 336068656;
isc_dyn_view_not_found = 336068662;
isc_dyn_domain_not_found = 336068697;
isc_dyn_cant_modify_auto_trig = 336068717;
isc_dyn_proc_not_found = 336068748;
isc_dyn_exception_not_found = 336068752;
isc_dyn_proc_param_not_found = 336068754;
isc_dyn_trig_not_found = 336068755;
isc_dyn_charset_not_found = 336068759;
isc_dyn_collation_not_found = 336068760;
isc_dyn_role_not_found = 336068763;
isc_dyn_name_longer = 336068767;
isc_dyn_gen_not_found = 336068822;
isc_dyn_coll_used_table = 336068843;
isc_dyn_coll_used_domain = 336068844;
isc_dyn_cannot_del_syscoll = 336068845;
isc_dyn_cannot_del_def_coll = 336068846;
isc_dyn_table_not_found = 336068849;
isc_dyn_coll_used_procedure = 336068851;
isc_dyn_package_not_found = 336068864;
isc_dyn_schema_not_found = 336068865;
isc_dyn_cannot_mod_sysproc = 336068866;
isc_dyn_cannot_mod_systrig = 336068867;
isc_dyn_cannot_mod_sysfunc = 336068868;
isc_dyn_invalid_ddl_proc = 336068869;
isc_dyn_invalid_ddl_trig = 336068870;
isc_dyn_funcnotdef_package = 336068871;
isc_dyn_procnotdef_package = 336068872;
isc_dyn_funcsignat_package = 336068873;
isc_dyn_procsignat_package = 336068874;
isc_dyn_defvaldecl_package = 336068875;
isc_dyn_package_body_exists = 336068877;
isc_dyn_invalid_ddl_func = 336068878;
isc_dyn_newfc_oldsyntax = 336068879;
isc_dyn_func_param_not_found = 336068886;
isc_dyn_routine_param_not_found = 336068887;
isc_dyn_routine_param_ambiguous = 336068888;
isc_dyn_coll_used_function = 336068889;
isc_dyn_domain_used_function = 336068890;
isc_dsql_alter_charset_failed = 336397258;
isc_dsql_comment_on_failed = 336397259;
isc_dsql_create_func_failed = 336397260;
isc_dsql_alter_func_failed = 336397261;
isc_dsql_create_alter_func_failed = 336397262;
isc_dsql_drop_func_failed = 336397263;
isc_dsql_recreate_func_failed = 336397264;
isc_dsql_create_proc_failed = 336397265;
isc_dsql_alter_proc_failed = 336397266;
isc_dsql_create_alter_proc_failed = 336397267;
isc_dsql_drop_proc_failed = 336397268;
isc_dsql_recreate_proc_failed = 336397269;
isc_dsql_create_trigger_failed = 336397270;
isc_dsql_alter_trigger_failed = 336397271;
isc_dsql_create_alter_trigger_failed = 336397272;
isc_dsql_drop_trigger_failed = 336397273;
isc_dsql_recreate_trigger_failed = 336397274;
isc_dsql_create_collation_failed = 336397275;
isc_dsql_drop_collation_failed = 336397276;
isc_dsql_create_domain_failed = 336397277;
isc_dsql_alter_domain_failed = 336397278;
isc_dsql_drop_domain_failed = 336397279;
isc_dsql_create_except_failed = 336397280;
isc_dsql_alter_except_failed = 336397281;
isc_dsql_create_alter_except_failed = 336397282;
isc_dsql_recreate_except_failed = 336397283;
isc_dsql_drop_except_failed = 336397284;
isc_dsql_create_sequence_failed = 336397285;
isc_dsql_create_table_failed = 336397286;
isc_dsql_alter_table_failed = 336397287;
isc_dsql_drop_table_failed = 336397288;
isc_dsql_recreate_table_failed = 336397289;
isc_dsql_create_pack_failed = 336397290;
isc_dsql_alter_pack_failed = 336397291;
isc_dsql_create_alter_pack_failed = 336397292;
isc_dsql_drop_pack_failed = 336397293;
isc_dsql_recreate_pack_failed = 336397294;
isc_dsql_create_pack_body_failed = 336397295;
isc_dsql_drop_pack_body_failed = 336397296;
isc_dsql_recreate_pack_body_failed = 336397297;
isc_dsql_create_view_failed = 336397298;
isc_dsql_alter_view_failed = 336397299;
isc_dsql_create_alter_view_failed = 336397300;
isc_dsql_recreate_view_failed = 336397301;
isc_dsql_drop_view_failed = 336397302;
isc_dyn_role_does_not_exist = 336068796;
isc_dyn_no_grant_admin_opt = 336068797;
isc_dyn_user_not_role_member = 336068798;
isc_dyn_delete_role_failed = 336068799;
isc_dyn_grant_role_to_user = 336068800;
isc_dyn_inv_sql_role_name = 336068801;
isc_dyn_dup_sql_role = 336068802;
isc_dyn_kywd_spec_for_role = 336068803;
isc_dyn_roles_not_supported = 336068804;
isc_dyn_domain_name_exists = 336068812;
isc_dyn_field_name_exists = 336068813;
isc_dyn_dependency_exists = 336068814;
isc_dyn_dtype_invalid = 336068815;
isc_dyn_char_fld_too_small = 336068816;
isc_dyn_invalid_dtype_conversion = 336068817;
isc_dyn_dtype_conv_invalid = 336068818;
// FB102 OR YF867
isc_dyn_zero_len_id = 336068820;
// IB71
isc_dyn_gen_does_not_exist = 336068820;
isc_dyn_delete_generator_failed = 336068821;
// IB75
isc_dyn_drop_db_owner = 336068836;
isc_gbak_unknown_switch = 336330753;
isc_gbak_page_size_missing = 336330754;
isc_gbak_page_size_toobig = 336330755;
isc_gbak_redir_ouput_missing = 336330756;
isc_gbak_switches_conflict = 336330757;
isc_gbak_unknown_device = 336330758;
isc_gbak_no_protection = 336330759;
isc_gbak_page_size_not_allowed = 336330760;
isc_gbak_multi_source_dest = 336330761;
isc_gbak_filename_missing = 336330762;
isc_gbak_dup_inout_names = 336330763;
isc_gbak_inv_page_size = 336330764;
isc_gbak_db_specified = 336330765;
isc_gbak_db_exists = 336330766;
isc_gbak_unk_device = 336330767;
isc_gbak_blob_info_failed = 336330772;
isc_gbak_unk_blob_item = 336330773;
isc_gbak_get_seg_failed = 336330774;
isc_gbak_close_blob_failed = 336330775;
isc_gbak_open_blob_failed = 336330776;
isc_gbak_put_blr_gen_id_failed = 336330777;
isc_gbak_unk_type = 336330778;
isc_gbak_comp_req_failed = 336330779;
isc_gbak_start_req_failed = 336330780;
isc_gbak_rec_failed = 336330781;
isc_gbak_rel_req_failed = 336330782;
isc_gbak_db_info_failed = 336330783;
isc_gbak_no_db_desc = 336330784;
isc_gbak_db_create_failed = 336330785;
isc_gbak_decomp_len_error = 336330786;
isc_gbak_tbl_missing = 336330787;
isc_gbak_blob_col_missing = 336330788;
isc_gbak_create_blob_failed = 336330789;
isc_gbak_put_seg_failed = 336330790;
isc_gbak_rec_len_exp = 336330791;
isc_gbak_inv_rec_len = 336330792;
isc_gbak_exp_data_type = 336330793;
isc_gbak_gen_id_failed = 336330794;
isc_gbak_unk_rec_type = 336330795;
isc_gbak_inv_bkup_ver = 336330796;
isc_gbak_missing_bkup_desc = 336330797;
isc_gbak_string_trunc = 336330798;
isc_gbak_cant_rest_record = 336330799;
isc_gbak_send_failed = 336330800;
isc_gbak_no_tbl_name = 336330801;
isc_gbak_unexp_eof = 336330802;
isc_gbak_db_format_too_old = 336330803;
isc_gbak_inv_array_dim = 336330804;
isc_gbak_xdr_len_expected = 336330807;
isc_gbak_open_bkup_error = 336330817;
isc_gbak_open_error = 336330818;
isc_gbak_missing_block_fac = 336330934;
isc_gbak_inv_block_fac = 336330935;
isc_gbak_block_fac_specified = 336330936;
isc_gbak_missing_username = 336330940;
isc_gbak_missing_password = 336330941;
isc_gbak_missing_skipped_bytes = 336330952;
isc_gbak_inv_skipped_bytes = 336330953;
isc_gbak_err_restore_charset = 336330965;
isc_gbak_err_restore_collation = 336330967;
isc_gbak_read_error = 336330972;
isc_gbak_write_error = 336330973;
isc_gbak_db_in_use = 336330985;
isc_gbak_sysmemex = 336330990;
isc_gbak_restore_role_failed = 336331002;
isc_gbak_role_op_missing = 336331005;
isc_gbak_page_buffers_missing = 336331010;
isc_gbak_page_buffers_wrong_param = 336331011;
isc_gbak_page_buffers_restore = 336331012;
isc_gbak_inv_size = 336331014;
isc_gbak_file_outof_sequence = 336331015;
isc_gbak_join_file_missing = 336331016;
isc_gbak_stdin_not_supptd = 336331017;
isc_gbak_stdout_not_supptd = 336331018;
isc_gbak_bkup_corrupt = 336331019;
isc_gbak_unk_db_file_spec = 336331020;
isc_gbak_hdr_write_failed = 336331021;
isc_gbak_disk_space_ex = 336331022;
isc_gbak_size_lt_min = 336331023;
isc_gbak_svc_name_missing = 336331025;
isc_gbak_not_ownr = 336331026;
isc_gbak_mode_req = 336331031;
// FB102 OR YF867
isc_gbak_just_data = 336331033;
isc_gbak_data_only = 336331034;
// FB150
isc_dsql_tableview_not_found = 336068783;
// FB20
isc_dsql_too_old_ods = 336397205;
isc_dsql_table_not_found = 336397206;
isc_dsql_view_not_found = 336397207;
isc_dsql_line_col_error = 336397208;
isc_dsql_unknown_pos = 336397209;
isc_dsql_no_dup_name = 336397210;
isc_dsql_too_many_values = 336397211;
// IB71
isc_gbak_validate_restore = 336331034;
isc_gsec_cant_open_db = 336723983;
isc_gsec_switches_error = 336723984;
isc_gsec_no_op_spec = 336723985;
isc_gsec_no_usr_name = 336723986;
isc_gsec_err_add = 336723987;
isc_gsec_err_modify = 336723988;
isc_gsec_err_find_mod = 336723989;
isc_gsec_err_rec_not_found = 336723990;
isc_gsec_err_delete = 336723991;
isc_gsec_err_find_del = 336723992;
isc_gsec_err_find_disp = 336723996;
isc_gsec_inv_param = 336723997;
isc_gsec_op_specified = 336723998;
isc_gsec_pw_specified = 336723999;
isc_gsec_uid_specified = 336724000;
isc_gsec_gid_specified = 336724001;
isc_gsec_proj_specified = 336724002;
isc_gsec_org_specified = 336724003;
isc_gsec_fname_specified = 336724004;
isc_gsec_mname_specified = 336724005;
isc_gsec_lname_specified = 336724006;
isc_gsec_inv_switch = 336724008;
isc_gsec_amb_switch = 336724009;
isc_gsec_no_op_specified = 336724010;
isc_gsec_params_not_allowed = 336724011;
isc_gsec_incompat_switch = 336724012;
isc_gsec_inv_username = 336724044;
isc_gsec_inv_pw_length = 336724045;
isc_gsec_db_specified = 336724046;
isc_gsec_db_admin_specified = 336724047;
isc_gsec_db_admin_pw_specified = 336724048;
isc_gsec_sql_role_specified = 336724049;
isc_license_no_file = 336789504;
isc_license_op_specified = 336789523;
isc_license_op_missing = 336789524;
isc_license_inv_switch = 336789525;
isc_license_inv_switch_combo = 336789526;
isc_license_inv_op_combo = 336789527;
isc_license_amb_switch = 336789528;
isc_license_inv_parameter = 336789529;
isc_license_param_specified = 336789530;
isc_license_param_req = 336789531;
isc_license_syntx_error = 336789532;
isc_license_dup_id = 336789534;
isc_license_inv_id_key = 336789535;
isc_license_err_remove = 336789536;
isc_license_err_update = 336789537;
isc_license_err_convert = 336789538;
isc_license_err_unk = 336789539;
isc_license_svc_err_add = 336789540;
isc_license_svc_err_remove = 336789541;
isc_license_eval_exists = 336789563;
// IB7
isc_smp_cpu_license = 336789570;
isc_node_locked_full_unlimited_serve = 336789571;
isc_dev_only_full_server_licenses = 336789572;
// IB75
isc_license_not_registered = 336789573;
isc_license_library_unloadable = 336789574;
isc_license_registration_file = 336789575;
isc_license_expire_limit = 336789576;
isc_license_bad_reg_file = 336789577;
isc_license_bad_lic_file = 336789578;
isc_gstat_unknown_switch = 336920577;
isc_gstat_retry = 336920578;
isc_gstat_wrong_ods = 336920579;
isc_gstat_unexpected_eof = 336920580;
isc_gstat_open_err = 336920605;
isc_gstat_read_err = 336920606;
isc_gstat_sysmemex = 336920607;
// ---------------------------------------------------------------------------
// OSRI database functions
// ---------------------------------------------------------------------------
{$IFDEF FireDAC_IB_STATIC}
const
{$IFDEF FireDAC_IB_STATIC_IBBRAND}
{$IF DEFINED(IOS) and (DEFINED(CPUARM) or DEFINED(CPUARM64))}
C_FD_IBLib = 'libibtogo.a';
C_FD_IBLib_DEP = 'stdc++';
{$ENDIF}
{$IF DEFINED(ANDROID)}
C_FD_IBLib = 'libibtogo.a';
{$ENDIF}
{$ENDIF}
function BLOB_close(Stream: PBStream): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function BLOB_display(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
field_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function BLOB_dump(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
file_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function BLOB_edit(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
field_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function BLOB_get(Stream: PBStream): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function BLOB_load(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
file_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function BLOB_open(blob: isc_blob_handle; buffer: PISC_SCHAR;
length: Integer): PBStream; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function BLOB_put(x: ISC_SCHAR; Stream: PBStream): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function BLOB_text_dump(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
file_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function BLOB_text_load(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
file_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function Bopen(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
mode: PISC_SCHAR): PBStream; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
// FB >= 2.0 returns ISC_STATUS, others - Integer
function isc_add_user(status: PISC_STATUS; user_data: PUSER_SEC_DATA): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_gen_sdl(status: PISC_STATUS; desc: PISC_ARRAY_DESC_V1; sdl_buffer_length: PISC_SHORT;
sdl_buffer: PISC_UCHAR; sdl_length: PISC_SHORT): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_get_slice(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; array_id: PISC_QUAD; desc: PISC_ARRAY_DESC_V1; array_: Pointer;
slice_length: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_lookup_bounds(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_SCHAR;
desc: PISC_ARRAY_DESC_V1): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_lookup_desc(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_SCHAR;
desc: PISC_ARRAY_DESC_V1): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_put_slice(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; array_id: PISC_QUAD; desc: PISC_ARRAY_DESC_V1; array_: Pointer;
slice_length: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_set_desc(status: PISC_STATUS; relation_name, field_name: PISC_SCHAR;
sql_dtype, sql_length, dimensions: PSmallint; desc: PISC_ARRAY_DESC_V1):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_gen_sdl2(status: PISC_STATUS; desc: PISC_ARRAY_DESC_V2; sdl_buffer_length: PISC_SHORT;
sdl_buffer: PISC_UCHAR; sdl_length: PISC_SHORT): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_get_slice2(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; array_id: PISC_QUAD; desc: PISC_ARRAY_DESC_V2; array_: Pointer;
slice_length: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_lookup_bounds2(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_SCHAR;
desc: PISC_ARRAY_DESC_V2): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_lookup_desc2(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_SCHAR;
desc: PISC_ARRAY_DESC_V2): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_put_slice2(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; array_id: PISC_QUAD; desc: PISC_ARRAY_DESC_V2; array_: Pointer;
slice_length: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_array_set_desc2(status: PISC_STATUS; relation_name, field_name: PISC_SCHAR;
sql_dtype, sql_length, dimensions: PSmallint; desc: PISC_ARRAY_DESC_V2):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_attach_database(user_status: PISC_STATUS; file_length: Smallint;
file_name: PISC_SCHAR; handle: Pisc_db_handle; dpb_length: Smallint;
dpb: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib
{$IF DEFINED(CPUARM)} dependency LibCPP {$IF DEFINED(IOS)}, C_FD_IBLib_DEP {$ENDIF} {$ENDIF};
procedure isc_blob_default_desc(desc: PISC_BLOB_DESC; relation_name,
field_name: PISC_UCHAR); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_blob_gen_bpb(status: PISC_STATUS; to_desc, from_desc: PISC_BLOB_DESC;
bpb_buffer_length: Word; bpb_buffer: PISC_UCHAR; var bpb_length: Word):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_blob_info(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle;
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint; buffer: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_blob_lookup_desc(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_UCHAR; desc: PISC_BLOB_DESC;
global: PISC_UCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_blob_set_desc(status: PISC_STATUS; relation_name, field_name: PISC_UCHAR;
subtype, charset, segment_size: Smallint; desc: PISC_BLOB_DESC): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_cancel_blob(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_cancel_events(user_status: PISC_STATUS; handle: Pisc_db_handle;
id: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_close(user_status: PISC_STATUS; name: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_close_blob(user_status: PISC_STATUS;
blob_handle: Pisc_blob_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_commit_retaining(user_status: PISC_STATUS;
tra_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_commit_transaction(user_status: PISC_STATUS;
tra_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_compile_request(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
req_handle: Pisc_req_handle; blr_length: Smallint; blr: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_compile_request2(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
req_handle: Pisc_req_handle; blr_length: Smallint; blr: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_create_blob(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blob_handle: Pisc_blob_handle; blob_id: PISC_QUAD):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_create_blob2(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blob_handle: Pisc_blob_handle; blob_id: PISC_QUAD;
bpb_length: Smallint; bpb: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_create_database(user_status: PISC_STATUS; file_length: Smallint;
file_name: PISC_SCHAR; handle: Pisc_db_handle; dpb_length: Smallint; dpb: PISC_SCHAR;
db_type: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_database_info(user_status: PISC_STATUS; handle: Pisc_db_handle;
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint;
buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_ddl(user_status: PISC_STATUS; db_handle: Pisc_db_handle; tra_handle: Pisc_tr_handle;
length: Smallint; ddl: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_declare(user_status: PISC_STATUS; statement, cursor: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_decode_date(date: PISC_QUAD; times_arg: PCTimeStructure);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_decode_sql_date(date: PISC_DATE; times_arg: PCTimeStructure);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_decode_sql_time(sql_time: PISC_TIME; times_arg: PCTimeStructure);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_decode_timestamp(date: PISC_TIMESTAMP; times_arg: PCTimeStructure);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
// FB >= 2.0 returns ISC_STATUS, others - Integer
function isc_delete_user(status: PISC_STATUS; user_data: PUSER_SEC_DATA): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_describe(user_status: PISC_STATUS; name: PISC_SCHAR;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_describe_bind(user_status: PISC_STATUS; name: PISC_SCHAR;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_detach_database(user_status: PISC_STATUS;
handle: Pisc_db_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_drop_database(user_status: PISC_STATUS; handle: Pisc_db_handle):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_alloc_statement2(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
stmt_handle: Pisc_stmt_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_allocate_statement(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
stmt_handle: Pisc_stmt_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_describe(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_describe_bind(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_exec_immed2(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; length: Word; statement: PISC_SCHAR; dialect: Word;
in_sqlda, out_sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_exec_immed3_m(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; Length: Word; statement: PISC_SCHAR; dialect, in_blr_length: Word;
in_blr: PISC_SCHAR; in_msg_type, in_msg_length: Word; in_msg: PISC_SCHAR; out_blr_length: Word;
out_blr: PISC_SCHAR; out_msg_type, out_msg_length: Word; out_msg: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_execute(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; dialect: Word; sqlda: PXSQLDA):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_execute_immediate(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; length: Word; statement: PISC_SCHAR; dialect: Word;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_execute_immediate_m(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; length: Word; statement: PISC_SCHAR; dialect, blr_length: Word;
blr: PISC_SCHAR; msg_type, msg_length: Word; msg: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_execute_m(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; blr_length: Word; blr: PISC_SCHAR; msg_type, msg_length: Word;
msg: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_execute2(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; dialect: Word; in_sqlda, out_sqlda: PXSQLDA):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_execute2_m(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; in_blr_length: Word; in_blr: PISC_SCHAR; in_msg_type,
in_msg_length: Word; in_msg: PISC_SCHAR; out_blr_length: Word; out_blr: PISC_SCHAR;
out_msg_type, out_msg_length: Word; out_msg: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_fetch(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_fetch_m(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
blr_length: Word; blr: PISC_SCHAR; msg_type, msg_length: Word; msg: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_finish(db_handle: Pisc_db_handle): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_free_statement(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
option: Word): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_insert(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_insert_m(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
blr_length: Word; blr: PISC_SCHAR; msg_type, msg_length: Word; msg: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_prepare(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; length: Word; string_: PISC_SCHAR; dialect: Word;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_prepare_m(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; length: Word; string_: PISC_SCHAR; dialect, item_length: Word;
items: PISC_SCHAR; buffer_length: Word; buffer: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_release(user_status: PISC_STATUS; name: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_set_cursor_name(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
cursor: PISC_SCHAR; type_: Word): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_sql_info(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint; buffer: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_close(user_status: PISC_STATUS; name: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_declare(user_status: PISC_STATUS;
stmt_name, cursor: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_describe(user_status: PISC_STATUS; stmt_name: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_describe_bind(user_status: PISC_STATUS; stmt_name: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_execute(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
stmt_name: PISC_SCHAR; dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_execute_immed(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; length: Word; string_: PISC_SCHAR; dialect: Word;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_execute2(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
stmt_name: PISC_SCHAR; dialect: Word; in_sqlda, out_sqlda: PXSQLDA): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_fetch(user_status: PISC_STATUS; cursor_name: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_insert(user_status: PISC_STATUS; cursor_name: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_open(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
cursor_name: PISC_SCHAR; dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_open2(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
cursor_name: PISC_SCHAR; dialect: Word; in_sqlda, out_sqlda: PXSQLDA): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_prepare(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; stmt_name: PISC_SCHAR; length: Word; string_: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_embed_dsql_release(user_status: PISC_STATUS;
stmt_name: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_encode_date(times_arg: PCTimeStructure; date: PISC_QUAD);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_encode_sql_date(times_arg: PCTimeStructure; date: PISC_DATE);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_encode_sql_time(times_arg: PCTimeStructure; time: PISC_TIME);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_encode_timestamp(times_arg: PCTimeStructure;
timestamp: PISC_TIMESTAMP); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
{$IF DEFINED(ANDROID)}
function isc_event_block(var event_buffer, result_buffer: PISC_UCHAR; count: ISC_USHORT;
v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15: PISC_UCHAR): ISC_LONG; cdecl; external C_FD_IBLib;
{$ELSE}
function isc_event_block(var event_buffer, result_buffer: PISC_UCHAR;
count: ISC_USHORT): ISC_LONG; cdecl varargs; external C_FD_IBLib;
{$ENDIF}
procedure isc_event_counts(event_counts: PISC_ULONG; buffer_length: ISC_SHORT;
event_buffer, result_buffer: PISC_UCHAR); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_execute(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
name: PISC_SCHAR; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_execute_immediate(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; length: PSmallint; string_: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_expand_dpb(dpb: PPISC_SCHAR; dpb_size: PSmallint; name_buffer: PPISC_SCHAR); cdecl; external C_FD_IBLib;
function isc_fetch(user_status: PISC_STATUS; name: PISC_SCHAR; sqlda: PXSQLDA):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_free(blk: Pointer): ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_ftof(string_: PISC_SCHAR; length1: Word; field: PISC_SCHAR;
length2: Word): ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_get_segment(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle; var length: Word;
buffer_length: Word; buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_get_slice(user_status: PISC_STATUS; db_handle: Pisc_db_handle; tra_handle: Pisc_tr_handle;
array_id: PISC_QUAD; sdl_length: Smallint; sdl: PISC_SCHAR; param_length: Smallint; param: PISC_LONG;
slice_length: ISC_LONG; slice: Pointer; return_length: PISC_LONG): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
// FB >= 2.0 returns ISC_LONG, others - ISC_STATUS
function isc_interprete(buffer: PISC_SCHAR; var status_vector: PISC_STATUS):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_modify_dpb(dpb: PPISC_SCHAR; dpb_length: PSmallint; type_: Word;
str: PISC_SCHAR; str_len: Smallint): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
// FB >= 2.0 returns ISC_STATUS, others - Integer
function isc_modify_user(status: PISC_STATUS;
user_data: PUSER_SEC_DATA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_open(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle; name: PISC_SCHAR;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_open_blob(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blob_handle: Pisc_blob_handle;
blob_id: PISC_QUAD): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_open_blob2(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blob_handle: Pisc_blob_handle; blob_id: PISC_QUAD; bpb_length: ISC_USHORT;
bpb: PISC_UCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_portable_integer(ptr: PISC_UCHAR; length: Smallint): ISC_INT64;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_prepare(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; name: PISC_SCHAR; length: PSmallint; string_: PISC_SCHAR;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_prepare_transaction(user_status: PISC_STATUS;
tra_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_prepare_transaction2(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
msg_length: ISC_USHORT; msg: PISC_UCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_print_blr(blr: PISC_SCHAR; callback: isc_callback; callback_argument: Pointer;
language: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_print_sqlerror(sqlcode: ISC_SHORT; status_vector: PISC_STATUS);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_print_status(status_vector: PISC_STATUS): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_put_segment(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle;
buffer_length: Word; buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_put_slice(user_status: PISC_STATUS; db_handle: Pisc_db_handle; tra_handle: Pisc_tr_handle;
array_id: PISC_QUAD; sdl_length: Smallint; sdl: PISC_SCHAR; param_length: Smallint; param: PISC_LONG;
slice_length: ISC_LONG; slice: Pointer): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_qtoq(quad1, quad2: PISC_QUAD); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_que_events(user_status: PISC_STATUS; handle: Pisc_db_handle; id: PISC_LONG;
length: Smallint; events: PISC_UCHAR; ast: isc_callback; arg: Pointer):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_receive(user_status: PISC_STATUS; req_handle: Pisc_req_handle; msg_type,
msg_length: Smallint; msg: Pointer; level: Smallint): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_reconnect_transaction(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; length: Smallint; id: PISC_SHORT): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_release_request(user_status: PISC_STATUS;
req_handle: Pisc_req_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_request_info(user_status: PISC_STATUS; req_handle: Pisc_req_handle; level,
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint;
buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_rollback_retaining(status_vector: PISC_STATUS;
trans_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_rollback_transaction(user_status: PISC_STATUS;
tra_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_seek_blob(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle; mode: Smallint;
offset: ISC_LONG; Result_: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_send(user_status: PISC_STATUS; req_handle: Pisc_req_handle; msg_type,
msg_length: Smallint; msg: Pointer; level: Smallint):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_service_attach(status_vector: PISC_STATUS; service_length: Word;
service_name: PISC_SCHAR; handle: Pisc_svc_handle; spb_length: Word;
spb: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib
{$IF DEFINED(CPUARM)} dependency LibCPP {$IF DEFINED(IOS)}, C_FD_IBLib_DEP {$ENDIF} {$ENDIF};
function isc_service_detach(status_vector: PISC_STATUS;
handle: Pisc_svc_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_service_query(status_vector: PISC_STATUS; svc_handle: Pisc_svc_handle;
reserved: Pisc_resv_handle; send_spb_length: Word; send_spb: PISC_SCHAR; request_spb_length: Word;
request_spb: PISC_SCHAR; buffer_length: Word; buffer: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_service_start(status_vector: PISC_STATUS; svc_handle: Pisc_svc_handle;
reserved: Pisc_resv_handle; spb_length: Word; spb: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_set_debug(flag: Integer); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_sql_interprete(SQLCODE: Smallint; buffer: PISC_SCHAR;
buffer_length: Smallint); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_sqlcode(user_status: PISC_STATUS): ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_start_and_send(user_status: PISC_STATUS; req_handle: Pisc_req_handle;
tra_handle: Pisc_tr_handle; msg_type, msg_length: Smallint; msg: Pointer;
level: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_start_multiple(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
count: Smallint; vector: PISCTEB): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_start_request(user_status: PISC_STATUS; req_handle: Pisc_req_handle;
tra_handle: Pisc_tr_handle; level: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_start_transaction(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
count: Smallint; db_handle: Pisc_db_handle; tpb_length: ISC_USHORT; tpb_ad: PISC_SCHAR): ISC_STATUS; cdecl; external C_FD_IBLib;
function isc_transact_request(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blr_length: Word; blr: PISC_SCHAR; in_msg_length: Word; in_msg: PISC_SCHAR;
out_msg_length: Word; out_msg: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_transaction_info(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint;
buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_unwind_request(user_status: PISC_STATUS; req_handle: Pisc_tr_handle;
level: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_vax_integer(ptr: PISC_SCHAR; length: Smallint): ISC_LONG;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_version(db_handle: Pisc_db_handle; callback: isc_callback;
callback_argument: Pointer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_vtof(string1, string2: PISC_SCHAR; length: Word);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_vtov(string1, string2: PISC_SCHAR; length: Smallint);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_wait_for_event(user_status: PISC_STATUS; handle: Pisc_db_handle;
length: Smallint; events, buffer: PISC_UCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_reset_fpe(fpe_status: ISC_USHORT): ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure isc_get_client_version(version: PISC_SCHAR); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_get_client_major_version: Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_get_client_minor_version: Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_release_savepoint(status: PISC_STATUS; TrHandle: Pisc_tr_handle;
name: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_rollback_savepoint(status: PISC_STATUS; TrHandle: Pisc_tr_handle;
name: PISC_SCHAR; Option: Word): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_start_savepoint(status: PISC_STATUS; TrHandle: Pisc_tr_handle;
name: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function isc_dsql_batch_execute(status: PISC_STATUS; TrHandle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; dialect: Word; insqlda: PXSQLDA; number_of_rows: Word;
batch_vars: PXSQLVAR_V2; rows_affected: PISC_ULONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
{$IFDEF FireDAC_IB_STATIC_FBBRAND}
function fb_interpret(buffer: PISC_SCHAR; v: Cardinal; var status_vector: PISC_STATUS):
ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
procedure fb_sqlstate(sqlstate: PISC_SCHAR; status_vector: PISC_STATUS);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function fb_cancel_operation(status: PISC_STATUS; db_handle: Pisc_db_handle;
options: ISC_USHORT): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function fb_shutdown(timeout: Cardinal; reason: Integer): Integer;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function fb_shutdown_callback(status: PISC_STATUS; callback_function: FB_SHUTDOWN_CALLBACK_FUNC;
mask: Integer; arg: Pointer): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function fb_ping(status: PISC_STATUS; db_handle: Pisc_db_handle): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function fb_get_database_handle(status: PISC_STATUS; db_handle: Pisc_db_handle;
data: Pointer): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
function fb_get_transaction_handle(status: PISC_STATUS; tr_handle: Pisc_tr_handle;
data: Pointer): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF}; external C_FD_IBLib;
{$ENDIF}
{$ENDIF}
type
TBLOB_close = function(Stream: PBStream): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBLOB_display = function(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
field_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBLOB_dump = function(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
file_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBLOB_edit = function(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
field_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBLOB_get = function(Stream: PBStream): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBLOB_load = function(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
file_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBLOB_open = function(blob: isc_blob_handle; buffer: PISC_SCHAR;
length: Integer): PBStream; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBLOB_put = function(x: ISC_SCHAR; Stream: PBStream): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBLOB_text_dump = function(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
file_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBLOB_text_load = function(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
file_name: PISC_SCHAR): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TBopen = function(blob_id: PISC_QUAD; database: isc_db_handle; transaction: isc_tr_handle;
mode: PISC_SCHAR): PBStream; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// FB >= 2.0 returns ISC_STATUS, others - Integer
Tisc_add_user = function(status: PISC_STATUS; user_data: PUSER_SEC_DATA): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_gen_sdl = function(status: PISC_STATUS; desc: PISC_ARRAY_DESC_V1; sdl_buffer_length: PISC_SHORT;
sdl_buffer: PISC_UCHAR; sdl_length: PISC_SHORT): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_get_slice = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; array_id: PISC_QUAD; desc: PISC_ARRAY_DESC_V1; array_: Pointer;
slice_length: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_lookup_bounds = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_SCHAR;
desc: PISC_ARRAY_DESC_V1): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_lookup_desc = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_SCHAR;
desc: PISC_ARRAY_DESC_V1): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_put_slice = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; array_id: PISC_QUAD; desc: PISC_ARRAY_DESC_V1; array_: Pointer;
slice_length: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_set_desc = function(status: PISC_STATUS; relation_name, field_name: PISC_SCHAR;
sql_dtype, sql_length, dimensions: PSmallint; desc: PISC_ARRAY_DESC_V1):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_gen_sdl2 = function(status: PISC_STATUS; desc: PISC_ARRAY_DESC_V2; sdl_buffer_length: PISC_SHORT;
sdl_buffer: PISC_UCHAR; sdl_length: PISC_SHORT): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_get_slice2 = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; array_id: PISC_QUAD; desc: PISC_ARRAY_DESC_V2; array_: Pointer;
slice_length: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_lookup_bounds2 = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_SCHAR;
desc: PISC_ARRAY_DESC_V2): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_lookup_desc2 = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_SCHAR;
desc: PISC_ARRAY_DESC_V2): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_put_slice2 = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; array_id: PISC_QUAD; desc: PISC_ARRAY_DESC_V2; array_: Pointer;
slice_length: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_array_set_desc2 = function(status: PISC_STATUS; relation_name, field_name: PISC_SCHAR;
sql_dtype, sql_length, dimensions: PSmallint; desc: PISC_ARRAY_DESC_V2):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_attach_database = function(user_status: PISC_STATUS; file_length: Smallint;
file_name: PISC_SCHAR; handle: Pisc_db_handle; dpb_length: Smallint;
dpb: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_blob_default_desc = procedure(desc: PISC_BLOB_DESC; relation_name,
field_name: PISC_UCHAR); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_blob_gen_bpb = function(status: PISC_STATUS; to_desc, from_desc: PISC_BLOB_DESC;
bpb_buffer_length: Word; bpb_buffer: PISC_UCHAR; var bpb_length: Word):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_blob_info = function(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle;
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint; buffer: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_blob_lookup_desc = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; relation_name, field_name: PISC_UCHAR; desc: PISC_BLOB_DESC;
global: PISC_UCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_blob_set_desc = function(status: PISC_STATUS; relation_name, field_name: PISC_UCHAR;
subtype, charset, segment_size: Smallint; desc: PISC_BLOB_DESC): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_cancel_blob = function(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_cancel_events = function(user_status: PISC_STATUS; handle: Pisc_db_handle;
id: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_close = function(user_status: PISC_STATUS; name: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_close_blob = function(user_status: PISC_STATUS;
blob_handle: Pisc_blob_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_commit_retaining = function(user_status: PISC_STATUS;
tra_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_commit_transaction = function(user_status: PISC_STATUS;
tra_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_compile_request = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
req_handle: Pisc_req_handle; blr_length: Smallint; blr: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_compile_request2 = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
req_handle: Pisc_req_handle; blr_length: Smallint; blr: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_create_blob = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blob_handle: Pisc_blob_handle; blob_id: PISC_QUAD):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_create_blob2 = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blob_handle: Pisc_blob_handle; blob_id: PISC_QUAD;
bpb_length: Smallint; bpb: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_create_database = function(user_status: PISC_STATUS; file_length: Smallint;
file_name: PISC_SCHAR; handle: Pisc_db_handle; dpb_length: Smallint; dpb: PISC_SCHAR;
db_type: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_database_info = function(user_status: PISC_STATUS; handle: Pisc_db_handle;
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint;
buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_ddl = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle; tra_handle: Pisc_tr_handle;
length: Smallint; ddl: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_declare = function(user_status: PISC_STATUS; statement, cursor: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_decode_date = procedure(date: PISC_QUAD; times_arg: PCTimeStructure);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_decode_sql_date = procedure(date: PISC_DATE; times_arg: PCTimeStructure);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_decode_sql_time = procedure(sql_time: PISC_TIME; times_arg: PCTimeStructure);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_decode_timestamp = procedure(date: PISC_TIMESTAMP; times_arg: PCTimeStructure);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// FB >= 2.0 returns ISC_STATUS, others - Integer
Tisc_delete_user = function(status: PISC_STATUS; user_data: PUSER_SEC_DATA): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_describe = function(user_status: PISC_STATUS; name: PISC_SCHAR;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_describe_bind = function(user_status: PISC_STATUS; name: PISC_SCHAR;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_detach_database = function(user_status: PISC_STATUS;
handle: Pisc_db_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_drop_database = function(user_status: PISC_STATUS; handle: Pisc_db_handle):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_alloc_statement2 = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
stmt_handle: Pisc_stmt_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_allocate_statement = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
stmt_handle: Pisc_stmt_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_describe = function(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_describe_bind = function(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_exec_immed2 = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; length: Word; statement: PISC_SCHAR; dialect: Word;
in_sqlda, out_sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_exec_immed3_m = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; Length: Word; statement: PISC_SCHAR; dialect, in_blr_length: Word;
in_blr: PISC_SCHAR; in_msg_type, in_msg_length: Word; in_msg: PISC_SCHAR; out_blr_length: Word;
out_blr: PISC_SCHAR; out_msg_type, out_msg_length: Word; out_msg: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_execute = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; dialect: Word; sqlda: PXSQLDA):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_execute_immediate = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; length: Word; statement: PISC_SCHAR; dialect: Word;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_execute_immediate_m = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; length: Word; statement: PISC_SCHAR; dialect, blr_length: Word;
blr: PISC_SCHAR; msg_type, msg_length: Word; msg: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_execute_m = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; blr_length: Word; blr: PISC_SCHAR; msg_type, msg_length: Word;
msg: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_execute2 = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; dialect: Word; in_sqlda, out_sqlda: PXSQLDA):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_execute2_m = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; in_blr_length: Word; in_blr: PISC_SCHAR; in_msg_type,
in_msg_length: Word; in_msg: PISC_SCHAR; out_blr_length: Word; out_blr: PISC_SCHAR;
out_msg_type, out_msg_length: Word; out_msg: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_fetch = function(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_fetch_m = function(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
blr_length: Word; blr: PISC_SCHAR; msg_type, msg_length: Word; msg: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_finish = function(db_handle: Pisc_db_handle): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_free_statement = function(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
option: Word): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_insert = function(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_insert_m = function(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
blr_length: Word; blr: PISC_SCHAR; msg_type, msg_length: Word; msg: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_prepare = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; length: Word; string_: PISC_SCHAR; dialect: Word;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_prepare_m = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; length: Word; string_: PISC_SCHAR; dialect, item_length: Word;
items: PISC_SCHAR; buffer_length: Word; buffer: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_release = function(user_status: PISC_STATUS; name: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_set_cursor_name = function(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
cursor: PISC_SCHAR; type_: Word): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_sql_info = function(user_status: PISC_STATUS; stmt_handle: Pisc_stmt_handle;
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint; buffer: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_close = function(user_status: PISC_STATUS; name: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_declare = function(user_status: PISC_STATUS;
stmt_name, cursor: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_describe = function(user_status: PISC_STATUS; stmt_name: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_describe_bind = function(user_status: PISC_STATUS; stmt_name: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_execute = function(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
stmt_name: PISC_SCHAR; dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_execute_immed = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; length: Word; string_: PISC_SCHAR; dialect: Word;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_execute2 = function(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
stmt_name: PISC_SCHAR; dialect: Word; in_sqlda, out_sqlda: PXSQLDA): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_fetch = function(user_status: PISC_STATUS; cursor_name: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_insert = function(user_status: PISC_STATUS; cursor_name: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_open = function(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
cursor_name: PISC_SCHAR; dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_open2 = function(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
cursor_name: PISC_SCHAR; dialect: Word; in_sqlda, out_sqlda: PXSQLDA): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_prepare = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; stmt_name: PISC_SCHAR; length: Word; string_: PISC_SCHAR;
dialect: Word; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_embed_dsql_release = function(user_status: PISC_STATUS;
stmt_name: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_encode_date = procedure(times_arg: PCTimeStructure; date: PISC_QUAD);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_encode_sql_date = procedure(times_arg: PCTimeStructure; date: PISC_DATE);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_encode_sql_time = procedure(times_arg: PCTimeStructure; time: PISC_TIME);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_encode_timestamp = procedure(times_arg: PCTimeStructure;
timestamp: PISC_TIMESTAMP); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
{$IF DEFINED(ANDROID)}
Tisc_event_block = function(var event_buffer, result_buffer: PISC_UCHAR; count: ISC_USHORT;
v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15: PISC_UCHAR): ISC_LONG; cdecl;
{$ELSE}
Tisc_event_block = function(var event_buffer, result_buffer: PISC_UCHAR;
count: ISC_USHORT): ISC_LONG; cdecl varargs;
{$ENDIF}
Tisc_event_counts = procedure(ser_status: PISC_STATUS; buffer_length: ISC_SHORT;
event_buffer, result_buffer: PISC_UCHAR); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_execute = function(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle;
name: PISC_SCHAR; sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_execute_immediate = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; length: PSmallint; string_: PISC_SCHAR):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_expand_dpb = procedure(dpb: PPISC_SCHAR; dpb_size: PSmallint; name_buffer: PPISC_SCHAR); cdecl;
Tisc_fetch = function(user_status: PISC_STATUS; name: PISC_SCHAR; sqlda: PXSQLDA):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_free = function(blk: Pointer): ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_ftof = function(string_: PISC_SCHAR; length1: Word; field: PISC_SCHAR;
length2: Word): ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_get_segment = function(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle; var length: Word;
buffer_length: Word; buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_get_slice = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle; tra_handle: Pisc_tr_handle;
array_id: PISC_QUAD; sdl_length: Smallint; sdl: PISC_SCHAR; param_length: Smallint; param: PISC_LONG;
slice_length: ISC_LONG; slice: Pointer; return_length: PISC_LONG): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// FB >= 2.0 returns ISC_LONG, others - ISC_STATUS
Tisc_interprete = function(buffer: PISC_SCHAR; var status_vector: PISC_STATUS):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tfb_interpret = function(buffer: PISC_SCHAR; v: Cardinal; var status_vector: PISC_STATUS):
ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_modify_dpb = function(dpb: PPISC_SCHAR; dpb_length: PSmallint; type_: Word;
str: PISC_SCHAR; str_len: Smallint): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// FB >= 2.0 returns ISC_STATUS, others - Integer
Tisc_modify_user = function(status: PISC_STATUS;
user_data: PUSER_SEC_DATA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_open = function(user_status: PISC_STATUS; trans_handle: Pisc_tr_handle; name: PISC_SCHAR;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_open_blob = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blob_handle: Pisc_blob_handle;
blob_id: PISC_QUAD): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_open_blob2 = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blob_handle: Pisc_blob_handle; blob_id: PISC_QUAD; bpb_length: ISC_USHORT;
bpb: PISC_UCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_portable_integer = function(ptr: PISC_UCHAR; length: Smallint): ISC_INT64;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_prepare = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
trans_handle: Pisc_tr_handle; name: PISC_SCHAR; length: PSmallint; string_: PISC_SCHAR;
sqlda: PXSQLDA): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_prepare_transaction = function(user_status: PISC_STATUS;
tra_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_prepare_transaction2 = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
msg_length: ISC_USHORT; msg: PISC_UCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_print_blr = function(blr: PISC_SCHAR; callback: isc_callback; callback_argument: Pointer;
language: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_print_sqlerror = procedure(sqlcode: ISC_SHORT; status_vector: PISC_STATUS);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_print_status = function(status_vector: PISC_STATUS): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_put_segment = function(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle;
buffer_length: Word; buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_put_slice = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle; tra_handle: Pisc_tr_handle;
array_id: PISC_QUAD; sdl_length: Smallint; sdl: PISC_SCHAR; param_length: Smallint; param: PISC_LONG;
slice_length: ISC_LONG; slice: Pointer): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_qtoq = procedure(quad1, quad2: PISC_QUAD); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_que_events = function(user_status: PISC_STATUS; handle: Pisc_db_handle; id: PISC_LONG;
length: Smallint; events: PISC_UCHAR; ast: isc_callback; arg: Pointer):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_receive = function(user_status: PISC_STATUS; req_handle: Pisc_req_handle; msg_type,
msg_length: Smallint; msg: Pointer; level: Smallint): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_reconnect_transaction = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; length: Smallint; id: PISC_SHORT): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_release_request = function(user_status: PISC_STATUS;
req_handle: Pisc_req_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_request_info = function(user_status: PISC_STATUS; req_handle: Pisc_req_handle; level,
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint;
buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_rollback_retaining = function(status_vector: PISC_STATUS;
trans_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_rollback_transaction = function(user_status: PISC_STATUS;
tra_handle: Pisc_tr_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_seek_blob = function(user_status: PISC_STATUS; blob_handle: Pisc_blob_handle; mode: Smallint;
offset: ISC_LONG; Result_: PISC_LONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_send = function(user_status: PISC_STATUS; req_handle: Pisc_req_handle; msg_type,
msg_length: Smallint; msg: Pointer; level: Smallint):
ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_service_attach = function(status_vector: PISC_STATUS; service_length: Word;
service_name: PISC_SCHAR; handle: Pisc_svc_handle; spb_length: Word;
spb: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_service_detach = function(status_vector: PISC_STATUS;
handle: Pisc_svc_handle): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_service_query = function(status_vector: PISC_STATUS; svc_handle: Pisc_svc_handle;
reserved: Pisc_resv_handle; send_spb_length: Word; send_spb: PISC_SCHAR; request_spb_length: Word;
request_spb: PISC_SCHAR; buffer_length: Word; buffer: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_service_start = function(status_vector: PISC_STATUS; svc_handle: Pisc_svc_handle;
reserved: Pisc_resv_handle; spb_length: Word; spb: PISC_SCHAR): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_set_debug = procedure(flag: Integer); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_sql_interprete = procedure(SQLCODE: Smallint; buffer: PISC_SCHAR;
buffer_length: Smallint); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_sqlcode = function(user_status: PISC_STATUS): ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_start_and_send = function(user_status: PISC_STATUS; req_handle: Pisc_req_handle;
tra_handle: Pisc_tr_handle; msg_type, msg_length: Smallint; msg: Pointer;
level: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_start_multiple = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
count: Smallint; vector: PISCTEB): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_start_request = function(user_status: PISC_STATUS; req_handle: Pisc_req_handle;
tra_handle: Pisc_tr_handle; level: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_start_transaction = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
count: Smallint; db_handle: Pisc_db_handle; tpb_length: ISC_USHORT; tpb_ad: PISC_SCHAR): ISC_STATUS; cdecl;
Tisc_transact_request = function(user_status: PISC_STATUS; db_handle: Pisc_db_handle;
tra_handle: Pisc_tr_handle; blr_length: Word; blr: PISC_SCHAR; in_msg_length: Word; in_msg: PISC_SCHAR;
out_msg_length: Word; out_msg: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_transaction_info = function(user_status: PISC_STATUS; tra_handle: Pisc_tr_handle;
item_length: Smallint; items: PISC_SCHAR; buffer_length: Smallint;
buffer: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_unwind_request = function(user_status: PISC_STATUS; req_handle: Pisc_tr_handle;
level: Smallint): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_vax_integer = function(ptr: PISC_SCHAR; length: Smallint): ISC_LONG;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_version = function(db_handle: Pisc_db_handle; callback: isc_callback;
callback_argument: Pointer): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_vtof = procedure(string1, string2: PISC_SCHAR; length: Word);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_vtov = procedure(string1, string2: PISC_SCHAR; length: Smallint);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_wait_for_event = function(user_status: PISC_STATUS; handle: Pisc_db_handle;
length: Smallint; events, buffer: PISC_UCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_reset_fpe = function(fpe_status: ISC_USHORT): ISC_LONG; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_get_client_version = procedure(version: PISC_SCHAR); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_get_client_major_version = function: Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_get_client_minor_version = function: Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_release_savepoint = function(status: PISC_STATUS; TrHandle: Pisc_tr_handle;
name: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_rollback_savepoint = function(status: PISC_STATUS; TrHandle: Pisc_tr_handle;
name: PISC_SCHAR; Option: Word): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_start_savepoint = function(status: PISC_STATUS; TrHandle: Pisc_tr_handle;
name: PISC_SCHAR): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tisc_dsql_batch_execute = function(status: PISC_STATUS; TrHandle: Pisc_tr_handle;
stmt_handle: Pisc_stmt_handle; dialect: Word; insqlda: PXSQLDA; number_of_rows: Word;
batch_vars: PXSQLVAR_V2; rows_affected: PISC_ULONG): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tfb_sqlstate = procedure (sqlstate: PISC_SCHAR; status_vector: PISC_STATUS);
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tfb_cancel_operation = function(status: PISC_STATUS; db_handle: Pisc_db_handle;
options: ISC_USHORT): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tfb_shutdown = function(timeout: Cardinal; reason: Integer): Integer;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tfb_shutdown_callback = function (status: PISC_STATUS; callback_function: FB_SHUTDOWN_CALLBACK_FUNC;
mask: Integer; arg: Pointer): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tfb_ping = function(status: PISC_STATUS; db_handle: Pisc_db_handle): ISC_STATUS;
{$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tfb_get_database_handle = function (status: PISC_STATUS; db_handle: Pisc_db_handle;
data: Pointer): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
Tfb_get_transaction_handle = function (status: PISC_STATUS; tr_handle: Pisc_tr_handle;
data: Pointer): ISC_STATUS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
function GETB(p: PBSTREAM; bg: TBLOB_get): ISC_SCHAR;
function PUTB(x: ISC_SCHAR; p: PBSTREAM; bp: TBLOB_put): Integer;
function PUTBX(x: ISC_SCHAR; p: PBSTREAM; bp: TBLOB_put): Integer;
implementation
{$IFDEF FireDAC_IB_STATIC}
{$IFDEF MSWINDOWS}
uses
System.Win.Crtl;
{$ENDIF}
{$ENDIF}
{-------------------------------------------------------------------------------}
function XSQLDA_LENGTH_V1(n: Integer): Integer;
begin
Result := SizeOf(XSQLDA_V1) + ((n - 1) * SizeOf(XSQLVAR_V1));
end;
{-------------------------------------------------------------------------------}
function XSQLDA_LENGTH_V2(n: Integer): Integer;
begin
Result := SizeOf(XSQLDA_V2) + ((n - 1) * SizeOf(XSQLVAR_V2));
end;
{-------------------------------------------------------------------------------}
function XSQLVAR_LENGTH(num_rows, num_vars: Integer): Integer;
begin
Result := SizeOf(XSQLVAR_V2) * num_rows * num_vars;
end;
{-------------------------------------------------------------------------------}
procedure ADD_SPB_LENGTH(var p: PISC_UCHAR; length: Integer);
begin
p^ := ISC_UCHAR(length);
Inc(p);
p^ := ISC_UCHAR(length shr 8);
Inc(p);
end;
{-------------------------------------------------------------------------------}
procedure ADD_SPB_NUMERIC(var p: PISC_UCHAR; data: Integer);
begin
p^ := ISC_UCHAR(data);
Inc(p);
p^ := ISC_UCHAR(data shr 8);
Inc(p);
p^ := ISC_UCHAR(data shr 16);
Inc(p);
p^ := ISC_UCHAR(data shr 24);
Inc(p);
end;
{-------------------------------------------------------------------------------}
function GETB(p: PBSTREAM; bg: TBLOB_get): ISC_SCHAR;
begin
Dec(p^.bstr_cnt);
if p^.bstr_cnt >= 0 then begin
Result := p^.bstr_ptr^ and $FF;
Inc(p^.bstr_ptr);
end
else
Result := bg(p);
end;
{-------------------------------------------------------------------------------}
function PUTB(x: ISC_SCHAR; p: PBSTREAM; bp: TBLOB_put): Integer;
var
lBP: Boolean;
begin
if x = ISC_SCHAR(#10) then
lBP := True
else begin
Dec(p^.bstr_cnt);
lBP := p^.bstr_cnt = 0;
end;
if lBP then
Result := bp(x, p)
else begin
p^.bstr_ptr^ := x;
Inc(p^.bstr_ptr);
Result := x;
end;
end;
{-------------------------------------------------------------------------------}
function PUTBX(x: ISC_SCHAR; p: PBSTREAM; bp: TBLOB_put): Integer;
begin
Dec(p^.bstr_cnt);
if p^.bstr_cnt = 0 then
Result := bp(x, p)
else begin
p^.bstr_ptr^ := x;
Inc(p^.bstr_ptr);
Result := x;
end;
end;
end.
|
unit SearchParamDefSubParamQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TParamDefSubParamW = class(TDSWrap)
private
FID: TFieldWrap;
FIDSubParameter: TFieldWrap;
FIsDefault: TFieldWrap;
FName: TFieldWrap;
FParameterType: TFieldWrap;
FParamSubParamID: TFieldWrap;
FTableName: TFieldWrap;
FTranslation: TFieldWrap;
FValue: TFieldWrap;
FValueT: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
property ID: TFieldWrap read FID;
property IDSubParameter: TFieldWrap read FIDSubParameter;
property IsDefault: TFieldWrap read FIsDefault;
property Name: TFieldWrap read FName;
property ParameterType: TFieldWrap read FParameterType;
property ParamSubParamID: TFieldWrap read FParamSubParamID;
property TableName: TFieldWrap read FTableName;
property Translation: TFieldWrap read FTranslation;
property Value: TFieldWrap read FValue;
property ValueT: TFieldWrap read FValueT;
end;
TQuerySearchParamDefSubParam = class(TQueryBase)
private
FW: TParamDefSubParamW;
{ Private declarations }
protected
public
constructor Create(AOwner: TComponent); override;
function SearchByID(AParameterID: Integer;
TestResult: Integer = -1): Integer;
property W: TParamDefSubParamW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TQuerySearchParamDefSubParam.Create(AOwner: TComponent);
begin
inherited;
FW := TParamDefSubParamW.Create(FDQuery);
end;
function TQuerySearchParamDefSubParam.SearchByID(AParameterID: Integer;
TestResult: Integer = -1): Integer;
begin
Assert(AParameterID > 0);
Result := SearchEx([TParamRec.Create(W.ID.FullName, AParameterID)],
TestResult);
end;
constructor TParamDefSubParamW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'p.ID', '', True);
FIDSubParameter := TFieldWrap.Create(Self, 'IDSubParameter');
FIsDefault := TFieldWrap.Create(Self, 'IsDefault');
FName := TFieldWrap.Create(Self, 'Name');
FParameterType := TFieldWrap.Create(Self, 'ParameterType');
FParamSubParamID := TFieldWrap.Create(Self, 'ParamSubParamID');
FTableName := TFieldWrap.Create(Self, 'TableName');
FTranslation := TFieldWrap.Create(Self, 'Translation');
FValue := TFieldWrap.Create(Self, 'Value', 'Наименование');
FValueT := TFieldWrap.Create(Self, 'ValueT');
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Компоненты медиа-преобразования }
{ }
{ <Область> Мультимедиа }
{ }
{ <Задача> Преобразователь медиа-потока в формате BMP. Склеивает кадры }
{ от разных каналов в один, панорамный }
{ Реализация. }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 21.01.2011 }
{ }
{ <Примечание> Отсутствует }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaProcessing.Panorama.RGB.Impl;
interface
uses SysUtils,Windows,Classes, Generics.Collections, SyncObjs,
MediaProcessing.Definitions,MediaProcessing.Global,MediaProcessing.Panorama.RGB;
//{$DEFINE CHECK_WITH_OLD_VER}
const
MaxPieces = 8; //Максимальное кол-во поддерживаемых каналов для склеивания
type
//Класс для описания части панорамы. Каждая часть закрепляется за соответсвующим входным каналом
TPanoramaPieceInfo = class
private
FLock: TCriticalSection;
FDib: TBytes;
FDibSize: cardinal;
FIndex: integer;
FXOffest: integer;
FYOffset: integer;
FBitmapInfoHeader: TBitmapInfoHeader;
FReversedVertical: boolean;
FLastDibDateTime : TDateTime;
public
Valid: boolean;
procedure SetHeader(const aHeader:TBitmapInfoHeader; aReversedVertical: boolean);
procedure SetOffsets(aXOffest,aYOffset: integer);
procedure StoreDib(aDib: pointer; aDibSize: integer);
function StitchedWidth: integer;
function StitchedHeght: integer;
constructor Create(aIndex: integer);
destructor Destroy; override;
procedure Lock;
procedure Unlock;
end;
//Собственно реализация медиа-процессора
TMediaProcessor_Panorama_Rgb_Impl =class (TMediaProcessor_Panorama_Rgb,IMediaProcessorImpl)
private
FResultBitmapDIB: TBytes;
FResultBitmapReversedVertical: boolean;
FResultBitmapHeader: TBitmapInfoHeader;
FPieceInfos: array [0..MaxPieces-1] of TPanoramaPieceInfo;
FPieceCount: integer;
FLastOutFrameTicks: cardinal;
FAutoImageStitchingThread: TThread;
protected
function CopyPieceToImage(const aBitmapInfoHeader: TBitmapInfoHeader; aDib: PByte; aReversedVertical: boolean; aPieceIndex: integer):boolean;
procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); override;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses Math,DateUtils, BitPlane,{$IFDEF CHECK_WITH_OLD_VER}CMSA, {$ENDIF} Cmsa.Correlator, Cmsa.Image, uBaseClasses, ThreadNames;
type
//Поток для выполнения коррекции границ склеивания смежных фрагментов панорамы
//Коррекция выпляется в фоновом режиме, вне зависимости от основной задачи формирования картинки
TImageStitchingThread = class (TThread)
private
FOwner: TMediaProcessor_Panorama_Rgb_Impl;
procedure Stitch(aLeftImage,aRightImage: TPanoramaPieceInfo; var aPositionChanged: boolean);
function Iteration: integer;
protected
constructor Create(aOwner: TMediaProcessor_Panorama_Rgb_Impl);
procedure Execute; override;
end;
{ TImageStitchingThread }
constructor TImageStitchingThread.Create(aOwner: TMediaProcessor_Panorama_Rgb_Impl);
begin
FOwner:=aOwner;
inherited Create(false);
end;
procedure TImageStitchingThread.Execute;
var
aStart: cardinal;
aEnd: cardinal;
aDuration: int64;
aFirstSuccess: boolean;
x: integer;
i: Integer;
aIsNewImage: boolean;
aLastIterationDateTime: TDateTime;
aPiece: TPanoramaPieceInfo;
begin
SetCurrentThreadName(ClassName);
aFirstSuccess:=false;
aLastIterationDateTime:=Now;
while not Terminated do
begin
aStart:=GetTickCount;
try
x:=Iteration;
aLastIterationDateTime:=Now;
//Пытаемся достичь хоть какого-то результата. Первая склейка должна пройти пораньше, иначе она отложится на несколько минут (FAutoImageStitchingIntervalSecs)
if not aFirstSuccess then
begin
if x=0 then
begin
Pause(1000);
continue;
end;
aFirstSuccess:=true;
end;
except
on E:Exception do
FOwner.SetLastError('Корреляция: '+E.Message);
end;
aEnd:=GetTickCount;
aDuration:=aEnd-aStart;
if (aDuration<0) then
aDuration:=0;
aDuration:=FOwner.FAutoImageStitchingIntervalSecs*1000-aDuration;
if aDuration>0 then
Pause(aDuration);
//Ждем свежих данных
while not Terminated do
begin
aIsNewImage:=false;
for i := 0 to High(FOwner.FPieceInfos)-1 do
begin
aPiece:=FOwner.FPieceInfos[i];
aPiece.Lock;
try
if aPiece.Valid then
//Если есть свежее изображение
if aPiece.FLastDibDateTime>aLastIterationDateTime then
begin
aIsNewImage:=true;
break;
end;
finally
aPiece.Unlock;
end;
end;
if aIsNewImage then //обновилась хотя бы одна картинка
break;
Pause(100);
end;
end;
end;
function TImageStitchingThread.Iteration: integer;
var
aPositionChanged: boolean;
aFormat: TMediaStreamDataHeader;
i: Integer;
begin
aPositionChanged:=false;
result:=0;
for i := 0 to High(FOwner.FPieceInfos)-1 do
begin
if Terminated then
break;
if not (FOwner.FPieceInfos[i]).Valid then
continue;
if not (FOwner.FPieceInfos[i+1]).Valid then
continue;
FOwner.FPieceInfos[i].Lock;
try
FOwner.FPieceInfos[i+1].Lock;
try
Stitch(FOwner.FPieceInfos[i],FOwner.FPieceInfos[i+1],aPositionChanged);
inc(result);
finally
FOwner.FPieceInfos[i+1].Unlock;
end;
finally
FOwner.FPieceInfos[i].Unlock;
end;
end;
if (aPositionChanged) then
begin
for i := 1 to High(FOwner.FPieceInfos) do
begin
if FOwner.FPieceInfos[i].Valid then
begin
aFormat.Assign(FOwner.FPieceInfos[i].FBitmapInfoHeader);
(*
FOwner.Process(
@FOwner.FPieceInfos[i].FDib[0],
FOwner.FPieceInfos[i].FDibSize,
aFormat,
nil,0);
*)
end;
end;
end;
end;
function DoSuperPos (
const aLeftBitmapHeader: TBitmapInfoHeader; //Заголовок левого битмапа
aLeftDIB: PByte; //Точки левого битмапа. Размер области памяти передается в BITMAPINFOHEADER::ImageSize
const aRightBitmapHeader: TBitmapInfoHeader; //Заголовок правого битмапа
aRightDIB:PByte; //Точки правого битмапа.
pcntMaxWinWidth, //насколько процентов по горизонтали от свой ширины изображения могут пересекаться.
pcntMaxYDisp: integer; //насколько процентов по вертикали изображение может сдвигаться
out aClmnIS: integer; //Перекрытие столбцов. Указывается положительная величина, с которой правая картинка наезжает на левую
out aVerticalOffset: integer; //Смещение по вертикали правой картинки относительно левой. >0 - правая ниже левой. <0 - правая выше левой
out aCorrelation: double //Коэффициент корреляции
):integer;
var
image_l: TCmsaImage;
image_r: TCmsaImage;
aCorrelator: TCorrelator ;
Params: TPicturesMergingParams;
begin
image_l:=TCmsaImage.Create;
image_r:=TCmsaImage.Create;
try
image_l.copyFrom (@aLeftBitmapHeader, aLeftDIB);
image_r.copyFrom (@aRightBitmapHeader, aRightDIB);
aCorrelator:=TCorrelator.Create;
try
Params:=aCorrelator.CorrelateWith(50, 25, image_l, image_r);
aClmnIS := image_l.Width- Params.disp.x;
aVerticalOffset := -Params.disp.y;
aCorrelation := Params.correlation;
finally
aCorrelator.Free;
end;
finally
image_l.Free;
image_r.Free;
end;
result:=0;
end;
procedure TImageStitchingThread.Stitch(aLeftImage,aRightImage: TPanoramaPieceInfo; var aPositionChanged: boolean);
var
{$IFDEF CHECK_WITH_OLD_VER}
aCmsaResult1: CMSA_RESULT;
aHorizontalOffs1: integer;
aVerticalOffs1: integer;
aCorrelation1: double;
{$ENDIF}
aCmsaResult2: integer;
aHorizontalOffs2: integer;
aVerticalOffs2: integer;
aCorrelation2: double;
begin
if not aLeftImage.Valid then
exit;
if not aRightImage.Valid then
exit;
if aLeftImage.FDibSize=0 then
exit;
if aRightImage.FDibSize=0 then
exit;
if (aLeftImage.FBitmapInfoHeader.biSizeImage<>aLeftImage.FDibSize) then
raise Exception.CreateFmt('Ошибка алгоритма: объявленный (%d байт) и фактический (%d байт) размеры изображения №%d не совпадают',[aLeftImage.FBitmapInfoHeader.biSizeImage,aLeftImage.FDibSize,aLeftImage.FIndex]);
if (aRightImage.FBitmapInfoHeader.biSizeImage<>aRightImage.FDibSize) then
raise Exception.CreateFmt('Ошибка алгоритма: объявленный (%d байт) и фактический (%d байт) размеры изображения №%d не совпадают',[aRightImage.FBitmapInfoHeader.biSizeImage,aRightImage.FDibSize,aRightImage.FIndex]);
//Test
//x: TBitPlaneDesc;
//x.Init(aLeftImage.FDib,aLeftImage.FDibSize,aLeftImage.FBitmapInfoHeader.biWidth,aLeftImage.FBitmapInfoHeader.biHeight,aLeftImage.FBitmapInfoHeader.biBitCount);
//x.CopyToFileAsBitmap('C:\left.bmp',false);
//x.Init(aRightImage.FDib,aRightImage.FDibSize,aRightImage.FBitmapInfoHeader.biWidth,aRightImage.FBitmapInfoHeader.biHeight,aRightImage.FBitmapInfoHeader.biBitCount);
//x.CopyToFileAsBitmap('C:\Right.bmp',false);
//aLeftBitplane.Init(aLeftImage.FDib,aLeftImage.FDibSize,aLeftImage.FBitmapInfoHeader.biWidth,aLeftImage.FBitmapInfoHeader.biHeight,aLeftImage.FBitmapInfoHeader.biBitCount);
//aLeftGreyDib:=aLeftBitplane.GetGrayscaleDIB(cgLuminosity);
{$IFDEF CHECK_WITH_OLD_VER}
aHorizontalOffs1:=0;
aVerticalOffs1:=0;
aCorrelation1:=1;
aCmsaResult1:=CMSA.superpos(
aLeftImage.FBitmapInfoHeader,
@aLeftImage.FDib[0],
aRightImage.FBitmapInfoHeader,
@aRightImage.FDib[0],
aHorizontalOffs1,
aVerticalOffs1,
aCorrelation1);
{$ENDIF}
aHorizontalOffs2:=0;
aVerticalOffs2:=0;
aCorrelation2:=1;
aCmsaResult2:=DoSuperPos(
aLeftImage.FBitmapInfoHeader,
@aLeftImage.FDib[0],
aRightImage.FBitmapInfoHeader,
@aRightImage.FDib[0],
FOwner.FAutoImageStitchingMaxWinWidthPercent,
FOwner.FAutoImageStitchingMaxYDispPercent,
aHorizontalOffs2,
aVerticalOffs2,
aCorrelation2);
{$IFDEF CHECK_WITH_OLD_VER}
Assert(aCmsaResult1=aCmsaResult2);
{$ENDIF}
if aCmsaResult2=0 then
begin
{$IFDEF CHECK_WITH_OLD_VER}
Assert(aVerticalOffs1=aVerticalOffs2);
Assert(aHorizontalOffs1=aHorizontalOffs2);
Assert(Round(aCorrelation1*1000)=Round(aCorrelation2*1000));
{$ENDIF}
if (aHorizontalOffs2<>aRightImage.FXOffest) or (aVerticalOffs2<>aRightImage.FYOffset) then
begin
aRightImage.SetOffsets(aHorizontalOffs2,aVerticalOffs2);
aPositionChanged:=true;
end;
end
else
raise Exception.CreateFmt('Error code =%d',[aCmsaResult2]);
end;
{ TMediaProcessor_Panorama_Rgb_Impl }
function TMediaProcessor_Panorama_Rgb_Impl.CopyPieceToImage(const aBitmapInfoHeader: TBitmapInfoHeader; aDib: PByte; aReversedVertical: boolean; aPieceIndex: integer):boolean;
var
aPanoramaWidth: integer;
aPanoramaHeight: integer;
i: integer;
x,y,ys: Integer;
aDestStride,aSourceStride: integer;
aPtrDst,aPtrSrc: PByte;
aPieceWidth: integer;
begin
result:=false;
//Считаем, из скольки кусочков будет состоять наша панорама, ища самый последний валидный кусочек
FPieceCount:=max(FPieceCount,aPieceIndex+1);
aPanoramaWidth:=0;
aPanoramaHeight:=aBitmapInfoHeader.biHeight;
//Смотрим, чтобы внутри диапазона все кусочки существовали
for i := 0 to FPieceCount-1 do
begin
if FPieceInfos[i].Valid then
begin
inc(aPanoramaWidth,FPieceInfos[i].StitchedWidth);
aPanoramaHeight:=min(aPanoramaHeight,FPieceInfos[i].StitchedHeght);
end
else begin //Если мы имеем кусочка, то предположим, что его размер равен нашему
inc(aPanoramaWidth,aBitmapInfoHeader.biWidth);
end;
end;
if (aPanoramaWidth<=0) or (aPanoramaHeight<=0) then
exit;
//Если размеры не сходятся с
if (aPanoramaWidth<>FResultBitmapHeader.biWidth) or (aPanoramaHeight<>FResultBitmapHeader.biHeight) then
begin
FResultBitmapHeader.biWidth:=aPanoramaWidth;
FResultBitmapHeader.biHeight:=aPanoramaHeight;
FResultBitmapHeader.biBitCount:=24;
FResultBitmapHeader.biSizeImage:=GetRGBSize(aPanoramaWidth,aPanoramaHeight,24);
FResultBitmapDIB:=nil;
SetLength(FResultBitmapDIB,FResultBitmapHeader.biSizeImage);
if FPieceInfos[0].Valid then
FResultBitmapReversedVertical:=FPieceInfos[0].FReversedVertical
else
FResultBitmapReversedVertical:=aReversedVertical;
end;
x:=0;
for i := 0 to aPieceIndex-1 do
if FPieceInfos[i].Valid then
inc(x,FPieceInfos[i].StitchedWidth)
else
inc(x,aBitmapInfoHeader.biWidth);
if aPieceIndex>0 then
dec(x,FPieceInfos[aPieceIndex].FXOffest);
if (x<0) then //Картинка вышла в отрицательную область (слишком "влево")
exit;
//Вставляем картинку
aSourceStride:=GetRGBLineSize(aBitmapInfoHeader.biWidth,aBitmapInfoHeader.biBitCount);
aDestStride:=GetRGBLineSize(FResultBitmapHeader.biWidth,FResultBitmapHeader.biBitCount);
aPieceWidth:=aBitmapInfoHeader.biWidth;
if (aPieceIndex<MaxPieces-1) then
if (FPieceInfos[aPieceIndex+1].Valid) then
if FPieceInfos[aPieceIndex+1].FXOffest>0 then
dec(aPieceWidth,FPieceInfos[aPieceIndex+1].FXOffest);
//TODO использовать готовый метод из bitplane
for y := 0 to aPanoramaHeight-1 do
begin
ys:=y+FPieceInfos[aPieceIndex].FYOffset;
if (ys<0) then
continue;
if (ys>=aBitmapInfoHeader.biHeight) then
break;
aPtrSrc:=aDib+(ys*aSourceStride);
aPtrDst:=@FResultBitmapDIB[y*aDestStride+x*3];
CopyMemory(aPtrDst,aPtrSrc,aPieceWidth*3);
end;
result:=true;
end;
constructor TMediaProcessor_Panorama_Rgb_Impl.Create;
var
i: Integer;
begin
inherited;
FResultBitmapHeader.biSize:=sizeof(FResultBitmapHeader);
for i := 0 to High(FPieceInfos) do
FPieceInfos[i]:=TPanoramaPieceInfo.Create(i);
end;
destructor TMediaProcessor_Panorama_Rgb_Impl.Destroy;
var
i: Integer;
begin
inherited;
FResultBitmapDIB:=nil;
FreeAndNil(FAutoImageStitchingThread);
for i := 0 to High(FPieceInfos) do
FreeAndNil(FPieceInfos[i]);
end;
procedure TMediaProcessor_Panorama_Rgb_Impl.Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal);
var
aStartTicks: cardinal;
aDT: TDateTime;
aPiece: TPanoramaPieceInfo;
begin
aStartTicks:=GetTickCount;
TArgumentValidation.NotNil(aInData);
Assert(aInFormat.biMediaType=mtVideo);
Assert(aInFormat.biStreamType=stRGB);
aOutData:=nil;
aOutDataSize:=0;
aOutInfo:=nil;
aOutInfoSize:=0;
aOutFormat:=aInFormat;
if (aInFormat.VideoBitCount<>24) then
begin
SetLastError(Format('Формат RGB должен имет глубину цвета 24 бита. Фактический формат - %d бит',[aInFormat.VideoBitCount]));
aOutFormat.Clear;
exit;
end;
if aInFormat.Channel>=MaxPieces then
exit; //Больше MaxPieces панорамных картинок не склеиваем
if not CopyPieceToImage(aInFormat.ToBitmapInfoHeader(aInDataSize),aInData,aInFormat.VideoReversedVertical, aInFormat.Channel) then
exit;
aPiece:=FPieceInfos[aInFormat.Channel];
aPiece.Lock;
try
aPiece.SetHeader(aInFormat.ToBitmapInfoHeader(aInDataSize),aInFormat.VideoReversedVertical);
if (FAutoImageStitching) then
begin
aDT:=aPiece.FLastDibDateTime;
if (aDT=0) or ((Now-aDT)*MSecsPerDay>FAutoImageStitchingIntervalSecs*1000-1000) then
aPiece.StoreDib(aInData,aInDataSize)
else begin
//Assert(true); //Для отладки
end;
end;
finally
aPiece.Unlock;
end;
if aStartTicks-FLastOutFrameTicks>cardinal(1000 div FFPSValue) then
begin
aOutData:=FResultBitmapDIB;
aOutDataSize:=FResultBitmapHeader.biSizeImage;
aOutFormat.Assign(FResultBitmapHeader);
aOutFormat.TimeStamp:=GetTickCount;
aOutFormat.TimeKoeff:=1;
aOutFormat.VideoReversedVertical:=FResultBitmapReversedVertical;
FLastOutFrameTicks:=aStartTicks;
end;
//Если поток сопряжения картинок еще не запущен - запускаем
if FAutoImageStitching then
if FAutoImageStitchingThread=nil then
FAutoImageStitchingThread:=TImageStitchingThread.Create(self);
end;
{ TPanoramaPieceInfo }
constructor TPanoramaPieceInfo.Create(aIndex: integer);
begin
FLock:=TCriticalSection.Create;
FIndex:=aIndex;
end;
destructor TPanoramaPieceInfo.Destroy;
begin
FreeAndNil(FLock);
inherited;
end;
procedure TPanoramaPieceInfo.Lock;
begin
FLock.Enter;
end;
procedure TPanoramaPieceInfo.SetHeader(const aHeader: TBitmapInfoHeader; aReversedVertical: boolean);
begin
Lock;
try
FBitmapInfoHeader:=aHeader;
FReversedVertical:=aReversedVertical;
Valid:=true;
finally
Unlock;
end;
end;
procedure TPanoramaPieceInfo.SetOffsets(aXOffest,aYOffset: integer);
begin
FXOffest:=aXOffest;
FYOffset:=aYOffset;
end;
function TPanoramaPieceInfo.StitchedHeght: integer;
begin
Lock;
try
result:=FBitmapInfoHeader.biHeight+Abs(FYOffset);
finally
Unlock;
end;
end;
function TPanoramaPieceInfo.StitchedWidth: integer;
begin
Lock;
try
result:=FBitmapInfoHeader.biWidth-FXOffest;
finally
Unlock;
end;
end;
procedure TPanoramaPieceInfo.StoreDib(aDib: pointer; aDibSize: integer);
begin
Lock;
try
FLastDibDateTime:=Now;
if Length(FDib)<aDibSize then
begin
FDib:=nil;
SetLength(FDib,aDibSize);
end;
CopyMemory(@FDib[0],aDib,aDibSize);
FDibSize:=aDibSize;
finally
Unlock;
end;
end;
procedure TPanoramaPieceInfo.Unlock;
begin
FLock.Leave;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessorImplementation(TMediaProcessor_Panorama_Rgb_Impl);
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit SvrSockRequest;
interface
uses Web.HTTPApp, IdTCPClient;
type
TRequestConnection = class(TObject)
private
FClient: TIdTCPClient;
public
constructor Create(APort: Integer);
destructor Destroy; override;
procedure Disconnect;
function Connect: Boolean;
procedure Request(ARequest: TWebRequest; AResponse: TWebResponse; AUsingStub: Boolean);
end;
implementation
uses SockRequestInterpreter, SockTransport, IndySockTransport, System.Classes, System.SysUtils,
IdException, IdStack, SockConst;
{ TRequestConnection }
function TRequestConnection.Connect: Boolean;
begin
try
FClient.Connect;
except
on E: EIdSocketError do
case E.LastError of
10061 { Connection refused } :
begin
Result := False;
Exit;
end;
end;
else
raise;
end;
Result := True;
end;
procedure TRequestConnection.Disconnect;
begin
FClient.Disconnect;
end;
constructor TRequestConnection.Create(APort: Integer);
begin
inherited Create;
FClient := TIdTCPClient.Create(nil);
FClient.Port := APort;
FClient.Host := '127.0.0.1';
end;
procedure TRequestConnection.Request(ARequest: TWebRequest; AResponse: TWebResponse; AUsingStub: Boolean);
var
DataBlockInterpreter: TLogWebAppDataBlockInterpreter;
Transport: ITransport;
begin
try
Transport := TIndyTCPConnectionTransport.Create(FClient);
try
DataBlockInterpreter := TLogWebAppDataBlockInterpreter.Create(TLogSendDataBlock.Create(Transport));
try
DataBlockInterpreter.CallHandleRequest(ARequest, AResponse, AUsingStub);
finally
DataBlockInterpreter.Free;
end;
finally
Transport := nil;
end;
except
on E: Exception do
raise Exception.Create(sSocketRequestError + E.Message);
end;
end;
destructor TRequestConnection.Destroy;
begin
Disconnect;
FClient.Free;
inherited;
end;
end.
|
unit uTravel;
interface
uses
Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd,
System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes,
System.Variants,
FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr;
type
TTravel = class(TCollectionItem)
public
Id: string;
Name: string;
end;
TTravelList = class(TCollection)
public
procedure AddTravel(Id, Name: string);
function ConnectToDb: TSQLConnection;
procedure SaveTravel(Item: TTravel);
procedure LoadAllTravels;
procedure UpdateOrInsert(Item: TTravel);
end;
implementation
{ TTravel }
{ TTravelList }
procedure TTravelList.AddTravel(Id, Name: string);
var
Item: TTravel;
begin
Item := TTravel(self.Add);
Item.Id := Id;
Item.Name := Name;
end;
function TTravelList.ConnectToDb: TSQLConnection;
var
ASQLConnection: TSQLConnection;
Path: string;
begin
ASQLConnection := TSQLConnection.Create(nil);
ASQLConnection.ConnectionName := 'SQLITECONNECTION';
ASQLConnection.DriverName := 'Sqlite';
ASQLConnection.LoginPrompt := false;
ASQLConnection.Params.Values['Host'] := 'localhost';
ASQLConnection.Params.Values['FailIfMissing'] := 'False';
ASQLConnection.Params.Values['ColumnMetaDataSupported'] := 'False';
Createdir(IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) +
IncludeTrailingPathDelimiter('ExampleDb'));
Path := IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) +
IncludeTrailingPathDelimiter('ExampleDb') + 'ExampleDb.db';
ASQLConnection.Params.Values['Database'] := Path;
ASQLConnection.Execute('CREATE TABLE if not exists travels(' +
'TravelId TEXT,' + 'Name TEXT' + ');', nil);
ASQLConnection.Open;
result := ASQLConnection;
end;
procedure TTravelList.LoadAllTravels;
var
ASQLConnection: TSQLConnection;
ResImage: TResourceStream;
RS: TDataset;
Item: TTravel;
begin
ASQLConnection := ConnectToDb;
try
ASQLConnection.Execute('select TravelId,Name from travels', nil, RS);
while not RS.Eof do
begin
Item := TTravel(self.Add);
Item.Id := RS.FieldByName('TravelId').Value;
Item.Name := RS.FieldByName('Name').Value;
RS.Next;
end;
finally
Freeandnil(ASQLConnection);
end;
freeandnil(rs);
end;
procedure TTravelList.SaveTravel(Item: TTravel);
var
i: integer;
DB: TSQLConnection;
Params: TParams;
query: string;
begin
query := 'INSERT INTO travels (TravelId,Name) VALUES (:TravelId,:Name)';
DB := ConnectToDb;
try
for i := 0 to self.Count - 1 do
begin
Params := TParams.Create;
Params.CreateParam(TFieldType.ftString, 'id', ptInput);
Params.ParamByName('id').AsString := TTravel(self.Items[i]).Id;
Params.CreateParam(TFieldType.ftString, 'Name', ptInput);
Params.ParamByName('Name').AsString := TTravel(self.Items[i]).Name;
DB.Execute(query, Params);
Freeandnil(Params);
end;
finally
Freeandnil(DB);
end;
end;
procedure TTravelList.UpdateOrInsert(Item: TTravel);
const
cInsertQuery =
'UPDATE travels SET `TravelId` =:TravelId, `Name`= :Name WHERE Travelid="%s"';
var
query: String;
querity: TSQLQuery;
connect: TSQLConnection;
Guid: TGUID;
begin
connect := ConnectToDb;
querity := TSQLQuery.Create(nil);
try
querity.SQLConnection := connect;
querity.SQL.Text := 'select TravelId from travels where TravelId = "' +
Item.Id + '"';
querity.Open;
if not querity.Eof then
begin
query := Format(cInsertQuery, [Item.Id]);
querity.Params.CreateParam(TFieldType.ftString, 'TravelId', ptInput);
querity.Params.ParamByName('TravelId').AsString := Item.Id;
querity.Params.CreateParam(TFieldType.ftString, 'Name', ptInput);
querity.Params.ParamByName('Name').AsString := Item.Name;
querity.SQL.Text := query;
querity.ExecSQL();
end
else
begin
CreateGUID(Guid);
query := 'INSERT INTO travels (TravelId,Name) VALUES (:TravelId,:Name)';
querity.Params.CreateParam(TFieldType.ftString, 'TravelId', ptInput);
querity.Params.ParamByName('TravelId').AsString := Item.Id;
querity.Params.CreateParam(TFieldType.ftString, 'Name', ptInput);
querity.Params.ParamByName('Name').AsString := Item.Name;
querity.SQL.Text := query;
querity.ExecSQL();
end;
finally
Freeandnil(querity);
end;
Freeandnil(connect);
end;
//
end.
|
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
This component is an analog for TLabel with additional feature to display
the running text instead static label.
}
unit RunText;
interface
{$I SMVersion.inc}
uses
Windows, Classes, Graphics, Controls, ExtCtrls;
type
TDirect = (diLeftToRight, diRightToLeft,
diTopToBottom, diBottomToTop);
TStyleLabel = (slNormal, slLowered, slRaised);
TTextLayout = (tlTop, tlCenter, tlBottom);
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TRunningText = class(TCustomPanel) //TGraphicControl)
private
{ Private declarations }
FTimer: TTimer;
FCurCycle: Integer;
FActive: Boolean;
FDirect: TDirect;
FStyleLabel: TStyleLabel;
FLayout: TTextLayout;
FSpeed: Integer;
FNumRepeat: Word; //number of repeat cycles
FContinuous: Boolean; //same that FNumRepeat = infinity
FSteps: Integer; { steps}
CurrentStep: Integer; { step number when running}
procedure SetActive(Value: Boolean);
procedure SetDirect(Value: TDirect);
procedure SetStyleLabel(Value: TStyleLabel);
procedure SetSteps(Value: Integer);
procedure SetSpeed(Value: Integer);
function GetTransparent: Boolean;
procedure SetTransparent(Value: Boolean);
procedure SetLayout(Value: TTextLayout);
procedure DoTextOut(ACanvas: TCanvas; X, Y: Integer; AText: string);
protected
{ Protected declarations }
procedure Paint; override;
procedure TimerExpired(Sender: TObject);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property Active: Boolean read FActive write SetActive;
property Direct: TDirect read FDirect write SetDirect;
property StyleLabel: TStyleLabel read FStyleLabel write SetStyleLabel;
property NumRepeat: Word read FNumRepeat write FNumRepeat;
property Continuous: Boolean read FContinuous write FContinuous;
property Steps: Integer read FSteps write SetSteps;
property Speed: Integer read FSpeed write SetSpeed;
// property Transparent: Boolean read GetTransparent write SetTransparent default False;
property Layout: TTextLayout read FLayout write SetLayout default tlTop;
property Align;
property Alignment;
// property BevelInner;
// property BevelOuter;
// property BevelWidth;
// property BorderWidth;
// property BorderStyle;
property DragCursor;
property DragMode;
property Enabled;
property Caption;
property Color;
property Ctl3D;
property Font;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDrag;
end;
implementation
constructor TRunningText.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSteps := 100;
CurrentStep := 0;
FSpeed := 100;
FTimer := TTimer.Create(Self);
with FTimer do
begin
Enabled := False;
OnTimer := TimerExpired;
Interval := FSpeed;
end;
end;
destructor TRunningText.Destroy;
begin
FTimer.Free;
inherited Destroy;
end;
procedure TRunningText.TimerExpired(Sender: TObject);
begin
if not FTimer.Enabled then Exit;
if (FCurCycle < FNumRepeat) or FContinuous then
begin
Inc(CurrentStep);
Paint;
if CurrentStep = FSteps then
begin
CurrentStep := 0;
if not FContinuous then
Inc(FCurCycle);
end;
end
else
Active := False;
end;
procedure TRunningText.DoTextOut(ACanvas: TCanvas; X, Y: Integer; AText: string);
begin
with ACanvas do
begin
Font := Self.Font;
Brush.Style := bsClear;
{ Draw text}
case FStyleLabel of
slRaised: begin
Font.Color := clBtnShadow;
TextOut(X + 2, Y + 2, AText);
end;
slLowered: begin
Font.Color := clBtnHighlight;
TextOut(X + 2, Y + 2, AText);
end;
end;
Font.Color := Self.Font.Color;
TextOut(X, Y, AText);
end;
end;
procedure TRunningText.Paint;
const
Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
Layouts: array[TTextLayout] of Word = (DT_TOP, DT_VCENTER, DT_BOTTOM);
var
TmpBmp: TBitmap;
StX, StY: Integer;
intWidth, intHeight: Integer;
CnX, CnY: Integer;
PctDone: Double;
begin
TmpBmp := TBitmap.Create;
try
TmpBmp.Width := Width;
TmpBmp.Height := Height;
with TmpBmp.Canvas do
begin
Font := Self.Font;
intWidth := TextWidth(Caption) + 2;
intHeight := TextHeight(Caption) + 2;
Brush.Color := Self.Color;
Brush.Style := bsSolid;
FillRect(ClipRect);
end;
{Calculate start points}
case Alignment of
taRightJustify: CnX := Width - intWidth;
taCenter: CnX := (Width - intWidth) div 2;
else // taLeftJustify
CnX := 0;
end;
case Layout of
tlBottom: CnY := Height - intHeight;
tlCenter: CnY := (Height - intHeight) div 2;
else // tlTop
CnY := 0;
end;
{Calculate percentages & starting points}
PctDone := CurrentStep/FSteps;
{set a static label parameters}
StX := CnX;
StY := CnY;
if Active then
case FDirect of
diRightToLeft: begin
StY := CnY;
StX := -intWidth + Round((intWidth + Width)*(1 - PctDone));
end;
diLeftToRight: begin
StY := CnY;
StX := -intWidth + Round((intWidth + Width)*(PctDone));
end;
diTopToBottom: begin
StX := CnX;
StY := -intHeight + Round((intHeight + Height)*(PctDone));
end;
diBottomToTop: begin
StX := CnX;
StY := -intHeight + Round((intHeight + Height)*(1 - PctDone));
end;
end;
DoTextOut(TmpBmp.Canvas, StX, StY, Caption);
Canvas.Draw(0, 0, TmpBmp);
finally
TmpBmp.Free;
end
end;
procedure TRunningText.SetActive(Value: Boolean);
begin
if (FActive <> Value) then
begin
FActive := Value;
FCurCycle := 0;
CurrentStep := 0;
FTimer.Enabled := Value;
if not Value then
Invalidate
end;
end;
procedure TRunningText.SetDirect;
begin
if (FDirect <> Value) then
begin
FDirect := Value;
if FActive then
Invalidate;
end;
end;
procedure TRunningText.SetSteps(Value: Integer);
begin
if FSteps <> Value then
begin
FSteps := Value;
if (csDesigning in ComponentState) then
begin
Invalidate;
end;
end;
end;
procedure TRunningText.SetStyleLabel(Value: TStyleLabel);
begin
if FStyleLabel <> Value then
begin
FStyleLabel := Value;
Invalidate;
end;
end;
procedure TRunningText.SetSpeed(Value: Integer);
begin
if FSpeed <> Value then
begin
FSpeed := Value;
if Value > 1000 then FSpeed := 1000;
if Value < 1 then FSpeed := 1;
{Change the timer interval}
if FTimer <> nil then
FTimer.Interval := FSpeed;
end;
end;
function TRunningText.GetTransparent: Boolean;
begin
Result := not (csOpaque in ControlStyle);
end;
procedure TRunningText.SetTransparent(Value: Boolean);
begin
// if Transparent <> Value then
begin
if Value then
ControlStyle := ControlStyle - [csOpaque]
else
ControlStyle := ControlStyle + [csOpaque];
Invalidate;
end;
end;
procedure TRunningText.SetLayout(Value: TTextLayout);
begin
if FLayout <> Value then
begin
FLayout := Value;
Invalidate;
end;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Themes;
type
TForm1 = class(TForm)
lblStyleServicesAvailable: TLabel;
Label1: TLabel;
lblIsAppThemed: TLabel;
Label3: TLabel;
lblCommonControlsVersion: TLabel;
Label4: TLabel;
lblStyleServicesEnabled: TLabel;
Label5: TLabel;
lblResult: TLabel;
procedure FormCreate(Sender: TObject);
procedure lblIsAppThemedClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
StrUtils,
Winapi.UxTheme,
Winapi.ShellAPI;
procedure TForm1.FormCreate(Sender: TObject);
var
version: Cardinal;
begin
lblStyleServicesAvailable.Caption := 'StyleServices.Available: '+IfThen(StyleServices.Available, 'True', 'False');
lblIsAppThemed.Caption := 'WinAPI.IsAppThemed: '+IfThen(IsAppThemed, 'True', 'False');
version := GetFileVersion('comctl32.dll');
lblCommonControlsVersion.Caption := 'Common Controls Version: '+IntToHex(version);
lblStyleServicesEnabled.Caption := 'StyleServices.Enabled: '+IfThen(STyleServices.Enabled, 'True', 'False');
if not StyleServices.Enabled then
lblStyleServicesEnabled.Font.Color := clMaroon;
if version < $00060000 then
begin
if StyleServices.Enabled then
begin
lblResult.Caption := 'Test passed: StyleServices.Enabled returns False if the Common Controls version is less than 6.0';
lblResult.Font.Color := clGreen;
end
else
begin
lblResult.Caption := 'Test failed: StyleServices.Enabled returns False if the Common Controls version is less than 6.0';
lblResult.Font.Color := clRed;
end;
end
else
begin
lblResult.Caption := 'Could not test case. This test requires the use of common controls version 5 or earlier';
lblResult.Font.Color := $00007CF7;
end;
StyleServices.ThemesAvailable
end;
procedure TForm1.lblIsAppThemedClick(Sender: TObject);
begin
//https://docs.microsoft.com/en-us/windows/win32/api/uxtheme/nf-uxtheme-isappthemed
ShellExecute(Self.Handle, 'open', 'https://docs.microsoft.com/en-us/windows/win32/api/uxtheme/nf-uxtheme-isappthemed', nil, nil, SW_SHOWNORMAL);
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
//
//主要实现:
//-----------------------------------------------------------------------------}
unit untEasyUtilFile;
interface
uses
Windows, Messages, SysUtils, Classes, ShellAPI, ZLib;
type
TFileVersionInfomation = record // 文件版本信息
rCommpanyName: string;
rFileDescription: string;
rFileVersion: string;
rInternalName: string;
rLegalCopyright: string;
rLegalTrademarks: string;
rOriginalFileName: string;
rProductName: string;
rProductVersion: string;
rComments: string;
rVsFixedFileInfo: VS_FIXEDFILEINFO;
rDefineValue: string;
end;
// 读取文件的版本信息
//mFileName 目标文件名
//nFileVersionInfomation 文件信息结构
//mDefineName 自定义字段名
//返回是否读取成功
function GetFileVersionInfomation(mFileName: string;
var nFileVersionInfomation: TFileVersionInfomation; mDefineName: string = ''): Boolean;
// 删除指定目录
//mDirName 目录名
//mPrefix 前缀
//mChangeAttrib 是否修改属性以便删除
// 返回删除指定目录是否成功
function DeletePath(mDirName: string; mPrefix: string; mChangeAttrib: Boolean): Boolean;
// 将文件时间处理为TDateTime
//mFileTime 文件时间
// 返回处理后的结果
function FileTimeToDateTime(mFileTime: TFileTime): TDateTime;
implementation
function GetFileVersionInfomation(mFileName: string;
var nFileVersionInfomation: TFileVersionInfomation; mDefineName: string = ''): Boolean;
var
vHandle: Cardinal;
vInfoSize: Cardinal;
vVersionInfo: Pointer;
vTranslation: Pointer;
vVersionValue: string;
vInfoPointer: Pointer;
begin
Result := False;
vInfoSize := GetFileVersionInfoSize(PChar(mFileName), vHandle); // 取得文件版本信息空间及资源句柄
FillChar(nFileVersionInfomation, SizeOf(nFileVersionInfomation), 0); // 初始化返回信息
if vInfoSize <= 0 then Exit; // 安全检查
GetMem(vVersionInfo, vInfoSize); // 分配资源
with nFileVersionInfomation do try
if not GetFileVersionInfo(PChar(mFileName),
vHandle, vInfoSize, vVersionInfo) then Exit;
CloseHandle(vHandle);
VerQueryValue(vVersionInfo, '\VarFileInfo\Translation',
vTranslation, vInfoSize);
if not Assigned(vTranslation) then Exit;
vVersionValue := Format('\StringFileInfo\%.4x%.4x\',
[LOWORD(Longint(vTranslation^)), HIWORD(Longint(vTranslation^))]);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'CompanyName'),
vInfoPointer, vInfoSize);
rCommpanyName := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'FileDescription'),
vInfoPointer, vInfoSize);
rFileDescription := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'FileVersion'),
vInfoPointer, vInfoSize);
rFileVersion := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'InternalName'),
vInfoPointer, vInfoSize);
rInternalName := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'LegalCopyright'),
vInfoPointer, vInfoSize);
rLegalCopyright := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'LegalTrademarks'),
vInfoPointer, vInfoSize);
rLegalTrademarks := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'OriginalFileName'),
vInfoPointer, vInfoSize);
rOriginalFileName := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'ProductName'),
vInfoPointer, vInfoSize);
rProductName := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'ProductVersion'),
vInfoPointer, vInfoSize);
rProductVersion := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, PChar(vVersionValue + 'Comments'),
vInfoPointer, vInfoSize);
rComments := PChar(vInfoPointer);
VerQueryValue(vVersionInfo, '\', vInfoPointer, vInfoSize);
rVsFixedFileInfo := TVSFixedFileInfo(vInfoPointer^);
if mDefineName <> '' then begin
VerQueryValue(vVersionInfo, PChar(vVersionValue + mDefineName),
vInfoPointer, vInfoSize);
rDefineValue := PChar(vInfoPointer);
end else rDefineValue := '';
finally
FreeMem(vVersionInfo, vInfoSize);
end;
Result := True;
end; { GetFileVersionInfomation }
function DeletePath(mDirName: string; mPrefix: string; mChangeAttrib: Boolean): Boolean;
var
vSearchRec: TSearchRec;
vPathName: string;
K: Integer;
begin
Result := True;
if mDirName = '' then Exit;
vPathName := mDirName + '\*.*';
K := FindFirst(vPathName, faAnyFile, vSearchRec);
while K = 0 do begin
if (vSearchRec.Attr and faDirectory > 0) and
(Pos(vSearchRec.Name, '..') = 0) then
begin
if mChangeAttrib then
FileSetAttr(mDirName + '\' + vSearchRec.Name, faDirectory);
if (mPrefix = '') or (Pos(mPrefix, vSearchRec.Name) = 1) then
Result := DeletePath(mDirName + '\' + vSearchRec.Name, mPrefix, mChangeAttrib);
end else if Pos(vSearchRec.Name, '..') = 0 then
begin
if mChangeAttrib then
FileSetAttr(mDirName + '\' + vSearchRec.Name, 0);
if (mPrefix = '') or (Pos(mPrefix, vSearchRec.Name) = 1) then
Result := DeleteFile(PChar(mDirName + '\' + vSearchRec.Name));
end;
if not Result then Break;
K := FindNext(vSearchRec);
end;
FindClose(vSearchRec);
Result := RemoveDir(mDirName);
end; { DeletePath }
function FileTimeToDateTime(mFileTime: TFileTime): TDateTime;
var
vSystemTime: TSystemTime;
vLocalFileTime: TFileTime;
begin
FileTimeToLocalFileTime(mFileTime, vLocalFileTime);
FileTimeToSystemTime(vLocalFileTime, vSystemTime);
Result := SystemTimeToDateTime(vSystemTime);
end; { FileTimeToDateTime }
end.
|
unit JSONparser;
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
System.Contnrs, superobject, supertypes;
type
PSuperObjectIter = ^TSuperObjectIter;
type
Tsobj = record
obj: ISuperObject;
end;
type
Psobj = ^Tsobj;
function ParseJSON(src: string): TStringList;
implementation
function ParseJSON(src: string): TStringList;
var
obj: ISuperObject;
objects: TStack;
entries: TStack;
piter: PSuperObjectIter;
pobj: Psobj;
list: TStringList;
val: extended;
begin
list := TStringList.Create;
try
objects := TStack.Create;
entries := TStack.Create;
try
objects.Push(Nil);
entries.Push(Nil);
obj := TSuperObject.ParseString(PSOChar(src), False);
if obj = Nil then
begin
// Пытаемся расшифровать строку как простое число
try
val := StrToFloat(src);
except
val := 0;
end;
list.Add(format('T=%g', [val]));
end
else
begin
New(piter);
New(pobj);
pobj^.obj := obj;
ObjectFindFirst(pobj^.obj, piter^); // Позиционируемся на первый подчиненный объект
while (True) do
begin
repeat
if (piter.val.DataType = stObject) or (piter.val.DataType = stArray) then
begin
// Если это объект составной, то переключаемся на его внутренние объекты, а сам текущий объект и итератор сохранаяем в стеке
objects.Push(pobj);
entries.Push(piter);
New(pobj);
pobj^.obj := piter.val;
New(piter);
if ObjectFindFirst(pobj^.obj, piter^) then
continue; // Позиционируемся на первый подчиненный объект
// Здесь неопределено, вероятно здесь будем в случае ошибки
end;
if piter.val = Nil then
break;
// Здесь имеем ключ и значение объекта JSON содержащего интересующие данные
list.Add(format('%s=%g', [piter.key, piter.val.AsDouble]));
// Memo1.Lines.Add('Type:' + IntToStr(Integer(piter.val.DataType)) + ' Key: "' + piter.key + '" Val: ' + piter.val.AsJSon + Format(' Number: %f' ,[piter.val.AsDouble]) );
if not ObjectFindNext(piter^) then
break;
until (False);
ObjectFindClose(piter^);
repeat
if objects.Count <> 0 then
begin
Dispose(pobj);
Dispose(piter);
pobj := Psobj(objects.Pop);
piter := PSuperObjectIter(entries.Pop);
if objects.Count = 0 Then
break;
end
else
begin
break;
end;
if not ObjectFindNext(piter^) then
ObjectFindClose(piter^)
else
begin
break;
end;
until (False);
if objects.Count = 0 then
break;
end;
if pobj <> Nil Then
Dispose(pobj);
if piter <> Nil Then
Dispose(piter);
end;
finally
objects.Free;
entries.Free;
end;
finally
result := list;
end;
end;
end.
|
unit uOperacoesEmLote_Controller;
interface
uses
uiOperacoesEmLote_Interface, Data.DB;
type
TOperacoesEmLote = class(TInterfacedObject, iOperacoesEmLote)
FDataSet :TDataSet;
function SetDataSet(DataSet:TDataSet):iOperacoesEmLote;
function SomaTotal : Double;
function SomaTotalDivisoes : Double;
end;
implementation
{ TController_OperacoesEmLote_Calculos }
function TOperacoesEmLote.SetDataSet(
DataSet: TDataSet): iOperacoesEmLote;
begin
Result := Self;
FDataSet := DataSet;
end;
function TOperacoesEmLote.SomaTotal: Double;
var
Total : Double;
begin
Total := 0;
FDataSet.First;
while not FDataSet.Eof do
begin
Total := Total + FDataSet.FieldByName('Valor').AsFloat;
FDataSet.Next;
end;
Result := Total;
end;
function TOperacoesEmLote.SomaTotalDivisoes: Double;
var
id: Integer;
Total, vrAtual, vrAnterior: Double;
begin
Total := 0;
FDataSet.First;
id := FDataSet.FieldByName('IdProjeto').AsInteger;
while not FDataSet.Eof do
begin
vrAtual := FDataSet.FieldByName('Valor').AsFloat;
if id <> FDataSet.FieldByName('IdProjeto').AsInteger then
Total := Total + (vrAtual/vrAnterior);
vrAnterior := FDataSet.FieldByName('Valor').AsFloat;
id := FDataSet.FieldByName('IdProjeto').AsInteger;
FDataSet.Next;
end;
Result := Total;
end;
end.
|
unit Dialogs4D.Factory;
interface
type
TDialogs = class
public
/// <summary>
/// Displays a dialog box for the user with a message.
/// </summary>
/// <param name="Content">
/// Message to be displayed to the user.
/// </param>
class procedure Info(const Content: string); static;
/// <summary>
/// Displays a dialog box for the user with a error message.
/// </summary>
/// <param name="Content">
/// Error message to be displayed to the user.
/// </param>
class procedure Error(const Content: string); static;
/// <summary>
/// Displays a dialog box for the user with a warning message.
/// </summary>
/// <param name="Content">
/// Warning message to be displayed to the user.
/// </param>
class procedure Warning(const Content: string); static;
/// <summary>
/// Displays a dialog box for the user with a question.
/// </summary>
/// <param name="Content">
/// Question to be displayed to the user.
/// </param>
/// <returns>
/// Returns true if the user has confirmed the question.
/// </returns>
class function Confirm(const Content: string): Boolean; static;
/// <summary>
/// Displays a dialog box for the user with an input box.
/// </summary>
/// <param name="Description">
/// Input box description.
/// </param>
/// <param name="Default">
/// Default value for the input box (default is empty).
/// </param>
/// <returns>
/// User defined value.
/// </returns>
class function Input(const Description: string; const Default: string = ''): string; static;
end;
implementation
uses Dialogs4D.Modal.Confirm, Dialogs4D.Modal.Error, Dialogs4D.Modal.Info, Dialogs4D.Input, Dialogs4D.Modal.Warning,
Dialogs4D.Modal.Intf, Dialogs4D.Input.Intf;
class function TDialogs.Input(const Description: string; const Default: string = ''): string;
var
Dialog: IDialogInput;
begin
Dialog := TDialogInput.Create;
Result := Dialog.Show(Description, default);
end;
class function TDialogs.Confirm(const Content: string): Boolean;
var
Dialog: IDialogModalConfirm;
begin
Dialog := TDialogModalConfirm.Create;
Result := Dialog.Show(Content);
end;
class procedure TDialogs.Error(const Content: string);
var
Dialog: IDialogModal;
begin
Dialog := TDialogModalError.Create;
Dialog.Show(Content);
end;
class procedure TDialogs.Info(const Content: string);
var
Dialog: IDialogModal;
begin
Dialog := TDialogModalInfo.Create;
Dialog.Show(Content);
end;
class procedure TDialogs.Warning(const Content: string);
var
Dialog: IDialogModal;
begin
Dialog := TDialogModalWarning.Create;
Dialog.Show(Content);
end;
end.
|
// This unit is part of the GLScene Project, http://glscene.org
{: LIBFREETYPE<p>
<b>Historique : </b><font size=-1><ul>
<li>21/01/11 - Yar - Creation
</ul></font>
}
unit LIBFREETYPE;
interface
{$I GLScene.inc}
uses
{$IFDEF GLS_LOGGING} GLSLog, {$ENDIF}
{$IFDEF MSWINDOWS} Windows, {$ENDIF}
{$IFDEF Unix} x, dynlibs, {$ENDIF}
GLCrossPlatform;
type
FT_Encoding = array[0..3] of char;
const
{$IFDEF MSWINDOWS}
FTLIBNAME = 'freetype.dll';
{$ENDIF }
{$IFDEF LINUX }
FTLIBNAME = 'freetype.so';
{$ENDIF }
{$IFDEF DARWIN }
FTLIBNAME = 'FTLIBNAME';
{$ENDIF }
FT_CURVE_TAG_ON = 1;
FT_CURVE_TAG_CONIC = 0;
FT_CURVE_TAG_CUBIC = 2;
FT_FACE_FLAG_SCALABLE = 1 shl 0;
FT_FACE_FLAG_KERNING = 1 shl 6;
FT_ENCODING_NONE: FT_Encoding = (#0, #0, #0, #0);
FT_LOAD_DEFAULT = $0000;
FT_LOAD_NO_HINTING = $0002;
FT_LOAD_FORCE_AUTOHINT = $0020;
FT_RENDER_MODE_NORMAL = 0;
FT_RENDER_MODE_LIGHT = FT_RENDER_MODE_NORMAL + 1;
FT_RENDER_MODE_MONO = FT_RENDER_MODE_LIGHT + 1;
FT_RENDER_MODE_LCD = FT_RENDER_MODE_MONO + 1;
FT_RENDER_MODE_LCD_V = FT_RENDER_MODE_LCD + 1;
FT_RENDER_MODE_MAX = FT_RENDER_MODE_LCD_V + 1;
FT_KERNING_DEFAULT = 0;
FT_KERNING_UNFITTED = 1;
FT_KERNING_UNSCALED = 2;
FT_STYLE_FLAG_ITALIC = 1 shl 0;
FT_STYLE_FLAG_BOLD = 1 shl 1;
T1_MAX_MM_AXIS = 4;
FT_VALIDATE_feat_INDEX = 0;
FT_VALIDATE_mort_INDEX = 1;
FT_VALIDATE_morx_INDEX = 2;
FT_VALIDATE_bsln_INDEX = 3;
FT_VALIDATE_just_INDEX = 4;
FT_VALIDATE_kern_INDEX = 5;
FT_VALIDATE_opbd_INDEX = 6;
FT_VALIDATE_trak_INDEX = 7;
FT_VALIDATE_prop_INDEX = 8;
FT_VALIDATE_lcar_INDEX = 9;
FT_VALIDATE_GX_LAST_INDEX = FT_VALIDATE_lcar_INDEX;
FT_VALIDATE_GX_LENGTH = FT_VALIDATE_GX_LAST_INDEX + 1;
FT_OPEN_MEMORY = $1;
FT_OPEN_STREAM = $2;
FT_OPEN_PATHNAME = $4;
FT_OPEN_DRIVER = $8;
FT_OPEN_PARAMS = $10;
FT_OUTLINE_NONE = $0;
FT_OUTLINE_OWNER = $1;
FT_OUTLINE_EVEN_ODD_FILL = $2;
FT_OUTLINE_REVERSE_FILL = $4;
FT_OUTLINE_IGNORE_DROPOUTS = $8;
FT_OUTLINE_HIGH_PRECISION = $100;
FT_OUTLINE_SINGLE_PASS = $200;
type
FT_Pointer = pointer;
FT_Byte = byte;
FT_Byte_array = array[0..MaxInt div (2*SizeOf(FT_Byte))-1] of FT_Byte;
FT_Bytes = ^FT_Byte_array;
FT_Short = smallint;
FT_UShort = word;
FT_Int = longint;
FT_UInt = longword;
FT_Int32 = longint;
FT_UInt32 = cardinal;
FT_Long = longint;
FT_ULong = longword;
FT_Fixed = longint;
FT_Bool = bytebool;
FT_Char = ShortInt;
FT_Pos = longint;
FT_Error = longint;
FT_F26Dot6 = longint;
FT_String = AnsiChar;
FT_Matrix = packed record
xx, xy: FT_Fixed;
yx, yy: FT_Fixed;
end;
FT_Byte_ptr = ^FT_Byte;
FT_Short_array = array[0..MaxInt div (2*SizeOf(FT_Short))-1] of FT_Short;
FT_Short_ptr = ^FT_Short_array;
FT_Long_ptr = ^FT_Long;
FT_Fixed_ptr = ^FT_Fixed;
FT_UInt_ptr = ^FT_UInt;
FT_Render_Mode = FT_Int;
FT_Library = ^FT_LibraryRec_;
FT_LibraryRec_ = record
end;
FT_Library_array = array[0..MaxInt div 16 - 1] of FT_Library;
FT_Library_ptr = ^FT_Library_array;
FT_Subglyph_ptr = ^FT_Subglyph;
FT_Subglyph = record
end;
FT_Bitmap_Size = packed record
height, width: FT_Short;
end;
AFT_Bitmap_Size = array[0..1023] of FT_Bitmap_Size;
FT_Bitmap_Size_ptr = ^AFT_Bitmap_Size;
FT_Generic_Finalizer = procedure(AnObject: pointer); cdecl;
FT_Generic = packed record
data: pointer;
finalizer: FT_Generic_Finalizer;
end;
FT_BBox_ptr = ^FT_BBox;
FT_BBox = packed record
xMin, yMin, xMax, yMax: FT_Pos;
end;
FT_Vector_ptr = ^FT_Vector_array;
FT_Vector = packed record
x, y: FT_Pos;
end;
FT_Vector_array = array[0..MaxInt div (2*SizeOf(FT_Vector)) - 1] of FT_Vector;
FT_Bitmap_ptr = ^FT_Bitmap;
FT_Bitmap = packed record
rows, width, pitch: FT_Int;
buffer: pointer;
num_grays: FT_Short;
pixel_mode, palette_mode: char;
palette: pointer;
end;
FT_Outline = ^FT_OutlineRec_;
FT_OutlineRec_ = packed record
n_contours, n_points: FT_Short;
points: FT_Vector_ptr;
tags: PChar;
contours: FT_Short_ptr;
flags: FT_Int;
end;
FT_Glyph_Metrics = packed record
width, height,
horiBearingX,
horiBearingY,
horiAdvance,
vertBearingX,
vertBearingY,
vertAdvance: FT_Pos;
end;
FT_Face = ^FT_FaceRec_;
FT_Face_array = array[0..MaxInt div 16 - 1] of FT_Face;
FT_Face_ptr = ^FT_Face_array;
FT_GlyphSlot = ^FT_GlyphSlotRec_;
FT_GlyphSlotRec_ = packed record
alibrary: FT_Library_ptr;
face: FT_Face_ptr;
next: FT_GlyphSlot;
flags: FT_UInt;
generic: FT_Generic;
metrics: FT_Glyph_Metrics;
linearHoriAdvance: FT_Fixed;
linearVertAdvance: FT_Fixed;
advance: FT_Vector;
format: longword;
bitmap: FT_Bitmap;
bitmap_left: FT_Int;
bitmap_top: FT_Int;
outline: FT_Outline;
num_subglyphs: FT_UInt;
subglyphs: FT_SubGlyph_ptr;
control_data: pointer;
control_len: longint;
other: pointer;
end;
FT_Size_Metrics = record
x_ppem, y_ppem: FT_UShort;
x_scale, y_scale: FT_Fixed;
ascender,
descender,
height,
max_advance: FT_Pos;
end;
FT_Size = ^FT_SizeRec_;
FT_SizeRec_ = record
face: FT_Face_ptr;
generic: FT_Generic;
metrics: FT_Size_Metrics;
//internal : FT_Size_Internal;
end;
FT_Charmap = ^FT_CharmapRec_;
FT_Charmap_ptr = ^FT_Charmap_array;
FT_FaceRec_ = packed record
num_faces,
face_index,
face_flags,
style_flags,
num_glyphs: FT_Long;
family_name,
style_name: PChar;
num_fixed_sizes: FT_Int;
available_sizes: FT_Bitmap_Size_ptr; // is array
num_charmaps: FT_Int;
charmaps: FT_CharMap_ptr; // is array
generic: FT_Generic;
bbox: FT_BBox;
units_per_EM: FT_UShort;
ascender,
descender,
height,
max_advance_width,
max_advance_height,
underline_position,
underline_thickness: FT_Short;
glyph: FT_GlyphSlot;
size: FT_Size;
charmap: FT_CharMap;
end;
FT_CharmapRec_ = packed record
face: FT_Face_ptr;
encoding: FT_Encoding;
platform_id,
encoding_id: FT_UShort;
end;
FT_Charmap_array = array[0..MaxInt div 16 - 1] of FT_Charmap;
FTC_CMapCache = ^FTC_CMapCacheRec_;
FTC_CMapCacheRec_ = record
end;
FTC_FaceID = FT_Pointer;
FTC_Manager = ^FTC_ManagerRec_;
FTC_ManagerRec_ = record
end;
FTC_ImageCache = ^FTC_ImageCacheRec_;
FTC_ImageCacheRec_ = record
end;
FTC_ImageType = ^FTC_ImageTypeRec_;
FTC_ImageTypeRec_ = packed record
face_id: FTC_FaceID;
width: FT_Int;
height: FT_Int;
flags: FT_Int32;
end;
FT_Glyph = ^FT_GlyphRec_;
FT_GlyphRec_ = record
end;
FTC_Node = ^FTC_NodeRec_;
FTC_NodeRec_ = record
end;
FTC_Scaler = ^FTC_ScalerRec_;
FTC_ScalerRec_ = packed record
face_id: FTC_FaceID;
width: FT_UInt;
height: FT_UInt;
pixel: FT_Int;
x_res: FT_UInt;
y_res: FT_UInt;
end;
FT_Angle = FT_Fixed;
FTC_Face_Requester = function(face_id: FTC_FaceID;
Alibrary: FT_Library;
request_data: FT_Pointer;
var aface: FT_Face): FT_Error; cdecl;
FTC_SBitCache = ^FTC_SBitCacheRec_;
FTC_SBitCacheRec_ = record
end;
FTC_SBit = ^FTC_SBitRec_;
FTC_SBitRec_ = packed record
width: FT_Byte;
height: FT_Byte;
left: FT_Char;
top: FT_Char;
format: FT_Byte;
max_grays: FT_Byte;
pitch: FT_Short;
xadvance: FT_Char;
yadvance: FT_Char;
buffer: ^FT_Byte;
end;
FT_Module_Class = FT_Pointer;
FT_Module = ^FT_ModuleRec_;
FT_ModuleRec_ = record
end;
FT_MM_Axis = packed record
name: ^FT_String;
minimum: FT_Long;
maximum: FT_Long;
end;
FT_Multi_Master = packed record
num_axis: FT_UInt;
num_designs: FT_UInt;
axis: array[0..T1_MAX_MM_AXIS - 1] of FT_MM_Axis;
end;
PS_FontInfo = ^PS_FontInfoRec_;
PS_FontInfoRec_ = packed record
version: ^FT_String;
notice: ^FT_String;
full_name: ^FT_String;
family_name: ^FT_String;
weight: ^FT_String;
italic_angle: FT_Long;
is_fixed_pitch: FT_Bool;
underline_position: FT_Short;
underline_thickness: FT_UShort;
end;
PS_Private = ^PS_PrivateRec_;
PS_PrivateRec_ = packed record
unique_id: FT_Int;
lenIV: FT_Int;
num_blue_values: FT_Byte;
num_other_blues: FT_Byte;
num_family_blues: FT_Byte;
num_family_other_blues: FT_Byte;
blue_values: array[0..13] of FT_Short;
other_blues: array[0..9] of FT_Short;
family_blues: array[0..13] of FT_Short;
family_other_blues: array[0..9] of FT_Short;
blue_scale: FT_Fixed;
blue_shift: FT_Int;
blue_fuzz: FT_Int;
standard_width: array[0..1] of FT_UShort;
standard_height: array[0..1] of FT_UShort;
num_snap_widths: FT_Byte;
num_snap_heights: FT_Byte;
force_bold: FT_Byte;
round_stem_up: FT_Byte;
snap_widths: array[0..13] of FT_Short;
snap_heights: array[0..13] of FT_Short;
expansion_factor: FT_Fixed;
language_group: FT_Long;
password: FT_Long;
min_feature: array[0..1] of FT_Short;
end;
FT_Glyph_Format =
(
FT_GLYPH_FORMAT_NONE = $00000000,
FT_GLYPH_FORMAT_COMPOSITE = $706D6F63,
FT_GLYPH_FORMAT_BITMAP = $73746962,
FT_GLYPH_FORMAT_OUTLINE = $6C74756F,
FT_GLYPH_FORMAT_PLOTTER = $746F6C70
);
FT_Glyph_Class = ^FT_Glyph_ClassRec_;
FT_Glyph_ClassRec_ = packed record
end;
FT_Raster = ^FT_RasterRec_;
FT_RasterRec_ = packed record
end;
pFT_Raster_Params = ^FT_Raster_Params;
FT_Raster_Render_Func = function(raster: FT_Raster;
params: pFT_Raster_Params): Integer; cdecl;
FT_Renderer = ^FT_RendererRec_;
FT_Renderer_RenderFunc = function(renderer: FT_Renderer;
slot: FT_GlyphSlot;
mode: FT_UInt;
const origin: FT_Vector): FT_Error; cdecl;
FT_Renderer_TransformFunc = function(renderer: FT_Renderer;
slot: FT_GlyphSlot;
const matrix: FT_Matrix;
const delta: FT_Vector): FT_Error; cdecl;
FT_Renderer_GetCBoxFunc = procedure(renderer: FT_Renderer;
slot: FT_GlyphSlot;
var cbox: FT_BBox); cdecl;
FT_Renderer_SetModeFunc = function(renderer: FT_Renderer;
mode_tag: FT_ULong;
mode_ptr: FT_Pointer): FT_Error; cdecl;
FT_Raster_NewFunc = function(memory: Pointer;
var raster: FT_Raster): Integer; cdecl;
FT_Raster_ResetFunc = procedure(raster: FT_Raster;
pool_base: PAnsiChar;
pool_size: PtrUint); cdecl;
FT_Raster_SetModeFunc = function(raster: FT_Raster;
mode: PtrUint;
args: Pointer): Integer; cdecl;
FT_Raster_RenderFunc = function(raster: FT_Raster;
params: pFT_Raster_Params): Integer; cdecl;
FT_Raster_DoneFunc = procedure(raster: FT_Raster); cdecl;
FT_Raster_Funcs = packed record
glyph_format: FT_Glyph_Format;
raster_new: FT_Raster_NewFunc;
raster_reset: FT_Raster_ResetFunc;
raster_set_mode: FT_Raster_SetModeFunc;
raster_render: FT_Raster_RenderFunc;
raster_done: FT_Raster_DoneFunc;
end;
FT_Renderer_Class = packed record
root: FT_Module_Class;
glyph_format: FT_Glyph_Format;
render_glyph: FT_Renderer_RenderFunc;
transform_glyph: FT_Renderer_TransformFunc;
get_glyph_cbox: FT_Renderer_GetCBoxFunc;
set_mode: FT_Renderer_SetModeFunc;
raster_class: ^FT_Raster_Funcs;
end;
FT_RendererRec_ = packed record
root: FT_ModuleRec_;
clazz: ^FT_Renderer_Class;
glyph_format: FT_Glyph_Format;
glyph_class: FT_Glyph_Class;
raster: FT_Raster;
raster_render: FT_Raster_Render_Func;
render: FT_Renderer_RenderFunc;
end;
FT_Memory = ^FT_MemoryRec_;
FT_Alloc_Func = function(memory: FT_Memory;
size: LongInt): Pointer;
FT_Free_Func = procedure(memory: FT_Memory;
block: Pointer); cdecl;
FT_Realloc_Func = function(memory: FT_Memory;
cur_size: LongInt;
new_size: LongInt;
block: Pointer): Pointer; cdecl;
FT_MemoryRec_ = packed record
user: Pointer;
alloc: FT_Alloc_Func;
free: FT_Free_Func;
realloc: FT_Realloc_Func;
end;
FT_SfntName = packed record
platform_id: FT_UShort;
encoding_id: FT_UShort;
language_id: FT_UShort;
name_id: FT_UShort;
AString: ^FT_Byte; // this string is *not* null-terminated!
string_len: FT_UInt; // in bytes
end;
FT_Sfnt_Tag =
(
ft_sfnt_head = 0, // TT_Header
ft_sfnt_maxp = 1, // TT_MaxProfile
ft_sfnt_os2 = 2, // TT_OS2
ft_sfnt_hhea = 3, // TT_HoriHeader
ft_sfnt_vhea = 4, // TT_VertHeader
ft_sfnt_post = 5, // TT_Postscript
ft_sfnt_pclt = 6
);
FT_TrueTypeEngineType =
(
FT_TRUETYPE_ENGINE_TYPE_NONE,
FT_TRUETYPE_ENGINE_TYPE_UNPATENTED,
FT_TRUETYPE_ENGINE_TYPE_PATENTE
);
FT_WinFNT_HeaderRec = packed record
version: FT_UShort;
file_size: FT_ULong;
copyright: array[0..59] of FT_Byte;
file_type: FT_UShort;
nominal_point_size: FT_UShort;
vertical_resolution: FT_UShort;
horizontal_resolution: FT_UShort;
ascent: FT_UShort;
internal_leading: FT_UShort;
external_leading: FT_UShort;
italic: FT_Byte;
underline: FT_Byte;
strike_out: FT_Byte;
weight: FT_UShort;
charset: FT_Byte;
pixel_width: FT_UShort;
pixel_height: FT_UShort;
pitch_and_family: FT_Byte;
avg_width: FT_UShort;
max_width: FT_UShort;
first_char: FT_Byte;
last_char: FT_Byte;
default_char: FT_Byte;
break_char: FT_Byte;
bytes_per_row: FT_UShort;
device_offset: FT_ULong;
face_name_offset: FT_ULong;
bits_pointer: FT_ULong;
bits_offset: FT_ULong;
reserved: FT_Byte;
flags: FT_ULong;
A_space: FT_UShort;
B_space: FT_UShort;
C_space: FT_UShort;
color_table_offset: FT_UShort;
reserved1: array[0..3] of FT_ULong;
end;
FT_Stroker = ^FT_StrokerRec_;
FT_StrokerRec_ = packed record
end;
FT_ListNode = ^FT_ListNodeRec_;
FT_ListNodeRec_ = packed record
prev: FT_ListNode;
next: FT_ListNode;
data: Pointer;
end;
FT_List = ^FT_ListRec_;
FT_ListRec_ = packed record
head: FT_ListNode;
tail: FT_ListNode;
end;
FT_List_Destructor = procedure(memory: FT_Memory;
data: Pointer;
user: Pointer); cdecl;
FT_List_Iterator = function(node: FT_ListNode;
user: Pointer): FT_Error; cdecl;
FT_StrokerBorder =
(
FT_STROKER_BORDER_LEFT,
FT_STROKER_BORDER_RIGHT
);
FT_Orientation =
(
FT_ORIENTATION_TRUETYPE = 0,
FT_ORIENTATION_POSTSCRIPT = 1,
FT_ORIENTATION_FILL_RIGHT = FT_ORIENTATION_TRUETYPE,
FT_ORIENTATION_FILL_LEFT = FT_ORIENTATION_POSTSCRIPT,
FT_ORIENTATION_NONE = 3
);
FT_Span = packed record
x: SmallInt;
len: Word;
coverage: Byte;
end;
FT_SpanFunc = procedure(y: Integer;
count: Integer;
var spans: FT_Span;
user: Pointer); cdecl;
FT_Raster_BitTest_Func = function(y: Integer;
x: Integer;
user: Pointer): Integer; cdecl;
FT_Raster_BitSet_Func = procedure(y: Integer;
x: Integer;
user: Pointer); cdecl;
FT_Raster_Params = packed record
target: ^FT_Bitmap;
source: Pointer;
flags: Integer;
gray_spans: FT_SpanFunc;
black_spans: FT_SpanFunc; // doesn't work!
bit_test: FT_Raster_BitTest_Func; // doesn't work!
bit_set: FT_Raster_BitSet_Func; // doesn't work!
user: Pointer;
clip_box: FT_BBox;
end;
FT_Size_Request_Type =
(
FT_SIZE_REQUEST_TYPE_NOMINAL,
FT_SIZE_REQUEST_TYPE_REAL_DIM,
FT_SIZE_REQUEST_TYPE_BBOX,
FT_SIZE_REQUEST_TYPE_CELL,
FT_SIZE_REQUEST_TYPE_SCALES,
FT_SIZE_REQUEST_TYPE_MAX
);
FT_Size_Request = ^FT_Size_RequestRec_;
FT_Size_RequestRec_ = packed record
atype: FT_Size_Request_Type;
width: FT_Long;
height: FT_Long;
horiResolution: FT_UInt;
vertResolution: FT_UInt;
end;
FT_DebugHook_Func = procedure(arg: Pointer); cdecl;
FT_StreamDesc = packed record
case Byte of
0: (Val: record Value: PtrUint;
end);
1: (Ptr: record Value: Pointer;
end);
end;
FT_Stream = ^FT_StreamRec_;
FT_Stream_IoFunc = function(stream: FT_Stream;
offset: PtrUint;
buffer: PAnsiChar;
count: PtrUint): PtrUint; cdecl;
FT_Stream_CloseFunc = procedure(stream: FT_Stream); cdecl;
FT_StreamRec_ = packed record
base: PAnsiChar;
size: PtrUint;
pos: PtrUint;
descriptor: FT_StreamDesc;
pathname: FT_StreamDesc;
read: FT_Stream_IoFunc;
close: FT_Stream_CloseFunc;
memory: FT_Memory;
cursor: PAnsiChar;
limit: PAnsiChar;
end;
FT_Parameter = packed record
tag: FT_ULong;
data: FT_Pointer;
end;
FT_Stroker_LineCap =
(
FT_STROKER_LINECAP_BUTT,
FT_STROKER_LINECAP_ROUND,
FT_STROKER_LINECAP_SQUARE
);
FT_Stroker_LineJoin =
(
FT_STROKER_LINEJOIN_ROUND,
FT_STROKER_LINEJOIN_BEVEL,
FT_STROKER_LINEJOIN_MITE
);
FT_Open_Args = packed record
flags: FT_UInt;
memory_base: FT_Byte_ptr;
memory_size: FT_Long;
pathname: ^FT_String;
stream: FT_Stream;
driver: FT_Module;
num_params: FT_Int;
params: ^FT_Parameter;
end;
FT_Var_Axis = packed record
name: ^FT_String;
minimum: FT_Fixed;
def: FT_Fixed;
maximum: FT_Fixed;
tag: FT_ULong;
strid: FT_UInt;
end;
FT_Var_Named_Style = packed record
coords: ^FT_Fixed;
strid: FT_UInt;
end;
FT_MM_Var = packed record
num_axis: FT_UInt;
num_designs: FT_UInt;
num_namedstyles: FT_UInt;
axis: ^FT_Var_Axis;
namedstyle: ^FT_Var_Named_Style;
end;
FT_Outline_MoveToFunc = function(const ato: FT_Vector;
user: Pointer): Integer; cdecl;
FT_Outline_LineToFunc = function(const ato: FT_Vector;
user: Pointer): Integer; cdecl;
FT_Outline_ConicToFunc = function(const control: FT_Vector;
const ato: FT_Vector;
user: Pointer): Integer; cdecl;
FT_Outline_CubicToFunc = function(const control1: FT_Vector;
const control2: FT_Vector;
const ato: FT_Vector;
user: Pointer): Integer; cdecl;
FT_Outline_Funcs = packed record
move_to: FT_Outline_MoveToFunc;
line_to: FT_Outline_LineToFunc;
conic_to: FT_Outline_ConicToFunc;
cubic_to: FT_Outline_CubicToFunc;
shift: Integer;
delta: FT_Pos;
end;
FT_Tables = array[0..FT_VALIDATE_GX_LENGTH - 1] of FT_Bytes;
var
FTC_CMapCache_Lookup: function(cache: FTC_CMapCache;
face_id: FTC_FaceID;
cmap_index: FT_Int;
char_code: FT_UInt32): FT_UInt; cdecl;
FTC_CMapCache_New: function(manager: FTC_Manager;
var acache: FTC_ImageCache): FT_Error; cdecl;
FTC_ImageCache_Lookup: function(cache: FTC_ImageCache;
Atype: FTC_ImageType;
gindex: FT_UInt;
var aglyph: FT_Glyph;
var anode: FTC_Node): FT_Error; cdecl;
FTC_ImageCache_LookupScaler: function(cache: FTC_ImageCache;
scaler: FTC_Scaler;
load_flags: FT_ULong;
gindex: FT_UInt;
var aglyph: FT_Glyph;
var anode: FTC_Node): FT_Error; cdecl;
FTC_ImageCache_New: function(manager: FTC_Manager;
var acache: FTC_ImageCache): FT_Error; cdecl;
FTC_Manager_Done: procedure(manager: FTC_Manager); cdecl;
FTC_Manager_LookupFace: function(manager: FTC_Manager;
face_id: FTC_FaceID;
var aface: FT_Face): FT_Error; cdecl;
FTC_Manager_LookupSize: function(manager: FTC_Manager;
scaler: FTC_Scaler;
var asize: FT_Size): FT_Error; cdecl;
FTC_Manager_New: function(Alibrary: FT_Library;
max_faces: FT_UInt;
max_sizes: FT_UInt;
max_bytes: FT_ULong;
requester: FTC_Face_Requester;
req_data: FT_Pointer;
var amanager: FTC_Manager): FT_Error; cdecl;
FTC_Manager_RemoveFaceID: procedure(manager: FTC_Manager;
face_id: FTC_FaceID); cdecl;
FTC_Manager_Reset: procedure(manager: FTC_Manager); cdecl;
FTC_Node_Unref: procedure(node: FTC_Node;
manage: FTC_Manager); cdecl;
FTC_SBitCache_Lookup: function(cache: FTC_SBitCache;
Atype: FTC_ImageType;
gindex: FT_UInt;
var sbit: FTC_SBit;
var anode: FTC_Node): FT_Error; cdecl;
FTC_SBitCache_LookupScaler: function(cache: FTC_SBitCache;
scaler: FTC_Scaler;
load_flags: FT_ULong;
gindex: FT_UInt;
var sbit: FTC_SBit;
var anode: FTC_Node): FT_Error; cdecl;
FTC_SBitCache_New: function(manager: FTC_Manager;
var acache: FTC_SBitCache): FT_Error; cdecl;
FT_Activate_Size: function(size: FT_Size): FT_Error; cdecl;
FT_Add_Default_Modules: function(Alibrary: FT_Library): FT_Error; cdecl;
FT_Add_Module: function(Alibrary: FT_Library;
const clazz: FT_Module_Class): FT_Error; cdecl;
FT_Angle_Diff: function(angle1: FT_Angle;
angle2: FT_Angle): FT_Angle; cdecl;
FT_Atan2: function(x: FT_Fixed;
y: FT_Fixed): FT_Angle; cdecl;
FT_Attach_File: function(face: FT_Face; filepathname: PAnsiChar): FT_Error; cdecl;
FT_Attach_Stream: function(face: FT_Face;
const parameters: FT_Open_Args): FT_Error; cdecl;
FT_Bitmap_Convert: function(Alibrary: FT_Library;
const source: FT_Bitmap;
var target: FT_Bitmap;
alignment: FT_Int): FT_Error; cdecl;
FT_Bitmap_Copy: function(Alibrary: FT_Library;
const source: FT_Bitmap;
var target: FT_Bitmap): FT_Error; cdecl;
FT_Bitmap_Done: function(Alibrary: FT_Library;
var bitmap: FT_Bitmap): FT_Error; cdecl;
FT_Bitmap_Embolden: function(Alibrary: FT_Library;
var bitmap: FT_Bitmap;
xStrength: FT_Pos;
yStrength: FT_Pos): FT_Error; cdecl;
FT_Bitmap_New: procedure(var abitmap: FT_Bitmap); cdecl;
FT_CeilFix: function(a: FT_Fixed): FT_Fixed; cdecl;
FT_ClassicKern_Free: procedure(face: FT_Face;
table: FT_Bytes); cdecl;
FT_ClassicKern_Validate: function(face: FT_Face;
validation_flags: FT_UInt;
var ckern_table: FT_Bytes): FT_Error; cdecl;
FT_Cos: function(angle: FT_Angle): FT_Fixed; cdecl;
FT_DivFix: function(a: FT_Long;
b: FT_Long): FT_Long; cdecl;
FT_Done_Face: function(face: FT_Face): FT_Error; cdecl;
FT_Done_FreeType: function(alibrary: FT_Library): FT_Error; cdecl;
FT_Done_Glyph: procedure(glyph: FT_Glyph); cdecl;
FT_Done_Library: function(Alibrary: FT_Library): FT_Error; cdecl;
FT_Done_Size: function(size: FT_Size): FT_Error; cdecl;
FT_Face_CheckTrueTypePatents: function(face: FT_Face): FT_Bool; cdecl;
FT_Face_SetUnpatentedHinting: function(face: FT_Face;
value: FT_Bool): FT_Bool; cdecl;
FT_FloorFix: function(a: FT_Fixed): FT_Fixed; cdecl;
FT_Get_CMap_Format: function(charmap: FT_CharMap): FT_Long; cdecl;
FT_Get_CMap_Language_ID: function(charmap: FT_CharMap): FT_ULong; cdecl;
FT_Get_Char_Index: function(face: FT_Face; charcode: FT_ULong): FT_UInt; cdecl;
FT_Get_Charmap_Index: function(charmap: FT_CharMap): FT_Int; cdecl;
FT_Get_First_Char: function(face: FT_Face;
var agindex: FT_UInt): FT_ULong; cdecl;
FT_Get_Glyph: function(slot: FT_GlyphSlot;
var aglyph: FT_Glyph): FT_Error; cdecl;
FT_Get_Glyph_Name: function(face: FT_Face;
glyph_index: FT_UInt;
buffer: FT_Pointer;
buffer_max: FT_UInt): FT_Error; cdecl;
FT_Get_Kerning: function(
face: FT_Face;
left_glyph, right_glyph, kern_mode: FT_UInt;
var akerning: FT_Vector): FT_Error; cdecl;
FT_Get_MM_Var: function(face: FT_Face;
var amaster: FT_MM_Var): FT_Error; cdecl;
FT_Get_Module: function(Alibrary: FT_Library;
module_name: PAnsiChar): FT_Module; cdecl;
FT_Get_Multi_Master: function(face: FT_Face;
var amaster: FT_Multi_Master): FT_Error; cdecl;
FT_Get_Name_Index: function(face: FT_Face;
var glyph_name: FT_String): FT_UInt; cdecl;
FT_Get_Next_Char: function(face: FT_Face;
char_code: FT_ULong;
var agindex: FT_UInt): FT_ULong; cdecl;
FT_Get_PFR_Advance: function(face: FT_Face;
gindex: FT_UInt;
var aadvance: FT_Pos): FT_Error; cdecl;
FT_Get_PFR_Kerning: function(face: FT_Face;
left: FT_UInt;
right: FT_UInt;
var avector: FT_Vector): FT_Error; cdecl;
FT_Get_PFR_Metrics: function(face: FT_Face;
var aoutline_resolution: FT_UInt;
var ametrics_resolution: FT_UInt;
ametrics_x_scale: FT_Fixed;
ametrics_y_scale: FT_Fixed): FT_Error; cdecl;
FT_Get_PS_Font_Info: function(face: FT_Face;
afont_info: PS_FontInfo): FT_Error; cdecl;
FT_Get_PS_Font_Private: function(face: FT_Face;
afont_private: PS_Private): FT_Error; cdecl;
FT_Get_Postscript_Name: function(face: FT_Face): PAnsiChar; cdecl;
FT_Get_Renderer: function(Alibrary: FT_Library;
format: FT_Glyph_Format): FT_Renderer; cdecl;
FT_Get_Sfnt_Name: function(face: FT_Face;
idx: FT_UInt;
var aname: FT_SfntName): FT_Error; cdecl;
FT_Get_Sfnt_Name_Count: function(face: FT_Face): FT_UInt; cdecl;
FT_Get_Sfnt_Table: function(face: FT_Face;
tag: FT_Sfnt_Tag): Pointer; cdecl;
FT_Get_SubGlyph_Info: function(glyph: FT_GlyphSlot;
sub_index: FT_UInt;
var p_index: FT_Int;
var p_flags: FT_UInt;
var p_arg1: FT_Int;
var p_arg2: FT_Int;
var p_transform: FT_Matrix): FT_Error; cdecl;
FT_Get_Track_Kerning: function(face: FT_Face;
point_size: FT_Fixed;
degree: FT_Int;
var akerning: FT_Fixed): FT_Error; cdecl;
FT_Get_TrueType_Engine_Type: function(Alibrary: FT_Library): FT_TrueTypeEngineType; cdecl;
FT_Get_WinFNT_Header: function(face: FT_Face;
var aheader: FT_WinFNT_HeaderRec): FT_Error; cdecl;
FT_GlyphSlot_Embolden: procedure(slot: FT_GlyphSlot); cdecl;
FT_GlyphSlot_Oblique: procedure(slot: FT_GlyphSlot); cdecl;
FT_GlyphSlot_Own_Bitmap: function(slot: FT_GlyphSlot): FT_Error; cdecl;
FT_Glyph_Copy: function(source: FT_Glyph;
var target: FT_Glyph): FT_Error; cdecl;
FT_Glyph_Get_CBox: procedure(glyph: FT_Glyph;
bbox_mode: FT_UInt;
var acbo: FT_BBox); cdecl;
FT_Glyph_Stroke: function(var pglyph: FT_Glyph;
stroker: FT_Stroker;
destroy: FT_Bool): FT_Error; cdecl;
FT_Glyph_StrokeBorder: function(var pglyph: FT_Glyph;
stroker: FT_Stroker;
inside: FT_Bool;
destroy: FT_Bool): FT_Error; cdecl;
FT_Glyph_To_Bitmap: function(var the_glyph: FT_Glyph;
render_mode: FT_Render_Mode;
var origin: FT_Vector;
destroy: FT_Bool): FT_Error; cdecl;
FT_Glyph_Transform: function(glyph: FT_Glyph;
var matrix: FT_Matrix;
var delta: FT_Vector): FT_Error; cdecl;
FT_Has_PS_Glyph_Names: function(face: FT_Face): FT_Int; cdecl;
FT_Init_FreeType: function(alibrary: FT_Library): FT_Error; cdecl;
FT_Library_Version: procedure(Alibrary: FT_Library;
var amajor: FT_Int;
var aminor: FT_Int;
var apatch: FT_Int); cdecl;
FT_List_Add: procedure(list: FT_List;
node: FT_ListNode); cdecl;
FT_List_Finalize: procedure(list: FT_List;
destroy: FT_List_Destructor;
memory: FT_Memory;
user: Pointer); cdecl;
FT_List_Find: function(list: FT_List;
data: Pointer): FT_ListNode; cdecl;
FT_List_Insert: procedure(list: FT_List;
node: FT_ListNode); cdecl;
FT_List_Iterate: function(list: FT_List;
iterator: FT_List_Iterator;
user: Pointer): FT_Error; cdecl;
FT_List_Remove: procedure(list: FT_List;
node: FT_ListNode); cdecl;
FT_List_Up: procedure(list: FT_List;
node: FT_ListNode); cdecl;
FT_Load_Char: function(face: FT_Face;
char_code: FT_ULong;
load_flags: FT_Int32): FT_Error; cdecl;
FT_Load_Glyph: function(
face: FT_Face;
glyph_index: FT_UInt;
load_flags: FT_Int32): FT_Error; cdecl;
FT_Load_Sfnt_Table: function(face: FT_Face;
tag: FT_ULong;
offset: FT_Long;
var buffer: FT_Byte;
var length: FT_ULong): FT_Error; cdecl;
FT_Matrix_Invert: function(var matrix: FT_Matrix): FT_Error; cdecl;
FT_Matrix_Multiply: procedure(var a: FT_Matrix;
var b: FT_Matrix); cdecl;
FT_MulDiv: function(a: FT_Long;
b: FT_Long;
c: FT_Long): FT_Long; cdecl;
FT_MulFix: function(a: FT_Long;
b: FT_Long): FT_Long; cdecl;
FT_New_Face: function(
library_: FT_Library;
filepathname: PAnsiChar;
face_index: FT_Long;
var aface: FT_Face): FT_Error; cdecl;
FT_New_Library: function(memory: FT_Memory;
var alibrary: FT_Library): FT_Error; cdecl;
FT_New_Memory_Face: function(
library_: FT_Library;
file_base: FT_Byte_ptr;
file_size,
face_index: FT_Long;
var aface: FT_Face): FT_Error; cdecl;
FT_New_Size: function(face: FT_Face;
var size: FT_Size): FT_Error; cdecl;
FT_OpenType_Free: procedure(face: FT_Face;
table: FT_Bytes); cdecl;
FT_OpenType_Validate: function(face: FT_Face;
validation_flags: FT_UInt;
var BASE_table: FT_Bytes;
var GDEF_table: FT_Bytes;
var GPOS_table: FT_Bytes;
var GSUB_table: FT_Bytes;
var JSTF_table: FT_Bytes): FT_Error; cdecl;
FT_Open_Face: function(Alibrary: FT_Library;
const args: FT_Open_Args;
face_index: FT_Long;
var aface: FT_Face): FT_Error; cdecl;
FT_Outline_Check: function(var outline: FT_Outline): FT_Error; cdecl;
FT_Outline_Copy: function(const source: FT_Outline;
var target: FT_Outline): FT_Error; cdecl;
FT_Outline_Decompose: function(var outline: FT_Outline;
const func_interface: FT_Outline_Funcs;
use: Pointer): FT_Error; cdecl;
FT_Outline_Done: function(Alibrary: FT_Library;
var outline: FT_Outline): FT_Error; cdecl;
FT_Outline_Done_Internal: function(memory: FT_Memory;
var outline: FT_Outline): FT_Error; cdecl;
FT_Outline_Embolden: function(var outline: FT_Outline;
strength: FT_Pos): FT_Error; cdecl;
FT_Outline_GetInsideBorder: function(const outline: FT_Outline): FT_StrokerBorder; cdecl;
FT_Outline_GetOutsideBorder: function(const outline: FT_Outline): FT_StrokerBorder; cdecl;
FT_Outline_Get_BBox: function(const outline: FT_Outline;
var abbox: FT_BBox): FT_Error; cdecl;
FT_Outline_Get_Bitmap: function(Alibrary: FT_Library;
const outline: FT_Outline;
var abitmap: FT_Bitmap): FT_Error; cdecl;
FT_Outline_Get_CBox: procedure(const outline: FT_Outline;
out acbo: FT_BBox); cdecl;
FT_Outline_Get_Orientation: function(const outline: FT_Outline): FT_Orientation; cdecl;
FT_Outline_New: function(Alibrary: FT_Library;
numPoints: FT_UInt;
numContours: FT_Int;
var anoutline: FT_Outline): FT_Error; cdecl;
FT_Outline_New_Internal: function(memory: FT_Memory;
numPoints: FT_UInt;
numContours: FT_Int;
var anoutline: FT_Outline): FT_Error; cdecl;
FT_Outline_Render: function(Alibrary: FT_Library;
var outline: FT_Outline;
const params: FT_Raster_Params): FT_Error; cdecl;
FT_Outline_Reverse: procedure(const outline: FT_Outline); cdecl;
FT_Outline_Transform: procedure(var outline: FT_Outline;
const matrix: FT_Matrix); cdecl;
FT_Outline_Translate: procedure(var outline: FT_Outline;
xOffset: FT_Pos;
yOffset: FT_Pos); cdecl;
FT_Remove_Module: function(Alibrary: FT_Library;
module: FT_Module): FT_Error; cdecl;
FT_Render_Glyph: function(slot: FT_GlyphSlot; render_mode: FT_Render_Mode): FT_Error; cdecl;
FT_Request_Size: function(face: FT_Face;
req: FT_Size_Request): FT_Error; cdecl;
FT_RoundFix: function(a: FT_Fixed): FT_Fixed; cdecl;
FT_Select_Charmap: function(face: FT_Face; encoding: FT_Encoding): FT_Error; cdecl;
FT_Select_Size: function(face: FT_Face;
strike_index: FT_Int): FT_Error; cdecl;
FT_Set_Char_Size: function(
face: FT_Face_ptr;
char_width, char_height: FT_F26dot6;
horz_res, vert_res: FT_UInt): FT_Error; cdecl;
FT_Set_Charmap: function(face: FT_Face;
charmap: FT_CharMap): FT_Error; cdecl;
FT_Set_Debug_Hook: procedure(Alibrary: FT_Library;
hook_index: FT_UInt;
debug_hook: FT_DebugHook_Func); cdecl;
FT_Set_MM_Blend_Coordinates: function(face: FT_Face;
num_coords: FT_UInt;
var coords: FT_Fixed): FT_Error; cdecl;
FT_Set_MM_Design_Coordinates: function(face: FT_Face;
num_coords: FT_UInt;
coords: FT_Long_ptr): FT_Error; cdecl;
FT_Set_Pixel_Sizes: function(
face: FT_Face_ptr;
pixel_width, pixel_height: FT_UInt): FT_Error; cdecl;
FT_Set_Renderer: function(Alibrary: FT_Library;
renderer: FT_Renderer;
num_params: FT_UInt;
const parameters: FT_Parameter): FT_Error; cdecl;
FT_Set_Transform: procedure(face: FT_Face;
var matrix: FT_Matrix;
var delta: FT_Vector); cdecl;
FT_Set_Var_Blend_Coordinates: function(face: FT_Face;
num_coords: FT_UInt;
coords: FT_Fixed_ptr): FT_Error; cdecl;
FT_Set_Var_Design_Coordinates: function(face: FT_Face;
num_coords: FT_UInt;
coords: FT_Fixed_ptr): FT_Error; cdecl;
FT_Sfnt_Table_Info: function(face: FT_Face;
table_index: FT_UInt;
var tag: FT_ULong;
var length: FT_ULong): FT_Error; cdecl;
FT_Sin: function(angle: FT_Angle): FT_Fixed; cdecl;
FT_Stream_OpenGzip: function(stream: FT_Stream;
sourc: FT_Stream): FT_Error; cdecl;
FT_Stream_OpenLZW: function(stream: FT_Stream;
sourc: FT_Stream): FT_Error; cdecl;
FT_Stroker_BeginSubPath: function(stroker: FT_Stroker;
const ato: FT_Vector;
open: FT_Bool): FT_Error; cdecl;
FT_Stroker_ConicTo: function(stroker: FT_Stroker;
const control: FT_Vector;
var t: FT_Vector): FT_Error; cdecl;
FT_Stroker_CubicTo: function(stroker: FT_Stroker;
const control1: FT_Vector;
const control2: FT_Vector;
var ato: FT_Vector): FT_Error; cdecl;
FT_Stroker_Done: procedure(stroker: FT_Stroker); cdecl;
FT_Stroker_EndSubPath: function(stroker: FT_Stroker): FT_Error; cdecl;
FT_Stroker_Export: procedure(stroker: FT_Stroker;
var outline: FT_Outline); cdecl;
FT_Stroker_ExportBorder: procedure(stroker: FT_Stroker;
border: FT_StrokerBorder;
var outline: FT_Outline); cdecl;
FT_Stroker_GetBorderCounts: function(stroker: FT_Stroker;
border: FT_StrokerBorder;
anum_points: FT_UInt_ptr;
anum_contours: FT_UInt_ptr): FT_Error; cdecl;
FT_Stroker_GetCounts: function(stroker: FT_Stroker;
anum_points: FT_UInt_ptr;
anum_contours: FT_UInt_ptr): FT_Error; cdecl;
FT_Stroker_LineTo: function(stroker: FT_Stroker;
var ato: FT_Vector): FT_Error; cdecl;
FT_Stroker_New: function(Alibrary: FT_Library;
var astroker: FT_Stroker): FT_Error; cdecl;
FT_Stroker_ParseOutline: function(stroker: FT_Stroker;
const outline: FT_Outline;
opened: FT_Bool): FT_Error; cdecl;
FT_Stroker_Rewind: procedure(stroker: FT_Stroker); cdecl;
FT_Stroker_Set: procedure(stroker: FT_Stroker;
radius: FT_Fixed;
line_cap: FT_Stroker_LineCap;
line_join: FT_Stroker_LineJoin;
miter_limit: FT_Fixed); cdecl;
FT_Tan: function(angle: FT_Angle): FT_Fixed; cdecl;
FT_TrueTypeGX_Free: procedure(face: FT_Face;
table: FT_Bytes); cdecl;
FT_TrueTypeGX_Validate: function(face: FT_Face;
validation_flags: FT_UInt;
const tables: FT_Tables;
table_length: FT_UInt): FT_Error; cdecl;
FT_Vector_From_Polar: procedure(var vec: FT_Vector;
length: FT_Fixed;
angle: FT_Angle); cdecl;
FT_Vector_Length: function(var vec: FT_Vector): FT_Fixed; cdecl;
FT_Vector_Polarize: procedure(const vec: FT_Vector;
var length: FT_Fixed;
var angl: FT_Angle); cdecl;
FT_Vector_Rotate: procedure(var vec: FT_Vector;
angle: FT_Angle); cdecl;
FT_Vector_Transform: procedure(var vec: FT_Vector;
const matrix: FT_Matrix); cdecl;
FT_Vector_Unit: procedure(var vec: FT_Vector;
angle: FT_Angle); cdecl;
function FT_Curve_Tag(flag: char): char;
function FT_Is_Scalable(face: FT_Face): boolean;
function FT_Has_Kerning(face: FT_Face): boolean;
function InitFreetype: Boolean;
procedure CloseFreetype;
function InitFreetypeFromLibrary(const FTName: WideString): Boolean;
function IsFreetypeInitialized: Boolean;
implementation
function FT_CURVE_TAG(flag: char): char;
begin
result := char(Byte(flag) and 3);
end;
function FT_IS_SCALABLE(face: FT_Face): boolean;
begin
result := boolean(face.face_flags and FT_FACE_FLAG_SCALABLE);
end;
function FT_HAS_KERNING(face: FT_Face): boolean;
begin
result := boolean(face.face_flags and FT_FACE_FLAG_KERNING);
end;
const
INVALID_MODULEHANDLE = 0;
// ************** Windows specific ********************
{$IFDEF MSWINDOWS}
var
FTHandle: HINST;
{$ENDIF}
// ************** UNIX specific ********************
{$IFDEF UNIX}
var
FTHandle: TLibHandle;
{$ENDIF}
function FTGetProcAddress(ProcName: PAnsiChar): Pointer;
begin
result := GetProcAddress(Cardinal(FTHandle), ProcName);
end;
// InitFreetype
//
function InitFreetype: Boolean;
begin
if FTHandle = INVALID_MODULEHANDLE then
Result := InitFreetypeFromLibrary(FTLIBNAME)
else
Result := True;
end;
// CloseFreetype
//
procedure CloseFreetype;
begin
if FTHandle <> INVALID_MODULEHANDLE then
begin
FreeLibrary(Cardinal(FTHandle));
FTHandle := INVALID_MODULEHANDLE;
end;
end;
// InitFreetypeFromLibrary
//
function InitFreetypeFromLibrary(const FTName: WideString): Boolean;
begin
Result := False;
CloseFreetype;
FTHandle := LoadLibraryW(PWideChar(FTName));
if FTHandle = INVALID_MODULEHANDLE then
Exit;
FTC_CMapCache_Lookup := FTGetProcAddress('FTC_CMapCache_Lookup');
FTC_CMapCache_New := FTGetProcAddress('FTC_CMapCache_New');
FTC_ImageCache_Lookup := FTGetProcAddress('FTC_ImageCache_Lookup');
FTC_ImageCache_LookupScaler := FTGetProcAddress('FTC_ImageCache_LookupScaler');
FTC_ImageCache_New := FTGetProcAddress('FTC_ImageCache_New');
FTC_Manager_Done := FTGetProcAddress('FTC_Manager_Done');
FTC_Manager_LookupFace := FTGetProcAddress('FTC_Manager_LookupFace');
FTC_Manager_LookupSize := FTGetProcAddress('FTC_Manager_LookupSize');
FTC_Manager_New := FTGetProcAddress('FTC_Manager_New');
FTC_Manager_RemoveFaceID := FTGetProcAddress('FTC_Manager_RemoveFaceID');
FTC_Manager_Reset := FTGetProcAddress('FTC_Manager_Reset');
FTC_Node_Unref := FTGetProcAddress('FTC_Node_Unref');
FTC_SBitCache_Lookup := FTGetProcAddress('FTC_SBitCache_Lookup');
FTC_SBitCache_LookupScaler := FTGetProcAddress('FTC_SBitCache_LookupScaler');
FTC_SBitCache_New := FTGetProcAddress('FTC_SBitCache_New');
FT_Activate_Size := FTGetProcAddress('FT_Activate_Size');
FT_Add_Default_Modules := FTGetProcAddress('FT_Add_Default_Modules');
FT_Add_Module := FTGetProcAddress('FT_Add_Module');
FT_Angle_Diff := FTGetProcAddress('FT_Angle_Diff');
FT_Atan2 := FTGetProcAddress('FT_Atan2');
FT_Attach_File := FTGetProcAddress('FT_Attach_File');
FT_Attach_Stream := FTGetProcAddress('FT_Attach_Stream');
FT_Bitmap_Convert := FTGetProcAddress('FT_Bitmap_Convert');
FT_Bitmap_Copy := FTGetProcAddress('FT_Bitmap_Copy');
FT_Bitmap_Done := FTGetProcAddress('FT_Bitmap_Done');
FT_Bitmap_Embolden := FTGetProcAddress('FT_Bitmap_Embolden');
FT_Bitmap_New := FTGetProcAddress('FT_Bitmap_New');
FT_CeilFix := FTGetProcAddress('FT_CeilFix');
FT_ClassicKern_Free := FTGetProcAddress('FT_ClassicKern_Free');
FT_ClassicKern_Validate := FTGetProcAddress('FT_ClassicKern_Validate');
FT_Cos := FTGetProcAddress('FT_Cos');
FT_DivFix := FTGetProcAddress('FT_DivFix');
FT_Done_Face := FTGetProcAddress('FT_Done_Face');
FT_Done_FreeType := FTGetProcAddress('FT_Done_FreeType');
FT_Done_Glyph := FTGetProcAddress('FT_Done_Glyph');
FT_Done_Library := FTGetProcAddress('FT_Done_Library');
FT_Done_Size := FTGetProcAddress('FT_Done_Size');
FT_Face_CheckTrueTypePatents := FTGetProcAddress('FT_Face_CheckTrueTypePatents');
FT_Face_SetUnpatentedHinting := FTGetProcAddress('FT_Face_SetUnpatentedHinting');
FT_FloorFix := FTGetProcAddress('FT_FloorFix');
FT_Get_CMap_Format := FTGetProcAddress('FT_Get_CMap_Format');
FT_Get_CMap_Language_ID := FTGetProcAddress('FT_Get_CMap_Language_ID');
FT_Get_Char_Index := FTGetProcAddress('FT_Get_Char_Index');
FT_Get_Charmap_Index := FTGetProcAddress('FT_Get_Charmap_Index');
FT_Get_First_Char := FTGetProcAddress('FT_Get_First_Char');
FT_Get_Glyph := FTGetProcAddress('FT_Get_Glyph');
FT_Get_Glyph_Name := FTGetProcAddress('FT_Get_Glyph_Name');
FT_Get_Kerning := FTGetProcAddress('FT_Get_Kerning');
FT_Get_MM_Var := FTGetProcAddress('FT_Get_MM_Var');
FT_Get_Module := FTGetProcAddress('FT_Get_Module');
FT_Get_Multi_Master := FTGetProcAddress('FT_Get_Multi_Master');
FT_Get_Name_Index := FTGetProcAddress('FT_Get_Name_Index');
FT_Get_Next_Char := FTGetProcAddress('FT_Get_Next_Char');
FT_Get_PFR_Advance := FTGetProcAddress('FT_Get_PFR_Advance');
FT_Get_PFR_Kerning := FTGetProcAddress('FT_Get_PFR_Kerning');
FT_Get_PFR_Metrics := FTGetProcAddress('FT_Get_PFR_Metrics');
FT_Get_PS_Font_Info := FTGetProcAddress('FT_Get_PS_Font_Info');
FT_Get_PS_Font_Private := FTGetProcAddress('FT_Get_PS_Font_Private');
FT_Get_Postscript_Name := FTGetProcAddress('FT_Get_Postscript_Name');
FT_Get_Renderer := FTGetProcAddress('FT_Get_Renderer');
FT_Get_Sfnt_Name := FTGetProcAddress('FT_Get_Sfnt_Name');
FT_Get_Sfnt_Name_Count := FTGetProcAddress('FT_Get_Sfnt_Name_Count');
FT_Get_Sfnt_Table := FTGetProcAddress('FT_Get_Sfnt_Table');
FT_Get_SubGlyph_Info := FTGetProcAddress('FT_Get_SubGlyph_Info');
FT_Get_Track_Kerning := FTGetProcAddress('FT_Get_Track_Kerning');
FT_Get_TrueType_Engine_Type := FTGetProcAddress('FT_Get_TrueType_Engine_Type');
FT_Get_WinFNT_Header := FTGetProcAddress('FT_Get_WinFNT_Header');
FT_GlyphSlot_Embolden := FTGetProcAddress('FT_GlyphSlot_Embolden');
FT_GlyphSlot_Oblique := FTGetProcAddress('FT_GlyphSlot_Oblique');
FT_GlyphSlot_Own_Bitmap := FTGetProcAddress('FT_GlyphSlot_Own_Bitmap');
FT_Glyph_Copy := FTGetProcAddress('FT_Glyph_Copy');
FT_Glyph_Get_CBox := FTGetProcAddress('FT_Glyph_Get_CBox');
FT_Glyph_Stroke := FTGetProcAddress('FT_Glyph_Stroke');
FT_Glyph_StrokeBorder := FTGetProcAddress('FT_Glyph_StrokeBorder');
FT_Glyph_To_Bitmap := FTGetProcAddress('FT_Glyph_To_Bitmap');
FT_Glyph_Transform := FTGetProcAddress('FT_Glyph_Transform');
FT_Has_PS_Glyph_Names := FTGetProcAddress('FT_Has_PS_Glyph_Names');
FT_Init_FreeType := FTGetProcAddress('FT_Init_FreeType');
FT_Library_Version := FTGetProcAddress('FT_Library_Version');
FT_List_Add := FTGetProcAddress('FT_List_Add');
FT_List_Finalize := FTGetProcAddress('FT_List_Finalize');
FT_List_Find := FTGetProcAddress('FT_List_Find');
FT_List_Insert := FTGetProcAddress('FT_List_Insert');
FT_List_Iterate := FTGetProcAddress('FT_List_Iterate');
FT_List_Remove := FTGetProcAddress('FT_List_Remove');
FT_List_Up := FTGetProcAddress('FT_List_Up');
FT_Load_Char := FTGetProcAddress('FT_Load_Char');
FT_Load_Glyph := FTGetProcAddress('FT_Load_Glyph');
FT_Load_Sfnt_Table := FTGetProcAddress('FT_Load_Sfnt_Table');
FT_Matrix_Invert := FTGetProcAddress('FT_Matrix_Invert');
FT_Matrix_Multiply := FTGetProcAddress('FT_Matrix_Multiply');
FT_MulDiv := FTGetProcAddress('FT_MulDiv');
FT_MulFix := FTGetProcAddress('FT_MulFix');
FT_New_Face := FTGetProcAddress('FT_New_Face');
FT_New_Library := FTGetProcAddress('FT_New_Library');
FT_New_Memory_Face := FTGetProcAddress('FT_New_Memory_Face');
FT_New_Size := FTGetProcAddress('FT_New_Size');
FT_OpenType_Free := FTGetProcAddress('FT_OpenType_Free');
FT_OpenType_Validate := FTGetProcAddress('FT_OpenType_Validate');
FT_Open_Face := FTGetProcAddress('FT_Open_Face');
FT_Outline_Check := FTGetProcAddress('FT_Outline_Check');
FT_Outline_Copy := FTGetProcAddress('FT_Outline_Copy');
FT_Outline_Decompose := FTGetProcAddress('FT_Outline_Decompose');
FT_Outline_Done := FTGetProcAddress('FT_Outline_Done');
FT_Outline_Done_Internal := FTGetProcAddress('FT_Outline_Done_Internal');
FT_Outline_Embolden := FTGetProcAddress('FT_Outline_Embolden');
FT_Outline_GetInsideBorder := FTGetProcAddress('FT_Outline_GetInsideBorder');
FT_Outline_GetOutsideBorder := FTGetProcAddress('FT_Outline_GetOutsideBorder');
FT_Outline_Get_BBox := FTGetProcAddress('FT_Outline_Get_BBox');
FT_Outline_Get_Bitmap := FTGetProcAddress('FT_Outline_Get_Bitmap');
FT_Outline_Get_CBox := FTGetProcAddress('FT_Outline_Get_CBox');
FT_Outline_Get_Orientation := FTGetProcAddress('FT_Outline_Get_Orientation');
FT_Outline_New := FTGetProcAddress('FT_Outline_New');
FT_Outline_New_Internal := FTGetProcAddress('FT_Outline_New_Internal');
FT_Outline_Render := FTGetProcAddress('FT_Outline_Render');
FT_Outline_Reverse := FTGetProcAddress('FT_Outline_Reverse');
FT_Outline_Transform := FTGetProcAddress('FT_Outline_Transform');
FT_Outline_Translate := FTGetProcAddress('FT_Outline_Translate');
FT_Remove_Module := FTGetProcAddress('FT_Remove_Module');
FT_Render_Glyph := FTGetProcAddress('FT_Render_Glyph');
FT_Request_Size := FTGetProcAddress('FT_Request_Size');
FT_RoundFix := FTGetProcAddress('FT_RoundFix');
FT_Select_Charmap := FTGetProcAddress('FT_Select_Charmap');
FT_Select_Size := FTGetProcAddress('FT_Select_Size');
FT_Set_Char_Size := FTGetProcAddress('FT_Set_Char_Size');
FT_Set_Charmap := FTGetProcAddress('FT_Set_Charmap');
FT_Set_Debug_Hook := FTGetProcAddress('FT_Set_Debug_Hook');
FT_Set_MM_Blend_Coordinates := FTGetProcAddress('FT_Set_MM_Blend_Coordinates');
FT_Set_MM_Design_Coordinates := FTGetProcAddress('FT_Set_MM_Design_Coordinates');
FT_Set_Pixel_Sizes := FTGetProcAddress('FT_Set_Pixel_Sizes');
FT_Set_Renderer := FTGetProcAddress('FT_Set_Renderer');
FT_Set_Transform := FTGetProcAddress('FT_Set_Transform');
FT_Set_Var_Blend_Coordinates := FTGetProcAddress('FT_Set_Var_Blend_Coordinates');
FT_Set_Var_Design_Coordinates := FTGetProcAddress('FT_Set_Var_Design_Coordinates');
FT_Sfnt_Table_Info := FTGetProcAddress('FT_Sfnt_Table_Info');
FT_Sin := FTGetProcAddress('FT_Sin');
FT_Stream_OpenGzip := FTGetProcAddress('FT_Stream_OpenGzip');
FT_Stream_OpenLZW := FTGetProcAddress('FT_Stream_OpenLZW');
FT_Stroker_BeginSubPath := FTGetProcAddress('FT_Stroker_BeginSubPath');
FT_Stroker_ConicTo := FTGetProcAddress('FT_Stroker_ConicTo');
FT_Stroker_CubicTo := FTGetProcAddress('FT_Stroker_CubicTo');
FT_Stroker_Done := FTGetProcAddress('FT_Stroker_Done');
FT_Stroker_EndSubPath := FTGetProcAddress('FT_Stroker_EndSubPath');
FT_Stroker_Export := FTGetProcAddress('FT_Stroker_Export');
FT_Stroker_ExportBorder := FTGetProcAddress('FT_Stroker_ExportBorder');
FT_Stroker_GetBorderCounts := FTGetProcAddress('FT_Stroker_GetBorderCounts');
FT_Stroker_GetCounts := FTGetProcAddress('FT_Stroker_GetCounts');
FT_Stroker_LineTo := FTGetProcAddress('FT_Stroker_LineTo');
FT_Stroker_New := FTGetProcAddress('FT_Stroker_New');
FT_Stroker_ParseOutline := FTGetProcAddress('FT_Stroker_ParseOutline');
FT_Stroker_Rewind := FTGetProcAddress('FT_Stroker_Rewind');
FT_Stroker_Set := FTGetProcAddress('FT_Stroker_Set');
FT_Tan := FTGetProcAddress('FT_Tan');
FT_TrueTypeGX_Free := FTGetProcAddress('FT_TrueTypeGX_Free');
FT_TrueTypeGX_Validate := FTGetProcAddress('FT_TrueTypeGX_Validate');
FT_Vector_From_Polar := FTGetProcAddress('FT_Vector_From_Polar');
FT_Vector_Length := FTGetProcAddress('FT_Vector_Length');
FT_Vector_Polarize := FTGetProcAddress('FT_Vector_Polarize');
FT_Vector_Rotate := FTGetProcAddress('FT_Vector_Rotate');
FT_Vector_Transform := FTGetProcAddress('FT_Vector_Transform');
FT_Vector_Unit := FTGetProcAddress('FT_Vector_Unit');
Result := True;
end;
// IsFreetypeInitialized
//
function IsFreetypeInitialized: Boolean;
begin
Result := (FTHandle <> INVALID_MODULEHANDLE);
end;
initialization
finalization
CloseFreetype;
end.
|
unit uObjectFeatureList;
interface
uses SysUtils, Types, Contnrs, uObjectFeature;
type
TFeaList = class(TObjectList)
protected
function GetItem(Index: Integer): TFeatureObject;
procedure SetItem(Index: Integer; FeaObj: TFeatureObject);
public
property Objects[Index: Integer]: TFeatureObject read GetItem write SetItem; default;
function _ToString: string;
end;
implementation
{ TFeaList }
function TFeaList.GetItem(Index: Integer): TFeatureObject;
begin
result := (Items[Index] as TFeatureObject);
end;
procedure TFeaList.SetItem(Index: Integer; FeaObj: TFeatureObject);
begin
Items[Index] := FeaObj;
end;
function TFeaList._ToString: string;
var
s: string;
i: Integer;
begin
s := '--- TFeaList DUMP ---' + #13+#10;
for i := 0 to Count-1 do
s := s + '#:' + IntToStr(i) + ', ID:' +inttostr(GetItem(i).ID) + ', Typ:' + IntToStr(GetItem(i).Typ) + #13+#10;
Result := s;
end;
end.
|
unit Chronogears.Azure.Model;
interface
type
TAzureConnection = class
public
TenantId: string;
SubscriptionId: string;
ClientId: string;
ClientSecret: string;
Resource: string;
RedirectURL: string;
AuthorizeEndPoint: string;
TokenEndPoint: string;
RESTEndPoint: string;
AuthCode: string;
AuthToken: string;
end;
implementation
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.