text stringlengths 14 6.51M |
|---|
unit ntvCtrls;
{$mode objfpc}{$H+}
interface
uses
Classes, Messages, Controls, StdCtrls, ExtCtrls, SysUtils, Math, Contnrs, Graphics, Forms,
LCLType, LCLIntf, LMessages, LCLProc, ntvThemes,
ntvUtils;
type
{ TntvCustomControl }
TntvCustomControl = class(TCustomControl)
protected
procedure InvalidateRect(ARect : TRect; Erase : Boolean); virtual; //this should be in Lazarus TCustomControl
end;
{ TntvEdit }
TntvEdit = class(TEdit, IThemeNotify)
protected
procedure InvalidateTheme;
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Color;
end;
implementation
{ TntvEdit }
procedure TntvEdit.InvalidateTheme;
begin
Color := Theme.Default.Background;
Font.Color := Theme.Default.Foreground;
Invalidate;
end;
procedure TntvEdit.Loaded;
begin
inherited Loaded;
if ParentColor then
begin
Color := Theme.Default.Background;
Font.Color := Theme.Default.Foreground;
end;
end;
constructor TntvEdit.Create(AOwner: TComponent);
begin
inherited;
ThemeEngine.AddNotification(Self);
end;
destructor TntvEdit.Destroy;
begin
ThemeEngine.RemoveNotification(Self);
inherited;
end;
{ TntvCustomControl }
procedure TntvCustomControl.InvalidateRect(ARect: TRect; Erase: Boolean);
begin
LCLIntf.InvalidateRect(Handle, @ARect, Erase);
end;
end.
|
unit raiden_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nec_v20_v30,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine,
sound_engine,seibu_sound,misc_functions;
function iniciar_raiden:boolean;
implementation
const
raiden_rom_main:array[0..3] of tipo_roms=(
(n:'1.u0253';l:$10000;p:0;crc:$a4b12785),(n:'2.u0252';l:$10000;p:$1;crc:$17640bd5),
(n:'3.u022';l:$20000;p:$20000;crc:$f6af09d0),(n:'4j.u023';l:$20000;p:$20001;crc:$505c4c5d));
raiden_rom_sub:array[0..1] of tipo_roms=(
(n:'5.u042';l:$20000;p:0;crc:$ed03562e),(n:'6.u043';l:$20000;p:1;crc:$a19d5b5d));
raiden_sound:tipo_roms=(n:'8.u212';l:$10000;p:0;crc:$cbe055c7);
raiden_chars:array[0..1] of tipo_roms=(
(n:'9';l:$8000;p:1;crc:$1922b25e),(n:'10';l:$8000;p:0;crc:$5f90786a));
raiden_bgtiles:tipo_roms=(n:'sei420';l:$80000;p:0;crc:$da151f0b);
raiden_fgtiles:tipo_roms=(n:'sei430';l:$80000;p:0;crc:$ac1f57ac);
raiden_sprites:tipo_roms=(n:'sei440';l:$80000;p:0;crc:$946d7bde);
raiden_oki:tipo_roms=(n:'7.u203';l:$10000;p:0;crc:$8f927822);
CPU_SYNC=1;
var
main_rom:array[0..$5ffff] of byte;
sub_rom:array[0..$3ffff] of byte;
scroll_ram:array[0..$3f] of byte;
ram:array[0..$8fff] of byte;
sub_ram:array[0..$2fff] of byte;
text:array[0..$7ff] of byte;
bg_enabled,fg_enabled,tx_enabled,sp_enabled:boolean;
procedure update_video_raiden;
var
f,x,y,nchar,scroll_x,scroll_y:word;
color,atrib:byte;
procedure draw_sprites(prio:byte);
var
atrib,atrib2,f,color:byte;
sx,sy,nchar:word;
begin
for f:=$ff downto 0 do begin
atrib2:=ram[$7005+(f*8)];
if prio<>(atrib2 shr 6) then continue;
atrib:=ram[$7001+(f*8)];
if (atrib and $80)=0 then continue;
sx:=ram[$7000+(f*8)];
nchar:=ram[$7002+(f*8)]+((ram[$7003+(f*8)] and $f) shl 8);
color:=(atrib and $f) shl 4;
if (atrib2 and 1)<>0 then sy:=(240-ram[$7004+(f*8)]) or $fe00
else sy:=240-ram[$7004+(f*8)];
put_gfx_sprite(nchar,color+$200,(atrib and $40)<>0,(atrib and $20)<>0,3);
actualiza_gfx_sprite(sx,sy,4,3);
end;
end;
begin
for f:=0 to $3ff do begin
//Text
if tx_enabled then begin
atrib:=text[(f*2)+1];
color:=atrib and $f;
if (gfx[0].buffer[f] or buffer_color[color+$30]) then begin
x:=f div 32;
y:=31-(f mod 32);
nchar:=text[(f*2)+0] or ((atrib and $c0) shl 2);
put_gfx_trans(x*8,y*8,nchar,(color shl 4)+$300,1,0);
gfx[0].buffer[f]:=false;
end;
end;
//Back
if bg_enabled then begin
atrib:=sub_ram[(f*2)+$2001];
color:=atrib shr 4;
if (gfx[1].buffer[f] or buffer_color[color]) then begin
x:=f mod 32;
y:=31-(f div 32);
nchar:=sub_ram[(f*2)+$2000] or ((atrib and $f) shl 8);
put_gfx(x*16,y*16,nchar,color shl 4,2,1);
gfx[1].buffer[f]:=false;
end;
end;
//Front
if fg_enabled then begin
atrib:=sub_ram[(f*2)+$2801];
color:=atrib shr 4;
if (gfx[2].buffer[f] or buffer_color[color+$10]) then begin
x:=f mod 32;
y:=31-(f div 32);
nchar:=sub_ram[(f*2)+$2800] or ((atrib and $f) shl 8);
put_gfx_trans(x*16,y*16,nchar,(color shl 4)+$100,3,2);
gfx[2].buffer[f]:=false;
end;
end;
end;
//if sp_enabled then draw_sprites(0); No sirve de nada!
if bg_enabled then begin
scroll_y:=((scroll_ram[$12] and $f0) shl 4) or ((scroll_ram[$14] and $7f) shl 1) or ((scroll_ram[$14] and $80) shr 7);
scroll_x:=((scroll_ram[$02] and $f0) shl 4) or ((scroll_ram[$04] and $7f) shl 1) or ((scroll_ram[$04] and $80) shr 7);
scroll_x_y(2,4,scroll_x,256-scroll_y);
end else fill_full_screen(4,$500);
if sp_enabled then draw_sprites(1);
if fg_enabled then begin
scroll_y:=((scroll_ram[$32] and $f0) shl 4) or ((scroll_ram[$34] and $7f) shl 1) or ((scroll_ram[$34] and $80) shr 7);
scroll_x:=((scroll_ram[$22] and $f0) shl 4) or ((scroll_ram[$24] and $7f) shl 1) or ((scroll_ram[$24] and $80) shr 7);
scroll_x_y(3,4,scroll_x,256-scroll_y);
end;
if sp_enabled then draw_sprites(2);
if sp_enabled then draw_sprites(3);
if tx_enabled then actualiza_trozo(0,0,256,256,1,0,0,256,256,4);
actualiza_trozo_final(16,0,224,256,4);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
end;
procedure eventos_raiden;
begin
if event.arcade then begin
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or $1);
if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or $2);
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or $4);
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fff7) else marcade.in0:=(marcade.in0 or $8);
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $ff7f) else marcade.in0:=(marcade.in0 or $80);
if arcade_input.up[1] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $100);
if arcade_input.down[1] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200);
if arcade_input.left[1] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $400);
if arcade_input.right[1] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $800);
if arcade_input.but0[1] then marcade.in0:=(marcade.in0 and $efff) else marcade.in0:=(marcade.in0 or $1000);
if arcade_input.but1[1] then marcade.in0:=(marcade.in0 and $dfff) else marcade.in0:=(marcade.in0 or $2000);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $7fff) else marcade.in0:=(marcade.in0 or $8000);
if arcade_input.coin[0] then seibu_snd_0.input:=(seibu_snd_0.input or $1) else seibu_snd_0.input:=(seibu_snd_0.input and $fe);
if arcade_input.coin[1] then seibu_snd_0.input:=(seibu_snd_0.input or $2) else seibu_snd_0.input:=(seibu_snd_0.input and $fd);
end;
end;
procedure raiden_principal;
var
frame_m,frame_s,frame_sub:single;
f,h:byte;
begin
init_controls(false,false,false,true);
frame_m:=nec_0.tframes;
frame_sub:=nec_1.tframes;
frame_s:=seibu_snd_0.z80.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
for h:=1 to CPU_SYNC do begin
//Main CPU
nec_0.run(frame_m);
frame_m:=frame_m+nec_0.tframes-nec_0.contador;
//Sub CPU
nec_1.run(frame_sub);
frame_sub:=frame_sub+nec_1.tframes-nec_1.contador;
//Sound CPU
seibu_snd_0.z80.run(frame_s);
frame_s:=frame_s+seibu_snd_0.z80.tframes-seibu_snd_0.z80.contador;
end;
if f=239 then begin
nec_0.vect_req:=$c8 div 4;
nec_0.change_irq(HOLD_LINE);
nec_1.vect_req:=$c8 div 4;
nec_1.change_irq(HOLD_LINE);
update_video_raiden;
end;
end;
eventos_raiden;
video_sync;
end;
end;
function raiden_getbyte(direccion:dword):byte;
begin
case direccion of
$0..$8fff:raiden_getbyte:=ram[direccion];
$a000..$a00d:raiden_getbyte:=seibu_snd_0.get((direccion and $e) shr 1);
$e000:raiden_getbyte:=marcade.in0 and $ff;
$e001:raiden_getbyte:=marcade.in0 shr 8;
$e002,$e003:raiden_getbyte:=$ff;
$a0000..$fffff:raiden_getbyte:=main_rom[direccion-$a0000];
end;
end;
procedure raiden_putbyte(direccion:dword;valor:byte);
begin
case direccion of
$0..$8fff:ram[direccion]:=valor;
$a000..$a00d:seibu_snd_0.put((direccion and $e) shr 1,valor);
$c000..$c7ff:if text[direccion and $7ff]<>valor then begin
text[direccion and $7ff]:=valor;
gfx[0].buffer[(direccion and $7ff) shr 1]:=true;
end;
$e004,$e005:;
$e006:begin
bg_enabled:=(valor and 1)=0;
fg_enabled:=(valor and 2)=0;
tx_enabled:=(valor and 4)=0;
sp_enabled:=(valor and 8)=0;
main_screen.flip_main_screen:=(valor and $40)<>0;
end;
$f000..$f03f:scroll_ram[direccion and $3f]:=valor;
$a0000..$fffff:; //ROM
end;
end;
function raiden_sub_getbyte(direccion:dword):byte;
begin
case direccion of
$0..$2fff:raiden_sub_getbyte:=sub_ram[direccion];
$3000..$3fff:raiden_sub_getbyte:=buffer_paleta[direccion and $fff];
$4000..$4fff:raiden_sub_getbyte:=ram[$8000+(direccion and $fff)];
$c0000..$fffff:raiden_sub_getbyte:=sub_rom[direccion-$c0000];
end;
end;
procedure raiden_sub_putbyte(direccion:dword;valor:byte);
procedure cambiar_color(dir:word);
var
color:tcolor;
tmp_color:byte;
begin
tmp_color:=buffer_paleta[dir or 1];
color.b:=pal4bit(tmp_color shr 0);
tmp_color:=buffer_paleta[dir];
color.g:=pal4bit(tmp_color shr 4);
color.r:=pal4bit(tmp_color);
dir:=dir shr 1;
set_pal_color(color,dir);
case dir of
0..$ff:buffer_color[(dir shr 4) and $f]:=true; //back
$100..$1ff:buffer_color[((dir shr 4) and $f)+$10]:=true; //front
$300..$3ff:buffer_color[((dir shr 4) and $f)+$30]:=true; //text
end;
end;
begin
case direccion of
$0..$1fff:sub_ram[direccion]:=valor;
$2000..$27ff:if sub_ram[direccion]<>valor then begin
sub_ram[direccion]:=valor;
gfx[1].buffer[(direccion and $7ff) shr 1]:=true;
end;
$2800..$2fff:if sub_ram[direccion]<>valor then begin
sub_ram[direccion]:=valor;
gfx[2].buffer[(direccion and $7ff) shr 1]:=true;
end;
$3000..$3fff:if buffer_paleta[direccion and $fff]<>valor then begin
buffer_paleta[direccion and $fff]:=valor;
cambiar_color(direccion and $ffe);
end;
$4000..$4fff:ram[$8000+(direccion and $fff)]:=valor;
$c0000..$fffff:; //ROM
end;
end;
//Main
procedure reset_raiden;
begin
nec_0.reset;
nec_1.reset;
seibu_snd_0.reset;
reset_audio;
marcade.in0:=$ffff;
seibu_snd_0.input:=0;
bg_enabled:=true;
fg_enabled:=true;
tx_enabled:=true;
sp_enabled:=true;
end;
function iniciar_raiden:boolean;
const
pc_x:array[0..15] of dword=(0, 1, 2, 3,16+0, 16+1, 16+2, 16+3,
16*16*2+0, 16*16*2+1, 16*16*2+2, 16*16*2+3, 16*16*2+16+0, 16*16*2+16+1, 16*16*2+16+2, 16*16*2+16+3);
pc_y:array[0..15] of dword=(0*16*2, 1*16*2, 2*16*2, 3*16*2, 4*16*2, 5*16*2, 6*16*2, 7*16*2,
8*16*2, 9*16*2, 10*16*2, 11*16*2, 12*16*2, 13*16*2, 14*16*2, 15*16*2);
main_xor_table:array[0..$f] of word=($200e,$0006,$000a,$0002,$240e,$000e,$04c2,$00c2,$008c,$0004,$0088,$0000,$048c,$000c,$04c0,$00c0);
sub_xor_table:array[0..7] of word=($0080,$0080,$0244,$0288,$0288,$0288,$1041,$1009);
var
memoria_temp:pbyte;
ptemp:pword;
f:dword;
tempw:word;
begin
iniciar_raiden:=false;
llamadas_maquina.reset:=reset_raiden;
llamadas_maquina.fps_max:=59.599998;
llamadas_maquina.bucle_general:=raiden_principal;
iniciar_audio(false);
screen_init(1,256,256,true);
screen_init(2,512,512);
screen_mod_scroll(2,512,256,511,512,256,511);
screen_init(3,512,512,true);
screen_mod_scroll(3,512,256,511,512,256,511);
screen_init(4,256,512,false,true);
iniciar_video(224,256);
//Main CPU
nec_0:=cpu_nec.create(10000000,256*CPU_SYNC,NEC_V30);
nec_0.change_ram_calls(raiden_getbyte,raiden_putbyte);
if not(roms_load16b(@main_rom,raiden_rom_main)) then exit;
ptemp:=@main_rom[$20000];
for f:=0 to $1ffff do begin
tempw:=ptemp^;
tempw:=tempw xor main_xor_table[f and $f];
tempw:=BITSWAP16(tempw,15,14,10,12,11,13,9,8,3,2,5,4,7,1,6,0);
ptemp^:=tempw;
inc(ptemp);
end;
//Sub CPU
nec_1:=cpu_nec.create(10000000,256*CPU_SYNC,NEC_V30);
nec_1.change_ram_calls(raiden_sub_getbyte,raiden_sub_putbyte);
if not(roms_load16b(@sub_rom,raiden_rom_sub)) then exit;
ptemp:=@sub_rom[0];
for f:=0 to $1ffff do begin
tempw:=ptemp^;
tempw:=tempw xor sub_xor_table[f and 7];
tempw:=BITSWAP16(tempw,15,14,13,9,11,10,12,8,2,0,5,4,7,3,1,6);
ptemp^:=tempw;
inc(ptemp);
end;
getmem(memoria_temp,$100000);
//sound
if not(roms_load(memoria_temp,raiden_sound)) then exit;
copymemory(@mem_snd,memoria_temp,$8000);
seibu_snd_0:=seibu_snd_type.create(SEIBU_OKI,3579545,256*CPU_SYNC,memoria_temp,true);
copymemory(@seibu_snd_0.sound_rom[0,0],@memoria_temp[$8000],$8000);
copymemory(@seibu_snd_0.sound_rom[1,0],@memoria_temp[0],$8000);
if not(roms_load(seibu_snd_0.oki_6295_get_rom_addr,raiden_oki)) then exit;
//convertir chars
if not(roms_load16b(memoria_temp,raiden_chars)) then exit;
init_gfx(0,8,8,$800);
gfx[0].trans[15]:=true;
gfx_set_desc_data(4,0,8*8*4,12,8,4,0);
convert_gfx(0,0,memoria_temp,@pc_x,@pc_y,false,true);
//bgtiles
if not(roms_load(memoria_temp,raiden_bgtiles)) then exit;
init_gfx(1,16,16,$1000);
gfx_set_desc_data(4,0,16*16*4,12,8,4,0);
convert_gfx(1,0,memoria_temp,@pc_x,@pc_y,false,true);
//fgtiles
if not(roms_load(memoria_temp,raiden_fgtiles)) then exit;
init_gfx(2,16,16,$1000);
gfx[2].trans[15]:=true;
convert_gfx(2,0,memoria_temp,@pc_x,@pc_y,false,true);
//convertir sprites
if not(roms_load(memoria_temp,raiden_sprites)) then exit;
init_gfx(3,16,16,$1000);
gfx[3].trans[15]:=true;
convert_gfx(3,0,memoria_temp,@pc_x,@pc_y,false,true);
freemem(memoria_temp);
reset_raiden;
iniciar_raiden:=true;
end;
end.
|
program centros;
type
centro = record
nombre :string;
universidad :string;
cantidadInvestigadores :integer;
cantidadBecarios :integer;
end;
universidad = record
nombre :string;
cantidadCentros :integer;
cantidadInvestigadores :integer;
cantidadBecarios :integer;
end;
minimos = record
primero :centro;
segundo :centro;
end;
procedure leerCentro(var c:centro);
begin
write('Ingrese el nombre del centro de investigación: ');
readln(c.nombre);
write('Ingrese la universidad a la que pertenece: ');
readln(c.universidad);
write('Ingrese la cantidad de investigadores: ');
readln(c.cantidadInvestigadores);
write('Ingrese la cantidad de becarios: ');
readln(c.cantidadBecarios);
end;
procedure informarUniversidad(u:universidad);
begin
writeln('La universidad ', u.nombre, ' tiene ', u.cantidadCentros, ' centros.')
end;
procedure reiniciarUniversidad(var u:universidad; c:centro);
begin
u.nombre := c.universidad;
u.cantidadInvestigadores := 0;
u.cantidadBecarios := 0;
end;
procedure actualizarInvestigadores(var u:universidad; c:centro);
begin
u.cantidadInvestigadores := u.cantidadInvestigadores + c.cantidadInvestigadores;
end;
procedure comprobarMaximo(var m:universidad; u:universidad);
begin
if (u.cantidadInvestigadores > m.cantidadInvestigadores) then
begin
m.cantidadInvestigadores := u.cantidadInvestigadores;
m.nombre := u.nombre;
end;
end;
procedure comprobarMinimos(var m:minimos; c:centro);
begin
if (c.cantidadBecarios <= m.primero.cantidadBecarios) then
begin
m.segundo.cantidadBecarios := m.primero.cantidadBecarios;
m.segundo.nombre := m.primero.nombre;
m.primero.cantidadBecarios := c.cantidadBecarios;
m.primero.nombre := c.nombre;
end
else
if (c.cantidadBecarios <= m.segundo.cantidadBecarios) then
begin
m.segundo.cantidadBecarios := c.cantidadBecarios;
m.segundo.nombre := c.nombre;
end;
end;
var
cenActual :centro;
uniActual, uniMaximo :universidad;
cenMinimo :minimos;
begin
cenMinimo.primero.cantidadBecarios := 999;
cenMinimo.primero.nombre := ' ';
cenMinimo.segundo.cantidadBecarios := 999;
cenMinimo.segundo.nombre := ' ';
leerCentro(cenActual);
reiniciarUniversidad(uniActual, cenActual);
while (cenActual.cantidadInvestigadores <> 0) do
begin
if (cenActual.universidad <> uniActual.nombre) then
begin
informarUniversidad(uniActual);
comprobarMaximo(uniMaximo, uniActual);
reiniciarUniversidad(uniActual, cenActual);
end;
actualizarInvestigadores(uniActual, cenActual);
comprobarMinimos(cenMinimo, cenActual);
uniActual.cantidadCentros := uniActual.cantidadCentros + 1;
leerCentro(cenActual);
end;
writeln(
'La universidad con mayor cantidad de investigadores es :',
uniMaximo.nombre
);
writeln(
'Los dos centros con menor cantidad de becarios son: ',
cenMinimo.primero.nombre, ' y ',
cenMinimo.segundo.nombre
);
end. |
{$I ACBr.inc}
unit ASCIOTConfiguracoes;
interface
uses
ASCIOTUtil, pciotCIOT,
{$IFNDEF ACBrCTeOpenSSL}
ACBrCAPICOM_TLB, JwaWinCrypt, JwaWinType, ACBrMSXML2_TLB,
{$ENDIF}
Classes, Sysutils, pcnConversao, ActiveX;
{$IFNDEF ACBrCTeOpenSSL}
const CAPICOM_STORE_NAME = 'My'; //My CA Root AddressBook
{$ENDIF}
type
TCertificadosConf = class(TComponent)
private
FSenhaCert: AnsiString;
{$IFDEF ACBrCTeOpenSSL}
FCertificado: AnsiString;
{$ELSE}
FNumeroSerie: AnsiString;
FDataVenc: TDateTime;
procedure SetNumeroSerie(const Value: AnsiString);
function GetNumeroSerie: AnsiString;
function GetDataVenc: TDateTime;
{$ENDIF}
public
{$IFNDEF ACBrCTeOpenSSL}
function SelecionarCertificado:AnsiString;
function GetCertificado: ICertificate2;
{$ENDIF}
published
{$IFDEF ACBrCTeOpenSSL}
property Certificado: AnsiString read FCertificado write FCertificado;
{$ELSE}
property NumeroSerie: AnsiString read GetNumeroSerie write SetNumeroSerie;
property DataVenc: TDateTime read GetDataVenc;
{$ENDIF}
property Senha: AnsiString read FSenhaCert write FSenhaCert;
end;
TWebServicesConf = Class(TComponent)
private
FVisualizar : Boolean;
FAmbiente: TpcnTipoAmbiente;
FAmbienteCodigo: Integer;
FProxyHost: String;
FProxyPort: String;
FProxyUser: String;
FProxyPass: String;
FAguardarConsultaRet : Cardinal;
FTentativas : Integer;
FIntervaloTentativas : Cardinal;
FAjustaAguardaConsultaRet : Boolean;
procedure SetAmbiente(AValue: TpcnTipoAmbiente);
procedure SetTentativas(const Value: Integer);
procedure SetIntervaloTentativas(const Value: Cardinal);
public
constructor Create(AOwner: TComponent); override ;
published
property Visualizar: Boolean read FVisualizar write FVisualizar default False ;
property Ambiente: TpcnTipoAmbiente read FAmbiente write SetAmbiente default taHomologacao ;
property AmbienteCodigo: Integer read FAmbienteCodigo;
property ProxyHost: String read FProxyHost write FProxyHost;
property ProxyPort: String read FProxyPort write FProxyPort;
property ProxyUser: String read FProxyUser write FProxyUser;
property ProxyPass: String read FProxyPass write FProxyPass;
property AguardarConsultaRet : Cardinal read FAguardarConsultaRet write FAguardarConsultaRet;
property Tentativas : Integer read FTentativas write SetTentativas default 5;
property IntervaloTentativas : Cardinal read FIntervaloTentativas write SetIntervaloTentativas;
property AjustaAguardaConsultaRet : Boolean read FAjustaAguardaConsultaRet write FAjustaAguardaConsultaRet;
end;
TGeralConf = class(TComponent)
private
FFormaEmissao: TpcnTipoEmissao;
FFormaEmissaoCodigo: Integer;
FSalvar: Boolean;
FAtualizarXMLCancelado: Boolean;
FPathSalvar: String;
FPathSchemas: String;
FExibirErroSchema: boolean;
FFormatoAlerta: string;
{$IFDEF ACBrCTeOpenSSL}
FIniFinXMLSECAutomatico: boolean;
{$ENDIF}
procedure SetFormaEmissao(AValue: TpcnTipoEmissao);
function GetPathSalvar: String;
function GetFormatoAlerta: string;
public
constructor Create(AOwner: TComponent); override ;
function Save(AXMLName: String; AXMLFile: WideString; aPath: String = ''): Boolean;
published
property FormaEmissao: TpcnTipoEmissao read FFormaEmissao
write SetFormaEmissao default teNormal ;
property FormaEmissaoCodigo: Integer read FFormaEmissaoCodigo;
property Salvar: Boolean read FSalvar write FSalvar default False;
property AtualizarXMLCancelado: Boolean read FAtualizarXMLCancelado write FAtualizarXMLCancelado default True ;
property PathSalvar: String read GetPathSalvar write FPathSalvar;
property PathSchemas: String read FPathSchemas write FPathSchemas;
property ExibirErroSchema: Boolean read FExibirErroSchema write FExibirErroSchema;
property FormatoAlerta: string read GetFormatoAlerta write FFormatoAlerta;
{$IFDEF ACBrCTeOpenSSL}
property IniFinXMLSECAutomatico: Boolean read FIniFinXMLSECAutomatico write FIniFinXMLSECAutomatico;
{$ENDIF}
end;
TArquivosConf = class(TComponent)
private
FSalvar : Boolean;
FMensal : Boolean;
FLiteral : Boolean;
FPathPDF: String;
FPathLog: String;
public
constructor Create(AOwner: TComponent); override ;
published
property Salvar : Boolean read FSalvar write FSalvar default False ;
property PastaMensal: Boolean read FMensal write FMensal default False ;
property AdicionarLiteral: Boolean read FLiteral write FLiteral default False ;
property PathLog : String read FPathLog write FPathLog;
property PathPDF: String read FPathPDF write FPathPDF;
end;
TConfiguracoes = class(TComponent)
private
FGeral: TGeralConf;
FWebServices: TWebServicesConf;
FCertificados: TCertificadosConf;
FArquivos: TArquivosConf;
FIntegradora: TIntegradora;
procedure setIntegradora(const Value: TIntegradora);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Geral: TGeralConf read FGeral ;
property WebServices: TWebServicesConf read FWebServices ;
property Certificados: TCertificadosConf read FCertificados ;
property Integradora: TIntegradora read FIntegradora write setIntegradora;
property Arquivos: TArquivosConf read FArquivos ;
end;
implementation
uses Math, StrUtils, ACBrUtil, ACBrDFeUtil, DateUtils;
{ TConfiguracoes }
constructor TConfiguracoes.Create(AOwner: TComponent);
begin
inherited Create( AOwner ) ;
FGeral := TGeralConf.Create(Self);
FGeral.Name := 'GeralConf' ;
{$IFDEF COMPILER6_UP}
FGeral.SetSubComponent( true );{ para gravar no DFM/XFM }
{$ENDIF}
FWebServices := TWebServicesConf.Create(self);
FWebServices.Name := 'WebServicesConf' ;
{$IFDEF COMPILER6_UP}
FWebServices.SetSubComponent( true );{ para gravar no DFM/XFM }
{$ENDIF}
FCertificados := TCertificadosConf.Create(self);
FCertificados.Name := 'CertificadosConf' ;
{$IFDEF COMPILER6_UP}
FCertificados.SetSubComponent( true );{ para gravar no DFM/XFM }
{$ENDIF}
FArquivos := TArquivosConf.Create(self);
FArquivos.Name := 'ArquivosConf' ;
{$IFDEF COMPILER6_UP}
FArquivos.SetSubComponent( true );{ para gravar no DFM/XFM }
{$ENDIF}
FIntegradora := TIntegradora.Create;
end;
destructor TConfiguracoes.Destroy;
begin
FGeral.Free;
FWebServices.Free;
FCertificados.Free;
FArquivos.Free;
FIntegradora.Free;
inherited;
end;
procedure TConfiguracoes.setIntegradora(const Value: TIntegradora);
begin
FIntegradora := Value;
end;
{ TGeralConf }
constructor TGeralConf.Create(AOwner: TComponent);
begin
Inherited Create( AOwner );
FFormaEmissao := teNormal;
FFormaEmissaoCodigo := StrToInt(TpEmisToStr(FFormaEmissao));
FSalvar := False;
FAtualizarXMLCancelado := True;
FPathSalvar := '' ;
FPathSchemas := '' ;
FExibirErroSchema := True;
FFormatoAlerta := 'TAG:%TAGNIVEL% ID:%ID%/%TAG%(%DESCRICAO%) - %MSG%.';
// O Formato da mensagem de erro pode ser alterado pelo usuario alterando-se a property FFormatoAlerta: onde;
// %TAGNIVEL% : Representa o Nivel da TAG; ex: <transp><vol><lacres>
// %TAG% : Representa a TAG; ex: <nLacre>
// %ID% : Representa a ID da TAG; ex X34
// %MSG% : Representa a mensagem de alerta
// %DESCRICAO% : Representa a Descrição da TAG
{$IFDEF ACBrCTeOpenSSL}
FIniFinXMLSECAutomatico:=True;
{$ENDIF}
end;
function TGeralConf.GetFormatoAlerta: string;
begin
if (FFormatoAlerta = '') or (
(pos('%TAGNIVEL%',FFormatoAlerta) <= 0) and
(pos('%TAG%',FFormatoAlerta) <= 0) and
(pos('%ID%',FFormatoAlerta) <= 0) and
(pos('%MSG%',FFormatoAlerta) <= 0) and
(pos('%DESCRICAO%',FFormatoAlerta) <= 0) )then
Result := 'TAG:%TAGNIVEL% ID:%ID%/%TAG%(%DESCRICAO%) - %MSG%.'
else
Result := FFormatoAlerta;
end;
function TGeralConf.GetPathSalvar: String;
begin
if EstaVazio(FPathSalvar) then
Result := ApplicationPath
else
Result := FPathSalvar;
Result := PathWithDelim( Trim(Result) ) ;
end;
function TGeralConf.Save(AXMLName: String; AXMLFile: WideString; aPath: String = ''): Boolean;
var
vSalvar: TStrings;
begin
Result := False;
vSalvar := TStringList.Create;
try
try
if NaoEstaVazio(ExtractFilePath(AXMLName)) then
begin
aPath := ExtractFilePath(AXMLName);
AXMLName := StringReplace(AXMLName,aPath,'',[rfIgnoreCase]);
end
else
begin
if EstaVazio(aPath) then
aPath := PathSalvar
else
aPath := PathWithDelim(aPath);
end;
vSalvar.Text := AXMLFile;
if not DirectoryExists( aPath ) then
ForceDirectories( aPath );
vSalvar.SaveToFile( aPath + AXMLName);
Result := True;
except on E: Exception do
raise Exception.Create('Erro ao salvar .'+E.Message);
end;
finally
vSalvar.Free;
end;
end;
procedure TGeralConf.SetFormaEmissao(AValue: TpcnTipoEmissao);
begin
FFormaEmissao := AValue;
FFormaEmissaoCodigo := StrToInt(TpEmisToStr(FFormaEmissao));
end;
{ TWebServicesConf }
constructor TWebServicesConf.Create(AOwner: TComponent);
begin
Inherited Create( AOwner );
FAmbiente := taHomologacao;
FVisualizar := False ;
FAmbienteCodigo := StrToInt(TpAmbToStr(FAmbiente));
end;
procedure TWebServicesConf.SetAmbiente(AValue: TpcnTipoAmbiente);
begin
FAmbiente := AValue;
FAmbienteCodigo := StrToInt(TpAmbToStr(AValue));
end;
procedure TWebServicesConf.SetIntervaloTentativas(const Value: Cardinal);
begin
if (Value > 0) and (Value < 1000) then
FIntervaloTentativas := 1000
else
FIntervaloTentativas := Value;
end;
procedure TWebServicesConf.SetTentativas(const Value: Integer);
begin
if Value <= 0 then
FTentativas := 5
else
FTentativas := Value;
end;
{ TCertificadosConf }
{$IFNDEF ACBrCTeOpenSSL}
function TCertificadosConf.GetCertificado: ICertificate2;
var
Store : IStore3;
Certs : ICertificates2;
Cert : ICertificate2;
i : Integer;
xmldoc : IXMLDOMDocument3;
xmldsig : IXMLDigitalSignature;
dsigKey : IXMLDSigKey;
SigKey : IXMLDSigKeyEx;
PrivateKey : IPrivateKey;
//hCryptProvider : HCRYPTPROV;
hCryptProvider : ULONG_PTR;
XML : String;
begin
CoInitialize(nil); // PERMITE O USO DE THREAD
if EstaVazio( FNumeroSerie ) then
raise Exception.Create('Número de Série do Certificado Digital não especificado !');
Result := nil;
Store := CoStore.Create;
Store.Open(CAPICOM_CURRENT_USER_STORE, CAPICOM_STORE_NAME, CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
Certs := Store.Certificates as ICertificates2;
for i:= 1 to Certs.Count do
begin
Cert := IInterface(Certs.Item[i]) as ICertificate2;
if Cert.SerialNumber = FNumeroSerie then
begin
if EstaVazio(NumCertCarregado) then
NumCertCarregado := Cert.SerialNumber;
PrivateKey := Cert.PrivateKey;
if CertStoreMem = nil then
begin
CertStoreMem := CoStore.Create;
CertStoreMem.Open(CAPICOM_MEMORY_STORE, 'Memoria', CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
CertStoreMem.Add(Cert);
if (FSenhaCert <> '') and PrivateKey.IsHardwareDevice then
begin
XML := XML + '<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />';
XML := XML + '<Reference URI="#">';
XML := XML + '<Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /><Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />';
XML := XML + '<DigestValue></DigestValue></Reference></SignedInfo><SignatureValue></SignatureValue><KeyInfo></KeyInfo></Signature>';
xmldoc := CoDOMDocument50.Create;
xmldoc.async := False;
xmldoc.validateOnParse := False;
xmldoc.preserveWhiteSpace := True;
xmldoc.loadXML(XML);
xmldoc.setProperty('SelectionNamespaces', DSIGNS);
xmldsig := CoMXDigitalSignature50.Create;
xmldsig.signature := xmldoc.selectSingleNode('.//ds:Signature');
xmldsig.store := CertStoreMem;
dsigKey := xmldsig.createKeyFromCSP(PrivateKey.ProviderType, PrivateKey.ProviderName, PrivateKey.ContainerName, 0);
if (dsigKey = nil) then
raise Exception.Create('Erro ao criar a chave do CSP.');
SigKey := dsigKey as IXMLDSigKeyEx;
SigKey.getCSPHandle( hCryptProvider );
try
CryptSetProvParam( hCryptProvider , PP_SIGNATURE_PIN, LPBYTE(FSenhaCert), 0 );
finally
CryptReleaseContext(hCryptProvider, 0);
end;
SigKey := nil;
dsigKey := nil;
xmldsig := nil;
xmldoc := nil;
end;
end;
Result := Cert;
FDataVenc := Cert.ValidToDate;
break;
end;
end;
if not(Assigned(Result)) then
raise Exception.Create('Certificado Digital não encontrado!');
CoUninitialize;
end;
function TCertificadosConf.GetNumeroSerie: AnsiString;
begin
Result := Trim(UpperCase(StringReplace(FNumeroSerie,' ','',[rfReplaceAll] )));
end;
procedure TCertificadosConf.SetNumeroSerie(const Value: AnsiString);
begin
FNumeroSerie := Trim(UpperCase(StringReplace(Value,' ','',[rfReplaceAll] )));
end;
function TCertificadosConf.SelecionarCertificado: AnsiString;
var
Store : IStore3;
Certs : ICertificates2;
Certs2 : ICertificates2;
Cert : ICertificate2;
begin
CoInitialize(nil); // PERMITE O USO DE THREAD
Store := CoStore.Create;
Store.Open(CAPICOM_CURRENT_USER_STORE, CAPICOM_STORE_NAME, CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
Certs := Store.Certificates as ICertificates2;
Certs2 := Certs.Select('Certificado(s) Digital(is) disponível(is)', 'Selecione o Certificado Digital para uso no aplicativo', false);
if not(Certs2.Count = 0) then
begin
Cert := IInterface(Certs2.Item[1]) as ICertificate2;
FNumeroSerie := Cert.SerialNumber;
FDataVenc := Cert.ValidToDate;
end;
Result := FNumeroSerie;
CoUninitialize;
end;
function TCertificadosConf.GetDataVenc: TDateTime;
begin
if NaoEstaVazio(FNumeroSerie) then
begin
if FDataVenc = 0 then
GetCertificado;
Result := FDataVenc;
end
else
Result := 0;
end;
{$ENDIF}
{ TArquivosConf }
constructor TArquivosConf.Create(AOwner: TComponent);
begin
inherited;
end;
end.
|
unit UserUnit;
interface
uses
REST.Json.Types, System.Generics.Collections, SysUtils,
JSONNullableAttributeUnit,
NullableBasicTypesUnit, GenericParametersUnit, EnumsUnit;
type
/// <summary>
/// Response json schema for the retrieved member's object
/// </summary>
/// <remarks>
/// https://github.com/route4me/json-schemas/blob/master/Member_response.dtd
/// </remarks>
TUser = class(TGenericParameters)
private
[JSONName('member_id')]
[Nullable]
FMemberId: NullableInteger;
[JSONName('account_type_id')]
[Nullable]
FAccountTypeId: NullableInteger;
[JSONName('member_type')]
[Nullable]
FMemberType: NullableString;
[JSONName('member_first_name')]
[Nullable]
FFirstName: NullableString;
[JSONName('member_last_name')]
[Nullable]
FLastName: NullableString;
[JSONName('member_email')]
[Nullable]
FEmail: NullableString;
[JSONName('phone_number')]
[Nullable]
FPhoneNumber: NullableString;
[JSONName('readonly_user')]
[Nullable]
FReadonlyUser: NullableBoolean;
[JSONName('show_superuser_addresses')]
[Nullable]
FShowSuperuserAddresses: NullableBoolean;
[JSONName('api_key')]
[Nullable]
FApiKey: NullableString;
[JSONName('hashed_member_id')]
[Nullable]
FHashedMemberId: NullableString;
function GetMemberType: TMemberType;
procedure SetMemberType(const Value: TMemberType);
public
/// <remarks>
/// Constructor with 0-arguments must be and be public.
/// For JSON-deserialization.
/// </remarks>
constructor Create; overload; override;
function Equals(Obj: TObject): Boolean; override;
/// <summary>
/// A first name of the member
/// </summary>
property FirstName: NullableString read FFirstName write FFirstName;
/// <summary>
/// A last name of the member
/// </summary>
property LastName: NullableString read FLastName write FLastName;
/// <summary>
/// An email of the member
/// </summary>
property Email: NullableString read FEmail write FEmail;
/// <summary>
/// A phone number of the member
/// </summary>
property PhoneNumber: NullableString read FPhoneNumber write FPhoneNumber;
/// <summary>
/// An unique ID of the member
/// </summary>
property MemberId: NullableInteger read FMemberId write FMemberId;
/// <summary>
/// Account type ID of the member
/// </summary>
property AccountTypeId: NullableInteger read FAccountTypeId write FAccountTypeId;
/// <summary>
/// A type of the member
/// </summary>
property MemberType: TMemberType read GetMemberType write SetMemberType;
/// <summary>
/// True if value is '1'
/// </summary>
property ReadonlyUser: NullableBoolean read FReadonlyUser write FReadonlyUser;
/// <summary>
/// Show superuser addresses
/// </summary>
property ShowSuperuserAddresses: NullableBoolean read FShowSuperuserAddresses write FShowSuperuserAddresses;
/// <summary>
/// Api key of the user
/// </summary>
property ApiKey: NullableString read FApiKey write FApiKey;
/// <summary>
/// Hashed member ID string
/// </summary>
property HashedMemberId: NullableString read FHashedMemberId write FHashedMemberId;
end;
TUserList = TObjectList<TUser>;
implementation
{ TUser }
constructor TUser.Create;
begin
Inherited Create;
FMemberId := NullableInteger.Null;
FAccountTypeId := NullableInteger.Null;
FMemberType := NullableString.Null;
FReadonlyUser := NullableBoolean.Null;
FShowSuperuserAddresses := NullableBoolean.Null;
FFirstName := EmptyStr;
FLastName := EmptyStr;
FEmail := EmptyStr;
FPhoneNumber := EmptyStr;
end;
function TUser.Equals(Obj: TObject): Boolean;
var
Other: TUser;
begin
Result := False;
if not (Obj is TUser) then
Exit;
Other := TUser(Obj);
Result :=
(FMemberId = Other.FMemberId) and
(FAccountTypeId = Other.FAccountTypeId) and
(FEmail = Other.FEmail) and
(FMemberId = Other.FMemberId) and
(FReadonlyUser = Other.FReadonlyUser) and
(FShowSuperuserAddresses = Other.FShowSuperuserAddresses) and
(FFirstName = Other.FFirstName) and
(FLastName = Other.FLastName) and
(FPhoneNumber = Other.FPhoneNumber);
end;
function TUser.GetMemberType: TMemberType;
var
MemberType: TMemberType;
begin
Result := TMemberType.mtUnknown;
if FMemberType.IsNotNull then
for MemberType := Low(TMemberType) to High(TMemberType) do
if (FMemberType = TMemberTypeDescription[MemberType]) then
Exit(MemberType);
end;
procedure TUser.SetMemberType(const Value: TMemberType);
begin
FMemberType := TMemberTypeDescription[Value];
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.7 2/23/2005 6:34:26 PM JPMugaas
New property for displaying permissions ina GUI column. Note that this
should not be used like a CHMOD because permissions are different on
different platforms - you have been warned.
Rev 1.6 10/26/2004 9:36:28 PM JPMugaas
Updated ref.
Rev 1.5 4/19/2004 5:05:52 PM JPMugaas
Class rework Kudzu wanted.
Rev 1.4 2004.02.03 5:45:30 PM czhower
Name changes
Rev 1.3 1/22/2004 4:42:38 PM SPerry
fixed set problems
Rev 1.2 10/19/2003 2:27:04 PM DSiders
Added localization comments.
Rev 1.1 4/7/2003 04:03:42 PM JPMugaas
User can now descover what output a parser may give.
Rev 1.0 2/19/2003 10:13:20 PM JPMugaas
Moved parsers to their own classes.
}
unit IdFTPListParseBullGCOS8;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase, IdFTPListTypes;
type
TIdFTPLPGOS8ListItem = class(TIdUnixPermFTPListItem);
TIdFTPLPGOS8 = class(TIdFTPListBase)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseBullGCOS8"'*)
implementation
uses
IdException,
IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils;
{ TIdFTPLPGOS8 }
class function TIdFTPLPGOS8.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
var
LData : String;
begin
{
d rwx rwx --- 0 02/25/98 ftptest2 catalog1
- rwx rwx --- 1280 05/06/98 10:12:10 uid testbcd
12345678901234567890123456789012345678901234567890123456789012345678901234567890
1 2 3 4 5 6 7 8
}
Result := False;
if AListing.Count > 0 then
begin
LData := AListing[0];
Result := (Length(LData) > 59) and
(CharIsInSet(LData, 1, 'd-')) and {Do not Localize}
(LData[2] = ' ') and
(CharIsInSet(LData, 3, 'tsrwx-')) and {Do not Localize}
(CharIsInSet(LData, 4, 'tsrwx-')) and {Do not Localize}
(CharIsInSet(LData, 5, 'tsrwx-')) and {Do not Localize}
(LData[6] = ' ') and
(CharIsInSet(LData, 7, 'tsrwx-')) and {Do not Localize}
(CharIsInSet(LData, 8, 'tsrwx-')) and {Do not Localize}
(CharIsInSet(LData, 9, 'tsrwx-')) and {Do not Localize}
(LData[10] = ' ') and
(CharIsInSet(LData, 11,'tsrwx-')) and {Do not Localize}
(CharIsInSet(LData, 12,'tsrwx-')) and {Do not Localize}
(CharIsInSet(LData, 13,'tsrwx-')) and {Do not Localize}
(LData[14] = ' ') and
IsNumeric(LData[25]) and
(LData[26] = ' ');
end;
end;
class function TIdFTPLPGOS8.GetIdent: String;
begin
Result := 'Bull GCOS8'; {do not localize}
end;
class function TIdFTPLPGOS8.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdFTPLPGOS8ListItem.Create(AOwner);
end;
class function TIdFTPLPGOS8.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
//Based on FTP 8 Administrator's and User's Guide
//which is available at: http://www.bull.com/us/cd_doc/cd_doc_data/rj05a03.pdf
// d rwx rwx --- 0 02/25/98 ftptest2 catalog1
// - rwx rwx --- 1280 05/06/98 10:12:10 uid testbcd
// 12345678901 12345678901234
// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
// 1 2 3 4 5 6 7 8
var
LBuf : String;
LI : TIdUnixPermFTPListItem;
begin
LI := AItem as TIdFTPLPGOS8ListItem;
if Length(AItem.Data) > 0 then
begin
if LI.Data[1] = 'd' then begin
LI.ItemType := ditDirectory;
end else begin
LI.ItemType := ditFile;
end;
LI.FileName := Copy(AItem.Data, 60, Length(AItem.Data));
//These may correspond roughly to Unix permissions
//The values are the same as reported with Unix emulation mode
LI.UnixOwnerPermissions := Copy(AItem.Data, 3, 3);
LI.UnixGroupPermissions := Copy(AItem.Data, 7, 3);
LI.UnixOtherPermissions := Copy(AItem.Data, 11, 3);
LI.PermissionDisplay := Copy(AItem.Data, 1, 13);
LI.Size := IndyStrToInt64(Copy(AItem.Data, 15, 11), 0);
LI.OwnerName := Trim(Copy(AItem.Data, 46, 14));
LI.ModifiedDate := DateMMDDYY(Copy(AItem.Data, 27, 8));
LBuf := Copy(AItem.Data, 36, 8);
if Length(Trim(LBuf)) > 0 then begin
LI.ModifiedDate := LI.ModifiedDate + TimeHHMMSS(LBuf);
end;
end;
Result := True;
end;
initialization
RegisterFTPListParser(TIdFTPLPGOS8);
finalization
UnRegisterFTPListParser(TIdFTPLPGOS8);
end.
|
unit WPRTEDefsConsts;
{ -----------------------------------------------------------------------------
Copyright (C) 2002-2013 by wpcubed GmbH - Author: Julian Ziersch
info: http://www.wptools.de mailto:support@wptools.de
__ __ ___ _____ _ _____
/ / /\ \ \/ _ \/__ \___ ___ | |___ |___ |
\ \/ \/ / /_)/ / /\/ _ \ / _ \| / __| / /
\ /\ / ___/ / / | (_) | (_) | \__ \ / /
\/ \/\/ \/ \___/ \___/|_|___/ /_/
*****************************************************************************
Constants and basis types for the RTF Engine
Must be platform independent
*****************************************************************************
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
----------------------------------------------------------------------------- }
{$I WPINC.INC}
interface
uses {$IFDEF DELPHIXE} System.Classes, System.SysUtils
{$ELSE} Classes, SysUtils
{$ENDIF}
, WPRTEPlatform
;
type
EWPIOClassError = class(Exception);
EWPEngineModeError = class(Exception);
EWPNoWriterClassFound = class(Exception);
TWPCustomAttrDlgAbstract = class(TComponent)
protected
FImplementsID : Integer;
public
function Execute: Boolean; virtual; abstract;
function ExecuteFor(WPRichText : TObject; Params : String = ''): Boolean; virtual; abstract;
function Show: Boolean; virtual; abstract;
function Implements(id : Integer): Boolean; virtual;
end;
TWPTableWidthMode = (
wpPageWidthPC,
wpContentsWidth,
wpTwipsWidth,
wpMMWidth
);
TWPParagraphType = (
wpIsSTDPar,
wpIsHTML_DIV,
wpIsHTML_LI,
wpIsHTML_CODE,
wpIsXMLTag,
wpIsXMLComment,
wpIsTable,
wpIsTableRow,
wpIsXMLTopLevel,
wpIsXMLSubLevel,
wpIsXMLDataLevel,
wpIsReportGroup,
wpIsReportHeaderBand,
wpIsReportDataBand,
wpIsReportFooterBand,
wpIsHTML_UOL,
wpIsTextBoxPar
);
TWPParagraphTypes = set of TWPParagraphType;
TWPClipboardOptions = set of
(wpcoNoInternalDragAndDrop,
wpcoNoDragAndDropFromOutside,
wpcoAlwaysDeleteInDragSource,
wpcoDontMoveCursorDuringDrag,
wpcoNoAutoSelSpaceExtension,
wpDontHideCaret,
wpcoDontPasteWPT, wpcoDontPasteRTF, wpcoDontPasteANSI, wpcoDontPasteUNICODE, wpcoDontPasteHTML,
wpcoPasteHTMLWhenAvailable,
wpcoDontPasteGraphics,
wpcoDontCopyRTF, wpcoDontCopyANSI, wpcoDontCopyUNICODE, wpcoDontCopyWPTOOLS, wpcoPreserveBorders, wpcoPreserveShading,
wpcoPreserveIndents,
wpcoDontAutoAppendSpace,
wpcoPasteAsNestedTable,
wpcoDontPasteFonts, wpcoDontPasteFontSizes,
wpcoDoNotUseInsertMode,
wpcoDontCopyProtectedText,
wpcoDontCopyProtectedAttribute,
wpcoAlwaysCopyImagesEmbedded,
wpcoAlsoCopyHTML,
wpcoAlsoPasteRTFVariables,
wpcoDontPasteWhenTextIsSelected,
wpcoPastedANSIDoesNotInheritParAttr
);
TWPEditOptions = set of
(wpTableResizing,
wpTableOneCellResizing,
wpTableColumnResizing,
wpTableRowResizing,
wpClearAttrOnStyleChange,
wpNoAutoWordSelection,
wpObjectMoving,
wpObjectResizingWidth,
wpObjectResizingHeight,
wpObjectResizingKeepRatio,
wpObjectSelecting,
wpObjectDeletion,
wpNoAutoScroll,
wpSpreadsheetCursorMovement,
wpAutoInsertRow,
wpNoEditOutsideTable,
wpBreakTableOnReturnInRow,
wpActivateUndo,
wpActivateUndoHotkey,
wpActivateRedo,
wpActivateRedoHotkey,
wpAlwaysInsert,
wpMoveCPOnPageUpDown,
wpAutoDetectHyperlinks,
wpNoHorzScrolling,
wpNoVertScrolling,
wpDontSelectCompleteField,
wpSelectCompleteFieldAlsoWhenInside,
wpStreamUndoOperation,
wpTabToEditFields,
wpSelectPageOnDblClick,
wpAllowCreateTableInTable
);
TWPEditOptionsEx = set of
(
wpDisableSelection,
wpDisableCaret,
wpDisableGetFocus,
wpDisableEditOfNonBodyDataBlocks,
wpAllowCursorInRow,
wpTextObjectMoving,
wpTextObjectSelecting,
wpNoAutoWordStartEndFieldSelection,
wpDisableAutoCharsetSelection,
wpIgnoreSingleCellSelection,
wpTABMovesToNextEditField,
wpDblClickCreateHeaderFooter,
wpRepaintOnFieldMove,
wpKeepCellsWhenCombiningCells,
wpAllowSplitOfCombinedCellsOnly,
wpDontClearStylesInNew,
wpDontResetPagesizeInNew,
wpSetDefaultAttrInNew,
wpAllowDrawDropBetweenTextBlocks,
wpDisableFastInitOnTyping,
wpDontTriggerPopupInContextEvent,
wpAlwaysColWidthPC,
wpDisableXPosLineUpDown,
wpDontInitSelTextAttrWithDefaultFont,
wpDontSelectCellOnSpreadsheetMovement,
wpScrollLineWise,
wpZoomWithMouseWheel,
wpTableRowResizingWithCTRL,
wpDontUseNumberIndents,
wpDontPreserveObjectsAgainstDeletion
, wpAutoCaptitalize
, wpTriggerOpenDialogForSectionProps
);
TWPEditOptionsEx2 = set of
(
wpDontAllowDragTextInFields,
wpDontAllowDragImagesInFields,
wpEnableDragFieldsInFields,
wpDisableDragDropInShowFieldsMode,
wpDisableDoubleclickSelectsMarker,
wpSuppressReplaceWordsMessage,
wpAlwaysTriggerFieldFocusEvent,
wpRowMultiSelect,
wpDeleteAtEOFRemovesSpaceAfter,
wpCellMultiSelect,
wpDisableSelectAll,
wpClearCellsOnDelete,
wpShowPageHoverframe,
wpSaveToFileCreatesBackupfile,
wpClearSelectionDontRemoveParAttr,
wpAlwaysLockTextBoxHeight,
wpNoMiddleMouseBtnScroll,
wpOnlySelectInSameCell,
wpRulerSharedBySplitscreenEditors,
wpSwapCursorKeysInRTLMode
);
TWPSecurityMode =
(wpSecDontUseGlobalSettings,
wpSecDontAllowPaste,
wpSecDontAllowCopy,
wpSecOnlyInternalClipboard,
wpSecNoSaveDialog,
wpSecNoLoadDialog,
wpSecNoPrintDialog
);
TWPSecurityModes = set of TWPSecurityMode;
TWPViewOptions = set of
(
wpShowGridlines,
wpDisableHotStyles,
wpShowCR,
wpShowCRButNotInCells,
wpShowFF,
wpShowNL,
wpShowSPC,
wpShowHardSPC,
wpShowTAB,
wpShowParCalcNames,
wpShowParCalcCommands,
wpShowParNames,
wpNoEndOfDocumentLine,
wpHideSelection,
wpHideSelectionNonFocussed,
wpHideSelectionNonFocussedAndInactive,
wpTraditionalMisspellMarkers,
wpDisableMisspellMarkers,
wpShowPageNRinGap,
wpDrawFineUnderlines,
wpDontGrayHeaderFooterInLayout,
wpInfiniteTextArea,
wpDontPaintPageFrame,
wpCenterPaintPages,
wpUseOwnDoubleBuffer,
wpDrawPageMarginLines,
wpDontDrawSectionMarker,
wpDrawHeaderFooterLines,
wpDontDisplayScrollPageHint,
wpDontDrawObjectAnchors
);
TWPViewOptionsEx = set of
(
wpAlwaysDrawImageAnchors,
wpAlwaysDrawTextboxAnchors,
wpAutoThumbnailMode,
wpDisableAllSpecialAttributes,
wpDisableCharacterStyles,
wpDisableColorInTableOfContents,
wpDontExtendSelectionToRightMargin,
wpInvertActiveRow,
wpInvertActiveRowExceptForProtected,
wpShowCurrentCellAsSelected,
wpShowCurrentRowAsSelected,
wpShowCurrentTableAsSelected,
wpCursorPreview,
wpUnderlineWebLinks,
wpHideParBordersBeforAndAfterPageBreaks,
wpShowColumns,
wpShowColumnCenterLine,
wpDontHideUnderlineAtLineEnd,
wpDisable2PassPaint,
wpDontClearPageBackground,
wpPaintThemedBackground,
wpPaintPageShade,
wpInstantDisplayAfterLoad,
wpDisableAutomaticImageAntialiasing,
wpInteractiveFORMTextObjects,
wppNoBlueRectsAroundFootnotesWhileEditing
);
TWPRTFViewOptions = set of
(
wpLockDATEandTIME
);
TWPEditBoxModes = set of
(
wpemLimitTextWidth,
wpemLimitTextHeight,
wpemAutoSizeWidth,
wpemAutoSizeHeight
);
TWPPageSides = (wpsAll, wpsEven, wpsOdd);
TWPPageRange = (wprAllPages, wprPageList );
TWPPrintHeaderFooter = (
wprNever, wprOnAllPages, wprNotOnFirstPage, wprOnlyOnFirstPage,
wprUseOnlyALLPAGEStext,
wprNotOnFirstAndLastPages,
wprNotOnLastPage,
wprOnlyOnOddPages,
wprOnlyOnEvenPages
);
TWPPrintHeaderFooterPageOpt = set of (wprHeader, wprFooter);
TWPPrintOptions = set of (
wpIgnoreBorders, wpIgnoreShading, wpIgnoreText, wpIgnoreGraphics,
wpUsePrintPageNumber, wpDoNotChangePrinterDefaults, wpDontPrintWatermark,
wpDontReadPapernamesFromPrinter,
wpAlwaysHideFieldmarkers,
wpDontAllowSelectionPrinting,
wpCompareWidthHeightToDetectLandscape,
wpAllColorsAreBlack
);
TWPDuplexMode = (wpdDontChangeDuplex, wpdNone, wpdHorizontal, wpdVertical);
TWPSpellCheckStrategie =
(wpspCheckInInit,
wpspCheckInPaint,
wpspCheckInInitAndPaint
);
TWPMeasureObjectMode = set of (wpMeasureInInit, wpMeasureInReformat, wpMeasureInReformatPar, wpMeasureInPaint);
TWPPagePropertyKind = (wpIsBody, wpIsHeader, wpIsFooter,
wpIsFootnote, wpIsLoadedBody, wpIsDeleted, wpIsOwnerSelected);
TWPPagePropertyKinds = set of TWPPagePropertyKind;
TWPPagePropertyRange =
(wpraOnAllPages, wpraOnOddPages, wpraOnEvenPages, wpraOnFirstPage,
wpraOnLastPage, wpraNotOnFirstAndLastPages, wpraNotOnLastPage,
wpraNamed, wpraIgnored, wpraNotOnFirstPage);
TWPPagePropertyRanges = set of TWPPagePropertyRange;
TWPFormatOptions = set of (
wpDisableAutosizeTables,
wpNoMinimumCellPadding,
wpfDontBreakTables,
wpfDontBreakTableRows,
wpDontClipCells,
wpfIgnoreMinimumRowheight,
wpfIgnoreMaximumRowheight,
wpTableRowIndicator,
wpfIgnoreKeep,
wpfIgnoreKeepN,
wpfKeepOutlineWithNext,
wpfAvoidWidows,
wpfAvoidOrphans,
wpfCenterOnPageVert,
wpfHangingIndentWithTab,
wpfDontTabToIndentFirst,
wpJustifySoftLinebreaks,
wpJustifyHardLinebreaks,
wpUseHyphenation,
wpFooterMinimumDistanceToText,
wpShowBookmarkCodes,
wpShowHyperlinkCodes,
wpShowSPANCodes,
wpShowInvisibleText,
wpfHideEmptyParElements,
wpfXMLOutlineMode,
wpWriteRightToLeft,
wpAutoWriteRightToLeft,
wpUseAbsoluteFontHeight,
wpfAlwaysFormatWithScreenRes,
wpDisableSpeedReformat,
wpDontAdjustFloatingImagePosition
);
TWPFormatOptionsEx = set of (
wpDontAddExternalFontLeading,
wpfKeepTablesInTextArea,
wpKeepTogetherAlwaysNewPage,
wpKeepTogetherAdjacentTables,
wpDontUseTablePadding,
wpfIgnoreVertAlignment,
wpfKeepNUsesParImages,
wpDontIgnoreSpacebeforeOnTopOfPage,
wpDontUseRowPadding,
wpDontUseBorderPadding,
wpDontInheritCellAttr,
wpDontUseSPANStyles,
wpAlwaysContinueBorderAfterCR,
wpNoDefaultParStyles,
wpfAutoRestartSimpleNumbering,
wpfNestedNumberingInTableCells,
wpfSimpleNumberingPriorityOverOutlines,
wpfNoAutoDecTabInTable,
wpfNoTableHeaderRows,
wpfNoTableFooterRows,
wpfDisableJustifiedText,
wpAllow_WPAT_NoWrap,
wpfMixRTLText,
wpfStoreWPObjectsInRTFDataProps,
wpCharEffectIsUserAttribute,
wpfIgnoreTrailingEmptyParAtFooter,
wpfDontHideParAboveNestedTable,
wpfDontCombineDifferentStylePars,
wpfNumberingControlledByStyles,
wpfSectionsRestartFootnoteNumbers,
wpfDontIgnoreKeepNInTable,
wpfDontIgnoreEmptyHeader
);
TWPWebPageFormat = set of (wpFormatAsWebpage, wpNoMinimumWidth,
wpNoMinimumHeight);
TWPFormatOptionsEx2 = set of (
wpfSectionsRestartPageNumbers
, wpfUseKerning
, wpfCodeObjectAsXMLTags
, wpDisableBalancedColumns
, wpfCodeObjectCheckParStyles
, wpfNewKeepNSupport
, wpfHideParagraphWithHiddenText
, wpAllowFullWidthImagesInHeaderFooter
, wpMarginMirrorBookPrint
, wpIgnboreAllTabsInPageMargin
, wpAlwaysContinueShadingAfterCR
, wpUseDIVTree
, wpfShowProtectionObjects
, wpfLabelAllowSoftPagebreak
, wpfIgnoreHardPagebreaks
, wpfIgnoreSoftPagebreaks
, wpfRestartOutlineNumbersAfterRegularText
, wpfIgnorePropertyNumberStart
, wpfSectionsWithPagesizeStartNewPage
, wpfDontHideOverflowLinesInTableCells
, wpfHideFirstTableHeaderRowAtStart
, wpfHideSecondTableHeaderRowAtStart
, wpfHideTableFooterRowAtEnd
, wpfUseFloatingImagesOfHiddenParagraph
, wpfAlwaysGenerateParBetweenTables
, wpfAlignTableFootersAtBottom
, wpfNoSecondTableHeaderRows
);
TWPOCurrState = (wobLoading, wobChecking, wobPainting, wobClicking, wobDblClicking);
TWPPaintModes = set of (
wppPaintHGrid,
wppPaintVGrid,
wppNoImages,
wppNoTextAtAll,
wppNoParShading,
wppNoParLines,
wppAllFontsAreBlack,
wppUsePrintPageNumberFromEnviroment,
wppWhiteIsTransparent,
wppGrayHeaderFooter,
wppGrayAll,
wppNoHeaderFooter,
wppNoWatermarks,
wppShowSelection,
wppShowGridlines,
wppShowTableRowIndicator,
wppShowHotStyles,
wppTextAsBlocks,
wppShowMargins,
wppPrintPageFrame,
wppShowSpecialTextAreas,
wppNoPageBackground,
wppNoPageScaling,
wppShowFocusOptional,
wppShowSymbolsOptional,
wppOutputToPrinter,
wppInPaintDesktop,
wppInPaintForwPDF,
wppInUseSaveDC,
wppPaintAllParBackground,
wppPaintAllCellBackground,
wppMetafilesAsBitmaps,
wppNoSaveDC
);
TWPPaintBandMode = (wpBandNormal, wpBandEnd, wpBandClosed);
THTMLStoreOptions = set of
(
soStrictXHTML,
spDontWriteNBSP,
soOnlyHTMLBody,
soDontWriteStyleSheet,
soWriteBasefontTag,
soNoSPANBackgroundColor,
soSPANInsteadOfFontTag,
soOnlyFieldTags,
soNoEntities,
soCreateImageEventForAllImages,
soAllUnicodeEntities,
soNoHeaderFooterText
);
TStoreOptions = set of (
soDontSaveListText,
soDontSaveListStyle,
soSaveOldPNNumbering,
soNoStyleTable,
soAllStylesInCollection,
soWriteObjectsAsRTFBinary,
soAlwaysEmbedFilesInRTF,
soNoWPToolsHeaderFooterRTF,
soNoHeaderText,
soNoFooterText,
soSelectionMarker,
soWriteDefaultBorderProps,
soNoNoNestTableText,
soNoCharacterAttributes,
soNoRTFStartTags,
soUseUnicode,
soNoFontTable,
soNoColorTableInRTF,
soNoPageFormatInRTF,
soNoSectionFormatInRTF,
soNoShadingInformation,
soANSIFormfeedCode,
soNoRTFVariables,
soWriteCellsAsParagraphs,
soDontWriteOpenTagsAutsideOfStartPar
);
TLoadOptions = set of (
loIgnoreDefaultTabstop,
loIgnorePageSize,
loIgnoreHeaderFooter,
loDontLoadRTFVariables,
loDontAddRTFVariables,
loIgnorePageMargins,
loIgnoreOutlineStyles,
loIgnoreFonts,
loIgnoreFontSize,
loIgnoreColorTable,
loPrintHeaderFooterParameter,
loIgnoreStylesheet,
loIgnoreUnknownStyles,
loDontOverwriteExistingStyles,
loAddOnlyUsedStyles,
loIgnoreListTable,
loIgnoreOldStyleListTable,
loIgnoreNumberDefs,
loDontIgnoreNumberText,
loDontDeleteAttrEqualToParStyle,
loNoCharStyles,
loANSIFormfeedCode,
loLoadKEEPNProperty,
loSelectionMarker,
loIgnoreGraphics,
loIgnoreWPToolsObjects,
loNoRTFStartTags
, loIgnorePageFrame
);
TLoadHTMLOptions = set of (
loIgnoreEmbeddedCSSStyleSheet,
loIgnoreEmbeddedScript,
loIgnoreLinkedCSSStyleSheet,
loIgnoreSPANTag,
loDoNotCreateSPANObjects,
loIgnoreStyleParameter,
loIgnoreStdHTMLParams,
loIgnoreShading,
loIgnoreTextOutsideOfHTMLTag,
loIgnoreTextOutsideOfBodyTag
);
TWPEditBoxLinkMsg = (
wpBeforeClear, wpAfterClear,
wpBeforeLoad, wpAfterLoad,
wpBeforeSave, wpAfterSave,
wpAfterGetFocus);
TWPObjectWriteRTFModeGlobal = (
wobStandard, wobRTF, wobStandardAndRTF, wobDontSaveImages,
wobStandardNoBinary, wobRTFNoBinary
);
TWPPageDef = record ID: Integer; UseCM: Boolean; Width, Height: Single; Name: string; end;
TWPPageSettings = (wp_Custom, wp_Letter, wp_Legal, wp_Executive,
wp_DinA1, wp_DinA2,
wp_DinA3, wp_DinA4, wp_DinA5, wp_DinA6);
TWPVCLString = (
meDefaultUnit_INCH_or_CM,
meUnitInch,
meUnitCm,
meDecimalSeperator,
meDefaultCharSet,
meFilterRTF,
meFilterHTML,
meFilterTXT,
meFilterXML,
meFilterCSS,
meFilterCustom,
meFilterALL,
meFilter,
meFilterMime,
meUserCancel,
meReady,
meReading,
meWriting,
meFormatA,
meFormatB,
meClearMemory,
meNoSelection,
meRichText,
mePlainText,
meSysError,
meClearTabs,
meObjGraphicFilter,
meObjGraphicFilterExt,
meObjTextFilter,
meObjNotSupported,
meObjGraphicNotLinked,
meObjDelete,
meObjInsert,
meSaveChangedText,
meClearChangedText,
meCannotRenameFile,
meErrorWriteToFile,
meErrorReadingFile,
meRecursiveToolbarUsage,
meWrongScreenmode,
meTextNotFound,
meUndefinedInsertpoint,
meNotSupportedProperty,
meUseOnlyBitmaps,
meWrongUsageOfFastAppend,
mePaletteCompletelyUsed,
meWriterClassNotFound,
meReaderClassNotFound,
meWrongArgumentError,
meIOClassError,
meNotSupportedError,
meutNone,
meutAny,
meutInput,
meutDeleteText,
meutChangeAttributes,
meutChangeIndent,
meutChangeSpacing,
meutChangeAlignment,
meutChangeTabs,
meutChangeBorder,
meutDeleteSelection,
meutDragAndDrop,
meutPaste,
meutChangeTable,
meutChangeGraphic,
meutChangeCode,
meutUpdateStyle,
meutChangeTemplate,
meutInsertBookmark,
meutInsertHyperlink,
meutInsertField,
meDiaAlLeft, meDiaAlCenter, meDiaAlRight, meDiaAlJustified,
meDiaYes, meDiaNo,
meTkLeft, meTkCenter, meTkRight, meTkDecimal,
meSpacingMultiple, meSpacingAtLeast, meSpacingExact,
mePaperCustom,
meWrongFormat, meReportTemplateErr,
meUnicodeModeNotActivated,
meUndefinedValue,
meUndefinedStyle,
meTransparent,
meNeutralColor,
meCreateNewStyle,
meNewStyleName,
meEditCurrStyle,
meTextFoundAndReplaced,
wpCannotInsObject,
wpInsertTextField,
wpInsertTextField_Name,
wpInsertMailmergeField,
wpInsertMailmergeField_Name,
wpInsertBookmark,
wpInsertBookmark_Name,
wpInsertEditField,
wpInsertEditField_Name,
wpInsertHyperlink,
wpInsertHyperlink_Name,
wpInsertHyperlink_URL,
wpZoomNormal,
wpZoom100,
wpZoomPageWidth,
wpZoomPageHeight,
wpZoomTwoPages,
wpThumbnails
);
const
TSpellCheckHyphenCount = 16;
WPMINWRAPDIVISOR = 6;
WPDefaultHighlightColor = $00F2BFB7;
WPDefaultHighlightCellShading = 60;
WPDefaultHighlightTextColor = $0;
TextObjCode = #1;
TextObjCodeOpening = #2;
TextObjCodeClosing = #3;
BitMask: array[1..16] of Word = (1, 2, 4, 8, 16, 32, 64, 128, 256, 512,
1024, 2048, 4096, 8192, 16384, 32768);
BitMaskL: array[1..32] of Cardinal = (1, 2, 4, 8, 16, 32, 64, 128, 256, 512,
1024, 2048, 4096, 8192, 16384, 32768,
65536, 131072, 262144, 524288,
1048576, 2097152, 4194304, 8388608,
16777216, 33554432, 67108864, 134217728,
268435456, 536870912, 1073741824, Cardinal(1073741824) * 2);
_WPAT_FirstCharAttr_ = 1;
_WPAT_LastCharAttr_ = 16;
WPAT_FirstCharAttr = 1;
WPAT_LastCharAttr = 16;
WPAT_CharFont = 1;
WPAT_CharCharset = 2;
WPAT_CharFontSize = 3;
WPAT_CharWidth = 4;
WPAT_CharEffect = 5;
WPEFF_CUSTOM1 = 1;
WPEFF_CUSTOMMASK = 63;
WPEFF_SHADOW = 64;
WPEFF_INSET = 128;
WPEFF_OUTSET = 256;
WPEFF_OUTLINE = 512;
WPEFF_FRAME = 1024;
WPEFF_ANIMbit1 = 2048;
WPEFF_ANIMbit2 = 4096;
WPEFF_ANIMbit3 = 8192;
WPEFF_ANIMMask = 8192 + 2048 + 4096;
WPAT_CharStyleMask = 6;
WPAT_CharStyleON = 7;
WPSTY_BOLD = 1;
WPSTY_ITALIC = 2;
WPSTY_UNDERLINE = 4;
WPSTY_STRIKEOUT = 8;
WPSTY_SUPERSCRIPT = 16;
WPSTY_SUBSCRIPT = 32;
WPSTY_HIDDEN = 64;
WPSTY_UPPERCASE = 128;
WPSTY_SMALLCAPS = 256;
WPSTY_LOWERCASE = 512;
WPSTY_NOPROOF = 1024;
WPSTY_DBLSTRIKEOUT = 2048;
WPSTY_BUTTON = 4096;
WPSTY_PROTECTED = 8192;
WPSTY_USERDEFINED = 16384;
cafsHyphen = $01000000;
cafsWasChecked = $02000000;
cafsMisSpelled = $04000000;
cafsMisSpelled2 = $08000000;
cafsInsertedText = $10000000;
cafsHiddenText = $20000000;
cafsWordHighlight = $40000000;
cafsDelete = $80000000;
cafsALL = $FF000000;
cafsNONE = $00FFFFFF;
WPAT_CharColor = 8;
WPAT_CharBGColor = 9;
WPAT_CharSpacing = 10;
WPAT_CharLevel = 11;
WPAT_CharHighlight = 12;
WPAT_UnderlineMode = 13;
WPUND_Standard = 1;
WPUND_Dotted = 2;
WPUND_Dashed = 3;
WPUND_Dashdotted = 4;
WPUND_Dashdotdotted = 5;
WPUND_Double = 6;
WPUND_Heavywave = 7;
WPUND_Longdashed = 8;
WPUND_Thick = 9;
WPUND_Thickdotted = 10;
WPUND_Thickdashed = 11;
WPUND_Thickdashdotted = 12;
WPUND_Thickdashdotdotted = 13;
WPUND_Thicklongdashed = 14;
WPUND_Doublewave = 15;
WPUND_WordUnderline = 16;
WPUND_wave = 17;
WPUND_curlyunderline = 18;
WPUND_NoLine = 200;
WPAT_UnderlineColor = 14;
WPAT_TextLanguage = 15;
WPAT_CharStyleSheet = 16;
WPAT_FirstParAttr = 17;
WPAT_LastParAttr = 59;
WPAT_IndentLeft = 17;
WPAT_IndentRight = 18;
WPAT_IndentFirst = 19;
WPAT_SpaceBefore = 20;
WPAT_SpaceAfter = 21;
WPAT_LineHeight = 22;
WPAT_SpaceBetween = 23;
WPAT_PaddingLeft = 24;
WPAT_PaddingRight = 25;
WPAT_PaddingTop = 26;
WPAT_PaddingBottom = 27;
WPAT_WordSpacing = 28;
WPAT_Alignment = 29;
WPAT_VertAlignment = 30;
WPAT_NumberSTYLE = 31;
WPAT_NumberLEVEL = 32;
WPAT_OUTLINELEVEL = 32;
WPAT_NumberMODE = 33;
WPNUM_ARABIC = 1;
WPNUM_UP_ROMAN = 2;
WPNUM_LO_ROMAN = 3;
WPNUM_UP_LETTER = 4;
WPNUM_LO_LETTER = 5;
WPNUM_LO_ORDINAL = 6;
WPNUM_Text = 7;
WPNUM_ORDINAL_TEXT = 8;
WPNUM_WIDECHAR = 15;
WPNUM_CHAR = 16;
WPNUM_CIRCLE = 19;
WPNUM_ARABIC0 = 23;
WPNUM_BULLET = 24;
WPAT_NumberTEXTB = 34;
WPAT_NumberTEXTA = 35;
WPAT_NumberTEXT = 36;
WPAT_Number_STARTAT = 37;
WPAT_Number_ALIGN = 38;
WPAT_Number_SPACE = 39;
WPAT_NumberFONT = 40;
WPAT_NumberFONTSIZE = 41;
WPAT_NumberFONTCOLOR = 42;
WPAT_NumberFONTSTYLES = 43;
WPAT_NumberINDENT = 44;
WPAT_NumberFLAGS = 45;
WPNUM_FLAGS_COMPAT = 1;
WPNUM_FLAGS_USEPREV = 2;
WPNUM_FLAGS_USEINDENT = 4;
WPNUM_FLAGS_FOLLOW_SPACE = 8;
WPNUM_FLAGS_FOLLOW_NOTHING = 16;
WPNUM_FLAGS_LEGAL = 32;
WPNUM_FLAGS_NORESTART = 64;
WPNUM_FLAGS_ONCE = 128;
WPNUM_FLAGS_ACROSS = 256;
WPNUM_FLAGS_HANG = 512;
WPNUM_NONumberING = 1024;
WPNUM_NumberSKIP = 2048;
WPAT_NumberPICTURE = 46;
WPAT_Number_Group = 47;
WPAT_Number_RES2 = 48;
WPAT_Number_RES3 = 49;
WPAT_BGColor = 50;
WPAT_FGColor = 51;
WPAT_ShadingValue = 52;
WPAT_ShadingType = 53;
WPSHAD_solidbg = 0;
WPSHAD_solidfg = 1;
WPSHAD_clear = 2;
WPSHAD_bdiag = 3;
WPSHAD_cross = 4;
WPSHAD_dcross = 5;
WPSHAD_dkbdiag = 6;
WPSHAD_dkcross = 7;
WPSHAD_dkdcross = 8;
WPSHAD_dkfdiag = 9;
WPSHAD_dkhor = 10;
WPSHAD_dkvert = 11;
WPSHAD_fdiag = 12;
WPSHAD_horiz = 13;
WPSHAD_vert = 14;
WPAT_BGBitMap = 54;
WPAT_BGBitMapMode = 55;
WPAT_AParRes1 = 56;
WPAT_AParRes2 = 57;
WPAT_AParRes3 = 58;
WPAT_AParRes4 = 59;
WPAT_BorderFirstAttr = 60;
WPAT_BorderTypeL = 60;
WPAT_BorderTypeT = 61;
WPAT_BorderTypeR = 62;
WPAT_BorderTypeB = 63;
WPBRD_SINGLE = 0;
WPBRD_NONE = 1;
WPBRD_DOUBLEW = 2;
WPBRD_SHADOW = 3;
WPBRD_DOUBLE = 4;
WPBRD_DOTTED = 5;
WPBRD_DASHED = 6;
WPBRD_HAIRLINE = 7;
WPBRD_INSET = 8;
WPBRD_DASHEDS = 9;
WPBRD_DOTDASH = 10;
WPBRD_DOTDOTDASH = 11;
WPBRD_OUTSET = 12;
WPBRD_TRIPPLE = 13;
WPBRD_THIKTHINS = 14;
WPBRD_THINTHICKS = 15;
WPBRD_THINTHICKTHINS = 16;
WPBRD_THICKTHIN = 17;
WPBRD_THINTHIK = 18;
WPBRD_THINTHICKTHIN = 19;
WPBRD_THICKTHINL = 20;
WPBRD_THINTHICKL = 21;
WPBRD_THINTHICKTHINL = 22;
WPBRD_WAVY = 23;
WPBRD_DBLWAVY = 24;
WPBRD_STRIPED = 25;
WPBRD_EMBOSSED = 26;
WPBRD_ENGRAVE = 27;
WPBRD_FRAME = 28;
WPAT_BorderTypeDiaTLBR = 64;
WPAT_BorderTypeDiaTRBL = 65;
WPAT_BorderWidthL = 66;
WPAT_BorderWidthT = 67;
WPAT_BorderWidthR = 68;
WPAT_BorderWidthB = 69;
WPAT_BorderWidthDiaTLBR = 70;
WPAT_BorderWidthDiaTRBL = 71;
WPAT_BorderColorL = 72;
WPAT_BorderColorT = 73;
WPAT_BorderColorR = 74;
WPAT_BorderColorB = 75;
WPAT_BorderColorDiaTLBR = 76;
WPAT_BorderColorDiaTRBL = 77;
WPAT_BorderTypeH = 78;
WPAT_BorderWidthH = 79;
WPAT_BorderColorH = 80;
WPAT_BorderTypeV = 81;
WPAT_BorderWidthV = 82;
WPAT_BorderColorV = 83;
WPAT_BorderTypeBar = 84;
WPAT_BorderWidthBar = 85;
WPAT_BorderColorBar = 86;
WPAT_BorderType = 87;
WPAT_BorderWidth = 88;
WPAT_BorderColor = 89;
WPAT_BorderFlags = 90;
WPBRD_DRAW_Left = 1;
WPBRD_DRAW_Top = 2;
WPBRD_DRAW_Right = 4;
WPBRD_DRAW_Bottom = 8;
WPBRD_DRAW_All4 = 15;
WPBRD_DRAW_DiagLB = 16;
WPBRD_DRAW_DiagRB = 32;
WPBRD_DRAW_Bar = 64;
WPBRD_DRAW_InsideV = 128;
WPBRD_DRAW_InsideH = 256;
WPBRD_DRAW_Box = 512;
WPBRD_DRAW_Finish = 1024;
WPBRD_DRAW_DefinedInStyle = 4194304;
WPDRAW_NEEDLINES = 1;
WPDRAW_NOCURSOR = 2;
WPDRAW_INVISIBLE = 4;
WPDRAW_RTFDATA = 8;
WPDRAW_ISCELL = 16;
WPDRAW_ISDIVPARENT = 512;
WPDRAW_AutomaticText = 1024;
WPDRAW_Hyperlink = 2048;
WPDRAW_Bookmark = 4096;
WPDRAW_TextProtection = 8192;
WPDRAW_BAND = 16384;
WPDRAW_TOPPAGE = 32768;
WPDRAW_BOTTOMPAGE = 32768 * 2;
WPDRAW_BANDEND = 32768 * 4;
WPDRAW_INACTIVE = 32768 * 8;
WPDRAW_HYPHEN = 32768 * 16;
WPDRAW_CONTINUEPAGE = 32768 * 32;
WPDRAW_HIDEOVERFLOWTEXT = 32768 * 64;
WPDRAW_TABLEBOX = 32768 * 64;
WPDRAW_TABLEOFCONTENTS = 32768 * 128;
WPDRAW_BORDERISCLOSED = 32768 * 256;
WPAT_BorderLastAttr = 90;
WPAT_PaddingAll = 91;
WPAT_ParProtected = 92;
WPAT_ParKeep = 93;
WPAT_ParKeepN = 94;
WPAT_LastCopiedParProp = 94;
WPAT_CellPadding = 95;
WPAT_CellSpacing = 96;
WPAT_Box_HPositionMode = 102;
WPAT_Box_VPositionMode = 103;
WPPOS_MARGIN = 0;
WPPOS_COLUMN = 1;
WPPOS_PAGE = 2;
WPPOS_PARAGRAPH = 3;
WPPOS_INLINE = 4;
WPPOS_ATSTART = 8;
WPPOS_CENTER = 16;
WPPOS_ATEND = 32;
WPPOS_WITHIN = 64;
WPPOS_OUTSIDE = 128;
WPPOS_LOCKANCHOR = 256;
WPPOS_ALLOWOVERLAP = 512;
WPAT_BoxWidth = 104;
WPAT_BoxHeight = 105;
WPAT_BoxMinWidth = 106;
WPAT_BoxMinHeight = 107;
WPAT_BoxMaxWidth = 108;
WPAT_BoxMaxHeight = 109;
WPAT_BoxOverflow = 110;
WPAT_Box_XPos = 111;
WPAT_Box_YPos = 112;
WPAT_Boy_ZIndex = 113;
WPAT_Box_TextDistanceX = 114;
WPAT_Box_TextDistanceY = 115;
WPAT_Box_NoWrapMode = 116;
WPAT_Box_TextFlow = 117;
WPAT_Box_Align = 118;
WPBOXALIGN_MINLEFT = 1;
WPBOXALIGN_LEFT = 2;
WPBOXALIGN_HCENTERPAGE = 4;
WPBOXALIGN_HCENTERTEXT = 8;
WPBOXALIGN_RIGHT = 16;
WPBOXALIGN_RIGHTMAX = 32;
WPBOXALIGN_MINTOP = 64;
WPBOXALIGN_TOP = 128;
WPBOXALIGN_VCENTERPAGE = 256;
WPBOXALIGN_VCENTERTEXT = 512;
WPBOXALIGN_BOTTOM = 1024;
WPBOXALIGN_BOTTOMMAX = 2048;
WPAT_BoxWidth_PC = 119;
WPAT_BoxMarginLeft = 120;
WPAT_BoxMarginRight = 121;
WPAT_Display = 122;
WPAT_Visibility = 123;
WPVIS_Hidden = 1;
WPVIS_Collapsed = 2;
WPAT_VisibilityOptions = 124;
WPAT_NoWrap = 125;
WPAT_ParID = 126;
WPAT_ParFlags = 127;
WPFLG_USER1 = 1;
WPFLG_USER2 = 2;
WPFLG_NOPROOF = 4;
WPFLG_INTELPAGEBREAK = 8;
WPFLG_NOJOINPARA = 16;
WPFLG_widctlpar = 32;
WPFLG_nowidctlpar = 64;
WPPARFL_NewPage = 256;
WPFLG_HASCHECK = 512;
WPFLG_FIXEDCHECK = 1024;
WPFLG_ISCHECKED = 2048;
WPFLG_SECTIONGRP = 4096;
WPPARFL_NewPageAfter = 8192;
WPAT_USEHTMLSYNTAX = 128;
WPSYNTAX_ALIGN = 1;
WPSYNTAX_BGCOLOR = 2;
WPSYNTAX_BORDER = 4;
WPSYNTAX_WIDTH = 8;
WPSYNTAX_FONT = 16;
WPSYNTAX_BOXALIGN = 32;
WPAT_BANDFLAGS_1 = 129;
WPAT_BANDFLAGS_2 = 130;
WPAT_BANDPAR_1 = 131;
WPAT_BANDPAR_VAR = 132;
WPAT_BANDPAR_STR = 133;
WPAT_CounterReset = 134;
WPAT_CounterID = 135;
WPAT_CounterIncrement = 136;
WPAT_ContentBefore = 137;
WPAT_ContentAfter = 138;
WPAT_ContentDefault = 139;
WPAT_LINENUM_INC = 140;
WPAT_LINENUM_X = 141;
WPAT_LINENUM_START = 142;
WPAT_LINENUM_FLAGS = 143;
WPLINEN_ENABLED = 1;
WPLINEN_RESTART = 2;
WPLINEN_PERPAGE = 4;
WPLINEN_CONTINUE = 8;
WPLINEN_NOLINE = 16;
WPAT_COLUMNS = 144;
WPAT_COLUMNS_X = 145;
WPAT_COLFLAGS = 146;
WPCOLUM_LINE = 1;
WPAT_COLRES1 = 147;
WPAT_COLRES2 = 148;
WPAT_COLUMNS_Y = 149;
WPAT_PAR_NAME = 150;
WPAT_PAR_COMMAND = 151;
WPAT_PAR_FORMAT = 152;
WPAT_Par_ResFlag1 = 153;
WPAT_ParProtectStyle = 154;
WPAT_ParOnlyNumbers = 155;
WPAT_ParOneLine = 156;
WPAT_Par_ResFlag2 = 157;
WPAT_Par_ResFlag3 = 158;
WPAT_NumberStart = 159;
WPAT_ParIsOutline = 160;
WPAT_ParOutlineBreak = 161;
WPAT_MaxLength = 162;
WPAT_PAR_CAPTION = 163;
WPAT_USER = 168;
WPAT_USER2 = 169;
_WPAT_NotCopiedParAttr_ = 159;
WPAT_CellSpaceL = 170;
WPAT_CellSpaceR = 171;
WPAT_CellSpaceT = 172;
WPAT_CellSpaceB = 173;
WPAT_CELLFlags = 174;
WPCELL_NOWORDWRAP = 1;
WPCELL_AUTOFIT = 2;
WPAT_COLWIDTH_PC = 175;
WPAT_COLWIDTH = 176;
WPAT_COLRESERVED = 177;
WPAT_CELLRes1 = 178;
WPAT_CELLRes2 = 179;
WPAT_STYLE_FLAGS = 180;
WPSTYLE_IGNORECHARSTYLE = 1;
WPSTYLE_IGNOREPARATTR = 2;
WPSTYLE_IGNORESHADING = 4;
WPSTYLE_IGNOREBORDERS = 8;
WPSTYLE_IGNORENumberS = 16;
WPSTYLE_AUTOUPDATE = 32;
WPSTYLE_HIDDEN = 64;
WPSTYLE_SEMIHIDDEN = 128;
WPSTYLE_ADDITIVE = 512;
WPAT_STYLE_NEXT_NAME = 181;
WPAT_STYLE_BASE_NAME = 182;
WPAT_UseFooterText = 212;
WPAT_UseHeaderText = 213;
WPAT_ROWSPAN = 214;
WPAT_COLSPAN = 215;
WPHYPER_BOOKMARKLINK = 1108;
WPTOC_FIELDNAME = '__TOC__';
WPST_Exception = 0;
WPST_Loading = 1;
WPST_Reformat = 2;
WPST_Reformat_Start = 3;
WPST_Reformat_Done = 4;
WPST_Reformat_Info = 10;
WPST_Reformat_Info_PicResize = 11;
WPST_Reformat_Error = 12;
WPST_ReadInfo = 20;
WPST_ReadProblem = 21;
WP_OBJPROP_INIWIDTH = 101;
WP_OBJPROP_INIHEIGHT = 102;
TABMAX = 128;
TABWORDMAX = 4;
MaxWPPageSettings = 9;
WPCustomTextReaderReadBufferLen = 8192;
WPPageSettings: array[TWPPageSettings] of TWPPageDef =
((ID: - 1; UseCM: TRUE; Width: 21; Height: 29; Name: 'Custom'),
(ID: 1 ; UseCM: FALSE; Width: 8.5; Height: 11.0; Name:
'Letter 8 1/2 x 11 in'),
(ID: 5 ; UseCM: FALSE; Width: 8.5; Height: 14.0; Name:
'Legal 8 1/2 x 14 in'),
(ID: 7 ; UseCM: FALSE; Width: 7.25; Height: 10.5; Name:
'Executive 7.25 x 10.5 in'),
(ID: - 1; UseCM: TRUE; Width: 59.4; Height: 84.0; Name:
'DIN A1 594 x 840 mm'),
(ID: - 1; UseCM: TRUE; Width: 42.0; Height: 59.4; Name:
'DIN A2 420 x 594 mm'),
(ID: 8 ; UseCM: TRUE; Width: 29.7; Height: 42.0; Name:
'DIN A3 297 x 420 mm'),
(ID: 9 ; UseCM: TRUE; Width: 21.0; Height: 29.7; Name:
'DIN A4 210 x 297 mm'),
(ID: 11 ; UseCM: TRUE; Width: 14.8; Height: 21.0; Name:
'DIN A5 148 x 210 mm'),
(ID: 70 ; UseCM: TRUE; Width: 10.5; Height: 14.8; Name:
'DIN A6 105 x 148 mm')
);
WPBROADCAST_REPAINT = 1000;
WPBROADCAST_INITIALIZE_PAGES = 1002;
WPBROADCAST_REORDER_PAGES = 1003;
WPBROADCAST_UPDATE_HSCROLL = 1004;
WPBROADCAST_UPDATE_VSCROLL = 1005;
WPBROADCAST_NEED_REFORMAT = 1006;
WPBROADCAST_UPDATE_CURSOR = 1007;
WPBROADCAST_UPDATE_SELECTION = 1008;
WPBROADCAST_SELECTBODY = 1009;
WPBROADCAST_BEFOREKILLFOCUS = 1010;
WPBROADCAST_AFTERSETFOCUS = 1011;
WPBROADCAST_BEFORE_DELETE_DATA = 1012;
WPBROADCAST_BEFORE_CLEARTEXT = 1013;
WPBROADCAST_AFTER_CLEARTEXT = 1014;
WPBROADCAST_AFTER_CREATEBODY = 1015;
WPBROADCAST_UNSELECTOBJECT = 1016;
WPBROADCAST_NEEDFOCUS = 1017;
WPBROADCAST_NEED_PAGESIZE = 1018;
WPBROADCAST_WORKONTEXTCHANGE = 1020;
WPBROADCAST_CHANGE_DISPLAYTEXT = 1021;
WPBROADCAST_NEED_REFORMATLATER = 1022;
WPBROADCAST_AFTER_REORDERPAGES = 1023;
WPBROADCAST_NEED_INITREFORMAT = 1024;
WPBROADCAST_UPDATE_CURSOR_AUTOSCROLL = 1025;
WPBROADCAST_UPDATE_DID_SCROLL = 1026;
WPBROADCAST_UPDATERULER = 1027;
WPBROADCAST_UPDATERULER_CP = 1028;
WPBROADCAST_NEED_REFORMAT_AT_ONCE = 1029;
WPBROADCAST_AFTER_LOAD = 1030;
WPBROADCAST_NEWRTFBLOCK = 1031;
WPBROADCAST_NEED_SPEEDREFORMAT = 1032;
WPBROADCAST_NEED_SELECTBODY = 1033;
WPBROADCAST_UNDOCHANGE = 1034;
WPBROADCAST_MOUSEWHEEL_ATEND = 1035;
WPBROADCAST_MOUSEWHEEL_ATSTART = 1036;
WPBROADCAST_ENTER = 1037;
WPBROADCAST_LEAVE = 1038;
WPBROADCAST_UPDATE_SELECTION_NOPAINT = 1039;
WPBROADCAST_CHANGING = 1040;
WPBROADCAST_CHANGED = 1041;
WPBROADCAST_CHANGED_PARSTYLECOUNT = 1042;
WPBROADCAST_CHANGED_PARSTYLES = 1043;
type
TWPExpectedValueForCode =
(
wpexInteger,
wpexTW,
wpexBITS,
wpexPERCENT,
wpexPT,
wpexFONT,
wpexCHARSET,
wpexCOLOR,
wpexSTRING,
wpexBOOL
);
TWPCodeNameRec =
record
name: string;
abr: string;
exp: TWPExpectedValueForCode;
hint: string;
end;
var
FWPVCLStrings: array[TWPVCLString] of string;
WPPagePropertyKindNames: array[TWPPagePropertyKind] of string =
('Body', 'Header', 'Footer', 'Unused', 'LoadedBody', 'Deleted', 'OwnerSelected');
WPPagePropertyRangeNames: array[TWPPagePropertyRange] of string;
WPAT_CodeNames: array[1..179] of TWPCodeNameRec =
(
(name: 'CharFont'; abr: 'cF'; exp: wpexFONT; hint: '[1] Index of the font in RTFProps.FontNames'),
(name: 'CharCharset'; abr: 'cCS'; exp: wpexCHARSET; hint: '[2] CharSet of the font'),
(name: 'CharFontSize'; abr: 'cS'; exp: wpexPT; hint: '[3] Font size pt*100'),
(name: 'CharWidth'; abr: 'cW'; exp: wpexInteger; hint: '[4] Character scaling value'),
(name: 'CharEffect'; abr: 'cE'; exp: wpexBITS; hint: '[5] Special character effects and character styles'),
(name: 'CharStyleMask'; abr: 'cSM'; exp: wpexBITS; hint: '[6] always used with "CharStyleON"'),
(name: 'CharStyleON'; abr: 'cSO'; exp: wpexBITS; hint:
'[7] Switch one or multiple of the following Styles on (WPSTY_BOLD ... )'),
(name: 'CharColor'; abr: 'cC'; exp: wpexCOLOR; hint: '[8] The text Color (as index in palette)'),
(name: 'CharBGColor'; abr: 'cBC'; exp: wpexCOLOR; hint: '[9] The text background Color (as index in palette)'),
(name: 'CharSpacing'; abr: 'cSP'; exp: wpexTW; hint: '[10] "Letter-Spacing" in twips, 0..$8000 to expand, larger: compress'),
(name: 'CharLevel'; abr: 'cLVL'; exp: wpexInteger; hint: '[11] Move Character up or down - in half points'),
(name: 'CharHighlight'; abr: 'cHigh'; exp: wpexInteger; hint: '[12] {reserved} Highlight mode (different styles and Colors)'),
(name: 'UnderlineMode'; abr: 'cUL'; exp: wpexInteger; hint:
'[13] {reserved} Underlining mode, 0=off, 1=solid, 2=double, 3= dotted ...'),
(name: 'UnderlineColor'; abr: 'cUC'; exp: wpexCOLOR; hint:
'[14] / {reserved} Underlining Color, 0=text Color, otherwise Colorindex +1'),
(name: 'TextLanguage'; abr: 'cB'; exp: wpexInteger; hint: '[15] {reserved} Language id for the text'),
(name: 'CharStyleSheet'; abr: 'cSTY'; exp: wpexInteger; hint: '[16] CharacterStyle'),
(name: 'IndentLeft'; abr: 'IL'; exp: wpexTW; hint: '[17] Indent Left (CSS: margin-left)'),
(name: 'IndentRight'; abr: 'IR'; exp: wpexTW; hint: '[18] Indent Right (CSS: margin-right)'),
(name: 'IndentFirst'; abr: 'IF'; exp: wpexTW; hint: '[19] Indent First (CSS: text-indent)'),
(name: 'SpaceBefore'; abr: 'SB'; exp: wpexTW; hint: '[20] Space Before (CSS: margin-top)'),
(name: 'SpaceAfter'; abr: 'SA'; exp: wpexTW; hint: '[21] Space After (CSS: margin-bottom)'),
(name: 'LineHeight'; abr: 'LH'; exp: wpexPERCENT; hint: '[22] LineHeight in in % ( Has priority over "SpaceBetween"'),
(name: 'SpaceBetween'; abr: 'SL'; exp: wpexTW; hint: '[23] Space Between - negative : Absolute, Positive minimum'),
(name: 'PaddingLeft'; abr: 'PL'; exp: wpexTW; hint: '[24] Distance from Border to Text'),
(name: 'PaddingRight'; abr: 'PR'; exp: wpexTW; hint: '[25] Distance from Border to Text'),
(name: 'PaddingTop'; abr: 'PT'; exp: wpexTW; hint: '[26] Distance from Border to Text'),
(name: 'PaddingBottom'; abr: 'PB'; exp: wpexTW; hint: '[27] Distance from Border to Text'),
(name: 'WordSpacing'; abr: 'WS'; exp: wpexInteger; hint: '[28] 0 for default or % of EM (ignored for justifed text)'),
(name: 'Alignment'; abr: 'AL'; exp: wpexInteger; hint: '[29] paralLeft, ...'),
(name: 'VertAlignment'; abr: 'VAL'; exp: wpexInteger; hint:
'[30] Cells: paralVertTop, paralVertCenter, paralVertBottom, paprVertJustified'),
(name: 'NumberStyle'; abr: 'NSTY'; exp: wpexInteger; hint: '[31] Reference to a different Style. It can be a single style or'),
(name: 'NumberLevel'; abr: 'NLVL'; exp: wpexInteger; hint: '[32] Numbering Level - used for outlines'),
(name: 'NumberMode'; abr: 'NMOD'; exp: wpexInteger; hint: '[33] Numbering Mode, decimal, roman ...'),
(name: 'NumberTEXTB'; abr: 'NTB'; exp: wpexSTRING; hint: '[34] Text Before (index in stringlist of RTFFProps)'),
(name: 'NumberTEXTA'; abr: 'NTA'; exp: wpexSTRING; hint: '[35] Text After (index in stringlist of RTFFProps)'),
(name: 'NumberTEXT'; abr: 'NT'; exp: wpexSTRING; hint:
'[36] Char #1..#10 are the level placeholders, the rest is the surrounding text'),
(name: 'Number_STARTAT'; abr: 'NST'; exp: wpexInteger; hint: '[37] Start Numbering if this is first in level'),
(name: 'Number_ALIGN'; abr: 'NA'; exp: wpexInteger; hint: '[38] 0=Left, 1=Center, 2=Right'),
(name: 'Number_SPACE'; abr: 'NSP'; exp: wpexInteger; hint:
'[39] Minimum distance from the right edge of the number to the start of the paragraph text'),
(name: 'NumberFONT'; abr: 'NF'; exp: wpexFONT; hint: '[40] Optional: Font for the text'),
(name: 'NumberFONTSIZE'; abr: 'NFS'; exp: wpexInteger; hint: '[41] Optional: FontSize (pnfs) in pt * 100'),
(name: 'NumberFONTColor'; abr: 'NFC'; exp: wpexPT; hint: '[42] Optional: FontColor (pncf)'),
(name: 'NumberFONTSTYLES'; abr: 'NFSty'; exp: wpexInteger; hint: '[43] Optional: CharStyles bitfield ( pnb, pni, pnul etc ...)'),
(name: 'NumberINDENT'; abr: 'NIND'; exp: wpexTW; hint:
'[44] Old Style Indent - NumberStyles may also use the INDENTFIRST/INDENTLEFT props!'),
(name: 'NumberFLAGS'; abr: 'NFLAGS'; exp: wpexInteger; hint: '[45] Numberation Options, i.e. lage numbering'),
(name: 'NumberPICTURE'; abr: 'NPIC'; exp: wpexInteger; hint: '[46] Reserved for number pictures'),
(name: 'Number_RES1'; abr: 'NRes1'; exp: wpexInteger; hint: '[47] - reserved'),
(name: 'Number_RES2'; abr: 'NRes2'; exp: wpexInteger; hint: '[48] - reserved'),
(name: 'Number_RES3'; abr: 'NRes3'; exp: wpexInteger; hint: '[49] - reserved'),
(name: 'BGColor'; abr: 'bgBC'; exp: wpexCOLOR; hint: '[50] Background Color'),
(name: 'FGColor'; abr: 'bgFC'; exp: wpexCOLOR; hint: '[51] Foreground Shading Color'),
(name: 'ShadingValue'; abr: 'shadV'; exp: wpexPERCENT; hint: '[52] Background Shading Percentage in % \tscellpct'),
(name: 'ShadingType'; abr: 'shadT'; exp: wpexInteger; hint: '[53] Background Shading Type ( \tsbgbdiag ... )'),
(name: 'BGBitMap'; abr: 'bgBit'; exp: wpexInteger; hint: '[54] Background Image.'),
(name: 'BGBitMapMode'; abr: 'bgBitM'; exp: wpexInteger; hint: '[55] Bitfield for scroll, center, center, repeat'),
(name: 'AParRes1'; abr: 'parres1'; exp: wpexInteger; hint: '[56] - reserved'),
(name: 'AParRes2'; abr: 'parres2'; exp: wpexInteger; hint: '[57] - reserved'),
(name: 'AParRes3'; abr: 'parres3'; exp: wpexInteger; hint: '[58] - reserved'),
(name: 'AParRes4'; abr: 'parres4'; exp: wpexInteger; hint: '[59] - reserved'),
(name: 'BorderTypeL'; abr: 'brTL'; exp: wpexInteger; hint: '[60] Border Mode Left(no, single, double etc)'),
(name: 'BorderTypeT'; abr: 'brTT'; exp: wpexInteger; hint: '[61] Border Mode Top (no, single, double etc)'),
(name: 'BorderTypeR'; abr: 'brTR'; exp: wpexInteger; hint: '[62] Border Mode Right(no, single, double etc)'),
(name: 'BorderTypeB'; abr: 'brTB'; exp: wpexInteger; hint: '[63] Border Mode Bottom (no, single, double etc)'),
(name: 'BorderTypeDiaTLBR'; abr: 'brTDa'; exp: wpexInteger; hint: '[64] Diagonal Line - TopLeft/BottomRight ( \cldglu )'),
(name: 'BorderTypeDiaTRBL'; abr: 'brTDb'; exp: wpexInteger; hint: '[65] Diagonal Line - TopRight/BottomLeft'),
(name: 'BorderWidthL'; abr: 'brWL'; exp: wpexInteger; hint: '[66] Thickness left inner Line'),
(name: 'BorderWidthT'; abr: 'brWT'; exp: wpexInteger; hint: '[67] Thickness top inner Line'),
(name: 'BorderWidthR'; abr: 'brWR'; exp: wpexInteger; hint: '[68] Thickness right inner Line'),
(name: 'BorderWidthB'; abr: 'brEB'; exp: wpexInteger; hint: '[69] Thickness bottom inner Line'),
(name: 'BorderWidthDiaTLBR'; abr: 'brWDa'; exp: wpexInteger; hint: '[70] Diagonal Line - TopLeft/BottomRight'),
(name: 'BorderWidthDiaTRBL'; abr: 'brWDb'; exp: wpexInteger; hint: '[71] Diagonal Line - TopRight/BottomLeft'),
(name: 'BorderColorL'; abr: 'brCL'; exp: wpexCOLOR; hint: '[72] Color left inner Line'),
(name: 'BorderColorT'; abr: 'brCT'; exp: wpexCOLOR; hint: '[73] Color top inner Line'),
(name: 'BorderColorR'; abr: 'brCR'; exp: wpexCOLOR; hint: '[74] Color right inner Line'),
(name: 'BorderColorB'; abr: 'brCB'; exp: wpexCOLOR; hint: '[75] Color bottom inner Line'),
(name: 'BorderColorDiaTLBR'; abr: 'brCDa'; exp: wpexCOLOR; hint: '[76] Diagonal Line - TopLeft/BottomRight'),
(name: 'BorderColorDiaTRBL'; abr: 'brCDb'; exp: wpexCOLOR; hint: '[77] Diagonal Line - TopRight/BottomLeft'),
(name: 'BorderTypeH'; abr: 'brTH'; exp: wpexInteger; hint: '[78] Border Mode ALL INNER horizontal LINES - for table'),
(name: 'BorderWidthH'; abr: 'brWH'; exp: wpexInteger; hint: '[79] Thickness ALL INNER horizontal LINES - for table'),
(name: 'BorderColorH'; abr: 'brCH'; exp: wpexCOLOR; hint: '[80] Color ALL ALL INNER horizontal LINES - for table'),
(name: 'BorderTypeV'; abr: 'brTV'; exp: wpexInteger; hint: '[81] Border Mode ALL INNER vertical LINES - for table'),
(name: 'BorderWidthV'; abr: 'brWV'; exp: wpexInteger; hint: '[82] Thickness ALL INNER vertical LINES - for table'),
(name: 'BorderColorV'; abr: 'brCV'; exp: wpexCOLOR; hint: '[83] Color ALL ALL INNER vertical LINES - for table'),
(name: 'BorderTypeBar'; abr: 'brTBa'; exp: wpexInteger; hint: '[84] Border Mode ALL INNER vertical LINES - for table'),
(name: 'BorderWidthBar'; abr: 'brWBa'; exp: wpexInteger; hint: '[85] Thickness ALL INNER vertical LINES - for table'),
(name: 'BorderColorBar'; abr: 'brCBa'; exp: wpexCOLOR; hint: '[86] Color ALL ALL INNER vertical LINES - for table'),
(name: 'BorderType'; abr: 'brT'; exp: wpexInteger; hint: '[87] Border Mode ALL LINES AROUND BOX'),
(name: 'BorderWidth'; abr: 'brW'; exp: wpexInteger; hint: '[88] Thickness ALL LINES'),
(name: 'BorderColor'; abr: 'brC'; exp: wpexCOLOR; hint: '[89] Color ALL LINES'),
(name: 'BorderFlags'; abr: 'brFL'; exp: wpexInteger; hint: '[90] - switch borders on - must be used to see any borders'),
(name: 'PaddingAll'; abr: 'Pall'; exp: wpexInteger; hint: '[91] - Padding all sides. Overridden by PaddingLeft etc.'),
(name: 'ParProtected'; abr: 'ParProtect'; exp: wpexInteger; hint: '[92] no editing'),
(name: 'ParKeep'; abr: 'ParKeep'; exp: wpexInteger; hint: '[93] Keep Paragraph together'),
(name: 'ParKeepN'; abr: 'ParKeepN'; exp: wpexInteger; hint: '[94] Keep Paragraph with next'),
(name: 'paresD'; abr: 'resD'; exp: wpexInteger; hint: '[95] Reserved'),
(name: 'paresE'; abr: 'resE'; exp: wpexInteger; hint: '[96] Reserved'),
(name: 'paresF'; abr: 'resF'; exp: wpexInteger; hint: '[97] Reserved'),
(name: 'paresG'; abr: 'resG'; exp: wpexInteger; hint: '[98] Reserved'),
(name: 'paresH'; abr: 'resH'; exp: wpexInteger; hint: '[99] Reserved'),
(name: 'paresI'; abr: 'resI'; exp: wpexInteger; hint: '[100] Reserved'),
(name: 'paresJ'; abr: 'resJ'; exp: wpexInteger; hint: '[101] Reserved'),
(name: 'Box_HPositionMode'; abr: 'bxHM'; exp: wpexInteger;
hint: '[102] Horizontal: normal, relative, absolute, fixed(on page), alignment ...'),
(name: 'Box_VPositionMode'; abr: 'bxVM'; exp: wpexInteger; hint: '[103] Vertical: normal, relative, absolute, fixed(on page)'),
(name: 'BoxWidth'; abr: 'bxW'; exp: wpexInteger; hint: '[104] TABLES'),
(name: 'BoxHeight'; abr: 'bxH'; exp: wpexInteger; hint: '[105] TABLES'),
(name: 'BoxMinWidth'; abr: 'bxMW'; exp: wpexInteger; hint: '[106;'),
(name: 'BoxMinHeight'; abr: 'bxMH'; exp: wpexInteger; hint: '[107] ALso used for -minimum- RowHeight !'),
(name: 'BoxMaxWidth'; abr: 'bxMxW'; exp: wpexInteger; hint: '[108] TABLES'),
(name: 'BoxMaxHeight'; abr: 'bxMxH'; exp: wpexInteger; hint: '[109] ALso used for -absolute- RowHeight !'),
(name: 'BoxOverflow'; abr: 'bxOV'; exp: wpexInteger; hint: '[110;'),
(name: 'Box_XPos'; abr: 'bxX'; exp: wpexInteger; hint: '[111] - reserved'),
(name: 'Box_YPos'; abr: 'bxY'; exp: wpexInteger; hint: '[112] - reserved'),
(name: 'Boy_ZIndex'; abr: 'bxZ'; exp: wpexInteger; hint: '[113] Stacking (only for images in CSS2) (Word evtl overlay)'),
(name: 'Box_TextDistanceX'; abr: 'bxDistX'; exp: wpexInteger; hint:
'[114] the horizontal distance in twips from text on both sides of the frame (dfrmtxtx)'),
(name: 'Box_TextDistanceY'; abr: 'bxDistY'; exp: wpexInteger; hint:
'[115] is the vertical distance in twips from text on both sides of the frame'),
(name: 'Box_NoWrapMode'; abr: 'bxNWR'; exp: wpexInteger; hint: '[116] switch off wrapping on left/right side'),
(name: 'Box_TextFlow'; abr: 'bxFlow'; exp: wpexInteger; hint: '[117] - reserved'),
(name: 'Box_Align'; abr: 'bxA'; exp: wpexInteger; hint: '[118] Alignment of the box or Image - override Position !'),
(name: 'BoxWidth_PC'; abr: 'bxWpc'; exp: wpexInteger; hint: '[119] - Width of table or row in % '),
(name: 'BoxMarginLeft'; abr: 'bxMargL'; exp: wpexInteger; hint: '[120] - the left margin of the table'),
(name: 'BoxMarginRight'; abr: 'bxMargR'; exp: wpexInteger; hint: '[121] - the right margin of the table'),
(name: 'Display'; abr: 'dspl'; exp: wpexInteger; hint: '[122] none to hide, for images: inline or block'),
(name: 'Visibility'; abr: 'vis'; exp: wpexInteger; hint: '[123] CSS: Visible, hidden, collaps, inherit'),
(name: 'VisibilityOptions'; abr: 'visO'; exp: wpexInteger; hint: '[124] - reserved'),
(name: 'NoWrap'; abr: 'nwrap'; exp: wpexInteger; hint: '[125] - 0 = neutral, otherwise length in char! '),
(name: 'ParID'; abr: 'ID'; exp: wpexInteger; hint: '[126] any value'),
(name: 'ParFlags'; abr: 'FL'; exp: wpexInteger; hint:
'[127] RTF flags such as \spv, \hyphpar, \noline, \nowidctlpar, \widctlpar \pagebb (Styles onnly)'),
(name: 'HTMLSyntax'; abr: 'HTMSTX'; exp: wpexInteger; hint:
'[128] Flags set by the HTML reader to use HTML instead of CSS syntax'),
(name: 'BANDFLAGS_1'; abr: 'BANDFLAGS_1'; exp: wpexInteger; hint: '[129] Used for WPReporter'),
(name: 'BANDFLAGS_2'; abr: 'BANDFLAGS_2'; exp: wpexInteger; hint: '[130] Used for WPReporter'),
(name: 'BANDPAR_1'; abr: 'BANDPAR_1'; exp: wpexInteger; hint: '[131] Used for WPReporter'),
(name: 'BANDPAR_2'; abr: 'BANDPAR_2'; exp: wpexInteger; hint: '[132] Used for WPReporter'),
(name: 'BANDPAR_STR'; abr: 'BANDPAR_STR'; exp: wpexSTRING; hint: '[133] Used for WPReporter'),
(name: 'CounterReset'; abr: 'CounterReset'; exp: wpexInteger; hint:
'[134] param lo word = id of counter, exp:wpexInteger; high word = value (ID=0 = current numbering style!)'),
(name: 'CounterID'; abr: 'CounterID'; exp: wpexInteger; hint: '[135] Counter ID'),
(name: 'CounterIncrement'; abr: 'CounterIncrement'; exp: wpexInteger; hint: '[136] Counter Increment Value'),
(name: 'ContentBefore'; abr: 'ContentBefore'; exp: wpexInteger; hint: '[137] "content:" command to create text ":before"'),
(name: 'ContentAfter'; abr: 'ContentAfter'; exp: wpexInteger; hint: '[138] "content:" command to create text ":after"'),
(name: 'ContentDefault'; abr: 'ContentDefault'; exp: wpexInteger; hint:
'[139] "content:" command to create text if element is empty otherwise (forms)'),
(name: 'LINENUM_INC'; abr: 'LINENUM_INC'; exp: wpexInteger; hint:
'[140] Line-number modulus amount to increase each line number (default = 1) \ linemodN'),
(name: 'LINENUM_X'; abr: 'LINENUM_X'; exp: wpexInteger; hint:
'[141] Distance from the line number to the left text margin in twips (the default is 360) \ linexN'),
(name: 'LINENUM_START '; abr: 'LINENUM_START'; exp: wpexInteger; hint: '[142] Start number'),
(name: 'LINENUM_FLAGS'; abr: 'LINENUM_FLAGS'; exp: wpexInteger; hint: '[143] Numbering flags'),
(name: 'COLUMNS'; abr: 'COLUMNS'; exp: wpexInteger; hint: '[144] Column Count - 0 to switch off'),
(name: 'COLUMN_X'; abr: 'COLUMN_X'; exp: wpexInteger; hint: '[145] Space between COlumns (the default is 720).'),
(name: 'COLFLAGS'; abr: 'COLFLAGS'; exp: wpexInteger; hint: '[146] Flags'),
(name: 'COLRES1'; abr: 'COLRES1'; exp: wpexInteger; hint: '[147] reserved for autoformat and width'),
(name: 'COLRES2'; abr: 'COLRES2'; exp: wpexInteger; hint: '[148]'),
(name: 'COLRES3'; abr: 'COLRES3'; exp: wpexInteger; hint: '[149]'),
(name: 'PAR_NAME'; abr: 'PAR_NAME'; exp: wpexSTRING; hint: '[150]'),
(name: 'PAR_COMMAND'; abr: 'PAR_COMMAND'; exp: wpexSTRING; hint: '[151]'),
(name: 'PAR_FORMAT'; abr: 'PAR_FORMAT'; exp: wpexInteger; hint: '[152]'),
(name: 'paresA'; abr: 'paresA'; exp: wpexInteger; hint: '[153] reserved'),
(name: 'ParProtectStyle'; abr: 'ProtectStyle'; exp: wpexInteger; hint: '[154] The style may not be changed'),
(name: 'ParOnlyNumbers'; abr: 'ParOnlyNum'; exp: wpexInteger; hint: '[155] only accept numbers (for table calc!)'),
(name: 'ParOneLine'; abr: 'ParOneLine'; exp: wpexInteger; hint: '[156] No Linebreak on Input allowed'),
(name: 'paresB'; abr: 'paresB'; exp: wpexInteger; hint: '[157] reserved'),
(name: 'paresC'; abr: 'ParKeepN'; exp: wpexInteger; hint: '[158] reserved'),
(name: 'NumberStart'; abr: 'NumberStart'; exp: wpexInteger; hint: '[159] a certain start number for numbering'),
(name: 'ParIsOutline'; abr: 'ParIsOutline'; exp: wpexInteger; hint: '[160] Is Outline (used by PDF Export) - value = level!'),
(name: 'ParOutlineBreak'; abr: 'ParOutlineBreak'; exp: wpexInteger; hint: '[161] Restart numbering'),
(name: 'paresK'; abr: 'resK'; exp: wpexInteger; hint: '[162] Maximum length for this paragraph.'),
(name: 'ParCaption'; abr: 'parcap'; exp: wpexString; hint: '[163] Caption for this paragraph or outline.'),
(name: 'paresM'; abr: 'resM'; exp: wpexInteger; hint: '[164] Reserved'),
(name: 'paresN'; abr: 'resN'; exp: wpexInteger; hint: '[165] Reserved'),
(name: 'paresO'; abr: 'resO'; exp: wpexInteger; hint: '[166] Reserved'),
(name: 'paresP'; abr: 'resO'; exp: wpexInteger; hint: '[167] Reserved'),
(name: 'USERPROPA'; abr: 'usrA'; exp: wpexInteger; hint: '[168] User Property 1'),
(name: 'USERPROPB'; abr: 'usrB'; exp: wpexInteger; hint: '[169] User Property 2'),
(name: 'CellSpaceL'; abr: 'clSL'; exp: wpexInteger; hint: '[170] Cell distance between adjacent cells. (Left Cell Spacing)'),
(name: 'CellSpaceR'; abr: 'clSR'; exp: wpexInteger; hint: '[171] (Right Cell Spacing)'),
(name: 'CellSpaceT'; abr: 'clST'; exp: wpexInteger; hint: '[172] (Top Cell Spacing)'),
(name: 'CellSpaceB'; abr: 'clSB'; exp: wpexInteger; hint: '[173] (Bottom Cell pacing)'),
(name: 'CELLFlags'; abr: 'clFL'; exp: wpexInteger; hint: '[174] Cell or Row flags (also note the flags in par.props)'),
(name: 'COLWIDTH_PC'; abr: 'clWpc'; exp: wpexPERCENT; hint: '[175] Width of this cell in %'),
(name: 'COLWIDTH'; abr: 'clW'; exp: wpexInteger; hint: '[176] Width of this cell in twips'),
(name: 'COLRESERVED'; abr: 'clReserved'; exp: wpexInteger; hint: '[177] reserved'),
(name: 'CellRes1'; abr: 'cResA'; exp: wpexInteger; hint: '[178] - reserved'),
(name: 'CellRes2'; abr: 'cResB'; exp: wpexInteger; hint: '[179] - reserved')
);
WPParagraphTypeNames: array[TWPParagraphType] of string =
('div', 'p', 'li', 'code', 'tag', 'com',
'table', 'tr',
'alevel', 'blevel', 'clevel',
'group', 'header', 'data', 'footer', 'ol'
,'parbox' );
function DebugBreak : Boolean;
function WPGetHashCode(const Buffer; Count: Integer): Word; {$IFNDEF FPC} assembler; {$ENDIF}
var
WPDefine_PNGIMG : Boolean = {$IFDEF DELPHIXE}true {$ELSE}false{$ENDIF};
implementation
function TWPCustomAttrDlgAbstract.Implements(id : Integer): Boolean;
begin if id=FImplementsID then Result := true else raise Exception.Create('Wrong dialog type:' + Self.Classname); end;
Resourcestring
wpSTmeDefaultUnitINCHorCM = 'INCH';
wpSTmeUnitInch = 'Inch';
wpSTmeUnitCm = 'cm';
wpSTmeDecimalSeperator = '';
wpSTmeDefaultCharSet = '0';
wpSTmeFilterRTF = 'RTF files (*.rtf)|*.RTF';
wpSTmeFilterCustom = 'Custom Format (*.xyz)|*.xyz';
wpSTmeFilterHTML = 'HTML files (*.htm,*.html,*.mht)|*.HTM;*.HTML;*.MHT';
wpSTmeFilterTXT = 'Text files (*.txt)|*.TXT';
wpSTmeFilterXML = 'XML files (*.xml)|*.XML';
wpSTmeFilterCSS = 'Stylesheets files (*.sty,*.css,*.wpcss)|*.STY;*.CSS;*.wpcss; ';
wpSTmeFilterALL = 'All files (*.*)|*.*';
wpSTmeFilterMime = 'RTF files (*.rtf)|*.RTF|HTML files (*.htm,*.html)|*.HTM;*.HTML|Webarchives (*.mht,*.msg)|*.MHT;*.MSG|Text files (*.txt)' +
'|*.TXT|Native Files (*.WPT)|*.WPT|All files (*.*)|*.*';
wpSTmeFilter = 'RTF files (*.rtf)|*.RTF|HTML files (*.htm,*.html)|*.HTM;*.HTML|Text files (*.txt)' +
'|*.TXT|Native Files (*.WPT)|*.WPT|All files (*.*)|*.*';
wpSTmeUserCancel = 'Do you want to abort operation?';
wpSTmeReady = 'Ready';
wpSTmeReading = 'reading ...';
wpSTmeWriting = 'writing ...';
wpSTmeFormatA = 'formatting ...';
wpSTmeFormatB = 'formatting ...';
wpSTmeClearMemory = 'initialize memory';
wpSTmeNoSelection = 'no text selected';
wpSTmeRichText = 'RICH';
wpSTmePlainText = 'PLAIN';
wpSTmeSysError = 'Internal Error';
wpSTmeClearTabs = 'Delete all tab stops?';
wpSTmeObjGraphicFilter = 'Graphic Files (*.BMP,*.EMF,*.WMF,*.JPG)|*.BMP;*.WMF;*.EMF;*.JPG;*.JPEG';
wpSTmeObjGraphicFilterExt = 'Graphic Files (*.BMP,*.EMF,*.WMF,*.JPG,*.GIF,*.PNG)|*.BMP;*.WMF;*.EMF;*.JPG;*.JPEG;*.GIF;*.PNG';
wpSTmeObjTextFilter = 'Textfiles (*.TXT)|*.TXT';
wpSTmeObjNotSupported = 'Cannot use other objects than of type "TWPObject".';
wpSTmeObjGraphicNotLinked = 'Graphic support was not linked. Please include unit "WPEmOBJ" to project.';
wpSTmeObjDelete = 'Delete the object';
wpSTmeObjInsert = 'Insert new object';
wpSTmeSaveChangedText = 'Save changed text?';
wpSTmeClearChangedText = 'Discard changes?';
wpSTmeCannotRenameFile = 'Cannot rename file %s!';
wpSTmeErrorWriteToFile = 'Cannot write to file %s!';
wpSTmeErrorReadingFile = 'Error occured when reading file %s!';
wpSTmeRecursiveToolbarUsage = 'Property "NextToolBar" was used recursively';
wpSTmeWrongScreenmode = 'Wrong "ScreenResMode" in object!';
wpSTmeTextNotFound = 'Text not found';
wpSTmeUndefinedInsertpoint = 'Insertpoint not defined. Provide tag or fieldname.';
wpSTmeNotSupportedProperty = 'This property is not yet supported!';
wpSTmeUseOnlyBitmaps = 'Please use only bitmaps';
wpSTmeWrongUsageOfFastAppend = 'cannot append text to "<self>"';
wpSTmePaletteCompletelyUsed = 'All colors in palette in use';
wpSTmeWriterClassNotFound = 'Text-Writer class not found';
wpSTmeReaderClassNotFound = 'Text-Reader class not found';
wpSTmeWrongArgumentError = 'Wrong Arguments!';
wpSTmeIOClassError = 'Incorrect IO Class :';
wpSTmeNotSupportedError = 'Mode not supported';
wpSTmeutNone = '';
wpSTmeutAny = 'Changes';
wpSTmeutInput = 'Input';
wpSTmeutDeleteText = 'Delete';
wpSTmeutChangeAttributes = 'Attribute Modification';
wpSTmeutChangeIndent = 'Indent Modification';
wpSTmeutChangeSpacing = 'Spacing Modification';
wpSTmeutChangeAlignment = 'Alignment Modification';
wpSTmeutChangeTabs = 'Tabs Modification';
wpSTmeutChangeBorder = 'Border Modification';
wpSTmeutDeleteSelection = 'Deletion';
wpSTmeutDragAndDrop = 'Drag and Drop';
wpSTmeutPaste = 'Paste';
wpSTmeutChangeTable = 'Change Table';
wpSTmeutChangeGraphic = 'Change Graphic';
wpSTmeutChangeCode = 'Change Code';
wpSTmeutUpdateStyle = 'Update Style';
wpSTmeutChangeTemplate = 'Change Template';
wpSTmeutInsertBookmark = 'Insert Bookmark';
wpSTmeutInsertHyperlink = 'Insert Hyperlink';
wpSTmeutInsertField = 'Insert Field';
wpSTmeDiaAlLeft = 'Left';
wpSTmeDiaAlCenter = 'Center';
wpSTmeDiaAlRight = 'Right';
wpSTmeDiaAlJustified = 'Justified';
wpSTmeDiaYes = 'Yes';
wpSTmeDiaNo = 'No';
wpSTmeTkLeft = 'Left';
wpSTmeTkCenter = 'Center';
wpSTmeTkRight = 'Right';
wpSTmeTkDecimal = 'Decimal';
wpSTmeSpacingMultiple = 'multiple';
wpSTmeSpacingAtLeast = 'at least';
wpSTmeSpacingExact = 'exactly';
wpSTmePaperCustom = 'Custom Size';
wpSTmeWrongFormat = 'File has wrong format!';
wpSTmeReportTemplateErr = 'Error in Report Template!';
wpSTmeUnicodeModeNotActivated = 'Unicode mode was not activated';
wpSTmeUndefinedValue = '<default>';
wpSTmeUndefinedStyle = '<default>';
wpSTmeTransparent = 'Transparent';
wpSTmeNeutralColor = 'None';
wpSTmeCreateNewStyle = '<New Style...>';
wpSTmeNewStyleName = '<New Style>';
wpSTmeEditCurrStyle = '<Edit Style...>';
wpSTmeTextFoundAndReplaced = 'Found and replaced text %d times!';
wpSTwpCannotInsObject = 'Cannot insert object in Object';
wpSTwpInsertTextField = 'Insert Text Field';
wpSTwpInsertTextField_Name = 'Name';
wpSTwpInsertMailmergeField = 'Insert Mailmerge Field';
wpSTwpInsertMailmergeFieldName = 'Fieldname';
wpSTwpInsertBookmark = 'Insert Bookmark';
wpSTwpInsertBookmark_Name = 'Name';
wpSTwpInsertEditField = 'Insert Form Field';
wpSTwpInsertEditFieldName = 'Fieldname';
wpSTwpInsertHyperlink = 'Insert Hyperlink';
wpSTwpInsertHyperlinkName = 'Hyperlink Name';
wpSTwpInsertHyperlinkURL = 'URL';
wpSTwpZoomNormal = 'Normal View';
wpSTwpZoom100 = '100%';
wpSTwpZoomPageWidth = 'Page Width';
wpSTwpZoomPageHeight = 'Page Height';
wpSTwpZoomTwoPages = 'Two Pages';
wpSTwpThumbnails = 'Thumbnails';
wpSTPagePrp0 = 'All pages';
wpSTPagePrp1 = 'Odd pages';
wpSTPagePrp2 = 'Even pages';
wpSTPagePrp3 = 'First page only';
wpSTPagePrp4 = 'Last page only';
wpSTPagePrp5 = 'Not on first or last pages';
wpSTPagePrp6 = 'Not on last page';
wpSTPagePrp7 = 'Named';
wpSTPagePrp8 = 'Disabled';
wpSTPagePrp9 = 'Not on first page';
procedure TransferResourceStrings;
begin
WPPagePropertyRangeNames[TWPPagePropertyRange(0)] := wpSTPagePrp0;
WPPagePropertyRangeNames[TWPPagePropertyRange(1)] := wpSTPagePrp1;
WPPagePropertyRangeNames[TWPPagePropertyRange(2)] := wpSTPagePrp2;
WPPagePropertyRangeNames[TWPPagePropertyRange(3)] := wpSTPagePrp3;
WPPagePropertyRangeNames[TWPPagePropertyRange(4)] := wpSTPagePrp4;
WPPagePropertyRangeNames[TWPPagePropertyRange(5)] := wpSTPagePrp5;
WPPagePropertyRangeNames[TWPPagePropertyRange(6)] := wpSTPagePrp6;
WPPagePropertyRangeNames[TWPPagePropertyRange(7)] := wpSTPagePrp7;
WPPagePropertyRangeNames[TWPPagePropertyRange(8)] := wpSTPagePrp8;
WPPagePropertyRangeNames[TWPPagePropertyRange(9)] := wpSTPagePrp9;
FWPVCLStrings[meDefaultUnit_INCH_or_CM] := wpSTmeDefaultUnitINCHorCM;
FWPVCLStrings[meUnitInch] := wpSTmeUnitInch;
FWPVCLStrings[meUnitCm] := wpSTmeUnitCm;
FWPVCLStrings[meDecimalSeperator] := wpSTmeDecimalSeperator;
FWPVCLStrings[meDefaultCharSet] := wpSTmeDefaultCharSet;
FWPVCLStrings[meFilterRTF] := wpSTmeFilterRTF;
FWPVCLStrings[meFilterHTML] := wpSTmeFilterHTML;
FWPVCLStrings[meFilterTXT] := wpSTmeFilterTXT;
FWPVCLStrings[meFilterXML] := wpSTmeFilterXML;
FWPVCLStrings[meFilterCSS] := wpSTmeFilterCSS;
FWPVCLStrings[meFilterCustom] := wpSTmeFilterCustom;
FWPVCLStrings[meFilterALL] := wpSTmeFilterALL;
FWPVCLStrings[meFilter] := wpSTmeFilter;
FWPVCLStrings[meFilterMime] := wpSTmeFilterMime;
FWPVCLStrings[meUserCancel] := wpSTmeUserCancel;
FWPVCLStrings[meReady] := wpSTmeReady;
FWPVCLStrings[meReading] := wpSTmeReading;
FWPVCLStrings[meWriting] := wpSTmeWriting;
FWPVCLStrings[meFormatA] := wpSTmeFormatA;
FWPVCLStrings[meFormatB] := wpSTmeFormatB;
FWPVCLStrings[meClearMemory] := wpSTmeClearMemory;
FWPVCLStrings[meNoSelection] := wpSTmeNoSelection;
FWPVCLStrings[meRichText] := wpSTmeRichText ;
FWPVCLStrings[mePlainText] := wpSTmePlainText;
FWPVCLStrings[meSysError] := wpSTmeSysError;
FWPVCLStrings[meClearTabs] := wpSTmeClearTabs;
FWPVCLStrings[meObjGraphicFilter] := wpSTmeObjGraphicFilter;
FWPVCLStrings[meObjGraphicFilterExt] := wpSTmeObjGraphicFilterExt;
FWPVCLStrings[meObjTextFilter] := wpSTmeObjTextFilter;
FWPVCLStrings[meObjNotSupported] := wpSTmeObjNotSupported;
FWPVCLStrings[meObjGraphicNotLinked] := wpSTmeObjGraphicNotLinked;
FWPVCLStrings[meObjDelete] := wpSTmeObjDelete;
FWPVCLStrings[meObjInsert] := wpSTmeObjInsert;
FWPVCLStrings[meSaveChangedText] := wpSTmeSaveChangedText;
FWPVCLStrings[meClearChangedText] := wpSTmeClearChangedText;
FWPVCLStrings[meCannotRenameFile] := wpSTmeCannotRenameFile;
FWPVCLStrings[meErrorWriteToFile] := wpSTmeErrorWriteToFile;
FWPVCLStrings[meErrorReadingFile] := wpSTmeErrorReadingFile;
FWPVCLStrings[meRecursiveToolbarUsage] := wpSTmeRecursiveToolbarUsage;
FWPVCLStrings[meWrongScreenmode] := wpSTmeWrongScreenmode;
FWPVCLStrings[meTextNotFound] := wpSTmeTextNotFound;
FWPVCLStrings[meUndefinedInsertpoint] := wpSTmeUndefinedInsertpoint;
FWPVCLStrings[meNotSupportedProperty] := wpSTmeNotSupportedProperty;
FWPVCLStrings[meUseOnlyBitmaps] := wpSTmeUseOnlyBitmaps;
FWPVCLStrings[meWrongUsageOfFastAppend] := wpSTmeWrongUsageOfFastAppend;
FWPVCLStrings[mePaletteCompletelyUsed] := wpSTmePaletteCompletelyUsed;
FWPVCLStrings[meWriterClassNotFound] := wpSTmeWriterClassNotFound;
FWPVCLStrings[meReaderClassNotFound] := wpSTmeReaderClassNotFound;
FWPVCLStrings[meWrongArgumentError] := wpSTmeWrongArgumentError;
FWPVCLStrings[meIOClassError] := wpSTmeIOClassError;
FWPVCLStrings[meNotSupportedError] := wpSTmeNotSupportedError;
FWPVCLStrings[meutNone] := wpSTmeutNone;
FWPVCLStrings[meutAny] := wpSTmeutAny;
FWPVCLStrings[meutInput] := wpSTmeutInput;
FWPVCLStrings[meutDeleteText] := wpSTmeutDeleteText;
FWPVCLStrings[meutChangeAttributes] := wpSTmeutChangeAttributes;
FWPVCLStrings[meutChangeIndent] := wpSTmeutChangeIndent;
FWPVCLStrings[meutChangeSpacing] := wpSTmeutChangeSpacing;
FWPVCLStrings[meutChangeAlignment] := wpSTmeutChangeAlignment;
FWPVCLStrings[meutChangeTabs] := wpSTmeutChangeTabs;
FWPVCLStrings[meutChangeBorder] := wpSTmeutChangeBorder;
FWPVCLStrings[meutDeleteSelection] := wpSTmeutDeleteSelection;
FWPVCLStrings[meutDragAndDrop] := wpSTmeutDragAndDrop;
FWPVCLStrings[meutPaste] := wpSTmeutPaste;
FWPVCLStrings[meutChangeTable] := wpSTmeutChangeTable;
FWPVCLStrings[meutChangeGraphic] := wpSTmeutChangeGraphic;
FWPVCLStrings[meutChangeCode] := wpSTmeutChangeCode;
FWPVCLStrings[meutUpdateStyle] := wpSTmeutUpdateStyle;
FWPVCLStrings[meutChangeTemplate] := wpSTmeutChangeTemplate;
FWPVCLStrings[meutInsertBookmark] := wpSTmeutInsertBookmark;
FWPVCLStrings[meutInsertHyperlink] := wpSTmeutInsertHyperlink;
FWPVCLStrings[meutInsertField] := wpSTmeutInsertField;
FWPVCLStrings[meDiaAlLeft] := wpSTmeDiaAlLeft;
FWPVCLStrings[meDiaAlCenter] := wpSTmeDiaAlCenter;
FWPVCLStrings[meDiaAlRight] := wpSTmeDiaAlRight;
FWPVCLStrings[meDiaAlJustified] := wpSTmeDiaAlJustified;
FWPVCLStrings[meDiaYes] := wpSTmeDiaYes;
FWPVCLStrings[meDiaNo] := wpSTmeDiaNo;
FWPVCLStrings[meTkLeft] := wpSTmeTkLeft;
FWPVCLStrings[meTkCenter] := wpSTmeTkCenter;
FWPVCLStrings[meTkRight] := wpSTmeTkRight;
FWPVCLStrings[meTkDecimal] := wpSTmeTkDecimal;
FWPVCLStrings[meSpacingMultiple] := wpSTmeSpacingMultiple;
FWPVCLStrings[meSpacingAtLeast] := wpSTmeSpacingAtLeast;
FWPVCLStrings[meSpacingExact] := wpSTmeSpacingExact;
FWPVCLStrings[mePaperCustom] := wpSTmePaperCustom;
FWPVCLStrings[meWrongFormat] := wpSTmeWrongFormat;
FWPVCLStrings[meReportTemplateErr] := wpSTmeReportTemplateErr;
FWPVCLStrings[meUnicodeModeNotActivated] := wpSTmeUnicodeModeNotActivated;
FWPVCLStrings[meUndefinedValue] := wpSTmeUndefinedValue;
FWPVCLStrings[meUndefinedStyle] := wpSTmeUndefinedStyle;
FWPVCLStrings[meTransparent] := wpSTmeTransparent;
FWPVCLStrings[meNeutralColor] := wpSTmeNeutralColor;
FWPVCLStrings[meCreateNewStyle] := wpSTmeCreateNewStyle;
FWPVCLStrings[meNewStyleName] := wpSTmeNewStyleName;
FWPVCLStrings[meEditCurrStyle] := wpSTmeEditCurrStyle;
FWPVCLStrings[meTextFoundAndReplaced] := wpSTmeTextFoundAndReplaced;
FWPVCLStrings[wpCannotInsObject] := wpSTwpCannotInsObject;
FWPVCLStrings[wpInsertTextField] := wpSTwpInsertTextField;
FWPVCLStrings[wpInsertTextField_Name] := wpSTwpInsertTextField_Name;
FWPVCLStrings[wpInsertMailmergeField] := wpSTwpInsertMailmergeField;
FWPVCLStrings[wpInsertMailmergeField_Name] := wpSTwpInsertMailmergeFieldName;
FWPVCLStrings[wpInsertBookmark] := wpSTwpInsertBookmark;
FWPVCLStrings[wpInsertBookmark_Name] := wpSTwpInsertBookmark_Name;
FWPVCLStrings[wpInsertEditField] := wpSTwpInsertEditField;
FWPVCLStrings[wpInsertEditField_Name] := wpSTwpInsertEditFieldName;
FWPVCLStrings[wpInsertHyperlink] := wpSTwpInsertHyperlink;
FWPVCLStrings[wpInsertHyperlink_Name] := wpSTwpInsertHyperlinkName;
FWPVCLStrings[wpInsertHyperlink_URL] := wpSTwpInsertHyperlinkURL;
FWPVCLStrings[wpZoomNormal] := wpSTwpZoomNormal;
FWPVCLStrings[wpZoom100] := wpSTwpZoom100;
FWPVCLStrings[wpZoomPageWidth] := wpSTwpZoomPageWidth;
FWPVCLStrings[wpZoomPageHeight] := wpSTwpZoomPageHeight;
FWPVCLStrings[wpZoomTwoPages] := wpSTwpZoomTwoPages;
FWPVCLStrings[wpThumbnails] := wpSTwpThumbnails;
end;
function DebugBreak : Boolean;
begin
Result := false;
end;
{$IFDEF FPC}
function WPGetHashCode(const Buffer; Count: Integer): Word;
var
I: Integer;
P: PByte;
begin
P := @Buffer;
Result := 0;
for I := 0 to Count - 1 do
begin
Result := ((Result and $F800) shr 11) or (Result shl 5);
Result := Result xor P^;
Inc(P);
end;
end;
{$ELSE}
{$IFDEF WIN64}
{$R-}
function WPGetHashCode(const Buffer; Count: Integer): Word;
var
I: Integer;
P: PByte;
begin
P := @Buffer;
Result := 0;
for I := 0 to Count - 1 do
begin
Result := ((Result and $F800) shr 11) or (Result shl 5);
Result := Result xor P^;
Inc(P);
end;
end;
{$IFDEF WPDEBUG}{$R+}{$ENDIF}
{$ELSE}
function WPGetHashCode(const Buffer; Count: Integer): Word; assembler;
asm
MOV ECX,EDX
MOV EDX,EAX
XOR EAX,EAX
@@1: ROL AX,5
XOR AL,[EDX]
INC EDX
DEC ECX
JNE @@1
end;
{$ENDIF}
{$IFDEF SHOWWARNINGS}
{$WARNINGS ON}
{$ENDIF}
{$ENDIF}
initialization
TransferResourceStrings;
end.
|
unit RSDialogs;
{ *********************************************************************** }
{ }
{ RSPak Copyright (c) Rozhenko Sergey }
{ http://sites.google.com/site/sergroj/ }
{ sergroj@mail.ru }
{ }
{ This file is a subject to any one of these licenses at your choice: }
{ BSD License, MIT License, Apache License, Mozilla Public License. }
{ }
{ *********************************************************************** }
{$I RSPak.inc}
interface
uses Dialogs, Forms, Classes, CommDlg, Windows, Messages, RSCommon;
type
TRSOpenSaveDialog = class;
TRSOpenSaveDialogBeforeShow = procedure(Sender: TRSOpenSaveDialog;
var DialogData: TOpenFilename) of object;
TRSWndProcEvent = RSCommon.TRSWndProcEvent;
TRSOpenSaveDialog = class(TOpenDialog)
private
FSaveDialog: boolean;
FOnBeforeShow: TRSOpenSaveDialogBeforeShow;
FOnWndProc: TRSWndProcEvent;
FObjectInstance: pointer;
procedure MainWndProc(var message: TMessage);
protected
function TaskModalDialog(DialogFunc: pointer; var DialogData): Bool; override;
procedure TranslateWndProc(var Msg: TMessage);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: boolean; override;
published
property SaveDialog: boolean read FSaveDialog write FSaveDialog default false;
property OnBeforeShow: TRSOpenSaveDialogBeforeShow read FOnBeforeShow write FOnBeforeShow;
property OnWndProc: TRSWndProcEvent read FOnWndProc write FOnWndProc;
end;
procedure register;
implementation
procedure register;
begin
RegisterComponents('RSPak', [TRSOpenSaveDialog]);
end;
constructor TRSOpenSaveDialog.Create(AOwner: TComponent);
begin
inherited;
FObjectInstance:= MakeObjectInstance(MainWndProc);
end;
destructor TRSOpenSaveDialog.Destroy;
begin
FreeObjectInstance(FObjectInstance);
inherited;
end;
procedure GetSaveFileNamePreviewA; external 'MSVFW32.dll';
procedure GetOpenFileNamePreviewA; external 'MSVFW32.dll';
function TRSOpenSaveDialog.Execute: boolean;
begin
if SaveDialog then
result:= DoExecute(@GetSaveFileNamePreviewA)
else
result:= DoExecute(@GetOpenFileNamePreviewA);
{
if SaveDialog then
Result:= DoExecute(@GetSaveFileName)
else
Result:= DoExecute(@GetOpenFileName);
}
end;
procedure TRSOpenSaveDialog.MainWndProc(var message: TMessage);
begin
try
TranslateWndProc(message);
except
Application.HandleException(Self);
end;
end;
function TRSOpenSaveDialog.TaskModalDialog(DialogFunc: pointer;
var DialogData): Bool;
begin
TOpenFilename(DialogData).lpfnHook:= FObjectInstance;
if Assigned(FOnBeforeShow) then
FOnBeforeShow(self, TOpenFilename(DialogData));
result:= inherited TaskModalDialog(DialogFunc, DialogData);
end;
procedure TRSOpenSaveDialog.TranslateWndProc(var Msg: TMessage);
var b:boolean;
begin
if Assigned(FOnWndProc) then
begin
b:=false;
FOnWndProc(Self, Msg, b, WndProc);
if b then exit;
end;
WndProc(Msg);
end;
end.
|
program hw3q3a;
type
TAGTYPE = (i, r, b);
IRB = record
case kind: TAGTYPE of
i: (IFIELD: integer);
r: (RFIELD: real);
b: (BFIELD: Boolean);
end;
var
Vtype : char ;
Vval : string ;
Vint : integer ;
Vreal : real ;
V : IRB ;
strCode : integer ;
procedure NEG(var test : IRB) ;
var
iresult : integer ;
rresult : real ;
bresult : Boolean ;
begin
with test do
(*check the kind of the variant field, then perform the appropriate
negation and print the result*)
case kind of
i : begin
iresult := -1 * IFIELD ;
writeln('Negation of input is: ', iresult)
end ;
r : begin
rresult := -1.0 * RFIELD ;
writeln('Negation of input is: ', rresult)
end ;
b : begin
bresult := not BFIELD ;
writeln('Negation of input is: ', bresult)
end ;
end; (*case*)
end; (*proc NEG*)
begin (*program*)
writeln('Mark Sattolo, 428500, CSI3125, DGD-2, Assn#3') ;
writeln ;
(*request input*)
writeln('Please enter a value preceded by its type (i, r, or b).') ;
writeln('For example: r 3.14129 ') ;
write('Input: ') ;
(*get input*)
readln(Vtype, Vval) ;
(*According to Prof.Szpackowicz in class on Nov.9, we can assume that all input
will be perfect and do not have to do any error-checking for this.*)
(*if a boolean*)
if Vtype = 'b' then begin
(*set the kind field of V*)
V.kind := b ;
(*check for the most probable variations of 'true'*)
if ((Vval = ' true') or (Vval = ' True') or (Vval = ' TRUE')) then V.BFIELD := true
(*else can assume the input must be some variation of 'false'*)
else V.BFIELD := false ;
end ;
(*if an integer*)
if Vtype = 'i' then begin
(*set the kind field of V*)
V.kind := i ;
(*convert the string to an integer value - we can assume Vval will represent an integer*)
Val(Vval, Vint, strCode) ;
(*set the integer field of V*)
V.IFIELD := Vint ;
end ;
(*if a real*)
if Vtype = 'r' then begin
(*set the kind field of V*)
V.kind := r ;
(*convert the string to a real value - we can assume Vval will represent a real*)
Val(Vval, Vreal, strCode) ;
(*set the real field of V*)
V.RFIELD := Vreal ;
end ;
(*negate the value in V by calling the NEG procedure*)
NEG(V) ;
end.
|
unit kwRAISE;
{* Зарезервированное слово RAISE. Аналогично raise из Delphi. Если не было исключения, то генерируется EtfwScriptException.
Пример:
[code]
TRY
'Тестовое исключение' RAISE
EXCEPT
true >>> WasException
END
[code] }
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwRAISE.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "RAISE" MUID: (4DBAE64F02F7)
// Имя типа: "TkwRAISE"
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwRegisterableWord
, tfwScriptingInterfaces
;
type
TkwRAISE = class(TtfwRegisterableWord)
{* Зарезервированное слово RAISE. Аналогично raise из Delphi. Если не было исключения, то генерируется EtfwScriptException.
Пример:
[code]
TRY
'Тестовое исключение' RAISE
EXCEPT
true >>> WasException
END
[code] }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
end;//TkwRAISE
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, SysUtils
//#UC START# *4DBAE64F02F7impl_uses*
//#UC END# *4DBAE64F02F7impl_uses*
;
class function TkwRAISE.GetWordNameForRegister: AnsiString;
begin
Result := 'RAISE';
end;//TkwRAISE.GetWordNameForRegister
procedure TkwRAISE.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_4DBAE64F02F7_var*
type
RException = class of Exception;
//#UC END# *4DAEEDE10285_4DBAE64F02F7_var*
begin
//#UC START# *4DAEEDE10285_4DBAE64F02F7_impl*
if (aCtx.rException <> nil) then
raise RException(aCtx.rException.ClassType).Create(aCtx.rException.Message)
else
raise EtfwScriptException.Create(aCtx.rEngine.PopDelphiString);
//#UC END# *4DAEEDE10285_4DBAE64F02F7_impl*
end;//TkwRAISE.DoDoIt
initialization
TkwRAISE.RegisterInEngine;
{* Регистрация RAISE }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit ChangePassword;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DialMessages, Utils, Placemnt, DataErrors;
type
TChangePasswordForm = class(TForm)
PasswordPropsGroupBox: TGroupBox;
CurrentPasswordLabel: TLabel;
NewPasswordLabel: TLabel;
NewPassword2Label: TLabel;
CurrentPasswordEdit: TEdit;
NewPasswordEdit: TEdit;
NewPassword2Edit: TEdit;
OKButton: TButton;
CancelButton: TButton;
FormPlacement: TFormPlacement;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ChangePasswordForm: TChangePasswordForm;
implementation
{$R *.dfm}
resourcestring
rsCurrentPasswordEmpty = 'Current password is empty!';
rsNewPasswordEmpty = 'New password is empty!';
rsPasswordsNotMatch = 'Passwords are not the same!';
procedure TChangePasswordForm.FormClose(Sender: TObject;
var Action: TCloseAction);
var
ErrorStr: string;
begin
if ModalResult = mrOk then
begin
ErrorStr := EmptyStr;
CheckError(CurrentPasswordEdit.Text = EmptyStr, ErrorStr, rsCurrentPasswordEmpty);
CheckError(NewPasswordEdit.Text = EmptyStr, ErrorStr, rsNewPasswordEmpty);
CheckError(NewPasswordEdit.Text <> NewPassword2Edit.Text, ErrorStr, rsPasswordsNotMatch);
TryCloseModal(ErrorStr, Action);
end;
end;
end.
|
///<summary>
/// Fixes the SelectDirectory function of Delphi 2007 (not sure whether it needs fixing
/// in later versions) </summary>
unit GX_dzSelectDirectoryFix;
interface
{$WARN UNIT_PLATFORM OFF}
uses
Windows,
SysUtils,
FileCtrl,
Controls;
///<summary>
/// Bugixed version of the FilCtrl SelectDirectory function with identical parameters
/// The following bugs have been fixed:
/// 1. Positioning the dialog works for all tested monitor combinations. This means
/// not only that the correct monitor is being selected (which is already fixed
/// Delphi 10.1 (and possibly earlier) but also that it is correctly centered
/// on that monitor.
/// 2. The given directory is not only selected but the tree view is also scrolled
/// to make the entry visible.
/// In addition to that, if passing a Parent parameter <> nil, the dialog will be
/// centered on that parent (or the form the parent belongs to), taking the monitor
/// work area into account. </summary>
function dzSelectDirectory(const Caption: string; const Root: WideString;
var Directory: string; Parent: TWinControl = nil): Boolean;
implementation
uses
Consts,
ShlObj,
ActiveX,
Dialogs,
Forms,
Messages,
Classes,
GX_dzVclUtils;
type
TSelectDirCallback = class(TObject)
private
FWndProcInstanceStub: Pointer;
FWndProcPrevious: TFNWndProc;
FWnd: HWND;
FParent: TWinControl;
FDirectory: string;
FInitialized: Boolean;
FPositioned: Boolean;
procedure WndProcSubClassed(var _Msg: TMessage);
procedure SetDialogPosition;
procedure SubClass(_Wnd: HWND);
procedure UnsubClass;
protected
function SelectDirCB(_Wnd: HWND; _uMsg: UINT; _lParam, _lpData: lParam): Integer;
public
constructor Create(const _Directory: string; _Parent: TWinControl);
end;
{ TSelectDirCallback }
constructor TSelectDirCallback.Create(const _Directory: string; _Parent: TWinControl);
begin
inherited Create;
FParent := _Parent;
FDirectory := _Directory;
end;
{$IFNDEF GX_VER160_up}
type
NativeInt = integer;
resourcestring
SInvalidPath = '"%s" is an invalid path';
const
BIF_NONEWFOLDERBUTTON = $200;
{$ENDIF GX_VER160_up}
{$IFNDEF GX_VER150_up}
BIF_NEWDIALOGSTYLE = $0040;
{$ENDIF not GX_VER150_up}
// subclass the given window by replacing its WindowProc
procedure TSelectDirCallback.SubClass(_Wnd: HWND);
begin
if FWndProcPrevious <> nil then
Exit;
FWnd := _Wnd;
FWndProcPrevious := TFNWndProc(GetWindowLong(_Wnd, GWL_WNDPROC));
FWndProcInstanceStub := MakeObjectInstance(WndProcSubClassed);
SetWindowlong(_Wnd, GWL_WNDPROC, NativeInt(FWndProcInstanceStub));
end;
// un-subclass the window by restoring the previous WindowProc
procedure TSelectDirCallback.UnsubClass;
begin
if FWndProcPrevious <> nil then begin
SetWindowlong(FWnd, GWL_WNDPROC, NativeInt(FWndProcPrevious));
FreeObjectInstance(FWndProcInstanceStub);
FWndProcPrevious := nil;
FWndProcInstanceStub := nil;
end;
end;
// The WindowsProc method set by sublcassing the window.
// Waits for the first WM_SIZE message, sets the dialog position
// and un-subclasses the window.
procedure TSelectDirCallback.WndProcSubClassed(var _Msg: TMessage);
begin
if (_Msg.Msg = WM_SIZE) then begin
SetDialogPosition;
_Msg.Result := CallWindowProc(FWndProcPrevious, FWnd, _Msg.Msg, _Msg.WParam, _Msg.lParam);
UnsubClass;
end;
_Msg.Result := CallWindowProc(FWndProcPrevious, FWnd, _Msg.Msg, _Msg.WParam, _Msg.lParam);
end;
procedure TSelectDirCallback.SetDialogPosition;
var
Rect: TRect;
Monitor: TMonitor;
ltwh: TRectLTWH;
RefLtwh: TRectLTWH;
frm: TCustomForm;
begin
GetWindowRect(FWnd, Rect);
if Assigned(FParent) then begin
// this is new: Center on the parent form if a parent was given
frm := GetParentForm(FParent);
Monitor := Screen.MonitorFromWindow(frm.Handle);
TRectLTWH_Assign(RefLtwh, frm.BoundsRect);
end else begin
if Assigned(Application.MainForm) then
Monitor := Screen.MonitorFromWindow(Application.MainForm.Handle)
else
Monitor := Screen.MonitorFromWindow(0);
TRectLTWH_Assign(RefLtwh, Monitor.BoundsRect);
end;
TRectLTWH_Assign(ltwh, Rect);
ltwh.Left := RefLtwh.Left + RefLtwh.Width div 2 - ltwh.Width div 2;
ltwh.Top := RefLtwh.Top + RefLtwh.Height div 2 - ltwh.Height div 2;
TMonitor_MakeFullyVisible(Monitor, ltwh);
SetWindowPos(FWnd, 0, ltwh.Left, ltwh.Top, 0, 0, SWP_NOZORDER or SWP_NOSIZE);
end;
function TSelectDirCallback.SelectDirCB(_Wnd: HWND; _uMsg: UINT; _lParam, _lpData: lParam): Integer;
procedure SelectDirectory;
begin
if FDirectory <> '' then begin
// we use PostMessage to asynchronously select the directory
PostMessage(_Wnd, BFFM_SETSELECTION, Windows.WParam(True), Windows.lParam(PChar(FDirectory)));
end;
end;
begin
Result := 0;
if _uMsg = BFFM_INITIALIZED then begin
// Subclass the window to catch the WM_SIZE message when it is automatically being resized
// later in the initialization process. Only then it is possible to get the final size
// and position it correctly.
SubClass(_Wnd);
FInitialized := True;
// Selecting the directory here only selects the entry but does not necessarily make
// it visible. So we set it here and again further below.
SelectDirectory;
end else if (_uMsg = BFFM_VALIDATEFAILEDW) or (_uMsg = BFFM_VALIDATEFAILEDA) then begin
// default code copied from FileCtrl
MessageDlg(Format(SInvalidPath, [PChar(_lParam)]), mtError, [mbOK], 0);
Result := 1;
end else if _uMsg = BFFM_SELCHANGED then begin
if FInitialized and not FPositioned then begin
FPositioned := True;
// The first call to SelectDirectory only selects it but does not scroll the tree view
// to make it visible. That's what this second call is for.
SelectDirectory;
end;
end;
end;
// This is the actual callback function passed to the Windows API. lpData is the TSelectDirCallback
// object we created. Here we simply call its SelectDirCB method.
function SelectDirCB(Wnd: HWND; uMsg: UINT; lParam, lpData: lParam): Integer stdcall;
begin
Result := TSelectDirCallback(lpData).SelectDirCB(Wnd, uMsg, lParam, lpData);
end;
// This is copied from FileCtrl, mostly unchanged. I removed the WITH statement though.
function dzSelectDirectory(const Caption: string; const Root: WideString;
var Directory: string; Parent: TWinControl = nil): Boolean;
var
BrowseInfo: TBrowseInfo;
OldErrorMode: Cardinal;
ShellMalloc: IMalloc;
IDesktopFolder: IShellFolder;
Eaten, Flags: LongWord;
CoInitResult: HRESULT;
SelectDirCallback: TSelectDirCallback;
WindowList: Pointer;
Buffer: PChar;
RootItemIDList, ItemIDList: PItemIDList;
begin
Result := False;
if not SysUtils.DirectoryExists(Directory) then
Directory := '';
FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then begin
Buffer := ShellMalloc.Alloc(MAX_PATH * SizeOf(Char));
try
RootItemIDList := nil;
if Root <> '' then begin
SHGetDesktopFolder(IDesktopFolder);
IDesktopFolder.ParseDisplayName(Application.Handle, nil,
POleStr(Root), Eaten, RootItemIDList, Flags);
end;
// fill BrowseInfo
if (Parent = nil) or not Parent.HandleAllocated then
BrowseInfo.hwndOwner := Application.Handle
else
BrowseInfo.hwndOwner := Parent.Handle;
BrowseInfo.pidlRoot := RootItemIDList;
BrowseInfo.pszDisplayName := Buffer;
BrowseInfo.lpszTitle := PChar(Caption);
BrowseInfo.lpfn := SelectDirCB;
BrowseInfo.ulFlags := BIF_RETURNONLYFSDIRS or BIF_NEWDIALOGSTYLE or BIF_NONEWFOLDERBUTTON or BIF_EDITBOX;
SelectDirCallback := TSelectDirCallback.Create(Directory, Parent);
try
BrowseInfo.lParam := lParam(SelectDirCallback);
// Not sure if this is necessary. Delphi 2007 does it, Delphi 10.1 doesn't
CoInitResult := CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
if CoInitResult = RPC_E_CHANGED_MODE then
BrowseInfo.ulFlags := BrowseInfo.ulFlags and not BIF_NEWDIALOGSTYLE;
try
WindowList := DisableTaskWindows(0);
OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
ItemIDList := ShBrowseForFolder(BrowseInfo);
finally
SetErrorMode(OldErrorMode);
EnableTaskWindows(WindowList);
end;
finally
CoUninitialize;
end;
finally
SelectDirCallback.Free;
end;
Result := ItemIDList <> nil;
if Result then begin
ShGetPathFromIDList(ItemIDList, Buffer);
ShellMalloc.Free(ItemIDList);
Directory := Buffer;
end;
finally
ShellMalloc.Free(Buffer);
end;
end;
end;
end.
|
{ Subroutine SST_R_SYN_COMMAND (STAT)
*
* Process COMMAND syntax. This is the top level SYN file syntax.
}
module sst_r_syn_command;
define sst_r_syn_command;
%include 'sst_r_syn.ins.pas';
procedure sst_r_syn_command ( {process COMMAND syntax}
out stat: sys_err_t); {completion status code}
label
trerr;
begin
sys_error_none (stat); {init to no errors}
if not syn_trav_next_down (syn_p^) {down into COMMAND syntax level}
then goto trerr;
case syn_trav_next_tag(syn_p^) of {which tag ?}
{
* End of input data.
}
1: begin
sys_stat_set (sst_subsys_k, sst_stat_eod_k, stat); {indicate EOD}
end;
{
* Syntax definition.
}
2: begin
sst_r_syn_define; {process DEFINE syntax}
end;
{
* Symbol declaration.
}
3: begin
sst_r_syn_declare; {process DECLARE syntax}
end;
otherwise
syn_msg_tag_bomb (syn_p^, 'sst_syn_read', 'syerr_command', nil, 0);
end; {end of top level tag cases}
if not syn_trav_up (syn_p^) {back up from COMMAND syntax level}
then goto trerr;
return;
{
* The syntax tree is not as expected. We assume this is due to a syntax
* error.
}
trerr:
sys_message ('sst_syn_read', 'syerr_command');
syn_parse_err_show (syn_p^);
sys_bomb;
end;
|
(* MPP_SS: HDO, 2004-02-06
------
Syntax analyzer and semantic evaluator for the MiniPascal parser.
Semantic actions to be included in MPI_SS and MPC_SS.
===================================================================*)
UNIT MPC_SS;
INTERFACE
VAR
success: BOOLEAN; (*true if no syntax errros*)
PROCEDURE S; (*parses whole MiniPascal program*)
IMPLEMENTATION
USES
MP_Lex, SymTab, CodeDef, CodeGen, BinTree;
FUNCTION SyIsNot(expectedSy: Symbol): BOOLEAN;
BEGIN
success:= success AND (sy = expectedSy);
SyIsNot := NOT success;
END; (*SyIsNot*)
PROCEDURE SemErr(msg: STRING);
BEGIN
WriteLn('*** Semantic error ***');
WriteLn(' ', msg);
success := FALSE;
end;
PROCEDURE MP(var binaryTree: TreePtr); FORWARD;
PROCEDURE VarDecl; FORWARD;
PROCEDURE StatSeq(var binaryTree: TreePtr); FORWARD;
PROCEDURE Stat(var binaryTree: TreePtr); FORWARD;
PROCEDURE Expr(var binaryTree: TreePtr); FORWARD;
PROCEDURE Term(var binaryTree: TreePtr); FORWARD;
PROCEDURE Fact(var binaryTree: TreePtr); FORWARD;
PROCEDURE EmitCodeForExprTree(t: TreePtr); FORWARD;
PROCEDURE Simplify(var t: TreePtr); FORWARD;
PROCEDURE ConstantFolding(var t: TreePtr); FORWARD;
PROCEDURE S;
(*-----------------------------------------------------------------*)
VAR
binaryTree: TreePtr;
BEGIN
binaryTree := newTree('');
WriteLn('parsing started ...');
success := TRUE;
MP(binaryTree);
IF NOT success OR SyIsNot(eofSy) THEN
WriteLn('*** Error in line ', syLnr:0, ', column ', syCnr:0)
ELSE
WriteLn('... parsing ended successfully ');
Simplify(binaryTree);
ConstantFolding(binaryTree);
writeTreeInOrder(binaryTree);
END; (*S*)
PROCEDURE MP(var binaryTree: TreePtr);
BEGIN
IF SyIsNot(programSy) THEN Exit;
(* sem *)
initSymbolTable;
InitCodeGenerator;
(* endsem *)
NewSy;
IF SyIsNot(identSy) THEN Exit;
NewSy;
IF SyIsNot(semicolonSy) THEN Exit;
NewSy;
IF sy = varSy THEN BEGIN
VarDecl; IF NOT success THEN Exit;
END; (*IF*)
IF SyIsNot(beginSy) THEN Exit;
NewSy;
StatSeq(binaryTree); IF NOT success THEN Exit;
(* sem *)
EmitCodeForExprTree(binaryTree);
Emit1(EndOpc);
(* endsem *)
IF SyIsNot(endSy) THEN Exit;
NewSy;
IF SyIsNot(periodSy) THEN Exit;
NewSy;
END; (*MP*)
PROCEDURE VarDecl;
var ok : BOOLEAN;
BEGIN
IF SyIsNot(varSy) THEN Exit;
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* sem *)
DeclVar(identStr, ok);
NewSy;
WHILE sy = commaSy DO BEGIN
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* sem *)
DeclVar(identStr, ok);
IF NOT ok THEN
SemErr('mult. decl.');
(* endsem *)
NewSy;
END; (*WHILE*)
IF SyIsNot(colonSy) THEN Exit;
NewSy;
IF SyIsNot(integerSy) THEN Exit;
NewSy;
IF SyIsNot(semicolonSy) THEN Exit;
NewSy;
END; (*VarDecl*)
PROCEDURE StatSeq(var binaryTree: TreePtr);
BEGIN
Stat(binaryTree); IF NOT success THEN Exit;
WHILE sy = semicolonSy DO BEGIN
NewSy;
Stat(binaryTree); IF NOT success THEN Exit;
END; (*WHILE*)
END; (*StatSeq*)
PROCEDURE Stat(var binaryTree: TreePtr);
var destId : STRING;
addr, addr1, addr2 : integer;
BEGIN
CASE sy OF
identSy: BEGIN
(* sem *)
destId := identStr;
IF NOT IsDecl(destId) THEN
SemErr('var. not decl.')
ELSE
Emit2(LoadAddrOpc, AddrOf(destId));
(* endsem *)
NewSy;
IF SyIsNot(assignSy) THEN Exit;
NewSy;
Expr(binaryTree); IF NOT success THEN Exit;
(* sem *)
IF IsDecl(destId) THEN
Emit1(StoreOpc);
(* endsem *)
END;
readSy: BEGIN
NewSy;
IF SyIsNot(leftParSy) THEN Exit;
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* sem *)
IF NOT IsDecl(identStr) THEN
SemErr('var not decl.')
ELSE BEGIN
Emit2(ReadOpc,AddrOf(identStr));
END;
(* endsem *)
NewSy;
IF SyIsNot(rightParSy) THEN Exit;
NewSy;
END;
writeSy: BEGIN
NewSy;
IF SyIsNot(leftParSy) THEN Exit;
NewSy;
Expr(binaryTree); IF NOT success THEN Exit;
(* sem *)
Emit1(WriteOpc);
(* endsem *)
IF SyIsNot(rightParSy) THEN Exit;
NewSy;
END;
beginSy: BEGIN
newSy;
StatSeq(binaryTree);
IF SyIsNot(endSy) THEN Exit;
NewSy;
END;
ifSy: BEGIN
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* SEM *)
IF NOT IsDecl(identStr) THEN BEGIN
SemErr('var not decl.');
END;
Emit2(LoadValOpc, AddrOf(identStr));
Emit2(JmpZOpc, 0); (*0 as dummy address*)
addr := CurAddr - 2;
(* ENDSEM *)
NewSy;
IF SyIsNot(thenSy) THEN Exit;
newSy;
Stat(binaryTree); IF NOT success THEN Exit;
IF sy = elseSy THEN BEGIN
newSy;
(* SEM *)
Emit2(JmpOpc, 0);
FixUp(addr, CurAddr);
addr := CurAddr - 2;
(* ENDSEM *)
Stat(binaryTree); IF NOT success THEN Exit;
END;
(* SEM *)
FixUp(addr, CurAddr);
(* ENDSEM *)
END;
whileSy: BEGIN
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* SEM *)
IF NOT IsDecl(identStr) THEN BEGIN
SemErr('var not decl.');
END;
addr1 := CurAddr;
Emit2(LoadValOpc, AddrOf(identStr));
Emit2(JmpZOpc, 0); (*0 as dummy address*)
addr2 := CurAddr - 2;
(* ENDSEM *)
NewSy;
IF SyIsNot(doSy) THEN Exit;
NewSy;
Stat(binaryTree);
(* SEM *)
Emit2(JmpOpc, addr1);
FixUp(addr2, CurAddr);
(* ENDSEM *)
END;
ELSE
; (*EPS*)
END; (*CASE*)
END; (*Stat*)
PROCEDURE Expr(var binaryTree: TreePtr);
var t: TreePtr;
BEGIN
Term(binaryTree); IF NOT success THEN Exit;
WHILE (sy = plusSy) OR (sy = minusSy) DO BEGIN
CASE sy OF
plusSy: BEGIN
NewSy;
Term(binaryTree^.right); IF NOT success THEN Exit;
(* sem *)
t := newTree('+');
t^.left := binaryTree;
t^.right := newTree('');
binaryTree := t;
(* endsem *)
END;
minusSy: BEGIN
NewSy;
Term(binaryTree^.right); IF NOT success THEN Exit;
(* sem *)
t := newTree('-');
t^.left := binaryTree;
t^.right := newTree('');
binaryTree := t;
(* endsem *)
END;
END; (*CASE*)
END; (*WHILE*)
END; (*Expr*)
PROCEDURE Term(var binaryTree: TreePtr);
var t: TreePtr;
BEGIN
Fact(binaryTree); IF NOT success THEN Exit;
WHILE (sy = timesSy) OR (sy = divSy) DO BEGIN
CASE sy OF
timesSy: BEGIN
NewSy;
Fact(binaryTree^.right); IF NOT success THEN Exit;
(* sem *)
t := newTree('*');
t^.left := binaryTree;
t^.right := newTree('');
binaryTree := t;
(* endsem *)
END;
divSy: BEGIN
NewSy;
Fact(binaryTree^.right); IF NOT success THEN Exit;
(* sem *)
t := newTree('/');
t^.left := binaryTree;
t^.right := newTree('');
binaryTree := t;
(* endsem *)
END;
END; (*CASE*)
END; (*WHILE*)
END; (*Term*)
PROCEDURE Fact(var binaryTree: TreePtr);
var t: TreePtr;
BEGIN
CASE sy OF
identSy: BEGIN
(* sem *)
t := newTree(identStr);
t^.left := binaryTree;
t^.right := newTree('');
binaryTree := t;
(* endsem *)
NewSy;
END;
numberSy: BEGIN
(* sem *)
t := newTree(numberVal);
t^.left := binaryTree;
t^.right := newTree('');
binaryTree := t;
(* endsem *)
NewSy;
END;
leftParSy: BEGIN
NewSy;
Expr(binaryTree); IF NOT success THEN Exit;
IF SyIsNot(rightParSy) THEN Exit;
NewSy;
END;
ELSE
success := FALSE;
END; (*CASE*)
END; (*Fact*)
PROCEDURE EmitCodeForExprTree(t: TreePtr);
var tVal : string;
i, code : integer;
opChar: char;
begin
if(t <> NIL) then begin
EmitCodeForExprTree(t^.left);
tVal := t^.val;
val(tVal, i, code);
if(code = 0) then
Emit2(LoadConstOpc,i)
else
if(length(tVal) > 1) then begin
IF NOT IsDecl(identStr) THEN
SemErr('var. not decl.')
ELSE
Emit2(LoadValOpc,AddrOf(identStr));
end else begin
opChar := tVal[1];
CASE opChar OF
'+': BEGIN
Emit1(AddOpc);
END;
'-': BEGIN
Emit1(SubOpc);
END;
'*': BEGIN
Emit1(MulOpc);
END;
'/': BEGIN
Emit1(DivOpc);
END;
ELSE BEGIN
IF NOT IsDecl(identStr) THEN
SemErr('var. not decl.')
ELSE
Emit2(LoadValOpc,AddrOf(identStr));
END;
END;
end;
EmitCodeForExprTree(t^.right);
end;
end;
procedure Simplify(var t: TreePtr);
var tVal : string;
i, code : integer;
opChar: char;
begin
if(t <> NIL) then begin
Simplify(t^.left);
Simplify(t^.right);
tVal := t^.val;
val(tVal, i, code);
if((code <> 0) and (length(tVal) = 1)) then begin
opChar := tVal[1];
CASE opChar OF
'+': BEGIN
if(t^.left^.val = '0') then
t := t^.right
else if(t^.right^.val = '0') then
t := t^.left;
END;
'-': BEGIN
if(t^.left^.val = '0') then
t := t^.right
else if(t^.right^.val = '0') then
t := t^.left;
END;
'*': BEGIN
if(t^.left^.val = '1') then
t := t^.right
else if(t^.right^.val = '1') then
t := t^.left;
END;
'/': BEGIN
if(t^.left^.val = '1') then
t := t^.right
else if(t^.right^.val = '1') then
t := t^.left;
END;
ELSE BEGIN
IF NOT IsDecl(identStr) THEN
SemErr('var. not decl.')
ELSE
Emit2(LoadValOpc,AddrOf(identStr));
END;
END;
end;
end;
end;
procedure ConstantFolding(var t: TreePtr);
var tValLeft,tValRight : string;
valString: string;
iLeft,iRight, codeLeft, codeRight : integer;
opChar: char;
begin
if(t <> NIL) then begin
valString := '';
ConstantFolding(t^.left);
ConstantFolding(t^.right);
if(t^.left <> NIL) and (t^.right <> NIL) then begin
tValLeft := t^.left^.val;
tValRight := t^.right^.val;
val(tValLeft, iLeft, codeLeft);
val(tValRight, iRight, codeRight);
if(codeLeft = 0) and (codeRight = 0) then begin
opChar := t^.val[1];
CASE opChar OF
'+': BEGIN
Str(iLeft + iRight, valString);
END;
'-': BEGIN
Str(iLeft - iRight, valString);
END;
'*': BEGIN
Str(iLeft * iRight, valString);
END;
'/': BEGIN
Str(iLeft DIV iRight, valString);
END;
END;
t^.val := valString;
end;
end;
end;
end;
BEGIN
END. (*MPP_SS*)
|
unit udmEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, udmGlobal, DB, DBAccess, Ora, DBClient, udmDBCore, udmDBRoot, uGlobals,
DBSearch;
type
TdmEditClass = class of TdmEdit;
TdmEdit = class(TdmDBRoot)
OraSession: TOraSession;
private
FhNumManPrv: boolean;
FhCallSender: TDBSearch;
{ Private declarations }
function getMainSession: TOraSession;
protected
procedure dmBeforePost(DataSet: TDataSet); override;
function dmCheckValidateData: boolean; override;
function dmAggNumPrgCustom: String; virtual;
function dmDimNumPrgCustom: boolean; virtual;
procedure dmSetSessionDefault; override;
public
{ Public declarations }
constructor Create(Owner: TComponent); override;
function dmCommit: boolean; override;
procedure dmRollBack; override;
procedure dmDelete;
procedure dmEdit;
procedure dmInsert;
procedure dmView;
procedure dmMasterTableSetKey;
procedure SetDmoLck;
procedure RemoveDmoLck;
property hNumManPrv : boolean read FhNumManPrv write FhNumManPrv;
property hCallSender : TDBSearch read FhCallSender write FhCallSender;
end;
var
dmEdit: TdmEdit;
implementation
{$R *.dfm}
{ TdmEdit }
function TdmEdit.getMainSession: TOraSession;
var
i : integer;
begin
Result := nil;
for i := 0 to Self.ComponentCount - 1 do
if Self.Components[i] is TOraSession then
begin
Result := TOraSession(Self.Components[i]);
Break;
end;
end;
function TdmEdit.dmCheckValidateData: boolean;
var
i : integer;
begin
inherited dmCheckValidateData;
if hDataSet.FieldByName(hKeyFields[hKeyFields.Count - 1]).IsNull then
dmMasterTableSetKey;
Result := True;
for i := 0 to hKeyFields.Count - 1 do
if hDataSet.FieldByName(hKeyFields[i]).isNull then
begin
MessageDlg(stReqDErr, mtInformation, [mbOK], 0);
Result := False;
end;
if Result and hNumManPrv then
begin
Result := not dmGlobal.dmCheckDupValue(hKeyFields, hDataSet);
if not Result then
MessageDlg(stDuplicateRec, mtInformation, [mbOK], 0);
end;
if Result and hNumManPrv then
begin
Result := dmGlobal.dmCheckMaxValue(hKeyFields, hDataSet);
if not Result then
MessageDlg(stMaxCod, mtInformation, [mbOK], 0);
end;
end;
function TdmEdit.dmCommit: boolean;
var
NewCod, KeyStr : String;
i : integer;
begin
inherited dmCommit;
Result := True;
KeyStr := '';
for i := 0 to hKeyFields.Count - 1 do
KeyStr := KeyStr + hKeyFields[i];
if hdmState = hdmDelete then
begin
if (hTipAttNum = hPrgAut) and (not FhNumManPrv) then
dmGlobal.DimNumPrg(KeyStr, hKeyValues[hKeyValues.Count - 1]);
if (hTipAttNum = hPrgAutAaa) and (not FhNumManPrv) then
dmDimNumPrgCustom;
Result := dmDsApplyUpdates(TClientDataSet(hDataSet));
end;
if Result then
begin
if (hdmState in [hdmInsert, hdmEdit]) then
begin
if dmCheckValidateData then
begin
if dmPostAll then
begin
if hdmState = hdmInsert then
begin
if (hTipAttNum = hPrgAut) and (not FhNumManPrv) then
begin
NewCod := dmGlobal.AggNumPrg(KeyStr);
dmDsEdit(hDataSet);
hDataSet.FieldByName(hKeyFields[hKeyFields.Count - 1]).AsString := NewCod;
dmPostAll;
end;
if (hTipAttNum = hPrgAutAaa) and (not FhNumManPrv) then
begin
NewCod := dmAggNumPrgCustom;
dmDsEdit(hDataSet);
hDataSet.FieldByName(hKeyFields[hKeyFields.Count - 1]).AsString := NewCod;
dmPostAll;
end;
end;
getMainSession.Commit;
if hdmState = hdmInsert then
begin
if (hTipAttNum in [hPrgAut, hPrgAutAaa]) and (not FhNumManPrv) then
MessageDlg('E'' stato inserito il record N° '+NewCod, mtInformation, [mbOK], 0);
if Assigned(FhCallSender) then
FhCallSender.Text := hDataSet.FieldByName(hKeyFields[hKeyFields.Count - 1]).AsString;
end;
if (hdmState in [hdmEdit, hdmDelete]) then
RemoveDmoLck;
end
else
Result := False;
end
else
Result := False;
end;
end;
if not Result then
begin
if (hdmState in [hdmEdit, hdmDelete]) then
RemoveDmoLck;
end;
end;
procedure TdmEdit.dmDelete;
begin
FhNumManPrv := False;
SetDmoLck;
hdmState := hdmDelete;
SetDataSetState;
SetMasterParams;
dmOpenAll;
dmDsDelete(hDataSet);
RemoveDmoLck;
end;
procedure TdmEdit.dmEdit;
begin
FhNumManPrv := False;
SetDmoLck;
hdmState := hdmEdit;
SetDataSetState;
SetMasterParams;
dmOpenAll;
dmDsEdit(hDataSet);
end;
procedure TdmEdit.dmInsert;
begin
FhNumManPrv := False;
dmOpenAll;
hdmState := hdmInsert;
SetDataSetState;
if Assigned(hDataSet) then
begin
if (hTipAttNum in [hPrgAut, hPrgAutAaa]) and (not FhNumManPrv) then
hKeyValues.Append(IntToStr(dmGlobal.GetNpaDet));
dmDsInsert(hDataSet);
if (hTipAttNum in [hPrgAut, hPrgAutAaa]) and (not FhNumManPrv) then
hDataSet.FieldByName(hKeyFields[hKeyFields.Count-1]).AsString := hKeyValues[hKeyValues.Count-1];
end;
end;
procedure TdmEdit.dmView;
begin
FhNumManPrv := False;
dmCloseAll;
hdmState := hdmView;
SetDataSetState;
SetMasterParams;
dmOpenAll;
end;
procedure TdmEdit.dmMasterTableSetKey;
begin
//do nothing
end;
procedure TdmEdit.dmRollBack;
begin
getMainSession.Rollback;
if (hdmState in [hdmEdit, hdmDelete]) then
RemoveDmoLck;
end;
procedure TdmEdit.RemoveDmoLck;
begin
dmGlobal.dmInsertDmoLck(Self.hKeyFields, GetCodValKey, '1');
end;
procedure TdmEdit.SetDmoLck;
begin
dmGlobal.dmInsertDmoLck(Self.hKeyFields, GetCodValKey, '0');
end;
procedure TdmEdit.dmBeforePost(DataSet: TDataSet);
begin
inherited;
if hApl <> 'USER' then
if Assigned(DataSet.FindField('Cod_Usr')) then
DataSet.FieldByName('Cod_Usr').AsString := hUsr;
end;
procedure TdmEdit.dmSetSessionDefault;
begin
inherited;
getMainSession.AutoCommit := False;
getMainSession.ConnectPrompt := False;
getMainSession.UserName := hDbsUsr;
getMainSession.PassWord := hDbsPwd;
getMainSession.Schema := getMainSession.UserName;
getMainSession.Server := hDbsNom;
getMainSession.ConnectString := getMainSession.UserName+'/'+getMainSession.PassWord+'@'+getMainSession.Server;
end;
function TdmEdit.dmAggNumPrgCustom: String;
begin
//do nothing;
end;
function TdmEdit.dmDimNumPrgCustom: boolean;
begin
Result := True;
//do nothing;
end;
constructor TdmEdit.Create(Owner: TComponent);
begin
inherited;
FhCallSender := nil;
end;
end.
|
unit LogTreeView;
{
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.
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Comctrls, Controls, MultiLog, LResources, Graphics;
type
{ TLogTreeView }
{$REGION 'Xls: Comments section'}
{ TLogTreeView is a way to display the TIntegratedLogger'messages, with images.}
{$ENDREGION}
TLogTreeView = class (TCustomTreeView)
private
FoImgList: TImageList;
FoChannel: TLogChannel;
Fo_LastNode: TTreeNode;
Fo_ParentNode: TTreeNode;
FbShowTime: Boolean;
FbShowPrefixMethod: Boolean;
FbShowDynamicFilter_forWhatReasonsToLogActually: Boolean;
FsTimeFormat: String;
function GetChannel: TLogChannel;
public
constructor Create(AnOwner: TComponent); override;
destructor Destroy; override;
procedure AddMessage(AMsg: TrecLogMessage);
procedure Clear;
property Channel: TLogChannel read GetChannel;
published
property Align;
property Anchors;
property AutoExpand;
property BorderSpacing;
//property BiDiMode;
property BackgroundColor;
property BorderStyle;
property BorderWidth;
property Color;
property Constraints;
property DefaultItemHeight;
property DragKind;
property DragCursor;
property DragMode;
property Enabled;
property ExpandSignType;
property Font;
property HideSelection;
property HotTrack;
//property Images;
property Indent;
//property ParentBiDiMode;
property ParentColor default False;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property RightClickSelect;
property RowSelect;
property ScrollBars;
property SelectionColor;
property ShowButtons;
property ShowHint;
property ShowLines;
property ShowRoot;
property SortType;
property StateImages;
property TabOrder;
property TabStop default True;
property Tag;
property ToolTips;
property Visible;
property OnAdvancedCustomDraw;
property OnAdvancedCustomDrawItem;
property OnChange;
property OnChanging;
property OnClick;
property OnCollapsed;
property OnCollapsing;
property OnCompare;
property OnContextPopup;
property OnCustomCreateItem;
property OnCustomDraw;
property OnCustomDrawItem;
property OnDblClick;
property OnDeletion;
property OnDragDrop;
property OnDragOver;
property OnEdited;
property OnEditing;
//property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnExpanded;
property OnExpanding;
property OnGetImageIndex;
property OnGetSelectedIndex;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnSelectionChanged;
property Options;
//property OnStartDock;
property OnStartDrag;
//property Items;
property TreeLineColor;
property ExpandSignColor;
property TimeFormat: String read FsTimeFormat write FsTimeFormat;
property ShowTime: Boolean read FbShowTime write FbShowTime;
property ShowPrefixMethod: Boolean read FbShowPrefixMethod write FbShowPrefixMethod;
property ShowDynamicFilter_forWhatReasonsToLogActually: Boolean read FbShowDynamicFilter_forWhatReasonsToLogActually write FbShowDynamicFilter_forWhatReasonsToLogActually;
end;
{ TLogTreeViewChannel }
TLogTreeViewChannel = class (TLogChannel)
private
Fo_Control: TLogTreeView;
public
constructor Create(AControl: TLogTreeView);
procedure Clear; override;
procedure Deliver(const AMsg: TrecLogMessage);override;
end;
implementation
{ TLogTreeViewChannel }
constructor TLogTreeViewChannel.Create(AControl: TLogTreeView);
begin
Fo_Control:= AControl;
Active:= True;
FbShowPrefixMethod:= false;
FbShowTime:= false;
FbShow_DynamicFilter_forWhatReasonsToLogActually:= false;
end;
procedure TLogTreeViewChannel.Clear;
begin
Fo_Control.Clear;
end;
procedure TLogTreeViewChannel.Deliver(const AMsg: TrecLogMessage);
begin
Fo_Control.AddMessage(AMsg);
end;
{ TLogTreeView }
function TLogTreeView.GetChannel: TLogChannel;
begin
if FoChannel = nil then
FoChannel:= TLogTreeViewChannel.Create(Self);
Result:= FoChannel;
end;
constructor TLogTreeView.Create(AnOwner: TComponent);
begin
inherited Create(AnOwner);
FsTimeFormat := 'hh:nn:ss:zzz';
FoImgList:= TImageList.Create(nil);
with FoImgList do begin
AddLazarusResource('info', clDefault);
AddLazarusResource('error', clDefault);
AddLazarusResource('warning', clDefault);
AddLazarusResource('value', clDefault);
AddLazarusResource('entermethod', clDefault);
AddLazarusResource('exitmethod', clDefault);
AddLazarusResource('whatisthis', clDefault); //conditional
AddLazarusResource('check', clDefault);
AddLazarusResource('strings', clDefault);
AddLazarusResource('callstack', clDefault);
AddLazarusResource('object', clDefault);
AddLazarusResource('error', clDefault);
AddLazarusResource('image', clDefault);
AddLazarusResource('whatisthis', clDefault); //heap
AddLazarusResource('whatisthis', clDefault); //memory
AddLazarusResource('whatisthis', clDefault); //custom data
end;
Images:= FoImgList;
end;
destructor TLogTreeView.Destroy;
begin
FoImgList.Destroy; FoImgList:= nil;
FreeAndNil(FoChannel);
inherited Destroy;
end;
procedure TLogTreeView.AddMessage(AMsg: TrecLogMessage);
procedure ParseStream(AStream:TStream);
var
i: Integer;
oStrList: TStringList;
begin
//todo: Parse the String in Stream directly instead of using StringList ??
oStrList:= TStringList.Create;
AStream.Position:=0;
oStrList.LoadFromStream(AStream);
for i:= 0 to oStrList.Count - 1 do
Items.AddChild(Fo_LastNode,oStrList[i]);
Fo_LastNode.Text:= Fo_LastNode.Text+' ('+IntToStr(oStrList.Count)+' Items)';
oStrList.Destroy;
end;
var
oTempStream: TStream;
sWholeMsg: String;
begin
sWholeMsg:= '';
if FbShowTime then
sWholeMsg:= FormatDateTime(FsTimeFormat, Time) + ' ';
if FbShowPrefixMethod then
sWholeMsg:= sWholeMsg + (ctsLogPrefixesMethod[AMsg.iMethUsed] + ': ');
//write second qualifier explaining for which tracking purposes Msg are Logged
if FbShowDynamicFilter_forWhatReasonsToLogActually then
sWholeMsg:= sWholeMsg + TLogChannelUtils.SetofToString(AMsg.setFilterDynamic);
sWholeMsg:= sWholeMsg + AMsg.sMsgText;
with Items, AMsg do begin
case AMsg.iMethUsed of
methEnterMethod:
begin
Fo_LastNode:= AddChild(Fo_ParentNode,sWholeMsg);
Fo_ParentNode:= Fo_LastNode;
end;
methExitMethod:
begin
if Fo_ParentNode <> nil then
Fo_LastNode:= AddChild(Fo_ParentNode.Parent,sWholeMsg)
else
Fo_LastNode:= AddChild(nil,sWholeMsg);
Fo_ParentNode:= Fo_LastNode.Parent;
end;
methTStrings, methCallStack, methHeapInfo, methException, methMemory:
begin
Fo_LastNode:= AddChild(Fo_ParentNode,sWholeMsg);
if Assigned(pData) and (pData.Size>0) then
ParseStream(pData)
else
Fo_LastNode.Text:= Fo_LastNode.Text+' (No Items)';
end;
methObject:
begin
Fo_LastNode:= AddChild(Fo_ParentNode,sWholeMsg);
if Assigned(pData) and (pData.Size>0) then begin
pData.Position:= 0;
oTempStream:= TStringStream.Create('');
ObjectBinaryToText(pData,oTempStream);
ParseStream(oTempStream);
oTempStream.Destroy;
end;
end;
else
begin
Fo_LastNode:= AddChild(Fo_ParentNode,sWholeMsg);
end;
end;
end;
//todo: hook TCustomTreeView to auto expand
if Fo_LastNode.Parent <> nil then
Fo_LastNode.Parent.Expanded:= True;
Fo_LastNode.GetFirstChild;
//todo: optimize painting
Fo_LastNode.ImageIndex:= AMsg.iMethUsed;
Fo_LastNode.SelectedIndex:= AMsg.iMethUsed;
end;
procedure TLogTreeView.Clear;
begin
Items.Clear;
Fo_LastNode:=nil;
Fo_ParentNode:=nil;
end;
initialization
{$i logimages.lrs}
end.
procedure TLogTreeView.Clear;
begin
Items.Clear;
FLastNode:=nil;
FParentNode:=nil;
end;
initialization
{$i logimages.lrs}
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Grids, IniFiles;
type
TForm1 = class(TForm)
img1: TImage;
btn1: TButton;
lbl1: TLabel;
lbl2: TLabel;
btn3: TButton;
strngrd1: TStringGrid;
edt1: TEdit;
lbl3: TLabel;
btn2: TButton;
lbl4: TLabel;
procedure btn1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btn2Click(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btn3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
snake=record
x_s, y_s: Byte;
end;
winners=record
name: string[10];
score: Byte;
end;
var
Form1: TForm1;
ingame: Boolean;
fld: array[1..20, 1..20] of Boolean;
snk: array[1..30] of snake;
pl: array[1..5] of winners;
Len, nap, balls: Byte;
x_f, y_f: Byte;
slp: Word;
rec: TIniFile;
implementation
{$R *.dfm}
procedure setprize;
var a, b: Byte;
label v;
begin
Form1.lbl1.Caption:='ОЧКИ:'+inttostr(balls);
Randomize;
v:
x_f:=Random(19)+1; y_f:=Random(19)+1;
if fld[x_f, y_f]=True then goto v;
for a:=1 to 10 do
for b:=1 to 10 do
Form1.img1.Canvas.Pixels[x_f*10+a, y_f*10+b]:=clBlue;
end;
procedure newgame;
var a, b: Byte;
begin
for a:=1 to 30 do begin snk[a].x_s:=30; snk[a].y_s:=30; end;
Form1.img1.Canvas.Brush.Color:=clBlack; Form1.img1.Canvas.Rectangle(0, 0, Form1.img1.Width, Form1.img1.Height);
Form1.img1.Canvas.Brush.Color:=clWhite; form1.img1.Canvas.Rectangle(10, 10, 211, 211);
len:=1; snk[1].x_s:=Random(10)+5; snk[1].y_s:=Random(10)+5; nap:=Random(3); ingame:=True;
for a:=1 to 10 do
for b:=1 to 10 do begin
fld[a, b]:=False;
Form1.img1.Canvas.Pixels[(snk[1].x_s*10)+a, (snk[1].y_s*10)+b]:=clRed;
end;
for a:=10 to 20 do
for b:=10 to 20 do
fld[a, b]:=False;
setprize;
slp:=1000;
balls:=0;
end;
procedure lose;
begin
ingame:=False;
form1.btn1.Enabled:=True;
showmessage('вы проиграили');
form1.strngrd1.Visible:=True;
form1.img1.Visible:=False;
form1.lbl4.Visible:=True;
if balls>pl[5].score then begin form1.edt1.Clear; form1.lbl3.Visible:=True; Form1.edt1.Visible:=True; Form1.btn1.Enabled:=False; form1.btn2.Visible:=True; end;
end;
procedure mov;
var a, b, x_h, y_h: Byte;
begin
Application.ProcessMessages;
x_h:=snk[Len].x_s;
y_h:=snk[Len].y_s;
for a:=len downto 2 do begin snk[a].x_s:=snk[a-1].x_s; snk[a].y_s:=snk[a-1].y_s; end;
case nap of
0: inc(snk[1].x_s);
1: Inc(snk[1].y_s);
2: Dec(snk[1].x_s);
3: Dec(snk[1].y_s);
end;
if (snk[1].x_s=0) or (snk[1].x_s=21) or (snk[1].y_s=0) or (snk[1].y_s=21) or (fld[snk[1].x_s, snk[1].y_s]=true) then begin lose; Exit; end;
if (snk[1].x_s=x_f) and (snk[1].y_s=y_f) then begin inc(balls); inc(Len); snk[Len].x_s:=x_h; snk[Len].y_s:=y_h; setprize; Dec(slp, 60); if slp<100 then slp:=60; end
else begin
for a:=1 to 10 do
for b:=1 to 10 do
Form1.img1.Canvas.Pixels[x_h*10+a, y_h*10+b]:=clwhite;
fld[x_h, y_h]:=False;
end;
for a:=1 to 10 do
for b:=1 to 10 do
Form1.img1.Canvas.Pixels[(snk[1].x_s*10)+a, (snk[1].y_s*10)+b]:=clRed;
fld[snk[1].x_s, snk[1].y_s]:=True;
Application.ProcessMessages;
Sleep(slp);
end;
procedure TForm1.btn1Click(Sender: TObject);
begin
lbl4.Visible:=False; strngrd1.Visible:=False;
img1.Visible:=True;
btn1.Enabled:=False;
newgame;
while ingame=True do mov;
end;
procedure TForm1.FormCreate(Sender: TObject);
var a: Byte;
begin
Randomize;
with strngrd1 do begin
Cells[0, 0]:='ник';
Cells[1, 0]:='счет';
ColWidths[0]:=90;
ColWidths[1]:=90;
end;
rec:=IniFiles.TIniFile.Create(ExtractFilePath(Application.ExeName)+'hi.ini');
try
for a:=1 to 5 do begin
pl[a].score:=rec.ReadInteger('pl'+inttostr(a),'score', 0);
pl[a].name:=rec.ReadString('pl'+inttostr(a),'name', '');
strngrd1.Cells[0, a]:=pl[a].Name;
strngrd1.Cells[1, a]:=IntToStr(pl[a].score);
end;
finally
rec.Free;
end;
end;
procedure TForm1.btn2Click(Sender: TObject);
var a, b: Byte;
label x;
begin
if Length(edt1.Text)>0 then begin
for a:=1 to 5 do
if balls>pl[a].score then begin
for b:=5 downto a+1 do begin pl[b].score:=pl[b-1].score; pl[b].name:=pl[b-1].name; end;
pl[a].name:=Form1.edt1.text;
pl[a].score:=balls;
goto x;
end;
x:
for a:=1 to 5 do begin
strngrd1.Cells[0, a]:=pl[a].Name;
strngrd1.Cells[1, a]:=IntToStr(pl[a].score);
end;
edt1.Visible:=False;
lbl3.Visible:=false;
btn2.Visible:=False;
btn1.Enabled:=True;
end;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key= ord(vk_up) then nap:=3;
if Key= ord(vk_down) then nap:=1;
if Key= ord(vk_left) then nap:=2;
if Key= ord(vk_right)then nap:=0;
end;
procedure TForm1.btn3Click(Sender: TObject);
var a: Byte;
begin
ingame:=False;
rec:=IniFiles.TIniFile.Create(ExtractFilePath(Application.ExeName)+'hi.ini');
try
for a:=1 to 5 do begin
rec.WriteString('pl'+inttostr(a), 'name', pl[a].name);
rec.WriteInteger('pl'+inttostr(a), 'score', pl[a].score);
end;
finally
rec.Free;
end;
Form1.Close;
end;
end.
|
unit CustomerInfoFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Dm, StdCtrls, PrjConst, A4onTypeUnit;
type
TCustomerInfoFrm = class(TFrame)
gbInfo: TGroupBox;
lblFIO: TLabel;
lblDebt: TLabel;
memAbonent: TMemo;
private
{ Private declarations }
ci : TCustomerInfo;
procedure SetCI(Value : TCustomerInfo);
public
{ Public declarations }
property Customer : TCustomerInfo read ci write SetCI;
end;
implementation
{$R *.dfm}
procedure TCustomerInfoFrm.SetCI(Value : TCustomerInfo);
var
clr : TColor;
s : string;
begin
ci := Value;
memAbonent.Lines.Clear;
lblFIO.Caption := '';
lblDEBT.Caption := '';
if Value.CUSTOMER_ID = -1
then begin
lblFIO.Caption := rsNOT_FOUND_CUST;
exit;
end;
lblFIO.Caption := Value.Account_no + ' ' +Value.FIO;
if (dmMain.AllowedAction(rght_Customer_Debt)) or (dmMain.AllowedAction(rght_Customer_full)) // просмотр сумм
then begin
if (dmMain.GetSettingsValue('SHOW_AS_BALANCE') = '1')
then s := rsBALANCE+' '+floatToStr(Value.Debt_sum)
else s := rsSALDO+' '+floatToStr(Value.Debt_sum);
lblDebt.Caption := s;
end;
s := '' + Value.Street+' '+ Value.HOUSE_NO+' '+ Value.flat_No;
memAbonent.Lines.Add(s);
memAbonent.Lines.Add(Value.CUST_STATE_DESCR);
memAbonent.Lines.Add(Value.notice);
s := rsCode + ' ' + Value.cust_code;
memAbonent.Lines.Insert(0,s);
memAbonent.Lines.Delete(memAbonent.Lines.Count-1);
if Value.color <> '' then Clr := StringToColor(Value.color)
else clr := clBtnFace;
memAbonent.Color := clr;
lblFIO.Color := clr;
lblDebt.Color := clr;
gbInfo.Color := clr;
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_Scene
* Implements a generic Scene
***********************************************************************************************************************
}
Unit TERRA_Scene;
{$I terra.inc}
Interface
Uses TERRA_Utils, TERRA_Matrix4x4, TERRA_Vector3D, TERRA_Viewport;
{$HINTS OFF}
Type
Scene = Class(TERRAObject)
Public
Procedure IncludeShadowCasters(V:Viewport; Var MinZ,MaxZ:Single; Const ShadowMatrix4x4:Matrix4x4); Virtual;
Procedure RenderShadowCasters(V:Viewport); Virtual;
{Procedure RenderReflections(V:Viewport); Virtual;
Procedure RenderReflectiveSurfaces(V:Viewport); Virtual;}
Procedure RenderViewport(V:Viewport); Virtual;
Procedure RenderSky(V:Viewport); Virtual;
Procedure RenderSkyEmission(V:Viewport); Virtual;
Procedure RenderSprites(V:Viewport); Virtual;
Procedure OnMouseDown(X,Y, Button:Integer); Virtual;
End;
Implementation
{ Scene }
Procedure Scene.IncludeShadowCasters(V:Viewport; Var MinZ, MaxZ: Single; Const ShadowMatrix4x4:Matrix4x4);
Begin
End;
Procedure Scene.OnMouseDown(X, Y, Button: Integer);
Begin
End;
Procedure Scene.RenderSprites(V:Viewport);
Begin
// do nothing
End;
Procedure Scene.RenderViewport(V:Viewport);
Begin
End;
{Procedure Scene.RenderReflections;
Begin
End;
procedure Scene.RenderReflectiveSurfaces;
begin
end;}
Procedure Scene.RenderShadowCasters;
Begin
End;
Procedure Scene.RenderSky;
Begin
End;
Procedure Scene.RenderSkyEmission;
Begin
End;
End.
|
unit ManifestUnit;
interface
uses
REST.Json.Types, System.Generics.Collections,
JSONNullableAttributeUnit,
NullableBasicTypesUnit;
type
/// <summary>
/// The manifest contains values derived from other values
/// </summary>
/// <remarks>
/// https://github.com/route4me/json-schemas/blob/master/Address.dtd
/// </remarks>
TManifest = class
private
[JSONName('running_service_time')]
[Nullable]
FRunningServiceTime: NullableInteger;
[JSONName('running_travel_time')]
[Nullable]
FRunningTravelTime: NullableInteger;
[JSONName('running_wait_time')]
[Nullable]
FRunningWaitTime: NullableInteger;
[JSONName('wait_time_to_next_destination')]
[Nullable]
FWaitTimeToNextDestination: NullableInteger;
[JSONName('running_distance')]
[Nullable]
FRunningDistance: NullableDouble;
[JSONName('fuel_from_start')]
[Nullable]
FFuelFromStart: NullableDouble;
[JSONName('fuel_cost_from_start')]
[Nullable]
FFuelCostFromStart: NullableDouble;
[JSONName('projected_arrival_time_ts')]
[Nullable]
FProjectedArrivalTimeTs: NullableInteger;
[JSONName('projected_departure_time_ts')]
[Nullable]
FProjectedDepartureTimeTs: NullableInteger;
[JSONName('actual_arrival_time_ts')]
[Nullable]
FActualArrivalTimeTs: NullableInteger;
[JSONName('actual_departure_time_ts')]
[Nullable]
FActualDepartureTimeTs: NullableInteger;
[JSONName('estimated_arrival_time_ts')]
[Nullable]
FEstimatedArrivalTimeTs: NullableInteger;
[JSONName('estimated_departure_time_ts')]
[Nullable]
FEstimatedDepartureTimeTs: NullableInteger;
[JSONName('time_impact')]
[Nullable]
FTimeImpact: NullableInteger;
public
/// <remarks>
/// Constructor with 0-arguments must be and be public.
/// For JSON-deserialization.
/// </remarks>
constructor Create;
function Equals(Obj: TObject): Boolean; override;
/// <summary>
/// How much time is to be spent on service from the start in seconds
/// </summary>
property RunningServiceTime: NullableInteger read FRunningServiceTime write FRunningServiceTime;
/// <summary>
/// How much time is spent driving from the start in seconds
/// </summary>
property RunningTravelTime: NullableInteger read FRunningTravelTime write FRunningTravelTime;
/// <summary>
/// Running Wait Time
/// </summary>
property RunningWaitTime: NullableInteger read FRunningWaitTime write FRunningWaitTime;
/// <summary>
/// Wait time to next destination
/// </summary>
property WaitTimeToNextDestination: NullableInteger read FWaitTimeToNextDestination write FWaitTimeToNextDestination;
/// <summary>
/// Distance traversed before reaching this address
/// </summary>
property RunningDistance: NullableDouble read FRunningDistance write FRunningDistance;
/// <summary>
/// Fuel From Start
/// </summary>
property FuelFromStart: NullableDouble read FFuelFromStart write FFuelFromStart;
/// <summary>
/// Fuel Cost From Start
/// </summary>
property FuelCostFromStart: NullableDouble read FFuelCostFromStart write FFuelCostFromStart;
/// <summary>
/// Projected arrival time UTC unixtime
/// </summary>
property ProjectedArrivalTimeTs: NullableInteger read FProjectedArrivalTimeTs write FProjectedArrivalTimeTs;
/// <summary>
/// Estimated departure time UTC unixtime
/// </summary>
property ProjectedDepartureTimeTs: NullableInteger read FProjectedDepartureTimeTs write FProjectedDepartureTimeTs;
/// <summary>
/// Time when the address was marked as visited UTC unixtime. This is actually equal to timestamp_last_visited most of the time
/// </summary>
property ActualArrivalTimeTs: NullableInteger read FActualArrivalTimeTs write FActualArrivalTimeTs;
/// <summary>
/// Time when the address was mared as departed UTC. This is actually equal to timestamp_last_departed most of the time
/// </summary>
property ActualDepartureTimeTs: NullableInteger read FActualDepartureTimeTs write FActualDepartureTimeTs;
/// <summary>
/// Estimated arrival time based on the current route progress, i.e. based on the last known actual_arrival_time
/// </summary>
property EstimatedArrivalTimeTs: NullableInteger read FEstimatedArrivalTimeTs write FEstimatedArrivalTimeTs;
/// <summary>
/// Estimated departure time based on the current route progress
/// </summary>
property EstimatedDepartureTimeTs: NullableInteger read FEstimatedDepartureTimeTs write FEstimatedDepartureTimeTs;
/// <summary>
/// This is the difference between the originally projected arrival time and Actual Arrival Time
/// </summary>
property TimeImpact: NullableInteger read FTimeImpact write FTimeImpact;
end;
implementation
{ TManifest }
constructor TManifest.Create;
begin
Inherited;
FRunningServiceTime := NullableInteger.Null;
FRunningTravelTime := NullableInteger.Null;
FRunningWaitTime := NullableInteger.Null;
FWaitTimeToNextDestination := NullableInteger.Null;
FRunningDistance := NullableDouble.Null;
FFuelFromStart := NullableDouble.Null;
FFuelCostFromStart := NullableDouble.Null;
FProjectedArrivalTimeTs := NullableInteger.Null;
FProjectedDepartureTimeTs := NullableInteger.Null;
FActualArrivalTimeTs := NullableInteger.Null;
FActualDepartureTimeTs := NullableInteger.Null;
FEstimatedArrivalTimeTs := NullableInteger.Null;
FEstimatedDepartureTimeTs := NullableInteger.Null;
FTimeImpact := NullableInteger.Null;
end;
function TManifest.Equals(Obj: TObject): Boolean;
var
Other: TManifest;
begin
Result := False;
if not (Obj is TManifest) then
Exit;
Other := TManifest(Obj);
Result :=
(FRunningServiceTime = Other.FRunningServiceTime) and
(FRunningTravelTime = Other.FRunningTravelTime) and
(FRunningWaitTime = Other.FRunningWaitTime) and
(FWaitTimeToNextDestination = Other.FWaitTimeToNextDestination) and
(FRunningDistance = Other.FRunningDistance) and
(FFuelFromStart = Other.FFuelFromStart) and
(FFuelCostFromStart = Other.FFuelCostFromStart) and
(FProjectedArrivalTimeTs = Other.FProjectedArrivalTimeTs) and
(FProjectedDepartureTimeTs = Other.FProjectedDepartureTimeTs) and
(FActualArrivalTimeTs = Other.FActualArrivalTimeTs) and
(FActualDepartureTimeTs = Other.FActualDepartureTimeTs) and
(FEstimatedArrivalTimeTs = Other.FEstimatedArrivalTimeTs) and
(FEstimatedDepartureTimeTs = Other.FEstimatedDepartureTimeTs) and
(FTimeImpact = Other.FTimeImpact);
end;
end.
|
unit evStyleTableFontSizeCorrector;
{* [RequestLink:209585097]. }
// Модуль: "w:\common\components\gui\Garant\Everest\evStyleTableFontSizeCorrector.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevStyleTableFontSizeCorrector" MUID: (4E32AB1401C0)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, evdLeafParaFilter
, k2Base
, l3Variant
;
type
TevStyleTableFontSizeCorrector = class(TevdLeafParaFilter)
{* [RequestLink:209585097]. }
protected
function ParaTypeForFiltering: Tk2Type; override;
{* Функция, определяющая тип абзацев, для которых будет выполняться фильтрация }
procedure DoWritePara(aLeaf: Tl3Variant); override;
{* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца }
end;//TevStyleTableFontSizeCorrector
implementation
uses
l3ImplUses
, evDefaultStylesFontSizes
, evdTextStyle_Const
, k2Tags
//#UC START# *4E32AB1401C0impl_uses*
//#UC END# *4E32AB1401C0impl_uses*
;
function TevStyleTableFontSizeCorrector.ParaTypeForFiltering: Tk2Type;
{* Функция, определяющая тип абзацев, для которых будет выполняться фильтрация }
//#UC START# *49E488070386_4E32AB1401C0_var*
//#UC END# *49E488070386_4E32AB1401C0_var*
begin
//#UC START# *49E488070386_4E32AB1401C0_impl*
Result := k2_typTextStyle;
//#UC END# *49E488070386_4E32AB1401C0_impl*
end;//TevStyleTableFontSizeCorrector.ParaTypeForFiltering
procedure TevStyleTableFontSizeCorrector.DoWritePara(aLeaf: Tl3Variant);
{* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца }
//#UC START# *49E4883E0176_4E32AB1401C0_var*
//#UC END# *49E4883E0176_4E32AB1401C0_var*
begin
//#UC START# *49E4883E0176_4E32AB1401C0_impl*
if aLeaf.HasSubAtom(k2_tiFont) then
if aLeaf.Attr[k2_tiFont].HasSubAtom(k2_tiSize) and not aLeaf.Attr[k2_tiFont].Attr[k2_tiSize].IsTransparent then
aLeaf.Attr[k2_tiFont].IntA[k2_tiSize] :=
TevDefaultStylesFontSizes.Instance.FontSizeForStyle(aLeaf.IntA[k2_tiHandle]);
inherited;
//#UC END# *49E4883E0176_4E32AB1401C0_impl*
end;//TevStyleTableFontSizeCorrector.DoWritePara
end.
|
unit TestUBird;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, UBird, UEuropean, UAfrican, UNorwegianBlue;
type
// Test methods for class TBird
TestTBird = class(TTestCase)
strict private
FBird: TBird;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestgetSpeed;
procedure TestgetSpeed1;
procedure TestgetSpeed2;
end;
implementation
procedure TestTBird.SetUp;
begin
// FBird := TBird.Create;
end;
procedure TestTBird.TearDown;
begin
FBird.Free;
FBird := nil;
end;
procedure TestTBird.TestgetSpeed;
var
ReturnValue: string;
begin
FBird := TEuropean.Create;
ReturnValue := FBird.getSpeed;
CheckEquals(ReturnValue, 'European', 'сообщение об ошибке');
end;
procedure TestTBird.TestgetSpeed1;
var
ReturnValue: string;
begin
FBird := TAfrican.Create;
ReturnValue := FBird.getSpeed;
CheckEquals(ReturnValue, 'African', 'сообщение об ошибке');
end;
procedure TestTBird.TestgetSpeed2;
var
ReturnValue: string;
begin
FBird := TNorwegianBlue.Create;
ReturnValue := FBird.getSpeed;
CheckEquals(ReturnValue, 'NorwegianBlue', 'сообщение об ошибке');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTBird.Suite);
end.
|
unit TokyoScript.Runtime;
{
TokyoScript (c)2018 Execute SARL
http://www.execute.Fr
}
interface
uses
System.Classes,
System.SysUtils;
const
FLAG_CONSOLE = 1;
type
TOpCode = (
opReturn, // empty
opGotoLabel, // goto vLabel
opJumpiEQ, // if vReg1 = vReg2 then goto vLabel
opJumpTrue, // if vReg then goto vLabel
opAssign, // vReg1 := vReg2
opiIncr, // Inc(vReg1)
opIMul, // vReg1 *= VReg2
opiLT, // vReg3 := vReg1 < vReg2
opConcat, // vReg1 += vReg2
opLoadInt, // vReg1 := vValue
opLoadStr, // vReg1 := vString
opWriteInt, // Write(vReg1)
opWriteStr // Write(vReg1)
);
TByteCode = class
Version: Word;
Flags : Word;
Strings: TArray<string>;
Values : TArray<Integer>;
Start : Integer;
Code : TArray<Byte>;
procedure Clear;
procedure SaveToFile(const AFileName: string);
procedure SaveToStream(AStream: TStream);
procedure LoadFromFile(const AFileName: string);
procedure LoadFromStream(AStream: TStream);
end;
TWriteStrEvent = procedure(Sender: TObject; const Value: string) of object;
TRuntime = class
private
FOnWriteStr: TWriteStrEvent;
public
procedure Execute(ByteCode: TByteCode);
procedure WriteStr(const Str: string); virtual;
property OnWriteStr: TWriteStrEvent read FOnWriteStr write FOnWriteStr;
end;
implementation
const
SIGN : array[0..3] of AnsiChar = 'TKS1';
VER = 1;
{ TByteCode }
procedure TByteCode.Clear;
begin
Version := 0;
Flags := 0;
Strings := nil;
Values := nil;
Start := 0;
Code := nil;
end;
procedure TByteCode.LoadFromFile(const AFileName: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TByteCode.LoadFromStream(AStream: TStream);
var
Count: Integer;
Index: Integer;
Len : Integer;
begin
Clear;
try
AStream.ReadBuffer(Count, SizeOf(Count));
if Count <> Integer(SIGN) then
raise Exception.Create('Not a TokyoScript file');
AStream.ReadBuffer(Version, SizeOf(Version));
if Version <> VER then
raise Exception.Create('Unsupported version');
AStream.ReadBuffer(Flags, SizeOf(Flags));
AStream.ReadBuffer(Count, SizeOf(Count));
SetLength(Strings, Count);
for Index := 0 to Count - 1 do
begin
AStream.ReadBuffer(Len, SizeOf(Len));
if Len > 0 then
begin
SetLength(Strings[Index], Len);
AStream.Read(Strings[Index][1], Len * SizeOf(Char));
end;
end;
AStream.ReadBuffer(Count, SizeOf(Count));
if Count > 0 then
begin
SetLength(Values, Count);
AStream.ReadBuffer(Values[0], Count * SizeOf(Integer));
end;
AStream.ReadBuffer(Len, SizeOf(Len));
if Len > 0 then
begin
SetLength(Code, Len);
AStream.Read(Code[0], Len);
end;
except
Clear;
raise;
end;
end;
procedure TByteCode.SaveToFile(const AFileName: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(AFileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
procedure TByteCode.SaveToStream(AStream: TStream);
var
Count: Integer;
Index: Integer;
Len : Integer;
begin
AStream.Write(SIGN, SizeOf(SIGN));
Version := VER;
AStream.Write(Version, SizeOf(Version));
AStream.Write(Flags, SizeOf(Flags));
Count := Length(Strings);
AStream.Write(Count, SizeOf(Count));
for Index := 0 to Count - 1 do
begin
Len := Length(Strings[Index]);
AStream.Write(Len, SizeOf(Len));
if Len > 0 then
AStream.Write(Strings[Index][1], Len * SizeOf(Char));
end;
Count := Length(Values);
AStream.Write(Count, SizeOf(Count));
if Count > 0 then
AStream.Write(Values[0], Count * SizeOf(Integer));
Len := Length(Code);
AStream.Write(Len, SizeOf(Len));
if Len > 0 then
AStream.Write(Code[0], Len)
end;
{ TContext }
type
TRegister = record
AsInteger: Integer;
AsString : string;
procedure LoadInt(Value: Integer);
procedure LoadStr(const Str: string);
procedure Assign(const Reg: TRegister);
end;
TContext = record
RT : TRuntime;
BC : TByteCode;
EOC : Integer;
PC : Integer;
Regs: TArray<TRegister>;
Lbls: TArray<Integer>;
procedure Get(var Data; Size: Integer);
function GetByte: Byte; inline;
function GetWord: Word; inline;
function GetShort: SmallInt; inline;
function GetLong: Integer; inline;
function GetVarLen: Integer;
function GetValue: Integer;
function GetString: string;
function GetReg: Integer;
function GetLabel: Integer;
procedure Start;
procedure Run;
function Next: TOpCode;
procedure LoadInt;
procedure LoadStr;
procedure WriteInt;
procedure WriteStr;
procedure AssignRegs;
procedure iIncr;
procedure iLT;
procedure JumpiEQ;
procedure JumpTrue;
procedure GotoLabel;
end;
{ TRegister }
procedure TRegister.Assign(const Reg: TRegister);
begin
AsInteger := Reg.AsInteger;
AsString := Reg.AsString;
end;
procedure TRegister.LoadInt(Value: Integer);
begin
AsInteger := Value;
end;
procedure TRegister.LoadStr(const Str: string);
begin
AsString := Str;
end;
{ TContext }
procedure TContext.Get(var Data; Size: Integer);
begin
if PC + Size > Length(BC.Code) then
raise Exception.Create('Code overflow');
Move(BC.Code[PC], Data, Size);
Inc(PC, Size);
end;
function TContext.GetByte: Byte;
begin
Get(Result, SizeOf(Result));
end;
function TContext.GetWord: Word;
begin
Get(Result, SizeOf(Result));
end;
function TContext.GetShort: SmallInt;
begin
Get(Result, SizeOf(Result));
end;
function TContext.GetLong: Integer;
begin
Get(Result, SizeOf(Result));
end;
function TContext.GetVarLen: Integer;
begin
Result := GetByte;
case Result of
254: Result := GetWord;
255: Result := GetLong;
end;
end;
function TContext.GetString: string;
var
Index: Integer;
begin
Index := GetVarLen;
if Index >= Length(BC.Strings) then
raise Exception.Create('Strings index overflow');
Result := BC.Strings[Index];
end;
function TContext.GetValue: Integer;
begin
Result := GetVarLen;
if Result >= Length(BC.Values) then
raise Exception.Create('Values overflow');
Result := BC.Values[Result];
end;
function TContext.GetLabel: Integer;
begin
Result := GetVarLen;
if Result >= Length(Lbls) then
raise Exception.Create('Labels overflow');
Result := Lbls[Result];
end;
function TContext.GetReg: Integer;
begin
Result := GetVarLen;
if Result >= Length(Regs) then
raise Exception.Create('Register overflow');
end;
procedure TContext.AssignRegs;
var
R1, R2: Integer;
begin
R1 := GetReg;
R2 := GetReg;
Regs[R1].Assign(Regs[R2]);
end;
procedure TContext.iIncr;
var
R: Integer;
begin
R := GetReg;
Inc(Regs[R].AsInteger);
end;
procedure TContext.iLT;
var
R1: Integer;
R2: Integer;
R3: Integer;
begin
R1 := GetReg;
R2 := GetReg;
R3 := GetReg;
Regs[R3].AsInteger := Ord(Regs[R1].AsInteger < Regs[R2].AsInteger);
end;
procedure TContext.GotoLabel;
begin
PC := GetLabel;
end;
procedure TContext.JumpiEQ;
var
R1: Integer;
R2: Integer;
AD: Integer;
begin
R1 := GetReg;
R2 := GetReg;
AD := GetLabel;
if Regs[R1].AsInteger = Regs[R2].AsInteger then
PC := AD;
end;
procedure TContext.JumpTrue;
var
R: Integer;
A: Integer;
begin
R := GetReg;
A := GetLabel;
if Regs[R].AsInteger <> 0 then
PC := A;
end;
procedure TContext.LoadInt;
var
R: Integer;
begin
R := GetReg;
Regs[R].LoadInt(GetValue);
end;
procedure TContext.LoadStr;
var
R: Integer;
begin
R := GetReg;
Regs[R].LoadStr(GetString);
end;
procedure TContext.WriteInt;
var
R: Integer;
begin
R := GetReg;
RT.WriteStr(IntToStr(Regs[R].AsInteger));
end;
procedure TContext.WriteStr;
var
R: Integer;
begin
R := GetReg;
RT.WriteStr(Regs[R].AsString);
end;
procedure TContext.Start;
begin
PC := BC.Start;
case GetByte of
1: Run; // Format 1
else
raise Exception.Create('Unsupported code version');
end;
end;
procedure TContext.Run;
var
Save : Integer;
Index: Integer;
begin
// Registers Count
SetLength(Regs, GetVarLen);
// Labels count
SetLength(Lbls, GetVarLen);
// End of code Offset
EOC := GetLong;
if EOC > Length(BC.Code) then
raise Exception.Create('Code overflow');
// get Labels offsets
if Length(Lbls) > 0 then
begin
Save := PC;
PC := EOC;
for Index := 0 to Length(Lbls) - 1 do
Lbls[Index] := GetVarLen;
PC := Save;
end;
// execute byte code until opReturn
repeat until Next() = opReturn;
end;
function TContext.Next: TOpCode;
begin
Result := TOpCode(GetByte);
case Result of
opReturn : { done };
opLoadInt : LoadInt;
opiIncr : iIncr;
opLoadStr : LoadStr;
opWriteInt : WriteInt;
opWriteStr : WriteStr;
opJumpiEQ : JumpiEQ;
opJumpTrue : JumpTrue;
opiLT : iLT;
opAssign : AssignRegs;
opGotoLabel : GotoLabel;
else
raise Exception.Create('Unknow opcode #' + IntToStr(Ord(Result)));
end;
end;
{ TRuntime }
procedure TRuntime.Execute(ByteCode: TByteCode);
var
C: TContext;
begin
if ByteCode.Version <> VER then
raise Exception.Create('Unsupported version');
C.RT := Self;
C.BC := ByteCode;
C.Start;
end;
procedure TRuntime.WriteStr(const Str: string);
begin
if Assigned(FOnWriteStr) then
FOnWriteStr(Self, Str);
end;
end.
|
unit FMX.Graphics.INativeCanvas;
interface
uses
System.Types,
System.UITypes,
System.Math.Vectors,
FMX.Types,
FMX.Graphics;
type
TDrawProc = reference to procedure;
TDrawMethod = (Native, Firemonkey);
INativeCanvas = interface
function GetCanvas: TCanvas;
procedure NativeDraw(const ARect: TRectF; const ADrawProc: TDrawProc);
{ aligning }
function AlignToPixel(const Value: TPointF): TPointF; overload;
function AlignToPixel(const Rect: TRectF): TRectF; overload;
function AlignToPixelVertically(const Value: Single): Single;
function AlignToPixelHorizontally(const Value: Single): Single;
// 涂色 + 线色一次完成
procedure DrawRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush; const ACornerType: TCornerType = TCornerType.Round; const Inside: Boolean = False); overload;
procedure DrawPath(const APath: TPathData; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush); overload;
procedure DrawEllipse(const ARect: TRectF; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush; const Inside: Boolean = False); overload;
procedure DrawArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush; const Inside: Boolean = False); overload;
procedure DrawPolygon(const Points: TPolygon; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush); overload;
// 下列为 Canvas 原有函数
procedure DrawBitmap(const ABitmap: TBitmap; const SrcRect, DstRect: TRectF; const AOpacity: Single; const HighSpeed: Boolean = False);
procedure FillText(const ARect: TRectF; const AText: string; const WordWrap: Boolean; const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign; const AVTextAlign: TTextAlign = TTextAlign.Center);
procedure DrawLine(const APt1, APt2: TPointF; const AOpacity: Single); overload;
procedure DrawLine(const APt1, APt2: TPointF; const AOpacity: Single; const ABrush: TStrokeBrush); overload;
procedure FillRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const ACornerType: TCornerType = TCornerType.Round); overload;
procedure FillRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const ABrush: TBrush; const ACornerType: TCornerType = TCornerType.Round); overload;
procedure DrawRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const ACornerType: TCornerType = TCornerType.Round); overload;
procedure DrawRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const ABrush: TStrokeBrush; const ACornerType: TCornerType = TCornerType.Round); overload;
procedure FillPath(const APath: TPathData; const AOpacity: Single); overload;
procedure FillPath(const APath: TPathData; const AOpacity: Single; const ABrush: TBrush); overload;
procedure DrawPath(const APath: TPathData; const AOpacity: Single); overload;
procedure DrawPath(const APath: TPathData; const AOpacity: Single; const ABrush: TStrokeBrush); overload;
procedure FillEllipse(const ARect: TRectF; const AOpacity: Single); overload;
procedure FillEllipse(const ARect: TRectF; const AOpacity: Single; const ABrush: TBrush); overload;
procedure DrawEllipse(const ARect: TRectF; const AOpacity: Single); overload;
procedure DrawEllipse(const ARect: TRectF; const AOpacity: Single; const ABrush: TStrokeBrush); overload;
procedure FillArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single); overload;
procedure FillArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single; const ABrush: TBrush); overload;
procedure DrawArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single); overload;
procedure DrawArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single; const ABrush: TStrokeBrush); overload;
procedure FillPolygon(const Points: TPolygon; const AOpacity: Single); overload;
procedure DrawPolygon(const Points: TPolygon; const AOpacity: Single); overload;
procedure IntersectClipRect(const ARect: TRectF); overload;
procedure ExcludeClipRect(const ARect: TRectF); overload;
function GetScale: Single;
function GetMatrix: TMatrix;
function GetStroke: TStrokeBrush;
function GetFill: TBrush;
function GetFont: TFont;
procedure SetFill(const Value: TBrush);
property Scale: Single read GetScale;
property Matrix: TMatrix read GetMatrix;
property Stroke: TStrokeBrush read GetStroke;
property Fill: TBrush read GetFill write SetFill;
property Font: TFont read GetFont;
end;
TAbstractCanvas = class(TInterfacedObject, INativeCanvas)
protected
FCanvas: TCanvas;
public
constructor Create(ACanvas: TCanvas); virtual;
function GetCanvas: TCanvas;
procedure NativeDraw(const ARect: TRectF; const ADrawProc: TDrawProc); virtual; abstract;
procedure DrawBitmap(const ABitmap: TBitmap; const SrcRect, DstRect: TRectF; const AOpacity: Single; const HighSpeed: Boolean = False); virtual; abstract;
procedure FillText(const ARect: TRectF; const AText: string; const WordWrap: Boolean; const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign; const AVTextAlign: TTextAlign = TTextAlign.Center); virtual; abstract;
// 涂色 + 线色一次完成
procedure DrawRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush; const ACornerType: TCornerType = TCornerType.Round; const Inside: Boolean = False); overload; virtual; abstract;
procedure DrawPath(const APath: TPathData; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush); overload; virtual; abstract;
procedure DrawEllipse(const ARect: TRectF; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush; const Inside: Boolean = False); overload; virtual; abstract;
procedure DrawArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush; const Inside: Boolean = False); overload; virtual; abstract;
procedure DrawPolygon(const Points: TPolygon; const AOpacity: Single; const AFill: TBrush; const AStroke: TStrokeBrush); overload; virtual; abstract;
// 下列为 Canvas 原有函数
{ aligning }
function AlignToPixel(const Value: TPointF): TPointF; overload; inline;
function AlignToPixel(const Rect: TRectF): TRectF; overload; inline;
function AlignToPixelVertically(const Value: Single): Single; inline;
function AlignToPixelHorizontally(const Value: Single): Single; inline;
procedure DrawLine(const APt1, APt2: TPointF; const AOpacity: Single); overload; virtual; abstract;
procedure DrawLine(const APt1, APt2: TPointF; const AOpacity: Single; const ABrush: TStrokeBrush); overload; virtual; abstract;
procedure FillRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const ACornerType: TCornerType = TCornerType.Round); overload; virtual; abstract;
procedure FillRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const ABrush: TBrush; const ACornerType: TCornerType = TCornerType.Round); overload; virtual; abstract;
procedure DrawRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const ACornerType: TCornerType = TCornerType.Round); overload; virtual; abstract;
procedure DrawRect(const ARect: TRectF; const XRadius, YRadius: Single; const ACorners: TCorners; const AOpacity: Single; const ABrush: TStrokeBrush; const ACornerType: TCornerType = TCornerType.Round); overload; virtual; abstract;
procedure FillPath(const APath: TPathData; const AOpacity: Single); overload; virtual; abstract;
procedure FillPath(const APath: TPathData; const AOpacity: Single; const ABrush: TBrush); overload; virtual; abstract;
procedure DrawPath(const APath: TPathData; const AOpacity: Single); overload; virtual; abstract;
procedure DrawPath(const APath: TPathData; const AOpacity: Single; const ABrush: TStrokeBrush); overload; virtual; abstract;
procedure FillEllipse(const ARect: TRectF; const AOpacity: Single); overload; virtual; abstract;
procedure FillEllipse(const ARect: TRectF; const AOpacity: Single; const ABrush: TBrush); overload; virtual; abstract;
procedure DrawEllipse(const ARect: TRectF; const AOpacity: Single); overload; virtual; abstract;
procedure DrawEllipse(const ARect: TRectF; const AOpacity: Single; const ABrush: TStrokeBrush); overload; virtual; abstract;
procedure FillArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single); overload; virtual; abstract;
procedure FillArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single; const ABrush: TBrush); overload; virtual; abstract;
procedure DrawArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single); overload; virtual; abstract;
procedure DrawArc(const Center, Radius: TPointF; StartAngle, SweepAngle: Single; const AOpacity: Single; const ABrush: TStrokeBrush); overload; virtual; abstract;
procedure FillPolygon(const Points: TPolygon; const AOpacity: Single); virtual; abstract;
procedure DrawPolygon(const Points: TPolygon; const AOpacity: Single); overload; virtual; abstract;
procedure IntersectClipRect(const ARect: TRectF); virtual; abstract;
procedure ExcludeClipRect(const ARect: TRectF); virtual; abstract;
function GetScale: Single; inline;
function GetMatrix: TMatrix; inline;
function GetStroke: TStrokeBrush; inline;
function GetFill: TBrush; inline;
procedure SetFill(const Value: TBrush); inline;
function GetFont: TFont; inline;
function GetWidth: Integer; inline;
function GetHeight: Integer; inline;
property Scale: Single read GetScale;
property Matrix: TMatrix read GetMatrix;
property Stroke: TStrokeBrush read GetStroke;
property Fill: TBrush read GetFill write SetFill;
property Font: TFont read GetFont;
property Width: Integer read GetWidth;
property Height: Integer read GetHeight;
end;
implementation
{ TAbstractCanvas }
function TAbstractCanvas.AlignToPixel(const Value: TPointF): TPointF;
begin
Result := FCanvas.AlignToPixel(Value);
end;
function TAbstractCanvas.AlignToPixel(const Rect: TRectF): TRectF;
begin
end;
function TAbstractCanvas.AlignToPixelHorizontally(const Value: Single): Single;
begin
end;
function TAbstractCanvas.AlignToPixelVertically(const Value: Single): Single;
begin
end;
constructor TAbstractCanvas.Create(ACanvas: TCanvas);
begin
FCanvas := ACanvas;
end;
function TAbstractCanvas.GetCanvas: TCanvas;
begin
Result := FCanvas;
end;
function TAbstractCanvas.GetFill: TBrush;
begin
Result := FCanvas.Fill;
end;
function TAbstractCanvas.GetFont: TFont;
begin
Result := FCanvas.Font;
end;
function TAbstractCanvas.GetHeight: Integer;
begin
Result := FCanvas.Height;
end;
function TAbstractCanvas.GetMatrix: TMatrix;
begin
Result := FCanvas.Matrix;
end;
function TAbstractCanvas.GetScale: Single;
begin
Result := FCanvas.Scale;
end;
function TAbstractCanvas.GetStroke: TStrokeBrush;
begin
Result := FCanvas.Stroke;
end;
function TAbstractCanvas.GetWidth: Integer;
begin
Result := FCanvas.Width;
end;
procedure TAbstractCanvas.SetFill(const Value: TBrush);
begin
FCanvas.Fill := Value;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2021 Kike Pérez
Unit : Quick.Conditions
Description : Conditions validator
Author : Kike Pérez
Version : 2.0
Created : 05/05/2021
Modified : 11/05/2021
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.Conditions;
{$i QuickLib.inc}
interface
uses
System.SysUtils,
System.StrUtils,
Quick.Commons;
type
ICondition = interface
['{54F1E937-CE14-426A-9FC5-C6C7944915A2}']
end;
TCondition = class(TInterfacedObject,ICondition)
protected
fName : string;
fExceptionClass : ExceptClass;
fPostCondition : Boolean;
public
constructor Create;
procedure ThrowException(const aMsg : string); overload;
procedure ThrowException(const aMsg : string; aValues : array of const); overload;
procedure ThrowException(aExceptionClass : ExceptClass; const aMsg : string); overload;
end;
IStringCondition = interface(ICondition)
['{B9591175-22E0-4624-94E2-B183DEE1F793}']
function WithExceptionOnFailure(aExceptionClass : ExceptClass) : IStringCondition;
function IsEmpty : IStringCondition; overload;
function IsEmpty(const aCustomMessage : string) : IStringCondition; overload;
function IsNotEmpty : IStringCondition; overload;
function IsNotEmpty(const aCustomMessage : string) : IStringCondition; overload;
function StartsWith(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function StartsWith(const aText, aCustomMessage : string; aIgnoreCase : Boolean = False): IStringCondition; overload;
function DoesNotStartsWith(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function DoesNotStartsWith(const aText, aCustomMessage : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function EndsWith(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function EndsWith(const aText, aCustomMessage : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function DoesNotEndsWith(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function DoesNotEndsWith(const aText,aCustomMessage : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function Contains(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function Contains(const aText, aCustomMessage : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function DoesNotContains(const aText: string; aIgnoreCase: Boolean = False): IStringCondition; overload;
function DoesNotContains(const aText, aCustomMessage: string; aIgnoreCase: Boolean = False): IStringCondition; overload;
function HasLength(aLen : Integer) : IStringCondition; overload;
function HasLength(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function DoesNotHasLength(aLen : Integer) : IStringCondition; overload;
function DoesNotHasLength(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsLongerThan(aLen : Integer) : IStringCondition; overload;
function IsLongerThan(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsLongerOrEqual(aLen : Integer) : IStringCondition; overload;
function IsLongerOrEqual(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsShorterThan(aLen : Integer) : IStringCondition; overload;
function IsShorterThan(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsShorterOrEqual(aLen : Integer) : IStringCondition; overload;
function IsShorterOrEqual(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function HasLengthRange(aMin, aMax : Integer) : IStringCondition; overload;
function HasLengthRange(aMin, aMax : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsUpperCase : IStringCondition; overload;
function IsUpperCase(const aCustomMessage : string) : IStringCondition; overload;
function IsLowerCase : IStringCondition; overload;
function IsLowerCase(const aCustomMessage : string) : IStringCondition; overload;
function IsNotUpperCase : IStringCondition; overload;
function IsNotUpperCase(const aCustomMessage : string) : IStringCondition; overload;
function IsNotLowerCase : IStringCondition; overload;
function IsNotLowerCase(const aCustomMessage : string) : IStringCondition; overload;
function Evaluate(aExpression : Boolean) : IStringCondition; overload;
function Evaluate(aExpression : Boolean; const aCustomMessage : string) : IStringCondition; overload;
end;
IIntegerCondition = interface(ICondition)
['{A34856DD-175B-40BB-BC64-CF131CB448C7}']
function WithExceptionOnFailure(aExceptionClass : ExceptClass) : IIntegerCondition;
function IsInRange(aMin, aMax : Int64) : IIntegerCondition; overload;
function IsInRange(aMin, aMax : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotInRange(aMin, aMax : Int64) : IIntegerCondition; overload;
function IsNotInRange(aMin, aMax : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsEqualTo(aValue : Int64) : IIntegerCondition; overload;
function IsEqualTo(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotEqualTo(aValue : Int64) : IIntegerCondition; overload;
function IsNotEqualTo(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsGreaterThan(aValue : Int64) : IIntegerCondition; overload;
function IsGreaterThan(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotGreaterThan(aValue : Int64) : IIntegerCondition; overload;
function IsNotGreaterThan(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsGreaterOrEqual(aValue : Int64) : IIntegerCondition; overload;
function IsGreaterOrEqual(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotGreaterOrEqual(aValue : Int64) : IIntegerCondition; overload;
function IsNotGreaterOrEqual(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsLessThan(aValue : Int64) : IIntegerCondition; overload;
function IsLessThan(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotLessThan(aValue : Int64) : IIntegerCondition; overload;
function IsNotLessThan(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsLessOrEqual(aValue : Int64) : IIntegerCondition; overload;
function IsLessOrEqual(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotLessOrEqual(aValue : Int64) : IIntegerCondition; overload;
function IsNotLessOrEqual(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function Evaluate(aExpression : Boolean) : IIntegerCondition; overload;
function Evaluate(aExpression : Boolean; const aCustomMessage : string) : IIntegerCondition; overload;
end;
IFloatCondition = interface(ICondition)
['{D0237A24-A00F-4B96-BA7B-0FF9BE7363E5}']
function WithExceptionOnFailure(aExceptionClass : ExceptClass) : IFloatCondition;
function IsInRange(aMin, aMax : Extended) : IFloatCondition; overload;
function IsInRange(aMin, aMax : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotInRange(aMin, aMax : Extended) : IFloatCondition; overload;
function IsNotInRange(aMin, aMax : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsEqualTo(aValue : Extended) : IFloatCondition; overload;
function IsEqualTo(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotEqualTo(aValue : Extended) : IFloatCondition; overload;
function IsNotEqualTo(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsGreaterThan(aValue : Extended) : IFloatCondition; overload;
function IsGreaterThan(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotGreaterThan(aValue : Extended) : IFloatCondition; overload;
function IsNotGreaterThan(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsGreaterOrEqual(aValue : Extended) : IFloatCondition; overload;
function IsGreaterOrEqual(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotGreaterOrEqual(aValue : Extended) : IFloatCondition; overload;
function IsNotGreaterOrEqual(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsLessThan(aValue : Extended) : IFloatCondition; overload;
function IsLessThan(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotLessThan(aValue : Extended) : IFloatCondition; overload;
function IsNotLessThan(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsLessOrEqual(aValue : Extended) : IFloatCondition; overload;
function IsLessOrEqual(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotLessOrEqual(aValue : Extended) : IFloatCondition; overload;
function IsNotLessOrEqual(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function Evaluate(aExpression : Boolean) : IFloatCondition; overload;
function Evaluate(aExpression : Boolean; const aCustomMessage : string) : IFloatCondition; overload;
end;
IObjectCondition = interface(ICondition)
['{497E21D2-7780-4C3B-B51E-921847491FC1}']
function WithExceptionOnFailure(aExceptionClass : ExceptClass) : IObjectCondition;
function IsNull : IObjectCondition; overload;
function IsNull(const aCustomMessage : string): IObjectCondition; overload;
function IsNotNull : IObjectCondition; overload;
function IsNotNull(const aCustomMessage : string) : IObjectCondition; overload;
function IsOfType(aClass : TClass) : IObjectCondition; overload;
function IsOfType(aClass : TClass; const aCustomMessage : string) : IObjectCondition; overload;
function DoesNotOfType(aClass : TClass) : IObjectCondition; overload;
function DoesNotOfType(aClass : TClass; const aCustomMessage : string) : IObjectCondition; overload;
function Evaluate(aExpression : Boolean) : IObjectCondition; overload;
function Evaluate(aExpression : Boolean; const aCustomMessage : string) : IObjectCondition; overload;
end;
TStringCondition = class(TCondition,IStringCondition)
private
fValue : string;
public
constructor Create(const aValue : string; const aName : string; aPostCondition : Boolean);
function WithExceptionOnFailure(aExceptionClass : ExceptClass) : IStringCondition;
function IsEmpty : IStringCondition; overload;
function IsEmpty(const aCustomMessage : string) : IStringCondition; overload;
function IsNotEmpty : IStringCondition; overload;
function IsNotEmpty(const aCustomMessage : string) : IStringCondition; overload;
function StartsWith(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function StartsWith(const aText, aCustomMessage : string; aIgnoreCase : Boolean = False): IStringCondition; overload;
function DoesNotStartsWith(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function DoesNotStartsWith(const aText, aCustomMessage : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function EndsWith(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function EndsWith(const aText, aCustomMessage : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function DoesNotEndsWith(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function DoesNotEndsWith(const aText,aCustomMessage : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function Contains(const aText : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function Contains(const aText, aCustomMessage : string; aIgnoreCase : Boolean = False) : IStringCondition; overload;
function DoesNotContains(const aText: string; aIgnoreCase: Boolean = False): IStringCondition; overload;
function DoesNotContains(const aText, aCustomMessage: string; aIgnoreCase: Boolean = False): IStringCondition; overload;
function HasLength(aLen : Integer) : IStringCondition; overload;
function HasLength(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function DoesNotHasLength(aLen : Integer) : IStringCondition; overload;
function DoesNotHasLength(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsLongerThan(aLen : Integer) : IStringCondition; overload;
function IsLongerThan(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsLongerOrEqual(aLen : Integer) : IStringCondition; overload;
function IsLongerOrEqual(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsShorterThan(aLen : Integer) : IStringCondition; overload;
function IsShorterThan(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsShorterOrEqual(aLen : Integer) : IStringCondition; overload;
function IsShorterOrEqual(aLen : Integer; const aCustomMessage : string) : IStringCondition; overload;
function HasLengthRange(aMin, aMax : Integer) : IStringCondition; overload;
function HasLengthRange(aMin, aMax : Integer; const aCustomMessage : string) : IStringCondition; overload;
function IsUpperCase : IStringCondition; overload;
function IsUpperCase(const aCustomMessage : string) : IStringCondition; overload;
function IsLowerCase : IStringCondition; overload;
function IsLowerCase(const aCustomMessage : string) : IStringCondition; overload;
function IsNotUpperCase : IStringCondition; overload;
function IsNotUpperCase(const aCustomMessage : string) : IStringCondition; overload;
function IsNotLowerCase : IStringCondition; overload;
function IsNotLowerCase(const aCustomMessage : string) : IStringCondition; overload;
function Evaluate(aExpression : Boolean) : IStringCondition; overload;
function Evaluate(aExpression : Boolean; const aCustomMessage : string) : IStringCondition; overload;
end;
TIntegerCondition = class(TCondition,IIntegerCondition)
private
fValue : Int64;
public
constructor Create(const aValue : Int64; const aName : string; aPostCondition : Boolean);
function WithExceptionOnFailure(aExceptionClass : ExceptClass) : IIntegerCondition;
function IsInRange(aMin, aMax : Int64) : IIntegerCondition; overload;
function IsInRange(aMin, aMax : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotInRange(aMin, aMax : Int64) : IIntegerCondition; overload;
function IsNotInRange(aMin, aMax : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsEqualTo(aValue : Int64) : IIntegerCondition; overload;
function IsEqualTo(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotEqualTo(aValue : Int64) : IIntegerCondition; overload;
function IsNotEqualTo(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsGreaterThan(aValue : Int64) : IIntegerCondition; overload;
function IsGreaterThan(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotGreaterThan(aValue : Int64) : IIntegerCondition; overload;
function IsNotGreaterThan(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsGreaterOrEqual(aValue : Int64) : IIntegerCondition; overload;
function IsGreaterOrEqual(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotGreaterOrEqual(aValue : Int64) : IIntegerCondition; overload;
function IsNotGreaterOrEqual(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsLessThan(aValue : Int64) : IIntegerCondition; overload;
function IsLessThan(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotLessThan(aValue : Int64) : IIntegerCondition; overload;
function IsNotLessThan(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsLessOrEqual(aValue : Int64) : IIntegerCondition; overload;
function IsLessOrEqual(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function IsNotLessOrEqual(aValue : Int64) : IIntegerCondition; overload;
function IsNotLessOrEqual(aValue : Int64; const aCustomMessage : string) : IIntegerCondition; overload;
function Evaluate(aExpression : Boolean) : IIntegerCondition; overload;
function Evaluate(aExpression : Boolean; const aCustomMessage : string) : IIntegerCondition; overload;
end;
TFloatCondition = class(TCondition,IFloatCondition)
private
fValue : Extended;
public
constructor Create(const aValue : Extended; const aName : string; aPostCondition : Boolean);
function WithExceptionOnFailure(aExceptionClass : ExceptClass) : IFloatCondition;
function IsInRange(aMin, aMax : Extended) : IFloatCondition; overload;
function IsInRange(aMin, aMax : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotInRange(aMin, aMax : Extended) : IFloatCondition; overload;
function IsNotInRange(aMin, aMax : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsEqualTo(aValue : Extended) : IFloatCondition; overload;
function IsEqualTo(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotEqualTo(aValue : Extended) : IFloatCondition; overload;
function IsNotEqualTo(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsGreaterThan(aValue : Extended) : IFloatCondition; overload;
function IsGreaterThan(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotGreaterThan(aValue : Extended) : IFloatCondition; overload;
function IsNotGreaterThan(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsGreaterOrEqual(aValue : Extended) : IFloatCondition; overload;
function IsGreaterOrEqual(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotGreaterOrEqual(aValue : Extended) : IFloatCondition; overload;
function IsNotGreaterOrEqual(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsLessThan(aValue : Extended) : IFloatCondition; overload;
function IsLessThan(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotLessThan(aValue : Extended) : IFloatCondition; overload;
function IsNotLessThan(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsLessOrEqual(aValue : Extended) : IFloatCondition; overload;
function IsLessOrEqual(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function IsNotLessOrEqual(aValue : Extended) : IFloatCondition; overload;
function IsNotLessOrEqual(aValue : Extended; const aCustomMessage : string) : IFloatCondition; overload;
function Evaluate(aExpression : Boolean) : IFloatCondition; overload;
function Evaluate(aExpression : Boolean; const aCustomMessage : string) : IFloatCondition; overload;
end;
TObjectCondition = class(TCondition,IObjectCondition)
private
fValue : TObject;
public
constructor Create(const aValue : TObject; const aName : string; aPostCondition : Boolean);
function WithExceptionOnFailure(aExceptionClass : ExceptClass) : IObjectCondition;
function IsNull : IObjectCondition; overload;
function IsNull(const aCustomMessage : string): IObjectCondition; overload;
function IsNotNull : IObjectCondition; overload;
function IsNotNull(const aCustomMessage : string) : IObjectCondition; overload;
function IsOfType(aClass : TClass) : IObjectCondition; overload;
function IsOfType(aClass : TClass; const aCustomMessage : string) : IObjectCondition; overload;
function DoesNotOfType(aClass : TClass) : IObjectCondition; overload;
function DoesNotOfType(aClass : TClass; const aCustomMessage : string) : IObjectCondition; overload;
function Evaluate(aExpression : Boolean) : IObjectCondition; overload;
function Evaluate(aExpression : Boolean; const aCustomMessage : string) : IObjectCondition; overload;
end;
IConditionValidator = interface
['{F707606E-7603-4690-BE76-2443B0A36D5F}']
function Requires(const aValue : string; const aName : string = '') : IStringCondition; overload;
function Requires(const aValue : Int64; const aName : string = '') : IIntegerCondition; overload;
function Requires(const aValue : Extended; const aName : string = '') : IFloatCondition; overload;
function Requires(const aValue : TObject; const aName : string = '') : IObjectCondition; overload;
function Ensures(const aValue : string; const aName : string = '') : IStringCondition; overload;
function Ensures(const aValue : Int64; const aName : string = '') : IIntegerCondition; overload;
function Ensures(const aValue : Extended; const aName : string = '') : IFloatCondition; overload;
function Ensures(const aValue : TObject; const aName : string = '') : IObjectCondition; overload;
end;
TConditionValidator = class(TInterfacedObject,IConditionValidator)
public
function Requires(const aValue : string; const aName : string = '') : IStringCondition; overload;
function Requires(const aValue : Int64; const aName : string = '') : IIntegerCondition; overload;
function Requires(const aValue : Extended; const aName : string = '') : IFloatCondition; overload;
function Requires(const aValue : TObject; const aName : string = '') : IObjectCondition; overload;
function Ensures(const aValue : string; const aName : string = '') : IStringCondition; overload;
function Ensures(const aValue : Int64; const aName : string = '') : IIntegerCondition; overload;
function Ensures(const aValue : Extended; const aName : string = '') : IFloatCondition; overload;
function Ensures(const aValue : TObject; const aName : string = '') : IObjectCondition; overload;
end;
EPreConditionError = class(Exception);
EPostConditionError = class(Exception);
function Condition : IConditionValidator;
implementation
function Condition : IConditionValidator;
begin
Result := TConditionValidator.Create;
end;
{ TEvaluator }
function TConditionValidator.Requires(const aValue: string; const aName : string = ''): IStringCondition;
begin
Result := TStringCondition.Create(aValue,aName,False);
end;
function TConditionValidator.Requires(const aValue: Int64; const aName : string = ''): IIntegerCondition;
begin
Result := TIntegerCondition.Create(aValue,aName,False);
end;
function TConditionValidator.Requires(const aValue: Extended; const aName : string = ''): IFloatCondition;
begin
Result := TFloatCondition.Create(aValue,aName,False);
end;
function TConditionValidator.Requires(const aValue: TObject; const aName : string = ''): IObjectCondition;
begin
Result := TObjectCondition.Create(aValue,aName,False);
end;
function TConditionValidator.Ensures(const aValue, aName: string): IStringCondition;
begin
Result := TStringCondition.Create(aValue,aName,True);
end;
function TConditionValidator.Ensures(const aValue: Int64; const aName: string): IIntegerCondition;
begin
Result := TIntegerCondition.Create(aValue,aName,True);
end;
function TConditionValidator.Ensures(const aValue: Extended; const aName: string): IFloatCondition;
begin
Result := TFloatCondition.Create(aValue,aName,True);
end;
function TConditionValidator.Ensures(const aValue: TObject; const aName: string): IObjectCondition;
begin
Result := TObjectCondition.Create(aValue,aName,True);
end;
{ TStringCondition }
constructor TStringCondition.Create(const aValue: string; const aName : string; aPostCondition : Boolean);
begin
fName := aName;
fValue := aValue;
fPostCondition := aPostCondition;
end;
function TStringCondition.WithExceptionOnFailure(aExceptionClass: ExceptClass): IStringCondition;
begin
fExceptionClass := aExceptionClass;
Result := Self;
end;
function TStringCondition.IsEmpty: IStringCondition;
begin
Result := Self.IsEmpty('');
end;
function TStringCondition.IsEmpty(const aCustomMessage : string): IStringCondition;
begin
if not fValue.IsEmpty then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentNilException,aCustomMessage)
else ThrowException('must be empty');
end;
Result := Self;
end;
function TStringCondition.IsNotEmpty: IStringCondition;
begin
Result := Self.IsNotEmpty('');
end;
function TStringCondition.IsNotEmpty(const aCustomMessage : string): IStringCondition;
begin
if fValue.IsEmpty then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentNilException,aCustomMessage)
else ThrowException('should not be empty');
end;
Result := Self;
end;
function TStringCondition.StartsWith(const aText: string; aIgnoreCase : Boolean = False): IStringCondition;
begin
Result := Self.StartsWith(aText,'',aIgnoreCase);
end;
function TStringCondition.StartsWith(const aText, aCustomMessage : string; aIgnoreCase : Boolean = False): IStringCondition;
begin
if not fValue.StartsWith(aText,aIgnoreCase) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must start with "%s"',[aText])
end;
Result := Self;
end;
function TStringCondition.DoesNotStartsWith(const aText: string; aIgnoreCase: Boolean): IStringCondition;
begin
Result := Self.DoesNotStartsWith(aText,'',aIgnoreCase);
end;
function TStringCondition.DoesNotStartsWith(const aText, aCustomMessage: string; aIgnoreCase: Boolean): IStringCondition;
begin
if fValue.StartsWith(aText,aIgnoreCase) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not start with "%s"',[aText]);
end;
Result := Self;
end;
function TStringCondition.EndsWith(const aText: string; aIgnoreCase : Boolean = False): IStringCondition;
begin
Result := Self.EndsWith(aText,'',aIgnoreCase);
end;
function TStringCondition.EndsWith(const aText, aCustomMessage: string; aIgnoreCase : Boolean = False): IStringCondition;
begin
if not fValue.EndsWith(aText,aIgnoreCase) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must end with "%s"',[aText]);
end;
Result := Self;
end;
function TStringCondition.DoesNotEndsWith(const aText: string; aIgnoreCase: Boolean): IStringCondition;
begin
Result := Self.DoesNotEndsWith(aText,'',aIgnoreCase);
end;
function TStringCondition.DoesNotEndsWith(const aText, aCustomMessage: string; aIgnoreCase: Boolean): IStringCondition;
begin
if fValue.EndsWith(aText,aIgnoreCase) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be end with "%s"',[aText]);
end;
Result := Self;
end;
function TStringCondition.Contains(const aText: string; aIgnoreCase: Boolean): IStringCondition;
begin
Result := Self.Contains(aText,'',aIgnoreCase);
end;
function TStringCondition.Contains(const aText, aCustomMessage: string; aIgnoreCase: Boolean): IStringCondition;
begin
if aIgnoreCase then
begin
if not ContainsText(fValue,aText) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must contain "%s"',[aText]);
end;
end
else
begin
if not fValue.Contains(aText) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must contain "%s"',[aText]);
end;
end;
Result := Self;
end;
function TStringCondition.DoesNotContains(const aText: string; aIgnoreCase: Boolean = False): IStringCondition;
begin
Result := Self.DoesNotContains(aText,'',aIgnoreCase);
end;
function TStringCondition.DoesNotContains(const aText, aCustomMessage: string; aIgnoreCase: Boolean = False): IStringCondition;
begin
if aIgnoreCase then
begin
if ContainsText(fValue,aText) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not contain "%s"',[aText]);
end;
end
else
begin
if fValue.Contains(aText) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not contain "%s"',[aText]);
end;
end;
Result := Self;
end;
function TStringCondition.HasLength(aLen: Integer): IStringCondition;
begin
Result := Self.HasLength(aLen,'');
end;
function TStringCondition.HasLength(aLen: Integer; const aCustomMessage : string): IStringCondition;
begin
if fValue.Length <> aLen then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be %d length',[aLen]);
end;
Result := Self;
end;
function TStringCondition.DoesNotHasLength(aLen: Integer): IStringCondition;
begin
Result := Self.DoesNotHasLength(aLen,'');
end;
function TStringCondition.DoesNotHasLength(aLen: Integer; const aCustomMessage : string): IStringCondition;
begin
if fValue.Length = aLen then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be %d length',[aLen]);
end;
Result := Self;
end;
function TStringCondition.IsShorterThan(aLen: Integer): IStringCondition;
begin
Result := Self.IsShorterThan(aLen,'');
end;
function TStringCondition.IsShorterThan(aLen: Integer; const aCustomMessage : string): IStringCondition;
begin
if fValue.Length >= aLen then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be shorten than %d',[aLen]);
end;
Result := Self;
end;
function TStringCondition.IsShorterOrEqual(aLen: Integer): IStringCondition;
begin
Result := Self.IsShorterOrEqual(aLen,'');
end;
function TStringCondition.IsShorterOrEqual(aLen: Integer; const aCustomMessage : string): IStringCondition;
begin
if fValue.Length > aLen then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be shorter or equal to %d',[aLen]);
end;
Result := Self;
end;
function TStringCondition.IsLongerOrEqual(aLen: Integer): IStringCondition;
begin
Result := Self.IsLongerOrEqual(aLen,'');
end;
function TStringCondition.IsLongerOrEqual(aLen: Integer; const aCustomMessage : string): IStringCondition;
begin
if fValue.Length < aLen then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be longer or equal to %d',[aLen]);
end;
Result := Self;
end;
function TStringCondition.IsLongerThan(aLen: Integer): IStringCondition;
begin
Result := Self.IsLongerThan(aLen,'');
end;
function TStringCondition.IsLongerThan(aLen: Integer; const aCustomMessage : string): IStringCondition;
begin
if fValue.Length <= aLen then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be longer than %d',[aLen]);
end;
Result := Self;
end;
function TStringCondition.HasLengthRange(aMin, aMax: Integer): IStringCondition;
begin
Result := Self.HasLengthRange(aMin,aMax,'');
end;
function TStringCondition.HasLengthRange(aMin, aMax: Integer; const aCustomMessage : string): IStringCondition;
begin
if (fValue.Length < aMin) or (fValue.Length > aMax) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentOutOfRangeException,aCustomMessage)
else ThrowException('must be in %d-%d length range',[aMin,aMax]);
end;
Result := Self;
end;
function TStringCondition.IsUpperCase: IStringCondition;
begin
Result := Self.IsUpperCase('');
end;
function TStringCondition.IsUpperCase(const aCustomMessage : string): IStringCondition;
begin
if fValue.ToUpper <> fValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be upper case');
end;
Result := Self;
end;
function TStringCondition.IsLowerCase: IStringCondition;
begin
Result := Self.IsLowerCase('');
end;
function TStringCondition.IsLowerCase(const aCustomMessage : string): IStringCondition;
begin
if fValue.ToLower <> fValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be lower case');
end;
Result := Self;
end;
function TStringCondition.IsNotUpperCase: IStringCondition;
begin
Result := Self.IsNotUpperCase('');
end;
function TStringCondition.IsNotUpperCase(const aCustomMessage : string): IStringCondition;
begin
if fValue.ToUpper = fValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be upper case');
end;
Result := Self;
end;
function TStringCondition.IsNotLowerCase: IStringCondition;
begin
Result := Self.IsNotLowerCase('');
end;
function TStringCondition.IsNotLowerCase(const aCustomMessage : string): IStringCondition;
begin
if fValue.ToLower = fValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be lower case');
end;
Result := Self;
end;
function TStringCondition.Evaluate(aExpression: Boolean): IStringCondition;
begin
Result := Self.Evaluate(aExpression,'');
end;
function TStringCondition.Evaluate(aExpression: Boolean; const aCustomMessage : string): IStringCondition;
begin
if not aExpression then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must meet condition');
end;
end;
{ TIntegerCondition }
constructor TIntegerCondition.Create(const aValue: Int64; const aName : string; aPostCondition : Boolean);
begin
fName := aName;
fValue := aValue;
fPostCondition := aPostCondition;
end;
function TIntegerCondition.WithExceptionOnFailure(aExceptionClass: ExceptClass): IIntegerCondition;
begin
fExceptionClass := aExceptionClass;
Result := Self;
end;
function TIntegerCondition.IsEqualTo(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsEqualTo(aValue,'');
end;
function TIntegerCondition.IsEqualTo(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue <> aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be equal to %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.IsGreaterOrEqual(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsGreaterOrEqual(aValue,'');
end;
function TIntegerCondition.IsGreaterOrEqual(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue < aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be greather or equal to %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.IsGreaterThan(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsGreaterThan(aValue,'');
end;
function TIntegerCondition.IsGreaterThan(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue <= aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be greather than %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.IsInRange(aMin, aMax: Int64): IIntegerCondition;
begin
Result := Self.IsInRange(aMin,aMax,'');
end;
function TIntegerCondition.IsInRange(aMin, aMax: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if (fValue < aMin) or (fValue > aMax) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentOutOfRangeException,aCustomMessage)
else ThrowException('must be in %d-%d range',[aMin,aMax]);
end;
Result := Self;
end;
function TIntegerCondition.IsLessOrEqual(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsLessOrEqual(aValue,'');
end;
function TIntegerCondition.IsLessOrEqual(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue > aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be less or equal to %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.IsLessThan(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsLessThan(aValue,'');
end;
function TIntegerCondition.IsLessThan(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue >= aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be less than %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.IsNotEqualTo(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsNotEqualTo(aValue,'');
end;
function TIntegerCondition.IsNotEqualTo(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue = aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be equal to %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.IsNotGreaterOrEqual(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsNotGreaterOrEqual(aValue,'');
end;
function TIntegerCondition.IsNotGreaterOrEqual(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue >= aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be greater or equal to %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.IsNotGreaterThan(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsNotGreaterThan(aValue,'');
end;
function TIntegerCondition.IsNotGreaterThan(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue > aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be greater than %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.IsNotInRange(aMin, aMax: Int64): IIntegerCondition;
begin
Result := Self.IsNotInRange(aMin,aMax,'');
end;
function TIntegerCondition.IsNotInRange(aMin, aMax: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if (fValue >= aMin) and (fValue <= aMax) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentOutOfRangeException,aCustomMessage)
else ThrowException('should not be in range %d-%d',[aMin,aMax]);
end;
Result := Self;
end;
function TIntegerCondition.IsNotLessOrEqual(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsNotLessOrEqual(aValue,'');
end;
function TIntegerCondition.IsNotLessOrEqual(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue <= aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be less or equal to %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.IsNotLessThan(aValue: Int64): IIntegerCondition;
begin
Result := Self.IsNotLessThan(aValue,'');
end;
function TIntegerCondition.IsNotLessThan(aValue: Int64; const aCustomMessage : string): IIntegerCondition;
begin
if fValue < aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be less than %d',[aValue]);
end;
Result := Self;
end;
function TIntegerCondition.Evaluate(aExpression: Boolean): IIntegerCondition;
begin
Result := Self.Evaluate(aExpression,'');
end;
function TIntegerCondition.Evaluate(aExpression: Boolean; const aCustomMessage : string): IIntegerCondition;
begin
if not aExpression then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must meet condition');
end;
end;
{ TFloatCondition }
constructor TFloatCondition.Create(const aValue: Extended; const aName : string; aPostCondition : Boolean);
begin
fName := aName;
fValue := aValue;
fPostCondition := aPostCondition;
end;
function TFloatCondition.WithExceptionOnFailure(aExceptionClass: ExceptClass): IFloatCondition;
begin
fExceptionClass := aExceptionClass;
Result := Self;
end;
function TFloatCondition.IsEqualTo(aValue: Extended): IFloatCondition;
begin
Result := Self.IsEqualTo(aValue,'');
end;
function TFloatCondition.IsEqualTo(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue <> aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be equal to %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.IsGreaterOrEqual(aValue: Extended): IFloatCondition;
begin
Result := Self.IsGreaterOrEqual(aValue,'');
end;
function TFloatCondition.IsGreaterOrEqual(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue < aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be greather or equal to %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.IsGreaterThan(aValue: Extended): IFloatCondition;
begin
Result := Self.IsGreaterThan(aValue,'');
end;
function TFloatCondition.IsGreaterThan(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue <= aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be greather than %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.IsInRange(aMin, aMax: Extended): IFloatCondition;
begin
Result := Self.IsInRange(aMin,aMax,'');
end;
function TFloatCondition.IsInRange(aMin, aMax: Extended; const aCustomMessage : string): IFloatCondition;
begin
if (fValue < aMin) or (fValue > aMax) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentOutOfRangeException,aCustomMessage)
else ThrowException('must be in %d-%d range',[aMin,aMax]);
end;
Result := Self;
end;
function TFloatCondition.IsLessOrEqual(aValue: Extended): IFloatCondition;
begin
Result := Self.IsLessOrEqual(aValue,'');
end;
function TFloatCondition.IsLessOrEqual(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue > aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be less or equal to %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.IsLessThan(aValue: Extended): IFloatCondition;
begin
Result := Self.IsLessThan(aValue,'');
end;
function TFloatCondition.IsLessThan(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue >= aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be less than %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.IsNotEqualTo(aValue: Extended): IFloatCondition;
begin
Result := Self.IsNotEqualTo(aValue,'');
end;
function TFloatCondition.IsNotEqualTo(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue = aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be equal to %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.IsNotGreaterOrEqual(aValue: Extended): IFloatCondition;
begin
Result := Self.IsNotGreaterOrEqual(aValue,'');
end;
function TFloatCondition.IsNotGreaterOrEqual(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue >= aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be greater or equal to %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.IsNotGreaterThan(aValue: Extended): IFloatCondition;
begin
Result := Self.IsNotGreaterThan(aValue,'');
end;
function TFloatCondition.IsNotGreaterThan(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue > aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be greater than %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.IsNotInRange(aMin, aMax: Extended): IFloatCondition;
begin
Result := Self.IsNotInRange(aMin,aMax,'');
end;
function TFloatCondition.IsNotInRange(aMin, aMax: Extended; const aCustomMessage : string): IFloatCondition;
begin
if (fValue >= aMin) and (fValue <= aMax) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentOutOfRangeException,aCustomMessage)
else ThrowException('should not be in range %d-%d',[aMin,aMax]);
end;
Result := Self;
end;
function TFloatCondition.IsNotLessOrEqual(aValue: Extended): IFloatCondition;
begin
Result := Self.IsNotLessOrEqual(aValue,'');
end;
function TFloatCondition.IsNotLessOrEqual(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue <= aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be less or equal to %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.IsNotLessThan(aValue: Extended): IFloatCondition;
begin
Result := Self.IsNotLessThan(aValue,'');
end;
function TFloatCondition.IsNotLessThan(aValue: Extended; const aCustomMessage : string): IFloatCondition;
begin
if fValue < aValue then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be less than %d',[aValue]);
end;
Result := Self;
end;
function TFloatCondition.Evaluate(aExpression: Boolean): IFloatCondition;
begin
Result := Self.Evaluate(aExpression,'');
end;
function TFloatCondition.Evaluate(aExpression: Boolean; const aCustomMessage : string): IFloatCondition;
begin
if not aExpression then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must meet condition');
end;
end;
{ TObjectCondition }
constructor TObjectCondition.Create(const aValue: TObject; const aName: string; aPostCondition : Boolean);
begin
fName := aName;
fValue := aValue;
fPostCondition := aPostCondition;
end;
function TObjectCondition.WithExceptionOnFailure(aExceptionClass: ExceptClass): IObjectCondition;
begin
fExceptionClass := aExceptionClass;
Result := Self;
end;
function TObjectCondition.IsNull: IObjectCondition;
begin
Result := Self.IsNull('');
end;
function TObjectCondition.IsNull(const aCustomMessage: string): IObjectCondition;
begin
if fValue <> nil then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentNilException,aCustomMessage)
else ThrowException('must be null');
end;
Result := Self;
end;
function TObjectCondition.IsNotNull: IObjectCondition;
begin
Result := Self.IsNotNull('');
end;
function TObjectCondition.IsNotNull(const aCustomMessage: string): IObjectCondition;
begin
if fValue = nil then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentNilException,aCustomMessage)
else ThrowException('should not be null');
end;
Result := Self;
end;
function TObjectCondition.IsOfType(aClass: TClass): IObjectCondition;
begin
Result := Self.IsOfType(aClass,'');
end;
function TObjectCondition.IsOfType(aClass: TClass; const aCustomMessage: string): IObjectCondition;
begin
if not(fValue is aClass) then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must be of type "%s"',[aClass.ClassName]);
end;
Result := Self;
end;
function TObjectCondition.DoesNotOfType(aClass: TClass): IObjectCondition;
begin
Result := Self.DoesNotOfType(aClass,'');
end;
function TObjectCondition.DoesNotOfType(aClass: TClass; const aCustomMessage: string): IObjectCondition;
begin
if fValue is aClass then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('should not be of type "%s"',[aClass.ClassName]);
end;
Result := Self;
end;
function TObjectCondition.Evaluate(aExpression: Boolean): IObjectCondition;
begin
Result := Self.Evaluate(aExpression,'');
end;
function TObjectCondition.Evaluate(aExpression: Boolean; const aCustomMessage: string): IObjectCondition;
begin
if not aExpression then
begin
if not aCustomMessage.IsEmpty then ThrowException(EArgumentException,aCustomMessage)
else ThrowException('must meet condition');
end;
Result := Self;
end;
{ TCondition }
constructor TCondition.Create;
begin
fName := '';
fExceptionClass := nil;
fPostCondition := False;
end;
procedure TCondition.ThrowException(const aMsg: string);
var
rexception : ExceptClass;
begin
if fExceptionClass <> nil then raise fExceptionClass.Create(aMsg)
else
begin
if fPostCondition then rexception := EPostConditionError
else rexception := EPreConditionError;
if fName.IsEmpty then raise rexception.Create(aMsg)
else raise rexception.CreateFmt('[%s] %s',[fName,aMsg]);
end;
end;
procedure TCondition.ThrowException(const aMsg: string; aValues: array of const);
begin
if fExceptionClass <> nil then raise fExceptionClass.Create(aMsg)
else ThrowException(Format(aMsg,aValues));
end;
procedure TCondition.ThrowException(aExceptionClass : ExceptClass; const aMsg : string);
begin
if fExceptionClass <> nil then raise fExceptionClass.Create(aMsg)
else raise aExceptionClass.Create(aMsg);
end;
end.
|
unit uClasse.Veiculo.Terrestre.Caminhao;
interface
uses
uClasse.Veiculo.Terrestre, System.SysUtils, System.DateUtils;
type
TCaminhao = class(TTerrestre)
private
public
DataInstalacao_tacografo: Tdatetime;
DataValidade_tacografo: Tdatetime;
QtdEixos: integer;
TipoCarroceria: string;
TamanhoCarroceria: string;
TipoCarga: string;
tara: double;
PesoMaximo: double;
function RetornaAplicacaoUso: string; override;
function RetornarProximaTrocaOleo: TDateTime; override;
end;
implementation
{ TCaminhao }
function TCaminhao.RetornaAplicacaoUso: string;
begin
inherited;
result:= tipo + ' - Veiculo Caminhão: Aplicação Terrestre';
end;
function TCaminhao.RetornarProximaTrocaOleo: TDateTime;
begin
if DiasMaximoProximaTrocaOleo > 0 then
result:= StrToDateTime(StringReplace(FormatDateTime('dd.mm.yyyy', incDay(DataUltimaTrocaOleo, DiasMaximoProximaTrocaOleo)),'.','/', [rfReplaceAll]))
else
begin
raise Exception.Create('Quantidade de dias para próxima troca de óleo deve ser maior do que 0.');
abort;
end;
end;
end.
|
unit BCEditor;
interface {********************************************************************}
uses
Windows, Messages, ActiveX, GDIPAPI, GDIPObj,
Classes, SysUtils, UITypes, StrUtils, Generics.Collections,
Forms, StdActns, Controls, Graphics, StdCtrls, Dialogs, Consts,
Menus,
BCEditor.Commands, BCEditor.CompletionProposal, BCEditor.Consts,
BCEditor.GotoLine, BCEditor.Highlighter, BCEditor.Lines, BCEditor.Properties,
BCEditor.Types;
type
TCustomBCEditor = class(TCustomControl, IDropSource, IDropTarget)
private type
TBCEditorColors = class(BCEditor.Properties.TBCEditorColors);
TBCEditorCompletionProposal = class(BCEditor.Properties.TBCEditorCompletionProposal);
TBCEditorCompletionProposalPopup = class(BCEditor.CompletionProposal.TBCEditorCompletionProposalPopup);
TBCEditorHighlighter = class(BCEditor.Highlighter.TBCEditorHighlighter);
TBCEditorLeftMargin = class(BCEditor.Properties.TBCEditorLeftMargin);
TBCEditorLines = class(BCEditor.Lines.TBCEditorLines);
TBCEditorTabs = class(BCEditor.Properties.TBCEditorTabs);
TDropData = class(TInterfacedObject, IDataObject, IEnumFORMATETC)
private
FEditor: TCustomBCEditor;
FEnumFormatEtcIndex: Integer;
protected
function Clone(out Enum: IEnumFormatEtc): HResult; stdcall;
function DAdvise(const formatetc: TFormatEtc; advf: Longint;
const advSink: IAdviseSink; out dwConnection: Longint): HResult; stdcall;
function DUnadvise(dwConnection: Longint): HResult; stdcall;
function EnumDAdvise(out enumAdvise: IEnumStatData): HResult; stdcall;
function EnumFormatEtc(dwDirection: Longint; out enumFormatEtc:
IEnumFormatEtc): HResult; stdcall;
function GetCanonicalFormatEtc(const formatetc: TFormatEtc;
out formatetcOut: TFormatEtc): HResult; stdcall;
function GetData(const formatetcIn: TFormatEtc; out medium: TStgMedium):
HResult; stdcall;
function GetDataHere(const formatetc: TFormatEtc; out medium: TStgMedium):
HResult; stdcall;
function Next(celt: Longint; out elt; pceltFetched: PLongint): HResult; stdcall;
function QueryGetData(const formatetc: TFormatEtc): HResult; stdcall;
function Reset(): HResult; stdcall;
function SetData(const formatetc: TFormatEtc; var medium: TStgMedium;
fRelease: BOOL): HResult; stdcall;
function Skip(celt: Longint): HResult; stdcall;
public
constructor Create(const AEditor: TCustomBCEditor);
end;
TClientJob = (cjTokenWidth, cjPaint, cjPaintOverlays,
cjMouseDown, cjMouseDblClk, cjMouseTrplClk, cjMouseMove, cjMouseUp,
cjHint, cjScrolling);
TIdleJob = (ijBuildRows, ijUpdateScrollBars);
TIdleJobs = set of TIdleJob;
TMouseCapture = (mcNone, mcSyncEditButton, mcMarks,
mcLineState, mcCodeFolding, mcText, mcScrolling);
TState = set of (esCaretInvalid, esCodeFoldingInvalid, esScrollBarsInvalid,
esMatchedPairInvalid, esSyncEditInvalid, esSyncEditOverlaysInvalid,
esDoubleBufferInvalid,
esCaretChanged, esFontChanged, esHighlighterChanged, esSelChanged,
esSizeChanged, esSysFontChanged, esTextChanged,
esBuildingRows, esDragging, esPainting, esScrolling, ecProcessingCommand,
esTextUpdated,
esHighlightSearchAllAreas,
esKeyHandled, esWaitForDrag, esMouseDblClk, esCenterCaret);
TOverlay = record
Area: TBCEditorLinesArea;
Style: (osRect, osUnderline, osWaveLine);
end;
TOverlays = class(TList<TOverlay>)
private
FEditor: TCustomBCEditor;
public
function Add(const AValue: TOverlay): Integer;
constructor Create(const AEditor: TCustomBCEditor);
end;
TPaintHelper = class(TObject)
type
TObjectFont = packed record
Handle: HFont;
Style: TFontStyles;
end;
TObjectFonts = class(TList<TObjectFont>)
strict private
FFont: TFont;
procedure SetFont(const AValue: TFont);
public
function Add(const AStyle: TFontStyles): Integer;
procedure Clear();
constructor Create();
destructor Destroy(); override;
property Font: TFont read FFont write SetFont;
end;
strict private
FBackgroundColor: TColor;
FBrush: TBrush;
FForegroundColor: TColor;
FHandle: HDC;
FHandles: TStack<HDC>;
FObjectFonts: TObjectFonts;
FSavedDCs: TStack<Integer>;
FStyle: TFontStyles;
procedure SetBackgroundColor(const AValue: TColor);
procedure SetFont(const AValue: TFont);
procedure SetForegroundColor(const AValue: TColor);
procedure SetStyle(const AValue: TFontStyles);
public
procedure BeginDraw(const AHandle: HDC);
constructor Create(const AFont: TFont);
destructor Destroy(); override;
procedure EndDraw();
function ExtTextOut(X, Y: Integer; Options: Longint;
Rect: TRect; Str: LPCWSTR; Count: Longint; Dx: PInteger): BOOL; {$IFNDEF Debug} inline; {$ENDIF}
function FillRect(const ARect: TRect): BOOL; {$IFNDEF Debug} inline; {$ENDIF}
function FrameRect(const ARect: TRect; AColor: TColor): Integer; {$IFNDEF Debug} inline; {$ENDIF}
function TextHeight(const AText: PChar; const ALength: Integer): Integer;
function TextWidth(const AText: PChar; const ALength: Integer): Integer;
property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor;
property ForegroundColor: TColor read FForegroundColor write SetForegroundColor;
property Font: TFont write SetFont;
property Style: TFontStyles read FStyle write SetStyle;
end;
PPaintVar = ^TPaintVar;
TPaintVar = record
type
TPart = record
type
TPartType = (ptNormal, ptSyncEdit, ptMatchingPair, ptSelection,
ptSearchResult);
public
BeginPosition: TBCEditorLinesPosition;
EndPosition: TBCEditorLinesPosition;
PartType: TPartType;
end;
public
Graphics: TGPGraphics;
LeftMarginBorderBrush: TGPBrush;
LineBackgroundColor: TColor;
LineForegroundColor: TColor;
OverlayIndex: Integer;
OverlayRectBrush: TGPBrush;
OverlayUnderlineBrush: TGPBrush;
Parts: TList<TPart>;
PreviousBackgroundColor: TColor;
PreviousFontStyles: TFontStyles;
PreviousUCC: Boolean;
SearchResultIndex: Integer;
SelArea: TBCEditorLinesArea;
UCCBrush: TGPBrush;
end;
TRow = record
type
TFlags = set of (rfFirstRowOfLine, rfLastRowOfLine, rfHasTabs);
TPart = record
BeginRange: Pointer;
Char: Integer;
Column: Integer;
Left: Integer;
end;
TParts = array of TPart;
public
BeginRange: Pointer;
Char: Integer;
Columns: Integer;
Flags: TFlags;
Length: Integer;
Line: Integer;
Parts: TParts;
Width: Integer;
end;
TRows = class(TList<TRow>)
private
FCaretPosition: TBCEditorRowsPosition;
FEditor: TCustomBCEditor;
FMaxColumns: Integer;
FMaxColumnsRow: Integer;
FMaxWidth: Integer;
FMaxWidthRow: Integer;
function GetCaretPosition(): TBCEditorRowsPosition;
function GetBORPosition(ARow: Integer): TBCEditorLinesPosition;
function GetEORPosition(ARow: Integer): TBCEditorLinesPosition;
function GetFmtText(): string;
function GetMaxColumns(): Integer;
function GetMaxWidth(): Integer;
function GetRowArea(ARow: Integer): TBCEditorLinesArea;
function GetText(ARow: Integer): string;
public
procedure Add(const AFlags: TRow.TFlags; const ALine: Integer;
const AChar, ALength, AColumns, AWidth: Integer;
const ABeginRange: Pointer; const AParts: TRow.TParts);
procedure Clear();
constructor Create(const AEditor: TCustomBCEditor);
procedure Delete(ARow: Integer);
destructor Destroy(); override;
procedure Insert(ARow: Integer;
const AFlags: TRow.TFlags; const ALine: Integer;
const AChar, ALength, AColumns, AWidth: Integer;
const ABeginRange: Pointer; const AParts: TRow.TParts);
property CaretPosition: TBCEditorRowsPosition read GetCaretPosition;
property BORPosition[Row: Integer]: TBCEditorLinesPosition read GetBORPosition;
property EORPosition[Row: Integer]: TBCEditorLinesPosition read GetEORPosition;
property FmtText: string read GetFmtText;
property MaxColumns: Integer read GetMaxColumns;
property MaxWidth: Integer read GetMaxWidth;
property RowArea[Row: Integer]: TBCEditorLinesArea read GetRowArea;
property Text[Row: Integer]: string read GetText; default;
end;
private const
DefaultOptions = [eoDropFiles, eoAutoIndent, eoHighlightAllFoundTexts,
eoHighlightCurrentLine, eoHighlightMatchingPairs, eoMiddleClickScrolling];
DefaultSelectionOptions = [soHighlightWholeLine, soTripleClickLineSelect];
DefaultSyncEditOptions = [seoShowButton, seoCaseSensitive];
DefaultUndoOptions = [uoGroupUndo];
UM_FIND_ALLAREAS = WM_USER;
UM_FIND_WRAPAROUND = WM_USER + 1;
UM_FREE_COMPLETIONPROPOSALPOPUP = WM_USER + 2;
private
FAfterProcessCommand: TBCEditorAfterProcessCommandEvent;
FAllCodeFoldingRanges: TBCEditorCodeFoldingAllRanges;
FBeforeProcessCommand: TBCEditorBeforeProcessCommandEvent;
FBookmarkBitmaps: array[0 .. BCEDITOR_BOOKMARKS - 1] of TGPCachedBitmap;
FBoldDotSignWidth: Integer;
FBorderStyle: TBorderStyle;
FCaretPos: TPoint; // Caret position in pixel - NOT related to CaretPos!
FCaretVisible: Boolean;
FCaretWidth: Integer;
FClientRect: TRect;
FCodeFoldingCollapsedBitmap: TGPCachedBitmap;
FCodeFoldingCollapsedMarkWidth: Integer;
FCodeFoldingEndLineBitmap: TGPCachedBitmap;
FCodeFoldingExpandedBitmap: TGPCachedBitmap;
FCodeFoldingLineBitmap: TGPCachedBitmap;
FCodeFoldingNoneBitmap: TGPCachedBitmap;
FCodeFoldingRect: TRect;
FCodeFoldingWidth: Integer;
FColors: TBCEditorColors;
FCompletionProposal: TBCEditorCompletionProposal;
FCompletionProposalPopup: TBCEditorCompletionProposalPopup;
FDoubleClickTime: Cardinal;
FDoubleBufferBitmap: TBitmap;
FDoubleBufferOverlayBitmap: TBitmap;
FDoubleBufferUpdateRect: TRect;
FFontPitchFixed: Boolean;
FFormWnd: HWND;
FHideSelectionBeforeSearch: Boolean;
FHideScrollBars: Boolean;
FHighlighter: TBCEditorHighlighter;
FCursorPoint: TPoint;
FDlgCtrlID: Integer;
FFindArea: TBCEditorLinesArea;
FFindDialog: TFindDialog;
FFindPosition: TBCEditorLinesPosition;
FFindState: (fsRequested, fsWrappedAround, fsAllAreas);
FFmtLines: Boolean;
FGotoLineDialog: TGotoLineDialog;
FHideSelection: Boolean;
FHintWindow: THintWindow;
FHookedCommandHandlers: TList<TBCEditorHookedCommandHandler>;
FHorzScrollBarDivider: Integer;
FIdleTerminated: Boolean;
FIMEStatus: LPARAM;
FInsertPos: TPoint;
FInsertPosBitmap: TGPCachedBitmap;
FInsertPosCache: TBitmap;
FLastBuiltLine: Integer;
FLastCursorPoint: TPoint;
FLastDoubleClickTime: Cardinal;
FLastSearch: (lsFind, lsReplace);
FLastSearchData: TBCEditorCommandData;
FLeftMargin: TBCEditorLeftMargin;
FLeftMarginBorderWidth: Integer;
FLeftMarginWidth: Integer;
FLineBreakSignWidth: Integer;
FLineHeight: Integer;
FLineNumbersRect: TRect;
FLineNumbersWidth: Integer;
FLines: TBCEditorLines;
FLineStateRect: TRect;
FLineStateWidth: Integer;
FMarksPanelPopupMenu: TPopupMenu;
FMarksPanelRect: TRect;
FMarksPanelWidth: Integer;
FMaxDigitWidth: Integer;
FMinusSignWidth: Integer;
FMouseCapture: TMouseCapture;
FMouseDownPoint: TPoint;
FNoParentNotify: Boolean;
FOldClientRect: TRect;
FOldCurrentLine: Integer;
FOldSelArea: TBCEditorLinesArea;
FOnCaretChanged: TBCEditorCaretChangedEvent;
FOnChange: TNotifyEvent;
FOnCompletionProposalClose: TBCEditorCompletionProposalCloseEvent;
FOnCompletionProposalShow: TBCEditorCompletionProposalShowEvent;
FOnCompletionProposalValidate: TBCEditorCompletionProposalValidateEvent;
FOnFindExecuted: TBCEditorFindExecutedEvent;
FOnFindWrapAround: TBCEditorFindWrapAroundEvent;
FOnHint: TBCEditorHintEvent;
FOnMarksPanelClick: TBCEditorMarksPanelClick;
FOnModified: TNotifyEvent;
FOnReplacePrompt: TBCEditorReplacePromptEvent;
FOnSelChanged: TNotifyEvent;
FOptions: TBCEditorOptions;
FOriginalLines: TBCEditorLines;
FOverlays: TOverlays;
FPaintHelper: TCustomBCEditor.TPaintHelper;
FParentWnd: HWND;
FPendingJobs: TIdleJobs;
FPopupMenu: HMENU;
FReadOnly: Boolean;
FReplaceAction: TBCEditorReplaceAction;
FReplaceDialog: TReplaceDialog;
FRows: TCustomBCEditor.TRows;
FScrollBars: UITypes.TScrollStyle;
FScrollingBitmap: TGPCachedBitmap;
FScrollingBitmapHeight: Integer;
FScrollingBitmapWidth: Integer;
FScrollingEnabled: Boolean;
FScrollingPoint: TPoint;
FScrollingRect: TRect;
FSelectedCaseCycle: TBCEditorCase;
FSelectedCaseText: string;
FSelectionOptions: TBCEditorSelectionOptions;
FSpaceWidth: Integer;
FSpecialCharsNullText: string;
FSpecialCharsSpaceText: string;
FState: TState;
FSyncEditButtonHotBitmap: TGPCachedBitmap;
FSyncEditButtonNormalBitmap: TGPCachedBitmap;
FSyncEditButtonPressedBitmap: TGPCachedBitmap;
FSyncEditButtonRect: TRect;
FSyncEditOptions: TBCEditorSyncEditOptions;
FTabSignWidth: Integer;
FTabs: TBCEditorTabs;
FTextEntryMode: TBCEditorTextEntryMode;
FTextPos: TPoint;
FTextRect: TRect;
FTopRow: Integer;
FUCCVisible: Boolean;
FUsableRows: Integer;
FUpdateCount: Integer;
FVertScrollBarDivider: Integer;
FVisibleRows: Integer;
FWantReturns: Boolean;
FWantTabs: Boolean;
FWheelScrollChars: UINT;
FWindowProducedMessage: Boolean;
FWordWrap: Boolean;
procedure AfterLinesUpdate(Sender: TObject);
procedure AskReplaceText(ASender: TObject; const AArea: TBCEditorLinesArea;
const ABackwards: Boolean; const AReplaceText: string; var AAction: TBCEditorReplaceAction);
function AskSearchWrapAround(const AData: PBCEditorCommandDataFind): Boolean;
procedure BeforeLinesUpdate(Sender: TObject);
procedure BookmarksChanged(ASender: TObject);
procedure BuildRows(const ATerminated: TBCEditorTerminatedFunc; const AEndRow: Integer = -1);
function ClientToLines(const X, Y: Integer; const AForCaret: Boolean = False): TBCEditorLinesPosition; {$IFNDEF Debug} inline; {$ENDIF}
function ClientToRows(const X, Y: Integer; const AForCaret: Boolean = False): TBCEditorRowsPosition;
procedure CMDoubleBufferedChanged(var AMessage: TMessage); message CM_DOUBLEBUFFEREDCHANGED;
procedure CMSysFontChanged(var AMessage: TMessage); message CM_SYSFONTCHANGED;
procedure CaretChanged(ASender: TObject);
function CodeFoldingCollapsableFoldRangeForLine(const ALine: Integer): TBCEditorCodeFoldingRanges.TRange;
function CodeFoldingFoldRangeForLineTo(const ALine: Integer): TBCEditorCodeFoldingRanges.TRange;
procedure CollapseCodeFoldingRange(const ARange: TBCEditorCodeFoldingRanges.TRange);
procedure ColorsChanged(ASender: TObject);
procedure DeleteChar;
procedure DeleteLastWordOrBOL(const ACommand: TBCEditorCommand);
procedure DeleteLine;
procedure DeleteLineFromRows(const ALine: Integer);
procedure DoBackspace();
procedure DoBlockComment;
procedure DoChar(const AData: PBCEditorCommandDataChar);
procedure DoCopyToClipboard();
procedure DoCutToClipboard();
procedure DoDeleteToEOL();
procedure DoDeleteWord();
procedure DoDropOLE(const AData: PBCEditorCommandDataDropOLE);
procedure DoEOF(const ACommand: TBCEditorCommand); {$IFNDEF Debug} inline; {$ENDIF}
procedure DoBOF(const ACommand: TBCEditorCommand); {$IFNDEF Debug} inline; {$ENDIF}
procedure DoEndKey(const ASelectionCommand: Boolean);
function DoFindBackwards(const AData: PBCEditorCommandDataFind): Boolean;
procedure DoFindFirst(const AData: PBCEditorCommandDataFind);
function DoFindForewards(const AData: PBCEditorCommandDataFind): Boolean;
procedure DoHomeKey(const ASelectionCommand: Boolean);
procedure DoInsertText(const AText: string);
procedure DoLineComment();
procedure DoPageKey(const ACommand: TBCEditorCommand);
procedure DoPageTopOrBottom(const ACommand: TBCEditorCommand);
procedure DoPosition(const AData: PBCEditorCommandDataPosition);
procedure DoReplace(const AData: TBCEditorCommandData);
procedure DoReturnKey();
procedure DoScroll(const ACommand: TBCEditorCommand);
procedure DoScrollTo(const AData: TBCEditorCommandData);
procedure DoSelectAll();
procedure DoSelection(const AData: PBCEditorCommandDataSelection);
procedure DoShowFind(const First: Boolean);
procedure DoShowGotoLine();
procedure DoShowReplace();
procedure DoSetBookmark(const ACommand: TBCEditorCommand);
procedure DoTabKey(const ACommand: TBCEditorCommand);
procedure DoText(const AData: PBCEditorCommandDataText);
procedure DoToggleSelectedCase(const ACommand: TBCEditorCommand);
procedure DoUnselect();
procedure DoWordLeft(const ACommand: TBCEditorCommand);
procedure DoWordRight(const ACommand: TBCEditorCommand);
procedure EMCanUndo(var AMessage: TMessage); message EM_CANUNDO;
procedure EMCharFromPos(var AMessage: TMessage); message EM_CHARFROMPOS;
procedure EMEmptyUndoBuffer(var AMessage: TMessage); message EM_EMPTYUNDOBUFFER;
procedure EMFmtLines(var AMessage: TMessage); message EM_FMTLINES;
procedure EMGetFirstVisible(var AMessage: TMessage); message EM_GETFIRSTVISIBLELINE;
procedure EMGetHandle(var AMessage: TMessage); message EM_GETHANDLE;
procedure EMGetIMEStatus(var AMessage: TMessage); message EM_GETIMESTATUS;
procedure EMGetLine(var AMessage: TMessage); message EM_GETLINE;
procedure EMGetLineCount(var AMessage: TMessage); message EM_GETLINECOUNT;
procedure EMGetModify(var AMessage: TMessage); message EM_GETMODIFY;
procedure EMGetRect(var AMessage: TMessage); message EM_GETRECT;
procedure EMGetSel(var AMessage: TMessage); message EM_GETSEL;
procedure EMGetThumb(var AMessage: TMessage); message EM_GETTHUMB;
procedure EMLineFromChar(var AMessage: TMessage); message EM_LINEFROMCHAR;
procedure EMLineIndex(var AMessage: TMessage); message EM_LINEINDEX;
procedure EMLineLength(var AMessage: TMessage); message EM_LINELENGTH;
procedure EMLineScroll(var AMessage: TMessage); message EM_LINESCROLL;
procedure EMPosFromChar(var AMessage: TMessage); message EM_POSFROMCHAR;
procedure EMReplaceSel(var AMessage: TMessage); message EM_REPLACESEL;
procedure EMScroll(var AMessage: TMessage); message EM_SCROLL;
procedure EMScrollCaret(var AMessage: TMessage); message EM_SCROLLCARET;
procedure EMSetIMEStatus(var AMessage: TMessage); message EM_SETIMESTATUS;
procedure EMSetModify(var AMessage: TMessage); message EM_SETMODIFY;
procedure EMSetReadOnly(var AMessage: TMessage); message EM_SETREADONLY;
procedure EMSetSel(var AMessage: TMessage); message EM_SETSEL;
procedure EMSetTabStop(var AMessage: TMessage); message EM_SETTABSTOPS;
procedure EMUndo(var AMessage: TMessage); message EM_UNDO;
procedure ExpandCodeFoldingRange(const ARange: TBCEditorCodeFoldingRanges.TRange);
procedure FindDialogClose(Sender: TObject);
procedure FindDialogFind(Sender: TObject);
procedure FindExecuted(const AData: Pointer);
procedure FontChanged(ASender: TObject);
function GetCanPaste(): Boolean; {$IFNDEF Debug} inline; {$ENDIF}
function GetCanRedo(): Boolean; {$IFNDEF Debug} inline; {$ENDIF}
function GetCanUndo(): Boolean; {$IFNDEF Debug} inline; {$ENDIF}
function GetCaretPos(): TPoint;
function GetCharAt(APos: TPoint): Char; {$IFNDEF Debug} inline; {$ENDIF}
function GetCursor(): TCursor; {$IFNDEF Debug} inline; {$ENDIF}
function GetFindTokenData(const ARow: Integer; var ALeft: Integer;
out ABeginRange: TBCEditorHighlighter.TRange;
out AText: PChar; out ALength, AChar: Integer; out AColumn: Integer): Boolean;
function GetLeadingExpandedLength(const AStr: string; const ABorder: Integer = 0): Integer;
function GetLineIndentLevel(const ALine: Integer): Integer;
function GetModified(): Boolean; {$IFNDEF Debug} inline; {$ENDIF}
function GetSearchResultCount(): Integer; {$IFNDEF Debug} inline; {$ENDIF}
function GetSelLength(): Integer; {$IFNDEF Debug} inline; {$ENDIF}
function GetSelStart(): Integer; {$IFNDEF Debug} inline; {$ENDIF}
function GetSelText(): string;
function GetText(): string; {$IFNDEF Debug} inline; {$ENDIF}
function GetUndoOptions(): TBCEditorUndoOptions;
function GetWordAt(ALinesPos: TPoint): string;
procedure HighlighterChanged(ASender: TObject);
function IndentText(const IndentCount: Integer): string;
procedure Idle();
function IdleTerminated(): Boolean;
procedure InsertLine();
procedure InsertLineIntoRows(const ALine: Integer; const ANewLine: Boolean); overload;
function InsertLineIntoRows(const ATerminated: TBCEditorTerminatedFunc;
const ALine: Integer; const ARow: Integer): Integer; overload;
procedure InvalidateCaret();
procedure InvalidateClient();
procedure InvalidateCodeFolding();
procedure InvalidateOverlays();
procedure InvalidateRect(const ARect: TRect; const AOverlay: Boolean = False); {$IFNDEF Debug} inline; {$ENDIF}
procedure InvalidateRows();
procedure InvalidateScrollBars();
procedure InvalidateSyncEdit();
procedure InvalidateSyncEditButton();
procedure InvalidateSyncEditOverlays();
procedure InvalidateText(); overload;
procedure InvalidateText(const ALine: Integer); overload;
function LeftSpaceCount(const AText: string; AWantTabs: Boolean = False): Integer;
function LeftTrimLength(const AText: string): Integer;
procedure LineDeleting(ASender: TObject; const ALine: Integer);
procedure LineInserted(ASender: TObject; const ALine: Integer);
procedure LinesCleared(ASender: TObject);
procedure LinesChanged();
procedure LinesLoaded(ASender: TObject);
procedure LinesSelChanged(ASender: TObject);
procedure LinesSyncEditChanged(ASender: TObject);
procedure MarksChanged(ASender: TObject);
procedure MatchingPairScanned(const AData: Pointer);
procedure MoveCaretAndSelection(const APosition: TBCEditorLinesPosition; const ASelect: Boolean);
procedure MoveCaretHorizontally(const AColumns: Integer; const ASelect: Boolean);
procedure MoveCaretVertically(const ARows: Integer; const ASelect: Boolean);
function NextWordPosition(const ALinesPosition: TBCEditorLinesPosition): TBCEditorLinesPosition; overload;
procedure NotifyParent(const ANotification: Word); {$IFNDEF Debug} inline; {$ENDIF}
function NotTerminated(): Boolean; inline;
procedure PaintTo(const ADC: HDC; const ARect: TRect; const AOverlays: Boolean = True);
function PreviousWordPosition(const ALinesPosition: TBCEditorLinesPosition): TBCEditorLinesPosition; overload;
function ProcessClient(const AJob: TClientJob;
const ADC: HDC; const APaintVar: PPaintVar; const AClipRect: TRect;
const AButton: TMouseButton; const AShift: TShiftState; AMousePoint: TPoint;
const APaintOverlays: Boolean = True): Boolean;
procedure ProcessIdle(const AJob: TIdleJob);
function ProcessToken(const AJob: TClientJob;
const APaintVar: PPaintVar; const AClipRect: TRect;
const AButton: TMouseButton; const AShift: TShiftState; const AMousePoint: TPoint;
var ARect: TRect;
const ALinesPosition: TBCEditorLinesPosition;
const ARowsPosition: TBCEditorRowsPosition;
const AText: PChar; const ALength: Integer;
const AToken: TBCEditorHighlighter.PTokenFind = nil;
const ARange: TBCEditorCodeFoldingRanges.TRange = nil): Boolean;
procedure ReplaceDialogFind(ASender: TObject);
procedure ReplaceDialogReplace(ASender: TObject);
procedure ReplaceExecuted(const AData: Pointer);
function RowsToClient(ARowsPosition: TBCEditorRowsPosition;
const AVisibleOnly: Boolean = False): TPoint;
function RowsToLines(const ARowsPosition: TBCEditorRowsPosition): TBCEditorLinesPosition;
function RowsToText(ARowsPosition: TBCEditorRowsPosition;
const AVisibleOnly: Boolean = False): TPoint;
procedure ScanCodeFolding();
procedure ScrollTo(AValue: TPoint); overload; inline;
procedure ScrollTo(AValue: TPoint; const AAlignToRow: Boolean); overload;
procedure ScrollTo(AX, AY: Integer); overload; inline;
procedure ScrollToCaret();
procedure SetBorderStyle(const AValue: TBorderStyle);
procedure SetCaretPos(const AValue: TPoint);
procedure SetColors(AValue: TBCEditorColors);
procedure SetCursor(AValue: TCursor);
procedure SetHideScrollBars(AValue: Boolean);
procedure SetHideSelection(AValue: Boolean); {$IFNDEF Debug} inline; {$ENDIF}
procedure SetInsertPos(AValue: TPoint);
procedure SetLeftMargin(const AValue: TBCEditorLeftMargin);
procedure SetLinesBeginRanges(const ALine: Integer);
procedure SetModified(const AValue: Boolean);
procedure SetMouseCapture(const AValue: TMouseCapture);
procedure SetOptions(const AValue: TBCEditorOptions);
procedure SetReadOnly(const AValue: Boolean);
procedure SetScrollBars(const AValue: UITypes.TScrollStyle);
procedure SetSelectedWord;
procedure SetSelectionOptions(AValue: TBCEditorSelectionOptions);
procedure SetSelLength(AValue: Integer);
procedure SetSelStart(AValue: Integer);
procedure SetSelText(const AValue: string);
procedure SetSyncEditOptions(AValue: TBCEditorSyncEditOptions);
procedure SetTabs(const AValue: TBCEditorTabs);
procedure SetText(const AValue: string); {$IFNDEF Debug} inline; {$ENDIF}
procedure SetTextPos(const AValue: TPoint); overload;
procedure SetTextPos(AX, AY: Integer); overload; inline;
procedure SetTopRow(const AValue: Integer);
procedure SetUndoOptions(AOptions: TBCEditorUndoOptions);
procedure SetWantReturns(const AValue: Boolean); {$IFNDEF Debug} inline; {$ENDIF}
procedure SetWordBlock(const ALinesPosition: TBCEditorLinesPosition);
procedure SetWordWrap(const AValue: Boolean);
procedure SyncEditActivated(const AData: Pointer);
procedure SyncEditChecked(const AData: Pointer);
procedure TabsChanged(ASender: TObject);
function TokenColumns(const AText: PChar; const ALength, AColumn: Integer): Integer; {$IFNDEF Debug} inline; {$ENDIF}
function TokenWidth(const AText: PChar; const ALength: Integer;
const AColumn: Integer; const AToken: TBCEditorHighlighter.TTokenFind): Integer; // inline takes the double time. Why???
procedure UMFindAllAreas(var AMessage: TMessage); message UM_FIND_ALLAREAS;
procedure UMFindWrapAround(var AMessage: TMessage); message UM_FIND_WRAPAROUND;
procedure UMFreeCompletionProposalPopup(var AMessage: TMessage); message UM_FREE_COMPLETIONPROPOSALPOPUP;
procedure UpdateCaret();
procedure UpdateCursor(); {$IFNDEF Debug} inline; {$ENDIF}
procedure UpdateLineInRows(const ALine: Integer);
procedure UpdateMetrics();
procedure UpdateScrollBars();
procedure WMClear(var AMessage: TWMClear); message WM_CLEAR;
procedure WMCommand(var AMessage: TWMCommand); message WM_COMMAND;
procedure WMContextMenu(var AMessage: TWMContextMenu); message WM_CONTEXTMENU;
procedure WMCopy(var AMessage: TWMCopy); message WM_COPY;
procedure WMCut(var AMessage: TWMCut); message WM_CUT;
procedure WMEraseBkgnd(var AMessage: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure WMGetDlgCode(var AMessage: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMGetText(var AMessage: TWMGetText); message WM_GETTEXT;
procedure WMGetTextLength(var AMessage: TWMGetTextLength); message WM_GETTEXTLENGTH;
procedure WMHScroll(var AMessage: TWMScroll); message WM_HSCROLL;
procedure WMIMEChar(var AMessage: TMessage); message WM_IME_CHAR;
procedure WMIMEComposition(var AMessage: TMessage); message WM_IME_COMPOSITION;
procedure WMIMENotify(var AMessage: TMessage); message WM_IME_NOTIFY;
procedure WMKillFocus(var AMessage: TWMKillFocus); message WM_KILLFOCUS;
procedure WMMouseHWheel(var AMessage: TWMMouseWheel); message WM_MOUSEHWHEEL;
procedure WMNCPaint(var AMessage: TWMNCPaint); message WM_NCPAINT;
procedure WMPaint(var AMessage: TWMPaint); message WM_PAINT;
procedure WMPaste(var AMessage: TWMPaste); message WM_PASTE;
procedure WMPrint(var AMessage: TWMPrint); message WM_PRINT;
procedure WMSetCursor(var AMessage: TWMSetCursor); message WM_SETCURSOR;
procedure WMSetFocus(var AMessage: TWMSetFocus); message WM_SETFOCUS;
procedure WMSettingChange(var AMessage: TWMSettingChange); message WM_SETTINGCHANGE;
procedure WMSetText(var AMessage: TWMSetText); message WM_SETTEXT;
procedure WMStyleChanged(var AMessage: TWMStyleChanged); message WM_STYLECHANGED;
procedure WMSysChar(var AMessage: TMessage); message WM_SYSCHAR;
procedure WMTimer(var Msg: TWMTimer); message WM_TIMER;
procedure WMUndo(var AMessage: TWMUndo); message WM_UNDO;
procedure WMVScroll(var AMessage: TWMScroll); message WM_VSCROLL;
protected // IDropSource
function GiveFeedback(dwEffect: Longint): HResult; stdcall;
function QueryContinueDrag(fEscapePressed: BOOL; grfKeyState: Longint): HResult; stdcall;
protected // IDropTarget
function DragEnter(const dataObj: IDataObject; grfKeyState: Longint;
pt: TPoint; var dwEffect: Longint): HResult; stdcall;
function DragLeave(): HResult; stdcall;
function DragOver(grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; reintroduce; overload; stdcall;
function Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint;
var dwEffect: Longint): HResult; stdcall;
protected
procedure Change(); virtual;
procedure ChangeScale(M, D: Integer); override;
procedure ClearUndo();
procedure CollapseCodeFoldingLevel(const AFirstLevel: Integer; const ALastLevel: Integer);
function CollapseCodeFoldingLines(const AFirstLine: Integer = -1; const ALastLine: Integer = -1): Integer;
function CreateLines(): BCEditor.Lines.TBCEditorLines;
procedure CreateParams(var AParams: TCreateParams); override;
procedure CreateWnd(); override;
function DeleteBookmark(const ALine: Integer; const AIndex: Integer): Boolean; overload;
procedure DestroyWnd(); override;
procedure DoBlockIndent(const ACommand: TBCEditorCommand);
procedure DoCompletionProposal(); virtual;
function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override;
function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override;
procedure DoSyncEdit();
procedure DoTripleClick;
procedure DragCanceled(); override;
procedure DragOver(ASource: TObject; X, Y: Integer; AState: TDragState; var AAccept: Boolean); overload; override;
procedure ExpandCodeFoldingLevel(const AFirstLevel: Integer; const ALastLevel: Integer);
function ExpandCodeFoldingLines(const AFirstLine: Integer = -1; const ALastLine: Integer = -1): Integer;
function GetBookmark(const AIndex: Integer; var ALinesPosition: TBCEditorLinesPosition): Boolean;
function GetMarks(): TBCEditorLines.TMarkList; inline;
procedure GotoBookmark(const AIndex: Integer);
procedure GotoNextBookmark;
procedure GotoPreviousBookmark;
procedure InvalidateMatchingPair();
function IsCommentChar(const AChar: Char): Boolean;
function IsEmptyChar(const AChar: Char): Boolean; {$IFNDEF Debug} inline; {$ENDIF}
function IsWordBreakChar(const AChar: Char): Boolean; {$IFNDEF Debug} inline; {$ENDIF}
procedure KeyDown(var AKey: Word; AShift: TShiftState); override;
procedure KeyPress(var AKey: Char); override;
procedure LeftMarginChanged(ASender: TObject);
function LinesToRows(const ALinesPosition: TBCEditorLinesPosition): TBCEditorRowsPosition;
procedure LineUpdated(ASender: TObject; const ALine: Integer); virtual;
procedure MouseDown(AButton: TMouseButton; AShift: TShiftState; X, Y: Integer); override;
procedure MouseMove(AShift: TShiftState; X, Y: Integer); override;
procedure MouseUp(AButton: TMouseButton; AShift: TShiftState; X, Y: Integer); override;
procedure Paint(); override;
procedure ReadState(Reader: TReader); override;
procedure Resize(); override;
procedure ScanCodeFoldingRanges(); virtual;
procedure SetBookmark(const AIndex: Integer; const ALinesPosition: TBCEditorLinesPosition);
procedure SetCaretAndSelection(ACaretPosition: TBCEditorLinesPosition;
ASelArea: TBCEditorLinesArea);
procedure SetLineColor(const ALine: Integer; const AForegroundColor, ABackgroundColor: TColor);
procedure SetMark(const AIndex: Integer; const ALinesPosition: TBCEditorLinesPosition;
const AImageIndex: Integer);
procedure SetParent(AParent: TWinControl); override;
procedure SetUndoOption(const AOption: TBCEditorUndoOption; const AEnabled: Boolean);
procedure SetUpdateState(AUpdating: Boolean); virtual;
function SplitTextIntoWords(AStringList: TStrings; const ACaseSensitive: Boolean): string;
function WordBegin(const ALinesPosition: TBCEditorLinesPosition): TBCEditorLinesPosition; overload;
function WordEnd(): TBCEditorLinesPosition; overload; {$IFNDEF Debug} inline; {$ENDIF}
function WordEnd(const ALinesPosition: TBCEditorLinesPosition): TBCEditorLinesPosition; overload;
property AllCodeFoldingRanges: TBCEditorCodeFoldingAllRanges read FAllCodeFoldingRanges;
property AfterProcessCommand: TBCEditorAfterProcessCommandEvent read FAfterProcessCommand write FAfterProcessCommand;
property BeforeProcessCommand: TBCEditorBeforeProcessCommandEvent read FBeforeProcessCommand write FBeforeProcessCommand;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property CanPaste: Boolean read GetCanPaste;
property CanRedo: Boolean read GetCanRedo;
property CanUndo: Boolean read GetCanUndo;
property CaretPos: TPoint read GetCaretPos write SetCaretPos;
property CharAt[Pos: TPoint]: Char read GetCharAt;
property Colors: TBCEditorColors read FColors write SetColors;
property CompletionProposal: TBCEditorCompletionProposal read FCompletionProposal write FCompletionProposal;
property Cursor: TCursor read GetCursor write SetCursor;
property HideScrollBars: Boolean read FHideScrollBars write SetHideScrollBars default True;
property HideSelection: Boolean read FHideSelection write SetHideSelection default True;
property Highlighter: TBCEditorHighlighter read FHighlighter;
property InsertPos: TPoint read FInsertPos write SetInsertPos;
property LeftMargin: TBCEditorLeftMargin read FLeftMargin write SetLeftMargin;
property LineHeight: Integer read FLineHeight;
property Lines: TBCEditorLines read FLines;
property Marks: TBCEditorLines.TMarkList read GetMarks;
property MarksPanelPopupMenu: TPopupMenu read FMarksPanelPopupMenu write FMarksPanelPopupMenu;
property Modified: Boolean read GetModified write SetModified;
property MouseCapture: TMouseCapture read FMouseCapture write SetMouseCapture;
property OnCaretChanged: TBCEditorCaretChangedEvent read FOnCaretChanged write FOnCaretChanged;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnCompletionProposalClose: TBCEditorCompletionProposalCloseEvent read FOnCompletionProposalClose write FOnCompletionProposalClose;
property OnCompletionProposalShow: TBCEditorCompletionProposalShowEvent read FOnCompletionProposalShow write FOnCompletionProposalShow;
property OnCompletionProposalValidate: TBCEditorCompletionProposalValidateEvent read FOnCompletionProposalValidate write FOnCompletionProposalValidate;
property OnFindExecuted: TBCEditorFindExecutedEvent read FOnFindExecuted write FOnFindExecuted;
property OnFindWrapAround: TBCEditorFindWrapAroundEvent read FOnFindWrapAround write FOnFindWrapAround;
property OnHint: TBCEditorHintEvent read FOnHint write FOnHint;
property OnMarksPanelClick: TBCEditorMarksPanelClick read FOnMarksPanelClick write FOnMarksPanelClick;
property OnModified: TNotifyEvent read FOnModified write FOnModified;
property OnReplacePrompt: TBCEditorReplacePromptEvent read FOnReplacePrompt write FOnReplacePrompt;
property OnSelChanged: TNotifyEvent read FOnSelChanged write FOnSelChanged;
property Options: TBCEditorOptions read FOptions write SetOptions default DefaultOptions;
property PaintHelper: TCustomBCEditor.TPaintHelper read FPaintHelper;
property ParentColor default False;
property ParentFont default False;
property ReadOnly: Boolean read FReadOnly write SetReadOnly default False;
property ScrollBars: UITypes.TScrollStyle read FScrollBars write SetScrollBars default ssBoth;
property SearchResultCount: Integer read GetSearchResultCount;
property SelectionOptions: TBCEditorSelectionOptions read FSelectionOptions write SetSelectionOptions default DefaultSelectionOptions;
property SelLength: Integer read GetSelLength write SetSelLength;
property SelStart: Integer read GetSelStart write SetSelStart;
property SelText: string read GetSelText write SetSelText;
property SyncEditOptions: TBCEditorSyncEditOptions read FSyncEditOptions write SetSyncEditOptions default DefaultSyncEditOptions;
property Tabs: TBCEditorTabs read FTabs write SetTabs;
property TabStop default True;
property Text: string read GetText write SetText;
property TextEntryMode: TBCEditorTextEntryMode read FTextEntryMode write FTextEntryMode default temInsert;
property TextPos: TPoint read FTextPos write ScrollTo;
property TextRect: TRect read FTextRect;
property TopRow: Integer read FTopRow write SetTopRow;
property UndoOptions: TBCEditorUndoOptions read GetUndoOptions write SetUndoOptions default DefaultUndoOptions;
property UpdateCount: Integer read FUpdateCount;
property VisibleRows: Integer read FVisibleRows;
property WantReturns: Boolean read FWantReturns write SetWantReturns default True;
property WantTabs: Boolean read FWantTabs write FWantTabs default True;
property WordAt[ATextPos: TPoint]: string read GetWordAt;
property WordWrap: Boolean read FWordWrap write SetWordWrap default False;
public
procedure ActivateHint(const X, Y: Integer; const AHint: string);
procedure AddHighlighterKeywords(AStringList: TStrings);
procedure Assign(ASource: TPersistent); override;
procedure BeginUndoBlock(); deprecated 'Use Lines.EndUpdate()'; // 2017-07-12
procedure BeginUpdate();
function CharIndexToPos(const ACharIndex: Integer): TPoint; {$IFNDEF Debug} inline; {$ENDIF}
procedure Clear(); virtual; deprecated 'Use Lines.Clear()';
function ClientToPos(const X, Y: Integer): TPoint; {$IFNDEF Debug} inline; {$ENDIF}
function ClientToText(const X, Y: Integer): TPoint; deprecated 'Use ClientToPos'; // 2017-05-13
function CharAtCursor(): Char; deprecated 'Use CharAt[CaretPos]'; // 2017-04-05
procedure CommandProcessor(ACommand: TBCEditorCommand; AChar: Char; AData: Pointer); deprecated 'Use ProcessCommand'; // 2017-08-11
procedure CopyToClipboard();
constructor Create(AOwner: TComponent); override;
procedure CutToClipboard();
destructor Destroy(); override;
procedure DoRedo(); deprecated 'Use Redo()'; // 2017-02-12
procedure DoUndo(); deprecated 'Use Undo()'; // 2017-02-12
procedure DragDrop(ASource: TObject; X, Y: Integer); override;
procedure EndUndoBlock(); deprecated 'Use Lines.EndUpdate()'; // 2017-07-12
procedure EndUpdate();
function ExecuteAction(Action: TBasicAction): Boolean; override;
procedure ExportToHTML(const AFileName: string; const ACharSet: string = ''; AEncoding: TEncoding = nil); overload;
procedure ExportToHTML(AStream: TStream; const ACharSet: string = ''; AEncoding: TEncoding = nil); overload;
procedure LoadFromFile(const AFileName: string; AEncoding: TEncoding = nil); deprecated 'Use Lines.LoadFromFile'; // 2017-03-10
procedure LoadFromStream(AStream: TStream; AEncoding: TEncoding = nil); deprecated 'Use Lines.LoadFromStream'; // 2017-03-10
procedure PasteFromClipboard();
function PosToCharIndex(const APos: TPoint): Integer;
function ProcessCommand(const ACommand: TBCEditorCommand; const AData: TBCEditorCommandData = nil): Boolean;
procedure Redo(); {$IFNDEF Debug} inline; {$ENDIF}
procedure RegisterCommandHandler(const AProc: Pointer; const AHandlerData: Pointer); overload;
procedure RegisterCommandHandler(const AProc: TBCEditorHookedCommandObjectProc); overload;
procedure SaveToFile(const AFileName: string; AEncoding: TEncoding = nil);
procedure SaveToStream(AStream: TStream; AEncoding: TEncoding = nil);
procedure SelectAll();
function SelectedText(): string; deprecated 'Use SelText'; // 2017-03-16
function SelectionAvailable: Boolean; deprecated 'Use SelLength <> 0'; // 2017-07-16
procedure SetFocus(); override;
procedure Sort(const ASortOrder: TBCEditorSortOrder = soAsc; const ACaseSensitive: Boolean = False);
function TextBetween(const ABeginPosition, AEndPosition: TBCEditorLinesPosition): string; deprecated 'Use SelStart := PosToCharIndex(BeginPos); SelLength := SelStart + PosToCharIndex(EndPos); Result := SelText;'; // 2017-07-23
function TextCaretPosition(): TBCEditorLinesPosition; deprecated 'Use CaretPos'; // 2017-02-12
procedure ToggleSelectedCase(const ACase: TBCEditorCase = cNone);
procedure Undo(); {$IFNDEF Debug} inline; {$ENDIF}
function UpdateAction(Action: TBasicAction): Boolean; override;
procedure UnregisterCommandHandler(const AProc: Pointer;
const AHandlerData: Pointer); overload;
procedure UnregisterCommandHandler(const AProc: TBCEditorHookedCommandObjectProc); overload;
procedure WndProc(var AMessage: TMessage); override;
function WordAtCursor(): string; deprecated 'Use WordAt[CaretPos]'; // 2017-03-13
end;
TBCEditor = class(TCustomBCEditor)
public
property CanPaste;
property CanRedo;
property CanUndo;
property Canvas;
property CaretPos;
property CharAt;
property Highlighter;
property InsertPos;
property Lines;
property Marks;
property Modified;
property SearchResultCount;
property SelLength;
property SelStart;
property SelText;
property Text;
property TextEntryMode;
property WordAt;
published
property AfterProcessCommand;
property Align;
property Anchors;
property BeforeProcessCommand;
property BorderStyle;
property Color default clWindow;
property Colors;
property CompletionProposal;
property Constraints;
property Ctl3D;
property DoubleBuffered default True;
property Enabled;
property Font;
property Height;
property HideScrollBars;
property HideSelection;
property ImeMode;
property ImeName;
property LeftMargin;
property OnCaretChanged;
property OnChange;
property OnClick;
property OnCompletionProposalClose;
property OnCompletionProposalShow;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnHint;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMarksPanelClick;
property OnModified;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnReplacePrompt;
property OnSelChanged;
property OnStartDock;
property Options;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property SelectionOptions;
property ShowHint;
property SyncEditOptions;
property TabOrder;
property Tabs;
property TabStop;
property Tag;
property UndoOptions;
property Visible;
property WantTabs;
property WantReturns;
property Width;
property WordWrap;
end;
EBCEditorBaseException = class(Exception);
implementation {***************************************************************}
{$R BCEditor.res}
uses
ShellAPI, Imm, CommCtrl,
Math, Types, Character, RegularExpressions, ComObj, SysConst,
Clipbrd, Themes, ImgList,
BCEditor.Language, BCEditor.ExportHTML;
resourcestring
SBCEditorLineIsNotVisible = 'Line %d is not visible';
SBCEditorOverlayInvalidArea = 'Overlay area invalid';
SBCEditorOverlayOverlap = 'Overlay overlap';
type
TUnprotectedWinControl = class(TWinControl);
const
InvalidRect: TRect = ( Left: -1; Top: -1; Right: -1; Bottom: -1 );
InvalidPos: TPoint = ( X: -1; Y: -1 );
tiCodeFolding = 0;
tiShowHint = 1;
tiScrolling = 2;
tiScroll = 3;
tiIdle = 4;
tiCompletionProposal = 5;
GRowToInsert = -2;
GClientRefreshTime = 40 {ms}; // Time between two client area refreshs
var
GLineWidth: Integer;
GImmEnabled: Boolean;
GPadding: Integer;
function EnumFontsFamiliesProc(var lpelf: TEnumLogFont; var lpntm: TNewTextMetric;
FontType: Integer; lParam: LPARAM): Integer; stdcall;
begin;
Result := Integer(lpelf.elfLogFont.lfPitchAndFamily and FIXED_PITCH <> 0);
end;
{ TCustomBCEditor.TDropData ***************************************************}
function TCustomBCEditor.TDropData.Clone(out Enum: IEnumFormatEtc): HResult;
begin
Enum := TDropData.Create(FEditor);
Result := S_OK;
end;
constructor TCustomBCEditor.TDropData.Create(const AEditor: TCustomBCEditor);
begin
inherited Create();
FEditor := AEditor;
end;
function TCustomBCEditor.TDropData.DAdvise(const formatetc: TFormatEtc; advf: Longint;
const advSink: IAdviseSink; out dwConnection: Longint): HResult;
begin
Result := OLE_E_ADVISENOTSUPPORTED;
end;
function TCustomBCEditor.TDropData.DUnadvise(dwConnection: Longint): HResult;
begin
Result := OLE_E_ADVISENOTSUPPORTED;
end;
function TCustomBCEditor.TDropData.EnumDAdvise(out enumAdvise: IEnumStatData): HResult;
begin
Result := OLE_E_ADVISENOTSUPPORTED;
end;
function TCustomBCEditor.TDropData.EnumFormatEtc(dwDirection: Longint; out enumFormatEtc:
IEnumFormatEtc): HResult;
begin
case (dwDirection) of
DATADIR_GET:
begin
enumFormatEtc := Self;
Result := S_OK;
end;
else
raise ERangeError.Create(SRangeError);
end;
end;
function TCustomBCEditor.TDropData.GetCanonicalFormatEtc(const formatetc: TFormatEtc;
out formatetcOut: TFormatEtc): HResult;
begin
MoveMemory(@formatetcOut, @formatetc, SizeOf(formatetc));
formatetcOut.ptd := nil;
Result := DATA_S_SAMEFORMATETC;
end;
function TCustomBCEditor.TDropData.GetData(const formatetcIn: TFormatEtc; out medium: TStgMedium):
HResult;
var
LText: string;
begin
if (formatetcin.lindex <> -1) then
Result := DV_E_LINDEX
else if (formatetcin.tymed <> TYMED_HGLOBAL) then
Result := DV_E_TYMED
else
begin
Result := S_OK;
case (formatetcin.cfFormat) of
CF_UNICODETEXT: LText := FEditor.SelText;
else Result := DV_E_FORMATETC;
end;
if (Result = S_OK) then
begin
FillChar(medium, SizeOf(medium), 0);
medium.tymed := TYMED_HGLOBAL;
medium.hGlobal := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, SizeOf(LText[1]) * Length(LText));
MoveMemory(GlobalLock(medium.hGlobal), PChar(LText), Length(LText) * SizeOf(LText[1]));
end;
end;
end;
function TCustomBCEditor.TDropData.GetDataHere(const formatetc: TFormatEtc; out medium: TStgMedium):
HResult;
var
LText: string;
begin
LText := FEditor.SelText;
if (formatetc.lindex <> -1) then
Result := DV_E_LINDEX
else if (formatetc.tymed <> TYMED_HGLOBAL) then
Result := DV_E_TYMED
else if (GlobalSize(medium.hGlobal) < SIZE_T(Length(LText) * SizeOf(LText[1]))) then
Result := STG_E_MEDIUMFULL
else
begin
MoveMemory(GlobalLock(medium.hGlobal), PChar(LText), Length(LText) * SizeOf(LText[1]));
Result := S_OK;
end;
end;
function TCustomBCEditor.TDropData.Next(celt: Longint; out elt; pceltFetched: PLongint): HResult;
type
TFormatEtcArray2 = array [0 .. $FFFF] of FORMATETC;
var
Formats: ^TFormatEtcArray2;
begin
if ((celt = 0) or (celt > 1) and not Assigned(pceltFetched)
or (FEnumFormatEtcIndex = 1)) then
Result := S_FALSE
else
begin
Formats := @elt;
case (FEnumFormatEtcIndex) of
0:
begin
Formats^[0].cfFormat := CF_UNICODETEXT;
Formats^[0].ptd := nil;
Formats^[0].dwAspect := DVASPECT_CONTENT;
Formats^[0].lindex := -1;
Formats^[0].tymed := TYMED_HGLOBAL;
end;
else
raise ERangeError.Create('Index: ' + IntToStr(FEnumFormatEtcIndex));
end;
Inc(FEnumFormatEtcIndex);
if (Assigned(pceltFetched)) then
Inc(pceltFetched^);
if (celt = 1) then
Result := S_OK
else
Result := Next(celt - 1, Formats^[1], pceltFetched);
end;
end;
function TCustomBCEditor.TDropData.QueryGetData(const formatetc: TFormatEtc): HResult;
var
LFormat: TFormatEtc;
begin
if (formatetc.lindex <> -1) then
Result := DV_E_LINDEX
else if (formatetc.tymed <> TYMED_HGLOBAL) then
Result := DV_E_TYMED
else
begin
Reset();
repeat
Result := Next(1, LFormat, nil);
until ((Result <> S_OK) or (LFormat.cfFormat = formatetc.cfFormat));
if (Result = S_FALSE) then
Result := DV_E_FORMATETC;
end;
end;
function TCustomBCEditor.TDropData.Reset(): HResult;
begin
FEnumFormatEtcIndex := 0;
Result := S_OK;
end;
function TCustomBCEditor.TDropData.SetData(const formatetc: TFormatEtc; var medium: TStgMedium;
fRelease: BOOL): HResult;
begin
Result := E_FAIL;
end;
function TCustomBCEditor.TDropData.Skip(celt: Longint): HResult;
begin
Result := S_FALSE;
end;
{ TCustomBCEditor.TOverlays ***************************************************}
function TCustomBCEditor.TOverlays.Add(const AValue: TOverlay): Integer;
var
LIndex: Integer;
begin
LIndex := 0;
while ((LIndex < Count) and (Items[LIndex].Area.BeginPosition < AValue.Area.BeginPosition)) do
Inc(LIndex);
if ((AValue.Area.BeginPosition.Line <> AValue.Area.EndPosition.Line)
or (AValue.Area.BeginPosition.Char < 0)
or (AValue.Area.EndPosition.Char < AValue.Area.BeginPosition.Char)
or (AValue.Area.EndPosition.Char > Length(FEditor.FLines.Items[AValue.Area.EndPosition.Line].Text))) then
raise ERangeError.Create(SBCEditorOverlayInvalidArea);
if ((LIndex > 0) and (Items[LIndex - 1].Area.EndPosition > AValue.Area.BeginPosition)) then
raise ERangeError.Create(SBCEditorOverlayOverlap);
Insert(LIndex, AValue);
Result := LIndex;
end;
constructor TCustomBCEditor.TOverlays.Create(const AEditor: TCustomBCEditor);
begin
inherited Create();
FEditor := AEditor;
end;
{ TCustomBCEditor.TPaintHelper.TObjectFonts *******************************************}
function TCustomBCEditor.TPaintHelper.TObjectFonts.Add(const AStyle: TFontStyles): Integer;
const
CBolds: array [Boolean] of Integer = (400, 700);
var
LFont: TObjectFont;
LIndex: Integer;
LLogFont: TLogFont;
begin
Result := -1;
for LIndex := 0 to Count - 1 do
if (Items[LIndex].Style = AStyle) then
Result := LIndex;
if (Result < 0) then
begin
GetObject(FFont.Handle, SizeOf(LLogFont), @LLogFont);
LLogFont.lfWeight := CBolds[fsBold in AStyle];
LLogFont.lfItalic := Ord(BOOL(fsItalic in AStyle));
LLogFont.lfUnderline := Ord(BOOL(fsUnderline in AStyle));
LLogFont.lfStrikeOut := Ord(BOOL(fsStrikeOut in AStyle));
StrCopy(@LLogFont.lfFaceName[0], PChar(FFont.Name));
LFont.Handle := CreateFontIndirect(LLogFont);
LFont.Style := AStyle;
Result := inherited Add(LFont);
end;
end;
procedure TCustomBCEditor.TPaintHelper.TObjectFonts.Clear();
var
LIndex: Integer;
begin
for LIndex := 0 to Count - 1 do
DeleteObject(Items[LIndex].Handle);
inherited;
end;
constructor TCustomBCEditor.TPaintHelper.TObjectFonts.Create();
begin
inherited;
FFont := nil;
end;
destructor TCustomBCEditor.TPaintHelper.TObjectFonts.Destroy();
begin
Clear();
inherited;
end;
procedure TCustomBCEditor.TPaintHelper.TObjectFonts.SetFont(const AValue: TFont);
begin
if (not Assigned(FFont)
or (AValue.Name <> FFont.Name)
or (AValue.Size <> FFont.Size)) then
begin
FFont := AValue;
Clear();
end;
end;
{ TCustomBCEditor.TPaintHelper ********************************************************}
procedure TCustomBCEditor.TPaintHelper.BeginDraw(const AHandle: HDC);
begin
Assert(AHandle <> 0);
FHandles.Push(FHandle);
FSavedDCs.Push(SaveDC(FHandle));
FHandle := AHandle;
SelectObject(FHandle, FObjectFonts.Items[FObjectFonts.Add(FStyle)].Handle);
SetTextColor(FHandle, ColorToRGB(FForegroundColor));
SetBkColor(FHandle, ColorToRGB(FBackgroundColor));
SetBkMode(FHandle, TRANSPARENT);
end;
constructor TCustomBCEditor.TPaintHelper.Create(const AFont: TFont);
begin
inherited Create();
FBackgroundColor := clWindow;
FBrush := TBrush.Create();
FForegroundColor := clWindowText;
FHandle := 0;
FHandles := TStack<HDC>.Create();
FObjectFonts := TObjectFonts.Create();
FSavedDCs := TStack<Integer>.Create();
FStyle := [];
SetFont(AFont);
end;
destructor TCustomBCEditor.TPaintHelper.Destroy();
begin
FBrush.Free();
FHandles.Free();
FObjectFonts.Free();
FSavedDCs.Free();
inherited;
end;
procedure TCustomBCEditor.TPaintHelper.EndDraw();
begin
Assert(FHandles.Count > 0);
FHandle := FHandles.Pop();
RestoreDC(FHandle, FSavedDCs.Pop());
end;
function TCustomBCEditor.TPaintHelper.ExtTextOut(X, Y: Integer; Options: Longint;
Rect: TRect; Str: LPCWSTR; Count: Longint; Dx: PInteger): BOOL;
begin
Assert(FHandle <> 0);
Result := Windows.ExtTextOut(FHandle, X, Y, Options, @Rect, Str, Count, Dx);
end;
function TCustomBCEditor.TPaintHelper.FillRect(const ARect: TRect): BOOL;
begin
Assert(FHandle <> 0);
Result := Windows.ExtTextOut(FHandle, 0, 0, ETO_OPAQUE, ARect, '', 0, nil);
end;
function TCustomBCEditor.TPaintHelper.FrameRect(const ARect: TRect; AColor: TColor): Integer;
begin
FBrush.Color := AColor;
Result := Windows.FrameRect(FHandle, ARect, FBrush.Handle);
end;
procedure TCustomBCEditor.TPaintHelper.SetBackgroundColor(const AValue: TColor);
begin
if (AValue <> FBackgroundColor) then
begin
FBackgroundColor := AValue;
if (FHandle <> 0) then
SetBkColor(FHandle, ColorToRGB(FBackgroundColor));
end;
end;
procedure TCustomBCEditor.TPaintHelper.SetFont(const AValue: TFont);
begin
Assert(Assigned(AValue));
FObjectFonts.Font := AValue;
ForegroundColor := AValue.Color;
Style := AValue.Style;
end;
procedure TCustomBCEditor.TPaintHelper.SetForegroundColor(const AValue: TColor);
begin
if (AValue <> FForegroundColor) then
begin
FForegroundColor := AValue;
if (FHandle <> 0) then
SetTextColor(FHandle, ColorToRGB(FForegroundColor));
end;
end;
procedure TCustomBCEditor.TPaintHelper.SetStyle(const AValue: TFontStyles);
begin
if (AValue <> FStyle) then
begin
FStyle := AValue;
if (FHandle <> 0) then
SelectObject(FHandle, FObjectFonts.Items[FObjectFonts.Add(FStyle)].Handle);
end;
end;
function TCustomBCEditor.TPaintHelper.TextHeight(const AText: PChar; const ALength: Integer): Integer;
var
LSize: TSize;
begin
Assert(FHandle <> 0);
if (not GetTextExtentPoint32(FHandle, AText, ALength, LSize)) then
RaiseLastOSError();
Result := LSize.cy;
end;
function TCustomBCEditor.TPaintHelper.TextWidth(const AText: PChar; const ALength: Integer): Integer;
var
LSize: TSize;
begin
Assert(FHandle <> 0);
if (not GetTextExtentPoint32(FHandle, AText, ALength, LSize)) then
RaiseLastOSError();
Result := LSize.cx;
end;
{ TCustomBCEditor.TRows *******************************************************}
procedure TCustomBCEditor.TRows.Add(const AFlags: TRow.TFlags; const ALine: Integer;
const AChar, ALength, AColumns, AWidth: Integer; const ABeginRange: Pointer;
const AParts: TRow.TParts);
begin
Insert(Count, AFlags, ALine, AChar, ALength, AColumns, AWidth, ABeginRange, AParts);
end;
procedure TCustomBCEditor.TRows.Clear();
begin
inherited;
FCaretPosition := InvalidRowsPosition;
FMaxColumns := -1;
FMaxColumnsRow := -1;
FMaxWidth := -1;
FMaxWidthRow := -1;
end;
constructor TCustomBCEditor.TRows.Create(const AEditor: TCustomBCEditor);
begin
inherited Create();
FEditor := AEditor;
FMaxColumns := -1;
FMaxColumnsRow := -1;
end;
procedure TCustomBCEditor.TRows.Delete(ARow: Integer);
begin
inherited;
if (FMaxColumnsRow = ARow) then
begin
FMaxColumns := -1;
FMaxColumnsRow := -1;
end
else if (FMaxColumnsRow > ARow) then
Dec(FMaxColumnsRow);
if (FMaxWidthRow = ARow) then
begin
FMaxWidth := -1;
FMaxWidthRow := -1;
end
else if (FMaxWidthRow > ARow) then
Dec(FMaxWidthRow);
end;
destructor TCustomBCEditor.TRows.Destroy();
begin
Clear(); // Clear is not virtual, so it must be called here
inherited;
end;
function TCustomBCEditor.TRows.GetCaretPosition(): TBCEditorRowsPosition;
begin
if (FCaretPosition = InvalidRowsPosition) then
FCaretPosition := FEditor.LinesToRows(FEditor.FLines.CaretPosition);
Result := FCaretPosition;
end;
function TCustomBCEditor.TRows.GetBORPosition(ARow: Integer): TBCEditorLinesPosition;
var
LChar: Integer;
LRow: Integer;
begin
if (ARow < Count) then
begin
LChar := 0;
LRow := FEditor.FLines.Items[Items[ARow].Line].FirstRow;
while (LRow < ARow) do
begin
Inc(LChar, Items[LRow].Length);
Inc(LRow);
end;
Result := LinesPosition(LChar, Items[ARow].Line);
end
else
Result := FEditor.FLines.BOLPosition[(ARow - Count) + FEditor.FLines.Count];
end;
function TCustomBCEditor.TRows.GetEORPosition(ARow: Integer): TBCEditorLinesPosition;
begin
Assert((0 <= ARow) and (ARow < Count));
if (not (rfLastRowOfLine in Items[ARow].Flags)) then
Result := LinesPosition(Items[ARow].Char + Items[ARow].Length - 1, Items[ARow].Line)
else
Result := FEditor.FLines.EOLPosition[Items[ARow].Line];
end;
function TCustomBCEditor.TRows.GetFmtText(): string;
var
LRow: Integer;
LStringBuilder: TStringBuilder;
begin
LStringBuilder := TStringBuilder.Create();
for LRow := 0 to Count - 1 do
begin
LStringBuilder.Append(FEditor.FLines.Items[Items[LRow].Line].Text, Items[LRow].Char, Items[LRow].Length);
if (not (rfLastRowOfLine in Items[LRow].Flags)) then
LStringBuilder.Append(#13#13#10)
else if (LRow < Count - 1) then
LStringBuilder.Append(#13#10);
end;
Result := LStringBuilder.ToString();
LStringBuilder.Free();
end;
function TCustomBCEditor.TRows.GetMaxColumns(): Integer;
var
LRow: Integer;
begin
if ((FMaxColumns < 0) and (Count > 0)) then
for LRow := 0 to Count - 1 do
if (Items[LRow].Columns > FMaxColumns) then
begin
FMaxColumnsRow := LRow;
FMaxColumns := Items[LRow].Columns;
end;
Result := FMaxColumns;
end;
function TCustomBCEditor.TRows.GetMaxWidth(): Integer;
var
LRow: Integer;
begin
if ((FMaxWidth < 0) and (Count > 0)) then
for LRow := 0 to Count - 1 do
if (Items[LRow].Width > FMaxWidth) then
begin
FMaxWidthRow := LRow;
FMaxWidth := Items[LRow].Width;
end;
Result := FMaxWidth;
end;
function TCustomBCEditor.TRows.GetRowArea(ARow: Integer): TBCEditorLinesArea;
begin
Result.BeginPosition := BORPosition[ARow];
Result.EndPosition := EORPosition[ARow];
end;
function TCustomBCEditor.TRows.GetText(ARow: Integer): string;
begin
Assert((0 <= ARow) and (ARow < Count));
Result := Copy(FEditor.FLines.Items[Items[ARow].Line].Text, 1 + Items[ARow].Char, Items[ARow].Length);
end;
procedure TCustomBCEditor.TRows.Insert(ARow: Integer; const AFlags: TRow.TFlags;
const ALine: Integer; const AChar, ALength, AColumns, AWidth: Integer;
const ABeginRange: Pointer; const AParts: TRow.TParts);
var
LItem: TRow;
LPos: PChar;
LEndPos: PChar;
begin
Assert((0 <= ARow) and (ARow <= Count));
LItem.BeginRange := ABeginRange;
LItem.Char := AChar;
LItem.Columns := AColumns;
LItem.Flags := AFlags;
LItem.Length := ALength;
LItem.Line := ALine;
LItem.Parts := AParts;
LItem.Width := AWidth;
if ((ALength > 0) and (lfContainsTabs in FEditor.FLines.Items[ALine].Flags)) then
begin
LPos := @FEditor.FLines.Items[ALine].Text[1 + AChar];
LEndPos := @LPos[ALength - 1];
while (LPos <= LEndPos) do
begin
if (LPos^ = BCEDITOR_TAB_CHAR) then
begin
Include(LItem.Flags, rfHasTabs);
break;
end;
Inc(LPos);
end;
end;
inherited Insert(ARow, LItem);
if ((FMaxColumns >= 0) and (AColumns > FMaxColumns)) then
begin
FMaxColumns := AColumns;
FMaxColumnsRow := ARow;
end
else if (FMaxColumnsRow >= ARow) then
Inc(FMaxColumnsRow);
if ((FMaxWidth >= 0) and (AWidth > FMaxWidth)) then
begin
FMaxWidth := AWidth;
FMaxWidthRow := ARow;
end
else if (FMaxWidthRow >= ARow) then
Inc(FMaxWidthRow);
end;
{ TCustomBCEditor *************************************************************}
procedure TCustomBCEditor.ActivateHint(const X, Y: Integer; const AHint: string);
var
LRect: TRect;
begin
if (not Assigned(FHintWindow)) then
begin
FHintWindow := THintWindow.Create(Self);
FHintWindow.Color := clInfoBk;
end;
LRect := FHintWindow.CalcHintRect(FClientRect.Width, AHint, nil);
LRect.Offset(X, Y);
FHintWindow.ActivateHint(LRect, AHint);
end;
procedure TCustomBCEditor.AddHighlighterKeywords(AStringList: TStrings);
var
LChar: Char;
LIndex: Integer;
LKeywordStringList: TStringList;
LStringList: TStringList;
LWord: string;
LWordList: string;
begin
LStringList := TStringList.Create;
LKeywordStringList := TStringList.Create;
LWordList := AStringList.Text;
try
FHighlighter.AddKeywords(LKeywordStringList);
for LIndex := 0 to LKeywordStringList.Count - 1 do
begin
LWord := LKeywordStringList.Strings[LIndex];
if Length(LWord) > 1 then
begin
LChar := LWord[1];
if LChar.IsLower or LChar.IsUpper or (LChar = BCEDITOR_UNDERSCORE) then
if Pos(LWord + BCEDITOR_CARRIAGE_RETURN + BCEDITOR_LINEFEED, LWordList) = 0 then { No duplicates }
LWordList := LWordList + LWord + BCEDITOR_CARRIAGE_RETURN + BCEDITOR_LINEFEED;
end;
end;
LStringList.Text := LWordList;
LStringList.Sort;
AStringList.Assign(LStringList);
finally
LKeywordStringList.Free;
LStringList.Free;
end;
end;
procedure TCustomBCEditor.AfterLinesUpdate(Sender: TObject);
begin
if (not (csReading in ComponentState)) then
EndUpdate();
end;
procedure TCustomBCEditor.AskReplaceText(ASender: TObject; const AArea: TBCEditorLinesArea;
const ABackwards: Boolean; const AReplaceText: string; var AAction: TBCEditorReplaceAction);
begin
Assert(ASender is TBCEditorLines.TSearch);
Include(FState, esCenterCaret);
try
if (ABackwards) then
SetCaretAndSelection(AArea.BeginPosition, AArea)
else
SetCaretAndSelection(AArea.EndPosition, AArea);
finally
Exclude(FState, esCenterCaret);
end;
if (Assigned(FOnReplacePrompt)) then
FOnReplacePrompt(Self, AArea, ABackwards, AReplaceText, FReplaceAction)
else
case (MessageBox(WindowHandle, PChar(Format(SBCEditorReplaceTextPrompt, [AReplaceText])), PChar(SBCEditorMessageQuestion), MB_ICONQUESTION or MB_YESNOCANCEL)) of
ID_YES:
FReplaceAction := raReplace;
ID_NO:
FReplaceAction := raSkip;
ID_CANCEL:
FReplaceAction := raCancel;
end;
end;
function TCustomBCEditor.AskSearchWrapAround(const AData: PBCEditorCommandDataFind): Boolean;
var
LHandle: THandle;
LText: string;
begin
if (foWrapAround in AData^.Options) then
Result := True
else if (Assigned(FOnFindWrapAround)) then
Result := FOnFindWrapAround(Self, AData^.Pattern, foBackwards in AData^.Options)
else
begin
if (Assigned(FFindDialog)) then
LHandle := FFindDialog.Handle
else
LHandle := WindowHandle;
if (foBackwards in AData^.Options) then
LText := Format(SBCEditorSearchWrapAroundBackwards, [AData^.Pattern])
else
LText := Format(SBCEditorSearchWrapAroundForwards, [AData^.Pattern]);
Result := MessageBox(LHandle, PChar(LText), PChar(SBCEditorSearchWrapAroundTitle), MB_ICONQUESTION or MB_YESNO) = IDYES;
end;
end;
procedure TCustomBCEditor.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TCustomBCEditor) then
with ASource as TCustomBCEditor do
begin
Self.FCompletionProposal.Assign(FCompletionProposal);
Self.FLeftMargin.Assign(FLeftMargin);
Self.FTabs.Assign(FTabs);
end
else
inherited Assign(ASource);
end;
procedure TCustomBCEditor.BeforeLinesUpdate(Sender: TObject);
begin
if (not (csReading in ComponentState)) then
BeginUpdate();
end;
procedure TCustomBCEditor.BeginUndoBlock;
begin
FLines.BeginUpdate();
end;
procedure TCustomBCEditor.BeginUpdate();
begin
if (FUpdateCount = 0) then SetUpdateState(True);
Inc(FUpdateCount);
end;
procedure TCustomBCEditor.BookmarksChanged(ASender: TObject);
begin
if (FLeftMargin.Marks.Visible) then
InvalidateRect(FMarksPanelRect);
end;
procedure TCustomBCEditor.BuildRows(const ATerminated: TBCEditorTerminatedFunc;
const AEndRow: Integer = -1);
var
LCodeFolding: Integer;
LLastUpdateScrollBars: Integer;
LLine: Integer;
LRange: TBCEditorCodeFoldingRanges.TRange;
LRow: Integer;
LTickCount: Integer;
begin
Include(FState, esBuildingRows);
FPaintHelper.BeginDraw(Canvas.Handle);
try
for LCodeFolding := 0 to FAllCodeFoldingRanges.AllCount - 1 do
begin
LRange := FAllCodeFoldingRanges[LCodeFolding];
if (Assigned(LRange) and LRange.Collapsed) then
for LLine := LRange.BeginLine + 1 to LRange.EndLine do
FLines.SetRow(LLine, -1, 0);
end;
LLastUpdateScrollBars := 0;
LRow := FRows.Count;
LLine := FLastBuiltLine + 1;
while ((LLine < FLines.Count)
and ((LRow <= AEndRow) or (AEndRow < 0) and not ATerminated())) do
begin
if (FLines.Items[LLine].FirstRow = GRowToInsert) then
Inc(LRow, InsertLineIntoRows(ATerminated, LLine, LRow))
else
Inc(FLastBuiltLine);
Inc(LLine);
if (AEndRow < 0) then
begin
LTickCount := GetTickCount();
if (LTickCount >= LLastUpdateScrollBars + GClientRefreshTime) then
begin
LLastUpdateScrollBars := LTickCount;
UpdateScrollBars();
end;
end;
end;
finally
FPaintHelper.EndDraw();
Exclude(FState, esBuildingRows);
end;
if (LLine < FLines.Count) then
ProcessIdle(ijBuildRows)
else
InvalidateScrollBars();
FOldClientRect := FClientRect;
end;
procedure TCustomBCEditor.CaretChanged(ASender: TObject);
begin
InvalidateMatchingPair();
InvalidateCaret();
InvalidateSyncEditOverlays();
if (esHighlightSearchAllAreas in FState) then
begin
Exclude(FState, esHighlightSearchAllAreas);
InvalidateText();
end;
ScrollToCaret();
if (FUpdateCount > 0) then
Include(FState, esCaretChanged)
else
if (Assigned(FOnCaretChanged)) then
FOnCaretChanged(Self, CaretPos);
end;
procedure TCustomBCEditor.Change();
begin
NotifyParent(EN_CHANGE);
if (Assigned(FOnChange)) then
FOnChange(Self);
Include(FState, esTextUpdated);
LinesChanged();
end;
procedure TCustomBCEditor.ChangeScale(M, D: Integer);
begin
FCompletionProposal.ChangeScale(M, D);
end;
function TCustomBCEditor.CharAtCursor(): Char;
begin
if (FLines.Count = 0) then
Result := BCEDITOR_NONE_CHAR
else
Result := FLines.Char[FLines.CaretPosition];
end;
function TCustomBCEditor.CharIndexToPos(const ACharIndex: Integer): TPoint;
begin
Result := FLines.PositionOf(ACharIndex);
end;
procedure TCustomBCEditor.Clear();
begin
FLines.Clear();
end;
procedure TCustomBCEditor.ClearUndo();
begin
FLines.ClearUndo();
end;
function TCustomBCEditor.ClientToLines(const X, Y: Integer; const AForCaret: Boolean = False): TBCEditorLinesPosition;
begin
Result := RowsToLines(ClientToRows(X, Y, AForCaret));
end;
function TCustomBCEditor.ClientToRows(const X, Y: Integer; const AForCaret: Boolean = False): TBCEditorRowsPosition;
var
LBeginRange: TBCEditorHighlighter.TRange;
LChar: Integer;
LColumn: Integer;
LIndex: Integer;
LLeft: Integer;
LLength: Integer;
LMiddle: Integer;
LRight: Integer;
LRow: Integer;
LRowText: string;
LText: PChar;
LToken: TBCEditorHighlighter.TTokenFind;
LTokenWidth: Integer;
LWidths: array of Integer;
LX: Integer;
begin
LRow := Max(0, FTopRow + Y div LineHeight);
if (X <= FTextRect.Left) then
Result := RowsPosition(0, LRow)
else if (FRows.Count = 0) then
begin
LX := X - FTextRect.Left + FTextPos.X;
if (AForCaret) then
Inc(LX, FSpaceWidth div 2);
Result := RowsPosition(LX div FSpaceWidth, LRow - FRows.Count);
end
else if (LRow >= FRows.Count) then
begin
LX := X - FTextRect.Left + FTextPos.X;
if (AForCaret) then
Inc(LX, FSpaceWidth div 2);
Result := RowsPosition(LX div FSpaceWidth, LRow - FRows.Count + FLines.Count);
end
else if (X > FTextRect.Right) then
Result := RowsPosition(FRows.Items[LRow].Length, LRow)
else
begin
LX := X - FTextRect.Left + FTextPos.X;
FPaintHelper.BeginDraw(Canvas.Handle);
try
LTokenWidth := 0;
LLeft := FTextPos.X;
if (GetFindTokenData(LRow, LLeft, LBeginRange, LText, LLength, LChar, LColumn)
and FHighlighter.FindFirstToken(LBeginRange, LText, LLength, LChar, LToken)) then
repeat
LTokenWidth := TokenWidth(LToken.Text, LToken.Length, LColumn, LToken);
if (LX < LLeft + LTokenWidth) then
break;
Inc(LLeft, LTokenWidth);
Inc(LColumn, TokenColumns(LToken.Text, LToken.Length, LColumn));
until (not FHighlighter.FindNextToken(LToken));
if (LX < LLeft + LTokenWidth) then
begin
SetLength(LWidths, LToken.Length + 1);
for LIndex := 1 to Length(LWidths) - 2 do
LWidths[LIndex] := -1;
LWidths[0] := LLeft;
LWidths[Length(LWidths) - 1] := LLeft + LTokenWidth;
LLeft := 0;
LRight := Length(LWidths) - 1;
while (LRight - LLeft >= 2) do
begin
LMiddle := (LLeft + LRight) div 2;
if (LWidths[LMiddle] < 0) then
LWidths[LMiddle] := LLeft + TokenWidth(LToken.Text, LMiddle, LColumn, LToken);
case (Sign(LWidths[LMiddle] - LX)) of
-1: LLeft := LMiddle;
0:
begin
Result := RowsPosition(LColumn + LMiddle, LRow);
LRowText := FRows[LRow];
while (Result.Column < Length(LRowText) - 1)
and ((LRowText[1 + Result.Column + 1].GetUnicodeCategory in [TUnicodeCategory.ucCombiningMark, TUnicodeCategory.ucNonSpacingMark])
or (LRowText[1 + Result.Column].GetUnicodeCategory = TUnicodeCategory.ucNonSpacingMark)
and not IsCombiningDiacriticalMark(LRowText[1 + Result.Column])) do
Inc(Result.Column);
Exit(Result);
end;
1: LRight := LMiddle;
end;
end;
if (LWidths[LLeft] < 0) then
LWidths[LLeft] := LLeft + TokenWidth(LToken.Text, LLeft, LColumn, LToken);
if (LWidths[LRight] < 0) then
LWidths[LRight] := LLeft + TokenWidth(LToken.Text, LRight, LColumn, LToken);
if ((LX - LWidths[LLeft]) < (LWidths[LRight] - LX)) then
Result := RowsPosition(LColumn + LLeft, LRow)
else
Result := RowsPosition(LColumn + LRight, LRow);
if (LRow < FRows.Count) then
begin
LRowText := FRows[LRow];
while (Result.Column < LRowText.Length - 1)
and ((LRowText[1 + Result.Column + 1].GetUnicodeCategory in [TUnicodeCategory.ucCombiningMark, TUnicodeCategory.ucNonSpacingMark])
or (LRowText[1 + Result.Column].GetUnicodeCategory = TUnicodeCategory.ucNonSpacingMark)
and not IsCombiningDiacriticalMark(LRowText[1 + Result.Column])) do
Inc(Result.Column);
end;
end
else if (not AForCaret) then
Result := RowsPosition(LColumn + (LX - LLeft) div FSpaceWidth, LRow)
else
Result := RowsPosition(LColumn + (LX - LLeft + FSpaceWidth div 2) div FSpaceWidth, LRow)
finally
FPaintHelper.EndDraw();
end;
end;
end;
function TCustomBCEditor.ClientToPos(const X, Y: Integer): TPoint;
begin
Result := ClientToLines(X, Y);
end;
function TCustomBCEditor.ClientToText(const X, Y: Integer): TPoint;
begin
Result := ClientToPos(X, Y);
end;
procedure TCustomBCEditor.CMDoubleBufferedChanged(var AMessage: TMessage);
begin
if (Assigned(FDoubleBufferBitmap)) then
FreeAndNil(FDoubleBufferBitmap);
if (Assigned(FDoubleBufferOverlayBitmap)) then
FreeAndNil(FDoubleBufferOverlayBitmap);
if (not DoubleBuffered) then
Exclude(FState, esDoubleBufferInvalid)
else
begin
if (Canvas.HandleAllocated) then
begin
FDoubleBufferBitmap := TBitmap.Create();
FDoubleBufferBitmap.Handle := CreateCompatibleBitmap(Canvas.Handle, FClientRect.Width, FClientRect.Height);
FDoubleBufferOverlayBitmap := TBitmap.Create();
FDoubleBufferOverlayBitmap.Handle := CreateCompatibleBitmap(Canvas.Handle, FClientRect.Width, FClientRect.Height);
end;
FDoubleBufferUpdateRect := Rect(-1, -1, -1, -1);
Include(FState, esDoubleBufferInvalid);
end;
end;
procedure TCustomBCEditor.CMSysFontChanged(var AMessage: TMessage);
begin
if (Assigned(FHintWindow)) then
FreeAndNil(FHintWindow);
FMarksPanelWidth := GetSystemMetrics(SM_CXSMICON) + GetSystemMetrics(SM_CXSMICON) div 4;
FLineStateWidth := GetSystemMetrics(SM_CXSMICON) div 4;
FLeftMarginBorderWidth := 2 * GLineWidth;
UpdateMetrics();
FState := FState + [esSysFontChanged];
inherited;
end;
function TCustomBCEditor.CodeFoldingCollapsableFoldRangeForLine(const ALine: Integer): TBCEditorCodeFoldingRanges.TRange;
var
LRange: TBCEditorCodeFoldingRanges.TRange;
begin
LRange := TBCEditorCodeFoldingRanges.TRange(FLines.Items[ALine].CodeFolding.BeginRange);
if (not Assigned(LRange) or not LRange.Collapsable()) then
Result := nil
else
Result := LRange;
end;
function TCustomBCEditor.CodeFoldingFoldRangeForLineTo(const ALine: Integer): TBCEditorCodeFoldingRanges.TRange;
var
LRange: TBCEditorCodeFoldingRanges.TRange;
begin
Result := nil;
LRange := FLines.Items[ALine].CodeFolding.EndRange;
if Assigned(LRange) then
if (LRange.EndLine = ALine) and not LRange.ParentCollapsed then
Result := LRange;
end;
procedure TCustomBCEditor.CollapseCodeFoldingLevel(const AFirstLevel: Integer; const ALastLevel: Integer);
var
LFirstLine: Integer;
LLastLine: Integer;
LLevel: Integer;
LLine: Integer;
LRange: TBCEditorCodeFoldingRanges.TRange;
LRangeLevel: Integer;
begin
if (not FLines.SelArea.IsEmpty()) then
begin
LFirstLine := FLines.SelArea.BeginPosition.Line;
LLastLine := FLines.SelArea.EndPosition.Line;
end
else
begin
LFirstLine := FLines.BOFPosition.Line;
LLastLine := FLines.EOFPosition.Line;
end;
BeginUpdate();
LLevel := -1;
for LLine := LFirstLine to LLastLine do
begin
LRange := TBCEditorCodeFoldingRanges.TRange(FLines.Items[LLine].CodeFolding.BeginRange);
if (Assigned(LRange)) then
begin
if (LLevel = -1) then
LLevel := LRange.FoldRangeLevel;
LRangeLevel := LRange.FoldRangeLevel - LLevel;
if ((AFirstLevel <= LRangeLevel) and (LRangeLevel <= ALastLevel)
and not LRange.Collapsed and LRange.Collapsable) then
CollapseCodeFoldingRange(LRange);
end;
end;
EndUpdate();
end;
function TCustomBCEditor.CollapseCodeFoldingLines(const AFirstLine: Integer = -1; const ALastLine: Integer = -1): Integer;
var
LFirstLine: Integer;
LLastLine: Integer;
LLine: Integer;
LRange: TBCEditorCodeFoldingRanges.TRange;
begin
if (AFirstLine >= 0) then
LFirstLine := AFirstLine
else
LFirstLine := 0;
if (ALastLine >= 0) then
LLastLine := ALastLine
else if (AFirstLine >= 0) then
LLastLine := AFirstLine
else
LLastLine := FLines.Count - 1;
BeginUpdate();
Result := 0;
for LLine := LFirstLine to LLastLine do
begin
LRange := TBCEditorCodeFoldingRanges.TRange(FLines.Items[LLine].CodeFolding.BeginRange);
if (Assigned(LRange) and not LRange.Collapsed and LRange.Collapsable) then
begin
CollapseCodeFoldingRange(LRange);
Inc(Result);
end;
end;
EndUpdate();
end;
procedure TCustomBCEditor.CollapseCodeFoldingRange(const ARange: TBCEditorCodeFoldingRanges.TRange);
var
LBeginRow: Integer;
LEndRow: Integer;
LLine: Integer;
begin
if (not ARange.Collapsed) then
begin
ARange.Collapsed := True;
ARange.SetParentCollapsedOfSubCodeFoldingRanges(True, ARange.FoldRangeLevel);
for LLine := ARange.BeginLine + 1 to ARange.EndLine do
DeleteLineFromRows(LLine);
if ((ARange.BeginLine + 1 <= FLines.CaretPosition.Line) and (FLines.CaretPosition.Line <= ARange.EndLine)) then
FLines.CaretPosition := FLines.BOLPosition[ARange.BeginLine];
LBeginRow := FLines.Items[ARange.BeginLine].FirstRow;
LEndRow := FLines.Items[ARange.EndLine].FirstRow + FLines.Items[ARange.EndLine].RowCount - 1;
if ((LBeginRow <= FTopRow + FVisibleRows) and (LEndRow >= FTopRow)) then
InvalidateRect(
Rect(
FTextRect.Left, Max(0, LBeginRow - FTopRow) * FLineHeight,
FTextRect.Right, FTextRect.Bottom));
InvalidateScrollBars();
end;
end;
procedure TCustomBCEditor.ColorsChanged(ASender: TObject);
begin
InvalidateClient();
end;
procedure TCustomBCEditor.CommandProcessor(ACommand: TBCEditorCommand; AChar: Char; AData: Pointer);
begin
end;
procedure TCustomBCEditor.CopyToClipboard();
begin
ProcessCommand(ecCopyToClipboard);
end;
constructor TCustomBCEditor.Create(AOwner: TComponent);
var
LIndex: Integer;
LLogFont: TLogFont;
LNonClientMetrics: TNonClientMetrics;
begin
inherited;
Color := clWindow;
ControlStyle := ControlStyle + [csOpaque, csNeedsBorderPaint];
DoubleBuffered := True;
ParentColor := False;
TabStop := True;
for LIndex := 0 to Length(FBookmarkBitmaps) - 1 do
FBookmarkBitmaps[LIndex] := nil;
FBorderStyle := bsSingle;
FCaretVisible := False;
FCaretWidth := 0;
FCursorPoint := Point(-1, -1);
FCodeFoldingCollapsedBitmap := nil;
FCodeFoldingExpandedBitmap := nil;
FCodeFoldingLineBitmap := nil;
FCodeFoldingEndLineBitmap := nil;
FDoubleBufferBitmap := nil;
FDoubleClickTime := GetDoubleClickTime();
FFmtLines := False;
FGotoLineDialog := nil;
FHideScrollBars := True;
FHideSelection := True;
FHintWindow := nil;
FHookedCommandHandlers := TList<TBCEditorHookedCommandHandler>.Create();
FIMEStatus := 0;
FInsertPos := InvalidPos;
FInsertPosBitmap := nil;
FInsertPosCache := nil;
FMouseCapture := mcNone;
FNoParentNotify := False;
FLastCursorPoint := Point(-1, -1);
FLastBuiltLine := -1;
FLastSearch := lsFind;
FLastSearchData := nil;
FLineHeight := 0;
FOldClientRect := Rect(-1, -1, -1, -1);
FOldCurrentLine := -1;
FOldSelArea := InvalidLinesArea;
FOnChange := nil;
FOnCompletionProposalClose := nil;
FOnCompletionProposalShow := nil;
FOnFindExecuted := nil;
FOnFindWrapAround := nil;
FOptions := DefaultOptions;
FParentWnd := 0;
FPendingJobs := [];
FPopupMenu := 0;
FReadOnly := False;
FReplaceAction := raReplace;
FScrollBars := ssBoth;
FScrollingBitmap := nil;
FFindDialog := nil;
FReplaceDialog := nil;
FSelectedCaseText := '';
FSelectionOptions := DefaultSelectionOptions;
FState := [];
FSyncEditButtonHotBitmap := nil;
FSyncEditButtonNormalBitmap := nil;
FSyncEditButtonPressedBitmap := nil;
FSyncEditOptions := DefaultSyncEditOptions;
FTextEntryMode := temInsert;
FTopRow := 0;
FUCCVisible := False;
FUsableRows := 0;
FUpdateCount := 0;
FVisibleRows := 0;
FWantTabs := True;
FWantReturns := True;
FWordWrap := False;
{ Colors }
FColors := TBCEditorColors.Create();
FColors.OnChange := ColorsChanged;
{ Code folding }
FAllCodeFoldingRanges := TBCEditorCodeFoldingAllRanges.Create;
{ Text buffer }
FLines := TBCEditorLines(CreateLines());
FOriginalLines := FLines;
FLines.OnAfterUpdate := AfterLinesUpdate;
FLines.OnBeforeUpdate := BeforeLinesUpdate;
FLines.OnBookmarksChange := BookmarksChanged;
FLines.OnCaretChanged := CaretChanged;
FLines.OnCleared := LinesCleared;
FLines.OnDeleting := LineDeleting;
FLines.OnInserted := LineInserted;
FLines.OnLoaded := LinesLoaded;
FLines.OnMarksChange := MarksChanged;
FLines.OnReplacePrompt := AskReplaceText;
FLines.OnSelChange := LinesSelChanged;
FLines.OnSyncEditChange := LinesSyncEditChanged;
FLines.OnUpdated := LineUpdated;
FRows := TCustomBCEditor.TRows.Create(Self);
{ Font }
LNonClientMetrics.cbSize := SizeOf(LNonClientMetrics);
if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, SizeOf(LNonClientMetrics), @LNonClientMetrics, 0)
and (GetObject(Font.Handle, SizeOf(LLogFont), @LLogFont) <> 0)) then
begin
LLogFont.lfQuality := LNonClientMetrics.lfMessageFont.lfQuality;
Font.Handle := CreateFontIndirect(LLogFont);
end;
Font.Name := 'Courier New';
Font.Size := Font.Size + 1;
Font.OnChange := FontChanged;
{ Painting }
FPaintHelper := TCustomBCEditor.TPaintHelper.Create(Font);
FOverlays := TOverlays.Create(Self);
{ Tabs }
FTabs := TBCEditorTabs.Create;
FTabs.OnChange := TabsChanged;
{ Completion proposal }
FCompletionProposal := TBCEditorCompletionProposal.Create(Self);
{ FLeftMargin }
FLeftMargin := TBCEditorLeftMargin.Create(Self);
FLeftMargin.OnChange := LeftMarginChanged;
{ Do update character constraints }
TabsChanged(nil);
{ Highlighter }
FHighlighter := TBCEditorHighlighter.Create(Self);
FHighlighter.OnChange := HighlighterChanged;
if (not SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, @FWheelScrollChars, 0)) then
FWheelScrollChars := 3;
end;
function TCustomBCEditor.CreateLines(): BCEditor.Lines.TBCEditorLines;
begin
Result := BCEditor.Lines.TBCEditorLines.Create();
end;
procedure TCustomBCEditor.CreateParams(var AParams: TCreateParams);
const
LBorderStyles: array [TBorderStyle] of DWORD = (0, WS_BORDER);
begin
inherited;
with AParams do
begin
WindowClass.Style := WindowClass.Style and not CS_VREDRAW and not CS_HREDRAW;
Style := Style or LBorderStyles[FBorderStyle] or WS_CLIPCHILDREN or ES_AUTOHSCROLL or ES_AUTOVSCROLL;
if (FReadOnly) then
Style := Style or ES_READONLY;
if (eoDropFiles in FOptions) then
ExStyle := ExStyle or WS_EX_ACCEPTFILES;
if (NewStyleControls and Ctl3D and (FBorderStyle = bsSingle)) then
begin
Style := Style and not WS_BORDER;
ExStyle := ExStyle or WS_EX_CLIENTEDGE;
end;
end;
end;
procedure TCustomBCEditor.CreateWnd();
begin
inherited;
if (not Assigned(Parent)) then
begin
FFormWnd := 0;
FParentWnd := 0;
end
else
begin
FFormWnd := GetParentForm(Self).Handle;
FParentWnd := Parent.Handle;
end;
FDlgCtrlID := GetDlgCtrlID(WindowHandle);
FNoParentNotify := GetWindowLong(WindowHandle, GWL_EXSTYLE) and WS_EX_NOPARENTNOTIFY <> 0;
OleCheck(RegisterDragDrop(WindowHandle, Self));
FState := FState + [esFontChanged, esSizeChanged, esScrollBarsInvalid];
end;
function TCustomBCEditor.DeleteBookmark(const ALine: Integer; const AIndex: Integer): Boolean;
var
LBookmark: TBCEditorLines.TMark;
LIndex: Integer;
begin
Result := False;
LIndex := 0;
while LIndex < FLines.Bookmarks.Count do
begin
LBookmark := FLines.Bookmarks.Items[LIndex];
if LBookmark.Pos.Y = ALine then
begin
if LBookmark.Index = AIndex then
Result := True;
FLines.Bookmarks.Delete(LIndex);
end
else
Inc(LIndex);
end;
end;
procedure TCustomBCEditor.CutToClipboard();
begin
ProcessCommand(ecCutToClipboard);
end;
procedure TCustomBCEditor.DeleteChar();
begin
if (not FLines.SelArea.IsEmpty()) then
SelText := ''
else if ((FLines.CaretPosition.Line < FLines.Count)
and (FLines.CaretPosition.Char < Length(FLines.Items[FLines.CaretPosition.Line].Text))) then
FLines.DeleteText(LinesArea(FLines.CaretPosition, LinesPosition(FLines.CaretPosition.Char + 1, FLines.CaretPosition.Line)))
else if (FLines.CaretPosition.Line < FLines.Count - 1) then
FLines.DeleteText(LinesArea(FLines.CaretPosition, FLines.BOLPosition[FLines.CaretPosition.Line + 1]));
end;
procedure TCustomBCEditor.DeleteLastWordOrBOL(const ACommand: TBCEditorCommand);
var
LNewCaretPosition: TBCEditorLinesPosition;
begin
if (ACommand = ecDeleteLastWord) then
LNewCaretPosition := PreviousWordPosition(FLines.CaretPosition)
else
LNewCaretPosition := FLines.BOLPosition[FLines.CaretPosition.Line];
if (LNewCaretPosition <> FLines.CaretPosition) then
if (FLines.CaretPosition.Line < FLines.Count) then
FLines.DeleteText(LinesArea(LNewCaretPosition, Min(FLines.CaretPosition, FLines.EOLPosition[FLines.CaretPosition.Line])))
else
FLines.CaretPosition := LNewCaretPosition;
end;
procedure TCustomBCEditor.DeleteLine();
begin
if (not FLines.SelArea.IsEmpty()) then
FLines.SelArea := LinesArea(FLines.CaretPosition, FLines.CaretPosition)
else if (FLines.CaretPosition.Line < FLines.Count) then
FLines.Delete(FLines.CaretPosition.Line);
end;
procedure TCustomBCEditor.DeleteLineFromRows(const ALine: Integer);
var
LDeletedRows: Integer;
LLastRow: Integer;
LLine: Integer;
LRow: Integer;
begin
if ((FRows.Count > 0)
and (FLines.Items[ALine].FirstRow >= 0)) then
begin
LLastRow := FLines.Items[ALine].FirstRow;
while (not (rfLastRowOfLine in FRows.Items[LLastRow].Flags)) do
Inc(LLastRow);
LDeletedRows := LLastRow - FLines.Items[ALine].FirstRow + 1;
if (FLines.CaretPosition.Line = ALine) then
if (ALine = 0) then
FLines.CaretPosition := FLines.BOFPosition
else
FLines.CaretPosition := FLines.BOLPosition[ALine - 1]
else if ((FLines.CaretPosition.Line > ALine)
and not (esCaretInvalid in FState)) then
begin
Dec(FCaretPos.Y, LDeletedRows * FLineHeight);
UpdateCaret();
end;
for LRow := LLastRow downto FLines.Items[ALine].FirstRow do
FRows.Delete(LRow);
for LLine := ALine to FLines.Count - 1 do
FLines.SetRow(LLine, FLines.Items[LLine].FirstRow - LDeletedRows, FLines.Items[LLine].RowCount);
Dec(FLastBuiltLine);
end;
end;
destructor TCustomBCEditor.Destroy();
begin
FLines.TerminateJob(True);
if Assigned(FCompletionProposalPopup) then
FCompletionProposalPopup.Free();
{ Do not use FreeAndNil, it first nil and then frees causing problems with code accessing FHookedCommandHandlers
while destruction }
FHookedCommandHandlers.Free();
FHookedCommandHandlers := nil;
FLeftMargin.Free();
FLeftMargin := nil; { Notification has a check }
FAllCodeFoldingRanges.Free();
FCompletionProposal.Free();
FColors.Free();
if (Assigned(FDoubleBufferBitmap)) then
FreeAndNil(FDoubleBufferBitmap);
if (Assigned(FDoubleBufferOverlayBitmap)) then
FreeAndNil(FDoubleBufferOverlayBitmap);
FHighlighter.Free();
if (Assigned(FHintWindow)) then
FHintWindow.Free();
FHookedCommandHandlers.Free();
if (Assigned(FInsertPosCache)) then
FInsertPosCache.Free();
if (Assigned(FInsertPosBitmap)) then
FInsertPosBitmap.Free();
FOriginalLines.Free();
FOverlays.Free();
FPaintHelper.Free();
FRows.Free();
if (Assigned(FScrollingBitmap)) then
FScrollingBitmap.Free();
if (Assigned(FSyncEditButtonHotBitmap)) then
FSyncEditButtonHotBitmap.Free();
if (Assigned(FSyncEditButtonNormalBitmap)) then
FSyncEditButtonNormalBitmap.Free();
if (Assigned(FSyncEditButtonPressedBitmap)) then
FSyncEditButtonPressedBitmap.Free();
FTabs.Free();
inherited;
end;
procedure TCustomBCEditor.DestroyWnd();
begin
RevokeDragDrop(WindowHandle);
FParentWnd := 0;
inherited;
end;
procedure TCustomBCEditor.DoBackspace();
var
LBackCounterLine: Integer;
LLength: Integer;
LNewCaretPosition: TBCEditorLinesPosition;
LRange: TBCEditorCodeFoldingRanges.TRange;
LSpaceCount1: Integer;
LSpaceCount2: Integer;
LVisualSpaceCount1: Integer;
LVisualSpaceCount2: Integer;
begin
FLines.BeginUpdate();
try
if (not FLines.SelArea.IsEmpty()) then
SelText := ''
else if (FLines.CaretPosition > FLines.BOFPosition) then
begin
if ((FLines.CaretPosition.Line < FLines.Count)
and (FLines.CaretPosition.Char > Length(FLines.Items[FLines.CaretPosition.Line].Text))) then
begin
if (Length(FLines.Items[FLines.CaretPosition.Line].Text) > 0) then
FLines.CaretPosition := FLines.EOLPosition[FLines.CaretPosition.Line]
else
begin
LSpaceCount1 := FLines.CaretPosition.Char;
LSpaceCount2 := 0;
if LSpaceCount1 > 0 then
begin
LBackCounterLine := FLines.CaretPosition.Line;
while LBackCounterLine >= 0 do
begin
LSpaceCount2 := LeftSpaceCount(FLines.Items[LBackCounterLine].Text);
if LSpaceCount2 < LSpaceCount1 then
Break;
Dec(LBackCounterLine);
end;
if (LBackCounterLine = -1) and (LSpaceCount2 > LSpaceCount1) then
LSpaceCount2 := 0;
end;
if LSpaceCount2 = LSpaceCount1 then
LSpaceCount2 := 0;
FLines.CaretPosition := LinesPosition(FLines.CaretPosition.Char - (LSpaceCount1 - LSpaceCount2), FLines.CaretPosition.Line);
end;
end
else if ((FLines.CaretPosition.Line < FLines.Count)
and (FLines.CaretPosition.Char > 0)) then
begin
LSpaceCount1 := LeftSpaceCount(FLines.Items[FLines.CaretPosition.Line].Text);
LSpaceCount2 := 0;
if ((FLines.CaretPosition.Char < Length(FLines.Items[FLines.CaretPosition.Line].Text) - 1)
and (FLines.Char[FLines.CaretPosition] = BCEDITOR_SPACE_CHAR)
or (LSpaceCount1 <> FLines.CaretPosition.Char)) then
begin
LNewCaretPosition := LinesPosition(FLines.CaretPosition.Char - 1, FLines.CaretPosition.Line);
if (FLines.Char[LNewCaretPosition].IsSurrogate()) then
Dec(LNewCaretPosition.Char);
end
else
begin
LVisualSpaceCount1 := GetLeadingExpandedLength(FLines.Items[FLines.CaretPosition.Line].Text);
LVisualSpaceCount2 := 0;
LBackCounterLine := FLines.CaretPosition.Line - 1;
while LBackCounterLine >= 0 do
begin
LVisualSpaceCount2 := GetLeadingExpandedLength(FLines.Items[LBackCounterLine].Text);
if LVisualSpaceCount2 < LVisualSpaceCount1 then
begin
LSpaceCount2 := LeftSpaceCount(FLines.Items[LBackCounterLine].Text);
Break;
end;
Dec(LBackCounterLine);
end;
if ((LSpaceCount2 > 0)
and ((LBackCounterLine >= 0) or (LSpaceCount2 <= LSpaceCount1))
and (LSpaceCount2 <> LSpaceCount1)) then
begin
LNewCaretPosition := FLines.CaretPosition;
LLength := GetLeadingExpandedLength(FLines.Items[FLines.CaretPosition.Line].Text, LNewCaretPosition.Char);
while ((LNewCaretPosition.Char > 0) and (LLength > LVisualSpaceCount2)) do
begin
Dec(LNewCaretPosition.Char);
LLength := GetLeadingExpandedLength(FLines.Items[FLines.CaretPosition.Line].Text, LNewCaretPosition.Char);
end;
end
else
begin
LNewCaretPosition := LinesPosition(FLines.CaretPosition.Char - 1, FLines.CaretPosition.Line);
LVisualSpaceCount2 := LVisualSpaceCount1 - (LVisualSpaceCount1 mod FTabs.Width);
if (LVisualSpaceCount2 = LVisualSpaceCount1) then
LVisualSpaceCount2 := Max(LVisualSpaceCount2 - FTabs.Width, 0);
LLength := GetLeadingExpandedLength(FLines.Items[FLines.CaretPosition.Line].Text, LNewCaretPosition.Char - 1);
while (LNewCaretPosition.Char > 0) and (LLength > LVisualSpaceCount2) do
begin
Dec(LNewCaretPosition.Char);
LLength := GetLeadingExpandedLength(FLines.Items[FLines.CaretPosition.Line].Text, LNewCaretPosition.Char);
end;
end;
end;
FLines.DeleteText(LinesArea(LNewCaretPosition, FLines.CaretPosition), True);
end
else if (FLines.CaretPosition.Line >= FLines.Count) then
if (FLines.CaretPosition.Char > 0) then
FLines.CaretPosition := LinesPosition(0, FLines.CaretPosition.Line)
else if (FLines.CaretPosition.Line = FLines.Count) then
FLines.CaretPosition := FLines.EOLPosition[FLines.CaretPosition.Line - 1]
else
FLines.CaretPosition := LinesPosition(0, FLines.CaretPosition.Line - 1)
else if (FLines.CaretPosition.Line > 0) then
begin
LNewCaretPosition := FLines.EOLPosition[FLines.CaretPosition.Line - 1];
LRange := CodeFoldingFoldRangeForLineTo(LNewCaretPosition.Line);
if (Assigned(LRange) and LRange.Collapsed) then
begin
LNewCaretPosition.Line := LRange.BeginLine;
Inc(LNewCaretPosition.Char, Length(FLines.Items[LNewCaretPosition.Line].Text) + 1);
end;
FLines.DeleteText(LinesArea(LNewCaretPosition, FLines.CaretPosition), True);
end
else
FLines.CaretPosition := FLines.BOFPosition;
end;
finally
FLines.EndUpdate();
end;
end;
procedure TCustomBCEditor.DoBlockComment();
var
LArea: TBCEditorLinesArea;
LCommentIndex: Integer;
LCommentLength: Integer;
LIndentText: string;
LIndex: Integer;
LLinesDeleted: Integer;
LText: string;
begin
LCommentLength := Length(FHighlighter.Comments.BlockComments);
if (LCommentLength = 0) then
// No BlockComment defined in the Highlighter
else
begin
LArea := FLines.SelArea;
if (LArea.EndPosition <> FLines.BOFPosition) then
begin
LText := Trim(FLines.TextIn[LArea]);
LCommentIndex := -2;
LIndex := 0;
while (LIndex + 1 < LCommentLength) do
if ((Length(LText) >= Length(FHighlighter.Comments.BlockComments[LIndex]) + Length(FHighlighter.Comments.BlockComments[LIndex + 1]))
and (LeftStr(LText, Length(FHighlighter.Comments.BlockComments[LIndex])) = FHighlighter.Comments.BlockComments[LIndex])
and (RightStr(LText, Length(FHighlighter.Comments.BlockComments[LIndex + 1])) = FHighlighter.Comments.BlockComments[LIndex + 1])) then
begin
LCommentIndex := LIndex;
break;
end
else
Inc(LIndex, 2);
if (LCommentIndex < 0) then
begin
LArea.BeginPosition.Char := 0;
if (LArea.EndPosition.Line < FLines.Count - 1) then
LArea.EndPosition := FLines.BOLPosition[LArea.EndPosition.Line]
else
LArea.EndPosition := FLines.EOLPosition[LArea.EndPosition.Line];
LText := Trim(FLines.TextIn[LArea]);
LCommentIndex := -2;
LIndex := 0;
while (LIndex + 1 < LCommentLength) do
if ((Length(LText) >= Length(FHighlighter.Comments.BlockComments[LIndex]) + Length(FHighlighter.Comments.BlockComments[LIndex + 1]))
and (LeftStr(LText, Length(FHighlighter.Comments.BlockComments[LIndex])) = FHighlighter.Comments.BlockComments[LIndex])
and (RightStr(LText, Length(FHighlighter.Comments.BlockComments[LIndex + 1])) = FHighlighter.Comments.BlockComments[LIndex + 1])) then
begin
LCommentIndex := LIndex;
break;
end
else
Inc(LIndex, 2);
end;
FLines.BeginUpdate();
try
if (LCommentIndex >= 0) then
begin
LText := FLines.TextIn[LArea];
LArea.BeginPosition := FLines.PositionOf(LeftTrimLength(LText), LArea.BeginPosition);
LArea.EndPosition := FLines.PositionOf(Length(Trim(LText)), LArea.BeginPosition);
LLinesDeleted := 0;
FLines.DeleteText(LinesArea(LArea.BeginPosition, LinesPosition(LArea.BeginPosition.Char + Length(FHighlighter.Comments.BlockComments[LIndex]), LArea.BeginPosition.Line)));
if (Trim(FLines.Items[LArea.BeginPosition.Line].Text) = '') then
begin
FLines.Delete(LArea.BeginPosition.Line);
Dec(LArea.EndPosition.Line);
LArea.BeginPosition.Char := 0;
Inc(LLinesDeleted);
end;
FLines.DeleteText(LinesArea(LArea.EndPosition, LinesPosition(LArea.EndPosition.Char, LArea.EndPosition.Line)));
if (Trim(FLines.Items[LArea.EndPosition.Line].Text) = '') then
begin
FLines.Delete(LArea.EndPosition.Line);
Dec(LArea.EndPosition.Line);
Inc(LLinesDeleted);
end;
if ((LLinesDeleted = 2) and (LArea.EndPosition >= LArea.BeginPosition)) then
FLines.DeleteIndent(LArea.BeginPosition, LinesPosition(LArea.BeginPosition.Char, LArea.EndPosition.Line), IndentText(Tabs.Width));
end;
Inc(LCommentIndex, 2);
if (LCommentIndex < LCommentLength) then
begin
LIndentText := IndentText(LeftSpaceCount(FLines.Items[LArea.BeginPosition.Line].Text));
FLines.InsertText(LArea.BeginPosition, LIndentText + FHighlighter.Comments.BlockComments[LCommentIndex] + FLines.LineBreak);
Inc(LArea.EndPosition.Line);
if ((LArea.EndPosition.Char = 0) and (LArea.EndPosition.Line > LArea.BeginPosition.Line)) then
LArea.EndPosition := FLines.EOLPosition[LArea.EndPosition.Line - 1];
FLines.InsertText(LArea.EndPosition, FLines.LineBreak + LIndentText + FHighlighter.Comments.BlockComments[LCommentIndex + 1]);
FLines.InsertIndent(FLines.BOLPosition[LArea.BeginPosition.Line + 1], LinesPosition(LArea.BeginPosition.Char, LArea.EndPosition.Line + 1), IndentText(Tabs.Width));
Inc(LArea.EndPosition.Line);
end;
if (LArea.EndPosition.Line < FLines.Count - 1) then
begin
LArea.EndPosition := FLines.BOLPosition[LArea.EndPosition.Line + 1];
SetCaretAndSelection(LArea.EndPosition, LArea);
end
else
FLines.CaretPosition := FLines.BOFPosition;
finally
FLines.EndUpdate();
end;
end;
end;
end;
procedure TCustomBCEditor.DoBlockIndent(const ACommand: TBCEditorCommand);
var
LIndentText: string;
LTextArea: TBCEditorLinesArea;
begin
if (FLines.Count > 0) then
begin
LTextArea.BeginPosition := FLines.BOLPosition[FLines.SelArea.BeginPosition.Line];
LTextArea.EndPosition := LinesPosition(LTextArea.BeginPosition.Char, FLines.SelArea.EndPosition.Line);
if (LTextArea.EndPosition = LTextArea.BeginPosition) then
if (LTextArea.EndPosition.Line < FLines.Count - 1) then
LTextArea.EndPosition := FLines.BOLPosition[LTextArea.EndPosition.Line + 1]
else
LTextArea.EndPosition := FLines.EOLPosition[LTextArea.EndPosition.Line];
LIndentText := IndentText(FTabs.Width);
FLines.BeginUpdate();
try
case (ACommand) of
ecBlockIndent:
FLines.InsertIndent(LTextArea.BeginPosition, LTextArea.EndPosition, LIndentText);
ecBlockUnindent:
FLines.DeleteIndent(LTextArea.BeginPosition, LTextArea.EndPosition, LIndentText);
else raise ERangeError.Create('ACommand: ' + IntToStr(Ord(ACommand)));
end;
if (FLines.SelArea.IsEmpty()) then
begin
LTextArea.BeginPosition.Char := 0;
if (LTextArea.EndPosition.Char > 0) then
LTextArea.EndPosition.Char := Length(FLines.Items[LTextArea.EndPosition.Line].Text);
SetCaretAndSelection(LTextArea.EndPosition, LTextArea);
end;
finally
FLines.EndUpdate();
end;
end;
end;
procedure TCustomBCEditor.DoChar(const AData: PBCEditorCommandDataChar);
begin
DoInsertText(AData^.Char);
end;
procedure TCustomBCEditor.DoCompletionProposal();
var
LCanExecute: Boolean;
LColumnIndex: Integer;
LControl: TWinControl;
LCurrentInput: string;
LIndex: Integer;
LItem: TBCEditorCompletionProposalItems.TItem;
LItems: TStrings;
LPoint: TPoint;
begin
Assert(FCompletionProposal.CompletionColumnIndex < FCompletionProposal.Columns.Count);
if (esCaretInvalid in FState) then
LPoint := FCaretPos
else
LPoint := RowsToClient(FRows.CaretPosition, True);
Inc(LPoint.Y, FLineHeight);
FCompletionProposalPopup := TBCEditorCompletionProposalPopup.Create(Self);
with FCompletionProposalPopup do
begin
LControl := Self;
while Assigned(LControl) and not (LControl is TCustomForm) do
LControl := LControl.Parent;
if LControl is TCustomForm then
PopupParent := TCustomForm(LControl);
OnClose := FOnCompletionProposalClose;
OnValidate := FOnCompletionProposalValidate;
Assign(FCompletionProposal);
LItems := TStringList.Create;
try
if cpoParseItemsFromText in FCompletionProposal.Options then
SplitTextIntoWords(LItems, False);
if cpoAddHighlighterKeywords in FCompletionProposal.Options then
AddHighlighterKeywords(LItems);
Items.Clear;
for LIndex := 0 to LItems.Count - 1 do
begin
LItem := Items.Add;
LItem.Value := LItems[LIndex];
{ Add empty items for columns }
for LColumnIndex := 1 to FCompletionProposal.Columns.Count - 1 do
FCompletionProposal.Columns[LColumnIndex].Items.Add;
end;
finally
LItems.Free;
end;
LCurrentInput := GetCurrentInput();
LCanExecute := True;
if Assigned(FOnCompletionProposalShow) then
FOnCompletionProposalShow(Self, FCompletionProposal.Columns,
LCurrentInput, LCanExecute);
if LCanExecute then
begin
ProcessCommand(ecUnselect);
Execute(LCurrentInput, LPoint);
end
else
begin
FCompletionProposalPopup.Free;
FCompletionProposalPopup := nil;
end;
end;
end;
procedure TCustomBCEditor.DoCopyToClipboard();
var
LClipboardData: Pointer;
LGlobal: HGLOBAL;
LOpened: Boolean;
LRetry: Integer;
LText: string;
begin
LRetry := 0;
repeat
LOpened := OpenClipboard(WindowHandle);
if (not LOpened) then
begin
Sleep(50);
Inc(LRetry);
end;
until (LOpened or (LRetry = 10));
if (not LOpened) then
raise EClipboardException.CreateFmt(SCannotOpenClipboard, [SysErrorMessage(GetLastError)])
else
begin
try
EmptyClipboard();
LText := SelText;
LGlobal := GlobalAlloc(GMEM_MOVEABLE or GMEM_DDESHARE, (Length(LText) + 1) * SizeOf(Char));
if (LGlobal <> 0) then
try
LClipboardData := GlobalLock(LGlobal);
if (Assigned(LClipboardData)) then
begin
StrPCopy(LClipboardData, LText);
SetClipboardData(CF_UNICODETEXT, LGlobal);
end;
finally
GlobalUnlock(LGlobal);
end;
finally
CloseClipboard();
end;
end;
end;
procedure TCustomBCEditor.DoCutToClipboard();
begin
if (FReadOnly or FLines.SelArea.IsEmpty()) then
EmptyClipboard()
else
begin
DoCopyToClipboard();
FLines.DeleteText(FLines.SelArea);
end;
end;
procedure TCustomBCEditor.DoDeleteToEOL();
begin
if (FLines.ValidPosition(FLines.CaretPosition)) then
FLines.DeleteText(LinesArea(FLines.CaretPosition, FLines.EOLPosition[FLines.CaretPosition.Line]));
end;
procedure TCustomBCEditor.DoDeleteWord();
var
LArea: TBCEditorLinesArea;
begin
LArea := FLines.WordArea[FLines.CaretPosition];
if (LArea <> InvalidLinesArea) then
FLines.DeleteText(LArea);
end;
procedure TCustomBCEditor.DoDropOLE(const AData: PBCEditorCommandDataDropOLE);
var
LFilename: string;
LFormat: FORMATETC;
LLen: UINT;
LMedium: STGMEDIUM;
LOldPosition: TBCEditorLinesPosition;
LText: string;
begin
LFormat.cfFormat := CF_UNICODETEXT;
LFormat.ptd := nil;
LFormat.dwAspect := DVASPECT_CONTENT;
LFormat.lindex := -1;
LFormat.tymed := TYMED_HGLOBAL;
if (AData^.dataObj.QueryGetData(LFormat) = S_OK) then
begin
OleCheck(AData^.dataObj.GetData(LFormat, LMedium));
SetString(LText, PChar(GlobalLock(LMedium.hGlobal)), GlobalSize(LMedium.hGlobal) div SizeOf(LText[1]));
FLines.CaretPosition := FInsertPos;
SelText := LText;
end
else
begin
LFormat.cfFormat := CF_HDROP;
LFormat.ptd := nil;
LFormat.dwAspect := DVASPECT_CONTENT;
LFormat.lindex := -1;
LFormat.tymed := TYMED_HGLOBAL;
OleCheck(AData^.dataObj.GetData(LFormat, LMedium));
LLen := DragQueryFile(LMedium.hGlobal, 0, nil, 0);
SetLength(LFilename, LLen + 1);
Assert(DragQueryFile(LMedium.hGlobal, 0, PChar(LFilename), LLen + 1) = LLen);
SetLength(LFilename, LLen);
LOldPosition := FInsertPos;
FLines.InsertFile(FInsertPos, LFilename);
SetCaretAndSelection(FLines.CaretPosition, LinesArea(LOldPosition, FLines.CaretPosition));
SetInsertPos(InvalidPos);
end;
end;
procedure TCustomBCEditor.DoEOF(const ACommand: TBCEditorCommand);
begin
if (FRows.Count = 0) then
MoveCaretAndSelection(FLines.BOFPosition, ACommand = ecSelEOF)
else
MoveCaretAndSelection(FLines.EOLPosition[FRows.Items[FRows.Count - 1].Line], ACommand = ecSelEOF);
end;
procedure TCustomBCEditor.DoBOF(const ACommand: TBCEditorCommand);
begin
MoveCaretAndSelection(FLines.BOFPosition, ACommand = ecSelBOF);
end;
procedure TCustomBCEditor.DoEndKey(const ASelectionCommand: Boolean);
var
LNewCaretPosition: TBCEditorLinesPosition;
begin
if (FRows.CaretPosition.Row < FRows.Count) then
LNewCaretPosition := FRows.EORPosition[FRows.CaretPosition.Row]
else
LNewCaretPosition := FLines.BOLPosition[FLines.CaretPosition.Line];
MoveCaretAndSelection(LNewCaretPosition, ASelectionCommand);
end;
function TCustomBCEditor.DoFindBackwards(const AData: PBCEditorCommandDataFind): Boolean;
var
LFindResult: TBCEditorLines.TSearchResult;
LIndex: Integer;
LLeft: Integer;
LMiddle: Integer;
LRight: Integer;
begin
Result := FLines.FoundAreas.Count > 0;
if (Result) then
begin
if (FLines.CaretPosition > FLines.FoundAreas[FLines.FoundAreas.Count - 1].BeginPosition) then
LIndex := FLines.FoundAreas.Count - 1
else if (FLines.CaretPosition > FLines.FoundAreas[0].BeginPosition) then
begin
LIndex := -1;
LLeft := 0;
LRight := FLines.FoundAreas.Count - 1;
while (LIndex < 0) do
begin
LMiddle := (LLeft + LRight) div 2;
if (FLines.FoundAreas[LMiddle].BeginPosition < FLines.CaretPosition) then
LLeft := LMiddle + 1
else if ((FLines.FoundAreas[LMiddle - 1].BeginPosition < FLines.CaretPosition)
and (FLines.CaretPosition <= FLines.FoundAreas[LMiddle].BeginPosition)) then
LIndex := LMiddle - 1
else
LRight := LMiddle - 1;
end;
end
else if (AskSearchWrapAround(AData)) then
LIndex := FLines.FoundAreas.Count - 1
else
LIndex := -1;
Result := LIndex >= 0;
if (not Result) then
begin
LFindResult.Area := InvalidLinesArea;
LFindResult.ErrorMessage := Format(SBCEditorSearchNotFound, [AData^.Pattern]);
end
else
begin
LFindResult.Area := FLines.FoundAreas[LIndex];
LFindResult.ErrorMessage := '';
end;
LFindResult.Backwards := False;
LFindResult.Count := -1;
FindExecuted(@LFindResult);
end;
end;
procedure TCustomBCEditor.DoFindFirst(const AData: PBCEditorCommandDataFind);
var
LSearch: TBCEditorLines.TSearch;
LSearchArea: TBCEditorLinesArea;
begin
if ((foSelection in AData^.Options) and not FLines.SelArea.IsEmpty()) then
FFindArea := FLines.SelArea
else
FFindArea := FLines.Area;
if (FLines.Count = 0) then
FFindPosition := FLines.BOFPosition
else if (not (foEntireScope in AData^.Options)) then
begin
FFindPosition.Line := Min(FLines.CaretPosition.Line, FLines.Count - 1);
FFindPosition.Char := Min(FLines.CaretPosition.Char, Length(FLines[FLines.CaretPosition.Line]));
end
else if (foBackwards in AData^.Options) then
FFindPosition := FLines.EOFPosition
else
FFindPosition := FLines.BOFPosition;
FFindState := fsRequested;
if (foEntireScope in AData^.Options) then
LSearchArea := FFindArea
else if (foBackwards in AData^.Options) then
LSearchArea := LinesArea(FFindArea.BeginPosition, FFindPosition)
else
LSearchArea := LinesArea(FFindPosition, FFindArea.EndPosition);
LSearch := TBCEditorLines.TSearch.Create(FLines,
LSearchArea,
foCaseSensitive in AData^.Options, foWholeWordsOnly in AData^.Options, foRegExpr in AData^.Options,
AData^.Pattern);
FLines.StartSearch(LSearch, FFindPosition, False, True, foBackwards in AData^.Options, FindExecuted);
UpdateCursor();
Sleep(GClientRefreshTime); // If search is fast enough, prevent double painting
end;
function TCustomBCEditor.DoFindForewards(const AData: PBCEditorCommandDataFind): Boolean;
var
LFindResult: TBCEditorLines.TSearchResult;
LIndex: Integer;
LLeft: Integer;
LMiddle: Integer;
LRight: Integer;
begin
Result := FLines.FoundAreas.Count > 0;
if (Result) then
begin
if (FLines.CaretPosition <= FLines.FoundAreas[0].BeginPosition) then
LIndex := 0
else if (FLines.CaretPosition <= FLines.FoundAreas[FLines.FoundAreas.Count - 1].BeginPosition) then
begin
LIndex := -1;
LLeft := 0;
LRight := FLines.FoundAreas.Count - 1;
while (LIndex < 0) do
begin
LMiddle := (LLeft + LRight) div 2;
if (FLines.FoundAreas[LMiddle].BeginPosition < FLines.CaretPosition) then
LLeft := LMiddle + 1
else if ((FLines.FoundAreas[LMiddle - 1].BeginPosition < FLines.CaretPosition)
and (FLines.CaretPosition <= FLines.FoundAreas[LMiddle].BeginPosition)) then
LIndex := LMiddle
else
LRight := LMiddle - 1;
end;
end
else if (AskSearchWrapAround(AData)) then
LIndex := 0
else
LIndex := -1;
Result := LIndex >= 0;
if (not Result) then
begin
LFindResult.Area := InvalidLinesArea;
LFindResult.ErrorMessage := Format(SBCEditorSearchNotFound, [AData^.Pattern]);
end
else
begin
LFindResult.Area := FLines.FoundAreas[LIndex];
LFindResult.ErrorMessage := '';
end;
LFindResult.Backwards := False;
LFindResult.Count := -1;
FindExecuted(@LFindResult);
end;
end;
procedure TCustomBCEditor.DoHomeKey(const ASelectionCommand: Boolean);
var
LLeftSpaceCount: Integer;
LNewCaretPosition: TBCEditorLinesPosition;
begin
LNewCaretPosition := FLines.CaretPosition;
if (FWordWrap) then
LNewCaretPosition := FRows.BORPosition[FRows.CaretPosition.Row]
else if (FLines.CaretPosition.Line < FLines.Count) then
begin
LLeftSpaceCount := LeftSpaceCount(FLines.Items[LNewCaretPosition.Line].Text);
if (LNewCaretPosition.Char > LLeftSpaceCount) then
LNewCaretPosition.Char := LLeftSpaceCount
else
LNewCaretPosition.Char := 0;
end
else
LNewCaretPosition := FLines.BOLPosition[LNewCaretPosition.Line];
MoveCaretAndSelection(LNewCaretPosition, ASelectionCommand);
end;
procedure TCustomBCEditor.DoInsertText(const AText: string);
begin
BeginUpdate();
try
if (not FLines.SelArea.IsEmpty()) then
FLines.ReplaceText(FLines.SelArea, AText)
else if ((FTextEntryMode = temOverwrite)
and (FLines.CaretPosition.Line < FLines.Count)
and (FLines.CaretPosition.Char < Length(FLines.Items[FLines.CaretPosition.Line].Text))) then
FLines.ReplaceText(LinesArea(FLines.CaretPosition, LinesPosition(FLines.CaretPosition.Char + 1, FLines.CaretPosition.Line)), AText)
else
FLines.InsertText(FLines.CaretPosition, AText);
finally
EndUpdate();
end;
end;
procedure TCustomBCEditor.DoLineComment();
var
LArea: TBCEditorLinesArea;
LComment: Integer;
LCommentsCount: Integer;
LCurrentComment: Integer;
LOpenToken: string;
begin
LCommentsCount := Length(FHighlighter.Comments.LineComments);
if (LCommentsCount > 0) then
begin
LArea.BeginPosition := FLines.BOLPosition[FLines.SelArea.BeginPosition.Line];
LArea.EndPosition := LinesPosition(LArea.BeginPosition.Char, FLines.SelArea.EndPosition.Line);
if (LArea.BeginPosition.Line < FLines.Count) then
begin
LCurrentComment := -1;
for LComment := LCommentsCount - 1 downto 0 do
if (Copy(FLines.Items[LArea.BeginPosition.Line].Text, 1 + LArea.BeginPosition.Char, Length(FHighlighter.Comments.LineComments[LComment])) = FHighlighter.Comments.LineComments[LComment]) then
LCurrentComment := LComment;
if (LCurrentComment < 0) then
LOpenToken := ''
else
LOpenToken := FHighlighter.Comments.LineComments[LCurrentComment];
FLines.BeginUpdate();
try
if (LCurrentComment >= 0) then
begin
FLines.DeleteIndent(LArea.BeginPosition, LArea.EndPosition,
FHighlighter.Comments.LineComments[LCurrentComment]);
end;
if ((LCurrentComment < 0)
or (LArea.BeginPosition.Line <> LArea.EndPosition.Line) and (LCurrentComment < LCommentsCount - 1)) then
begin
Inc(LCurrentComment);
FLines.InsertIndent(LArea.BeginPosition, LArea.EndPosition,
FHighlighter.Comments.LineComments[LCurrentComment]);
end;
if (FLines.SelArea.IsEmpty()) then
begin
LArea.BeginPosition.Char := 0;
if (LArea.EndPosition.Char > 0) then
LArea.EndPosition := FLines.EOLPosition[LArea.EndPosition.Line]
else if (LArea.IsEmpty() and (LArea.EndPosition.Line < FLines.Count - 1)) then
LArea := LinesArea(FLines.BOLPosition[LArea.EndPosition.Line + 1], FLines.BOLPosition[LArea.EndPosition.Line + 1]);
SetCaretAndSelection(LArea.EndPosition, LArea);
end;
finally
FLines.EndUpdate();
end;
end;
end;
end;
function TCustomBCEditor.DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
if (esScrolling in FState) then
ProcessClient(cjMouseDown, 0, nil, FClientRect, mbMiddle, [], FScrollingPoint);
Result := inherited;
if (not Result) then
begin
if (ssCtrl in Shift) then
ScrollTo(FTextPos.X, FTextPos.Y + FUsableRows * FLineHeight)
else if (ssShift in Shift) then
begin
if (FRows.CaretPosition.Row < FRows.Count - 2) then
MoveCaretVertically(Mouse.WheelScrollLines, False);
end
else
ScrollTo(FTextPos.X, FTextPos.Y + Mouse.WheelScrollLines * FLineHeight);
Result := True;
end;
end;
function TCustomBCEditor.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
if (esScrolling in FState) then
ProcessClient(cjMouseDown, 0, nil, FClientRect, mbMiddle, [], FScrollingPoint);
Result := inherited;
if (not Result) then
begin
if (ssCtrl in Shift) then
ScrollTo(FTextPos.X, FTextPos.Y - FUsableRows * FLineHeight)
else if (ssShift in Shift) then
begin
if (FRows.CaretPosition.Row > 0) then
MoveCaretVertically(- Mouse.WheelScrollLines, False);
end
else
ScrollTo(FTextPos.X, FTextPos.Y - Mouse.WheelScrollLines * FLineHeight);
Result := True;
end;
end;
procedure TCustomBCEditor.DoPageKey(const ACommand: TBCEditorCommand);
begin
BeginUpdate();
try
case (ACommand) of
ecPageUp, ecSelPageUp:
begin
ScrollTo(FTextPos.X, FTextPos.Y - FUsableRows * FLineHeight);
MoveCaretVertically(FUsableRows, ACommand = ecSelPageUp);
end;
ecPageDown, ecSelPageDown:
begin
ScrollTo(FTextPos.X, FTextPos.Y + FUsableRows * FLineHeight);
MoveCaretVertically(FUsableRows, ACommand = ecSelPageDown);
end;
end;
finally
EndUpdate();
end;
end;
procedure TCustomBCEditor.DoPageTopOrBottom(const ACommand: TBCEditorCommand);
var
LNewRow: Integer;
LNewCaretPosition: TBCEditorLinesPosition;
begin
case (ACommand) of
ecBOP,
ecSelBOP:
LNewRow := FTopRow;
ecEOP,
ecSelEOP:
LNewRow := FTopRow + FUsableRows - 1;
else raise ERangeError.Create('ACommand: ' + IntToStr(Ord(ACommand)));
end;
LNewCaretPosition := RowsToLines(RowsPosition(FRows.CaretPosition.Column, LNewRow));
if (not (eoBeyondEndOfFile in Options)) then
LNewCaretPosition.Line := Min(LNewCaretPosition.Line, FLines.Count - 1);
MoveCaretAndSelection(LNewCaretPosition, ACommand in [ecSelBOP, ecSelEOP]);
end;
procedure TCustomBCEditor.DoPosition(const AData: PBCEditorCommandDataPosition);
begin
MoveCaretAndSelection(AData^.Pos, AData^.Selection);
end;
procedure TCustomBCEditor.DoRedo();
begin
Redo();
end;
procedure TCustomBCEditor.DoReplace(const AData: TBCEditorCommandData);
var
LArea: TBCEditorLinesArea;
LData: PBCEditorCommandDataReplace;
LSearch: TBCEditorLines.TSearch;
LSearchPosition: TBCEditorLinesPosition;
begin
LData := @AData[0];
if ((roSelection in LData^.Options) and not FLines.SelArea.IsEmpty()) then
LArea := FLines.SelArea
else
LArea := FLines.Area;
if (not (roEntireScope in LData^.Options) and not (roSelection in LData^.Options)) then
if (roBackwards in LData^.Options) then
LArea.EndPosition := FLines.CaretPosition
else
LArea.BeginPosition := FLines.CaretPosition;
if ((Length(LData^.Pattern) > 0) and not (LArea.IsEmpty())) then
begin
LSearch := TBCEditorLines.TSearch.Create(FLines,
LArea,
roCaseSensitive in LData^.Options, roWholeWordsOnly in LData^.Options, roRegExpr in LData^.Options,
LData^.Pattern,
sjFindAndReplace, LData^.ReplaceText, roPrompt in LData^.Options);
if (FLines.Count = 0) then
LSearchPosition := FLines.BOFPosition
else if (not (roSelection in LData^.Options)) then
begin
LSearchPosition := FLines.CaretPosition;
LSearchPosition.Line := Min(LSearchPosition.Line, FLines.Count - 1);
LSearchPosition.Char := Min(LSearchPosition.Char, Length(FLines[LSearchPosition.Line]));
end
else if (roBackwards in LData^.Options) then
LSearchPosition := FLines.SelArea.EndPosition
else
LSearchPosition := FLines.SelArea.BeginPosition;
FLines.StartSearch(LSearch, LSearchPosition, roReplaceAll in LData^.Options, True, roBackwards in LData^.Options, ReplaceExecuted);
end;
end;
procedure TCustomBCEditor.DoReturnKey();
var
LInsertText: string;
begin
if (not FLines.SelArea.IsEmpty()) then
SelText := ''
else if (FLines.CaretPosition.Line >= FLines.Count) then
FLines.CaretPosition := FLines.BOLPosition[FLines.CaretPosition.Line + 1]
else if (FTextEntryMode = temInsert) then
begin
LInsertText := FLines.LineBreak;
if ((FLines.CaretPosition.Char > 0) and (eoAutoIndent in FOptions)) then
LInsertText := LInsertText + IndentText(Min(FRows.CaretPosition.Column, LeftSpaceCount(FLines.Items[FLines.CaretPosition.Line].Text, True)));
FLines.InsertText(FLines.CaretPosition, LInsertText);
end
else
begin
if ((FLines.CaretPosition.Char > 0) and (eoAutoIndent in FOptions)) then
FLines.CaretPosition := LinesPosition(Min(FLines.CaretPosition.Char, LeftSpaceCount(FLines.Items[FLines.CaretPosition.Line].Text, True)), FLines.CaretPosition.Line + 1)
else
FLines.CaretPosition := FLines.BOLPosition[FLines.CaretPosition.Line + 1];
end;
end;
procedure TCustomBCEditor.DoScroll(const ACommand: TBCEditorCommand);
begin
case (ACommand) of
ecScrollUp:
SetTextPos(FTextPos.X, FTextPos.Y - FLineHeight);
ecScrollDown:
SetTextPos(FTextPos.X, FTextPos.Y + FLineHeight);
ecScrollLeft:
SetTextPos(FTextPos.X - FHorzScrollBarDivider * FSpaceWidth, FTextPos.Y);
ecScrollRight:
SetTextPos(FTextPos.X + FHorzScrollBarDivider * FSpaceWidth, FTextPos.Y);
end;
end;
procedure TCustomBCEditor.DoScrollTo(const AData: TBCEditorCommandData);
var
LData: PBCEditorCommandDataScrollTo;
begin
LData := @AData[0];
SetTextPos(LData^.Pos);
end;
procedure TCustomBCEditor.DoSelectAll();
begin
SetCaretAndSelection(FLines.EOFPosition, FLines.Area);
end;
procedure TCustomBCEditor.DoSelection(const AData: PBCEditorCommandDataSelection);
begin
SetCaretAndSelection(AData^.CaretPos, LinesArea(AData^.BeginPos, AData^.EndPos));
end;
procedure TCustomBCEditor.DoShowFind(const First: Boolean);
begin
if (not Assigned(FFindDialog)) then
begin
FFindDialog := TFindDialog.Create(Self);
FFindDialog.Options := FFindDialog.Options - [frMatchCase, frWholeWord] + [frDown];
FFindDialog.OnFind := FindDialogFind;
FFindDialog.OnClose := FindDialogClose;
end;
FHideSelectionBeforeSearch := HideSelection;
HideSelection := False;
FFindDialog.Execute();
end;
procedure TCustomBCEditor.DoShowGotoLine();
begin
if (not Assigned(FGotoLineDialog)) then
FGotoLineDialog := TGotoLineDialog.Create(Self);
FGotoLineDialog.Min := FLeftMargin.LineNumbers.Offset;
FGotoLineDialog.Max := Max(1, FLines.Count) + FLeftMargin.LineNumbers.Offset;
FGotoLineDialog.Line := FLines.CaretPosition.Line + FLeftMargin.LineNumbers.Offset;
if (FGotoLineDialog.Execute()) then
SetCaretPos(FLines.BOLPosition[FGotoLineDialog.Line - FLeftMargin.LineNumbers.Offset]);
end;
procedure TCustomBCEditor.DoShowReplace();
begin
if (not Assigned(FReplaceDialog)) then
begin
FReplaceDialog := TReplaceDialog.Create(Self);
FReplaceDialog.FindText := '';
FReplaceDialog.ReplaceText := '';
FReplaceDialog.Options := FReplaceDialog.Options - [frMatchCase, frWholeWord, frReplaceAll];
FReplaceDialog.OnClose := FindDialogClose;
FReplaceDialog.OnFind := ReplaceDialogFind;
FReplaceDialog.OnReplace := ReplaceDialogReplace;
end;
FHideSelectionBeforeSearch := HideSelection;
HideSelection := False;
FReplaceDialog.Execute();
end;
procedure TCustomBCEditor.DoSetBookmark(const ACommand: TBCEditorCommand);
var
LIndex: Integer;
begin
LIndex := Ord(ACommand) - Ord(ecSetBookmark1);
if not DeleteBookmark(FLines.CaretPosition.Line, LIndex) then
SetBookmark(LIndex, FLines.CaretPosition);
end;
procedure TCustomBCEditor.DoSyncEdit();
begin
if (FLines.SyncEdit) then
begin
FLines.ActivateSyncEdit(FHighlighter, SyncEditActivated);
UpdateCursor();
InvalidateText();
Sleep(GClientRefreshTime); // If activation is fast enough, prevent double painting
end
else
begin
FLines.DeactivateSyncEdit();
UpdateCursor();
InvalidateText();
end;
end;
procedure TCustomBCEditor.DoTabKey(const ACommand: TBCEditorCommand);
var
LChangeScrollPastEndOfLine: Boolean;
LCharCount: Integer;
LIndex: Integer;
LLengthAfterLine: Integer;
LNewCaretPosition: TBCEditorLinesPosition;
LPreviousLine: Integer;
LPreviousLineCharCount: Integer;
LRowsPosition: TBCEditorRowsPosition;
LTabText: string;
LTabWidth: Integer;
LLinesCaretPosition: TBCEditorLinesPosition;
begin
if (not FLines.SyncEdit) then
LIndex := -1
else
LIndex := FLines.SyncEditItemIndexOf(FLines.CaretPosition);
case (ACommand) of
ecTab:
begin
if (LIndex >= 0) then
begin
if (LIndex < FLines.SyncEditItems.Count - 1) then
Inc(LIndex)
else
LIndex := 0;
SetCaretAndSelection(FLines.SyncEditItems[LIndex].Area.BeginPosition, FLines.SyncEditItems[LIndex].Area);
end
else if ((FLines.SelArea.BeginPosition.Line <> FLines.SelArea.EndPosition.Line)
and (toSelectedBlockIndent in FTabs.Options)) then
DoBlockIndent(ecBlockIndent)
else if (not FLines.SelArea.IsEmpty() or
(FLines.CaretPosition.Line >= FLines.Count)) then
begin
if (not (toTabsToSpaces in FTabs.Options)) then
begin
LTabText := StringOfChar(BCEDITOR_TAB_CHAR, FTabs.Width div FTabs.Width);
LTabText := LTabText + StringOfChar(BCEDITOR_TAB_CHAR, FTabs.Width mod FTabs.Width);
end
else
LTabText := StringOfChar(BCEDITOR_SPACE_CHAR, FTabs.Width - (FRows.CaretPosition.Column - 1) mod FTabs.Width);
DoInsertText(LTabText);
end
else
begin
FLines.BeginUpdate();
try
LLinesCaretPosition := FLines.CaretPosition;
LRowsPosition := FRows.CaretPosition;
LLengthAfterLine := Max(0, LRowsPosition.Column - FRows.Items[LRowsPosition.Row].Columns);
if LLengthAfterLine > 1 then
LCharCount := LLengthAfterLine
else
LCharCount := FTabs.Width;
if toPreviousLineIndent in FTabs.Options then
if Trim(FLines.Items[LLinesCaretPosition.Line].Text) = '' then
begin
LPreviousLine := LLinesCaretPosition.Line - 1;
while (LPreviousLine >= 0) and (FLines.Items[LPreviousLine].Text = '') do
Dec(LPreviousLine);
LPreviousLineCharCount := LeftSpaceCount(FLines.Items[LPreviousLine].Text, True);
if LPreviousLineCharCount > LLinesCaretPosition.Char + 1 then
LCharCount := LPreviousLineCharCount - LeftSpaceCount(FLines.Items[LLinesCaretPosition.Line].Text, True)
end;
if LLengthAfterLine > 1 then
LLinesCaretPosition := FLines.BOLPosition[LLinesCaretPosition.Line];
if (not (toTabsToSpaces in FTabs.Options)) then
begin
LTabText := StringOfChar(BCEDITOR_TAB_CHAR, LCharCount div FTabs.Width);
LTabText := LTabText + StringOfChar(BCEDITOR_TAB_CHAR, LCharCount mod FTabs.Width);
end
else
LTabText := StringOfChar(BCEDITOR_SPACE_CHAR, LCharCount - (LRowsPosition.Column - 1) mod FTabs.Width);
if FTextEntryMode = temInsert then
FLines.InsertText(LLinesCaretPosition, LTabText);
LChangeScrollPastEndOfLine := not (loBeyondEndOfLine in FLines.Options);
try
if LChangeScrollPastEndOfLine then
FLines.Options := FLines.Options + [loBeyondEndOfLine];
if FTextEntryMode = temOverwrite then
LTabText := StringReplace(LTabText, BCEDITOR_TAB_CHAR, StringOfChar(BCEDITOR_SPACE_CHAR, FTabs.Width),
[rfReplaceAll]);
FLines.CaretPosition := LinesPosition(LLinesCaretPosition.Char + Length(LTabText), FLines.CaretPosition.Line);
finally
if LChangeScrollPastEndOfLine then
FLines.Options := FLines.Options - [loBeyondEndOfLine];
end;
finally
FLines.EndUpdate();
end;
end;
end;
ecShiftTab:
begin
if (FLines.SelArea.IsEmpty()) then
begin
if (FRows.CaretPosition.Column > 0) then
if (FLines.Char[LinesPosition(FLines.CaretPosition.Char - 1, FLines.CaretPosition.Line)] = BCEDITOR_TAB_CHAR) then
FLines.CaretPosition := LinesPosition(FLines.CaretPosition.Char - 1, FLines.CaretPosition.Line)
else if (FRows.CaretPosition.Column mod FTabs.Width = 0) then
FLines.CaretPosition := RowsToLines(RowsPosition(FRows.CaretPosition.Column - FTabs.Width, FRows.CaretPosition.Row))
else
FLines.CaretPosition := RowsToLines(RowsPosition(FRows.CaretPosition.Column - FRows.CaretPosition.Column mod FTabs.Width, FRows.CaretPosition.Row));
end
else if (LIndex >= 0) then
begin
if (LIndex = 0) then
LIndex := FLines.SyncEditItems.Count - 1
else
Dec(LIndex);
SetCaretAndSelection(FLines.SyncEditItems[LIndex].Area.BeginPosition, FLines.SyncEditItems[LIndex].Area);
end
else if ((toSelectedBlockIndent in FTabs.Options) and not FLines.SelArea.IsEmpty()) then
DoBlockIndent(ecBlockUnindent)
else
begin
if (toTabsToSpaces in FTabs.Options) then
LTabWidth := FTabs.Width
else
LTabWidth := 1;
LNewCaretPosition := LinesPosition(Max(0, FLines.CaretPosition.Char - LTabWidth + 1), FLines.CaretPosition.Line);
if ((LNewCaretPosition <> FLines.CaretPosition)
and (Copy(FLines.Items[FLines.CaretPosition.Line].Text, 1 + LNewCaretPosition.Char, LTabWidth) = BCEDITOR_TAB_CHAR)) then
FLines.DeleteText(LinesArea(LNewCaretPosition, FLines.CaretPosition));
end;
end;
end;
end;
procedure TCustomBCEditor.DoText(const AData: PBCEditorCommandDataText);
var
LOldCaretPosition: TBCEditorLinesPosition;
begin
FLines.BeginUpdate();
try
if (AData.Delete and not FLines.SelArea.IsEmpty()) then
FLines.DeleteText(FLines.SelArea);
LOldCaretPosition := FLines.CaretPosition;
FLines.InsertText(FLines.CaretPosition, AData^.Text);
if (AData.Selection) then
SetCaretAndSelection(FLines.CaretPosition, LinesArea(LOldCaretPosition, FLines.CaretPosition));
finally
FLines.EndUpdate();
end;
end;
procedure TCustomBCEditor.DoToggleSelectedCase(const ACommand: TBCEditorCommand);
var
LSelectedText: string;
begin
if (not FLines.SelArea.IsEmpty()) then
begin
LSelectedText := SelText;
case (ACommand) of
ecUpperCase:
SelText := AnsiUpperCase(LSelectedText);
ecLowerCase:
SelText := AnsiLowerCase(LSelectedText);
else ERangeError.Create('ACommand: ' + IntToStr(Ord(ACommand)));
end;
end;
end;
procedure TCustomBCEditor.DoTripleClick();
begin
FLines.SelArea := FLines.LineArea[FLines.CaretPosition.Line];
FLastDoubleClickTime := 0;
end;
procedure TCustomBCEditor.DoUndo();
begin
Undo();
end;
procedure TCustomBCEditor.DoUnselect();
begin
FLines.SelArea := LinesArea(FLines.CaretPosition, FLines.CaretPosition);
end;
procedure TCustomBCEditor.DoWordLeft(const ACommand: TBCEditorCommand);
var
LNewCaretPosition: TBCEditorLinesPosition;
begin
if ((FLines.CaretPosition.Line = 0) and (FLines.Count = 0)) then
FLines.CaretPosition := FLines.BOFPosition
else if (FLines.CaretPosition.Line < FLines.Count) then
begin
LNewCaretPosition := FLines.CaretPosition;
if (LNewCaretPosition.Line >= FLines.Count) then
LNewCaretPosition := FLines.EOLPosition[FLines.Count - 1];
if ((LNewCaretPosition.Char = 0)
or (LNewCaretPosition.Char >= Length(FLines.Items[LNewCaretPosition.Line].Text))
or IsWordBreakChar(FLines.Items[LNewCaretPosition.Line].Text[1 + LNewCaretPosition.Char - 1])) then
LNewCaretPosition := PreviousWordPosition(LNewCaretPosition);
if ((LNewCaretPosition.Char > 0)
and ((LNewCaretPosition = FLines.CaretPosition) or (LNewCaretPosition.Char < Length(FLines.Items[LNewCaretPosition.Line].Text)))
and not IsWordBreakChar(FLines.Items[LNewCaretPosition.Line].Text[1 + LNewCaretPosition.Char - 1])) then
LNewCaretPosition := WordBegin(LNewCaretPosition);
MoveCaretAndSelection(LNewCaretPosition, ACommand = ecSelWordLeft);
end
else if (FLines.CaretPosition.Line = FLines.Count) then
FLines.CaretPosition := FLines.EOLPosition[FLines.CaretPosition.Line - 1]
else
FLines.CaretPosition := FLines.BOLPosition[FLines.CaretPosition.Line - 1];
end;
procedure TCustomBCEditor.DoWordRight(const ACommand: TBCEditorCommand);
var
LNewCaretPosition: TBCEditorLinesPosition;
begin
LNewCaretPosition := FLines.CaretPosition;
if (LNewCaretPosition.Line < FLines.Count) then
begin
if ((LNewCaretPosition.Char < Length(FLines.Items[LNewCaretPosition.Line].Text))
and not IsWordBreakChar(FLines.Char[LNewCaretPosition])) then
begin
LNewCaretPosition := WordEnd();
Inc(LNewCaretPosition.Char);
while ((LNewCaretPosition.Char < Length(FLines.Items[LNewCaretPosition.Line].Text))) and IsEmptyChar(FLines.Char[LNewCaretPosition]) do
Inc(LNewCaretPosition.Char);
end;
if ((LNewCaretPosition.Char >= Length(FLines.Items[LNewCaretPosition.Line].Text))
or IsWordBreakChar(FLines.Char[LNewCaretPosition])) then
LNewCaretPosition := NextWordPosition(LNewCaretPosition);
MoveCaretAndSelection(LNewCaretPosition, ACommand = ecSelWordRight);
end;
end;
procedure TCustomBCEditor.DragCanceled();
begin
inherited;
SetInsertPos(InvalidPos);
end;
procedure TCustomBCEditor.DragDrop(ASource: TObject; X, Y: Integer);
begin
if (not FReadOnly) then
begin
inherited;
SetInsertPos(InvalidPos);
end;
end;
function TCustomBCEditor.DragEnter(const dataObj: IDataObject; grfKeyState: Longint;
pt: TPoint; var dwEffect: Longint): HResult;
var
LFormat: FORMATETC;
LMedium: STGMEDIUM;
begin
if (dwEffect = DROPEFFECT_NONE) then
Result := E_INVALIDARG
else
begin
LFormat.cfFormat := CF_UNICODETEXT;
LFormat.ptd := nil;
LFormat.dwAspect := DVASPECT_CONTENT;
LFormat.lindex := -1;
LFormat.tymed := TYMED_HGLOBAL;
if (dataObj.QueryGetData(LFormat) = S_OK) then
Result := DragOver(grfKeyState, pt, dwEffect)
else
begin
LFormat.cfFormat := CF_HDROP;
LFormat.ptd := nil;
LFormat.dwAspect := DVASPECT_CONTENT;
LFormat.lindex := -1;
LFormat.tymed := TYMED_HGLOBAL;
if (not (eoDropFiles in FOptions) or (dataObj.QueryGetData(LFormat) <> S_OK)) then
Result := E_UNEXPECTED
else
begin
OleCheck(dataObj.GetData(LFormat, LMedium));
if (DragQueryFile(LMedium.hGlobal, $FFFFFFFF, nil, 0) <> 1) then
Result := E_UNEXPECTED
else
Result := DragOver(grfKeyState, pt, dwEffect);
end;
end;
end;
end;
function TCustomBCEditor.DragLeave(): HResult;
begin
SetInsertPos(InvalidPos);
Result := S_OK;
end;
function TCustomBCEditor.DragOver(grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult;
var
LPosition: TBCEditorLinesPosition;
LScreen: TPoint;
begin
if (FReadOnly
or (pt.X <= FLeftMarginWidth)) then
begin
SetInsertPos(InvalidPos);
dwEffect := DROPEFFECT_NONE;
end
else
begin
LScreen := ScreenToClient(pt);
LPosition := ClientToLines(LScreen.X, LScreen.Y);
if (FLines.SelArea.Contains(LPosition)
or not ProcessCommand(ecAcceptDrop, TBCEditorCommandDataPosition.Create(LPosition))) then
begin
SetInsertPos(InvalidPos);
dwEffect := DROPEFFECT_NONE;
end
else
begin
SetInsertPos(LPosition);
if (grfKeyState and MK_CONTROL <> 0) then
dwEffect := DROPEFFECT_COPY
else if (grfKeyState and MK_SHIFT <> 0) then
dwEffect := DROPEFFECT_MOVE
else if (esDragging in FState) then
dwEffect := DROPEFFECT_MOVE
else
dwEffect := DROPEFFECT_COPY;
end;
end;
Result := S_OK;
end;
procedure TCustomBCEditor.DragOver(ASource: TObject; X, Y: Integer;
AState: TDragState; var AAccept: Boolean);
var
LPosition: TBCEditorLinesPosition;
LScreen: TPoint;
begin
LScreen := ScreenToClient(Point(X, Y));
LPosition := ClientToLines(LScreen.X, LScreen.Y);
AAccept := not FReadOnly and not ProcessCommand(ecAcceptDrop, TBCEditorCommandDataPosition.Create(LPosition));
if (AAccept) then
inherited;
end;
function TCustomBCEditor.Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint;
var dwEffect: Longint): HResult;
var
LMedium: STGMEDIUM;
LText: string;
begin
if (dwEffect and (DROPEFFECT_COPY or DROPEFFECT_MOVE) = 0) then
Result := E_INVALIDARG
else
begin
LText := '';
if (not ProcessCommand(ecDropOLE, TBCEditorCommandDataDropOLE.Create(FInsertPos, dataObj))) then
Result := E_UNEXPECTED
else
begin
if (grfKeyState and MK_CONTROL <> 0) then
dwEffect := DROPEFFECT_COPY
else if (grfKeyState and MK_SHIFT <> 0) then
dwEffect := DROPEFFECT_MOVE
else if (esDragging in FState) then
dwEffect := DROPEFFECT_MOVE
else
dwEffect := DROPEFFECT_COPY;
if (not Assigned(LMedium.unkForRelease)) then
ReleaseStgMedium(LMedium)
else
IUnknown(LMedium.unkForRelease)._Release();
Result := S_OK;
end;
if (Result = S_OK) then
Result := DragLeave();
end;
end;
procedure TCustomBCEditor.EMCanUndo(var AMessage: TMessage);
begin
AMessage.Result := LRESULT(CanUndo);
end;
procedure TCustomBCEditor.EMCharFromPos(var AMessage: TMessage);
var
LPosition: TBCEditorLinesPosition;
begin
LPosition := ClientToLines(AMessage.LParamLo, AMessage.LParamHi, True);
AMessage.ResultLo := LPosition.Char;
AMessage.ResultHi := LPosition.Line;
end;
procedure TCustomBCEditor.EMEmptyUndoBuffer(var AMessage: TMessage);
begin
FLines.ClearUndo();
end;
procedure TCustomBCEditor.EMFmtLines(var AMessage: TMessage);
begin
FFmtLines := BOOL(AMessage.WParam);
AMessage.Result := AMessage.WParam;
end;
procedure TCustomBCEditor.EMGetFirstVisible(var AMessage: TMessage);
begin
if (FTopRow < FRows.Count) then
AMessage.Result := FRows.Items[FTopRow].Line
else
AMessage.Result := FLines.Count - 1;
end;
procedure TCustomBCEditor.EMGetHandle(var AMessage: TMessage);
begin
AMessage.Result := 0;
end;
procedure TCustomBCEditor.EMGetIMEStatus(var AMessage: TMessage);
begin
if (AMessage.WParam <> EMSIS_COMPOSITIONSTRING) then
AMessage.Result := 0
else
AMessage.Result := FIMEStatus;
end;
procedure TCustomBCEditor.EMGetLine(var AMessage: TMessage);
var
LLine: Integer;
begin
if (AMessage.WParam > 0) then
LLine := Integer(AMessage.WParam)
else if (FTopRow >= FRows.Count) then
LLine := -1
else
LLine := FRows.Items[FTopRow].Line;
if ((LLine < 0) or (AMessage.LParam = 0) or (Word(Pointer(AMessage.LParam)^) >= Length(FLines.Items[LLine].Text))) then
AMessage.Result := 0
else
StrPCopy(PChar(AMessage.LParam), FLines.Items[LLine].Text);
end;
procedure TCustomBCEditor.EMGetLineCount(var AMessage: TMessage);
begin
if (FLines.Count = 0) then
AMessage.Result := 1
else
AMessage.Result := LPARAM(FLines.Count);
end;
procedure TCustomBCEditor.EMGetModify(var AMessage: TMessage);
begin
AMessage.Result := LRESULT(Modified);
end;
procedure TCustomBCEditor.EMGetRect(var AMessage: TMessage);
begin
if (AMessage.LParam <> 0) then
Windows.PRect(AMessage.LParam)^ := FTextRect;
end;
procedure TCustomBCEditor.EMGetSel(var AMessage: TMessage);
var
LSelStart: Integer;
LSelLength: Integer;
begin
LSelStart := SelStart;
LSelLength := SelLength;
if (AMessage.WParam <> 0) then
PDWORD(AMessage.WParam)^ := LSelStart;
if (AMessage.WParam <> 0) then
PDWORD(AMessage.WParam)^ := LSelStart + SelLength;
if (LSelStart + LSelLength > 65535) then
AMessage.Result := -1
else
begin
AMessage.ResultLo := LSelStart;
AMessage.ResultHi := LSelStart + LSelLength;
end;
end;
procedure TCustomBCEditor.EMGetThumb(var AMessage: TMessage);
begin
AMessage.Result := FTopRow * FLineHeight;
end;
procedure TCustomBCEditor.EMLineFromChar(var AMessage: TMessage);
begin
if (Integer(AMessage.WParam) <> -1) then
if (AMessage.WParam <= WPARAM(FLines.TextLength)) then
AMessage.Result := FLines.PositionOf(Integer(AMessage.WParam)).Line
else
AMessage.Result := 0
else if (not FLines.SelArea.IsEmpty()) then
AMessage.Result := FLines.SelArea.BeginPosition.Line
else
AMessage.Result := Min(Max(0, FLines.Count - 1), FLines.CaretPosition.Line);
end;
procedure TCustomBCEditor.EMLineIndex(var AMessage: TMessage);
var
LLine: Integer;
begin
if (Integer(AMessage.WParam) = - 1) then
LLine := FLines.CaretPosition.Line
else
LLine := Integer(AMessage.WParam);
AMessage.Result := LRESULT(FLines.CharIndexOf(FLines.BOLPosition[LLine]));
end;
procedure TCustomBCEditor.EMLineLength(var AMessage: TMessage);
var
LLine: Integer;
begin
if (Integer(AMessage.WParam) = -1) then
AMessage.Result := FLines.CharIndexOf(FLines.SelArea.BeginPosition) - FLines.CharIndexOf(FLines.BOLPosition[FLines.SelArea.BeginPosition.Line])
else if (Integer(AMessage.WParam) < FLines.TextLength) then
AMessage.Result := 0
else
begin
LLine := FLines.PositionOf(AMessage.WParam).Line;
if (LLine < FLines.Count) then
AMessage.Result := Length(FLines.Items[LLine].Text)
else
AMessage.Result := 0;
end;
end;
procedure TCustomBCEditor.EMLineScroll(var AMessage: TMessage);
begin
AMessage.Result := LRESULT(TRUE);
end;
procedure TCustomBCEditor.EMPosFromChar(var AMessage: TMessage);
var
LClient: TPoint;
begin
if (AMessage.WParam >= WPARAM(FLines.TextLength)) then
AMessage.Result := -1
else
begin
LClient := RowsToClient(LinesToRows(FLines.PositionOf(AMessage.WParam)));
AMessage.ResultLo := LClient.X;
AMessage.ResultHi := LClient.Y;
end;
end;
procedure TCustomBCEditor.EMReplaceSel(var AMessage: TMessage);
begin
SelText := StrPas(PChar(AMessage.LParam));
if (not BOOL(AMessage.WParam)) then
ClearUndo();
end;
procedure TCustomBCEditor.EMScroll(var AMessage: TMessage);
begin
case (AMessage.WParam) of
SB_LINEDOWN: MoveCaretVertically(1, False);
SB_LINEUP: MoveCaretVertically(-1, False);
SB_PAGEDOWN: MoveCaretVertically(FVisibleRows, False);
SB_PAGEUP: MoveCaretVertically(- FVisibleRows, False);
end;
end;
procedure TCustomBCEditor.EMScrollCaret(var AMessage: TMessage);
begin
ScrollToCaret();
end;
procedure TCustomBCEditor.EMSetIMEStatus(var AMessage: TMessage);
begin
if (AMessage.WParam <> EMSIS_COMPOSITIONSTRING) then
AMessage.Result := 0
else
begin
AMessage.Result := FIMEStatus;
FIMEStatus := AMessage.LParam;
end;
end;
procedure TCustomBCEditor.EMSetModify(var AMessage: TMessage);
begin
Modified := BOOL(AMessage.WParam);
end;
procedure TCustomBCEditor.EMSetReadOnly(var AMessage: TMessage);
begin
ReadOnly := BOOL(AMessage.WParam);
AMessage.Result := LRESULT(TRUE);
end;
procedure TCustomBCEditor.EMSetSel(var AMessage: TMessage);
var
LSelArea: TBCEditorLinesArea;
begin
if (AMessage.wParam = WPARAM(-1)) then
SelLength := 0
else if (AMessage.lParam = LPARAM(-1)) then
SelectAll()
else
begin
LSelArea.BeginPosition := FLines.PositionOf(Integer(AMessage.WParam));
LSelArea.EndPosition := FLines.PositionOf(Integer(AMessage.LParam), LSelArea.BeginPosition);
ProcessCommand(ecSel, TBCEditorCommandDataSelection.Create(LSelArea.EndPosition, LSelArea));
end;
end;
procedure TCustomBCEditor.EMSetTabStop(var AMessage: TMessage);
type
PUNIT = ^UINT;
begin
if (AMessage.WParam <> 1) then
AMessage.Result := LRESULT(FALSE)
else
begin
FTabs.Width := PUNIT(AMessage.LParam)^;
AMessage.Result := LRESULT(TRUE);
end;
end;
procedure TCustomBCEditor.EMUndo(var AMessage: TMessage);
begin
AMessage.Result := LRESULT(CanUndo);
Undo();
end;
procedure TCustomBCEditor.EndUndoBlock();
begin
FLines.EndUpdate();
end;
procedure TCustomBCEditor.EndUpdate();
begin
Dec(FUpdateCount);
if (FUpdateCount = 0) then SetUpdateState(False);
end;
procedure TCustomBCEditor.ExpandCodeFoldingLevel(const AFirstLevel: Integer; const ALastLevel: Integer);
var
LFirstLine: Integer;
LLastLine: Integer;
LLevel: Integer;
LLine: Integer;
LRange: TBCEditorCodeFoldingRanges.TRange;
LRangeLevel: Integer;
begin
if (not FLines.SelArea.IsEmpty()) then
begin
LFirstLine := FLines.SelArea.BeginPosition.Line;
LLastLine := FLines.SelArea.EndPosition.Line;
end
else
begin
LFirstLine := 0;
LLastLine := FLines.Count - 1;
end;
BeginUpdate();
LLevel := -1;
for LLine := LFirstLine to LLastLine do
begin
LRange := TBCEditorCodeFoldingRanges.TRange(FLines.Items[LLine].CodeFolding.BeginRange);
if (Assigned(LRange)) then
begin
if LLevel = -1 then
LLevel := LRange.FoldRangeLevel;
LRangeLevel := LRange.FoldRangeLevel - LLevel;
if ((AFirstLevel <= LRangeLevel) and (LRangeLevel <= ALastLevel)
and LRange.Collapsed) then
ExpandCodeFoldingRange(LRange);
end;
end;
EndUpdate();
end;
function TCustomBCEditor.ExpandCodeFoldingLines(const AFirstLine: Integer = -1; const ALastLine: Integer = -1): Integer;
var
LFirstLine: Integer;
LLastLine: Integer;
LLine: Integer;
LRange: TBCEditorCodeFoldingRanges.TRange;
begin
if (AFirstLine >= 0) then
LFirstLine := AFirstLine
else
LFirstLine := 0;
if (ALastLine >= -1) then
LLastLine := ALastLine
else if (AFirstLine >= 0) then
LLastLine := AFirstLine
else
LLastLine := FLines.Count - 1;
Result := 0;
for LLine := LFirstLine to LLastLine do
begin
LRange := TBCEditorCodeFoldingRanges.TRange(FLines.Items[LLine].CodeFolding.BeginRange);
if (Assigned(LRange) and LRange.Collapsed) then
begin
ExpandCodeFoldingRange(LRange);
Inc(Result);
end;
end;
end;
procedure TCustomBCEditor.ExpandCodeFoldingRange(const ARange: TBCEditorCodeFoldingRanges.TRange);
var
LBeginRow: Integer;
LEndRow: Integer;
LLine: Integer;
begin
if (ARange.Collapsed) then
begin
ARange.Collapsed := False;
ARange.SetParentCollapsedOfSubCodeFoldingRanges(False, ARange.FoldRangeLevel);
for LLine := ARange.BeginLine + 1 to ARange.EndLine do
InsertLineIntoRows(LLine, False);
LBeginRow := FLines.Items[ARange.BeginLine].FirstRow;
LEndRow := FLines.Items[ARange.EndLine].FirstRow + FLines.Items[ARange.EndLine].RowCount - 1;
if ((LBeginRow <= FTopRow + FVisibleRows) and (LEndRow >= FTopRow)) then
InvalidateRect(
Rect(
FTextRect.Left, Max(0, LBeginRow - FTopRow) * FLineHeight,
FTextRect.Right, FTextRect.Bottom));
InvalidateScrollBars();
end;
end;
function TCustomBCEditor.ExecuteAction(Action: TBasicAction): Boolean;
begin
Result := True;
if (Action is TEditCut) then
ProcessCommand(ecCutToClipboard)
else if (Action is TEditCopy) then
ProcessCommand(ecCopyToClipboard)
else if (Action is TEditPaste) then
ProcessCommand(ecPasteFromClipboard)
else if (Action is TEditDelete) then
ProcessCommand(ecBackspace)
else if (Action is TEditSelectAll) then
ProcessCommand(ecSelectAll)
else if (Action is TEditUndo) then
ProcessCommand(ecUndo)
else if (Action is TSearchFindFirst) then
ProcessCommand(ecShowFind)
else if (Action is TSearchFindNext) then
ProcessCommand(ecFindNext)
else if (Action is TSearchReplace) then
ProcessCommand(ecShowReplace)
else
Result := inherited;
end;
procedure TCustomBCEditor.ExportToHTML(const AFileName: string; const ACharSet: string = '';
AEncoding: TEncoding = nil);
var
LFileStream: TFileStream;
begin
LFileStream := TFileStream.Create(AFileName, fmCreate);
try
ExportToHTML(LFileStream, ACharSet, AEncoding);
finally
LFileStream.Free;
end;
end;
procedure TCustomBCEditor.ExportToHTML(AStream: TStream; const ACharSet: string = '';
AEncoding: TEncoding = nil);
begin
with TBCEditorExportHTML.Create(FLines, FHighlighter, Font, FTabs.Width, ACharSet) do
try
SaveToStream(AStream, AEncoding);
finally
Free;
end;
end;
procedure TCustomBCEditor.FindDialogClose(Sender: TObject);
begin
HideSelection := FHideSelectionBeforeSearch;
end;
procedure TCustomBCEditor.FindDialogFind(Sender: TObject);
var
LOptions: TBCEditorFindOptions;
begin
LOptions := LOptions - [foRegExpr];
if (frDown in TFindDialog(Sender).Options) then
LOptions := LOptions - [foBackwards]
else
LOptions := LOptions + [foBackwards];
if (frMatchCase in TFindDialog(Sender).Options) then
LOptions := LOptions + [foCaseSensitive]
else
LOptions := LOptions - [foCaseSensitive];
LOptions := LOptions - [foEntireScope];
if (FLines.SelArea.IsEmpty()) then
LOptions := LOptions - [foSelection]
else
LOptions := LOptions + [foSelection];
if (frWholeWord in TFindDialog(Sender).Options) then
LOptions := LOptions + [foWholeWordsOnly]
else
LOptions := LOptions - [foWholeWordsOnly];
FLastSearch := lsFind;
FLastSearchData := TBCEditorCommandDataFind.Create(TFindDialog(Sender).FindText, LOptions);
ProcessCommand(ecFindFirst, FLastSearchData);
end;
procedure TCustomBCEditor.FindExecuted(const AData: Pointer);
var
LHandle: THandle;
LSearchResult: TBCEditorLines.TSearchResult;
begin
LSearchResult := TBCEditorLines.PSearchResult(AData)^;
if ((LSearchResult.Area <> InvalidLinesArea)
and (FFindState = fsWrappedAround)
and not AskSearchWrapAround(AData)) then
LSearchResult.Area := InvalidLinesArea;
if ((LSearchResult.Area = InvalidLinesArea)
and (LSearchResult.ErrorMessage = '')) then
LSearchResult.ErrorMessage := Format(SBCEditorSearchNotFound, [PBCEditorCommandDataFind(FLastSearchData)^.Pattern]);
if (LSearchResult.Area <> InvalidLinesArea) then
begin
Include(FState, esCenterCaret);
try
if (LSearchResult.Backwards) then
SetCaretAndSelection(LSearchResult.Area.BeginPosition, LSearchResult.Area)
else
SetCaretAndSelection(LSearchResult.Area.EndPosition, LSearchResult.Area);
finally
Exclude(FState, esCenterCaret);
end;
end;
UpdateCursor();
if ((LSearchResult.Area = InvalidLinesArea)
and not (foEntireScope in PBCEditorCommandDataFind(FLastSearchData)^.Options)
and (not LSearchResult.Backwards and (FFindArea.BeginPosition > FLines.BOFPosition)
or LSearchResult.Backwards and (FFindArea.EndPosition < FLines.EOFPosition))
and (FFindState = fsRequested)) then
PostMessage(WindowHandle, UM_FIND_WRAPAROUND, 0, 0)
else
begin
if ((LSearchResult.Area <> InvalidLinesArea)
or (FFindState = fsRequested)) then
if (Assigned(FOnFindExecuted)) then
FOnFindExecuted(Self, LSearchResult.ErrorMessage)
else if (LSearchResult.ErrorMessage <> '') then
begin
if (Assigned(FFindDialog)) then
LHandle := FFindDialog.Handle
else
LHandle := WindowHandle;
MessageBox(LHandle, PChar(LSearchResult.ErrorMessage), PChar(SBCEditorMessageInformation), MB_ICONINFORMATION or MB_OK);
end;
if ((eoHighlightAllFoundTexts in FOptions)
and (LSearchResult.Area <> InvalidLinesArea)) then
begin
if (FFindState in [fsRequested, fsWrappedAround]) then
PostMessage(WindowHandle, UM_FIND_ALLAREAS, 0, 0)
else if (FFindState = fsAllAreas) then
begin
Include(FState, esHighlightSearchAllAreas);
InvalidateText();
end;
end;
end;
end;
procedure TCustomBCEditor.FontChanged(ASender: TObject);
begin
FState := FState + [esFontChanged];
InvalidateScrollBars();
InvalidateClient();
end;
function TCustomBCEditor.GetBookmark(const AIndex: Integer; var ALinesPosition: TBCEditorLinesPosition): Boolean;
var
LIndex: Integer;
begin
Result := False;
LIndex := FLines.Bookmarks.IndexOfIndex(AIndex);
if (LIndex >= 0) then
begin
ALinesPosition := FLines.Bookmarks[LIndex].Pos;
Result := True;
end;
end;
function TCustomBCEditor.GetCanPaste(): Boolean;
begin
Result := not FReadOnly and (IsClipboardFormatAvailable(CF_TEXT) or IsClipboardFormatAvailable(CF_UNICODETEXT));
end;
function TCustomBCEditor.GetCanRedo(): Boolean;
begin
Result := not FReadOnly and FLines.CanRedo;
end;
function TCustomBCEditor.GetCanUndo(): Boolean;
begin
Result := not FReadOnly and FLines.CanUndo;
end;
function TCustomBCEditor.GetCaretPos(): TPoint;
begin
Result := FLines.CaretPosition;
end;
function TCustomBCEditor.GetCharAt(APos: TPoint): Char;
begin
Result := FLines.Char[APos];
end;
function TCustomBCEditor.GetCursor(): TCursor;
begin
Result := inherited Cursor;
end;
function TCustomBCEditor.GetFindTokenData(const ARow: Integer; var ALeft: Integer;
out ABeginRange: TBCEditorHighlighter.TRange;
out AText: PChar; out ALength, AChar: Integer; out AColumn: Integer): Boolean;
var
LIndex: Integer;
begin
Result := ARow < FRows.Count;
if (Result) then
if (Assigned(FRows.Items[ARow].Parts)) then
begin
LIndex := 0;
while ((LIndex + 1 < Length(FRows.Items[ARow].Parts))
and (ALeft > FRows.Items[ARow].Parts[LIndex + 1].Left)) do
Inc(LIndex);
ALeft := FRows.Items[ARow].Parts[LIndex].Left;
ABeginRange := FRows.Items[ARow].Parts[LIndex].BeginRange;
AText := @FLines.Items[FRows.Items[ARow].Line].Text[1 + FRows.Items[ARow].Char + FRows.Items[ARow].Parts[LIndex].Char];
ALength := FRows.Items[ARow].Length - FRows.Items[ARow].Parts[LIndex].Char;
AChar := FRows.Items[ARow].Parts[LIndex].Char;
AColumn := FRows.Items[ARow].Parts[LIndex].Column;
end
else if (FLines.Items[FRows.Items[ARow].Line].Text <> '') then
begin
ALeft := 0;
ABeginRange := FRows.Items[ARow].BeginRange;
AText := @FLines.Items[FRows.Items[ARow].Line].Text[1 + FRows.Items[ARow].Char];
ALength := FRows.Items[ARow].Length;
AChar := 0;
AColumn := 0;
end
else
begin
ALeft := 0;
ABeginRange := nil;
AText := nil;
ALength := 0;
AChar := 0;
AColumn := 0;
end;
end;
function TCustomBCEditor.GetLeadingExpandedLength(const AStr: string; const ABorder: Integer = 0): Integer;
var
LChar: PChar;
LLength: Integer;
begin
Result := 0;
LChar := PChar(AStr);
if ABorder > 0 then
LLength := Min(PInteger(LChar - 2)^, ABorder)
else
LLength := PInteger(LChar - 2)^;
while LLength > 0 do
begin
if LChar^ = BCEDITOR_TAB_CHAR then
Inc(Result, FTabs.Width - (Result mod FTabs.Width))
else
if (CharInSet(LChar^, [BCEDITOR_NONE_CHAR, BCEDITOR_SPACE_CHAR])) then
Inc(Result)
else
Exit;
Inc(LChar);
Dec(LLength);
end;
end;
function TCustomBCEditor.GetLineIndentLevel(const ALine: Integer): Integer;
var
LLineEndPos: PChar;
LLinePos: PChar;
begin
Assert((0 <= ALine) and (ALine < FLines.Count));
Result := 0;
if (FLines.Items[ALine].Text <> '') then
begin
LLinePos := @FLines.Items[ALine].Text[1];
LLineEndPos := @FLines.Items[ALine].Text[Length(FLines.Items[ALine].Text)];
while ((LLinePos <= LLineEndPos) and CharInSet(LLinePos^, [BCEDITOR_NONE_CHAR, BCEDITOR_TAB_CHAR, BCEDITOR_SPACE_CHAR])) do
begin
if (LLinePos^ <> BCEDITOR_TAB_CHAR) then
Inc(Result)
else
Inc(Result, FTabs.Width - Result mod FTabs.Width);
Inc(LLinePos);
end;
end;
end;
function TCustomBCEditor.GetMarks(): TBCEditorLines.TMarkList;
begin
Result := FLines.Marks;
end;
function TCustomBCEditor.GetModified(): Boolean;
begin
Result := FLines.Modified;
end;
function TCustomBCEditor.GetSearchResultCount: Integer;
begin
Result := FLines.FoundAreas.Count;
end;
function TCustomBCEditor.GetSelLength(): Integer;
begin
Result := FLines.CharIndexOf(FLines.SelArea.EndPosition, FLines.SelArea.BeginPosition);
end;
function TCustomBCEditor.GetSelStart(): Integer;
begin
Result := FLines.CharIndexOf(FLines.SelArea.BeginPosition);
end;
function TCustomBCEditor.GetSelText(): string;
begin
Result := FLines.TextIn[FLines.SelArea];
end;
function TCustomBCEditor.GetText(): string;
begin
Result := FLines.Text;
end;
function TCustomBCEditor.GetUndoOptions(): TBCEditorUndoOptions;
begin
Result := [];
if (loUndoGrouped in FLines.Options) then
Result := Result + [uoGroupUndo];
if (loUndoAfterLoad in FLines.Options) then
Result := Result + [uoUndoAfterLoad];
if (loUndoAfterSave in FLines.Options) then
Result := Result + [uoUndoAfterSave];
end;
function TCustomBCEditor.GetWordAt(ALinesPos: TPoint): string;
var
LArea: TBCEditorLinesArea;
begin
LArea := FLines.WordArea[ALinesPos];
if (LArea = InvalidLinesArea) then
Result := ''
else
Result := FLines.TextIn[LArea];
end;
function TCustomBCEditor.GiveFeedback(dwEffect: Longint): HResult;
begin
Result := DRAGDROP_S_USEDEFAULTCURSORS;
end;
procedure TCustomBCEditor.GotoBookmark(const AIndex: Integer);
var
LNewCaretPosition: TBCEditorLinesPosition;
begin
if (GetBookmark(AIndex, LNewCaretPosition)) then
begin
Include(FState, esCenterCaret);
try
FLines.CaretPosition := LNewCaretPosition;
finally
Exclude(FState, esCenterCaret);
end;
end;
end;
procedure TCustomBCEditor.GotoNextBookmark;
var
LIndex: Integer;
LMark: TBCEditorLines.TMark;
begin
for LIndex := 0 to FLines.Bookmarks.Count - 1 do
begin
LMark := FLines.Bookmarks.Items[LIndex];
if (LMark.Pos > FLines.CaretPosition) then
begin
GotoBookmark(LMark.Index);
Exit;
end;
end;
if FLines.Bookmarks.Count > 0 then
GotoBookmark(FLines.Bookmarks.Items[0].Index);
end;
procedure TCustomBCEditor.GotoPreviousBookmark;
var
LIndex: Integer;
LMark: TBCEditorLines.TMark;
begin
for LIndex := FLines.Bookmarks.Count - 1 downto 0 do
begin
LMark := FLines.Bookmarks.Items[LIndex];
if (LMark.Pos < FLines.CaretPosition) then
begin
GotoBookmark(LMark.Index);
Exit;
end;
end;
if FLines.Bookmarks.Count > 0 then
GotoBookmark(FLines.Bookmarks.Items[FLines.Bookmarks.Count - 1].Index);
end;
procedure TCustomBCEditor.HighlighterChanged(ASender: TObject);
var
LElement: TBCEditorHighlighter.PElement;
begin
LElement := FHighlighter.Colors.GetElement(BCEDITOR_ATTRIBUTE_ELEMENT_EDITOR);
if (Assigned(LElement) and (LElement^.Foreground <> clNone)) then
Font.Color := LElement^.Foreground
else
Font.Color := clWindowText;
if (Assigned(LElement) and (LElement^.Background <> clNone)) then
Color := LElement^.Background
else
Color := clWindow;
FLines.TerminateJob();
InvalidateRows();
Include(FState, esHighlighterChanged);
end;
procedure TCustomBCEditor.Idle();
// Will be executed after painting
begin
FIdleTerminated := False;
while (not FIdleTerminated and (FPendingJobs <> [])) do
begin
if (ijUpdateScrollBars in FPendingJobs) then
begin
Exclude(FPendingJobs, ijUpdateScrollBars);
if (esScrollBarsInvalid in FState) then
UpdateScrollBars();
end
else if (ijBuildRows in FPendingJobs) then
begin
Exclude(FPendingJobs, ijBuildRows);
BuildRows(IdleTerminated);
end
else
FPendingJobs := [];
FIdleTerminated := FIdleTerminated or IdleTerminated();
end;
if (FIdleTerminated) then
SetTimer(WindowHandle, tiIdle, 10, nil);
end;
function TCustomBCEditor.IdleTerminated(): Boolean;
// Check, if there is any other request inside the parent form
var
LMsg: TMsg;
begin
if (not FIdleTerminated) then
FIdleTerminated := PeekMessage(LMsg, 0, 0, 0, PM_NOREMOVE)
or GetUpdateRect(FFormWnd, nil, False);
Result := FIdleTerminated;
end;
function TCustomBCEditor.IndentText(const IndentCount: Integer): string;
begin
if (not (eoAutoIndent in FOptions)) then
Result := ''
else if (toTabsToSpaces in FTabs.Options) then
Result := StringOfChar(BCEDITOR_SPACE_CHAR, IndentCount)
else
begin
Result := StringOfChar(BCEDITOR_TAB_CHAR, IndentCount div FTabs.Width);
Result := Result + StringOfChar(BCEDITOR_SPACE_CHAR, IndentCount mod FTabs.Width);
end;
end;
procedure TCustomBCEditor.InsertLine();
begin
if (not FLines.SelArea.IsEmpty()) then
SelText := FLines.LineBreak
else
FLines.InsertText(FLines.CaretPosition, FLines.LineBreak);
end;
procedure TCustomBCEditor.InsertLineIntoRows(const ALine: Integer; const ANewLine: Boolean);
var
LCodeFolding: Integer;
LInsertedRows: Integer;
LLine: Integer;
LRange: TBCEditorCodeFoldingRanges.TRange;
LRow: Integer;
begin
if (FRows.Count > 0) then
begin
for LCodeFolding := 0 to FAllCodeFoldingRanges.AllCount - 1 do
begin
LRange := FAllCodeFoldingRanges[LCodeFolding];
if (Assigned(LRange)
and LRange.Collapsed
and (LRange.BeginLine < ALine) and (ALine <= LRange.EndLine)) then
Exit;
end;
LLine := ALine + 1;
while ((LLine < FLines.Count) and (FLines.Items[LLine].FirstRow < 0)) do
Inc(LLine);
if (LLine < FLines.Count) then
LRow := FLines.Items[LLine].FirstRow
else
LRow := FRows.Count;
LInsertedRows := InsertLineIntoRows(NotTerminated, ALine, LRow);
if (not (esCaretInvalid in FState)
and (FLines.CaretPosition.Line >= ALine)) then
begin
Inc(FCaretPos.Y, LInsertedRows * FLineHeight);
UpdateCaret();
end;
if (ANewLine) then
for LRow := LRow + LInsertedRows to FRows.Count - 1 do
FRows.List[LRow].Line := FRows.List[LRow].Line + 1;
end;
end;
function TCustomBCEditor.InsertLineIntoRows(const ATerminated: TBCEditorTerminatedFunc;
const ALine: Integer; const ARow: Integer): Integer;
// Long lines will be splitted into multiple parts to proceed the painting
// faster.
const
CRowPartLength = 1000;
var
LBeginRange: TBCEditorHighlighter.TRange;
LChar: Integer;
LColumn: Integer;
LFlags: TRow.TFlags;
LLine: Integer;
LRow: Integer;
LRowLength: Integer;
LRowPart: TRow.TPart;
LRowPartList: TList<TRow.TPart>;
LRowParts: TRow.TParts;
LRowWidth: Integer;
LTerminated: Boolean;
LToken: TBCEditorHighlighter.TTokenFind;
LTokenBeginPos: PChar;
LTokenEndPos: PChar;
LTokenPos: PChar;
LTokenPrevPos: PChar;
LTokenRowBeginPos: PChar;
LTokenRowText: string;
LTokenRowWidth: Integer;
LTokenWidth: Integer;
begin
FPaintHelper.BeginDraw(Canvas.Handle);
try
LTerminated := False;
LRowPart.Char := 0;
LRowPartList := nil;
if (not FWordWrap) then
begin
LColumn := 0;
LRowWidth := 0;
if (FHighlighter.FindFirstToken(FLines.Items[ALine].BeginRange,
PChar(FLines.Items[ALine].Text), Length(FLines.Items[ALine].Text), 0,
LToken)) then
begin
repeat
if (LToken.Char - LRowPart.Char > CRowPartLength) then
begin
if (not Assigned(LRowPartList)) then
begin
LRowPartList := TList<TRow.TPart>.Create();
LRowPart.BeginRange := FLines.Items[ALine].BeginRange;
LRowPart.Column := 0;
LRowPart.Left := 0;
LRowPartList.Add(LRowPart);
end
else
LRowPartList.Add(LRowPart);
LRowPart.BeginRange := LToken.Range;
LRowPart.Char := LToken.Char;
LRowPart.Column := LColumn;
LRowPart.Left := LRowWidth;
LTerminated := ATerminated();
end;
Inc(LRowWidth, TokenWidth(LToken.Text, LToken.Length, LColumn, LToken));
Inc(LColumn, TokenColumns(LToken.Text, LToken.Length, LColumn));
until (LTerminated or not FHighlighter.FindNextToken(LToken));
if (Assigned(LRowPartList)) then
LRowPartList.Add(LRowPart);
end;
if (LTerminated) then
Result := 0
else
begin
if (not Assigned(LRowPartList)) then
FRows.Insert(ARow, [rfFirstRowOfLine, rfLastRowOfLine], ALine, 0,
Length(FLines.Items[ALine].Text), LColumn, LRowWidth, FLines.Items[ALine].BeginRange, nil)
else
begin
SetLength(LRowParts, LRowPartList.Count);
Move(LRowPartList.List[0], LRowParts[0], LRowPartList.Count * SizeOf(LRowParts[0]));
FRows.Insert(ARow, [rfFirstRowOfLine, rfLastRowOfLine], ALine, 0,
Length(FLines.Items[ALine].Text), LColumn, LRowWidth, FLines.Items[ALine].BeginRange, LRowParts);
end;
Result := 1;
end;
if (Assigned(LRowPartList)) then
LRowPartList.Free();
end
else
begin
LRow := ARow;
LFlags := [rfFirstRowOfLine];
LRowWidth := 0;
LRowLength := 0;
LColumn := 0;
LChar := 0;
LBeginRange := FLines.Items[ALine].BeginRange;
if (FHighlighter.FindFirstToken(FLines.Items[ALine].BeginRange,
PChar(FLines.Items[ALine].Text), Length(FLines.Items[ALine].Text), 0,
LToken)) then
repeat
LTokenWidth := TokenWidth(LToken.Text, LToken.Length, LColumn, LToken);
if (LRowWidth + LTokenWidth <= FTextRect.Width) then
begin
{ no row break in token }
Inc(LRowLength, LToken.Length);
Inc(LRowWidth, LTokenWidth);
Inc(LColumn, TokenColumns(LToken.Text, LToken.Length, LColumn));
end
else if (LRowLength > 0) then
begin
{ row break before token }
FRows.Insert(LRow, LFlags, ALine, LChar, LRowLength, LColumn, LRowWidth, LBeginRange, nil);
Exclude(LFlags, rfFirstRowOfLine);
Inc(LChar, LRowLength);
Inc(LRow);
LBeginRange := LToken.Range;
LRowLength := LToken.Length;
LRowWidth := LTokenWidth;
LColumn := TokenColumns(LToken.Text, LToken.Length, LColumn);
LTerminated := ATerminated();
end
else
begin
{ row break inside token }
LTokenBeginPos := LToken.Text;
LTokenPos := LTokenBeginPos;
LTokenEndPos := @LTokenPos[LToken.Length];
repeat
LTokenRowBeginPos := LTokenPos;
Inc(LTokenPos);
repeat
LTokenPrevPos := LTokenPos;
LTokenRowWidth := TokenWidth(LToken.Text, LTokenPos - LTokenRowBeginPos, LColumn, LToken);
if (LTokenRowWidth < FTextRect.Width) then
repeat
Inc(LTokenPos);
until ((LTokenPos > LTokenEndPos)
or (Char((LTokenPos - 1)^).GetUnicodeCategory() <> TUnicodeCategory.ucNonSpacingMark) or IsCombiningDiacriticalMark((LTokenPos - 1)^)
and not (Char(LTokenPos^).GetUnicodeCategory in [TUnicodeCategory.ucCombiningMark, TUnicodeCategory.ucNonSpacingMark]));
until ((LTokenPos > LTokenEndPos) or (LTokenRowWidth >= FTextRect.Width));
if (LTokenRowWidth >= FTextRect.Width) then
begin
LTokenPos := LTokenPrevPos;
LRowLength := LTokenPos - LTokenRowBeginPos - 1;
FRows.Insert(LRow, LFlags, ALine, LChar, LRowLength, LColumn, LTokenRowWidth, LBeginRange, nil);
Exclude(LFlags, rfFirstRowOfLine);
Inc(LChar, LRowLength);
Inc(LRow);
LBeginRange := LToken.Range;
LRowLength := 0;
LRowWidth := 0;
LColumn := 0;
end
else
begin
LRowLength := LTokenPos - LTokenRowBeginPos;
LRowWidth := LTokenRowWidth;
SetString(LTokenRowText, PChar(@LToken.Text[LTokenRowBeginPos - LTokenBeginPos]), LRowLength);
LColumn := TokenColumns(PChar(LTokenRowText), Length(LTokenRowText), LColumn);
end;
until ((LTokenPos > LTokenEndPos) or (LTokenRowWidth < FTextRect.Width));
LTerminated := ATerminated();
end;
until (LTerminated or not FHighlighter.FindNextToken(LToken));
if (not LTerminated and ((LRowLength > 0) or (FLines.Items[ALine].Text = ''))) then
begin
FRows.Insert(LRow, LFlags + [rfLastRowOfLine], ALine, LChar, LRowLength, LColumn, LRowWidth, LBeginRange, nil);
Inc(LRow);
end;
Result := LRow - ARow;
end;
finally
FPaintHelper.EndDraw();
end;
if (LTerminated) then
begin
for LRow := ARow to ARow + Result - 1 do
FRows.Delete(ARow);
end
else
begin
FLines.SetRow(ALine, ARow, Result);
for LLine := ALine + 1 to FLines.Count - 1 do
if (FLines.Items[LLine].FirstRow >= 0) then
FLines.SetRow(LLine, FLines.Items[LLine].FirstRow + Result, FLines.Items[LLine].RowCount);
Inc(FLastBuiltLine);
end;
end;
procedure TCustomBCEditor.InvalidateCaret();
begin
FRows.FCaretPosition := InvalidRowsPosition;
FCaretPos := InvalidPos;
SetInsertPos(InvalidPos);
FState := FState + [esCaretInvalid];
if ((UpdateCount = 0) and not (esPainting in FState) and (FRows.Count > 0)) then
UpdateCaret();
if ((eoHighlightCurrentLine in FOptions)
and (FLines.CaretPosition.Line <> FOldCurrentLine)) then
begin
InvalidateText(FOldCurrentLine);
InvalidateText(FLines.CaretPosition.Line);
end;
end;
procedure TCustomBCEditor.InvalidateClient();
begin
InvalidateRect(FClientRect);
InvalidateCaret();
end;
procedure TCustomBCEditor.InvalidateCodeFolding();
var
LLine: Integer;
begin
FAllCodeFoldingRanges.ClearAll();
for LLine := 0 to FLines.Count - 1 do
begin
FLines.SetCodeFoldingBeginRange(LLine, nil);
FLines.SetCodeFoldingEndRange(LLine, nil);
FLines.SetCodeFoldingTreeLine(LLine, False);
end;
Include(FState, esCodeFoldingInvalid);
InvalidateRect(FCodeFoldingRect);
if (HandleAllocated) then
KillTimer(WindowHandle, tiCodeFolding);
end;
procedure TCustomBCEditor.InvalidateMatchingPair();
begin
InvalidateText(FLines.MatchedPairOpenArea.BeginPosition.Line);
InvalidateText(FLines.MatchedPairCloseArea.BeginPosition.Line);
Include(FState, esMatchedPairInvalid);
end;
procedure TCustomBCEditor.InvalidateOverlays();
var
LIndex: Integer;
begin
if (not (esPainting in FState)) then
for LIndex := 0 to FOverlays.Count - 1 do
InvalidateText(FOverlays[LIndex].Area.BeginPosition.Line);
FOverlays.Clear();
end;
procedure TCustomBCEditor.InvalidateRect(const ARect: TRect; const AOverlay: Boolean = False);
var
LRect: TRect;
begin
if (not ARect.IsEmpty()) then
begin
LRect := TRect.Intersect(ARect, FClientRect);
if (not LRect.IsEmpty()) then
begin
if (DoubleBuffered and not AOverlay) then
if (FDoubleBufferUpdateRect.IsEmpty()) then
FDoubleBufferUpdateRect := LRect
else
FDoubleBufferUpdateRect.Union(LRect);
Windows.InvalidateRect(WindowHandle, LRect, not (csOpaque in ControlStyle))
end;
end;
end;
procedure TCustomBCEditor.InvalidateRows();
var
LLine: Integer;
begin
FRows.Clear();
for LLine := 0 to FLines.Count - 1 do
FLines.SetRow(LLine, GRowToInsert, 0);
FLastBuiltLine := -1;
InvalidateText();
end;
procedure TCustomBCEditor.InvalidateScrollBars();
begin
Include(FState, esScrollBarsInvalid);
if (not (esPainting in FState)) then
ProcessIdle(ijUpdateScrollBars);
end;
procedure TCustomBCEditor.InvalidateSyncEdit();
begin
if (not FLines.SyncEdit and not FLines.SelArea.IsEmpty()) then
Include(FState, esSyncEditInvalid);
end;
procedure TCustomBCEditor.InvalidateSyncEditButton();
var
LRect: TRect;
begin
if (FSyncEditButtonRect.IsEmpty()) then
begin
LRect.Left := 2 * GetSystemMetrics(SM_CXEDGE);
LRect.Top := (LinesToRows(FLines.SelArea.EndPosition).Row - FTopRow) * FLineHeight;
LRect.Right := LRect.Left + GetSystemMetrics(SM_CXSMICON) + 2 * GetSystemMetrics(SM_CXEDGE);
LRect.Bottom := LRect.Top + GetSystemMetrics(SM_CYSMICON) + 2 * GetSystemMetrics(SM_CYEDGE);
InvalidateRect(LRect);
end
else
InvalidateRect(FSyncEditButtonRect);
end;
procedure TCustomBCEditor.InvalidateSyncEditOverlays();
begin
if (FLines.SyncEdit) then
begin
Include(FState, esSyncEditOverlaysInvalid);
InvalidateOverlays();
end;
end;
procedure TCustomBCEditor.InvalidateText();
begin
InvalidateRect(FTextRect);
InvalidateCaret();
end;
procedure TCustomBCEditor.InvalidateText(const ALine: Integer);
var
LRect: TRect;
LRow: Integer;
begin
if (FLineHeight > 0) then
if ((0 <= ALine) and (ALine < FLines.Count)
and (FLines.Items[ALine].FirstRow >= 0)) then
begin
for LRow := FLines.Items[ALine].FirstRow to FLines.Items[ALine].FirstRow + FLines.Items[ALine].RowCount do
begin
LRect := Rect(FTextRect.Left, (LRow - FTopRow) * FLineHeight, FTextRect.Right, (LRow - FTopRow + 1) * FLineHeight);
InvalidateRect(LRect);
end;
end
else if (ALine >= FLines.Count) then
begin
LRect := Rect(
FTextRect.Left, (FRows.Count - FTopRow + ALine - FLines.Count) * FLineHeight,
FTextRect.Right - 1, (FRows.Count - FTopRow + ALine - FLines.Count + 1) * FLineHeight - 1);
InvalidateRect(LRect);
end;
end;
function TCustomBCEditor.IsCommentChar(const AChar: Char): Boolean;
begin
Result := Assigned(FHighlighter) and CharInSet(AChar, FHighlighter.Comments.Chars);
end;
function TCustomBCEditor.IsEmptyChar(const AChar: Char): Boolean;
begin
Result := CharInSet(AChar, BCEDITOR_EMPTY_CHARACTERS);
end;
function TCustomBCEditor.IsWordBreakChar(const AChar: Char): Boolean;
begin
Result := FLines.IsWordBreakChar(AChar);
end;
procedure TCustomBCEditor.KeyDown(var AKey: Word; AShift: TShiftState);
var
LCommand: TBCEditorCommand;
begin
inherited;
if (Assigned(BCEditorCommandManager)
and BCEditorCommandManager.TryShortCutToCommand(ShortCut(AKey, AShift), LCommand)) then
begin
Include(FState, esKeyHandled);
if (ProcessCommand(LCommand)) then
AKey := 0;
end;
end;
procedure TCustomBCEditor.KeyPress(var AKey: Char);
begin
inherited;
if (not (esKeyHandled in FState)
and (AKey <> #0)
and ProcessCommand(ecChar, TBCEditorCommandDataChar.Create(AKey))) then
begin
AKey := #0;
if (FCompletionProposal.Enabled
and not Assigned(FCompletionProposalPopup)) then
if ((cpoAutoInvoke in FCompletionProposal.Options) and AKey.IsLetter) then
ProcessCommand(ecShowCompletionProposal)
else if (FCompletionProposal.Trigger.Enabled) then
if (Pos(AKey, FCompletionProposal.Trigger.Chars) > 0) then
SetTimer(WindowHandle, tiCompletionProposal, FCompletionProposal.Trigger.Interval, nil)
else
KillTimer(WindowHandle, tiCompletionProposal);
end;
Exclude(FState, esKeyHandled);
end;
procedure TCustomBCEditor.LeftMarginChanged(ASender: TObject);
begin
ExpandCodeFoldingLines();
Include(FState, esSizeChanged);
UpdateMetrics();
InvalidateCodeFolding();
InvalidateScrollBars();
InvalidateClient();
end;
function TCustomBCEditor.LeftSpaceCount(const AText: string; AWantTabs: Boolean = False): Integer;
var
LTextEndPos: PChar;
LTextPos: PChar;
begin
if ((AText = '') or not (eoAutoIndent in FOptions)) then
Result := 0
else
begin
LTextPos := @AText[1];
LTextEndPos := @AText[Length(AText)];
Result := 0;
while ((LTextPos <= LTextEndPos) and (LTextPos^ <= BCEDITOR_SPACE_CHAR)) do
begin
if ((LTextPos^ = BCEDITOR_TAB_CHAR) and AWantTabs) then
Inc(Result, FTabs.Width - Result mod FTabs.Width)
else
Inc(Result);
Inc(LTextPos);
end;
end;
end;
function TCustomBCEditor.LeftTrimLength(const AText: string): Integer;
begin
Result := 0;
while ((Result < Length(AText)) and (AText[1 + Result] <= BCEDITOR_SPACE_CHAR)) do
Inc(Result);
end;
procedure TCustomBCEditor.LineDeleting(ASender: TObject; const ALine: Integer);
var
LRow: Integer;
begin
if (ALine <= FLastBuiltLine) then
begin
LRow := FLines.Items[ALine].FirstRow + FLines.Items[ALine].RowCount;
for LRow := LRow to FRows.Count - 1 do
Dec(FRows.List[LRow].Line);
LRow := FLines.Items[ALine].FirstRow;
if ((FTopRow <= LRow) and (LRow < FTopRow + FVisibleRows)) then
InvalidateRect(Rect(0, LRow * FLineHeight, FClientRect.Width - 1, FClientRect.Height - 1));
DeleteLineFromRows(ALine);
if (ALine < FLines.Count - 1) then
FLines.SetBeginRange(ALine + 1, FLines.Items[ALine].BeginRange);
InvalidateCodeFolding();
InvalidateScrollBars();
end;
if (UpdateCount > 0) then
Include(FState, esTextChanged)
else
Change();
end;
procedure TCustomBCEditor.LineInserted(ASender: TObject; const ALine: Integer);
var
LRow: Integer;
begin
if (FRows.Count = 0) then
InvalidateRows()
else if (ALine <= FLastBuiltLine) then
begin
SetLinesBeginRanges(ALine);
InsertLineIntoRows(ALine, True);
InvalidateCodeFolding();
LRow := FLines.Items[ALine].FirstRow;
if ((FTopRow <= LRow) and (LRow < FTopRow + FVisibleRows)) then
InvalidateRect(Rect(0, LRow * FLineHeight, FClientRect.Width - 1, FClientRect.Height - 1));
InvalidateScrollBars();
end;
if (UpdateCount > 0) then
Include(FState, esTextChanged)
else
Change();
end;
procedure TCustomBCEditor.LinesCleared(ASender: TObject);
begin
FTextPos := Point(0, 0);
FTopRow := 0;
InvalidateRows();
InvalidateMatchingPair();
InvalidateCaret();
InvalidateScrollBars();
InvalidateCodeFolding();
InvalidateClient();
Modified := True;
if (UpdateCount > 0) then
Include(FState, esTextChanged)
else
Change();
end;
procedure TCustomBCEditor.LinesChanged();
begin
if (FLeftMargin.LineNumbers.Visible) then
begin
FLineNumbersWidth := 2 * GPadding + Max(2, Length(IntToStr(FLines.Count + FVisibleRows))) * FMaxDigitWidth;
UpdateMetrics();
end;
InvalidateMatchingPair();
InvalidateScrollBars();
end;
procedure TCustomBCEditor.LinesLoaded(ASender: TObject);
begin
Loaded();
Modified := False;
end;
procedure TCustomBCEditor.LinesSelChanged(ASender: TObject);
var
LArea: TBCEditorLinesArea;
LLine: Integer;
begin
if (not FOldSelArea.IsEmpty() or not FLines.SelArea.IsEmpty()) then
begin
LArea := LinesArea(
Min(FOldSelArea.BeginPosition, FLines.SelArea.BeginPosition),
Max(FOldSelArea.BeginPosition, FLines.SelArea.BeginPosition));
if (not LArea.IsEmpty()) then
for LLine := LArea.BeginPosition.Line to LArea.EndPosition.Line do
InvalidateText(LLine);
LArea := LinesArea(
Min(FOldSelArea.EndPosition, FLines.SelArea.EndPosition),
Max(FOldSelArea.EndPosition, FLines.SelArea.EndPosition));
if (not LArea.IsEmpty()) then
for LLine := LArea.BeginPosition.Line to LArea.EndPosition.Line do
InvalidateText(LLine);
end;
InvalidateSyncEditButton();
InvalidateSyncEdit();
if (UpdateCount > 0) then
Include(FState, esSelChanged)
else
if (Assigned(FOnSelChanged)) then
FOnSelChanged(Self);
end;
procedure TCustomBCEditor.LinesSyncEditChanged(ASender: TObject);
var
LLine: Integer;
begin
for LLine := FLines.SyncEditArea.BeginPosition.Line to FLines.SyncEditArea.EndPosition.Line do
InvalidateText(LLine);
InvalidateSyncEditButton();
if (FLines.SyncEdit) then
InvalidateSyncEditOverlays()
else
InvalidateOverlays();
end;
function TCustomBCEditor.LinesToRows(const ALinesPosition: TBCEditorLinesPosition): TBCEditorRowsPosition;
var
LChar: Integer;
LColumn: Integer;
LLinePos: PChar;
LLineEndPos: PChar;
LRow: Integer;
begin
if (FRows.Count = 0) then
Result := RowsPosition(ALinesPosition.Char, ALinesPosition.Line)
else if (ALinesPosition.Line >= FLines.Count) then
Result := RowsPosition(ALinesPosition.Char, FRows.Count + ALinesPosition.Line - FLines.Count)
else if (FLines.Items[ALinesPosition.Line].FirstRow < 0) then
raise ERangeError.CreateFmt(SBCEditorLineIsNotVisible, [ALinesPosition.Line])
else
begin
LRow := FLines.Items[ALinesPosition.Line].FirstRow;
LChar := ALinesPosition.Char;
while ((LChar >= FRows.Items[LRow].Length) and not (rfLastRowOfLine in FRows.Items[LRow].Flags)) do
begin
Dec(LChar, FRows.Items[LRow].Length);
Inc(LRow);
end;
if (not (rfHasTabs in FRows.Items[LRow].Flags)) then
Result := RowsPosition(ALinesPosition.Char - FRows.Items[LRow].Char, LRow)
else
begin
LColumn := 0;
LLinePos := @FLines[ALinesPosition.Line][1 + FRows.Items[LRow].Char];
LLineEndPos := @FLines[ALinesPosition.Line][Min(1 + FRows.Items[LRow].Char + LChar, Length(FLines[ALinesPosition.Line]))];
while (LLinePos < LLineEndPos) do
begin
Inc(LColumn, TokenColumns(LLinePos, 1, LColumn));
Inc(LLinePos);
end;
if (Length(FLines[ALinesPosition.Line]) < LChar) then
Inc(LColumn, LChar - Length(FLines[ALinesPosition.Line]));
Result := RowsPosition(LColumn, LRow);
end;
end;
end;
procedure TCustomBCEditor.LineUpdated(ASender: TObject; const ALine: Integer);
var
LBeginRow: Integer;
LEndRow: Integer;
LNewRowCount: Integer;
LOldRowCount: Integer;
begin
if (ALine <= FLastBuiltLine) then
begin
SetLinesBeginRanges(ALine);
LOldRowCount := FLines.Items[ALine].RowCount;
UpdateLineInRows(ALine);
LNewRowCount := FLines.Items[ALine].RowCount;
InvalidateCodeFolding();
LBeginRow := FLines.Items[ALine].FirstRow;
LEndRow := LBeginRow + Max(LOldRowCount, LNewRowCount) - 1;
if ((LBeginRow <= FTopRow + FVisibleRows) and (LEndRow >= FTopRow)) then
if (LNewRowCount = LOldRowCount) then
InvalidateRect(
Rect(
FTextRect.Left, Max(0, LBeginRow - FTopRow) * FLineHeight,
FTextRect.Right, (Min(FVisibleRows, LEndRow - FTopRow) + 1) * FLineHeight))
else
InvalidateRect(
Rect(
FTextRect.Left, Max(0, LBeginRow - FTopRow) * FLineHeight,
FTextRect.Right, FTextRect.Bottom));
InvalidateScrollBars();
end;
if (UpdateCount > 0) then
Include(FState, esTextChanged)
else
Change();
end;
procedure TCustomBCEditor.LoadFromFile(const AFileName: string; AEncoding: TEncoding = nil);
begin
FLines.LoadFromFile(AFileName, AEncoding);
end;
procedure TCustomBCEditor.LoadFromStream(AStream: TStream; AEncoding: TEncoding = nil);
begin
FLines.LoadFromStream(AStream, AEncoding);
end;
procedure TCustomBCEditor.MarksChanged(ASender: TObject);
begin
if (FLeftMargin.Marks.Visible) then
InvalidateRect(FMarksPanelRect);
end;
procedure TCustomBCEditor.MatchingPairScanned(const AData: Pointer);
begin
InvalidateText(FLines.MatchedPairOpenArea.BeginPosition.Line);
InvalidateText(FLines.MatchedPairCloseArea.BeginPosition.Line);
Exclude(FState, esMatchedPairInvalid);
end;
procedure TCustomBCEditor.MouseDown(AButton: TMouseButton; AShift: TShiftState; X, Y: Integer);
var
LAction: TClientJob;
begin
KillTimer(WindowHandle, tiShowHint);
if (Assigned(FHintWindow)) then
FreeAndNil(FHintWindow);
FLines.UndoGroupBreak();
FMouseDownPoint := Point(X, Y);
inherited;
if (GetTickCount() < FLastDoubleClickTime + FDoubleClickTime) then
begin
LAction := cjMouseTrplClk;
FLastDoubleClickTime := 0;
Include(FState, esMouseDblClk);
end
else if (ssDouble in AShift) then
begin
LAction := cjMouseDblClk;
FLastDoubleClickTime := GetTickCount();
Include(FState, esMouseDblClk);
end
else
LAction := cjMouseDown;
ProcessClient(LAction, 0, nil, FClientRect, AButton, AShift, Point(X, Y));
end;
procedure TCustomBCEditor.MouseMove(AShift: TShiftState; X, Y: Integer);
var
LMsg: TMsg;
begin
if (Assigned(FHintWindow)
and (Point(X, Y) <> FCursorPoint)) then
FreeAndNil(FHintWindow);
if (MouseCapture = mcText) then
KillTimer(WindowHandle, tiScroll);
FCursorPoint := Point(X, Y);
inherited;
if (PeekMessage(LMsg, WindowHandle, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_NOREMOVE)
and (KeysToShiftState(LMsg.wParam) = AShift)) then
// Do nothing - handle this message within the next same message
else if (FLineHeight > 0) then
begin
ProcessClient(cjMouseMove, 0, nil, FClientRect, mbLeft, AShift, FCursorPoint);
if (not Assigned(FHintWindow)
and (Point(X, Y) <> FLastCursorPoint)
and (AShift * [ssLeft, ssRight, ssMiddle] = [])) then
if (FClientRect.Contains(Point(X, Y))) then
SetTimer(WindowHandle, tiShowHint, Application.HintPause, nil)
else
KillTimer(WindowHandle, tiShowHint);
FLastCursorPoint := FCursorPoint;
end;
end;
procedure TCustomBCEditor.MouseUp(AButton: TMouseButton; AShift: TShiftState; X, Y: Integer);
begin
KillTimer(WindowHandle, tiShowHint);
if (MouseCapture = mcText) then
KillTimer(WindowHandle, tiScroll);
inherited;
ProcessClient(cjMouseUp, 0, nil, FClientRect, AButton, AShift, Point(X, Y));
if (not (esScrolling in FState)) then
MouseCapture := mcNone;
Exclude(FState, esMouseDblClk);
end;
procedure TCustomBCEditor.MoveCaretAndSelection(const APosition: TBCEditorLinesPosition; const ASelect: Boolean);
var
LNewCaretPosition: TBCEditorLinesPosition;
begin
LNewCaretPosition := APosition;
if (not (eoBeyondEndOfLine in FOptions)) then
if (LNewCaretPosition.Line < FLines.Count) then
LNewCaretPosition.Char := Min(LNewCaretPosition.Char, Length(FLines[LNewCaretPosition.Line]))
else
LNewCaretPosition.Char := 0;
if (not (eoBeyondEndOfLine in FOptions)) then
LNewCaretPosition.Line := Max(0, Min(LNewCaretPosition.Line, FLines.Count - 1));
if (not ASelect) then
FLines.CaretPosition := LNewCaretPosition
else
SetCaretAndSelection(LNewCaretPosition, LinesArea(FLines.SelBeginPosition, LNewCaretPosition));
end;
procedure TCustomBCEditor.MoveCaretHorizontally(const AColumns: Integer;
const ASelect: Boolean);
var
LLineEndPos: PChar;
LLinePos: PChar;
LLineTextLength: Integer;
LNewCaretPosition: TBCEditorLinesPosition;
begin
if (FLines.CaretPosition.Char + AColumns >= 0) then
if (FLines.CaretPosition.Line < FLines.Count) then
begin
LLineTextLength := Length(FLines.Items[FLines.CaretPosition.Line].Text);
LNewCaretPosition := LinesPosition(Max(0, FLines.CaretPosition.Char + AColumns), FLines.CaretPosition.Line);
if (not (eoBeyondEndOfLine in FOptions) or FWordWrap) then
LNewCaretPosition.Char := Min(LNewCaretPosition.Char, LLineTextLength);
{ Skip combined and non-spacing marks }
if ((0 < LLineTextLength) and (LNewCaretPosition.Char < LLineTextLength)) then
begin
LLinePos := @FLines.Items[FLines.CaretPosition.Line].Text[1 + LNewCaretPosition.Char];
LLineEndPos := @FLines.Items[FLines.CaretPosition.Line].Text[Length(FLines.Items[FLines.CaretPosition.Line].Text)];
while ((LLinePos <= LLineEndPos)
and ((LLinePos^.GetUnicodeCategory in [TUnicodeCategory.ucCombiningMark, TUnicodeCategory.ucNonSpacingMark])
or ((LLinePos - 1)^ <> BCEDITOR_NONE_CHAR)
and ((LLinePos - 1)^.GetUnicodeCategory = TUnicodeCategory.ucNonSpacingMark)
and not IsCombiningDiacriticalMark((LLinePos - 1)^))) do
begin
Dec(LLinePos);
Dec(LNewCaretPosition.Char);
end;
end;
MoveCaretAndSelection(LNewCaretPosition, ASelect);
end
else if ((eoBeyondEndOfLine in FOptions) and not FWordWrap) then
MoveCaretAndSelection(LinesPosition(FLines.CaretPosition.Char + AColumns, FLines.CaretPosition.Line), ASelect);
end;
procedure TCustomBCEditor.MoveCaretVertically(const ARows: Integer; const ASelect: Boolean);
var
LNewCaretPosition: TBCEditorRowsPosition;
LX: Integer;
begin
if (not InvalidPoint(FCaretPos)) then
LX := FCaretPos.X
else
LX := RowsToClient(FRows.CaretPosition).X;
LNewCaretPosition := FRows.CaretPosition;
if ((ARows < 0) or (eoBeyondEndOfFile in FOptions)) then
LNewCaretPosition.Row := Max(0, LNewCaretPosition.Row + ARows)
else
LNewCaretPosition.Row := Max(0, Min(FRows.Count - 1, LNewCaretPosition.Row + ARows));
LNewCaretPosition.Column := ClientToRows(LX, LNewCaretPosition.Row * FLineHeight, True).Column;
if (not (eoBeyondEndOfLine in FOptions) or FWordWrap) then
if (LNewCaretPosition.Row < FRows.Count) then
if (not (rfLastRowOfLine in FRows.Items[LNewCaretPosition.Row].Flags)) then
LNewCaretPosition.Column := Min(LNewCaretPosition.Column, FRows.Items[LNewCaretPosition.Row].Length - 1)
else
LNewCaretPosition.Column := Min(LNewCaretPosition.Column, FRows.Items[LNewCaretPosition.Row].Length)
else
LNewCaretPosition.Column := 0;
MoveCaretAndSelection(RowsToLines(LNewCaretPosition), ASelect);
end;
function TCustomBCEditor.NextWordPosition(const ALinesPosition: TBCEditorLinesPosition): TBCEditorLinesPosition;
begin
if (ALinesPosition.Line >= FLines.Count) then
Result := FLines.EOFPosition
else
begin
Result := Min(ALinesPosition, FLines.EOLPosition[ALinesPosition.Line]);
if (Result.Char < Length(FLines.Items[Result.Line].Text)) then
while ((Result.Char < Length(FLines.Items[Result.Line].Text)) and IsWordBreakChar(FLines.Char[Result])) do
Inc(Result.Char)
else if (Result.Line < FLines.Count - 1) then
begin
Result := FLines.BOLPosition[Result.Line + 1];
while ((Result.Char + 1 < Length(FLines.Items[Result.Line].Text)) and IsWordBreakChar(FLines.Items[Result.Line].Text[Result.Char + 1])) do
Inc(Result.Char);
end
end;
end;
procedure TCustomBCEditor.NotifyParent(const ANotification: Word);
begin
if ((WindowHandle <> 0) and (FParentWnd <> 0) and not FNoParentNotify) then
SendMessage(FParentWnd, WM_COMMAND, ANotification shl 16 + FDlgCtrlID and $FFFF, LPARAM(WindowHandle));
end;
function TCustomBCEditor.NotTerminated(): Boolean;
begin
Result := False;
end;
procedure TCustomBCEditor.Paint();
begin
PaintTo(Canvas.Handle, FClientRect);
end;
procedure TCustomBCEditor.PaintTo(const ADC: HDC; const ARect: TRect;
const AOverlays: Boolean = True);
procedure BuildBitmaps(const APaintVar: PPaintVar);
const
aclBookmarkBorder = $FF977302;
aclBookmarkCover = $FFFAE6B2;
aclBookmarkRingLeft = $FF929292;
aclBookmarkRingMiddle = $FFFCFCFC;
aclBookmarkRingRight = $FFBCBCBC;
aclBookmarkNumber = $FF977302;
var
LBackgroundColor: TGPColor;
LBitmap: TGPBitmap;
LBrush: TGPSolidBrush;
LColor: TGPColor;
LFont: TGPFont;
LGraphics: TGPGraphics;
LHDC: HDC;
LHeight: Integer;
LIcon: TGPBitmap;
LIconId: Integer;
LIndex: Integer;
LPen: TGPPen;
LPoints: array [0 .. 2] of TGPPoint;
LRect: TRect;
LRectF: TGPRectF;
LResData: HGLOBAL;
LResInfo: HRSRC;
LResource: Pointer;
LStringFormat: TGPStringFormat;
LText: string;
LWidth: Integer;
LY: Integer;
begin
LBrush := TGPSolidBrush.Create(aclTransparent);
LFont := TGPFont.Create(GetParentForm(Self).Font.Name, FLineHeight - 2 * GPadding - 2 * GLineWidth, FontStyleRegular, UnitPixel);
LStringFormat := TGPStringFormat.Create();
LStringFormat.SetAlignment(StringAlignmentCenter);
LPen := TGPPen.Create(aclTransparent, GLineWidth);
LWidth := Min(FLineHeight, GetSystemMetrics(SM_CXSMICON));
LHeight := LWidth;
// Bookmarks
LBitmap := TGPBitmap.Create(LWidth, LHeight);
LGraphics := TGPGraphics.Create(LBitmap);
for LIndex := 0 to BCEDITOR_BOOKMARKS - 1 do
begin
if (Assigned(FBookmarkBitmaps[LIndex])) then FBookmarkBitmaps[LIndex].Free();
LBrush.SetColor(aclTransparent);
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
if (LIndex < BCEDITOR_BOOKMARKS - 1) then
LText := IntToStr(LIndex + 1)
else
LText := '0';
LRectF := MakeRect(GPadding + 2 * GLineWidth + 0.0,
GPadding + GLineWidth,
LWidth - 2 * GPadding - 3 * GLineWidth,
LHeight - 2 * GPadding - 3 * GLineWidth);
LBrush.SetColor(aclBookmarkCover);
LGraphics.FillRectangle(LBrush, LRectF);
LRectF := MakeRect(GPadding + 2 * GLineWidth + 0.0,
GPadding + GLineWidth - 2,
LWidth - 2 * GPadding - 3 * GLineWidth,
LHeight - 2 * GPadding - GLineWidth);
LBrush.SetColor(aclBookmarkNumber);
LGraphics.DrawString(LText, -1, LFont, LRectF, LStringFormat, LBrush);
LPen.SetColor(aclBookmarkBorder);
LGraphics.DrawRectangle(LPen, GPadding + GLineWidth, GPadding, FLineHeight - 2 * GPadding - 2 * GLineWidth, FLineHeight - 3 * GPadding - GLineWidth);
LY := GPadding + 2 * GLineWidth;
repeat
LBrush.SetColor(aclBookmarkRingLeft);
LGraphics.FillRectangle(LBrush, GPadding, LY, GLineWidth, GLineWidth);
LBrush.SetColor(aclBookmarkRingMiddle);
LGraphics.FillRectangle(LBrush, GPadding + GLineWidth, LY, GLineWidth, GLineWidth);
LBrush.SetColor(aclBookmarkRingRight);
LGraphics.FillRectangle(LBrush, GPadding + 2 * GLineWidth, LY, GLineWidth, GLineWidth);
Inc(LY, 2 * GLineWidth);
until (LY >= FLineHeight - 2 * GPadding - 2 * GLineWidth);
FBookmarkBitmaps[LIndex] := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
end;
LGraphics.Free();
LBitmap.Free();
// CodeFoling
if (not (csOpaque in ControlStyle)) then
LBackgroundColor := aclTransparent
else if (FColors.CodeFolding.Background <> clNone) then
LBackgroundColor :=ColorRefToARGB(ColorToRGB(FColors.CodeFolding.Background))
else
LBackgroundColor :=ColorRefToARGB(ColorToRGB(Color));
if (FColors.CodeFolding.Foreground <> clNone) then
LColor := ColorRefToARGB(ColorToRGB(FColors.CodeFolding.Foreground))
else
LColor := ColorRefToARGB(ColorToRGB(Font.Color));
LPen.SetColor(LColor);
// CodeFolding None / Collapsed / Expanded
if (Assigned(FCodeFoldingNoneBitmap)) then FCodeFoldingNoneBitmap.Free();
if (Assigned(FCodeFoldingCollapsedBitmap)) then FCodeFoldingCollapsedBitmap.Free();
if (Assigned(FCodeFoldingExpandedBitmap)) then FCodeFoldingExpandedBitmap.Free();
LBitmap := TGPBitmap.Create(LWidth, LHeight);
LGraphics := TGPGraphics.Create(LBitmap);
LBrush.SetColor(LBackgroundColor);
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
FCodeFoldingNoneBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
LBrush.SetColor(LColor);
LGraphics.DrawRectangle(LPen, GPadding + 2 * GLineWidth, GPadding + 2 * GLineWidth, LWidth - 2 * GPadding - 6 * GLineWidth, LHeight - 2 * GPadding - 6 * GLineWidth);
LGraphics.DrawLine(LPen, GPadding + 4 * GLineWidth, (2 * LHeight - GLineWidth) div 4, LWidth - GPadding - 6 * GLineWidth, (2 * LHeight - GLineWidth) div 4);
FCodeFoldingCollapsedBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
LGraphics.DrawLine(LPen, (2 * LWidth - GLineWidth) div 4, GPadding + 4 * GLineWidth, (2 * LWidth - GLineWidth) div 4, LHeight - GPadding - 6 * GLineWidth);
FCodeFoldingExpandedBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
LGraphics.Free();
LBitmap.Free();
// CodeFolding Line / EndLine
if (Assigned(FCodeFoldingLineBitmap)) then FCodeFoldingLineBitmap.Free();
if (Assigned(FCodeFoldingEndLineBitmap)) then FCodeFoldingEndLineBitmap.Free();
LBitmap := TGPBitmap.Create(LWidth, LHeight);
LGraphics := TGPGraphics.Create(LBitmap);
LBrush.SetColor(LBackgroundColor);
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
LGraphics.DrawLine(LPen, (2 * LWidth - GLineWidth) div 4, 0, (2 * LWidth - GLineWidth) div 4, LHeight - GLineWidth);
FCodeFoldingLineBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
LGraphics.DrawLine(LPen, (2 * LWidth - GLineWidth) div 4, LHeight - GLineWidth, LWidth - GLineWidth, LHeight - GLineWidth);
FCodeFoldingEndLineBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
LGraphics.Free();
// InsertPos Mark
if (Assigned(FInsertPosBitmap)) then FInsertPosBitmap.Free();
LWidth := 3 * GLineWidth;
LHeight := FLineHeight;
LBitmap := TGPBitmap.Create(LWidth, LHeight);
LGraphics := TGPGraphics.Create(LBitmap);
LBrush.SetColor(aclTransparent);
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
LBrush.SetColor(ColorRefToARGB(ColorToRGB(Font.Color)));
LGraphics.FillRectangle(LBrush, GLineWidth, GPadding, GLineWidth, FLineHeight - GLineWidth - GPadding);
LGraphics.SetSmoothingMode(SmoothingModeHighQuality);
LPen.SetColor(ColorRefToARGB(ColorToRGB(Font.Color)));
LPoints[0] := MakePoint(0, GPadding);
LPoints[1] := MakePoint(GLineWidth, GPadding + GLineWidth);
LPoints[2] := MakePoint(GLineWidth, GPadding);
LGraphics.DrawPolygon(LPen, PGPPoint(@LPoints[0]), 3);
LGraphics.FillPolygon(LBrush, PGPPoint(@LPoints[0]), 3);
LPoints[0] := MakePoint(2 * GLineWidth - 1, GPadding);
LPoints[1] := MakePoint(2 * GLineWidth - 1, GPadding + GLineWidth);
LPoints[2] := MakePoint(3 * GLineWidth - 1, GPadding);
LGraphics.DrawPolygon(LPen, PGPPoint(@LPoints[0]), 3);
LGraphics.FillPolygon(LBrush, PGPPoint(@LPoints[0]), 3);
LPoints[0] := MakePoint(0, FLineHeight - 1 - GPadding);
LPoints[1] := MakePoint(GLineWidth, FLineHeight - 1 - GLineWidth - GPadding);
LPoints[2] := MakePoint(GLineWidth, FLineHeight - 1 - GPadding);
LGraphics.DrawPolygon(LPen, PGPPoint(@LPoints[0]), 3);
LGraphics.FillPolygon(LBrush, PGPPoint(@LPoints[0]), 3);
LPoints[0] := MakePoint(2 * GLineWidth - 1, FLineHeight - 1 - GPadding);
LPoints[1] := MakePoint(2 * GLineWidth - 1, FLineHeight - 1 - GLineWidth - GPadding);
LPoints[2] := MakePoint(3 * GLineWidth - 1, FLineHeight - 1 - GPadding);
LGraphics.DrawPolygon(LPen, PGPPoint(@LPoints[0]), 3);
LGraphics.FillPolygon(LBrush, PGPPoint(@LPoints[0]), 3);
FInsertPosBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
LGraphics.Free();
if (esSysFontChanged in FState) then
begin
// Scrolling Anchor
if (Assigned(FScrollingBitmap)) then FScrollingBitmap.Free();
LWidth := 2 * GetSystemMetrics(SM_CXSMICON) - GetSystemMetrics(SM_CXSMICON) div 4;
LHeight := LWidth;
FScrollingBitmapWidth := LWidth;
FScrollingBitmapHeight := LHeight;
LBitmap := TGPBitmap.Create(LWidth, LHeight);
LGraphics := TGPGraphics.Create(LBitmap);
LBrush.SetColor(aclTransparent);
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
LGraphics.SetSmoothingMode(SmoothingModeHighQuality);
LBrush.SetColor(ColorRefToARGB(ColorToRGB(Color)));
LGraphics.FillEllipse(LBrush, GLineWidth, GLineWidth, LWidth - GLineWidth - 1, LHeight - GLineWidth - 1);
LPen.SetColor(ColorRefToARGB(ColorToRGB(Font.Color)));
LGraphics.DrawEllipse(LPen, GLineWidth, GLineWidth, LWidth - GLineWidth - 1, LHeight - GLineWidth - 1);
LBrush.SetColor(ColorRefToARGB(ColorToRGB(Font.Color)));
LPoints[0].X := LWidth div 2;
LPoints[0].Y := 4 * GLineWidth;
LPoints[1].X := LWidth div 2 - 4 * GLineWidth;
LPoints[1].Y := 8 * GLineWidth;
LPoints[2].X := LWidth div 2 + 4 * GLineWidth;
LPoints[2].Y := 8 * GLineWidth;
LGraphics.DrawPolygon(LPen, PGPPoint(@LPoints[0]), 3);
LGraphics.FillPolygon(LBrush, PGPPoint(@LPoints[0]), 3);
LPoints[0].X := LWidth - 4 * GLineWidth;
LPoints[0].Y := LHeight div 2;
LPoints[1].X := LWidth - 8 * GLineWidth;
LPoints[1].Y := LHeight div 2 - 4 * GLineWidth;
LPoints[2].X := LWidth - 8 * GLineWidth;
LPoints[2].Y := LHeight div 2 + 4 * GLineWidth;
LGraphics.DrawPolygon(LPen, PGPPoint(@LPoints[0]), 3);
LGraphics.FillPolygon(LBrush, PGPPoint(@LPoints[0]), 3);
LPoints[0].X := LWidth div 2;
LPoints[0].Y := LHeight - 4 * GLineWidth;
LPoints[1].X := LWidth div 2 - 4 * GLineWidth;
LPoints[1].Y := LHeight - 8 * GLineWidth;
LPoints[2].X := LWidth div 2 + 4 * GLineWidth;
LPoints[2].Y := LHeight - 8 * GLineWidth;
LGraphics.DrawPolygon(LPen, PGPPoint(@LPoints[0]), 3);
LGraphics.FillPolygon(LBrush, PGPPoint(@LPoints[0]), 3);
LPoints[0].X := 4 * GLineWidth;
LPoints[0].Y := LHeight div 2;
LPoints[1].X := 8 * GLineWidth;
LPoints[1].Y := LHeight div 2 - 4 * GLineWidth;
LPoints[2].X := 8 * GLineWidth;
LPoints[2].Y := LHeight div 2 + 4 * GLineWidth;
LGraphics.DrawPolygon(LPen, PGPPoint(@LPoints[0]), 3);
LGraphics.FillPolygon(LBrush, PGPPoint(@LPoints[0]), 3);
LGraphics.DrawEllipse(LPen, LWidth div 2 - 2 * GLineWidth, LHeight div 2 - 2 * GLineWidth, 4 * GLineWidth, 4 * GLineWidth);
LGraphics.FillEllipse(LBrush, LWidth div 2 - 2 * GLineWidth, LHeight div 2 - 2 * GLineWidth, 4 * GLineWidth, 4 * GLineWidth);
FScrollingBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
LGraphics.Free();
// SyncEdit Button
LResInfo := FindResource(HInstance, BCEDITOR_SYNCEDIT, RT_GROUP_ICON);
LResData := LoadResource(HInstance, LResInfo);
LResource := LockResource(LResData);
LIconId := LookupIconIdFromDirectoryEx(LResource, TRUE, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
LResInfo := FindResource(HInstance, MAKEINTRESOURCE(LIconId), RT_ICON);
LResData := LoadResource(HInstance, LResInfo);
LIcon := TGPBitmap.Create(CreateIconFromResourceEx(
LockResource(LResData), SizeOfResource(HInstance, LResInfo),
TRUE, $00030000, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR));
LWidth := GetSystemMetrics(SM_CXSMICON) + 2 * GetSystemMetrics(SM_CXEDGE);
LHeight := GetSystemMetrics(SM_CYSMICON) + 2 * GetSystemMetrics(SM_CYEDGE);
LRect := Rect(0, 0, LWidth, LHeight);
LBrush.SetColor(aclTransparent);
LBitmap := TGPBitmap.Create(LWidth, LHeight);
LGraphics := TGPGraphics.Create(LBitmap);
if (Assigned(FSyncEditButtonNormalBitmap)) then FSyncEditButtonNormalBitmap.Free();
if (not StyleServices.Enabled) then
begin
LBrush.SetColor(ColorRefToARGB(ColorToRGB(clBtnFace)));
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
LHDC := LGraphics.GetHDC();
DrawEdge(LHDC, LRect, BDR_RAISEDINNER, BF_RECT);
LGraphics.ReleaseHDC(LHDC);
end
else
begin
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
LHDC := LGraphics.GetHDC();
StyleServices.DrawElement(LHDC, StyleServices.GetElementDetails(tbPushButtonNormal), LRect);
LGraphics.ReleaseHDC(LHDC);
end;
LGraphics.DrawImage(LIcon, GetSystemMetrics(SM_CXEDGE), GetSystemMetrics(SM_CYEDGE));
FSyncEditButtonNormalBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
if (Assigned(FSyncEditButtonHotBitmap)) then FSyncEditButtonHotBitmap.Free();
if (not StyleServices.Enabled) then
begin
LBrush.SetColor(ColorRefToARGB(ColorToRGB(clBtnFace)));
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
LHDC := LGraphics.GetHDC();
DrawEdge(LHDC, LRect, BDR_RAISED, BF_RECT);
LGraphics.ReleaseHDC(LHDC);
end
else
begin
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
LHDC := LGraphics.GetHDC();
StyleServices.DrawElement(LHDC, StyleServices.GetElementDetails(tbPushButtonHot), LRect);
LGraphics.ReleaseHDC(LHDC);
end;
LGraphics.DrawImage(LIcon, GetSystemMetrics(SM_CXEDGE), GetSystemMetrics(SM_CYEDGE));
FSyncEditButtonHotBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
if (Assigned(FSyncEditButtonPressedBitmap)) then FSyncEditButtonPressedBitmap.Free();
if (not StyleServices.Enabled) then
begin
LBrush.SetColor(ColorRefToARGB(ColorToRGB(clBtnFace)));
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
LHDC := LGraphics.GetHDC();
DrawEdge(LHDC, LRect, BDR_SUNKENOUTER, BF_RECT);
LGraphics.ReleaseHDC(LHDC);
end
else
begin
LGraphics.FillRectangle(LBrush, 0, 0, LWidth, LHeight);
LHDC := LGraphics.GetHDC();
StyleServices.DrawElement(LHDC, StyleServices.GetElementDetails(tbPushButtonPressed), LRect);
LGraphics.ReleaseHDC(LHDC);
end;
LGraphics.DrawImage(LIcon, GetSystemMetrics(SM_CXEDGE), GetSystemMetrics(SM_CYEDGE));
FSyncEditButtonPressedBitmap := TGPCachedBitmap.Create(LBitmap, APaintVar^.Graphics);
LGraphics.Free();
LBitmap.Free();
LIcon.Free();
end;
LBrush.Free();
LPen.Free();
end;
procedure BuildOverlaysFromSyncEdit();
var
LCurrentId: Integer;
LCurrentIndex: Integer;
LIndex: Integer;
LOverlay: TOverlay;
begin
InvalidateOverlays();
if (FLines.SyncEdit) then
begin
LCurrentIndex := -1;
LCurrentId := -1;
for LIndex := 0 to FLines.SyncEditItems.Count - 1 do
if (FLines.SyncEditItems[LIndex].Area.Contains(FLines.CaretPosition)
or (FLines.SyncEditItems[LIndex].Area.EndPosition = FLines.CaretPosition)) then
begin
LCurrentIndex := LIndex;
LCurrentId := FLines.SyncEditItems[LIndex].Id;
break;
end;
for LIndex := 0 to FLines.SyncEditItems.Count - 1 do
if (LIndex <> LCurrentIndex) then
begin
LOverlay.Area := FLines.SyncEditItems[LIndex].Area;
if (FLines.SyncEditItems[LIndex].Id = LCurrentId) then
LOverlay.Style := osRect
else
LOverlay.Style := osUnderline;
FOverlays.Add(LOverlay);
end;
end;
end;
var
LIndex: Integer;
LInsertPos: TPoint;
LPaintVar: TPaintVar;
begin
if (not ARect.IsEmpty()) then
begin
LPaintVar.Graphics := TGPGraphics.Create(ADC);
LPaintVar.LeftMarginBorderBrush := TGPSolidBrush.Create(ColorRefToARGB(ColorToRGB(Color)));
LPaintVar.LineForegroundColor := clNone;
LPaintVar.LineBackgroundColor := clNone;
LPaintVar.OverlayIndex := 0;
LPaintVar.Parts := TList<TPaintVar.TPart>.Create();
LPaintVar.PreviousBackgroundColor := clNone;
LPaintVar.PreviousFontStyles := [];
LPaintVar.SearchResultIndex := 0;
LPaintVar.SelArea := FLines.SelArea;
if (FUCCVisible) then
if (FColors.SpecialChars.Foreground <> clNone) then
LPaintVar.UCCBrush := TGPSolidBrush.Create(ColorRefToARGB(ColorToRGB(FColors.SpecialChars.Foreground)))
else
LPaintVar.UCCBrush := TGPSolidBrush.Create(ColorRefToARGB(ColorToRGB(clGrayText)));
Include(FState, esPainting);
try
if ((FState * [esFontChanged] <> [])
or ((FState * [esSizeChanged] <> []) and FWordWrap)) then
InvalidateRows();
if (FState * [esFontChanged, esSysFontChanged, esHighlighterChanged] <> []) then
begin
FPaintHelper.BeginDraw(ADC);
try
FFontPitchFixed := EnumFontFamilies(ADC, PChar(Font.Name),
@EnumFontsFamiliesProc, 0);
FPaintHelper.Font := Font;
FPaintHelper.Style := [];
FLineHeight := FPaintHelper.TextHeight(BCEDITOR_SPACE_CHAR, 1);
FMaxDigitWidth := FPaintHelper.TextWidth('0', 1);
for LIndex := 1 to 9 do
FMaxDigitWidth := Max(FMaxDigitWidth, FPaintHelper.TextWidth(PChar(IntToStr(LIndex)), 1));
LinesChanged();
FSpaceWidth := FPaintHelper.TextWidth(BCEDITOR_SPACE_CHAR, 1);
FTabSignWidth := FPaintHelper.TextWidth(#187, 1);
FLineBreakSignWidth := FPaintHelper.TextWidth(#182, 1);
FMinusSignWidth := FPaintHelper.TextWidth('-', 1);
FCodeFoldingCollapsedMarkWidth := FPaintHelper.TextWidth(BCEDITOR_CODEFOLDING_COLLAPSEDMARK, StrLen(BCEDITOR_CODEFOLDING_COLLAPSEDMARK));
FPaintHelper.Style := [fsBold];
FBoldDotSignWidth := FPaintHelper.TextWidth(#183, 1);
FCodeFoldingWidth := Min(FLineHeight, GetSystemMetrics(SM_CXSMICON));
UpdateMetrics();
if (FFontPitchFixed) then
FCaretWidth := GetSystemMetrics(SM_CXEDGE)
else
FCaretWidth := Max(1, GetSystemMetrics(SM_CXEDGE) div 2);
InvalidateCaret();
BuildBitmaps(@LPaintVar);
finally
FPaintHelper.EndDraw();
end;
end;
if ((FRows.Count = 0) and (FLines.Count > 0)) then
BuildRows(NotTerminated, FTopRow + FVisibleRows);
if (esSyncEditInvalid in FState) then
begin
FLines.CheckSyncEdit(FHighlighter, SyncEditChecked);
Exclude(FState, esSyncEditInvalid);
end;
if (esMatchedPairInvalid in FState) then
begin
if ((eoHighlightMatchingPairs in FOptions) and (FHighlighter.MatchingPairs.Count > 0)) then
FLines.StartScanMatchingPair(FHighlighter, MatchingPairScanned);
Exclude(FState, esMatchedPairInvalid);
end;
if (esSyncEditOverlaysInvalid in FState) then
begin
BuildOverlaysFromSyncEdit();
Exclude(FState, esSyncEditOverlaysInvalid);
end;
if (FOverlays.Count > 0) then
begin
LPaintVar.OverlayRectBrush := TGPSolidBrush.Create(ColorRefToARGB(ColorToRGB(Colors.SyncEdit.Overlays)));
LPaintVar.OverlayUnderlineBrush := TGPSolidBrush.Create(ColorRefToARGB(ColorToRGB(Colors.SyncEdit.Overlays)));
end;
ProcessClient(cjPaint, ADC, @LPaintVar, ARect, mbLeft, [], Point(-1, -1), AOverlays);
if (not InvalidPoint(FInsertPos)) then
begin
LInsertPos := FInsertPos;
FInsertPos := InvalidPos;
SetInsertPos(LInsertPos);
end;
FState := FState - [esFontChanged, esHighlighterChanged, esSizeChanged, esSysFontChanged];
finally
LPaintVar.Graphics.Free();
LPaintVar.LeftMarginBorderBrush.Free();
if (FOverlays.Count > 0) then
begin
LPaintVar.OverlayRectBrush.Free();
LPaintVar.OverlayUnderlineBrush.Free();
end;
LPaintVar.Parts.Free();
if (FUCCVisible) then
LPaintVar.UCCBrush.Free();
Exclude(FState, esPainting);
end;
if (not (eoHighlightCurrentLine in FOptions)) then
FOldCurrentLine := -1
else
FOldCurrentLine := FLines.CaretPosition.Line;
FOldSelArea := FLines.SelArea;
end;
end;
procedure TCustomBCEditor.PasteFromClipboard();
var
LClipboardData: Pointer;
LGlobal: HGLOBAL;
LOpened: Boolean;
LRetry: Integer;
LText: string;
begin
LRetry := 0;
repeat
LOpened := OpenClipboard(WindowHandle);
if (not LOpened) then
begin
Sleep(50);
Inc(LRetry);
end;
until (LOpened or (LRetry = 10));
if (not LOpened) then
raise EClipboardException.CreateFmt(SCannotOpenClipboard, [SysErrorMessage(GetLastError)])
else
begin
try
LGlobal := GetClipboardData(CF_UNICODETEXT);
if (LGlobal <> 0) then
begin
LClipboardData := GlobalLock(LGlobal);
if (Assigned(LClipboardData)) then
LText := StrPas(PChar(LClipboardData));
GlobalUnlock(LGlobal);
end;
finally
CloseClipboard();
end;
FLines.BeginUpdate();
try
FLines.UndoGroupBreak();
DoInsertText(LText);
finally
FLines.EndUpdate();
end;
end;
end;
function TCustomBCEditor.PosToCharIndex(const APos: TPoint): Integer;
begin
Result := FLines.CharIndexOf(APos);
end;
function TCustomBCEditor.PreviousWordPosition(const ALinesPosition: TBCEditorLinesPosition): TBCEditorLinesPosition;
begin
if (ALinesPosition.Line < FLines.Count) then
Result := Min(ALinesPosition, FLines.EOLPosition[ALinesPosition.Line])
else
Result := FLines.EOFPosition;
if (Result.Char > 0) then
while ((Result.Char > 0) and IsWordBreakChar(FLines.Items[Result.Line].Text[1 + Result.Char - 1])) do
Dec(Result.Char)
else if (Result.Line > 0) then
Result := FLines.EOLPosition[Result.Line - 1]
else
Result := FLines.BOFPosition;
end;
function TCustomBCEditor.ProcessClient(const AJob: TClientJob;
const ADC: HDC; const APaintVar: PPaintVar; const AClipRect: TRect;
const AButton: TMouseButton; const AShift: TShiftState; AMousePoint: TPoint;
const APaintOverlays: Boolean = True): Boolean;
function ProcessMarks(var ARect: TRect; const ALine, ARow: Integer): Boolean;
var
LBookmark: TBCEditorLines.TMark;
LIndex: Integer;
LLeft: Integer;
LMark: TBCEditorLines.TMark;
LRect: TRect;
begin
Result := False;
LRect := ARect;
LRect.Right := LRect.Left + FMarksPanelWidth;
case (AJob) of
cjPaint:
if (LRect.IntersectsWith(AClipRect)) then
begin
if (csOpaque in ControlStyle) then
begin
if (Colors.Marks.Background <> clNone) then
FPaintHelper.BackgroundColor := Colors.Marks.Background
else
FPaintHelper.BackgroundColor := Color;
FPaintHelper.FillRect(LRect);
end;
if ((ARow < FRows.Count)
and (rfFirstRowOfLine in FRows.Items[ARow].Flags)) then
begin
LLeft := LRect.Left;
LBookmark := nil;
for LIndex := FLines.Bookmarks.Count - 1 downto 0 do
if (FLines.Bookmarks[LIndex].Pos.Y = ALine) then
LBookmark := FLines.Bookmarks[LIndex];
if (Assigned(LBookmark)) then
APaintVar^.Graphics.DrawCachedBitmap(FBookmarkBitmaps[LBookmark.Index], LLeft, LRect.Top);
LMark := nil;
for LIndex := FLines.Marks.Count - 1 downto 0 do
if (FLines.Marks[LIndex].Pos.Y = ALine) then
LBookmark := FLines.Marks[LIndex];
if (Assigned(LMark)) then
begin
if (Assigned(LBookmark)) then
Inc(LLeft, GetSystemMetrics(SM_CXSMICON) div 4);
if (Assigned(LMark)) then
ImageList_DrawEx(FLeftMargin.Marks.Images.Handle, LMark.ImageIndex,
ADC, LLeft, LRect.Top, 0, 0, CLR_DEFAULT, CLR_DEFAULT, ILD_TRANSPARENT);
end;
end;
end;
cjMouseDown:
if ((MouseCapture in [mcNone, mcMarks])
and LRect.Contains(AMousePoint) and not FSyncEditButtonRect.Contains(AMousePoint)
and (AButton = mbLeft)) then
begin
MouseCapture := mcMarks;
Result := True;
end;
cjMouseMove:
if ((MouseCapture in [mcNone])
and LRect.Contains(AMousePoint) and not FSyncEditButtonRect.Contains(AMousePoint)) then
begin
Cursor := crDefault;
Result := True;
end
else if (MouseCapture = mcMarks) then
begin
if (not LRect.Contains(AMousePoint) or FSyncEditButtonRect.Contains(AMousePoint)) then
MouseCapture := mcNone;
Result := True;
end;
cjMouseUp:
if ((MouseCapture in [mcNone, mcMarks])
and LRect.Contains(AMousePoint) and not FSyncEditButtonRect.Contains(AMousePoint)
and (AButton = mbLeft)) then
begin
if ((ALine <> -1) and Assigned(FOnMarksPanelClick)) then
FOnMarksPanelClick(Self, ALine);
MouseCapture := mcNone;
Result := True;
end;
end;
ARect.Left := LRect.Right;
end;
function ProcessLineNumber(var ARect: TRect; const ALine, ARow: Integer): Boolean;
var
LOptions: Longint;
LRect: TRect;
LText: string;
LWidth: Integer;
begin
Result := False;
LRect := ARect;
LRect.Right := LRect.Left + FLineNumbersWidth;
case (AJob) of
cjPaint:
if (LRect.IntersectsWith(AClipRect)) then
begin
if (Colors.LineNumbers.Foreground <> clNone) then
FPaintHelper.ForegroundColor := Colors.LineNumbers.Foreground
else
FPaintHelper.ForegroundColor := Font.Color;
if (Colors.LineNumbers.Background <> clNone) then
FPaintHelper.BackgroundColor := Colors.LineNumbers.Background
else
FPaintHelper.BackgroundColor := Color;
if ((ARow = 0) and (FLines.Count = 0)) then
begin
FPaintHelper.Style := [];
LText := IntToStr(FLeftMargin.LineNumbers.Offset);
LWidth := FPaintHelper.TextWidth(PChar(LText), Length(LText));
end
else if ((ALine < 0) and not (lnoAfterLastLine in FLeftMargin.LineNumbers.Options)
or (0 <= ARow) and (ARow < FRows.Count) and not (rfFirstRowOfLine in FRows.Items[ARow].Flags)) then
begin
FPaintHelper.Style := [];
LText := '';
LWidth := 0;
end
else if (((FRows.Count = 0) or (rfFirstRowOfLine in FRows.Items[ARow].Flags))
and ((ALine = 0)
or (ALine = FLines.CaretPosition.Line)
or ((ALine + FLeftMargin.LineNumbers.Offset) mod 10 = 0)
or not (lnoIntens in FLeftMargin.LineNumbers.Options))) then
begin
FPaintHelper.Style := [];
LText := IntToStr(ALine + FLeftMargin.LineNumbers.Offset);
LWidth := FPaintHelper.TextWidth(PChar(LText), Length(LText));
end
else if ((ALine + FLeftMargin.LineNumbers.Offset) mod 5 = 0) then
begin
FPaintHelper.Style := [];
LText := '-';
LWidth := FMinusSignWidth;
end
else
begin
FPaintHelper.Style := [fsBold];
LText := #183;
LWidth := FBoldDotSignWidth;
end;
if (csOpaque in ControlStyle) then
LOptions := ETO_OPAQUE
else
LOptions := 0;
FPaintHelper.ExtTextOut(
LRect.Right - LWidth - GPadding,
LRect.Top,
LOptions, LRect, PChar(LText), Length(LText), nil);
end;
cjMouseDown:
if ((MouseCapture in [mcNone])
and LRect.Contains(AMousePoint) and not FSyncEditButtonRect.Contains(AMousePoint)
and (ALine >= 0)) then
AMousePoint.X := FLeftMarginWidth;
cjMouseMove:
if ((MouseCapture in [mcNone])
and (LRect.Contains(AMousePoint) and not FSyncEditButtonRect.Contains(AMousePoint))) then
begin
Cursor := crDefault;
Result := True;
end;
end;
ARect.Left := LRect.Right;
end;
function ProcessLineState(var ARect: TRect; const ALine, ARow: Integer): Boolean;
var
LRect: TRect;
begin
Result := False;
LRect := ARect;
LRect.Right := LRect.Left + FLineStateWidth;
case (AJob) of
cjPaint:
if (LRect.IntersectsWith(AClipRect)
and (csOpaque in ControlStyle)) then
begin
if (ARow < FRows.Count) then
begin
case (FLines.Items[ALine].State) of
lsModified:
if (FColors.LineState.Modified <> clNone) then
FPaintHelper.BackgroundColor := FColors.LineState.Modified
else
FPaintHelper.BackgroundColor := Color;
lsSaved:
if (FColors.LineState.Saved <> clNone) then
FPaintHelper.BackgroundColor := FColors.LineState.Saved
else
FPaintHelper.BackgroundColor := Color;
else
if (FColors.LineState.Loaded <> clNone) then
FPaintHelper.BackgroundColor := FColors.LineState.Loaded
else
FPaintHelper.BackgroundColor := Color;
end
end
else
if (FColors.LineState.Loaded <> clNone) then
FPaintHelper.BackgroundColor := FColors.LineState.Loaded
else
FPaintHelper.BackgroundColor := Color;
FPaintHelper.FillRect(LRect);
end;
cjMouseMove:
if ((MouseCapture in [mcNone, mcLineState])
and LRect.Contains(AMousePoint) and not FSyncEditButtonRect.Contains(AMousePoint)) then
begin
Cursor := crDefault;
Result := True;
end;
end;
ARect.Left := LRect.Right;
end;
function ProcessCodeFolding(var ARect: TRect; const ALine, ARow: Integer): Boolean;
var
LBitmap: TGPCachedBitmap;
LRange: TBCEditorCodeFoldingRanges.TRange;
LRect: TRect;
begin
Result := False;
LRect := ARect;
LRect.Right := LRect.Left + FCodeFoldingWidth;
if (ALine < 0) then
LRange := nil
else
LRange := CodeFoldingCollapsableFoldRangeForLine(ALine);
case (AJob) of
cjPaint:
if (LRect.IntersectsWith(AClipRect)) then
begin
if (Assigned(LRange) and LRange.Collapsable) then
if (not LRange.Collapsed) then
LBitmap := FCodeFoldingCollapsedBitmap
else
LBitmap := FCodeFoldingExpandedBitmap
else if ((0 <= ALine) and (ALine < FLines.Count) and FLines.Items[ALine].CodeFolding.TreeLine) then
LBitmap := FCodeFoldingLineBitmap
else if ((0 <= ALine) and (ALine < FLines.Count) and Assigned(FLines.Items[ALine].CodeFolding.EndRange)) then
LBitmap := FCodeFoldingEndLineBitmap
else
LBitmap := FCodeFoldingNoneBitmap;
APaintVar^.Graphics.DrawCachedBitmap(LBitmap, LRect.Left, LRect.Top)
end;
cjMouseDown:
if ((MouseCapture in [mcNone, mcCodeFolding])
and LRect.Contains(AMousePoint) and not FSyncEditButtonRect.Contains(AMousePoint)
and (AButton = mbLeft)
and Assigned(LRange) and LRange.Collapsable) then
begin
if (not LRange.Collapsed) then
CollapseCodeFoldingRange(LRange)
else
ExpandCodeFoldingRange(LRange);
Result := True;
end;
cjMouseMove:
if ((MouseCapture in [mcNone, mcCodeFolding])
and LRect.Contains(AMousePoint) and not FSyncEditButtonRect.Contains(AMousePoint)) then
begin
Cursor := crDefault;
Result := True;
end;
end;
ARect.Left := LRect.Right;
end;
function ProcessLeftMarginBorder(var ARect: TRect; const ALine, ARow: Integer): Boolean;
var
LRect: TRect;
begin
Result := False;
LRect := ARect;
LRect.Right := LRect.Left + FLeftMarginBorderWidth;
case (AJob) of
cjPaint:
if (LRect.IntersectsWith(AClipRect)
and (csOpaque in ControlStyle)) then
APaintVar^.Graphics.FillRectangle(APaintVar^.LeftMarginBorderBrush, LRect.Left, LRect.Top, LRect.Width, LRect.Height);
cjMouseDown,
cjMouseDblClk,
cjMouseTrplClk,
cjMouseUp,
cjHint:
if (LRect.Contains(AMousePoint)) then
AMousePoint.X := LRect.Right;
cjMouseMove:
if ((MouseCapture = mcNone)
and LRect.Contains(AMousePoint)) then
Cursor := crDefault;
end;
ARect.Left := LRect.Right;
end;
function ProcessSyncEditButton(): Boolean;
var
LRow: Integer;
begin
Result := False;
if (FLines.SyncEdit) then
begin
LRow := LinesToRows(FLines.SyncEditArea.BeginPosition).Row;
LRow := Max(LRow, FTopRow);
LRow := Min(LRow, FTopRow + FUsableRows);
end
else if (lsSyncEditAvailable in FLines.State) then
LRow := LinesToRows(FLines.SelArea.EndPosition).Row
else
LRow := -1;
if (LRow = -1) then
FSyncEditButtonRect := InvalidRect
else
begin
FSyncEditButtonRect.Left := 2 * GetSystemMetrics(SM_CXEDGE);
FSyncEditButtonRect.Top := (LRow - FTopRow) * FLineHeight;
FSyncEditButtonRect.Right := FSyncEditButtonRect.Left + GetSystemMetrics(SM_CXSMICON) + 2 * GetSystemMetrics(SM_CXEDGE);
FSyncEditButtonRect.Bottom := FSyncEditButtonRect.Top + GetSystemMetrics(SM_CYSMICON) + 2 * GetSystemMetrics(SM_CYEDGE);
case (AJob) of
cjPaint,
cjPaintOverlays:
if (APaintOverlays
and FSyncEditButtonRect.IntersectsWith(AClipRect)) then
if (not FLines.SyncEdit) then
APaintVar^.Graphics.DrawCachedBitmap(FSyncEditButtonNormalBitmap, FSyncEditButtonRect.Left, FSyncEditButtonRect.Top)
else
APaintVar^.Graphics.DrawCachedBitmap(FSyncEditButtonPressedBitmap, FSyncEditButtonRect.Left, FSyncEditButtonRect.Top);
cjMouseDown:
if ((MouseCapture in [mcNone, mcSyncEditButton])
and FSyncEditButtonRect.Contains(AMousePoint)
and (AButton = mbLeft)) then
begin
InvalidateRect(FSyncEditButtonRect, True);
MouseCapture := mcSyncEditButton;
Result := True;
end;
cjMouseMove:
if ((MouseCapture in [mcNone, mcSyncEditButton])
and FSyncEditButtonRect.Contains(AMousePoint)) then
begin
if (MouseCapture <> mcSyncEditButton) then
begin
InvalidateRect(FSyncEditButtonRect, True);
MouseCapture := mcSyncEditButton;
end;
end
else if (MouseCapture = mcSyncEditButton) then
begin
InvalidateRect(FSyncEditButtonRect, True);
if (not FSyncEditButtonRect.Contains(AMousePoint)) then
MouseCapture := mcNone;
end;
cjMouseUp:
if ((MouseCapture in [mcNone, mcSyncEditButton])
and FSyncEditButtonRect.Contains(AMousePoint)
and (AButton = mbLeft)) then
begin
ProcessCommand(ecSyncEdit);
MouseCapture := mcNone;
Result := True;
end;
end;
end;
end;
procedure ProcessScroll();
var
LLinesPosition: TBCEditorLinesPosition;
begin
LLinesPosition := ClientToLines(AMousePoint.X, AMousePoint.Y);
if (LLinesPosition <> FLines.CaretPosition) then
MoveCaretAndSelection(LLinesPosition, True);
end;
function ProcessScrolling(): Boolean;
var
LTextPos: TPoint;
begin
Result := False;
case (AJob) of
cjPaint,
cjPaintOverlays:
if (APaintOverlays
and (esScrolling in FState)
and FScrollingRect.IntersectsWith(AClipRect)) then
APaintVar^.Graphics.DrawCachedBitmap(FScrollingBitmap, FScrollingRect.Left, FScrollingRect.Top);
cjMouseDown:
if (esScrolling in FState) then
begin
Exclude(FState, esScrolling);
MouseCapture := mcNone;
InvalidateRect(FScrollingRect, True);
ScrollTo(FTextPos); // Pleace TopRow to the top
Result := True;
end
else if (Rect(FLeftMarginWidth, 0, FClientRect.Width, FClientRect.Height).Contains(AMousePoint)
and (AButton = mbMiddle)) then
begin
FScrollingPoint := AMousePoint;
FScrollingRect.Left := FScrollingPoint.X - FScrollingBitmapWidth div 2;
FScrollingRect.Top := FScrollingPoint.Y - FScrollingBitmapHeight div 2;
FScrollingRect.Right := FScrollingPoint.X + FScrollingBitmapWidth div 2;
FScrollingRect.Bottom := FScrollingPoint.Y + FScrollingBitmapHeight div 2;
InvalidateRect(FScrollingRect, True);
Include(FState, esScrolling);
Cursor := crSizeAll;
MouseCapture := mcScrolling;
SetTimer(WindowHandle, tiScrolling, GClientRefreshTime, nil);
Result := True;
end;
cjScrolling:
if (MouseCapture = mcScrolling) then
begin
LTextPos := FTextPos;
if (AMousePoint.X < FScrollingPoint.X) then
Inc(LTextPos.X, Min(0, (AMousePoint.X - FScrollingPoint.X) div 2 + GetSystemMetrics(SM_CXEDGE)))
else
Inc(LTextPos.X, Max(0, (AMousePoint.X - FScrollingPoint.X) div 2 - GetSystemMetrics(SM_CXEDGE)));
if (AMousePoint.Y < FScrollingPoint.Y) then
Inc(LTextPos.Y, Min(0, (AMousePoint.Y - FScrollingPoint.Y) div 2 + GetSystemMetrics(SM_CXEDGE)))
else
Inc(LTextPos.Y, Max(0, (AMousePoint.Y - FScrollingPoint.Y) div 2 - GetSystemMetrics(SM_CXEDGE)));
ScrollTo(LTextPos, False);
end;
end;
end;
var
LBeginRange: TBCEditorHighlighter.TRange;
LChar: Integer;
LCodeFoldingRange: TBCEditorCodeFoldingRanges.TRange;
LColumn: Integer;
LLeft: Integer;
LLength: Integer;
LLine: Integer;
LMouseRect: TRect;
LRowRect: TRect;
LRow: Integer;
LText: PChar;
LTextClipRect: TRect;
LToken: TBCEditorHighlighter.TTokenFind;
begin
Assert(FLineHeight > 0);
Result := False;
if (ADC = 0) then
FPaintHelper.BeginDraw(Canvas.Handle)
else
FPaintHelper.BeginDraw(ADC);
try
LTextClipRect := AClipRect;
LTextClipRect.Intersect(FTextRect);
if ((AJob in [cjPaint, cjPaintOverlays])
or not (seoShowButton in FSyncEditOptions)) then
FSyncEditButtonRect := InvalidRect
else
Result := Result or ProcessSyncEditButton();
if (not (AJob in [cjPaint, cjPaintOverlays])
and FScrollingEnabled) then
Result := Result or ProcessScrolling();
LRowRect.Left := 0;
LRowRect.Top := - FTextPos.Y mod FLineHeight - FLineHeight;
LRowRect.Right := FClientRect.Width;
LRowRect.Bottom := LRowRect.Top + FLineHeight;
if (not (AJob in [cjPaintOverlays])) then
for LRow := FTopRow to FTopRow + FVisibleRows do
if (not Result) then
begin
Inc(LRowRect.Top, FLineHeight);
Inc(LRowRect.Bottom, FLineHeight);
LMouseRect := LRowRect;
if (MouseCapture <> mcNone) then
begin
LMouseRect.Left := Min(LMouseRect.Left, AMousePoint.X);
LMouseRect.Right := Max(LMouseRect.Right, AMousePoint.X);
if (LRow = FTopRow) then
LMouseRect.Top := Min(LMouseRect.Top, AMousePoint.Y);
if (LRow = FTopRow + FVisibleRows) then
LMouseRect.Bottom := Max(LMouseRect.Bottom, AMousePoint.Y);
end;
if ((AJob = cjPaint) and LRowRect.IntersectsWith(AClipRect)
or (AJob <> cjPaint) and LMouseRect.Contains(AMousePoint)) then
begin
if (LRow < FRows.Count) then
LLine := FRows.Items[LRow].Line
else
LLine := -1;
if (FLeftMargin.Bookmarks.Visible or FLeftMargin.Marks.Visible) then
Result := Result or ProcessMarks(LRowRect, LLine, LRow);
if (FLeftMargin.LineNumbers.Visible) then
Result := Result or ProcessLineNumber(LRowRect, LLine, LRow);
if (FLeftMargin.LineState.Visible) then
Result := Result or ProcessLineState(LRowRect, LLine, LRow);
if (FLeftMargin.CodeFolding.Visible) then
Result := Result or ProcessCodeFolding(LRowRect, LLine, LRow);
if (FLeftMarginWidth > 0) then
Result := Result or ProcessLeftMarginBorder(LRowRect, LLine, LRow);
if (not Result) then
begin
if (AJob = cjMouseTrplClk) then
begin
if ((AButton = mbLeft)
and (soTripleClickLineSelect in FSelectionOptions)
and (LRow < FRows.Count)) then
begin
ProcessCommand(ecSel, TBCEditorCommandDataSelection.Create(FRows.EORPosition[LRow], LinesArea(FRows.BORPosition[LRow], FRows.EORPosition[LRow])));
FLastDoubleClickTime := 0;
Result := True;
end;
end
else
begin
if ((LRow < FRows.Count)
and (AJob <> cjScrolling)) then
begin
LLeft := FTextPos.X;
if (GetFindTokenData(LRow, LLeft, LBeginRange, LText, LLength, LChar, LColumn)
and FHighlighter.FindFirstToken(LBeginRange, LText, LLength, LChar, LToken)) then
begin
Dec(LRowRect.Left, FTextPos.X - LLeft);
if (Assigned(APaintVar)) then
begin
if ((LLine >= FLines.Count) or (FLines.Items[LLine].Foreground = clNone)) then
APaintVar^.LineForegroundColor := clNone
else
APaintVar^.LineForegroundColor := FLines.Items[LLine].Foreground;
if ((LLine >= FLines.Count) or (FLines.Items[LLine].Background = clNone)) then
APaintVar^.LineBackgroundColor := clNone
else
APaintVar^.LineBackgroundColor := FLines.Items[LLine].Background;
APaintVar^.PreviousFontStyles := [];
APaintVar^.PreviousBackgroundColor := clNone;
APaintVar^.PreviousUCC := False;
end;
repeat
Result := Result or ProcessToken(AJob, APaintVar, LTextClipRect, AButton, AShift, AMousePoint, LRowRect,
LinesPosition(FRows.Items[LRow].Char + LToken.Char, LLine),
RowsPosition(LColumn, LRow),
LToken.Text, LToken.Length,
@LToken);
if (LToken.Text^ = BCEDITOR_TAB_CHAR) then
Inc(LColumn, FTabs.Width - LColumn div FTabs.Width)
else
Inc(LColumn, LToken.Length);
until ((LRowRect.Left > FClientRect.Width)
or not FHighlighter.FindNextToken(LToken));
end
else
Dec(LRowRect.Left, FTextPos.X);
if (LRowRect.Left <= FClientRect.Width) then
begin
if (not FLeftMargin.CodeFolding.Visible
or not (rfFirstRowOfLine in FRows.Items[LRow].Flags)) then
LCodeFoldingRange := nil
else
begin
LCodeFoldingRange := CodeFoldingCollapsableFoldRangeForLine(LLine);
if (Assigned(LCodeFoldingRange) and (not LCodeFoldingRange.Collapsed or LCodeFoldingRange.ParentCollapsed)) then
LCodeFoldingRange := nil;
end;
Result := Result or ProcessToken(AJob, APaintVar, LTextClipRect, AButton, AShift, AMousePoint, LRowRect,
FRows.EORPosition[LRow], RowsPosition(FRows.Items[LRow].Length, LRow),
nil, 0, nil, LCodeFoldingRange);
end;
end
else
Result := ProcessToken(AJob, APaintVar, LTextClipRect, AButton, AShift, AMousePoint, LRowRect,
FRows.BORPosition[LRow], RowsPosition(0, LRow),
nil, 0);
end;
LRowRect.Left := 0;
LRowRect.Right := FClientRect.Width;
end;
end;
end;
if ((AJob = cjMouseMove)
and not Result
and (MouseCapture = mcText)) then
begin
ProcessScroll();
SetTimer(WindowHandle, tiScroll, 100, nil);
end;
if ((AJob in [cjPaint, cjPaintOverlays])
and (seoShowButton in FSyncEditOptions)) then
Result := Result or ProcessSyncEditButton();
if ((AJob in [cjPaint, cjPaintOverlays])
and FScrollingEnabled) then
Result := ProcessScrolling() or Result;
finally
FPaintHelper.EndDraw();
end;
end;
function TCustomBCEditor.ProcessCommand(const ACommand: TBCEditorCommand; const AData: TBCEditorCommandData = nil): Boolean;
var
LAllow: Boolean;
LCollapsedCount: Integer;
LHandled: Boolean;
LHandledLong: LongBool;
LIndex: Integer;
LLine: Integer;
LNewSelArea: TBCEditorLinesArea;
begin
Assert(not (ecProcessingCommand in FState));
Include(FState, ecProcessingCommand);
if (ACommand = ecNone) then
Result := False
else
begin
LAllow := True;
if ((ACommand = ecRecordMacro) and FLines.SyncEdit) then
LAllow := ProcessCommand(ecSyncEdit);
if (Assigned(FBeforeProcessCommand)) then
FBeforeProcessCommand(Self, ACommand, AData, LAllow);
LHandled := False;
if (LAllow) then
begin
for LIndex := FHookedCommandHandlers.Count - 1 downto 0 do
if (Assigned(FHookedCommandHandlers[LIndex].ObjectProc)) then
FHookedCommandHandlers[LIndex].ObjectProc(Self, True, ACommand, AData, LHandled)
else
begin
LHandledLong := LHandled;
FHookedCommandHandlers[LIndex].Proc(Self, True, Ord(ACommand), @AData[0], Length(AData),
LHandledLong, FHookedCommandHandlers[LIndex].HandlerData);
LHandled := LHandledLong;
end;
if (not LHandled and (ACommand <> ecNone)) then
begin
if (FLeftMargin.CodeFolding.Visible) then
case (ACommand) of
ecBackspace, ecDeleteChar, ecDeleteWord, ecDeleteLastWord, ecDeleteLine,
ecClear, ecReturn, ecChar, ecText, ecCutToClipboard, ecPasteFromClipboard,
ecBlockIndent, ecBlockUnindent, ecTab:
if (not FLines.SelArea.IsEmpty()) then
begin
LNewSelArea := FLines.SelArea;
LCollapsedCount := 0;
for LLine := LNewSelArea.BeginPosition.Line to LNewSelArea.EndPosition.Line do
LCollapsedCount := ExpandCodeFoldingLines(LLine + 1);
if LCollapsedCount <> 0 then
begin
Inc(LNewSelArea.EndPosition.Line, LCollapsedCount);
LNewSelArea.EndPosition.Char := Length(FLines.Items[LNewSelArea.EndPosition.Line].Text);
end;
FLines.BeginUpdate();
try
FLines.SelArea := LNewSelArea;
finally
FLines.EndUpdate();
end;
end
else
ExpandCodeFoldingLines(FLines.CaretPosition.Line + 1);
end;
LHandled := True;
case (ACommand) of
ecAcceptDrop:
; // Do nothing, but LHandled should be True
ecBackspace:
DoBackspace();
ecBlockComment:
DoBlockComment();
ecBlockIndent:
DoBlockIndent(ACommand);
ecBlockUnindent:
DoBlockIndent(ACommand);
ecBOF:
DoBOF(ACommand);
ecBOL:
DoHomeKey(ACommand = ecSelBOL);
ecBOP:
DoPageTopOrBottom(ACommand);
ecCancel:
if (FLines.SyncEdit) then
DoSyncEdit()
else if (esScrolling in FState) then
ProcessClient(cjMouseDown, 0, nil, FClientRect, mbMiddle, [], FScrollingPoint)
else if (not ReadOnly and not FLines.CanModify) then
FLines.TerminateJob()
else if (esHighlightSearchAllAreas in FState) then
begin
Exclude(FState, esHighlightSearchAllAreas);
InvalidateText();
end;
ecClear:
FLines.Clear();
ecChar:
DoChar(PBCEditorCommandDataChar(AData));
ecCopyToClipboard:
DoCopyToClipboard();
ecCutToClipboard:
DoCutToClipboard();
ecDeleteChar:
DeleteChar();
ecDeleteLastWord:
DeleteLastWordOrBOL(ACommand);
ecDeleteLine:
DeleteLine();
ecDeleteToBOL:
DeleteLastWordOrBOL(ACommand);
ecDeleteToEOL:
DoDeleteToEOL();
ecDeleteWord:
DoDeleteWord();
ecDown:
MoveCaretVertically(1, ACommand = ecSelDown);
ecDropOLE:
DoDropOLE(PBCEditorCommandDataDropOLE(AData));
ecEOF:
DoEOF(ACommand);
ecEOL:
DoEndKey(ACommand = ecSelEOL);
ecEOP:
DoPageTopOrBottom(ACommand);
ecFindFirst:
DoFindFirst(PBCEditorCommandDataFind(AData));
ecFindNext:
if (FLastSearch = lsReplace) then
DoReplace(FLastSearchData)
else if (not Assigned(FLastSearchData)) then
DoShowFind(True)
else if (foBackwards in PBCEditorCommandDataFind(FLastSearchData)^.Options) then
DoFindBackwards(PBCEditorCommandDataFind(FLastSearchData))
else
DoFindForewards(PBCEditorCommandDataFind(FLastSearchData));
ecFindPrevious:
if (FLastSearch = lsReplace) then
DoReplace(FLastSearchData)
else if (not Assigned(FLastSearchData)) then
DoShowFind(True)
else if (foBackwards in PBCEditorCommandDataFind(FLastSearchData)^.Options) then
DoFindForewards(PBCEditorCommandDataFind(FLastSearchData))
else
DoFindBackwards(PBCEditorCommandDataFind(FLastSearchData));
ecGotoBookmark1 ..
ecGotoBookmark0: GotoBookmark(Ord(ACommand) - Ord(ecGotoBookmark1));
ecGotoNextBookmark:
GotoNextBookmark();
ecGotoPreviousBookmark:
GotoPreviousBookmark();
ecInsertLine:
InsertLine();
ecInsertTextMode:
TextEntryMode := temInsert;
ecLeft:
MoveCaretHorizontally(-1, ACommand = ecSelLeft);
ecLineComment:
DoLineComment();
ecLowerCase:
DoToggleSelectedCase(ACommand);
ecOverwriteTextMode:
TextEntryMode := temOverwrite;
ecPageDown:
DoPageKey(ACommand);
ecPageUp:
DoPageKey(ACommand);
ecPasteFromClipboard:
PasteFromClipboard();
ecPosition:
DoPosition(PBCEditorCommandDataPosition(AData));
ecRedo:
FLines.Redo();
ecReplace:
DoReplace(AData);
ecReturn:
if (FWantReturns) then DoReturnKey();
ecRight:
MoveCaretHorizontally(1, ACommand = ecSelRight);
ecScrollDown:
DoScroll(ACommand);
ecScrollLeft:
DoScroll(ACommand);
ecScrollRight:
DoScroll(ACommand);
ecScrollTo:
DoScrollTo(AData);
ecScrollUp:
DoScroll(ACommand);
ecSel:
DoSelection(PBCEditorCommandDataSelection(AData));
ecSelBOF:
DoBOF(ACommand);
ecSelBOL:
DoHomeKey(ACommand = ecSelBOL);
ecSelBOP:
DoPageTopOrBottom(ACommand);
ecSelDown:
MoveCaretVertically(1, ACommand = ecSelDown);
ecSelectAll:
DoSelectAll();
ecSelEOF:
DoEOF(ACommand);
ecSelEOL:
DoEndKey(ACommand = ecSelEOL);
ecSelEOP:
DoPageTopOrBottom(ACommand);
ecSelLeft:
MoveCaretHorizontally(-1, ACommand = ecSelLeft);
ecSelPageDown:
DoPageKey(ACommand);
ecSelPageUp:
DoPageKey(ACommand);
ecSelRight:
MoveCaretHorizontally(1, ACommand = ecSelRight);
ecSelUp:
MoveCaretVertically(-1, ACommand = ecSelUp);
ecSelWord:
SetSelectedWord;
ecSelWordLeft:
DoWordLeft(ACommand);
ecSelWordRight:
DoWordRight(ACommand);
ecSetBookmark1 ..
ecSetBookmark0: DoSetBookmark(ACommand);
ecShiftTab:
if (FWantTabs) then DoTabKey(ACommand);
ecShowCompletionProposal:
DoCompletionProposal();
ecShowFind:
DoShowFind(True);
ecShowGotoLine:
DoShowGotoLine();
ecShowReplace:
DoShowReplace();
ecSyncEdit:
DoSyncEdit();
ecTab:
if (FWantTabs) then DoTabKey(ACommand);
ecText:
DoText(PBCEditorCommandDataText(AData));
ecToggleTextMode:
if (FTextEntryMode = temInsert) then
TextEntryMode := temOverwrite
else
TextEntryMode := temInsert;
ecUndo:
FLines.Undo();
ecUnselect:
DoUnselect();
ecUp:
MoveCaretVertically(-1, ACommand = ecSelUp);
ecUpperCase:
DoToggleSelectedCase(ACommand);
ecWordLeft:
DoWordLeft(ACommand);
ecWordRight:
DoWordRight(ACommand);
else
LHandled := False;
end;
end;
for LIndex := 0 to FHookedCommandHandlers.Count - 1 do
if (Assigned(FHookedCommandHandlers[LIndex].ObjectProc)) then
FHookedCommandHandlers[LIndex].ObjectProc(Self, False, ACommand, AData, LHandled)
else
begin
LHandledLong := LHandled;
FHookedCommandHandlers[LIndex].Proc(Self, False, Ord(ACommand), @AData[0], Length(AData),
LHandledLong, FHookedCommandHandlers[LIndex].HandlerData);
LHandled := LHandledLong;
end;
end;
if (Assigned(FAfterProcessCommand)) then
FAfterProcessCommand(Self, ACommand, AData);
Result := LHandled;
end;
Exclude(FState, ecProcessingCommand);
end;
procedure TCustomBCEditor.ProcessIdle(const AJob: TIdleJob);
begin
if (HandleAllocated and (FPendingJobs = [])) then
SetTimer(WindowHandle, tiIdle, 10, nil);
Include(FPendingJobs, AJob);
end;
function TCustomBCEditor.ProcessToken(const AJob: TClientJob;
const APaintVar: PPaintVar; const AClipRect: TRect;
const AButton: TMouseButton; const AShift: TShiftState; const AMousePoint: TPoint;
var ARect: TRect;
const ALinesPosition: TBCEditorLinesPosition;
const ARowsPosition: TBCEditorRowsPosition;
const AText: PChar; const ALength: Integer;
const AToken: TBCEditorHighlighter.PTokenFind = nil;
const ARange: TBCEditorCodeFoldingRanges.TRange = nil): Boolean;
var
LEndPosition: TBCEditorLinesPosition;
procedure AddPart(const APartBeginPosition, APartEndPosition: TBCEditorLinesPosition;
const APartType: TPaintVar.TPart.TPartType);
var
LIndex: Integer;
LPart: TPaintVar.TPart;
begin
LIndex := APaintVar^.Parts.Count - 1;
while (LIndex >= 0) do
begin
if (APaintVar^.Parts.List[LIndex].BeginPosition = APartBeginPosition) then
begin
if (APaintVar^.Parts.List[LIndex].BeginPosition = APartBeginPosition) then
begin
if (APaintVar^.Parts.List[LIndex].EndPosition = APartEndPosition) then
APaintVar^.Parts.List[LIndex].PartType := APartType
else if (APaintVar^.Parts.List[LIndex].EndPosition > APartEndPosition) then
begin
APaintVar^.Parts.List[LIndex].BeginPosition := APartEndPosition;
LPart.BeginPosition := APartBeginPosition;
LPart.EndPosition := APartEndPosition;
LPart.PartType := APartType;
APaintVar^.Parts.Insert(LIndex, LPart);
end
else
begin
APaintVar^.Parts.List[LIndex].EndPosition := APartEndPosition;
APaintVar^.Parts.List[LIndex].PartType := APartType;
while ((LIndex < APaintVar^.Parts.Count) and (APaintVar^.Parts.List[LIndex].EndPosition < APartEndPosition)) do
APaintVar^.Parts.Delete(LIndex);
if (LIndex < APaintVar^.Parts.Count) then
APaintVar^.Parts.List[LIndex].BeginPosition := APartEndPosition;
end;
exit;
end
end
else if (APaintVar^.Parts.List[LIndex].BeginPosition < APartBeginPosition) then
begin
while ((LIndex >= 0) and (APaintVar^.Parts.List[LIndex].BeginPosition > APartBeginPosition)) do
begin
APaintVar^.Parts.Delete(LIndex);
Dec(LIndex);
end;
if ((LIndex > 0) and (APaintVar^.Parts.List[LIndex - 1].EndPosition > APartBeginPosition)) then
APaintVar^.Parts.List[LIndex - 1].EndPosition := APartBeginPosition;
Inc(LIndex);
break;
end;
Dec(LIndex);
end;
if (LIndex < 0) then
LIndex := 0;
LPart.BeginPosition := APartBeginPosition;
LPart.EndPosition := APartEndPosition;
LPart.PartType := APartType;
if ((APaintVar^.Parts.Count > 0) and (LIndex < APaintVar^.Parts.Count)) then
APaintVar^.Parts.Insert(LIndex, LPart)
else
APaintVar^.Parts.Add(LPart);
end;
procedure ApplyPart(const AArea: TBCEditorLinesArea; APartType: TPaintVar.TPart.TPartType);
begin
if (AArea <> InvalidLinesArea) then
if ((AArea.BeginPosition <= ALinesPosition) and (ALinesPosition < AArea.EndPosition)) then
AddPart(ALinesPosition, Min(LEndPosition, AArea.EndPosition), APartType)
else if ((ALinesPosition < AArea.BeginPosition) and (AArea.BeginPosition < LEndPosition)) then
AddPart(AArea.BeginPosition, Min(LEndPosition, AArea.EndPosition), APartType);
end;
procedure CompleteParts();
var
LIndex: Integer;
LPosition: TBCEditorLinesPosition;
begin
LPosition := ALinesPosition;
LIndex := 0;
while (LPosition < LEndPosition) do
if (LIndex = APaintVar^.Parts.Count) then
begin
AddPart(LPosition, LEndPosition, ptNormal);
exit;
end
else if (LPosition < APaintVar^.Parts.List[LIndex].BeginPosition) then
begin
AddPart(LPosition, APaintVar^.Parts.List[LIndex].BeginPosition, ptNormal);
Inc(LIndex);
LPosition := LinesPosition(APaintVar^.Parts.List[LIndex].EndPosition.Char, APaintVar^.Parts.List[LIndex].EndPosition.Line);
end
else
begin
LPosition := LinesPosition(APaintVar^.Parts.List[LIndex].EndPosition.Char, APaintVar^.Parts.List[LIndex].EndPosition.Line);
Inc(LIndex);
end;
end;
var
LAddOnColor: TColor;
LArea: TBCEditorLinesArea;
LBackgroundColor: TColor;
LBorderColor: TColor;
LChar: Integer;
LCollapsedMarkRect: TRect;
LCursorPosition: TBCEditorLinesPosition;
LEffect: Longint;
LFontStyles: TFontStyles;
LForegroundColor: TColor;
LHint: string;
LIsLineBreakToken: Boolean;
LIsTabToken: Boolean;
LIsUCCToken: Boolean;
LLeft: Integer;
LLength: Integer;
LLine: Integer;
LOptions: Longint;
LOverlayBeginChar: Integer;
LOverlayEndChar: Integer;
LPartBackgroundColor: TColor;
LPartForegroundColor: TColor;
LPartIndex: Integer;
LPartLength: Integer;
LPartText: PChar;
LRect: TRect;
LRight: Integer;
LSelArea: TBCEditorLinesArea;
LSelLength: Integer;
LSelStartAfter: Integer;
LSelStartBefore: Integer;
LStep: Integer;
LText: PChar;
LSize: TSize;
begin
Result := False;
LIsLineBreakToken := not Assigned(AText) and (ALinesPosition.Line < FLines.Count - 1);
LIsTabToken := Assigned(AText) and (AText^ = BCEDITOR_TAB_CHAR);
LIsUCCToken := Assigned(AText) and (ALength = 1) and AText^.IsInArray(BCEditor_UCCs);
if (not LIsLineBreakToken) then
begin
LText := AText;
LLength := ALength;
end
else if ((eoShowSpecialChars in FOptions)
and (0 <= ARowsPosition.Row) and (ARowsPosition.Row < FRows.Count)
and (rfLastRowOfLine in FRows.Items[ARowsPosition.Row].Flags)
and (ALinesPosition.Line < FLines.Count - 1)) then
begin
LText := #182;
LLength := 1;
end
else
begin
LText := #0;
LLength := 0;
end;
if (Assigned(AToken) and Assigned(AToken^.Attribute)) then
LFontStyles := AToken^.Attribute.FontStyles
else
LFontStyles := [];
if (Assigned(LText)) then
case (LText^) of
BCEDITOR_NONE_CHAR:
begin
if (ALength > Length(FSpecialCharsNullText)) then
if (eoShowSpecialChars in FOptions) then
FSpecialCharsNullText := StringOfChar(Char(#127), ALength)
else
FSpecialCharsNullText := StringOfChar(#32, ALength);
LText := PChar(FSpecialCharsNullText);
if (eoShowSpecialChars in FOptions) then
LFontStyles := LFontStyles - [fsBold];
end;
BCEDITOR_TAB_CHAR:
begin
if (eoShowSpecialChars in FOptions) then
LText := #187
else
LText := #32;
if (eoShowSpecialChars in FOptions) then
LFontStyles := LFontStyles - [fsBold];
end;
BCEDITOR_LINEFEED,
BCEDITOR_CARRIAGE_RETURN,
BCEDITOR_SPACE_CHAR:
begin
if (ALength > Length(FSpecialCharsSpaceText)) then
if (eoShowSpecialChars in FOptions) then
FSpecialCharsSpaceText := StringOfChar(Char(#183), ALength)
else
FSpecialCharsSpaceText := StringOfChar(#32, ALength);
LText := PChar(FSpecialCharsSpaceText);
if (eoShowSpecialChars in FOptions) then
LFontStyles := LFontStyles + [fsBold];
end;
end;
FPaintHelper.Style := LFontStyles;
LRect := ARect;
if (not Assigned(AText)) then
LRect.Right := ARect.Right
else if (LIsTabToken) then
LRect.Right := LRect.Left + (FTabs.Width - ARowsPosition.Column mod FTabs.Width) * FTabSignWidth
else if (LLength = 0) then
LRect.Right := LRect.Left
else
LRect.Right := LRect.Left + FPaintHelper.TextWidth(LText, LLength);
if (not Assigned(ARange)) then
LCollapsedMarkRect := Rect(-1, -1, -1, -1)
else
begin
LCollapsedMarkRect := Rect(
LRect.Left + FSpaceWidth,
LRect.Top + GLineWidth,
LRect.Left + FSpaceWidth + 2 * GLineWidth + FCodeFoldingCollapsedMarkWidth + 2 * GLineWidth,
LRect.Bottom - GLineWidth);
if (eoShowSpecialChars in FOptions) then
begin
Inc(LCollapsedMarkRect.Left, FLineBreakSignWidth);
Inc(LCollapsedMarkRect.Right, FLineBreakSignWidth);
end;
end;
case (AJob) of
cjPaint:
if (LRect.IntersectsWith(AClipRect)
and (not LIsLineBreakToken or (ALinesPosition.Line < FLines.Count - 1))) then
begin
LEndPosition := LinesPosition(ALinesPosition.Char + LLength, ALinesPosition.Line);
if (not Assigned(APaintVar)) then
LForegroundColor := clNone
else if (APaintVar^.LineForegroundColor <> clNone) then
LForegroundColor := APaintVar^.LineForegroundColor
else if ((eoShowSpecialChars in FOptions)
and (LIsLineBreakToken or Assigned(LText) and CharInSet(AText^, [BCEDITOR_NONE_CHAR, BCEDITOR_TAB_CHAR, BCEDITOR_LINEFEED, BCEDITOR_CARRIAGE_RETURN, BCEDITOR_SPACE_CHAR]))) then
if (FColors.SpecialChars.Foreground <> clNone) then
LForegroundColor := FColors.SpecialChars.Foreground
else
LForegroundColor := clGrayText
else if (Assigned(AToken) and Assigned(AToken^.Attribute) and (AToken^.Attribute.Foreground <> clNone)) then
LForegroundColor := AToken^.Attribute.Foreground
else if (Font.Color <> clNone) then
LForegroundColor := Font.Color
else
LForegroundColor := clWindowText;
if (not Assigned(APaintVar)) then
LBackgroundColor := clNone
else if (APaintVar^.LineBackgroundColor <> clNone) then
LBackgroundColor := APaintVar^.LineBackgroundColor
else if ((eoHighlightCurrentLine in FOptions)
and (ALinesPosition.Line = FLines.CaretPosition.Line)
and (Colors.CurrentLine.Background <> clNone)) then
LBackgroundColor := Colors.CurrentLine.Background
else if (Assigned(AToken) and Assigned(AToken^.Attribute) and (AToken^.Attribute.Background <> clNone)) then
LBackgroundColor := AToken^.Attribute.Background
else if (Color <> clNone) then
LBackgroundColor := Color
else
LBackgroundColor := clWindow;
if (not LIsLineBreakToken
or (soHighlightWholeLine in FSelectionOptions)) then
begin
if (FLines.SyncEdit
and (FLines.SyncEditArea.BeginPosition < FLines.SyncEditArea.EndPosition)) then
ApplyPart(FLines.SyncEditArea, ptSyncEdit);
if ((esHighlightSearchAllAreas in FState)
and (APaintVar^.SearchResultIndex < FLines.FoundAreas.Count)) then
repeat
if ((ALinesPosition <= FLines.FoundAreas[APaintVar^.SearchResultIndex].BeginPosition)
or (FLines.FoundAreas[APaintVar^.SearchResultIndex].EndPosition < LEndPosition)) then
ApplyPart(FLines.FoundAreas[APaintVar^.SearchResultIndex], ptSearchResult);
if (FLines.FoundAreas[APaintVar^.SearchResultIndex].EndPosition <= LEndPosition) then
Inc(APaintVar^.SearchResultIndex)
else
break;
until ((APaintVar^.SearchResultIndex = FLines.FoundAreas.Count)
or (FLines.FoundAreas[APaintVar^.SearchResultIndex].BeginPosition > LEndPosition));
ApplyPart(FLines.MatchedPairOpenArea, ptMatchingPair);
ApplyPart(FLines.MatchedPairCloseArea, ptMatchingPair);
if (not APaintVar^.SelArea.IsEmpty()) then
ApplyPart(APaintVar^.SelArea, ptSelection);
if (APaintVar^.Parts.Count > 0) then
CompleteParts();
end;
LBorderColor := clNone;
LAddOnColor := clNone;
LPartForegroundColor := LForegroundColor;
LPartBackgroundColor := LBackgroundColor;
LPartIndex := 0;
repeat
if (APaintVar^.Parts.Count = 0) then
begin
LPartText := LText;
LPartLength := LLength;
end
else
begin
if (LPartIndex > 0) then
LRect.Left := LRect.Right;
LPartText := @LText[APaintVar^.Parts[LPartIndex].BeginPosition.Char - ALinesPosition.Char];
LPartLength := APaintVar^.Parts[LPartIndex].EndPosition.Char - APaintVar^.Parts[LPartIndex].BeginPosition.Char;
case (APaintVar^.Parts[LPartIndex].PartType) of
ptNormal:
begin
LPartForegroundColor := LForegroundColor;
LPartBackgroundColor := LBackgroundColor;
end;
ptSyncEdit:
begin
LPartForegroundColor := LForegroundColor;
if (Colors.SyncEdit.Background <> clNone) then
LPartBackgroundColor := Colors.SyncEdit.Background;
end;
ptMatchingPair:
begin
LPartForegroundColor := LForegroundColor;
if (FColors.MatchingPairs.Background <> clNone) then
LPartBackgroundColor := FColors.MatchingPairs.Background
else
LPartBackgroundColor := LBackgroundColor;
end;
ptSelection:
begin
if (not Focused() and HideSelection) then
LPartForegroundColor := clWindowText
else if (FColors.Selection.Foreground <> clNone) then
LPartForegroundColor := FColors.Selection.Foreground
else
LPartForegroundColor := clHighlightText;
if (not Focused() and HideSelection) then
LPartBackgroundColor := cl3DLight
else if (FColors.Selection.Background <> clNone) then
LPartBackgroundColor := FColors.Selection.Background
else
LPartBackgroundColor := clHighlight;
end;
ptSearchResult:
begin
if (FColors.FoundText.Foreground <> clNone) then
LPartForegroundColor := FColors.FoundText.Foreground
else
LPartForegroundColor := LForegroundColor;
if (FColors.FoundText.Background <> clNone) then
LPartBackgroundColor := FColors.FoundText.Background
else
LPartBackgroundColor := LBackgroundColor;
end;
else raise ERangeError.Create('PartType: ' + IntToStr(Ord(APaintVar^.Parts[LPartIndex].PartType)));
end;
if (LIsTabToken) then
// Tab-Tokens have one part only - and they are computed before
else if (LIsLineBreakToken) then
// LineBreak-Tokens have one part only - and they are computed before
else if (not Assigned(AText)) then
// ... rest of the line
else
LRect.Right := LRect.Left + FPaintHelper.TextWidth(LPartText, LPartLength);
end;
FPaintHelper.ForegroundColor := LPartForegroundColor;
FPaintHelper.BackgroundColor := LPartBackgroundColor;
LLeft := LRect.Left;
if (LRect.Left < FLeftMarginWidth) then
begin
LRect.Left := FLeftMarginWidth;
LOptions := ETO_CLIPPED;
end
else
LOptions := 0;
if (csOpaque in ControlStyle) then
LOptions := LOptions or ETO_OPAQUE;
if (LRect.Left <= LRect.Right) then
begin
if (LIsTabToken) then
FPaintHelper.ExtTextOut(LLeft + (LRect.Width - FTabSignWidth) div 2, LRect.Top,
LOptions, LRect, LPartText, LPartLength, nil)
else if (LIsLineBreakToken or not Assigned(AText)) then
FPaintHelper.ExtTextOut(LLeft, LRect.Top,
LOptions, LRect, LPartText, LPartLength, nil)
else if (not (fsItalic in LFontStyles)) then
FPaintHelper.ExtTextOut(LLeft, LRect.Top,
LOptions, LRect, LPartText, LPartLength, nil)
else if (not (fsItalic in APaintVar^.PreviousFontStyles)
or (LPartBackgroundColor <> APaintVar^.PreviousBackgroundColor)
or (APaintVar^.PreviousBackgroundColor = clNone)) then
FPaintHelper.ExtTextOut(LLeft, LRect.Top,
LOptions, Rect(LRect.Left, LRect.Top, ARect.Right, LRect.Bottom), LPartText, LPartLength, nil)
else
FPaintHelper.ExtTextOut(LLeft, LRect.Top,
LOptions and not ETO_OPAQUE, LRect, LPartText, LPartLength, nil);
if (FUCCVisible and APaintVar^.PreviousUCC) then
begin
APaintVar^.Graphics.FillRectangle(APaintVar^.UCCBrush, LRect.Left, LRect.Top, GLineWidth, FLineHeight);
if (LIsTabToken) then
FPaintHelper.ExtTextOut(LLeft + (LRect.Width - FTabSignWidth) div 2, LRect.Top,
0, LRect, LPartText, 1, nil)
else
FPaintHelper.ExtTextOut(LLeft, LRect.Top,
0, LRect, LPartText, 1, nil);
end;
APaintVar^.PreviousBackgroundColor := LPartBackgroundColor;
APaintVar^.PreviousFontStyles := LFontStyles;
end;
Inc(LPartIndex);
until ((APaintVar^.Parts.Count = 0) or (LPartIndex = APaintVar^.Parts.Count));
APaintVar^.PreviousUCC := False;
APaintVar^.Parts.Clear();
if (Assigned(LText) and (LLength > 0) and not LIsUCCToken) then
while ((APaintVar^.OverlayIndex < FOverlays.Count)
and ((FOverlays[APaintVar^.OverlayIndex].Area.EndPosition.Line < ALinesPosition.Line)
or (FOverlays[APaintVar^.OverlayIndex].Area.EndPosition.Line = ALinesPosition.Line)
and (FOverlays[APaintVar^.OverlayIndex].Area.EndPosition.Char <= ALinesPosition.Char + LLength))) do
begin
if ((FOverlays[APaintVar^.OverlayIndex].Area.EndPosition.Line = ALinesPosition.Line)
and (ALinesPosition.Char < FOverlays[APaintVar^.OverlayIndex].Area.EndPosition.Char)) then
begin
LOverlayBeginChar := Max(FOverlays[APaintVar^.OverlayIndex].Area.BeginPosition.Char, ALinesPosition.Char);
LOverlayEndChar := Min(FOverlays[APaintVar^.OverlayIndex].Area.EndPosition.Char, ALinesPosition.Char + LLength);
if ((ALinesPosition.Char <= LOverlayBeginChar) and (LOverlayEndChar <= ALinesPosition.Char + LLength)) then
begin
if (LOverlayBeginChar - ALinesPosition.Char = 0) then
LLeft := LRect.Left
else
LLeft := LRect.Left + FPaintHelper.TextWidth(LText, LOverlayBeginChar - ALinesPosition.Char);
if (LOverlayEndChar - ALinesPosition.Char = ALength) then
LRight := LRect.Right
else
LRight := LRect.Left + FPaintHelper.TextWidth(LText, LOverlayEndChar - ALinesPosition.Char);
case (FOverlays[APaintVar^.OverlayIndex].Style) of
osRect:
begin
if ((FOverlays[APaintVar^.OverlayIndex].Area.BeginPosition.Char >= ALinesPosition.Char)
and (LLeft >= LRect.Left)) then
APaintVar^.Graphics.FillRectangle(APaintVar^.OverlayRectBrush, LLeft, LRect.Top, GLineWidth, FLineHeight);
APaintVar^.Graphics.FillRectangle(APaintVar^.OverlayRectBrush, LLeft, LRect.Top, LRight - LLeft, GLineWidth);
APaintVar^.Graphics.FillRectangle(APaintVar^.OverlayRectBrush, LLeft, LRect.Bottom - GLineWidth, LRight - LLeft, GLineWidth);
if (FOverlays[APaintVar^.OverlayIndex].Area.EndPosition.Char <= ALinesPosition.Char + LLength) then
APaintVar^.Graphics.FillRectangle(APaintVar^.OverlayRectBrush, LRight - GLineWidth, LRect.Top, GLineWidth, FLineHeight);
end;
osUnderline:
begin
APaintVar^.Graphics.FillRectangle(APaintVar^.OverlayUnderlineBrush, LLeft, LRect.Bottom - 2 * GLineWidth, LRight - LLeft, GLineWidth);
end;
// osWaveLine:
// begin
// LStep := 0;
// while LStep < ARect.Right - 4 do
// begin
// Canvas.MoveTo(ARect.Left + LStep, ARect.Bottom - 3);
// Canvas.LineTo(ARect.Left + LStep + 2, ARect.Bottom - 1);
// Canvas.LineTo(ARect.Left + LStep + 4, ARect.Bottom - 3);
// Inc(LStep, 4);
// end;
// end;
end;
end;
end;
if ((FOverlays[APaintVar^.OverlayIndex].Area.EndPosition.Line < ALinesPosition.Line)
or (FOverlays[APaintVar^.OverlayIndex].Area.EndPosition.Char <= ALinesPosition.Char + LLength)) then
Inc(APaintVar^.OverlayIndex)
else
break;
end;
if (Assigned(ARange)
and (LCollapsedMarkRect.Right >= ARect.Left)
and (LCollapsedMarkRect.Left < ARect.Right)) then
begin
FPaintHelper.FrameRect(LCollapsedMarkRect, FColors.CodeFolding.Foreground);
FPaintHelper.ForegroundColor := FColors.CodeFolding.Foreground;
FPaintHelper.ExtTextOut(LCollapsedMarkRect.Left, LCollapsedMarkRect.Top,
0, LCollapsedMarkRect, BCEDITOR_CODEFOLDING_COLLAPSEDMARK, Length(BCEDITOR_CODEFOLDING_COLLAPSEDMARK), nil);
end;
if ((FState * [esCaretInvalid] <> [])
and (ALinesPosition.Line = FLines.CaretPosition.Line)
and (ALinesPosition.Char <= FLines.CaretPosition.Char) and (FLines.CaretPosition.Char < ALinesPosition.Char + ALength)) then
begin
LLength := FLines.CaretPosition.Char - ALinesPosition.Char;
if (LLength = 0) then
FCaretPos := Point(ARect.Left, ARect.Top)
else
FCaretPos := Point(ARect.Left + FPaintHelper.TextWidth(LText, LLength), ARect.Top);
end;
if (Assigned(APaintVar)) then
APaintVar^.PreviousUCC := LIsUCCToken;
end;
cjMouseDown,
cjMouseDblClk,
cjMouseMove,
cjMouseUp,
cjHint:
if (LRect.Contains(AMousePoint)
and (MouseCapture in [mcNone, mcText])
and (not LIsLineBreakToken or (ALinesPosition.Line < FLines.Count - 1))) then
begin
LLine := ALinesPosition.Line;
if (not Assigned(AText)) then
begin
if (not (eoBeyondEndOfFile in FOptions) and (ALinesPosition.Line >= FLines.Count)) then
LLine := Max(0, FLines.Count - 1);
if (not (eoBeyondEndOfLine in FOptions)) then
LChar := 0
else
LChar := (AMousePoint.X + FSpaceWidth div 2 - LRect.Left) div FSpaceWidth;
end
else if (LIsTabToken) then
if (AMousePoint.X <= LRect.Left + (LRect.Right - LRect.Left) div 2) then
LChar := 0
else
LChar := 1
else
begin
LChar := 1;
while (AMousePoint.X >= LRect.Left + FPaintHelper.TextWidth(LText, LChar)) do
Inc(LChar);
if (AMousePoint.X <= LRect.Left + FPaintHelper.TextWidth(LText, LChar - 1) + FPaintHelper.TextWidth(@LText[LChar - 1], 1) div 2) then
Dec(LChar);
end;
LCursorPosition := LinesPosition(ALinesPosition.Char + LChar, LLine);
case (AJob) of
cjMouseDown:
if (AButton = mbLeft) then
if (FLines.SelArea.Contains(LCursorPosition)) then
begin
Include(FState, esWaitForDrag);
FLastDoubleClickTime := 0;
end
else if (LCollapsedMarkRect.Contains(AMousePoint)) then
begin
ProcessCommand(ecPosition, TBCEditorCommandDataPosition.Create(FLines.EOLPosition[ALinesPosition.Line], ssShift in AShift));
MouseCapture := mcText;
end
else
begin
ProcessCommand(ecPosition, TBCEditorCommandDataPosition.Create(LCursorPosition, ssShift in AShift));
MouseCapture := mcText;
end;
cjMouseDblClk:
if (LRect.Contains(AMousePoint)
and (AButton = mbLeft)
and (not LIsLineBreakToken or (ALinesPosition.Line < FLines.Count - 1))) then
if (LCollapsedMarkRect.Contains(AMousePoint)) then
begin
ExpandCodeFoldingRange(ARange);
SetCaretPos(FLines.EOLPosition[ALinesPosition.Line]);
FLastDoubleClickTime := 0;
end
else
SetWordBlock(LCursorPosition);
cjMouseMove:
begin
if (LCollapsedMarkRect.Contains(AMousePoint)) then
Cursor := crDefault
else
Cursor := crIBeam;
if (AShift * [ssLeft, ssRight, ssMiddle] = [ssLeft]) then
if (not (esWaitForDrag in FState)) then
begin
if ((MouseCapture = mcText)
and not (esMouseDblClk in FState)) then
ProcessCommand(ecPosition, TBCEditorCommandDataPosition.Create(LCursorPosition, ssShift in AShift));
end
else if ((Abs(FMouseDownPoint.X - AMousePoint.X) >= GetSystemMetrics(SM_CXDRAG))
or (Abs(FMouseDownPoint.Y - AMousePoint.Y) >= GetSystemMetrics(SM_CYDRAG))) then
begin
Exclude(FState, esWaitForDrag);
Include(FState, esDragging);
try
LSelStartBefore := SelStart;
LSelLength := SelLength;
if (Succeeded(DoDragDrop(TDropData.Create(Self), Self, DROPEFFECT_COPY or DROPEFFECT_MOVE, LEffect))
and (LEffect = DROPEFFECT_MOVE)) then
begin
LSelStartAfter := SelStart;
BeginUpdate();
try
if (LSelStartBefore < LSelStartAfter) then
begin
LArea.BeginPosition := FLines.PositionOf(LSelStartBefore);
LArea.EndPosition := FLines.PositionOf(LSelLength, LArea.BeginPosition);
FLines.DeleteText(LArea);
LSelArea.BeginPosition := FLines.PositionOf(LSelStartAfter - LSelLength);
LSelArea.EndPosition := FLines.PositionOf(LSelLength, LSelArea.BeginPosition);
end
else
begin
LSelArea := FLines.SelArea;
LArea.BeginPosition := FLines.PositionOf(LSelStartBefore + SelLength);
LArea.EndPosition := FLines.PositionOf(LSelLength, LArea.BeginPosition);
FLines.DeleteText(LArea);
end;
SetCaretAndSelection(LSelArea.EndPosition, LSelArea);
finally
EndUpdate();
end;
end;
finally
Exclude(FState, esDragging);
end;
end;
end;
cjMouseUp:
if (LCollapsedMarkRect.Contains(AMousePoint)) then
else
begin
if ((AButton = mbLeft)
and (esWaitForDrag in FState)) then
begin
ProcessCommand(ecPosition, TBCEditorCommandDataPosition.Create(LCursorPosition, ssShift in AShift));
Exclude(FState, esWaitForDrag);
end;
end;
cjHint:
if (LCollapsedMarkRect.Contains(AMousePoint)) then
ActivateHint(AMousePoint.X, AMousePoint.Y + FLineHeight,
Format(SBCEditorCodeFoldingCollapsedMark, [ARange.EndLine - ARange.BeginLine]))
else if (LRect.Contains(AMousePoint)) then
if (Assigned(FOnHint)) then
begin
FOnHint(Self,
LRect.Left, LRect.Top + FLineHeight,
Point(ALinesPosition.Char + LChar, ALinesPosition.Line),
FLines.CharIndexOf(LinesPosition(ALinesPosition.Char + LChar, ALinesPosition.Line)),
LHint);
Result := LHint <> '';
if (Result) then
ActivateHint(LRect.Left, LRect.Top + FLineHeight, LHint);
{$IFDEF Nils}
end
else if (Assigned(AToken)) then
begin
LHint := 'Position: ' + LCursorPosition.ToString() + #10;
LHint := LHint + 'Area: ' + ALinesPosition.ToString() + ' - ' + LinesPosition(ALinesPosition.Char + ALength - 1, ALinesPosition.Line).ToString() + #10;
if (Assigned(AToken.Attribute) and (AToken.Attribute.Element <> BCEDITOR_ATTRIBUTE_ELEMENT_EDITOR)) then
LHint := LHint + 'Element: ' + AToken.Attribute.Element + #10;
if (FLines.ValidPosition(LCursorPosition) and IsWordBreakChar(FLines.Char[LCursorPosition])) then
LHint := LHint + 'IsWordBreakChar: True' + #10;
LHint := Trim(LHint);
ActivateHint(LRect.Left, LRect.Top + FLineHeight, Trim(LHint));
{$ENDIF}
end;
end;
Result := True;
end;
end;
if (Assigned(ARange)) then
ARect.Left := Max(ARect.Left, LCollapsedMarkRect.Right)
else if (not LIsLineBreakToken) then
ARect.Left := Max(ARect.Left, LRect.Right)
else if (eoShowSpecialChars in FOptions) then
ARect.Left := Max(ARect.Left, LRect.Left + FLineBreakSignWidth);
end;
function TCustomBCEditor.QueryContinueDrag(fEscapePressed: BOOL; grfKeyState: Longint): HResult;
begin
if (fEscapePressed) then
Result := DRAGDROP_S_CANCEL
else if (grfKeyState and MK_LBUTTON = 0) then
Result := DRAGDROP_S_DROP
else
Result := S_OK;
end;
procedure TCustomBCEditor.ReadState(Reader: TReader);
begin
inherited;
if (eoTrimTrailingLines in Options) then
FLines.Options := FLines.Options + [loTrimTrailingLines]
else
FLines.Options := FLines.Options - [loTrimTrailingLines];
if (eoTrimTrailingSpaces in Options) then
FLines.Options := FLines.Options + [loTrimTrailingSpaces]
else
FLines.Options := FLines.Options - [loTrimTrailingSpaces];
end;
procedure TCustomBCEditor.Redo();
begin
ProcessCommand(ecRedo);
end;
procedure TCustomBCEditor.RegisterCommandHandler(const AProc: Pointer;
const AHandlerData: Pointer);
var
LCommandHandler: TBCEditorHookedCommandHandler;
begin
if (Assigned(AProc)) then
begin
FillChar(LCommandHandler, SizeOf(LCommandHandler), 0);
LCommandHandler.Proc := AProc;
LCommandHandler.HandlerData := AHandlerData;
if (FHookedCommandHandlers.IndexOf(LCommandHandler) < 0) then
FHookedCommandHandlers.Add(LCommandHandler);
end;
end;
procedure TCustomBCEditor.RegisterCommandHandler(const AProc: TBCEditorHookedCommandObjectProc);
var
LCommandHandler: TBCEditorHookedCommandHandler;
begin
if (Assigned(AProc)) then
begin
FillChar(LCommandHandler, SizeOf(LCommandHandler), 0);
LCommandHandler.ObjectProc := AProc;
if (FHookedCommandHandlers.IndexOf(LCommandHandler) < 0) then
FHookedCommandHandlers.Add(LCommandHandler);
end;
end;
procedure TCustomBCEditor.ReplaceDialogFind(ASender: TObject);
var
LOptions: TBCEditorFindOptions;
begin
LOptions := LOptions - [foRegExpr];
if (frDown in TReplaceDialog(ASender).Options) then
LOptions := LOptions - [foBackwards]
else
LOptions := LOptions + [foBackwards];
if (frMatchCase in TReplaceDialog(ASender).Options) then
LOptions := LOptions + [foCaseSensitive]
else
LOptions := LOptions - [foCaseSensitive];
LOptions := LOptions - [foEntireScope];
if (frWholeWord in TReplaceDialog(ASender).Options) then
LOptions := LOptions + [foWholeWordsOnly]
else
LOptions := LOptions - [foWholeWordsOnly];
FLastSearch := lsFind;
FLastSearchData := TBCEditorCommandDataFind.Create(TReplaceDialog(ASender).FindText, LOptions);
ProcessCommand(ecFindFirst, FLastSearchData);
end;
procedure TCustomBCEditor.ReplaceDialogReplace(ASender: TObject);
var
LOptions: TBCEditorReplaceOptions;
begin
LOptions := LOptions - [roBackwards, roRegExpr];
if (frMatchCase in TReplaceDialog(ASender).Options) then
LOptions := LOptions + [roCaseSensitive]
else
LOptions := LOptions - [roCaseSensitive];
LOptions := LOptions - [roEntireScope];
LOptions := LOptions - [roPrompt];
if (frReplaceAll in TReplaceDialog(ASender).Options) then
LOptions := LOptions + [roReplaceAll]
else
LOptions := LOptions - [roReplaceAll];
if (FLines.SelArea.IsEmpty()) then
LOptions := LOptions - [roSelection]
else
LOptions := LOptions + [roSelection];
if (frWholeWord in TReplaceDialog(ASender).Options) then
LOptions := LOptions + [roWholeWordsOnly]
else
LOptions := LOptions - [roWholeWordsOnly];
FLastSearch := lsReplace;
FLastSearchData := TBCEditorCommandDataReplace.Create(TReplaceDialog(ASender).FindText, TReplaceDialog(ASender).ReplaceText, LOptions);
ProcessCommand(ecReplace, FLastSearchData);
end;
procedure TCustomBCEditor.ReplaceExecuted(const AData: Pointer);
var
LSearchResult: TBCEditorLines.TSearchResult;
begin
LSearchResult := TBCEditorLines.PSearchResult(AData)^;
if (LSearchResult.Count > 0) then
InvalidateClient();
UpdateCursor();
end;
procedure TCustomBCEditor.Resize();
begin
inherited;
if (FWordWrap and (FClientRect.Width <> FOldClientRect.Width) and (FRows.Count > 0)) then
begin
InvalidateRows();
if (FVisibleRows > 0) then
BuildRows(nil, FTopRow + FVisibleRows);
end;
UpdateMetrics();
Include(FState, esCenterCaret);
try
ScrollToCaret();
finally
Exclude(FState, esCenterCaret);
end;
Include(FState, esSizeChanged);
InvalidateScrollBars();
if (DoubleBuffered) then
Perform(CM_DOUBLEBUFFEREDCHANGED, 0, 0);
end;
function TCustomBCEditor.RowsToClient(ARowsPosition: TBCEditorRowsPosition;
const AVisibleOnly: Boolean = False): TPoint;
begin
Result := RowsToText(ARowsPosition, AVisibleOnly);
if (not InvalidPoint(Result)) then
Result := Result - FTextPos + FTextRect.TopLeft;
end;
function TCustomBCEditor.RowsToLines(const ARowsPosition: TBCEditorRowsPosition): TBCEditorLinesPosition;
var
LChar: Integer;
LColumn: Integer;
LLine: Integer;
LLineEndPos: PChar;
LLinePos: PChar;
begin
Assert((ARowsPosition.Column >= 0) and (ARowsPosition.Row >= 0));
if (FRows.Count = 0) then
Result := LinesPosition(ARowsPosition.Column, ARowsPosition.Row)
else if (ARowsPosition.Row >= FRows.Count) then
Result := LinesPosition(ARowsPosition.Column, ARowsPosition.Row - FRows.Count + FLines.Count)
else
begin
LLine := FRows.Items[ARowsPosition.Row].Line;
if (not (rfHasTabs in FRows.Items[ARowsPosition.Row].Flags)) then
begin
LChar := FRows.Items[ARowsPosition.Row].Char + ARowsPosition.Column;
if (LChar >= Length(FLines[LLine])) then
begin
LLinePos := nil;
LLineEndPos := nil;
end
else
begin
LLinePos := @FLines[LLine][1 + LChar];
LLineEndPos := @FLines[LLine][Min(1 + FRows.Items[ARowsPosition.Row].Length, Length(FLines[LLine]))];
end;
end
else
begin
LLinePos := @FLines[LLine][1 + FRows.Items[ARowsPosition.Row].Char];
LLineEndPos := @FLines[LLine][Min(FRows.Items[ARowsPosition.Row].Length, Length(FLines[LLine]))];
LColumn := 0;
LChar := 0;
while ((LColumn < ARowsPosition.Column) and (LLinePos < LLineEndPos)) do
begin
Inc(LColumn, TokenColumns(LLinePos, 1, LColumn));
Inc(LChar);
Inc(LLinePos);
end;
Inc(LChar, ARowsPosition.Column - LColumn);
end;
if (Assigned(LLinePos)) then
while ((LLinePos <= LLineEndPos)
and ((LLinePos^.GetUnicodeCategory in [TUnicodeCategory.ucCombiningMark, TUnicodeCategory.ucNonSpacingMark])
or ((LLinePos - 1)^ <> BCEDITOR_NONE_CHAR)
and ((LLinePos - 1)^.GetUnicodeCategory = TUnicodeCategory.ucNonSpacingMark)
and not IsCombiningDiacriticalMark((LLinePos - 1)^))) do
begin
Inc(LChar);
Inc(LLinePos);
end;
Result := LinesPosition(LChar, LLine);
end;
end;
function TCustomBCEditor.RowsToText(ARowsPosition: TBCEditorRowsPosition;
const AVisibleOnly: Boolean = False): TPoint;
var
LBeginRange: TBCEditorHighlighter.TRange;
LChar: Integer;
LCharColumns: Integer;
LColumn: Integer;
LEOL: Boolean;
LLeft: Integer;
LLength: Integer;
LLinePos: PChar;
LRow: Integer;
LRowColumns: Integer;
LText: PChar;
LToken: TBCEditorHighlighter.TTokenFind;
LTokenColumns: Integer;
LTokenWidth: Integer;
begin
if (not AVisibleOnly) then
begin
Result := RowsToText(ARowsPosition, True);
if (not InvalidPoint(Result)) then
Exit;
end;
if ((FRows.Count = 0)
or (ARowsPosition.Column = 0)
or (ARowsPosition.Row >= FRows.Count)
or (FRows.Items[ARowsPosition.Row].Length = 0)) then
Result := Point(ARowsPosition.Column * FSpaceWidth, ARowsPosition.Row * FLineHeight)
else if (ARowsPosition.Row = FRows.Items[ARowsPosition.Row].Length) then
Result := Point(FRows.Items[ARowsPosition.Row].Width, ARowsPosition.Row * FLineHeight)
else
begin
FPaintHelper.BeginDraw(Canvas.Handle);
try
LRow := ARowsPosition.Row;
LRowColumns := 0;
LTokenColumns := 0;
LEOL := True;
if (AVisibleOnly) then
LLeft := Max(0, FTextPos.X - FTextRect.Width)
else
LLeft := 0;
if (GetFindTokenData(LRow, LLeft, LBeginRange, LText, LLength, LChar, LColumn)
and FHighlighter.FindFirstToken(LBeginRange, LText, LLength, LChar, LToken)) then
begin
LRowColumns := LColumn;
if (LRowColumns <= ARowsPosition.Column) then
repeat
LTokenColumns := TokenColumns(LToken.Text, LToken.Length, LColumn);
LTokenWidth := TokenWidth(LToken.Text, LToken.Length, LColumn, LToken);
if (LRowColumns + LTokenColumns > ARowsPosition.Column) then
LEOL := False;
if (AVisibleOnly) then
if (LRowColumns + LTokenColumns = ARowsPosition.Column) then
Exit(Point(LLeft + LTokenWidth, ARowsPosition.Row * FLineHeight))
else if (LLeft > FTextPos.X + 2 * FTextRect.Width) then
Exit(Point(-1, -1));
if (LEOL) then
begin
Inc(LRowColumns, LTokenColumns);
Inc(LLeft, LTokenWidth);
Inc(LColumn, LTokenColumns);
end;
until (not LEOL or not FHighlighter.FindNextToken(LToken));
end;
if ((LRowColumns < ARowsPosition.Column) and (LTokenColumns > 0)
and not LEOL) then
begin
LLinePos := LToken.Text;
while ((LRowColumns < ARowsPosition.Column) and (LTokenColumns > 0)) do
begin
LCharColumns := TokenColumns(LLinePos, 1, LColumn);
Inc(LRowColumns, LCharColumns);
Inc(LLeft, TokenWidth(LLinePos, 1, LColumn, LToken));
Inc(LColumn, LCharColumns);
Inc(LLinePos);
end;
end;
if (LRowColumns < ARowsPosition.Column) then
Inc(LLeft, (ARowsPosition.Column - LRowColumns) * FSpaceWidth);
finally
FPaintHelper.EndDraw();
end;
if (AVisibleOnly and LEOL) then
Result := Point(-1, -1)
else
Result := Point(LLeft, ARowsPosition.Row * FLineHeight);
end;
end;
procedure TCustomBCEditor.SaveToFile(const AFileName: string; AEncoding: TEncoding = nil);
var
LFileStream: TFileStream;
begin
LFileStream := TFileStream.Create(AFileName, fmCreate);
try
SaveToStream(LFileStream, AEncoding);
finally
LFileStream.Free;
end;
end;
procedure TCustomBCEditor.SaveToStream(AStream: TStream; AEncoding: TEncoding = nil);
begin
FLines.SaveToStream(AStream, AEncoding);
SetModified(False);
end;
procedure TCustomBCEditor.ScanCodeFolding();
var
LIndex: Integer;
LLine: Integer;
LRange: TBCEditorCodeFoldingRanges.TRange;
begin
if (FLeftMargin.CodeFolding.Visible) then
begin
for LLine := 0 to FLines.Count - 1 do
begin
FLines.SetCodeFoldingBeginRange(LLine, nil);
FLines.SetCodeFoldingEndRange(LLine, nil);
FLines.SetCodeFoldingTreeLine(LLine, False);
end;
FAllCodeFoldingRanges.ClearAll();
ScanCodeFoldingRanges();
Exclude(FState, esCodeFoldingInvalid);
for LIndex := FAllCodeFoldingRanges.AllCount - 1 downto 0 do
begin
LRange := FAllCodeFoldingRanges[LIndex];
if (Assigned(LRange)
and not LRange.ParentCollapsed
and ((LRange.BeginLine <> LRange.EndLine)
or LRange.RegionItem.TokenEndIsPreviousLine)) then
begin
FLines.SetCodeFoldingBeginRange(LRange.BeginLine, LRange);
if LRange.Collapsable then
begin
for LLine := LRange.BeginLine + 1 to LRange.EndLine - 1 do
FLines.SetCodeFoldingTreeLine(LLine, True);
FLines.SetCodeFoldingEndRange(LRange.EndLine, LRange);
end;
end;
end;
if (FLeftMargin.CodeFolding.Visible) then
InvalidateRect(FCodeFoldingRect);
end;
end;
procedure TCustomBCEditor.ScanCodeFoldingRanges;
const
DEFAULT_CODE_FOLDING_RANGE_INDEX = 0;
var
LBeginningOfLine: Boolean;
LCodeFoldingRangeIndexList: TList;
LCurrentCodeFoldingRegion: TBCEditorCodeFoldingRegion;
LFoldCount: Integer;
LFoldRanges: TBCEditorCodeFoldingRanges;
LLastFoldRange: TBCEditorCodeFoldingRanges.TRange;
LLine: Integer;
LLineEndPos: PChar;
LLinePos: PChar;
LOpenTokenFoldRangeList: TList;
LOpenTokenSkipFoldRangeList: TList;
LPBookmarkText: PChar;
LPBookmarkText2: PChar;
function IsValidChar(Character: PChar): Boolean;
begin
Result := Character^.IsLower or Character^.IsUpper or Character^.IsNumber or
CharInSet(Character^, BCEDITOR_CODE_FOLDING_VALID_CHARACTERS);
end;
function IsWholeWord(FirstChar, LastChar: PChar): Boolean;
begin
Result := not IsValidChar(FirstChar) and not IsValidChar(LastChar);
end;
function SkipEmptySpace(): Boolean;
begin
while ((LLinePos <= LLineEndPos) and (LLinePos^ < BCEDITOR_EXCLAMATION_MARK)) do
Inc(LLinePos);
Result := LLinePos > LLineEndPos;
end;
function CountCharsBefore(APText: PChar; const Character: Char): Integer;
var
LPText: PChar;
begin
Result := 0;
LPText := APText - 1;
while LPText^ = Character do
begin
Inc(Result);
Dec(LPText);
end;
end;
function OddCountOfStringEscapeChars(APText: PChar): Boolean;
begin
Result := False;
if LCurrentCodeFoldingRegion.StringEscapeChar <> BCEDITOR_NONE_CHAR then
Result := Odd(CountCharsBefore(APText, LCurrentCodeFoldingRegion.StringEscapeChar));
end;
function EscapeChar(APText: PChar): Boolean;
begin
Result := False;
if LCurrentCodeFoldingRegion.EscapeChar <> BCEDITOR_NONE_CHAR then
Result := APText^ = LCurrentCodeFoldingRegion.EscapeChar;
end;
function IsNextSkipChar(APText: PChar; ASkipRegionItem: TBCEditorCodeFoldingSkipRegions.TItem): Boolean;
begin
Result := False;
if ASkipRegionItem.SkipIfNextCharIsNot <> BCEDITOR_NONE_CHAR then
Result := APText^ = ASkipRegionItem.SkipIfNextCharIsNot;
end;
function SkipRegionsClose: Boolean;
var
LSkipRegionItem: TBCEditorCodeFoldingSkipRegions.TItem;
LTokenEndPos: PChar;
LTokenPos: PChar;
LTokenText: string;
begin
Result := False;
{ Note! Check Close before Open because close and open keys might be same. }
if ((LOpenTokenSkipFoldRangeList.Count > 0)
and CharInSet(LLinePos^, FHighlighter.SkipCloseKeyChars)
and not OddCountOfStringEscapeChars(LLinePos)) then
begin
LSkipRegionItem := LOpenTokenSkipFoldRangeList.Last;
if (LSkipRegionItem.CloseToken <> LSkipRegionItem.CloseToken) then
begin
LTokenText := LSkipRegionItem.CloseToken;
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
LPBookmarkText := LLinePos;
{ Check if the close keyword found }
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and ((LLinePos^ = LTokenPos^) or (LSkipRegionItem.SkipEmptyChars and (LLinePos^ < BCEDITOR_EXCLAMATION_MARK)))) do
begin
if (not CharInSet(LLinePos^, [BCEDITOR_NONE_CHAR, BCEDITOR_SPACE_CHAR, BCEDITOR_TAB_CHAR])) then
Inc(LTokenPos);
Inc(LLinePos);
end;
if (LTokenPos >= LTokenEndPos) then { If found, pop skip region from the stack }
begin
LOpenTokenSkipFoldRangeList.Delete(LOpenTokenSkipFoldRangeList.Count - 1);
Result := True;
end
else
LLinePos := LPBookmarkText; { Skip region close not found, return pointer back }
end;
end;
end;
function SkipRegionsOpen: Boolean;
var
LCount: Integer;
LIndex: Integer;
LSkipRegionItem: TBCEditorCodeFoldingSkipRegions.TItem;
LTokenEndPos: PChar;
LTokenPos: PChar;
LTokenText: string;
begin
Result := False;
if CharInSet(LLinePos^, FHighlighter.SkipOpenKeyChars) then
if LOpenTokenSkipFoldRangeList.Count = 0 then
begin
LCount := LCurrentCodeFoldingRegion.SkipRegions.Count - 1;
for LIndex := 0 to LCount do
begin
LSkipRegionItem := LCurrentCodeFoldingRegion.SkipRegions[LIndex];
if ((LLinePos^ = LSkipRegionItem.OpenToken[1])
and not OddCountOfStringEscapeChars(LLinePos)
and not IsNextSkipChar(LLinePos + Length(LSkipRegionItem.OpenToken), LSkipRegionItem)) then
begin
LTokenText := LSkipRegionItem.OpenToken;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
LPBookmarkText := LLinePos;
{ Check, if the open keyword found }
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and ((LLinePos^ = LTokenPos^) or (LSkipRegionItem.SkipEmptyChars and (LLinePos^ < BCEDITOR_EXCLAMATION_MARK)))) do
begin
if (not LSkipRegionItem.SkipEmptyChars
or LSkipRegionItem.SkipEmptyChars and not CharInSet(LLinePos^, [BCEDITOR_NONE_CHAR, BCEDITOR_SPACE_CHAR, BCEDITOR_TAB_CHAR])) then
Inc(LTokenPos);
Inc(LLinePos);
end;
if (LTokenPos > LTokenEndPos) then { If found, skip single line comment or push skip region into stack }
begin
if LSkipRegionItem.RegionType = ritSingleLineString then
begin
LTokenText := LSkipRegionItem.CloseToken;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and ((LLinePos^ <> LTokenPos^) or OddCountOfStringEscapeChars(LLinePos))) do
Inc(LLinePos);
Inc(LLinePos);
end;
end
else if LSkipRegionItem.RegionType = ritSingleLineComment then
{ Single line comment skip until next line }
Exit(True)
else
LOpenTokenSkipFoldRangeList.Add(LSkipRegionItem);
Dec(LLinePos); { The end of the while loop will increase }
Break;
end
else
LLinePos := LPBookmarkText; { Skip region open not found, return pointer back }
end;
end;
end;
end;
end;
procedure RegionItemsClose;
procedure SetCodeFoldingRangeToLine(ARange: TBCEditorCodeFoldingRanges.TRange);
var
LIndex: Integer;
begin
if ARange.RegionItem.TokenEndIsPreviousLine then
begin
LIndex := LLine;
while (LIndex > 0) and (FLines.Items[LIndex - 1].Text = '') do
Dec(LIndex);
ARange.EndLine := LIndex
end
else
ARange.EndLine := LLine;
end;
var
LCodeFoldingRange: TBCEditorCodeFoldingRanges.TRange;
LCodeFoldingRangeLast: TBCEditorCodeFoldingRanges.TRange;
LIndex: Integer;
LIndexDecrease: Integer;
LItemIndex: Integer;
LTokenEndPos: PChar;
LTokenPos: PChar;
LTokenText: string;
begin
if ((LOpenTokenSkipFoldRangeList.Count = 0)
and (LOpenTokenFoldRangeList.Count > 0)
and CharInSet(UpCase(LLinePos^), FHighlighter.FoldCloseKeyChars)) then
begin
LIndexDecrease := 1;
{$if defined(VER250)}
LCodeFoldingRange := nil;
{$endif}
repeat
LIndex := LOpenTokenFoldRangeList.Count - LIndexDecrease;
if LIndex < 0 then
Break;
LCodeFoldingRange := LOpenTokenFoldRangeList.Items[LIndex];
if LCodeFoldingRange.RegionItem.CloseTokenBeginningOfLine and not LBeginningOfLine then
Exit;
LTokenText := LCodeFoldingRange.RegionItem.CloseToken;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
LPBookmarkText := LLinePos;
{ Check if the close keyword found }
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and (UpCase(LLinePos^) = LTokenPos^)) do
begin
Inc(LLinePos);
Inc(LTokenPos);
end;
if (LTokenPos > LTokenEndPos) then { If found, pop skip region from the stack }
begin
if not LCodeFoldingRange.RegionItem.BreakCharFollows or
LCodeFoldingRange.RegionItem.BreakCharFollows and IsWholeWord(LPBookmarkText - 1, LLinePos) then
begin
LOpenTokenFoldRangeList.Remove(LCodeFoldingRange);
Dec(LFoldCount);
if ((LCodeFoldingRange.RegionItem.BreakIfNotFoundBeforeNextRegion <> '')
and not LCodeFoldingRange.IsExtraTokenFound) then
begin
LLinePos := LPBookmarkText;
Exit;
end;
SetCodeFoldingRangeToLine(LCodeFoldingRange);
{ Check if the code folding ranges have shared close }
if LOpenTokenFoldRangeList.Count > 0 then
for LItemIndex := LOpenTokenFoldRangeList.Count - 1 downto 0 do
begin
LCodeFoldingRangeLast := LOpenTokenFoldRangeList.Items[LItemIndex];
if Assigned(LCodeFoldingRangeLast.RegionItem) and LCodeFoldingRangeLast.RegionItem.SharedClose then
begin
LTokenText := LCodeFoldingRangeLast.RegionItem.CloseToken;
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
LLinePos := LPBookmarkText;
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and (UpCase(LLinePos^) = LTokenPos^)) do
begin
Inc(LLinePos);
Inc(LTokenPos);
end;
if (LTokenPos > LTokenEndPos) then
begin
SetCodeFoldingRangeToLine(LCodeFoldingRangeLast);
LOpenTokenFoldRangeList.Remove(LCodeFoldingRangeLast);
Dec(LFoldCount);
end;
end;
end;
LLinePos := LPBookmarkText; { Go back where we were }
end
else
LLinePos := LPBookmarkText; { Region close not found, return pointer back }
end
else
LLinePos := LPBookmarkText; { Region close not found, return pointer back }
end;
Inc(LIndexDecrease);
until Assigned(LCodeFoldingRange) and ((LCodeFoldingRange.RegionItem.BreakIfNotFoundBeforeNextRegion = '') or
(LOpenTokenFoldRangeList.Count - LIndexDecrease < 0));
end;
end;
function RegionItemsOpen: Boolean;
var
LArrayIndex: Integer;
LIndex: Integer;
LLineTempPos: PChar;
LRange: TBCEditorCodeFoldingRanges.TRange;
LRegionItem: TBCEditorCodeFoldingRegionItem;
LSkipIfFoundAfterOpenToken: Boolean;
LTokenEndPos: PChar;
LTokenFollowEndPos: PChar;
LTokenFollowPos: PChar;
LTokenFollowText: string;
LTokenPos: PChar;
LTokenText: string;
begin
Result := False;
if LOpenTokenSkipFoldRangeList.Count <> 0 then
Exit;
if CharInSet(UpCase(LLinePos^), FHighlighter.FoldOpenKeyChars) then
begin
LRange := nil;
if LOpenTokenFoldRangeList.Count > 0 then
LRange := LOpenTokenFoldRangeList.Last;
if Assigned(LRange) and LRange.RegionItem.NoSubs then
Exit;
for LIndex := 0 to LCurrentCodeFoldingRegion.Count - 1 do
begin
LRegionItem := LCurrentCodeFoldingRegion[LIndex];
if (LRegionItem.OpenTokenBeginningOfLine and LBeginningOfLine) or (not LRegionItem.OpenTokenBeginningOfLine) then
begin
{ Check if extra token found }
if Assigned(LRange) then
begin
if LRange.RegionItem.BreakIfNotFoundBeforeNextRegion <> '' then
if (LLinePos^ = LRange.RegionItem.BreakIfNotFoundBeforeNextRegion[1]) then { If first character match }
begin
LTokenText := LRange.RegionItem.BreakIfNotFoundBeforeNextRegion;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
LPBookmarkText := LLinePos;
{ Check if open keyword found }
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and ((UpCase(LLinePos^) = LTokenPos^)
or CharInSet(LLinePos^, [BCEDITOR_NONE_CHAR, BCEDITOR_SPACE_CHAR, BCEDITOR_TAB_CHAR]))) do
begin
if (CharInSet(LTokenPos^, [BCEDITOR_NONE_CHAR, BCEDITOR_SPACE_CHAR, BCEDITOR_TAB_CHAR])
or not CharInSet(LLinePos^, [BCEDITOR_NONE_CHAR, BCEDITOR_SPACE_CHAR, BCEDITOR_TAB_CHAR])) then
Inc(LTokenPos);
Inc(LLinePos);
end;
if (LTokenPos > LTokenEndPos) then
begin
LRange.IsExtraTokenFound := True;
Continue;
end
else
LLinePos := LPBookmarkText; { Region not found, return pointer back }
end;
end;
end;
{ First word after newline }
if (UpCase(LLinePos^) = LRegionItem.OpenToken[1]) then { If first character match }
begin
LTokenText := LRegionItem.OpenToken;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
LPBookmarkText := LLinePos;
{ Check if open keyword found }
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and (UpCase(LLinePos^) = LTokenPos^)) do
begin
Inc(LLinePos);
Inc(LTokenPos);
end;
if ((LRegionItem.OpenTokenCanBeFollowedBy <> '')
and (UpCase(LLinePos^) = LRegionItem.OpenTokenCanBeFollowedBy[1])) then
begin
LLineTempPos := LLinePos;
LTokenFollowText := LRegionItem.OpenTokenCanBeFollowedBy;
LTokenFollowPos := @LTokenFollowText[1];
LTokenFollowEndPos := @LTokenFollowText[Length(LTokenFollowText)];
while (LLineTempPos <= LLineEndPos) and (LTokenFollowPos <= LTokenFollowEndPos)
and (UpCase(LLineTempPos^) = LTokenFollowPos^) do
begin
Inc(LLineTempPos);
Inc(LTokenFollowPos);
end;
if (LTokenFollowPos > LTokenFollowEndPos) then
LLinePos := LLineTempPos;
end;
if (LTokenPos > LTokenEndPos) then
begin
if ((not LRegionItem.BreakCharFollows or LRegionItem.BreakCharFollows and IsWholeWord(LPBookmarkText - 1, LLinePos))
and not EscapeChar(LPBookmarkText - 1)) then { Not interested in partial hits }
begin
{ Check if special rule found }
LSkipIfFoundAfterOpenToken := False;
if (LRegionItem.SkipIfFoundAfterOpenTokenArrayCount > 0) then
while (LLinePos <= LLineEndPos) do
begin
for LArrayIndex := 0 to LRegionItem.SkipIfFoundAfterOpenTokenArrayCount - 1 do
begin
LTokenText := LRegionItem.SkipIfFoundAfterOpenTokenArray[LArrayIndex];
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
LPBookmarkText2 := LLinePos;
if (UpCase(LLinePos^) = LTokenPos^) then { If first character match }
begin
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and (UpCase(LLinePos^) = LTokenPos^)) do
begin
Inc(LLinePos);
Inc(LTokenPos);
end;
if (LTokenPos > LTokenEndPos) then
begin
LSkipIfFoundAfterOpenToken := True;
Break; { for }
end
else
LLinePos := LPBookmarkText2; { Region not found, return pointer back }
end;
end;
if LSkipIfFoundAfterOpenToken then
Break; { while }
Inc(LLinePos);
end;
if LSkipIfFoundAfterOpenToken then
begin
LLinePos := LPBookmarkText; { Skip found, return pointer back }
Continue;
end;
if Assigned(LRange) and (LRange.RegionItem.BreakIfNotFoundBeforeNextRegion <> '')
and not LRange.IsExtraTokenFound then
begin
LOpenTokenFoldRangeList.Remove(LRange);
Dec(LFoldCount);
end;
if LOpenTokenFoldRangeList.Count > 0 then
LFoldRanges := TBCEditorCodeFoldingRanges.TRange(LOpenTokenFoldRangeList.Last).SubCodeFoldingRanges
else
LFoldRanges := FAllCodeFoldingRanges;
LRange := LFoldRanges.Add(FAllCodeFoldingRanges, LLine, GetLineIndentLevel(LLine),
LFoldCount, LRegionItem, LLine);
{ Open keyword found }
LOpenTokenFoldRangeList.Add(LRange);
Inc(LFoldCount);
Dec(LLinePos); { The end of the while loop will increase }
Result := LRegionItem.OpenTokenBreaksLine;
Break;
end
else
LLinePos := LPBookmarkText; { Region not found, return pointer back }
end
else
LLinePos := LPBookmarkText; { Region not found, return pointer back }
end;
end;
end;
end;
end;
end;
function MultiHighlighterOpen: Boolean;
var
LChar: Char;
LCodeFoldingRegion: TBCEditorCodeFoldingRegion;
LIndex: Integer;
LTokenEndPos: PChar;
LTokenPos: PChar;
LTokenText: string;
begin
Result := False;
if LOpenTokenSkipFoldRangeList.Count <> 0 then
Exit;
LChar := UpCase(LLinePos^);
LPBookmarkText := LLinePos;
for LIndex := 1 to Highlighter.CodeFoldingRangeCount - 1 do { First (0) is the default range }
begin
LCodeFoldingRegion := Highlighter.CodeFoldingRegions[LIndex];
if (LChar = LCodeFoldingRegion.OpenToken[1]) then { If first character match }
begin
LTokenText := LCodeFoldingRegion.OpenToken;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
{ Check if open keyword found }
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and (UpCase(LLinePos^) = LTokenPos^)) do
begin
Inc(LLinePos);
Inc(LTokenPos);
end;
LLinePos := LPBookmarkText; { Return pointer always back }
if (LTokenPos > LTokenEndPos) then
begin
LCodeFoldingRangeIndexList.Add(Pointer(LIndex));
LCurrentCodeFoldingRegion := Highlighter.CodeFoldingRegions[LIndex];
Exit(True)
end;
end;
end;
end;
end;
procedure MultiHighlighterClose;
var
LChar: Char;
LCodeFoldingRegion: TBCEditorCodeFoldingRegion;
LIndex: Integer;
LTokenEndPos: PChar;
LTokenPos: PChar;
LTokenText: string;
begin
if (LOpenTokenSkipFoldRangeList.Count = 0) then
begin
LChar := UpCase(LLinePos^);
LPBookmarkText := LLinePos;
for LIndex := 1 to Highlighter.CodeFoldingRangeCount - 1 do { First (0) is the default range }
begin
LCodeFoldingRegion := Highlighter.CodeFoldingRegions[LIndex];
if (LChar = LCodeFoldingRegion.CloseToken[1]) then { If first character match }
begin
LTokenText := LCodeFoldingRegion.CloseToken;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
{ Check if close keyword found }
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and (UpCase(LLinePos^) = LTokenEndPos^)) do
begin
Inc(LLinePos);
Inc(LTokenPos);
end;
LLinePos := LPBookmarkText; { Return pointer always back }
if (LTokenPos > LTokenEndPos) then
begin
if LCodeFoldingRangeIndexList.Count > 0 then
LCodeFoldingRangeIndexList.Delete(LCodeFoldingRangeIndexList.Count - 1);
if LCodeFoldingRangeIndexList.Count > 0 then
LCurrentCodeFoldingRegion := Highlighter.CodeFoldingRegions[Integer(LCodeFoldingRangeIndexList.Last)]
else
LCurrentCodeFoldingRegion := Highlighter.CodeFoldingRegions[DEFAULT_CODE_FOLDING_RANGE_INDEX];
Exit;
end
end;
end;
end;
end;
end;
function TagFolds: Boolean;
var
LCodeFoldingRegion: TBCEditorCodeFoldingRegion;
LIndex: Integer;
begin
Result := False;
for LIndex := 0 to Highlighter.CodeFoldingRangeCount - 1 do
begin
LCodeFoldingRegion := Highlighter.CodeFoldingRegions[LIndex];
if LCodeFoldingRegion.FoldTags then
Exit(True);
end;
end;
procedure AddTagFolds;
var
LAdded: Boolean;
LCloseToken: string;
LOpenToken: string;
LText: string;
LTextBeginPos: PChar;
LTextEndPos: PChar;
LTextPos: PChar;
LRegionItem: TBCEditorCodeFoldingRegionItem;
LTokenAttributes: string;
LTokenAttributesBeginPos: PChar;
LTokenName: string;
LRegion: TBCEditorCodeFoldingRegion;
begin
LText := FLines.Text;
LTextBeginPos := @LText[1];
LTextEndPos := @LText[Length(LText)];
LTextPos := LTextBeginPos;
LAdded := False;
while (LTextPos <= LTextEndPos) do
begin
if (LTextPos^ = '<') then
begin
Inc(LTextPos);
if not CharInSet(LTextPos^, ['?', '!', '/']) then
begin
LTokenName := '';
while ((LTextPos <= LTextEndPos) and not CharInSet(LTextPos^, [' ', '>'])) do
begin
LTokenName := LTokenName + UpCase(LTextPos^);
Inc(LTextPos);
end;
if (LTextPos^ <> ' ') then
LTokenAttributes := ''
else
begin
LTokenAttributesBeginPos := LTextPos;
while ((LTextPos <= LTextEndPos) and not CharInSet(LTextPos^, ['/', '>'])) do
begin
Inc(LTextPos);
if (CharInSet(LTextPos^, ['"', ''''])) then
begin
Inc(LTextPos);
while ((LTextPos <= LTextEndPos) and not CharInSet(LTextPos^, ['"', ''''])) do
Inc(LTextPos);
end;
end;
LTokenAttributes := UpperCase(Copy(LText, 1 + LTokenAttributesBeginPos - LTextBeginPos, LTextPos - LTokenAttributesBeginPos));
end;
LOpenToken := '<' + LTokenName + LTokenAttributes + LTextPos^;
LCloseToken := '</' + LTokenName + '>';
if (LTextPos^ = '>') and (LTextPos^ <> '/') then
begin
LRegion := FHighlighter.CodeFoldingRegions[0];
if not LRegion.Contains(LOpenToken, LCloseToken) then { First (0) is the default range }
begin
LRegionItem := LRegion.Add(LOpenToken, LCloseToken);
LRegionItem.BreakCharFollows := False;
LAdded := True;
end;
end;
end;
end;
Inc(LTextPos);
end;
if (LAdded) then
begin
FHighlighter.AddKeyChar(ctFoldOpen, '<');
FHighlighter.AddKeyChar(ctFoldClose, '<');
end;
end;
var
LRange: TBCEditorCodeFoldingRanges.TRange;
LRow: Integer;
LPreviousLine: Integer;
begin
LFoldCount := 0;
LOpenTokenSkipFoldRangeList := TList.Create;
LOpenTokenFoldRangeList := TList.Create;
LCodeFoldingRangeIndexList := TList.Create;
try
if TagFolds then
AddTagFolds;
{ Go through the text line by line, character by character }
LPreviousLine := -1;
LCodeFoldingRangeIndexList.Add(Pointer(DEFAULT_CODE_FOLDING_RANGE_INDEX));
if Highlighter.CodeFoldingRangeCount > 0 then
LCurrentCodeFoldingRegion := Highlighter.CodeFoldingRegions[DEFAULT_CODE_FOLDING_RANGE_INDEX];
for LRow := 0 to FRows.Count - 1 do
begin
LLine := FRows.Items[LRow].Line;
LRange := TBCEditorCodeFoldingRanges.TRange(FLines.Items[LLine].CodeFolding.BeginRange);
if Assigned(LRange) and LRange.Collapsed then
begin
LPreviousLine := LLine;
Continue;
end;
if ((LPreviousLine <> LLine) and (FLines.Items[LLine].Text <> '')) then
begin
LLinePos := @FLines.Items[LLine].Text[1];
LLineEndPos := @FLines.Items[LLine].Text[Length(FLines.Items[LLine].Text)];
LBeginningOfLine := True;
while (LLinePos <= LLineEndPos) do
if (not SkipEmptySpace()) then
begin
if Highlighter.MultiHighlighter then
if not MultiHighlighterOpen then
MultiHighlighterClose;
if SkipRegionsClose then
Continue; { while LTextPos <= LTextEndPos do }
if SkipRegionsOpen then
Break; { Line comment breaks }
if SkipEmptySpace then
Break;
if LOpenTokenSkipFoldRangeList.Count = 0 then
begin
RegionItemsClose;
if RegionItemsOpen then
Break; { OpenTokenBreaksLine region item option breaks }
end;
if (LLinePos <= LLineEndPos) then
Inc(LLinePos);
{ Skip rest of the word }
while ((LLinePos <= LLineEndPos)
and (LLinePos^.IsLower or LLinePos^.IsUpper or LLinePos^.IsNumber)) do
Inc(LLinePos);
LBeginningOfLine := False; { Not in the beginning of the line anymore }
end;
end;
LPreviousLine := LLine;
end;
{ Check the last not empty line }
LLine := FLines.Count - 1;
while (LLine >= 0) and (Trim(FLines.Items[LLine].Text) = '') do
Dec(LLine);
if ((LLine >= 0) and (FLines.Items[LLine].Text <> '')) then
begin
LLinePos := @FLines.Items[LLine].Text[1];
LLineEndPos := @FLines.Items[LLine].Text[Length(FLines.Items[LLine].Text)];
while LOpenTokenFoldRangeList.Count > 0 do
begin
LLastFoldRange := LOpenTokenFoldRangeList.Last;
if Assigned(LLastFoldRange) then
begin
Inc(LLine);
LLine := Min(LLine, FLines.Count - 1);
if LLastFoldRange.RegionItem.OpenIsClose then
LLastFoldRange.EndLine := LLine;
LOpenTokenFoldRangeList.Remove(LLastFoldRange);
Dec(LFoldCount);
RegionItemsClose;
end;
end;
end;
finally
LCodeFoldingRangeIndexList.Free;
LOpenTokenSkipFoldRangeList.Free;
LOpenTokenFoldRangeList.Free;
end;
end;
procedure TCustomBCEditor.ScrollTo(AValue: TPoint);
begin
ScrollTo(AValue, True);
end;
procedure TCustomBCEditor.ScrollTo(AValue: TPoint; const AAlignToRow: Boolean);
var
LValue: TPoint;
begin
LValue := AValue;
if (not (eoBeyondEndOfLine in FOptions)) then
if (eoShowSpecialChars in FOptions) then
LValue.X := Min(AValue.X, FRows.MaxWidth + FLineBreakSignWidth + FCaretWidth - FTextRect.Width)
else
LValue.X := Min(AValue.X, FRows.MaxWidth + FCaretWidth - FTextRect.Width);
LValue.X := Max(0, LValue.X);
if (not (eoBeyondEndOfFile in FOptions)) then
LValue.Y := Min(AValue.Y, (FRows.Count - FUsableRows) * FLineHeight);
if (AAlignToRow) then
Dec(LValue.Y, LValue.Y mod FLineHeight);
LValue.Y := Max(0, LValue.Y);
if (LValue <> FTextPos) then
ProcessCommand(ecScrollTo, TBCEditorCommandDataScrollTo.Create(LValue));
end;
procedure TCustomBCEditor.ScrollTo(AX, AY: Integer);
begin
ScrollTo(Point(AX, AY), True);
end;
procedure TCustomBCEditor.ScrollToCaret();
var
LCaretTextPos: TPoint;
LTextPos: TPoint;
begin
if ((FRows.Count > 0)
and (GetWindowLong(WindowHandle, GWL_STYLE) and (ES_AUTOVSCROLL or ES_AUTOHSCROLL) <> 0)) then
begin
LCaretTextPos := RowsToText(FRows.CaretPosition);
LTextPos := FTextPos;
if (GetWindowLong(WindowHandle, GWL_STYLE) and ES_AUTOHSCROLL <> 0) then
begin
if (LCaretTextPos.X < LTextPos.X) then
if (not (esCenterCaret in FState)) then
LTextPos.X := LCaretTextPos.X
else if (LCaretTextPos.X < FTextRect.Width * 3 div 4) then
LTextPos.X := 0
else
LTextPos.X := LCaretTextPos.X - FTextRect.Width * 3 div 4;
if (LCaretTextPos.X > LTextPos.X + FTextRect.Width - FCaretWidth) then
if (not (esCenterCaret in FState)) then
LTextPos.X := LCaretTextPos.X + FCaretWidth - FTextRect.Width
else
LTextPos.X := LCaretTextPos.X - FTextRect.Width * 3 div 4;
end;
if (GetWindowLong(WindowHandle, GWL_STYLE) and ES_AUTOVSCROLL <> 0) then
begin
if (LCaretTextPos.Y < LTextPos.Y) then
if (not (esCenterCaret in FState)) then
LTextPos.Y := LCaretTextPos.Y
else
LTextPos.Y := Max(0, FRows.CaretPosition.Row - FUsableRows div 2) * FLineHeight;
if (LCaretTextPos.Y > LTextPos.Y + (FUsableRows - 1) * FLineHeight) then
if (not (esCenterCaret in FState)) then
LTextPos.Y := LCaretTextPos.Y - (FUsableRows - 1) * FLineHeight
else
LTextPos.Y := Max(0, FRows.CaretPosition.Row - FUsableRows div 2) * FLineHeight;
end;
SetTextPos(LTextPos);
end;
end;
procedure TCustomBCEditor.SelectAll();
begin
ProcessCommand(ecSelectAll);
end;
function TCustomBCEditor.SelectedText(): string;
begin
Result := SelText;
end;
function TCustomBCEditor.SelectionAvailable: Boolean;
begin
Result := SelLength <> 0;
end;
procedure TCustomBCEditor.SetBookmark(const AIndex: Integer; const ALinesPosition: TBCEditorLinesPosition);
var
LBookmark: TBCEditorLines.TMark;
LIndex: Integer;
begin
if (ALinesPosition.Line >= 0) and (ALinesPosition.Line <= Max(0, FLines.Count - 1)) then
begin
LIndex := FLines.Bookmarks.IndexOfIndex(AIndex);
if (LIndex >= 0) then
FLines.Bookmarks.Delete(LIndex);
LBookmark := TBCEditorLines.TMark.Create(FLines.Bookmarks);
LBookmark.Pos := ALinesPosition;
LBookmark.ImageIndex := Min(AIndex, BCEDITOR_BOOKMARKS - 1);
LBookmark.Index := AIndex;
LBookmark.Visible := True;
FLines.Bookmarks.Add(LBookmark);
end;
end;
procedure TCustomBCEditor.SetBorderStyle(const AValue: TBorderStyle);
begin
if (AValue <> FBorderStyle) then
begin
FBorderStyle := AValue;
RecreateWnd;
end;
end;
procedure TCustomBCEditor.SetCaretAndSelection(ACaretPosition: TBCEditorLinesPosition;
ASelArea: TBCEditorLinesArea);
begin
FLines.BeginUpdate();
try
FLines.CaretPosition := ACaretPosition;
FLines.SelArea := ASelArea;
finally
FLines.EndUpdate();
end;
end;
procedure TCustomBCEditor.SetCaretPos(const AValue: TPoint);
begin
ProcessCommand(ecPosition, TBCEditorCommandDataPosition.Create(AValue));
end;
procedure TCustomBCEditor.SetColors(AValue: TBCEditorColors);
begin
FColors.Assign(AValue);
end;
procedure TCustomBCEditor.SetCursor(AValue: TCursor);
begin
if (not ReadOnly and not FLines.CanModify) then
inherited Cursor := crHourGlass
else if (esScrolling in FState) then
inherited Cursor := crSizeAll
else
inherited Cursor := AValue;
Windows.SetCursor(Screen.Cursors[inherited Cursor]);
end;
procedure TCustomBCEditor.SetFocus();
begin
// Todo: Implement EIMES_CANCELCOMPSTRINGFOCUS and EIMES_COMPLETECOMPSTRKILLFOCUS
inherited;
end;
procedure TCustomBCEditor.SetHideScrollBars(AValue: Boolean);
begin
if (AValue <> FHideScrollBars) then
begin
FHideScrollBars := AValue;
InvalidateScrollBars();
end;
end;
procedure TCustomBCEditor.SetHideSelection(AValue: Boolean);
begin
if (AValue <> FHideSelection) then
begin
FHideSelection := HideSelection;
if (HandleAllocated) then
if (not AValue) then
SetWindowLong(WindowHandle, GWL_STYLE, GetWindowLong(WindowHandle, GWL_STYLE) or ES_NOHIDESEL)
else
SetWindowLong(WindowHandle, GWL_STYLE, GetWindowLong(WindowHandle, GWL_STYLE) and not ES_NOHIDESEL);
end;
end;
procedure TCustomBCEditor.SetLeftMargin(const AValue: TBCEditorLeftMargin);
begin
FLeftMargin.Assign(AValue);
end;
procedure TCustomBCEditor.SetLinesBeginRanges(const ALine: Integer);
var
LLine: Integer;
LRange: TBCEditorHighlighter.TRange;
LToken: TBCEditorHighlighter.TTokenFind;
begin
Assert((0 <= ALine) and (ALine < FLines.Count));
LLine := ALine;
while (LLine < FLines.Count - 1) do
begin
if (FHighlighter.FindFirstToken(FLines.Items[LLine].BeginRange,
PChar(FLines.Items[LLine].Text), Length(FLines.Items[LLine].Text), 0, LToken)) then
LRange := FLines.Items[LLine].BeginRange
else
repeat
LRange := LToken.Range;
until (not FHighlighter.FindNextToken(LToken));
if (LRange = FLines.Items[LLine + 1].BeginRange) then
exit;
FLines.SetBeginRange(LLine + 1, LRange);
Inc(LLine);
end;
end;
procedure TCustomBCEditor.SetTextPos(const AValue: TPoint);
begin
if (Assigned(FHintWindow)) then
FreeAndNil(FHintWindow);
if (AValue.X <> FTextPos.X) then
NotifyParent(EN_HSCROLL);
if (AValue.Y <> FTextPos.Y) then
NotifyParent(EN_VSCROLL);
if (not (esPainting in FState)) then
if (FTextPos.Y = FTextPos.Y) then
InvalidateText()
else
InvalidateClient()
else
InvalidateCaret();
InvalidateScrollBars();
FTextPos := AValue;
FTopRow := FTextPos.Y div FLineHeight;
end;
procedure TCustomBCEditor.SetTextPos(AX, AY: Integer);
begin
SetTextPos(Point(AX, AY));
end;
procedure TCustomBCEditor.SetInsertPos(AValue: TPoint);
var
LClient: TPoint;
LGraphics: TGPGraphics;
begin
if (AValue <> FInsertPos) then
begin
if (HandleAllocated and Assigned(FInsertPosCache)) then
begin
if (not InvalidPoint(FInsertPos)) then
begin
LClient := RowsToClient(LinesToRows(FInsertPos), True);
if (FInsertPos.X >= 0) then
BitBlt(Canvas.Handle, LClient.X - GLineWidth, LClient.Y, 3 * GLineWidth, FLineHeight,
FInsertPosCache.Canvas.Handle, 0, 0,
SRCCOPY);
end;
FInsertPosCache.Free();
FInsertPosCache := nil;
end;
if (AValue.Y < 0) then
FInsertPos := InvalidPos
else
begin
AValue.X := Max(AValue.X, 0);
AValue.Y := Min(AValue.Y, Max(0, FLines.Count - 1));
if (AValue.Y < FLines.Count) then
AValue.X := Min(AValue.X, FRows.Items[AValue.Y].Length)
else
AValue.X := 0;
FInsertPos := AValue;
if (HandleAllocated
and (not InvalidPoint(FInsertPos))
and ((FTopRow <= LinesToRows(FInsertPos).Row) and (LinesToRows(FInsertPos).Row <= FTopRow + FVisibleRows))) then
begin
LClient := RowsToClient(LinesToRows(FInsertPos), True);
FInsertPosCache := TBitmap.Create();
FInsertPosCache.Handle := CreateCompatibleBitmap(Canvas.Handle, 3 * GLineWidth, FLineHeight);
BitBlt(FInsertPosCache.Canvas.Handle, 0, 0, 3 * GLineWidth, FLineHeight,
Canvas.Handle, LClient.X - GLineWidth, LClient.Y,
SRCCOPY);
LGraphics := TGPGraphics.Create(Canvas.Handle);
LGraphics.DrawCachedBitmap(FInsertPosBitmap, LClient.X - GLineWidth, LClient.Y);
LGraphics.Free();
end;
end;
end;
end;
procedure TCustomBCEditor.SetLineColor(const ALine: Integer; const AForegroundColor, ABackgroundColor: TColor);
begin
if ((0 <= ALine) and (ALine < FLines.Count)
and ((AForegroundColor <> FLines.Items[ALine].Foreground) or (ABackgroundColor <> FLines.Items[ALine].Background))) then
begin
FLines.SetForeground(ALine, AForegroundColor);
FLines.SetBackground(ALine, ABackgroundColor);
InvalidateText(ALine);
end;
end;
procedure TCustomBCEditor.SetMark(const AIndex: Integer; const ALinesPosition: TBCEditorLinesPosition;
const AImageIndex: Integer);
var
LIndex: Integer;
LMark: TBCEditorLines.TMark;
begin
if (ALinesPosition.Line >= 0) and (ALinesPosition.Line <= Max(0, FLines.Count - 1)) then
begin
LIndex := FLines.Marks.IndexOfIndex(AIndex);
if (LIndex >= 0) then
FLines.Marks.Delete(LIndex);
LMark := TBCEditorLines.TMark.Create(FLines.Marks);
with LMark do
begin
Pos := ALinesPosition;
ImageIndex := AImageIndex;
Index := AIndex;
Visible := True;
end;
FLines.Marks.Add(LMark);
end;
end;
procedure TCustomBCEditor.SetModified(const AValue: Boolean);
begin
FLines.Modified := AValue;
end;
procedure TCustomBCEditor.SetMouseCapture(const AValue: TMouseCapture);
begin
if (AValue <> FMouseCapture) then
begin
FMouseCapture := AValue;
inherited MouseCapture := FMouseCapture <> mcNone;
end;
end;
procedure TCustomBCEditor.SetOptions(const AValue: TBCEditorOptions);
begin
if (AValue <> FOptions) then
begin
FOptions := AValue;
if (eoTrimTrailingLines in FOptions) then
FLines.Options := FLines.Options + [loTrimTrailingLines]
else
FLines.Options := FLines.Options - [loTrimTrailingLines];
if (eoTrimTrailingSpaces in FOptions) then
FLines.Options := FLines.Options + [loTrimTrailingSpaces]
else
FLines.Options := FLines.Options - [loTrimTrailingSpaces];
if (eoBeyondEndOfLine in FOptions) then
FLines.Options := FLines.Options + [loBeyondEndOfLine]
else
FLines.Options := FLines.Options - [loBeyondEndOfLine];
if (eoBeyondEndOfFile in FOptions) then
FLines.Options := FLines.Options + [loBeyondEndOfFile]
else
FLines.Options := FLines.Options - [loBeyondEndOfFile];
if (eoDropFiles in FOptions) then
SetWindowLong(WindowHandle, GWL_EXSTYLE, GetWindowLong(WindowHandle, GWL_EXSTYLE) or WS_EX_ACCEPTFILES)
else
SetWindowLong(WindowHandle, GWL_EXSTYLE, GetWindowLong(WindowHandle, GWL_EXSTYLE) and not WS_EX_ACCEPTFILES);
end;
InvalidateClient();
end;
procedure TCustomBCEditor.SetParent(AParent: TWinControl);
begin
inherited;
if (not Assigned(Parent)) then
begin
FFormWnd := 0;
FParentWnd := 0;
end
else
begin
FFormWnd := GetParentForm(Self).Handle;
FParentWnd := Parent.Handle;
end;
end;
procedure TCustomBCEditor.SetReadOnly(const AValue: Boolean);
begin
if (AValue <> FReadOnly) then
begin
FReadOnly := AValue;
if (not FReadOnly) then
FLines.Options := FLines.Options - [loReadOnly]
else
FLines.Options := FLines.Options + [loReadOnly];
if (HandleAllocated) then
if (not FReadOnly) then
SetWindowLong(WindowHandle, GWL_STYLE, GetWindowLong(WindowHandle, GWL_STYLE) and not ES_READONLY)
else
SetWindowLong(WindowHandle, GWL_STYLE, GetWindowLong(WindowHandle, GWL_STYLE) or ES_READONLY);
end;
end;
procedure TCustomBCEditor.SetScrollBars(const AValue: UITypes.TScrollStyle);
begin
if (AValue <> FScrollBars) then
begin
FScrollBars := AValue;
InvalidateScrollBars();
end;
end;
procedure TCustomBCEditor.SetSelectedWord();
begin
SetWordBlock(FLines.CaretPosition);
end;
procedure TCustomBCEditor.SetSelLength(AValue: Integer);
begin
ProcessCommand(ecSel,
TBCEditorCommandDataSelection.Create(FLines.SelArea.BeginPosition,
LinesArea(FLines.SelArea.BeginPosition, FLines.PositionOf(AValue, FLines.SelArea.BeginPosition))));
end;
procedure TCustomBCEditor.SetSelStart(AValue: Integer);
var
LCaretPosition: TBCEditorLinesPosition;
begin
LCaretPosition := FLines.PositionOf(AValue);
ProcessCommand(ecSel, TBCEditorCommandDataSelection.Create(LCaretPosition, LinesArea(LCaretPosition, LCaretPosition)));
end;
procedure TCustomBCEditor.SetSelText(const AValue: string);
begin
ProcessCommand(ecText, TBCEditorCommandDataText.Create(AValue, True, True));
end;
procedure TCustomBCEditor.SetSelectionOptions(AValue: TBCEditorSelectionOptions);
begin
if (AValue <> FSelectionOptions) then
begin
FSelectionOptions := AValue;
if (not FLines.SelArea.IsEmpty()) then
InvalidateText();
end;
end;
procedure TCustomBCEditor.SetSyncEditOptions(AValue: TBCEditorSyncEditOptions);
begin
if (AValue <> FSyncEditOptions) then
begin
FSyncEditOptions := AValue;
if (seoCaseSensitive in FSyncEditOptions) then
FLines.Options := FLines.Options + [loSyncEditCaseSensitive]
else
FLines.Options := FLines.Options - [loSyncEditCaseSensitive];
if (FLines.SyncEdit) then
begin
FLines.SelArea := FLines.SyncEditArea;
ProcessCommand(ecSyncEdit); // Deactivate
ProcessCommand(ecSyncEdit); // Re-activate
end;
end;
end;
procedure TCustomBCEditor.SetTabs(const AValue: TBCEditorTabs);
begin
FTabs.Assign(AValue);
end;
procedure TCustomBCEditor.SetText(const AValue: string);
begin
FLines.Text := AValue;
end;
procedure TCustomBCEditor.SetTopRow(const AValue: Integer);
begin
ScrollTo(FTextPos.X, AValue * FLineHeight);
end;
procedure TCustomBCEditor.SetUndoOption(const AOption: TBCEditorUndoOption; const AEnabled: Boolean);
begin
case (AOption) of
uoGroupUndo:
if (AEnabled) then
FLines.Options := FLines.Options + [loUndoGrouped]
else
FLines.Options := FLines.Options - [loUndoGrouped];
uoUndoAfterLoad:
if (AEnabled) then
FLines.Options := FLines.Options + [loUndoAfterLoad]
else
FLines.Options := FLines.Options - [loUndoAfterLoad];
uoUndoAfterSave:
if (AEnabled) then
FLines.Options := FLines.Options + [loUndoAfterSave]
else
FLines.Options := FLines.Options - [loUndoAfterSave];
end;
end;
procedure TCustomBCEditor.SetUndoOptions(AOptions: TBCEditorUndoOptions);
var
LLinesOptions: TBCEditorLines.TOptions;
begin
LLinesOptions := FLines.Options;
LLinesOptions := LLinesOptions - [loUndoGrouped, loUndoAfterLoad, loUndoAfterSave];
if (uoGroupUndo in AOptions) then
LLinesOptions := LLinesOptions + [loUndoGrouped];
if (uoUndoAfterLoad in AOptions) then
LLinesOptions := LLinesOptions + [loUndoAfterLoad];
if (uoUndoAfterSave in AOptions) then
LLinesOptions := LLinesOptions + [loUndoAfterSave];
FLines.Options := LLinesOptions;
end;
procedure TCustomBCEditor.SetUpdateState(AUpdating: Boolean);
begin
if (not AUpdating) then
begin
if ((FState * [esTextChanged] <> [])
and not (csReading in ComponentState)) then
Change();
if (Assigned(FOnCaretChanged) and (FState * [esCaretChanged] <> [])) then
FOnCaretChanged(Self, CaretPos);
if ((FState * [esSelChanged] <> []) and Assigned(FOnSelChanged)) then
FOnSelChanged(Self);
if ((FState * [esCaretInvalid] <> [])
and (FRows.Count > 0)
and HandleAllocated
and not GetUpdateRect(WindowHandle, nil, not (csOpaque in ControlStyle))) then
UpdateCaret();
FState := FState - [esTextChanged, esSelChanged, esCaretChanged];
end;
end;
procedure TCustomBCEditor.SetWantReturns(const AValue: Boolean);
begin
if (AValue <> FWantReturns) then
begin
FWantReturns := AValue;
if (HandleAllocated) then
if (not AValue) then
SetWindowLong(WindowHandle, GWL_STYLE, GetWindowLong(WindowHandle, GWL_STYLE) and not ES_WANTRETURN)
else
SetWindowLong(WindowHandle, GWL_STYLE, GetWindowLong(WindowHandle, GWL_STYLE) or ES_WANTRETURN);
end;
end;
procedure TCustomBCEditor.SetWordBlock(const ALinesPosition: TBCEditorLinesPosition);
var
LArea: TBCEditorLinesArea;
LLineTextLength: Integer;
begin
if (ALinesPosition.Line < FLines.Count) then
begin
LLineTextLength := Length(FLines.Items[ALinesPosition.Line].Text);
LArea.BeginPosition := LinesPosition(Min(ALinesPosition.Char, LLineTextLength), ALinesPosition.Line);
while ((LArea.BeginPosition.Char > 0)
and not IsWordBreakChar(FLines.Items[ALinesPosition.Line].Text[1 + LArea.BeginPosition.Char - 1])) do
Dec(LArea.BeginPosition.Char);
while ((LArea.BeginPosition.Char > 0)
and not IsWordBreakChar(FLines.Items[ALinesPosition.Line].Text[1 + LArea.BeginPosition.Char - 1])) do
Dec(LArea.BeginPosition.Char);
if ((soDoubleClickRealNumbers in FSelectionOptions) and FLines.Items[ALinesPosition.Line].Text[1 + LArea.BeginPosition.Char].IsNumber) then
while ((LArea.BeginPosition.Char > 0)
and CharInSet(FLines.Items[ALinesPosition.Line].Text[1 + LArea.BeginPosition.Char - 1], BCEDITOR_REAL_NUMBER_CHARS)) do
Dec(LArea.BeginPosition.Char);
LArea.EndPosition := LArea.BeginPosition;
while ((LArea.EndPosition.Char < LLineTextLength)
and not IsWordBreakChar(FLines.Items[ALinesPosition.Line].Text[1 + LArea.EndPosition.Char])) do
Inc(LArea.EndPosition.Char);
if ((soDoubleClickRealNumbers in FSelectionOptions) and FLines.Items[ALinesPosition.Line].Text[1 + LArea.BeginPosition.Char].IsNumber) then
while ((LArea.EndPosition.Char < LLineTextLength)
and CharInSet(FLines.Items[ALinesPosition.Line].Text[1 + LArea.EndPosition.Char], BCEDITOR_REAL_NUMBER_CHARS)) do
Inc(LArea.EndPosition.Char);
SetCaretAndSelection(LArea.EndPosition, LArea);
end;
end;
procedure TCustomBCEditor.SetWordWrap(const AValue: Boolean);
begin
if (AValue <> FWordWrap) then
begin
FWordWrap := AValue;
ScrollToCaret();
InvalidateClient();
end;
end;
procedure TCustomBCEditor.Sort(const ASortOrder: TBCEditorSortOrder = soAsc; const ACaseSensitive: Boolean = False);
var
LBeginLine: Integer;
LEndLine: Integer;
LLine: Integer;
LSelectionBeginPosition: TBCEditorLinesPosition;
LSelectionEndPosition: TBCEditorLinesPosition;
begin
for LLine := 0 to FLines.Count - 1 do
begin
FLines.SetCodeFoldingBeginRange(LLine, nil);
FLines.SetCodeFoldingEndRange(LLine, nil);
FLines.SetCodeFoldingTreeLine(LLine, False);
end;
if (not FLines.SelArea.IsEmpty()) then
begin
LSelectionBeginPosition := FLines.SelArea.BeginPosition;
LSelectionEndPosition := FLines.SelArea.EndPosition;
LBeginLine := LSelectionBeginPosition.Line;
LEndLine := LSelectionEndPosition.Line;
if ((LSelectionEndPosition.Char = 0) and (LSelectionEndPosition.Line > LSelectionBeginPosition.Line)) then
Dec(LEndLine);
end
else
begin
LBeginLine := 0;
LEndLine := FLines.Count - 1;
end;
FLines.CaseSensitive := ACaseSensitive;
FLines.SortOrder := ASortOrder;
FLines.Sort(LBeginLine, LEndLine);
InvalidateRows();
InvalidateCodeFolding();
end;
function TCustomBCEditor.SplitTextIntoWords(AStringList: TStrings; const ACaseSensitive: Boolean): string;
var
LSkipCloseKeyChars: TBCEditorAnsiCharSet;
LSkipOpenKeyChars: TBCEditorAnsiCharSet;
LSkipRegionItem: TBCEditorCodeFoldingSkipRegions.TItem;
procedure AddKeyChars();
var
LIndex: Integer;
LTokenEndPos: PChar;
LTokenPos: PChar;
LTokenText: string;
begin
LSkipOpenKeyChars := [];
LSkipCloseKeyChars := [];
for LIndex := 0 to FHighlighter.CompletionProposalSkipRegions.Count - 1 do
begin
LSkipRegionItem := FHighlighter.CompletionProposalSkipRegions[LIndex];
LTokenText := LSkipRegionItem.OpenToken;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
while (LTokenPos <= LTokenEndPos) do
begin
LSkipOpenKeyChars := LSkipOpenKeyChars + [LTokenPos^];
Inc(LTokenPos);
end;
LTokenText := LSkipRegionItem.CloseToken;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
while (LTokenPos <= LTokenEndPos) do
begin
LSkipCloseKeyChars := LSkipCloseKeyChars + [LTokenPos^];
Inc(LTokenPos);
end;
end;
end;
end;
end;
var
LIndex: Integer;
LLine: Integer;
LLineEndPos: PChar;
LLinePos: PChar;
LOpenTokenSkipFoldRangeList: TList;
LPBookmarkText: PChar;
LStringList: TStringList;
LTokenEndPos: PChar;
LTokenPos: PChar;
LTokenText: string;
LWord: string;
LWordList: string;
begin
Result := '';
AddKeyChars;
AStringList.Clear;
LOpenTokenSkipFoldRangeList := TList.Create;
try
for LLine := 0 to FLines.Count - 1 do
if (FLines.Items[LLine].Text <> '') then
begin
{ Add document words }
LLinePos := @FLines.Items[LLine].Text[1];
LLineEndPos := @FLines.Items[LLine].Text[Length(FLines.Items[LLine].Text)];
LWord := '';
while (LLinePos <= LLineEndPos) do
begin
{ Skip regions - Close }
if (LOpenTokenSkipFoldRangeList.Count > 0) and CharInSet(LLinePos^, LSkipCloseKeyChars) then
begin
LTokenText := TBCEditorCodeFoldingSkipRegions.TItem(LOpenTokenSkipFoldRangeList.Last).CloseToken;
if (LTokenText <> '') then
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
LPBookmarkText := LLinePos;
{ Check if the close keyword found }
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and (LLinePos^ = LTokenPos^)) do
begin
Inc(LLinePos);
Inc(LTokenPos);
end;
if (LTokenPos > LTokenEndPos) then { If found, pop skip region from the list }
begin
LOpenTokenSkipFoldRangeList.Delete(LOpenTokenSkipFoldRangeList.Count - 1);
Continue;
end
else
LLinePos := LPBookmarkText;
{ Skip region close not found, return pointer back }
end;
end;
{ Skip regions - Open }
if (CharInSet(LLinePos^, LSkipOpenKeyChars)) then
for LIndex := 0 to FHighlighter.CompletionProposalSkipRegions.Count - 1 do
begin
LSkipRegionItem := FHighlighter.CompletionProposalSkipRegions[LIndex];
LTokenText := LSkipRegionItem.OpenToken;
if ((LTokenText <> '') and (LLinePos^ = LTokenText[1])) then { If the first character is a match }
begin
LTokenPos := @LTokenText[1];
LTokenEndPos := @LTokenText[Length(LTokenText)];
LPBookmarkText := LLinePos;
{ Check if the open keyword found }
while ((LLinePos <= LLineEndPos) and (LTokenPos <= LTokenEndPos)
and (LLinePos^ = LTokenPos^)) do
begin
Inc(LLinePos);
Inc(LTokenPos);
end;
if (LTokenPos > LTokenEndPos) then { If found, skip single line comment or push skip region into stack }
begin
if LSkipRegionItem.RegionType = ritSingleLineComment then
{ Single line comment skip until next line }
LLinePos := LLineEndPos
else
LOpenTokenSkipFoldRangeList.Add(LSkipRegionItem);
Dec(LLinePos); { The end of the while loop will increase }
Break;
end
else
LLinePos := LPBookmarkText;
{ Skip region open not found, return pointer back }
end;
end;
if LOpenTokenSkipFoldRangeList.Count = 0 then
begin
if ((LWord = '') and (LLinePos^.IsLower or LLinePos^.IsUpper or (LLinePos^ = BCEDITOR_UNDERSCORE))
or (LWord <> '') and (LLinePos^.IsLower or LLinePos^.IsUpper or LLinePos^.IsNumber or (LLinePos^ = BCEDITOR_UNDERSCORE))) then
LWord := LWord + LLinePos^
else
begin
if (LWord <> '') and (Length(LWord) > 1) then
if Pos(LWord + FLines.LineBreak, LWordList) = 0 then { No duplicates }
LWordList := LWordList + LWord + FLines.LineBreak;
LWord := ''
end;
end;
LLinePos := LLineEndPos + 1;
end;
if (Length(LWord) > 1) then
if Pos(LWord + FLines.LineBreak, LWordList) = 0 then { No duplicates }
LWordList := LWordList + LWord + FLines.LineBreak;
end;
LStringList := TStringList.Create();
LStringList.LineBreak := FLines.LineBreak;
LStringList.Text := LWordList;
LStringList.Sort();
AStringList.Assign(LStringList);
LStringList.Free();
finally
LOpenTokenSkipFoldRangeList.Free;
end;
end;
procedure TCustomBCEditor.SyncEditActivated(const AData: Pointer);
begin
Assert(FLines.SyncEdit and (FLines.SyncEditItems.Count > 0));
SetCaretAndSelection(FLines.SyncEditItems[0].Area.BeginPosition, FLines.SyncEditItems[0].Area);
UpdateCursor();
InvalidateText();
end;
procedure TCustomBCEditor.SyncEditChecked(const AData: Pointer);
begin
if (lsSyncEditAvailable in FLines.State) then
InvalidateSyncEditButton();
end;
procedure TCustomBCEditor.TabsChanged(ASender: TObject);
begin
if (FWordWrap) then
InvalidateRows();
InvalidateText();
end;
function TCustomBCEditor.TextBetween(const ABeginPosition, AEndPosition: TBCEditorLinesPosition): string;
var
LSelArea: TBCEditorLinesArea;
begin
LSelArea := FLines.SelArea;
SelStart := PosToCharIndex(Min(ABeginPosition, AEndPosition));
SelLength := SelStart + PosToCharIndex(Max(ABeginPosition, AEndPosition));
Result := SelText;
FLines.SelArea := LSelArea;
end;
function TCustomBCEditor.TextCaretPosition(): TBCEditorLinesPosition;
begin
Result := FLines.CaretPosition;
end;
function TCustomBCEditor.TokenColumns(const AText: PChar;
const ALength, AColumn: Integer): Integer;
begin
if (Assigned(AText) and (AText^ = BCEDITOR_TAB_CHAR)) then
Result := FTabs.Width - AColumn mod FTabs.Width
else
Result := ALength;
end;
function TCustomBCEditor.TokenWidth(const AText: PChar;
const ALength: Integer; const AColumn: Integer;
const AToken: TBCEditorHighlighter.TTokenFind): Integer;
var
LRect: TRect;
begin
LRect := Rect(0, 0, MaxInt, MaxInt);
ProcessToken(cjTokenWidth, nil, FTextRect, mbLeft, [], Point(-1, -1), LRect,
InvalidLinesPosition, RowsPosition(AColumn, -1),
AText, ALength, @AToken);
Result := LRect.Left;
end;
procedure TCustomBCEditor.ToggleSelectedCase(const ACase: TBCEditorCase = cNone);
var
LCommand: TBCEditorCommand;
LSelArea: TBCEditorLinesArea;
begin
if AnsiUpperCase(SelText) <> AnsiUpperCase(FSelectedCaseText) then
begin
FSelectedCaseCycle := cUpper;
FSelectedCaseText := SelText;
end;
if ACase <> cNone then
FSelectedCaseCycle := ACase;
BeginUpdate();
LSelArea := LinesArea(FLines.SelBeginPosition, FLines.SelEndPosition);
LCommand := ecNone;
case FSelectedCaseCycle of
cUpper: { UPPERCASE }
LCommand := ecUpperCase;
cLower: { lowercase }
LCommand := ecLowerCase;
cOriginal: { Original text }
SelText := FSelectedCaseText;
end;
if FSelectedCaseCycle <> cOriginal then
ProcessCommand(LCommand);
FLines.SelArea := LSelArea;
EndUpdate();
Inc(FSelectedCaseCycle);
if FSelectedCaseCycle > cOriginal then
FSelectedCaseCycle := cUpper;
end;
procedure TCustomBCEditor.UMFindAllAreas(var AMessage: TMessage);
var
LSearch: TBCEditorLines.TSearch;
begin
if (FFindArea <> InvalidLinesArea) then
begin
LSearch := TBCEditorLines.TSearch.Create(FLines,
FFindArea,
foCaseSensitive in PBCEditorCommandDataFind(FLastSearchData)^.Options, foWholeWordsOnly in PBCEditorCommandDataFind(FLastSearchData)^.Options, foRegExpr in PBCEditorCommandDataFind(FLastSearchData)^.Options,
PBCEditorCommandDataFind(FLastSearchData)^.Pattern);
FFindArea := InvalidLinesArea;
FFindState := fsAllAreas;
FLines.StartSearch(LSearch, FLines.BOFPosition, True, False, False, FindExecuted);
Sleep(GClientRefreshTime); // If search is fast enough, prevent double painting
end;
end;
procedure TCustomBCEditor.UMFindWrapAround(var AMessage: TMessage);
var
LSearch: TBCEditorLines.TSearch;
begin
if (FFindArea <> InvalidLinesArea) then
begin
if (foBackwards in PBCEditorCommandDataFind(FLastSearchData)^.Options) then
begin
FFindArea.BeginPosition := FFindPosition;
FFindPosition := FLines.EOFPosition;
end
else
begin
FFindArea.EndPosition := FFindPosition;
FFindPosition := FLines.BOFPosition;
end;
LSearch := TBCEditorLines.TSearch.Create(FLines,
FFindArea,
foCaseSensitive in PBCEditorCommandDataFind(FLastSearchData)^.Options, foWholeWordsOnly in PBCEditorCommandDataFind(FLastSearchData)^.Options, foRegExpr in PBCEditorCommandDataFind(FLastSearchData)^.Options,
PBCEditorCommandDataFind(FLastSearchData)^.Pattern);
FFindState := fsWrappedAround;
FLines.StartSearch(LSearch, FFindPosition, False, True, foBackwards in PBCEditorCommandDataFind(FLastSearchData)^.Options, FindExecuted);
Sleep(GClientRefreshTime); // If search is fast enough, prevent double painting
end;
end;
procedure TCustomBCEditor.UMFreeCompletionProposalPopup(var AMessage: TMessage);
begin
if (Assigned(FCompletionProposalPopup)) then
FreeAndNil(FCompletionProposalPopup);
end;
procedure TCustomBCEditor.Undo();
begin
ProcessCommand(ecUndo);
end;
procedure TCustomBCEditor.UnregisterCommandHandler(const AProc: Pointer;
const AHandlerData: Pointer);
var
LCommandHandler: TBCEditorHookedCommandHandler;
begin
FillChar(LCommandHandler, SizeOf(LCommandHandler), 0);
LCommandHandler.Proc := AProc;
LCommandHandler.HandlerData := AHandlerData;
FHookedCommandHandlers.Remove(LCommandHandler);
end;
procedure TCustomBCEditor.UnregisterCommandHandler(const AProc: TBCEditorHookedCommandObjectProc);
var
LCommandHandler: TBCEditorHookedCommandHandler;
begin
FillChar(LCommandHandler, SizeOf(LCommandHandler), 0);
LCommandHandler.ObjectProc := AProc;
FHookedCommandHandlers.Remove(LCommandHandler);
end;
function TCustomBCEditor.UpdateAction(Action: TBasicAction): Boolean;
begin
Result := Focused;
if (Result) then
if Action is TEditCut then
TEditCut(Action).Enabled := not FReadOnly and not FLines.SelArea.IsEmpty()
else if Action is TEditCopy then
TEditCopy(Action).Enabled := not FLines.SelArea.IsEmpty()
else if Action is TEditPaste then
TEditPaste(Action).Enabled := Focused() and CanPaste
else if Action is TEditDelete then
TEditDelete(Action).Enabled := not FReadOnly and not FLines.SelArea.IsEmpty()
else if Action is TEditSelectAll then
TEditSelectAll(Action).Enabled := (FLines.Count > 0)
else if Action is TEditUndo then
TEditUndo(Action).Enabled := not FReadOnly and FLines.CanUndo
else if Action is TSearchFindNext then
TSearchFindNext(Action).Enabled := Assigned(FLastSearchData)
else if Action is TSearchReplace then
TSearchReplace(Action).Enabled := (FLines.Count > 0)
else
Result := inherited;
end;
procedure TCustomBCEditor.UpdateCaret();
var
LCompForm: TCompositionForm;
LRect: TRect;
LImc: HIMC;
begin
if (not (csDesigning in ComponentState)
and HandleAllocated) then
begin
if ((FLineHeight > 0)
and InvalidPoint(FCaretPos)) then
FCaretPos := RowsToClient(FRows.CaretPosition, True);
LRect := FClientRect;
Inc(LRect.Left, FLeftMarginWidth);
if (not LRect.Contains(FCaretPos)
or not Focused() and not Assigned(FCompletionProposalPopup)) then
begin
if (FCaretVisible) then
begin
DestroyCaret();
FCaretVisible := False;
end;
end
else
begin
if (not FCaretVisible) then
begin
CreateCaret(WindowHandle, 0, FCaretWidth, FLineHeight);
ShowCaret(WindowHandle);
FCaretVisible := True;
end;
Windows.SetCaretPos(FCaretPos.X, FCaretPos.Y);
if (GImmEnabled) then
begin
LCompForm.dwStyle := CFS_POINT;
LCompForm.ptCurrentPos := FCaretPos;
LImc := ImmGetContext(WindowHandle);
ImmSetCompositionWindow(LImc, @LCompForm);
ImmReleaseContext(WindowHandle, LImc);
end;
end;
FState := FState - [esCaretInvalid];
end;
end;
procedure TCustomBCEditor.UpdateCursor();
begin
Perform(WM_SETCURSOR, WindowHandle, MakeLong(HTCLIENT, WM_MOUSEMOVE));
end;
procedure TCustomBCEditor.UpdateLineInRows(const ALine: Integer);
var
LRow: Integer;
begin
if (FRows.Count > 0) then
begin
LRow := FLines.Items[ALine].FirstRow;
if (LRow >= 0) then
begin
DeleteLineFromRows(ALine);
InsertLineIntoRows(NotTerminated, ALine, LRow);
end;
end;
end;
procedure TCustomBCEditor.UpdateMetrics();
begin
FClientRect := ClientRect;
FLeftMarginWidth := 0;
if (FLeftMargin.Bookmarks.Visible or FLeftMargin.Marks.Visible) then
begin
FMarksPanelRect := Rect(FLeftMarginWidth, 0, FLeftMarginWidth + FMarksPanelWidth, FClientRect.Height);
Inc(FLeftMarginWidth, FMarksPanelWidth);
end
else
FMarksPanelRect := Rect(-1, -1, -1, -1);
if (FLeftMargin.LineNumbers.Visible) then
begin
FLineNumbersRect := Rect(FLeftMarginWidth, 0, FLeftMarginWidth + FLineNumbersWidth, FClientRect.Height);
Inc(FLeftMarginWidth, FLineNumbersWidth);
end
else
FLineNumbersRect := Rect(-1, -1, -1, -1);
if (FLeftMargin.LineState.Visible) then
begin
FLineStateRect := Rect(FLeftMarginWidth, 0, FLeftMarginWidth + FLineStateWidth, FClientRect.Height);
Inc(FLeftMarginWidth, FLineStateWidth);
end
else
FLineStateRect := Rect(-1, -1, -1, -1);
if (FLeftMargin.CodeFolding.Visible) then
begin
FCodeFoldingRect := Rect(FLeftMarginWidth, 0, FLeftMarginWidth + FCodeFoldingWidth, FClientRect.Height);
Inc(FLeftMarginWidth, FCodeFoldingWidth);
end
else
FCodeFoldingRect := Rect(-1, -1, -1, -1);
if (FLeftMarginWidth > 0) then
Inc(FLeftMarginWidth, FLeftMarginBorderWidth);
FTextRect := Rect(FLeftMarginWidth, 0, FClientRect.Width, FClientRect.Height);
if (FLineHeight > 0) then
begin
FUsableRows := Max(1, FClientRect.Height div FLineHeight);
if (FClientRect.Height = FUsableRows * FLineHeight) then
FVisibleRows := FUsableRows
else
FVisibleRows := FUsableRows + 1;
end;
end;
procedure TCustomBCEditor.UpdateScrollBars();
var
LHorzScrollInfo: TScrollInfo;
LVertScrollInfo: TScrollInfo;
begin
LVertScrollInfo.cbSize := SizeOf(ScrollInfo);
LVertScrollInfo.fMask := SIF_RANGE or SIF_PAGE or SIF_POS;
LVertScrollInfo.nMin := 0;
if (FRows.Count = 0) then
LVertScrollInfo.nMax := 0
else
LVertScrollInfo.nMax := Max(FRows.CaretPosition.Row, FRows.Count - 1);
LVertScrollInfo.nPage := FUsableRows;
LVertScrollInfo.nPos := FTopRow;
LVertScrollInfo.nTrackPos := 0;
SetScrollInfo(WindowHandle, SB_VERT, LVertScrollInfo, TRUE);
// In WM_VSCROLL Message Pos is a SmallInt value... :-/
if (LVertScrollInfo.nMax <= High(SmallInt)) then
FVertScrollBarDivider := 1
else
begin
FVertScrollBarDivider := LVertScrollInfo.nMax div (High(SmallInt) + 1) + 1;
LVertScrollInfo.nMax := LVertScrollInfo.nMax div FVertScrollBarDivider;
LVertScrollInfo.nPage := LVertScrollInfo.nPage div Cardinal(FVertScrollBarDivider);
LVertScrollInfo.nPos := LVertScrollInfo.nPos div FVertScrollBarDivider;
end;
if (LVertScrollInfo.nMax >= Integer(LVertScrollInfo.nPage)) then
EnableScrollBar(WindowHandle, SB_VERT, ESB_ENABLE_BOTH)
else if (not FHideScrollBars) then
begin
ShowScrollBar(WindowHandle, SB_VERT, True);
EnableScrollBar(WindowHandle, SB_VERT, ESB_DISABLE_BOTH);
end;
LHorzScrollInfo.cbSize := SizeOf(ScrollInfo);
LHorzScrollInfo.fMask := SIF_RANGE or SIF_PAGE or SIF_POS;
LHorzScrollInfo.nMin := 0;
LHorzScrollInfo.nMax := FRows.MaxWidth;
if ((FRows.Count = 0)
or (FRows.CaretPosition.Row >= FRows.Count)
or (FRows.Items[FRows.CaretPosition.Row].Length = 0)) then
LHorzScrollInfo.nMax := Max(LHorzScrollInfo.nMax, FRows.CaretPosition.Column * FSpaceWidth)
else if (FRows.CaretPosition.Column > FRows.Items[FRows.CaretPosition.Row].Length) then
LHorzScrollInfo.nMax := Max(LHorzScrollInfo.nMax, FRows.MaxWidth + (FRows.CaretPosition.Column - FRows.Items[FRows.CaretPosition.Row].Length) * FSpaceWidth);
if (eoShowSpecialChars in FOptions) then
Inc(LHorzScrollInfo.nMax, FLineBreakSignWidth);
Inc(LHorzScrollInfo.nMax, FCaretWidth);
LHorzScrollInfo.nPage := FTextRect.Width;
LHorzScrollInfo.nPos := FTextPos.X;
LHorzScrollInfo.nTrackPos := 0;
// In WM_HSCROLL Message Pos is a SmallInt value... :-/
if (LHorzScrollInfo.nMax <= High(SmallInt)) then
FHorzScrollBarDivider := 1
else
begin
FHorzScrollBarDivider := LHorzScrollInfo.nMax div (High(SmallInt) + 1) + 1;
LHorzScrollInfo.nMax := LHorzScrollInfo.nMax div FHorzScrollBarDivider;
LHorzScrollInfo.nPage := LHorzScrollInfo.nPage div Cardinal(FHorzScrollBarDivider);
LHorzScrollInfo.nPos := LHorzScrollInfo.nPos div FHorzScrollBarDivider;
end;
SetScrollInfo(WindowHandle, SB_HORZ, LHorzScrollInfo, TRUE);
if (LHorzScrollInfo.nMax >= Integer(LHorzScrollInfo.nPage)) then
EnableScrollBar(WindowHandle, SB_HORZ, ESB_ENABLE_BOTH)
else if (not FHideScrollBars) then
begin
ShowScrollBar(WindowHandle, SB_HORZ, True);
EnableScrollBar(WindowHandle, SB_HORZ, ESB_DISABLE_BOTH);
end;
if (not (esScrolling in FState)) then
FScrollingEnabled := (eoMiddleClickScrolling in FOptions)
and ((LVertScrollInfo.nMax >= Integer(LVertScrollInfo.nPage))
or (LHorzScrollInfo.nMax >= Integer(LHorzScrollInfo.nPage)));
FState := FState - [esScrollBarsInvalid];
end;
procedure TCustomBCEditor.WMClear(var AMessage: TWMClear);
begin
SelText := '';
end;
procedure TCustomBCEditor.WMCommand(var AMessage: TWMCommand);
begin
if ((AMessage.NotifyCode = 0) and (AMessage.Ctl = 0)) then
case (AMessage.ItemID) of
WM_UNDO,
WM_CUT,
WM_COPY,
WM_PASTE,
WM_CLEAR: Perform(AMessage.ItemID, 0, 0);
EM_SETSEL: Perform(AMessage.ItemID, 0, -1);
WM_APP + 0: { Right to left Reading order }
MessageBox(WindowHandle, 'Does it make sense to heave a right to left order this editor?' + #10
+ 'If yes, please explaint it to the developer of the BCEditor at: https://github.com/bonecode/BCEditor/',
'Help wanted',
MB_OK);
WM_APP + 1: { Show Unicode control characters }
begin
FUCCVisible := not FUCCVisible;
InvalidateText();
end;
WM_APP + 2: Perform(WM_CHAR, Ord(BCEditor_UCC_ZWJ), 0); { ZWJ Unicode control character }
WM_APP + 3: Perform(WM_CHAR, Ord(BCEditor_UCC_ZWNJ), 0); { ZWNJ Unicode control character }
WM_APP + 4: Perform(WM_CHAR, Ord(BCEditor_UCC_LRM), 0); { LRM Unicode control character }
WM_APP + 5: Perform(WM_CHAR, Ord(BCEditor_UCC_RLM), 0); { RLM Unicode control character }
WM_APP + 6: Perform(WM_CHAR, Ord(BCEditor_UCC_LRE), 0); { LRE Unicode control character }
WM_APP + 7: Perform(WM_CHAR, Ord(BCEditor_UCC_RLE), 0); { RLE Unicode control character }
WM_APP + 8: Perform(WM_CHAR, Ord(BCEditor_UCC_LRO), 0); { LRO Unicode control character }
WM_APP + 9: Perform(WM_CHAR, Ord(BCEditor_UCC_RLO), 0); { RLO Unicode control character }
WM_APP + 10: Perform(WM_CHAR, Ord(BCEditor_UCC_PDF), 0); { PDF Unicode control character }
WM_APP + 11: Perform(WM_CHAR, Ord(BCEditor_UCC_NADS), 0); { NADS Unicode control character }
WM_APP + 12: Perform(WM_CHAR, Ord(BCEditor_UCC_NODS), 0); { NODS Unicode control character }
WM_APP + 13: Perform(WM_CHAR, Ord(BCEditor_UCC_ASS), 0); { ASS Unicode control character }
WM_APP + 14: Perform(WM_CHAR, Ord(BCEditor_UCC_ISS), 0); { ISS Unicode control character }
WM_APP + 15: Perform(WM_CHAR, Ord(BCEditor_UCC_AAFS), 0); { AAFS Unicode control character }
WM_APP + 16: Perform(WM_CHAR, Ord(BCEditor_UCC_IAFS), 0); { IAFS Unicode control character }
WM_APP + 17: Perform(WM_CHAR, Ord(BCEditor_UCC_RS), 0); { RS Unicode control character }
WM_APP + 18: Perform(WM_CHAR, Ord(BCEditor_UCC_US), 0); { US Unicode control character }
WM_APP + 20: { Open IME }
MessageBox(WindowHandle, 'The developer of the BCEditor don''t know, how to implement this feature.' + #10
+ 'If you know it, please contact him at: https://github.com/bonecode/BCEditor/',
'Help wanted',
MB_OK);
WM_APP + 21: ; { Reconversion }
else
inherited;
end
else
inherited;
end;
procedure TCustomBCEditor.WMContextMenu(var AMessage: TWMContextMenu);
var
LBuffer: array [0 .. 100] of Char;
LClient: TPoint;
LIndex: Integer;
LIndex2: Integer;
LInstance: THandle;
LLen: Integer;
LMenu: HMENU;
LMenuItemInfo: MENUITEMINFO;
LNewCaretPosition: TBCEditorLinesPosition;
begin
LClient := ScreenToClient(Point(AMessage.XPos, AMessage.YPos));
if (FLeftMargin.Marks.Visible
and (LClient.X <= FMarksPanelWidth)
and Assigned(FMarksPanelPopupMenu)) then
begin
FMarksPanelPopupMenu.Popup(AMessage.XPos, AMessage.YPos);
AMessage.Result := LRESULT(TRUE);
end
else if (LClient.X > FLeftMarginWidth) then
begin
LNewCaretPosition := ClientToLines(LClient.X, LClient.Y);
if (Assigned(PopupMenu)) then
inherited
else
begin
if (FPopupMenu = 0) then
begin
LInstance := GetModuleHandle('User32.dll');
LMenu := LoadMenu(LInstance, MAKEINTRESOURCE(1));
if ((LMenu > 0) and (GetMenuItemCount(LMenu) = 1)) then
begin
LMenu := GetSubMenu(LMenu, 0);
LMenuItemInfo.cbSize := SizeOf(LMenuItemInfo);
LMenuItemInfo.fMask := MIIM_ID or MIIM_STATE or MIIM_SUBMENU;
if ((LMenu > 0) and GetMenuItemInfo(LMenu, 0, TRUE, LMenuItemInfo)) then
begin
FPopupMenu := LMenu;
for LIndex := 0 to GetMenuItemCount(FPopupMenu) - 1 do
if (GetMenuItemInfo(FPopupMenu, LIndex, TRUE, LMenuItemInfo)) then
case (LMenuItemInfo.wID) of
WM_APP + 1: { Show Unicode control characters }
begin
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED;
SetMenuItemInfo(FPopupMenu, LIndex, TRUE, LMenuItemInfo);
end;
WM_APP + 19: { Insert Unicode control character }
begin
LMenu := LMenuItemInfo.hSubMenu;
for LIndex2 := 0 to GetMenuItemCount(LMenu) - 1 do
if (GetMenuItemInfo(LMenu, LIndex2, TRUE, LMenuItemInfo)) then
begin
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED;
SetMenuItemInfo(LMenu, LIndex2, TRUE, LMenuItemInfo);
end;
end;
end;
LLen := LoadString(LInstance, 700, @LBuffer[0], Length(LBuffer));
if (LLen > 0) then
begin
AppendMenu(FPopupMenu, MF_SEPARATOR, 0, nil);
AppendMenu(FPopupMenu, MF_STRING, WM_APP + 20, @LBuffer[0]);
LLen := LoadString(LInstance, 705, @LBuffer[0], Length(LBuffer));
if (LLen > 0) then
AppendMenu(FPopupMenu, MF_STRING, WM_APP + 21, @LBuffer[0]);
end;
end;
end;
end;
if (FPopupMenu <> 0) then
begin
LMenuItemInfo.cbSize := SizeOf(LMenuItemInfo);
LMenuItemInfo.fMask := MIIM_ID or MIIM_STATE;
for LIndex := 0 to GetMenuItemCount(FPopupMenu) - 1 do
if (GetMenuItemInfo(FPopupMenu, LIndex, TRUE, LMenuItemInfo)) then
begin
case (LMenuItemInfo.wID) of
WM_UNDO:
if (CanUndo) then
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED
else
LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_DISABLED;
WM_CUT:
if (not FLines.SelArea.IsEmpty() and not FReadOnly) then
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED
else
LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_DISABLED;
WM_COPY:
if (not FLines.SelArea.IsEmpty()) then
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED
else
LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_DISABLED;
WM_PASTE:
if (CanPaste) then
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED
else
LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_DISABLED;
WM_CLEAR:
if (not FLines.SelArea.IsEmpty() and not FReadOnly) then
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED
else
LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_DISABLED;
EM_SETSEL:
if ((FLines.SelArea <> FLines.Area) and (FLines.Count > 0)) then
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED
else
LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_DISABLED;
WM_APP + 0: { Right to left Reading order }
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED;
// WM_APP + 1: { Show Unicode control characters }
// if (not FUCCVisible) then
// LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_CHECKED
// else
// LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_CHECKED;
// WM_APP + 19: { Insert Unicode control character }
// if (FReadOnly) then
// LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_DISABLED
// else
// LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED;
WM_APP + 20: { Open IME }
LMenuItemInfo.fState := LMenuItemInfo.fState and not MFS_DISABLED;
WM_APP + 21: { Reconversion }
LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_DISABLED
else
LMenuItemInfo.fState := LMenuItemInfo.fState or MFS_DISABLED;
end;
SetMenuItemInfo(FPopupMenu, LIndex, TRUE, LMenuItemInfo);
end;
TrackPopupMenu(FPopupMenu, 2, AMessage.XPos, AMessage.YPos, 0, WindowHandle, nil);
end;
end;
end;
end;
procedure TCustomBCEditor.WMCopy(var AMessage: TWMCopy);
begin
if (FLines.SelArea.IsEmpty()) then
AMessage.Result := LRESULT(FALSE)
else
begin
CopyToClipboard();
AMessage.Result := LRESULT(TRUE);
end;
end;
procedure TCustomBCEditor.WMCut(var AMessage: TWMCut);
begin
if (FReadOnly or FLines.SelArea.IsEmpty()) then
AMessage.Result := LRESULT(FALSE)
else
begin
CutToClipboard();
AMessage.Result := LRESULT(TRUE);
end;
end;
procedure TCustomBCEditor.WMEraseBkgnd(var AMessage: TWMEraseBkgnd);
begin
AMessage.Result := 1;
end;
procedure TCustomBCEditor.WMGetDlgCode(var AMessage: TWMGetDlgCode);
begin
inherited;
AMessage.Result := AMessage.Result or DLGC_WANTARROWS or DLGC_WANTMESSAGE or DLGC_HASSETSEL or DLGC_WANTCHARS;
if (FWantTabs) then
AMessage.Result := AMessage.Result or DLGC_WANTTAB;
if (FWantReturns) then
AMessage.Result := AMessage.Result or DLGC_WANTALLKEYS;
end;
procedure TCustomBCEditor.WMGetText(var AMessage: TWMGetText);
var
LText: string;
begin
if (FFmtLines) then
LText := FRows.FmtText
else
LText := FLines.Text;
StrLCopy(PChar(AMessage.Text), PChar(LText), AMessage.TextMax - 1);
AMessage.Result := StrLen(PChar(AMessage.Text));
end;
procedure TCustomBCEditor.WMGetTextLength(var AMessage: TWMGetTextLength);
begin
if ((csDocking in ControlState) or (csDestroying in ComponentState)) then
AMessage.Result := 0
else
AMessage.Result := FLines.TextLength;
end;
procedure TCustomBCEditor.WMHScroll(var AMessage: TWMScroll);
begin
inherited;
case (AMessage.ScrollCode) of
SB_LINELEFT:
ScrollTo(FTextPos.X - Integer(FWheelScrollChars) * FSpaceWidth, FTextPos.Y);
SB_LINERIGHT:
ScrollTo(FTextPos.X + Integer(FWheelScrollChars) * FSpaceWidth, FTextPos.Y);
SB_PAGELEFT:
ScrollTo(FTextPos.X - FTextRect.Width, FTextPos.Y);
SB_PAGERIGHT:
ScrollTo(FTextPos.X + FTextRect.Width, FTextPos.Y);
SB_THUMBPOSITION,
SB_THUMBTRACK:
ScrollTo(AMessage.Pos * FHorzScrollBarDivider, FTextPos.Y);
SB_LEFT:
ScrollTo(0, FTextPos.Y);
SB_RIGHT:
ScrollTo(FRows.MaxWidth - FTextRect.Width, FTextPos.Y);
end;
AMessage.Result := 0;
end;
procedure TCustomBCEditor.WMIMEChar(var AMessage: TMessage);
begin
{ Do nothing here, the IME string is retrieved in WMIMEComposition
Handling the WM_IME_CHAR message stops Windows from sending WM_CHAR messages while using the IME }
end;
procedure TCustomBCEditor.WMIMEComposition(var AMessage: TMessage);
var
LImc: HIMC;
LSize: Integer;
LText: string;
begin
if ((AMessage.LParam and GCS_RESULTSTR <> 0)
and (FIMEStatus and EIMES_GETCOMPSTRATONCE = 0)) then
begin
LImc := ImmGetContext(WindowHandle);
try
LSize := ImmGetCompositionString(LImc, GCS_RESULTSTR, nil, 0);
{ ImeCount is always the size in bytes, also for Unicode }
SetLength(LText, LSize div SizeOf(Char));
ImmGetCompositionString(LImc, GCS_RESULTSTR, PChar(LText), LSize);
ProcessCommand(ecText, TBCEditorCommandDataText.Create(LText));
finally
ImmReleaseContext(WindowHandle, LImc);
end;
end;
inherited;
end;
procedure TCustomBCEditor.WMIMENotify(var AMessage: TMessage);
var
LImc: HIMC;
LLogFont: TLogFont;
begin
case (AMessage.wParam) of
IMN_SETOPENSTATUS:
begin
LImc := ImmGetContext(WindowHandle);
GetObject(Font.Handle, SizeOf(TLogFont), @LLogFont);
ImmSetCompositionFont(LImc, @LLogFont);
ImmReleaseContext(WindowHandle, LImc);
end;
end;
inherited;
end;
procedure TCustomBCEditor.WMMouseHWheel(var AMessage: TWMMouseWheel);
begin
if (esScrolling in FState) then
ProcessClient(cjMouseDown, 0, nil, FClientRect, mbMiddle, [], FScrollingPoint);
if (AMessage.WheelDelta < 0) then
ScrollTo(FTextPos.X - FHorzScrollBarDivider * FSpaceWidth, FTextPos.Y)
else if (AMessage.WheelDelta > 0) then
ScrollTo(FTextPos.X + FHorzScrollBarDivider * FSpaceWidth, FTextPos.Y);
AMessage.Result := 1;
end;
procedure TCustomBCEditor.WMNCPaint(var AMessage: TWMNCPaint);
var
LRect: TRect;
LRgn: HRGN;
begin
if (StyleServices.Enabled
and (GetWindowLong(WindowHandle, GWL_EXSTYLE) and WS_EX_CLIENTEDGE <> 0)) then
begin
GetWindowRect(WindowHandle, LRect);
InflateRect(LRect, -GetSystemMetrics(SM_CXEDGE), -GetSystemMetrics(SM_CYEDGE));
LRgn := CreateRectRgnIndirect(LRect);
DefWindowProc(WindowHandle, AMessage.Msg, WPARAM(LRgn), 0);
DeleteObject(LRgn);
end
else
DefaultHandler(AMessage);
if (StyleServices.Enabled) then
StyleServices.PaintBorder(Self, False);
end;
procedure TCustomBCEditor.WMKillFocus(var AMessage: TWMKillFocus);
begin
if (Assigned(FHintWindow)) then
FreeAndNil(FHintWindow);
inherited;
NotifyParent(EN_KILLFOCUS);
if (not Assigned(FCompletionProposalPopup)) then
UpdateCaret();
if (HideSelection and not FLines.SelArea.IsEmpty()) then
InvalidateText();
end;
procedure TCustomBCEditor.WMPaint(var AMessage: TWMPaint);
var
LPaintStruct: TPaintStruct;
LPaintVar: TPaintVar;
begin
if (esTextUpdated in FState) then
begin
NotifyParent(EN_UPDATE);
Exclude(FState, esTextUpdated);
end;
BeginPaint(WindowHandle, LPaintStruct);
try
if (not DoubleBuffered) then
PaintTo(LPaintStruct.hdc, LPaintStruct.rcPaint)
else
begin
if (not Assigned(FDoubleBufferBitmap)) then
begin
Canvas.Handle; // Allocate Handle
Perform(CM_DOUBLEBUFFEREDCHANGED, 0, 0);
end;
if (esDoubleBufferInvalid in FState) then
begin
PaintTo(FDoubleBufferBitmap.Canvas.Handle, FClientRect, False);
Exclude(FState, esDoubleBufferInvalid);
FDoubleBufferUpdateRect := Rect(-1, -1, -1, -1);
end
else if (LPaintStruct.rcPaint.IntersectsWith(FDoubleBufferUpdateRect)) then
begin
PaintTo(FDoubleBufferBitmap.Canvas.Handle, FDoubleBufferUpdateRect, False);
FDoubleBufferUpdateRect := Rect(-1, -1, -1, -1);
end;
if (FSyncEditButtonRect.IsEmpty() and FScrollingRect.IsEmpty()) then
BitBlt(LPaintStruct.hdc,
LPaintStruct.rcPaint.Left, LPaintStruct.rcPaint.Top, LPaintStruct.rcPaint.Width, LPaintStruct.rcPaint.Height,
FDoubleBufferBitmap.Canvas.Handle,
LPaintStruct.rcPaint.Left, LPaintStruct.rcPaint.Top,
SRCCOPY)
else
begin
BitBlt(FDoubleBufferOverlayBitmap.Canvas.Handle,
LPaintStruct.rcPaint.Left, LPaintStruct.rcPaint.Top, LPaintStruct.rcPaint.Width, LPaintStruct.rcPaint.Height,
FDoubleBufferBitmap.Canvas.Handle,
LPaintStruct.rcPaint.Left, LPaintStruct.rcPaint.Top,
SRCCOPY);
FillChar(LPaintVar, SizeOf(LPaintVar), 0);
LPaintVar.Graphics := TGPGraphics.Create(FDoubleBufferOverlayBitmap.Canvas.Handle);
ProcessClient(cjPaintOverlays,
FDoubleBufferOverlayBitmap.Canvas.Handle, @LPaintVar, FSyncEditButtonRect,
mbLeft, [], Point(-1, -1), True);
ProcessClient(cjPaintOverlays,
FDoubleBufferOverlayBitmap.Canvas.Handle, @LPaintVar, FScrollingRect,
mbLeft, [], Point(-1, -1), True);
LPaintVar.Graphics.Free();
BitBlt(LPaintStruct.hdc,
LPaintStruct.rcPaint.Left, LPaintStruct.rcPaint.Top, LPaintStruct.rcPaint.Width, LPaintStruct.rcPaint.Height,
FDoubleBufferOverlayBitmap.Canvas.Handle,
LPaintStruct.rcPaint.Left, LPaintStruct.rcPaint.Top,
SRCCOPY);
end;
end;
finally
EndPaint(WindowHandle, LPaintStruct);
end;
if (FState * [esScrollBarsInvalid, esSizeChanged] <> []) then
UpdateScrollBars();
if ((FState * [esCaretInvalid] <> [])
and ((FRows.Count > 0) or not (esSizeChanged in FState))) then
UpdateCaret();
if (FLeftMargin.CodeFolding.Visible
and (esCodeFoldingInvalid in FState)) then
SetTimer(WindowHandle, tiCodeFolding, FLeftMargin.CodeFolding.DelayInterval, nil);
end;
procedure TCustomBCEditor.WMPaste(var AMessage: TWMPaste);
begin
if (FReadOnly or not IsClipboardFormatAvailable(CF_UNICODETEXT)) then
AMessage.Result := LRESULT(FALSE)
else
begin
PasteFromClipboard();
AMessage.Result := LRESULT(TRUE);
end;
end;
procedure TCustomBCEditor.WMPrint(var AMessage: TWMPrint);
begin
if (AMessage.Flags and PRF_CLIENT <> 0) then
PaintTo(AMessage.DC, FClientRect);
end;
procedure TCustomBCEditor.WMSetCursor(var AMessage: TWMSetCursor);
var
LCursorPoint: TPoint;
begin
if ((AMessage.CursorWnd = WindowHandle)
and (AMessage.HitTest = HTCLIENT)
and (FLineHeight > 0)
and not (csDesigning in ComponentState)) then
begin
GetCursorPos(LCursorPoint);
LCursorPoint := ScreenToClient(LCursorPoint);
ProcessClient(cjMouseMove, 0, nil, FClientRect, mbLeft, [], LCursorPoint);
AMessage.Result := LRESULT(TRUE);
end
else
inherited;
end;
procedure TCustomBCEditor.WMSetFocus(var AMessage: TWMSetFocus);
begin
inherited;
NotifyParent(EN_SETFOCUS);
UpdateCaret();
if (HideSelection and not FLines.SelArea.IsEmpty()) then
InvalidateText();
if (Assigned(FCompletionProposalPopup)) then
PostMessage(WindowHandle, UM_FREE_COMPLETIONPROPOSALPOPUP, 0, 0);
end;
procedure TCustomBCEditor.WMSettingChange(var AMessage: TWMSettingChange);
begin
case (AMessage.Flag) of
// This didn't work on my end. :-(
SPI_SETDOUBLECLICKTIME:
FDoubleClickTime := GetDoubleClickTime();
SPI_GETWHEELSCROLLCHARS:
if (not SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, @FWheelScrollChars, 0)) then
FWheelScrollChars := 3;
end;
end;
procedure TCustomBCEditor.WMSetText(var AMessage: TWMSetText);
begin
if (FReadOnly) then
AMessage.Result := LPARAM(FALSE)
else
begin
AMessage.Result := LPARAM(TRUE);
Text := StrPas(AMessage.Text);
end;
end;
procedure TCustomBCEditor.WMStyleChanged(var AMessage: TWMStyleChanged);
begin
inherited;
if (AMessage.StyleType = WPARAM(GWL_STYLE)) then
begin
SetReadOnly(AMessage.StyleStruct^.styleNew and ES_READONLY <> 0);
SetWantReturns(AMessage.StyleStruct^.styleNew and ES_WANTRETURN <> 0);
SetHideSelection(AMessage.StyleStruct^.styleNew and ES_NOHIDESEL = 0);
if (not Focused() and not FLines.SelArea.IsEmpty()) then
InvalidateText();
end
else if (AMessage.StyleType = WPARAM(GWL_EXSTYLE)) then
begin
FNoParentNotify := AMessage.StyleStruct^.styleNew and WS_EX_NOPARENTNOTIFY <> 0;
if (AMessage.StyleStruct^.styleNew and WS_EX_ACCEPTFILES = 0) then
SetOptions(FOptions - [eoDropFiles])
else
SetOptions(FOptions + [eoDropFiles]);
end;
end;
procedure TCustomBCEditor.WMSysChar(var AMessage: TMessage);
begin
if (AMessage.LParam and (1 shl 29) <> 0) then
// Do nothing to prevent a beep sound
else
inherited;
end;
procedure TCustomBCEditor.WMTimer(var Msg: TWMTimer);
var
LMsg: TMsg;
begin
case (Msg.TimerID) of
tiCodeFolding:
begin
KillTimer(WindowHandle, Msg.TimerID);
ScanCodeFolding();
end;
tiShowHint:
begin
KillTimer(WindowHandle, Msg.TimerID);
if (ShowHint
and not (esScrolling in FState)) then
ProcessClient(cjHint, 0, nil, FClientRect, mbLeft, [], FCursorPoint);
end;
tiScrolling:
ProcessClient(cjScrolling, 0, nil, FTextRect, mbLeft, [], FCursorPoint);
tiScroll:
ProcessClient(cjMouseMove, 0, nil, FTextRect, mbLeft, [], FCursorPoint);
tiIdle:
if (not PeekMessage(LMsg, 0, 0, 0, PM_NOREMOVE)) then
begin
KillTimer(WindowHandle, Msg.TimerID);
Idle();
end;
tiCompletionProposal:
begin
KillTimer(WindowHandle, Msg.TimerID);
DoCompletionProposal();
end;
end;
end;
procedure TCustomBCEditor.WMUndo(var AMessage: TWMUndo);
begin
FLines.Undo();
end;
procedure TCustomBCEditor.WMVScroll(var AMessage: TWMScroll);
var
LLine: Integer;
LCursorPos: TPoint;
LHint: string;
LRect: TRect;
begin
case (AMessage.ScrollCode) of
SB_LINEUP:
ScrollTo(FTextPos.X, FTextPos.Y - 1 * FLineHeight);
SB_LINEDOWN:
ScrollTo(FTextPos.X, FTextPos.Y + 1 * FLineHeight);
SB_PAGEUP:
ScrollTo(FTextPos.X, FTextPos.Y - FUsableRows * FLineHeight);
SB_PAGEDOWN:
ScrollTo(FTextPos.X, FTextPos.Y + FUsableRows * FLineHeight);
SB_TOP:
ScrollTo(FTextPos.X, 0 * FLineHeight);
SB_BOTTOM:
ScrollTo(FTextPos.X, (FRows.Count - 1) * FLineHeight);
SB_THUMBPOSITION,
SB_THUMBTRACK:
begin
ScrollTo(FTextPos.X, AMessage.Pos * FVertScrollBarDivider * FLineHeight);
if (FLeftMargin.LineNumbers.Visible and ShowHint) then
begin
if (not Assigned(FHintWindow)) then
begin
FHintWindow := THintWindow.Create(Self);
FHintWindow.Color := clInfoBk;
end;
if (FTopRow < FRows.Count) then
LLine := FRows.Items[FTopRow].Line + FLeftMargin.LineNumbers.Offset
else
LLine := FTopRow - FRows.Count + FLines.Count + FLeftMargin.LineNumbers.Offset;
LHint := Format(SBCEditorScrollInfo, [LLine]);
LRect := FHintWindow.CalcHintRect(FClientRect.Width, LHint, nil);
LRect.Offset(ClientToScreen(Point(FClientRect.Width - LRect.Width, 0)));
if (GetCursorPos(LCursorPos)) then
LRect.Offset(0,
Min(FClientRect.Height - GetSystemMetrics(SM_CYVSCROLL), Max(GetSystemMetrics(SM_CYVSCROLL), ScreenToClient(LCursorPos).Y))
- LRect.Height shr 1);
FHintWindow.ActivateHint(LRect, LHint);
end;
end;
SB_ENDSCROLL:
if (Assigned(FHintWindow)) then
FreeAndNil(FHintWindow);
end;
AMessage.Result := 0;
end;
procedure TCustomBCEditor.WndProc(var AMessage: TMessage);
begin
case (AMessage.Msg) of
WM_LBUTTONDOWN,
WM_LBUTTONDBLCLK:
if (not (csDesigning in ComponentState) and not Focused()) then
begin
Windows.SetFocus(WindowHandle);
if (not Focused) then Exit;
end;
WM_SETTEXT,
WM_GETTEXT,
WM_GETTEXTLENGTH:
{ Handle direct WndProc calls that could happen through VCL-methods like Perform }
if (HandleAllocated) then
if (FWindowProducedMessage) then
FWindowProducedMessage := False
else
begin
FWindowProducedMessage := True;
with AMessage do
Result := SendMessageA(WindowHandle, Msg, wParam, LParam);
Exit;
end;
end;
inherited;
end;
function TCustomBCEditor.WordAtCursor(): string;
begin
Result := GetWordAt(CaretPos);
end;
function TCustomBCEditor.WordBegin(const ALinesPosition: TBCEditorLinesPosition): TBCEditorLinesPosition;
begin
Result := ALinesPosition;
while ((Result.Char - 1 >= 0) and not IsWordBreakChar(FLines.Items[Result.Line].Text[1 + Result.Char - 1])) do
Dec(Result.Char);
end;
function TCustomBCEditor.WordEnd(): TBCEditorLinesPosition;
begin
Result := WordEnd(FLines.CaretPosition);
end;
function TCustomBCEditor.WordEnd(const ALinesPosition: TBCEditorLinesPosition): TBCEditorLinesPosition;
begin
Result := ALinesPosition;
while ((Result.Char + 1 < Length(FLines.Items[Result.Line].Text)) and not IsWordBreakChar(FLines.Items[Result.Line].Text[1 + Result.Char + 1])) do
Inc(Result.Char);
end;
initialization
GImmEnabled := BOOL(GetSystemMetrics(SM_DBCSENABLED));
GLineWidth := Round(Screen.PixelsPerInch / USER_DEFAULT_SCREEN_DPI);
GPadding := Round(Screen.PixelsPerInch / USER_DEFAULT_SCREEN_DPI);
OleCheck(OleInitialize(nil));
finalization
OleUninitialize();
end.
|
unit RijndaelECB;
{ Copyright (c) 2001, Tom Verhoeff (TUE) }
{ Version 1.0 (July 2001) }
{ FreePascal library for use of Rijndael in Electronic Codebook Mode }
interface
const
HexStrLen = 32;
BlockLen = 16;
type
HexStr = String [ HexStrLen ]; { hex digits only: ['0'..'9', 'A'..'F'] }
Block = array [ 0 .. BlockLen-1 ] of Byte;
procedure HexStrToBlock ( const hs: HexStr; var b: Block );
procedure BlockToHexStr ( const b: Block; var hs: HexStr );
procedure Encrypt ( const p, k: Block; var c: Block );
procedure Decrypt ( const c, k: Block; var p: Block );
implementation
uses Rijndael;
const
HexBits = 4; { # bits per hex }
HexBase = 1 SHL HexBits;
type
Hex = 0 .. HexBase-1;
function CharToHex ( c: Char ): Hex;
{ pre: IsHexChar(c) }
{ impl. note: raises range check error if not IsHexChar(c) }
begin
if ( '0' <= c ) and ( c <= '9' ) then { c in ['0'..'9'] }
CharToHex := ord ( c ) - ord ( '0' )
else if ( 'A' <= c ) and ( c <= 'F' ) then { c in ['A'..'F'] }
CharToHex := ord ( c ) - ord ( 'A' ) + 10
else if ( 'a' <= c ) and ( c <= 'f' ) then { c in ['a'..'f'] }
CharToHex := ord ( c ) - ord ( 'a' ) + 10
else begin
writeln ( '''', c, ''' is not a hexadecimal digit' )
; Halt ( 201 ) { range check error }
end { else }
end; { CharToHex }
function HexToChar ( h: Hex ): Char;
begin
if h < 10 then
HexToChar := chr ( ord ( '0' ) + h )
else { 10 <= h < 16 }
HexToChar := chr ( ord ( 'A' ) + h - 10 )
end; { HexToChar }
procedure HexStrToBlock ( const hs: HexStr; var b: Block );
{ impl. note: right-pad with zeroes }
var
i: Integer; { to traverse b }
j: Integer; { to traverse hs }
h: Byte;
begin
for i := 0 to BlockLen - 1 do begin
b [ i ] := 0
end { for i }
; for j := 1 to Length ( hs ) do begin
h := CharToHex ( hs[j] )
; if odd ( j ) then begin { most significant nibble }
h := h SHL HexBits
end { if }
; b [ (j-1) div 2 ] := b [ (j-1) div 2 ] OR h
end { for j }
end; { HexStrToBlock }
procedure BlockToHexStr ( const b: Block; var hs: HexStr );
var
i: Integer; { to traverse b }
begin
hs := ' '
; for i := 0 to BlockLen - 1 do begin
hs [ 2*i+1 ] := HexToChar ( b[i] SHR HexBits )
; hs [ 2*i+2 ] := HexToChar ( b[i] AND (HexBase-1) )
end { for i }
end; { BlockToHexStr }
procedure Encrypt ( const p, k: Block; var c: Block );
var
ek: ExpandedKey;
nr: LongInt; { number of rounds }
begin
nr := Rijndael.KeySetupEnc ( ek, k, 128 )
; Rijndael.Encrypt ( ek, nr, p, 0, c, 0 )
end; { Encrypt }
procedure Decrypt ( const c, k: Block; var p: Block );
var
ek: ExpandedKey;
nr: LongInt; { number of rounds }
begin
nr := Rijndael.KeySetupDec ( ek, k, 128 )
; Rijndael.Decrypt ( ek, nr, c, 0, p, 0 )
end; { Decrypt }
end { unit RijndaelECB }.
|
unit Parsers.SRC;
interface
uses
Parsers.Abstract, SysUtils, GsDocument, Classes, Generics.Collections, Parsers.Excel.Tools;
type
TSRCRow = class
private
FValue: string;
FArray: TArray<string>;
function GetValue: string;
function GetParam(index: integer): string;
function GetParamCount: integer;
public
constructor Create(AStr: string);
destructor Destroy; override;
property Value: string read GetValue;
property Params[Index: integer]: string read GetParam;
property ParamsCount: integer read GetParamCount;
end;
TSRCRowClass = class of TSRCRow;
TAbstractSRCParser = class(TInterfacedObject, IParser<TSRCRow>)
private
FList: TObjectList<TSRCRow>;
FRowClass: TSRCRowClass;
FDocument: TGsDocument;
function GetRow(index: integer): TSRCRow;
function GetCount: integer;
protected
procedure ParseData(Data: TSRCRow); virtual; abstract;
procedure InitDocument(Document: TGsDocument); virtual; abstract;
public
constructor Create(ARowClass: TSRCRowClass);
procedure LoadFromFile(AFileName: string);
procedure Parse(OutFile: string);
destructor Destroy; override;
property Rows[Index: integer]: TSRCRow read GetRow; default;
property RowsCount: integer read GetCount;
property Document: TGsDocument read FDocument;
end;
TPriceSRCRow = class(TSRCRow)
public
function IsChapter: Boolean;
function GetChapterCaption: string;
function IsPriceRow: Boolean;
function GetCode: string;
function GetCaption: string;
function GetMeasure: string;
function GetPriceCE: Real;
function GetPriceCT: Real;
function GetCode2017: string;
function GetCargoClass: integer;
end;
TPriceSRCParser = class(TAbstractSRCParser)
private
FChapter: TGsAbstractContainer;
protected
procedure ParseData(Data: TSRCRow); override;
procedure InitDocument(Document: TGsDocument); override;
public
constructor Create; reintroduce;
end;
implementation
{ TSRCParser }
constructor TAbstractSRCParser.Create(ARowClass: TSRCRowClass);
begin
inherited Create;
FList := TObjectList<TSRCRow>.Create;
FRowClass := ARowClass;
FDocument := TGsDocument.Create;
end;
destructor TAbstractSRCParser.Destroy;
begin
FDocument.Free;
FList.Free;
inherited Destroy;
end;
function TAbstractSRCParser.GetCount: integer;
begin
Result := FList.Count;
end;
function TAbstractSRCParser.GetRow(index: integer): TSRCRow;
begin
Result := TSRCRow(FList[Index]);
end;
procedure TAbstractSRCParser.LoadFromFile(AFileName: string);
var
F: TextFile;
S: string;
Row: TSRCRow;
begin
AssignFile(F, AFileName);
try
Reset(F);
while not Eof(F) do
begin
ReadLn(F, S);
Row := FRowClass.Create(S);
FList.Add(Row);
end;
finally
Close(F);
end;
end;
procedure TAbstractSRCParser.Parse(OutFile: string);
var
I: integer;
begin
InitDocument(FDocument);
for I := 0 to FList.Count - 1 do
begin
try
ParseData(FList[I]);
except
on E: Exception do
raise Exception.Create('Ошибка при обработке строки: ' + FList[I].Value + sLineBreak + E.Message);
end;
end;
FDocument.SaveToFile(OutFile);
end;
{ TSRCRow }
constructor TSRCRow.Create(AStr: string);
begin
inherited Create;
FValue := AStr;
FArray := FValue.Split(['@']);
end;
destructor TSRCRow.Destroy;
begin
SetLength(FArray, 0);
FValue := '';
inherited;
end;
function TSRCRow.GetParam(index: integer): string;
begin
if (Index >= 0) and (Index < Length(FArray)) then
Result := FArray[Index]
else
raise Exception.Create('Такого параметра не существует');
end;
function TSRCRow.GetParamCount: integer;
begin
Result := Length(FArray);
end;
function TSRCRow.GetValue: string;
begin
Result := FValue;
end;
{ TPriceSRCParser }
constructor TPriceSRCParser.Create;
begin
inherited Create(TPriceSRCRow);
end;
procedure TPriceSRCParser.InitDocument(Document: TGsDocument);
begin
Document.DocumentType := dtPrice;
FChapter := Document.Materials;
end;
procedure TPriceSRCParser.ParseData(Data: TSRCRow);
var
PriceRow: TPriceSRCRow;
Elem: TGsPriceElement;
begin
PriceRow := TPriceSRCRow(Data);
if PriceRow.IsChapter then
begin
if AnsiSameText('Сметные расценки на эксплуатацию строительных машин, механизмов и средств малой механизации',
PriceRow.GetChapterCaption) then
FChapter := Document.Mashines
else
if AnsiSameText('Тарифные ставки оплаты труда в строительстве', PriceRow.GetChapterCaption) then
FChapter := Document.Workers
else
if AnsiSameText('Территориальный сборник сметных цен на перевозку грузов для строительства', PriceRow.GetChapterCaption) then
FChapter := Document.Mashines
else
begin
FChapter := TGsDocument.CreateChapterByPriority(FChapter, TParserTools.GetChapterPriority(PriceRow.GetChapterCaption));
FChapter.Caption := PriceRow.GetChapterCaption;
end;
end
else if PriceRow.IsPriceRow then
begin
Elem := TGsPriceElement.Create(Document);
FChapter.Add(Elem);
Elem.Code := PriceRow.GetCode;
Elem.Caption := PriceRow.GetCaption;
Elem.Measure := PriceRow.GetMeasure;
Elem.PriceCE := PriceRow.GetPriceCE;
Elem.PriceCT := PriceRow.GetPriceCT;
Elem.Attributes[Ord(paComment)] := PriceRow.GetCode2017;
if PriceRow.GetCargoClass <> -1 then
Elem.Attributes[Ord(paCargo)] := PriceRow.GetCargoClass;
end;
end;
{ TPriceSRCRow }
function TPriceSRCRow.GetCaption: string;
begin
Result := Params[3];
end;
function TPriceSRCRow.GetCargoClass: integer;
begin
if AnsiSameText(Params[5], 'I') then
Result := 1
else
if AnsiSameText(Params[5], 'II') then
Result := 2
else
if AnsiSameText(Params[5], 'III') then
Result := 3
else
if AnsiSameText(Params[5], 'IV') then
Result := 4
else
Result := -1;
end;
function TPriceSRCRow.GetChapterCaption: string;
begin
Result := Params[1];
end;
function TPriceSRCRow.GetCode: string;
begin
Result := Params[2];
end;
function TPriceSRCRow.GetCode2017: string;
begin
Result := Params[8];
end;
function TPriceSRCRow.GetMeasure: string;
begin
Result := Params[4];
end;
function TPriceSRCRow.GetPriceCE: Real;
begin
Result := TParserTools.ConvertToFloat(Params[7]);
end;
function TPriceSRCRow.GetPriceCT: Real;
begin
Result := TParserTools.ConvertToFloat(Params[6]);
end;
function TPriceSRCRow.IsChapter: Boolean;
begin
Result := AnsiSameText('L1:', Params[0]) or AnsiSameText('L2:', Params[0]) or AnsiSameText('L3:', Params[0]);
end;
function TPriceSRCRow.IsPriceRow: Boolean;
begin
Result := AnsiSameText('L4:', Params[0])
end;
end.
|
unit ConcreateFactoryMethod;
interface
uses
FactoryMethod;
type
TConcreteProductCreator = class(TAbstractProductCreator)
public
function CreateProduct(AProductID: integer): IProduct; override;
end;
// The function that creates the products is virtual and can be overridden at least from
implementation
type
TAdvancedProductX = class(TInterfacedObject, IProduct)
// definition not important for illustration
end;
TAdvancedProductY = class(TProductA)
// definition not important for illustration
end;
function TConcreteProductCreator.CreateProduct(AProductID: integer): IProduct;
begin
Case AProductID of
1: result := TAdvancedProductX.Create;
2: result := TAdvancedProductY.Create;
else
result := inherited;
end;
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, XPMan, Spin, ComCtrls, FDOTable, ClipBrd, ShowMsgs,
IniFiles, OSUtils, Strings;
type
TMainFrm = class(TForm)
CancelBtn: TButton;
OKBtn: TButton;
GroupBox2: TGroupBox;
Label3: TLabel;
TypeBox: TComboBox;
Label2: TLabel;
CommitSpn: TSpinEdit;
TableEdt: TEdit;
Label4: TLabel;
UpdateFieldEdt: TEdit;
Label5: TLabel;
CommitChk: TCheckBox;
Label6: TLabel;
SQLBox: TMemo;
ProgressBar: TProgressBar;
Label1: TLabel;
RecordsLbl: TLabel;
NullValueEdt: TEdit;
Label7: TLabel;
PasteClipboardBtn: TButton;
CopyClipboardBtn: TButton;
procedure CancelBtnClick(Sender: TObject);
procedure OKBtnClick(Sender: TObject);
procedure TypeBoxChange(Sender: TObject);
procedure TableEdtChange(Sender: TObject);
procedure UpdateFieldEdtChange(Sender: TObject);
procedure NullValueEdtChange(Sender: TObject);
procedure CommitChkClick(Sender: TObject);
procedure CommitSpnChange(Sender: TObject);
procedure PasteClipboardBtnClick(Sender: TObject);
procedure CopyClipboardBtnClick(Sender: TObject);
private
FTable: TFDOTable;
FConfig: TIniFile;
FUser: String;
function ConfigRead(const Ident: String; const Default: String = ''): String;
function ConfigReadInt(const Ident: String; const Default: Integer = 0): Integer;
procedure ConfigWrite(const Ident, Value: String);
procedure SetControlsEnabled(const Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ControlsEnabled: Boolean write SetControlsEnabled;
end;
var
MainFrm: TMainFrm;
implementation
{$R *.dfm}
procedure TMainFrm.PasteClipboardBtnClick(Sender: TObject);
begin
SQLBox.Text := Clipboard.AsText;
FTable.Document := SQLBox.Text;
RecordsLbl.Caption := IntToStr(FTable.RecordCount);
end;
procedure TMainFrm.CommitChkClick(Sender: TObject);
begin
ConfigWrite('InsertCommit', BoolToStr(CommitChk.Checked));
end;
procedure TMainFrm.CommitSpnChange(Sender: TObject);
begin
ConfigWrite('CommitEveryX', IntToStr(CommitSpn.Value));
end;
function TMainFrm.ConfigRead(const Ident, Default: String): String;
begin
if FConfig.SectionExists(FUser) then begin
Result := FConfig.ReadString(FUser, Ident, Default);
end
else Result := Default;
end;
function TMainFrm.ConfigReadInt(const Ident: String;
const Default: Integer): Integer;
begin
if not TryStrToInt(ConfigRead(Ident, ''), Result) then
Result := Default;
end;
procedure TMainFrm.ConfigWrite(const Ident, Value: String);
begin
FConfig.WriteString(FUser, Ident, StringReplace(Value,'''','''''',[rfReplaceAll]));
end;
procedure TMainFrm.CopyClipboardBtnClick(Sender: TObject);
begin
Clipboard.AsText := SQLBox.Text;
ShowInfo('Text is copied to Clipboard.');
end;
constructor TMainFrm.Create(AOwner: TComponent);
begin
inherited;
FUser := GetUserName;
FTable := TFDOTable.Create;
FConfig := TIniFile.Create(ExtractFilePath(ParamStr(0))+'Config.ini');
TypeBox.ItemIndex := TypeBox.Items.IndexOf(ConfigRead('StatementType', TypeBox.Text));
if TypeBox.ItemIndex = -1 then
TypeBox.ItemIndex := TypeBox.Items.IndexOf('INSERT');
TableEdt.Text := ConfigRead('Target', TableEdt.Text);
UpdateFieldEdt.Text := ConfigRead('UpdateField', UpdateFieldEdt.Text);
NullValueEdt.Text := ConfigRead('NullValue', NullValueEdt.Text);
CommitChk.Checked := StrToBool(ConfigRead('InsertCommit', BoolToStr(CommitChk.Checked)));
CommitSpn.Value := ConfigReadInt('CommitEveryX', CommitSpn.Value);
TypeBoxChange(nil);
end;
destructor TMainFrm.Destroy;
begin
FTable.Free;
inherited;
end;
procedure TMainFrm.NullValueEdtChange(Sender: TObject);
begin
ConfigWrite('NullValue', NullValueEdt.Text);
end;
procedure TMainFrm.OKBtnClick(Sender: TObject);
var
Text: String;
procedure Write(const S: String);
begin
Text := Text + S;
end;
function GetField(const S: String): String;
var
Tmp: String;
begin
Result := S;
Tmp := LeaveChars(Result, ['a'..'z','A'..'Z','0'..'9','_']);
if CompareText(Result, Tmp) <> 0 then begin
Result := '['+Result+']';
end;
end;
function GetValue(const S: String): String;
begin
if S = '' then Result := NullValueEdt.Text
else begin
Result := S;
Result := StringReplace(Result, '‘', '''', [rfReplaceAll]);
Result := StringReplace(Result, '’', '''', [rfReplaceAll]);
Result := ''''+StringReplace(Result, '''', '''''', [rfReplaceAll])+'''';
end;
end;
var
I, C: Integer;
begin
ControlsEnabled := False;
try
Text := '';
ProgressBar.Max := FTable.RecordCount;
FTable.First;
repeat
case TypeBox.ItemIndex of
0: begin
Write('insert into '+TableEdt.Text+' (');
for I := 0 to FTable.FieldList.Count-1 do begin
if I > 0 then Write(',');
Write(GetField(FTable.FieldList[I]));
end;
Write(') values (');
for I := 0 to FTable.FieldList.Count-1 do begin
if I > 0 then Write(',');
Write(GetValue(FTable.Fields[I].AsString));
end;
Write(');'#13#10);
end;
1: begin
Write('update '+TableEdt.Text+' set ');
C := 0;
for I := 0 to FTable.FieldList.Count-1 do begin
if SameText(FTable.FieldList[I],UpdateFieldEdt.Text) = False then begin
if C > 0 then Write(', ');
Write(GetField(FTable.FieldList[I])+' = '+GetValue(FTable.Fields[I].AsString));
Inc(C);
end;
end;
Write(
' where '+GetField(UpdateFieldEdt.Text)+' = '+
GetValue(FTable.FieldByName(UpdateFieldEdt.Text).AsString)+
';'#13#10);
end;
end;
if CommitChk.Checked and (CommitSpn.Value > 0) then begin
if (FTable.RecNo + 1) mod CommitSpn.Value = 0 then
Write(#13#10'commit work;'#13#10#13#10);
end;
FTable.Next;
ProgressBar.Position := FTable.RecNo + 1;
ProgressBar.Update;
until FTable.EOF;
if CommitChk.Checked then begin
Write(#13#10'commit work;');
end;
SQLBox.Text := Text;
ProgressBar.Position := 0;
finally
ControlsEnabled := True;
end;
end;
procedure TMainFrm.SetControlsEnabled(const Value: Boolean);
begin
OKBtn.Enabled := Value;
CancelBtn.Enabled := Value;
TypeBox.Enabled := Value;
CommitSpn.Enabled := Value;
end;
procedure TMainFrm.TableEdtChange(Sender: TObject);
begin
ConfigWrite('Target', TableEdt.Text);
end;
procedure TMainFrm.TypeBoxChange(Sender: TObject);
begin
UpdateFieldEdt.Enabled := (TypeBox.Text <> 'INSERT');
end;
procedure TMainFrm.UpdateFieldEdtChange(Sender: TObject);
begin
ConfigWrite('UpdateField', UpdateFieldEdt.Text);
end;
procedure TMainFrm.CancelBtnClick(Sender: TObject);
begin
Close;
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_Log
* Implements portable logging utilities
***********************************************************************************************************************
}
{$IFDEF OXYGENE}
namespace TERRA;
{$ELSE}
Unit TERRA_Log;
{$I terra.inc}
{$ENDIF}
{$IFDEF WINDOWS}{$UNDEF ANDROID}{$ENDIF}
Interface
{$IFDEF IPHONE}
{$UNDEF USE_LOGFILE}
{$ELSE}
{$DEFINE USE_LOGFILE}
{$ENDIF}
{$IFDEF WINDOWS}
{-$DEFINE CONSOLEWINDOW}
{$ENDIF}
{$IFDEF LINUX}
{.$DEFINE CONSOLEWINDOW}
{$ENDIF}
{$IFDEF OSX}
{.$DEFINE USE_SYSLOG}
{$DEFINE CONSOLEWINDOW}
{$ENDIF}
Uses TERRA_FileStream, TERRA_String
{$IFDEF USE_SYSLOG},systemlog{$ENDIF}
{$IFDEF WINDOWS},Windows{$ENDIF}
;
Const
logDebug = 0;
logError = 1;
logWarning = 2;
logConsole = 3;
logFilterCount = 4;
Type
LogFilterHandler = Procedure(ModuleName, Description:TERRAString);
{$IFDEF OXYGENE}
LogEntry = Class
{$ELSE}
LogEntry = Record
{$ENDIF}
ModuleName:TERRAString;
Description:TERRAString;
End;
LogFilter = Record
FilterType:Integer;
Modules:TERRAString;
Handler:LogFilterHandler;
End;
Procedure Log(LogType:Integer; Const ModuleName, Description:TERRAString);
Procedure AddLogFilter(LogType:Integer; Const Modules:TERRAString; Handler:LogFilterHandler);
Var
LoggingEnabled:Boolean = False;
LogFileName:TERRAString;
ForceLogFlush:Boolean;
Implementation
Uses TERRA_Utils, TERRA_OS, TERRA_Application, TERRA_FileUtils;
{$IFDEF ANDROID}
Const
ANDROID_LOG_UNKNOWN=0;
ANDROID_LOG_DEFAULT=1;
ANDROID_LOG_VERBOSE=2;
ANDROID_LOG_DEBUG=3;
ANDROID_LOG_INFO=4;
ANDROID_LOG_WARN=5;
ANDROID_LOG_ERROR=6;
ANDROID_LOG_FATAL=7;
ANDROID_LOG_SILENT=8;
Function __android_log_write(prio:Integer; tag,text:PAnsiChar):Integer; cdecl; external 'liblog.so' name '__android_log_write';
//function LOGI(prio:longint;tag,text:PAnsiChar):longint; cdecl; varargs; external 'liblog.so' name '__android_log_print';
{$ENDIF}
Var
_LogShutdown:Boolean;
{$IFDEF USE_LOGFILE}
{$IFNDEF USE_SYSLOG}
_LogFile:FileStream;
{$ENDIF}
{$ENDIF}
_LogActive:Boolean;
_LogStarted:Boolean;
_Filters:Array Of LogFilter;
_FilterCount:Integer;
{$IFDEF CONSOLEWINDOW}
_LogHasConsole:Boolean;
{$ENDIF}
_LastWrite:Cardinal;
Function LogFormatStr(LogType:Integer; ModuleName, Description:TERRAString):TERRAString;
Begin
If ModuleName<>'' Then
Begin
Description := '['+ModuleName+'] '+Description;
End;
Case LogType Of
logDebug: Description := 'Debug: ' + Description;
logWarning: Description := 'Warning: ' + Description;
logError: Description := 'Error: '+ Description;
End;
Result := Description;
End;
Procedure AddLogFilter(LogType:Integer; Const Modules:TERRAString; Handler:LogFilterHandler);
Begin
If (LogType<0) Or (LogType>=logFilterCount) Or (@Handler = Nil) Then
Exit;
Inc(_FilterCount);
SetLength(_Filters, _FilterCount);
_Filters[Pred(_FilterCount)].FilterType := LogType;
_Filters[Pred(_FilterCount)].Modules := StringLower(Modules);
_Filters[Pred(_FilterCount)].Handler := Handler;
End;
Procedure WriteToLog(Const S:TERRAString);
Var
T:Cardinal;
Begin
{$IFNDEF DISABLELOG}
{$IFDEF CONSOLEWINDOW}
WriteLn(S);
{$ENDIF}
T := Application.GetTime();
{$IFDEF USE_LOGFILE}
{$IFDEF USE_SYSLOG}
syslog(log_info, PAnsiChar(S), []);
{$ELSE}
If Assigned(_LogFile) Then
Begin
_LogFile.WriteLine(S);
If (ForceLogFlush) Or (T-_LastWrite>2000) Then
_LogFile.Flush();
End;
{$ENDIF}
_LastWrite := T;
{$ENDIF}
{$ENDIF}
End;
{$IFNDEF OXYGENE}
Procedure Log_Shutdown();
Begin
If _LogShutdown Then
Exit;
_LogShutdown := True;
{$IFNDEF DISABLELOG}
If (_LogStarted) Then
WriteToLog('End of log session.');
{$IFDEF CONSOLEWINDOW}
{$IFDEF WINDOWS}
If (_LogHasConsole) Then
Begin
FreeConsole();
_LogHasConsole := False;
End;
{$ENDIF}
{$ENDIF}
{$IFDEF USE_LOGFILE}
{$IFDEF USE_SYSLOG}
closelog();
{$ELSE}
ReleaseObject(_LogFile);
{$ENDIF}
{$ENDIF}
{$ENDIF}
End;
{$ENDIF}
Function Log_Ready():Boolean;
Var
CurrentTime:TERRATime;
Begin
If (_LogShutdown) Or (Not LoggingEnabled) Then
Begin
Result := False;
Exit;
End;
{$IFNDEF DISABLELOG}
If _LogStarted Then
Begin
Result := True;
Exit;
End;
{$IFNDEF PC}
If (Application.Instance = Nil) Or (Application.Instance.DocumentPath='') Then
Begin
Result := False;
Exit;
End;
LogFileName := Application.Instance.DocumentPath + PathSeparator+ 'terra.log';
{$ELSE}
LogFileName := GetFileName(ParamStr(0), True)+'.log';
{$IFDEF WINDOWS}
LogFileName := GetFilePath(ParamStr(0)) + LogFileName;
{$ENDIF}
{$ENDIF}
{$IFDEF USE_LOGFILE}
{$IFDEF USE_SYSLOG}
openlog('TERRA',LOG_NOWAIT,LOG_DEBUG);
{$ELSE}
_LogFile := FileStream.Create(LogFileName);
{$ENDIF}
CurrentTime := Application.GetCurrentTime();
WriteToLog('Log session started at '+TimeToString(CurrentTime, ':', ':', ''));
WriteToLog('Engine: TERRA '+VersionToString(EngineVersion){$IFDEF FULLDEBUG}+' [Debug mode]'{$ENDIF});
{$ENDIF}
_LogStarted := True;
Result := True;
{$ENDIF}
End;
{$IFNDEF OXYGENE}
{$I-}
{$ENDIF}
Procedure Log(LogType:Integer; Const ModuleName, Description:TERRAString);
Var
I:Integer;
S:TERRAString;
Begin
If _LogShutdown Then
Exit;
{$IFNDEF DISABLELOG}
//WriteLn(Module,':',Desc);
{$IFNDEF MOBILE}
If Not LoggingEnabled Then
Exit;
{$ENDIF}
{$IFDEF CONSOLEWINDOW}
{$IFDEF WINDOWS}
If (Not _LogHasConsole) Then
Begin
_LogHasConsole := True;
AllocConsole();
End;
{$ENDIF}
{$ENDIF}
If (LogType<0) Or (LogType>logFilterCount) Then
LogType := 0;
S := LogFormatStr(LogType, ModuleName, Description);
{$IFNDEF DISABLETHREADS}
S := CardinalToString(PtrUInt(GetCurrentThreadId())) + ': '+ S;
{$ENDIF}
{$IFDEF IPHONE}
iPhoneLog(PAnsiChar(S));
{$ENDIF}
{$IFDEF ANDROID}
__android_log_write(ANDROID_LOG_DEBUG, PAnsiChar(ModuleName), PAnsiChar(S));
{$ENDIF}
{$IFDEF MOBILE}
If Not LoggingEnabled Then
Exit;
{$ENDIF}
For I:=0 To Pred(_FilterCount) Do
If (_Filters[I].FilterType = LogType) And ((_Filters[I].Modules='') Or (StringContains(ModuleName, _Filters[I].Modules))) Then
Begin
_Filters[I].Handler(ModuleName, Description);
Exit;
End;
If (LogType = logConsole) Then
Begin
Application.Instance.LogToConsole(Description);
Exit;
End;
{$IFDEF IPHONE}
Exit;
{$ENDIF}
If (_LogActive) Then
Exit;
_LogActive := True;
If (Log_Ready()) Then
WriteToLog(S);
_LogActive := False;
{$ENDIF}
End;
Initialization
{$IFDEF DEBUG_LOG}
LoggingEnabled := True;
{$ELSE}
{$IFDEF PC}
LoggingEnabled := Application.GetOption('log') = '1';
{$ELSE}
{$IFDEF CRASH_REPORT}
LoggingEnabled := False;
{$ELSE}
LoggingEnabled := True;
{$ENDIF}
{$ENDIF}
{$ENDIF}
Finalization
Log_Shutdown();
End.
|
unit CommonTypesUnit;
interface
uses
System.Generics.Collections, SysUtils;
type
TIntegerArray = TArray<integer>;
TStringArray = TArray<String>;
T2DimensionalStringArray = array of array of String;
TStringPair = TPair<String,String>;
TArrayStringPair = TArray<TStringPair>;
TListStringPair = TList<TStringPair>;
TListString = TList<String>;
TClassArray = TArray<TClass>;
TSimpleString = class
private
FValue: String;
public
constructor Create(Value: String);
property Value: String read FValue;
end;
TSimpleInteger = class
private
FValue: integer;
public
constructor Create(Value: integer);
property Value: integer read FValue;
end;
function SortSimpleIntegerArray(Integers: TArray<TSimpleInteger>): TArray<TSimpleInteger>;
implementation
uses
Generics.Defaults, Math;
{ TSimpleString }
constructor TSimpleString.Create(Value: String);
begin
FValue := Value;
end;
{ TSimpleInteger }
constructor TSimpleInteger.Create(Value: integer);
begin
FValue := Value;
end;
function SortSimpleIntegerArray(Integers: TArray<TSimpleInteger>): TArray<TSimpleInteger>;
begin
SetLength(Result, Length(Integers));
if Length(Integers) = 0 then
Exit;
TArray.Copy<TSimpleInteger>(Integers, Result, Length(Integers));
TArray.Sort<TSimpleInteger>(Result, TComparer<TSimpleInteger>.Construct(
function (const Value1, Value2: TSimpleInteger): Integer
begin
Result := Math.CompareValue(Value1.FValue, Value2.FValue);
end));
end;
end.
|
unit IsometricMap;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
SpeedBmp, Threads, IsometricMapTypes;
type
TZoomLevel = 1..100; // Percent
type
TCanvasImage = TSpeedBitmap;
hfocus = integer;
type
TOnIsometricChange = procedure (Sender : TObject) of object;
TOnSelect = procedure (Sender : TObject; i, j : integer) of object;
type
TIsometricMap =
class(TCustomControl)
public
constructor Create(Owner : TComponent); override;
destructor Destroy; override;
private
fMapper : IIsometricMapper;
fZoomLevel : TZoomLevel;
fOrigin : TPoint;
fQuality : boolean;
fOnChange : TOnIsometricChange;
fOnSelect : TOnSelect;
procedure SetMapper(which : IIsometricMapper);
procedure SetZoomLevel(which : TZoomLevel);
procedure SetOrigin(which : TPoint);
procedure SetQuality(which : boolean);
published
property Mapper : IIsometricMapper read fMapper write SetMapper;
property ZoomLevel : TZoomLevel read fZoomLevel write SetZoomLevel default low(TZoomLevel);
property Origin : TPoint read fOrigin write SetOrigin;
property Quality : boolean read fQuality write SetQuality default false;
property OnChange : TOnIsometricChange read fOnChange write fOnChange default nil;
property OnSelect : TOnSelect read fOnSelect write fOnSelect;
private
fSize : TPoint;
fSelection : TPoint; // Map coordinates
fArea : TRect; // Screen Coordinates
fRatio : integer;
procedure SetSelection(const which : TPoint);
public
property Size : TPoint read fSize;
property Selection : TPoint read fSelection write SetSelection; // Map coordinates
procedure SetArea(const Origin, Size : TPoint; Ratio : integer);
procedure SynchronizeSelection;
procedure ViewSelection;
procedure ViewArea;
private
fMouseDown : boolean;
fClicked : boolean;
fMouseX : integer;
fMouseY : integer;
fExposed : boolean;
protected
fHardInvalidated : boolean;
procedure SetParent(which : TWinControl); override;
procedure Paint; override;
procedure MouseDown(Button : TMouseButton; Shift : TShiftState; x, y : integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button : TMouseButton; Shift : TShiftState; x, y : integer); override;
procedure InvalidateIsometric(hard : boolean);
private
fBitmap : TCanvasImage;
nu, du : integer;
w, h : integer;
rows : integer;
cols : integer;
procedure GetArea(out which : TRect);
procedure DrawArea;
procedure CheckArea;
procedure NotifySelect(x, y : integer);
procedure UpdateIsometric;
procedure UpdateRegion(const which : TRect);
procedure UpdateUnits;
procedure DraftRender;
procedure wmSize(var msg : TWMSize); message WM_SIZE;
procedure cmWantSpecialKey(var msg : TCMWantSpecialKey); message CM_WANTSPECIALKEY;
procedure wmEraseBkGnd(var msg); message WM_ERASEBKGND;
end;
procedure Register;
implementation
const
cCanvasBitCount = 16;
const
cSelectionColor = clYellow;
cAreaColor = clYellow;
// Utils
type
TScrollRegion = array[0..1] of TRect;
function GetScrollRegion(const Client : TRect; dx, dy : integer; out which : TScrollRegion) : integer;
begin
fillchar(which, sizeof(which), 0);
Result := 0;
if dx <> 0
then
begin
if dx > 0
then which[Result] := Rect(Client.Right - dx, 0, Client.Right, Client.Bottom)
else which[Result] := Rect(Client.Left, Client.Top, Client.Left - dx, Client.Bottom);
inc(Result);
end;
if dy <> 0
then
begin
if dy > 0
then which[Result] := Rect(0, Client.Bottom - dy, Client.Right, Client.Bottom)
else which[Result] := Rect(Client.Left, Client.Top, Client.Right, Client.Top - dy);
inc(Result);
end;
end;
// TIsometricMap
constructor TIsometricMap.Create(Owner : TComponent);
begin
inherited;
fZoomLevel := low(fZoomLevel);
fBitmap := TCanvasImage.CreateSized(1, 1, cCanvasBitCount);
fHardInvalidated := true;
end;
destructor TIsometricMap.Destroy;
begin
fBitmap.Free;
inherited;
end;
procedure TIsometricMap.SetMapper(which : IIsometricMapper);
begin
if fMapper <> which
then
begin
fMapper := which;
if fMapper <> nil
then
begin
rows := fMapper.GetRows;
cols := fMapper.GetCols;
end
else
begin
rows := 0;
cols := 0;
end;
fExposed := (fMapper <> nil) and (Parent <> nil) and (fRatio <> 0);
if fExposed
then UpdateUnits;
UpdateIsometric;
end;
end;
procedure TIsometricMap.SetZoomLevel(which : TZoomLevel);
begin
if fZoomLevel <> which
then
begin
fZoomLevel := which;
if fExposed
then
begin
UpdateUnits;
CheckArea;
end;
end;
end;
procedure TIsometricMap.SetOrigin(which : TPoint);
var
dx, dy : integer;
procedure Scroll;
var
Client : TRect;
Region : TScrollRegion;
Count : integer;
i : integer;
hCanvas : HDC;
begin
fBitmap.Canvas.RequiredState([csHandleValid, csPenValid]);
hCanvas := fBitmap.Canvas.Handle;
Client := GetClientRect;
ScrollDC(hCanvas, -dx, -dy, Client, Client, 0, nil);
inc(fOrigin.x, dx);
inc(fOrigin.y, dy);
Count := GetScrollRegion(Client, dx, dy, Region);
for i := 0 to pred(Count) do
UpdateRegion(Region[i]);
Refresh;
if assigned(fOnChange)
then fOnChange(Self);
end;
begin
if which.x < 0
then which.x := 0
else
if which.x > fSize.x - w
then which.x := fSize.x - w;
if which.y < 0
then which.y := 0
else
if which.y > fSize.y - h
then which.y := fSize.y - h;
if (which.x <> fOrigin.x) or (which.y <> fOrigin.y)
then
begin
dx := which.x - fOrigin.x;
dy := which.y - fOrigin.y;
if (abs(dx) < w div 2) and (abs(dy) < h div 2)
then Scroll
else
begin
fOrigin := which;
UpdateIsometric;
end;
end;
end;
procedure TIsometricMap.SetQuality(which : boolean);
begin
if fQuality <> which
then
begin
fQuality := which;
if fQuality
then UpdateIsometric;
end;
end;
procedure TIsometricMap.SetSelection(const which : TPoint);
begin
fSelection := which;
UpdateIsometric;
end;
procedure TIsometricMap.SetArea(const Origin, Size : TPoint; Ratio : integer);
begin
assert(Ratio <> 0);
fArea.TopLeft := Origin;
fArea.Right := Origin.x + Size.x;
fArea.Bottom := Origin.y + Size.y;
fRatio := Ratio;
fExposed := (fMapper <> nil) and (Parent <> nil);
if fExposed
then
begin
UpdateUnits;
CheckArea;
end;
end;
procedure TIsometricMap.SynchronizeSelection;
var
x, y : integer;
i, j : integer;
begin
i := fSelection.y;
j := fSelection.x;
if (i <> 0) and (j <> 0) and fExposed
then
begin
x := 2*nu*(rows - i + j) div du - fOrigin.x;
y := nu*((rows - i) + (cols - j)) div du - fOrigin.y;
NotifySelect(x, y);
end;
end;
procedure TIsometricMap.ViewSelection;
var
i, j : integer;
size : TPoint;
begin
if fExposed
then
begin
size := ClientRect.BottomRight;
i := fSelection.y;
j := fSelection.x;
if (i <> 0) and (j <> 0)
then Origin := Point(2*nu*(rows - i + j) div du - size.x div 2, nu*((rows - i) + (cols - j)) div du - size.y div 2);
end;
end;
procedure TIsometricMap.ViewArea;
var
size : TPoint;
x, y : integer;
dx, dy : integer;
u : double;
begin
if fExposed
then
begin
size := ClientRect.BottomRight;
u := nu/fRatio/du;
x := trunc(u*fArea.Left);
y := trunc(u*fArea.Top);
dx := round((size.x + x - u*fArea.Right)/2);
dy := round((size.y + y - u*fArea.Bottom)/2);
Origin := Point(x - dx, y - dy);
end;
end;
procedure TIsometricMap.SetParent(which : TWinControl);
begin
inherited;
fExposed := (which <> nil) and (fMapper <> nil) and (fRatio <> 0);
if fExposed
then UpdateUnits;
end;
procedure TIsometricMap.Paint;
begin
inherited;
if fExposed
then
begin
if fHardInvalidated
then
begin
DraftRender;
fHardInvalidated := false;
end;
fBitmap.Draw(Canvas, 0, 0);
DrawArea;
end;
end;
procedure TIsometricMap.MouseDown(Button : TMouseButton; Shift : TShiftState; x, y : integer);
begin
inherited;
fMouseX := x;
fMouseY := y;
if Button = mbLeft
then
begin
fClicked := true;
MouseCapture := true;
fMouseDown := true;
end;
end;
procedure TIsometricMap.MouseMove(Shift: TShiftState; X, Y: Integer);
const
cClickDelta = 3;
var
dx, dy : integer;
org : TPoint;
begin
inherited;
if fMouseDown
then
begin
org := Origin;
dx := x - fMouseX;
dy := y - fMouseY;
fClicked := fClicked and (abs(dx) + abs(dy) < cClickDelta);
Origin := Point(org.x - dx, org.y - dy);
fMouseX := x;
fMouseY := y;
end;
end;
procedure TIsometricMap.MouseUp(Button : TMouseButton; Shift : TShiftState; x, y : integer);
begin
inherited;
if fMouseDown
then
begin
MouseCapture := false;
fMouseDown := false;
if fClicked
then NotifySelect(x, y);
end;
end;
procedure TIsometricMap.InvalidateIsometric(hard : boolean);
begin
if hard
then fHardInvalidated := true;
Invalidate;
end;
procedure TIsometricMap.GetArea(out which : TRect);
var
u : double;
begin
u := nu/fRatio/du;
with fArea do
begin
which.Left := trunc(u*Left) - fOrigin.x;
which.Top := trunc(u*Top) - fOrigin.y;
which.Right := trunc(u*Right) - fOrigin.x;
which.Bottom := trunc(u*Bottom) - fOrigin.y;
end;
end;
procedure TIsometricMap.DrawArea;
var
aux : TRect;
begin
GetArea(aux);
Canvas.Pen.Color := cAreaColor;
Canvas.FrameRect(aux);
end;
procedure TIsometricMap.CheckArea;
var
aux, tmp : TRect;
begin
GetArea(aux);
if not (IntersectRect(tmp, aux, ClientRect) and EqualRect(tmp, aux))
then ViewArea
else InvalidateIsometric(false);
end;
procedure TIsometricMap.NotifySelect(x, y : integer);
var
i, j : integer;
begin
if assigned(fOnSelect)
then
begin
inc(x, fOrigin.x);
inc(y, fOrigin.y);
i := (2*nu*(2*rows + cols) - du*(x + 2*y)) div (4*nu);
j := (2*nu*cols + du*(x - 2*y)) div (4*nu);
fMapper.TransFormCoords(i, j);
fOnSelect(Self, i, j);
end;
end;
procedure TIsometricMap.UpdateIsometric;
begin
InvalidateIsometric(true);
Refresh;
if assigned(fOnChange)
then fOnChange(Self);
end;
procedure TIsometricMap.UpdateRegion(const which : TRect);
var
x, y : integer;
ox, oy : integer;
x1, x2 : integer;
y2 : integer;
ry, ly : integer;
ww, hh : integer;
ix, jx : integer;
iy, jy : integer;
hCanvas : HDC;
begin
with fBitmap, Canvas do
begin
Pen.Color := clBlack;
Brush.Color := clBlack;
FillRect(which);
//Rectangle(0, 0, Width, Height);
end;
ww := (which.Right - which.Left);
hh := (which.Bottom - which.Top);
fBitmap.Canvas.RequiredState([csHandleValid, csPenValid]);
hCanvas := fBitmap.Canvas.Handle;
ox := fOrigin.x + which.Left;
oy := fOrigin.y + which.Top;
y2 := nu*(rows + cols) div du;
if y2 >= oy + hh
then y2 := pred(oy + hh);
ly := nu*(cols + 1) div du;
ry := nu*(rows + 1) div du;
iy := 2*(nu*(2*rows + cols) - du*oy);
jy := 2*(nu*cols - du*oy);
for y := oy to y2 do
begin
if y <= ly
then x1 := 2*(nu*(cols + 2) - du*y)
else x1 := 2*(du*y - nu*cols);
if x1 < ox*du
then x1 := ox*du;
if y <= ry
then x2 := 2*(nu*(cols - 2) + du*y)
else x2 := 2*(nu*(2*rows + cols) - du*y);
if x2 >= (ox + ww)*du
then x2 := pred(ox + ww)*du;
ix := iy - x1;
jx := jy + x1;
x1 := x1 div du;
x2 := x2 div du;
for x := x1 to x2 do
begin
SetPixel(hCanvas, x - fOrigin.x, y - fOrigin.y, fMapper.GetColor(ix div (4*nu), jx div (4*nu)));
dec(ix, du);
inc(jx, du);
end;
dec(iy, 2*du);
dec(jy, 2*du);
end;
end;
procedure TIsometricMap.UpdateUnits;
begin
assert((rows > 0) and (cols > 0));
w := ClientWidth;
h := ClientHeight;
if w < 2*h
then h := w div 2;
w := 2*h;
nu := (fZoomLevel - low(fZoomLevel))*(2*(rows + cols) - w) + (high(fZoomLevel) - low(fZoomLevel))*w;
du := (2*(high(fZoomLevel) - low(fZoomLevel)))*(rows + cols);
fSize.y := (rows + cols)*nu div du;
fSize.x := 2*fSize.y;
if fOrigin.x < 0
then fOrigin.x := 0
else
if fOrigin.x > fSize.x - w
then fOrigin.x := fSize.x - w;
if fOrigin.y < 0
then fOrigin.y := 0
else
if fOrigin.y > fSize.y - h
then fOrigin.y := fSize.y - h;
InvalidateIsometric(true);
end;
procedure TIsometricMap.DraftRender;
begin
UpdateRegion(ClientRect);
end;
procedure TIsometricMap.wmSize(var msg : TWMSize);
begin
inherited;
if (msg.Width > 0) and (msg.Height > 0)
then
begin
fBitmap.NewSize(msg.Width, msg.Height, cCanvasBitCount);
UpdateIsometric;
end;
end;
procedure TIsometricMap.cmWantSpecialKey(var msg : TCMWantSpecialKey);
begin
inherited;
if msg.CharCode in [VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN]
then msg.Result := 1;
end;
procedure TIsometricMap.wmEraseBkGnd(var msg);
begin
end;
procedure Register;
begin
RegisterComponents('Five', [TIsometricMap]);
end;
end.
|
unit Thread._201010_importar_pedidos_tfo;
interface
uses
System.Classes, Dialogs, Windows, Forms, SysUtils, Messages, Controls, System.DateUtils, System.StrUtils, Generics.Collections,
Control.Entregas, Control.Sistema, FireDAC.Comp.Client, Common.ENum,
FireDAC.Comp.DataSet, Data.DB, Control.PlanilhaEntradaEntregas, Model.PlanilhaEntradaEntregas;
type
Tthread_201010_importar_pedidos_tfo = class(TThread)
private
{ Private declarations }
FEntregas: TEntregasControl;
FPlanilha : TPlanilhasEntradasEntregasControl;
FPlanilhasCSV : TObjectList<TPlanilhaEntradaEntregas>;
sMensagem: String;
FdPos: Double;
iLinha : Integer;
iPosition: Integer;
fdEntregas: TFDQuery;
fdEntregasInsert: TFDQuery;
fdEntregasUpdate: TFDQuery;
iCountInsert : Integer;
iCountUpdate : Integer;
protected
procedure Execute; override;
procedure UpdateLog;
procedure UpdateProgress;
procedure TerminateProcess;
procedure BeginProcesso;
procedure SetupClassUpdate(FDQuery: TFDQuery);
procedure SetupClassInsert(i: Integer);
procedure SetupQueryInsert();
procedure SetupQueryUpdate();
procedure SaveInsert(iCount: Integer);
procedure SaveUpdate(iCount: Integer);
public
FFile: String;
iCodigoCliente: Integer;
bCancel : Boolean;
end;
const
TABLENAME = 'tbentregas';
SQLINSERT = 'INSERT INTO ' + TABLENAME +
'(NUM_NOSSONUMERO, COD_AGENTE, COD_ENTREGADOR, COD_CLIENTE, NUM_NF, NOM_CONSUMIDOR, DES_ENDERECO, DES_COMPLEMENTO, ' +
'DES_BAIRRO, NOM_CIDADE, NUM_CEP, NUM_TELEFONE, DAT_EXPEDICAO, DAT_PREV_DISTRIBUICAO, QTD_VOLUMES, DAT_ATRIBUICAO, ' +
'DAT_BAIXA, DOM_BAIXADO, DAT_PAGAMENTO, DOM_PAGO, DOM_FECHADO, COD_STATUS, DAT_ENTREGA, QTD_PESO_REAL, ' +
'QTD_PESO_FRANQUIA, VAL_VERBA_FRANQUIA, VAL_ADVALOREM, VAL_PAGO_FRANQUIA, VAL_VERBA_ENTREGADOR, NUM_EXTRATO, ' +
'QTD_DIAS_ATRASO, QTD_VOLUMES_EXTRA, VAL_VOLUMES_EXTRA, QTD_PESO_COBRADO, DES_TIPO_PESO, DAT_RECEBIDO, DOM_RECEBIDO, ' +
'NUM_CTRC, NUM_MANIFESTO, DES_RASTREIO, NUM_LOTE_REMESSA, DES_RETORNO, DAT_CREDITO, DOM_CREDITO, NUM_CONTAINER, ' +
'VAL_PRODUTO, QTD_ALTURA, QTD_LARGURA, QTD_COMPRIMENTO, COD_FEEDBACK, DAT_FEEDBACK, DOM_CONFERIDO, NUM_PEDIDO, ' +
'COD_CLIENTE_EMPRESA) ' +
'VALUES ' +
'(:NUM_NOSSONUMERO, :COD_AGENTE, :COD_ENTREGADOR, :COD_CLIENTE, :NUM_NF, :NOM_CONSUMIDOR, :DES_ENDERECO, ' +
':DES_COMPLEMENTO, :DES_BAIRRO, :NOM_CIDADE, :NUM_CEP, :NUM_TELEFONE, :DAT_EXPEDICAO, :DAT_PREV_DISTRIBUICAO, ' +
':QTD_VOLUMES, :DAT_ATRIBUICAO, :DAT_BAIXA, :DOM_BAIXADO, :DAT_PAGAMENTO, :DOM_PAGO, :DOM_FECHADO, :COD_STATUS, ' +
':DAT_ENTREGA, :QTD_PESO_REAL, :QTD_PESO_FRANQUIA, :VAL_VERBA_FRANQUIA, :VAL_ADVALOREM, :VAL_PAGO_FRANQUIA, ' +
':VAL_VERBA_ENTREGADOR, :NUM_EXTRATO, :QTD_DIAS_ATRASO, :QTD_VOLUMES_EXTRA, :VAL_VOLUMES_EXTRA, :QTD_PESO_COBRADO, ' +
':DES_TIPO_PESO, :DAT_RECEBIDO, :DOM_RECEBIDO, :NUM_CTRC, :NUM_MANIFESTO, :DES_RASTREIO, :NUM_LOTE_REMESSA, ' +
':DES_RETORNO, :DAT_CREDITO, :DOM_CREDITO, :NUM_CONTAINER, :VAL_PRODUTO, :QTD_ALTURA, :QTD_LARGURA, :QTD_COMPRIMENTO, ' +
':COD_FEEDBACK, :DAT_FEEDBACK, :DOM_CONFERIDO, :NUM_PEDIDO, :COD_CLIENTE_EMPRESA);';
SQLUPDATE = 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'COD_AGENTE = :COD_AGENTE, COD_ENTREGADOR = :COD_ENTREGADOR, ' +
'COD_CLIENTE = :COD_CLIENTE, NUM_NF = :NUM_NF, NOM_CONSUMIDOR = :NOM_CONSUMIDOR, DES_ENDERECO = :DES_ENDERECO, ' +
'DES_COMPLEMENTO = :DES_COMPLEMENTO, DES_BAIRRO = :DES_BAIRRO, NOM_CIDADE = :NOM_CIDADE, NUM_CEP = :NUM_CEP, ' +
'NUM_TELEFONE = :NUM_TELEFONE, DAT_EXPEDICAO = :DAT_EXPEDICAO, DAT_PREV_DISTRIBUICAO = :DAT_PREV_DISTRIBUICAO, ' +
'QTD_VOLUMES = :QTD_VOLUMES, DAT_ATRIBUICAO = :DAT_ATRIBUICAO, DAT_BAIXA = :DAT_BAIXA, DOM_BAIXADO = :DOM_BAIXADO, ' +
'DAT_PAGAMENTO = :DAT_PAGAMENTO, DOM_PAGO = :DOM_PAGO, DOM_FECHADO = :DOM_FECHADO, COD_STATUS = :COD_STATUS, ' +
'DAT_ENTREGA = :DAT_ENTREGA, QTD_PESO_REAL = :QTD_PESO_REAL, QTD_PESO_FRANQUIA = :QTD_PESO_FRANQUIA, ' +
'VAL_VERBA_FRANQUIA = :VAL_VERBA_FRANQUIA, VAL_ADVALOREM = :VAL_ADVALOREM, VAL_PAGO_FRANQUIA = :VAL_PAGO_FRANQUIA, ' +
'VAL_VERBA_ENTREGADOR = :VAL_VERBA_ENTREGADOR, NUM_EXTRATO = :NUM_EXTRATO, QTD_DIAS_ATRASO = :QTD_DIAS_ATRASO, ' +
'QTD_VOLUMES_EXTRA = :QTD_VOLUMES_EXTRA, VAL_VOLUMES_EXTRA = :VAL_VOLUMES_EXTRA, QTD_PESO_COBRADO = :QTD_PESO_COBRADO, ' +
'DES_TIPO_PESO = :DES_TIPO_PESO, DAT_RECEBIDO = :DAT_RECEBIDO, DOM_RECEBIDO = :DOM_RECEBIDO, NUM_CTRC = :NUM_CTRC, ' +
'NUM_MANIFESTO = :NUM_MANIFESTO, DES_RASTREIO = :DES_RASTREIO, NUM_LOTE_REMESSA = :NUM_LOTE_REMESSA, ' +
'DES_RETORNO = :DES_RETORNO, DAT_CREDITO = :DAT_CREDITO, DOM_CREDITO = :DOM_CREDITO, NUM_CONTAINER = :NUM_CONTAINER, ' +
'VAL_PRODUTO = :VAL_PRODUTO, QTD_ALTURA = :QTD_ALTURA, QTD_LARGURA = :QTD_LARGURA, QTD_COMPRIMENTO = :QTD_COMPRIMENTO, ' +
'COD_FEEDBACK = :COD_FEEDBACK, DAT_FEEDBACK = :DAT_FEEDBACK, DOM_CONFERIDO = :DOM_CONFERIDO, ' +
'NUM_PEDIDO = :NUM_PEDIDO, COD_CLIENTE_EMPRESA = :COD_CLIENTE_EMPRESA ' +
'WHERE ' +
'NUM_NOSSONUMERO = :NUM_NOSSONUMERO;';
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure Tthread_201010_importar_pedidos_tfo.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ Tthread_201010_importar_pedidos_tfo }
uses Common.Utils, Global.Parametros, View.ImportarPedidos;
procedure Tthread_201010_importar_pedidos_tfo.BeginProcesso;
begin
bCancel := False;
view_ImportarPedidos.actCancelar.Enabled := True;
view_ImportarPedidos.actFechar.Enabled := False;
view_ImportarPedidos.actImportar.Enabled := False;
view_ImportarPedidos.actAbrirArquivo.Enabled := False;
view_ImportarPedidos.dxLayoutItem8.Visible := True;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' iniciando importação do arquivo ' + FFile;
UpdateLog;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' tratando os dados da planilha. Aguarde...';
UpdateLog;
end;
procedure Tthread_201010_importar_pedidos_tfo.Execute;
var
aParam: Array of variant;
iPos : Integer;
iTotal: Integer;
sCEP: String;
begin
{ Place thread code here }
try
try
Synchronize(BeginProcesso);
FEntregas := TEntregasControl.Create;
FPlanilha := TPlanilhasEntradasEntregasControl.Create;
FPlanilhasCSV := TObjectList<TPlanilhaEntradaEntregas>.Create;
Screen.Cursor := crHourGlass;
FPlanilhasCSV := FPlanilha.GetPlanilha(FFile);
Screen.Cursor := crDefault;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importando os dados. Aguarde...';
Synchronize(UpdateLog);
iCountInsert := 0;
iCountUpdate := 0;
if FPlanilhasCSV.Count > 0 then
begin
iPos := 0;
FdPos := 0;
iTotal := FPlanilhasCSV.Count;
fdEntregas := TSistemaControl.GetInstance.Conexao.ReturnQuery;
fdEntregasInsert := TSistemaControl.GetInstance.Conexao.ReturnQuery;
fdEntregasUpdate := TSistemaControl.GetInstance.Conexao.ReturnQuery;
for iPos := 0 to Pred(iTotal) do
begin
fdEntregasInsert.SQL.Text := SQLINSERT;
fdEntregasUpdate.SQL.Text := SQLUPDATE;
SetLength(aParam,2);
aParam[0] := 'NN';
aParam[1] := Trim(FPlanilhasCSV[iPos].NossoNumero);
fdEntregas := FEntregas.Localizar(aParam);
Finalize(aParam);
if fdEntregas.IsEmpty then
begin
SetupClassInsert(iPos);
Inc(iCountInsert);
FEntregas.Entregas.Status := 909;
FEntregas.Entregas.Rastreio := '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importado por ' +
Global.Parametros.pUser_Name;
SetupQueryInsert;
end
else
begin
SetupClassUpdate(fdEntregas);
Inc(iCountUpdate);
FEntregas.Entregas.Status := 909;
FEntregas.Entregas.Rastreio := FEntregas.Entregas.Rastreio + #13 +
'> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' atualizado por importação por ' +
Global.Parametros.pUser_Name;
SetupQueryUpdate;
end;
fdEntregas.Close;
iPosition := iPos + 1;
FdPos := (iPosition / iTotal) * 100;
if not(Self.Terminated) then
begin
Synchronize(UpdateProgress);
end
else
begin
Abort;
end;
fdEntregas.Close;
end;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' salvando no banco de dados. Aguarde...';
Synchronize(UpdateLog);
Synchronize(procedure begin Screen.Cursor := crHourGlass end);
if iCountInsert > 0 then SaveInsert(iCountInsert);
if iCountUpdate > 0 then SaveUpdate(iCountUpdate);
fdEntregasInsert.Connection.Close;
fdEntregasUpdate.Connection.Close;
fdEntregasInsert.Free;
fdEntregasUpdate.Free;
Synchronize(procedure begin Screen.Cursor := crDefault end);
end;
Except
on E: Exception do
begin
Application.MessageBox(PChar('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message), 'Erro', MB_OK + MB_ICONERROR);
bCancel := True;
end;
end;
finally
if bCancel then
begin
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação cancelada ...';
Synchronize(UpdateLog);
Application.MessageBox('Importação cancelada!', 'Importação de Entregas', MB_OK + MB_ICONWARNING);
end
else
begin
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação concluída com sucesso';
Synchronize(UpdateLog);
Application.MessageBox('Importação concluída com sucesso!', 'Importação de Entregas', MB_OK + MB_ICONINFORMATION);
end;
Synchronize(TerminateProcess);
FEntregas.Free;
FPlanilha.Free;
FPlanilhasCSV.Free;
fdEntregas.Free;
end;
end;
procedure Tthread_201010_importar_pedidos_tfo.SaveInsert(iCount: Integer);
begin
fdEntregasInsert.Execute(iCount, 0);
end;
procedure Tthread_201010_importar_pedidos_tfo.SaveUpdate(iCount: Integer);
begin
fdEntregasUpdate.Execute(iCount, 0);
end;
procedure Tthread_201010_importar_pedidos_tfo.SetupClassInsert(i: Integer);
begin
FEntregas.Entregas.NN := FPlanilhasCSV[i].NossoNumero;
FEntregas.Entregas.Distribuidor := 0;
FEntregas.Entregas.Entregador := 0;
FEntregas.Entregas.Cliente := StrToIntDef(FPlanilhasCSV[i].CodigoCliente,0);
FEntregas.Entregas.NF := FPlanilhasCSV[i].NumeroNF;
FEntregas.Entregas.Consumidor := FPlanilhasCSV[i].NomeConsumidor;
FEntregas.Entregas.Endereco := FPlanilhasCSV[i].Logradouro;
FEntregas.Entregas.Complemento := Copy(FPlanilhasCSV[i].Complemento + ' - ' + FPlanilhasCSV[i].AosCuidados,1,70);
FEntregas.Entregas.Bairro := FPlanilhasCSV[i].Bairro;
FEntregas.Entregas.Cidade := FPlanilhasCSV[i].Cidade;
FEntregas.Entregas.Cep := FPlanilhasCSV[i].CEP;
FEntregas.Entregas.Telefone := Copy(FPlanilhasCSV[i].Telefone,1,30);
FEntregas.Entregas.Expedicao := StrToDateDef(FPlanilhasCSV[i].Expedicao, StrToDate('30/12/1899'));
FEntregas.Entregas.Previsao := StrToDateDef(FPlanilhasCSV[i].Previsao, StrToDate('30/12/1899'));
FEntregas.Entregas.Volumes := StrToIntDef(FPlanilhasCSV[i].Volume,1);
FEntregas.Entregas.Atribuicao := StrToDate('30/12/1899');
FEntregas.Entregas.Baixa := StrToDate('30/12/1899');
FEntregas.Entregas.Baixado := 'N';
FEntregas.Entregas.Pagamento := StrToDate('30/12/1899');
FEntregas.Entregas.Pago := 'N';
FEntregas.Entregas.Fechado := 'N';
FEntregas.Entregas.Status := StrToIntDef(FPlanilhasCSV[I].Status,0);
FEntregas.Entregas.Entrega := StrToDate('30/12/1899');
FPlanilhasCSV[I].Peso := ReplaceStr(FPlanilhasCSV[I].Peso, ' KG', '');
FPlanilhasCSV[I].Peso := ReplaceStr(FPlanilhasCSV[I].Peso, '.', ',');
FEntregas.Entregas.PesoReal := StrToFloatDef(FPlanilhasCSV[I].Peso,0);
FEntregas.Entregas.TipoPeso := '';
FEntregas.Entregas.PesoFranquia := 0;
FEntregas.Entregas.Advalorem := 0;
FEntregas.Entregas.PagoFranquia := 0;
FEntregas.Entregas.VerbaEntregador := 0;
FEntregas.Entregas.Extrato := '0';
FEntregas.Entregas.Atraso := 0;
FEntregas.Entregas.VolumesExtra := 0;
FEntregas.Entregas.ValorVolumes := 0;
FEntregas.Entregas.PesoCobrado := 0;
FEntregas.Entregas.Recebimento := StrToDate('30/12/1899');
FEntregas.Entregas.Recebido := 'N';
FEntregas.Entregas.CTRC := 0;
FEntregas.Entregas.Manifesto := 0;
FEntregas.Entregas.Rastreio := '';
FPlanilhasCSV[I].ValorVerba := ReplaceStr(FPlanilhasCSV[I].ValorVerba, 'R$ ', '');
FEntregas.Entregas.VerbaFranquia := StrToFloatDef(FPlanilhasCSV[I].ValorVerba, 0);
FEntregas.Entregas.Lote := 0;
FEntregas.Entregas.Retorno := '';
FEntregas.Entregas.Credito := StrToDate('30/12/1899');;
FEntregas.Entregas.Creditado := 'N';
FEntregas.Entregas.Container :=FPlanilhasCSV[I].Container;
FPlanilhasCSV[I].ValorProuto := ReplaceStr(FPlanilhasCSV[I].ValorProuto, 'R$ ', '');
FPlanilhasCSV[I].ValorProuto := ReplaceStr(FPlanilhasCSV[I].ValorProuto, '.', '');
FEntregas.Entregas.ValorProduto := StrToFloatDef(FPlanilhasCSV[i].ValorProuto, 0);
FEntregas.Entregas.Altura := StrToIntDef(FPlanilhasCSV[I].Altura, 0);
FEntregas.Entregas.Largura := StrToIntDef(FPlanilhasCSV[I].Largura, 0);;
FEntregas.Entregas.Comprimento := StrToIntDef(FPlanilhasCSV[I].Comprimento, 0);;
FEntregas.Entregas.CodigoFeedback := 0;
FEntregas.Entregas.DataFeedback := StrToDate('30/12/1899');
FEntregas.Entregas.Conferido := 0;
FEntregas.Entregas.Pedido := '0';;
FEntregas.Entregas.CodCliente := iCodigoCliente;
end;
procedure Tthread_201010_importar_pedidos_tfo.SetupClassUpdate(FDQuery: TFDQuery);
begin
FEntregas.Entregas.NN := FDQuery.FieldByName('NUM_NOSSONUMERO').AsString;
FEntregas.Entregas.Distribuidor := FDQuery.FieldByName('COD_AGENTE').AsInteger;
FEntregas.Entregas.Entregador := FDQuery.FieldByName('COD_ENTREGADOR').AsInteger;
FEntregas.Entregas.Cliente := FDQuery.FieldByName('COD_CLIENTE').AsInteger;
FEntregas.Entregas.NF := FDQuery.FieldByName('NUM_NF').AsString;
FEntregas.Entregas.Consumidor := FDQuery.FieldByName('NOM_CONSUMIDOR').AsString;
FEntregas.Entregas.Endereco := FDQuery.FieldByName('DES_ENDERECO').AsString;
FEntregas.Entregas.Complemento := FDQuery.FieldByName('DES_COMPLEMENTO').AsString;
FEntregas.Entregas.Bairro := FDQuery.FieldByName('DES_BAIRRO').AsString;
FEntregas.Entregas.Cidade := FDQuery.FieldByName('NOM_CIDADE').AsString;
FEntregas.Entregas.Cep := FDQuery.FieldByName('NUM_CEP').AsString;
FEntregas.Entregas.Telefone := FDQuery.FieldByName('NUM_TELEFONE').AsString;
FEntregas.Entregas.Expedicao := FDQuery.FieldByName('DAT_EXPEDICAO').AsDateTime;
FEntregas.Entregas.Previsao := FDQuery.FieldByName('DAT_PREV_DISTRIBUICAO').AsDateTime;
FEntregas.Entregas.Volumes := FDQuery.FieldByName('QTD_VOLUMES').AsInteger;
FEntregas.Entregas.Atribuicao := FDQuery.FieldByName('DAT_ATRIBUICAO').AsDateTime;
FEntregas.Entregas.Baixa := FDQuery.FieldByName('DAT_BAIXA').AsDateTime;
FEntregas.Entregas.Baixado := FDQuery.FieldByName('DOM_BAIXADO').AsString;
FEntregas.Entregas.Pagamento := FDQuery.FieldByName('DAT_PAGAMENTO').AsDateTime;
FEntregas.Entregas.Pago := FDQuery.FieldByName('DOM_PAGO').AsString;
FEntregas.Entregas.Fechado := FDQuery.FieldByName('DOM_FECHADO').AsString;
FEntregas.Entregas.Status := FDQuery.FieldByName('COD_STATUS').AsInteger;
FEntregas.Entregas.Entrega := FDQuery.FieldByName('DAT_ENTREGA').AsDateTime;
FEntregas.Entregas.PesoReal := FDQuery.FieldByName('QTD_PESO_REAL').AsFloat;
FEntregas.Entregas.PesoFranquia := FDQuery.FieldByName('QTD_PESO_FRANQUIA').AsFloat;
FEntregas.Entregas.VerbaFranquia := FDQuery.FieldByName('VAL_VERBA_FRANQUIA').AsFloat;
FEntregas.Entregas.Advalorem := FDQuery.FieldByName('VAL_ADVALOREM').AsFloat;
FEntregas.Entregas.PagoFranquia := FDQuery.FieldByName('VAL_PAGO_FRANQUIA').AsFloat;
FEntregas.Entregas.VerbaEntregador := FDQuery.FieldByName('VAL_VERBA_ENTREGADOR').AsFloat;
FEntregas.Entregas.Extrato := FDQuery.FieldByName('NUM_EXTRATO').AsString;
FEntregas.Entregas.Atraso := FDQuery.FieldByName('QTD_DIAS_ATRASO').AsInteger;
FEntregas.Entregas.VolumesExtra := FDQuery.FieldByName('QTD_VOLUMES_EXTRA').AsFloat;
FEntregas.Entregas.ValorVolumes := FDQuery.FieldByName('VAL_VOLUMES_EXTRA').AsFloat;
FEntregas.Entregas.PesoCobrado := FDQuery.FieldByName('QTD_PESO_COBRADO').AsFloat;
FEntregas.Entregas.TipoPeso := FDQuery.FieldByName('DES_TIPO_PESO').AsString;
FEntregas.Entregas.Recebimento := FDQuery.FieldByName('DAT_RECEBIDO').AsDateTime;
FEntregas.Entregas.Recebido := FDQuery.FieldByName('DOM_RECEBIDO').AsString;
FEntregas.Entregas.CTRC := FDQuery.FieldByName('NUM_CTRC').AsInteger;
FEntregas.Entregas.Manifesto := FDQuery.FieldByName('NUM_MANIFESTO').AsInteger;
FEntregas.Entregas.Rastreio := FDQuery.FieldByName('DES_RASTREIO').AsString;
FEntregas.Entregas.VerbaFranquia := FDQuery.FieldByName('VAL_VERBA_FRANQUIA').AsFloat;
FEntregas.Entregas.Lote := FDQuery.FieldByName('NUM_LOTE_REMESSA').AsInteger;
FEntregas.Entregas.Retorno := FDQuery.FieldByName('DES_RETORNO').AsString;
FEntregas.Entregas.Credito := FDQuery.FieldByName('DAT_CREDITO').AsDateTime;
FEntregas.Entregas.Creditado := FDQuery.FieldByName('DOM_CREDITO').AsString;
FEntregas.Entregas.Container := FDQuery.FieldByName('NUM_CONTAINER').AsString;
FEntregas.Entregas.ValorProduto := FDQuery.FieldByName('VAL_PRODUTO').AsFloat;
FEntregas.Entregas.Altura := FDQuery.FieldByName('QTD_ALTURA').AsInteger;
FEntregas.Entregas.Largura := FDQuery.FieldByName('QTD_LARGURA').AsInteger;
FEntregas.Entregas.Comprimento := FDQuery.FieldByName('QTD_COMPRIMENTO').AsInteger;
FEntregas.Entregas.CodigoFeedback := FDQuery.FieldByName('COD_FEEDBACK').AsInteger;
FEntregas.Entregas.DataFeedback := FDQuery.FieldByName('DAT_FEEDBACK').AsDateTime;
FEntregas.Entregas.Conferido := FDQuery.FieldByName('DOM_CONFERIDO').AsInteger;
FEntregas.Entregas.Pedido := FDQuery.FieldByName('NUM_PEDIDO').AsString;
FEntregas.Entregas.CodCliente := FDQuery.FieldByName('COD_CLIENTE_EMPRESA').AsInteger;
end;
procedure Tthread_201010_importar_pedidos_tfo.SetupQueryInsert;
begin
fdEntregasInsert.Params.ArraySize := iCountInsert;
fdEntregasInsert.ParamByName('NUM_NOSSONUMERO').AsStrings[Pred(iCountInsert)]:= FEntregas.Entregas.NN;
fdEntregasInsert.ParamByName('COD_AGENTE').AsIntegers[Pred(iCountInsert)]:= FEntregas.Entregas.Distribuidor;
fdEntregasInsert.ParamByName('COD_ENTREGADOR').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Entregador;
fdEntregasInsert.ParamByName('COD_CLIENTE').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Cliente;
fdEntregasInsert.ParamByName('NUM_NF').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.NF;
fdEntregasInsert.ParamByName('NOM_CONSUMIDOR').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Consumidor;
fdEntregasInsert.ParamByName('DES_ENDERECO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Endereco;
fdEntregasInsert.ParamByName('DES_COMPLEMENTO').AsStrings[Pred(iCountInsert)] := LeftStr(FEntregas.Entregas.Complemento,70);
fdEntregasInsert.ParamByName('DES_BAIRRO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Bairro;
fdEntregasInsert.ParamByName('NOM_CIDADE').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Cidade;
fdEntregasInsert.ParamByName('NUM_CEP').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Cep;
fdEntregasInsert.ParamByName('NUM_TELEFONE').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Telefone;
fdEntregasInsert.ParamByName('DAT_EXPEDICAO').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.Expedicao;
fdEntregasInsert.ParamByName('DAT_PREV_DISTRIBUICAO').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.Previsao;
fdEntregasInsert.ParamByName('QTD_VOLUMES').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Volumes;
fdEntregasInsert.ParamByName('DAT_ATRIBUICAO').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.Atribuicao;
fdEntregasInsert.ParamByName('DAT_BAIXA').AsDates[Pred(iCountInsert)] := FEntregas.Entregas.Baixa;
fdEntregasInsert.ParamByName('DOM_BAIXADO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Baixado;
fdEntregasInsert.ParamByName('DAT_PAGAMENTO').AsDates[Pred(iCountInsert)] := FEntregas.Entregas.Pagamento;
fdEntregasInsert.ParamByName('DOM_PAGO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Pago;
fdEntregasInsert.ParamByName('DOM_FECHADO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Fechado;
fdEntregasInsert.ParamByName('COD_STATUS').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Status;
fdEntregasInsert.ParamByName('DAT_ENTREGA').AsDates[Pred(iCountInsert)] := FEntregas.Entregas.Entrega;
fdEntregasInsert.ParamByName('QTD_PESO_REAL').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.PesoReal;
fdEntregasInsert.ParamByName('QTD_PESO_FRANQUIA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.PesoFranquia;
fdEntregasInsert.ParamByName('VAL_VERBA_FRANQUIA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.VerbaFranquia;
fdEntregasInsert.ParamByName('VAL_ADVALOREM').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.Advalorem;
fdEntregasInsert.ParamByName('VAL_PAGO_FRANQUIA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.PagoFranquia;
fdEntregasInsert.ParamByName('VAL_VERBA_ENTREGADOR').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.VerbaEntregador;
fdEntregasInsert.ParamByName('NUM_EXTRATO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Extrato;
fdEntregasInsert.ParamByName('QTD_DIAS_ATRASO').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Atraso;
fdEntregasInsert.ParamByName('QTD_VOLUMES_EXTRA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.VolumesExtra;
fdEntregasInsert.ParamByName('VAL_VOLUMES_EXTRA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.ValorVolumes;
fdEntregasInsert.ParamByName('QTD_PESO_COBRADO').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.PesoCobrado;
fdEntregasInsert.ParamByName('DES_TIPO_PESO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.TipoPeso;
fdEntregasInsert.ParamByName('DAT_RECEBIDO').AsDates[Pred(iCountInsert)] := FEntregas.Entregas.Recebimento;
fdEntregasInsert.ParamByName('DOM_RECEBIDO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Recebido;
fdEntregasInsert.ParamByName('NUM_CTRC').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.CTRC;
fdEntregasInsert.ParamByName('NUM_MANIFESTO').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Manifesto;
fdEntregasInsert.ParamByName('DES_RASTREIO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Rastreio;
fdEntregasInsert.ParamByName('VAL_VERBA_FRANQUIA').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.VerbaFranquia;
fdEntregasInsert.ParamByName('NUM_LOTE_REMESSA').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Lote;
fdEntregasInsert.ParamByName('DES_RETORNO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Retorno;
fdEntregasInsert.ParamByName('DAT_CREDITO').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.Credito;
fdEntregasInsert.ParamByName('DOM_CREDITO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Creditado;
fdEntregasInsert.ParamByName('NUM_CONTAINER').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Container;
fdEntregasInsert.ParamByName('VAL_PRODUTO').AsFloats[Pred(iCountInsert)] := FEntregas.Entregas.ValorProduto;
fdEntregasInsert.ParamByName('QTD_ALTURA').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Altura;
fdEntregasInsert.ParamByName('QTD_LARGURA').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Largura;
fdEntregasInsert.ParamByName('QTD_COMPRIMENTO').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Comprimento;
fdEntregasInsert.ParamByName('COD_FEEDBACK').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.CodigoFeedback;
fdEntregasInsert.ParamByName('DAT_FEEDBACK').AsDateTimes[Pred(iCountInsert)] := FEntregas.Entregas.DataFeedback;
fdEntregasInsert.ParamByName('DOM_CONFERIDO').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.Conferido;
fdEntregasInsert.ParamByName('NUM_PEDIDO').AsStrings[Pred(iCountInsert)] := FEntregas.Entregas.Pedido;
fdEntregasInsert.ParamByName('COD_CLIENTE_EMPRESA').AsIntegers[Pred(iCountInsert)] := FEntregas.Entregas.CodCliente;
end;
procedure Tthread_201010_importar_pedidos_tfo.SetupQueryUpdate;
begin
fdEntregasUpdate.Params.ArraySize := iCountUpdate;
fdEntregasUpdate.ParamByName('NUM_NOSSONUMERO').AsStrings[Pred(iCountUpdate)]:= FEntregas.Entregas.NN;
fdEntregasUpdate.ParamByName('COD_AGENTE').AsIntegers[Pred(iCountUpdate)]:= FEntregas.Entregas.Distribuidor;
fdEntregasUpdate.ParamByName('COD_ENTREGADOR').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Entregador;
fdEntregasUpdate.ParamByName('COD_CLIENTE').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Cliente;
fdEntregasUpdate.ParamByName('NUM_NF').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.NF;
fdEntregasUpdate.ParamByName('NOM_CONSUMIDOR').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Consumidor;
fdEntregasUpdate.ParamByName('DES_ENDERECO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Endereco;
fdEntregasUpdate.ParamByName('DES_COMPLEMENTO').AsStrings[Pred(iCountUpdate)] := LeftStr(FEntregas.Entregas.Complemento,70);
fdEntregasUpdate.ParamByName('DES_BAIRRO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Bairro;
fdEntregasUpdate.ParamByName('NOM_CIDADE').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Cidade;
fdEntregasUpdate.ParamByName('NUM_CEP').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Cep;
fdEntregasUpdate.ParamByName('NUM_TELEFONE').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Telefone;
fdEntregasUpdate.ParamByName('DAT_EXPEDICAO').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.Expedicao;
fdEntregasUpdate.ParamByName('DAT_PREV_DISTRIBUICAO').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.Previsao;
fdEntregasUpdate.ParamByName('QTD_VOLUMES').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Volumes;
fdEntregasUpdate.ParamByName('DAT_ATRIBUICAO').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.Atribuicao;
fdEntregasUpdate.ParamByName('DAT_BAIXA').AsDates[Pred(iCountUpdate)] := FEntregas.Entregas.Baixa;
fdEntregasUpdate.ParamByName('DOM_BAIXADO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Baixado;
fdEntregasUpdate.ParamByName('DAT_PAGAMENTO').AsDates[Pred(iCountUpdate)] := FEntregas.Entregas.Pagamento;
fdEntregasUpdate.ParamByName('DOM_PAGO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Pago;
fdEntregasUpdate.ParamByName('DOM_FECHADO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Fechado;
fdEntregasUpdate.ParamByName('COD_STATUS').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Status;
fdEntregasUpdate.ParamByName('DAT_ENTREGA').AsDates[Pred(iCountUpdate)] := FEntregas.Entregas.Entrega;
fdEntregasUpdate.ParamByName('QTD_PESO_REAL').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.PesoReal;
fdEntregasUpdate.ParamByName('QTD_PESO_FRANQUIA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.PesoFranquia;
fdEntregasUpdate.ParamByName('VAL_VERBA_FRANQUIA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.VerbaFranquia;
fdEntregasUpdate.ParamByName('VAL_ADVALOREM').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.Advalorem;
fdEntregasUpdate.ParamByName('VAL_PAGO_FRANQUIA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.PagoFranquia;
fdEntregasUpdate.ParamByName('VAL_VERBA_ENTREGADOR').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.VerbaEntregador;
fdEntregasUpdate.ParamByName('NUM_EXTRATO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Extrato;
fdEntregasUpdate.ParamByName('QTD_DIAS_ATRASO').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Atraso;
fdEntregasUpdate.ParamByName('QTD_VOLUMES_EXTRA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.VolumesExtra;
fdEntregasUpdate.ParamByName('VAL_VOLUMES_EXTRA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.ValorVolumes;
fdEntregasUpdate.ParamByName('QTD_PESO_COBRADO').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.PesoCobrado;
fdEntregasUpdate.ParamByName('DES_TIPO_PESO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.TipoPeso;
fdEntregasUpdate.ParamByName('DAT_RECEBIDO').AsDates[Pred(iCountUpdate)] := FEntregas.Entregas.Recebimento;
fdEntregasUpdate.ParamByName('DOM_RECEBIDO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Recebido;
fdEntregasUpdate.ParamByName('NUM_CTRC').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.CTRC;
fdEntregasUpdate.ParamByName('NUM_MANIFESTO').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Manifesto;
fdEntregasUpdate.ParamByName('DES_RASTREIO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Rastreio;
fdEntregasUpdate.ParamByName('VAL_VERBA_FRANQUIA').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.VerbaFranquia;
fdEntregasUpdate.ParamByName('NUM_LOTE_REMESSA').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Lote;
fdEntregasUpdate.ParamByName('DES_RETORNO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Retorno;
fdEntregasUpdate.ParamByName('DAT_CREDITO').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.Credito;
fdEntregasUpdate.ParamByName('DOM_CREDITO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Creditado;
fdEntregasUpdate.ParamByName('NUM_CONTAINER').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Container;
fdEntregasUpdate.ParamByName('VAL_PRODUTO').AsFloats[Pred(iCountUpdate)] := FEntregas.Entregas.ValorProduto;
fdEntregasUpdate.ParamByName('QTD_ALTURA').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Altura;
fdEntregasUpdate.ParamByName('QTD_LARGURA').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Largura;
fdEntregasUpdate.ParamByName('QTD_COMPRIMENTO').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Comprimento;
fdEntregasUpdate.ParamByName('COD_FEEDBACK').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.CodigoFeedback;
fdEntregasUpdate.ParamByName('DAT_FEEDBACK').AsDateTimes[Pred(iCountUpdate)] := FEntregas.Entregas.DataFeedback;
fdEntregasUpdate.ParamByName('DOM_CONFERIDO').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.Conferido;
fdEntregasUpdate.ParamByName('NUM_PEDIDO').AsStrings[Pred(iCountUpdate)] := FEntregas.Entregas.Pedido;
fdEntregasUpdate.ParamByName('COD_CLIENTE_EMPRESA').AsIntegers[Pred(iCountUpdate)] := FEntregas.Entregas.CodCliente;
end;
procedure Tthread_201010_importar_pedidos_tfo.TerminateProcess;
begin
view_ImportarPedidos.actCancelar.Enabled := False;
view_ImportarPedidos.actFechar.Enabled := True;
view_ImportarPedidos.actImportar.Enabled := True;
view_ImportarPedidos.actAbrirArquivo.Enabled := True;
view_ImportarPedidos.edtArquivo.Clear;
view_ImportarPedidos.pbImportacao.Position := 0;
view_ImportarPedidos.pbImportacao.Clear;
view_ImportarPedidos.dxLayoutItem8.Visible := False;
view_ImportarPedidos.cboCliente.ItemIndex := 0;
end;
procedure Tthread_201010_importar_pedidos_tfo.UpdateLog;
begin
view_ImportarPedidos.memLOG.Lines.Add(sMensagem);
view_ImportarPedidos.memLOG.Lines.Add('');
iLinha := view_ImportarPedidos.memLOG.Lines.Count - 1;
view_ImportarPedidos.memLOG.Refresh;
end;
procedure Tthread_201010_importar_pedidos_tfo.UpdateProgress;
begin
view_ImportarPedidos.pbImportacao.Position := FdPos;
view_ImportarPedidos.pbImportacao.Properties.Text := FormatFloat('0.00%',FdPos) +
' - (' + IntToStr(iPosition) + ' registros processados)';
view_ImportarPedidos.pbImportacao.Refresh;
if not(view_ImportarPedidos.actCancelar.Visible) then
begin
view_ImportarPedidos.actCancelar.Visible := True;
view_ImportarPedidos.actFechar.Enabled := False;
view_ImportarPedidos.actImportar.Enabled := False;
end;
end;
end.
|
unit commandhandling;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, levelhandling, typehandling;
procedure start();
procedure undergo(Text: string);
procedure askload();
procedure asksave();
procedure attemptmove();
procedure attemptfight();
procedure attemptbuy();
implementation
//Prepares the game
procedure start();
begin
new(level);
new(player);
askload;
end;
//Command crossroads and checks player status after the command
procedure undergo(Text: string);
begin
case Text of
'load', 'l': askload;
'save', 's': asksave;
'move', 'm': attemptmove;
'fight', 'f': attemptfight;
'buy', 'b': attemptbuy;
end;
if player^.health <= 0 then
begin
writeln('You have died and have to start a new game or load a previous save');
start();
end;
end;
//Loads what the player wants to load
procedure askload();
var
path: string;
begin
writeln('Do you want to load a saved game?');
readln(path);
if ((path = 'Yes') or (path = 'yes')) then
begin
writeln('Please enter the name of the desired save:');
readln(path);
loadlevel('saves/' + path);
end
else
begin
writeln('Please enter the name of the desired map:');
readln(path);
loadlevel(path);
end;
writelevel;
end;
//Saves the game with a player-chosen name
procedure asksave();
var
path: string;
begin
writeln('Please enter the desired name of your save:');
readln(path);
savelevel('saves/' + path);
end;
//Attempts to move the player in a specified direction
procedure attemptmove();
var
direction: string;
begin
writeln('Where would you like to move? (up, down, left, right)');
readln(direction);
case direction of
'up', 'u': if level^.area[player^.y - 1][player^.x] = ' ' then
movecharacter(0, -1)
else
writeln('Cannot move there');
'down', 'd': if level^.area[player^.y + 1][player^.x] = ' ' then
movecharacter(0, 1)
else
writeln('Cannot move there');
'left', 'l': if level^.area[player^.y][player^.x - 1] = ' ' then
movecharacter(-1, 0)
else
writeln('Cannot move there');
'right', 'r': if level^.area[player^.y][player^.x + 1] = ' ' then
movecharacter(1, 0)
else
writeln('Cannot move there');
end;
writelevel;
end;
//Attemps to fight an adjacent monster (First clockwise from the top in case of multiple enemies)
procedure attemptfight();
var
monsterx, monstery, index, i: integer;
begin
monsterx := 0;
monstery := 0;
if level^.area[player^.y - 1][player^.x] = 'M' then
begin
monsterx := player^.x;
monstery := player^.y - 1;
end
else if level^.area[player^.y][player^.x + 1] = 'M' then
begin
monsterx := player^.x + 1;
monstery := player^.y;
end
else if level^.area[player^.y + 1][player^.x] = 'M' then
begin
monsterx := player^.x;
monstery := player^.y + 1;
end
else if level^.area[player^.y][player^.x - 1] = 'M' then
begin
monsterx := player^.x - 1;
monstery := player^.y;
end
else
writeln('No monsters nearby');
if (monsterx <> 0) and (monstery <> 0) then
begin
index := 0;
i := 0;
while index = 0 do
begin
writeln(i);
if ((level^.monsters[i]^.x = monsterx) and
(level^.monsters[i]^.y = monstery)) then
begin
index := i;
end;
i := i + 1;
end;
fight(index);
end;
end;
//Attempts to buy from an adjacent merchant
procedure attemptbuy();
var
shopx, shopy: integer;
begin
shopx := 0;
shopy := 0;
if (level^.area[player^.y - 1][player^.x] = 'B') or
(level^.area[player^.y - 1][player^.x] = 'H') then
begin
shopx := player^.x;
shopy := player^.y - 1;
end
else if (level^.area[player^.y][player^.x + 1] = 'B') or
(level^.area[player^.y][player^.x + 1] = 'H') then
begin
shopx := player^.x + 1;
shopy := player^.y;
end
else if (level^.area[player^.y + 1][player^.x] = 'B') or
(level^.area[player^.y + 1][player^.x] = 'H') then
begin
shopx := player^.x;
shopy := player^.y + 1;
end
else if (level^.area[player^.y][player^.x - 1] = 'B') or
(level^.area[player^.y][player^.x - 1] = 'H') then
begin
shopx := player^.x - 1;
shopy := player^.y;
end;
if (shopx <> 0) and (shopy <> 0) then
begin
if level^.area[shopy][shopx] = 'B' then
buyweapon()
else
buyhealth();
end;
end;
end.
|
unit dates;
interface
type
weekdaytype = array[0..6] of string[3];
Procedure initweekdays(var weekdays:weekdaytype);
Function packit(m,d,y:integer):integer;
Procedure unpackit(date:integer;var m,d,y:integer);
Function dateval(x:string):integer;
Function datestr(x:integer):string;
implementation
type monthoffsettype = array[1..12] of integer;
Procedure initmonthoffset(var moffset:monthoffsettype);
begin
moffset[1] := 0;
moffset[2] := 31;
moffset[3] := 59;
moffset[4] := 90;
moffset[5] := 120;
moffset[6] := 151;
moffset[7] := 181;
moffset[8] := 212;
moffset[9] := 243;
moffset[10] := 273;
moffset[11] := 304;
moffset[12] := 334
end;
Procedure initweekdays(var weekdays:weekdaytype);
begin
weekdays[0] := 'Sun';
weekdays[1] := 'Mon';
weekdays[2] := 'Tue';
weekdays[3] := 'Wed';
weekdays[4] := 'Thu';
weekdays[5] := 'Fri';
weekdays[6] := 'Sat'
end;
Function packit(m,d,y:integer):integer;
var temp:integer;
moffset:monthoffsettype;
begin
if y >= 80 then y := y - 80 else y := y + 20;
initmonthoffset(moffset);
temp := 2 + y*365 + moffset[m] + d + (y div 4);
if (y mod 4 = 0) and (m <= 2) then temp := temp - 1;
packit := temp
end;
Procedure unpackit(date:integer;var m,d,y:integer);
var y4,y1,cnt:integer;
moffset:monthoffsettype;
done:boolean;
begin
initmonthoffset(moffset);
date := date - 2;
y4 := date div 1461;
date := date mod 1461;
if date = 59 then
begin
y := 4*y4;
if y < 20 then y := y + 80 else y := y - 20;
m := 2;
d := 29
end
else
begin
if date > 59 then date := date - 1;
y1 := date div 365;
date := date mod 365;
y := 4*y4 + y1;
if y < 20 then y := y + 80 else y := y - 20;
cnt := 1;
done := false;
while not done do
if cnt = 12 then done := true
else if moffset[cnt + 1] > date then done := true
else cnt := cnt + 1;
m := cnt;
date := date - moffset[cnt];
d := date + 1
end
end;
Function dateval(x:string):integer;
var d:array[1..3] of integer;
posit,un:integer;
begin
posit := 1;
un := 1;
while (posit <= length(x)) and (un <= 3) do
begin
d[un] := 0;
while (posit <= length(x)) and (x[posit] <> '/') do
begin
d[un] := 10*d[un] - 48 + ord(x[posit]);
posit := posit + 1
end;
un := un + 1;
posit := posit + 1
end;
if (un <= 3) then
dateval := -1
else
dateval := packit(d[1],d[2],d[3])
end;
Function datestr(x:integer):string;
var d,m,y:integer;
dstr,ystr,mstr:string[2];
begin
unpackit(x,m,d,y);
str(m,mstr);
str(d,dstr);
str(y,ystr);
if length(mstr) < 2 then mstr := '0'+mstr;
if length(dstr) < 2 then dstr := '0'+dstr;
if length(ystr) < 2 then ystr := '0'+ystr;
datestr := mstr+'/'+dstr+'/'+ystr
end;
end. |
unit VCLBackup;
interface
uses
BackupInterfaces, Classes, SysUtils;
procedure RegisterBackup;
type
TStringListBackupAgent =
class( TBackupAgent )
public
class procedure Write( Stream : IBackupWriter; Obj : TObject ); override;
class procedure Read ( Stream : IBackupReader; Obj : TObject ); override;
end;
implementation
class procedure TStringListBackupAgent.Write( Stream : IBackupWriter; Obj : TObject );
var
List : TStringList;
i : integer;
begin
List := TStringList(Obj);
Stream.WriteInteger( 'Count', List.Count );
for i := 0 to pred(List.Count) do
Stream.WriteString( 'Item.' + IntToStr(i), List[i] );
end;
class procedure TStringListBackupAgent.Read( Stream : IBackupReader; Obj : TObject );
var
count : integer;
List : TStringList;
i : integer;
str : string;
begin
count := Stream.ReadInteger( 'Count', 0 );
List := TStringList(Obj);
for i := 0 to pred(count) do
begin
str := Stream.ReadString( 'Item.' + IntToStr(i), '' );
List.Add( str );
end;
end;
procedure RegisterBackup;
begin
TStringListBackupAgent.Register( [TStringList] );
end;
end.
|
unit Bird.Socket.Helpers;
interface
uses IdIOHandler, IdGlobal, System.SysUtils, System.JSON;
type
TIdIOHandlerHelper = class helper for TIdIOHandler
private
function GetHandShaked: Boolean;
function ReadBytes: TArray<byte>;
procedure Send(const ARawData: TArray<byte>); overload;
procedure SetHandShaked(const AValue: Boolean);
public
property HandShaked: Boolean read GetHandShaked write SetHandShaked;
function ReadString: string;
procedure Send(const AMessage: string); overload;
procedure Send(const ACode: Integer; const AMessage: string); overload;
procedure Send(const ACode: Integer; const AMessage: string; const AValues: array of const); overload;
procedure Send(const AJSONObject: TJSONObject; const AOwns: Boolean = True); overload;
procedure SendFile(const AFile: string); overload;
end;
implementation
function TIdIOHandlerHelper.GetHandShaked: Boolean;
begin
Result := Boolean(Self.Tag);
end;
function TIdIOHandlerHelper.ReadBytes: TArray<byte>;
var
LByte: Byte;
LBytes: array [0..7] of byte;
I, LDecodedSize: int64;
LMask: array [0..3] of byte;
begin
try
if ReadByte = $81 then
begin
LByte := ReadByte;
case LByte of
$FE:
begin
LBytes[1] := ReadByte; LBytes[0] := ReadByte;
LBytes[2] := 0; LBytes[3] := 0; LBytes[4] := 0; LBytes[5] := 0; LBytes[6] := 0; LBytes[7] := 0;
LDecodedSize := Int64(LBytes);
end;
$FF:
begin
LBytes[7] := ReadByte; LBytes[6] := ReadByte; LBytes[5] := ReadByte; LBytes[4] := ReadByte;
LBytes[3] := ReadByte; LBytes[2] := ReadByte; LBytes[1] := ReadByte; LBytes[0] := ReadByte;
LDecodedSize := Int64(LBytes);
end;
else
LDecodedSize := LByte - 128;
end;
LMask[0] := ReadByte; LMask[1] := ReadByte; LMask[2] := ReadByte; LMask[3] := ReadByte;
if LDecodedSize < 1 then
begin
Result := [];
Exit;
end;
SetLength(result, LDecodedSize);
inherited ReadBytes(TIdBytes(result), LDecodedSize, False);
for I := 0 to LDecodedSize - 1 do
Result[I] := Result[I] xor LMask[I mod 4];
end;
except
end;
end;
function TIdIOHandlerHelper.ReadString: string;
begin
Result := IndyTextEncoding_UTF8.GetString(TIdBytes(ReadBytes));
end;
procedure TIdIOHandlerHelper.Send(const ACode: Integer; const AMessage: string);
begin
Self.Send(TJSONObject.Create.AddPair('code', TJSONNumber.Create(ACode)).AddPair('message', AMessage));
end;
procedure TIdIOHandlerHelper.Send(const ACode: Integer; const AMessage: string; const AValues: array of const);
begin
Self.Send(ACode, Format(AMessage, AValues));
end;
procedure TIdIOHandlerHelper.Send(const AJSONObject: TJSONObject; const AOwns: Boolean);
begin
try
Self.Send(AJSONObject.ToString);
finally
if AOwns then
AJSONObject.Free;
end;
end;
procedure TIdIOHandlerHelper.SendFile(const AFile: string);
begin
WriteFile(AFile, True);
end;
procedure TIdIOHandlerHelper.SetHandShaked(const AValue: Boolean);
begin
Self.Tag := Ord(AValue);
end;
procedure TIdIOHandlerHelper.Send(const ARawData: TArray<byte>);
var
LBytes: TArray<Byte>;
begin
LBytes := [$81];
if Length(ARawData) <= 125 then
LBytes := LBytes + [Length(ARawData)]
else if (Length(ARawData) >= 126) and (Length(ARawData) <= 65535) then
LBytes := LBytes + [126, (Length(ARawData) shr 8) and 255, Length(ARawData) and 255]
else
LBytes := LBytes + [127, (int64(Length(ARawData)) shr 56) and 255, (int64(Length(ARawData)) shr 48) and 255,
(int64(Length(ARawData)) shr 40) and 255, (int64(Length(ARawData)) shr 32) and 255,
(Length(ARawData) shr 24) and 255, (Length(ARawData) shr 16) and 255, (Length(ARawData) shr 8) and 255, Length(ARawData) and 255];
LBytes := LBytes + ARawData;
try
Write(TIdBytes(LBytes), Length(LBytes));
except
end;
end;
procedure TIdIOHandlerHelper.Send(const AMessage: string);
begin
Self.Send(TArray<Byte>(IndyTextEncoding_UTF8.GetBytes(AMessage)));
end;
end.
|
unit pgTableModifier;
// Модуль: "w:\common\components\rtl\Garant\PG\pgTableModifier.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TpgTableModifier" MUID: (564B212F02DA)
{$Include w:\common\components\rtl\Garant\PG\pgDefine.inc}
interface
{$If Defined(UsePostgres)}
uses
l3IntfUses
, l3ProtoObject
, daParamList
, daInterfaces
, pgConnection
, daTypes
, LibPQ
;
type
TpgTableModifier = class(Tl3ProtoObject)
private
f_Params: TdaParamList;
f_DataConverter: IdaDataConverter;
f_InsertName: AnsiString;
f_Connection: TpgConnection;
f_TableID: TdaTables;
f_UpdateName: AnsiString;
f_DeleteName: AnsiString;
f_OldParams: TdaParamList;
private
procedure BuildSQLAndFillParams(aTableID: TdaTables;
out anInsertSQL: AnsiString;
out anUpdateSQL: AnsiString;
out aDeleteSQL: AnsiString;
aParams: TdaParamList;
anOldParams: TdaParamList;
out anUpdateParamTypes: TPQOIDArray);
procedure PrepareSQL(aTableID: TdaTables);
procedure UnPrepareSQL;
procedure PrepareSubQuery(const aName: AnsiString;
const aSQL: AnsiString;
aParamsCount: Integer;
const anOIDArray: TPQOIDArray = nil);
procedure UnPrepareSubQuery(var aName: AnsiString);
protected
function pm_GetParams(const Name: AnsiString): IdaParam;
function pm_GetOldParams(const aName: AnsiString): IdaParam; virtual;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aTableID: TdaTables;
aConnection: TpgConnection;
const aDataConverter: IdaDataConverter); reintroduce;
procedure Insert;
function BeginTransaction: Boolean;
procedure CommitTransaction;
procedure RollBackTransaction;
procedure Update;
procedure Delete;
public
property Params[const Name: AnsiString]: IdaParam
read pm_GetParams;
property OldParams[const aName: AnsiString]: IdaParam
read pm_GetOldParams;
end;//TpgTableModifier
{$IfEnd} // Defined(UsePostgres)
implementation
{$If Defined(UsePostgres)}
uses
l3ImplUses
, SysUtils
, pgUtils
, pgInterfaces
, daScheme
, daParam
, daFieldParamDescription
, l3MinMax
//#UC START# *564B212F02DAimpl_uses*
//#UC END# *564B212F02DAimpl_uses*
;
function TpgTableModifier.pm_GetParams(const Name: AnsiString): IdaParam;
//#UC START# *564C2778019B_564B212F02DAget_var*
var
l_IDX: Integer;
//#UC END# *564C2778019B_564B212F02DAget_var*
begin
//#UC START# *564C2778019B_564B212F02DAget_impl*
if f_Params.FindData(Name, l_IDX) then
Result := f_Params[l_IDX]
else
Result := nil;
//#UC END# *564C2778019B_564B212F02DAget_impl*
end;//TpgTableModifier.pm_GetParams
function TpgTableModifier.pm_GetOldParams(const aName: AnsiString): IdaParam;
//#UC START# *5774E56501BB_564B212F02DAget_var*
var
l_IDX: Integer;
//#UC END# *5774E56501BB_564B212F02DAget_var*
begin
//#UC START# *5774E56501BB_564B212F02DAget_impl*
if f_OldParams.FindData(aName, l_IDX) then
Result := f_OldParams[l_IDX]
else
Result := nil;
//#UC END# *5774E56501BB_564B212F02DAget_impl*
end;//TpgTableModifier.pm_GetOldParams
constructor TpgTableModifier.Create(aTableID: TdaTables;
aConnection: TpgConnection;
const aDataConverter: IdaDataConverter);
//#UC START# *564C1BDD02FE_564B212F02DA_var*
//#UC END# *564C1BDD02FE_564B212F02DA_var*
begin
//#UC START# *564C1BDD02FE_564B212F02DA_impl*
inherited Create;
f_TableID := aTableID;
f_Params := TdaParamList.Make;
f_OldParams := TdaParamList.Make;
f_DataConverter := aDataConverter;
aConnection.SetRefTo(f_Connection);
PrepareSQL(aTableID);
//#UC END# *564C1BDD02FE_564B212F02DA_impl*
end;//TpgTableModifier.Create
procedure TpgTableModifier.BuildSQLAndFillParams(aTableID: TdaTables;
out anInsertSQL: AnsiString;
out anUpdateSQL: AnsiString;
out aDeleteSQL: AnsiString;
aParams: TdaParamList;
anOldParams: TdaParamList;
out anUpdateParamTypes: TPQOIDArray);
//#UC START# *564C664702D3_564B212F02DA_var*
var
l_Table: IdaTableDescription;
l_InsertFields: AnsiString;
l_Values: AnsiString;
l_UpdateFields: AnsiString;
l_UpdateWhereClause: AnsiString;
l_DeleteWhereClause: AnsiString;
l_ParamIDX: Integer;
l_OldParamIDX: Integer;
l_HasPrimaryKey: Boolean;
l_PrimaryKeyCount: Integer;
function lp_HasPrimaryKey(const anItem: IdaFieldDescription): Boolean;
begin
if anItem.IsPrimaryKey then
begin
l_HasPrimaryKey := True;
l_PrimaryKeyCount := l_PrimaryKeyCount + 1;
end;
Result := True;
end;
function DoBuild(const anItem: IdaFieldDescription): Boolean;
begin
Result := True;
if l_InsertFields <> '' then
l_InsertFields := l_InsertFields + ', ';
if l_Values <> '' then
l_Values := l_Values + ', ';
l_InsertFields := l_InsertFields + anItem.SQLName;
l_Values := l_Values + Format('$%d', [l_ParamIDX]);
if not anItem.IsPrimaryKey then
begin
if l_UpdateFields <> '' then
l_UpdateFields := l_UpdateFields + ','#13#10;
l_UpdateFields := Format('%s%s = $%d', [l_UpdateFields, anItem.SQLName, l_ParamIDX]);
anUpdateParamTypes[l_ParamIDX - 1] := 0;
end
else
anUpdateParamTypes[l_ParamIDX - 1] := 1043;
if anItem.IsPrimaryKey or not l_HasPrimaryKey then
begin
if l_UpdateWhereClause <> '' then
l_UpdateWhereClause := l_UpdateWhereClause + ' AND ';
l_UpdateWhereClause := Format('%s(%s = $%d)', [l_UpdateWhereClause, anItem.SQLName, l_Table.FieldsCount + l_OldParamIDX]);
if l_DeleteWhereClause <> '' then
l_DeleteWhereClause := l_DeleteWhereClause + ' AND ';
l_DeleteWhereClause := Format('%s(%s = $%d)', [l_DeleteWhereClause, anItem.SQLName, l_OldParamIDX]);
Inc(l_OldParamIDX);
anOldParams.Add(TdaParam.Make(f_DataConverter, TdaFieldParamDescription.Make(anItem)));
end;
Inc(l_ParamIDX);
aParams.Add(TdaParam.Make(f_DataConverter, TdaFieldParamDescription.Make(anItem)));
end;
//#UC END# *564C664702D3_564B212F02DA_var*
begin
//#UC START# *564C664702D3_564B212F02DA_impl*
aParams.Clear;
l_InsertFields := '';
l_Values := '';
l_UpdateFields := '';
l_UpdateWhereClause := '';
l_DeleteWhereClause := '';
l_ParamIDX := 1;
l_OldParamIDX := 1;
l_Table := TdaScheme.Instance.Table(aTableID);
l_HasPrimaryKey := False;
l_PrimaryKeyCount := 0;
l_Table.IterateFieldsF(L2DaTableDescriptionIteratorIterateFieldsFAction(@lp_HasPrimaryKey));
if not l_HasPrimaryKey then
l_PrimaryKeyCount := l_Table.FieldsCount;
SetLength(anUpdateParamTypes, l_Table.FieldsCount + l_PrimaryKeyCount);
FillChar(anUpdateParamTypes[0], SizeOf(anUpdateParamTypes[0]) * Length(anUpdateParamTypes), 0);
l_Table.IterateFieldsF(L2DaTableDescriptionIteratorIterateFieldsFAction(@DoBuild));
anInsertSQL := Format('INSERT INTO %s.%s (%s)'#13#10'VALUES'#13#10'(%s);', [TdaScheme.Instance.CheckScheme(l_Table.Scheme), l_Table.SQLName, l_InsertFields, l_Values]);
if l_UpdateFields = '' then
anUpdateSQL := ''
else
anUpdateSQL := Format('UPDATE %s.%s '#13#10'SET %s'#13#10'WHERE %s;', [TdaScheme.Instance.CheckScheme(l_Table.Scheme), l_Table.SQLName, l_UpdateFields, l_UpdateWhereClause]);
aDeleteSQL := Format('DELETE FROM %s.%s '#13#10'WHERE %s;', [TdaScheme.Instance.CheckScheme(l_Table.Scheme), l_Table.SQLName, l_DeleteWhereClause]);
//#UC END# *564C664702D3_564B212F02DA_impl*
end;//TpgTableModifier.BuildSQLAndFillParams
procedure TpgTableModifier.PrepareSQL(aTableID: TdaTables);
//#UC START# *564C66AF0221_564B212F02DA_var*
var
l_InsertSQL: AnsiString;
l_UpdateSQL: AnsiString;
l_DeleteSQL: AnsiString;
l_OIDArray: TPQOidArray;
//#UC END# *564C66AF0221_564B212F02DA_var*
begin
//#UC START# *564C66AF0221_564B212F02DA_impl*
f_InsertName := Format('Ins%p', [Pointer(Self)]);
f_UpdateName := Format('Upd%p', [Pointer(Self)]);
f_DeleteName := Format('Del%p', [Pointer(Self)]);
BuildSQLAndFillParams(aTableID, l_InsertSQL, l_UpdateSQL, l_DeleteSQL, f_Params, f_OldParams, l_OIDArray);
PrepareSubQuery(f_InsertName, l_InsertSQL, f_Params.Count);
if l_UpdateSQL = '' then
f_UpdateName := ''
else
PrepareSubQuery(f_UpdateName, l_UpdateSQL, f_Params.Count + f_OldParams.Count, l_OIDArray);
PrepareSubQuery(f_DeleteName, l_DeleteSQL, f_OldParams.Count);
//#UC END# *564C66AF0221_564B212F02DA_impl*
end;//TpgTableModifier.PrepareSQL
procedure TpgTableModifier.UnPrepareSQL;
//#UC START# *564C66BE013F_564B212F02DA_var*
//#UC END# *564C66BE013F_564B212F02DA_var*
begin
//#UC START# *564C66BE013F_564B212F02DA_impl*
UnPrepareSubQuery(f_InsertName);
if f_UpdateName <> '' then
UnPrepareSubQuery(f_UpdateName);
UnPrepareSubQuery(f_DeleteName);
//#UC END# *564C66BE013F_564B212F02DA_impl*
end;//TpgTableModifier.UnPrepareSQL
procedure TpgTableModifier.PrepareSubQuery(const aName: AnsiString;
const aSQL: AnsiString;
aParamsCount: Integer;
const anOIDArray: TPQOIDArray = nil);
//#UC START# *5774E86500B0_564B212F02DA_var*
var
l_Result: PPGResult;
//#UC END# *5774E86500B0_564B212F02DA_var*
begin
//#UC START# *5774E86500B0_564B212F02DA_impl*
if anOIDArray = nil then
l_Result := PQprepare(f_Connection.Handle, PAnsiChar(aName), PAnsiChar(aSQL), aParamsCount, nil)
else
l_Result := PQprepare(f_Connection.Handle, PAnsiChar(aName), PAnsiChar(aSQL), aParamsCount, @anOIDArray[0]);
try
pgCheckStatus(l_Result);
finally
PQclear(l_Result);
end;
//#UC END# *5774E86500B0_564B212F02DA_impl*
end;//TpgTableModifier.PrepareSubQuery
procedure TpgTableModifier.UnPrepareSubQuery(var aName: AnsiString);
//#UC START# *5774E8C20370_564B212F02DA_var*
var
l_Result: PPGResult;
//#UC END# *5774E8C20370_564B212F02DA_var*
begin
//#UC START# *5774E8C20370_564B212F02DA_impl*
Assert(aName <> '');
l_Result := PQExec(f_Connection.Handle, PAnsiChar(Format('DEALLOCATE PREPARE "%s"', [aName])));
try
aName := '';
pgCheckStatus(l_Result);
finally
PQClear(l_Result);
end;
//#UC END# *5774E8C20370_564B212F02DA_impl*
end;//TpgTableModifier.UnPrepareSubQuery
procedure TpgTableModifier.Insert;
//#UC START# *564C58CD016F_564B212F02DA_var*
var
l_ParamsValue: array of AnsiString;
l_ParamsValuePtr: TPQparamValues;
l_Result: PPGResult;
l_IDX: Integer;
//#UC END# *564C58CD016F_564B212F02DA_var*
begin
//#UC START# *564C58CD016F_564B212F02DA_impl*
SetLength(l_ParamsValue, f_Params.Count);
SetLength(l_ParamsValuePtr, f_Params.Count);
for l_IDX := 0 to f_Params.Count - 1 do
begin
l_ParamsValue[l_IDX] := f_Params[l_IDX].AsString;
l_ParamsValuePtr[l_IDX] := PAnsiChar(l_ParamsValue[l_IDX]);
end;
l_Result := PQexecPrepared(f_Connection.Handle, PAnsiChar(f_InsertName), f_Params.Count, l_ParamsValuePtr, nil, 0, 0);
try
if not (PQresultStatus(l_Result) in [PGRES_COMMAND_OK]) then
raise EpgError.Create(PQresultErrorMessage(l_Result));
finally
PQclear(l_Result);
end;
//#UC END# *564C58CD016F_564B212F02DA_impl*
end;//TpgTableModifier.Insert
function TpgTableModifier.BeginTransaction: Boolean;
//#UC START# *565C36A402A0_564B212F02DA_var*
//#UC END# *565C36A402A0_564B212F02DA_var*
begin
//#UC START# *565C36A402A0_564B212F02DA_impl*
Result := f_Connection.BeginTransaction([f_TableID]);
//#UC END# *565C36A402A0_564B212F02DA_impl*
end;//TpgTableModifier.BeginTransaction
procedure TpgTableModifier.CommitTransaction;
//#UC START# *565C36BF0228_564B212F02DA_var*
//#UC END# *565C36BF0228_564B212F02DA_var*
begin
//#UC START# *565C36BF0228_564B212F02DA_impl*
f_Connection.CommitTransaction;
//#UC END# *565C36BF0228_564B212F02DA_impl*
end;//TpgTableModifier.CommitTransaction
procedure TpgTableModifier.RollBackTransaction;
//#UC START# *565C36CE0339_564B212F02DA_var*
//#UC END# *565C36CE0339_564B212F02DA_var*
begin
//#UC START# *565C36CE0339_564B212F02DA_impl*
f_Connection.RollBackTransaction;
//#UC END# *565C36CE0339_564B212F02DA_impl*
end;//TpgTableModifier.RollBackTransaction
procedure TpgTableModifier.Update;
//#UC START# *5774E4090377_564B212F02DA_var*
var
l_ParamsValue: array of AnsiString;
l_ParamsValuePtr: TPQparamValues;
l_Result: PPGResult;
l_IDX: Integer;
//#UC END# *5774E4090377_564B212F02DA_var*
begin
//#UC START# *5774E4090377_564B212F02DA_impl*
Assert(f_UpdateName <> '');
SetLength(l_ParamsValue, f_Params.Count + f_OldParams.Count);
SetLength(l_ParamsValuePtr, f_Params.Count + f_OldParams.Count);
for l_IDX := 0 to f_Params.Count - 1 do
begin
l_ParamsValue[l_IDX] := f_Params[l_IDX].AsString;
l_ParamsValuePtr[l_IDX] := PAnsiChar(l_ParamsValue[l_IDX]);
end;
for l_IDX := 0 to f_OldParams.Count - 1 do
begin
l_ParamsValue[f_Params.Count + l_IDX] := f_OldParams[l_IDX].AsString;
l_ParamsValuePtr[f_Params.Count + l_IDX] := PAnsiChar(l_ParamsValue[f_Params.Count + l_IDX]);
end;
l_Result := PQexecPrepared(f_Connection.Handle, PAnsiChar(f_UpdateName), f_Params.Count + f_OldParams.Count, l_ParamsValuePtr, nil, 0, 0);
try
if not (PQresultStatus(l_Result) in [PGRES_COMMAND_OK]) then
raise EpgError.Create(PQresultErrorMessage(l_Result));
finally
PQclear(l_Result);
end;
//#UC END# *5774E4090377_564B212F02DA_impl*
end;//TpgTableModifier.Update
procedure TpgTableModifier.Delete;
//#UC START# *5774E4160259_564B212F02DA_var*
var
l_ParamsValue: array of AnsiString;
l_ParamsValuePtr: TPQparamValues;
l_Result: PPGResult;
l_IDX: Integer;
//#UC END# *5774E4160259_564B212F02DA_var*
begin
//#UC START# *5774E4160259_564B212F02DA_impl*
SetLength(l_ParamsValue, f_OldParams.Count);
SetLength(l_ParamsValuePtr, f_OldParams.Count);
for l_IDX := 0 to f_OldParams.Count - 1 do
begin
l_ParamsValue[l_IDX] := f_OldParams[l_IDX].AsString;
l_ParamsValuePtr[l_IDX] := PAnsiChar(l_ParamsValue[l_IDX]);
end;
l_Result := PQexecPrepared(f_Connection.Handle, PAnsiChar(f_DeleteName), f_OldParams.Count, l_ParamsValuePtr, nil, 0, 0);
try
if not (PQresultStatus(l_Result) in [PGRES_COMMAND_OK]) then
raise EpgError.Create(PQresultErrorMessage(l_Result));
finally
PQclear(l_Result);
end;
//#UC END# *5774E4160259_564B212F02DA_impl*
end;//TpgTableModifier.Delete
procedure TpgTableModifier.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_564B212F02DA_var*
//#UC END# *479731C50290_564B212F02DA_var*
begin
//#UC START# *479731C50290_564B212F02DA_impl*
UnPrepareSQL;
FreeAndNil(f_Params);
FreeAndNil(f_OldParams);
f_DataConverter := nil;
FreeAndNil(f_Connection);
inherited;
//#UC END# *479731C50290_564B212F02DA_impl*
end;//TpgTableModifier.Cleanup
{$IfEnd} // Defined(UsePostgres)
end.
|
unit BaiduMapAPI.NaviService.Android;
//author:Xubzhlin
//Email:371889755@qq.com
//百度地图API 安卓导航服务 单元
//官方链接:http://lbsyun.baidu.com/
//TAndroidBaiduMapNaviService 百度地图 安卓导航服务
interface
uses
System.Classes, BaiduMapAPI.NaviService, Androidapi.JNI.baidu.navisdk, Androidapi.JNI.JavaTypes,
Androidapi.JNIBridge, Androidapi.JNI.Os, BaiduMapAPI.NaviService.CommTypes,
Androidapi.JNI.Embarcadero, Androidapi.JNI.GraphicsContentViewText;
type
TAndroidBaiduMapNaviService = class;
TNaviManager_BaseListerer = class(TJavaLocal)
private
[weak]FNaviService:TAndroidBaiduMapNaviService;
public
constructor Create(NaviService:TAndroidBaiduMapNaviService);
end;
TNaviManager_NaviInitListener = class(TNaviManager_BaseListerer, JBaiduNaviManager_NaviInitListener)
public
procedure onAuthResult(P1: Integer; P2: JString); cdecl;
procedure initStart; cdecl;
procedure initSuccess; cdecl;
procedure initFailed; cdecl;
end;
TNaviManager_RoutePlanListener = class(TNaviManager_BaseListerer, JBaiduNaviManager_RoutePlanListener)
public
procedure onJumpToNavigator; cdecl;
procedure onRoutePlanFailed; cdecl;
end;
TJBNRouteGuideManager_OnNavigationListener = class(TNaviManager_BaseListerer, JBNRouteGuideManager_OnNavigationListener)
public
procedure onNaviGuideEnd; cdecl;
procedure notifyOtherAction(P1: Integer; P2: Integer; P3: Integer; P4: JObject); cdecl;
end;
TAndroidBaiduMapNaviService = class(TBaiduMapNaviService)
private
FSDCardPath:JString;
FNaviManager:JBaiduNaviManager;
FJNativeLayout:JNativeLayout;
FView:JView;
FNaviInitListener:TNaviManager_NaviInitListener;
FRoutePlanListener:TNaviManager_RoutePlanListener;
FNavigationListener:TJBNRouteGuideManager_OnNavigationListener;
function DoinitDirs:Boolean;
procedure DoJumpToNavigator;
procedure RealignView;
procedure DoInitTTS;
procedure DoInitNaviManager;
protected
procedure DoinitService; override;
procedure DostartNaviRoutePlan(RoutePlan:TBNRoutePlanNodes); override;
procedure DoSetVisible(const Value: Boolean); override;
procedure DoUpdateBaiduNaviFromControl; override;
end;
implementation
uses
Androidapi.Helpers, FMX.Helpers.Android, Androidapi.IOUtils, Androidapi.JNI.Os.Environment,
FMX.Platform.Android, FMX.Forms, System.Types, FMX.CallUIThread.Helper.Android;
{ TAndroidBaiduMapNaviService }
function TAndroidBaiduMapNaviService.DoinitDirs:Boolean;
var
F:JFile;
begin
Result:=False;
if TJEnvironment.JavaClass.getExternalStorageState.equalsIgnoreCase(TJEnvironment.JavaClass.MEDIA_MOUNTED) then
FSDCardPath:=TJEnvironment.JavaClass.getExternalStorageDirectory.toString;
if FSDCardPath<>nil then
begin
F:=TJFile.JavaClass.init(FSDCardPath, SharedActivityContext.getPackageName);
if not F.exists then
begin
try
F.mkdir;
Result:=True;
except
end;
end
else
Result:=True;
end;
end;
procedure TAndroidBaiduMapNaviService.DoinitService;
var
PM:JPackageManager;
SDK_INT:Integer;
permissions: TJavaObjectArray<JString>;
begin
if DoinitDirs then
begin
SDK_INT:=TJBuild_VERSION.JavaClass.SDK_INT;
if TJBuild_VERSION.JavaClass.SDK_INT>=23 then
begin
permissions:= TJavaObjectArray<JString>.Create(1);
permissions.Items[0]:=StringToJString('Manifest.permission.WRITE_EXTERNAL_STORAGE');
PM:=SharedActivity.getPackageManager;
if PM.checkPermission(permissions.Items[0], SharedActivity.getPackageName)
<> TJPackageManager.JavaClass.PERMISSION_GRANTED then
SharedActivity.requestPermissions(permissions, 1);
permissions.Items[0]:=StringToJString('Manifest.permission.ACCESS_FINE_LOCATION');
PM:=SharedActivity.getPackageManager;
if PM.checkPermission(permissions.Items[0], SharedActivity.getPackageName)
<> TJPackageManager.JavaClass.PERMISSION_GRANTED then
SharedActivity.requestPermissions(permissions, 1);
end;
//
CallInUIThreadAndWaitFinishingFix(DoInitNaviManager)
end;
end;
procedure TAndroidBaiduMapNaviService.DoInitTTS;
var
bundle:JBundle;
begin
bundle:=TJBundle.JavaClass.init;
bundle.putString(TJBNCommonSettingParam.JavaClass.TTS_APP_ID, StringToJString(TTSKey));
TJBNaviSettingManager.JavaClass.setNaviSdkParam(bundle);
end;
procedure TAndroidBaiduMapNaviService.DoInitNaviManager;
begin
DoInitTTS;
if FNaviManager = nil then
FNaviManager:=TJBaiduNaviManager.JavaClass.getInstance;
if FNaviInitListener = nil then
FNaviInitListener := TNaviManager_NaviInitListener.Create(Self);
//使用默认TTS 不设置 自定义TTS回调
FNaviManager.init(SharedActivity, FSDCardPath, SharedActivityContext.getPackageName, FNaviInitListener, nil);
end;
procedure TAndroidBaiduMapNaviService.DoJumpToNavigator;
begin
//设置途径点以及resetEndNode会回调该接口
CallInUIThread(
procedure
begin
if FNavigationListener = nil then
FNavigationListener:=TJBNRouteGuideManager_OnNavigationListener.Create(Self);
if FView = nil then
FView:=TJBNRouteGuideManager.JavaClass.getInstance.onCreate(SharedActivity, FNavigationListener);
FJNativeLayout := TJNativeLayout.JavaClass.init(SharedActivity,
MainActivity.getWindow.getDecorView.getWindowToken);
FJNativeLayout.setPosition(0, 0);
FJNativeLayout.setSize(Round(Screen.Height), Round(Screen.Width));
FJNativeLayout.setControl(FView);
RealignView;
//View.bringToFront;
//MainActivity.setContentView(View);
end);
end;
procedure TAndroidBaiduMapNaviService.DoSetVisible(const Value: Boolean);
begin
if FView = nil then exit;
CallInUIThread(procedure
begin
if Value then
TJBNRouteGuideManager.JavaClass.getInstance.onStart
else
TJBNRouteGuideManager.JavaClass.getInstance.onStop;
end);
end;
procedure TAndroidBaiduMapNaviService.DostartNaviRoutePlan(RoutePlan:TBNRoutePlanNodes);
var
List:JArrayList;
Node:JBNRoutePlanNode;
i: Integer;
b:Boolean;
begin
//List:=TJList.Wrap((TJArrayList.JavaClass.Init as ILocalObject).GetObjectID);
List:=TJArrayList.JavaClass.Init;
for i := 0 to Length(RoutePlan) - 1 do
begin
//默认使用 TJBNRoutePlanNode_CoordinateType.JavaClass.BD09LL 坐标系
Node:= TJBNRoutePlanNode.JavaClass.init(RoutePlan[i].location.Longitude, RoutePlan[i].location.Latitude,
StringToJString(RoutePlan[i].name), StringToJString(RoutePlan[i].description), TJBNRoutePlanNode_CoordinateType.JavaClass.BD09LL);
List.add(Node);
end;
if FRoutePlanListener = nil then
FRoutePlanListener:=TNaviManager_RoutePlanListener.Create(Self);
b := TJBaiduNaviManager.JavaClass.isNaviInited;
b := TJBaiduNaviManager.JavaClass.isNaviSoLoadSuccess;
b:=FNaviManager.launchNavigator(SharedActivity, JList(List), 1, True, FRoutePlanListener);
end;
procedure TAndroidBaiduMapNaviService.DoUpdateBaiduNaviFromControl;
begin
CallInUiThread(RealignView);
end;
procedure TAndroidBaiduMapNaviService.RealignView;
const
MapExtraSpace = 100;
// To be sure that destination rect will fit to fullscreen
var
MapRect: TRectF;
RoundedRect: TRect;
LSizeF: TPointF;
LRealBounds: TRectF;
LRealPosition, LRealSize: TPointF;
begin
if (FJNativeLayout <> nil) then
begin
//全屏
LRealPosition := TPointF.Zero;
LSizeF := TPointF.Create(screen.Size.cx, screen.Size.cy);
LRealSize := LSizeF * Scale;
LRealBounds := TRectF.Create(LRealPosition, LRealSize);
MapRect := TRectF.Create(0, 0, Screen.Width * MapExtraSpace,
Screen.Height * MapExtraSpace);
RoundedRect := MapRect.FitInto(LRealBounds).Round;
if FView=nil then
RoundedRect.Left := Round(Screen.Size.cx * Scale);
FJNativeLayout.setPosition(RoundedRect.TopLeft.X, RoundedRect.TopLeft.Y);
FJNativeLayout.setSize(RoundedRect.Width, RoundedRect.Height);
end;
end;
{ TNaviManager_NavEventLister }
procedure TNaviManager_NaviInitListener.initFailed;
begin
//初始化失败
end;
procedure TNaviManager_NaviInitListener.initStart;
begin
//初始化开始
end;
procedure TNaviManager_NaviInitListener.initSuccess;
begin
//初始化成功
end;
procedure TNaviManager_NaviInitListener.onAuthResult(P1: Integer; P2: JString);
begin
// key 校验 P1 = 0 校验成功 其他校验失败
end;
{ TNaviManager_BaseListerer }
constructor TNaviManager_BaseListerer.Create(
NaviService: TAndroidBaiduMapNaviService);
begin
inherited Create;
FNaviService:=NaviService;
end;
{ TNaviManager_RoutePlanListener }
procedure TNaviManager_RoutePlanListener.onJumpToNavigator;
begin
if (FNaviService<>nil) then
FNaviService.DoJumpToNavigator;
end;
procedure TNaviManager_RoutePlanListener.onRoutePlanFailed;
begin
//算路失败
end;
{ TJBNRouteGuideManager_OnNavigationListener }
procedure TJBNRouteGuideManager_OnNavigationListener.notifyOtherAction(P1, P2,
P3: Integer; P4: JObject);
begin
end;
procedure TJBNRouteGuideManager_OnNavigationListener.onNaviGuideEnd;
begin
TJBNRouteGuideManager.JavaClass.getInstance.onStop;
TJBNRouteGuideManager.JavaClass.getInstance.onDestroy;
FNaviService.FView:=nil;
CallInUIThread(FNaviService.RealignView);
end;
end.
|
unit uicombo;
interface
uses ui, uimpl, uihandle, uicomp, uiform, uilist, datastorage;
type
TWinPopupListForm=class(TWinModal)
private
wItems:TWinList;
protected
public
constructor Create(Owner:TWinHandle);override;
procedure CreatePerform;override;
procedure Show(nCmdShow:integer = SW_SHOWNORMAL);override;
end;
TWinCombo=class(TWinComp)
private
ComboList:TWinPopupListForm;
protected
procedure ListSelected(Sender:TWinHandle);
function GetItems:TStringListEx;
function GetSelected:integer;
procedure SetSelected(AValue:integer);
public
constructor Create(Owner:TWinHandle);override;
procedure CustomPaint;override;
procedure CreatePerform;override;
procedure MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override;
procedure KillFocusPerform(handle:HWND);override;
property Items:TStringListEx read GetItems;
property Selected:integer read GetSelected write SetSelected;
end;
implementation
constructor TWinPopupListForm.Create(Owner:TWinHandle);
begin
inherited;
CreatePopupStyle;
end;
procedure TWinPopupListForm.CreatePerform;
begin
inherited;
wItems:=TWinList.Create(self);
wItems.SetBounds(0,0,10,10);
wItems.Align:=alClient;
wItems.CreatePerform;
end;
procedure TWinPopupListForm.Show(nCmdShow:integer = SW_SHOWNORMAL);
begin
inherited;
end;
constructor TWinCombo.Create(Owner:TWinHandle);
begin
inherited;
ComboList:=TWinPopupListForm.Create(self);
end;
procedure TWinCombo.CustomPaint;
var r:trect;
begin
r:=GetClientRect;
BeginPaint;
Polygon(color, bkcolor, r.Left, r.Top, r.Right-1, r.Bottom-1);
r.Left:=r.Left+2;
DrawText(r, text, font, color, bkcolor, TRANSPARENT, DT_SINGLELINE or DT_LEFT or DT_VCENTER or DT_NOPREFIX);
EndPaint;
end;
procedure TWinCombo.CreatePerform;
begin
inherited;
ComboList.SetBounds(50,50,300,300);
ComboList.CreatePerform;
ComboList.wItems.OnSelected:=ListSelected;
end;
function TWinCombo.GetItems:TStringListEx;
begin
result:=Combolist.wItems.Items;
end;
function TWinCombo.GetSelected:integer;
begin
result:=Combolist.wItems.Selected
end;
procedure TWinCombo.SetSelected(AValue:integer);
begin
Combolist.wItems.Selected:=AValue
end;
procedure TWinCombo.MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);
var p:TPoint;
begin
inherited;
if AButton=mbLeft
then begin
p.x:=0;
p.y:=0;
GetCursorPos(p);
ComboList.SetBounds(p.x-x,p.y-y+height,width,150);
ComboList.SetPosPerform;
ComboList.SizePerform;
combolist.Show;
end
end;
procedure TWinCombo.KillFocusPerform(handle:HWND);
begin
inherited;
if (ComboList<>nil)and(handle<>ComboList.Window)
and(ComboList.wItems<>nil)and(handle<>ComboList.wItems.Window)
then begin
ComboList.hide;
end;
end;
procedure TWinCombo.ListSelected(Sender:TWinHandle);
var L:TWinList;
begin
L:=TWinList(Sender);
text:=L.Items[L.Selected];
RedrawPerform;
ComboList.hide;
// SetFocus;
end;
end.
|
unit Progress;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Utils, StdCtrls, ComCtrls, ExtCtrls;
type
TProgressForm = class(TForm)
StepProgressLabel: TLabel;
StepProgressBar: TProgressBar;
OverallProgressLabel: TLabel;
OverallProgressBar: TProgressBar;
CancelButton: TButton;
RunJob: TTimer;
procedure CancelButtonClick(Sender: TObject);
procedure RunJobTimer(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
Language: TLanguage;
Preset: TPreset;
CancelProcess: Boolean;
procedure Run;
public
{ Public declarations }
constructor Create(AOwner: TComponent; const Language: TLanguage;
const Preset: TPreset); reintroduce;
end;
var
ProgressForm: TProgressForm;
implementation
{$R *.dfm}
{ TProgressForm }
constructor TProgressForm.Create(AOwner: TComponent;
const Language: TLanguage; const Preset: TPreset);
begin
inherited Create(AOwner);
Self.Language := Language;
Self.Preset := Preset;
CancelProcess := False;
end;
procedure TProgressForm.CancelButtonClick(Sender: TObject);
begin
CancelProcess := True;
end;
procedure TProgressForm.Run;
begin
end;
procedure TProgressForm.RunJobTimer(Sender: TObject);
begin
RunJob.Enabled := False;
Close;
end;
procedure TProgressForm.FormActivate(Sender: TObject);
begin
RunJob.Enabled := True;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clHttp;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, Windows, SysUtils, Contnrs, WinSock,{$IFDEF DEMO} Forms, clEncoder, clEncryptor, clCertificate, clHtmlParser,{$ENDIF}
{$ELSE}
System.Classes, Winapi.Windows, System.SysUtils, System.Contnrs, Winapi.WinSock,{$IFDEF DEMO} Vcl.Forms, clEncoder, clEncryptor, clCertificate, clHtmlParser,{$ENDIF}
{$ENDIF}
clTcpClient, clTcpClientTls, clSocket, clHttpUtils, clUriUtils, clCookieManager, clHttpHeader,
clHttpRequest, clHttpAuth, clSspiTls, clWUtils, clSocketUtils, clUtils, clHeaderFieldList;
type
EclHttpError = class(EclTcpClientError)
private
FResponseText: string;
public
constructor Create(const AErrorMsg: string; AErrorCode: Integer; const AResponseText: string);
property ResponseText: string read FResponseText;
end;
TclHttpRequestEvent = procedure (Sender: TObject; const AMethod, AUrl: string;
ARequestHeader: TStrings) of object;
TclHttpHeaderEvent = procedure (Sender: TObject; const AMethod, AUrl: string;
AResponseHeader: TStrings; ACookies: TclCookieList; var Cancel: Boolean) of object;
TclHttpResponseEvent = procedure (Sender: TObject; const AMethod, AUrl: string;
AResponseHeader: TStrings; ACookies: TclCookieList) of object;
TclHttpRedirectEvent = procedure (Sender: TObject; ARequestHeader: TStrings;
AStatusCode: Integer; AResponseHeader: TclHttpResponseHeader; AResponseText: TStrings;
var AMethod: string; var CanRedirect, Handled: Boolean) of object;
TclHttpTunnelStatus = (htNone, htConnect, htTunnel);
TclHttp = class(TclTcpClientTls)
private
FCharSet: string;
FUrl: TclUrlParser;
FHttpVersion: TclHttpVersion;
FUserName: string;
FPassword: string;
FStatusCode: Integer;
FStatusText: string;
FUserAgent: string;
FAuthorizationType: TclAuthorizationType;
FKeepConnection: Boolean;
FAllowCaching: Boolean;
FAllowRedirects: Boolean;
FProxySettings: TclHttpProxySettings;
FMaxRedirects: Integer;
FMaxAuthRetries: Integer;
FCookieManager: TclCookieManager;
FOwnCookieManager: TclCookieManager;
FAllowCookies: Boolean;
FAllowCompression: Boolean;
FRequest: TclHttpRequest;
FResponseHeader: TclHttpResponseHeader;
FMethod: string;
FResponseVersion: TclHttpVersion;
FOwnRequest: TclHttpRequest;
FProgressHandled: Boolean;
FResponseCookies: TclCookieList;
FOldProxyServer: string;
FOldProxyPort: Integer;
FSilentHTTP: Boolean;
FAuthorization: string;
FOnSendRequest: TclHttpRequestEvent;
FOnReceiveResponse: TclHttpResponseEvent;
FOnRedirect: TclHttpRedirectEvent;
FOnSendProgress: TclProgressEvent;
FOnReceiveProgress: TclProgressEvent;
FOnReceiveHeader: TclHttpHeaderEvent;
FExpect100Continue: Boolean;
procedure SetHttpVersion(const Value: TclHttpVersion);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
procedure InitConnection(ATunnelStatus: TclHttpTunnelStatus);
procedure PrepareRequestHeader(ATunnelStatus: TclHttpTunnelStatus; ARequestHeader: TStrings; ARequestBody: TStream);
procedure WriteRequestHeader(ATunnelStatus: TclHttpTunnelStatus;
ARequestHeader: TStrings; ARequestBody: TStream);
procedure WriteRequestData(ARequestBody: TStream);
procedure ReadResponseBody(AResponseHeader: TStrings;
AExtraSize: Int64; AExtraData, AResponseBody: TStream);
function ReadResponseHeader(AResponseHeader: TStrings; ARawData: TStream): Boolean;
function GetResponseLength: Int64;
function GetKeepAlive: Boolean;
function GetTunnelStatus: TclHttpTunnelStatus;
function ExtractStatusCode(ABuffer: TclByteArray; var ADataPos: Integer): Integer;
function ExtractStatusText(ABuffer: TclByteArray; var ADataPos: Integer): string;
function ExtractResponseVersion(ABuffer: TclByteArray; var ADataPos: Integer): TclHttpVersion;
function BasicAuthorization(const AUserName, APassword, AuthorizationField: string; ARequestHeader: TStrings): Boolean;
function Authorize(const AUserName, APassword, AuthorizationField: string;
AuthChallenge, ARequestHeader: TStrings; var AStartNewConnection: Boolean): Boolean;
function Redirect(ARequestHeader, AResponseText: TStrings; var AMethod: string): Boolean;
procedure RaiseHttpError(AStatusCode: Integer; AResponseHeader, AResponseText: TStrings);
procedure ReadResponseText(AResponseHeader: TStrings; AExtraSize: Int64; AExtraData: TStream; AResponseText: TStrings);
procedure LoadResponseStream(AResponseText: TStrings; AResponseBody: TStream);
procedure ReadResponseStream(AResponseHeader: TStrings; AExtraSize: Int64; AExtraData, AResponseBody: TStream);
procedure RemoveHeaderTrailer(AHeader: TStrings);
procedure RemoveRequestLine(AHeader: TStrings);
procedure SetUserAgent(const Value: string);
procedure SetAuthorizationType(const Value: TclAuthorizationType);
procedure SetAllowCaching(const Value: Boolean);
procedure SetKeepConnection(const Value: Boolean);
procedure SetAllowRedirects(const Value: Boolean);
procedure SetProxySettings(const Value: TclHttpProxySettings);
procedure SetMaxAuthRetries(const Value: Integer);
procedure SetMaxRedirects(const Value: Integer);
procedure SetAllowCookies(const Value: Boolean);
procedure SetAllowCompression(const Value: Boolean);
function IsUseProxy: Boolean;
procedure ReadCookies(AResponseHeader: TStrings);
procedure SetRequest(const Value: TclHttpRequest);
procedure DoDataSendProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64);
procedure DoDataReceiveProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64);
function GetUserName_: string;
function GetPassword: string;
procedure SetAuthorizationField(const AFieldName, AFieldValue: string; ARequestHeader: TStrings);
function GetResourcePath: string;
procedure InternalSendRequest(const AMethod: string; ARequestHeader: TStrings;
ARequestBody: TStream; AResponseHeader: TStrings; AResponseBody: TStream);
procedure InitProgress(ABytesProceed, ATotalBytes: Int64);
procedure ConnectProxy;
procedure SetCookieManager(const Value: TclCookieManager);
function GetCookieManager: TclCookieManager;
procedure SetRequestCookies(ARequestHeader: TStrings);
procedure SetSilentHTTP(const Value: Boolean);
procedure SetAuthorization(const Value: string);
procedure SetExpect100Continue(const Value: Boolean);
procedure SetCharSet(const Value: string);
protected
function GetResponseCharSet: string;
function GetRequest: TclHttpRequest;
procedure InternalGet(const AUrl: string; ARequest: TclHttpRequest; AResponseHeader: TStrings; ADestination: TStream); virtual;
procedure InternalHead(const AUrl: string; AResponseHeader: TStrings); virtual;
procedure InternalPut(const AUrl, AContentType: string; ASource: TStream; AResponseHeader: TStrings; AResponseBody: TStream); virtual;
procedure InternalPost(const AUrl: string; ARequest: TclHttpRequest; AResponseHeader: TStrings; AResponseBody: TStream); virtual;
procedure InternalDelete(const AUrl: string; AResponseHeader: TStrings; AResponseBody: TStream); virtual;
function GetRedirectMethod(AStatusCode: Integer; const AMethod: string): string; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoDestroy; override;
function GetDefaultPort: Integer; override;
procedure OpenConnection(const AServer: string; APort: Integer); override;
procedure DoSendRequest(const AMethod, AUrl: string; ARequestHeader: TStrings); dynamic;
procedure DoReceiveHeader(const AMethod, AUrl: string;
AResponseHeader: TStrings; ACookies: TclCookieList; var Cancel: Boolean); dynamic;
procedure DoReceiveResponse(const AMethod, AUrl: string;
AResponseHeader: TStrings; ACookies: TclCookieList); dynamic;
procedure DoSendProgress(ABytesProceed, ATotalBytes: Int64); dynamic;
procedure DoReceiveProgress(ABytesProceed, ATotalBytes: Int64); dynamic;
procedure DoRedirect(ARequestHeader: TStrings; AStatusCode: Integer;
AResponseHeader: TclHttpResponseHeader; AResponseText: TStrings;
var AMethod: string; var CanRedirect, Handled: Boolean); dynamic;
public
constructor Create(AOwner: TComponent); override;
procedure SendRequest(const AMethod, AUrl: string; ARequestHeader: TStrings;
ARequestBody: TStream; AResponseHeader: TStrings; AResponseBody: TStream); overload;
procedure SendRequest(const AMethod, AUrl: string;
ARequest: TclHttpRequest; AResponseHeader: TStrings; AResponseBody: TStream); overload;
procedure SendRequest(const AMethod, AUrl: string; ARequestHeader: TStrings;
ARequestBody: TStream; AResponseBody: TStream); overload;
procedure SendRequest(const AMethod, AUrl: string;
ARequest: TclHttpRequest; AResponseBody: TStream); overload;
procedure Get(const AUrl: string; ADestination: TStream); overload;
procedure Get(const AUrl: string; ADestination: TStrings); overload;
procedure Get(const AUrl: string; AResponseHeader: TStrings; AResponseBody: TStream); overload;
procedure Get(const AUrl: string; ARequest: TclHttpRequest; ADestination: TStream); overload;
procedure Get(const AUrl: string; ARequest: TclHttpRequest; ADestination: TStrings); overload;
procedure Get(const AUrl: string; ARequest: TclHttpRequest; AResponseHeader: TStrings; AResponseBody: TStream); overload;
procedure Head(const AUrl: string); overload;
procedure Head(const AUrl: string; AResponseHeader: TStrings); overload;
procedure Put(const AUrl, AContentType: string; ASource: TStream); overload;
procedure Put(const AUrl, AContentType: string; ASource: TStrings); overload;
procedure Put(const AUrl, AContentType: string; ASource, AResponseBody: TStream); overload;
procedure Put(const AUrl, AContentType: string; ASource: TStream; AResponseBody: TStrings); overload;
procedure Put(const AUrl, AContentType: string; ASource, AResponseBody: TStrings); overload;
procedure Put(const AUrl, AContentType: string; ASource: TStream; AResponseHeader: TStrings; AResponseBody: TStrings); overload;
procedure Put(const AUrl: string; ASource: TStream); overload;
procedure Put(const AUrl: string; ASource: TStrings); overload;
procedure Put(const AUrl: string; ASource, AResponseBody: TStream); overload;
procedure Put(const AUrl: string; ASource: TStream; AResponseBody: TStrings); overload;
procedure Put(const AUrl: string; ASource, AResponseBody: TStrings); overload;
procedure Put(const AUrl: string; ASource: TStream; AResponseHeader: TStrings; AResponseBody: TStrings); overload;
procedure Post(const AUrl: string; AResponseBody: TStream); overload;
procedure Post(const AUrl: string; AResponseBody: TStrings); overload;
procedure Post(const AUrl: string; ARequest: TclHttpRequest; AResponseBody: TStream); overload;
procedure Post(const AUrl: string; ARequest: TclHttpRequest; AResponseBody: TStrings); overload;
procedure Post(const AUrl: string; ARequest: TclHttpRequest; AResponseHeader: TStrings; AResponseBody: TStream); overload;
procedure Delete(const AUrl: string); overload;
procedure Delete(const AUrl: string; AResponseHeader: TStrings); overload;
procedure Delete(const AUrl: string; AResponseHeader, AResponseBody: TStrings); overload;
procedure Delete(const AUrl: string; AResponseHeader: TStrings; AResponseBody: TStream); overload;
procedure Delete(const AUrl: string; AResponseBody: TStream); overload;
property Url: TclUrlParser read FUrl;
property StatusCode: Integer read FStatusCode;
property StatusText: string read FStatusText;
property ResponseVersion: TclHttpVersion read FResponseVersion;
property ResponseHeader: TclHttpResponseHeader read FResponseHeader;
property ResponseCookies: TclCookieList read FResponseCookies;
published
property Request: TclHttpRequest read FRequest write SetRequest;
property HttpVersion: TclHttpVersion read FHttpVersion write SetHttpVersion default hvHttp1_1;
property UserName: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property Authorization: string read FAuthorization write SetAuthorization;
property AuthorizationType: TclAuthorizationType read FAuthorizationType write SetAuthorizationType default atAutoDetect;
property UserAgent: string read FUserAgent write SetUserAgent;
property KeepConnection: Boolean read FKeepConnection write SetKeepConnection default True;
property AllowCaching: Boolean read FAllowCaching write SetAllowCaching default True;
property AllowRedirects: Boolean read FAllowRedirects write SetAllowRedirects default True;
property AllowCookies: Boolean read FAllowCookies write SetAllowCookies default True;
property AllowCompression: Boolean read FAllowCompression write SetAllowCompression default True;
property ProxySettings: TclHttpProxySettings read FProxySettings write SetProxySettings;
property MaxRedirects: Integer read FMaxRedirects write SetMaxRedirects default 15;
property MaxAuthRetries: Integer read FMaxAuthRetries write SetMaxAuthRetries default 5;
property CookieManager: TclCookieManager read FCookieManager write SetCookieManager;
property Port default DefaultHttpPort;
property TLSFlags default [tfUseSSL3, tfUseTLS, tfUseTLS11, tfUseTLS12];
property SilentHTTP: Boolean read FSilentHTTP write SetSilentHTTP default False;
property Expect100Continue: Boolean read FExpect100Continue write SetExpect100Continue default False;
property CharSet: string read FCharSet write SetCharSet;
property OnSendRequest: TclHttpRequestEvent read FOnSendRequest write FOnSendRequest;
property OnReceiveHeader: TclHttpHeaderEvent read FOnReceiveHeader write FOnReceiveHeader;
property OnReceiveResponse: TclHttpResponseEvent read FOnReceiveResponse write FOnReceiveResponse;
property OnSendProgress: TclProgressEvent read FOnSendProgress write FOnSendProgress;
property OnReceiveProgress: TclProgressEvent read FOnReceiveProgress write FOnReceiveProgress;
property OnRedirect: TclHttpRedirectEvent read FOnRedirect write FOnRedirect;
end;
{$IFDEF DEMO}
{$IFNDEF IDEDEMO}
var
IsHttpDemoDisplayed: Boolean = False;
{$ENDIF}
{$ENDIF}
implementation
uses
clZLibStreams, clTranslator, clStreams{$IFDEF LOGGER}, clLogger{$ENDIF};
const
httpVersions: array[TclHttpVersion] of string = ('HTTP/1.0', 'HTTP/1.1');
cacheFields: array[TclHttpVersion] of string = ('Pragma', 'Cache-Control');
connFields: array[Boolean] of string = ('Connection', 'Proxy-Connection');
{ TclHttp }
constructor TclHttp.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FResponseHeader := TclHttpResponseHeader.Create();
FResponseCookies := TclCookieList.Create(nil, TclCookieItem);
FProxySettings := TclHttpProxySettings.Create();
FUrl := TclUrlParser.Create();
TLSFlags := [tfUseSSL3, tfUseTLS, tfUseTLS11, tfUseTLS12];
FHttpVersion := hvHttp1_1;
FAuthorizationType := atAutoDetect;
FUserAgent := DefaultInternetAgent;
FKeepConnection := True;
FAllowCaching := True;
FAllowRedirects := True;
FAllowCookies := True;
FAllowCompression := True;
FMaxRedirects := 15;
FMaxAuthRetries := 5;
FSilentHTTP := False;
FExpect100Continue := False;
end;
procedure TclHttp.DoDestroy;
begin
FOwnRequest.Free();
FOwnCookieManager.Free();
FUrl.Free();
FProxySettings.Free();
FResponseCookies.Free();
FResponseHeader.Free();
inherited DoDestroy();
end;
procedure TclHttp.ConnectProxy;
var
reqHdr, respHdr: TStrings;
nullBody: TStream;
oldCompression: Boolean;
oldCookies: Boolean;
oldVersion: TclHttpVersion;
oldMethod: string;
begin
reqHdr := nil;
respHdr := nil;
nullBody := nil;
oldCompression := AllowCompression;
oldCookies := AllowCookies;
oldVersion := HttpVersion;
oldMethod := FMethod;
try
reqHdr := TStringList.Create();
respHdr := TStringList.Create();
nullBody := TclNullStream.Create();
HttpVersion := hvHttp1_0;
KeepConnection := True;
AllowCompression := False;
AllowCaching := False;
AllowCookies := False;
InternalSendRequest('CONNECT', reqHdr, nullBody, respHdr, nullBody);
finally
FMethod := oldMethod;
HttpVersion := oldVersion;
AllowCookies := oldCookies;
AllowCompression := oldCompression;
nullBody.Free();
respHdr.Free();
reqHdr.Free();
end;
end;
procedure TclHttp.InitConnection(ATunnelStatus: TclHttpTunnelStatus);
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsHttpDemoDisplayed) and (not IsHttpRequestDemoDisplayed)
and (not IsEncoderDemoDisplayed) and (not IsCertDemoDisplayed)
and (not IsHtmlDemoDisplayed) and (not IsEncryptorDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsHttpDemoDisplayed := True;
IsHttpRequestDemoDisplayed := True;
IsEncoderDemoDisplayed := True;
IsEncryptorDemoDisplayed := True;
IsCertDemoDisplayed := True;
IsHtmlDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'InitConnection');{$ENDIF}
if IsUseProxy() then
begin
if (FOldProxyServer <> ProxySettings.Server) or (FOldProxyPort <> ProxySettings.Port) then
begin
Close();
end;
FOldProxyServer := ProxySettings.Server;
FOldProxyPort := ProxySettings.Port;
end;
if (Url.Host <> '') and (Url.Host <> '*') then
begin
if (Server <> Url.Host) or (Port <> Url.Port) then
begin
Close();
end;
Server := Url.Host;
Port := Url.Port;
end;
if IsUseProxy() then
begin
if (Url.UrlType = utHTTPS) and (ATunnelStatus <> htConnect) then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InitConnection ConnectProxy');{$ENDIF}
ConnectProxy();
StartTls();
end else
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InitConnection TunnelProxy');{$ENDIF}
UseTLS := ctNone;
end;
end else
begin
if (Url.UrlType = utHTTPS) then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InitConnection HTTPS');{$ENDIF}
UseTLS := ctImplicit;
end else
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InitConnection HTTP');{$ENDIF}
UseTLS := ctNone;
end;
end;
Open();
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InitConnection'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InitConnection', E); raise; end; end;{$ENDIF}
end;
procedure TclHttp.PrepareRequestHeader(ATunnelStatus: TclHttpTunnelStatus;
ARequestHeader: TStrings; ARequestBody: TStream);
function GetPortIfNeed(APort: Integer): string;
begin
if (APort <> 80) and (APort <> 443) then
begin
Result := Format(':%d', [APort]);
end else
begin
Result := '';
end;
end;
var
fieldList: TclHeaderFieldList;
path, host, contentLength: string;
requestSize: Int64;
begin
requestSize := ARequestBody.Size - ARequestBody.Position;
RemoveRequestLine(ARequestHeader);
RemoveHeaderTrailer(ARequestHeader);
if IsUseProxy() then
begin
case ATunnelStatus of
htConnect: path := Format('%s:%d', [Url.Host, Url.Port]);
htTunnel: path := Url.AbsolutePath;
else
path := Url.AbsoluteUri;
end;
end else
begin
path := Url.AbsolutePath;
end;
if (path = '') then
begin
path := '/';
end;
ARequestHeader.Insert(0, Format('%s %s %s', [FMethod, path, httpVersions[HttpVersion]]));
fieldList := TclHeaderFieldList.Create();
try
fieldList.Parse(0, ARequestHeader);
fieldList.RemoveField('Host');
if AllowCompression then
begin
fieldList.AddFieldIfNotExist('Accept-Encoding', 'gzip');
end;
if (Url.Host <> '') then
begin
host := Url.Host + GetPortIfNeed(Url.Port);
end else
begin
host := Server + GetPortIfNeed(Port);
end;
fieldList.AddField('Host', host);
fieldList.AddFieldIfNotExist('User-Agent', UserAgent);
contentLength := fieldList.GetFieldValue('Content-Length');
if ((StrToInt64Def(contentLength, 0) > 0) and (requestSize = 0)) then
begin
fieldList.RemoveField('Content-Length');
fieldList.RemoveField('Content-Type');
end else
if ((contentLength = '') and ((ATunnelStatus = htConnect) or (requestSize > 0))) then
begin
fieldList.AddField('Content-Length', IntToStr(requestSize));
end else
if ((contentLength = '') and (requestSize = 0) and SameText('POST', FMethod)) then
begin
fieldList.AddField('Content-Length', '0');
end;
if not AllowCaching then
begin
fieldList.AddFieldIfNotExist(cacheFields[HttpVersion], 'no-cache');
end;
if KeepConnection then
begin
fieldList.AddFieldIfNotExist(connFields[IsUseProxy()], 'Keep-Alive');
end;
fieldList.RemoveField('Expect');
if (Expect100Continue and (requestSize > 0)) then
begin
fieldList.AddField('Expect', '100-continue');
end;
SetRequestCookies(ARequestHeader);
ARequestHeader.Add('');
finally
fieldList.Free();
end;
end;
procedure TclHttp.SetRequestCookies(ARequestHeader: TStrings);
var
cookies: TclCookieList;
begin
if AllowCookies then
begin
cookies := TclCookieList.Create(nil, TclCookieItem);
try
GetCookieManager().GetCookies(cookies, Url.Host, Url.AbsolutePath, Url.Port, Url.UrlType = utHTTPS);
cookies.SetRequestCookies(ARequestHeader);
finally
cookies.Free();
end;
end;
end;
procedure TclHttp.SetSilentHTTP(const Value: Boolean);
begin
if (FSilentHTTP <> Value) then
begin
FSilentHTTP := Value;
Changed();
end;
end;
function TclHttp.GetTunnelStatus: TclHttpTunnelStatus;
begin
if IsUseProxy() and (Url.UrlType = utHTTPS) then
begin
if SameText('CONNECT', FMethod) then
begin
Result := htConnect;
end else
begin
Result := htTunnel;
end;
end else
begin
Result := htNone;
end;
end;
procedure TclHttp.WriteRequestHeader(ATunnelStatus: TclHttpTunnelStatus;
ARequestHeader: TStrings; ARequestBody: TStream);
begin
InitConnection(ATunnelStatus);
PrepareRequestHeader(ATunnelStatus, ARequestHeader, ARequestBody);
Connection.WriteString(ARequestHeader.Text, 'us-ascii');
end;
procedure TclHttp.WriteRequestData(ARequestBody: TStream);
begin
if (ARequestBody.Size > 0) then
begin
InitProgress(ARequestBody.Position, ARequestBody.Size);
Connection.OnProgress := DoDataSendProgress;
try
Connection.WriteData(ARequestBody);
if not FProgressHandled then
begin
DoSendProgress(ARequestBody.Size, ARequestBody.Size);
end;
finally
Connection.OnProgress := nil;
end;
end;
end;
function TclHttp.ExtractStatusCode(ABuffer: TclByteArray; var ADataPos: Integer): Integer;
var
ind: Integer;
s: string;
lexem: TclByteArray;
begin
SetLength(lexem, 1);
lexem[0] := 32;
Result := 0;
ind := BytesPos(lexem, ABuffer, ADataPos, Length(ABuffer));
if (ind > -1) then
begin
s := TclTranslator.GetString(ABuffer, ADataPos, ind - ADataPos, 'us-ascii');
ADataPos := ind;
Result := StrToIntDef(s, 0);
end;
end;
function TclHttp.ExtractStatusText(ABuffer: TclByteArray; var ADataPos: Integer): string;
var
ind: Integer;
lexem: TclByteArray;
begin
SetLength(lexem, 1);
lexem[0] := 10;
ind := BytesPos(lexem, ABuffer, ADataPos, Length(ABuffer));
if (ind <= 0) then
begin
ind := Length(ABuffer);
end;
Result := Trim(TclTranslator.GetString(ABuffer, ADataPos, ind - ADataPos, 'us-ascii'));
ADataPos := ind;
end;
function TclHttp.ExtractResponseVersion(ABuffer: TclByteArray; var ADataPos: Integer): TclHttpVersion;
var
ind: Integer;
s: string;
lexem: TclByteArray;
begin
SetLength(lexem, 1);
lexem[0] := 32;
Result := HttpVersion;
ind := BytesPos(lexem, ABuffer, ADataPos, Length(ABuffer));
if (ind > -1) then
begin
s := Trim(UpperCase(TclTranslator.GetString(ABuffer, 0, ind - ADataPos, 'us-ascii')));
ADataPos := ind;
for Result := Low(TclHttpVersion) to High(TclHttpVersion) do
begin
if (httpVersions[Result] = s) then
begin
Exit;
end;
end;
Result := HttpVersion;
end;
end;
function TclHttp.ReadResponseHeader(AResponseHeader: TStrings; ARawData: TStream): Boolean;
procedure LoadTextFromStream(AStream: TStream; ACount: Integer; AList: TStrings);
var
buf: TclByteArray;
begin
Assert(ACount > 0);
SetLength(buf, ACount);
AStream.Read(buf[0], ACount);
AList.Text := TclTranslator.GetString(buf, 0, ACount, 'us-ascii');
end;
function GetRawBuffer(AStream: TStream): TclByteArray;
var
oldPos: Int64;
begin
oldPos := AStream.Position;
try
AStream.Position := 0;
SetLength(Result, AStream.Size);
if (Length(Result) > 0) then
begin
AStream.Read(Result[0], Length(Result));
end;
finally
AStream.Position := oldPos;
end;
end;
var
ind, hdrStart, statusLineInd, eofLength: Integer;
oldBytesToProceed: Int64;
EndOfHeader, EndOfHeader2, rawBuffer: TclByteArray;
begin
{$IFNDEF DELPHI2005}rawBuffer := nil;{$ENDIF}
SetLength(EndOfHeader, 4);
EndOfHeader[0] := $D; EndOfHeader[1] := $A; EndOfHeader[2] := $D; EndOfHeader[3] := $A;
SetLength(EndOfHeader2, 2);
EndOfHeader2[0] := $A; EndOfHeader2[1] := $A;
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ReadResponseHeader');{$ENDIF}
ARawData.Size := 0;
hdrStart := 0;
FStatusCode := 0;
FStatusText := '';
FResponseVersion := HttpVersion;
Connection.IsReadUntilClose := False;
oldBytesToProceed := Connection.BytesToProceed;
Connection.InitProgress(0, 0);
Connection.BytesToProceed := BatchSize;
repeat
try
Connection.ReadData(ARawData);
finally
Connection.BytesToProceed := oldBytesToProceed;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ReadResponseHeader, after ReadData, Connection.BytesProceed=%d', nil, [Connection.BytesProceed]);{$ENDIF}
rawBuffer := GetRawBuffer(ARawData);
repeat
ind := BytesPos(EndOfHeader, rawBuffer, hdrStart, Length(rawBuffer));
eofLength := Length(EndOfHeader);
if(ind < 0) then
begin
ind := BytesPos(EndOfHeader2, rawBuffer, hdrStart, Length(rawBuffer));
eofLength := Length(EndOfHeader2);
end;
if (ind > 0) then
begin
statusLineInd := hdrStart;
FResponseVersion := ExtractResponseVersion(rawBuffer, statusLineInd);
Inc(statusLineInd);
FStatusCode := ExtractStatusCode(rawBuffer, statusLineInd);
Inc(statusLineInd);
FStatusText := ExtractStatusText(rawBuffer, statusLineInd);
if (FStatusCode = 100) then
begin
hdrStart := ind + eofLength;
end else
begin
Break;
end;
end else
begin
Break;
end;
until False;
until (FStatusCode <> 0) and (FStatusCode <> 100);
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ReadResponseHeader, after loop');{$ENDIF}
ARawData.Position := hdrStart;
LoadTextFromStream(ARawData, ind + eofLength - hdrStart, AResponseHeader);
ResponseHeader.ParseHeader(AResponseHeader);
ReadCookies(AResponseHeader);
Result := False;
DoReceiveHeader(FMethod, Url.AbsoluteUri, AResponseHeader, FResponseCookies, Result);
Result := not Result;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'ReadResponseHeader'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'ReadResponseHeader', E); raise; end; end;{$ENDIF}
end;
procedure TclHttp.LoadResponseStream(AResponseText: TStrings; AResponseBody: TStream);
begin
if (AResponseBody <> nil) then
begin
TclStringsUtils.SaveStrings(AResponseText, AResponseBody, GetResponseCharSet());
end;
end;
procedure TclHttp.ReadResponseStream(AResponseHeader: TStrings; AExtraSize: Int64; AExtraData, AResponseBody: TStream);
var
nullResp: TStream;
begin
if (SameText('HEAD', FMethod)) then
begin
Exit;
end;
nullResp := nil;
try
if (AResponseBody = nil) then
begin
nullResp := TclNullStream.Create();
AResponseBody := nullResp;
end;
ReadResponseBody(AResponseHeader, AExtraSize, AExtraData, AResponseBody);
finally
nullResp.Free();
end;
end;
procedure TclHttp.ReadResponseBody(AResponseHeader: TStrings;
AExtraSize: Int64; AExtraData, AResponseBody: TStream);
var
totalSize, bodySize, oldProceed: Int64;
chunkedBody: TclChunkedStream;
dest, compressor: TStream;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ReadResponseBody');{$ENDIF}
compressor := nil;
Connection.OnProgress := DoDataReceiveProgress;
try
if (system.Pos('gzip', LowerCase(ResponseHeader.ContentEncoding)) > 0) then
begin
compressor := TclGZipInflateStream.Create(AResponseBody);
dest := compressor;
end else
begin
dest := AResponseBody;
end;
if SameText('chunked', ResponseHeader.TransferEncoding) then
begin
chunkedBody := TclChunkedStream.Create(dest);
try
if (AExtraSize > 0) then
begin
chunkedBody.CopyFrom(AExtraData, AExtraSize);
end;
InitProgress(AExtraSize, -1);
if Active then
begin
while not chunkedBody.IsCompleted do
begin
Connection.ReadData(chunkedBody);
end;
end;
if not FProgressHandled then
begin
DoReceiveProgress(Connection.BytesProceed, -1);
end;
finally
chunkedBody.Free();
end;
end else
begin
if (AExtraSize > 0) then
begin
dest.CopyFrom(AExtraData, AExtraSize);
end;
bodySize := GetResponseLength();
totalSize := bodySize;
InitProgress(AExtraSize, totalSize);
if (bodySize < 0) then
begin
if Active then
begin
Connection.IsReadUntilClose := True;
Connection.ReadData(dest);
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ReadResponseBody IsReadUntilClose');{$ENDIF}
end;
end else
begin
oldProceed := Connection.BytesProceed;
bodySize := bodySize - AExtraSize;
if Active then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ReadResponseBody before while, %d ', nil, [bodySize]);{$ENDIF}
while ((Connection.BytesProceed - oldProceed) < bodySize) do
begin
Connection.ReadData(dest);
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ReadResponseBody after ReadData, %d ', nil, [Connection.BytesProceed]);{$ENDIF}
end;
end;
end;
if not FProgressHandled then
begin
DoReceiveProgress(totalSize, totalSize);
end;
end;
finally
Connection.OnProgress := nil;
compressor.Free();
{$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'ReadResponseBody, received response', AResponseBody, 0);{$ENDIF}
end;
DoReceiveResponse(FMethod, Url.AbsoluteUri, AResponseHeader, FResponseCookies);
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'ReadResponseBody'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'ReadResponseBody', E); raise; end; end;{$ENDIF}
end;
procedure TclHttp.ReadResponseText(AResponseHeader: TStrings;
AExtraSize: Int64; AExtraData: TStream; AResponseText: TStrings);
var
rawData: TStream;
begin
if (SameText('HEAD', FMethod)) then
begin
AResponseText.Clear();
Exit;
end;
rawData := TMemoryStream.Create();
try
ReadResponseBody(AResponseHeader, AExtraSize, AExtraData, rawData);
rawData.Position := 0;
TclStringsUtils.LoadStrings(rawData, AResponseText, GetResponseCharSet());
finally
rawData.Free();
end;
end;
function TclHttp.GetResponseCharSet: string;
begin
Result := ResponseHeader.CharSet;
if (Result = '') then
begin
Result := CharSet;
end;
end;
function TclHttp.GetResponseLength: Int64;
begin
if ((StatusCode = 204) and (ResponseHeader.ContentLength = '')) then
begin
Result := 0;
end else
if SameText('CONNECT', FMethod) and (StatusCode = 200) then
begin
Result := 0;
end else
if SameText('HEAD', FMethod) or (StatusCode = 304) then
begin
Result := 0;
end else
if ((HttpVersion = hvHttp1_0) or (ResponseVersion = hvHttp1_0))
and (ResponseHeader.ContentLength = '') then
begin
Result := -1;
end else
if (ResponseHeader.ContentLength = '') and ((StatusCode and 200) = 200) then
begin
Result := -1;
end else
begin
Result := StrToInt64Def(Trim(ResponseHeader.ContentLength), 0);
end;
end;
function TclHttp.GetKeepAlive: Boolean;
begin
if (HttpVersion = hvHttp1_1) and (ResponseVersion = hvHttp1_1) then
begin
if IsUseProxy() then
begin
Result := not SameText('close', ResponseHeader.ProxyConnection);
end else
begin
Result := not SameText('close', ResponseHeader.Connection);
end;
{$IFDEF LOGGER}
clPutLogMessage(Self, edInside, 'GetKeepAlive inside if, Result: ' + IntToStr(Integer(Result)));
{$ENDIF}
end else
begin
if IsUseProxy() then
begin
Result := SameText('Keep-Alive', ResponseHeader.ProxyConnection);
end else
begin
Result := SameText('Keep-Alive', ResponseHeader.Connection);
end;
{$IFDEF LOGGER}
clPutLogMessage(Self, edInside, 'GetKeepAlive inside else, Result: ' + IntToStr(Integer(Result)));
{$ENDIF}
end;
Result := Result and KeepConnection;
end;
procedure TclHttp.RemoveHeaderTrailer(AHeader: TStrings);
begin
while (AHeader.Count > 0) and (AHeader[AHeader.Count - 1] = '') do
begin
AHeader.Delete(AHeader.Count - 1);
end;
end;
procedure TclHttp.RemoveRequestLine(AHeader: TStrings);
var
space, colon: Integer;
begin
if (AHeader.Count > 0) then
begin
space := system.Pos(#32, AHeader[0]);
colon := system.Pos(':', AHeader[0]);
if (space <> 0) then
begin
if (colon = 0) or (space < colon) then
begin
AHeader.Delete(0);
end;
end;
end;
end;
function TclHttp.BasicAuthorization(const AUserName, APassword, AuthorizationField: string;
ARequestHeader: TStrings): Boolean;
var
authChallenge: TStrings;
oldKeepConnection, temp: Boolean;
begin
oldKeepConnection := KeepConnection;
authChallenge := TStringList.Create();
try
authChallenge.Add('Basic');
Result := Authorize(AUserName, APassword, AuthorizationField, authChallenge, ARequestHeader, temp);
finally
authChallenge.Free();
KeepConnection := oldKeepConnection;
end;
end;
procedure TclHttp.SetAuthorizationField(const AFieldName, AFieldValue: string;
ARequestHeader: TStrings);
var
fieldList: TclHeaderFieldList;
begin
RemoveHeaderTrailer(ARequestHeader);
fieldList := TclHeaderFieldList.Create();
try
fieldList.Parse(0, ARequestHeader);
fieldList.RemoveField(AFieldName);
fieldList.AddField(AFieldName, AFieldValue);
finally
fieldList.Free();
end;
end;
function TclHttp.Authorize(const AUserName, APassword,
AuthorizationField: string; AuthChallenge, ARequestHeader: TStrings;
var AStartNewConnection: Boolean): Boolean;
var
auth: TclHttpAuthorization;
begin
AStartNewConnection := False;
auth := TclHttpAuthorization.Authorize(Url, FMethod, AUserName, APassword, AuthChallenge, Self);
Result := (auth <> nil);
if Result then
begin
AStartNewConnection := auth.StartNewConnection;
SetAuthorizationField(AuthorizationField, auth.AuthValue, ARequestHeader);
KeepConnection := True;
end;
end;
procedure TclHttp.Delete(const AUrl: string; AResponseHeader: TStrings);
begin
InternalDelete(AUrl, AResponseHeader, nil);
end;
procedure TclHttp.DoRedirect(ARequestHeader: TStrings; AStatusCode: Integer;
AResponseHeader: TclHttpResponseHeader; AResponseText: TStrings; var AMethod: string;
var CanRedirect, Handled: Boolean);
begin
if Assigned(OnRedirect) then
begin
OnRedirect(Self, ARequestHeader, AStatusCode,
AResponseHeader, AResponseText, AMethod, CanRedirect, Handled);
end;
end;
function TclHttp.GetResourcePath: string;
var
ind: Integer;
begin
Result := LowerCase(Url.AbsoluteUri);
ind := LastDelimiter('/', Result);
Result := system.Copy(Result, 1, ind);
ind := Length(Result);
if (ind > 0) and (Result[ind] <> '/') then
begin
Result := Result + '/';
end;
end;
function TclHttp.GetRedirectMethod(AStatusCode: Integer; const AMethod: string): string;
begin
if (StatusCode = 302) or (StatusCode = 303) then
begin
Result := 'GET';
end else
begin
Result := AMethod;
end;
end;
function TclHttp.GetRequest: TclHttpRequest;
begin
Result := Request;
if (Result = nil) then
begin
if (FOwnRequest = nil) then
begin
FOwnRequest := TclHttpRequest.Create(nil);
end;
Result := FOwnRequest;
Result.Clear();
end;
if (CharSet <> '') then
begin
Result.Header.CharSet := CharSet;
end;
end;
function TclHttp.Redirect(ARequestHeader, AResponseText: TStrings;
var AMethod: string): Boolean;
var
location: string;
handled: Boolean;
oldPath: string;
fieldList: TclHeaderFieldList;
begin
location := ResponseHeader.Location;
Result := False;
handled := False;
oldPath := GetResourcePath();
DoRedirect(ARequestHeader, StatusCode, ResponseHeader, AResponseText, AMethod, Result, handled);
if not handled and (location <> '') then
begin
Result := (Url.Parse(Url.CombineUrl(location, Url.AbsoluteUri, CharSet), CharSet) <> '');
if Result then
begin
AMethod := GetRedirectMethod(StatusCode, AMethod);
if (system.Pos(oldPath, GetResourcePath()) <> 1) then
begin
fieldList := TclHeaderFieldList.Create();
try
fieldList.Parse(0, ARequestHeader);
fieldList.RemoveField('Authorization');
finally
fieldList.Free();
end;
end;
end;
end;
end;
procedure TclHttp.RaiseHttpError(AStatusCode: Integer; AResponseHeader, AResponseText: TStrings);
var
msg: string;
begin
msg := '';
if (AResponseHeader.Count > 0) then
begin
msg := AResponseHeader[0];
end;
raise EclHttpError.Create(msg, AStatusCode, AResponseText.Text);
end;
procedure TclHttp.ReadCookies(AResponseHeader: TStrings);
begin
FResponseCookies.GetResponseCookies(AResponseHeader, Url.Host, Url.AbsolutePath, Url.Port);
if AllowCookies then
begin
GetCookieManager().AddCookies(FResponseCookies);
end;
end;
procedure TclHttp.InternalSendRequest(const AMethod: string;
ARequestHeader: TStrings; ARequestBody: TStream;
AResponseHeader: TStrings; AResponseBody: TStream);
var
extraSize: Int64;
redirects, authRetries, proxyRetries: Integer;
rawData: TStream;
reqHeader, respText: TStrings;
needClose, startNewConnection: Boolean;
requestPos: Int64;
nullBody: TStream;
newMethod: string;
tunnelStatus: TclHttpTunnelStatus;
wasActive: Boolean;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'SendRequest, TimeOut: %d', nil, [TimeOut]);{$ENDIF}
reqHeader := nil;
rawData := nil;
respText := nil;
nullBody := nil;
try
reqHeader := TStringList.Create();
rawData := TMemoryStream.Create();
respText := TStringList.Create();
reqHeader.Assign(ARequestHeader);
FMethod := AMethod;
if (AuthorizationType = atBasic) then
begin
BasicAuthorization(GetUserName_(), GetPassword(), 'Authorization', reqHeader);
end else
if (Authorization <> '') then
begin
SetAuthorizationField('Authorization', Authorization, reqHeader);
end;
if IsUseProxy() and (ProxySettings.AuthorizationType = atBasic) then
begin
BasicAuthorization(ProxySettings.UserName, ProxySettings.Password,
'Proxy-Authorization', reqHeader);
end;
requestPos := ARequestBody.Position;
needClose := False;
redirects := 0;
authRetries := 0;
proxyRetries := 0;
tunnelStatus := htNone;
try
repeat
tunnelStatus := GetTunnelStatus();
wasActive := Active;
try
ARequestBody.Position := requestPos;
WriteRequestHeader(tunnelStatus, reqHeader, ARequestBody);
WriteRequestData(ARequestBody);
DoSendRequest(FMethod, Url.AbsoluteUri, reqHeader);
if not ReadResponseHeader(AResponseHeader, rawData) then
begin
needClose := True;
Break;
end;
except
on E: EclSocketError do
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InternalSendRequest, re-open the connection, error code: %d', E, [E.ErrorCode]);{$ENDIF}
if (not wasActive) or
((E.ErrorCode <> 10053) and (E.ErrorCode <> 10038)) then raise;
Close();
continue;
end;
end;
extraSize := rawData.Size - rawData.Position;
needClose := not GetKeepAlive();
if ((StatusCode div 100 ) = 3) and (StatusCode <> 304) and (StatusCode <> 305) then
begin
Inc(redirects);
ReadResponseText(AResponseHeader, extraSize, rawData, respText);
if (MaxRedirects > 0) and (redirects > MaxRedirects) then
begin
if SilentHTTP then
begin
LoadResponseStream(respText, AResponseBody);
Break;
end else
begin
RaiseHttpError(StatusCode, AResponseHeader, respText);
end;
end;
newMethod := FMethod;
if not (AllowRedirects and Redirect(reqHeader, respText, newMethod)) then
begin
if SilentHTTP then
begin
LoadResponseStream(respText, AResponseBody);
Break;
end else
begin
RaiseHttpError(StatusCode, AResponseHeader, respText);
end;
end;
if SameText('GET', newMethod) then
begin
if (nullBody = nil) then
begin
nullBody := TclNullStream.Create();
end;
ARequestBody := nullBody;
end;
{$IFDEF LOGGER}
clPutLogMessage(Self, edInside, 'SendRequest new Method: '
+ newMethod + '; old Method: ' + FMethod + '; need clode: ' + IntToStr(Integer(needClose)));
{$ENDIF}
FMethod := newMethod;
if IsUseProxy() then
begin
needClose := True;
end;
end else
if (StatusCode = 401) then
begin
Inc(authRetries);
ReadResponseText(AResponseHeader, extraSize, rawData, respText);
if (Authorization <> '')
or ((MaxAuthRetries > 0) and (authRetries > MaxAuthRetries)) then
begin
if SilentHTTP then
begin
LoadResponseStream(respText, AResponseBody);
Break;
end else
begin
RaiseHttpError(StatusCode, AResponseHeader, respText);
end;
end;
if not Authorize(GetUserName_(), GetPassword(),
'Authorization', ResponseHeader.Authenticate, reqHeader, startNewConnection) then
begin
if SilentHTTP then
begin
LoadResponseStream(respText, AResponseBody);
Break;
end else
begin
RaiseHttpError(StatusCode, AResponseHeader, respText);
end;
end;
if (authRetries = 1) and startNewConnection then
begin
needClose := True;
end;
end else
if (StatusCode = 407) then
begin
Inc(proxyRetries);
ReadResponseText(AResponseHeader, extraSize, rawData, respText);
if (MaxAuthRetries > 0) and (proxyRetries > MaxAuthRetries) then
begin
if SilentHTTP then
begin
LoadResponseStream(respText, AResponseBody);
Break;
end else
begin
RaiseHttpError(StatusCode, AResponseHeader, respText);
end;
end;
if not Authorize(ProxySettings.UserName, ProxySettings.Password,
'Proxy-Authorization', ResponseHeader.ProxyAuthenticate, reqHeader, startNewConnection) then
begin
if SilentHTTP then
begin
LoadResponseStream(respText, AResponseBody);
Break;
end else
begin
RaiseHttpError(StatusCode, AResponseHeader, respText);
end;
end;
if (proxyRetries = 1) and startNewConnection then
begin
needClose := True;
end;
end else
if (StatusCode >= 400) then
begin
if SilentHTTP then
begin
ReadResponseStream(AResponseHeader, extraSize, rawData, AResponseBody);
Break;
end else
begin
ReadResponseText(AResponseHeader, extraSize, rawData, respText);
RaiseHttpError(StatusCode, AResponseHeader, respText);
end;
end else
begin
ReadResponseStream(AResponseHeader, extraSize, rawData, AResponseBody);
Break;
end;
if needClose then
begin
Close();
end;
until False;
finally
if needClose and (tunnelStatus <> htConnect) then
begin
Close();
end;
end;
finally
nullBody.Free();
respText.Free();
rawData.Free();
reqHeader.Free();
end;
end;
procedure TclHttp.SendRequest(const AMethod, AUrl: string; ARequestHeader: TStrings;
ARequestBody: TStream; AResponseHeader: TStrings; AResponseBody: TStream);
var
reqHeader, respHeader: TStrings;
nullBody: TStream;
begin
reqHeader := nil;
respHeader := nil;
nullBody := nil;
try
if (ARequestHeader = nil) then
begin
reqHeader := TStringList.Create();
ARequestHeader := reqHeader;
end;
if (AResponseHeader = nil) then
begin
respHeader := TStringList.Create();
AResponseHeader := respHeader;
end;
if (ARequestBody = nil) then
begin
if (nullBody = nil) then
begin
nullBody := TclNullStream.Create();
end;
ARequestBody := nullBody;
end;
if (AResponseBody = nil) then
begin
if (nullBody = nil) then
begin
nullBody := TclNullStream.Create();
end;
AResponseBody := nullBody;
end;
Url.Parse(AUrl, CharSet);
InternalSendRequest(AMethod, ARequestHeader, ARequestBody, AResponseHeader, AResponseBody);
finally
nullBody.Free();
respHeader.Free();
reqHeader.Free();
end;
end;
procedure TclHttp.SetHttpVersion(const Value: TclHttpVersion);
begin
if (FHttpVersion <> Value) then
begin
FHttpVersion := Value;
Changed();
end;
end;
procedure TclHttp.SetPassword(const Value: string);
begin
if (FPassword <> Value) then
begin
FPassword := Value;
Changed();
end;
end;
procedure TclHttp.SetUserName(const Value: string);
begin
if (FUserName <> Value) then
begin
FUserName := Value;
Changed();
end;
end;
procedure TclHttp.SetUserAgent(const Value: string);
begin
if (FUserAgent <> Value) then
begin
FUserAgent := Value;
Changed();
end;
end;
procedure TclHttp.SetAuthorizationType(const Value: TclAuthorizationType);
begin
if (FAuthorizationType <> Value) then
begin
FAuthorizationType := Value;
Changed();
end;
end;
procedure TclHttp.SendRequest(const AMethod, AUrl: string;
ARequestHeader: TStrings; ARequestBody, AResponseBody: TStream);
begin
SendRequest(AMethod, AUrl, ARequestHeader, ARequestBody, nil, AResponseBody);
end;
procedure TclHttp.SendRequest(const AMethod, AUrl: string;
ARequest: TclHttpRequest; AResponseBody: TStream);
begin
SendRequest(AMethod, AUrl, ARequest, nil, AResponseBody);
end;
procedure TclHttp.SetAllowCaching(const Value: Boolean);
begin
if (FAllowCaching <> Value) then
begin
FAllowCaching := Value;
Changed();
end;
end;
procedure TclHttp.SetKeepConnection(const Value: Boolean);
begin
if (FKeepConnection <> Value) then
begin
FKeepConnection := Value;
Changed();
end;
end;
procedure TclHttp.SetAllowRedirects(const Value: Boolean);
begin
if (FAllowRedirects <> Value) then
begin
FAllowRedirects := Value;
Changed();
end;
end;
procedure TclHttp.SetProxySettings(const Value: TclHttpProxySettings);
begin
FProxySettings.Assign(Value);
end;
procedure TclHttp.SetMaxAuthRetries(const Value: Integer);
begin
if (FMaxAuthRetries <> Value) then
begin
FMaxAuthRetries := Value;
Changed();
end;
end;
procedure TclHttp.SetMaxRedirects(const Value: Integer);
begin
if (FMaxRedirects <> Value) then
begin
FMaxRedirects := Value;
Changed();
end;
end;
procedure TclHttp.SetAuthorization(const Value: string);
begin
if (FAuthorization <> Value) then
begin
FAuthorization := Value;
Changed();
end;
end;
function TclHttp.IsUseProxy: Boolean;
begin
Result := (ProxySettings.Server <> '');
end;
procedure TclHttp.SetAllowCookies(const Value: Boolean);
begin
if (FAllowCookies <> Value) then
begin
FAllowCookies := Value;
Changed();
end;
end;
procedure TclHttp.DoReceiveResponse(const AMethod, AUrl: string;
AResponseHeader: TStrings; ACookies: TclCookieList);
begin
if Assigned(OnReceiveResponse) then
begin
OnReceiveResponse(Self, AMethod, AUrl, AResponseHeader, ACookies);
end;
end;
procedure TclHttp.DoSendRequest(const AMethod, AUrl: string; ARequestHeader: TStrings);
begin
if Assigned(OnSendRequest) then
begin
OnSendRequest(Self, AMethod, AUrl, ARequestHeader);
end;
end;
procedure TclHttp.SetAllowCompression(const Value: Boolean);
begin
if (FAllowCompression <> Value) then
begin
FAllowCompression := Value;
Changed();
end;
end;
procedure TclHttp.SetRequest(const Value: TclHttpRequest);
begin
if (FRequest <> Value) then
begin
if (FRequest <> nil) then
begin
FRequest.RemoveFreeNotification(Self);
end;
FRequest := Value;
if (FRequest <> nil) then
begin
FRequest.FreeNotification(Self);
end;
end;
end;
procedure TclHttp.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation <> opRemove) then Exit;
if (AComponent = FRequest) then
begin
FRequest := nil;
end;
if (AComponent = FCookieManager) then
begin
FCookieManager := nil;
end;
end;
procedure TclHttp.Delete(const AUrl: string);
begin
InternalDelete(AUrl, nil, nil);
end;
procedure TclHttp.Get(const AUrl: string; ADestination: TStream);
begin
InternalGet(AUrl, nil, nil, ADestination);
end;
procedure TclHttp.Head(const AUrl: string);
begin
InternalHead(AUrl, nil);
end;
procedure TclHttp.Post(const AUrl: string; ARequest: TclHttpRequest; AResponseBody: TStream);
begin
InternalPost(AUrl, ARequest, nil, AResponseBody);
end;
procedure TclHttp.Post(const AUrl: string; AResponseBody: TStream);
begin
Post(AUrl, Request, AResponseBody);
end;
procedure TclHttp.Put(const AUrl: string; ASource: TStream);
begin
Put(AUrl, '', ASource);
end;
procedure TclHttp.SendRequest(const AMethod, AUrl: string;
ARequest: TclHttpRequest; AResponseHeader: TStrings; AResponseBody: TStream);
var
stream: TStream;
reqHeader: TStrings;
begin
reqHeader := ARequest.HeaderSource;
stream := ARequest.RequestStream;
try
SendRequest(AMethod, AUrl, reqHeader, stream, AResponseHeader, AResponseBody);
finally
stream.Free();
end;
end;
procedure TclHttp.DoSendProgress(ABytesProceed, ATotalBytes: Int64);
begin
FProgressHandled := True;
if Assigned(OnSendProgress) then
begin
OnSendProgress(Self, ABytesProceed, ATotalBytes);
end;
end;
procedure TclHttp.DoReceiveHeader(const AMethod, AUrl: string;
AResponseHeader: TStrings; ACookies: TclCookieList; var Cancel: Boolean);
begin
if Assigned(OnReceiveHeader) then
begin
OnReceiveHeader(Self, AMethod, AUrl, AResponseHeader, ACookies, Cancel);
end;
end;
procedure TclHttp.DoReceiveProgress(ABytesProceed, ATotalBytes: Int64);
begin
FProgressHandled := True;
if Assigned(OnReceiveProgress) then
begin
OnReceiveProgress(Self, ABytesProceed, ATotalBytes);
end;
end;
procedure TclHttp.InitProgress(ABytesProceed, ATotalBytes: Int64);
begin
FProgressHandled := False;
Connection.InitProgress(ABytesProceed, ATotalBytes);
end;
procedure TclHttp.DoDataSendProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64);
begin
DoSendProgress(ABytesProceed, ATotalBytes);
end;
procedure TclHttp.DoDataReceiveProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64);
begin
DoReceiveProgress(ABytesProceed, ATotalBytes);
end;
function TclHttp.GetPassword: string;
begin
Result := Password;
if (Result = '') then
begin
Result := Url.Password;
end;
end;
function TclHttp.GetUserName_: string;
begin
Result := UserName;
if (Result = '') then
begin
Result := Url.UserName;
end;
end;
procedure TclHttp.Head(const AUrl: string; AResponseHeader: TStrings);
begin
InternalHead(AUrl, AResponseHeader);
end;
function TclHttp.GetDefaultPort: Integer;
begin
Result := DefaultHttpPort;
end;
procedure TclHttp.Get(const AUrl: string; ADestination: TStrings);
var
dest: TStream;
begin
dest := TMemoryStream.Create();
try
Get(AUrl, dest);
dest.Position := 0;
TclStringsUtils.LoadStrings(dest, ADestination, GetResponseCharSet());
finally
dest.Free();
end;
end;
procedure TclHttp.Post(const AUrl: string; AResponseBody: TStrings);
var
dest: TStream;
begin
dest := TMemoryStream.Create();
try
Post(AUrl, dest);
dest.Position := 0;
TclStringsUtils.LoadStrings(dest, AResponseBody, GetResponseCharSet());
finally
dest.Free();
end;
end;
procedure TclHttp.OpenConnection(const AServer: string; APort: Integer);
begin
if IsUseProxy() then
begin
inherited OpenConnection(ProxySettings.Server, ProxySettings.Port);
end else
begin
inherited OpenConnection(AServer, APort);
end;
end;
procedure TclHttp.Put(const AUrl: string; ASource, AResponseBody: TStream);
begin
Put(AUrl, '', ASource, AResponseBody);
end;
procedure TclHttp.Put(const AUrl: string; ASource: TStream; AResponseBody: TStrings);
begin
Put(AUrl, '', ASource, AResponseBody);
end;
procedure TclHttp.SetCharSet(const Value: string);
begin
if (FCharSet <> Value) then
begin
FCharSet := Value;
Changed();
end;
end;
procedure TclHttp.SetCookieManager(const Value: TclCookieManager);
begin
if (FCookieManager <> Value) then
begin
if (FCookieManager <> nil) then
begin
FCookieManager.RemoveFreeNotification(Self);
end;
FCookieManager := Value;
if (FCookieManager <> nil) then
begin
FCookieManager.FreeNotification(Self);
end;
FOwnCookieManager.Free();
FOwnCookieManager := nil;
end;
end;
procedure TclHttp.SetExpect100Continue(const Value: Boolean);
begin
if (FExpect100Continue <> Value) then
begin
FExpect100Continue := Value;
Changed();
end;
end;
procedure TclHttp.Get(const AUrl: string; AResponseHeader: TStrings; AResponseBody: TStream);
begin
InternalGet(AUrl, nil, AResponseHeader, AResponseBody);
end;
procedure TclHttp.Get(const AUrl: string; ARequest: TclHttpRequest; ADestination: TStream);
begin
InternalGet(AUrl, ARequest, nil, ADestination);
end;
procedure TclHttp.Get(const AUrl: string; ARequest: TclHttpRequest; ADestination: TStrings);
var
dest: TStream;
begin
dest := TMemoryStream.Create();
try
Get(AUrl, ARequest, dest);
dest.Position := 0;
TclStringsUtils.LoadStrings(dest, ADestination, GetResponseCharSet());
finally
dest.Free();
end;
end;
procedure TclHttp.Get(const AUrl: string; ARequest: TclHttpRequest; AResponseHeader: TStrings; AResponseBody: TStream);
begin
InternalGet(AUrl, ARequest, AResponseHeader, AResponseBody);
end;
function TclHttp.GetCookieManager: TclCookieManager;
begin
Result := CookieManager;
if (Result = nil) then
begin
if (FOwnCookieManager = nil) then
begin
FOwnCookieManager := TclCookieManager.Create(nil);
end;
Result := FOwnCookieManager;
end;
end;
procedure TclHttp.InternalGet(const AUrl: string; ARequest: TclHttpRequest; AResponseHeader: TStrings; ADestination: TStream);
var
s: string;
req: TclHttpRequest;
begin
req := ARequest;
if (req = nil) then
begin
req := GetRequest();
end;
s := Trim(req.RequestSource.Text);
if (s <> '') then
begin
s := '?' + s;
end;
s := AUrl + s;
SendRequest('GET', s, req.HeaderSource, nil, AResponseHeader, ADestination);
end;
procedure TclHttp.InternalHead(const AUrl: string; AResponseHeader: TStrings);
begin
SendRequest('HEAD', AUrl, GetRequest(), AResponseHeader, nil);
end;
procedure TclHttp.InternalPut(const AUrl, AContentType: string; ASource: TStream; AResponseHeader: TStrings; AResponseBody: TStream);
var
req: TclHttpRequest;
begin
req := GetRequest();
req.Header.Accept := '';
if (AContentType <> '') then
begin
req.Header.ContentType := AContentType;
end;
SendRequest('PUT', AUrl, req.HeaderSource, ASource, AResponseHeader, AResponseBody);
end;
procedure TclHttp.InternalPost(const AUrl: string; ARequest: TclHttpRequest; AResponseHeader: TStrings; AResponseBody: TStream);
var
req: TclHttpRequest;
begin
req := ARequest;
if (req = nil) then
begin
req := GetRequest();
end;
SendRequest('POST', AUrl, req, AResponseHeader, AResponseBody);
end;
procedure TclHttp.InternalDelete(const AUrl: string; AResponseHeader: TStrings; AResponseBody: TStream);
begin
SendRequest('DELETE', AUrl, GetRequest(), AResponseHeader, AResponseBody);
end;
procedure TclHttp.Post(const AUrl: string; ARequest: TclHttpRequest; AResponseBody: TStrings);
var
dest: TStream;
begin
dest := TMemoryStream.Create();
try
Post(AUrl, ARequest, dest);
dest.Position := 0;
TclStringsUtils.LoadStrings(dest, AResponseBody, GetResponseCharSet());
finally
dest.Free();
end;
end;
procedure TclHttp.Put(const AUrl: string; ASource: TStrings);
begin
Put(AUrl, '', ASource);
end;
procedure TclHttp.Put(const AUrl: string; ASource, AResponseBody: TStrings);
begin
Put(AUrl, '', ASource, AResponseBody);
end;
procedure TclHttp.Put(const AUrl: string; ASource: TStream; AResponseHeader, AResponseBody: TStrings);
begin
Put(AUrl, '', ASource, AResponseHeader, AResponseBody);
end;
procedure TclHttp.Post(const AUrl: string; ARequest: TclHttpRequest; AResponseHeader: TStrings; AResponseBody: TStream);
begin
InternalPost(AUrl, ARequest, AResponseHeader, AResponseBody);
end;
procedure TclHttp.Put(const AUrl, AContentType: string; ASource, AResponseBody: TStream);
begin
InternalPut(AUrl, AContentType, ASource, nil, AResponseBody);
end;
procedure TclHttp.Put(const AUrl, AContentType: string; ASource: TStrings);
var
src: TStream;
begin
src := TMemoryStream.Create();
try
TclStringsUtils.SaveStrings(ASource, src, CharSet);
src.Position := 0;
Put(AUrl, AContentType, src);
finally
src.Free();
end;
end;
procedure TclHttp.Put(const AUrl, AContentType: string; ASource: TStream);
var
dst: TStream;
begin
dst := TclNullStream.Create();
try
Put(AUrl, AContentType, ASource, dst);
finally
dst.Free();
end;
end;
procedure TclHttp.Put(const AUrl, AContentType: string; ASource: TStream;
AResponseHeader, AResponseBody: TStrings);
var
dst: TStream;
begin
dst := TMemoryStream.Create();
try
InternalPut(AUrl, AContentType, ASource, AResponseHeader, dst);
dst.Position := 0;
TclStringsUtils.LoadStrings(dst, AResponseBody, GetResponseCharSet());
finally
dst.Free();
end;
end;
procedure TclHttp.Put(const AUrl, AContentType: string; ASource, AResponseBody: TStrings);
var
src: TStream;
begin
src := TMemoryStream.Create();
try
TclStringsUtils.SaveStrings(ASource, src, CharSet);
src.Position := 0;
Put(AUrl, AContentType, src, AResponseBody);
finally
src.Free();
end;
end;
procedure TclHttp.Put(const AUrl, AContentType: string; ASource: TStream; AResponseBody: TStrings);
var
dst: TStream;
begin
dst := TMemoryStream.Create();
try
Put(AUrl, AContentType, ASource, dst);
dst.Position := 0;
TclStringsUtils.LoadStrings(dst, AResponseBody, GetResponseCharSet());
finally
dst.Free();
end;
end;
procedure TclHttp.Delete(const AUrl: string; AResponseHeader, AResponseBody: TStrings);
var
responseBody: TStream;
begin
responseBody := TMemoryStream.Create();
try
InternalDelete(AUrl, AResponseHeader, responseBody);
responseBody.Position := 0;
TclStringsUtils.LoadStrings(responseBody, AResponseBody, GetResponseCharSet());
finally
responseBody.Free();
end;
end;
procedure TclHttp.Delete(const AUrl: string; AResponseHeader: TStrings; AResponseBody: TStream);
begin
InternalDelete(AUrl, AResponseHeader, AResponseBody);
end;
procedure TclHttp.Delete(const AUrl: string; AResponseBody: TStream);
begin
InternalDelete(AUrl, nil, AResponseBody);
end;
{ EclHttpError }
constructor EclHttpError.Create(const AErrorMsg: string;
AErrorCode: Integer; const AResponseText: string);
begin
inherited Create(AErrorMsg, AErrorCode);
FResponseText := AResponseText;
end;
end.
|
unit ce_search;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Menus, StdCtrls, actnList, Buttons, SynEdit, SynEditSearch, SynEditTypes,
ce_common, ce_mru, ce_widget, ce_synmemo, ce_interfaces, ce_observer,
ce_writableComponent;
type
// TCESearchWidget persistents settings
TCESearchOptions = class(TWritableLfmTextComponent)
private
fPrompt: boolean;
fFromCur: boolean;
fRegex: boolean;
fCaseSens:boolean;
fBackWard: boolean;
fWholeWord: boolean;
fMrSearches: TStringList;
fMrReplacements: TStringList;
procedure setMrSearches(aValue: TStringList);
procedure setMrReplacements(aValue: TStringList);
published
property prompt: boolean read fPrompt write fPrompt;
property fromCursor: boolean read fFromCur write fFromCur;
property regex: boolean read fRegex write fRegex;
property caseSensistive: boolean read fCaseSens write fCaseSens;
property backward: boolean read fBackWard write fBackWard;
property wholeWord: boolean read fWholeWord write fWholeWord;
property recentSearches: TStringList read fMrSearches write setMrSearches;
property recentReplacements: TStringList read fMrReplacements write setMrReplacements;
public
constructor create(aOwner: TComponent); override;
destructor destroy; override;
procedure Assign(aValue: TPersistent); override;
procedure AssignTo(aValue: TPersistent); override;
end;
{ TCESearchWidget }
TCESearchWidget = class(TCEWidget, ICEMultiDocObserver)
btnFind: TBitBtn;
btnReplace: TBitBtn;
btnReplaceAll: TBitBtn;
cbToFind: TComboBox;
cbReplaceWth: TComboBox;
chkEnableRep: TCheckBox;
chkPrompt: TCheckBox;
chkRegex: TCheckBox;
chkWWord: TCheckBox;
chkBack: TCheckBox;
chkFromCur: TCheckBox;
chkCaseSens: TCheckBox;
grpOpts: TGroupBox;
imgList: TImageList;
Panel1: TPanel;
procedure cbReplaceWthChange(Sender: TObject);
procedure cbToFindChange(Sender: TObject);
procedure chkEnableRepChange(Sender: TObject);
private
fDoc: TCESynMemo;
fToFind: string;
fReplaceWth: string;
fActFindNext, fActReplaceNext: TAction;
fActReplaceAll: TAction;
fSearchMru, fReplaceMru: TCEMruList;
fCancelAll: boolean;
fHasSearched: boolean;
fHasRestarted: boolean;
function getOptions: TSynSearchOptions;
procedure actReplaceAllExecute(sender: TObject);
procedure replaceEvent(Sender: TObject; const ASearch, AReplace:
string; Line, Column: integer; var ReplaceAction: TSynReplaceAction);
protected
procedure updateImperative; override;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
//
procedure docNew(aDoc: TCESynMemo);
procedure docClosing(aDoc: TCESynMemo);
procedure docFocused(aDoc: TCESynMemo);
procedure docChanged(aDoc: TCESynMemo);
//
function contextName: string; override;
function contextActionCount: integer; override;
function contextAction(index: integer): TAction; override;
//
procedure actFindNextExecute(sender: TObject);
procedure actReplaceNextExecute(sender: TObject);
end;
implementation
{$R *.lfm}
const
OptsFname = 'search.txt';
{$REGION TCESearchOptions ------------------------------------------------------}
constructor TCESearchOptions.create(aOwner: TComponent);
begin
inherited;
fMrReplacements := TStringList.Create;
fMrSearches := TStringList.Create;
end;
destructor TCESearchOptions.destroy;
begin
fMrSearches.Free;
fMrReplacements.Free;
inherited;
end;
procedure TCESearchOptions.Assign(aValue: TPersistent);
var
widg: TCESearchWidget;
begin
if aValue is TCESearchWidget then
begin
widg := TCESearchWidget(aValue);
fMrSearches.Assign(widg.fSearchMru);
fMrReplacements.Assign(widg.fReplaceMru);
fPrompt := widg.chkPrompt.Checked;
fBackWard := widg.chkBack.Checked;
fCaseSens := widg.chkCaseSens.Checked;
fRegex := widg.chkRegex.Checked;
fFromCur := widg.chkFromCur.Checked;
fWholeWord := widg.chkWWord.Checked;
end
else inherited;
end;
procedure TCESearchOptions.AssignTo(aValue: TPersistent);
var
widg: TCESearchWidget;
begin
if aValue is TCESearchWidget then
begin
widg := TCESearchWidget(aValue);
widg.cbToFind.Items.Assign(fMrSearches);
widg.fSearchMru.Assign(fMrSearches);
widg.cbReplaceWth.Items.Assign(fMrReplacements);
widg.fReplaceMru.Assign(fMrReplacements);
widg.chkPrompt.Checked := fPrompt;
widg.chkBack.Checked := fBackWard;
widg.chkCaseSens.Checked:= fCaseSens;
widg.chkRegex.Checked := fRegex;
widg.chkFromCur.Checked := fFromCur;
widg.chkWWord.Checked := fWholeWord;
end
else inherited;
end;
procedure TCESearchOptions.setMrSearches(aValue: TStringList);
begin
fMrSearches.Assign(aValue);
end;
procedure TCESearchOptions.setMrReplacements(aValue: TStringList);
begin
fMrReplacements.Assign(aValue);
end;
{$ENDREGION}
{$REGION Standard Comp/Obj------------------------------------------------------}
constructor TCESearchWidget.Create(aOwner: TComponent);
var
fname: string;
begin
fActFindNext := TAction.Create(self);
fActFindNext.Caption := 'Find';
fActFindNext.OnExecute := @actFindNextExecute;
fActReplaceNext := TAction.Create(self);
fActReplaceNext.Caption := 'Replace';
fActReplaceNext.OnExecute := @actReplaceNextExecute;
fActReplaceAll := TAction.Create(self);
fActReplaceAll.Caption := 'Replace all';
fActReplaceAll.OnExecute := @actReplaceAllExecute;
inherited;
//
fSearchMru := TCEMruList.Create;
fReplaceMru:= TCEMruList.Create;
//
fname := getCoeditDocPath + OptsFname;
if FileExists(fname) then with TCESearchOptions.create(nil) do
try
loadFromFile(fname);
AssignTo(self);
finally
free;
end;
//
btnFind.Action := fActFindNext;
btnReplace.Action := fActReplaceNext;
btnReplaceAll.Action := fActReplaceAll;
updateImperative;
//
EntitiesConnector.addObserver(self);
end;
destructor TCESearchWidget.Destroy;
begin
with TCESearchOptions.create(nil) do
try
Assign(self);
saveToFile(getCoeditDocPath + OptsFname);
finally
free;
end;
//
EntitiesConnector.removeObserver(self);
fSearchMru.Free;
fReplaceMru.Free;
inherited;
end;
{$ENDREGION}
{$REGION ICEContextualActions---------------------------------------------------}
function TCESearchWidget.contextName: string;
begin
exit('Search');
end;
function TCESearchWidget.contextActionCount: integer;
begin
exit(3);
end;
function TCESearchWidget.contextAction(index: integer): TAction;
begin
case index of
0: exit(fActFindNext);
1: exit(fActReplaceNext);
2: exit(fActReplaceAll);
else exit(nil);
end;
end;
function TCESearchWidget.getOptions: TSynSearchOptions;
begin
result := [];
if chkRegex.Checked then result += [ssoRegExpr];
if chkWWord.Checked then result += [ssoWholeWord];
if chkBack.Checked then result += [ssoBackwards];
if chkCaseSens.Checked then result += [ssoMatchCase];
if chkPrompt.Checked then result += [ssoPrompt];
end;
function dlgReplaceAll: TModalResult;
const
Btns = [mbYes, mbNo, mbYesToAll, mbNoToAll];
begin
exit( MessageDlg('Coedit', 'Replace this match ?', mtConfirmation, Btns, ''));
end;
procedure TCESearchWidget.replaceEvent(Sender: TObject; const ASearch, AReplace:
string; Line, Column: integer; var ReplaceAction: TSynReplaceAction);
begin
case dlgReplaceAll of
mrYes: ReplaceAction := raReplace;
mrNo: ReplaceAction := raSkip;
mrYesToAll: ReplaceAction := raReplaceAll;
mrCancel, mrClose, mrNoToAll:
begin
ReplaceAction := raCancel;
fCancelAll := true;
end;
end;
end;
procedure TCESearchWidget.actFindNextExecute(sender: TObject);
begin
if fDoc = nil then exit;
//
fSearchMru.Insert(0,fToFind);
cbToFind.Items.Assign(fSearchMru);
//
if not chkFromCur.Checked then
begin
if chkBack.Checked then
fDoc.CaretXY := Point(high(Integer), high(Integer))
else
begin
if not fHasRestarted then
fDoc.CaretXY := Point(0,0);
fHasRestarted := true;
end;
end
else if fHasSearched then
begin
if chkBack.Checked then
fDoc.CaretX := fDoc.CaretX - 1
else
fDoc.CaretX := fDoc.CaretX + length(fToFind);
end;
if fDoc.SearchReplace(fToFind, '', getOptions) = 0 then
dlgOkInfo('the expression cannot be found')
else
begin
fHasSearched := true;
fHasRestarted := false;
chkFromCur.Checked := true;
end;
updateImperative;
end;
procedure TCESearchWidget.actReplaceNextExecute(sender: TObject);
begin
if fDoc = nil then exit;
//
fSearchMru.Insert(0, fToFind);
fReplaceMru.Insert(0, fReplaceWth);
cbToFind.Items.Assign(fSearchMru);
cbReplaceWth.Items.Assign(fReplaceMru);
//
if chkPrompt.Checked then
fDoc.OnReplaceText := @replaceEvent;
if not chkFromCur.Checked then
begin
if chkBack.Checked then
fDoc.CaretXY := Point(high(Integer), high(Integer))
else
fDoc.CaretXY := Point(0,0);
end
else if fHasSearched then
begin
if chkBack.Checked then
fDoc.CaretX := fDoc.CaretX - 1
else
fDoc.CaretX := fDoc.CaretX + length(fToFind);
end;
if fDoc.SearchReplace(fToFind, fReplaceWth, getOptions + [ssoReplace]) <> 0 then
fHasSearched := true;
fDoc.OnReplaceText := nil;
updateImperative;
end;
procedure TCESearchWidget.actReplaceAllExecute(sender: TObject);
var
opts: TSynSearchOptions;
begin
if fDoc = nil then exit;
cbReplaceWth.Items.Assign(fReplaceMru);
opts := getOptions + [ssoReplace];
opts -= [ssoBackwards];
//
fSearchMru.Insert(0, fToFind);
fReplaceMru.Insert(0, fReplaceWth);
if chkPrompt.Checked then fDoc.OnReplaceText := @replaceEvent;
fDoc.CaretXY := Point(0,0);
while(true) do
begin
if fDoc.SearchReplace(fToFind, fReplaceWth, opts) = 0
then break;
if fCancelAll then
begin
fCancelAll := false;
break;
end;
end;
fDoc.OnReplaceText := nil;
updateImperative;
end;
{$ENDREGION}
{$REGION ICEMultiDocObserver ---------------------------------------------------}
procedure TCESearchWidget.docNew(aDoc: TCESynMemo);
begin
fDoc := aDoc;
updateImperative;
end;
procedure TCESearchWidget.docClosing(aDoc: TCESynMemo);
begin
if fDoc = aDoc then fDoc := nil;
updateImperative;
end;
procedure TCESearchWidget.docFocused(aDoc: TCESynMemo);
begin
if fDoc = aDoc then exit;
fDoc := aDoc;
updateImperative;
end;
procedure TCESearchWidget.docChanged(aDoc: TCESynMemo);
begin
end;
{$ENDREGION}
{$REGION Misc. -----------------------------------------------------------------}
procedure TCESearchWidget.cbToFindChange(Sender: TObject);
begin
if Updating then exit;
fToFind := cbToFind.Text;
fHasSearched := false;
updateImperative;
end;
procedure TCESearchWidget.chkEnableRepChange(Sender: TObject);
begin
if Updating then exit;
updateImperative;
end;
procedure TCESearchWidget.cbReplaceWthChange(Sender: TObject);
begin
if Updating then exit;
fReplaceWth := cbReplaceWth.Text;
fHasSearched := false;
updateImperative;
end;
procedure TCESearchWidget.updateImperative;
begin
btnFind.Enabled := (fDoc <> nil) and (fToFind <> '');
btnReplace.Enabled := (fDoc <> nil) and (chkEnableRep.Checked) and (fToFind <> '');
btnReplaceAll.Enabled := btnReplace.Enabled;
cbReplaceWth.Enabled := (fDoc <> nil) and (chkEnableRep.Checked);
cbToFind.Enabled := fDoc <> nil;
end;
{$ENDREGION}
end.
|
UNIT CountingWords1;
INTERFACE
TYPE
Tree = ^Node;
Node = RECORD
Word: STRING; //поле ячейки, содержит в себе слово-символы
Counter: INTEGER; //счётчик, показывает, кол-во одинаково обработанных Word при вставке в дерево
Left, Right: Tree //указатели в бинарном дереве
END;
TempNode = RECORD
Word: STRING;
Counter: INTEGER
END;
PROCEDURE CountWord(Word: STRING); { Вставляет слово Word в бинарное дерево }
PROCEDURE PrintFileStatistic(VAR DataFile: TEXT); { Печать содержимого дерева }
IMPLEMENTATION
{ Реализовано бинарным деревом, с контролем по памяти }
CONST
MaxWordAmount = 20;
VAR
WordAmount: INTEGER;
WasOverflow: BOOLEAN;
PROCEDURE EmptyTree(VAR Pointer: Tree);
{ Используй для полного уничтожения дерева }
BEGIN { EmptyTree }
IF Pointer <> NIL
THEN
BEGIN
EmptyTree(Pointer^.Left);
EmptyTree(Pointer^.Right);
DISPOSE(Pointer);
Pointer := NIL;
WordAmount := WordAmount - 1
END
END; { EmptyTree }
VAR
TempFile1, TempFile2: FILE OF TempNode;
PROCEDURE SaveNode(VAR SavedNode: TempNode);
{ Бери ячейку динамической структуры и сохраняй её в типизированный файл }
VAR
Temp: TempNode;
BEGIN { SaveNode }
RESET(TempFile1);
REWRITE(TempFile2);
//запишем хотя бы одно слово
IF EOF(TempFile1) THEN WRITE(TempFile1, SavedNode);
RESET(TempFile1);
//транслируем Т1 в Т2, попутно ищем место для вставки ячейки
WHILE NOT EOF(TempFile1)
DO
BEGIN
READ(TempFile1, Temp);
IF SavedNode.Word = Temp.Word
THEN
BEGIN
SavedNode.Counter := SavedNode.Counter + Temp.Counter;
WRITE(TempFile2, SavedNode);
BREAK
END;
IF SavedNode.Word > Temp.Word THEN WRITE(TempFile2, Temp);
IF SavedNode.Word < Temp.Word THEN WRITE(TempFile2, SavedNode, Temp);
IF EOF(TempFile1) AND (SavedNode.Word <> Temp.Word) THEN WRITE(TempFile2, SavedNode)
END;
//обновим состояние Т1 до Т2
REWRITE(TempFile1);
RESET(TempFile2);
WHILE NOT EOF(TempFile2)
DO
BEGIN
READ(TempFile2, Temp);
WRITE(TempFile1, Temp)
END
END; { SaveNode }
PROCEDURE WriteTempFile(VAR DataFile: TEXT);
{ Используй для вывода бинарного файла в DataFile }
VAR
Temp: TempNode;
BEGIN
RESET(TempFile2);
WHILE NOT EOF(TempFile2)
DO
BEGIN
READ(TempFile2, Temp);
WRITELN(DataFile, Temp.Word, ' ', Temp.Counter)
END
END;
PROCEDURE SaveTree(VAR Pointer: Tree);
{ Пройди по всем элементам дерева и сохрани их }
VAR
SavedNode: TempNode;
BEGIN { SaveTree }
IF Pointer <> NIL
THEN
BEGIN
SaveTree(Pointer^.Left);
SavedNode.Word := Pointer^.Word;
SavedNode.Counter := Pointer^.Counter;
SaveNode(SavedNode);
SaveTree(Pointer^.Right)
END
END; { SaveTree }
VAR
Root: Tree;
PROCEDURE Insert(VAR Pointer: Tree; Word: STRING);
{ Кладёт слово в бинарное дерево, реализован контроль переполнения }
//Требуется знать устройтсво бинарного дерева!//
BEGIN { Insert }
IF WordAmount < MaxWordAmount
THEN
IF Pointer = NIL
THEN
BEGIN
NEW(Pointer);
Pointer^.Word := Word;
Pointer^.Counter := 1;
Pointer^.Left := NIL;
Pointer^.Right := NIL;
WordAmount := WordAmount + 1 //
END
ELSE
BEGIN
IF Pointer^.Word > Word
THEN
Insert(Pointer^.Left, Word);
IF Pointer^.Word < Word
THEN
Insert(Pointer^.Right, Word);
{ Слово уже есть в дереве?
Тогда просто увеличить счётчик на 1,
без вставки в дерево }
IF Pointer^.Word = Word
THEN
Pointer^.Counter := Pointer^.Counter + 1
END
ELSE
BEGIN //контроль переполнения
SaveTree(Root);
EmptyTree(Root);
DISPOSE(Root);
Root := NIL;
WordAmount := 0;
WasOverflow := TRUE
END
END; { Insert }
PROCEDURE PrintTree(Pointer: Tree; VAR DataFile: TEXT);
{ Печать бинарного дерева }
BEGIN { PrintTree }
IF Pointer <> NIL
THEN
BEGIN
PrintTree(Pointer^.Left, DataFile);
{ Pointer^.Word = '' - пробел, если хочешь отобразить
кол-во пробелов в тексте - убери условие }
IF Pointer^.Word <> ''
THEN
WRITELN(DataFile, Pointer^.Word, ' ', Pointer^.Counter);
PrintTree(Pointer^.Right, DataFile);
END
END; { PrintTree }
PROCEDURE CountWord(Word: STRING);
BEGIN { CountWord }
Insert(Root, Word)
END; { CountWord }
PROCEDURE PrintFileStatistic(VAR DataFile: TEXT);
BEGIN { PrintFileStatistic }
IF WasOverflow
THEN
BEGIN
SaveTree(Root); //сохранить остатки
WriteTempFile(DataFile);
END
ELSE
PrintTree(Root, DataFile)
END; { PrintFileStatistic }
BEGIN { InsertTree }
WordAmount := 0;
WasOverflow := FALSE;
Root := NIL; //tree's root
ASSIGN(TempFile1, '~Temp1.txt'); //file, which contains saved tree after tree's overflow event
REWRITE(TempFile1);
ASSIGN(TempFile2, '~Temp2.txt');
REWRITE(TempFile2)
END. { InsertTree }
|
unit DAO.ContatosEmpresa;
interface
uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.ContatosEmpresa;
type
TContatosEmpresaDAO = class
private
FConexao : TConexao;
public
constructor Create();
function GetID(iID: Integer): Integer;
function Insert(aContatos: TContatosEmpresa): Boolean;
function Update(aContatos: TContatosEmpresa): Boolean;
function Delete(aContatos: TContatosEmpresa): Boolean;
function Localizar(aParam: Array of variant): TFDQuery;
end;
const
TABLENAME = 'cadastro_contatos_empresa';
implementation
function TContatosEmpresaDAO.GetID(iID: Integer): Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(SEQ_CONTATO),0) + 1 from ' + TABLENAME + ' WHERE ID_EMPRESA = ' + iID.toString);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Free;
end;
end;
function TContatosEmpresaDAO.Insert(aContatos: TContatosEmpresa): Boolean;
var
sSQL: String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
aContatos.Sequencia := GetID(aContatos.ID);
sSQL := 'INSERT INTO ' + TABLENAME + '(' +
'ID_EMPRESA, SEQ_CONTATO, DES_CONTATO, NUM_TELEFONE, DES_EMAIL) ' +
'VALUES (' +
':pID_EMPRESA, :pSEQ_CONTATO, :pDES_CONTATO, :pNUM_TELEFONE, :pDES_EMAIL);';
FDQuery.ExecSQL(sSQL,[aContatos.ID, aContatos.Sequencia, aContatos.Descricao, aContatos.Telefone, aContatos.EMail]);
Result := True;
finally
FDQuery.Free;
end;
end;
function TContatosEmpresaDAO.Localizar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('WHERE ID_EMPRESA = :ID_EMPRESA');
FDQuery.ParamByName('ID_EMPRESA').AsInteger := aParam[1];
end;
if aParam[0] = 'SEQUENCIA' then
begin
FDQuery.SQL.Add('WHERE ID_EMPRESA = :ID_EMPRESA AND SEQ_CONTATO = :SEQ_CONTATO');
FDQuery.ParamByName('ID_EMPRESA').AsInteger := aParam[1];
FDQuery.ParamByName('SEQ_ENDERECO').AsInteger := aParam[2];
end;
if aParam[0] = 'DESCRICAO' then
begin
FDQuery.SQL.Add('WHERE DES_CONTATO LIKE :DES_CONTATO');
FDQuery.ParamByName('DES_CONTATO').AsString := aParam[1];
end;
if aParam[0] = 'TELEFONE' then
begin
FDQuery.SQL.Add('WHERE NUM_TELEFONE LIKE :NUM_TELEFONE');
FDQuery.ParamByName('NUM_TELEFONE').AsString := aParam[1];
end;
if aParam[0] = 'EMAIL' then
begin
FDQuery.SQL.Add('WHERE DES_EMAIL LIKE :DES_EMAIL');
FDQuery.ParamByName('DES_EMAIL').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('WHERE ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
Result := FDQuery;
end;
function TContatosEmpresaDAO.Update(aContatos: TContatosEmpresa): Boolean;
var
sSQL: String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
sSQL := 'UPDATE ' + TABLENAME + ' SET ' +
'DES_CONTATO = :pDES_CONTATO, NUM_TELEFONE = :pNUM_TELEFONE, DES_EMAIL = :pDES_EMAIL ' +
'WHERE ID_EMPRESA = :pID_EMPRESA AND SEQ_CONTATO = :pSEQ_CONTATO;';
FDQuery.ExecSQL(sSQL,[aContatos.Descricao, aContatos.Telefone, aContatos.EMail,
aContatos.ID, aContatos.Sequencia]);
Result := True;
finally
FDQuery.Free;
end;
end;
constructor TContatosEmpresaDAO.Create;
begin
FConexao := TConexao.Create;
end;
function TContatosEmpresaDAO.Delete(aContatos: TContatosEmpresa): Boolean;
var
sSQL: String;
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
if aContatos.Sequencia = -1 then
begin
sSQL := 'DELETE FROM ' + TABLENAME + ' ' +
'WHERE ID_EMPRESA = :pID_EMPRESA;';
FDQuery.ExecSQL(sSQL,[aContatos.ID]);
end
else
begin
sSQL := 'DELETE FROM ' + TABLENAME + ' ' +
'WHERE ID_EMPRESA = :pID_EMPRESA AND SEQ_CONTATO = :pSEQ_CONTATO;';
FDQuery.ExecSQL(sSQL,[aContatos.ID, aContatos.Sequencia]);
end;
Result := True;
finally
FDQuery.Free;
end;
end;
end.
|
PROGRAM TestRemove(INPUT,OUTPUT);
{Читает строку из входа, пропускает её через RemoveExtraBlanks}
USES Queue;
PROCEDURE RemoveExtraBlanks;
{Удаляет лишние пробелы между словами на одной строке}
VAR
Ch, Blank, LineEnd: CHAR;
BEGIN {RemoveExtraBlanks}
Blank := ' ';
LineEnd := '#';
AddQ(LineEnd); {помечаем конец текста в очереди}
HeadQ(Ch); {Ch = 1ый элемент}
WHILE Ch = Blank
DO
BEGIN
DelQ;
HeadQ(Ch)
END;
WHILE Ch <> LineEnd
DO
BEGIN
WHILE (Ch <> Blank) AND (Ch <> LineEnd)
DO
BEGIN
AddQ(Ch);
DelQ;
HeadQ(Ch)
END;
WHILE Ch = Blank
DO
BEGIN
DelQ;
HeadQ(Ch)
END;
IF Ch <> LineEnd
THEN
AddQ(Blank)
END;
DelQ {удаяем LineEnd из очереди}
END; {RemoveExtraBlanks}
VAR
Ch: CHAR;
BEGIN {TestRemove}
EmptyQ;
WHILE NOT EOLN
DO
BEGIN
READ(Ch);
AddQ(Ch)
END;
WRITE('Вход: ');
WriteQ;
RemoveExtraBlanks;
WRITE('Выход: ');
HeadQ(Ch);
WriteQ;
WRITELN
END. {TestRemove}
|
PROGRAM WriteSymbol(INPUT, OUTPUT);
CONST
Min = 0;
Max = 25;
DrawingSymbol = 'X';
SpaceSymbol = ' ';
SymbolWidth = 5;
TYPE
Matrix = SET OF Min..Max;
VAR
Symbol: CHAR;
MatrixSymbol: Matrix;
PROCEDURE DefineSymbol(VAR Symbol: CHAR; VAR MatrixSymbol: Matrix);
BEGIN {DefineSymbol}
CASE Symbol OF
'A': MatrixSymbol := [1, 6, 7, 11, 13, 16, 17, 18, 19, 21, 25];
'B': MatrixSymbol := [1, 2, 3, 4, 6, 10, 11, 12, 13, 14, 16, 20, 21, 22, 23, 24];
'C': MatrixSymbol := [2, 3, 4, 5, 6, 11, 16, 22, 23, 24, 25];
'D': MatrixSymbol := [1, 2, 3, 4, 6, 10, 11, 15, 16, 20, 21, 22, 23, 24];
'E': MatrixSymbol := [1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25];
'F': MatrixSymbol := [1, 2, 3, 4, 5, 6, 11, 12, 13, 16, 21];
'G': MatrixSymbol := [2, 3, 4, 6, 11, 13, 14, 15, 16, 20, 22, 23, 24];
'H': MatrixSymbol := [1, 5, 6, 10, 11, 12, 13, 14, 15, 16, 20, 21, 25];
'I': MatrixSymbol := [2, 3, 4, 8, 13, 18, 22, 23, 24];
'J': MatrixSymbol := [1, 2, 3, 4, 5, 8, 13, 16, 18, 22];
'K': MatrixSymbol := [1, 4, 6, 8, 11, 12, 16, 18, 21, 24];
'L': MatrixSymbol := [1, 6, 11, 16, 21, 22, 23, 24, 25];
'M': MatrixSymbol := [1, 5, 6, 7, 9, 10, 11, 13, 15, 16, 20, 21, 25];
'N': MatrixSymbol := [1, 5, 6, 7, 10, 11, 13, 15, 16, 19, 20, 21, 25];
'O': MatrixSymbol := [2, 3, 4, 6, 10, 11, 15, 16, 20, 22, 23, 24];
'P': MatrixSymbol := [1, 2, 3, 6, 9, 11, 12, 13, 16, 21];
'Q': MatrixSymbol := [2, 3, 4, 6, 10, 11, 15, 16, 19, 22, 23, 25];
'R': MatrixSymbol := [1, 2, 6, 8, 11, 12, 16, 18, 21, 24];
'S': MatrixSymbol := [2, 3, 4, 5, 6, 12, 13, 14, 20, 21, 22, 23, 24];
'T': MatrixSymbol := [1, 2, 3, 4, 5, 8, 13, 18, 23];
'U': MatrixSymbol := [1, 5, 6, 10, 11, 15, 16, 20, 22, 23, 24];
'V': MatrixSymbol := [1, 5, 7, 9, 12, 14, 18];
'W': MatrixSymbol := [1, 5, 6, 10, 11, 13, 15, 16, 18, 20, 22, 24];
'X': MatrixSymbol := [1, 5, 7, 9, 13, 17, 19, 21, 25];
'Y': MatrixSymbol := [1, 5, 7, 9, 13, 18, 23];
'Z': MatrixSymbol := [1, 2, 3, 4, 5, 9, 13, 17, 21, 22, 23, 24, 25]
ELSE
MatrixSymbol := []
END
END; {DefineSymbol}
PROCEDURE WriteMatrixSymbol(VAR MatrixSymbol: Matrix);
VAR
Count: INTEGER;
BEGIN {WriteMatrixSymbol}
FOR Count := Min TO Max
DO
BEGIN
IF (Count IN MatrixSymbol)
THEN
WRITE(DrawingSymbol)
ELSE
WRITE(SpaceSymbol);
IF (COUNT MOD SymbolWidth = 0)
THEN
WRITELN
END
END; {WriteMatrixSymbol}
BEGIN {WriteSymbol}
IF NOT EOLN
THEN
BEGIN
READ(INPUT, Symbol);
DefineSymbol(Symbol, MatrixSymbol);
IF (MatrixSymbol = [])
THEN
WRITELN(Symbol, ' IS NOT DEFINED')
ELSE
WriteMatrixSymbol(MatrixSymbol)
END
ELSE
WRITELN('INPUT IS EMPTY')
END. {WriteSymbol}
|
unit secp256k1;
{ ******************
Big thanks to Velthuis for his BigInteger
You saved my ass :)
Multiplatform ECDSA Pair creation in pure Pascal
****************** {$DEFINE PUREPASCAL }
interface
uses
Velthuis.BigIntegers, misc, System.SysUtils, ClpBigInteger,
ClpIX9ECParameters,
ClpIECDomainParameters, ClpECDomainParameters, ClpIECKeyPairGenerator,
ClpECKeyPairGenerator, ClpIECKeyGenerationParameters,
ClpIAsymmetricCipherKeyPair, ClpIECPrivateKeyParameters,
ClpIECPublicKeyParameters, ClpECPrivateKeyParameters, ClpIECInterface, ClpHex,
ClpCustomNamedCurves, ClpHMacDsaKCalculator, ClpDigestUtilities;
type
TBIPoint = record
XCoordinate: BigInteger;
YCoordinate: BigInteger;
end;
function make256bit(var bi: BigInteger): BigInteger;
function secp256k1_get_public(privkey: AnsiString; forEth: boolean = false)
: AnsiString;
function secp256k1_signDER(e, d: AnsiString; forEth: boolean = false)
: AnsiString;
function getG: TBIPoint;
function getN: BigInteger;
function BIToHEX(bi: BigInteger): AnsiString;
implementation
uses
uHome;
function getG: TBIPoint;
var
tmp: BigInteger;
begin
result.XCoordinate := BigInteger.Parse
('0x079BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798');
result.YCoordinate := BigInteger.Parse
('0x0483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8');
end;
function make256bit(var bi: BigInteger): BigInteger;
begin
if bi.IsNegative then
bi := bi + BigInteger.Parse
('+0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F')
else
bi := bi mod BigInteger.Parse
('+0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF');
result := bi;
end;
function getP: BigInteger;
begin
result := BigInteger.Parse
('+0x0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F');
end;
function getN: BigInteger;
begin
result := BigInteger.Parse
('+0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141');
end;
function cmpecp(p, q: TBIPoint): boolean;
begin
result := (p.XCoordinate = q.XCoordinate) and (p.YCoordinate = q.YCoordinate)
end;
function BIToHEX(bi: BigInteger): AnsiString;
var
i: integer;
b: TArray<Byte>;
begin
bi := bi mod BigInteger.Parse
('0x10000000000000000000000000000000000000000000000000000000000000000');
b := bi.ToByteArray;
result := '';
for i := 31 downto Low(b) do
begin
result := result + inttohex(System.UInt8(b[i]), 2);
end;
end;
function point_add(p, q: TBIPoint): TBIPoint;
var
xp, yp, xq, yq, L, rx, ry: BigInteger;
bitwo, biP: BigInteger;
begin
// Android optimalisations
bitwo := BigInteger.Parse('2');
biP := getP;
/// ///////////////////
xp := p.XCoordinate;
yp := p.YCoordinate;
xq := q.XCoordinate;
yq := q.YCoordinate;
if cmpecp(p, q) then
L := (BigInteger.ModPow((yp * bitwo) mod biP, biP - bitwo, biP) *
(3 * xp * xp)) mod biP
else
L := (BigInteger.ModPow(xq - xp, biP - bitwo, biP) * (yq - yp)) mod biP;
rx := (BigInteger.Pow(L, 2) - xp) - xq;
ry := (L * xp) - (L * rx) - yp;
result.XCoordinate := rx mod biP;
result.YCoordinate := ry mod biP;
end;
function point_mul(p: TBIPoint; d: BigInteger): TBIPoint;
var
G, n, q: TBIPoint;
var
i: integer;
tmp: BigInteger;
bi0, bi1: BigInteger;
begin
bi0 := BigInteger.Zero;
bi1 := BigInteger.One;
n.XCoordinate := p.XCoordinate;
n.YCoordinate := p.YCoordinate;
q.XCoordinate := bi0;
q.YCoordinate := bi0;
for i := 0 to 255 do
begin
tmp := (bi1 shl i);
if (d and tmp <> bi0) then
begin
if (q.XCoordinate = bi0) and (q.YCoordinate = bi0) then
q := n
else
q := point_add(q, n);
end;
n := point_add(n, n);
end;
result := q;
end;
function hex64pad(data: TArray<System.Byte>; Padding: integer = 64): AnsiString;
var
i: integer;
Begin
for i := 0 to length(data) - 1 do
result := result + inttohex(data[i], 2);
while length(result) < Padding do
begin
result := '0' + result;
end;
// Keep padding!
result := Copy((result), 0, Padding);
End;
function secp256k1_get_public(privkey: AnsiString; forEth: boolean = false)
: AnsiString;
var
q: TBIPoint;
ss, sx, sy: AnsiString;
sign: AnsiString;
var
domain: IECDomainParameters;
generator: IECKeyPairGenerator;
keygenParams: IECKeyGenerationParameters;
KeyPair: IAsymmetricCipherKeyPair;
privParams: IECPrivateKeyParameters;
pubParams: IECPublicKeyParameters;
FCurve: IX9ECParameters;
PrivateKeyBytes, PayloadToDecodeBytes, DecryptedCipherText: TBytes;
RegeneratedPublicKey: IECPublicKeyParameters;
RegeneratedPrivateKey: IECPrivateKeyParameters;
PrivD: TBigInteger;
ax, ay: BigInteger;
begin
BigInteger.Decimal;
BigInteger.AvoidPartialFlagsStall(True);
ss := '$' + (privkey);
/// / Hyperspeed
FCurve := TCustomNamedCurves.GetByName('secp256k1');
domain := TECDomainParameters.Create(FCurve.Curve, FCurve.G, FCurve.n,
FCurve.H, FCurve.GetSeed);
PrivateKeyBytes := THex.Decode(privkey);
PrivD := TBigInteger.Create(1, PrivateKeyBytes);
RegeneratedPrivateKey := TECPrivateKeyParameters.Create('ECDSA',
PrivD, domain);
RegeneratedPublicKey := TECKeyPairGenerator.GetCorrespondingPublicKey
(RegeneratedPrivateKey);
sx := hex64pad(RegeneratedPublicKey.q.Normalize.AffineXCoord.ToBigInteger.
ToByteArrayUnsigned);
sy := hex64pad(RegeneratedPublicKey.q.Normalize.AffineYCoord.ToBigInteger.
ToByteArrayUnsigned);
if RegeneratedPublicKey.q.Normalize.AffineYCoord.ToBigInteger.&And
(TBigInteger.One).Equals(TBigInteger.Zero) then
sign := '02'
else
sign := '03';
if not forEth then
result := sign + sx
else
result := '04' + sx + sy;
wipeAnsiString(ss);
wipeAnsiString(privkey);
end;
function GetDetermisticRandomForSign(e, d: AnsiString): BigInteger;
var
hmac: THMacDsaKCalculator;
var
xn, xd: TBigInteger;
xe: TBytes;
begin
/// RFC 6979 - "Deterministic Usage of the Digital
/// Signature Algorithm (DSA) and Elliptic Curve Digital Signature
/// Algorithm (ECDSA)".
hmac := THMacDsaKCalculator.Create(TDigestUtilities.GetDigest('SHA-256'));
xn := TBigInteger.Create
('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141', 16);
xd := TBigInteger.Create(d, 16);
xe := THex.Decode(e);
hmac.Init(xn, xd, xe);
result := BigInteger.Parse('+0x00' + THex.Encode(hmac.NextK.ToByteArray));
hmac.Free;
wipeAnsiString(d);
end;
function secp256k1_signDER(e, d: AnsiString; forEth: boolean = false)
: AnsiString;
var
C: TBIPoint;
r, s: BigInteger;
k: BigInteger;
sr, ss: AnsiString;
b, recid: System.UInt8;
overflow: System.UInt8;
begin
overflow := 0;
BigInteger.Decimal;
BigInteger.AvoidPartialFlagsStall(True);
k := GetDetermisticRandomForSign(e, d); // mod getN;
C := point_mul(getG, k);
if C.YCoordinate.IsNegative then
C.YCoordinate := C.YCoordinate + BigInteger.Parse
('+0x0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F');;
if C.XCoordinate.IsNegative then
C.XCoordinate := C.XCoordinate + BigInteger.Parse
('+0x0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F');
r := C.XCoordinate mod getN;
// s=(e+rd)/k
s := BigInteger.ModInverse(k, getN) *
(BigInteger.Parse('+0x0' + (e)) +
(BigInteger(r * BigInteger.Parse('+0x0' + d)) mod getN)) mod getN;
if C.YCoordinate.isEven then
recid := 0
else
recid := 1;
if (s > (getN div BigInteger.Parse('2'))) then
begin
s := getN - s;
recid := recid xor 1;
end;
recid := 37 + (recid);
sr := BIToHEX(r);
ss := BIToHEX(s);
if length(sr + ss) mod 2 <> 0 then
begin
result := secp256k1_signDER(e, d);
exit;
end;
if forEth then
begin
result := inttohex(recid, 2);
result := result + 'a0' + sr + 'a0' + ss;
end
else
begin
b := System.UInt8(strtointdef('$' + Copy(sr, 0, 2), 0));
if b >= System.UInt8($80) then
sr := '00' + sr;
result := ss;
result := '02' + IntToTx(length(ss) div 2, 2) + result;
result := sr + result;
result := '02' + IntToTx(length(sr) div 2, 2) + result;
result := '30' + IntToTx(length(result) div 2, 2) + result;
end;
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 ClpDerTaggedObject;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
ClpCryptoLibTypes,
ClpAsn1Tags,
ClpDerSequence,
{$IFDEF DELPHI}
ClpIDerSequence,
{$ENDIF DELPHI}
ClpIProxiedInterface,
ClpDerOutputStream,
ClpAsn1TaggedObject,
ClpIDerTaggedObject;
type
/// <summary>
/// DER TaggedObject - in ASN.1 notation this is any object preceded by <br />
/// a [n] where n is some number - these are assumed to follow the
/// construction <br />rules (as with sequences). <br />
/// </summary>
TDerTaggedObject = class(TAsn1TaggedObject, IDerTaggedObject)
public
/// <param name="tagNo">
/// the tag number for this object.
/// </param>
/// <param name="obj">
/// the tagged object.
/// </param>
constructor Create(tagNo: Int32; const obj: IAsn1Encodable); overload;
/// <param name="explicitly">
/// true if an explicitly tagged object.
/// </param>
/// <param name="tagNo">
/// the tag number for this object.
/// </param>
/// <param name="obj">
/// the tagged object.
/// </param>
constructor Create(explicitly: Boolean; tagNo: Int32;
const obj: IAsn1Encodable); overload;
/// <summary>
/// create an implicitly tagged object that contains a zero length
/// sequence.
/// </summary>
/// <param name="tagNo">
/// the tag number for this object.
/// </param>
constructor Create(tagNo: Int32); overload;
procedure Encode(const derOut: TStream); override;
end;
implementation
{ TDerTaggedObject }
constructor TDerTaggedObject.Create(tagNo: Int32; const obj: IAsn1Encodable);
begin
Inherited Create(tagNo, obj);
end;
constructor TDerTaggedObject.Create(explicitly: Boolean; tagNo: Int32;
const obj: IAsn1Encodable);
begin
Inherited Create(explicitly, tagNo, obj)
end;
constructor TDerTaggedObject.Create(tagNo: Int32);
begin
Inherited Create(false, tagNo, TDerSequence.Empty)
end;
procedure TDerTaggedObject.Encode(const derOut: TStream);
var
bytes: TCryptoLibByteArray;
flags: Int32;
begin
if (not IsEmpty()) then
begin
bytes := obj.GetDerEncoded();
if (explicitly) then
begin
(derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.Constructed or
TAsn1Tags.Tagged, tagNo, bytes);
end
else
begin
//
// need to mark constructed types... (preserve Constructed tag)
//
flags := (bytes[0] and TAsn1Tags.Constructed) or TAsn1Tags.Tagged;
(derOut as TDerOutputStream).WriteTag(flags, tagNo);
derOut.Write(bytes[1], System.Length(bytes) - 1);
end
end
else
begin
(derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.Constructed or
TAsn1Tags.Tagged, tagNo, Nil);
end;
end;
end.
|
unit MFichas.Model.Permissoes.Metodos.Lista;
interface
uses
System.SysUtils,
System.Generics.Collections,
MFichas.Model.Entidade.USUARIOPERMISSOES,
MFichas.Model.Permissoes.Interfaces,
MFichas.Controller.Types;
type
TModelPermissoesMetodosLista = class(TInterfacedObject, iModelPermissoesLista)
private
[weak]
FParent: iModelPermissoes;
var FList : TDictionary<String, TTypeTipoUsuario>;
constructor Create(AParent: iModelPermissoes; var AList: TDictionary<String, TTypeTipoUsuario>);
public
destructor Destroy; override;
class function New(AParent: iModelPermissoes; var AList: TDictionary<String, TTypeTipoUsuario>): iModelPermissoesLista;
function AbrirCaixa : Integer;
function FecharCaixa : Integer;
function Suprimento : Integer;
function Sangria : Integer;
function CadastrarProdutos : Integer;
function CadastrarGrupos : Integer;
function CadastrarUsuarios : Integer;
function AcessarRelatorios : Integer;
function AcessarConfiguracoes : Integer;
function ExcluirProdutosPosImpressao: Integer;
function &End : iModelPermissoes;
end;
implementation
{ TModelPermissoesMetodosLista }
function TModelPermissoesMetodosLista.AbrirCaixa: Integer;
begin
Result := Integer(FList.Items['ABRIRCAIXA']);
end;
function TModelPermissoesMetodosLista.AcessarConfiguracoes: Integer;
begin
Result := Integer(FList.Items['ACESSARCONFIGURACOES']);
end;
function TModelPermissoesMetodosLista.AcessarRelatorios: Integer;
begin
Result := Integer(FList.Items['ACESSARRELATORIOS']);
end;
function TModelPermissoesMetodosLista.CadastrarGrupos: Integer;
begin
Result := Integer(FList.Items['CADASTRARGRUPOS']);
end;
function TModelPermissoesMetodosLista.CadastrarProdutos: Integer;
begin
Result := Integer(FList.Items['CADASTRARPRODUTOS']);
end;
function TModelPermissoesMetodosLista.CadastrarUsuarios: Integer;
begin
Result := Integer(FList.Items['CADASTRARUSUARIOS']);
end;
function TModelPermissoesMetodosLista.&End: iModelPermissoes;
begin
Result := FParent;
end;
constructor TModelPermissoesMetodosLista.Create(AParent: iModelPermissoes; var AList: TDictionary<String, TTypeTipoUsuario>);
begin
FParent := AParent;
FList := AList;
end;
destructor TModelPermissoesMetodosLista.Destroy;
begin
inherited;
end;
function TModelPermissoesMetodosLista.ExcluirProdutosPosImpressao: Integer;
begin
Result := Integer(FList.Items['EXCLUIRPRODUTOS']);
end;
function TModelPermissoesMetodosLista.FecharCaixa: Integer;
begin
Result := Integer(FList.Items['FECHARCAIXA']);
end;
class function TModelPermissoesMetodosLista.New(AParent: iModelPermissoes; var AList: TDictionary<String, TTypeTipoUsuario>): iModelPermissoesLista;
begin
Result := Self.Create(AParent, AList);
end;
function TModelPermissoesMetodosLista.Sangria: Integer;
begin
Result := Integer(FList.Items['SANGRIACAIXA']);
end;
function TModelPermissoesMetodosLista.Suprimento: Integer;
begin
Result := Integer(FList.Items['SUPRIMENTOCAIXA']);
end;
end.
|
program Shortest_Path_by_Ford_Bellman;
const
max = 100;
maxC = 10000;
var
c: array[1..max, 1..max] of Integer;
d: array[1..max] of Integer;
Trace: array[1..max] of Integer;
n, S, F: Integer;
procedure LoadGraph;
var
i, m: Integer;
u, v: Integer;
begin
ReadLn(n, m, S, F);
for u := 1 to n do
for v := 1 to n do
if u = v then c[u, v] := 0 else c[u, v] := maxC;
for i := 1 to m do ReadLn(u, v, c[u, v]);
end;
procedure Init;
var
i: Integer;
begin
for i := 1 to n do
begin
d[i] := c[S, i];
Trace[i] := S;
end;
end;
procedure Ford_Bellman;
var
Stop: Boolean;
u, v, CountLoop: Integer;
begin
CountLoop := 0;
repeat
Stop := True;
for u := 1 to n do
for v := 1 to n do
if d[v] > d[u] + c[u, v] then
begin
d[v] := d[u] + c[u, v];
Trace[v] := u;
Stop := False;
end;
Inc(CountLoop);
until Stop or (CountLoop >= n - 2);
end;
procedure PrintResult;
begin
if d[F] = maxC then
WriteLn('Path from ', S, ' to ', F, ' not found')
else
begin
WriteLn('Distance from ', S, ' to ', F, ': ', d[F]);
while F <> S do
begin
Write(F, '<-');
F := Trace[F];
end;
WriteLn(S);
end;
end;
begin
Assign(Input, 'MINPATH.INP'); Reset(Input);
Assign(Output, 'MINPATH.OUT'); Rewrite(Output);
LoadGraph;
Init;
Ford_Bellman;
PrintResult;
Close(Input);
Close(Output);
end.
|
library colorlib;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{$mode objfpc}{$H+}
uses
SysUtils,
Classes,
Math,
Header,
Finder,
Utils,
ColorConversion;
{$I SimbaPlugin.inc}
// -----------------------------------------------------------------------------------------
// Finder exports
procedure TFinder_Init(var Finder:TFinder; ComparePreset: EDistanceFormula; NumThreads, CacheSize:UInt8); cdecl;
begin
Finder.Init(ComparePreset, NumThreads, CacheSize);
end;
procedure TFinder_Free(var Finder:TFinder); cdecl;
begin
Finder.Free();
end;
procedure TFinder_SetFormula(var Finder:TFinder; ComparePreset: EDistanceFormula); cdecl;
begin
Finder.SetFormula(ComparePreset);
end;
function TFinder_GetFormula(var Finder:TFinder): EDistanceFormula; cdecl;
begin
Result := Finder.GetFormula();
end;
procedure TFinder_SetNumThreads(var Finder:TFinder; Threads:Uint8); cdecl;
begin
Finder.SetNumThreads(Threads);
end;
function TFinder_GetNumThreads(var Finder:TFinder): UInt8; cdecl;
begin
Result := Finder.GetNumThreads();
end;
procedure TFinder_SetMultipliers(var Finder:TFinder; const Mul: TMultiplier); cdecl;
begin
Finder.SetMultipliers(Mul);
end;
procedure TFinder_GetMultipliers(var Finder:TFinder; out Result: TMultiplier); cdecl;
begin
Result := Finder.GetMultipliers();
end;
function TFinder_GetMaxDistance(var Finder:TFinder): Single; cdecl;
begin
Result := Finder.GetMaxDistance();
end;
function TFinder_SimilarColors(var Finder:TFinder; Color1, Color2: TColor; Tolerance: Single): LongBool; cdecl;
begin
Result := Finder.SimilarColors(Color1, Color2, Tolerance);
end;
function TFinder_ColorDistance(var Finder:TFinder; color1, color2: TColor): Single; cdecl;
begin
Result := Finder.ColorDistance(Color1, Color2);
end;
procedure TFinder_MatchColor(var Finder:TFinder; src:TIntMatrix; var dest:TSingleMatrix; color:Int32); cdecl;
begin
Finder.MatchColor(src, dest, color);
end;
function TFinder_FindColor(var Finder:TFinder; src:TIntMatrix; out dest:TPointArray; color:TColor; tolerance:Single): Boolean; cdecl;
begin
Result := Finder.FindColor(src, dest, color, Tolerance);
end;
// -----------------------------------------------------------------------------------------
// Matrix exports
function _GetRawMatrix(var _:Pointer; data:PInt32; x1,y1,x2,y2:Int32; W,H:Int32): TIntMatrix; cdecl;
begin Result := GetRawMatrix(data,x1,y1,x2,y2,W,H); end;
procedure _Where(const Params: PParamArray; const Result:Pointer); cdecl;
begin TPointArray(Result^) := Where(TBoolMatrix(Params^[1]^)); end;
procedure _MatrixLT_MatVal(const Params: PParamArray; const Result:Pointer); cdecl;
begin TBoolMatrix(Result^) := MatrixLT(TSingleMatrix(Params^[1]^), Single(Params^[2]^)); end;
procedure _MatrixLT_ValMat(const Params: PParamArray; const Result:Pointer); cdecl;
begin TBoolMatrix(Result^) := MatrixLT(Single(Params^[1]^), TSingleMatrix(Params^[2]^)); end;
procedure _MatrixGT_MatVal(const Params: PParamArray; const Result:Pointer); cdecl;
begin TBoolMatrix(Result^) := MatrixGT(TSingleMatrix(Params^[1]^), Single(Params^[2]^)); end;
procedure _MatrixGT_ValMat(const Params: PParamArray; const Result:Pointer); cdecl;
begin TBoolMatrix(Result^) := MatrixGT(Single(Params^[1]^), TSingleMatrix(Params^[2]^)); end;
procedure _MatrixEQ_MatVal(const Params: PParamArray; const Result:Pointer); cdecl;
begin TBoolMatrix(Result^) := MatrixEQ(TSingleMatrix(Params^[1]^), Single(Params^[2]^)); end;
procedure _MatrixEQ_ValMat(const Params: PParamArray; const Result:Pointer); cdecl;
begin TBoolMatrix(Result^) := MatrixEQ(Single(Params^[1]^), TSingleMatrix(Params^[2]^)); end;
procedure _MatrixNE_MatVal(const Params: PParamArray; const Result:Pointer); cdecl;
begin TBoolMatrix(Result^) := MatrixNE(TSingleMatrix(Params^[1]^), Single(Params^[2]^)); end;
procedure _MatrixNE_ValMat(const Params: PParamArray; const Result:Pointer); cdecl;
begin TBoolMatrix(Result^) := MatrixNE(Single(Params^[1]^), TSingleMatrix(Params^[2]^)); end;
// -----------------------------------------------------------------------------------------
// Color conversion exports
procedure _ColorToGray(const Params: PParamArray; const Result:Pointer); cdecl;
begin PByte(Result)^ := ColorToGray(PColor(Params^[0])^); end;
procedure _ColorIntensity(const Params: PParamArray; const Result:Pointer); cdecl;
begin PByte(Result)^ := ColorIntensity(PColor(Params^[0])^); end;
procedure _ColorToRGB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorRGB(Result)^ := ColorToRGB(PColor(Params^[0])^); end;
procedure _ColorToXYZ(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorXYZ(Result)^ := ColorToXYZ(PColor(Params^[0])^); end;
procedure _ColorToLAB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorLAB(Result)^ := ColorToLAB(PColor(Params^[0])^); end;
procedure _ColorToLCH(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorLCH(Result)^ := ColorToLCH(PColor(Params^[0])^); end;
procedure _ColorToHSV(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorHSV(Result)^ := ColorToHSV(PColor(Params^[0])^); end;
procedure _ColorToHSL(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorHSL(Result)^ := ColorToHSL(PColor(Params^[0])^); end;
procedure _RGBToColor(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColor(Result)^ := RGBToColor(PColorRGB(Params^[0])^); end;
procedure _RGBToXYZ(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorXYZ(Result)^ := ColorToXYZ(RGBToColor(PColorRGB(Params^[0])^)); end;
procedure _RGBToLAB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorLAB(Result)^ := ColorToLAB(RGBToColor(PColorRGB(Params^[0])^)); end;
procedure _RGBToLCH(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorLCH(Result)^ := ColorToLCH(RGBToColor(PColorRGB(Params^[0])^)); end;
procedure _RGBToHSV(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorHSV(Result)^ := ColorToHSV(RGBToColor(PColorRGB(Params^[0])^)); end;
procedure _RGBToHSL(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorHSL(Result)^ := ColorToHSL(RGBToColor(PColorRGB(Params^[0])^)); end;
procedure _XYZToColor(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColor(Result)^ := XYZToColor(PColorXYZ(Params^[0])^); end;
procedure _XYZToRGB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorRGB(Result)^ := XYZToRGB(PColorXYZ(Params^[0])^); end;
procedure _XYZToLAB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorLAB(Result)^ := XYZToLAB(PColorXYZ(Params^[0])^); end;
procedure _XYZToLCH(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorLCH(Result)^ := XYZToLCH(PColorXYZ(Params^[0])^); end;
procedure _LABToColor(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColor(Result)^ := LABToColor(PColorLAB(Params^[0])^); end;
procedure _LABToRGB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorRGB(Result)^ := LABToRGB(PColorLAB(Params^[0])^); end;
procedure _LABToXYZ(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorXYZ(Result)^ := LABToXYZ(PColorLAB(Params^[0])^); end;
procedure _LABToLCH(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorLCH(Result)^ := LABToLCH(PColorLAB(Params^[0])^); end;
procedure _LCHToColor(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColor(Result)^ := LCHToColor(PColorLCH(Params^[0])^); end;
procedure _LCHToRGB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorRGB(Result)^ := LCHToRGB(PColorLCH(Params^[0])^); end;
procedure _LCHToXYZ(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorXYZ(Result)^ := LCHToXYZ(PColorLCH(Params^[0])^); end;
procedure _LCHToLAB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorLAB(Result)^ := LCHToLAB(PColorLCH(Params^[0])^); end;
procedure _HSVToColor(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColor(Result)^ := HSVToColor(PColorHSV(Params^[0])^); end;
procedure _HSVToRGB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorRGB(Result)^ := HSVToRGB(PColorHSV(Params^[0])^); end;
procedure _HSLToColor(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColor(Result)^ := HSLToColor(PColorHSL(Params^[0])^); end;
procedure _HSLToRGB(const Params: PParamArray; const Result:Pointer); cdecl;
begin PColorRGB(Result)^ := HSLToRGB(PColorHSL(Params^[0])^); end;
// -----------------------------------------------------------------------------------------
initialization
ExportType('TBoolMatrix', 'array of array of LongBool;');
ExportType('TIntMatrix', 'array of array of Int32;');
ExportType('EDistanceFormula', '(dfRGB, dfHSV, dfHSL, dfXYZ, dfLAB, dfLCH, dfDeltaE);');
ExportType('TChMultiplier', 'array [0..2] of Single;');
ExportType('TColorlib', 'type Pointer');
ExportType('TFinder', 'packed record ' + #13#10 +
' FCompareFunc: Pointer; ' + #13#10 +
' FNumThreads: UInt8; ' + #13#10 +
' FCacheSize: UInt8; ' + #13#10 +
' FColorInfo : Pointer; ' + #13#10 +
' FFormula: EDistanceFormula;' + #13#10 +
' FChMul: TChMultiplier; ' + #13#10 +
' FThreadPool: TObject; ' + #13#10 +
'end;');
ExportMethod(@TFinder_Init, 'procedure TFinder.Init(Formula:EDistanceFormula=dfRGB; NumThreads:UInt8=2; CacheSize:UInt8=3);');
ExportMethod(@TFinder_Free, 'procedure TFinder.Free();');
ExportMethod(@TFinder_SetFormula, 'procedure TFinder.SetFormula(ComparePreset: EDistanceFormula);');
ExportMethod(@TFinder_GetFormula, 'function TFinder.GetFormula(): EDistanceFormula;');
ExportMethod(@TFinder_SetNumThreads, 'procedure TFinder.SetNumThreads(N: UInt8);');
ExportMethod(@TFinder_GetNumThreads, 'function TFinder.GetNumThreads(): UInt8;');
ExportMethod(@TFinder_SetMultipliers, 'procedure TFinder.SetMultipliers(const Mul: TChMultiplier);');
ExportMethod(@TFinder_GetMultipliers, 'procedure TFinder.GetMultipliers(out Mul: TChMultiplier);');
ExportMethod(@TFinder_GetMaxDistance, 'function TFinder.GetMaxDistance(): Single;');
ExportMethod(@TFinder_SimilarColors, 'function TFinder.SimilarColors(Color1, Color2: TColor; Tolerance: Single): LongBool;');
ExportMethod(@TFinder_ColorDistance, 'function TFinder.ColorDistance(Color1, Color2: TColor): Single;');
ExportMethod(@TFinder_MatchColor, 'procedure TFinder.MatchColor(Src: TIntMatrix; var Dest: TSingleMatrix; Color: TColor);');
ExportMethod(@TFinder_FindColor, 'function TFinder.FindColor(Src: TIntMatrix; out Dest: TPointArray; color: TColor; Tolerance: Single): Boolean;');
ExportMethod(@_GetRawMatrix, 'function TColorlib.GetRawMatrix(data:Pointer; x1,y1,x2,y2:Int32; W,H:Int32): TIntMatrix; constref;');
ExportMethod(@_Where, 'function TColorlib.Where(Matrix:TBoolMatrix): TPointArray; constref; native;');
ExportMethod(@_MatrixLT_MatVal, 'function TColorlib.LessThan(Left:TSingleMatrix; Right:Single): TBoolMatrix; constref; overload; native;');
ExportMethod(@_MatrixLT_ValMat, 'function TColorlib.LessThan(Left:Single; Right:TSingleMatrix): TBoolMatrix; constref; overload; native;');
ExportMethod(@_MatrixGT_MatVal, 'function TColorlib.GreaterThan(Left:TSingleMatrix; Right:Single): TBoolMatrix; constref; overload; native;');
ExportMethod(@_MatrixGT_ValMat, 'function TColorlib.GreaterThan(Left:Single; Right:TSingleMatrix): TBoolMatrix; constref; overload; native;');
ExportMethod(@_MatrixEQ_MatVal, 'function TColorlib.EqualTo(Left:TSingleMatrix; Right:Single): TBoolMatrix; constref; overload; native;');
ExportMethod(@_MatrixEQ_ValMat, 'function TColorlib.EqualTo(Left:Single; Right:TSingleMatrix): TBoolMatrix; constref; overload; native;');
ExportMethod(@_MatrixNE_MatVal, 'function TColorlib.NotEqualTo(Left:TSingleMatrix; Right:Single): TBoolMatrix; constref; overload; native;');
ExportMethod(@_MatrixNE_ValMat, 'function TColorlib.NotEqualTo(Left:Single; Right:TSingleMatrix): TBoolMatrix; constref; overload; native;');
// -----------------------------------------------------------------------------------
// Color conversions
ExportType('ColorRGB', 'record R,G,B: Byte; end;');
ExportType('ColorXYZ', 'record X,Y,Z: Single; end;');
ExportType('ColorLAB', 'record L,A,B: Single; end;');
ExportType('ColorLCH', 'record L,C,H: Single; end;');
ExportType('ColorHSV', 'record H,S,V: Single; end;');
ExportType('ColorHSL', 'record H,S,L: Single; end;');
ExportMethod(@_ColorToGray, 'function TColor.ToGray(): Byte; constref; native;');
ExportMethod(@_ColorIntensity, 'function TColor.Intensity(): Byte; constref; native;');
ExportMethod(@_ColorToRGB, 'function TColor.ToRGB(): ColorRGB; constref; native;');
ExportMethod(@_ColorToXYZ, 'function TColor.ToXYZ(): ColorXYZ; constref; native;');
ExportMethod(@_ColorToLAB, 'function TColor.ToLAB(): ColorLAB; constref; native;');
ExportMethod(@_ColorToLCH, 'function TColor.ToLCH(): ColorLCH; constref; native;');
ExportMethod(@_ColorToHSV, 'function TColor.ToHSV(): ColorHSV; constref; native;');
ExportMethod(@_ColorToHSL, 'function TColor.ToHSL(): ColorHSL; constref; native;');
ExportMethod(@_RGBToColor, 'function ColorRGB.ToColor(): TColor; constref; native;');
ExportMethod(@_RGBToXYZ, 'function ColorRGB.ToXYZ(): ColorXYZ; constref; native;');
ExportMethod(@_RGBToLAB, 'function ColorRGB.ToLAB(): ColorLAB; constref; native;');
ExportMethod(@_RGBToLCH, 'function ColorRGB.ToLCH(): ColorLCH; constref; native;');
ExportMethod(@_RGBToHSV, 'function ColorRGB.ToHSV(): ColorHSV; constref; native;');
ExportMethod(@_RGBToHSL, 'function ColorRGB.ToHSL(): ColorHSL; constref; native;');
ExportMethod(@_XYZToColor, 'function ColorXYZ.ToColor(): TColor; constref; native;');
ExportMethod(@_XYZToRGB, 'function ColorXYZ.ToRGB(): ColorRGB; constref; native;');
ExportMethod(@_XYZToLAB, 'function ColorXYZ.ToLAB(): ColorLAB; constref; native;');
ExportMethod(@_XYZToLCH, 'function ColorXYZ.ToLCH(): ColorLCH; constref; native;');
ExportMethod(@_LABToColor, 'function ColorLAB.ToColor(): TColor; constref; native;');
ExportMethod(@_LABToRGB, 'function ColorLAB.ToRGB(): ColorRGB; constref; native;');
ExportMethod(@_LABToXYZ, 'function ColorLAB.ToXYZ(): ColorXYZ; constref; native;');
ExportMethod(@_LABToLCH, 'function ColorLAB.ToLCH(): ColorLCH; constref; native;');
ExportMethod(@_LCHToColor, 'function ColorLCH.ToColor(): TColor; constref; native;');
ExportMethod(@_LCHToRGB, 'function ColorLCH.ToRGB(): ColorRGB; constref; native;');
ExportMethod(@_LCHToLAB, 'function ColorLCH.ToLAB(): ColorLAB; constref; native;');
ExportMethod(@_LCHToXYZ, 'function ColorLCH.ToXYZ(): ColorXYZ; constref; native;');
ExportMethod(@_HSVToColor, 'function ColorHSV.ToColor(): TColor; constref; native;');
ExportMethod(@_HSVToRGB, 'function ColorHSV.ToRGB(): ColorRGB; constref; native;');
ExportMethod(@_HSLToColor, 'function ColorHSL.ToColor(): TColor; constref; native;');
ExportMethod(@_HSLToRGB, 'function ColorHSL.ToRGB(): ColorRGB; constref; native;');
end.
|
{
Writes AvisoCNC G-Code
License: The same modified LGPL as the Free Pascal RTL
See the file COPYING.modifiedLGPL for more details
AUTHORS: Felipe Monteiro de Carvalho
Pedro Sol Pegorini L de Lima
}
unit avisocncgcodewriter;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
fpvectorial;
type
{ TvAvisoCNCGCodeWriter }
TvAvisoCNCGCodeWriter = class(TvCustomVectorialWriter)
public
{ General reading methods }
procedure WriteToStrings(AStrings: TStrings; AData: TvVectorialDocument); override;
end;
implementation
{ TvGCodeVectorialWriter }
procedure TvAvisoCNCGCodeWriter.WriteToStrings(AStrings: TStrings;
AData: TvVectorialDocument);
var
i, j: Integer;
Str: string;
APath: TPath;
begin
AStrings.Clear;
AStrings.Add('M216 // Ligar monitor de carga');
AStrings.Add('G28 // Ir rapidamente para posição inicial');
AStrings.Add('G00');
// itera por todos os itens
for i := 0 to AData.GetPathCount - 1 do
begin
APath := AData.GetPath(i);
// levanta a broca
AStrings.Add('P01 // Sobe a cabeça de gravação');
// vai para o ponto inicial
AStrings.Add(Format('G01 X%f Y%f',
[APath.Points[0].X, APath.Points[0].Y]));
AStrings.Add('P02 // Abaixa a cabeça de gravação');
for j := 1 to APath.Len - 1 do
begin
case APath.Points[j].SegmentType of
st2DLine: AStrings.Add(Format('G01 X%f Y%f',
[APath.Points[j].X, APath.Points[j].Y]));
st3DLine: AStrings.Add(Format('G01 X%f Y%f Z%f',
[APath.Points[j].X, APath.Points[j].Y, APath.Points[j].Z]));
st2DBezier: AStrings.Add(Format('B02 X%f Y%f X%f Y%f X%f Y%f',
[APath.Points[j].X2, APath.Points[j].Y2,
APath.Points[j].X3, APath.Points[j].Y3,
APath.Points[j].X, APath.Points[j].Y]));
st3DBezier: AStrings.Add(Format('B03 X%f Y%f Z%f X%f Y%f Z%f X%f Y%f Z%f',
[APath.Points[j].X2, APath.Points[j].Y2, APath.Points[j].Z2,
APath.Points[j].X3, APath.Points[j].Y3, APath.Points[j].Z3,
APath.Points[j].X, APath.Points[j].Y, APath.Points[j].Z]));
end;
end;
end;
AStrings.Add('P01 // Sobe a cabeça de gravação');
AStrings.Add('M30 // Parar o programa e retornar para posição inicial');
AStrings.Add('M215 // Desligar monitor de carga');
end;
initialization
RegisterVectorialWriter(TvAvisoCNCGCodeWriter, vfGCodeAvisoCNCPrototipoV5);
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.8 7/23/04 6:36:54 PM RLebeau
Added extra exception handling to Open()
Rev 1.7 2004.05.20 12:34:30 PM czhower
Removed more non .NET compatible stream read and writes
Rev 1.6 2004.02.03 4:17:16 PM czhower
For unit name changes.
Rev 1.5 2003.10.17 6:15:54 PM czhower
Upgrades
Rev 1.4 2003.10.16 11:24:36 AM czhower
Bug fix
Rev 1.3 10/15/2003 8:00:10 PM DSiders
Added resource string for exception raised in TIdLogFile.SetFilename.
Rev 1.2 2003.10.14 1:27:10 PM czhower
Uupdates + Intercept support
Rev 1.1 6/16/2003 11:01:06 AM EHill
Throw exception if the filename is set while the log is open.
Expose Open and Close as public instead of protected.
Rev 1.0 11/13/2002 07:56:12 AM JPMugaas
19-Aug-2001 DSiders
Fixed bug in Open. Use file mode fmCreate when Filename does *not* exist.
19-Aug-2001 DSiders
Added protected method TIdLogFile.LogWriteString.
19-Aug-2001 DSiders
Changed implementation of TIdLogFile methods LogStatus, LogReceivedData, and
LogSentData to use LogWriteString.
19-Aug-2001 DSiders
Added class TIdLogFileEx with the LogFormat method.
}
unit IdLogFile;
interface
{$I IdCompilerDefines.inc}
//Put FPC into Delphi mode
uses
Classes,
IdLogBase;
type
TIdLogFile = class(TIdLogBase)
protected
FFilename: String;
FFileStream: TStream;
//
procedure LogFormat(const AFormat: string; const AArgs: array of const); virtual;
procedure LogReceivedData(const AText, AData: string); override;
procedure LogSentData(const AText, AData: string); override;
procedure LogStatus(const AText: string); override;
procedure LogWriteString(const AText: string); virtual;
//
procedure SetFilename(const AFilename: String);
public
procedure Open; override;
procedure Close; override;
published
property Filename: String read FFilename write SetFilename;
end;
implementation
uses
IdGlobal, IdException, IdResourceStringsCore, IdBaseComponent, SysUtils;
{ TIdLogFile }
procedure TIdLogFile.Close;
begin
FreeAndNil(FFileStream);
end;
procedure TIdLogFile.LogReceivedData(const AText, AData: string);
begin
LogWriteString(RSLogRecv + AText + ': ' + AData + EOL); {Do not translate}
end;
procedure TIdLogFile.LogSentData(const AText, AData: string);
begin
LogWriteString(RSLogSent + AText + ': ' + AData + EOL); {Do not translate}
end;
procedure TIdLogFile.LogStatus(const AText: string);
begin
LogWriteString(RSLogStat + AText + EOL);
end;
procedure TIdLogFile.Open;
begin
if not IsDesignTime then begin
FFileStream := TIdAppendFileStream.Create(Filename);
end;
end;
procedure TIdLogFile.LogWriteString(const AText: string);
begin
if Assigned(FFileStream) then begin
WriteStringToStream(FFileStream, AText, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF});
end;
end;
procedure TIdLogFile.LogFormat(const AFormat: string; const AArgs: array of const);
var
sPre: string;
sMsg: string;
sData: string;
begin
// forces Open to be called prior to Connect
if not Active then begin
Active := True;
end;
sPre := ''; {Do not translate}
sMsg := ''; {Do not translate}
if LogTime then begin
sPre := DateTimeToStr(Now) + ' '; {Do not translate}
end;
sData := IndyFormat(AFormat, AArgs);
if FReplaceCRLF then begin
sData := ReplaceCR(sData);
end;
sMsg := sPre + sData + EOL;
LogWriteString(sMsg);
end;
procedure TIdLogFile.SetFilename(const AFilename: String);
begin
if Assigned(FFileStream) then begin
EIdException.Toss(RSLogFileAlreadyOpen);
end;
FFilename := AFilename;
end;
end.
|
unit alcuSubmitterWorkPool;
{* Коллекция служебно-рабочих пользователей }
// Модуль: "w:\archi\source\projects\PipeInAuto\Tasks\alcuSubmitterWorkPool.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TalcuSubmitterWorkPool" MUID: (53CDF9FE006B)
{$Include w:\archi\source\projects\PipeInAuto\alcuDefine.inc}
interface
{$If Defined(ServerTasks) AND Defined(AppServerSide)}
uses
l3IntfUses
, l3ProtoObject
, alcuServerAsyncExecutionInterfaces
, alcuSubmitterWorkThreadList
, alcuAsyncTaskFinishedNotifierList
{$If NOT Defined(Nemesis)}
, csProcessTask
{$IfEnd} // NOT Defined(Nemesis)
;
type
TalcuSubmitterWorkPool = class(Tl3ProtoObject, IalcuAsyncTaskFinishedNotifier)
{* Коллекция служебно-рабочих пользователей }
private
f_LockSubmitTaskCounter: Integer;
f_List: TalcuSubmitterWorkThreadList;
f_FinishNotifierList: TalcuAsyncTaskFinishedNotifierList;
f_SubmitGuard: Integer;
f_HasWorkThreads: Boolean;
f_WorkThreadCount: integer;
f_Manager: IalcuAsyncSubmitterManager;
private
procedure NotifySubscribers(const aTask: TddProcessTask);
protected
procedure pm_SetWorkThreadCount(aValue: integer);
procedure TaskFinished(const aTask: TddProcessTask);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure ClearFields; override;
public
constructor Create(const aManager: IalcuAsyncSubmitterManager); reintroduce;
function SubmitTask(const aTask: TddProcessTask): Boolean;
procedure CheckExecution(const aServices: IcsRunTaskServices);
function HasRunningTask(const aServices: IcsRunTaskServices;
CountAbortingTask: Boolean): Boolean;
procedure RegisterNotifier(const aNotifier: IalcuAsyncTaskFinishedNotifier);
procedure UnRegisterNotifier(const aNotifier: IalcuAsyncTaskFinishedNotifier);
function AllowSubmitTask: Boolean;
procedure LockSubmitTask;
procedure UnLockSubmitTask;
protected
property Manager: IalcuAsyncSubmitterManager
read f_Manager;
public
property HasWorkThreads: Boolean
read f_HasWorkThreads;
property WorkThreadCount: integer
read f_WorkThreadCount
write pm_SetWorkThreadCount;
end;//TalcuSubmitterWorkPool
{$IfEnd} // Defined(ServerTasks) AND Defined(AppServerSide)
implementation
{$If Defined(ServerTasks) AND Defined(AppServerSide)}
uses
l3ImplUses
, alcuAsyncSubmitter
, l3Types
, l3Base
, Windows
, SysUtils
, daInterfaces
{$If NOT Defined(Nemesis)}
, csTaskTypes
{$IfEnd} // NOT Defined(Nemesis)
, l3Interlocked
, daDataProvider
//#UC START# *53CDF9FE006Bimpl_uses*
//#UC END# *53CDF9FE006Bimpl_uses*
;
procedure TalcuSubmitterWorkPool.pm_SetWorkThreadCount(aValue: integer);
//#UC START# *5416C3670067_53CDF9FE006Bset_var*
function DoDeactivate(aThread: PalcuSubmitterWorkThread; Index: Long): Bool;
begin
Result := True;
aThread.Active := False;
end;
var
l_IDX: Integer;
l_UserIDX: Cardinal;
l_NeedRefillUserList: Boolean;
l_Thread: TalcuSubmitterWorkThread;
//#UC END# *5416C3670067_53CDF9FE006Bset_var*
begin
//#UC START# *5416C3670067_53CDF9FE006Bset_impl*
if not TalcuSubmitterWorkThread.AssistantExists then
begin
l3System.Msg2Log('Утилита alcuTaskExecutor.exe не найдена. Асинхронное выполнение задач отключено.');
aValue := 0;
end;
if aValue <> f_WorkThreadCount then
begin
f_WorkThreadCount := aValue;
f_HasWorkThreads := WorkThreadCount > 0;
f_List.IterateAllF(l3L2IA(@DoDeactivate));
l_NeedRefillUserList := False;
for l_UserIDX := usFirstWorkUser downto usFirstWorkUser - (WorkThreadCount - 1) do
begin
if not GlobalDataProvider.UserManager.IsUserExists(l_UserIDX) then
begin
GlobalDataProvider.UserManager.AddUserID(l_UserIDX, Format('Служебный пользователь %d', [usFirstWorkUser - l_UserIDX + 1]), Format('%s%.8x', [Chr(3), l_UserIDX]), '', 1);
l_NeedRefillUserList := True;
end;
end;
if l_NeedRefillUserList then
GlobalDataProvider.UserManager.MakeFullArchiUsersList;
l_UserIDX := usFirstWorkUser;
for l_IDX := 0 to WorkThreadCount - 1 do
begin
if l_IDX < f_List.Count then
f_List.Items[l_IDX].Active := True
else
begin
l_Thread := TalcuSubmitterWorkThread.Create(l_UserIDX, Manager);
try
l_Thread.RegisterNotifier(Self);
f_List.Add(l_Thread);
finally
FreeAndNil(l_Thread);
end;
end;
Dec(l_UserIDX);
end;
if HasWorkThreads then
l3System.Msg2Log('Асинхронное выполнение задач включено (%d утилит).', [WorkThreadCount])
else
l3System.Msg2Log('Асинхронное выполнение задач отключено.');
end;
//#UC END# *5416C3670067_53CDF9FE006Bset_impl*
end;//TalcuSubmitterWorkPool.pm_SetWorkThreadCount
constructor TalcuSubmitterWorkPool.Create(const aManager: IalcuAsyncSubmitterManager);
//#UC START# *53CDFAF10205_53CDF9FE006B_var*
//#UC END# *53CDFAF10205_53CDF9FE006B_var*
begin
//#UC START# *53CDFAF10205_53CDF9FE006B_impl*
inherited Create;
f_List := TalcuSubmitterWorkThreadList.Make;
f_Manager := aManager;
f_FinishNotifierList := TalcuAsyncTaskFinishedNotifierList.Make;
//#UC END# *53CDFAF10205_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.Create
procedure TalcuSubmitterWorkPool.NotifySubscribers(const aTask: TddProcessTask);
//#UC START# *53D0E7D8019F_53CDF9FE006B_var*
function DoIt(aNotifier: PalcuAsyncTaskFinishedNotifier; Index: Long): Bool;
begin
aNotifier.TaskFinished(aTask);
Result := True;
end;
//#UC END# *53D0E7D8019F_53CDF9FE006B_var*
begin
//#UC START# *53D0E7D8019F_53CDF9FE006B_impl*
f_FinishNotifierList.IterateAllF(l3L2IA(@DoIt))
//#UC END# *53D0E7D8019F_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.NotifySubscribers
function TalcuSubmitterWorkPool.SubmitTask(const aTask: TddProcessTask): Boolean;
//#UC START# *53CDFABD0075_53CDF9FE006B_var*
var
l_Result: Boolean;
function DoIt(aThread: PalcuSubmitterWorkThread; Index: Long): Bool;
begin
l_Result := aThread.SubmitTask(aTask);
Result := not l_Result;
end;
//#UC END# *53CDFABD0075_53CDF9FE006B_var*
begin
//#UC START# *53CDFABD0075_53CDF9FE006B_impl*
l3InterlockedIncrement(f_SubmitGuard);
try
if aTask.Status = cs_tsAsyncRun then
begin
Result := True;
Exit;
end;
if f_SubmitGuard <> 1 then
begin
Result := False;
Exit;
end;
l_Result := False;
if aTask.Status <> cs_tsQuery then
l3System.Msg2Log('ALERT! В очередь ставиться задача %s с неподходящим статусом', [aTask.Description]);
if AllowSubmitTask then
f_List.IterateAllF(l3L2IA(@DoIt));
Result := l_Result;
finally
l3InterlockedDecrement(f_SubmitGuard);
end;
//#UC END# *53CDFABD0075_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.SubmitTask
procedure TalcuSubmitterWorkPool.CheckExecution(const aServices: IcsRunTaskServices);
//#UC START# *53CDFADC00B4_53CDF9FE006B_var*
function DoIt(aThread: PalcuSubmitterWorkThread; Index: Long): Bool;
begin
Result := True;
aThread.CheckExecution(aServices);
end;
//#UC END# *53CDFADC00B4_53CDF9FE006B_var*
begin
//#UC START# *53CDFADC00B4_53CDF9FE006B_impl*
if f_SubmitGuard = 0 then
f_List.IterateAllF(l3L2IA(@DoIt));
//#UC END# *53CDFADC00B4_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.CheckExecution
function TalcuSubmitterWorkPool.HasRunningTask(const aServices: IcsRunTaskServices;
CountAbortingTask: Boolean): Boolean;
//#UC START# *53CF9B060043_53CDF9FE006B_var*
var
l_Result: Boolean;
function DoIt(aThread: PalcuSubmitterWorkThread; Index: Long): Bool;
begin
aThread.CheckExecution(aServices);
if aThread.StillRunning(CountAbortingTask) then
l_Result := True;
Result := not l_Result;
end;
//#UC END# *53CF9B060043_53CDF9FE006B_var*
begin
//#UC START# *53CF9B060043_53CDF9FE006B_impl*
l_Result := False;
f_List.IterateAllF(l3L2IA(@DoIt));
Result := l_Result;
//#UC END# *53CF9B060043_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.HasRunningTask
procedure TalcuSubmitterWorkPool.RegisterNotifier(const aNotifier: IalcuAsyncTaskFinishedNotifier);
//#UC START# *53D0E39102B2_53CDF9FE006B_var*
//#UC END# *53D0E39102B2_53CDF9FE006B_var*
begin
//#UC START# *53D0E39102B2_53CDF9FE006B_impl*
f_FinishNotifierList.Add(aNotifier);
//#UC END# *53D0E39102B2_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.RegisterNotifier
procedure TalcuSubmitterWorkPool.UnRegisterNotifier(const aNotifier: IalcuAsyncTaskFinishedNotifier);
//#UC START# *53D0E3AE025B_53CDF9FE006B_var*
//#UC END# *53D0E3AE025B_53CDF9FE006B_var*
begin
//#UC START# *53D0E3AE025B_53CDF9FE006B_impl*
f_FinishNotifierList.Remove(aNotifier);
//#UC END# *53D0E3AE025B_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.UnRegisterNotifier
function TalcuSubmitterWorkPool.AllowSubmitTask: Boolean;
//#UC START# *541173D101EC_53CDF9FE006B_var*
//#UC END# *541173D101EC_53CDF9FE006B_var*
begin
//#UC START# *541173D101EC_53CDF9FE006B_impl*
Result := f_LockSubmitTaskCounter = 0;
//#UC END# *541173D101EC_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.AllowSubmitTask
procedure TalcuSubmitterWorkPool.LockSubmitTask;
//#UC START# *541173EF01F8_53CDF9FE006B_var*
//#UC END# *541173EF01F8_53CDF9FE006B_var*
begin
//#UC START# *541173EF01F8_53CDF9FE006B_impl*
Inc(f_LockSubmitTaskCounter);
//#UC END# *541173EF01F8_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.LockSubmitTask
procedure TalcuSubmitterWorkPool.UnLockSubmitTask;
//#UC START# *541174030002_53CDF9FE006B_var*
//#UC END# *541174030002_53CDF9FE006B_var*
begin
//#UC START# *541174030002_53CDF9FE006B_impl*
if f_LockSubmitTaskCounter > 0 then
Dec(f_LockSubmitTaskCounter);
//#UC END# *541174030002_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.UnLockSubmitTask
procedure TalcuSubmitterWorkPool.TaskFinished(const aTask: TddProcessTask);
//#UC START# *53D0E2CD0227_53CDF9FE006B_var*
//#UC END# *53D0E2CD0227_53CDF9FE006B_var*
begin
//#UC START# *53D0E2CD0227_53CDF9FE006B_impl*
NotifySubscribers(aTask);
//#UC END# *53D0E2CD0227_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.TaskFinished
procedure TalcuSubmitterWorkPool.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_53CDF9FE006B_var*
//#UC END# *479731C50290_53CDF9FE006B_var*
begin
//#UC START# *479731C50290_53CDF9FE006B_impl*
FreeAndNil(f_List);
FreeAndNil(f_FinishNotifierList);
inherited;
//#UC END# *479731C50290_53CDF9FE006B_impl*
end;//TalcuSubmitterWorkPool.Cleanup
procedure TalcuSubmitterWorkPool.ClearFields;
begin
f_Manager := nil;
inherited;
end;//TalcuSubmitterWorkPool.ClearFields
{$IfEnd} // Defined(ServerTasks) AND Defined(AppServerSide)
end.
|
unit UninstProgressForm;
{
Inno Setup
Copyright (C) 1997-2010 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Uninstaller progress form
$jrsoftware: issrc/Projects/UninstProgressForm.pas,v 1.16 2010/10/30 20:26:25 jr Exp $
}
interface
{$I VERSION.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
SetupForm, StdCtrls, ExtCtrls, BitmapImage, NewProgressBar, NewStaticText,
NewNotebook, BidiCtrls;
type
TUninstallProgressForm = class(TSetupForm)
OuterNotebook: TNewNotebook;
InnerPage: TNewNotebookPage;
InnerNotebook: TNewNotebook;
InstallingPage: TNewNotebookPage;
MainPanel: TPanel;
PageNameLabel: TNewStaticText;
PageDescriptionLabel: TNewStaticText;
WizardSmallBitmapImage: TBitmapImage;
Bevel1: TBevel;
StatusLabel: TNewStaticText;
ProgressBar: TNewProgressBar;
BeveledLabel: TNewStaticText;
Bevel: TBevel;
CancelButton: TNewButton;
private
{ Private declarations }
protected
procedure CreateParams(var Params: TCreateParams); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Initialize(const ATitle, AAppName: String);
procedure UpdateProgress(const AProgress, ARange: Integer);
end;
var
UninstallProgressForm: TUninstallProgressForm;
implementation
uses
TaskbarProgressFunc, Main, Msgs, MsgIDs, CmnFunc;
{$R *.DFM}
{ TUninstallProgressForm }
procedure UninstallMessageBoxCallback(const Flags: LongInt; const After: Boolean;
const Param: LongInt);
const
States: array [TNewProgressBarState] of TTaskbarProgressState =
(tpsNormal, tpsError, tpsPaused);
var
UninstallProgressForm: TUninstallProgressForm;
NewState: TNewProgressBarState;
begin
UninstallProgressForm := TUninstallProgressForm(Param);
if After then
NewState := npbsNormal
else if (Flags and MB_ICONSTOP) <> 0 then
NewState := npbsError
else
NewState := npbsPaused;
with UninstallProgressForm.ProgressBar do begin
State := NewState;
Invalidate;
end;
SetAppTaskbarProgressState(States[NewState]);
end;
constructor TUninstallProgressForm.Create(AOwner: TComponent);
begin
inherited;
SetMessageBoxCallbackFunc(UninstallMessageBoxCallback, LongInt(Self));
InitializeFont;
Center;
{$IFDEF IS_D7}
MainPanel.ParentBackGround := False;
{$ENDIF}
PageNameLabel.Font.Style := [fsBold];
PageNameLabel.Caption := SetupMessages[msgWizardUninstalling];
WizardSmallBitmapImage.Bitmap.Canvas.Brush.Color := clWindow;
WizardSmallBitmapImage.Bitmap.Width := Application.Icon.Width;
WizardSmallBitmapImage.Bitmap.Height := Application.Icon.Height;
WizardSmallBitmapImage.Bitmap.Canvas.Draw(0, 0, Application.Icon);
if SetupMessages[msgBeveledLabel] <> '' then begin
BeveledLabel.Caption := ' ' + SetupMessages[msgBeveledLabel] + ' ';
BeveledLabel.Visible := True;
end;
CancelButton.Caption := SetupMessages[msgButtonCancel];
end;
destructor TUninstallProgressForm.Destroy;
begin
SetMessageBoxCallbackFunc(nil, 0);
SetAppTaskbarProgressState(tpsNoProgress);
inherited;
end;
procedure TUninstallProgressForm.Initialize(const ATitle, AAppName: String);
begin
Caption := ATitle;
PageDescriptionLabel.Caption := FmtSetupMessage1(msgUninstallStatusLabel, AAppName);
StatusLabel.Caption := FmtSetupMessage1(msgStatusUninstalling, AAppName);
end;
procedure TUninstallProgressForm.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.WindowClass.style := Params.WindowClass.style or CS_NOCLOSE;
end;
procedure TUninstallProgressForm.UpdateProgress(const AProgress, ARange: Integer);
var
NewPos: Integer;
begin
NewPos := MulDiv(AProgress, ProgressBar.Max, ARange);
if ProgressBar.Position <> NewPos then begin
ProgressBar.Position := NewPos;
SetAppTaskbarProgressValue(NewPos, ProgressBar.Max);
end;
end;
end.
|
unit InfoCLDOCTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoCLDOCRecord = record
PClaimNumber: String[6];
PImageId: String[9];
PType: String[10];
PDate: String[10];
PUserID: String[6];
End;
TInfoCLDOCBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoCLDOCRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoCLDOC = (InfoCLDOCPrimaryKey);
TInfoCLDOCTable = class( TDBISAMTableAU )
private
FDFClaimNumber: TStringField;
FDFImageId: TStringField;
FDFType: TStringField;
FDFDate: TStringField;
FDFUserID: TStringField;
procedure SetPClaimNumber(const Value: String);
function GetPClaimNumber:String;
procedure SetPImageId(const Value: String);
function GetPImageId:String;
procedure SetPType(const Value: String);
function GetPType:String;
procedure SetPDate(const Value: String);
function GetPDate:String;
procedure SetPUserID(const Value: String);
function GetPUserID:String;
procedure SetEnumIndex(Value: TEIInfoCLDOC);
function GetEnumIndex: TEIInfoCLDOC;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoCLDOCRecord;
procedure StoreDataBuffer(ABuffer:TInfoCLDOCRecord);
property DFClaimNumber: TStringField read FDFClaimNumber;
property DFImageId: TStringField read FDFImageId;
property DFType: TStringField read FDFType;
property DFDate: TStringField read FDFDate;
property DFUserID: TStringField read FDFUserID;
property PClaimNumber: String read GetPClaimNumber write SetPClaimNumber;
property PImageId: String read GetPImageId write SetPImageId;
property PType: String read GetPType write SetPType;
property PDate: String read GetPDate write SetPDate;
property PUserID: String read GetPUserID write SetPUserID;
published
property Active write SetActive;
property EnumIndex: TEIInfoCLDOC read GetEnumIndex write SetEnumIndex;
end; { TInfoCLDOCTable }
procedure Register;
implementation
procedure TInfoCLDOCTable.CreateFields;
begin
FDFClaimNumber := CreateField( 'ClaimNumber' ) as TStringField;
FDFImageId := CreateField( 'ImageId' ) as TStringField;
FDFType := CreateField( 'Type' ) as TStringField;
FDFDate := CreateField( 'Date' ) as TStringField;
FDFUserID := CreateField( 'UserID' ) as TStringField;
end; { TInfoCLDOCTable.CreateFields }
procedure TInfoCLDOCTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoCLDOCTable.SetActive }
procedure TInfoCLDOCTable.SetPClaimNumber(const Value: String);
begin
DFClaimNumber.Value := Value;
end;
function TInfoCLDOCTable.GetPClaimNumber:String;
begin
result := DFClaimNumber.Value;
end;
procedure TInfoCLDOCTable.SetPImageId(const Value: String);
begin
DFImageId.Value := Value;
end;
function TInfoCLDOCTable.GetPImageId:String;
begin
result := DFImageId.Value;
end;
procedure TInfoCLDOCTable.SetPType(const Value: String);
begin
DFType.Value := Value;
end;
function TInfoCLDOCTable.GetPType:String;
begin
result := DFType.Value;
end;
procedure TInfoCLDOCTable.SetPDate(const Value: String);
begin
DFDate.Value := Value;
end;
function TInfoCLDOCTable.GetPDate:String;
begin
result := DFDate.Value;
end;
procedure TInfoCLDOCTable.SetPUserID(const Value: String);
begin
DFUserID.Value := Value;
end;
function TInfoCLDOCTable.GetPUserID:String;
begin
result := DFUserID.Value;
end;
procedure TInfoCLDOCTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('ClaimNumber, String, 6, N');
Add('ImageId, String, 9, N');
Add('Type, String, 10, N');
Add('Date, String, 10, N');
Add('UserID, String, 6, N');
end;
end;
procedure TInfoCLDOCTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, ClaimNumber, Y, Y, N, N');
end;
end;
procedure TInfoCLDOCTable.SetEnumIndex(Value: TEIInfoCLDOC);
begin
case Value of
InfoCLDOCPrimaryKey : IndexName := '';
end;
end;
function TInfoCLDOCTable.GetDataBuffer:TInfoCLDOCRecord;
var buf: TInfoCLDOCRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PClaimNumber := DFClaimNumber.Value;
buf.PImageId := DFImageId.Value;
buf.PType := DFType.Value;
buf.PDate := DFDate.Value;
buf.PUserID := DFUserID.Value;
result := buf;
end;
procedure TInfoCLDOCTable.StoreDataBuffer(ABuffer:TInfoCLDOCRecord);
begin
DFClaimNumber.Value := ABuffer.PClaimNumber;
DFImageId.Value := ABuffer.PImageId;
DFType.Value := ABuffer.PType;
DFDate.Value := ABuffer.PDate;
DFUserID.Value := ABuffer.PUserID;
end;
function TInfoCLDOCTable.GetEnumIndex: TEIInfoCLDOC;
var iname : string;
begin
result := InfoCLDOCPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoCLDOCPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoCLDOCTable, TInfoCLDOCBuffer ] );
end; { Register }
function TInfoCLDOCBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..5] of string = ('CLAIMNUMBER','IMAGEID','TYPE','DATE','USERID' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 5) and (flist[x] <> s) do inc(x);
if x <= 5 then result := x else result := 0;
end;
function TInfoCLDOCBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
end;
end;
function TInfoCLDOCBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PClaimNumber;
2 : result := @Data.PImageId;
3 : result := @Data.PType;
4 : result := @Data.PDate;
5 : result := @Data.PUserID;
end;
end;
end.
|
{
Author: Jarl K. Holta
License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html)
Runtime datatype representations
}
unit xpr.list;
{$I express.inc}
interface
{$I objh.inc}
uses
SysUtils,
xpr.express,
xpr.objbase;
type
TListObject = class(TEpObject)
value: TObjectArray;
constructor Create(AValue:TObjectArray);
function Release: Boolean; override;
function Copy(gcGen:Byte=0): TEpObject; override;
function DeepCopy: TEpObject; override;
function AsString: epString; override;
function AsBool: Boolean; override;
//temporary
procedure INPLACE_ADD(other:TEpObject); override;
//
procedure ASGN(other:TEpObject; var dest:TEpObject); override;
procedure GET_ITEM(constref index:TEpObject; var dest:TEpObject); override;
procedure SET_ITEM(constref index:TEpObject; constref other:TEpObject); override;
end;
implementation
uses
xpr.utils,
xpr.errors,
xpr.mmgr,
xpr.bool,
xpr.int;
constructor TListObject.Create(AValue:TObjectArray);
begin
self.Value := AValue;
end;
function TListObject.Release: Boolean;
begin
Result := False;
end;
function TListObject.Copy(gcGen:Byte=0): TEpObject;
begin
Result := self; //meh
end;
function TListObject.DeepCopy: TEpObject;
var
i:Int32;
tmp:TObjectArray;
begin
SetLength(tmp, Length(self.value));
for i:=0 to High(self.value) do
tmp[i] := self.value[i].DeepCopy();
Result := TGarbageCollector(GC).AllocList(tmp);
end;
function TListObject.AsString: epString;
var i:Int32;
begin
Result := '[';
for i:=0 to High(self.value) do
begin
if (Pointer(self.value[i]) = Pointer(self)) then
Result += '[...]'
else
Result += self.value[i].AsString;
if i <> High(self.value) then Result += ',';
end;
Result += ']';
end;
function TListObject.AsBool: Boolean;
begin
Result := Length(self.value) > 0;
end;
procedure TListObject.ASGN(other:TEpObject; var dest:TEpObject);
begin
//if other is TListObject then
// self.value := TListObject(other).value
//else
inherited;
end;
procedure TListObject.INPLACE_ADD(other:TEpObject);
var
l:Int32;
begin
l := Length(self.value);
SetLength(self.value, l+1);
self.value[l] := other.Copy();
end;
procedure TListObject.GET_ITEM(constref index:TEpObject; var dest:TEpObject);
var
idx,real_idx,len:SizeInt;
begin
real_idx := index.AsInt;
len := Length(self.value);
if real_idx < 0 then
idx := len-real_idx
else
idx := real_idx;
if (idx < 0) or (idx >= len) then
raise RuntimeError.CreateFmt(eIndexOutOfRange, [real_idx, len]);
dest.ASGN(self.value[idx], dest);
end;
procedure TListObject.SET_ITEM(constref index:TEpObject; constref other:TEpObject);
var
idx,real_idx,len:SizeInt;
begin
real_idx := index.AsInt;
len := Length(self.value);
if real_idx < 0 then
idx := len-real_idx
else
idx := real_idx;
if (idx < 0) or (idx >= len) then
raise RuntimeError.CreateFmt(eIndexOutOfRange, [real_idx, len]);
self.value[idx].ASGN(other, self.value[idx]);
end;
end.
|
unit IterateableService;
// Модуль: "w:\common\components\SandBox\IterateableService.pas"
// Стереотип: "Service"
// Элемент модели: "TIterateableService" MUID: (5519611903CF)
{$Include w:\common\components\SandBox\sbDefine.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, Classes
;
type
MIterateableService_IterateF_Action = function(anItem: TComponent): Boolean;
{* Тип подитеративной функции для MIterateableService.IterateF }
(*
MIterateableService = interface
{* Контракт сервиса TIterateableService }
procedure IterateF(anAction: MIterateableService_IterateF_Action;
anOwner: TComponent);
end;//MIterateableService
*)
IIterateableService = interface
{* Интерфейс сервиса TIterateableService }
procedure IterateF(anAction: MIterateableService_IterateF_Action;
anOwner: TComponent);
end;//IIterateableService
TIterateableService = {final} class(Tl3ProtoObject)
private
f_Alien: IIterateableService;
{* Внешняя реализация сервиса IIterateableService }
protected
procedure pm_SetAlien(const aValue: IIterateableService);
procedure ClearFields; override;
public
procedure IterateF(anAction: MIterateableService_IterateF_Action;
anOwner: TComponent);
class function Instance: TIterateableService;
{* Метод получения экземпляра синглетона TIterateableService }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
public
property Alien: IIterateableService
write pm_SetAlien;
{* Внешняя реализация сервиса IIterateableService }
end;//TIterateableService
function L2MIterateableServiceIterateFAction(anAction: Pointer): MIterateableService_IterateF_Action;
{* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для MIterateableService.IterateF }
implementation
uses
l3ImplUses
, SysUtils
, l3Base
//#UC START# *5519611903CFimpl_uses*
//#UC END# *5519611903CFimpl_uses*
;
var g_TIterateableService: TIterateableService = nil;
{* Экземпляр синглетона TIterateableService }
function L2MIterateableServiceIterateFAction(anAction: Pointer): MIterateableService_IterateF_Action;
{* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для MIterateableService.IterateF }
asm
jmp l3LocalStub
end;//L2MIterateableServiceIterateFAction
procedure TIterateableServiceFree;
{* Метод освобождения экземпляра синглетона TIterateableService }
begin
l3Free(g_TIterateableService);
end;//TIterateableServiceFree
procedure TIterateableService.pm_SetAlien(const aValue: IIterateableService);
begin
Assert((f_Alien = nil) OR (aValue = nil));
f_Alien := aValue;
end;//TIterateableService.pm_SetAlien
procedure TIterateableService.IterateF(anAction: MIterateableService_IterateF_Action;
anOwner: TComponent);
//#UC START# *551961AE0005_5519611903CF_var*
var
Hack : Pointer absolute anAction;
//#UC END# *551961AE0005_5519611903CF_var*
begin
//#UC START# *551961AE0005_5519611903CF_impl*
if (f_Alien <> nil) then
f_Alien.IterateF(anAction, anOwner)
else
begin
try
//anAction(nil);
finally
l3FreeLocalStub(Hack);
end;//try..finally
end;//f_Alien <> nil
//#UC END# *551961AE0005_5519611903CF_impl*
end;//TIterateableService.IterateF
class function TIterateableService.Instance: TIterateableService;
{* Метод получения экземпляра синглетона TIterateableService }
begin
if (g_TIterateableService = nil) then
begin
l3System.AddExitProc(TIterateableServiceFree);
g_TIterateableService := Create;
end;
Result := g_TIterateableService;
end;//TIterateableService.Instance
class function TIterateableService.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_TIterateableService <> nil;
end;//TIterateableService.Exists
procedure TIterateableService.ClearFields;
begin
Alien := nil;
inherited;
end;//TIterateableService.ClearFields
end.
|
unit clCEPAgentes;
interface
uses clConexao;
type
TCEPAgentes = Class(TObject)
private
function getAgente: Integer;
function getCep: String;
procedure setAgente(const Value: Integer);
procedure setCep(const Value: String);
function getGrupo: Integer;
procedure setGrupo(const Value: Integer);
protected
_agente: Integer;
_cep: String;
_grupo: Integer;
_conexao: TConexao;
public
constructor Create;
destructor Destroy;
property Agente: Integer read getAgente write setAgente;
property Cep: String read getCep write setCep;
property Grupo: Integer read getGrupo write setGrupo;
function Validar(): Boolean;
function Delete(filtro: String): Boolean;
function getObject(id, filtro: String): Boolean;
function Insert(): Boolean;
function Update(): Boolean;
function getField(campo, coluna: String): String;
end;
const
TABLENAME = 'TBCEPAGENTE';
implementation
{ TCEPAgentes }
uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB;
constructor TCEPAgentes.Create;
begin
_conexao := TConexao.Create;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
end;
destructor TCEPAgentes.Destroy;
begin
_conexao.Free;
end;
function TCEPAgentes.getAgente: Integer;
begin
Result := _agente;
end;
function TCEPAgentes.getCep: String;
begin
Result := _cep;
end;
function TCEPAgentes.Validar(): Boolean;
begin
try
Result := False;
if Self.Agente = 0 then
begin
MessageDlg('Informe o Agente!', mtWarning, [mbOK], 0);
Exit;
end;
if TUtil.Empty(Self.Cep) then
begin
MessageDlg('Informe a Cabeça de CEP!', mtWarning, [mbOK], 0);
Exit;
end;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TCEPAgentes.Delete(filtro: String): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM ' + TABLENAME);
if filtro = 'AGENTE' then
begin
SQL.Add('WHERE COD_AGENTE = :AGENTE');
ParamByName('AGENTE').AsInteger := Self.Agente;
end
else if filtro = 'CEP' then
begin
SQL.Add('WHERE COD_CABECA_CEP = :CEP');
ParamByName('CEP').AsString := Self.Cep;
end;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TCEPAgentes.getObject(id, filtro: String): Boolean;
begin
try
Result := False;
if TUtil.Empty(id) then
Exit;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
if filtro = 'AGENTE' then
begin
SQL.Add('WHERE COD_AGENTE= :AGENTE');
ParamByName('AGENTE').AsInteger := StrToInt(id);
end
else if filtro = 'CEP' then
begin
SQL.Add('WHERE COD_CABECA_CEP = :CEP');
ParamByName('CEP').AsString := id;
end;
Open;
if not IsEmpty then
First;
end;
if dm.QryGetObject.RecordCount > 0 then
begin
Self.Agente := dm.QryGetObject.FieldByName('COD_AGENTE').AsInteger;
Self.Cep := dm.QryGetObject.FieldByName('COD_CABECA_CEP').AsString;
Result := True;
end
else
begin
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
end;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TCEPAgentes.Insert(): Boolean;
begin
Try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO ' + TABLENAME + '(' +
'COD_AGENTE, ' +
'COD_CABECA_CEP, ' +
'COD_GRUPO) ' +
'VALUES (' +
':AGENTE, ' +
':CEP, ' +
':GRUPO)';
ParamByName('AGENTE').AsInteger := Self.Agente;
ParamByName('CEP').AsString := Self.Cep;
ParamByName('GRUPO').AsInteger := Self.Grupo;
dm.ZConn.Ping;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TCEPAgentes.Update(): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' +
'COD_CABECA_CEP = :CEP ' +
'WHERE ' +
'COD_AGENTE = :AGENTE, ' +
'COD_GRUPO = :GRUPO';
ParamByName('AGENTE').AsInteger := Self.Agente;
ParamByName('CEP').AsString := Self.Cep;
ParamByName('GRUPO').AsInteger := Self.Grupo;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TCEPAgentes.getField(campo, coluna: String): String;
begin
Try
Result := '';
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME;
if coluna = 'CEP' then
begin
SQL.Add(' WHERE COD_CABECA_CEP =:CEP ');
ParamByName('CEP').AsString := Self.Cep;
end;
Open;
if not IsEmpty then
First;
end;
if dm.QryGetObject.RecordCount > 0 then
Result := dm.QryGetObject.FieldByName(campo).AsString;
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TCEPAgentes.getGrupo: Integer;
begin
Result := _grupo;
end;
procedure TCEPAgentes.setAgente(const Value: Integer);
begin
_agente := Value;
end;
procedure TCEPAgentes.setCep(const Value: String);
begin
_cep := Value;
end;
procedure TCEPAgentes.setGrupo(const Value: Integer);
begin
_grupo := Value;
end;
end.
|
unit PaintWindow;
{
Tablet Enable PaintBox Sample
by LI Qingrui
emailto: qrli@hotmail.com
This file is supplied "AS IS", without warranty of any kind.
Feel free to use and modify for any purpose.
Enjoy yourself.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
WinTab32, Math;
type
TPenEvent = procedure(sender: TObject; X, Y, P: single; key: boolean) of object;
TPaintWindow = class(TCustomControl)
private
FTablet: HCTX;
FMaxNPressure: integer;
FBitmap: TBitmap;
FScale: integer;
FOnPenMove: TPenEvent;
FOnPenUp: TPenEvent;
FOnPenDown: TPenEvent;
FIsPenDown: boolean;
procedure InitializeTablet;
procedure FinalizeTablet;
procedure UpdateSize;
procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND;
procedure SetScale(const Value: integer);
procedure SetTabletContextActive(const Value: boolean);
protected
procedure Paint; override;
procedure CreateWnd; override;
procedure DestroyWnd; override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(o: TComponent); override;
destructor Destroy; override;
procedure SetDimension(w, h: integer);
procedure UpdateRect(const r: TRect);
procedure FlushPackets;
property Bitmap: TBitmap read FBitmap;
property TabletContextActive: boolean write SetTabletContextActive;
property MouseCapture;
property IsPenDown: boolean read FIsPenDown;
published
property Scale: integer read FScale write SetScale default 100;
property Align;
property Anchors;
property PopupMenu;
property Visible;
property OnPenDown: TPenEvent read FOnPenDown write FOnPenDown;
property OnPenMove: TPenEvent read FOnPenMove write FOnPenMove;
property OnPenUp: TPenEvent read FOnPenUp write FOnPenUp;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Excite', [TPaintWindow]);
end;
{ TPaintWindow }
constructor TPaintWindow.Create(o: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csOpaque];
FBitmap := TBitmap.Create;
FBitmap.PixelFormat := pf32bit;
FScale := 100;
end;
procedure TPaintWindow.CreateWnd;
begin
inherited;
if not (csDesigning in ComponentState) then
InitializeTablet;
end;
destructor TPaintWindow.Destroy;
begin
FBitmap.Free;
if not (csDesigning in ComponentState) then
FinalizeTablet;
inherited;
end;
procedure TPaintWindow.DestroyWnd;
begin
if not (csDesigning in ComponentState) then
FinalizeTablet;
inherited;
end;
procedure TPaintWindow.FinalizeTablet;
begin
if FTablet <> 0 then
begin
WTClose(FTablet);
FTablet := 0;
end;
end;
procedure TPaintWindow.InitializeTablet;
var
lc: LOGCONTEXT;
npAxis: AXIS;
begin
if not IsWinTab32Available then Exit;
// get default
WTInfo(WTI_DEFSYSCTX, 0, @lc);
// modify the digitizing region
StrCopy(lc.lcName, PChar('PaintWindow '+IntToHex(HInstance, 8)));
lc.lcOptions := lc.lcOptions or CXO_SYSTEM;
lc.lcMsgBase := WT_DEFBASE;
lc.lcPktData := PACKETDATA;
lc.lcPktMode := PACKETMODE;
lc.lcMoveMask := PACKETDATA;
lc.lcBtnUpMask := lc.lcBtnDnMask;
lc.lcOutExtX := lc.lcOutExtX * 10;
lc.lcOutExtY := lc.lcOutExtY * 10;
FTablet := WTOpen(Handle, lc, TRUE);
WTInfo(WTI_DEVICES + lc.lcDevice, DVC_NPRESSURE, @npAxis);
FMaxNPressure := npAxis.axMax;
end;
procedure TPaintWindow.MouseMove(Shift: TShiftState; X, Y: Integer);
var
buf: array[0..31] of PACKET;
org: TPoint;
n, scrH: integer;
procedure ProcessPackets;
var
i: integer;
x, y, p: single;
begin
for i := 0 to n-1 do
begin
if buf[i].pkNormalPressure > 0 then
if i=0 then;
x := (buf[i].pkX / 10 - org.x) * 100/FScale;
y := ((scrH*10 - buf[i].pkY) / 10 - org.y) * 100/FScale;
if not IsPenDown then p := 0
else if FMaxNPressure = 0 then p := 1
else begin
p := EnsureRange(buf[i].pkNormalPressure / FMaxNPressure, 0.0, 1.0);
end;
if i = n-1 then FOnPenMove(self, x, y, p, true)
else FOnPenMove(self, x, y, p, false);
end;
end;
procedure ProcessMouse;
begin
if ssLeft in Shift then FOnPenMove(self, X+0.5, Y+0.5, 1, true)
else FOnPenMove(self, X+0.5, Y+0.5, 0, true);
end;
begin
inherited;
if not Assigned(FOnPenMove) then Exit;
if IsWinTab32Available then
begin
org := ClientToScreen(Point(0, 0));
scrH := Screen.Height;
n := WTPacketsGet(FTablet, 32, @buf);
if n <= 0 then ProcessMouse
else repeat
ProcessPackets;
n := WTPacketsGet(FTablet, 32, @buf);
until n = 0;
end
else
ProcessMouse;
end;
procedure TPaintWindow.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
if Button = mbLeft then
begin
FIsPenDown := true;
FlushPackets;
end;
if Assigned(FOnPenDown) and (mbLeft = Button) then
begin
FOnPenDown(self, X+0.5, Y+0.5, 1, true);
end;
end;
procedure TPaintWindow.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
if Button = mbLeft then
begin
FIsPenDown := false;
end;
if Assigned(FOnPenUp) and (mbLeft = Button) then
FOnPenUp(self, X+0.5, Y+0.5, 0, false);
end;
procedure TPaintWindow.Paint;
begin
if FBitmap.Height = 0 then canvas.FillRect(ClientRect)
else canvas.StretchDraw(ClientRect, FBitmap);
end;
procedure TPaintWindow.SetTabletContextActive(const Value: boolean);
begin
if FTablet <> 0 then
if value then
begin
WTEnable(FTablet, true);
WTOverlap(FTablet, true);
end
else begin
WTOverlap(FTablet, false);
WTEnable(FTablet, false);
end;
end;
procedure TPaintWindow.SetDimension(w, h: integer);
begin
FBitmap.Width := w;
FBitmap.Height := h;
UpdateSize;
end;
procedure TPaintWindow.SetScale(const Value: integer);
begin
if value < 25 then Exit;
FScale := Value;
UpdateSize;
end;
procedure TPaintWindow.UpdateSize;
begin
if not FBitmap.Empty then
begin
Width := FBitmap.Width * FScale div 100;
Height := FBitmap.Height * FScale div 100;
Repaint;
end;
end;
procedure TPaintWindow.WMEraseBkgnd(var Message: TWmEraseBkgnd);
begin
Message.result := 1;
end;
procedure TPaintWindow.UpdateRect(const r: TRect);
begin
if IsRectEmpty(r) then Exit;
with r do
StretchBlt(canvas.Handle, left * 100 div FScale, top * 100 div FScale,
(right - left) * 100 div FScale, (bottom - top) * 100 div FScale,
FBitmap.canvas.handle, left, top, right - left, bottom - top, SRCCOPY);
end;
procedure TPaintWindow.FlushPackets;
begin
if IsWinTab32Available then WTPacketsGet(FTablet, 0, nil);
end;
end.
|
unit uROWebsocketChannel;
interface
uses
Classes, SysUtils,
uROClient, uROClientIntf,
//copied from: http://code.google.com/p/bauglir-websocket/downloads/detail?name=BauglirWebSocket2_pascal_library.2.0.4.zip
WebSocket2;
type
TROWebsocketChannel = class(TROTransportChannel,
IROTransport, IROTCPTransport, IROTCPTransportProperties)
private
FClient: TWebSocketClientConnection;
fKeepAlive: boolean;
fDisableNagle: boolean;
FHost: string;
FPort: Integer;
FTimeOut: Integer;
FStreamRead: TMemoryStream;
procedure WebSocketConnectionDataFull(aSender: TWebSocketCustomConnection; aCode: integer; aData: TMemoryStream);
protected
procedure IntDispatch(aRequest, aResponse : TStream); override;
{ IROTransport }
function GetTransportObject : TObject; override;
{ IROTCPTransport }
function GetClientAddress : string;
{IROTCPTransportProperties}
function GetHost: string;
function GetPort: integer;
procedure SetHost(const Value: string);
procedure SetPort(const Value: integer);
function GetTimeout: Integer;
procedure SetTimeout(const Value: Integer);
public
constructor Create(aOwner : TComponent); override;
procedure Assign(aSource: TPersistent); override;
destructor Destroy; override;
property Port : integer read GetPort write SetPort;
property Host : string read GetHost write SetHost;
//property DisableNagle : boolean read fDisableNagle write fDisableNagle default FALSE;
//property KeepAlive : boolean read fKeepAlive write fKeepAlive default false;
published
// from TROTransportChannel
property DispatchOptions;
property OnAfterProbingServer;
property OnAfterProbingServers;
property OnBeforeProbingServer;
property OnBeforeProbingServers;
property OnLoginNeeded;
property OnProgress;
property OnReceiveStream;
property OnSendStream;
property OnServerLocatorAssignment;
property ProbeFrequency;
property ProbeServers;
property ServerLocators;
property SynchronizedProbing;
end;
implementation
{ TROWebsocketChannel }
procedure TROWebsocketChannel.Assign(aSource: TPersistent);
begin
inherited;
//
end;
constructor TROWebsocketChannel.Create(aOwner: TComponent);
begin
inherited;
//
end;
destructor TROWebsocketChannel.Destroy;
begin
//
inherited;
end;
function TROWebsocketChannel.GetClientAddress: string;
begin
if FClient <> nil then
Result := FClient.Origin
else
Result := '';
end;
function TROWebsocketChannel.GetHost: string;
begin
Result := FHost;
end;
function TROWebsocketChannel.GetPort: integer;
begin
Result := FPort;
end;
function TROWebsocketChannel.GetTimeout: Integer;
begin
Result := FTimeOut;
end;
function TROWebsocketChannel.GetTransportObject: TObject;
begin
Result := Self;
end;
procedure TROWebsocketChannel.IntDispatch(aRequest, aResponse: TStream);
begin
if FClient = nil then
FClient := TWebSocketClientConnection.Create(FHost, IntToStr(FPort),
Format('ws://%s:%d/', [FHost, FPort]) );
FClient.Start;
while not FClient.CanReceiveOrSend do
Sleep(10);
FClient.FullDataProcess := True;
FClient.OnReadFull := WebSocketConnectionDataFull;
FStreamRead := nil;
//FClient.SendBinary(aRequest);
with TStreamReader.Create(aRequest) do
begin
FClient.SendText(ReadToEnd);
Free;
end;
while FStreamRead = nil do
CheckSynchronize(10);
aResponse.CopyFrom(FStreamRead, FStreamRead.Size);
end;
procedure TROWebsocketChannel.SetHost(const Value: string);
begin
FHost := Value;
end;
procedure TROWebsocketChannel.SetPort(const Value: integer);
begin
FPort := Value;
end;
procedure TROWebsocketChannel.SetTimeout(const Value: Integer);
begin
FTimeOut := Value;
end;
procedure TROWebsocketChannel.WebSocketConnectionDataFull(
aSender: TWebSocketCustomConnection; aCode: integer; aData: TMemoryStream);
begin
FStreamRead := aData;
end;
end.
|
unit Unit6;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Edit, FMX.StdCtrls,
FMX.Objects, FMX.Layouts, FMX.ListBox, FMX.TabControl;
type
TForm6 = class(TForm)
Button2: TSpeedButton;
Button3: TSpeedButton;
Text1: TText;
edtValue: TClearingEdit;
Button1: TSpeedButton;
ListBox1: TListBox;
btnList: TSpeedButton;
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure btnListClick(Sender: TObject);
private
{ Private declarations }
function MyINIFilePath : string;
public
{ Public declarations }
end;
var
Form6: TForm6;
implementation
{$R *.fmx}
uses INIFiles;
function TForm6.MyINIFilePath: string;
begin
// Result := GetHomePath + PathDelim + 'Library' + PathDelim+'My.ini';
Result := GetHomePath + PathDelim + 'Documents' + PathDelim+'MyD.ini';
end;
procedure TForm6.FormCreate(Sender: TObject);
begin
// Show the Path on screen.
Text1.Text := MyINIFilePath;
end;
procedure TForm6.btnListClick(Sender: TObject);
var
Source : string;
procedure DoListFiles(const Src:string);
var
SearchRec : TSearchRec;
Res : Integer;
PathFromRoot: string;
begin
Res := FindFirst(src + '*', faAnyFile, SearchRec);
while Res = 0 do
begin
if (SearchRec.Attr and faDirectory) = faDirectory then
begin
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
begin
// Do the recurse thing...
DoListFiles(Src+SearchRec.Name+PathDelim);
end;
end
else begin
PathFromRoot := Copy(Src+SearchRec.Name,Length(GetHomePath+PathDelim),Length(Src+SearchRec.Name));
ListBox1.Items.Add(PathFromRoot);
end;
Res := FindNext(SearchRec);
end;
end;
begin
Source := GetHomePath+PathDelim;
ListBox1.BeginUpdate;
try
ListBox1.Items.Clear;
DoListFiles(Source);
finally
ListBox1.EndUpdate;
end;
end;
procedure TForm6.Button1Click(Sender: TObject);
begin
if FileExists(MyINIFilePath) then
if DeleteFile(MyINIFilePath) then
ShowMessage('Deleted')
else
ShowMessage('Not deleted');
end;
procedure TForm6.Button2Click(Sender: TObject);
var
Ini : TINIFile;
begin
Ini := Tinifile.Create(MyINIFilePath);
try
edtValue.Text := Ini.ReadString('Section','ID','');
finally
Ini.Free;
end;
end;
procedure TForm6.Button3Click(Sender: TObject);
var
Ini : TINIFile;
begin
Ini := Tinifile.Create(MyINIFilePath);
try
Ini.WriteString('Section','ID',edtValue.Text);
finally
Ini.Free;
end;
end;
end.
|
namespace Sugar.IO;
interface
uses
{$IF WINDOWS_PHONE OR NETFX_CORE}
Windows.Storage,
{$ENDIF}
Sugar;
{$HIDE W37}
type
[Obsolete("Use Folder instead")]
FolderUtils = public static class
private
{$IF COOPER}
method RecursiveDelete(Item: java.io.File);
method ListItems(FolderName: java.io.File; AllFolders: Boolean; FilesOnly: Boolean): array of String;
{$ELSEIF TOFFEE}
method ListItems(FolderName: String; AllFolders: Boolean; FilesOnly: Boolean): array of String;
{$ELSEIF WINDOWS_PHONE OR NETFX_CORE}
method GetFolder(FolderName: String): StorageFolder;
{$ENDIF}
public
method &Create(FolderName: String);
method Delete(FolderName: String);
method Exists(FolderName: String): Boolean;
method GetFiles(FolderName: String; AllFolders: Boolean := false): array of String;
method GetFolders(FolderName: String; AllFolders: Boolean := false): array of String;
end;
implementation
{$IF WINDOWS_PHONE OR NETFX_CORE}
class method FolderUtils.GetFolder(FolderName: String): StorageFolder;
begin
exit StorageFolder.GetFolderFromPathAsync(FolderName).Await;
end;
{$ENDIF}
class method FolderUtils.Create(FolderName: String);
begin
if Exists(FolderName) then
raise new SugarIOException(ErrorMessage.FOLDER_EXISTS, FolderName);
{$IF COOPER}
if not (new java.io.File(FolderName).mkdir) then
raise new SugarIOException(ErrorMessage.FOLDER_CREATE_ERROR, FolderName);
{$ELSEIF WINDOWS_PHONE OR NETFX_CORE}
var ParentFolder := GetFolder(Path.GetParentDirectory(FolderName));
FolderName := Path.GetFileName(FolderName);
ParentFolder.CreateFolderAsync(FolderName, CreationCollisionOption.FailIfExists).Await;
{$ELSEIF ECHOES}
System.IO.Directory.CreateDirectory(FolderName);
{$ELSEIF TOFFEE}
var lError: NSError := nil;
if not NSFileManager.defaultManager.createDirectoryAtPath(FolderName) withIntermediateDirectories(false) attributes(nil) error(var lError) then
raise new SugarNSErrorException(lError);
{$ENDIF}
end;
{$IF COOPER}
class method FolderUtils.RecursiveDelete(Item: java.io.File);
begin
if Item.isDirectory then begin
var Items := Item.list;
for Element in Items do
RecursiveDelete(new java.io.File(Item, Element));
end;
if not Item.delete then
raise new SugarIOException(ErrorMessage.FOLDER_DELETE_ERROR, Item.Name);
end;
{$ENDIF}
class method FolderUtils.Delete(FolderName: String);
begin
if not Exists(FolderName) then
raise new SugarIOException(ErrorMessage.FOLDER_NOTFOUND, FolderName);
{$IF COOPER}
RecursiveDelete(new java.io.File(FolderName));
{$ELSEIF WINDOWS_PHONE OR NETFX_CORE}
GetFolder(FolderName).DeleteAsync.AsTask.Wait;
{$ELSEIF ECHOES}
System.IO.Directory.Delete(FolderName, true);
{$ELSEIF TOFFEE}
var lError: NSError := nil;
if not NSFileManager.defaultManager.removeItemAtPath(FolderName) error(var lError) then
raise new SugarNSErrorException(lError);
{$ENDIF}
end;
class method FolderUtils.Exists(FolderName: String): Boolean;
begin
SugarArgumentNullException.RaiseIfNil(FolderName, "FolderName");
{$IF COOPER}
var lFile := new java.io.File(FolderName);
exit lFile.exists and lFile.isDirectory;
{$ELSEIF WINDOWS_PHONE OR NETFX_CORE}
try
exit GetFolder(FolderName) <> nil;
except
exit false;
end;
{$ELSEIF ECHOES}
exit System.IO.Directory.Exists(FolderName);
{$ELSEIF TOFFEE}
var RetVal: Boolean := false;
result := NSFileManager.defaultManager.fileExistsAtPath(FolderName) isDirectory(@RetVal) and RetVal;
{$ENDIF}
end;
{$IF COOPER}
class method FolderUtils.ListItems(FolderName: java.io.File; AllFolders: Boolean; FilesOnly: Boolean): array of String;
begin
var Elements := FolderName.listFiles;
var Items := new Sugar.Collections.List<String>;
for Element in Elements do begin
if (FilesOnly and Element.isFile) or ((not FilesOnly) and Element.isDirectory) then
Items.Add(Element.AbsolutePath);
if AllFolders then
Items.AddRange(ListItems(Element, AllFolders, FilesOnly));
end;
exit Items.ToArray;
end;
{$ELSEIF TOFFEE}
class method FolderUtils.ListItems(FolderName: String; AllFolders: Boolean; FilesOnly: Boolean): array of String;
begin
var Enumerator := NSFileManager.defaultManager.enumeratorAtPath(FolderName);
var Item: NSString := Enumerator.nextObject;
var Items := new Sugar.Collections.List<String>;
while Item <> nil do begin
if (not AllFolders) and (Enumerator.level <> 1) then
break;
var IsDir: Boolean := false;
Item := Path.Combine(FolderName, Item);
NSFileManager.defaultManager.fileExistsAtPath(Item) isDirectory(@IsDir);
if (FilesOnly and (not IsDir)) or ((not FilesOnly) and IsDir) then
Items.Add(Item);
Item := Enumerator.nextObject;
end;
exit Items.ToArray;
end;
{$ENDIF}
class method FolderUtils.GetFiles(FolderName: String; AllFolders: Boolean): array of String;
begin
if not Exists(FolderName) then
raise new SugarIOException(ErrorMessage.FOLDER_NOTFOUND, FolderName);
{$IF COOPER}
exit ListItems(new java.io.File(FolderName), AllFolders, true);
{$ELSEIF WINDOWS_PHONE OR NETFX_CORE}
var Items := new Sugar.Collections.List<String>;
if AllFolders then begin
Items.AddRange(GetFiles(FolderName, false));
var Folders := GetFolders(FolderName, true);
for i: Integer := 0 to Folders.Length - 1 do
Items.AddRange(GetFiles(Folders[i], false));
end
else begin
var Files := GetFolder(FolderName).GetFilesAsync.Await;
for i: Integer := 0 to Files.Count - 1 do
Items.Add(Files.Item[i].Path);
end;
exit Items.ToArray;
{$ELSEIF ECHOES}
exit System.IO.Directory.GetFiles(FolderName, "*", iif(AllFolders, System.IO.SearchOption.AllDirectories, System.IO.SearchOption.TopDirectoryOnly));
{$ELSEIF TOFFEE}
exit ListItems(FolderName, AllFolders, true);
{$ENDIF}
end;
class method FolderUtils.GetFolders(FolderName: String; AllFolders: Boolean): array of String;
begin
if not Exists(FolderName) then
raise new SugarIOException(ErrorMessage.FOLDER_NOTFOUND, FolderName);
{$IF COOPER}
exit ListItems(new java.io.File(FolderName), AllFolders, false);
{$ELSEIF WINDOWS_PHONE OR NETFX_CORE}
var lFolder := GetFolder(FolderName);
var Folders := lFolder.GetFoldersAsync.Await;
var Items := new Sugar.Collections.List<String>;
for i: Integer := 0 to Folders.Count - 1 do begin
Items.Add(Folders.Item[i].Path);
if AllFolders then
Items.AddRange(GetFolders(Folders.Item[i].Path, AllFolders));
end;
exit Items.ToArray;
{$ELSEIF ECHOES}
exit System.IO.Directory.GetDirectories(FolderName, "*", iif(AllFolders, System.IO.SearchOption.AllDirectories, System.IO.SearchOption.TopDirectoryOnly));
{$ELSEIF TOFFEE}
exit ListItems(FolderName, AllFolders, false);
{$ENDIF}
end;
end. |
unit uFiltroLicenca;
interface
uses
System.SysUtils, uFiltroCliente;
type
TFiltroLicenca = class
private
FCliente: TFiltroCliente;
FIdCliente: integer;
FDataUtilizacaoInicial: string;
FDataUtilizacaoFinal: string;
FTipo: string;
FUtilizadas: string;
FSituacao: string;
procedure SetSituacao(const Value: string);
procedure SetUtilizadas(const Value: string);
public
property IdCliente: integer read FIdCliente write FIdCliente;
property Cliente: TFiltroCliente read FCliente write FCliente;
property DataUtilizacaoInicial: string read FDataUtilizacaoInicial write FDataUtilizacaoInicial;
property DataUtilizacaoFinal: string read FDataUtilizacaoFinal write FDataUtilizacaoFinal;
property Tipo: string read FTipo write FTipo;
property Situacao: string read FSituacao write SetSituacao;
property Utilizadas: string read FUtilizadas write SetUtilizadas;
constructor Create(); overload;
destructor destroy; override;
end;
implementation
{ TFiltroLicenca }
constructor TFiltroLicenca.Create;
begin
inherited Create;
FCliente := TFiltroCliente.Create;
end;
destructor TFiltroLicenca.destroy;
begin
FreeAndNil(FCliente);
inherited;
end;
procedure TFiltroLicenca.SetSituacao(const Value: string);
begin
FSituacao := Value;
end;
procedure TFiltroLicenca.SetUtilizadas(const Value: string);
begin
FUtilizadas := Value;
end;
end.
|
unit RoadsHandler;
interface
uses
Controls,
Classes,
VoyagerInterfaces,
VoyagerServerInterfaces,
CircuitsRenderer,
CircuitsDownloader;
type
TRoadId = TCircuitId;
type
TOnAreaRefreshedNotification = procedure ( const RoadsData : ICircuitsData ) of object;
type
IRoadsHandler =
interface ['{FD0207E0-EF3C-11d1-8B24-008029E5CA8C}']
procedure RefreshArea( x, y, dx, dy : integer; OnAreaRefreshed : TOnAreaRefreshedNotification );
procedure asyncRefreshArea( x, y, dx, dy : integer; OnAreaRefreshed : TOnAreaRefreshedNotification );
function RoadIdAt( x, y : integer ) : TRoadId;
end;
type
TRoadsHandler =
class( TInterfacedObject, IMetaURLHandler, IURLHandler, IRoadsHandler )
public
constructor Create;
destructor Destroy; override;
private
fMasterURLHandler : IMasterURLHandler;
fClientView : IClientView;
fRoadsDownloader : ICircuitsDownloader;
// 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 );
// IRoadsHandler
private
procedure RefreshArea( x, y, dx, dy : integer; OnAreaRefreshed : TOnAreaRefreshedNotification );
procedure asyncRefreshArea( x, y, dx, dy : integer; OnAreaRefreshed : TOnAreaRefreshedNotification );
function RoadIdAt( x, y : integer ) : TRoadId;
end;
const
tidMetaHandler_Roads = 'RoadsHandler';
const
evnAnswerRoadsHandler = 7000;
//evnAnswerClientView = 7500;
implementation
uses
SysUtils;
type
TAreaRoadsRefresherThread =
class( TThread )
private
fRoadsDownloader : ICircuitsDownloader;
fX, fY, fDX, fDY : integer;
fOnAreaRefreshed : TOnAreaRefreshedNotification;
public
constructor Create( const RoadsDownloader : ICircuitsDownloader; x, y, dx, dy : integer; OnAreaRefreshed : TOnAreaRefreshedNotification );
protected
procedure Execute; override;
end;
// TAreaRoadsRefresherThread
constructor TAreaRoadsRefresherThread.Create( const RoadsDownloader : ICircuitsDownloader; x, y, dx, dy : integer; OnAreaRefreshed : TOnAreaRefreshedNotification );
begin
fRoadsDownloader := RoadsDownloader;
fX := x;
fY := y;
fDX := dx;
fDY := dy;
fOnAreaRefreshed := OnAreaRefreshed;
inherited Create( false )
end;
procedure TAreaRoadsRefresherThread.Execute;
var
RoadsData : ICircuitsData;
begin
RoadsData := RenderCircuits( fRoadsDownloader.CircuitsInArea( fX, fY, fDX, fDY ), fDX, fDY );
if Assigned( fOnAreaRefreshed )
then
fOnAreaRefreshed( RoadsData )
end;
// TRoadsHandler
constructor TRoadsHandler.Create;
begin
inherited Create
end;
destructor TRoadsHandler.Destroy;
begin
inherited
end;
function TRoadsHandler.getName : string;
begin
Result := tidMetaHandler_Roads
end;
function TRoadsHandler.getOptions : TURLHandlerOptions;
begin
Result := [ hopCacheable, hopNonVisual ]
end;
function TRoadsHandler.getCanHandleURL( URL : TURL ) : THandlingAbility;
begin
Result := 0;
end;
function TRoadsHandler.Instantiate : IURLHandler;
begin
Result := Self
end;
function TRoadsHandler.HandleURL( URL : TURL ) : TURLHandlingResult;
begin
Result := urlNotHandled;
end;
function TRoadsHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
begin
if EventId = evnAnswerRoadsHandler
then
begin
IRoadsHandler( info ) := Self as IRoadsHandler;
Result := evnHandled
end
else
Result := evnNotHandled
end;
function TRoadsHandler.getControl : TControl;
begin
result := nil;
end;
procedure TRoadsHandler.setMasterURLHandler( URLHandler : IMasterURLHandler );
begin
fMasterURLHandler := URLHandler;
fMasterURLHandler.HandleEvent( evnAnswerClientView, fClientView );
fRoadsDownloader := TCircuitsDownloader.Create( fClientView, ckRoads )
end;
procedure TRoadsHandler.RefreshArea( x, y, dx, dy : integer; OnAreaRefreshed : TOnAreaRefreshedNotification );
var
fRoadsData : ICircuitsData;
begin
fRoadsData := RenderCircuits( fRoadsDownloader.CircuitsInArea( x, y, dx, dy ), dx, dy );
if Assigned( OnAreaRefreshed )
then
OnAreaRefreshed( fRoadsData )
end;
procedure TRoadsHandler.asyncRefreshArea( x, y, dx, dy : integer; OnAreaRefreshed : TOnAreaRefreshedNotification );
begin
TAreaRoadsRefresherThread.Create( fRoadsDownloader, x, y, dx, dy, OnAreaRefreshed )
end;
function TRoadsHandler.RoadIdAt( x, y : integer ) : TRoadId;
var
fRoadsData : ICircuitsData;
begin
fRoadsData := RenderCircuits( fRoadsDownloader.CircuitsInArea( x, y, 1, 1 ), 1, 1 );
Result := fRoadsData[ 0, 0 ]
end;
end.
|
unit uScenes;
interface
uses Classes, uScene;
type
TScenes = class(TScene)
private
FScene: TScene;
procedure SetScene(const Value: TScene);
public
procedure Timer; override;
procedure MouseUp(Button: TMouseBtn); override;
procedure MouseDn(Button: TMouseBtn); override;
procedure Render; override;
procedure KeyDown(var Key: Word); override;
procedure MouseMove(X, Y: Integer); override;
property Scene: TScene read FScene write SetScene default nil;
procedure Clear;
end;
var
Scenes: TScenes;
implementation
{ TScenes }
procedure TScenes.Clear;
begin
Scene := nil;
end;
procedure TScenes.MouseUp(Button: TMouseBtn);
begin
if (Scene <> nil) then Scene.MouseUp(Button);
end;
procedure TScenes.KeyDown(var Key: Word);
begin
if (Scene <> nil) then Scene.KeyDown(Key);
end;
procedure TScenes.MouseMove(X, Y: Integer);
begin
if (Scene <> nil) then Scene.MouseMove(X, Y);
end;
procedure TScenes.Render;
begin
if (Scene <> nil) then Scene.Render;
end;
procedure TScenes.SetScene(const Value: TScene);
begin
FScene := Value;
Render;
end;
procedure TScenes.Timer;
begin
if (Scene <> nil) then Scene.Timer;
end;
procedure TScenes.MouseDn(Button: TMouseBtn);
begin
if (Scene <> nil) then Scene.MouseDn(Button);
end;
initialization
Scenes := TScenes.Create;
finalization
Scenes.Free;
end.
|
unit TileMap;
interface
uses
SysUtils,
Math,
PNGImage,
PNGImageList,
Graphics,
PositionRecord,
SizeRecord;
type
TTileMap = class
protected
fTileLst: TPNGImageList;
fColumns : integer;
fRows : integer;
fTileMapArray : array of array of Integer;
fTileSize : integer;
function getTileName(tileName : string) : string;
function createPngImageFromFile(tileName : string) : TPNGImage;
public
constructor Create(aTileSize : integer; aColumns : Integer; aRows : integer);
destructor Destroy();
procedure RandomizeMap();
procedure Draw(canvas : TCanvas; OffsetPosition : TPositionRecord; clientSize : TSizeRecord);
end;
implementation
uses
ImgList;
constructor TTileMap.Create(aTileSize : integer; aColumns : Integer; aRows : integer);
begin
fColumns := aColumns;
fRows := aRows;
SetLength(fTileMapArray, fColumns, fRows);
fTileSize := aTileSize;
fTileLst := TPNGImageList.Create(nil);
fTileLst.ColorDepth := cd32Bit;
fTileLst.Height := fTileSize;
fTileLst.Width := fTileSize;
fTileLst.AddPng(createPngImageFromFile('grass'));
fTileLst.AddPng(createPngImageFromFile('grass2'));
fTileLst.AddPng(createPngImageFromFile('grass_with_sand'));
fTileLst.AddPng(createPngImageFromFile('grass_around_sand'));
fTileLst.AddPng(createPngImageFromFile('grass_around_sand2'));
fTileLst.AddPng(createPngImageFromFile('sand_left_grass'));
fTileLst.AddPng(createPngImageFromFile('sand'));
//fTileLst.AddPng(createPngImageFromFile('sand_left_trans'));
end;
destructor TTileMap.Destroy();
begin
fTileLst.Free();
end;
procedure TTileMap.RandomizeMap();
var
col : Integer;
row : Integer;
tileIndex : Integer;
begin
for row := 0 to fRows - 1 do
begin
for col := 0 to fColumns - 1 do
begin
if(col < 3) and (row < 3) then
tileIndex := RandomRange(0,2)
else if(col < 5) and (row < 5) then
tileIndex := RandomRange(0,3)
else if(col < 7) and (row < 7) then
tileIndex := RandomRange(1,3)
else
tileIndex := RandomRange(1,5);
fTileMapArray[col][row] := tileIndex;
end;
end;
end;
function TTileMap.createPngImageFromFile(tileName : string) : TPNGImage;
var
image : TPNGImage;
begin
image := TPNGImage.Create();
image.LoadFromFile(getTileName(tileName));
Result := image;
end;
function TTileMap.getTileName(tileName : string) : string;
begin
Result := Format('.\Tiles%d\%s.png',[fTileSize,tileName]);
end;
procedure TTileMap.Draw(canvas : TCanvas; OffsetPosition : TPositionRecord; clientSize : TSizeRecord);
var
col,x : Integer;
row,y : Integer;
begin
if( OffsetPosition.X < 0) then
OffsetPosition.X := 0;
if( OffsetPosition.Y < 0) then
OffsetPosition.Y := 0;
if( OffsetPosition.X > (fColumns * fTileSize) - clientSize.Width) then
OffsetPosition.X := (fColumns * fTileSize) - clientSize.Width;
if( OffsetPosition.Y > (fRows * fTileSize) - clientSize.Height) then
OffsetPosition.Y := (fRows * fTileSize) - clientSize.Height;
for row := 0 to fRows - 1 do
begin
for col := 0 to fColumns - 1 do
begin
x := col * fTileSize - OffsetPosition.X;
y := row * fTileSize - OffsetPosition.Y;
if((x > -fTileSize) and (x < clientSize.Width)) and ((y > - fTileSize) and (y < clientSize.Height)) then
fTileLst.Draw(canvas,x,y,fTileMapArray[col][row],True);
end;
end;
end;
end.
|
unit DW.IdleHandler.Android;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
// ******************************** PLEASE NOTE ********************************
//
// This unit should be used ONLY in conjunction with the patch suggested here:
// https://forums.embarcadero.com/thread.jspa?messageID=894946
//
// *****************************************************************************
interface
implementation
uses
// RTL
System.Classes,
// Android
Androidapi.JNIBridge, Androidapi.JNI.Os,
// FMX
FMX.Forms;
type
TIdleHandler = class(TJavaLocal, JMessageQueue_IdleHandler)
private
class var FHandler: TIdleHandler;
protected
class procedure RegisterHandler;
class procedure UnregisterHandler;
public
constructor Create;
destructor Destroy; override;
function queueIdle: Boolean; cdecl;
end;
{ TIdleHandler }
constructor TIdleHandler.Create;
begin
inherited Create;
TJLooper.JavaClass.myQueue.addIdleHandler(Self);
end;
destructor TIdleHandler.Destroy;
begin
TJLooper.JavaClass.myQueue.removeIdleHandler(Self);
inherited;
end;
class procedure TIdleHandler.RegisterHandler;
begin
if FHandler = nil then
FHandler := TIdleHandler.Create;
end;
class procedure TIdleHandler.UnregisterHandler;
begin
FHandler.Free;
FHandler := nil;
end;
function TIdleHandler.queueIdle: Boolean;
var
LDone: Boolean;
begin
Result := True;
if TThread.CurrentThread.ThreadID = MainThreadID then
begin
CheckSynchronize;
if ApplicationState <> TApplicationState.Terminating then
begin
try
LDone := False;
Application.DoIdle(LDone);
except
Application.HandleException(Application);
end;
end;
end;
end;
initialization
TIdleHandler.RegisterHandler;
finalization
TIdleHandler.UnregisterHandler;
end.
|
unit Scenario;
interface
uses
ScenarioIntf, Classes, dCucuberListIntf, ValidationRuleIntf, TestFramework, StepIntf;
type
TScenario = class(TTestCase, IScenario, IValidationRule)
private
FSteps: ICucumberList;
FTitulo: string;
FValidationRule: IValidationRule;
function GetSteps: ICucumberList;
function GetTestName: string;
function GetTitulo: string;
function GetValidationRule: IValidationRule;
procedure SetSteps(const Value: ICucumberList);
procedure SetTitulo(const Value: string);
procedure SetValidationRule(const Value: IValidationRule);
class function HasTestMethodFor(const AStep: IStep): Boolean;
public
constructor Create(MethodName: string); override;
property ValidationRule: IValidationRule read GetValidationRule write SetValidationRule implements IValidationRule;
property Steps: ICucumberList read GetSteps write SetSteps;
property Titulo: string read GetTitulo write SetTitulo;
property TestName: string read GetTestName;
end;
implementation
uses
dCucuberList, ValidationRule, TypeUtils;
constructor TScenario.Create(MethodName: string);
begin
inherited Create(MethodName);
FSteps := TCucumberList.Create;
FSteps.ValidationRule.ValidateFunction := function: Boolean
var
i: Integer;
LStep: IStep;
begin
Result := FSteps.Count > 0;
for I := 0 to FSteps.Count - 1 do
begin
LStep := (FSteps[i] as IStep);
Result := Result and LStep.ValidationRule.Valid;
Result := Result and HasTestMethodFor(LStep);
if not Result then
Break;
end;
end;
ValidationRule.ValidateFunction := function: Boolean
begin
Result := not S(FTitulo).IsEmpty(True);
Result := Result and FSteps.ValidationRule.Valid;
end;
end;
function TScenario.GetSteps: ICucumberList;
begin
Result := FSteps;
end;
function TScenario.GetTestName: string;
begin
Result := S(FTitulo).AsClassName;
end;
function TScenario.GetTitulo: string;
begin
Result := FTitulo;
end;
function TScenario.GetValidationRule: IValidationRule;
begin
if FValidationRule = nil then
FValidationRule := TValidationRule.Create;
Result := FValidationRule;
end;
class function TScenario.HasTestMethodFor(const AStep: IStep): Boolean;
var
I: Integer;
LTest: ITest;
begin
Result := False;
if Suite.Tests.Count > 0 then
for I := 0 to Suite.Tests.Count - 1 do
begin
LTest := Suite.Tests[i] as ITest;
Result := S(LTest.Name).Equals(AStep.MetodoDeTeste);
if Result then
Break;
end;
end;
procedure TScenario.SetSteps(const Value: ICucumberList);
begin
FSteps := Value;
end;
procedure TScenario.SetTitulo(const Value: string);
begin
FTitulo := Value;
end;
procedure TScenario.SetValidationRule(const Value: IValidationRule);
begin
FValidationRule := Value;
end;
end.
|
program SPLITPAS ( INPUT , OUTPUT , OUTTEXT , OUTBIN ) ;
(***********************************************************)
(* *)
(* This program splits the large download file *)
(* - see download.pas - into the original seperate *)
(* files and writes them (on Windows etc.) into *)
(* directories; the names of the directories are *)
(* built from the names of the original MVS datasets. *)
(* *)
(* The hex flags are recognized; the hex encoded *)
(* files are written in the original binary *)
(* representation, so that they could be transferred *)
(* to a target mainframe using binary FTP or *)
(* equivalent transfer protocols. *)
(* *)
(***********************************************************)
(* *)
(* Author: Bernd Oppolzer - May 2017 *)
(* *)
(***********************************************************)
(* *)
(* outtext = output file for text *)
(* outbin = output file for binary (recfm f lrecl 80) *)
(* *)
(* the program uses the new anyfile type; *)
(* this was needed to make assign on binary files *)
(* possible *)
(* *)
(* assign assigns Windows file names (and paths) *)
(* to Pascal files (before rewrite in this case) *)
(* *)
(***********************************************************)
const SIZEDSN = 44 ;
SIZEMEM = 8 ;
SIZEEXT = 3 ;
MAXLINEOFFS = 72 ;
MAXOUT = 100 ;
type CHARPTR = -> CHAR ;
CHAR6 = array [ 1 .. 6 ] of CHAR ;
CHAR80 = array [ 1 .. 80 ] of CHAR ;
ZEILE = array [ 1 .. 128 ] of CHAR ;
RECBIN = record
Z : CHAR80 ;
end ;
var OUTTEXT : TEXT ;
OUTBIN : FILE of RECBIN ;
OUTREC : RECBIN ;
ZINP : ZEILE ;
ZOUT : array [ 1 .. 1000 ] of CHAR ;
LOUT : INTEGER ;
OUTPOS : INTEGER ;
CPOUT : CHARPTR ;
TAG : CHAR6 ;
DSN : array [ 1 .. SIZEDSN ] of CHAR ;
MEM : array [ 1 .. SIZEMEM ] of CHAR ;
EXT : array [ 1 .. SIZEEXT ] of CHAR ;
HEXFLAG : CHAR ;
procedure ASSIGN ( var X : ANYFILE ; FNAME : CHARPTR ; LEN : INTEGER )
;
EXTERNAL ;
procedure ASSIGN_FILE ( PDSN : CHARPTR ; PMEM : CHARPTR ; PEXT :
CHARPTR ; HEXFLAG : CHAR ) ;
(***********************************************************)
(* *)
(* this procedure assigns a file name and path *)
(* to the pascal file OUTBIN or OUTTEXT *)
(* (depending on the HEXFLAG). The directory is *)
(* built from the DSN, the file name is built from *)
(* the member name and the extension *)
(* *)
(***********************************************************)
var DSN : array [ 1 .. SIZEDSN ] of CHAR ;
MEM : array [ 1 .. SIZEMEM ] of CHAR ;
EXT : array [ 1 .. SIZEEXT ] of CHAR ;
PFADNAME : array [ 1 .. SIZEDSN ] of CHAR ;
PFADLEN : INTEGER ;
FILENAME : array [ 1 .. 100 ] of CHAR ;
FILELEN : INTEGER ;
I : INTEGER ;
MD_CMD : array [ 1 .. 100 ] of CHAR ;
RC : INTEGER ;
CMDPART : CHAR80 ;
begin (* ASSIGN_FILE *)
MEMCPY ( ADDR ( DSN ) , PDSN , SIZEDSN ) ;
MEMCPY ( ADDR ( MEM ) , PMEM , SIZEMEM ) ;
MEMCPY ( ADDR ( EXT ) , PEXT , SIZEEXT ) ;
WRITELN ( '-----------------------------' ) ;
WRITELN ( 'dsn = ' , DSN ) ;
WRITELN ( 'mem = ' , MEM ) ;
WRITELN ( 'ext = ' , EXT ) ;
WRITELN ( 'hex = ' , HEXFLAG ) ;
WRITELN ( '-----------------------------' ) ;
PFADLEN := 0 ;
PFADNAME := DSN ;
for I := 1 to SIZEDSN do
if PFADNAME [ I ] <> ' ' then
begin
PFADLEN := I ;
if PFADNAME [ I ] = '.' then
PFADNAME [ I ] := '_'
end (* then *) ;
WRITELN ( 'pfadname = ' , PFADNAME ) ;
WRITELN ( 'pfadlen = ' , PFADLEN ) ;
/********************************************************/
/* create directory */
/********************************************************/
MD_CMD := 'mkdir ' ;
MEMCPY ( ADDR ( MD_CMD [ 7 ] ) , ADDR ( PFADNAME ) , SIZEDSN ) ;
CMDPART := '2>NUL #' ;
MEMCPY ( ADDR ( MD_CMD [ 53 ] ) , ADDR ( CMDPART ) , 8 ) ;
WINX ( ADDR ( MD_CMD ) , RC ) ;
/********************************************************/
/* ASSign file */
/********************************************************/
FILENAME := ' ' ;
MEMCPY ( ADDR ( FILENAME ) , ADDR ( PFADNAME ) , SIZEDSN ) ;
FILENAME [ PFADLEN + 1 ] := '/' ;
MEMCPY ( ADDR ( FILENAME [ PFADLEN + 2 ] ) , ADDR ( MEM ) ,
SIZEMEM ) ;
for I := PFADLEN + 2 to PFADLEN + 10 do
if FILENAME [ I ] = ' ' then
begin
FILELEN := I - 1 ;
break
end (* then *) ;
FILENAME [ FILELEN + 1 ] := '.' ;
MEMCPY ( ADDR ( FILENAME [ FILELEN + 2 ] ) , ADDR ( EXT ) ,
SIZEEXT ) ;
FILELEN := FILELEN + 1 + SIZEEXT ;
WRITELN ( 'filename = ' , FILENAME ) ;
WRITELN ( 'filelen = ' , FILELEN ) ;
WRITELN ( '-----------------------------' ) ;
if HEXFLAG = 'H' then
ASSIGN ( OUTBIN , ADDR ( FILENAME ) , FILELEN )
else
ASSIGN ( OUTTEXT , ADDR ( FILENAME ) , FILELEN ) ;
end (* ASSIGN_FILE *) ;
procedure WRITEBUF ( HEXFLAG : CHAR ; CPOUT : CHARPTR ; LOUT : INTEGER
) ;
var I : INTEGER ;
H : INTEGER ;
HEX : INTEGER ;
CH : CHAR ;
CPLAST : CHARPTR ;
(***********************************************************)
(* *)
(* the buffer (addressed by cpout, length in lout) *)
(* is written to the output file. *)
(* *)
(* if hex, the decoding is done. *)
(* *)
(* if not hex, trailing blanks are eliminated. *)
(* *)
(***********************************************************)
begin (* WRITEBUF *)
if HEXFLAG = 'H' then
begin
OUTREC . Z := '' ;
for I := 1 to 80 do
begin
CH := CPOUT -> ;
if ( CH >= '0' ) and ( CH <= '9' ) then
H := ORD ( CH ) - ORD ( '0' )
else
if ( CH >= 'A' ) and ( CH <= 'F' ) then
H := ORD ( CH ) - ORD ( 'A' ) + 10 ;
HEX := H * 16 ;
CPOUT := PTRADD ( CPOUT , 1 ) ;
CH := CPOUT -> ;
if ( CH >= '0' ) and ( CH <= '9' ) then
H := ORD ( CH ) - ORD ( '0' )
else
if ( CH >= 'A' ) and ( CH <= 'F' ) then
H := ORD ( CH ) - ORD ( 'A' ) + 10 ;
HEX := HEX + H ;
CPOUT := PTRADD ( CPOUT , 1 ) ;
OUTREC . Z [ I ] := CHR ( HEX ) ;
end (* for *) ;
/***************************************/
/* PUT ( OUTBIN ) ; */
/* OUTBIN -> := OUTREC ; */
/***************************************/
WRITE ( OUTBIN , OUTREC ) ;
end (* then *)
else
begin
CPLAST := PTRADD ( CPOUT , LOUT - 1 ) ;
while ( LOUT > 0 ) and ( CPLAST -> = ' ' ) do
begin
LOUT := LOUT - 1 ;
CPLAST := PTRADD ( CPLAST , - 1 ) ;
end (* while *) ;
for I := 1 to LOUT do
begin
WRITE ( OUTTEXT , CPOUT -> ) ;
CPOUT := PTRADD ( CPOUT , 1 ) ;
end (* for *) ;
WRITELN ( OUTTEXT ) ;
end (* else *)
end (* WRITEBUF *) ;
begin (* HAUPTPROGRAMM *)
READLN ( ZINP ) ;
while not EOF ( INPUT ) do
begin
MEMCPY ( ADDR ( TAG ) , ADDR ( ZINP ) , 6 ) ;
(***********************************************************)
(* the record tagged with FILE contains the *)
(* meta information (DSN, MEM, EXT, Hex Flag) *)
(***********************************************************)
if TAG = '++FILE' then
begin
MEMCPY ( ADDR ( DSN ) , ADDR ( ZINP [ 8 ] ) , SIZEDSN ) ;
MEMCPY ( ADDR ( MEM ) , ADDR ( ZINP [ 58 ] ) , SIZEMEM ) ;
MEMCPY ( ADDR ( EXT ) , ADDR ( ZINP [ 71 ] ) , SIZEEXT ) ;
HEXFLAG := ZINP [ 79 ] ;
ASSIGN_FILE ( ADDR ( DSN ) , ADDR ( MEM ) , ADDR ( EXT ) ,
HEXFLAG ) ;
if HEXFLAG = 'H' then
REWRITE ( OUTBIN )
else
REWRITE ( OUTTEXT ) ;
LOUT := - 1 ;
repeat
if EOF ( INPUT ) then
break ;
READLN ( ZINP ) ;
MEMCPY ( ADDR ( TAG ) , ADDR ( ZINP ) , 6 ) ;
(***********************************************************)
(* the other records (DATA) are collected into *)
(* the large buffer ZOUT. When the buffer is complete, *)
(* WRITEBUF is called to flush the buffer. *)
(***********************************************************)
if HEXFLAG = 'H' then
begin
if TAG = '++DATA' then
begin
if ZINP [ 7 ] = '1' then
begin
if LOUT > 0 then
WRITEBUF ( HEXFLAG , ADDR ( ZOUT ) , LOUT ) ;
LOUT := IVALSTR ( ADDR ( ZINP [ 8 ] ) , 5 ) ;
OUTPOS := IVALSTR ( ADDR ( ZINP [ 13 ] ) , 5 )
;
OUTPOS := OUTPOS * 2 ;
CPOUT := PTRADD ( ADDR ( ZOUT ) , OUTPOS ) ;
MEMCPY ( CPOUT , ADDR ( ZINP [ 19 ] ) , 100 ) ;
end (* then *)
else
begin
OUTPOS := IVALSTR ( ADDR ( ZINP [ 13 ] ) , 5 )
;
OUTPOS := OUTPOS * 2 ;
CPOUT := PTRADD ( ADDR ( ZOUT ) , OUTPOS ) ;
MEMCPY ( CPOUT , ADDR ( ZINP [ 19 ] ) , 100 ) ;
end (* else *)
end (* then *)
end (* then *)
else
if TAG <> '++FILE' then
WRITEBUF ( HEXFLAG , ADDR ( ZINP ) , 80 ) ;
until TAG = '++FILE' ;
if LOUT > 0 then
WRITEBUF ( HEXFLAG , ADDR ( ZOUT ) , LOUT ) ;
if HEXFLAG = 'H' then
CLOSE ( OUTBIN )
else
CLOSE ( OUTTEXT ) ;
end (* then *)
else
begin
WRITELN ( '+++ falsche Satzart: ' , TAG ) ;
break ;
end (* else *)
end (* while *)
end (* HAUPTPROGRAMM *) .
|
Unit Joystick;
(****************************************************************************)
INTERFACE
(****************************************************************************)
var
JoyXMin,JoyXMax,JoyXHalf,JoyYMin,JoyYMax,JoyYHalf: integer;
function JoystickExists : Boolean;
function JoystickPosX : Integer;
function JoystickPosY : Integer;
function JoystickButtonA : Boolean;
function JoystickButtonB : Boolean;
procedure CalibrateJoystick;
function JoystickRight: boolean;
function JoystickLeft: boolean;
(****************************************************************************)
IMPLEMENTATION
(****************************************************************************)
uses Crt, Dos;
const
GamePortAddr = $200;
MaxCount = 500;
function JoystickStatus (Mask: Byte): Integer;
var
Counter: Integer;
label
Read;
begin
asm
mov cx,MaxCount
mov dx,GamePortAddr
mov ah,Mask
out dx,al
read:
in al,dx
test al,ah
loopnz read
mov counter,cx
end;
JoystickStatus:=MaxCount-Counter;
Delay (2);
end;
function JoystickPosX: Integer;
begin
JoystickPosX:=JoystickStatus(1);
end;
function JoystickPosY: Integer;
begin
JoystickPosY:=JoystickStatus(2);
end;
function JoystickButtonA:Boolean;
begin
JoystickButtonA:=(Port [GamePortAddr] and 16)=0;
end;
function JoystickButtonB: Boolean;
begin
JoystickButtonB:=(Port [GamePortAddr] and 32)=0;
end;
function JoystickExists: Boolean;
var
Regs: Registers;
begin
JoystickExists:= not ((JoystickPosX=0) and (JoystickPosY=0));
end;
procedure CalibrateJoystick;
begin
write (' Press joystick to upper left corner and press button 1...');
repeat until JoystickButtonA;
JoyXMin:=JoystickPosX;
JoyYMin:=JoystickPosY;
writeln('OK.');
repeat until not JoystickButtonA;
write (' Press joystick to lower right corner and press button 2...');
repeat until JoystickButtonB;
JoyXMax:=JoystickPosX;
JoyYMax:=JoystickPosY;
writeln ('OK.');
repeat until not JoystickButtonB;
JoyXHalf:=(JoyXMin+JoyXMax) div 2;
JoyYHalf:=(JoyYMin+JoyYMax) div 2;
end;
function JoystickRight: boolean;
begin
JoystickRight:=(JoystickPosX=JoyXMax);
end;
function JoystickLeft: boolean;
begin
JoystickLeft:=(JoystickPosX=JoyXMin);
end;
end.
{
JOYSTICK PIN-OUTS
1 - +5V to Joystick A (& to Joystick B via pin 9)
2 - + to Button 1 on Joystick A
3 - X Coordinate on Joystick A
4 - Joystick A to ground
5 - Joystick B to ground
6 - Y Coordinate on Joystick A
7 - + to Button 2 on Joystick A
8 - Ground
9 - +5V to Joystick B
10 - + to Button 1 on Joystick B
11 - X Coordinate on Joystick B
12 - not used for joysticks
13 - Y Coordinate on Joystick B
14 - + to Button 2 on Joystick B
15 - not used for joysticks
Pin ID:
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15
} |
unit ExtAIForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
ExtAILog, ExtAIDelphi,
// Detection of IP address
Winsock, Vcl.ComCtrls;
type
TExtAI = class(TForm)
btnConnectClient: TButton;
btnSendAction: TButton;
btnSendState: TButton;
edPort: TEdit;
gbExtAI: TGroupBox;
labPort: TLabel;
mLog: TMemo;
procedure btnConnectClientClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnSendActionClick(Sender: TObject);
private
{ Private declarations }
fExtAI: TExtAIDelphi;
fLog: TExtAILog;
procedure RefreshAIGUI(Sender: TObject);
procedure Log(const aText: String);
public
{ Public declarations }
end;
var
ExtAI: TExtAI;
implementation
{$R *.dfm}
procedure TExtAI.FormCreate(Sender: TObject);
begin
fLog := TExtAILog.Create(Log);
fExtAI := TExtAIDelphi.Create(fLog,1);
fExtAI.Client.OnConnectSucceed := RefreshAIGUI;
fExtAI.Client.OnForcedDisconnect := RefreshAIGUI;
end;
procedure TExtAI.FormDestroy(Sender: TObject);
begin
fExtAI.TerminateSimulation();
Sleep(500);
fExtAI.Free;
fLog.Free;
end;
procedure TExtAI.btnConnectClientClick(Sender: TObject);
function GetIP(var aIPAddress: String): Boolean;
type
pu_long = ^u_long;
var
TWSA: TWSAData;
phe: PHostEnt;
Addr: TInAddr;
Buffer: array[0..255] of AnsiChar;
begin
Result := False;
aIPAddress := '';
if (WSAStartup($101,TWSA) = 0) AND (GetHostName(Buffer, SizeOf(Buffer)) = 0) then
begin
phe := GetHostByName(Buffer);
if (phe = nil) then
Exit;
Addr.S_addr := u_long(pu_long(phe^.h_addr_list^)^);
aIPAddress := String(inet_ntoa(Addr));
Result := True;
end;
WSACleanUp;
end;
var
IP, Port: String;
begin
if fExtAI.Client.Connected then
begin
fExtAI.Client.Disconnect;
btnConnectClient.Caption := 'Connect Client';
btnSendAction.Enabled := False;
btnSendState.Enabled := False;
end
else if GetIP(IP) then
begin
try
Port := edPort.Text;
//fExtAI.Client.ConnectTo(IP, StrToInt(Port));
fExtAI.Client.ConnectTo('127.0.0.1', StrToInt(Port));
except
Log('Invalid port number');
end;
end
else
Log('IP address was not detected')
end;
procedure TExtAI.btnSendActionClick(Sender: TObject);
begin
fExtAI.Actions.Log('This is debug message (Action.Log) from ExtAI');
end;
procedure TExtAI.RefreshAIGUI(Sender: TObject);
begin
if fExtAI.Client.Connected then
begin
btnConnectClient.Caption := 'Disconnect Client';
btnSendAction.Enabled := True;
//btnSendState.Enabled := True;
end
else
begin
btnConnectClient.Caption := 'Connect Client';
btnSendAction.Enabled := False;
btnSendState.Enabled := False;
end;
end;
procedure TExtAI.Log(const aText: String);
begin
mLog.Lines.Append(aText);
end;
end.
|
unit Sokoban;
{ Sokoban component for Delphi 2+ (C)2K by Paul TOTH <tothpaul@free.fr>
http://tothpaul.free.fr
}
{
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
Const
maxx=19;
maxy=11;
type
TBoard=array[0..maxx-1,0..maxy-1] of byte;
TMove=(mNone,mNorth,mSouth,mEast,mWest);
TSoko = class(TCustomControl)
private
fBoard:TBoard;
fEndOfGame:boolean;
fMoveCount:integer;
fMaxX:integer;
fMaxY:integer;
fCellX:integer;
fCellY:integer;
fPlayerX:integer;
fPlayerY:integer;
fMouseX:integer;
fMouseY:integer;
fMove:TMove;
fMines:integer;
fDock:integer;
EOnNewGame:TNotifyEvent;
EOnWin:TNotifyEvent;
procedure SetCell(X,Y:integer;State:integer);
procedure WMSetCursor(Var Msg:TWMSetCursor); message wm_setcursor;
procedure WMGetDlgCode(Var Msg:TWMGetDlgCode); message wm_getdlgcode;
protected
procedure Paint; override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Play;
public
constructor Create(AOwner:TComponent); override;
procedure LoadLevel(Level:array of PChar);
procedure LoadStrings(S:TStringList);
property EndOfGame:boolean read fEndOfGame;
property MoveCount:integer read fMoveCount;
published
property OnNewGame:TNotifyEvent read EOnNewGame write EOnNewGame;
property OnWin:TNotifyEvent read EOnWin write EOnWin;
property TabStop;
property OnMouseDown;
property OnMouseUp;
property OnKeyDown;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('MySoft.Fun', [TSoko]);
end;
{$R SOKOBAN.RES}
Var
Images:HBitmap;
Cursors:array[TMove] of HCursor;
Const
//TMove=(mNone,mNorth,mSouth,mEast,mWest);
Delta:array[TMove] of record dx,dy:integer end=(
(dx:0;dy:0), (dx:0;dy:-1), (dx:0;dy:+1), (dx:+1;dy:0), (dx:-1;dy:0)
);
Hello:array[0..10] of PChar=(
'XXXXXXXXXXXXXXXXXXX',
'XXXXXXXXXXXXXXXXXXX',
'XX@@@XXX@XX@X@XX@XX',
'X@XXXXX@X@X@X@X@X@X',
'XX@@@XX@X@X@@XX@X@X',
'XXXXX@X@X@X@X@X@X@X',
'XX@@@XXX@XX@X@XX@XX',
'XXXXXXXXXXXXXXXXXXX',
'X!.......*.......@X',
'XXXXXXXXXXXXXXXXXXX',
'XXXXXXXXXXXXXXXXXXX'
);
Constructor TSoko.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
LoadLevel(Hello);
fMines:=1;
TabStop:=true;
end;
Procedure TSoko.Paint;
var
dc:HDC;
mx,my:integer;
begin
dc:=CreateCompatibleDC(Canvas.Handle);
SelectObject(dc,Images);
for mx:=0 to maxx-1 do
for my:=0 to maxy-1 do
BitBlt(Canvas.Handle,16*mx,16*my,16,16,DC,0,16*fBoard[mx,my],SRCCOPY);
DeleteDC(dc);
end;
Procedure TSoko.LoadLevel(Level:Array of PChar);
var
x,y:integer;
begin
fMaxY:=High(Level)+1;
fMaxX:=StrLen(Level[0]);
Width:=16*fMaxX;
Height:=16*fMaxY;
fEndOfGame:=False;
fMoveCount:=0;
fDock:=0;
fMines:=0;
FillChar(fBoard,SizeOf(fBoard),0);
for y:=0 to MaxY-1 do begin
for x:=0 to MaxX-1 do begin
fBoard[x,y]:=Pos(Level[y][x],{.}'@**!!X');
case fBoard[x,y]of
2 : inc(fMines);
4 : begin fPlayerX:=X; fPlayerY:=Y; end;
end;
end;
end;
Invalidate;
if Assigned(EOnNewGame) then EOnNewGame(Self);
end;
procedure TSoko.LoadStrings(S:TStringList);
var
x,y:integer;
begin
// fMaxY:=s.Count;
// fMaxX:=Length(s[0]);
// Width:=16*fMaxX;
// Height:=16*fMaxY;
fEndOfGame:=False;
fMoveCount:=0;
fDock:=0;
fMines:=0;
FillChar(fBoard,SizeOf(fBoard),0);
for y:=0 to MaxY-1 do begin
for x:=0 to MaxX-1 do begin
fBoard[x,y]:=Pos(s[y+1][x+1],{.}'@**!!X');
case fBoard[x,y]of
2 : inc(fMines);
4 : begin fPlayerX:=X; fPlayerY:=Y; end;
end;
end;
end;
Invalidate;
if Assigned(EOnNewGame) then EOnNewGame(Self);
end;
procedure TSoko.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
fMouseX:=X div 16;
fMouseY:=Y div 16;
inherited MouseMove(Shift,X,Y);
end;
procedure TSoko.WMSetCursor(Var Msg:TWMSetCursor);
var
dy:integer;
begin
dy:=fPlayerY-fMouseY;
fMove:=mNone;
if fBoard[fMouseX,fMouseY]<4 then begin
case fPlayerX-fMouseX of
-1: if dy=0 then fMove:=mEast;
0: case dy of
-1 : fMove:=mSouth;
+1 : fMove:=mNorth;
end;
+1: if dy=0 then fMove:=mWest;
end;
end;
SetCursor(Cursors[fMove]);
end;
procedure TSoko.WMGetDlgCode(Var Msg:TWMGetDlgCode);
begin
inherited;
Msg.Result:=Msg.Result or dlgc_WantArrows;
end;
procedure TSoko.SetCell(X,Y:integer;State:integer);
Var
R:TRect;
begin
if (x<0)or(x>=maxx)or(y<0)or(y>=maxy) then exit;
if fBoard[x,y]=3 then dec(fDock);
fBoard[X,Y]:=fBoard[X,Y]+State;
if fBoard[x,y]=3 then inc(fDock);
R.Left:=16*X; R.Right:=R.Left+16;
R.Top :=16*Y; R.Bottom:=R.Top+16;
InvalidateRect(Handle,@R,False);
end;
procedure TSoko.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited MouseDown(Button,Shift,X,Y);
if fEndOfGame then exit;
if fMove=mNone then exit;
fCellX:=X div 16;
fCellY:=Y div 16;
Play;
end;
procedure TSoko.KeyDown(var Key: Word; Shift: TShiftState);
var
dx,dy:integer;
begin
inherited KeyDown(Key,Shift);
if fEndOfGame then exit;
case key of
vk_up : fMove:=mNorth;
vk_down : fMove:=mSouth;
vk_left : fMove:=mWest;
vk_right : fMove:=mEast;
else exit;
end;
dx:=Delta[fMove].dx;
dy:=Delta[fMove].dy;
fCellX:=fPlayerX+dx;
fCellY:=fPlayerY+dy;
if fBoard[fCellX,fCellY]>=4 then begin
Beep;
exit;
end;
Play;
end;
procedure TSoko.Play;
var
dx,dy:integer;
begin
dx:=Delta[fMove].dx;
dy:=Delta[fMove].dy;
if fBoard[fCellX,fCellY]>1 then begin
if fBoard[fCellX+dx,fCellY+dy]<2 then begin
SetCell(fCellX+dx,fCellY+dy,+2);
SetCell(fCellX,fCellY,-2);
end else begin
Beep;
exit;
end;
end;
SetCell(fCellX,fCellY,+4);
SetCell(fPlayerX,fPlayerY,-4);
fPlayerX:=fCellX;
fPlayerY:=fCellY;
inc(fMoveCount);
if fDock=fMines then begin
fEndOfGame:=True;
if Assigned(EOnWin) then EOnWin(Self) else begin
end;
end;
end;
initialization
Randomize;
Images:=LoadBitmap(HInstance,'SOKOBAN');;
Cursors[mNone] :=Screen.Cursors[crDefault];
Cursors[mNorth]:=LoadCursor(HInstance,'NORTH');
Cursors[mSouth]:=LoadCursor(HInstance,'SOUTH');
Cursors[mEast ]:=LoadCursor(HInstance,'EAST');
Cursors[mWest ]:=LoadCursor(HInstance,'WEST');
finalization
DeleteObject(Images);
DeleteObject(Cursors[mNorth]);
DeleteObject(Cursors[mSouth]);
DeleteObject(Cursors[mEast]);
DeleteObject(Cursors[mWest]);
end.
|
{ 13.01.2012 18:11:22 (GMT+1:00) > [shmia on SHMIA01] checked in Bugfix
für function ISO8601Timezone() }
{ 13.01.2012 17:43:43 (GMT+1:00) > [shmia on SHMIA01] checked in Erweiterung
für Zeitzonen }
{ 26.06.2009 10:38:50 (GMT+2:00) > [shmia on SHMIA01] checked in ISO8601StrToDateTime:
korrekte Behandlung von "0000-00-00" }
{ 02.12.2008 12:31:16 (GMT+1:00) > [haide on HAIDE02] checked in }
{ 07.11.2008 18:48:12 (GMT+1:00) > [haide on HAIDE02] checked in ISO8601StrToDateTime:
Zeitanteile wurde nicht umgewandelt, weil diese von der falschen
Position kopiert wurden. }
{ 04.04.2007 12:29:25 (GMT+2:00) > [shmia on SHMIA01] checked in function
ISO8601StrToDateTime() hinzu }
{ 09.05.2006 15:05:52 (GMT+2:00) > [shmia on SHMIA01] checked in }
{ 09.05.2006 14:22:47 (GMT+2:00) > [shmia on SHMIA01] checked in }
unit ISO8601;
// see: http://www.iso.org/iso/en/prods-services/popstds/datesandtime.html
interface
function ISO8601DateTimeToStr(DateTime: TDateTime):string;overload;
function ISO8601DateTimeToStr(DateTime: TDateTime; tzbias:Integer):string;overload;
function ISO8601DateToStr(Date: TDateTime):string;
function ISO8601TimeToStr(Time: TDateTime):string;overload;
function ISO8601TimeToStr(Date: TDateTime; tzbias:Integer):string;overload;
function ISO8601StrToDateTime(const s:string):TDateTime;
implementation
uses SysUtils;
function ISO8601Timezone(tzbias{in Minutes}:Integer):string;
var
sign : Char;
begin
if tzbias = 0 then
Result := 'Z'
else
begin
if tzbias < 0 then
begin
tzbias := -tzbias;
sign := '-';
end
else
sign := '+';
Result := Result + Format('%s%2.2d:%2.2d',[sign,tzbias div 60, tzbias mod 60]);
end;
end;
function ISO8601DateTimeToStr(DateTime: TDateTime):string;
begin
Result := FormatDateTime('yyyy-mm-dd"T"hh":"nn":"ss', DateTime);
end;
function ISO8601DateTimeToStr(DateTime: TDateTime; tzbias:Integer):string;overload;
begin
Result := ISO8601DateTimeToStr(DateTime) + ISO8601Timezone(tzbias);
end;
function ISO8601DateToStr(Date: TDateTime):string;
begin
Result := FormatDateTime('yyyy-mm-dd', Date);
end;
function ISO8601TimeToStr(Time: TDateTime):string;
begin
Result := FormatDateTime('hh":"nn":"ss', Time);
end;
function ISO8601TimeToStr(Date: TDateTime; tzbias:Integer):string;
begin
Result := ISO8601TimeToStr(Date) + ISO8601Timezone(tzbias);
end;
(*
function CheckDateTimeFormat(const Value, DTFormat: String): Boolean;
var
i: Integer;
begin
Result := False;
if Length(Value) = Length(DTFormat) then
begin
for i := 1 to Length(Value) do begin
if DTFormat[i] = '9' then begin // Digit
if not (Value[i] in ['0'..'9']) then
Exit;
end
else begin
if DTFormat[i] <> Value[i] then
Exit;
end;
end;
Result := True;
end;
end;
*)
function ISO8601StrToTime(const s:string):TDateTime;
function ExtractNum(a, len: Integer):Integer;
begin
Result := StrToIntDef(Copy(s, a, len), 0);
end;
begin
if (Length(s) >= 8) and (s[3]=':') then
begin
Result := EncodeTime(ExtractNum(1,2), ExtractNum(4,2), ExtractNum(7,2), 0);
end
else
Result := 0.0;
end;
function ISO8601StrToDateTime(const s:string):TDateTime;
function ExtractNum(a, len: Integer):Integer;
begin
Result := StrToIntDef(Copy(s, a, len), 0);
end;
var
year, month, day: Integer;
begin
if (Length(s) >= 10) and (s[5]='-') and (s[8]='-') then
begin
year := ExtractNum(1, 4);
month := ExtractNum(6,2);
day := ExtractNum(9,2);
if (year=0) and (month=0) and (day=0) then // shmia#26.06.2009
Result := 0.0
else
Result := EncodeDate(year, month, day);
if (Length(s) > 10) and (s[11] = 'T') then
Result := Result + ISO8601StrToTime(Copy(s, 12, 999));
end
else
Result := ISO8601StrToTime(s);
end;
end.
|
unit uPenarikanDeposit;
interface
uses
uAccount, uModel, uSupplier, uAR;
type
TPenarikanDeposit = class(TAppObject)
private
FAP: TAP;
FKeterangan: string;
FNoBukti: string;
FNominal: Double;
FSantri: TSupplier;
FTanggal: TDatetime;
function GetAP: TAP;
public
published
property AP: TAP read GetAP write FAP;
property Keterangan: string read FKeterangan write FKeterangan;
property NoBukti: string read FNoBukti write FNoBukti;
property Nominal: Double read FNominal write FNominal;
property Santri: TSupplier read FSantri write FSantri;
property Tanggal: TDatetime read FTanggal write FTanggal;
end;
implementation
function TPenarikanDeposit.GetAP: TAP;
begin
if FAP = nil then
FAP := TAP.Create;
FAP.Supplier := TSupplier.CreateID(Santri.ID);
FAP.IDTransaksi := Self.ID;
FAP.Nominal := -1 * Self.Nominal;
FAP.NoBukti := Self.NoBukti;
FAP.NoBuktiTransaksi := Self.NoBukti;
FAP.Transaksi := Self.ClassName;
FAP.TglBukti := Self.Tanggal;
Result := FAP;
end;
initialization
TPenarikanDeposit.PokeRTTI;
end.
|
unit Ragna.Intf;
{$IF DEFINED(FPC)}
{$MODE DELPHI}{$H+}
{$ENDIF}
interface
uses FireDAC.Comp.Client, System.JSON, Data.DB;
type
IRagna = interface
['{0F1AD1E9-A82C-44BE-9208-685B9C3C77F9}']
procedure Paginate(const AOffSet, ALimit: Integer);
procedure RadicalResearch(const AValue: string; const AFields: array of TField);
procedure Remove(const AField: TField; const AValue: Int64);
procedure FindById(const AField: TField; const AValue: Int64);
procedure UpdateById(const AField: TField; const AValue: Int64; const ABody: TJSONObject);
procedure OpenUp;
procedure OpenEmpty;
procedure Reset;
procedure EditFromJson(const AJSON: TJSONObject); overload;
procedure EditFromJson(const AJSON: TJSONArray); overload;
procedure EditFromJson(const AJSON: string); overload;
procedure New(const ABody: TJSONObject); overload;
procedure New(const ABody: TJSONArray); overload;
procedure New(const ABody: string); overload;
function ToJSONArray: TJSONArray;
function ToJSONObject: TJSONObject;
end;
implementation
end.
|
unit Control.FinanceiroEmpresa;
interface
uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Control.Sistema, Model.FinanceiroEmpresa;
type
TFinanceiroEmpresaControl = class
private
FFinanceiro : TFinanceiroEmpresa;
public
constructor Create;
destructor Destroy; override;
property Financeiro: TFinanceiroEmpresa read FFinanceiro write FFinanceiro;
function GetID(iID: Integer): Integer;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
function ValidaCampos(): Boolean;
end;
implementation
{ TFinanceiroEmpresaControl }
uses Common.ENum;
constructor TFinanceiroEmpresaControl.Create;
begin
FFinanceiro := TFinanceiroEmpresa.Create;
end;
destructor TFinanceiroEmpresaControl.Destroy;
begin
Financeiro.Free;
inherited;
end;
function TFinanceiroEmpresaControl.GetID(iID: Integer): Integer;
begin
Result := FFinanceiro.GetID(iID);
end;
function TFinanceiroEmpresaControl.Gravar: Boolean;
begin
Result := FFinanceiro.Gravar;
end;
function TFinanceiroEmpresaControl.Localizar(aParam: array of variant): TFDQuery;
begin
Result := FFinanceiro.Localizar(aParam);
end;
function TFinanceiroEmpresaControl.ValidaCampos: Boolean;
var
FDQuery : TFDQuery;
aParam: Array of variant;
begin
try
Result := False;
FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery;
if FFinanceiro.ID = 0 then
begin
Application.MessageBox('Informe o ID do cadastro!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FFinanceiro.Acao <> tacIncluir then
begin
if FFinanceiro.Sequencia = 0 then
begin
Application.MessageBox('Informe a sequência!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
end;
if FFinanceiro.TipoConta.IsEmpty then
begin
Application.MessageBox('Informe o tipo de conta!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if StrToIntDef(FFinanceiro.Banco,0) = 0 then
begin
Application.MessageBox('Informe o banco da conta!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FFinanceiro.Agencia.IsEmpty then
begin
Application.MessageBox('Informe a agência da conta!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FFinanceiro.Conta.IsEmpty then
begin
Application.MessageBox('Informe a conta!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
finally
FDQuery.Free;
end;
end;
end.
|
{
archive handler
c:\windows\hene\hede.zip\hene.dir\hede
openfs called with url of archive name and directories are added as needed
this way parents should work better
}
unit fsarchive;
interface
uses
fs,
SysUtils, Classes;
type
TArchiveFSHandler = class(TFSHandler)
protected
Base : string;
Stream : TStream;
function getSubPath:string;
public
procedure OpenFS(const url:string);override;
procedure CloseFS;override;
function contentsChanged:boolean;override;
procedure setParent;override;
end;
implementation
{ TArchiveFSHandler }
function TArchiveFSHandler.getSubPath;
begin
with Info do
if pos(UpperCase(Base),UpperCase(Path)) = 0 then
Result := System.copy(Path,length(Base)+1,length(Path))
else
raise EFSException.Create(Format('Path<->Base inconsistent "%s"/"%s"',
[Path,Base]));
end;
procedure TArchiveFSHandler.OpenFS(const url: string);
begin
Base := url;
Stream := TFileStream.Create(url,fmOpenRead);
setPath(IncludeTrailingPathDelimiter(url));
end;
procedure TArchiveFSHandler.CloseFS;
begin
Stream.Free;
end;
function TArchiveFSHandler.contentsChanged: boolean;
begin
Result := false;
end;
procedure TArchiveFSHandler.setParent;
var
pnew:string;
begin
pnew := ExtractFilePath(ExcludeTrailingPathDelimiter(Info.Path));
if length(pnew) < length(Base) then
raise EFSChangeRequired.Create(pnew)
else
setPath(pnew);
end;
end.
|
unit FastShareMem;
(*
* Shared Memory Allocator for Delphi DLL's
* Version: 1.21
*
* Features:
* no runtime dll required.
* no performance degradation.
*
* Usage:
* Must be the first unit listed in the project file's USES section
* for both dll and exe projects. If you install a memory manager for
* leak detection, it should be listed immediately after this unit.
*
* Author: Emil M. Santos
* You may use and modify this software as you wish, but this section
* must be kept intact. Please see Readme.txt for copyright and disclaimer.
*
* Send bugs/comments to fastsharemem@codexterity.com
* On the web: http://www.codexterity.com
* To be notified of new versions by email, subscribe to the site alerter facility.
Revision History:
2002 Oct 9: Separated MEM_DECOMMIT and MEM_RELEASE calls. Thanks to Maurice Fletcher and Alexandr Kozin.
2002 Sep 9: Thanks to Ai Ming (aiming@ynxx.com) for these changes:
Modified to work with Windows NT/2000/XP.
Added reference-counting mechanism.
2002 Aug 14: Rewrote address-computation code to better match windows 98
allocation. VirtualAlloc may round down requested address *twice*.
Replaced ASSERTs with (lower-level) Win32 MessageBox calls.
(Thanks to Darryl Strickland (DStrickland@carolina.rr.com))
*)
interface
implementation
uses Windows, SysUtils;
const SignatureBytes1 = $BABE01234567FEED;
SignatureBytes2 = $F00D76543210B00B;
const iPagesBound = 15;
type
TMemMgrPack = record
RefCount: Integer; //Reference Count of the MemMgr
Signature1: int64;
MemMgr: TMemoryManager;
Signature2: int64;
end;
PMemMgrPack = ^TMemMgrPack;
procedure ValidatePack( p: PMemMgrPack );
var pid: DWORD;
begin
// use pid for additional safety;
p^.RefCount := 1;
pid := GetCurrentProcessId;
p^.Signature1 := SignatureBytes1 xor pid;
p^.Signature2 := SignatureBytes2 xor pid;
end;
function IsPackValid( p: PMemMgrPack ): boolean;
var pid: DWORD;
begin
pid := GetCurrentProcessId;
Result := (p^.Signature1 = SignatureBytes1 xor pid) and
(p^.Signature2 = SignatureBytes2 xor pid);
end;
var
si: TSYSTEMINFO;
OldMemMgr: TMemoryManager;
requested, allocated: PMemMgrPack;
err: integer;
lpMsgBuf: PChar;
granul: integer;
iPages: integer;
initialization
GetSystemInfo( si );
iPages := 0;
//next, fixed by Aimingoo
repeat
requested := si.lpMaximumApplicationAddress ;
requested := pointer( (integer(requested) div $10000) * $10000 ); // align on start of last full 64k page
dec(integer(requested), iPages * $10000);
requested := pointer( (integer(requested) div si.dwPageSize) * si.dwPageSize ); // align on start of last full 64k page
allocated := VirtualAlloc( requested, si.dwPageSize, MEM_RESERVE or MEM_COMMIT, PAGE_READWRITE );
//find a free memory block or a valid MemMgr
if (allocated <> nil) then
if (requested = allocated) then
Break
else
else
if IsPackValid(requested) then
Break;
inc(iPages);
until iPages > iPagesBound;
if allocated <> nil then
begin
if requested <> allocated then
begin
MessageBox( 0, 'Shared Memory Allocator setup failed: Address was relocated.', 'FastShareMem', 0 );
Halt;
end;
GetMemoryManager( allocated^.MemMgr );
ValidatePack( allocated );
end
else
begin
if not IsPackValid( requested ) then
begin
MessageBox( 0, 'Shared Memory Allocator setup failed: Address already reserved.', 'FastShareMem', 0 );
Halt;
end;
GetMemoryManager( OldMemMgr );
SetMemoryManager( requested^.MemMgr );
inc(requested^.RefCount);
end;
finalization
//next, fixed by Aimingoo
(* fix Reference Count *)
dec(requested^.RefCount);
(* restore MemMgr to Old, only for DLL or other model *)
if allocated = nil then
SetMemoryManager( OldMemMgr )
else
if requested^.RefCount > 0 then
begin
TerminateProcess(GetCurrentProcess, 0);
end;
(* cleanup *)
if requested^.RefCount = 0 then
begin
VirtualFree( allocated, si.dwPageSize, MEM_DECOMMIT );
VirtualFree( allocated, 0, MEM_RELEASE );
end;
end.
|
unit Model.PlanilhaRespostaCTNC;
interface
uses Generics.Collections;
type
TPlanilhaRespostaCTNC = class
private
FPrevisao: String;
FCodigoEmbarcador: String;
FSequencia: String;
FNN: String;
FFlag: String;
FPedido: String;
FLeitura: String;
FEntregador: String;
FNomeEmbarcador: String;
FConsumidor: String;
FResposta: String;
FUsuario: String;
FCidade: String;
FAtribuicao: String;
FTelefone: String;
FData: String;
public
property Flag: String read FFlag write FFlag;
property Data: String read FData write FData;
property NN: String read FNN write FNN;
property Resposta: String read FResposta write FResposta;
property CodigoEmbarcador: String read FCodigoEmbarcador write FCodigoEmbarcador;
property NomeEmbarcador: String read FNomeEmbarcador write FNomeEmbarcador;
property Pedido: String read FPedido write FPedido;
property Consumidor: String read FConsumidor write FConsumidor;
property Telefone: String read FTelefone write FTelefone;
property Atribuicao: String read FAtribuicao write FAtribuicao;
property Entregador: String read FEntregador write FEntregador;
property Previsao: String read FPrevisao write FPrevisao;
property Leitura: String read FLeitura write FLeitura;
property Usuario: String read FUsuario write FUsuario;
property Sequencia: String read FSequencia write FSequencia;
property Cidade: String read FCidade write FCidade;
function GetPlanilha(sFile: String): TObjectList<TPlanilhaRespostaCTNC>;
end;
implementation
{ TPlanilhaRespostaCTNC }
uses DAO.PlanilhaRespostaCTNC;
function TPlanilhaRespostaCTNC.GetPlanilha(sFile: String): TObjectList<TPlanilhaRespostaCTNC>;
var
planilha : TPlanilhaRespostaCTNCDAO;
begin
try
planilha := TPlanilhaRespostaCTNCDAO.Create;
Result := planilha.GetPlanilha(sFile);
finally
planilha.Free;
end;end;
end.
|
{small demo for TLMDFormDisplay.
demonstrates:
- creating forms at runtime and assigning them to the TLMDFormdisplay control.
- Hiding Forms (play with SaveResources and check the difference! )
- Focus-Handling
- handling modal forms shown from page forms
Note:
If property SaveRessources is enabled, please set
BorderStyle: bsNone
BorderIcons: []
for all forms which should be displayed in a TLMDFormDisplay-component}
unit lmdfd1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
lmdcont,
LMDFormTabControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDFormDisplay, LMDControl, LMDBaseControl, LMDBaseGraphicControl,
LMDBaseLabel, LMDCustomSimpleLabel, LMDSimpleLabel, StdCtrls, ComCtrls;
type
Tfdisplay0 = class(TForm)
Button1: TButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
fd: TLMDFormDisplay;
LMDSimpleLabel1: TLMDSimpleLabel;
ComboBox1: TComboBox;
ComboBox2: TComboBox;
LMDSimpleLabel2: TLMDSimpleLabel;
LMDSimpleLabel3: TLMDSimpleLabel;
lmdtab: TLMDFormTabControl;
LMDSimpleLabel4: TLMDSimpleLabel;
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure halloClick(Sender: TObject);
procedure LMDButton1Click(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
fdisplay0: Tfdisplay0;
implementation
uses lmdfd2, lmdfd3, lmdfd4;
{$R *.DFM}
procedure Tfdisplay0.Button2Click(Sender: TObject);
begin
Close
end;
procedure Tfdisplay0.FormCreate(Sender: TObject);
begin
{add the forms to TLMDFormDisplay}
fd.AddFormClass(Tt1, true);
fd.AddFormClass(Tt2, false);
fd.AddFormClass(Tt3, false);
ComboBox1.ItemIndex:=0;
ComboBox2.ItemIndex:=4;
{ad the forms to TLMDFormDisplay}
lmdtab.AddFormClass(Tt1, true);
lmdtab.AddFormClass(Tt2, false);
lmdtab.AddFormClass(Tt3, false);
end;
procedure Tfdisplay0.ComboBox1Change(Sender: TObject);
begin
fd.ActiveFormIndex:=combobox1.ItemIndex;
end;
procedure Tfdisplay0.ComboBox2Change(Sender: TObject);
begin
fd.Position:=TLMDFormDisplayPosition(combobox2.ItemIndex);
end;
procedure Tfdisplay0.halloClick(Sender: TObject);
begin
fd.ActiveFormIndex:=-1;
end;
procedure Tfdisplay0.LMDButton1Click(Sender: TObject);
begin
fd.MoveForm(fd.Forms[0], 2);
end;
end.
|
unit AutolinkerTask_Const;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "EVD"
// Модуль: "w:/common/components/rtl/Garant/EVD/AutolinkerTask_Const.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<Tag::Class>> Shared Delphi Low Level::EVD::Standard::evdTasks::AutolinkerTask
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Константы для значений тега AutolinkerTask .
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\EVD\evdDefine.inc}
interface
uses
k2Base {a},
evdTasks_Schema
;
function k2_attrClearLinksBeforeRun: Integer;
function k2_typAutolinkerTask: AutolinkerTaskTag;
implementation
uses
k2Facade {a},
k2Attributes {a}
;
var
g_AutolinkerTask : AutolinkerTaskTag = nil;
// start class AutolinkerTaskTag
function k2_typAutolinkerTask: AutolinkerTaskTag;
begin
if (g_AutolinkerTask = nil) then
begin
Assert(Tk2TypeTable.GetInstance Is TevdTasksSchema);
g_AutolinkerTask := TevdTasksSchema(Tk2TypeTable.GetInstance).t_AutolinkerTask;
end;//g_AutolinkerTask = nil
Result := g_AutolinkerTask;
end;
var
g_k2_attrClearLinksBeforeRun: Integer = -1;
function k2_attrClearLinksBeforeRun: Integer;
begin
if (g_k2_attrClearLinksBeforeRun = -1) then
g_k2_attrClearLinksBeforeRun := Tk2Attributes.Instance.CheckIDByName('ClearLinksBeforeRun');
Result := g_k2_attrClearLinksBeforeRun;
end;
end. |
unit SeleWin;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs
,StdCtrls,ExtCtrls;
type
TSeleWin = class(TPanel)
private
{ Private declarations }
dragX,dragY:integer;
_Items:TStrings;
_OkOnClick:TNotifyEvent;
_CloseOnClick:TNotifyEvent;
procedure wOkOnClick(value:TNotifyEvent);
procedure wCloseOnClick(value:TNotifyEvent);
protected
{ Protected declarations }
procedure HMouseDown(Sender:TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure HMouseUp(Sender:TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure HMouseMove(Sender:TObject; Shift: TShiftState; X,
Y: Integer);
public
{ Public declarations }
headP:TPanel;
seleP:TPanel;
seleLst:TListBox;
okB:TButton;
closeB:TButton;
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
published
{ Published declarations }
property OkOnClick:TNotifyEvent
read _OkOnClick write wOkOnClick;
property CloseOnClick:TNotifyEvent
read _CloseOnClick write wCloseOnClick;
property Items:TStrings read _Items write _Items;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TSeleWin]);
end;
procedure TSeleWin.HMouseDown;
begin
dragX:=X;dragY:=Y;
inherited MouseDown (Button,Shift,X,Y);
end;
procedure TSeleWin.HMouseUp;
var pas:integer;
begin
dragX:=-1;dragY:=-1;pas:=20;
if Top<0 then Top:=0;
if Left<0 then Left:=0;
if Left+pas>Parent.ClientWidth then Left:=Parent.ClientWidth-pas;
if Top+pas>Parent.ClientHeight then Top:=Parent.ClientHeight-pas;
inherited MouseUp(Button,Shift,X,Y);
end;
procedure TSeleWin.HMouseMove;
begin
if (dragX<0)or(dragY<0)then exit;
Left:=Left+(X-dragX);Top:=Top+(Y-dragY);refresh;
inherited MouseMove(Shift,X,Y);
end;
constructor TSeleWin.Create;
begin
inherited Create(AOwner);
BorderWidth:=1;
dragX:=-1;dragY:=-1;
headP:=TPanel.Create(Self);
headP.Parent:=Self;
with headP do begin
Align:=alTop;
BevelInner:=bvNone;
BevelOuter:=bvLowered;
Color:=clHighlight;
Height:=20;
OnMouseDown:=HMouseDown;
OnMouseUp:=HMouseUp;
OnMouseMove:=HMouseMove;
end;
seleP:=TPanel.Create(Self);
seleP.Parent:=Self;
with seleP do begin
Align:=alClient;
BorderWidth:=5;
BevelInner:=bvNone;
BevelOuter:=bvNone;
end;
seleLst:=TListBox.Create(Self);
seleLst.Parent:=seleP;
Items:=seleLst.Items;
with seleLst do begin
Align:=alClient;
end;
okB:=TButton.Create(headP);
okB.Parent:=headP;
with okB do begin
Caption:='OK';
Height:=15;
Width:=45;
Top:=3;
Left:=5;
end;
closeB:=TButton.Create(headP);
closeB.Parent:=headP;
with closeB do begin
Caption:='Inchide';
Height:=okB.Height;;
Width:=okB.Width;
Top:=okB.Top;
Left:=okB.Left+okB.Width+10;
end;
end;
destructor TSeleWin.Destroy;
begin
okB.Destroy;
closeB.Destroy;
headP.Destroy;
seleLst.Destroy;
seleP.Destroy;
inherited Destroy;
end;
procedure TSeleWin.wOkOnClick;
begin
_OkOnClick:=value;OkB.OnClick:=value;
end;
procedure TSeleWin.wCloseOnClick;
begin
_CloseOnClick:=value;CloseB.OnClick:=value;
end;
end.
|
unit ComSec;
interface
uses
Windows, ActiveX, ComObj, Registry, SysUtils;
const
RPC_C_AUTHN_NONE = 0;
RPC_C_AUTHN_DCE_PRIVATE = 1;
RPC_C_AUTHN_DCE_PUBLIC = 2;
RPC_C_AUTHN_DEC_PUBLIC = 4;
RPC_C_AUTHN_GSS_NEGOTIATE = 9;
RPC_C_AUTHN_WINNT = 10;
RPC_C_AUTHN_GSS_KERBEROS = 16;
RPC_C_AUTHN_MSN = 17;
RPC_C_AUTHN_DPA = 18;
RPC_C_AUTHN_MQ = 100;
RPC_C_AUTHN_DEFAULT = $FFFFFFFF;
const
// Legacy Authentication Level
RPC_C_AUTHN_LEVEL_DEFAULT = 0;
RPC_C_AUTHN_LEVEL_NONE = 1;
RPC_C_AUTHN_LEVEL_CONNECT = 2;
RPC_C_AUTHN_LEVEL_CALL = 3;
RPC_C_AUTHN_LEVEL_PKT = 4;
RPC_C_AUTHN_LEVEL_PKT_INTEGRITY = 5;
RPC_C_AUTHN_LEVEL_PKT_PRIVACY = 6;
const
RPC_C_AUTHZ_NONE = 0;
RPC_C_AUTHZ_NAME = 1;
RPC_C_AUTHZ_DCE = 2;
RPC_C_AUTHZ_DEFAULT = $ffffffff;
const
// Legacy Impersonation Level
RPC_C_IMP_LEVEL_DEFAULT = 0;
RPC_C_IMP_LEVEL_ANONYMOUS = 1;
RPC_C_IMP_LEVEL_IDENTIFY = 2;
RPC_C_IMP_LEVEL_IMPERSONATE = 3;
RPC_C_IMP_LEVEL_DELEGATE = 4;
const
EOAC_NONE = $0;
EOAC_DEFAULT = $800;
EOAC_MUTUAL_AUTH = $1;
EOAC_STATIC_CLOAKING = $20;
EOAC_DYNAMIC_CLOAKING = $40;
// These are only valid for CoInitializeSecurity
EOAC_SECURE_REFS = $2;
EOAC_ACCESS_CONTROL = $4;
EOAC_APPID = $8;
EOAC_NO_CUSTOM_MARSHAL = $2000;
EOAC_DISABLE_AAA = $1000;
procedure InitializeSecurity;
implementation
type
{ TCoInitializeSecurity }
TCoInitializeSecurityProc = function (pSecDesc: PSecurityDescriptor;
cAuthSvc: Longint;
asAuthSvc: PSOleAuthenticationService;
pReserved1: Pointer;
dwAuthnLevel, dImpLevel: Longint;
pReserved2: Pointer;
dwCapabilities: Longint;
pReserved3: Pointer): HResult; stdcall;
var
CoInitializeSecurity: TCoInitializeSecurityProc = nil;
procedure InitializeSecurity;
begin
if Assigned(CoInitializeSecurity) then
begin
OleCheck(CoInitializeSecurity(
nil, //Points to security descriptor
-1, //Count of entries in asAuthSvc
nil, //Array of names to register
nil, //Reserved for future use
RPC_C_AUTHN_LEVEL_NONE, //Default authentication level
// for proxies
RPC_C_IMP_LEVEL_IMPERSONATE, //Default impersonation level
// for proxies
nil, //Reserved; must be set to NULL
EOAC_NONE, //Additional client or
// server-side capabilities
nil)); //Reserved for future use
end;
end;
procedure LoadComExProcs;
var
Ole32: HModule;
begin
Ole32 := GetModuleHandle('ole32.dll');
if Ole32 <> 0 then
begin
@CoInitializeSecurity := GetProcAddress(Ole32, 'CoInitializeSecurity');
end;
end;
initialization
LoadComExProcs;
end.
|
unit dcPassEdit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, DataController, dbctrls, db, ffsException;
type
TdcPassEdit = class(TEdit)
private
{ Private declarations }
fdcLink : TdcLink;
fTranData : String;
frequired : boolean;
OldReadonly : boolean;
OriginalData : string;
function GetDataBufIndex: integer;
procedure SetDataBufIndex(const Value: integer);
protected
{ Protected declarations }
// std data awareness
function GetDataField:string;
procedure SetDataField(value:string);
// data controller
function GetDataController:TDataController;
procedure SetDataController(value:TDataController);
function GetDataSource:TDataSource;
procedure SetDataSource(value:TDataSource);
procedure ReadData(sender:TObject);
procedure WriteData(sender:TObject);
procedure ClearData(sender:TObject);
procedure Change;override;
procedure DoEnter;override;
procedure DoExit;override;
public
{ Public declarations }
constructor Create(AOwner:Tcomponent);override;
destructor Destroy;override;
property TranData : String read fTranData;
published
{ Published declarations }
property DataController : TDataController read GetDataController write setDataController;
property DataField : String read GetDataField write SetDataField;
property Required : boolean read fRequired write fRequired;
property DataSource : TDataSource read getDataSource write SetDataSource;
property DataBufIndex:integer read GetDataBufIndex write SetDataBufIndex;
end;
procedure Register;
implementation
constructor TdcPassEdit.Create(AOwner:Tcomponent);
begin
inherited;
fdclink := tdclink.create(self);
with fdcLink do
begin
OnReadData := ReadData;
OnWriteData := WriteData;
OnClearData := ClearData;
end;
end;
destructor TdcPassEdit.Destroy;
begin
fdclink.Free;
inherited;
end;
function TdcPassEdit.getdatasource;
begin
result := fdclink.DataSource;
end;
procedure TdcPassEdit.SetDatasource(value:TDataSource);
begin
end;
procedure TdcPassEdit.SetDataController(value:TDataController);
begin
fdcLink.datacontroller := value;
end;
function TdcPassEdit.GetDataController:TDataController;
begin
result := fdcLink.DataController;
end;
function TdcPassEdit.GetDataField:string;
begin
result := fdcLink.FieldName;
end;
procedure TdcPassEdit.SetDataField(value:string);
begin
fdcLink.FieldName := value;
end;
procedure TdcPassEdit.ReadData;
begin
if fdclink.DataController <> nil then
begin
OriginalData := '';
if assigned(fdclink.datacontroller.databuf) then OriginalData := fdclink.datacontroller.databuf.AsString[DataBufIndex];
text := OriginalData;
end;
end;
procedure TdcPassEdit.ClearData;
begin
if assigned(fdclink.Field) then
begin
maxlength := fdclink.Field.Size;
text := trim(fdclink.Field.DefaultExpression);
end;
end;
procedure TdcPassEdit.WriteData;
var olddata : string;
begin
if ReadOnly then exit;
if assigned(fdclink.DataController) then
begin
if assigned(fdclink.field) then
begin
olddata := fdclink.Field.AsString;
if trim(text) <> trim(olddata) then
begin
if trim(text) = '' then fTranData := '~' else fTranData := trim(text);
end;
end;
if assigned(fdclink.datacontroller.databuf) then fdclink.datacontroller.databuf.asString[DataBufIndex] := text;
end;
end;
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TdcPassEdit]);
end;
procedure TdcPassEdit.DoEnter;
begin
OldReadOnly := ReadOnly;
if DataController <> nil then
begin
if DataController.ReadOnly then ReadOnly := true;
end;
inherited;
end;
procedure TdcPassEdit.DoExit;
begin
ReadOnly := OldReadOnly;
inherited;
end;
procedure TdcPassEdit.Change;
begin
fdclink.BeginEdit;
inherited;
end;
function TdcPassEdit.GetDataBufIndex: integer;
begin
result := 0;
if assigned(fdclink.Datacontroller) then
if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName);
end;
procedure TdcPassEdit.SetDataBufIndex(const Value: integer);
begin
end;
end.
|
unit ConnectionStubUnit;
interface
uses
REST.Types, System.JSON, Classes, ConnectionUnit;
type
TConnectionStub = class(TConnection)
private
const ApiKey = '11111111111111111111111111111111';
var
FUrl: String;
FMethod: TRESTRequestMethod;
FRequestBody: String;
FContentType: TRESTContentType;
FStream: TStream;
protected
function RunRequest(URL: String; Method: TRESTRequestMethod;
RequestBody: String; ContentType: TRESTContentType;
out ErrorString: String; out ResponseAsString: String): TJsonValue; override;
function RunRequest(URL: String; Stream: TStream; out ErrorString: String;
out ResponseAsString: String): TJsonValue; overload; virtual;
public
constructor Create(); reintroduce;
property Url: String read FUrl;
property Method: TRESTRequestMethod read FMethod;
property RequestBody: String read FRequestBody;
property ContentType: TRESTContentType read FContentType;
property Stream: TStream read FStream;
end;
implementation
{ TConnectionStub }
constructor TConnectionStub.Create;
begin
Inherited Create(ApiKey);
FStream := nil;
end;
function TConnectionStub.RunRequest(URL: String;
Method: TRESTRequestMethod; RequestBody: String; ContentType: TRESTContentType;
out ErrorString: String; out ResponseAsString: String{; out NeedFreeResult: boolean}): TJsonValue;
begin
FUrl := URL;
FMethod := Method;
FRequestBody := RequestBody;
FContentType := ContentType;
FStream := nil;
Result := nil;
end;
function TConnectionStub.RunRequest(URL: String; Stream: TStream;
out ErrorString, ResponseAsString: String): TJsonValue;
begin
FUrl := URL;
FMethod := rmPOST;
FRequestBody := '';
FContentType := TRESTContentType.ctMULTIPART_FORM_DATA;
FStream := Stream;
Result := nil;
end;
end.
|
unit uSpace;
{$mode delphi}
interface
uses
glr_render, glr_render2d, glr_math, glr_scene;
const
STARS_PER_LAYER = 100;
type
TSpacePatch = record
Position: TglrVec2f;
Stars: array of TglrSprite;
Initials: array of TglrVec2f;
end;
{ TSpace }
TSpace = class
protected
fCount: Integer;
fBatch: TglrSpriteBatch;
fMaterial: TglrMaterial;
fPatch: TSpacePatch;
public
Camera: TglrCamera;
constructor Create(aPatchStart, aPatchSize: TglrVec2f; StarTR: PglrTextureRegion;
aMaterial: TglrMaterial; aParallaxLevels: Integer = 3); virtual;
destructor Destroy(); override;
procedure RenderSelf();
end;
implementation
const
colorWhite: TglrVec4f = (x: 1.0; y: 1.0; z: 1.0; w: 1.0);
colorBlue: TglrVec4f = (x: 74/255; y: 151/255; z: 215/255; w: 1.0);
colorRed: TglrVec4f = (x: 215/255; y: 109/255; z: 74/255; w: 1.0);
constructor TSpace.Create(aPatchStart, aPatchSize: TglrVec2f; StarTR: PglrTextureRegion;
aMaterial: TglrMaterial; aParallaxLevels: Integer);
var
i: Integer;
z: Single;
pos: TglrVec3f;
col: TglrVec4f;
begin
inherited Create();
fBatch := TglrSpriteBatch.Create();
fMaterial := aMaterial;
fPatch.Position := Vec2f(0, 0);
fCount := STARS_PER_LAYER * aParallaxLevels;
SetLength(fPatch.Stars, fCount);
SetLength(fPatch.Initials, fCount);
Randomize();
for i := 0 to fCount - 1 do
begin
z := - (i div STARS_PER_LAYER) / aParallaxLevels;
pos := Vec3f(aPatchStart.x + Random(Round(aPatchSize.x)),
aPatchStart.y + Random(Round(aPatchSize.y)), z);
fPatch.Initials[i] := Vec2f(pos);
z := Random();
if z < 0.3 then
col := colorBlue
else if z < 0.6 then
col := colorRed
else
col := colorWhite;
col.w := pos.z + 0.8;
fPatch.Stars[i] := TglrSprite.Create();
with fPatch.Stars[i] do
begin
Position := pos;
SetTextureRegion(StarTR);
SetSize(6 * (1 + pos.z), 6 * (1 + pos.z));
SetVerticesColor(col);
end;
//fBatch.Childs.Add(fPatch.Stars[i]);
end;
end;
destructor TSpace.Destroy;
var
i: Integer;
begin
fBatch.Free();
for i := 0 to fCount - 1 do
fPatch.Stars[i].Free();
inherited Destroy;
end;
procedure TSpace.RenderSelf;
var
i: Integer;
begin
fMaterial.Bind();
fBatch.Start();
for i := 0 to fCount - 1 do
with fPatch.Stars[i] do
begin
Position := Vec3f(fPatch.Initials[i] - Position.z * Vec2f(Camera.Position), Position.z);
fBatch.Draw(fPatch.Stars[i]);
end;
fBatch.Finish();
end;
end.
|
unit uModuloVO;
interface
uses System.SysUtils, uKeyField, uTableName;
type
[TableName('Modulo')]
TModuloVO = class
private
FId: Integer;
FCodigo: Integer;
FNome: string;
FAtivo: Boolean;
FIdStr: string;
public
[KeyField('Mod_Id')]
property Id: Integer read FId write FId;
[FieldName('Mod_Codigo')]
property Codigo: Integer read FCodigo write FCodigo;
[FieldName('Mod_Nome')]
property Nome: string read FNome write FNome;
[FieldName('Mod_Ativo')]
property Ativo: Boolean read FAtivo write FAtivo;
property IdStr: string read FIdStr write FIdStr;
end;
implementation
end.
|
unit PT4WordBase;
{
База слов и выражений
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
const
RuNumWords = 4;
EnNumWords = 4;
RuNumSent = 4;
EnNumSent = 4;
RuNumText = 1;
EnNumText = 1;
function RuGetWord(N : integer) : string;
function RuGetSentence(N : integer) : string;
function RuGetText(N : integer) : string;
function EnGetWord(N : integer) : string;
function EnGetSentence(N : integer) : string;
function EnGetText(N : integer) : string;
implementation
const
RuWords : array [1..RuNumWords] of string =
('Слово', 'каракатица', 'Усть-Мусохранск', 'Синхрофазотрон');
RuSents : array [1..RuNumSent] of string =
('От топота копыт', 'Мал еж, да колюч', 'Крокодилы не летают', 'Пушки не игрушки');
RuTexts : array [1..RuNumText] of string =
('Это текст. Он прост. Запятых здесь нет, как и дефисов - все просто.');
EnWords : array [1..EnNumWords] of string =
('Help', 'Duck', 'Gentoo', 'capital');
EnSents : array [1..EnNumSent] of string =
('A quick brown fox.', 'Duck duck go!', 'Kill it with fire!', 'Nobody cares.');
EnTexts : array [1..EnNumText] of string =
('London is a capital of Great britain. Yo, dunno now you, brazza?');
function RuGetWord(N : integer) : string;
begin
RuGetWord := UTF8ToAnsi(RuWords[N+1]);
end;
function RuGetSentence(N : integer) : string;
begin
RuGetSentence := UTF8ToAnsi(RuSents[N+1]);
end;
function RuGetText(N : integer) : string;
begin
RuGetText := UTF8ToAnsi(RuTexts[N+1]);
end;
function EnGetWord(N : integer) : string;
begin
EnGetWord := UTF8ToAnsi(EnWords[N+1]);
end;
function EnGetSentence(N : integer) : string;
begin
EnGetSentence := UTF8ToAnsi(EnSents[N+1]);
end;
function EnGetText(N : integer) : string;
begin
EnGetText := UTF8ToAnsi(EnTexts[N+1]);
end;
end.
|
{ basic fs functions }
{$WARN SYMBOL_PLATFORM OFF}
unit fs;
interface
uses
Classes, Windows, SysUtils, Contnrs;
const
faBrowseable = $10000000;
faNonSelectable = $20000000;
faCalculated = $40000000;
dirIndex : integer = -1;
dateTimeFormatMask : string = 'mm/dd/yy hh:mm';
type
EFSException = class(Exception);
EFSChangeRequired = class(EFSException);
TVolumeType = (vtUnknown, vtRemovable, vtFixed, vtRemote, vtArchive);
TFSItemList = TThreadList;
TFSVolumeList = TThreadList;
TPanelList = TList;
TFSItem = class(TObject)
Name : string;
Size : Int64;
Date : TDateTime;
Flags : integer;
ImageIndex : integer;
Selected : boolean;
constructor Create;
function SizeStr:string;
function DateStr:string;
function AttrStr:string;
end;
TFSInfo = class(TObject)
Path : string;
VolumeName : string;
VolumeLabel : string;
FileSystem : string;
SerialNumber : string;
VolumeType : TVolumeType;
VolumeSize : Int64;
FreeSpace : Int64;
TotalFileSizes : Int64;
Items : TFSItemList;
constructor Create;
destructor Destroy;override;
procedure clearSelection;
end;
THandleWhat = (hNA,hFrom,hTo);
THandleStatus = set of THandleWhat;
PFileItem = ^TFileItem;
TFileItem = packed record
Source : string;
Dest : string;
Size : integer;
Next : PFileItem;
end;
TFSHandlerClass = class of TFSHandler;
TFSHandler = class(TObject)
Info : TFSInfo;
constructor Create;
destructor Destroy;override;
procedure OpenFS(const url:string);virtual;
procedure setPath(const url:string);virtual;
procedure setParent;virtual;
procedure CloseFS;virtual;
procedure ContextPopup(item:TFSItem; x,y:integer);virtual;abstract;
function selectCopyDestination(var path:string):boolean;virtual;
function selectMoveDestination(var path:string):boolean;virtual;
procedure Rename(item:TFSItem; const newname:string);virtual;
procedure Delete;virtual;
procedure Copy(const dest:string);virtual;
procedure Move(const dest:string);virtual;
procedure MkDir(const dir:string);virtual;
procedure Execute(item:TFSItem);virtual;
procedure SetAttributes(item:TFSItem; newattr:integer);virtual;
procedure SetDate(item:TFSItem; newdate:TDateTime);virtual;
function SupportedAttributes:integer;virtual;
function canHandleTransfer(afs:TFSHandler):THandleStatus;virtual;
procedure readItemSize(item:TFSItem);virtual;
procedure readVolumeInfo;virtual;
procedure readItems;virtual;
function getStream(item:TFSItem):TStream;virtual;abstract;
procedure Refresh;virtual;
function ContentsChanged : boolean;virtual;
class function canHandle(const url:string):boolean;virtual;
class function getName:string;virtual;
procedure debug(s: string);
procedure addParentDir;
procedure DisposeFiles(root:PFileItem);
end;
TFSVolume = class(TObject)
Path : string;
Name : string;
VolumeType : TVolumeType;
end;
TFSHandlerList = TClassList;
var
VolumeList : TFSVolumeList;
Panels : TPanelList;
globSortColumn:integer;
globSortOrder:boolean;
FSHandlers : TFSHandlerList;
function readableSize(size:Int64):string;
function buildVolumeList(param:Pointer):integer;
function CompareItems(i1,i2:Pointer):integer;
function detectFSType(const url:string):TFSHandlerClass;
implementation
uses
copytofrm, procs, fsnative,
Forms, Controls, Dialogs, Math, DateUtils;
procedure TFSHandler.DisposeFiles;
var
temp:PFileItem;
begin
temp := root;
while temp <> NIL do begin
with temp^ do begin
Source := EmptyStr;
Dest := EmptyStr;
end;
root := temp;
temp := temp.Next;
Dispose(root);
end;
end;
procedure TFSHandler.addParentDir;
var
item:TFSItem;
begin
item := TFSItem.Create;
with item do begin
item.Name := '..';
item.Flags := faDirectory or faBrowseable or faNonSelectable;
end;
Info.Items.Add(item);
end;
class function TFSHandler.canHandle;
begin
Result := true;
end;
class function TFSHandler.getName;
begin
Result := '(null)';
end;
function detectFSType;
var
n:integer;
T:TFSHandlerClass;
begin
for n:=0 to FSHandlers.Count-1 do begin
TClass(T) := FSHandlers[n];
if T.canHandle(url) then begin
Result := T;
exit;
end;
end;
Result := NIL;
end;
function readableSize;
const
kb = 1024;
mb = kb*1024;
gb = mb*1024;
tb = gb*1024.0;
begin
if size = 0 then Result := '' else
if size < kb then Result := IntToStr(size) else
if size < mb then Result := FloatToStrF(size/kb,ffFixed,3,1)+'k' else
if size < gb then Result := FloatToStrF(size/mb,ffFixed,3,1)+'mb' else
if size < tb then Result := FloatToStrF(size/gb,ffFixed,3,1)+'gb'
else Result := FloatToStrF(size/tb,ffFixed,3,1)+'tb';
end;
function buildVolumeList;
begin
try
status('Reading volume information');
VolumeList.Clear;
TNativeFSHandler.fillVolumes(VolumeList.LockList);
VolumeList.UnlockList;
Result := 0;
status('');
except
Result := -1;
end;
end;
function CompareItems(i1,i2:Pointer):integer;
var
it1,it2:TFSItem;
begin
it1 := TFSItem(i1);
it2 := TFSItem(i2);
Result := CompareValue(it2.Flags and faDirectory,it1.Flags and faDirectory);
if Result = 0 then begin
if it1.Flags and faDirectory <> 0 then begin
if it1.Name = '..' then begin
if it2.Name = '..' then Result := 0 else Result := -1;
end else if it2.Name = '..' then Result := 1;
end;
if Result = 0 then begin
case globSortColumn of
0 : Result := CompareText(it1.Name,it2.Name);
else begin
case globSortColumn of
1 : begin
if it1.Size < it2.Size then Result := -1 else
if it1.Size = it2.Size then Result := 0 else Result := 1;
end;
2 : Result := CompareDateTime(it1.Date,it2.Date);
else Result := 0;
end;
if Result = 0 then Result := CompareText(it1.Name,it2.Name);
end;
end; {case}
if globSortOrder then Result := -Result;
end;
end;
end;
function TFSItem.DateStr;
begin
if date <> 0 then Result := FormatDateTime(dateTimeFormatMask, Date) else Result := '';
end;
function TFSItem.SizeStr;
begin
if (Size = 0) and (Flags and faDirectory > 0) then Result := '' else Result := FormatFloat('0,',size);
end;
function TFSItem.AttrStr;
function g(c:char; attr:integer):char;
begin
if Flags and attr <> 0 then Result := c else Result := ' ';
end;
begin
Result := g('h',faHidden)+g('s',faSysFile)+g('r',faReadOnly)+g('a',faArchive);
end;
{ TFSInfo }
procedure TFSInfo.clearSelection;
var
n:integer;
l:TList;
begin
with Items do begin
l := LockList;
for n:=0 to l.Count-1 do TFSItem(l[n]).Selected := false;
UnlockList;
end;
end;
constructor TFSInfo.Create;
begin
inherited;
Items := TFSItemList.Create;
end;
destructor TFSInfo.Destroy;
begin
Items.Free;
inherited;
end;
{ TFSHandler }
constructor TFSHandler.Create;
begin
inherited;
Info := TFSInfo.Create;
end;
destructor TFSHandler.Destroy;
begin
if Info <> NIL then Info.Free;
inherited;
end;
procedure TFSHandler.debug(s: string);
begin
// TODO:
end;
procedure TFSHandler.setPath(const url: string);
begin
Info.Path := url;
end;
procedure TFSHandler.Refresh;
begin
readVolumeInfo;
readItems;
with Info.Items do begin
LockList.Sort(CompareItems);
UnlockList;
end;
end;
procedure TFSHandler.CloseFS;
begin
end;
procedure TFSHandler.OpenFS(const url: string);
begin
end;
procedure TFSHandler.readItems;
begin
end;
procedure TFSHandler.readVolumeInfo;
begin
end;
procedure TFSHandler.setParent;
begin
end;
procedure TFSHandler.Rename(item: TFSItem; const newname: string);
begin
end;
procedure TFSHandler.Delete;
begin
end;
function TFSHandler.selectCopyDestination(var path: string): boolean;
var
f:TfCopyTo;
begin
Application.CreateForm(TfCopyTo,f);
if f.ShowModal = mrOk then begin
path := f.cbPath.Text;
Result := true;
end else Result := false;
f.Free;
end;
function TFSHandler.selectMoveDestination(var path: string): boolean;
var
f:TfCopyTo;
begin
Application.CreateForm(TfCopyTo,f);
f.Caption := 'Move to';
if f.ShowModal = mrOk then begin
path := f.cbPath.Text;
Result := true;
end else Result := false;
f.Free;
end;
procedure TFSHandler.Copy(const dest: string);
begin
end;
procedure TFSHandler.readItemSize(item: TFSItem);
begin
end;
procedure TFSHandler.Move(const dest: string);
begin
end;
procedure TFSHandler.MkDir(const dir: string);
begin
end;
procedure TFSHandler.Execute;
begin
end;
function TFSHandler.canHandleTransfer;
begin
if Self = afs then
Result := [hFrom,hTo]
else
Result := [];
end;
function TFSHandler.ContentsChanged: boolean;
begin
Result := false;
end;
constructor TFSItem.Create;
begin
inherited;
ImageIndex := -1;
end;
procedure TFSHandler.SetDate;
begin
end;
procedure TFSHandler.SetAttributes(item: TFSItem; newattr: integer);
begin
end;
function TFSHandler.SupportedAttributes: integer;
begin
Result := 0;
end;
begin
VolumeList := TFSVolumeList.Create;
Panels := TPanelList.Create;
FSHandlers := TFSHandlerList.Create;
end.
|
unit TpylabelUnit;
{$mode delphi}
interface
uses
Classes, SysUtils, Controls, PyAPI, objectlistunit, pyutil, StdCtrls,
callbacunit, Forms;
type
Tpylabel = class(TButton)
constructor Create(obj: Tlaz4py);
procedure reg(var k: integer; var Methods: array of PyMethodDef);
end;
implementation
function setShowAccelChar(Self: PyObject; Args: PyObject): PyObject; cdecl;
var
control: TLabel;
para: integer;
control_hash: integer;
begin
PyArg_ParseTuple(Args, 'ii', @control_hash, @para);
control := TLabel(control_hash);
control.ShowAccelChar := inttobool(para);
Result := PyInt_FromLong(0);
end;
function getShowAccelChar(Self: PyObject; Args: PyObject): PyObject; cdecl;
var
control: TLabel;
para: integer;
control_hash: integer;
begin
PyArg_ParseTuple(Args, 'ii', @control_hash, @para);
control := TLabel(control_hash);
Result := PyInt_FromLong(booltoint(control.ShowAccelChar));
end;
function setTransparent(Self: PyObject; Args: PyObject): PyObject; cdecl;
var
control: TLabel;
para: integer;
control_hash: integer;
begin
PyArg_ParseTuple(Args, 'ii', @control_hash, @para);
control := TLabel(control_hash);
control.Transparent := inttobool(para);
Result := PyInt_FromLong(0);
end;
function getTransparent(Self: PyObject; Args: PyObject): PyObject; cdecl;
var
control: TLabel;
para: integer;
control_hash: integer;
begin
PyArg_ParseTuple(Args, 'ii', @control_hash, @para);
control := TLabel(control_hash);
Result := PyInt_FromLong(booltoint(control.Transparent));
end;
function setWordWrap(Self: PyObject; Args: PyObject): PyObject; cdecl;
var
control: TLabel;
para: integer;
control_hash: integer;
begin
PyArg_ParseTuple(Args, 'ii', @control_hash, @para);
control := TLabel(control_hash);
control.WordWrap := inttobool(para);
Result := PyInt_FromLong(0);
end;
function getWordWrap(Self: PyObject; Args: PyObject): PyObject; cdecl;
var
control: TLabel;
para: integer;
control_hash: integer;
begin
PyArg_ParseTuple(Args, 'ii', @control_hash, @para);
control := TLabel(control_hash);
Result := PyInt_FromLong(booltoint(control.WordWrap));
end;
function setOptimalFill(Self: PyObject; Args: PyObject): PyObject; cdecl;
var
control: TLabel;
para: integer;
control_hash: integer;
begin
PyArg_ParseTuple(Args, 'ii', @control_hash, @para);
control := TLabel(control_hash);
control.OptimalFill := inttobool(para);
Result := PyInt_FromLong(0);
end;
function getOptimalFill(Self: PyObject; Args: PyObject): PyObject; cdecl;
var
control: TLabel;
para: integer;
control_hash: integer;
begin
PyArg_ParseTuple(Args, 'ii', @control_hash, @para);
control := TLabel(control_hash);
Result := PyInt_FromLong(booltoint(control.OptimalFill));
end;
constructor Tpylabel.Create(obj: Tlaz4py);
begin
end;
procedure Tpylabel.reg(var k: integer; var Methods: packed array of PyMethodDef);
begin
Inc(k);
Methods[k].Name := 'setShowAccelChar';
Methods[k].meth := @setShowAccelChar;
Methods[k].flags := METH_VARARGS;
Methods[k].doc := 'set ShowAccelChar';
Inc(k);
Methods[k].Name := 'getShowAccelChar';
Methods[k].meth := @getShowAccelChar;
Methods[k].flags := METH_VARARGS;
Methods[k].doc := 'set ShowAccelChar';
Inc(k);
Methods[k].Name := 'setTransparent';
Methods[k].meth := @setTransparent;
Methods[k].flags := METH_VARARGS;
Methods[k].doc := 'set Transparent';
Inc(k);
Methods[k].Name := 'getTransparent';
Methods[k].meth := @getTransparent;
Methods[k].flags := METH_VARARGS;
Methods[k].doc := 'set Transparent';
Inc(k);
Methods[k].Name := 'setWordWrap';
Methods[k].meth := @setWordWrap;
Methods[k].flags := METH_VARARGS;
Methods[k].doc := 'set WordWrap';
Inc(k);
Methods[k].Name := 'getWordWrap';
Methods[k].meth := @getWordWrap;
Methods[k].flags := METH_VARARGS;
Methods[k].doc := 'set WordWrap';
Inc(k);
Methods[k].Name := 'setOptimalFill';
Methods[k].meth := @setOptimalFill;
Methods[k].flags := METH_VARARGS;
Methods[k].doc := 'set OptimalFill';
Inc(k);
Methods[k].Name := 'getOptimalFill';
Methods[k].meth := @getOptimalFill;
Methods[k].flags := METH_VARARGS;
Methods[k].doc := 'set OptimalFill';
end;
end.
|
unit uilist;
interface
uses ui, uimpl, uihandle, uicomp, datastorage;
type
TWinList=class(TWinComp)
private
wItems:TStringListEx;
wTopItem:integer;
wSelected:integer; // TODO multi
wOnSelected:TWinHandleEvent;
protected
procedure SetSelected(AValue:integer);
public
constructor Create(Owner:TWinHandle);override;
procedure CustomPaint;override;
procedure CreatePerform;override;
procedure MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer);override;
procedure MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);override;
property Items:TStringListEx read wItems;
property Selected:integer read wSelected write SetSelected;
property TopItem:integer read wTopItem write wTopItem;
property OnSelected:TWinHandleEvent read wOnSelected write wOnSelected;
end;
implementation
uses math;
constructor TWinList.Create(Owner:TWinHandle);
begin
inherited;
wItems:=TStringListEx.Create; //TODO destroy
wTopItem:=0;
wSelected:=-1;
end;
procedure TWinList.CreatePerform;
begin
inherited;
end;
procedure TWinList.CustomPaint;
var
r, rtxt : trect;
i:integer;
begin
r:=GetClientRect;
BeginPaint;
rtxt:=r;
rtxt.Left:=rtxt.Left+3;
rtxt.Right:=rtxt.Right-1;
rtxt.Top:=rtxt.Top+1;
rtxt.Bottom:=rtxt.Top+18;
i:=wTopItem;
while(rtxt.Top<r.Bottom) do begin
if i<Items.count
then begin
if i=Selected
then begin
Polygon(clFaceBook1, clFaceBook1, rtxt.Left-2, rtxt.Top, rtxt.Right-1, rtxt.Bottom-1);
DrawText(rtxt, Items[i], font, clWhite, clFaceBook1, OPAQUE, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
end
else begin
Polygon(bkcolor, bkcolor, rtxt.Left-2, rtxt.Top, rtxt.Right-1, rtxt.Bottom-1);
DrawText(rtxt, Items[i], font, color, bkcolor, OPAQUE, DT_SINGLELINE or DT_LEFT or DT_VCENTER);
end;
end;
inc(i);
rtxt.Top:=rtxt.Top+18;
rtxt.Bottom:=rtxt.Bottom+18;
end;
PolyLine(clDkGray, 0, 5, r.Left, r.Top, r.Right-1, r.Bottom-1);
EndPaint;
end;
procedure TWinList.MouseWheelPerform(AButtonControl:cardinal; deltawheel:integer; x, y:integer);
begin
inherited;
wTopItem:=max(wTopItem-deltawheel,0);
RedrawPerform
end;
procedure TWinList.SetSelected(AValue:integer);
begin
if (AValue<Items.count)and(wSelected<>AValue)
then begin
wSelected:=AValue;
RedrawPerform;
if Assigned(wOnSelected)
then wOnSelected(self)
end
end;
procedure TWinList.MouseButtonDownPerform(AButton:TMouseButton; AButtonControl:cardinal; x,y:integer);
begin
inherited;
if AButton=mbLeft
then begin
SetSelected(wTopItem+(y div 18));
end
end;
end.
|
unit TMC.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Tabs, SynEditHighlighter,
SynHighlighterPas, SynEdit, SynMemo, System.Generics.Collections, Vcl.Grids,
TableDraw, Vcl.StdCtrls, Vcl.ExtCtrls, SQLLang, Vcl.Menus;
type
TTMCField = record
private
FFieldName:string;
function GetFieldName:string;
function GetIsOtherUID: Boolean;
public
FieldType:TFieldType;
FieldDataType:string;
UIDName:Boolean;
UID:Boolean;
PrimaryKey:Boolean;
NotNull:Boolean;
Orded:Boolean;
Comments:string;
property IsOtherUID:Boolean read GetIsOtherUID;
property FieldName:string read GetFieldName write FFieldName;
property FieldNameSet:string read FFieldName;
end;
TTMCFields = class(TTableData<TTMCField>)
function ExistsUID:Boolean;
function GetUID:TTMCField;
function GetUIDName:TTMCField;
end;
TTMCRecord = record
TableName:string;
ClassName:string;
HumanName:string;
DBName:string;
UnitName:string;
Fields:TTMCFields;
CreateInsert:Boolean;
CreateUpdate:Boolean;
CreateUpdateField:Boolean;
CreateDelete:Boolean;
CreateGet:Boolean;
CreateGetUID:Boolean;
CreateFillList:Boolean;
CreateFillListField:Boolean;
CreateClear:Boolean;
end;
TTMCData = TTableData<TTMCRecord>;
TFieldEditMode = (femAdd, femEdit);
TFormMain = class(TForm)
MemoData: TSynMemo;
SynPasSyn2: TSynPasSyn;
TabSetTables: TTabSet;
ButtonAddTable: TButton;
Panel2: TPanel;
TableExFields: TTableEx;
Splitter1: TSplitter;
Panel3: TPanel;
CheckBoxCreate: TCheckBox;
CheckBoxCreateInsert: TCheckBox;
CheckBoxCreateUpdate: TCheckBox;
CheckBoxCreateDelete: TCheckBox;
CheckBoxCreateGet: TCheckBox;
CheckBoxCreateFillList: TCheckBox;
CheckBoxCreateFillListField: TCheckBox;
ButtonCreate: TButton;
Panel4: TPanel;
EditFieldName: TEdit;
ComboBoxFieldDataType: TComboBox;
ComboBoxFieldSQLType: TComboBox;
CheckBoxFieldPK: TCheckBox;
CheckBoxFieldNN: TCheckBox;
ButtonAdd_Apply: TButton;
ButtonChange_Cancel: TButton;
ButtonDelete: TButton;
EditTableName: TEdit;
EditClass: TEdit;
EditHumanName: TEdit;
EditUnitName: TEdit;
CheckBoxCreateClear: TCheckBox;
EditDBName: TComboBox;
EditFieldComments: TEdit;
MainMenu: TMainMenu;
MenuItemFile: TMenuItem;
MenuItemQuit: TMenuItem;
MenuItemSave: TMenuItem;
ButtonSave: TButton;
FileSaveDialog: TFileSaveDialog;
FileOpenDialog: TFileOpenDialog;
ButtonOpen: TButton;
CheckBoxFieldOrd: TCheckBox;
CheckBoxFieldUIDN: TCheckBox;
CheckBoxFieldUID: TCheckBox;
CheckBoxCreateGetUID: TCheckBox;
CheckBoxCreateUpdateField: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure TableExFieldsGetData(FCol, FRow: Integer; var Value: string);
procedure ButtonAdd_ApplyClick(Sender: TObject);
procedure ButtonChange_CancelClick(Sender: TObject);
procedure TabSetTablesChange(Sender: TObject; NewTab: Integer;
var AllowChange: Boolean);
procedure ButtonAddTableClick(Sender: TObject);
procedure ButtonDeleteClick(Sender: TObject);
procedure ButtonCreateClick(Sender: TObject);
procedure ButtonSaveClick(Sender: TObject);
procedure ButtonOpenClick(Sender: TObject);
private
FData:TTMCData;
FCurrentData:Integer;
FMode:TFieldEditMode;
FEditRec:Integer;
procedure CancelEdit;
procedure SetMode(const Value: TFieldEditMode);
function SetTable(ID:Integer):Boolean;
public
procedure UpdateTabs;
function Save(ID:Integer; FN:string):Boolean;
function Open(FN:string):Boolean;
function Add(Item:TTMCRecord):Integer;
property Mode:TFieldEditMode read FMode write SetMode;
end;
var
FormMain: TFormMain;
implementation
uses IniFiles;
{$R *.dfm}
function TFormMain.Add(Item:TTMCRecord):Integer;
begin
Result:=FData.Add(Item);
UpdateTabs;
if TabSetTables.Tabs.Count > 0 then TabSetTables.TabIndex:=TabSetTables.Tabs.Count-1;
end;
procedure TFormMain.ButtonOpenClick(Sender: TObject);
begin
if FileOpenDialog.Execute(Handle) then Open(FileOpenDialog.FileName);
end;
procedure TFormMain.ButtonAddTableClick(Sender: TObject);
var RecData:TTMCRecord;
begin
RecData.Fields:=TTMCFields.Create(TableExFields);
RecData.TableName:=EditTableName.Text; EditTableName.Clear;
RecData.ClassName:=EditClass.Text; EditClass.Clear;
RecData.HumanName:=EditHumanName.Text; EditHumanName.Clear;
RecData.DBName:=EditDBName.Text; EditDBName.Text:='';
RecData.UnitName:=EditUnitName.Text; EditUnitName.Clear;
Add(RecData);
end;
procedure TFormMain.ButtonAdd_ApplyClick(Sender: TObject);
var FF:TTMCField;
begin
if not IndexInList(FCurrentData, FData.Count) then Exit;
FF.FieldName:=EditFieldName.Text;
FF.FieldDataType:=ComboBoxFieldDataType.Text;
FF.FieldType:=TFieldType(ComboBoxFieldSQLType.ItemIndex);
FF.PrimaryKey:=CheckBoxFieldPK.Checked;
FF.UIDName:=CheckBoxFieldUIDN.Checked;
FF.UID:=CheckBoxFieldUID.Checked;
FF.NotNull:=CheckBoxFieldNN.Checked;
FF.Orded:=CheckBoxFieldOrd.Checked;
FF.Comments:=EditFieldComments.Text;
case Mode of
femAdd:
begin
TableExFields.ItemIndex:=FData[FCurrentData].Fields.Add(FF);
end;
femEdit:
begin
if IndexInList(FEditRec, FData[FCurrentData].Fields.Count) then
begin
FData[FCurrentData].Fields[FEditRec]:=FF;
FData[FCurrentData].Fields.UpdateTable;
end;
end;
end;
Mode:=femAdd;
end;
procedure TFormMain.ButtonChange_CancelClick(Sender: TObject);
var FF:TTMCField;
begin
if not IndexInList(FCurrentData, FData.Count) then Exit;
case Mode of
femAdd:
begin
Mode:=femEdit;
if not IndexInList(TableExFields.ItemIndex, FData[FCurrentData].Fields.Count) then Exit;
FEditRec:=TableExFields.ItemIndex;
FF:=FData[FCurrentData].Fields[FEditRec];
EditFieldName.Text:=FF.FieldNameSet;
ComboBoxFieldDataType.Text:=FF.FieldDataType;
ComboBoxFieldSQLType.ItemIndex:=Ord(FF.FieldType);
CheckBoxFieldPK.Checked:=FF.PrimaryKey;
CheckBoxFieldNN.Checked:=FF.NotNull;
CheckBoxFieldOrd.Checked:=FF.Orded;
EditFieldComments.Text:=FF.Comments;
EditFieldName.SetFocus;
end;
femEdit:
begin
Mode:=femAdd;
end;
end;
end;
procedure TFormMain.ButtonCreateClick(Sender: TObject);
var Buf:TStringList;
RData:TTMCRecord;
i:Integer;
begin
if not IndexInList(FCurrentData, FData.Count) then Exit;
if FData[FCurrentData].Fields.Count <= 0 then Exit;
RData:=FData[FCurrentData];
RData.CreateInsert:=CheckBoxCreateInsert.Checked;
RData.CreateUpdate:=CheckBoxCreateUpdate.Checked;
RData.CreateUpdateField:=CheckBoxCreateUpdateField.Checked;
RData.CreateGet:=CheckBoxCreateGet.Checked;
RData.CreateGetUID:=CheckBoxCreateGetUID.Checked;
RData.CreateClear:=CheckBoxCreateClear.Checked;
RData.CreateDelete:=CheckBoxCreateDelete.Checked;
RData.CreateFillList:=CheckBoxCreateFillList.Checked;
RData.CreateFillListField:=CheckBoxCreateFillListField.Checked;
Buf:=TStringList.Create;
//Uint
Buf.Add(Format('unit %s;', [RData.UnitName]));
Buf.Add(Format('', []));
//interface
Buf.Add(Format('interface', []));
Buf.Add(Format(' uses', []));
Buf.Add(Format(' Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,', []));
Buf.Add(Format(' Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin, Vcl.Menus, SQLite3, SQLiteTable3,', []));
Buf.Add(Format(' PawnShop.Constants, SQLLang, System.Generics.Collections, PawnShop.Data, PawnShop.Types, TableDraw;', []));
Buf.Add(Format('', []));
//const
Buf.Add(Format(' const', []));
Buf.Add(Format(' /// <summary>', []));
Buf.Add(Format(' /// %s', [RData.HumanName]));
Buf.Add(Format(' /// </summary>', []));
Buf.Add(Format(' tn%s = ''%s'';', [RData.HumanName, RData.TableName]));
for i:= 0 to RData.Fields.Count-1 do
begin
Buf.Add(Format(' /// <summary>', []));
Buf.Add(Format(' /// %s', [RData.Fields[i].Comments]));
Buf.Add(Format(' /// </summary>', []));
Buf.Add(Format(' fn%s = ''%s'';', [RData.Fields[i].FieldNameSet, RData.Fields[i].FieldNameSet]));
end;
Buf.Add(Format('', []));
//type
Buf.Add(Format(' type', []));
Buf.Add(Format(' TData%s = record', [RData.HumanName]));
for i:= 0 to RData.Fields.Count-1 do
begin
Buf.Add(Format(' /// <summary>', []));
Buf.Add(Format(' /// %s', [RData.Fields[i].Comments]));
Buf.Add(Format(' /// </summary>', []));
Buf.Add(Format(' %s:%s;', [RData.Fields[i].FieldNameSet, RData.Fields[i].FieldDataType]));
end;
Buf.Add(Format(' end;', []));
Buf.Add(Format(' T%s = TTableData<TData%s>;', [RData.ClassName, RData.HumanName]));
Buf.Add(Format('', []));
//Class
Buf.Add(Format(' %s = class', [RData.ClassName]));
Buf.Add(Format(' class function CreateTable:TTable; static;', []));
if RData.CreateInsert then
Buf.Add(Format(' class function Insert(DB:TDataBase; Data:TData%s):TUID;', [RData.HumanName]));
if RData.CreateUpdate then
Buf.Add(Format(' class function Update(DB:TDataBase; Data:TData%s):Boolean;', [RData.HumanName]));
if RData.CreateDelete and (RData.Fields.Count > 0) then
Buf.Add(Format(' class function Delete(DB:TDataBase; ID:string):Boolean;', []));
if RData.CreateGet and (RData.Fields.Count > 0) then
Buf.Add(Format(' class function Get(DB:TDataBase; ID:string; var Data:TData%s):Boolean;', [RData.HumanName]));
if RData.CreateGetUID and (RData.Fields.Count > 0) and (RData.Fields.ExistsUID) then
Buf.Add(Format(' class function GetUID(DB:TDataBase; ID:string):TUID;', [RData.HumanName]));
if RData.CreateFillList then
Buf.Add(Format(' class function FillList(DB:TDataBase; var List:T%s; Filter:string):Integer;', [RData.ClassName]));
if RData.CreateFillListField then
Buf.Add(Format(' class function FillListField(DB:TDataBase; Field:string; var List:TStringList; ADistinct:Boolean = False):Integer;', []));
if RData.CreateClear then
Buf.Add(Format(' class function Clear(DB:TDataBase):Integer;', []));
if RData.CreateUpdateField and (RData.Fields.GetUID.FieldName <> '') then
begin
Buf.Add(Format(' class function UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:Integer):Boolean; overload;', []));
Buf.Add(Format(' class function UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:string):Boolean; overload;', []));
Buf.Add(Format(' class function UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:Double):Boolean; overload;', []));
Buf.Add(Format(' class function UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:TDateTime):Boolean; overload;', []));
Buf.Add(Format(' class function UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:Boolean):Boolean; overload;', []));
end;
Buf.Add(Format(' end;', []));
Buf.Add(Format('', []));
Buf.Add(Format('implementation', []));
Buf.Add(Format('', []));
Buf.Add(Format('{ %s }', [RData.ClassName]));
Buf.Add(Format('', []));
//Create
Buf.Add(Format('class function %s.CreateTable:TTable;', [RData.ClassName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=TTable.Create(tn%s);', [RData.HumanName]));
Buf.Add(Format(' with Result do', []));
Buf.Add(Format(' begin', []));
for i:= 0 to RData.Fields.Count-1 do
Buf.Add(Format(' AddField(fn%s, %s, %s, %s);', [RData.Fields[i].FieldNameSet, FieldTypeToString(RData.Fields[i].FieldType), BoolToStr(RData.Fields[i].PrimaryKey ,True), BoolToStr(RData.Fields[i].NotNull ,True)]));
Buf.Add(Format(' end;', []));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
//Update
if RData.CreateInsert and (RData.Fields.Count > 0) then
begin
Buf.Add(Format('class function %s.Update(DB:TDataBase; Data:TData%s):Boolean;', [RData.ClassName, RData.HumanName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=False;', []));
Buf.Add(Format(' with SQL.Update(tn%s) do', [RData.HumanName]));
Buf.Add(Format(' begin', []));
for i:= 0 to RData.Fields.Count-1 do
if not RData.Fields[i].Orded then
Buf.Add(Format(' AddValue(fn%s, Data.%s);', [RData.Fields[i].FieldNameSet, RData.Fields[i].FieldName]))
else
Buf.Add(Format(' AddValue(fn%s, Ord(Data.%s));', [RData.Fields[i].FieldNameSet, RData.Fields[i].FieldNameSet]));
Buf.Add(Format(' WhereFieldEqual(fn%s, Data.%s);', [RData.Fields[0].FieldNameSet, RData.Fields[0].FieldName]));
Buf.Add(Format(' try', []));
Buf.Add(Format(' DB.%s.ExecSQL(GetSQL);', [RData.DBName]));
Buf.Add(Format(' DB.HistoryAdd(haChange, tn%s, Data.%s);', [RData.HumanName, RData.Fields[0].FieldName]));
Buf.Add(Format(' DB.InitUpdateTable(tn%s);', [RData.HumanName]));
Buf.Add(Format(' Result:=DB.%s.GetLastChangedRows > 0;', [RData.DBName]));
Buf.Add(Format(' except', []));
Buf.Add(Format(' on E:Exception do DB.CreateException(DB.%s, E);', [RData.DBName]));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' EndCreate;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
end;
//UpdateField
if RData.CreateUpdateField and (RData.Fields.GetUID.FieldName <> '') then
begin
Buf.Add(Format('class function %s.UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:string):Boolean;', [RData.ClassName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=CommonSQLFunc.UpdateField(DB, DB.%s, ID, tn%s, FieldName, fn%s, FieldValue);', [RData.DBName, RData.HumanName, RData.Fields[0].FieldNameSet]));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
Buf.Add(Format('class function %s.UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:Integer):Boolean;', [RData.ClassName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=CommonSQLFunc.UpdateField(DB, DB.%s, ID, tn%s, FieldName, fn%s, FieldValue);', [RData.DBName, RData.HumanName, RData.Fields[0].FieldNameSet]));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
Buf.Add(Format('class function %s.UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:Double):Boolean;', [RData.ClassName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=CommonSQLFunc.UpdateField(DB, DB.%s, ID, tn%s, FieldName, fn%s, FieldValue);', [RData.DBName, RData.HumanName, RData.Fields[0].FieldNameSet]));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
Buf.Add(Format('class function %s.UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:Boolean):Boolean;', [RData.ClassName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=CommonSQLFunc.UpdateField(DB, DB.%s, ID, tn%s, FieldName, fn%s, FieldValue);', [RData.DBName, RData.HumanName, RData.Fields[0].FieldNameSet]));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
Buf.Add(Format('class function %s.UpdateField(DB:TDataBase; ID:string; FieldName:string; FieldValue:TDateTime):Boolean;', [RData.ClassName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=CommonSQLFunc.UpdateField(DB, DB.%s, ID, tn%s, FieldName, fn%s, FieldValue);', [RData.DBName, RData.HumanName, RData.Fields[0].FieldNameSet]));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
end;
//Insert
if RData.CreateUpdate and (RData.Fields.Count > 0) then
begin
Buf.Add(Format('class function %s.Insert(DB:TDataBase; Data:TData%s):TUID;', [RData.ClassName, RData.HumanName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result.Clear;', []));
Buf.Add(Format(' with SQL.InsertInto(tn%s) do', [RData.HumanName]));
Buf.Add(Format(' begin', []));
Buf.Add(Format(' Data.%s:=DB.GetUID(tn%s);', [RData.Fields[0].FieldName, RData.HumanName]));
for i:= 0 to RData.Fields.Count-1 do
if not RData.Fields[i].Orded then
Buf.Add(Format(' AddValue(fn%s, Data.%s);', [RData.Fields[i].FieldNameSet, RData.Fields[i].FieldName]))
else
Buf.Add(Format(' AddValue(fn%s, Ord(Data.%s));', [RData.Fields[i].FieldNameSet, RData.Fields[i].FieldNameSet]));
Buf.Add(Format(' try', []));
Buf.Add(Format(' DB.%s.ExecSQL(GetSQL);', [RData.DBName]));
Buf.Add(Format(' DB.HistoryAdd(haAdd, tn%s, Data.%s);', [RData.HumanName, RData.Fields[0].FieldName]));
Buf.Add(Format(' DB.InitUpdateTable(tn%s);', [RData.HumanName]));
if RData.Fields.ExistsUID then
begin
Buf.Add(Format(' Data.%s.Name:=Data.%s;', [RData.Fields.GetUID.FieldNameSet, RData.Fields.GetUIDName.FieldName]));
end;
Buf.Add(Format(' Result:=Data.%s;', [RData.Fields[0].FieldNameSet]));
Buf.Add(Format(' except', []));
Buf.Add(Format(' on E:Exception do DB.CreateException(DB.%s, E);', [RData.DBName]));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' EndCreate;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
end;
//Delete
if RData.CreateDelete and (RData.Fields.Count > 0) then
begin
Buf.Add(Format('class function %s.Delete(DB:TDataBase; ID:string):Boolean;', [RData.ClassName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=False;', []));
Buf.Add(Format(' with SQL.Delete(tn%s) do', [RData.HumanName]));
Buf.Add(Format(' begin', []));
Buf.Add(Format(' WhereFieldEqual(fn%s, ID);', [RData.Fields[0].FieldNameSet]));
Buf.Add(Format(' try', []));
Buf.Add(Format(' DB.%s.ExecSQL(GetSQL);', [RData.DBName]));
Buf.Add(Format(' DB.HistoryAdd(haDelete, tn%s, ID);', [RData.HumanName]));
Buf.Add(Format(' DB.InitUpdateTable(tn%s);', [RData.HumanName]));
Buf.Add(Format(' Result:=True;', []));
Buf.Add(Format(' except', []));
Buf.Add(Format(' on E:Exception do DB.CreateException(DB.%s, E);', [RData.DBName]));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' EndCreate;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
end;
//Get
if RData.CreateGet and (RData.Fields.Count > 0) then
begin
Buf.Add(Format('class function %s.Get(DB:TDataBase; ID:string; var Data:TData%s):Boolean;', [RData.ClassName, RData.HumanName]));
Buf.Add(Format('var Table:TSQLiteTable;', []));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=False;', []));
Buf.Add(Format(' with SQL.Select(tn%s) do', [RData.HumanName]));
Buf.Add(Format(' begin', []));
for i:= 0 to RData.Fields.Count-1 do
Buf.Add(Format(' AddField(fn%s);', [RData.Fields[i].FieldNameSet]));
Buf.Add(Format(' WhereFieldEqual(fn%s, ID);', [RData.Fields[0].FieldNameSet]));
Buf.Add(Format(' Limit:=1;', []));
Buf.Add(Format(' try', []));
Buf.Add(Format(' Table:=DB.%s.GetTable(GetSQL);', [RData.DBName]));
Buf.Add(Format(' if Table.RowCount > 0 then', []));
Buf.Add(Format(' begin', []));
for i:= 0 to RData.Fields.Count-1 do
begin
case RData.Fields[i].FieldType of
ftInteger:
if not RData.Fields[i].Orded then
Buf.Add(Format(' Data.%s:=Table.FieldAsInteger(%d);', [RData.Fields[i].FieldName, i]))
else Buf.Add(Format(' Data.%s:=%s(Table.FieldAsInteger(%d));', [RData.Fields[i].FieldName, RData.Fields[i].FieldDataType, i]));
ftString: Buf.Add(Format(' Data.%s:=Table.FieldAsString(%d);', [RData.Fields[i].FieldName, i]));
ftDateTime: Buf.Add(Format(' Data.%s:=Table.FieldAsDouble(%d);', [RData.Fields[i].FieldName, i]));
ftFloat: Buf.Add(Format(' Data.%s:=Table.FieldAsDouble(%d);', [RData.Fields[i].FieldName, i]));
ftBoolean: Buf.Add(Format(' Data.%s:=Table.FieldAsBoolean(%d);', [RData.Fields[i].FieldName, i]));
ftBlob: Buf.Add(Format(' Data.%s:=Table.FieldAsBlob(%d);', [RData.Fields[i].FieldName, i]));
end;
if RData.Fields[i].IsOtherUID then
Buf.Add(Format(' { Заполнить UID другой таблицы }', []));
end;
if RData.Fields.ExistsUID then
begin
Buf.Add(Format(' Data.%s.Name:=Data.%s;', [RData.Fields.GetUID.FieldNameSet, RData.Fields.GetUIDName.FieldNameSet]));
end;
Buf.Add(Format(' end;', []));
Buf.Add(Format(' Result:=Table.RowCount > 0;', []));
Buf.Add(Format(' Table.Free;', []));
Buf.Add(Format(' except', []));
Buf.Add(Format(' on E:Exception do DB.CreateException(DB.%s, E);', [RData.DBName]));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' EndCreate;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
end;
//GetUID
if RData.CreateGetUID and (RData.Fields.Count > 0) and (RData.Fields.ExistsUID) then
begin
Buf.Add(Format('class function %s.GetUID(DB:TDataBase; ID:string):TUID;', [RData.ClassName]));
Buf.Add(Format('var Table:TSQLiteTable;', []));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result.Clear;', []));
Buf.Add(Format(' with SQL.Select(tn%s) do', [RData.HumanName]));
Buf.Add(Format(' begin', []));
Buf.Add(Format(' AddField(fn%s);', [RData.Fields.GetUIDName.FieldNameSet]));
Buf.Add(Format(' WhereFieldEqual(fn%s, ID);', [RData.Fields[0].FieldNameSet]));
Buf.Add(Format(' Limit:=1;', []));
Buf.Add(Format(' try', []));
Buf.Add(Format(' Table:=DB.%s.GetTable(GetSQL);', [RData.DBName]));
Buf.Add(Format(' if Table.RowCount > 0 then', []));
Buf.Add(Format(' begin', []));
Buf.Add(Format(' Result.Fill(ID, Table.FieldAsString(0));', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' Table.Free;', []));
Buf.Add(Format(' except', []));
Buf.Add(Format(' on E:Exception do DB.CreateException(DB.%s, E);', [RData.DBName]));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' EndCreate;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
end;
//FillList
if RData.CreateFillList and (RData.Fields.Count > 0) then
begin
Buf.Add(Format('class function %s.FillList(DB:TDataBase; var List:T%s; Filter:string):Integer;', [RData.ClassName, RData.ClassName]));
Buf.Add(Format('var Table:TSQLiteTable;', []));
Buf.Add(Format(' Item:TData%s;', [RData.HumanName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=-1;', []));
Buf.Add(Format(' with SQL.Select(tn%s) do', [RData.HumanName]));
Buf.Add(Format(' begin', []));
for i:= 0 to RData.Fields.Count-1 do
Buf.Add(Format(' AddField(fn%s);', [RData.Fields[i].FieldNameSet]));
Buf.Add(Format(' WhereStr(Filter);', []));
Buf.Add(Format(' {OrderBy}', []));
Buf.Add(Format(' try', []));
Buf.Add(Format(' Table:=DB.%s.GetTable(GetSQL);', [RData.DBName]));
Buf.Add(Format(' List.BeginUpdate;', []));
Buf.Add(Format(' List.Clear;', []));
Buf.Add(Format(' if Table.RowCount > 0 then', []));
Buf.Add(Format(' begin', []));
Buf.Add(Format(' Table.MoveFirst;', []));
Buf.Add(Format(' while not Table.EOF do', []));
Buf.Add(Format(' begin', []));
for i:= 0 to RData.Fields.Count-1 do
begin
case RData.Fields[i].FieldType of
ftInteger:
if not RData.Fields[i].Orded then
Buf.Add(Format(' Item.%s:=Table.FieldAsInteger(%d);', [RData.Fields[i].FieldName, i]))
else
Buf.Add(Format(' Item.%s:=%s(Table.FieldAsInteger(%d));', [RData.Fields[i].FieldName, RData.Fields[i].FieldDataType, i]));
ftString: Buf.Add(Format(' Item.%s:=Table.FieldAsString(%d);', [RData.Fields[i].FieldName, i]));
ftDateTime: Buf.Add(Format(' Item.%s:=Table.FieldAsDouble(%d);', [RData.Fields[i].FieldName, i]));
ftFloat: Buf.Add(Format(' Item.%s:=Table.FieldAsDouble(%d);', [RData.Fields[i].FieldName, i]));
ftBoolean: Buf.Add(Format(' Item.%s:=Table.FieldAsBoolean(%d);', [RData.Fields[i].FieldName, i]));
ftBlob: Buf.Add(Format(' Item.%s:=Table.FieldAsBlob(%d);', [RData.Fields[i].FieldName, i]));
end;
if RData.Fields[i].IsOtherUID then
Buf.Add(Format(' { Заполнить UID другой таблицы }', []));
end;
if RData.Fields.ExistsUID then
begin
Buf.Add(Format(' Item.%s.Name:=Item.%s;', [RData.Fields.GetUID.FieldNameSet, RData.Fields.GetUIDName.FieldNameSet]));
end;
//Buf.Add(Format(' Item.%s:=Table.FieldAsString(%d);', [RData.Fields[i].FieldName, i]));
Buf.Add(Format(' List.Add(Item);', []));
Buf.Add(Format(' Table.Next;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' List.EndUpdate;', []));
Buf.Add(Format(' Result:=Table.RowCount;', []));
Buf.Add(Format(' Table.Free;', []));
Buf.Add(Format(' except', []));
Buf.Add(Format(' on E:Exception do DB.CreateException(DB.%s, E);', [RData.DBName]));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' EndCreate;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
end;
//FillListField
if RData.CreateFillListField then
begin
Buf.Add(Format('class function %s.FillListField(DB:TDataBase; Field:string; var List:TStringList; ADistinct:Boolean):Integer;', [RData.ClassName]));
Buf.Add(Format('var Table:TSQLiteTable;', []));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=-1;', []));
Buf.Add(Format(' with SQL.Select(tn%s) do', [RData.HumanName]));
Buf.Add(Format(' begin', []));
Buf.Add(Format(' AddField(Field);', []));
Buf.Add(Format(' Distinct:=ADistinct;', []));
Buf.Add(Format(' OrderBy(Field);', []));
Buf.Add(Format(' Limit:=1000;', []));
Buf.Add(Format(' try', []));
Buf.Add(Format(' Table:=DB.%s.GetTable(GetSQL);', [RData.DBName]));
Buf.Add(Format(' if Table.RowCount > 0 then', []));
Buf.Add(Format(' begin', []));
Buf.Add(Format(' Table.MoveFirst;', []));
Buf.Add(Format(' while not Table.EOF do', []));
Buf.Add(Format(' begin', []));
Buf.Add(Format(' List.Add(Table.FieldAsString(0));', []));
Buf.Add(Format(' Table.Next;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' Result:=Table.RowCount;', []));
Buf.Add(Format(' Table.Free;', []));
Buf.Add(Format(' except', []));
Buf.Add(Format(' on E:Exception do DB.CreateException(DB.%s, E);', [RData.DBName]));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' EndCreate;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
end;
//Clear
if RData.CreateClear then
begin
Buf.Add(Format('class function %s.Clear(DB:TDataBase):Integer;', [RData.ClassName]));
Buf.Add(Format('begin', []));
Buf.Add(Format(' Result:=-1;', []));
Buf.Add(Format(' with SQL.Delete(tn%s) do', [RData.HumanName]));
Buf.Add(Format(' begin', []));
Buf.Add(Format(' try', []));
Buf.Add(Format(' DB.%s.ExecSQL(GetSQL);', [RData.DBName]));
Buf.Add(Format(' Result:=DB.%s.GetLastChangedRows;', [RData.DBName]));
Buf.Add(Format(' DB.HistoryAdd(haDelete, tn%s, ''ALL'');', [RData.HumanName]));
Buf.Add(Format(' DB.InitUpdateTable(tn%s);', [RData.HumanName]));
Buf.Add(Format(' except', []));
Buf.Add(Format(' on E:Exception do DB.CreateException(DB.%s, E);', [RData.DBName]));
Buf.Add(Format(' end;', []));
Buf.Add(Format(' EndCreate;', []));
Buf.Add(Format(' end;', []));
Buf.Add(Format('end;', []));
Buf.Add(Format('', []));
end;
Buf.Add(Format('end.', []));
////
MemoData.Clear;
MemoData.Lines.AddStrings(Buf);
end;
procedure TFormMain.ButtonDeleteClick(Sender: TObject);
begin
if not IndexInList(FCurrentData, FData.Count) then Exit;
if not IndexInList(TableExFields.ItemIndex, FData[FCurrentData].Fields.Count) then Exit;
FData[FCurrentData].Fields.Delete(TableExFields.ItemIndex);
end;
function TFormMain.Save(ID:Integer; FN:string):Boolean;
var Ini:TIniFile;
Item:TTMCRecord;
FieldItem:TTMCField;
Count, i:Integer;
begin
Result:=False;
Ini:=TIniFile.Create(FN);
Item:=FData[ID];
Ini.WriteString('GENERAL', 'TableName', Item.TableName);
Ini.WriteString('GENERAL', 'ClassName', Item.ClassName);
Ini.WriteString('GENERAL', 'HumanName', Item.HumanName);
Ini.WriteString('GENERAL', 'DBName', Item.DBName);
Ini.WriteString('GENERAL', 'UnitName', Item.UnitName);
Ini.WriteInteger('GENERAL', 'FieldCount', Item.Fields.Count);
if Item.Fields.Count > 0 then
begin
for i:= 0 to Item.Fields.Count-1 do
begin
Ini.WriteString('FIELD_'+IntToStr(i+1), 'FieldName', Item.Fields[i].FieldNameSet);
Ini.WriteInteger('FIELD_'+IntToStr(i+1), 'FieldType', Ord(Item.Fields[i].FieldType));
Ini.WriteString('FIELD_'+IntToStr(i+1), 'FieldDataType', Item.Fields[i].FieldDataType);
Ini.WriteString('FIELD_'+IntToStr(i+1), 'Comments', Item.Fields[i].Comments);
Ini.WriteBool('FIELD_'+IntToStr(i+1), 'PrimaryKey', Item.Fields[i].PrimaryKey);
Ini.WriteBool('FIELD_'+IntToStr(i+1), 'UIDName', Item.Fields[i].UIDName);
Ini.WriteBool('FIELD_'+IntToStr(i+1), 'UID', Item.Fields[i].UID);
Ini.WriteBool('FIELD_'+IntToStr(i+1), 'NotNull', Item.Fields[i].NotNull);
Ini.WriteBool('FIELD_'+IntToStr(i+1), 'Orded', Item.Fields[i].Orded);
end;
end;
Ini.Free;
Result:=True;
end;
procedure TFormMain.ButtonSaveClick(Sender: TObject);
begin
if not IndexInList(FCurrentData, FData.Count) then Exit;
if FileSaveDialog.Execute(Handle) then Save(FCurrentData, FileSaveDialog.FileName);
end;
procedure TFormMain.CancelEdit;
var FF:TTMCField;
begin
if not IndexInList(FCurrentData, FData.Count) then Exit;
if not IndexInList(TableExFields.ItemIndex, FData[FCurrentData].Fields.Count) then Exit;
//FF:=FData[FCurrentData].Fields[TableExFields.ItemIndex];
EditFieldName.Text:='';
ComboBoxFieldDataType.Text:='';
CheckBoxFieldPK.Checked:=False;
CheckBoxFieldNN.Checked:=False;
end;
procedure TFormMain.FormCreate(Sender: TObject);
var FF:TTMCField;
begin
FData:=TTMCData.Create(nil);
with TableExFields do
begin
FirstColumn('№ п/п', 60);
AddColumn('Имя поля', 200);
AddColumn('Тип данных', 120);
AddColumn('Orded', 60);
AddColumn('Тип данных SQL', 120);
AddColumn('PrimaryKey', 60);
AddColumn('NotNull', 60);
AddColumn('УИД', 60);
AddColumn('УИД описание', 60);
AddColumn('Описание/Комментарий', 200);
AddColumn(' ', 60);
end;
ComboBoxFieldSQLType.Items.Clear;
ComboBoxFieldSQLType.Items.Add('Integer');
ComboBoxFieldSQLType.Items.Add('String');
ComboBoxFieldSQLType.Items.Add('Float');
ComboBoxFieldSQLType.Items.Add('DateTime');
ComboBoxFieldSQLType.Items.Add('Blob');
ComboBoxFieldSQLType.Items.Add('Boolean');
ComboBoxFieldSQLType.ItemIndex:=0;
ComboBoxFieldDataType.Items.Clear;
ComboBoxFieldDataType.Items.Add('Integer');
ComboBoxFieldDataType.Items.Add('String');
ComboBoxFieldDataType.Items.Add('Double');
ComboBoxFieldDataType.Items.Add('TDateTime');
ComboBoxFieldDataType.Items.Add('Boolean');
ComboBoxFieldDataType.Items.Add('TUID');
Mode:=femAdd;
UpdateTabs;
ButtonAddTableClick(nil);
FF.FieldName:='PM_UID';
FF.FieldType:=ftString;
FF.FieldDataType:='TUID';
FF.PrimaryKey:=True;
FF.UID:=True;
FF.UIDName:=False;
FF.NotNull:=True;
FF.Orded:=False;
FF.Comments:='ИД записи';
FData[FCurrentData].Fields.Add(FF);
FF.FieldName:='PM_NAME';
FF.FieldType:=ftString;
FF.FieldDataType:='String';
FF.PrimaryKey:=False;
FF.UID:=False;
FF.UIDName:=True;
FF.NotNull:=True;
FF.Orded:=False;
FF.Comments:='Наименование';
FData[FCurrentData].Fields.Add(FF);
FF.FieldName:='PM_CAT';
FF.FieldType:=ftInteger;
FF.FieldDataType:='TCat';
FF.PrimaryKey:=False;
FF.UID:=False;
FF.UIDName:=False;
FF.NotNull:=True;
FF.Orded:=True;
FF.Comments:='Категория';
FData[FCurrentData].Fields.Add(FF);
FF.FieldName:='PM_CUT';
FF.FieldType:=ftString;
FF.FieldDataType:='String';
FF.PrimaryKey:=False;
FF.UID:=False;
FF.UIDName:=False;
FF.NotNull:=True;
FF.Orded:=False;
FF.Comments:='Сокр';
FData[FCurrentData].Fields.Add(FF);
FF.FieldName:='PM_CLIENT';
FF.FieldType:=ftString;
FF.FieldDataType:='TUID';
FF.PrimaryKey:=False;
FF.UID:=False;
FF.UIDName:=False;
FF.NotNull:=True;
FF.Orded:=False;
FF.Comments:='ИД клиента';
FData[FCurrentData].Fields.Add(FF);
end;
function TFormMain.Open(FN:string):Boolean;
var Ini:TIniFile;
Item:TTMCRecord;
FieldItem:TTMCField;
Count, i:Integer;
begin
Result:=False;
Ini:=TIniFile.Create(FN);
Item.TableName:=Ini.ReadString('GENERAL', 'TableName', '');
Item.ClassName:=Ini.ReadString('GENERAL', 'ClassName', '');
Item.HumanName:=Ini.ReadString('GENERAL', 'HumanName', '');
Item.DBName:=Ini.ReadString('GENERAL', 'DBName', '');
Item.UnitName:=Ini.ReadString('GENERAL', 'UnitName', '');
Count:=Ini.ReadInteger('GENERAL', 'FieldCount', 0);
Item.Fields:=TTMCFields.Create(TableExFields);
if Count > 0 then
begin
for i:= 1 to Count do
begin
FieldItem.FieldName:=Ini.ReadString('FIELD_'+IntToStr(i), 'FieldName', '');
FieldItem.FieldType:=TFieldType(Ini.ReadInteger('FIELD_'+IntToStr(i), 'FieldType', 0));
FieldItem.FieldDataType:=Ini.ReadString('FIELD_'+IntToStr(i), 'FieldDataType', '');
FieldItem.Comments:=Ini.ReadString('FIELD_'+IntToStr(i), 'Comments', '');
FieldItem.PrimaryKey:=Ini.ReadBool('FIELD_'+IntToStr(i), 'PrimaryKey', False);
FieldItem.UID:=Ini.ReadBool('FIELD_'+IntToStr(i), 'UID', False);
FieldItem.UIDName:=Ini.ReadBool('FIELD_'+IntToStr(i), 'UIDName', False);
FieldItem.NotNull:=Ini.ReadBool('FIELD_'+IntToStr(i), 'NotNull', False);
FieldItem.Orded:=Ini.ReadBool('FIELD_'+IntToStr(i), 'Orded', False);
Item.Fields.Add(FieldItem);
end;
end;
Ini.Free;
Result:=Add(Item) >= 0;
end;
procedure TFormMain.SetMode(const Value: TFieldEditMode);
begin
CancelEdit;
FMode:=Value;
case FMode of
femAdd:
begin
ButtonAdd_Apply.Caption:='Добавить';
ButtonChange_Cancel.Caption:='Изменить';
TableExFields.Enabled:=True;
end;
femEdit:
begin
TableExFields.Enabled:=False;
ButtonAdd_Apply.Caption:='Применить';
ButtonChange_Cancel.Caption:='Отменить';
end;
end;
end;
function TFormMain.SetTable(ID:Integer):Boolean;
begin
if not IndexInList(ID, FData.Count) then Exit(False);
FCurrentData:=ID;
FData[FCurrentData].Fields.UpdateTable;
Result:=True;
end;
procedure TFormMain.TableExFieldsGetData(FCol, FRow: Integer; var Value: string);
begin
Value:='';
if not IndexInList(FCurrentData, FData.Count) then Exit;
if not IndexInList(FRow, FData[FCurrentData].Fields.Count) then Exit;
case FCol of
0:Value:=IntToStr(FRow+1);
1:Value:=FData[FCurrentData].Fields[FRow].FieldNameSet;
2:Value:=FData[FCurrentData].Fields[FRow].FieldDataType;
3:Value:=BoolToStr(FData[FCurrentData].Fields[FRow].Orded, True);
4:Value:=FieldTypeToStr(FData[FCurrentData].Fields[FRow].FieldType);
5:Value:=BoolToStr(FData[FCurrentData].Fields[FRow].PrimaryKey, True);
6:Value:=BoolToStr(FData[FCurrentData].Fields[FRow].NotNull, True);
7:Value:=BoolToStr(FData[FCurrentData].Fields[FRow].UID, True);
8:Value:=BoolToStr(FData[FCurrentData].Fields[FRow].UIDName, True);
9:Value:=FData[FCurrentData].Fields[FRow].Comments;
end;
end;
procedure TFormMain.TabSetTablesChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
begin
AllowChange:=SetTable(NewTab);
end;
procedure TFormMain.UpdateTabs;
var i, ti:Integer;
begin
ti:=TabSetTables.TabIndex;
TabSetTables.Tabs.BeginUpdate;
TabSetTables.Tabs.Clear;
for i:= 0 to FData.Count-1 do TabSetTables.Tabs.Add(FData[i].TableName);
TabSetTables.Tabs.EndUpdate;
if not((ti < -1) or (ti >= TabSetTables.Tabs.Count)) then TabSetTables.TabIndex:=ti;
end;
{ TTMCField }
function TTMCField.GetFieldName: string;
begin
Result:= FFieldName;
if FieldDataType = 'TUID' then Result:=Result+'.ID';
end;
function TTMCField.GetIsOtherUID:Boolean;
begin
Result:=(not UID) and (FieldDataType = 'TUID');
end;
{ TTMCFields }
function TTMCFields.ExistsUID:Boolean;
var i:Integer;
begin
Result:=False;
for i:= 0 to Count-1 do if Items[i].UID then begin Result:=True; Break; end;
if not Result then Exit;
Result:=False;
for i:= 0 to Count-1 do if Items[i].UIDName then begin Result:=True; Break; end;
if not Result then Exit;
end;
function TTMCFields.GetUID:TTMCField;
var i:Integer;
begin
Result.FieldName:='';
for i:= 0 to Count-1 do if Items[i].UID then Exit(Items[i]);
end;
function TTMCFields.GetUIDName:TTMCField;
var i:Integer;
begin
Result.FieldName:='';
for i:= 0 to Count-1 do if Items[i].UIDName then Exit(Items[i]);
end;
end.
|
unit AddOrderToOptimizationRequestUnit;
interface
uses
REST.Json.Types, SysUtils,
JSONNullableAttributeUnit, HttpQueryMemberAttributeUnit,
GenericParametersUnit, RouteParametersUnit, AddressUnit,
NullableBasicTypesUnit, EnumsUnit;
type
TAddOrderToOptimizationRequest = class(TGenericParameters)
private
[JSONMarshalled(False)]
[HttpQueryMember('optimization_problem_id')]
[Nullable]
FOptimizationProblemId: NullableString;
[JSONMarshalled(False)]
[HttpQueryMember('redirect')]
[Nullable]
FRedirect: NullableBoolean;
[JSONNameAttribute('addresses')]
[NullableArray(TOrderedAddress)]
FAddresses: TOrderedAddressArray;
[JSONNameAttribute('parameters')]
[NullableObject(TRouteParameters)]
FParameters: NullableObject;
function GetAddress(AddressString: String; Addresses: TOrderedAddressArray): TOrderedAddress;
public
constructor Create; override;
destructor Destroy; override;
function Equals(Obj: TObject): Boolean; override;
/// <summary>
/// Route Parameters.
/// </summary>
property Parameters: NullableObject read FParameters write FParameters;
/// <summary>
/// Route Addresses.
/// </summary>
property Addresses: TOrderedAddressArray read FAddresses;
procedure AddAddress(Address: TOrderedAddress);
property OptimizationProblemId: NullableString read FOptimizationProblemId write FOptimizationProblemId;
property Redirect: NullableBoolean read FRedirect write FRedirect;
end;
implementation
{ TAddOrderToOptimizationRequest }
procedure TAddOrderToOptimizationRequest.AddAddress(Address: TOrderedAddress);
begin
SetLength(FAddresses, Length(FAddresses) + 1);
FAddresses[High(FAddresses)] := Address;
end;
constructor TAddOrderToOptimizationRequest.Create;
begin
Inherited;
SetLength(FAddresses, 0);
FParameters := NullableObject.Null;
FOptimizationProblemId := NullableString.Null;
FRedirect := NullableBoolean.Null;
end;
destructor TAddOrderToOptimizationRequest.Destroy;
begin
// Request does not own objects
inherited;
end;
function TAddOrderToOptimizationRequest.Equals(Obj: TObject): Boolean;
var
Other: TAddOrderToOptimizationRequest;
Address, OtherAddress: TAddress;
AddressEquals: boolean;
begin
Result := False;
if not (Obj is TAddOrderToOptimizationRequest) then
Exit;
Other := TAddOrderToOptimizationRequest(Obj);
Result :=
(FParameters = Other.FParameters) and
(FOptimizationProblemId = Other.FOptimizationProblemId) and
(FRedirect = Other.FRedirect);
if (not Result) then
Exit;
Result := False;
if (Length(FAddresses) <> Length(Other.Addresses)) then
Exit;
AddressEquals := True;
for Address in FAddresses do
begin
OtherAddress := GetAddress(Address.AddressString, Other.Addresses);
if (OtherAddress = nil) then
Exit;
AddressEquals := AddressEquals and Address.Equals(OtherAddress);
if not AddressEquals then
Break;
end;
end;
function TAddOrderToOptimizationRequest.GetAddress(AddressString: String;
Addresses: TOrderedAddressArray): TOrderedAddress;
var
Address: TOrderedAddress;
begin
Result := nil;
for Address in Addresses do
if (Address.AddressString = AddressString) then
Exit(Address);
end;
end.
|
unit uChamadoColaboradorVO;
interface
uses
System.SysUtils, System.DateUtils, uUsuarioVO;
type
TChamadoColaboradorVO = class
private
FHoraInicial: TTime;
FIdUsuario: Integer;
FId: Integer;
FIdOcorrencia: Integer;
FHoraFim: TTime;
FTotalHoras: Double;
FUsuarioVO: TUsuarioVO;
procedure SetHoraFim(const Value: TTime);
procedure SetHoraInicial(const Value: TTime);
procedure SetId(const Value: Integer);
procedure SetIdOcorrencia(const Value: Integer);
procedure SetIdUsuario(const Value: Integer);
procedure SetTotalHoras(const Value: Double);
procedure SetUsuarioVO(const Value: TUsuarioVO);
public
property Id: Integer read FId write SetId;
property IdOcorrencia: Integer read FIdOcorrencia write SetIdOcorrencia;
property HoraInicial: TTime read FHoraInicial write SetHoraInicial;
property HoraFim: TTime read FHoraFim write SetHoraFim;
property IdUsuario: Integer read FIdUsuario write SetIdUsuario;
property TotalHoras: Double read FTotalHoras write SetTotalHoras;
property UsuarioVO: TUsuarioVO read FUsuarioVO write SetUsuarioVO;
constructor Create;
destructor Destroy; override;
end;
implementation
{ TChamadoColaboradorVO }
constructor TChamadoColaboradorVO.Create;
begin
inherited Create;
FUsuarioVO := TUsuarioVO.Create;
end;
destructor TChamadoColaboradorVO.Destroy;
begin
FreeAndNil(FUsuarioVO);
inherited;
end;
procedure TChamadoColaboradorVO.SetHoraFim(const Value: TTime);
begin
FHoraFim := Value;
end;
procedure TChamadoColaboradorVO.SetHoraInicial(const Value: TTime);
begin
FHoraInicial := Value;
end;
procedure TChamadoColaboradorVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TChamadoColaboradorVO.SetIdOcorrencia(const Value: Integer);
begin
FIdOcorrencia := Value;
end;
procedure TChamadoColaboradorVO.SetIdUsuario(const Value: Integer);
begin
FIdUsuario := Value;
end;
procedure TChamadoColaboradorVO.SetTotalHoras(const Value: Double);
begin
FTotalHoras := Value;
end;
procedure TChamadoColaboradorVO.SetUsuarioVO(const Value: TUsuarioVO);
begin
FUsuarioVO := Value;
end;
end.
|
program ejercicio6;
type
procesador = record
marca :string;
linea :string;
nucleos :integer;
reloj :real;
escala :integer;
end;
actual = record
marca :string;
cantidad :integer;
end;
maximos = record
primera :actual;
segunda :actual;
end;
procedure leerProcesador(var p:procesador);
begin
write('Ingrese la marca del procesador: ');
readln(p.marca);
write('Ingrese la linea del procesador: ');
readln(p.linea);
write('Ingrese la cantidad de núcleos del procesador: ');
readln(p.nucleos);
write('Ingrese la frecuencia de reloj del procesador: ');
readln(p.reloj);
write('Ingrese la escala en nm de los transistores del procesador: ');
readln(p.escala);
end;
procedure incrementar(var c:integer);
begin
c := c + 1;
end;
procedure comprobarCondPrimera(p:procesador);
function cond(p:procesador):boolean;
begin
cond := (p.nucleos > 2) and (p.escala <= 22);
end;
begin
if (cond(p)) then
writeln(
'El procesador de la marca ', p.marca,
', linea ', p.linea,
' tiene más de 2 núcleos y transistores de como mucho 22nm.'
);
end;
procedure comprobarCondSegunda(var contador:integer; escala:integer);
function cond(e:integer):boolean;
begin
cond := (e = 14);
end;
begin
if (cond(escala)) then
incrementar(contador);
end;
procedure comprobarCondTercera(var contador:integer; p:procesador);
function cond(p:procesador):boolean;
begin
cond := (p.nucleos > 1)
and (p.reloj >= 2)
and ((p.marca = 'Intel') or (p.marca = 'AMD'));
end;
begin
if (cond(p)) then
incrementar(contador);
end;
procedure reiniciarMarca(var m:actual; p:procesador);
begin
m.marca := p.marca;
m.cantidad := 0;
end;
procedure comprobarMaximos(var max:maximos; m:actual);
begin
if (m.cantidad >= max.primera.cantidad) then
begin
max.segunda.cantidad := max.primera.cantidad;
max.segunda.marca := max.primera.marca;
max.primera.cantidad := m.cantidad;
max.primera.marca := m.marca;
end
else
if (m.cantidad >= max.segunda.cantidad) then
begin
max.segunda.cantidad := m.cantidad;
max.segunda.marca := m.marca;
end;
end;
var
p :procesador;
marcaActual :actual;
maximosActual :maximos;
cantidadCondTercera :integer;
begin
maximosActual.primera.cantidad := 0;
maximosActual.primera.marca := ' ';
maximosActual.segunda.cantidad := 0;
maximosActual.segunda.marca := ' ';
leerProcesador(p);
reiniciarMarca(marcaActual, p);
while (p.nucleos <> 0) do
begin
comprobarCondPrimera(p);
if (p.marca <> marcaActual.marca) then
begin
comprobarMaximos(maximosActual, marcaActual);
reiniciarMarca(marcaActual, p);
end;
comprobarCondSegunda(marcaActual.cantidad, p.escala);
comprobarCondTercera(cantidadCondTercera, p);
leerProcesador(p);
end;
writeln('Las dos marcas con mayor cantidad de procesadores de 14nm son: ');
writeln('1- ', maximosActual.primera.marca);
writeln('2- ', maximosActual.segunda.marca);
writeln(
'La cantidad de procesadores multicore de ',
'Intel o AMD con reloj de almenos 2Ghz es: ',
cantidadCondTercera
);
end. |
unit PublicUtils;
interface
uses IdGlobal, System.SysUtils, Math, Constants, ProtocolCommon, ProtocolApp, ProtocolKop, ProtocolLib;
type TIntRecord = packed record
int: Uint32;
end;
ArrOfByte = array[0..7] of byte;
function Buf36ToStr(Buf: TBuf36): string;
function StrToBuf36(Value: string): TBuf36;
function Buf36ToStrUni(Buf: TBuf36): string;
function StrToBuf36Uni(Value: string): TBuf36;
function BytesToHex(Buf: TIdBytes; Sep: string = ''): string;
function Buf200ToStr(Buf: TBuf200): string;
function StrToBuf200(Value: string): TBuf200;
function BtsToInt(Buf: TIdBytes; Len: Word = 0): integer;
function SwapBytes(Buf: TIdBytes): TIdBytes;
function HexToInt(HexStr : string) : Int64;
function IntToBytes(Value: Int64; Len: Word): TIdBytes;
function Uint16ToBin(Value: Uint16): TBuf16;
function IntToBin(Value: Word; Digits: Integer): TBytes;
function Buf6ToInt(Buf: TBuf6): int64;
procedure KeyStrToBuf(KeyStr:string; var Buf: TSecKey);
function Buf20ToStr(Buf: TBuf20): string;
function StrToBuf20(Value: string): TBuf20;
function HighLowByte(Val:byte;var LowB:byte;var HighB:byte):Boolean;
function IntToOct(Value: Longint; digits: Integer): string;
function RetrData(Value:integer;var RetrLevel:byte):byte;
function HostAndPort(Host: string; Port: word): string;
function Bytes16ToInt(Buf: TBuf16): Extended;
function BytesToFloat(buf: TBuf4):Single;
function BytesToBin(Val:integer): TBuf8;
function GetDevClass(ParDevType: word; DevType: Word): Byte;
implementation
function Buf36ToStr(Buf: TBuf36): string;
var i: byte;
begin
Result := '';
for i := 0 to Length(Buf) - 1 do
begin
if Buf[i] = 0 then Break;
Result := Result + Chr(Buf[i]);
end;
end;
function StrToBuf36(Value: string): TBuf36;
var i: byte;
begin
for i := 1 to Length(Result) do Result[i] := 0;
if Length(Value) > Length(Result) then
SetLength(Value, Length(Result));
for i := 1 to Length(Value) do
Result[i - 1] := Ord(Value[i]);
end;
function Buf36ToStrUni(Buf: TBuf36): string;
var i: integer; IdBytes: TIdBytes; Flag: boolean;
begin
Result := '';
Flag := False;
if Buf[0] = 0 then Exit;
SetLength(IdBytes, Length(Buf));
for i := 0 to High(IdBytes) do
begin
if Buf[i] = 0 then Break;
IdBytes[i] := Buf[i];
end;
Result := Trim(TEncoding.UTF8.GetString(IdBytes));
end;
function StrToBuf36Uni(Value: string): TBuf36;
var i: integer; Buf: TBytes;
begin
for i := 0 to High(Result) do Result[i] := 0;
if Length(Value) > Trunc(Length(Result)/2) then
Value := Copy(Value, 1, Trunc(Length(Result)/2));
SetLength(Buf, Length(Result));
Buf := TEncoding.UTF8.GetBytes(Value);
for i := 0 to High(Buf) do Result[i] := Buf[i];
end;
function BytesToHex(Buf: TIdBytes; Sep: string = ''): string;
var
I: Integer;
begin
for I := 0 to High(Buf) do
Result := Result + Sep + IntToHex(Buf[I], 2);
end;
function Buf200ToStr(Buf: TBuf200): string;
var i: integer; IdBytes: TIdBytes; Flag: boolean;
begin
Result := '';
Flag := False;
if Buf[0] = 0 then Exit;
SetLength(IdBytes, Length(Buf));
for i := 0 to High(IdBytes) do
begin
if Buf[i] = 0 then Break;
IdBytes[i] := Buf[i];
end;
Result := Trim(TEncoding.UTF8.GetString(IdBytes));
end;
function StrToBuf200(Value: string): TBuf200;
var i: integer; Buf: TBytes;
begin
for i := 0 to High(Result) do Result[i] := 0;
if Length(Value) > Trunc(Length(Result)/2) then
Value := Copy(Value, 1, Trunc(Length(Result)/2));
SetLength(Buf, Length(Result));
Buf := TEncoding.UTF8.GetBytes(Value);
for i := 0 to High(Buf) do Result[i] := Buf[i];
end;
function BtsToInt(Buf: TIdBytes; Len: Word = 0): integer;
begin
if Length(Buf) <> 4 then
SetLength(Buf, 4);
Result := BytesToInt32(Buf, 0);
end;
function SwapBytes(Buf: TIdBytes): TIdBytes;
var L, I: Integer;
begin
SetLength(Result, Length(Buf));
I := 0;
for L := High(Buf) downto 0 do
begin
Result[I] := Buf[L];
Inc(I);
end;
end;
function HexToInt(HexStr : string) : Int64;
var RetVar : Int64;
i : byte;
begin
HexStr := UpperCase(HexStr);
if HexStr[length(HexStr)] = 'H' then
Delete(HexStr,length(HexStr),1);
RetVar := 0;
for i := 1 to length(HexStr) do begin
RetVar := RetVar shl 4;
if HexStr[i] in ['0'..'9'] then
RetVar := RetVar + (byte(HexStr[i]) - 48)
else
if HexStr[i] in ['A'..'F'] then
RetVar := RetVar + (byte(HexStr[i]) - 55)
else begin
Retvar := 0;
break;
end;
end;
Result := RetVar;
end;
procedure AddBytes(Value: Int64; Len: Integer; var Buf: TIdBytes);
var I, L: Integer;
Arr, Arr1: TIdBytes;
begin
SetLength(Arr, 0);
Arr1 := RawToBytes(Value, Len);
Arr := SwapBytes(Arr1);
L := Length(Buf);
SetLength(Buf, L + Len);
for I := 0 to Len - 1 do
Buf[I + L] := Arr[I];
end;
function HexStrToBytes(Str: string): TIdBytes;
var
Hex: string;
Pos: Integer;
begin
SetLength(Result, 0);
Pos := 1;
while Pos < Length(Str) do
begin
Hex := Copy(Str, Pos, 2);
AddBytes(HexToInt(Hex), 1, Result);
Pos := Pos + 2;
end;
end;
function IntToBytes(Value: Int64; Len: Word): TIdBytes;
var
Str: string;
begin
SetLength(Result, 0);
Str := IntToHex(Value, Len * 2);
Result := HexStrToBytes(Str);
end;
function Uint16ToBin(Value: Uint16): TBuf16;
var i: Integer;
begin
for i := 15 downto 0 do
if Value and (1 shl i) <> 0 then Result[i] := 1
else
Result[i] := 0;
end;
function IntToBin(Value: Word; Digits: Integer): TBytes;
var i: Integer;
begin
SetLength(Result, Digits);
for i := Digits downto 0 do
if Value and (1 shl i) <> 0 then Result[i] := 1
else
Result[i] := 0;
end;
function Buf6ToInt(Buf: TBuf6): int64;
var i:integer; Hex:string;
begin
Hex := '';
for i := 0 to Length(Buf) -1 do Hex := Hex + IntToHex(Buf[i],2);
Result := HexToInt(Hex);
end;
procedure KeyStrToBuf(KeyStr:string; var Buf: TSecKey);
var i:byte; Start:byte; Hex:string;
begin
//361248f36323a11464daac2244a61d11361238046323a1f364da453334d63412
if KeyStr = '' then KeyStr := DefaultKeyString;
for i := 0 to 31 do
begin
Start := i*2 + 1;
Hex := Copy(KeyStr, Start, 2);
Buf[i] := HexToInt(Hex);
end;
end;
function Buf20ToStr(Buf: TBuf20): string;
var i: integer;
begin
Result := '';
for i := 0 to High(Buf) do
Result := Result + Chr(Buf[i]);
Result := Trim(Result);
end;
function StrToBuf20(Value: string): TBuf20;
var i: integer; Len: byte;
begin
Len := Length(Value);
if len > Length(Result) then Len := Length(Result);
for i := 1 to Len do Result[i - 1] := Ord(Value[i]);
end;
function HighLowByte(Val:byte;var LowB:byte;var HighB:byte):Boolean;
var HexVal:string;
begin
HexVal:=IntToHex(Val,2);
LowB:=HexToInt(Copy(HexVal,2,1));
HighB:=HexToInt(Copy(HexVal,1,1));
Result:=True;
end;
function IntToOct(Value: Longint; digits: Integer): string;
var
rest: Longint;
oct: string;
begin
oct := '';
while Value <> 0 do
begin
rest := Value mod 8;
Value := Value div 8;
oct := IntToStr(rest) + oct;
end;
//for i := Length(oct) + 1 to digits do
//oct := '0' + oct;
Result := oct;
end;
function BinToInt(Value: string): Integer;
var
i, iValueSize: Integer;
begin
Result := 0;
iValueSize := Length(Value);
for i := iValueSize downto 1 do
if Value[i] = '1' then Result := Result + (1 shl (iValueSize - i));
end;
function IntToBinAr(Value: Longint; Digits: Integer): ArrOfByte;
var i: Integer; Mas:ArrOfByte;
begin
for i := Digits downto 0 do
begin
if Value and (1 shl i) <> 0 then Mas[i]:=1 else Mas[i]:=0;
end;
Result := Mas;
end;
function RetrData(Value: integer; var RetrLevel: byte): byte;
var BinStr: string; Mas: ArrOfByte; i: integer; BinVal: String;
begin
Mas := IntToBinAr(Value,7);
BinStr := '';
for i :=0 to 7 do BinStr := BinStr+IntToStr(Mas[i]);
BinVal := '';
for i := 5 to 7 do BinVal := BinVal + IntToStr(Mas[i]);
Result := BinToInt(BinVal);
BinVal := '';
for i := 0 to 4 do BinVal := BinVal + IntToStr(Mas[i]);
RetrLevel := BinToInt(BinVal);
end;
function HostAndPort(Host: string; Port: word): string;
begin
Result := Host + ':' + IntToStr(Port);
end;
function Bytes16ToInt(Buf: TBuf16): Extended;
var i:integer;
begin
Result := 0;
for i := 0 to 15 do
begin
if Buf[i] = 1 then Result := Result + Power(2, i);
end;
end;
function BytesToFloat(buf: TBuf4):Single;
begin
Result := Single(buf);
end;
function BytesToBin(Val:integer): TBuf8;
var i,Rez:integer; BinStr:string;
Remain:integer;
var temp: TBuf8;
begin
//SetLength(Result,7);
for i:=0 to 7 do temp[i]:=0;
BinStr:='';
Remain := Val;
i:=0;
while Remain > 0 do
begin
Rez := Remain Div 2;
if Rez = Remain/2 then
begin
Temp[i] := 0;
Remain := Remain div 2;
end else
begin
Temp[i] := 1;
Remain := Remain div 2;
end;
i:=i+1;
end;
for i:=0 to 7 do
begin
BinStr:=BinStr+IntToStr(Temp[i]);
Result[i] := Temp[i];
end;
end;
function GetDevClass(ParDevType: word; DevType: Word): Byte;
begin
Result := 255;
if (ParDevType <> 157) and (DevType = 157) then Result := Byte(DevClassPrd);
if (ParDevType = 157) and (DevType = 157) then Result := Byte(DevClassPpk);
if DevType = 162 then Result := Byte(DevClassZone);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.