text stringlengths 14 6.51M |
|---|
namespace Sugar;
interface
type
{$IF ECHOES}
Color = public static class
public
class method colorWithRGBAPercentage(aRed, aGreen, aBlue, aAlpha: Single): {$IF WINDOWS_PHONE}System.Windows.Media.Color{$ELSEIF NETFX_CORE}Windows.UI.Color{$ELSE}System.Drawing.Color{$ENDIF};
class method colorWithRGBA256(aRed, aGreen, aBlue, aAlpha: Byte): {$IF WINDOWS_PHONE}System.Windows.Media.Color{$ELSEIF NETFX_CORE}Windows.UI.Color{$ELSE}System.Drawing.Color{$ENDIF};
end;
{$ELSEIF COOPER}
Color = public record mapped to Int64
public
class method colorWithRGBAPercentage(aRed, aGreen, aBlue, aAlpha: Single): Color;
class method colorWithRGBA256(aRed, aGreen, aBlue, aAlpha: Byte): Color;
end;
{$ELSE TOFFEE}
{$IF IOS OR TVOS}
Color = public class mapped to UIKit.UIColor
public
class method colorWithRGBAPercentage(aRed, aGreen, aBlue, aAlpha: Single): Color; mapped to colorWithRed(aRed) green(aGreen) blue(aBlue) alpha(aAlpha);
class method colorWithRGBA256(aRed, aGreen, aBlue, aAlpha: Byte): Color; mapped to colorWithRed(aRed/256.0) green(aGreen/256.0) blue(aBlue/256.0) alpha(aAlpha/256.0);
end;
{$ELSEIF WATCHOS}
Color = public class mapped to UIKit.UIColor
public
//class method colorWithRGBAPercentage(aRed, aGreen, aBlue, aAlpha: Single): Color; mapped to colorWithRed(aRed) green(aGreen) blue(aBlue) alpha(aAlpha);
//class method colorWithRGBA256(aRed, aGreen, aBlue, aAlpha: Byte): Color; mapped to colorWithRed(aRed/256.0) green(aGreen/256.0) blue(aBlue/256.0) alpha(aAlpha/256.0);
end;
{$ELSEIF OSX}
Color = public class mapped to AppKit.NSColor
public
class method colorWithRGBAPercentage(aRed, aGreen, aBlue, aAlpha: Single): Color; mapped to colorWithCalibratedRed(aRed) green(aGreen) blue(aBlue) alpha(aAlpha);
class method colorWithRGBA256(aRed, aGreen, aBlue, aAlpha: Byte): Color; mapped to colorWithCalibratedRed(aRed/256.0) green(aGreen/256.0) blue(aBlue/256.0) alpha(aAlpha/256.0);
end;
{$ENDIF}
{$ENDIF}
implementation
{$IF ECHOES}
class method Color.colorWithRGBAPercentage(aRed: Single; aGreen: Single; aBlue: Single; aAlpha: Single): {$IF WINDOWS_PHONE}System.Windows.Media.Color{$ELSEIF NETFX_CORE}Windows.UI.Color{$ELSE}System.Drawing.Color{$ENDIF};
begin
result := {$IF WINDOWS_PHONE}System.Windows.Media.Color{$ELSEIF NETFX_CORE}Windows.UI.Color{$ELSE}System.Drawing.Color{$ENDIF}.FromArgb(aAlpha*256 as Int32, aRed*256 as Int32, aGreen*256 as Int32, aBlue*256 as Int32);
end;
class method Color.colorWithRGBA256(aRed: Byte; aGreen: Byte; aBlue: Byte; aAlpha: Byte): {$IF WINDOWS_PHONE}System.Windows.Media.Color{$ELSEIF NETFX_CORE}Windows.UI.Color{$ELSE}System.Drawing.Color{$ENDIF};
begin
result := {$IF WINDOWS_PHONE}System.Windows.Media.Color{$ELSEIF NETFX_CORE}Windows.UI.Color{$ELSE}System.Drawing.Color{$ENDIF}.FromArgb(aAlpha, aRed, aGreen, aBlue);
end;
{$ELSEIF COOPER}
class method Color.colorWithRGBAPercentage(aRed: Single; aGreen: Single; aBlue: Single; aAlpha: Single): Color;
begin
result := colorWithRGBA256(aRed*256 as Byte, aGreen*256 as Byte, aBlue*256 as Byte, aAlpha*256 as Byte);
end;
class method Color.colorWithRGBA256(aRed: Byte; aGreen: Byte; aBlue: Byte; aAlpha: Byte): Color;
begin
result := (aAlpha shl 24) and (aRed shl 16) and (aGreen shl 8) and (aBlue) as Color;
end;
{$ENDIF}
end. |
unit renegade_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m6502,m6809,main_engine,controls_engine,gfx_engine,m6805,ym_3812,
rom_engine,pal_engine,sound_engine,msm5205;
function iniciar_renegade:boolean;
implementation
const
renegade_rom:array[0..1] of tipo_roms=(
(n:'na-5.ic52';l:$8000;p:$0;crc:$de7e7df4),(n:'nb-5.ic51';l:$8000;p:$8000;crc:$ba683ddf));
renegade_char:tipo_roms=(n:'nc-5.bin';l:$8000;p:$0;crc:$9adfaa5d);
renegade_snd:tipo_roms=(n:'n0-5.ic13';l:$8000;p:$8000;crc:$3587de3b);
renegade_mcu:tipo_roms=(n:'nz-5.ic97';l:$800;p:$0;crc:$32e47560);
renegade_tiles:array[0..5] of tipo_roms=(
(n:'n1-5.ic1';l:$8000;p:$0;crc:$4a9f47f3),(n:'n6-5.ic28';l:$8000;p:$8000;crc:$d62a0aa8),
(n:'n7-5.ic27';l:$8000;p:$10000;crc:$7ca5a532),(n:'n2-5.ic14';l:$8000;p:$18000;crc:$8d2e7982),
(n:'n8-5.ic26';l:$8000;p:$20000;crc:$0dba31d3),(n:'n9-5.ic25';l:$8000;p:$28000;crc:$5b621b6a));
renegade_sprites:array[0..11] of tipo_roms=(
(n:'nh-5.bin';l:$8000;p:$0;crc:$dcd7857c),(n:'nd-5.bin';l:$8000;p:$8000;crc:$2de1717c),
(n:'nj-5.bin';l:$8000;p:$10000;crc:$0f96a18e),(n:'nn-5.bin';l:$8000;p:$18000;crc:$1bf15787),
(n:'ne-5.bin';l:$8000;p:$20000;crc:$924c7388),(n:'nk-5.bin';l:$8000;p:$28000;crc:$69499a94),
(n:'ni-5.bin';l:$8000;p:$30000;crc:$6f597ed2),(n:'nf-5.bin';l:$8000;p:$38000;crc:$0efc8d45),
(n:'nl-5.bin';l:$8000;p:$40000;crc:$14778336),(n:'no-5.bin';l:$8000;p:$48000;crc:$147dd23b),
(n:'ng-5.bin';l:$8000;p:$50000;crc:$a8ee3720),(n:'nm-5.bin';l:$8000;p:$58000;crc:$c100258e));
renegade_adpcm:array[0..2] of tipo_roms=(
(n:'n3-5.ic33';l:$8000;p:$0;crc:$78fd6190),(n:'n4-5.ic32';l:$8000;p:$8000;crc:$6557564c),
(n:'n5-5.ic31';l:$8000;p:$10000;crc:$7ee43a3c));
//Dip
renegade_dip_a:array [0..6] of def_dip=(
(mask:$3;name:'Coin A';number:4;dip:((dip_val:$0;dip_name:'2C 1C'),(dip_val:$3;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(dip_val:$1;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'2C 1C'),(dip_val:$c;dip_name:'1C 1C'),(dip_val:$8;dip_name:'1C 2C'),(dip_val:$4;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$10;name:'Lives';number:2;dip:((dip_val:$10;dip_name:'1'),(dip_val:$0;dip_name:'2'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Bonus';number:2;dip:((dip_val:$20;dip_name:'30K'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$40;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Flip Screen';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
renegade_dip_b:array [0..1] of def_dip=(
(mask:$3;name:'Difficulty';number:4;dip:((dip_val:$2;dip_name:'Easy'),(dip_val:$3;dip_name:'Normal'),(dip_val:$1;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())),());
var
rom_mem:array[0..1,0..$3fff] of byte;
mcu_mem:array[0..$7ff] of byte;
adpcm_rom:array[0..$17fff] of byte;
adpcm_play:boolean;
adpcm_pos,adpcm_end:dword;
rom_bank,sound_latch:byte;
scroll_comp,scroll_x:word;
port_c_in,port_c_out,port_b_out,port_b_in,port_a_in,port_a_out:byte;
ddr_a,ddr_b,ddr_c,from_main,from_mcu:byte;
main_sent,mcu_sent:boolean;
procedure update_video_renegade;
var
f,nchar,x,y:word;
color,atrib:byte;
flip_x:boolean;
begin
for f:=0 to $3ff do begin
//Background
atrib:=memoria[$2c00+f];
color:=atrib shr 5;
if (gfx[1].buffer[f] or buffer_color[color+4]) then begin
x:=f mod 64;
y:=f div 64;
nchar:=memoria[$2800+f]+((atrib and $7) shl 8);
put_gfx_trans(x*16,y*16,nchar,(color shl 3)+192,1,1);
gfx[1].buffer[f]:=false;
end;
//Foreground
atrib:=memoria[$1c00+f];
color:=atrib shr 6;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
x:=f mod 32;
y:=f div 32;
nchar:=memoria[$1800+f]+((atrib and $3) shl 8);
put_gfx_trans(x*8,y*8,nchar,color shl 3,2,0);
gfx[0].buffer[f]:=false;
end;
end;
scroll__x(1,3,(scroll_x-scroll_comp) and $3ff);
for f:=0 to $7f do begin
y:=224-memoria[$2000+(f*4)];
if y>=16 then begin
atrib:=memoria[$2001+(f*4)];
x:=memoria[$2003+(f*4)];
nchar:=memoria[$2002+(f*4)]+((atrib and $f) shl 8);
color:=(atrib and $30) shr 1;
flip_x:=(atrib and $40)<>0;
if (atrib and $80)<>0 then begin
nchar:=nchar and $ffe;
put_gfx_sprite_diff(nchar+1,color+128,flip_x,false,2,0,16);
put_gfx_sprite_diff(nchar,color+128,flip_x,false,2,0,0);
actualiza_gfx_sprite_size(x,y,3,16,32);
end else begin
put_gfx_sprite(nchar,color+128,flip_x,false,2);
actualiza_gfx_sprite(x,y+16,3,2);
end;
end;
end;
actualiza_trozo(0,0,256,256,2,0,0,256,256,3);
actualiza_trozo_final(8,0,240,240,3);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
end;
procedure eventos_renegade;
begin
if event.arcade then begin
//P1
if arcade_input.right[0] then marcade.in0:=marcade.in0 and $fe else marcade.in0:=marcade.in0 or 1;
if arcade_input.left[0] then marcade.in0:=marcade.in0 and $fd else marcade.in0:=marcade.in0 or 2;
if arcade_input.up[0] then marcade.in0:=marcade.in0 and $fb else marcade.in0:=marcade.in0 or 4;
if arcade_input.down[0] then marcade.in0:=marcade.in0 and $f7 else marcade.in0:=marcade.in0 or 8;
if arcade_input.but0[0] then marcade.in0:=marcade.in0 and $ef else marcade.in0:=marcade.in0 or $10;
if arcade_input.but1[0] then marcade.in0:=marcade.in0 and $df else marcade.in0:=marcade.in0 or $20;
if arcade_input.but2[0] then marcade.dswb:=marcade.dswb and $fb else marcade.dswb:=marcade.dswb or $4;
if arcade_input.start[0] then marcade.in0:=marcade.in0 and $bf else marcade.in0:=marcade.in0 or $40;
if arcade_input.start[1] then marcade.in0:=marcade.in0 and $7f else marcade.in0:=marcade.in0 or $80;
//p2
if arcade_input.right[1] then marcade.in1:=marcade.in1 and $fe else marcade.in1:=marcade.in1 or 1;
if arcade_input.left[1] then marcade.in1:=marcade.in1 and $fd else marcade.in1:=marcade.in1 or 2;
if arcade_input.up[1] then marcade.in1:=marcade.in1 and $fb else marcade.in1:=marcade.in1 or 4;
if arcade_input.down[1] then marcade.in1:=marcade.in1 and $f7 else marcade.in1:=marcade.in1 or 8;
if arcade_input.but0[1] then marcade.in1:=marcade.in1 and $ef else marcade.in1:=marcade.in1 or $10;
if arcade_input.but1[1] then marcade.in1:=marcade.in1 and $df else marcade.in1:=marcade.in1 or $20;
if arcade_input.but2[1] then marcade.dswb:=marcade.dswb and $f7 else marcade.dswb:=marcade.dswb or $8;
if arcade_input.coin[0] then begin
marcade.in1:=marcade.in1 and $bf;
m6502_0.change_irq(ASSERT_LINE);
end else begin
marcade.in1:=marcade.in1 or $40;
if arcade_input.coin[1] then begin
marcade.in1:=marcade.in1 and $7f;
m6502_0.change_irq(ASSERT_LINE);
end else begin
marcade.in1:=marcade.in1 or $80;
m6502_0.change_irq(CLEAR_LINE);
end;
end;
end;
end;
procedure principal_renegade;
var
frame_m,frame_s,frame_mcu:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m6502_0.tframes;
frame_s:=m6809_0.tframes;
frame_mcu:=m6805_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
m6502_0.run(frame_m);
frame_m:=frame_m+m6502_0.tframes-m6502_0.contador;
//Sound
m6809_0.run(frame_s);
frame_s:=frame_s+m6809_0.tframes-m6809_0.contador;
//mcu
m6805_0.run(frame_mcu);
frame_mcu:=frame_mcu+m6805_0.tframes-m6805_0.contador;
case f of
60:marcade.dswb:=marcade.dswb and $bf;
239:begin
update_video_renegade;
m6502_0.change_nmi(ASSERT_LINE);
marcade.dswb:=marcade.dswb or $40;
end;
end;
end;
eventos_renegade;
video_sync;
end;
end;
function getbyte_renegade(direccion:word):byte;
begin
case direccion of
0..$1fff,$2800..$2fff,$8000..$ffff:getbyte_renegade:=memoria[direccion];
$2000..$27ff:getbyte_renegade:=memoria[$2000+(direccion and $1ff)];
$3000..$31ff:getbyte_renegade:=buffer_paleta[direccion and $1ff];
$3800:getbyte_renegade:=marcade.in0;
$3801:getbyte_renegade:=marcade.in1;
$3802:getbyte_renegade:=marcade.dswb or $10*byte(not(main_sent)) or $20*byte(not(mcu_sent));
$3803:getbyte_renegade:=marcade.dswa;
$3804:begin
mcu_sent:=false;
getbyte_renegade:=from_mcu;
end;
$3805:m6805_0.change_reset(PULSE_LINE);
$4000..$7fff:getbyte_renegade:=rom_mem[rom_bank,direccion and $3fff];
end;
end;
procedure putbyte_renegade(direccion:word;valor:byte);
procedure cambiar_color(dir:byte);
var
tmp_color:byte;
color:tcolor;
begin
tmp_color:=buffer_paleta[dir];
color.g:=pal4bit(tmp_color shr 4);
color.r:=pal4bit(tmp_color);
tmp_color:=buffer_paleta[dir+$100];
color.b:=pal4bit(tmp_color);
set_pal_color(color,dir);
case dir of
$0..$1f:buffer_color[dir shr 3]:=true;
$c0..$ff:buffer_color[((dir shr 3) and 7)+4]:=true;
end;
end;
begin
case direccion of
0..$17ff:memoria[direccion]:=valor;
$1800..$1fff:if memoria[direccion]<>valor then begin
gfx[0].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$2000..$27ff:memoria[$2000+(direccion and $1ff)]:=valor;
$2800..$2fff:if memoria[direccion]<>valor then begin
gfx[1].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$3000..$31ff:if buffer_paleta[direccion and $1ff]<>valor then begin
buffer_paleta[direccion and $1ff]:=valor;
cambiar_color(direccion and $ff);
end;
$3800:scroll_x:=(scroll_x and $ff00) or valor;
$3801:scroll_x:=(scroll_x and $ff) or (valor shl 8);
$3802:begin
sound_latch:=valor;
m6809_0.change_irq(HOLD_LINE);
end;
$3803:if ((valor and 1)=0) then begin
scroll_comp:=0;
main_screen.flip_main_screen:=true;
end else begin
scroll_comp:=256;
main_screen.flip_main_screen:=false;
end;
$3804:begin
from_main:=valor;
main_sent:=true;
m6805_0.irq_request(0,ASSERT_LINE);
end;
$3805:rom_bank:=valor and 1;
$3806:m6502_0.change_nmi(CLEAR_LINE);
$3807:; //Coin
$4000..$ffff:; //ROM
end;
end;
function getbyte_snd_renegade(direccion:word):byte;
begin
case direccion of
0..$fff,$8000..$ffff:getbyte_snd_renegade:=mem_snd[direccion];
$1000:getbyte_snd_renegade:=sound_latch;
$2800:getbyte_snd_renegade:=ym3812_0.status;
end;
end;
procedure putbyte_snd_renegade(direccion:word;valor:byte);
begin
case direccion of
0..$fff:mem_snd[direccion]:=valor;
$1800:begin //adpcm start
msm5205_0.reset_w(0);
adpcm_play:=true;
end;
$2000:begin //adpcm addr
case (valor and $1c) of
$18:adpcm_pos:=0*$8000*2; // 110 -> ic33
$14:adpcm_pos:=1*$8000*2; // 101 -> ic32
$0c:adpcm_pos:=2*$8000*2; // 011 -> ic31
else begin
adpcm_pos:=0;
adpcm_end:=0;
exit;
end;
end;
// bits 0-1 are a13-a14
adpcm_pos:= adpcm_pos or ((valor and $03)*$2000*2);
// a0-a12 are driven by a binary counter; playback ends when it rolls over
adpcm_end:=adpcm_pos+$2000*2;
end;
$2800:ym3812_0.control(valor);
$2801:ym3812_0.write(valor);
$3000:begin //adpcm stop
msm5205_0.reset_w(1);
adpcm_play:=false;
end;
$8000..$ffff:; //ROM
end;
end;
function renegade_mcu_getbyte(direccion:word):byte;
begin
direccion:=direccion and $7ff;
case direccion of
0:renegade_mcu_getbyte:=(port_a_out and ddr_a) or (port_a_in and not(ddr_a));
1:renegade_mcu_getbyte:=(port_b_out and ddr_b) or (port_b_in and not(ddr_b));
2:begin
port_c_in:=$1*byte(main_sent) or $2*byte(not(mcu_sent));
renegade_mcu_getbyte:=(port_c_out and ddr_c) or (port_c_in and not(ddr_c));
end;
$10..$7ff:renegade_mcu_getbyte:=mcu_mem[direccion];
end;
end;
procedure renegade_mcu_putbyte(direccion:word;valor:byte);
begin
direccion:=direccion and $7ff;
case direccion of
0:port_a_out:=valor;
1:begin
if (((ddr_b and $02)<>0) and ((not(valor) and $02)<>0) and ((port_b_out and $2)<>0)) then begin
port_a_in:=from_main;
if main_sent then m6805_0.irq_request(0,CLEAR_LINE);
main_sent:=false;
end;
if (((ddr_b and $04)<>0) and ((valor and $04)<>0) and ((not(port_b_out) and $04)<>0)) then begin
from_mcu:=port_a_out;
mcu_sent:=true;
end;
port_b_out:=valor;
end;
2:port_c_out:=valor;
4:ddr_a:=valor;
5:ddr_b:=valor;
6:ddr_c:=valor;
$10..$7f:mcu_mem[direccion]:=valor;
$80..$7ff:; //ROM
end;
end;
procedure renegade_sound_update;
begin
ym3812_0.update;
end;
procedure snd_irq(irqstate:byte);
begin
m6809_0.change_firq(irqstate);
end;
procedure snd_adpcm;
var
data:byte;
begin
if not(adpcm_play) then exit;
if (adpcm_pos>=adpcm_end) then begin
msm5205_0.reset_w(1);
adpcm_play:=false;
m6809_0.change_nmi(PULSE_LINE);
end else begin
data:=adpcm_rom[adpcm_pos shr 1];
if (adpcm_pos and 1)<>0 then msm5205_0.data_w(data and $f)
else msm5205_0.data_w(data shr 4);
adpcm_pos:=adpcm_pos+1;
end;
end;
//Main
procedure reset_renegade;
begin
m6502_0.reset;
m6809_0.reset;
m6805_0.reset;
ym3812_0.reset;
msm5205_0.reset_w(1);
marcade.in0:=$ff;
marcade.in1:=$ff;
rom_bank:=0;
sound_latch:=0;
scroll_x:=0;
port_c_in:=0;
port_c_out:=0;
port_b_out:=0;
port_b_in:=0;
port_a_in:=0;
port_a_out:=0;
ddr_a:=0;
ddr_b:=0;
ddr_c:=0;
from_main:=0;
from_mcu:=0;
main_sent:=false;
mcu_sent:=false;
scroll_comp:=256;
adpcm_play:=false;
adpcm_pos:=0;
adpcm_end:=0;
end;
function iniciar_renegade:boolean;
const
pc_x:array[0..7] of dword=(1, 0, 65, 64, 129, 128, 193, 192);
pt_x:array[0..15] of dword=(3, 2, 1, 0, 16*8+3, 16*8+2, 16*8+1, 16*8+0,
32*8+3,32*8+2 ,32*8+1 ,32*8+0 ,48*8+3 ,48*8+2 ,48*8+1 ,48*8+0);
pt_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8);
var
f:byte;
memoria_temp:array[0..$5ffff] of byte;
begin
llamadas_maquina.bucle_general:=principal_renegade;
llamadas_maquina.reset:=reset_renegade;
iniciar_renegade:=false;
iniciar_audio(false);
screen_init(1,1024,256);
screen_mod_scroll(1,1024,256,1023,256,256,255);
screen_init(2,256,256,true);
screen_init(3,256,256,false,true);
iniciar_video(240,240);
//Main CPU
m6502_0:=cpu_m6502.create(1500000,256,TCPU_M6502);
m6502_0.change_ram_calls(getbyte_renegade,putbyte_renegade);
//Sound CPU
m6809_0:=cpu_m6809.Create(1500000,256,TCPU_M6809);
m6809_0.change_ram_calls(getbyte_snd_renegade,putbyte_snd_renegade);
m6809_0.init_sound(renegade_sound_update);
//MCU CPU
m6805_0:=cpu_m6805.create(3000000,256,tipo_m68705);
m6805_0.change_ram_calls(renegade_mcu_getbyte,renegade_mcu_putbyte);
//Sound Chip
ym3812_0:=ym3812_chip.create(YM3526_FM,3000000);
ym3812_0.change_irq_calls(snd_irq);
msm5205_0:=MSM5205_chip.create(12000000 div 32,MSM5205_S48_4B,1,snd_adpcm);
if not(roms_load(@adpcm_rom,renegade_adpcm)) then exit;
//cargar roms
if not(roms_load(@memoria_temp,renegade_rom)) then exit;
copymemory(@memoria[$8000],@memoria_temp[$8000],$8000);
copymemory(@rom_mem[0,0],@memoria_temp[$0],$4000);
copymemory(@rom_mem[1,0],@memoria_temp[$4000],$4000);
//cargar roms audio
if not(roms_load(@mem_snd,renegade_snd)) then exit;
//cargar roms mcu
if not(roms_load(@mcu_mem,renegade_mcu)) then exit;
//Cargar chars
if not(roms_load(@memoria_temp,renegade_char)) then exit;
init_gfx(0,8,8,$400);
gfx[0].trans[0]:=true;
gfx_set_desc_data(3,0,32*8,2,4,6);
convert_gfx(0,0,@memoria_temp,@pc_x,@pt_y,false,false);
//Cargar tiles
if not(roms_load(@memoria_temp,renegade_tiles)) then exit;
init_gfx(1,16,16,$800);
for f:=0 to 1 do begin
gfx_set_desc_data(3,8,64*8,4,$8000*8+0,$8000*8+4);
convert_gfx(1,f*$400*16*16,@memoria_temp[f*$18000],@pt_x,@pt_y,false,false);
gfx_set_desc_data(3,8,64*8,0,$c000*8+0,$c000*8+4);
convert_gfx(1,(f*$400*16*16)+($100*16*16),@memoria_temp[f*$18000],@pt_x,@pt_y,false,false);
gfx_set_desc_data(3,8,64*8,$4000*8+4,$10000*8+0,$10000*8+4);
convert_gfx(1,(f*$400*16*16)+($200*16*16),@memoria_temp[f*$18000],@pt_x,@pt_y,false,false);
gfx_set_desc_data(3,8,64*8,$4000*8+0,$14000*8+0,$14000*8+4);
convert_gfx(1,(f*$400*16*16)+($300*16*16),@memoria_temp[f*$18000],@pt_x,@pt_y,false,false);
end;
//sprites
if not(roms_load(@memoria_temp,renegade_sprites)) then exit;
init_gfx(2,16,16,$1000);
gfx[2].trans[0]:=true;
for f:=0 to 3 do begin
gfx_set_desc_data(3,16,64*8,4,$8000*8+0,$8000*8+4);
convert_gfx(2,f*$400*16*16,@memoria_temp[f*$18000],@pt_x,@pt_y,false,false);
gfx_set_desc_data(3,16,64*8,0,$c000*8+0,$c000*8+4);
convert_gfx(2,(f*$400*16*16)+($100*16*16),@memoria_temp[f*$18000],@pt_x,@pt_y,false,false);
gfx_set_desc_data(3,16,64*8,$4000*8+4,$10000*8+0,$10000*8+4);
convert_gfx(2,(f*$400*16*16)+($200*16*16),@memoria_temp[f*$18000],@pt_x,@pt_y,false,false);
gfx_set_desc_data(3,16,64*8,$4000*8+0,$14000*8+0,$14000*8+4);
convert_gfx(2,(f*$400*16*16)+($300*16*16),@memoria_temp[f*$18000],@pt_x,@pt_y,false,false);
end;
//Dip
marcade.dswa:=$bf;
marcade.dswb:=$8f;
marcade.dswa_val:=@renegade_dip_a;
marcade.dswb_val:=@renegade_dip_b;
//final
reset_renegade;
iniciar_renegade:=true;
end;
end.
|
unit tmsXlsMessages;
{$INCLUDE ..\FLXCOMPILER.INC}
{$INCLUDE ..\FLXCONFIG.INC}
interface
uses SysUtils,
{$IFDEF FLX_NEEDSVARIANTS} variants,{$ENDIF}
tmsUFlxMessages;
resourcestring
{$IFDEF SPANISH}
{$INCLUDE XlsSpanish.inc}
{$ELSE}
{$IFDEF FRENCH}
{$INCLUDE XlsFrench.inc}
{$ELSE}
{$IFDEF ITALIAN}
{$INCLUDE XlsItalian.inc}
{$ELSE}
{$IFDEF ROMANIAN}
{$INCLUDE XlsRomanian.inc}
{$ELSE}
{$IFDEF PORTUGUESEBR}
{$INCLUDE XlsPortugueseBR.inc}
{$ELSE}
{$IFDEF CHINESE}
{$INCLUDE XlsChinese.inc}
{$ELSE}
{$IFDEF RUSSIAN}
{$INCLUDE XlsRussian.inc}
{$ELSE}
{$IFDEF GERMAN}
{$INCLUDE XlsGerman.inc}
{$ELSE}
{$IFDEF POLISH}
{$INCLUDE XlsPolish.inc}
{$ELSE}
{$IFDEF FINNISH}
{$INCLUDE XlsFinnish.inc}
{$ELSE}
{$INCLUDE XlsEnglish.inc}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
WorkbookStrS='Workbook';
ErrInvalidStream = 'Invalid OLE Stream operation on stream: "%s"';
ErrEofReached = 'End of stream reached with %d bytes left to read';
ErrInvalidPropertySector = 'FlexCel can''t read the properties of this file.';
//Error Codes
xlerr_Null = '#NULL!';
xlerr_Div0 = '#DIV/0!';
xlerr_Value = '#VALUE!';
xlerr_Ref = '#REF!';
xlerr_Name = '#NAME?';
xlerr_Num = '#NUM!';
xlerr_NA = '#N/A';
//MADE: Traducir mensajes
const
xlerrcode_Null = $00;
xlerrcode_Div0 = $07;
xlerrcode_Value = $0F;
xlerrcode_Ref = $17;
xlerrcode_Name = $1D;
xlerrcode_Num = $24;
xlerrcode_NA = $2A;
MaxRecordDataSize=8223;
MaxExternSheetDataSize= 8220; // 1370 records of 6 bytes each, and 2 bytes for the count
MaxHPageBreaks=1025;
MaxVPageBreaks=1025;
type
ArrayOfByte = array[0..maxint div 2] of byte;
PArrayOfByte=^ArrayOfByte;
TRecordHeader = packed record
Id: word;
Size: word;
end;
PRecordHeader= ^TRecordHeader;
EExcelException=class (Exception)
end;
TGetSheet=function(const aSheetRef: word): integer of object;
TSheetInfo= record
InsSheet, FormulaSheet: integer;
GetSheet, SetSheet: TGetSheet;
Names: TObject;
end;
const
Max_Columns = 255;
Max_Rows = 65535; //0 based
MaxSheets = 65000; //some negative values are reserved
xlr_BofVersion = $0600;
xlb_Globals = $0005;
xlb_Worksheet = $0010;
xlb_Chart = $0020;
xlr_INTEGER = $0002;
xlr_FORMULA = $0006;
xlr_EOF = $000A;
xlr_CALCCOUNT = $000C;
xlr_CALCMODE = $000D;
xlr_PRECISION = $000E;
xlr_REFMODE = $000F;
xlr_DELTA = $0010;
xlr_ITERATION = $0011;
xlr_PROTECT = $0012;
xlr_PASSWORD = $0013;
xlr_HEADER = $0014;
xlr_FOOTER = $0015;
xlr_EXTERNCOUNT = $0016;
xlr_EXTERNSHEET = $0017;
xlr_NAME = $0018;
xlr_WINDOWPROTECT = $0019;
xlr_VERTICALPAGEBREAKS = $001A;
xlr_HORIZONTALPAGEBREAKS = $001B;
xlr_NOTE = $001C;
xlr_SELECTION = $001D;
xlr_FORMATCOUNT = $001F;
xlr_COLUMNDEFAULT = $0020;
xlr_1904 = $0022;
xlr_COLWIDTH = $0024;
xlr_LEFTMARGIN = $0026;
xlr_RIGHTMARGIN = $0027;
xlr_TOPMARGIN = $0028;
xlr_BOTTOMMARGIN = $0029;
xlr_PRINTHEADERS = $002A;
xlr_PRINTGRIDLINES = $002B;
xlr_FILEPASS = $002F;
xlr_PRINTSIZE = $0033;
xlr_CONTINUE = $003C;
xlr_WINDOW1 = $003D;
xlr_BACKUP = $0040;
xlr_PANE = $0041;
xlr_CODEPAGE = $0042;
xlr_IXFE = $0044;
xlr_PLS = $004D;
xlr_DCON = $0050;
xlr_DCONREF = $0051;
xlr_DCONNAME = $0053;
xlr_DEFCOLWIDTH = $0055;
xlr_BUILTINFMTCNT = $0056;
xlr_XCT = $0059;
xlr_CRN = $005A;
xlr_FILESHARING = $005B;
xlr_WRITEACCESS = $005C;
xlr_OBJ = $005D;
xlr_UNCALCED = $005E;
xlr_SAFERECALC = $005F;
xlr_TEMPLATE = $0060;
xlr_OBJPROTECT = $0063;
xlr_COLINFO = $007D;
xlr_IMDATA = $007F;
xlr_GUTS = $0080;
xlr_WSBOOL = $0081;
xlr_GRIDSET = $0082;
xlr_HCENTER = $0083;
xlr_VCENTER = $0084;
xlr_BOUNDSHEET = $0085;
xlr_WRITEPROT = $0086;
xlr_ADDIN = $0087;
xlr_EDG = $0088;
xlr_PUB = $0089;
xlr_COUNTRY = $008C;
xlr_HIDEOBJ = $008D;
xlr_BUNDLESOFFSET = $008E;
xlr_BUNDLEHEADER = $008F;
xlr_SORT = $0090;
xlr_SUB = $0091;
xlr_PALETTE = $0092;
xlr_LHRECORD = $0094;
xlr_LHNGRAPH = $0095;
xlr_SOUND = $0096;
xlr_LPR = $0098;
xlr_STANDARDWIDTH = $0099;
xlr_FNGROUPNAME = $009A;
xlr_FILTERMODE = $009B;
xlr_FNGROUPCOUNT = $009C;
xlr_AUTOFILTERINFO = $009D;
xlr_AUTOFILTER = $009E;
xlr_SCL = $00A0;
xlr_SETUP = $00A1;
xlr_COORDLIST = $00A9;
xlr_GCW = $00AB;
xlr_SCENMAN = $00AE;
xlr_SCENARIO = $00AF;
xlr_SXVIEW = $00B0;
xlr_SXVD = $00B1;
xlr_SXVI = $00B2;
xlr_SXIVD = $00B4;
xlr_SXLI = $00B5;
xlr_SXPI = $00B6;
xlr_DOCROUTE = $00B8;
xlr_RECIPNAME = $00B9;
xlr_MULRK = $00BD;
xlr_MULBLANK = $00BE;
xlr_MMS = $00C1;
xlr_ADDMENU = $00C2;
xlr_DELMENU = $00C3;
xlr_SXDI = $00C5;
xlr_SXDB = $00C6;
xlr_SXFIELD = $00C7;
xlr_SXINDEXLIST = $00C8;
xlr_SXDOUBLE = $00C9;
xlr_SXSTRING = $00CD;
xlr_SXDATETIME = $00CE;
xlr_SXTBL = $00D0;
xlr_SXTBRGITEM = $00D1;
xlr_SXTBPG = $00D2;
xlr_OBPROJ = $00D3;
xlr_SXIDSTM = $00D5;
xlr_RSTRING = $00D6;
xlr_DBCELL = $00D7;
xlr_BOOKBOOL = $00DA;
xlr_SXEXTPARAMQRY = $00DC;
xlr_SCENPROTECT = $00DD;
xlr_OLESIZE = $00DE;
xlr_UDDESC = $00DF;
xlr_INTERFACEHDR = $00E1;
xlr_INTERFACEEND = $00E2;
xlr_SXVS = $00E3;
xlr_CELLMERGING = $00E5;
xlr_BITMAP = $00E9;
xlr_MSODRAWINGGROUP = $00EB;
xlr_MSODRAWING = $00EC;
xlr_MSODRAWINGSELECTION = $00ED;
xlr_PHONETIC = $00EF;
xlr_SXRULE = $00F0;
xlr_SXEX = $00F1;
xlr_SXFILT = $00F2;
xlr_SXNAME = $00F6;
xlr_SXSELECT = $00F7;
xlr_SXPAIR = $00F8;
xlr_SXFMLA = $00F9;
xlr_SXFORMAT = $00FB;
xlr_SST = $00FC;
xlr_LABELSST = $00FD;
xlr_EXTSST = $00FF;
xlr_SXVDEX = $0100;
xlr_SXFORMULA = $0103;
xlr_SXDBEX = $0122;
xlr_CHTRINSERT = $0137;
xlr_CHTRINFO = $0138;
xlr_CHTRCELLCONTENT = $013B;
xlr_TABID = $013D;
xlr_CHTRMOVERANGE = $0140;
xlr_CHTRINSERTTAB = $014D;
xlr_USESELFS = $0160;
xlr_XL5MODIFY = $0162;
xlr_CHTRHEADER = $0196;
xlr_USERBVIEW = $01A9;
xlr_USERSVIEWBEGIN = $01AA;
xlr_USERSVIEWEND = $01AB;
xlr_QSI = $01AD;
xlr_SUPBOOK = $01AE;
xlr_PROT4REV = $01AF;
xlr_DSF = $0161;
xlr_CONDFMT = $01B0;
xlr_CF = $01B1;
xlr_DVAL = $01B2;
xlr_DCONBIN = $01B5;
xlr_TXO = $01B6;
xlr_REFRESHALL = $01B7;
xlr_HLINK = $01B8;
xlr_CODENAME = $01BA;
xlr_SXFDBTYPE = $01BB;
xlr_PROT4REVPASS = $01BC;
xlr_DV = $01BE;
xlr_XL9FILE = $01C0;
xlr_RECALCID = $01C1;
xlr_DIMENSIONS = $0200;
xlr_BLANK = $0201;
xlr_NUMBER = $0203;
xlr_LABEL = $0204;
xlr_BOOLERR = $0205;
xlr_STRING = $0207;
xlr_ROW = $0208;
xlr_INDEX = $020B;
xlr_ARRAY = $0221;
xlr_EXTERNNAME = $0023;
xlr_EXTERNNAME2 = $0223;
xlr_DEFAULTROWHEIGHT = $0225;
xlr_FONT = $0031;
xlr_TABLE = $0236;
xlr_WINDOW2 = $023E;
xlr_RK = $027E;
xlr_STYLE = $0293;
xlr_FORMAT = $041E;
xlr_XF = $00E0;
xlr_SHRFMLA = $04BC;
xlr_SCREENTIP = $0800;
xlr_WEBQRYSETTINGS = $0803;
xlr_WEBQRYTABLES = $0804;
xlr_BOF = $0809;
xlr_UNITS = $1001;
xlr_ChartChart = $1002;
xlr_ChartSeries = $1003;
xlr_ChartDataformat = $1006;
xlr_ChartLineformat = $1007;
xlr_ChartMarkerformat = $1009;
xlr_ChartAreaformat = $100A;
xlr_ChartPieformat = $100B;
xlr_ChartAttachedlabel = $100C;
xlr_ChartSeriestext = $100D;
xlr_ChartChartformat = $1014;
xlr_ChartLegend = $1015;
xlr_ChartSerieslist = $1016;
xlr_ChartBar = $1017;
xlr_ChartLine = $1018;
xlr_ChartPie = $1019;
xlr_ChartArea = $101A;
xlr_ChartScatter = $101B;
xlr_ChartChartline = $101C;
xlr_ChartAxis = $101D;
xlr_ChartTick = $101E;
xlr_ChartValuerange = $101F;
xlr_ChartCatserrange = $1020;
xlr_ChartAxislineformat = $1021;
xlr_ChartFormatlink = $1022;
xlr_ChartDefaulttext = $1024;
xlr_ChartText = $1025;
xlr_ChartFontx = $1026;
xlr_ChartObjectLink = $1027;
xlr_ChartFrame = $1032;
xlr_BEGIN = $1033;
xlr_END = $1034;
xlr_ChartPlotarea = $1035;
xlr_Chart3D = $103A;
xlr_ChartPicf = $103C;
xlr_ChartDropbar = $103D;
xlr_ChartRadar = $103E;
xlr_ChartSurface = $103F;
xlr_ChartRadararea = $1040;
xlr_ChartAxisparent = $1041;
xlr_ChartLegendxn = $1043;
xlr_ChartShtprops = $1044;
xlr_ChartSertocrt = $1045;
xlr_ChartAxesused = $1046;
xlr_ChartSbaseref = $1048;
xlr_ChartSerparent = $104A;
xlr_ChartSerauxtrend = $104B;
xlr_ChartIfmt = $104E;
xlr_ChartPos = $104F;
xlr_ChartAlruns = $1050;
xlr_ChartAI = $1051;
xlr_ChartSerauxerrbar = $105B;
xlr_ChartClrClient = $105C;
xlr_ChartSerfmt = $105D;
xlr_Chart3DDataFormat = $105F;
xlr_ChartFbi = $1060;
xlr_ChartBoppop = $1061;
xlr_ChartAxcext = $1062;
xlr_ChartDat = $1063;
xlr_ChartPlotgrowth = $1064;
xlr_ChartSiindex = $1065;
xlr_ChartGelframe = $1066;
xlr_ChartBoppcustom = $1067;
//------------------------------------Tokens-------------------------//
//Globals
tk_Arrayformula = $1;
tk_Table = $2;
tk_BinaryOps = [$3..$11];
tk_UnaryOps = [$12..$15];
//Constants
tk_MissArg = $16;
tk_Str = $17;
tk_Attr = $19;
tk_Err = $1C;
tk_Bool = $1D;
tk_Int = $1E;
tk_Num = $1F;
tk_MemFunc = $29;
//Func
tk_Func = [$21, $41, $61];
tk_FuncVar = [$22, $42, $62];
//Operand
tk_Array = [$20, $40, $60];
tk_Name = [$23, $43, $63];
tk_Ref = [$24, $44, $64];
tk_Area = [$25, $45, $65];
tk_RefErr = [$2A, $4A, $6A];
tk_AreaErr = [$2B, $4B, $6B];
tk_RefN = [$2C, $4C, $6C]; //Reference relative to the current row. Can be < 0
tk_AreaN = [$2D, $4D, $6D]; //Area relative to the current row
tk_NameX = [$39, $59, $79];
tk_Ref3D = [$3A, $5A, $7A];
tk_Area3D = [$3B, $5B, $7B];
tk_Ref3DErr = [$3C, $5C, $7C];
tk_Area3DErr = [$3D, $5D, $7D];
tk_RefToRefErr = $2A - $24;
tk_AreaToAreaErr = $2B - $25;
tk_Ref3DToRef3DErr = $3C - $3A;
tk_Area3DToArea3DErr = $3D - $3B;
tk_Operand=
tk_Array+
tk_Name+
tk_Ref+
tk_Area+
tk_RefErr+
tk_AreaErr+
tk_RefN+
tk_AreaN+
tk_NameX+
tk_Ref3D+
tk_Area3D+
tk_Ref3DErr+
tk_Area3DErr;
//-------------------------------------Object Types--------------------------//
ftEnd = $0000;
ftMacro = $0004;
ftButton = $0005;
ftGmo = $0006;
ftCf = $0007;
ftPioGrbit = $0008;
ftPictFmla = $0009;
ftCbls = $000A;
ftRbo = $000B;
ftSbs = $000C;
ftNts = $000D;
ftSbsFmla = $000E;
ftGboData = $000F;
ftEdoData = $0010;
ftRboData = $0011;
ftCblsData = $0012;
ftLbsData = $0013;
ftCblsFmla = $0014;
ftCmo = $0015;
//-------------------------------------Cmo Object Types-----------------------//
xlcmo_Group = $00;
xlcmo_Line = $01;
xlcmo_Rectangle = $02;
xlcmo_Oval = $03;
xlcmo_Arc = $04;
xlcmo_Chart = $05;
xlcmo_TextBox = $06;
xlcmo_Button = $07;
xlcmo_Picture = $08;
xlcmo_Polygon = $09;
xlcmo_CheckBox = $0B;
xlcmo_Option = $0C;
xlcmo_Edit = $0D;
xlcmo_Label = $0E;
xlcmo_Dialog = $0F;
xlcmo_Spinner = $10;
xlcmo_Scroll = $11;
xlcmo_List = $12;
xlcmo_Group1 = $13;
xlcmo_Combo = $14;
xlcmo_Comment = $19;
xlcmo_MSDrawingx = $1E;
// Escher records
MsofbtDggContainer = $F000;
MsofbtDgg = $F006;
MsofbtCLSID = $F016;
MsofbtOPT = $F00B;
MsofbtColorMRU = $F11A;
MsofbtSplitMenuColors = $F11E;
MsofbtBstoreContainer = $F001;
MsofbtBSE = $F007;
MsofbtDgContainer = $F002;
MsofbtDg = $F008;
MsofbtRegroupItem = $F118;
MsofbtColorScheme = $F120;
MsofbtSpgrContainer = $F003;
MsofbtSpContainer = $F004;
MsofbtSpgr = $F009;
MsofbtSp = $F00A;
MsofbtTextbox = $F00C;
MsofbtClientTextbox = $F00D;
MsofbtAnchor = $F00E;
MsofbtChildAnchor = $F00F;
MsofbtClientAnchor = $F010;
MsofbtClientData = $F011;
MsofbtOleObject = $F11F;
MsofbtDeletedPspl = $F11D;
MsofbtSolverContainer = $F005;
MsofbtConnectorRule = $F012;
MsofbtAlignRule = $F013;
MsofbtArcRule = $F014;
MsofbtClientRule = $F015;
MsofbtCalloutRule = $F017;
MsofbtSelection = $F119;
//Image types
msobiUNKNOWN = 0;
msobiWMF = $216; // Metafile header then compressed WMF
msobiEMF = $3D4; // Metafile header then compressed EMF
msobiPICT = $542; // Metafile header then compressed PICT
msobiPNG = $6E0; // One byte tag then PNG data
msobiJFIF = $46A; // One byte tag then JFIF data
msobiJPEG = msobiJFIF;
msobiDIB = $7A8; // One byte tag then DIB data
msobiClient=$800; // Clients should set this bit
msoblipERROR = 0; // An error occured during loading
msoblipUNKNOWN = 1; // An unknown blip type
msoblipEMF = 2; // Windows Enhanced Metafile
msoblipWMF = 3; // Windows Metafile
msoblipPICT = 4; // Macintosh PICT
msoblipJPEG = 5; // JFIF
msoblipPNG = 6; // PNG
msoblipDIB = 7; // Windows DIB
XlsImgConv: array[TXlsImgTypes] of byte = (msoblipEMF, msoblipWMF, msoblipJPEG, msoblipPNG, msoblipDIB, msoblipUNKNOWN);
XlsBlipHeaderConv: array[TXlsImgTypes] of Word=($F01A, $F01B, $F01D, $F01E, $F01F, $F01A-1);
XlsBlipSignConv: array[TXlsImgTypes] of Word=(msobiEMF, msobiWMF, msobiJPEG, msobiPNG, msobiDIB, msobiUNKNOWN);
procedure IncMax(var X: word ; N, Max: Longint );
procedure IncMaxMin(var X: word ; N, Max, Min: Longint );
procedure IncByte( const Pdata: PArrayOfByte; const tPos: integer; const Offset: integer; const Max: integer);
procedure IncWord( const Pdata: PArrayOfByte; const tPos: integer; const Offset: integer; const Max: integer);
function GetWord(const Pdata: PArrayOfByte; const tPos: integer): word;
procedure SetWord(const Pdata: PArrayOfByte; const tPos: integer; const number: Word);
procedure IncLongWord( const Pdata: PArrayOfByte; const tPos: integer; const Offset: int64);
function GetLongWord(const Pdata: PArrayOfByte; const tPos: integer): LongWord;
procedure SetLongWord(const Pdata: PArrayOfByte; const tPos: integer; const number: LongWord);
//These functions do not take Continue records. use them with care, only where we are sure we don't have continues
function GetStrLen(const Length16Bit: boolean ;const Pdata: PArrayOfByte; const tPos: integer; const UseExtStrLen: boolean; const ExtStrLen: LongWord): int64;
procedure GetSimpleString(const Length16Bit: boolean ;const Pdata: PArrayOfByte; const tPos: integer;const UseExtStrLen: boolean; const ExtStrLen: LongWord; var St: UTF16String; var StSize: integer);
function IsWide(const W: UTF16String): boolean;
function WideStringToStringNoCodePage(const W: UTF16String): AnsiString;
function StringToWideStringNoCodePage(const s: AnsiString): UTF16String;
procedure CompressBestUnicode(const w: UTF16String; const PData: PArrayOfByte; const PDataPos: integer);
type
pWord=^Word;
pLongWord=^LongWord;
implementation
procedure IncWord( const Pdata: PArrayOfByte; const tPos: integer; const Offset: integer; const Max: integer);
var
w: int64;
begin
w:=Pdata^[tPos] or (PData^[tPos+1] shl 8);
inc(w, Offset);
if (w<0) or (w>Max) then Raise Exception.CreateFmt(ErrTooManyEntries,[w, Max]);
Pdata^[tPos]:= byte(w);
Pdata^[tPos+1]:= hi(word(w));
end;
procedure IncByte( const Pdata: PArrayOfByte; const tPos: integer; const Offset: integer; const Max: integer);
var
w: int64;
begin
w:=Pdata^[tPos];
inc(w, Offset);
if (w<0) or (w>Max) then Raise Exception.CreateFmt(ErrTooManyEntries,[w, Max]);
Pdata^[tPos]:= byte(w);
end;
procedure IncMax(var X: word ; N, Max: Longint );
begin
if (N+X>Max) or (N+X<0) then Raise Exception.CreateFmt(ErrTooManyEntries,[N+X, Max]);
Inc(X,N);
end;
procedure IncLongWord( const Pdata: PArrayOfByte; const tPos: integer; const Offset: int64);
var
Pc: ^LongWord;
begin
Pc:= @PData[tPos];
Inc(Pc^,Offset);
end;
procedure IncMaxMin(var X: word ; N, Max, Min: Longint );
begin
if (N+X>Max) then X:=Max else if N+X<Min then X:=Min else Inc(X,N);
end;
function GetWord(const Pdata: PArrayOfByte; const tPos: integer): word;
begin
Result:=pWord(PAddress(Pdata)+tPos)^;
end;
function GetLongWord(const Pdata: PArrayOfByte; const tPos: integer): LongWord;
begin
result:=PLongWord(PAddress(Pdata)+tPos)^;
end;
procedure SetLongWord(const Pdata: PArrayOfByte; const tPos: integer; const number: LongWord);
begin
System.Move(Number, Pdata^[tPos], sizeof(LongWord))
end;
procedure SetWord(const Pdata: PArrayOfByte; const tPos: integer; const number: Word);
begin
System.Move(Number, Pdata^[tPos], sizeof(Word))
end;
function GetStrLen(const Length16Bit: boolean ;const Pdata: PArrayOfByte; const tPos: integer;const UseExtStrLen: boolean; const ExtStrLen: LongWord): int64;
var
l, rt: LongWord;
bsize: byte;
sz: LongWord;
myPos: integer;
oField: byte;
begin
myPos:=tPos;
if UseExtStrLen then l:= ExtStrLen
else
begin
if Length16Bit then begin;l:=GetWord( Pdata, myPos);inc(myPos,2);end
else begin;l:=Pdata^[myPos];inc(myPos);end;
end;
oField:= Pdata^[myPos];
inc(myPos);
bsize:= oField and $1;
rt:=0;
if (oField and $8)= $8 then //RTF Info
begin
rt:=GetWord( Pdata, myPos);
inc(myPos, 2);
end;
sz:=0;
if (oField and $4)= $4 then //Far East Info
begin
sz:= GetLongWord( Pdata, myPos);
inc(myPos, 4);
end;
Result:=int64(myPos-tPos) + l shl bsize+ rt shl 2 + sz;
end;
procedure GetSimpleString(const Length16Bit: boolean ;const Pdata: PArrayOfByte; const tPos: integer;const UseExtStrLen: boolean; const ExtStrLen: LongWord; var St: UTF16String; var StSize: integer);
var
l, rt: LongWord;
bsize: byte;
sz: LongWord;
myPos: integer;
oField: byte;
ShortSt: AnsiString;
begin
myPos:=tPos;
if UseExtStrLen then l:= ExtStrLen
else
begin
if Length16Bit then begin;l:=GetWord( Pdata, myPos);inc(myPos,2);end
else begin;l:=Pdata^[myPos];inc(myPos);end;
end;
oField:= Pdata^[myPos];
inc(myPos);
bsize:= oField and $1;
rt:=0;
if (oField and $8)= $8 then //RTF Info
begin
rt:=GetWord( Pdata, myPos);
inc(myPos, 2);
end;
sz:=0;
if (oField and $4)= $4 then //Far East Info
begin
sz:= GetLongWord( Pdata, myPos);
inc(myPos, 4);
end;
StSize:=int64(myPos-tPos) + l shl bsize+ rt shl 2 + sz;
if bsize=0 then
begin
SetLength(ShortSt, l);
Move(pData^[myPos], ShortSt[1], l);
St:=StringToWideStringNoCodePage(ShortSt);
end else
begin
SetLength(St, l);
Move(pData^[myPos], St[1], l shl bsize);
end;
end;
function IsWide(const W: UTF16String): boolean;
var
i:integer;
begin
for i:=1 to length(w) do if ord(w[i])>$FF then begin;Result:=true;exit;end;
Result:=false;
end;
function WideStringToStringNoCodePage(const W: UTF16String): AnsiString;
var
i:integer;
begin
SetLength(Result, Length(W));
for i:=1 to length(w) do Result[i]:=AnsiChar(Ord(w[i]) and $FF);
end;
procedure CompressBestUnicode(const w: UTF16String; const PData: PArrayOfByte; const PDataPos: integer);
var
i:integer;
begin
for i:=1 to length(w) do
if Ord(w[i])<=$FF then PData[PDataPos+i-1]:=Ord(w[i]) else PData[PDataPos+i-1]:=Ord('?');
end;
function StringToWideStringNoCodePage(const s: AnsiString): UTF16String;
var
i:integer;
begin
SetLength(Result, Length(s));
for i:=1 to length(s) do Result[i]:=UTF16Char(Ord(s[i]));
end;
end.
|
unit GameBoardU;
interface
uses
System.Classes, System.SysUtils, System.Math, System.Generics.Collections, TileU;
type
TDirection = (dLeft, dRight, dUp, dDown);
TGameState = (gsPlaying, gsLost, gsWon, gsHiScore);
TGameStateChanged = procedure(const aOldState, aNewState: TGameState) of object;
TTileList = class(TObjectList<TTile>)
public
constructor Create(aTileList: TTileList; aOwnsObjects: Boolean = True); reintroduce;
function Add(const Value: TTile): TTile; reintroduce;
end;
TGameBoard = class
private
FColCount: Integer;
FGameState: TGameState;
FOnGameStateChanged: TGameStateChanged;
FRowCount: Integer;
FScore: Integer;
FTiles: TTileList;
class var
class var Finstance: TGameBoard;
constructor Create(const aRowCount: Integer; const aColCount: Integer); reintroduce;
procedure AlignDown;
procedure AlignLeft;
procedure AlignRight;
procedure AlignUp;
procedure FillRandomEmptyTile;
function GetTile(aRow: Integer; aCol: Integer): TTile;
function GetTilesCount: Integer; inline;
function HasLost: Boolean;
function HasWon: Boolean;
procedure IncScore(const aScore: Integer);
procedure Initialize;
procedure SetGameState(NewGameState: TGameState);
procedure UpdateGameState;
public
class constructor Create;
destructor Destroy; override;
class destructor Destroy;
function NewGame: TGameBoard;
function Swap(const aDirection: TDirection): Boolean;
property GameState: TGameState read FGameState;
property Score: Integer read FScore;
property Tile[aRow: Integer; aCol: Integer]: TTile read GetTile; default;
property OnGameStateChanged: TGameStateChanged read FOnGameStateChanged write FOnGameStateChanged;
end;
function GameBoard: TGameBoard;
implementation
uses
System.Threading, HighScoreU;
const
DEFAULT_INDEX: Integer = -1;
function GameBoard: TGameBoard;
begin
if TGameBoard.Finstance = nil then
TGameBoard.Create(4, 4);
Result := TGameBoard.Finstance;
end;
class constructor TGameBoard.Create;
begin
Randomize;
end;
class destructor TGameBoard.Destroy;
begin
FreeAndNil(Finstance);
end;
constructor TGameBoard.Create(const aRowCount: Integer; const aColCount: Integer);
begin
inherited Create;
FScore := 0;
FRowCount := aRowCount;
FColCount := aColCount;
Finstance := Self;
Initialize;
end;
destructor TGameBoard.Destroy;
begin
FreeAndNil(FTiles);
inherited;
end;
procedure TGameBoard.AlignDown;
var
Tile: TTile;
begin
for Tile in FTiles do
Tile.AlignDown;
end;
procedure TGameBoard.AlignLeft;
var
Tile: TTile;
begin
for Tile in FTiles do
Tile.AlignLeft;
end;
procedure TGameBoard.AlignRight;
var
Tile: TTile;
begin
for Tile in FTiles do
Tile.AlignRight;
end;
procedure TGameBoard.AlignUp;
var
Tile: TTile;
begin
for Tile in FTiles do
Tile.AlignUp;
end;
procedure TGameBoard.FillRandomEmptyTile;
var
Tile: TTile;
TileList: TTileList;
begin
TileList := TTileList.Create(nil, False);
try
for Tile in FTiles do
if Tile.IsEmpty then
TileList.Add(Tile);
TileList[Random(TileList.Count)].Fill
finally
TileList.Free
end;
end;
function TGameBoard.GetTile(aRow: Integer; aCol: Integer): TTile;
begin
if (aRow <= FRowCount) and (aCol <= FColCount) then
Result := FTiles.Items[(aCol - 1) + ((aRow - 1) * FColCount)]
else
Result := nil;
end;
function TGameBoard.GetTilesCount: Integer;
begin
Result := FRowCount * FColCount;
end;
function TGameBoard.HasLost: Boolean;
var
Tile: TTile;
begin
Result := True;
for Tile in FTiles do
if Tile.CanMerge then
exit(False);
end;
function TGameBoard.HasWon: Boolean;
var
Tile: TTile;
begin
Result := False;
for Tile in FTiles do
if Tile.IsMax then
exit(True);
end;
procedure TGameBoard.IncScore(const aScore: Integer);
begin
Inc(FScore, aScore);
end;
procedure TGameBoard.Initialize;
var
Row, Col: Integer;
begin
if GetTilesCount > 0 then
begin
FTiles := TTileList.Create(nil);
for Row := 1 to FRowCount do
for Col := 1 to FColCount do
FTiles.Add(TTile.Create(Row, Col)).OnIncScore := IncScore;
end;
for Row := 1 to FRowCount do
for Col := 1 to FColCount do
begin
if (FRowCount > 1) then
begin
if Row > 1 then
Tile[Row, Col].UpTile := Tile[Row - 1, Col];
if Row < FRowCount then
Tile[Row, Col].DownTile := Tile[Row + 1, Col];
end;
if (FColCount > 1) then
begin
if Col > 1 then
Tile[Row, Col].LeftTile := Tile[Row, Col - 1];
if Col < FColCount then
Tile[Row, Col].RightTile := Tile[Row, Col + 1];
end;
end;
end;
function TGameBoard.NewGame: TGameBoard;
begin
FTiles.Clear;
Initialize;
FScore := 0;
SetGameState(TGameState.gsPlaying);
FillRandomEmptyTile;
FillRandomEmptyTile;
Result := Self;
end;
procedure TGameBoard.SetGameState(NewGameState: TGameState);
begin
if Assigned(FOnGameStateChanged) then
FOnGameStateChanged(FGameState, NewGameState);
FGameState := NewGameState;
end;
function TGameBoard.Swap(const aDirection: TDirection): Boolean;
var
Tile: TTile;
begin
Result := False;
if GetTilesCount = 0 then
exit;
case aDirection of
dLeft:
AlignLeft;
dRight:
AlignRight;
dUp:
AlignUp;
dDown:
AlignDown;
end;
for Tile in FTiles do
if Tile.Changed then
begin
Result := True;
Tile.Changed := False;
end;
if Result then
FillRandomEmptyTile;
if Result then
TTask.Run(
procedure
begin
TThread.Synchronize(nil,
procedure
begin
UpdateGameState;
end);
end);
end;
procedure TGameBoard.UpdateGameState;
begin
if HasLost then
SetGameState(TGameState.gsLost)
else if HasWon then
SetGameState(TGameState.gsWon);
if (FGameState <> TGameState.gsHiScore) and (GameBoard.Score > Highscore.ReadHighScore.Score) then
SetGameState(TGameState.gsHiScore);
end;
constructor TTileList.Create(aTileList: TTileList; aOwnsObjects: Boolean);
var
aTile: TTile;
begin
inherited Create;
OwnsObjects := aOwnsObjects;
if aTileList <> nil then
for aTile in aTileList do
Add(TTile.Create(aTile));
end;
{ TTileList }
function TTileList.Add(const Value: TTile): TTile;
begin
inherited Add(Value);
Result := Value;
end;
end.
|
unit Concrete;
interface
uses
GameTypes, MapTypes;
const
cCenter = 0;
cUp = -1;
cDown = 1;
cLeft = -1;
cRight = 1;
type
ConcreteAround = (caUp, caDown, caLeft, caRight);
type
TConcreteConfig = array [cUp..cDown, cLeft..cRight] of boolean;
TConcreteCfg = array [0..7] of boolean;
const
cMaxConcreteConfigs = 13;
const
cFullConcrete = 12;
cSpecialConcrete = 15;
cRoadConcrete = $10;
const
cPlatformFlag = $80;
cPlatformMask = $7F;
const
//cPlatformShift = 18;
cPlatformShift = 12;
const
concreteNone = high(TConcrete);
function GetConcreteId(const concreteconfig : TConcreteCfg) : TConcrete;
function GetWaterConcreteId(const concreteconfig : TConcreteCfg): TConcrete;
function PlaceSpecialConcrete(i, j : integer) : boolean;
function RotateConcreteId(id : integer; rotation : TRotation) : integer;
implementation
const
caConcreteConfigs : array [0..pred(cMaxConcreteConfigs), 0..7] of boolean =
( //
( {}false, false, {}false, true, true, true, true, true ), // 1
( false, true, true, true, true, true, true, true), // 2
( false, false, false, true, false, true, true, false ), // 3
( true, true, false, true, false, false, false, false), // 4
( true, true, false, true, true, true, true, true ), // 5
( true, true, {}false, true, false, true, true, {}false ), // 6
( true, true, true, true, true, false, false, false), // 7
( false, true, true, false, true, false, true, true ), // 8
( true, true, true, true, true, true, true, false ), // 9
( false, true, true, false, true, false, false, false ), // 10
( false, false, false, false, true, false, true, true), // 11
( true, true, true, true, true, false, true, true ), // 12
( true, true, true, true, true, true, true, true ) // 13
); // 14 Not Fount
cWaterConcreteConfigs : array [0..8, 0..3] of boolean =
(
(true, true, true, true), // 0
(false, true, false, true), // 1
(true, true, false, false), // 2
(true, true, false, true), // 3
(true, true, true, false), // 4
(false, false, true, true), // 5
(false, true, true, true), // 6
(true, false, true, true), // 7
(true, false, true, false) // 8
);
function GetWaterConcreteId(const concreteconfig : TConcreteCfg): TConcrete;
var
match : boolean;
begin
match := false;
result := 0;
while (not match) and (result<9) do
begin
match := (cWaterConcreteConfigs[result][0] = concreteconfig[1]) and
(cWaterConcreteConfigs[result][1] = concreteconfig[3]) and
(cWaterConcreteConfigs[result][2] = concreteconfig[4]) and
(cWaterConcreteConfigs[result][3] = concreteconfig[6]);
inc(result);
end;
if match
then
begin
dec(result);
result := result or cPlatformFlag;
end
else result := concreteNone;
end;
function GetConcreteId(const concreteconfig : TConcreteCfg) : TConcrete;
{ var
match : boolean;
i : integer;}
begin
{ match := false;
result := 0;
while (not match) and (result<cMaxConcreteConfigs) do
begin
match := ((caConcreteConfigs[result][0] = concreteconfig[0]) or (result=0) or (result=7) or (result=9) or (result=2)) and
(caConcreteConfigs[result][1] = concreteconfig[1]) and
((caConcreteConfigs[result][2] = concreteconfig[2]) or (result=0) or (result=5) or (result=3) or (result=10)) and
(caConcreteConfigs[result][3] = concreteconfig[3]) and
(caConcreteConfigs[result][4] = concreteconfig[4]) and
((caConcreteConfigs[result][5] = concreteconfig[5]) or (result=6) or (result=7) or (result=3) or (result=10)) and
(caConcreteConfigs[result][6] = concreteconfig[6]) and
((caConcreteConfigs[result][7] = concreteconfig[7]) or (result=5) or (result=6) or (result=9) or (result=2));
inc(result);
end;
if match
then dec(Result)
else result := 12;} // concreteNone;
result := 12;
if concreteconfig[1]
then
begin // 1, 3, 4, 5, 6, 7, 8, 9, 11, 12
if concreteconfig[3]
then
begin // 1, 3, 4, 5, 6, 8, 11, 12
if concreteconfig[4]
then
begin // 1, 4, 6, 8, 11, 12
if concreteconfig[6]
then
begin // 1, 4, 8, 12, 11
if concreteconfig[0]
then
begin // 4, 8, 12, 11
if concreteconfig[2]
then
begin // 8, 11, 12
if concreteconfig[7]
then
begin // 11, 2
if concreteconfig[5]
then result := 12
else result := 11;
end
else result := 8;
end
else result := 4;
end
else result := 1;
end
else
if concreteconfig[0]
then
if concreteconfig[2]
then result := 6
else result := 3
else result := 9;
end
else
begin // 3, 5
if concreteconfig[5]
then
begin
if concreteconfig[0]
then
if concreteconfig[6]
then result := 5
else result := 3
else result := 2;
end
else result := 3;
end;
end
else
begin // 7, 9 10
if concreteconfig[7]
then
begin
if concreteconfig[2]
then
if concreteconfig[6]
then result := 7
else result := 9
else result := 10;
end
else result := 9;
end;
end
else
begin // 0, 2. 10
if concreteconfig[3]
then
if concreteconfig[4]
then
begin
if concreteconfig[5]
then
if concreteconfig[7]
then result := 0
else result := 2
else result := 10;
end
else result := 2
else result := 10;
end;
end;
function PlaceSpecialConcrete(i, j : integer) : boolean;
begin
Result := ((i mod 2) = 0) and ((j mod 2) = 0);
end;
function RotateConcreteId(id : integer; rotation : TRotation) : integer;
const
cRotatedConcreteIds : array [TRotation, 0..pred(cMaxConcreteConfigs)] of TConcrete =
(
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), // drNorth
(5, 4, 3, 9, 8, 6, 7, 0, 11, 10, 2, 1, 12), // drEast
(6, 8, 9, 10, 11, 7, 0, 5, 1, 2, 3, 4, 12), // drSouth
(7, 11, 10, 2, 1, 0, 5, 6, 4, 3, 9, 8, 12)// drWest
);
cWaterRotatedConcreteIds : array [TRotation, 0..8] of TConcrete =
(
($80, $81, $82, $83, $84, $85, $86, $87, $88), // drNorth
($80, $82, $88, $84, $87, $81, $83, $86, $85), // drEast
($80, $88, $85, $87, $86, $82, $84, $83, $81), // drSouth
($80, $85, $81, $86, $83, $88, $87, $84, $82) // drWest
);
begin
if (id and cPlatformFlag>0)
then Result := cWaterRotatedConcreteIds[rotation, id and cPlatformMask]
else
begin
if id<>cSpecialConcrete
then
begin
Result := cRotatedConcreteIds[rotation, id and not cRoadConcrete];
if (id and cRoadConcrete)<>0
then Result := Result or cRoadConcrete;
end
else result := cSpecialConcrete;
end;
end;
end.
|
unit QuickExport;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
ComObj, ActiveX, FB2_to_LIT_TLB, StdVcl,fb2lit_engine;
type
TFB2AnyQuickExport = class(TAutoObject, IFB2AnyQuickExport)
procedure AfterConstruction; Override;
procedure BeforeDestruction; override;
protected
Converter:TFB2LitConverter;
SettingsLoaded:Boolean;
procedure Export(hWnd: Integer; filename: OleVariant;
const document: IDispatch; appName: OleVariant); safecall;
procedure Setup(hWnd: Integer; appName: OleVariant); safecall;
{ Protected declarations }
end;
implementation
uses ComServ,QuickExportSetup,Registry,Windows;
procedure TFB2AnyQuickExport.AfterConstruction;
Begin
inherited AfterConstruction;
Converter:=TFB2LitConverter.Create;
SettingsLoaded:=False;
end;
procedure TFB2AnyQuickExport.BeforeDestruction;
Begin
inherited BeforeDestruction;
Converter.Free;
end;
procedure TFB2AnyQuickExport.Export(hWnd: Integer; filename: OleVariant;
const document: IDispatch; appName: OleVariant);
Var
Reg:TRegistry;
begin
if not SettingsLoaded then
begin
Reg:=TRegistry.Create(KEY_READ);
Try
if Reg.OpenKeyReadOnly(QuickSetupKey+appName) then
Begin
Converter.SkipImg:=Reg.ReadBool('Skip images');
Converter.TocDeep:=Reg.ReadInteger('TOC deepness');
end;
SettingsLoaded:=True;
Finally
Reg.Free;
end;
end;
Converter.Convert(document,filename);
end;
procedure TFB2AnyQuickExport.Setup(hWnd: Integer; appName: OleVariant);
begin
with TQuickExportSetupForm.CreateWithForeighnParent(hWnd,appName) do
Begin
ShowModal;
Free;
end;
end;
initialization
TAutoObjectFactory.Create(ComServer, TFB2AnyQuickExport, Class_FB2AnyQuickExport,
ciMultiInstance, tmApartment);
end.
|
unit TraceToolCom_TLB;
// ************************************************************************ //
// WARNING
// -------
// The types declared in this file were generated from data read from a
// Type Library. If this type library is explicitly or indirectly (via
// another type library referring to this type library) re-imported, or the
// 'Refresh' command of the Type Library Editor activated while editing the
// Type Library, the contents of this file will be regenerated and all
// manual modifications will be lost.
// ************************************************************************ //
// $Rev: 16059 $
// File generated on 30/03/2009 16:20:43 from Type Library described below.
// ************************************************************************ //
// Type Lib: \\.host\Shared Folders\tracetool\ActiveX\Lib\TraceToolCom (1)
// LIBID: {9E046325-C625-4726-B6F4-16D2E3D5CFBD}
// LCID: 0
// Helpfile:
// HelpString: TraceToolCom Library
// DepndLst:
// (1) v2.0 stdole, (C:\WINDOWS\system32\stdole2.tlb)
// ************************************************************************ //
{$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers.
{$WARN SYMBOL_PLATFORM OFF}
{$WRITEABLECONST ON}
{$VARPROPSETTER ON}
{$ALIGN 4}
interface
uses Windows, ActiveX, Classes, Graphics, OleServer, StdVCL, Variants;
// *********************************************************************//
// GUIDS declared in the TypeLibrary. Following prefixes are used:
// Type Libraries : LIBID_xxxx
// CoClasses : CLASS_xxxx
// DISPInterfaces : DIID_xxxx
// Non-DISP interfaces: IID_xxxx
// *********************************************************************//
const
// TypeLibrary Major and minor versions
TraceToolComMajorVersion = 11;
TraceToolComMinorVersion = 0;
LIBID_TraceToolCom: TGUID = '{9E046325-C625-4726-B6F4-16D2E3D5CFBD}';
IID_IXTrace: TGUID = '{3DF44A95-5044-46B1-A947-9CB5135943DD}';
IID_IXTraceNodeBase: TGUID = '{B5604A34-11A5-4CC6-AED3-CC9B542AF198}';
IID_IXTraceNodeEx: TGUID = '{2267AF79-9C4B-4689-9E5F-1AE2EC0946D7}';
IID_IXMemberNode: TGUID = '{A1C8577E-15E7-4190-ACD9-256BE360F388}';
IID_IXWinWatch: TGUID = '{AEF54A58-09A3-49FE-8FD8-31290649BB35}';
IID_IXTraceOptions: TGUID = '{8F7167DD-8300-4D43-B434-C536C93D5CB8}';
IID_IXTraceToSend: TGUID = '{2564ABB2-A952-42E9-A412-67F45384D3AB}';
CLASS_XTrace: TGUID = '{14C8EA3E-1930-48E1-9BCC-63E7737CEF29}';
IID_IXTraceNode: TGUID = '{67D4B6E1-C1E0-4715-BB23-8A289E77D907}';
CLASS_XTraceNodeEx: TGUID = '{03DF9B86-BF3A-415C-A6ED-52531CD0D533}';
CLASS_XMemberNode: TGUID = '{DC02B3E8-FA4A-4A7D-A967-14CA31AF8968}';
CLASS_XWinWatch: TGUID = '{D1CA152D-E3AC-49D5-84B4-409FA0CCF750}';
CLASS_XTraceOptions: TGUID = '{58F75201-E834-4B63-84B9-24CCFF36F75E}';
IID_IXWinTrace: TGUID = '{4365CFCE-6247-4F05-ADBB-2F42FF8B6348}';
CLASS_XWinTrace: TGUID = '{1DF8CC03-48DB-4EA2-B0F6-F3116F33C38F}';
CLASS_XTraceNode: TGUID = '{0D7E252F-7FD3-4173-B53B-0DFAE57CE9D1}';
CLASS_XTraceToSend: TGUID = '{418EA4E6-F6F8-438F-AB27-B19067842B2C}';
IID_IXTraceTable: TGUID = '{1EF2CA18-A338-4F31-A420-6F03C4FEFE63}';
CLASS_XTraceTable: TGUID = '{BAFF53E4-4E34-4059-9599-132713F81521}';
// *********************************************************************//
// Declaration of Enumerations defined in Type Library
// *********************************************************************//
// Constants for enum SendMode
type
SendMode = TOleEnum;
const
WinMsg = $00000000;
Socket = $00000001;
None = $00000002;
// Constants for enum LogMode
type
LogMode = TOleEnum;
const
ViewerLogDisabled = $00000000;
ViewerLogEnabled = $00000001;
ViewerLogDaily = $00000002;
LocalLogDisabled = $00000003;
LocalLogEnabled = $00000004;
LocalLogDaily = $00000005;
// Constants for enum ColorKind
type
ColorKind = TOleEnum;
const
BGR = $00000000;
RGB = $00000001;
type
// *********************************************************************//
// Forward declaration of types defined in TypeLibrary
// *********************************************************************//
IXTrace = interface;
IXTraceDisp = dispinterface;
IXTraceNodeBase = interface;
IXTraceNodeBaseDisp = dispinterface;
IXTraceNodeEx = interface;
IXTraceNodeExDisp = dispinterface;
IXMemberNode = interface;
IXMemberNodeDisp = dispinterface;
IXWinWatch = interface;
IXWinWatchDisp = dispinterface;
IXTraceOptions = interface;
IXTraceOptionsDisp = dispinterface;
IXTraceToSend = interface;
IXTraceToSendDisp = dispinterface;
IXTraceNode = interface;
IXTraceNodeDisp = dispinterface;
IXWinTrace = interface;
IXWinTraceDisp = dispinterface;
IXTraceTable = interface;
IXTraceTableDisp = dispinterface;
// *********************************************************************//
// Declaration of CoClasses defined in Type Library
// (NOTE: Here we map each CoClass to its Default Interface)
// *********************************************************************//
XTrace = IXTrace;
XTraceNodeEx = IXTraceNodeEx;
XMemberNode = IXMemberNode;
XWinWatch = IXWinWatch;
XTraceOptions = IXTraceOptions;
XWinTrace = IXWinTrace;
XTraceNode = IXTraceNode;
XTraceToSend = IXTraceToSend;
XTraceTable = IXTraceTable;
// *********************************************************************//
// Declaration of structures, unions and aliases.
// *********************************************************************//
PPUserType1 = ^IXTraceTable;
PPUserType2 = ^IXTraceTable;
PPUserType3 = ^IXTraceTable;
PPUserType4 = ^IXTraceTable;
PPUserType5 = ^IXTraceTable;
PPUserType6 = ^IXTraceTable;
PPUserType7 = ^IXTraceTable;
PPUserType8 = ^IXTraceTable; {*}
// *********************************************************************//
// Interface: IXTrace
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {3DF44A95-5044-46B1-A947-9CB5135943DD}
// *********************************************************************//
IXTrace = interface(IDispatch)
['{3DF44A95-5044-46B1-A947-9CB5135943DD}']
function Get_Warning: IXTraceToSend; safecall;
function Get_Error: IXTraceToSend; safecall;
function Get_Debug: IXTraceToSend; safecall;
function Get_Options: IXTraceOptions; safecall;
function Get_WinTrace: IXWinTrace; safecall;
function Get_Watches: IXWinWatch; safecall;
procedure ClearAll; safecall;
procedure Show(IsVisible: WordBool); safecall;
procedure Flush(FlushTimeOut: SYSINT); safecall;
function CreateWinTrace(const WinTraceId: WideString; const WinTraceText: WideString): IXWinTrace; safecall;
function CreateWinWatch(const WinWatchId: WideString; const WinWatchText: WideString): IXWinWatch; safecall;
function CreateTraceTable: IXTraceTable; safecall;
procedure Start; safecall;
procedure Stop; safecall;
procedure CloseViewer; safecall;
property Warning: IXTraceToSend read Get_Warning;
property Error: IXTraceToSend read Get_Error;
property Debug: IXTraceToSend read Get_Debug;
property Options: IXTraceOptions read Get_Options;
property WinTrace: IXWinTrace read Get_WinTrace;
property Watches: IXWinWatch read Get_Watches;
end;
// *********************************************************************//
// DispIntf: IXTraceDisp
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {3DF44A95-5044-46B1-A947-9CB5135943DD}
// *********************************************************************//
IXTraceDisp = dispinterface
['{3DF44A95-5044-46B1-A947-9CB5135943DD}']
property Warning: IXTraceToSend readonly dispid 102;
property Error: IXTraceToSend readonly dispid 103;
property Debug: IXTraceToSend readonly dispid 104;
property Options: IXTraceOptions readonly dispid 105;
property WinTrace: IXWinTrace readonly dispid 106;
property Watches: IXWinWatch readonly dispid 107;
procedure ClearAll; dispid 108;
procedure Show(IsVisible: WordBool); dispid 109;
procedure Flush(FlushTimeOut: SYSINT); dispid 110;
function CreateWinTrace(const WinTraceId: WideString; const WinTraceText: WideString): IXWinTrace; dispid 201;
function CreateWinWatch(const WinWatchId: WideString; const WinWatchText: WideString): IXWinWatch; dispid 202;
function CreateTraceTable: IXTraceTable; dispid 203;
procedure Start; dispid 204;
procedure Stop; dispid 205;
procedure CloseViewer; dispid 206;
end;
// *********************************************************************//
// Interface: IXTraceNodeBase
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {B5604A34-11A5-4CC6-AED3-CC9B542AF198}
// *********************************************************************//
IXTraceNodeBase = interface(IDispatch)
['{B5604A34-11A5-4CC6-AED3-CC9B542AF198}']
function Get_Id: WideString; safecall;
procedure Set_Id(const Value: WideString); safecall;
function Get_Enabled: WordBool; safecall;
procedure Set_Enabled(Value: WordBool); safecall;
function Get_IconIndex: SYSINT; safecall;
procedure Set_IconIndex(Value: SYSINT); safecall;
function Get_Tag: SYSINT; safecall;
procedure Set_Tag(Value: SYSINT); safecall;
function Get_WinTraceId: WideString; safecall;
procedure Set_WinTraceId(const Value: WideString); safecall;
function CreateNodeEx: IXTraceNodeEx; safecall;
property Id: WideString read Get_Id write Set_Id;
property Enabled: WordBool read Get_Enabled write Set_Enabled;
property IconIndex: SYSINT read Get_IconIndex write Set_IconIndex;
property Tag: SYSINT read Get_Tag write Set_Tag;
property WinTraceId: WideString read Get_WinTraceId write Set_WinTraceId;
end;
// *********************************************************************//
// DispIntf: IXTraceNodeBaseDisp
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {B5604A34-11A5-4CC6-AED3-CC9B542AF198}
// *********************************************************************//
IXTraceNodeBaseDisp = dispinterface
['{B5604A34-11A5-4CC6-AED3-CC9B542AF198}']
property Id: WideString dispid 200;
property Enabled: WordBool dispid 201;
property IconIndex: SYSINT dispid 202;
property Tag: SYSINT dispid 203;
property WinTraceId: WideString dispid 204;
function CreateNodeEx: IXTraceNodeEx; dispid 205;
end;
// *********************************************************************//
// Interface: IXTraceNodeEx
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {2267AF79-9C4B-4689-9E5F-1AE2EC0946D7}
// *********************************************************************//
IXTraceNodeEx = interface(IXTraceNodeBase)
['{2267AF79-9C4B-4689-9E5F-1AE2EC0946D7}']
function Get_LeftMsg: WideString; safecall;
procedure Set_LeftMsg(const Value: WideString); safecall;
function Get_RightMsg: WideString; safecall;
procedure Set_RightMsg(const Value: WideString); safecall;
function Get_ParentNodeId: WideString; safecall;
procedure Set_ParentNodeId(const Value: WideString); safecall;
function Get_Members: IXMemberNode; safecall;
procedure AddObject(Obj: OleVariant); safecall;
procedure AddValue(Obj: OleVariant; const ObjTitle: WideString; MaxLevel: Integer); safecall;
procedure AddDump(const ShortTitle: WideString; Adr: PChar; Count: SYSINT); safecall;
procedure AddFontDetail(ColId: SYSINT; Bold: WordBool; Italic: WordBool; Color: SYSINT;
Size: SYSINT; const FontName: WideString); safecall;
procedure AddTable(var Table: IXTraceTable); safecall;
procedure AddXml(const Xml: WideString); safecall;
procedure AddBackgroundColor(ColId: SYSINT; Color: SYSINT); safecall;
function Send: IXTraceNode; safecall;
function Resend: IXTraceNode; safecall;
property LeftMsg: WideString read Get_LeftMsg write Set_LeftMsg;
property RightMsg: WideString read Get_RightMsg write Set_RightMsg;
property ParentNodeId: WideString read Get_ParentNodeId write Set_ParentNodeId;
property Members: IXMemberNode read Get_Members;
end;
// *********************************************************************//
// DispIntf: IXTraceNodeExDisp
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {2267AF79-9C4B-4689-9E5F-1AE2EC0946D7}
// *********************************************************************//
IXTraceNodeExDisp = dispinterface
['{2267AF79-9C4B-4689-9E5F-1AE2EC0946D7}']
property LeftMsg: WideString dispid 250;
property RightMsg: WideString dispid 251;
property ParentNodeId: WideString dispid 252;
property Members: IXMemberNode readonly dispid 253;
procedure AddObject(Obj: OleVariant); dispid 254;
procedure AddValue(Obj: OleVariant; const ObjTitle: WideString; MaxLevel: Integer); dispid 255;
procedure AddDump(const ShortTitle: WideString; Adr: {??PChar}OleVariant; Count: SYSINT); dispid 256;
procedure AddFontDetail(ColId: SYSINT; Bold: WordBool; Italic: WordBool; Color: SYSINT;
Size: SYSINT; const FontName: WideString); dispid 257;
procedure AddTable(var Table: IXTraceTable); dispid 258;
procedure AddXml(const Xml: WideString); dispid 259;
procedure AddBackgroundColor(ColId: SYSINT; Color: SYSINT); dispid 260;
function Send: IXTraceNode; dispid 261;
function Resend: IXTraceNode; dispid 262;
property Id: WideString dispid 200;
property Enabled: WordBool dispid 201;
property IconIndex: SYSINT dispid 202;
property Tag: SYSINT dispid 203;
property WinTraceId: WideString dispid 204;
function CreateNodeEx: IXTraceNodeEx; dispid 205;
end;
// *********************************************************************//
// Interface: IXMemberNode
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {A1C8577E-15E7-4190-ACD9-256BE360F388}
// *********************************************************************//
IXMemberNode = interface(IDispatch)
['{A1C8577E-15E7-4190-ACD9-256BE360F388}']
function Get_Col1: WideString; safecall;
procedure Set_Col1(const Value: WideString); safecall;
function Get_Col2: WideString; safecall;
procedure Set_Col2(const Value: WideString); safecall;
function Get_Col3: WideString; safecall;
procedure Set_Col3(const Value: WideString); safecall;
function Get_Tag: SYSINT; safecall;
procedure Set_Tag(Value: SYSINT); safecall;
function Add(const Col1: WideString; const Col2: WideString; const Col3: WideString): IXMemberNode; safecall;
function SetFontDetail(ColId: SYSINT; Bold: WordBool; Italic: WordBool; Color: SYSINT;
Size: SYSINT; const FontName: WideString): IXMemberNode; safecall;
property Col1: WideString read Get_Col1 write Set_Col1;
property Col2: WideString read Get_Col2 write Set_Col2;
property Col3: WideString read Get_Col3 write Set_Col3;
property Tag: SYSINT read Get_Tag write Set_Tag;
end;
// *********************************************************************//
// DispIntf: IXMemberNodeDisp
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {A1C8577E-15E7-4190-ACD9-256BE360F388}
// *********************************************************************//
IXMemberNodeDisp = dispinterface
['{A1C8577E-15E7-4190-ACD9-256BE360F388}']
property Col1: WideString dispid 201;
property Col2: WideString dispid 202;
property Col3: WideString dispid 203;
property Tag: SYSINT dispid 101;
function Add(const Col1: WideString; const Col2: WideString; const Col3: WideString): IXMemberNode; dispid 204;
function SetFontDetail(ColId: SYSINT; Bold: WordBool; Italic: WordBool; Color: SYSINT;
Size: SYSINT; const FontName: WideString): IXMemberNode; dispid 205;
end;
// *********************************************************************//
// Interface: IXWinWatch
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {AEF54A58-09A3-49FE-8FD8-31290649BB35}
// *********************************************************************//
IXWinWatch = interface(IDispatch)
['{AEF54A58-09A3-49FE-8FD8-31290649BB35}']
function Get_Enabled: WordBool; safecall;
procedure Set_Enabled(Value: WordBool); safecall;
function Get_Tag: SYSINT; safecall;
procedure Set_Tag(Value: SYSINT); safecall;
procedure DisplayWin; safecall;
procedure ClearAll; safecall;
procedure Send(const WatchName: WideString; v: OleVariant); safecall;
function Get_Id: WideString; safecall;
procedure Set_Id(const Value: WideString); safecall;
procedure Close; safecall;
property Enabled: WordBool read Get_Enabled write Set_Enabled;
property Tag: SYSINT read Get_Tag write Set_Tag;
property Id: WideString read Get_Id write Set_Id;
end;
// *********************************************************************//
// DispIntf: IXWinWatchDisp
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {AEF54A58-09A3-49FE-8FD8-31290649BB35}
// *********************************************************************//
IXWinWatchDisp = dispinterface
['{AEF54A58-09A3-49FE-8FD8-31290649BB35}']
property Enabled: WordBool dispid 201;
property Tag: SYSINT dispid 202;
procedure DisplayWin; dispid 203;
procedure ClearAll; dispid 204;
procedure Send(const WatchName: WideString; v: OleVariant); dispid 205;
property Id: WideString dispid 101;
procedure Close; dispid 206;
end;
// *********************************************************************//
// Interface: IXTraceOptions
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {8F7167DD-8300-4D43-B434-C536C93D5CB8}
// *********************************************************************//
IXTraceOptions = interface(IDispatch)
['{8F7167DD-8300-4D43-B434-C536C93D5CB8}']
function Get_SocketHost: WideString; safecall;
procedure Set_SocketHost(const Value: WideString); safecall;
function Get_SendMode: SendMode; safecall;
procedure Set_SendMode(Value: SendMode); safecall;
function Get_SendDate: WordBool; safecall;
procedure Set_SendDate(Value: WordBool); safecall;
function Get_SendFunctions: WordBool; safecall;
procedure Set_SendFunctions(Value: WordBool); safecall;
function Get_SendThreadId: WordBool; safecall;
procedure Set_SendThreadId(Value: WordBool); safecall;
function Get_SendProcessName: WordBool; safecall;
procedure Set_SendProcessName(Value: WordBool); safecall;
function Get_SocketPort: SYSINT; safecall;
procedure Set_SocketPort(Value: SYSINT); safecall;
function Get_ColorKind: ColorKind; safecall;
procedure Set_ColorKind(Value: ColorKind); safecall;
function Get_SocketUdp: WordBool; safecall;
procedure Set_SocketUdp(Value: WordBool); safecall;
property SocketHost: WideString read Get_SocketHost write Set_SocketHost;
property SendMode: SendMode read Get_SendMode write Set_SendMode;
property SendDate: WordBool read Get_SendDate write Set_SendDate;
property SendFunctions: WordBool read Get_SendFunctions write Set_SendFunctions;
property SendThreadId: WordBool read Get_SendThreadId write Set_SendThreadId;
property SendProcessName: WordBool read Get_SendProcessName write Set_SendProcessName;
property SocketPort: SYSINT read Get_SocketPort write Set_SocketPort;
property ColorKind: ColorKind read Get_ColorKind write Set_ColorKind;
property SocketUdp: WordBool read Get_SocketUdp write Set_SocketUdp;
end;
// *********************************************************************//
// DispIntf: IXTraceOptionsDisp
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {8F7167DD-8300-4D43-B434-C536C93D5CB8}
// *********************************************************************//
IXTraceOptionsDisp = dispinterface
['{8F7167DD-8300-4D43-B434-C536C93D5CB8}']
property SocketHost: WideString dispid 201;
property SendMode: SendMode dispid 202;
property SendDate: WordBool dispid 203;
property SendFunctions: WordBool dispid 204;
property SendThreadId: WordBool dispid 102;
property SendProcessName: WordBool dispid 101;
property SocketPort: SYSINT dispid 103;
property ColorKind: ColorKind dispid 205;
property SocketUdp: WordBool dispid 206;
end;
// *********************************************************************//
// Interface: IXTraceToSend
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {2564ABB2-A952-42E9-A412-67F45384D3AB}
// *********************************************************************//
IXTraceToSend = interface(IXTraceNodeBase)
['{2564ABB2-A952-42E9-A412-67F45384D3AB}']
function Send(const LeftMsg: WideString; const RightMsg: WideString): IXTraceNode; safecall;
function SendObject(const LeftMsg: WideString; Obj: OleVariant): IXTraceNode; safecall;
function SendValue(const LeftMsg: WideString; Obj: OleVariant; const ObjTitle: WideString): IXTraceNode; safecall;
function SendValueIDisptach(const LeftMsg: WideString; const Obj: IDispatch;
const ObjTitle: WideString): IXTraceNode; safecall;
function SendDump(const LeftMsg: WideString; const ShortTitle: WideString; Adress: PChar;
Count: SYSINT): IXTraceNode; safecall;
procedure SendTable(const LeftMsg: WideString; var Table: IXTraceTable); safecall;
procedure SendXml(const LeftMsg: WideString; const Xml: WideString); safecall;
procedure SendBackgroundColor(const LeftMsg: WideString; Color: SYSINT; ColId: SYSINT); safecall;
procedure EnterMethod(const LeftMsg: WideString; const RightMsg: WideString); safecall;
procedure ExitMethod(const LeftMsg: WideString; const RightMsg: WideString); safecall;
procedure Indent(const LeftMsg: WideString; const RightMsg: WideString); safecall;
procedure UnIndent(const LeftMsg: WideString; const RightMsg: WideString); safecall;
end;
// *********************************************************************//
// DispIntf: IXTraceToSendDisp
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {2564ABB2-A952-42E9-A412-67F45384D3AB}
// *********************************************************************//
IXTraceToSendDisp = dispinterface
['{2564ABB2-A952-42E9-A412-67F45384D3AB}']
function Send(const LeftMsg: WideString; const RightMsg: WideString): IXTraceNode; dispid 250;
function SendObject(const LeftMsg: WideString; Obj: OleVariant): IXTraceNode; dispid 251;
function SendValue(const LeftMsg: WideString; Obj: OleVariant; const ObjTitle: WideString): IXTraceNode; dispid 252;
function SendValueIDisptach(const LeftMsg: WideString; const Obj: IDispatch;
const ObjTitle: WideString): IXTraceNode; dispid 253;
function SendDump(const LeftMsg: WideString; const ShortTitle: WideString;
Adress: {??PChar}OleVariant; Count: SYSINT): IXTraceNode; dispid 254;
procedure SendTable(const LeftMsg: WideString; var Table: IXTraceTable); dispid 255;
procedure SendXml(const LeftMsg: WideString; const Xml: WideString); dispid 256;
procedure SendBackgroundColor(const LeftMsg: WideString; Color: SYSINT; ColId: SYSINT); dispid 257;
procedure EnterMethod(const LeftMsg: WideString; const RightMsg: WideString); dispid 258;
procedure ExitMethod(const LeftMsg: WideString; const RightMsg: WideString); dispid 259;
procedure Indent(const LeftMsg: WideString; const RightMsg: WideString); dispid 260;
procedure UnIndent(const LeftMsg: WideString; const RightMsg: WideString); dispid 261;
property Id: WideString dispid 200;
property Enabled: WordBool dispid 201;
property IconIndex: SYSINT dispid 202;
property Tag: SYSINT dispid 203;
property WinTraceId: WideString dispid 204;
function CreateNodeEx: IXTraceNodeEx; dispid 205;
end;
// *********************************************************************//
// Interface: IXTraceNode
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {67D4B6E1-C1E0-4715-BB23-8A289E77D907}
// *********************************************************************//
IXTraceNode = interface(IXTraceToSend)
['{67D4B6E1-C1E0-4715-BB23-8A289E77D907}']
function Resend(const LeftMsg: WideString; const RightMsg: WideString): IXTraceNode; safecall;
function ResendLeft(const LeftMsg: WideString): IXTraceNode; safecall;
function ResendRight(const RightMsg: WideString): IXTraceNode; safecall;
function Append(const NewLeftMsg: WideString; const NewRightMsg: WideString): IXTraceNode; safecall;
function AppendLeft(const NewLeftMsg: WideString): IXTraceNode; safecall;
function AppendRight(const NewRightMsg: WideString): IXTraceNode; safecall;
function Show: IXTraceNode; safecall;
function SetSelected: IXTraceNode; safecall;
function Delete: IXTraceNode; safecall;
function DeleteChildren: IXTraceNode; safecall;
function SetFontDetail(ColId: SYSINT; Bold: WordBool; Italic: WordBool; Color: SYSINT;
Size: SYSINT; const FontName: WideString): IXTraceNode; safecall;
function ResendIconIndex(Index: SYSINT): IXTraceNode; safecall;
function SetBackgroundColor(Color: SYSINT; ColId: SYSINT): IXTraceNode; safecall;
end;
// *********************************************************************//
// DispIntf: IXTraceNodeDisp
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {67D4B6E1-C1E0-4715-BB23-8A289E77D907}
// *********************************************************************//
IXTraceNodeDisp = dispinterface
['{67D4B6E1-C1E0-4715-BB23-8A289E77D907}']
function Resend(const LeftMsg: WideString; const RightMsg: WideString): IXTraceNode; dispid 300;
function ResendLeft(const LeftMsg: WideString): IXTraceNode; dispid 301;
function ResendRight(const RightMsg: WideString): IXTraceNode; dispid 302;
function Append(const NewLeftMsg: WideString; const NewRightMsg: WideString): IXTraceNode; dispid 303;
function AppendLeft(const NewLeftMsg: WideString): IXTraceNode; dispid 304;
function AppendRight(const NewRightMsg: WideString): IXTraceNode; dispid 305;
function Show: IXTraceNode; dispid 306;
function SetSelected: IXTraceNode; dispid 307;
function Delete: IXTraceNode; dispid 308;
function DeleteChildren: IXTraceNode; dispid 309;
function SetFontDetail(ColId: SYSINT; Bold: WordBool; Italic: WordBool; Color: SYSINT;
Size: SYSINT; const FontName: WideString): IXTraceNode; dispid 310;
function ResendIconIndex(Index: SYSINT): IXTraceNode; dispid 311;
function SetBackgroundColor(Color: SYSINT; ColId: SYSINT): IXTraceNode; dispid 312;
function Send(const LeftMsg: WideString; const RightMsg: WideString): IXTraceNode; dispid 250;
function SendObject(const LeftMsg: WideString; Obj: OleVariant): IXTraceNode; dispid 251;
function SendValue(const LeftMsg: WideString; Obj: OleVariant; const ObjTitle: WideString): IXTraceNode; dispid 252;
function SendValueIDisptach(const LeftMsg: WideString; const Obj: IDispatch;
const ObjTitle: WideString): IXTraceNode; dispid 253;
function SendDump(const LeftMsg: WideString; const ShortTitle: WideString;
Adress: {??PChar}OleVariant; Count: SYSINT): IXTraceNode; dispid 254;
procedure SendTable(const LeftMsg: WideString; var Table: IXTraceTable); dispid 255;
procedure SendXml(const LeftMsg: WideString; const Xml: WideString); dispid 256;
procedure SendBackgroundColor(const LeftMsg: WideString; Color: SYSINT; ColId: SYSINT); dispid 257;
procedure EnterMethod(const LeftMsg: WideString; const RightMsg: WideString); dispid 258;
procedure ExitMethod(const LeftMsg: WideString; const RightMsg: WideString); dispid 259;
procedure Indent(const LeftMsg: WideString; const RightMsg: WideString); dispid 260;
procedure UnIndent(const LeftMsg: WideString; const RightMsg: WideString); dispid 261;
property Id: WideString dispid 200;
property Enabled: WordBool dispid 201;
property IconIndex: SYSINT dispid 202;
property Tag: SYSINT dispid 203;
property WinTraceId: WideString dispid 204;
function CreateNodeEx: IXTraceNodeEx; dispid 205;
end;
// *********************************************************************//
// Interface: IXWinTrace
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {4365CFCE-6247-4F05-ADBB-2F42FF8B6348}
// *********************************************************************//
IXWinTrace = interface(IXTraceToSend)
['{4365CFCE-6247-4F05-ADBB-2F42FF8B6348}']
function Get_Warning: IXTraceToSend; safecall;
function Get_Error: IXTraceToSend; safecall;
function Get_Debug: IXTraceToSend; safecall;
function Get_WinTraceText: WideString; safecall;
procedure Set_WinTraceText(const Value: WideString); safecall;
procedure SaveToTextfile(const Filename: WideString); safecall;
procedure SaveToXml(const Filename: WideString; const StyleSheet: WideString); safecall;
procedure LoadXml(const Filename: WideString); safecall;
procedure DisplayWin; safecall;
procedure setMultiColumn(MainColIndex: SYSINT); safecall;
procedure setColumnsTitle(const Titles: WideString); safecall;
procedure setColumnsWidth(const Widths: WideString); safecall;
procedure ClearAll; safecall;
procedure setLogFile(const Filename: WideString; Mode: LogMode; MaxLines: Integer); safecall;
procedure Close; safecall;
property Warning: IXTraceToSend read Get_Warning;
property Error: IXTraceToSend read Get_Error;
property Debug: IXTraceToSend read Get_Debug;
property WinTraceText: WideString read Get_WinTraceText write Set_WinTraceText;
end;
// *********************************************************************//
// DispIntf: IXWinTraceDisp
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {4365CFCE-6247-4F05-ADBB-2F42FF8B6348}
// *********************************************************************//
IXWinTraceDisp = dispinterface
['{4365CFCE-6247-4F05-ADBB-2F42FF8B6348}']
property Warning: IXTraceToSend readonly dispid 300;
property Error: IXTraceToSend readonly dispid 301;
property Debug: IXTraceToSend readonly dispid 302;
property WinTraceText: WideString dispid 303;
procedure SaveToTextfile(const Filename: WideString); dispid 304;
procedure SaveToXml(const Filename: WideString; const StyleSheet: WideString); dispid 305;
procedure LoadXml(const Filename: WideString); dispid 306;
procedure DisplayWin; dispid 307;
procedure setMultiColumn(MainColIndex: SYSINT); dispid 308;
procedure setColumnsTitle(const Titles: WideString); dispid 309;
procedure setColumnsWidth(const Widths: WideString); dispid 310;
procedure ClearAll; dispid 311;
procedure setLogFile(const Filename: WideString; Mode: LogMode; MaxLines: Integer); dispid 312;
procedure Close; dispid 401;
function Send(const LeftMsg: WideString; const RightMsg: WideString): IXTraceNode; dispid 250;
function SendObject(const LeftMsg: WideString; Obj: OleVariant): IXTraceNode; dispid 251;
function SendValue(const LeftMsg: WideString; Obj: OleVariant; const ObjTitle: WideString): IXTraceNode; dispid 252;
function SendValueIDisptach(const LeftMsg: WideString; const Obj: IDispatch;
const ObjTitle: WideString): IXTraceNode; dispid 253;
function SendDump(const LeftMsg: WideString; const ShortTitle: WideString;
Adress: {??PChar}OleVariant; Count: SYSINT): IXTraceNode; dispid 254;
procedure SendTable(const LeftMsg: WideString; var Table: IXTraceTable); dispid 255;
procedure SendXml(const LeftMsg: WideString; const Xml: WideString); dispid 256;
procedure SendBackgroundColor(const LeftMsg: WideString; Color: SYSINT; ColId: SYSINT); dispid 257;
procedure EnterMethod(const LeftMsg: WideString; const RightMsg: WideString); dispid 258;
procedure ExitMethod(const LeftMsg: WideString; const RightMsg: WideString); dispid 259;
procedure Indent(const LeftMsg: WideString; const RightMsg: WideString); dispid 260;
procedure UnIndent(const LeftMsg: WideString; const RightMsg: WideString); dispid 261;
property Id: WideString dispid 200;
property Enabled: WordBool dispid 201;
property IconIndex: SYSINT dispid 202;
property Tag: SYSINT dispid 203;
property WinTraceId: WideString dispid 204;
function CreateNodeEx: IXTraceNodeEx; dispid 205;
end;
// *********************************************************************//
// Interface: IXTraceTable
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {1EF2CA18-A338-4F31-A420-6F03C4FEFE63}
// *********************************************************************//
IXTraceTable = interface(IDispatch)
['{1EF2CA18-A338-4F31-A420-6F03C4FEFE63}']
procedure AddColumnTitle(const ColTitle: WideString); safecall;
procedure AddRow; safecall;
procedure AddRowData(const Cell: WideString); safecall;
function GetTitle: WideString; safecall;
function GetRowData(Row: Integer): WideString; safecall;
function Get_RowCount: Integer; safecall;
property RowCount: Integer read Get_RowCount;
end;
// *********************************************************************//
// DispIntf: IXTraceTableDisp
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {1EF2CA18-A338-4F31-A420-6F03C4FEFE63}
// *********************************************************************//
IXTraceTableDisp = dispinterface
['{1EF2CA18-A338-4F31-A420-6F03C4FEFE63}']
procedure AddColumnTitle(const ColTitle: WideString); dispid 201;
procedure AddRow; dispid 202;
procedure AddRowData(const Cell: WideString); dispid 203;
function GetTitle: WideString; dispid 204;
function GetRowData(Row: Integer): WideString; dispid 205;
property RowCount: Integer readonly dispid 206;
end;
// *********************************************************************//
// The Class CoXTrace provides a Create and CreateRemote method to
// create instances of the default interface IXTrace exposed by
// the CoClass XTrace. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXTrace = class
class function Create: IXTrace;
class function CreateRemote(const MachineName: string): IXTrace;
end;
// *********************************************************************//
// The Class CoXTraceNodeEx provides a Create and CreateRemote method to
// create instances of the default interface IXTraceNodeEx exposed by
// the CoClass XTraceNodeEx. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXTraceNodeEx = class
class function Create: IXTraceNodeEx;
class function CreateRemote(const MachineName: string): IXTraceNodeEx;
end;
// *********************************************************************//
// The Class CoXMemberNode provides a Create and CreateRemote method to
// create instances of the default interface IXMemberNode exposed by
// the CoClass XMemberNode. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMemberNode = class
class function Create: IXMemberNode;
class function CreateRemote(const MachineName: string): IXMemberNode;
end;
// *********************************************************************//
// The Class CoXWinWatch provides a Create and CreateRemote method to
// create instances of the default interface IXWinWatch exposed by
// the CoClass XWinWatch. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXWinWatch = class
class function Create: IXWinWatch;
class function CreateRemote(const MachineName: string): IXWinWatch;
end;
// *********************************************************************//
// The Class CoXTraceOptions provides a Create and CreateRemote method to
// create instances of the default interface IXTraceOptions exposed by
// the CoClass XTraceOptions. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXTraceOptions = class
class function Create: IXTraceOptions;
class function CreateRemote(const MachineName: string): IXTraceOptions;
end;
// *********************************************************************//
// The Class CoXWinTrace provides a Create and CreateRemote method to
// create instances of the default interface IXWinTrace exposed by
// the CoClass XWinTrace. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXWinTrace = class
class function Create: IXWinTrace;
class function CreateRemote(const MachineName: string): IXWinTrace;
end;
// *********************************************************************//
// The Class CoXTraceNode provides a Create and CreateRemote method to
// create instances of the default interface IXTraceNode exposed by
// the CoClass XTraceNode. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXTraceNode = class
class function Create: IXTraceNode;
class function CreateRemote(const MachineName: string): IXTraceNode;
end;
// *********************************************************************//
// The Class CoXTraceToSend provides a Create and CreateRemote method to
// create instances of the default interface IXTraceToSend exposed by
// the CoClass XTraceToSend. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXTraceToSend = class
class function Create: IXTraceToSend;
class function CreateRemote(const MachineName: string): IXTraceToSend;
end;
// *********************************************************************//
// The Class CoXTraceTable provides a Create and CreateRemote method to
// create instances of the default interface IXTraceTable exposed by
// the CoClass XTraceTable. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXTraceTable = class
class function Create: IXTraceTable;
class function CreateRemote(const MachineName: string): IXTraceTable;
end;
implementation
uses ComObj;
class function CoXTrace.Create: IXTrace;
begin
Result := CreateComObject(CLASS_XTrace) as IXTrace;
end;
class function CoXTrace.CreateRemote(const MachineName: string): IXTrace;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XTrace) as IXTrace;
end;
class function CoXTraceNodeEx.Create: IXTraceNodeEx;
begin
Result := CreateComObject(CLASS_XTraceNodeEx) as IXTraceNodeEx;
end;
class function CoXTraceNodeEx.CreateRemote(const MachineName: string): IXTraceNodeEx;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XTraceNodeEx) as IXTraceNodeEx;
end;
class function CoXMemberNode.Create: IXMemberNode;
begin
Result := CreateComObject(CLASS_XMemberNode) as IXMemberNode;
end;
class function CoXMemberNode.CreateRemote(const MachineName: string): IXMemberNode;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMemberNode) as IXMemberNode;
end;
class function CoXWinWatch.Create: IXWinWatch;
begin
Result := CreateComObject(CLASS_XWinWatch) as IXWinWatch;
end;
class function CoXWinWatch.CreateRemote(const MachineName: string): IXWinWatch;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XWinWatch) as IXWinWatch;
end;
class function CoXTraceOptions.Create: IXTraceOptions;
begin
Result := CreateComObject(CLASS_XTraceOptions) as IXTraceOptions;
end;
class function CoXTraceOptions.CreateRemote(const MachineName: string): IXTraceOptions;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XTraceOptions) as IXTraceOptions;
end;
class function CoXWinTrace.Create: IXWinTrace;
begin
Result := CreateComObject(CLASS_XWinTrace) as IXWinTrace;
end;
class function CoXWinTrace.CreateRemote(const MachineName: string): IXWinTrace;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XWinTrace) as IXWinTrace;
end;
class function CoXTraceNode.Create: IXTraceNode;
begin
Result := CreateComObject(CLASS_XTraceNode) as IXTraceNode;
end;
class function CoXTraceNode.CreateRemote(const MachineName: string): IXTraceNode;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XTraceNode) as IXTraceNode;
end;
class function CoXTraceToSend.Create: IXTraceToSend;
begin
Result := CreateComObject(CLASS_XTraceToSend) as IXTraceToSend;
end;
class function CoXTraceToSend.CreateRemote(const MachineName: string): IXTraceToSend;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XTraceToSend) as IXTraceToSend;
end;
class function CoXTraceTable.Create: IXTraceTable;
begin
Result := CreateComObject(CLASS_XTraceTable) as IXTraceTable;
end;
class function CoXTraceTable.CreateRemote(const MachineName: string): IXTraceTable;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XTraceTable) as IXTraceTable;
end;
end.
|
unit uFormSelectSource_VCL;
{$I DelphiTwain.inc}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
interface
uses
SysUtils, Types, Variants, Classes, Graphics,
Controls, Forms, Dialogs, ExtCtrls, StdCtrls;
type
TFormSelectSource = class(TForm)
protected
procedure DoCreate; override;
public
LBSources: TListBox;
PnlBottom: TPanel;
BtnOK: TButton;
BtnCancel: TButton;
procedure FormResize(Sender: TObject);
procedure LBSourcesDblClick(Sender: TObject);
end;
implementation
uses DelphiTwainLang;
procedure TFormSelectSource.DoCreate;
var
xM: TMonitor;
xR: TRect;
begin
inherited;
Caption := DELPHITWAIN_SelectSource;
Position := poDesigned;
Width := 300;
Height := 200;
xM := Screen.MonitorFromPoint(Mouse.CursorPos);
xR := xM.WorkareaRect;
Left := (xR.Left+xR.Right-Width) div 2;
Top := (xR.Top+xR.Bottom-Height) div 2;
BorderIcons := [biSystemMenu];
LBSources := TListBox.Create(Self);
LBSources.Parent := Self;
LBSources.Align := alClient;
{$IFDEF DELPHI_2009_UP}
LBSources.AlignWithMargins := True;
{$ENDIF}
LBSources.OnDblClick := LBSourcesDblClick;
PnlBottom := TPanel.Create(Self);
PnlBottom.Parent := Self;
PnlBottom.Height := 41;
PnlBottom.Top := Self.Height;
PnlBottom.Align := alBottom;
PnlBottom.BevelOuter := bvNone;
BtnOk := TButton.Create(Self);
BtnOk.Parent := PnlBottom;
BtnOk.ModalResult := mrOk;
BtnOk.Caption := DELPHITWAIN_OK;
BtnOk.Default := True;
BtnCancel := TButton.Create(Self);
BtnCancel.Parent := PnlBottom;
BtnCancel.ModalResult := mrCancel;
BtnCancel.Caption := DELPHITWAIN_Cancel;
OnResize := FormResize;
FormResize(nil);
end;
procedure TFormSelectSource.LBSourcesDblClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TFormSelectSource.FormResize(Sender: TObject);
begin
BtnCancel.Left := PnlBottom.ClientWidth - BtnCancel.Width - 6;
BtnOK.Left := BtnCancel.Left - BtnOK.Width - 6;
BtnCancel.Top := (PnlBottom.ClientHeight - BtnCancel.Height) div 2;
BtnOK.Top := BtnCancel.Top;
end;
end.
|
unit ATxNextFile;
interface
uses
Windows, TntClasses;
type
TATNextFile = (nfNext, nfPrev, nfCurrent);
TATFileSort = (fsName, fsNameDesc, fsExt, fsExtDesc);
type
TATFileList = class
private
FList: TTntStringList;
FListCountLimit: integer;
FDirectory: WideString;
FSortOrder: TATFileSort;
FLocked: boolean;
FLockedDir: boolean;
FListIndex: integer;
FSkipHidden: boolean;
FExtIgnore: string;
FExtIgnoreUse: boolean;
procedure SetLocked(AValue: boolean);
function GetCount: integer;
function GetItem(AIndex: integer): WideString;
function IndexBad(n: integer): boolean;
function IndexGot(n: integer): boolean;
public
constructor Create;
destructor Destroy; override;
function ReadDirectory(const ADirName: WideString): boolean;
function ReadFileList(const AFileName: WideString): boolean;
function GetFirst: WideString;
function GetNext(const AFileName: WideString; ANext: TATNextFile; AMessage: boolean = false): WideString;
procedure Delete(const AFileName: WideString);
procedure ShowList;
property SortOrder: TATFileSort read FSortOrder write FSortOrder;
property Locked: boolean read FLocked write SetLocked;
property LockedDir: boolean read FLockedDir write FLockedDir;
property Count: integer read GetCount;
property ListIndex: integer read FListIndex;
property SkipHidden: boolean read FSkipHidden write FSkipHidden;
property ExtIgnore: string read FExtIgnore write FExtIgnore;
property ExtIgnoreUse: boolean read FExtIgnoreUse write FExtIgnoreUse;
end;
implementation
uses
SysUtils, Classes, Forms,
ATxFProc, ATxSProc, ATViewerMsg, ATxMsg;
{ Helper functions }
const
cListCountLimit = 200; //Limit of files num (used for nfCurrent)
var
FGlobalSortOrder: TATFileSort = fsExt;
//get: s1 - filename without number and ext,
// s2 - number (at the end), sExt - extension.
procedure SFilenameParts(const fn: WideString; var s1, s2, sExt: WideString);
begin
sExt:= SExtractFileExt(fn);
s1:= Copy(fn, 1, Length(fn) - Length(sExt));
s2:= '';
while (s1 <> '') and (Char(s1[Length(s1)]) in ['0'..'9']) do
begin
s2:= s1[Length(s1)] + s2;
Delete(s1, Length(s1), 1);
end;
end;
function CompareFNames(const fn1, fn2: WideString): Integer;
var
ss1, ss2, sn1, sn2, sExt1, sExt2: WideString;
begin
SFilenameParts(fn1, ss1, sn1, sExt1);
SFilenameParts(fn2, ss2, sn2, sExt2);
//MsgInfo(Format('1: %s %s %s, 2: %s %s %s', [ss1, sn1, sExt1, ss2, sn2, sExt2]));
Result:= SCompareIW(ss1, ss2);
if Result = 0 then
Result:= StrToIntDef(sn1, 0) - StrToIntDef(sn2, 0);
if Result = 0 then
Result:= SCompareIW(sExt1, sExt2);
end;
function ListCompare(List: TTntStringList; Index1, Index2: integer): integer;
var
fn1, fn2: WideString;
begin
fn1:= List[Index1];
fn2:= List[Index2];
case FGlobalSortOrder of
fsExt,
fsExtDesc:
begin
Result:= SCompareIW(SExtractFileExt(fn1), SExtractFileExt(fn2));
if Result = 0 then
Result:= CompareFNames(fn1, fn2);
if FGlobalSortOrder = fsExtDesc then
Result:= -Result;
end;
fsName,
fsNameDesc:
begin
Result:= CompareFNames(fn1, fn2);
if FGlobalSortOrder = fsNameDesc then
Result:= -Result;
end;
else
Result:= 0;
end;
end;
{ TATFileList }
constructor TATFileList.Create;
begin
inherited;
FList:= TTntStringList.Create;
FListCountLimit:= 0;
with FList do
begin
Duplicates:= dupIgnore;
Sorted:= false;
CaseSensitive:= false;
end;
FDirectory:= '';
FSortOrder:= fsExt;
FLocked:= false;
FLockedDir:= false;
FListIndex:= -1;
FSkipHidden:= true;
end;
destructor TATFileList.Destroy;
begin
FreeAndNil(FList);
inherited;
end;
function TATFileList.GetItem(AIndex: integer): WideString;
begin
Result:= '';
if (AIndex >= 0) and (AIndex < FList.Count) then
begin
FListIndex:= AIndex;
if FLocked and not (FLockedDir) then
Result:= FList[AIndex]
else
Result:= FDirectory + '\' + FList[AIndex];
end;
end;
function TATFileList.GetFirst: WideString;
begin
Result:= GetItem(0);
end;
function TATFileList.ReadDirectory(const ADirName: WideString): boolean;
var
h: THandle;
fdA: TWin32FindDataA;
fdW: TWin32FindDataW;
fn, dir: string;
fnW: WideString;
IsDir, IsHidden, IsSystem: boolean;
begin
Result:=
IsDirExist(ADirName) or
IsFileOrDirExist(ADirName + '\*.*');
if not Result then Exit;
FDirectory:= ADirName;
FList.Clear;
h:= INVALID_HANDLE_VALUE;
try
if Win32Platform=VER_PLATFORM_WIN32_NT then
begin
h:= FindFirstFileW(PWChar(ADirName+'\*.*'), fdW);
if h<>INVALID_HANDLE_VALUE then
repeat
fnW:= fdW.cFileName;
//if Length(fnW)>MAX_PATH then SetLength(fnW, MAX_PATH);
//if (fnW='.') or (fnW='..') then Continue;
IsDir:= (fdW.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY)<>0;
IsHidden:= (fdW.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN)<>0;
IsSystem:= (fdW.dwFileAttributes and FILE_ATTRIBUTE_SYSTEM)<>0;
if (not IsDir) and ((not FSkipHidden) or (not IsHidden)) and (not IsSystem) then
FList.Add(fnW);
if (FListCountLimit > 0) and
(FList.Count >= FListCountLimit) then Break;
until not FindNextFileW(h, fdW);
end
else
begin
dir:= string(ADirName);
h:= FindFirstFileA(PAnsiChar(dir+'\*.*'), fdA);
if h<>INVALID_HANDLE_VALUE then
repeat
fn:= fdA.cFileName;
//if Length(fn)>MAX_PATH then SetLength(fn, MAX_PATH);
//if (fn='.') or (fn='..') then Continue;
IsDir:= (fdA.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY)<>0;
IsHidden:= (fdA.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN)<>0;
IsSystem:= (fdA.dwFileAttributes and FILE_ATTRIBUTE_SYSTEM)<>0;
if (not IsDir) and ((not FSkipHidden) or (not IsHidden)) and (not IsSystem) then
FList.Add(fn);
if (FListCountLimit > 0) and
(FList.Count >= FListCountLimit) then Break;
until not FindNextFileA(h, fdA);
end;
finally
Windows.FindClose(h);
end;
FGlobalSortOrder:= FSortOrder;
FList.CustomSort(ListCompare);
end;
function FReadToString(const FileName: WideString; var S: string): boolean;
const
cMaxFilelistSize = 1024*1024; //Maximal size of a file list
const
cSign: PChar = #$EF#$BB#$BF;
var
Buffer: PChar;
BufferSize, ReadSize: DWORD;
Handle: THandle;
begin
Result:= false;
S:= '';
Handle:= FFileOpen(FileName);
if Handle<>INVALID_HANDLE_VALUE then
try
Buffer:= nil;
BufferSize:= DWORD(FGetFileSize(Handle));
if BufferSize > cMaxFilelistSize then Exit;
GetMem(Buffer, BufferSize);
if ReadFile(Handle, Buffer^, BufferSize, ReadSize, nil) then
begin
SetString(S, Buffer, ReadSize);
if Copy(S, 1, Length(cSign))=cSign then
Delete(S, 1, Length(cSign));
Result:= true;
end;
finally
if Assigned(Buffer) then
FreeMem(Buffer);
CloseHandle(Handle);
end;
end;
function SGetItem(var SList: string): string;
const
CR1 = #13#10;
CR2 = #13;
var
k: integer;
len: integer;
begin
k:= Pos(CR1, SList);
if k>0 then
len:= Length(CR1)
else
begin
k:= Pos(CR2, SList);
if k>0 then
len:= Length(CR2)
else
begin
k:= MaxInt;
len:= 0;
end;
end;
Result:= Copy(SList, 1, k-1);
Delete(SList, 1, k+len-1);
end;
function TATFileList.ReadFileList(const AFileName: WideString): boolean;
var
S: string;
Item: Widestring;
IsRTF, IsUTF: boolean;
begin
Result:= false;
FDirectory:= '';
FList.Clear;
if not FReadToString(AFileName, S) then
begin
MsgError(SFormatW(MsgViewerErrInvalidFilelist, [AFileName]));
Exit;
end;
IsFileRTFAndUTF8(AFileName, IsRTF, IsUTF);
repeat
if IsUTF then
Item:= UTF8Decode(SGetItem(S))
else
Item:= SGetItem(S);
if Item = '' then Break;
if (FList.Count = 0) and (not IsFileExist(Item)) then
begin
MsgWarning(SFormatW(MsgViewerErrCannotFindFile, [Item]));
Exit;
end;
FList.Add(Item);
until false;
//Delete filelist only when success
//(filelist contains at last 1 valid file name):
FDeleteToRecycle(Application.Handle, AFileName, false);
Locked:= true;
Result:= true;
end;
function TATFileList.GetNext(
const AFileName: WideString;
ANext: TATNextFile;
AMessage: boolean = false): WideString;
var
fnW, dirW: WideString;
n: integer;
s: string;
begin
Result:= '';
FListIndex:= -1;
//Limit file count when ANext=nfCurrent
if ANext = nfCurrent then
FListCountLimit:= cListCountLimit
else
FListCountLimit:= 0;
fnW:= SExtractFileName(AFileName);
dirW:= SExtractFileDir(AFileName);
SDelLastSlashW(dirW); //Case of root folder
if dirW = '' then dirW:= '.'; //Case of filename without path
if not FLocked then
if not ReadDirectory(dirW) then
begin
if AMessage then
MsgWarning(MsgViewerJumpDirEmpty);
Exit
end;
//debug
//MsgInfo('Debug:'#13'dir: '+dirW+#13'file: '+fnW+#13'files count: '+IntToStr(FList.Count));
if FList.Count = 0 then
begin
if AMessage then
MsgWarning(MsgViewerJumpDirEmpty);
Exit
end;
if FLocked and (not FLockedDir) then
n:= FList.IndexOf(AFileName)
else
n:= FList.IndexOf(fnW);
//File not found in directory
if n < 0 then
begin
if ANext = nfCurrent then Exit;
if (not AMessage) or (MsgBox(SFormatW(MsgViewerJumpNotFound, [fnW]), MsgViewerCaption, MB_OKCANCEL or MB_ICONWARNING)=IDOK)
then Result:= GetFirst else Exit;
end
else
begin
//File is single in directory
if FList.Count = 1 then
begin
if AMessage then
MsgWarning(SFormatW(MsgViewerJumpSingleFile, [fnW]));
Exit;
end;
//Some files in directory
case ANext of
nfNext,
nfPrev:
begin
if ANext=nfNext then S:= MsgViewerJumpToFirst else S:= MsgViewerJumpToLast;
repeat
if ANext=nfNext then Inc(n) else Dec(n);
until IndexGot(n);
if IndexBad(n) then
if (not AMessage) or (MsgBox(S, MsgViewerCaption, MB_OKCANCEL or MB_ICONWARNING)=IDOK) then
begin
if ANext=nfNext then n:= -1 else n:= FList.Count;
repeat
if ANext=nfNext then Inc(n) else Dec(n);
until IndexGot(n);
if IndexBad(n) then Exit;
end
else
Exit;
Result:= GetItem(n);
end;
nfCurrent:
//For current file: just update FListIndex (callGetItem)
Result:= GetItem(n);
end;
end;
end;
procedure TATFileList.ShowList;
var
S: WideString;
i: integer;
begin
S:= '';
for i:= 0 to FList.Count-1 do
S:= S+GetItem(i)+#13;
MsgInfo('File list:'#13#13+S);
end;
procedure TATFileList.SetLocked(AValue: boolean);
begin
FLocked:= AValue;
FLockedDir:= false;
if not FLocked then
begin
FList.Clear;
FListIndex:= -1;
end;
end;
function TATFileList.GetCount: integer;
begin
Result:= FList.Count;
end;
procedure TATFileList.Delete(const AFileName: WideString);
var
i: integer;
begin
for i:= 0 to FList.Count - 1 do
if SCompareIW(AFileName, GetItem(i)) = 0 then
begin
FList.Delete(i);
Break;
end;
end;
function TATFileList.IndexGot(n: integer): boolean;
begin
Result := IndexBad(n) or (not FExtIgnoreUse) or (not SFileExtensionMatch(GetItem(n), FExtIgnore));
end;
function TATFileList.IndexBad(n: integer): boolean;
begin
Result := (n < 0) or (n > Pred(FList.Count));
end;
end.
|
unit VoiceRx;
interface
uses
Classes,
DirectSound,
DSoundOut,
CompressIntf;
type
TVoiceRx =
class
public
constructor Create;
destructor Destroy; override;
public
procedure Start;
procedure Stop;
private
fPlayer : TDSoundOut;
fDecompressor : IDecompressor;
procedure SetDecompressor(aDecompressor : IDecompressor);
function GetDirectSound : IDirectSound;
procedure SetDirectSound(const aDSound : IDirectSound);
public
property Decompressor : IDecompressor read fDecompressor write SetDecompressor;
property DirectSound : IDirectSound read GetDirectSound write SetDirectSound;
private
fHold : boolean;
fHoldCount : integer;
//fHoldTime : integer;
procedure SetHold(aHold : boolean);
function PlayerData(var Data; Size : integer) : integer;
private
property Hold : boolean read fHold write SetHold;
private
// fTT : TStream;
end;
implementation
uses
SysUtils;
const
HoldTime = 16;
const
MinHold = 0;
MaxHold = 8000 * 5{seconds} * sizeof(smallint);
constructor TVoiceRx.Create;
begin
inherited Create;
fPlayer := TDSoundOut.Create;
fPlayer.OnData := PlayerData;
//.test fTT := TFileStream.Create('c:\x.raw', fmCreate);
end;
destructor TVoiceRx.Destroy;
begin
Stop;
fPlayer.Free;
//.test fTT.Free;
inherited;
end;
procedure TVoiceRx.Start;
begin
fPlayer.Play;
end;
procedure TVoiceRx.Stop;
begin
fPlayer.Stop;
end;
procedure TVoiceRx.SetDecompressor(aDecompressor : IDecompressor);
var
srate : integer;
bits : integer;
ch : integer;
begin
Stop;
Assert(aDecompressor <> nil);
fDecompressor := aDecompressor;
fDecompressor.GetOutputType(srate, bits, ch);
fPlayer.SamplingRate := srate;
fPlayer.BitsPerSample := bits;
fPlayer.Channels := ch;
end;
function TVoiceRx.GetDirectSound : IDirectSound;
begin
Result := fPlayer.DirectSound;
end;
procedure TVoiceRx.SetDirectSound(const aDSound : IDirectSound);
begin
fPlayer.DirectSound := aDSound;
end;
procedure TVoiceRx.SetHold(aHold : boolean);
begin
if aHold <> fHold
then
begin
fHold := aHold;
if fHold
then fHoldCount := HoldTime
else fHoldCount := 0;
end;
end;
function TVoiceRx.PlayerData(var Data; Size : integer) : integer;
var
Count : integer;
Avail : integer;
begin
if not Hold
then fDecompressor.Convert(Data, Size, Count)
else Count := 0;
if Count < Size
then fillchar(TByteArray(Data)[Count], Size - Count, 0);
fDecompressor.GetAvailData(Avail);
if Avail <= MinHold
then Hold := true
else
if Avail >= MaxHold
then Hold := false;
if fHoldCount > 0
then
begin
dec(fHoldCount);
if fHoldCount = 1
then Hold := false;
end;
//.test if Size > 0
//.test then fTT.Write(Data, Size);
Result := Size;
end;
end.
|
unit HCAdapter; {$Z4}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Модуль: "w:/garant6x/implementation/Garant/HCAdapter/HCAdapter.pas"
// Delphi интерфейсы для адаптера (.pas)
// Generated from UML model, root element: <<AdapterTarget::Category>> garant6x::HCAdapter
//
// Библиотека для взаимодействия сервера консультаций и ПО отдела правовой поддержки
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
interface
uses
SysConst
, SysUtils
, Windows
, Classes
, ActiveX
, IOUnit
, HCInterfacesUnit;
const
CLibraryVersion: LongWord = 237;
CLibraryName: PAnsiChar = 'HCAdapter.dll';
{$IF DEFINED(UseNoServerExceptionEvent)}
var
g_NoServerExceptionEvent: procedure (var a_Exception: Exception) = nil;
{$IFEND} // UseNoServerExceptionEvent
type
// Системные исключения.
ELoadLibraryError = class (Exception); // используется при загрузке dll;
EGetProcAddressError = class (Exception); // используется при вызове операции dll;
EStdException = class (Exception); // используется при мапинге неизвестных Sdt исключений;
ECorbaException = class (Exception); // используется при мапинге неизвестных CORBA исключений;
EWrongVersion = class (Exception); // выбрасывается в случае не соответствия версии клиента и dll
EUnknownFactoryKey = class (Exception); // выбрасывается в случае, если нет ни одного зарегестрированного серванта c заданным ключом для запрашиваемого интерфейса
ECantFindServer = class (Exception); // client-server DLL can't find corresponding server
// exported root factory interface
IHCAdapterRoot = interface (IInterface) ['{FA9E7DCD-7E2B-43FF-8715-865704C0C74B}']
procedure MakeStream (
out aRet {: IStream}
); stdcall; overload;
procedure MakeStream (
const aPath: PAnsiChar;
out aRet {: IStream}
); stdcall; overload;
procedure AllocString (
aMaximum: Longword;
out aRet {: IString}
); stdcall; overload;
procedure MakeString (
const aStr: PAnsiChar;
out aRet {: IString}
); stdcall; overload;
procedure MakeBusinessLogicLifeCycle (
out aRet {: IBusinessLogicLifeCycle}
); stdcall; overload;
procedure MakeConsultingRequests (
out aRet {: IConsultingRequests}
); stdcall; overload;
end;
// DLL wrapper interface
IHCAdapterDll = interface (IInterface)
function GetVersion (): LongWord;
function MakeStream (
) : IStream; overload;
function MakeStream (
const aPath: PAnsiChar
) : IStream; overload;
function AllocString (
aMaximum: Longword
) : IString; overload;
function MakeString (
const aStr: PAnsiChar
) : IString; overload;
function MakeBusinessLogicLifeCycle (
) : IBusinessLogicLifeCycle; overload;
function MakeConsultingRequests (
) : IConsultingRequests; overload;
end;
// DLL wrapper impl
THCAdapterDll = class (TInterfacedObject, IHCAdapterDll)
private
f_HModule: HModule;
f_DllRoot: IHCAdapterRoot;
private
procedure DllLoad;
procedure DllFree;
procedure RootInit(aClientVersion: LongWord); overload;
procedure RootInit(aClientVersion: LongWord; const aLocale: PAnsiChar); overload;
procedure RootDone;
function GetRoot: IHCAdapterRoot;
public
constructor Create (aClientVersion: LongWord); reintroduce; overload;
constructor Create (aClientVersion: LongWord; const aLocale: PAnsiChar); reintroduce; overload;
destructor Destroy; override;
class function Make(): IHCAdapterDll; overload; // can raise ECantFindServer;
class function Make(const aLocale: PAnsiChar): IHCAdapterDll; overload; // can raise ECantFindServer;
function GetVersion: LongWord;
public
function MakeStream (
) : IStream; overload;
function MakeStream (
const aPath: PAnsiChar
) : IStream; overload;
function AllocString (
aMaximum: Longword
) : IString; overload;
function MakeString (
const aStr: PAnsiChar
) : IString; overload;
function MakeBusinessLogicLifeCycle (
) : IBusinessLogicLifeCycle; overload;
function MakeConsultingRequests (
) : IConsultingRequests; overload;
end;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
implementation
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function THCAdapterDll.MakeStream (
) : IStream;
var
aRes: IStream;
begin
GetRoot().MakeStream(aRes);
Result := aRes;
end;
function THCAdapterDll.MakeStream (
const aPath: PAnsiChar
) : IStream;
var
aRes: IStream;
begin
GetRoot().MakeStream(aPath, aRes);
Result := aRes;
end;
function THCAdapterDll.MakeString (
const aStr: PAnsiChar
) : IString;
var
aRes: IString;
begin
GetRoot().MakeString(aStr, aRes);
Result := aRes;
end;
function THCAdapterDll.AllocString (
aMaximum: Longword
) : IString;
var
aRes: IString;
begin
GetRoot().AllocString(aMaximum, aRes);
Result := aRes;
end;
function THCAdapterDll.MakeBusinessLogicLifeCycle (
) : IBusinessLogicLifeCycle;
var
aRes: IBusinessLogicLifeCycle;
begin
GetRoot().MakeBusinessLogicLifeCycle(aRes);
Result := aRes;
end;
function THCAdapterDll.MakeConsultingRequests (
) : IConsultingRequests;
var
aRes: IConsultingRequests;
begin
GetRoot().MakeConsultingRequests(aRes);
Result := aRes;
end;
procedure THCAdapterDll.DllLoad;
function GetOsDependentCatalog: string;
begin
if (Longint (Windows.GetVersion) < 0) then
Result := ExtractFilePath (ParamStr (0))+'win9X'
else
Result := ExtractFilePath (ParamStr (0))+'winNT';
end;
var
l_CurrentDir: string;
l_ErrorMode: UINT;
l_OsDependentCatalog: string;
begin
l_ErrorMode := SetErrorMode (SEM_FAILCRITICALERRORS);
try
l_CurrentDir := GetCurrentDir;
l_OsDependentCatalog := GetOsDependentCatalog;
if SetCurrentDir (l_OsDependentCatalog) then
try
f_HModule := LoadLibraryA (CLibraryName);
(* K: 384075072 *)
if (f_HModule = HMODULE (0)) then
f_HModule := LoadLibraryExA (PAnsiChar (l_OsDependentCatalog+'\'+CLibraryName), 0, LOAD_WITH_ALTERED_SEARCH_PATH);
finally
SetCurrentDir (l_CurrentDir);
end
else
f_HModule := LoadLibraryA (PAnsiChar (l_OsDependentCatalog+'\'+CLibraryName));
if (f_HModule = HMODULE (0)) then
begin
f_HModule := LoadLibraryA (CLibraryName);
if (f_HModule = HMODULE (0)) then
raise ELoadLibraryError.Create ('Dynamic library "'+CLibraryName+'" not found');
end;
finally
SetErrorMode (l_ErrorMode);
end;
end;
procedure THCAdapterDll.DllFree;
begin
if (f_HModule <> HMODULE (0)) then
begin
try
FreeLibrary (f_HModule);
except
end;
end;
end;
constructor THCAdapterDll.Create(aClientVersion: LongWord);
begin
inherited Create;
DllLoad;
RootInit(aClientVersion);
end;
constructor THCAdapterDll.Create (aClientVersion: LongWord; const aLocale: PAnsiChar);
begin
inherited Create;
DllLoad;
RootInit(aClientVersion, aLocale);
end;
destructor THCAdapterDll.Destroy;
begin
f_DllRoot := nil;
RootDone;
DllFree;
inherited;
end;
class function THCAdapterDll.Make(const aLocale: PAnsiChar): IHCAdapterDll;
begin
Result := THCAdapterDll.Create(CLibraryVersion, aLocale);
end;
class function THCAdapterDll.Make: IHCAdapterDll;
begin
Result := THCAdapterDll.Create(CLibraryVersion);
end;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// plain DLL method's wrappers
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function THCAdapterDll.GetVersion: LongWord;
const
CProcName = '_tie_dll_version@0';
type
TProcType = function: Integer; stdcall;
var
l_ProcAddress: Pointer;
begin
l_ProcAddress := GetProcAddress (f_HModule, PAnsiChar (CProcName));
if (not Assigned (l_ProcAddress)) then
raise EGetProcAddressError.Create ('DLL method not found: '+CLibraryName+'.'+CProcName);
Result := TProcType (l_ProcAddress);
end;
function THCAdapterDll.GetRoot: IHCAdapterRoot;
const
CProcName = '_tie_dll_get_root@4';
type
TProcType = procedure (out aRoot{: IHCAdapterRoot}); stdcall;
var
l_ProcAddress: Pointer;
begin
if (not Assigned (f_DllRoot)) then
begin
l_ProcAddress := GetProcAddress (f_HModule, PAnsiChar (CProcName));
if (not Assigned (l_ProcAddress)) then
raise EGetProcAddressError.Create ('DLL method not found: '+CLibraryName+'.'+CProcName);
TProcType (l_ProcAddress)(f_DllRoot);
end;
Result := f_DllRoot;
end;
procedure THCAdapterDll.RootInit (aClientVersion: LongWord; const aLocale: PAnsiChar);
const
CProcName = '_tie_dll_init_with_locale@8';
type
TProcType = procedure (aClientVersion: LongWord; const aLocale: PAnsiChar); stdcall;
var
l_ProcAddress: Pointer;
begin
l_ProcAddress := GetProcAddress (f_HModule, PAnsiChar (CProcName));
if (not Assigned (l_ProcAddress)) then
raise EGetProcAddressError.Create ('DLL method not found: '+CLibraryName+'.'+CProcName);
TProcType (l_ProcAddress) (aClientVersion, aLocale);
end;
procedure THCAdapterDll.RootInit(aClientVersion: LongWord);
const
CProcName = '_tie_dll_init@4';
type
TProcType = procedure (aClientVersion: LongWord); stdcall;
var
l_ProcAddress: Pointer;
begin
l_ProcAddress := GetProcAddress (f_HModule, PAnsiChar (CProcName));
if (not Assigned (l_ProcAddress)) then
raise EGetProcAddressError.Create ('DLL method not found: '+CLibraryName+'.'+CProcName);
TProcType (l_ProcAddress) (aClientVersion);
end;
procedure THCAdapterDll.RootDone;
const
CProcName = '_tie_dll_done@0';
type
TProcType = procedure; stdcall;
var
l_ProcAddress: Pointer;
begin
if f_HModule <> HMODULE (0) then
begin
l_ProcAddress := GetProcAddress (f_HModule, PAnsiChar (CProcName));
if (not Assigned (l_ProcAddress)) then
raise EGetProcAddressError.Create ('DLL method not found: '+CLibraryName+'.'+CProcName);
TProcType (l_ProcAddress);
end;
end;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// exception maping support
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type
TExceptionIdMapItem = record
rId: AnsiString;
rEClass: ExceptClass;
rMessage: string;
end;
resourcestring
// "Нормальные" текстовые сообщения для исключений, которые "видит" пользователь.
// (!) Общий формат для имен: строка с именем `S<ИмяИсключения>` соответствует классу с именем `E<ИмяИсключения>`.
//
_SNotImplemented = 'функция не реализована';
_SOperationError = 'Во время выполнения операции copy_to один из потоков, участвовавших в операции перешёл в некорректное состояние.';
_SCantFindXerces = 'Не смогли загрузить библиотеку для работы с XML';
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const
// Карта [map] перекодировки: текстовой строке ставиться в соответствие нужный мета-класс исключения и сообщение.
//
cIdToExceptionMapMaxItems = 8; // максимальное количество элементов в таблице
type
TIdToExceptionMapArray = array [0..cIdToExceptionMapMaxItems - 1] of TExceptionIdMapItem;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type
TIdToExceptionMap = class(TObject)
private
f_Map: TIdToExceptionMapArray;
public
constructor Create;
reintroduce;
function ConvertIdToIndex(const aId: PAnsiChar; out aIndex: Longword): Boolean;
function GetExceptionClass(anIndex: Longword): ExceptClass;
function CreateException(anIndex: Longword): Exception;
end;
{TIdToExceptionMap}
function TIdToExceptionMap.ConvertIdToIndex(const aId: PAnsiChar; out aIndex: Longword): Boolean;
var
l_Index: Longword;
begin
Result := False;
aIndex := 0;
for l_Index := Low (f_Map) to High (f_Map) do
if (StrComp (aId, PAnsiChar (f_Map[l_Index].rId)) = 0) then
begin
aIndex := l_Index;
Result := True;
Break;
end;
end;
constructor TIdToExceptionMap.Create;
procedure lp_Init(anIndex: Longword; const aGUID, aMessage: string; const aClass: ExceptClass);
begin
with f_Map[anIndex] do
begin
rId := aGUID;
rEClass := aClass;
rMessage := aMessage;
end;
end;
begin
inherited Create;
// заполнение f_Map
lp_Init (0, '0000-0000-0000-0000-000000000000', 'dummy exception', EStdException);
lp_Init (1, '4DDEBC97-3F88-4811-9423-8BDEE07A9C21', 'Выход за границы массива', EListError);
lp_Init (2, '69708A24-C2D3-4685-8016-7E2FD8A5888C', 'Неправильная версия ДЛЛ', EWrongVersion);
lp_Init (3, '42540CD0-2B0C-45F2-82DB-0474D2D29867', 'No one servant was registers in factory with a given key', EUnknownFactoryKey);
lp_Init (4, 'F11331C9-6903-4F59-9876-78B3CCEE3209', 'DLL can''t find corresponding server', ECantFindServer);
lp_Init (5, 'F5A55B66-C39A-4758-BE4D-844DE9E142A4', '_SOperationError', EOperationError);
lp_Init (6, 'BA9EDABD-A788-46FF-B5C3-45E967EFEE3C', '_SNotImplemented', ENotImplemented);
lp_Init (7, '55D0E5EB-A193-459C-B12C-8C926D673910', '_SCantFindXerces', ECantFindXerces);
end;
function TIdToExceptionMap.CreateException(anIndex: Longword): Exception;
begin
with f_Map [anIndex] do
Result := rEClass.Create (rMessage);
end;
function TIdToExceptionMap.GetExceptionClass(anIndex: Longword): ExceptClass;
begin
Result := f_Map [anIndex].rEClass;
end;
var
g_ExceptionMap: TIdToExceptionMap = nil;
var
gExceptClsProc: Pointer;
gExceptObjProc: Pointer;
function GetExceptionClass (aExceptionRecord: PExceptionRecord): ExceptClass;
type
TExceptClsProc = function (aExceptionRecord: PExceptionRecord): ExceptClass;
var
lIndex: Cardinal;
begin
Result := nil;
case aExceptionRecord^.ExceptionCode of
DWORD ($E0040200):
begin
if (
((aExceptionRecord^.ExceptionFlags and EXCEPTION_NONCONTINUABLE) <> 0)
and (aExceptionRecord^.NumberParameters = 0)
) then
begin
Result := EOutOfMemory;
end;
end;
DWORD ($E0040201):
begin
if (
((aExceptionRecord^.ExceptionFlags and EXCEPTION_NONCONTINUABLE) <> 0)
and (aExceptionRecord^.NumberParameters = 1)
and (aExceptionRecord^.ExceptionInformation [0] <> 0)
) then
begin
Result := EStdException;
end;
end;
DWORD ($E0040202):
begin
if (
((aExceptionRecord^.ExceptionFlags and EXCEPTION_NONCONTINUABLE) <> 0)
and (aExceptionRecord^.NumberParameters = 1)
and (aExceptionRecord^.ExceptionInformation [0] <> 0)
) then
begin
Result := ECorbaException;
end;
end;
DWORD ($E0040203):
begin
if (
((aExceptionRecord^.ExceptionFlags and EXCEPTION_NONCONTINUABLE) <> 0)
and (aExceptionRecord^.NumberParameters = 1)
and (aExceptionRecord^.ExceptionInformation [0] <> 0)
and g_ExceptionMap.ConvertIdToIndex (PAnsiChar (aExceptionRecord^.ExceptionInformation [0]), lIndex)
) then
begin
Result := g_ExceptionMap.GetExceptionClass(lIndex);
end
else
if (
((aExceptionRecord^.ExceptionFlags and EXCEPTION_NONCONTINUABLE) <> 0)
and (aExceptionRecord^.NumberParameters = 2)
and (aExceptionRecord^.ExceptionInformation [0] = 0)
and (aExceptionRecord^.ExceptionInformation [1] <> 0)
) then
begin
Result := g_ExceptionMap.GetExceptionClass(aExceptionRecord^.ExceptionInformation [1]);
end;
end;
end;
if (
Result = nil
) then
begin
Result := TExceptClsProc (gExceptClsProc) (aExceptionRecord);
end;
end;
var
g_CorbaExceptionMessage : String = '';
g_StdExceptionMessage : String = '';
function GetExceptionObject (aExceptionRecord: PExceptionRecord): Exception;
type
TExceptObjProc = function (aExceptionRecord: PExceptionRecord): Exception;
var
lIndex: Cardinal;
begin
Result := nil;
case aExceptionRecord^.ExceptionCode of
DWORD ($E0040200):
begin
if (
((aExceptionRecord^.ExceptionFlags and EXCEPTION_NONCONTINUABLE) <> 0)
and (aExceptionRecord^.NumberParameters = 0)
) then
begin
// (!) Специальный трюк: это исключение о "нехватке" памяти и оно не может быть создано динамически.
try
OutOfMemoryError ();
except
on l_Exception: EOutOfMemory do Result := l_Exception;
end;
end;
end;
DWORD ($E0040201):
begin
if ((aExceptionRecord^.ExceptionFlags and EXCEPTION_NONCONTINUABLE) <> 0) then
begin
if (
(aExceptionRecord^.NumberParameters = 1)
and (aExceptionRecord^.ExceptionInformation [0] <> 0)
) then
begin
try
g_StdExceptionMessage := PAnsiChar (aExceptionRecord^.ExceptionInformation [0]);
Result := EStdException.Create (g_StdExceptionMessage);
finally
try
CoTaskMemFree (Pointer (aExceptionRecord^.ExceptionInformation [0]));
finally
aExceptionRecord^.NumberParameters := 2;
aExceptionRecord^.ExceptionInformation [0] := 0;
aExceptionRecord^.ExceptionInformation [1] := DWORD (-1);
end;
end;
end
else
begin
if (
(aExceptionRecord^.NumberParameters = 2)
and (aExceptionRecord^.ExceptionInformation [0] = 0)
and (aExceptionRecord^.ExceptionInformation [1] = DWORD (-1))
) then
begin
Result := EStdException.Create (g_StdExceptionMessage);
end;
end;
end;
end;
DWORD ($E0040202):
begin
if ((aExceptionRecord^.ExceptionFlags and EXCEPTION_NONCONTINUABLE) <> 0) then
begin
if (
(aExceptionRecord^.NumberParameters = 1)
and (aExceptionRecord^.ExceptionInformation [0] <> 0)
) then
begin
try
g_CorbaExceptionMessage := PAnsiChar (aExceptionRecord^.ExceptionInformation [0]);
Result := ECorbaException.Create (g_CorbaExceptionMessage);
finally
try
CoTaskMemFree (Pointer (aExceptionRecord^.ExceptionInformation [0]));
finally
aExceptionRecord^.NumberParameters := 2;
aExceptionRecord^.ExceptionInformation [0] := 0;
aExceptionRecord^.ExceptionInformation [1] := DWORD (-1);
end;
end;
end
else
begin
if (
(aExceptionRecord^.NumberParameters = 2)
and (aExceptionRecord^.ExceptionInformation [0] = 0)
and (aExceptionRecord^.ExceptionInformation [1] = DWORD (-1))
) then
begin
Result := ECorbaException.Create (g_CorbaExceptionMessage);
end;
end;
end;
end;
DWORD ($E0040203):
begin
if ((aExceptionRecord^.ExceptionFlags and EXCEPTION_NONCONTINUABLE) <> 0) then
begin
if (
(aExceptionRecord^.NumberParameters = 1)
and (aExceptionRecord^.ExceptionInformation [0] <> 0)
) then
begin
try
if (
g_ExceptionMap.ConvertIdToIndex (PAnsiChar (aExceptionRecord^.ExceptionInformation [0]), lIndex)
) then
begin
Result := g_ExceptionMap.CreateException(lIndex);
end;
finally
try
CoTaskMemFree (Pointer (aExceptionRecord^.ExceptionInformation [0]));
finally
aExceptionRecord^.NumberParameters := 2;
aExceptionRecord^.ExceptionInformation [0] := 0;
aExceptionRecord^.ExceptionInformation [1] := DWORD (lIndex);
end;
end;
end
else
begin
if (
(aExceptionRecord^.NumberParameters = 2)
and (aExceptionRecord^.ExceptionInformation [0] = 0)
and (aExceptionRecord^.ExceptionInformation [1] <> 0)
) then
begin
lIndex := Longword (aExceptionRecord^.ExceptionInformation [1]);
Result := g_ExceptionMap.CreateException(lIndex);
end;
end;
end;
end;
end;
if (Result = nil) then
begin
Result := TExceptObjProc (gExceptObjProc) (aExceptionRecord);
end
else
begin
{$IF DEFINED(UseNoServerExceptionEvent)}
if ((Result is ENoServer) and Assigned(g_NoServerExceptionEvent)) then
begin
g_NoServerExceptionEvent(Result);
end;
{$IFEND} // UseNoServerExceptionEvent
end;
end;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
procedure ExitProc;
begin
ExceptObjProc := gExceptObjProc;
ExceptClsProc := gExceptClsProc;
FreeAndNil(g_ExceptionMap);
end;
procedure InitProc;
begin
g_ExceptionMap := TIdToExceptionMap.Create;
gExceptClsProc := ExceptClsProc;
gExceptObjProc := ExceptObjProc;
//
ExceptClsProc := @GetExceptionClass;
ExceptObjProc := @GetExceptionObject;
end;
//#UC START# *442BEE8500AB_CUSTOM_MAPPINHG_IMPL*
//#UC END# *442BEE8500AB_CUSTOM_MAPPINHG_IMPL*
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
initialization
InitProc;
finalization
ExitProc;
Finalize(g_CorbaExceptionMessage);
Finalize(g_StdExceptionMessage);
end. |
unit First;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, RTTI, IniFiles, TypInfo,
Vcl.ExtCtrls, Vcl.Grids, Vcl.ValEdit, Generics.Collections, System.Generics.Collections;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
RadioGroup1: TRadioGroup;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure RadioGroup1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
// Класс от коротого наследуемся, родитель
{
Наследуемся от этого класса, все объекты от него имеют 2 основных метода:
procedure RestorePublishedProps(name: string
function GetPublishedPropsToStrings(): TStrings;
Т.е. каждый объект наследуемый от данного класса будет иметь возможность
сохранять и восстанавливать свои published параметры.
Сохранение было сделано в INI Файлы.
Тут необходимо заметить, что можно было сделать некую "Обертку" на
сохранение, чтобы в дальнейшем было легко заменить на храние в другом месте,
в БД или реестре.
}
TParent = class(TObject)
var
//Словарь для хранения названия параметров и их значений
PropsDict: TDictionary <string, TValue>;
public
procedure SavePublishedProps(); //Сохраняет в INI файлы публичные параметры
//Восстанавливает параметры из INI файла, название передается в name
procedure RestorePublishedProps(name: string);
//Для работы с TMemo, для наглядности
function GetPublishedPropsToStrings(): TStrings;
private
//Устанавливает значение параметра у по имени и значению НЕ ИСПОЛЬЗУЕТСЯ
//Планироваловась для взаимодействия с объектами формы
procedure SetPublishedPropByName(name: string; value: TValue); virtual;
//Процедура заргужает в Словарь определенный выше (PropsDict) все
//паблишед параметры
procedure GetAllPublishedProps(); virtual;
//Проверка параметра по имени на сущетвование, НЕ ИСПОЛЬЗУЕТСЯ
//Планироваловась для взаимодействия с объектами формы
function IsPropExist(name: string): boolean; virtual;
//Выдает значение параметра по имени, НЕ ИСПОЛЬЗУЕТСЯ
//Планироваловась для взаимодействия с объектами формы
function GetPublishedPropByName(name: string): TValue; virtual;
constructor Create();
destructor Destroy();
end;
TChild1 = class(TParent)
private
FPriNumber : Integer;
public
Int : Integer;
Ch : Char;
I64: Int64;
Fl: Double;
Str : String;
constructor Create();
destructor Destroy();
published
property FPubNumber: Integer read Int write Int;
property FSome: String read Str write Str;
property FBigInt64: Int64 read I64 write I64;
property FChar: Char read Ch write Ch;
property FFloat: Double read Fl write Fl;
end;
TChild2 = class(TParent)
private
public
Int : Integer;
Ch : Char;
I64: Int64;
Fl: Double;
Str : String;
constructor Create();
destructor Destroy();
published
property SPubNumber: Integer read Int write Int;
property SSome: String read Str write Str;
property SBigInt64: Int64 read I64 write I64;
property SChar: Char read Ch write Ch;
property SFloat: Double read Fl write Fl;
end;
var
Form1: TForm1;
Child1: TChild1;
Child2: TChild2;
implementation
{$R *.dfm}
{ TChild2 }
constructor TChild2.Create;
begin
inherited;
Int := 222200;
Ch := 'S';
I64 := 123999999999999321;
Fl := 2.654321;
Str := 'Объекст два';
end;
destructor TChild2.Destroy;
begin
inherited;
end;
{ TChild1 }
constructor TChild1.Create;
begin
inherited;
Int := 1000000;
Ch := 'М';
I64 := 99999999999999;
Fl := 0.123456;
Str := 'Объекст Один';
end;
destructor TChild1.Destroy;
begin
inherited;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
case Form1.RadioGroup1.ItemIndex of
0:
begin
try
Child1.SavePublishedProps();
except
on E: Exception do MessageDlg(E.Message + ' ' + IntToStr(E.HelpContext) ,mtError, mbOKCancel, 0);
end;
end;
1:
begin
try
Child2.SavePublishedProps();
except
on E: Exception do MessageDlg(E.Message + ' ' + IntToStr(E.HelpContext) ,mtError, mbOKCancel, 0);
end;
end;
end;
end;
{ TParent }
procedure TParent.SavePublishedProps;
var
SettingsFile : TCustomIniFile;
Pair: TPair<string, TValue>;
begin
Self.GetAllPublishedProps();
SettingsFile := TMemIniFile.Create(ChangeFileExt(Application.ExeName, '.INI'), TEncoding.UTF8);
SettingsFile.EraseSection(self.ClassName);
try
for Pair in PropsDict do
begin
case Pair.Value.Kind of
tkInteger:
begin
SettingsFile.WriteInteger(self.ClassName, Pair.Key, Pair.Value.AsInteger);
SettingsFile.UpdateFile;
end;
tkInt64:
begin
SettingsFile.WriteString(self.ClassName, Pair.Key, IntToStr(Pair.Value.AsInt64));
SettingsFile.UpdateFile;
end;
tkstring, tkUString, tkLString, tkWString, tkChar, tkWChar:
begin
SettingsFile.WriteString(self.ClassName, Pair.Key, Pair.Value.AsString);
SettingsFile.UpdateFile;
end;
tkFloat:
begin
SettingsFile.WriteFloat(self.ClassName, Pair.Key, Pair.Value.AsExtended);
SettingsFile.UpdateFile;
end;
end;
end;
finally
SettingsFile.Free;
end;
end;
procedure TParent.SetPublishedPropByName(name: string; value: TValue);
var
FRtti: TRttiContext;
FTyp: TRttiType;
FProp: TRttiProperty;
begin
FRtti := TRttiContext.Create;
FTyp := FRtti.GetType(self.ClassType);
FProp := FTyp.GetProperty(name);
FProp.SetValue(self, value);
FRtti.Free;
end;
constructor TParent.Create;
begin
PropsDict := TDictionary <string, TValue>.Create();
end;
destructor TParent.Destroy;
begin
PropsDict.Destroy;
end;
procedure TParent.GetAllPublishedProps;
var
FRtti: TRttiContext;
FTyp: TRttiType;
FProp: TRttiProperty;
Value: TValue;
begin
FRtti := TRttiContext.Create;
FTyp := FRtti.GetType(self.ClassType);
PropsDict.Clear();
for FProp in FTyp.GetProperties do
begin
Value := FProp.GetValue(self);
PropsDict.Add(Fprop.Name, Value);
end;
FRtti.Free;
end;
function TParent.GetPublishedPropByName(name: string): TValue;
var
FRtti: TRttiContext;
FTyp: TRttiType;
FProp: TRttiProperty;
FValue: TValue;
begin
FRtti := TRttiContext.Create;
FTyp := FRtti.GetType(self.ClassType);
FProp := FTyp.GetProperty(name);
if FProp <> nil then
begin
FValue := FProp.GetValue(self);
end;
FRtti.Free;
Result := FValue;
end;
function TParent.GetPublishedPropsToStrings: TStrings;
var
FRtti: TRttiContext;
FTyp: TRttiType;
FProp: TRttiProperty;
Value: TValue;
PropsLines: TStrings;
L: string;
begin
FRtti := TRttiContext.Create;
FTyp := FRtti.GetType(self.ClassType);
PropsLines := TStringList.Create;
for FProp in FTyp.GetProperties do
begin
Value := FProp.GetValue(self);
case Value.Kind of
tkInteger, tkInt64:
begin
L := FProp.Name + ': ' + IntToStr(Value.AsInt64);
end;
tkstring, tkUString, tkLString, tkWString, tkChar, tkWChar:
begin
L := FProp.Name + ': ' + Value.AsString;
end;
tkFloat:
begin
L := FProp.Name + ': ' + FloatToStr(Value.AsExtended);
end;
end;
PropsLines.Add(L);
end;
Result := PropsLines;
FRtti.Free;
end;
function TParent.IsPropExist(name: string): boolean;
var
FRtti: TRttiContext;
FTyp: TRttiType;
FProp: TRttiProperty;
begin
FRtti := TRttiContext.Create;
FTyp := FRtti.GetType(self.ClassType);
FProp := FTyp.GetProperty(name);
if FProp <> nil then
begin
Result := True;
end
else
begin
Result := False;
end;
FRtti.Free;
end;
procedure TParent.RestorePublishedProps(name: string);
var
SettingsFile : TCustomIniFile;
FRtti: TRttiContext;
FTyp: TRttiType;
FProp: TRttiProperty;
Value: TValue;
V: TValue;
begin
FRtti := TRttiContext.Create;
FTyp := FRtti.GetType(self.ClassType);
if FileExists(name) then
begin
SettingsFile := TMemIniFile.Create(name, TEncoding.UTF8);
if SettingsFile.SectionExists(self.ClassName) then
begin
for FProp in FTyp.GetProperties do
begin
Value := FProp.GetValue(self);
if SettingsFile.ValueExists(self.ClassName, FProp.Name) then
begin
case Value.Kind of
tkInteger:
begin
V := SettingsFile.ReadInteger(self.ClassName, FProp.Name, 0);
FProp.SetValue(self, V);
end;
tkInt64:
begin
V := SettingsFile.ReadString(self.ClassName, FProp.Name, '');
FProp.SetValue(self, StrToInt64(V.AsString));
end;
tkstring, tkUString, tkLString, tkWString, tkChar, tkWChar:
begin
V := SettingsFile.ReadString(self.ClassName, FProp.Name, '');
FProp.SetValue(self, V);
end;
tkFloat:
begin
V := SettingsFile.ReadFloat(self.ClassName, FProp.Name, 0);
FProp.SetValue(self, V);
end;
end;
end
else
begin
ShowMessage('В файле нет данных для параметра ' + FProp.Name + '!');
end;
end;
end
else
begin
ShowMessage('Нет параметров для текущего объекта в Файле!');
end;
end
else
begin
ShowMessage('Файла с параметрами не существует!');
end;
FRtti.Free;
SettingsFile.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
var OpenDlg : TOpenDialog;
begin
OpenDlg := TOpenDialog.Create(Self);
OpenDlg.Filter :='*.INI';
OpenDlg.InitialDir := ExtractFilePath(Application.ExeName);
if OpenDlg.Execute then begin
case Form1.RadioGroup1.ItemIndex of
0:
begin
Child1.RestorePublishedProps(OpenDlg.FileName);
Form1.Memo1.Clear;
Form1.Memo1.Lines := Child1.GetPublishedPropsToStrings();
end;
1:
begin
Child2.RestorePublishedProps(OpenDlg.FileName);
Form1.Memo1.Clear;
Form1.Memo1.Lines := Child2.GetPublishedPropsToStrings();
end;
end;
end;
OpenDlg.Free;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Child1 := TChild1.Create;
Child2 := TChild2.Create;
case Form1.RadioGroup1.ItemIndex of
0:
Form1.Memo1.Lines := Child1.GetPublishedPropsToStrings();
1:
Form1.Memo1.Lines := Child2.GetPublishedPropsToStrings();
end;
end;
procedure TForm1.RadioGroup1Click(Sender: TObject);
begin
Memo1.Clear;
case Form1.RadioGroup1.ItemIndex of
0:
Form1.Memo1.Lines := Child1.GetPublishedPropsToStrings();
1:
Form1.Memo1.Lines := Child2.GetPublishedPropsToStrings();
end;
end;
end.
|
unit ULicenca;
interface
uses
System.SysUtils, System.Classes,
Data.DB,
FireDAC.Comp.Client,
FireDAC.Comp.DataSet, ULicencaVO, uLicencaItensVO, System.Generics.Collections,
uDM, uFireDAC, uGenericDAO;
const CConsulta: string =
'SELECT CLILICID, CLILICCNPJCPF,CLILICEMPRESA,CLILICQUANTESTACAO,CLILICQUANTUSUARIO,CLILICIPEXTERNO,CLILICDATAHRATUALIZACAO,CLILICBUILD,CLILICIPLOCAL FROM TCLIENTELICENCA';
const CConsultaItens: string =
'SELECT LICID, LICCNPJCPF,LICDATAHORALCTO,LICLICENCA,LICUTILIZADA,LICDATAHRUTILIZACAO, LICSITUACAO FROM TLICENCA';
type
TLicenca = class
private
function LocalizarPorId(AId: Integer): TLicencaVO;
function LocalizarPorCNPJ(ACNPJ: string): Integer;
procedure Salvar(ALicenca: TLicencaVO);
procedure BuscarBancoDados();
//--- ITENS---------------------------------------------------------------------
function LocalizarItensPorId(AId: Integer): TLicencaItensVO;
function LocalizarItensPorCNPJ(ACNPJ: string): Integer;
procedure SalvarItem(ALicencaItem: TLicencaItensVO);
//--- FIREBIRD---------------------------------------------------------------------
public
function FBListarLicenca(AUtilizada: Boolean = False): TObjectList<TLicencaVO>;
function FBListarLicencaItens(AUtilizada: Boolean = False): TObjectList<TLicencaItensVO>;
procedure Importar();
procedure ImportarItens();
function ListarTodos: TObjectList<TLicencaVO>;
function ListarTodosItens: TObjectList<TLicencaItensVO>;
end;
implementation
{ TLicenca }
procedure TLicenca.BuscarBancoDados;
begin
DM.Conexao.Open();
end;
function TLicenca.FBListarLicenca(AUtilizada: Boolean = False): TObjectList<TLicencaVO>;
var
sb: TStringBuilder;
Qry: TFDQuery;
lista: TObjectList<TLicencaVO>;
model: TLicencaVO;
begin
BuscarBancoDados();
lista := TObjectList<TLicencaVO>.Create();
sb := TStringBuilder.Create;
Qry := TFDQuery.create(nil);
try
try
sb.AppendLine('select ');
sb.AppendLine('clilicid,');
sb.AppendLine('cliliccnpjcpf,');
sb.AppendLine('clilicempresa,');
sb.AppendLine('clilicquantestacao,');
sb.AppendLine('clilicquantusuario,');
sb.AppendLine('clilicipexterno,');
sb.AppendLine('clilicdatahratualizacao,');
sb.AppendLine('clilicbuild,');
sb.AppendLine('cliliciplocal');
sb.AppendLine(' from tclientelicenca CLI ');
sb.AppendLine(' WHERE EXISTS(');
sb.AppendLine(' SELECT 1 FROM TLICENCA LIC');
sb.AppendLine(' WHERE CLI.CLILICCNPJCPF = LIC.LICCNPJCPF ');
if AUtilizada = False then
begin
sb.AppendLine(' AND LIC.LICSITUACAO = 1');
sb.AppendLine(' AND LIC.LICUTILIZADA = ''N'') ');
end
else begin
sb.AppendLine(' AND LIC.LICSITUACAO in (1,2)');
sb.AppendLine(' AND LIC.LICUTILIZADA = ''N'') ');
end;
Qry.Connection := DM.Conexao;
Qry.SQL.Text := sb.ToString();
Qry.Open();
while not Qry.Eof do
begin
model := TLicencaVO.Create;
model.Codigo := Qry.FieldByName('clilicid').AsInteger;
model.CNPJCPF := Qry.FieldByName('cliliccnpjcpf').AsString;
model.Empresa := Qry.FieldByName('clilicempresa').AsString;
model.QtdeEstacao := Qry.FieldByName('clilicquantestacao').AsInteger;
model.QtdeUsuario := Qry.FieldByName('clilicquantusuario').AsInteger;
model.IPExterno := Qry.FieldByName('clilicipexterno').AsString;
model.DataAtualizacao := Qry.FieldByName('clilicdatahratualizacao').AsDateTime;
model.Build := Qry.FieldByName('clilicbuild').AsString;
model.IPLocal := Qry.FieldByName('cliliciplocal').AsString;
lista.Add(model);
Qry.Next;
end;
Result := lista;
except
On E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
finally
FreeAndNil(sb);
freeAndNil(Qry);
end;
end;
function TLicenca.FBListarLicencaItens(AUtilizada: Boolean = False): TObjectList<TLicencaItensVO>;
var
sb: TStringBuilder;
FD: TFDQuery;
lista: TObjectList<TLicencaItensVO>;
model: TLicencaItensVO;
begin
BuscarBancoDados();
lista := TObjectList<TLicencaItensVO>.Create();
sb := TStringBuilder.Create;
FD := TFDQuery.create(nil);
try
try
sb.AppendLine('select ');
sb.AppendLine('licid,');
sb.AppendLine('liccnpjcpf,');
sb.AppendLine('licdatahoralcto,');
sb.AppendLine('liclicenca,');
sb.AppendLine('licutilizada,');
sb.AppendLine('licdatahrutilizacao,');
sb.AppendLine('licsituacao');
sb.AppendLine(' from tlicenca lic');
if AUtilizada = False then
sb.AppendLine(' WHERE LICSITUACAO = 1 AND LICUTILIZADA = ''N''')
else
sb.AppendLine(' WHERE LICSITUACAO in (1,2)');
FD.Connection := DM.Conexao;
FD.SQL.Text := sb.ToString();
FD.Open();
while not FD.Eof do
begin
model := TLicencaItensVO.Create;
model.Codigo := FD.FieldByName('licid').AsInteger;
model.CNPJCPF := FD.FieldByName('liccnpjcpf').AsString;
model.DataLcto := FD.FieldByName('licdatahoralcto').AsDateTime;
model.Licenca := FD.FieldByName('liclicenca').AsString;
model.LicencaUtilizada := FD.FieldByName('licutilizada').AsString;
model.DataUtilizacao := FD.FieldByName('licdatahrutilizacao').AsDateTime;
model.Situacao := FD.FieldByName('licsituacao').AsString;
lista.Add(model);
FD.Next;
end;
except
On E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
Result := lista;
finally
FreeAndNil(sb);
freeAndNil(FD);
end;
end;
procedure TLicenca.Importar();
var
lista: TObjectList<TLicencaVO>;
model: TLicencaVO;
i: Integer;
id: Integer;
count: Integer;
begin
lista := FBListarLicenca();
model := TLicencaVO.Create;
count := lista.Count;
try
for i := 0 to count -1 do
begin
id := LocalizarPorCNPJ(lista[i].CNPJCPF);
model.Id := id;
model.CNPJCPF := lista[i].CNPJCPF;
model.Empresa := lista[i].Empresa;
model.QtdeEstacao := lista[i].QtdeEstacao;
model.QtdeUsuario := lista[i].QtdeUsuario;
model.IPExterno := lista[i].IPExterno;
model.DataAtualizacao := lista[i].DataAtualizacao;
model.Build := lista[i].Build;
model.IPLocal := lista[i].IPLocal;
model.Codigo := lista[i].Codigo;
Salvar(model);
end;
finally
FreeAndNil(lista);
FreeAndNil(model);
end;
end;
procedure TLicenca.ImportarItens;
var
lista: TObjectList<TLicencaItensVO>;
model: TLicencaItensVO;
i: Integer;
id: Integer;
count: Integer;
begin
lista := FBListarLicencaItens();
model := TLicencaItensVO.Create;
count := lista.Count;
try
for i := 0 to count -1 do
begin
id := LocalizarItensPorCNPJ(lista[i].CNPJCPF);
model.Id := id;
model.CNPJCPF := lista[i].CNPJCPF;
model.Codigo := lista[i].Codigo;
model.CNPJCPF := lista[i].CNPJCPF;
model.DataLcto := lista[i].DataLcto;
model.Licenca := lista[i].Licenca;
model.DataUtilizacao := lista[i].DataUtilizacao;
model.Situacao := lista[i].Situacao;
model.LicencaUtilizada := lista[i].LicencaUtilizada;
model.Codigo := lista[i].Codigo;
SalvarItem(model);
end;
finally
FreeAndNil(lista);
FreeAndNil(model);
end;
end;
function TLicenca.ListarTodos: TObjectList<TLicencaVO>;
var
obj: TFireDAC;
lista: TObjectList<TLicencaVO>;
model: TLicencaVO;
begin
lista := TObjectList<TLicencaVO>.Create();
obj := TFireDAC.create;
try
obj.OpenSQL('SELECT * FROM TCLIENTELICENCA'); // CConsulta
while not obj.Model.Eof do
begin
model := TLicencaVO.Create;
model.Id := obj.Model.FieldByName('CLILICID').AsInteger;
model.Codigo := obj.Model.FieldByName('CLILICID').AsInteger;
model.CNPJCPF := obj.Model.FieldByName('CLILICCNPJCPF').AsString;
model.Empresa := obj.Model.FieldByName('CLILICEMPRESA').AsString;
model.QtdeEstacao := obj.Model.FieldByName('CLILICQUANTESTACAO').AsInteger;
model.QtdeUsuario := obj.Model.FieldByName('CLILICQUANTUSUARIO').AsInteger;
model.IPExterno := obj.Model.FieldByName('CLILICIPEXTERNO').AsString;
model.DataAtualizacao := obj.Model.FieldByName('CLILICDATAHRATUALIZACAO').AsDateTime;
model.Build := obj.Model.FieldByName('CLILICBUILD').AsString;
model.IPLocal := obj.Model.FieldByName('CLILICIPLOCAL').AsString;
lista.Add(model);
obj.Model.Next;
end;
finally
FreeAndNil(obj);
end;
Result := lista;
end;
function TLicenca.ListarTodosItens: TObjectList<TLicencaItensVO>;
var
obj: TFireDAC;
lista: TObjectList<TLicencaItensVO>;
model: TLicencaItensVO;
begin
lista := TObjectList<TLicencaItensVO>.Create();
obj := TFireDAC.create;
try
obj.OpenSQL(CConsultaItens);
while not obj.Model.Eof do
begin
model := TLicencaItensVO.Create;
model.Id := obj.Model.FieldByName('LICID').AsInteger;
model.Codigo := obj.Model.FieldByName('LICID').AsInteger;
model.CNPJCPF := obj.Model.FieldByName('LICCNPJCPF').AsString;
model.DataLcto := obj.Model.FieldByName('LICDATAHORALCTO').AsDateTime;
model.Licenca := obj.Model.FieldByName('LICLICENCA').AsString;
model.LicencaUtilizada := obj.Model.FieldByName('LICUTILIZADA').AsString;
model.DataUtilizacao := obj.Model.FieldByName('LICDATAHRUTILIZACAO').AsDateTime;
model.Situacao := obj.Model.FieldByName('LICSITUACAO').AsString;
lista.Add(model);
obj.Model.Next;
end;
finally
FreeAndNil(obj);
end;
Result := lista;
end;
function TLicenca.LocalizarItensPorCNPJ(ACNPJ: string): Integer;
var
obj: TFireDAC;
begin
obj := TFireDAC.create;
try
obj.OpenSQL(CConsultaItens + ' WHERE LicIte_CNPJCPF = ' + QuotedStr(ACNPJ));
Result := obj.Model.FieldByName('LicIte_Id').AsInteger;
finally
FreeAndNil(obj);
end;
end;
function TLicenca.LocalizarItensPorId(AId: Integer): TLicencaItensVO;
var
obj: TFireDAC;
model: TLicencaItensVO;
begin
model := TLicencaItensVO.Create;
obj := TFireDAC.create;
try
obj.OpenSQL(CConsulta + ' WHERE LicIte_Id = ' + IntToStr(AId));
model.Id := obj.Model.FieldByName('LicIte_Id').AsInteger;
model.Codigo := obj.Model.FieldByName('LicIte_Codigo').AsInteger;
model.CNPJCPF := obj.Model.FieldByName('LicIte_CNPJCPF').AsString;
model.DataLcto := obj.Model.FieldByName('LicIte_DataLcto').AsDateTime;
model.Licenca := obj.Model.FieldByName('LicIte_Licenca').AsString;
model.DataUtilizacao := obj.Model.FieldByName('LicIte_DataUtilizacao').AsDateTime;
model.Situacao := obj.Model.FieldByName('LicIte_Situacao').AsString;
model.LicencaUtilizada := obj.Model.FieldByName('LicIte_Utilizada').AsString;
finally
FreeAndNil(obj);
end;
Result := model;
end;
function TLicenca.LocalizarPorCNPJ(ACNPJ: string): Integer;
var
obj: TFireDAC;
begin
obj := TFireDAC.create;
try
obj.OpenSQL(CConsulta + ' WHERE Lic_CNPJCPF = ' + QuotedStr(ACNPJ));
Result := obj.Model.FieldByName('Lic_Id').AsInteger;
finally
FreeAndNil(obj);
end;
end;
function TLicenca.LocalizarPorId(AId: Integer): TLicencaVO;
var
obj: TFireDAC;
model: TLicencaVO;
begin
model := TLicencaVO.Create();
obj := TFireDAC.create;
try
obj.OpenSQL(CConsulta + ' WHERE Lic_Id = ' + IntToStr(AId));
model.Id := obj.Model.FieldByName('Lic_Id').AsInteger;
model.Codigo := obj.Model.FieldByName('Lic_Codigo').AsInteger;
model.CNPJCPF := obj.Model.FieldByName('Lic_CNPJCPF').AsString;
model.Empresa := obj.Model.FieldByName('Lic_Empresa').AsString;
model.QtdeEstacao := obj.Model.FieldByName('Lic_QtdeEstacao').AsInteger;
model.QtdeUsuario := obj.Model.FieldByName('Lic_QtdeUsuario').AsInteger;
model.IPExterno := obj.Model.FieldByName('Lic_IPExterno').AsString;
model.DataAtualizacao := obj.Model.FieldByName('Lic_DataAtualizacao').AsDateTime;
model.Build := obj.Model.FieldByName('Lic_Build').AsString;
model.IPLocal := obj.Model.FieldByName('Lic_IPLocal').AsString;
finally
FreeAndNil(obj);
end;
Result := model;
end;
procedure TLicenca.Salvar(ALicenca: TLicencaVO);
begin
TGenericDAO.Save<TLicencaVO>(ALicenca);
end;
procedure TLicenca.SalvarItem(ALicencaItem: TLicencaItensVO);
begin
TGenericDAO.Save<TLicencaItensVO>(ALicencaItem);
end;
end.
|
unit FolderTreeView;
{
Inno Setup
Copyright (C) 1997-2008 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
TFolderTreeView component
$jrsoftware: issrc/Components/FolderTreeView.pas,v 1.42 2009/03/25 11:47:32 mlaan Exp $
}
interface
{$IFDEF VER200}
{$DEFINE DELPHI2009}
{$ENDIF}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, CommCtrl;
type
TCustomFolderTreeView = class;
TFolderRenameEvent = procedure(Sender: TCustomFolderTreeView;
var NewName: String; var Accept: Boolean) of object;
TCustomFolderTreeView = class(TWinControl)
private
FDestroyingHandle: Boolean;
FDirectory: String;
FFriendlyTree: Boolean;
FItemExpanding: Boolean;
FOnChange: TNotifyEvent;
FOnRename: TFolderRenameEvent;
procedure Change;
procedure DeleteObsoleteNewItems(const ParentItem, ItemToKeep: HTREEITEM);
function FindItem(const ParentItem: HTREEITEM; const AName: String): HTREEITEM;
function FindOrCreateItem(const ParentItem: HTREEITEM; const AName: String): HTREEITEM;
function GetItemFullPath(Item: HTREEITEM): String; virtual;
function InsertItem(const ParentItem: HTREEITEM; const AName, ACustomDisplayName: String;
const ANewItem: Boolean): HTREEITEM;
procedure SelectItem(const Item: HTREEITEM);
procedure SetItemHasChildren(const Item: HTREEITEM; const AHasChildren: Boolean);
procedure SetDirectory(const Value: String);
function TryExpandItem(const Item: HTREEITEM): Boolean;
procedure CNKeyDown(var Message: TWMKeyDown); message CN_KEYDOWN;
procedure CNNotify(var Message: TWMNotify); message CN_NOTIFY;
procedure WMCtlColorEdit(var Message: TMessage); message WM_CTLCOLOREDIT;
procedure WMDestroy(var Message: TWMDestroy); message WM_DESTROY;
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
protected
function ItemChildrenNeeded(const Item: HTREEITEM): Boolean; virtual; abstract;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
function GetItemImageIndex(const Item: HTREEITEM;
const NewItem, SelectedImage: Boolean): Integer; virtual; abstract;
function GetRootItem: HTREEITEM; virtual;
function ItemHasChildren(const Item: HTREEITEM): Boolean; virtual; abstract;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnRename: TFolderRenameEvent read FOnRename write FOnRename;
public
constructor Create(AOwner: TComponent); override;
procedure ChangeDirectory(const Value: String; const CreateNewItems: Boolean);
procedure CreateNewDirectory(const ADefaultName: String);
property Directory: String read FDirectory write SetDirectory;
end;
TFolderTreeView = class(TCustomFolderTreeView)
private
procedure RefreshDriveItem(const Item: HTREEITEM; const ANewDisplayName: String);
protected
function ItemChildrenNeeded(const Item: HTREEITEM): Boolean; override;
function ItemHasChildren(const Item: HTREEITEM): Boolean; override;
function GetItemFullPath(Item: HTREEITEM): String; override;
function GetItemImageIndex(const Item: HTREEITEM;
const NewItem, SelectedImage: Boolean): Integer; override;
published
property TabOrder;
property TabStop default True;
property Visible;
property OnChange;
property OnRename;
end;
TStartMenuFolderTreeView = class(TCustomFolderTreeView)
private
FUserPrograms, FCommonPrograms: String;
FUserStartup, FCommonStartup: String;
FImageIndexes: array[Boolean] of Integer;
protected
procedure CreateParams(var Params: TCreateParams); override;
function GetRootItem: HTREEITEM; override;
function ItemChildrenNeeded(const Item: HTREEITEM): Boolean; override;
function ItemHasChildren(const Item: HTREEITEM): Boolean; override;
function GetItemImageIndex(const Item: HTREEITEM;
const NewItem, SelectedImage: Boolean): Integer; override;
public
procedure SetPaths(const AUserPrograms, ACommonPrograms,
AUserStartup, ACommonStartup: String);
published
property TabOrder;
property TabStop default True;
property Visible;
property OnChange;
property OnRename;
end;
procedure Register;
implementation
{
Notes:
1. Don't call TreeView_SelectItem without calling TreeView_Expand on the
item's parents first. Otherwise infinite recursion can occur:
a. TreeView_SelectItem will first set the selected item. It will then try
to expand the parent node, causing a TVN_ITEMEXPANDING message to be
sent.
b. If the TVN_ITEMEXPANDING handler calls TreeView_SortChildren, TV_SortCB
will call TV_EnsureVisible if the selected item was one of the items
affected by the sorting (which will always be the case).
c. TV_EnsureVisible will expand parent nodes if necessary. However, since
we haven't yet returned from the original TVN_ITEMEXPANDING message
handler, the parent node doesn't yet have the TVIS_EXPANDED state,
thus it thinks the node still needs expanding.
d. Another, nested TVN_ITEMEXPANDING message is sent, bringing us back to
step b.
(Reproducible on Windows 95 and 2000.)
The recursion can be seen if you comment out the ExpandParents call in
the SelectItem method, then click "New Folder" on a folder with no
children.
(Note, however, that because of the ChildrenAdded check in our
TVN_ITEMEXPANDING handler, it can only recurse once. That won't cause a
fatal stack overflow (like it did before the ChildrenAdded check was
added), but it's still wrong to allow that to happen.)
}
uses
PathFunc, ShellApi, UxThemeISX{$IFDEF DELPHI2009}, Types{$ENDIF};
const
SHPPFW_NONE = $00000000;
var
SHPathPrepareForWriteFunc: function(hwnd: HWND; punkEnableModless: Pointer;
pszPath: PChar; dwFlags: DWORD): HRESULT; stdcall;
const
TVM_SETEXTENDEDSTYLE = TV_FIRST + 44;
TVS_EX_DOUBLEBUFFER = $0004;
procedure Register;
begin
RegisterComponents('JR', [TFolderTreeView, TStartMenuFolderTreeView]);
end;
function IsListableDirectory(const FindData: TWin32FindData): Boolean;
begin
Result := (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) and
(FindData.dwFileAttributes and (FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM) <>
(FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM)) and
(StrComp(FindData.cFileName, '.') <> 0) and
(StrComp(FindData.cFileName, '..') <> 0);
end;
function HasSubfolders(const Path: String): Boolean;
var
H: THandle;
FindData: TWin32FindData;
begin
Result := False;
H := FindFirstFile(PChar(AddBackslash(Path) + '*'), FindData);
if H <> INVALID_HANDLE_VALUE then begin
try
repeat
if IsListableDirectory(FindData) then begin
Result := True;
Break;
end;
until not FindNextFile(H, FindData);
finally
Windows.FindClose(H);
end;
end;
end;
function GetFileDisplayName(const Filename: String): String;
var
FileInfo: TSHFileInfo;
begin
if SHGetFileInfo(PChar(Filename), 0, FileInfo, SizeOf(FileInfo),
SHGFI_DISPLAYNAME) <> 0 then
Result := FileInfo.szDisplayName
else
Result := '';
end;
function GetFileImageIndex(const Filename: String; const OpenIcon: Boolean): Integer;
const
OpenFlags: array[Boolean] of UINT = (0, SHGFI_OPENICON);
var
FileInfo: TSHFileInfo;
begin
if SHGetFileInfo(PChar(Filename), 0, FileInfo, SizeOf(FileInfo),
SHGFI_SYSICONINDEX or SHGFI_SMALLICON or OpenFlags[OpenIcon]) <> 0 then
Result := FileInfo.iIcon
else
Result := 0;
end;
function GetDefFolderImageIndex(const OpenIcon: Boolean): Integer;
const
OpenFlags: array[Boolean] of UINT = (0, SHGFI_OPENICON);
var
FileInfo: TSHFileInfo;
begin
if SHGetFileInfo('c:\directory', FILE_ATTRIBUTE_DIRECTORY, FileInfo, SizeOf(FileInfo),
SHGFI_USEFILEATTRIBUTES or SHGFI_SYSICONINDEX or SHGFI_SMALLICON or OpenFlags[OpenIcon]) <> 0 then
Result := FileInfo.iIcon
else
Result := 0;
end;
function IsNetworkDrive(const Drive: Char): Boolean;
{ Returns True if Drive is a network drive. Unlike GetLogicalDrives and
GetDriveType, this will find the drive even if it's currently in an
unavailable/disconnected state (i.e. showing a red "X" on the drive icon
in Windows Explorer). }
var
LocalName: String;
RemoteName: array[0..MAX_PATH-1] of Char;
RemoteNameLen, ErrorCode: DWORD;
begin
LocalName := Drive + ':';
RemoteNameLen := SizeOf(RemoteName) div SizeOf(RemoteName[0]);
ErrorCode := WNetGetConnection(PChar(LocalName), RemoteName, RemoteNameLen);
Result := (ErrorCode = NO_ERROR) or (ErrorCode = ERROR_CONNECTION_UNAVAIL);
end;
function MoveAppWindowToActiveWindowMonitor(var OldRect: TRect): Boolean;
{ This moves the application window (Application.Handle) to the same monitor
as the active window, so that a subsequent Windows dialog will display on
the same monitor. Based on code from D4+'s TApplication.MessageBox.
NOTE: This function was copied from CmnFunc.pas. }
type
HMONITOR = type THandle;
TMonitorInfo = record
cbSize: DWORD;
rcMonitor: TRect;
rcWork: TRect;
dwFlags: DWORD;
end;
const
MONITOR_DEFAULTTONEAREST = $00000002;
var
ActiveWindow: HWND;
Module: HMODULE;
MonitorFromWindow: function(hwnd: HWND; dwFlags: DWORD): HMONITOR; stdcall;
GetMonitorInfo: function(hMonitor: HMONITOR; var lpmi: TMonitorInfo): BOOL; stdcall;
MBMonitor, AppMonitor: HMONITOR;
Info: TMonitorInfo;
begin
Result := False;
ActiveWindow := GetActiveWindow;
if ActiveWindow = 0 then Exit;
Module := GetModuleHandle(user32);
MonitorFromWindow := GetProcAddress(Module, 'MonitorFromWindow');
GetMonitorInfo := GetProcAddress(Module, 'GetMonitorInfoA');
if Assigned(MonitorFromWindow) and Assigned(GetMonitorInfo) then begin
MBMonitor := MonitorFromWindow(ActiveWindow, MONITOR_DEFAULTTONEAREST);
AppMonitor := MonitorFromWindow(Application.Handle, MONITOR_DEFAULTTONEAREST);
if MBMonitor <> AppMonitor then begin
Info.cbSize := SizeOf(Info);
if GetMonitorInfo(MBMonitor, Info) then begin
GetWindowRect(Application.Handle, OldRect);
SetWindowPos(Application.Handle, 0,
Info.rcMonitor.Left + ((Info.rcMonitor.Right - Info.rcMonitor.Left) div 2),
Info.rcMonitor.Top + ((Info.rcMonitor.Bottom - Info.rcMonitor.Top) div 2),
0, 0, SWP_NOACTIVATE or SWP_NOREDRAW or SWP_NOSIZE or SWP_NOZORDER);
Result := True;
end;
end;
end;
end;
procedure MoveAppWindowBack(const OldRect: TRect);
{ Moves the application window back to its previous position after a
successful call to MoveAppWindowToActiveWindowMonitor }
begin
SetWindowPos(Application.Handle, 0,
OldRect.Left + ((OldRect.Right - OldRect.Left) div 2),
OldRect.Top + ((OldRect.Bottom - OldRect.Top) div 2),
0, 0, SWP_NOACTIVATE or SWP_NOREDRAW or SWP_NOSIZE or SWP_NOZORDER);
end;
function EnsurePathIsAccessible(const Path: String): Boolean;
{ Calls SHPathPrepareForWrite which ensures the specified path is accessible by
reconnecting network drives (important) and prompting for media on removable
drives (not so important for our purposes). (Note that despite its name,
the function does not test for write access.) }
var
ActiveWindow: HWND;
DidMove: Boolean;
OldRect: TRect;
WindowList: Pointer;
begin
{ SHPathPrepareForWrite only exists on Windows 2000, Me, and later.
Do nothing on older versions of Windows. }
if @SHPathPrepareForWriteFunc = nil then begin
Result := True;
Exit;
end;
{ Note: The SHPathPrepareForWrite documentation claims that "user interface
windows will not be created" when hwnd is NULL, however I found that on
Windows 2000, it would still display message boxes for network errors.
(To reproduce: Disable your Local Area Connection and try expanding a
network drive.) So to avoid bugs from having unowned message boxes floating
around, go ahead and pass a proper owner window. }
ActiveWindow := GetActiveWindow;
DidMove := MoveAppWindowToActiveWindowMonitor(OldRect);
WindowList := DisableTaskWindows(0);
try
Result := SUCCEEDED(SHPathPrepareForWriteFunc(Application.Handle, nil,
PChar(Path), SHPPFW_NONE));
finally
if DidMove then
MoveAppWindowBack(OldRect);
EnableTaskWindows(WindowList);
SetActiveWindow(ActiveWindow);
end;
end;
function UseFriendlyTree: Boolean;
{ Returns True if running Windows XP or 2003 and the "Display simple folder
view" option in Explorer is enabled (by default, it is).
Note: Windows Vista also has this option, but regardless of how it is set,
folders never expand with a single click in Explorer. So on Vista and later,
False is always returned. }
var
Ver: Word;
K: HKEY;
Typ, Value, Size: DWORD;
begin
Ver := Word(GetVersion);
if (Lo(Ver) = 5) and (Hi(Ver) >= 1) then begin
Result := True;
if RegOpenKeyEx(HKEY_CURRENT_USER,
'Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced',
0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin
Size := SizeOf(Value);
if (RegQueryValueEx(K, 'FriendlyTree', nil, @Typ, @Value, @Size) = ERROR_SUCCESS) and
(Typ = REG_DWORD) and (Size = SizeOf(Value)) then
Result := (Value <> 0);
RegCloseKey(K);
end;
end
else
Result := False;
end;
{ TCustomFolderTreeView }
type
PItemData = ^TItemData;
TItemData = record
Name: String;
NewItem: Boolean;
ChildrenAdded: Boolean;
end;
constructor TCustomFolderTreeView.Create(AOwner: TComponent);
var
LogFont: TLogFont;
begin
inherited;
ControlStyle := ControlStyle - [csCaptureMouse];
Width := 121;
Height := 97;
ParentColor := False;
TabStop := True;
if Lo(GetVersion) < 6 then
Cursor := crArrow; { prevent hand cursor from appearing in TVS_TRACKSELECT mode }
if SystemParametersInfo(SPI_GETICONTITLELOGFONT, SizeOf(LogFont), @LogFont, 0) then
Font.Handle := CreateFontIndirect(LogFont);
end;
procedure TCustomFolderTreeView.CreateParams(var Params: TCreateParams);
const
TVS_TRACKSELECT = $0200;
TVS_SINGLEEXPAND = $0400;
begin
InitCommonControls;
inherited;
CreateSubClass(Params, WC_TREEVIEW);
with Params do begin
Style := Style or WS_CLIPCHILDREN or WS_CLIPSIBLINGS or TVS_LINESATROOT or
TVS_HASBUTTONS or TVS_SHOWSELALWAYS or TVS_EDITLABELS;
FFriendlyTree := UseFriendlyTree;
if FFriendlyTree then
Style := Style or TVS_TRACKSELECT or TVS_SINGLEEXPAND
else begin
if Lo(GetVersion) >= 6 then
Style := Style or TVS_TRACKSELECT
else
Style := Style or TVS_HASLINES;
end;
ExStyle := ExStyle or WS_EX_CLIENTEDGE;
WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW);
end;
end;
procedure TCustomFolderTreeView.CreateWnd;
var
ImageList: HIMAGELIST;
FileInfo: TSHFileInfo;
SaveCursor: HCURSOR;
begin
FDestroyingHandle := False;
inherited;
FDirectory := '';
if csDesigning in ComponentState then
Exit;
{ On Vista, enable the new Explorer-style look }
if (Lo(GetVersion) >= 6) and Assigned(SetWindowTheme) then begin
SetWindowTheme(Handle, 'Explorer', nil);
{ Like Explorer, enable double buffering to avoid flicker when the mouse
is moved across the items }
SendMessage(Handle, TVM_SETEXTENDEDSTYLE, TVS_EX_DOUBLEBUFFER,
TVS_EX_DOUBLEBUFFER);
end;
{ Initialize the image list }
ImageList := SHGetFileInfo('', 0, FileInfo, SizeOf(FileInfo),
SHGFI_USEFILEATTRIBUTES or SHGFI_SYSICONINDEX or SHGFI_SMALLICON);
TreeView_SetImageList(Handle, ImageList, TVSIL_NORMAL);
{ Add the root items }
SaveCursor := SetCursor(LoadCursor(0, IDC_WAIT));
try
ItemChildrenNeeded(nil);
finally
SetCursor(SaveCursor);
end;
end;
procedure TCustomFolderTreeView.WMDestroy(var Message: TWMDestroy);
begin
{ Work around bug in pre-v6 COMCTL32: If we have the TVS_SINGLEEXPAND style
and there is a selected item when the window is destroyed, we end up
getting a bunch of TVN_SINGLEEXPAND messages because it keeps moving the
selection as it's destroying items, resulting in a stream of "Please
insert a disk in drive X:" message boxes as the selection moves across
removable drives.
Currently, however, this problem isn't seen in practice because we don't
use TVS_SINGLEEXPAND on pre-XP Windows. }
FDestroyingHandle := True; { disables our TVN_SELCHANGED handling }
SelectItem(nil);
inherited;
end;
procedure TCustomFolderTreeView.KeyDown(var Key: Word; Shift: TShiftState);
var
Item: HTREEITEM;
begin
inherited;
if (Key = VK_F2) and (Shift * [ssShift, ssAlt, ssCtrl] = []) then begin
Key := 0;
Item := TreeView_GetSelection(Handle);
if Assigned(Item) then
TreeView_EditLabel(Handle, Item);
end;
end;
procedure TCustomFolderTreeView.CNKeyDown(var Message: TWMKeyDown);
var
FocusWnd: HWND;
begin
{ On Delphi 5+, if a non-VCL control is focused, TApplication.IsKeyMsg will
send the CN_KEYDOWN message to the nearest VCL control. This means that
when the edit control is focused, the tree view itself gets CN_KEYDOWN
messages. Don't let the VCL handle Enter and Escape; if we're on a dialog,
those keys will close the window. }
FocusWnd := GetFocus;
if (FocusWnd <> 0) and (TreeView_GetEditControl(Handle) = FocusWnd) then
if (Message.CharCode = VK_RETURN) or (Message.CharCode = VK_ESCAPE) then
Exit;
inherited;
end;
procedure TCustomFolderTreeView.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
{ For TVS_EX_DOUBLEBUFFER to be truly flicker-free on Vista, we must use
comctl32's default WM_ERASEBKGND handling, not the VCL's (which calls
FillRect). }
DefaultHandler(Message);
end;
procedure TCustomFolderTreeView.WMCtlColorEdit(var Message: TMessage);
begin
{ We can't let TWinControl.DefaultHandler handle this message. It tries to
send a CN_CTLCOLOREDIT message to the tree view's internally-created edit
control, which it won't understand because it's not a VCL control. Without
this special handling, the border is painted incorrectly on Windows XP
with themes enabled. }
Message.Result := DefWindowProc(Handle, Message.Msg, Message.WParam,
Message.LParam);
end;
function TCustomFolderTreeView.GetItemFullPath(Item: HTREEITEM): String;
var
TVItem: TTVItem;
begin
Result := '';
while Assigned(Item) do begin
TVItem.mask := TVIF_PARAM;
TVItem.hItem := Item;
if not TreeView_GetItem(Handle, TVItem) then begin
Result := '';
Exit;
end;
if Result = '' then
Result := PItemData(TVItem.lParam).Name
else
Insert(AddBackslash(PItemData(TVItem.lParam).Name), Result, 1);
Item := TreeView_GetParent(Handle, Item);
end;
end;
procedure TCustomFolderTreeView.Change;
var
Item: HTREEITEM;
begin
Item := TreeView_GetSelection(Handle);
if Assigned(Item) then
FDirectory := GetItemFullPath(Item)
else
FDirectory := '';
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TCustomFolderTreeView.CNNotify(var Message: TWMNotify);
const
TVN_SINGLEEXPAND = (TVN_FIRST-15);
TVNRET_SKIPOLD = 1;
TVNRET_SKIPNEW = 2;
procedure HandleClick;
var
Item: HTREEITEM;
HitTestInfo: TTVHitTestInfo;
begin
HitTestInfo.pt := ScreenToClient(SmallPointToPoint(TSmallPoint(GetMessagePos())));
Item := TreeView_HitTest(Handle, HitTestInfo);
if Assigned(Item) then begin
if HitTestInfo.flags and TVHT_ONITEMBUTTON <> 0 then
TreeView_Expand(Handle, Item, TVE_TOGGLE)
else begin
if TreeView_GetSelection(Handle) <> Item then
SelectItem(Item)
else begin
{ In 'friendly tree' mode, if the item is already selected, ensure
it's expanded.
Note: We do this only if SelectItem wasn't called, since newly
selected items are expanded automatically. If we were to call this
unconditionally, any error message would be shown twice. }
if FFriendlyTree and (HitTestInfo.flags and TVHT_ONITEM <> 0) then
TreeView_Expand(Handle, Item, TVE_EXPAND);
end;
end;
end;
end;
var
Hdr: PNMTreeView;
SaveCursor: HCURSOR;
DispItem: PTVItem;
TVItem: TTVItem;
S: String;
Accept: Boolean;
begin
inherited;
case Message.NMHdr.code of
TVN_DELETEITEM:
begin
Dispose(PItemData(PNMTreeView(Message.NMHdr).itemOld.lParam));
end;
TVN_ITEMEXPANDING:
begin
{ Sanity check: Make sure this message isn't sent recursively.
(See top of source code for details.) }
if FItemExpanding then
raise Exception.Create('Internal error: Item already expanding');
FItemExpanding := True;
try
Hdr := PNMTreeView(Message.NMHdr);
if (Hdr.action = TVE_EXPAND) and
not PItemData(Hdr.itemNew.lParam).ChildrenAdded and
not PItemData(Hdr.itemNew.lParam).NewItem then begin
PItemData(Hdr.itemNew.lParam).ChildrenAdded := True;
SaveCursor := SetCursor(LoadCursor(0, IDC_WAIT));
try
if ItemChildrenNeeded(Hdr.itemNew.hItem) then begin
{ If no subfolders were found, and there are no 'new' items
underneath the parent item, remove the '+' sign }
if TreeView_GetChild(Handle, Hdr.itemNew.hItem) = nil then
SetItemHasChildren(Hdr.itemNew.hItem, False);
end
else begin
{ A result of False means no children were added due to a
temporary error and that it should try again next time }
PItemData(Hdr.itemNew.lParam).ChildrenAdded := False;
{ Return 1 to cancel the expansion process (although it seems
to do that anyway when it sees no children were added) }
Message.Result := 1;
end;
finally
SetCursor(SaveCursor);
end;
end;
finally
FItemExpanding := False;
end;
end;
TVN_GETDISPINFO:
begin
DispItem := @PTVDispInfo(Message.NMHdr).item;
if DispItem.mask and TVIF_IMAGE <> 0 then begin
DispItem.iImage := GetItemImageIndex(DispItem.hItem,
PItemData(DispItem.lParam).NewItem, False);
end;
if DispItem.mask and TVIF_SELECTEDIMAGE <> 0 then begin
DispItem.iSelectedImage := GetItemImageIndex(DispItem.hItem,
PItemData(DispItem.lParam).NewItem, True);
end;
if DispItem.mask and TVIF_CHILDREN <> 0 then begin
DispItem.cChildren := Ord(Assigned(TreeView_GetChild(Handle, DispItem.hItem)));
if (DispItem.cChildren = 0) and not PItemData(DispItem.lParam).NewItem then
DispItem.cChildren := Ord(ItemHasChildren(DispItem.hItem));
end;
{ Store the values with the item so the callback isn't called again }
DispItem.mask := DispItem.mask or TVIF_DI_SETITEM;
end;
TVN_SELCHANGED:
begin
if not FDestroyingHandle then
Change;
end;
TVN_BEGINLABELEDIT:
begin
DispItem := @PTVDispInfo(Message.NMHdr).item;
{ Only 'new' items may be renamed }
if not PItemData(DispItem.lParam).NewItem then
Message.Result := 1;
end;
TVN_ENDLABELEDIT:
begin
DispItem := @PTVDispInfo(Message.NMHdr).item;
{ Only 'new' items may be renamed }
if PItemData(DispItem.lParam).NewItem and
Assigned(DispItem.pszText) then begin
S := DispItem.pszText;
Accept := True;
if Assigned(FOnRename) then
FOnRename(Self, S, Accept);
if Accept then begin
PItemData(DispItem.lParam).Name := S;
{ Instead of returning 1 to let the tree view update the text,
set the text ourself. This will downconvert any Unicode
characters to ANSI (if we're compiled as an ANSI app). }
TVItem.mask := TVIF_TEXT;
TVItem.hItem := DispItem.hItem;
TVItem.pszText := PChar(S);
TreeView_SetItem(Handle, TVItem);
TreeView_SortChildren(Handle, TreeView_GetParent(Handle, DispItem.hItem), 0);
Change;
end;
end;
end;
NM_CLICK:
begin
{ Use custom click handler to work more like Windows XP Explorer:
- Items can be selected by clicking anywhere on their respective
rows, except for the button.
- In 'friendly tree' mode, clicking an item's icon or caption causes
the item to expand, but never to collapse. }
HandleClick;
Message.Result := 1;
end;
TVN_SINGLEEXPAND:
begin
Hdr := PNMTreeView(Message.NMHdr);
{ Trying to emulate Windows XP's Explorer here:
Only collapse old item if it's at the same level as the new item. }
if Assigned(Hdr.itemOld.hItem) and Assigned(Hdr.itemNew.hItem) and
(TreeView_GetParent(Handle, Hdr.itemNew.hItem) <>
TreeView_GetParent(Handle, Hdr.itemOld.hItem)) then
Message.Result := Message.Result or TVNRET_SKIPOLD;
{ Selecting expanded items shouldn't collapse them }
if Assigned(Hdr.itemNew.hItem) then begin
TVItem.mask := TVIF_STATE;
TVItem.hItem := Hdr.itemNew.hItem;
TVItem.stateMask := TVIS_EXPANDED;
if TreeView_GetItem(Handle, TVItem) and
(TVItem.state and TVIS_EXPANDED <> 0) then
Message.Result := Message.Result or TVNRET_SKIPNEW;
end;
end;
end;
end;
procedure TCustomFolderTreeView.SetItemHasChildren(const Item: HTREEITEM;
const AHasChildren: Boolean);
var
TVItem: TTVItem;
begin
TVItem.mask := TVIF_CHILDREN;
TVItem.hItem := Item;
TVItem.cChildren := Ord(AHasChildren);
TreeView_SetItem(Handle, TVItem);
end;
procedure TCustomFolderTreeView.DeleteObsoleteNewItems(const ParentItem,
ItemToKeep: HTREEITEM);
{ Destroys all 'new' items except for ItemToKeep and its parents. (ItemToKeep
doesn't necessarily have to be a 'new' item.) Pass nil in the ParentItem
parameter when calling this method. }
function EqualsOrContains(const AParent: HTREEITEM; AChild: HTREEITEM): Boolean;
begin
Result := False;
repeat
if AChild = AParent then begin
Result := True;
Break;
end;
AChild := TreeView_GetParent(Handle, AChild);
until AChild = nil;
end;
var
Item, NextItem: HTREEITEM;
TVItem: TTVItem;
begin
Item := TreeView_GetChild(Handle, ParentItem);
while Assigned(Item) do begin
{ Determine the next item in advance since Item might get deleted }
NextItem := TreeView_GetNextSibling(Handle, Item);
TVItem.mask := TVIF_PARAM;
TVItem.hItem := Item;
if TreeView_GetItem(Handle, TVItem) then begin
if PItemData(TVItem.lParam).NewItem and not EqualsOrContains(Item, ItemToKeep) then begin
TreeView_DeleteItem(Handle, Item);
{ If there are no children left on the parent, remove its '+' sign }
if TreeView_GetChild(Handle, ParentItem) = nil then
SetItemHasChildren(ParentItem, False);
end
else
DeleteObsoleteNewItems(Item, ItemToKeep);
end;
Item := NextItem;
end;
end;
function TCustomFolderTreeView.InsertItem(const ParentItem: HTREEITEM;
const AName, ACustomDisplayName: String; const ANewItem: Boolean): HTREEITEM;
var
InsertStruct: TTVInsertStruct;
ItemData: PItemData;
begin
if ANewItem then
DeleteObsoleteNewItems(nil, ParentItem);
InsertStruct.hParent := ParentItem;
if ANewItem then
InsertStruct.hInsertAfter := TVI_SORT
else
InsertStruct.hInsertAfter := TVI_LAST;
InsertStruct.item.mask := TVIF_TEXT or TVIF_IMAGE or
TVIF_SELECTEDIMAGE or TVIF_CHILDREN or TVIF_PARAM;
InsertStruct.item.hItem := nil; { not used }
if ANewItem then begin
InsertStruct.item.mask := InsertStruct.item.mask or TVIF_STATE;
InsertStruct.item.stateMask := TVIS_CUT;
InsertStruct.item.state := TVIS_CUT;
end;
{ Note: There's no performance advantage in using a callback for the text.
During a TreeView_InsertItem call, the tree view will try to read the
new item's text in order to update the horizontal scroll bar range.
(It doesn't wait until the item is painted.)
In addition, the caller may sort newly-inserted subitems, which obviously
requires reading their text. }
if ACustomDisplayName = '' then
InsertStruct.item.pszText := PChar(AName)
else
InsertStruct.item.pszText := PChar(ACustomDisplayName);
InsertStruct.item.iImage := I_IMAGECALLBACK;
InsertStruct.item.iSelectedImage := I_IMAGECALLBACK;
if ANewItem then
InsertStruct.item.cChildren := 0
else begin
if ParentItem = nil then
InsertStruct.item.cChildren := 1
else
InsertStruct.item.cChildren := I_CHILDRENCALLBACK;
end;
InsertStruct.item.lParam := 0;
New(ItemData);
ItemData.Name := AName;
ItemData.NewItem := ANewItem;
ItemData.ChildrenAdded := False;
Pointer(InsertStruct.item.lParam) := ItemData;
Result := TreeView_InsertItem(Handle, InsertStruct);
end;
function TCustomFolderTreeView.FindItem(const ParentItem: HTREEITEM;
const AName: String): HTREEITEM;
var
TVItem: TTVItem;
begin
Result := TreeView_GetChild(Handle, ParentItem);
while Assigned(Result) do begin
TVItem.mask := TVIF_PARAM;
TVItem.hItem := Result;
if TreeView_GetItem(Handle, TVItem) then
if PathCompare(PItemData(TVItem.lParam).Name, AName) = 0 then
Break;
Result := TreeView_GetNextSibling(Handle, Result);
end;
end;
function TCustomFolderTreeView.FindOrCreateItem(const ParentItem: HTREEITEM;
const AName: String): HTREEITEM;
begin
Result := FindItem(ParentItem, AName);
if Result = nil then begin
if Assigned(ParentItem) then
SetItemHasChildren(ParentItem, True);
Result := InsertItem(ParentItem, AName, '', True);
end;
end;
function TCustomFolderTreeView.GetRootItem: HTREEITEM;
begin
Result := nil;
end;
procedure TCustomFolderTreeView.SelectItem(const Item: HTREEITEM);
procedure ExpandParents(Item: HTREEITEM);
begin
Item := TreeView_GetParent(Handle, Item);
if Assigned(Item) then begin
ExpandParents(Item);
TreeView_Expand(Handle, Item, TVE_EXPAND);
end;
end;
begin
{ Must manually expand parents prior to calling TreeView_SelectItem;
see top of source code for details }
if Assigned(Item) then
ExpandParents(Item);
TreeView_SelectItem(Handle, Item);
end;
function TCustomFolderTreeView.TryExpandItem(const Item: HTREEITEM): Boolean;
{ Tries to expand the specified item. Returns True if the item's children were
initialized (if any), or False if the initialization failed due to a
temporary error (i.e. ItemChildrenNeeded returned False). }
var
TVItem: TTVItem;
begin
TreeView_Expand(Handle, Item, TVE_EXPAND);
TVItem.mask := TVIF_CHILDREN or TVIF_PARAM;
TVItem.hItem := Item;
Result := TreeView_GetItem(Handle, TVItem) and
(PItemData(TVItem.lParam).ChildrenAdded or (TVItem.cChildren = 0));
end;
procedure TCustomFolderTreeView.ChangeDirectory(const Value: String;
const CreateNewItems: Boolean);
{ Changes to the specified directory. Value must begin with a drive letter
(e.g. "C:\directory"); relative paths and UNC paths are not allowed.
If CreateNewItems is True, new items will be created if one or more elements
of the path do not exist. }
var
PStart, PEnd: PChar;
S: String;
ParentItem, Item: HTREEITEM;
begin
SelectItem(nil);
ParentItem := GetRootItem;
PStart := PChar(Value);
while PStart^ <> #0 do begin
if Assigned(ParentItem) then
if not TryExpandItem(ParentItem) then
Break;
{ Extract a single path component }
PEnd := PStart;
while (PEnd^ <> #0) and not PathCharIsSlash(PEnd^) do
PEnd := PathStrNextChar(PEnd);
SetString(S, PStart, PEnd - PStart);
{ Find that component under ParentItem }
if CreateNewItems and Assigned(ParentItem) then
Item := FindOrCreateItem(ParentItem, S)
else
Item := FindItem(ParentItem, S);
if Item = nil then
Break;
ParentItem := Item;
PStart := PEnd;
while PathCharIsSlash(PStart^) do
Inc(PStart);
end;
if Assigned(ParentItem) then
SelectItem(ParentItem);
end;
procedure TCustomFolderTreeView.SetDirectory(const Value: String);
begin
ChangeDirectory(Value, False);
end;
procedure TCustomFolderTreeView.CreateNewDirectory(const ADefaultName: String);
{ Creates a new node named AName underneath the selected node. Does nothing
if there is no selected node. }
var
ParentItem, Item: HTREEITEM;
I: Integer;
S: String;
begin
ParentItem := TreeView_GetSelection(Handle);
if ParentItem = nil then
Exit;
DeleteObsoleteNewItems(nil, ParentItem);
{ Expand and find a unique name }
if not TryExpandItem(ParentItem) then
Exit;
I := 0;
repeat
Inc(I);
if I = 1 then
S := ADefaultName
else
S := ADefaultName + Format(' (%d)', [I]);
until FindItem(ParentItem, S) = nil;
SetItemHasChildren(ParentItem, True);
Item := InsertItem(ParentItem, S, '', True);
SelectItem(Item);
if CanFocus then
SetFocus;
TreeView_EditLabel(Handle, Item);
end;
{ TFolderTreeView }
function TFolderTreeView.ItemChildrenNeeded(const Item: HTREEITEM): Boolean;
procedure AddDrives;
var
Drives: DWORD;
Drive: Char;
begin
Drives := GetLogicalDrives;
for Drive := 'A' to 'Z' do begin
if (Drives and 1 <> 0) or IsNetworkDrive(Drive) then
InsertItem(nil, Drive + ':', GetFileDisplayName(Drive + ':\'), False);
Drives := Drives shr 1;
end;
end;
function AddSubdirectories(const ParentItem: HTREEITEM;
const Path: String): Boolean;
var
OldErrorMode: UINT;
H: THandle;
FindData: TWin32FindData;
S: String;
begin
OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
{ The path might be on a disconnected network drive. Ensure it's
connected before attempting to enumerate subdirectories. }
if Length(Path) = 3 then begin { ...only do this on the root }
if not EnsurePathIsAccessible(Path) then begin
Result := False;
Exit;
end;
{ Refresh the icon and text in case the drive was indeed reconnected }
RefreshDriveItem(ParentItem, GetFileDisplayName(Path));
end;
Result := True;
H := FindFirstFile(PChar(AddBackslash(Path) + '*'), FindData);
if H <> INVALID_HANDLE_VALUE then begin
try
repeat
if IsListableDirectory(FindData) then begin
S := FindData.cFileName;
InsertItem(ParentItem, S, GetFileDisplayName(AddBackslash(Path) + S),
False);
end;
until not FindNextFile(H, FindData);
finally
Windows.FindClose(H);
end;
end;
finally
SetErrorMode(OldErrorMode);
end;
end;
begin
if Item = nil then begin
AddDrives;
Result := True;
end
else begin
Result := AddSubdirectories(Item, GetItemFullPath(Item));
if Result then begin
{ When a text callback is used, sorting after all items are inserted is
exponentially faster than using hInsertAfter=TVI_SORT }
TreeView_SortChildren(Handle, Item, 0);
end;
end;
end;
function TFolderTreeView.GetItemFullPath(Item: HTREEITEM): String;
begin
Result := inherited GetItemFullPath(Item);
if (Length(Result) = 2) and (Result[2] = ':') then
Result := Result + '\';
end;
function TFolderTreeView.GetItemImageIndex(const Item: HTREEITEM;
const NewItem, SelectedImage: Boolean): Integer;
begin
if NewItem then
Result := GetDefFolderImageIndex(SelectedImage)
else
Result := GetFileImageIndex(GetItemFullPath(Item), SelectedImage);
end;
function TFolderTreeView.ItemHasChildren(const Item: HTREEITEM): Boolean;
var
Path: String;
OldErrorMode: UINT;
begin
Path := GetItemFullPath(Item);
OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
Result := (GetDriveType(PChar(AddBackslash(PathExtractDrive(Path)))) = DRIVE_REMOTE) or
HasSubfolders(Path);
finally
SetErrorMode(OldErrorMode);
end;
end;
procedure TFolderTreeView.RefreshDriveItem(const Item: HTREEITEM;
const ANewDisplayName: String);
var
TVItem: TTVItem;
begin
TVItem.mask := TVIF_IMAGE or TVIF_SELECTEDIMAGE;
TVItem.hItem := Item;
TVItem.iImage := I_IMAGECALLBACK;
TVItem.iSelectedImage := I_IMAGECALLBACK;
if ANewDisplayName <> '' then begin
TVItem.mask := TVItem.mask or TVIF_TEXT;
TVItem.pszText := PChar(ANewDisplayName);
end;
TreeView_SetItem(Handle, TVItem);
end;
{ TStartMenuFolderTreeView }
procedure TStartMenuFolderTreeView.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.Style := Params.Style and not TVS_LINESATROOT;
end;
function TStartMenuFolderTreeView.GetItemImageIndex(const Item: HTREEITEM;
const NewItem, SelectedImage: Boolean): Integer;
begin
Result := FImageIndexes[SelectedImage];
end;
function TStartMenuFolderTreeView.GetRootItem: HTREEITEM;
begin
{ The top item ('Programs') is considered the root }
Result := TreeView_GetRoot(Handle);
end;
function TStartMenuFolderTreeView.ItemChildrenNeeded(const Item: HTREEITEM): Boolean;
procedure AddSubfolders(const ParentItem: HTREEITEM; const Path, StartupPath: String);
var
StartupName: String;
OldErrorMode: UINT;
H: THandle;
FindData: TWin32FindData;
S: String;
begin
{ Determine the name of the Startup folder so that we can hide it from the
list }
if StartupPath <> '' then
if PathCompare(AddBackslash(Path), PathExtractPath(StartupPath)) = 0 then
StartupName := PathExtractName(StartupPath);
OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
H := FindFirstFile(PChar(AddBackslash(Path) + '*'), FindData);
if H <> INVALID_HANDLE_VALUE then begin
try
repeat
if IsListableDirectory(FindData) then begin
S := FindData.cFileName;
if PathCompare(S, StartupName) <> 0 then
if FindItem(ParentItem, S) = nil then
InsertItem(ParentItem, S, GetFileDisplayName(AddBackslash(Path) + S), False);
end;
until not FindNextFile(H, FindData);
finally
Windows.FindClose(H);
end;
end;
finally
SetErrorMode(OldErrorMode);
end;
end;
var
Root, S: String;
NewItem: HTREEITEM;
Path: String;
begin
Result := True;
if Item = nil then begin
Root := FUserPrograms;
if Root = '' then begin
{ User programs folder doesn't exist for some reason? }
Root := FCommonPrograms;
if Root = '' then
Exit;
end;
FImageIndexes[False] := GetFileImageIndex(Root, False);
FImageIndexes[True] := FImageIndexes[False];
S := GetFileDisplayName(Root);
if S = '' then
S := PathExtractName(Root);
NewItem := InsertItem(nil, '', S, False);
TreeView_Expand(Handle, NewItem, TVE_EXPAND);
end
else begin
Path := GetItemFullPath(Item);
if FCommonPrograms <> '' then
AddSubfolders(Item, AddBackslash(FCommonPrograms) + Path, FCommonStartup);
if FUserPrograms <> '' then
AddSubfolders(Item, AddBackslash(FUserPrograms) + Path, FUserStartup);
TreeView_SortChildren(Handle, Item, 0);
end;
end;
function TStartMenuFolderTreeView.ItemHasChildren(const Item: HTREEITEM): Boolean;
var
Path: String;
begin
Path := GetItemFullPath(Item);
if (FCommonPrograms <> '') and HasSubfolders(AddBackslash(FCommonPrograms) + Path) then
Result := True
else if (FUserPrograms <> '') and HasSubfolders(AddBackslash(FUserPrograms) + Path) then
Result := True
else
Result := False;
end;
procedure TStartMenuFolderTreeView.SetPaths(const AUserPrograms, ACommonPrograms,
AUserStartup, ACommonStartup: String);
begin
FUserPrograms := AUserPrograms;
FCommonPrograms := ACommonPrograms;
FUserStartup := AUserStartup;
FCommonStartup := ACommonStartup;
RecreateWnd;
end;
initialization
InitThemeLibrary;
SHPathPrepareForWriteFunc := GetProcAddress(LoadLibrary(shell32),
{$IFDEF UNICODE}'SHPathPrepareForWriteW'{$ELSE}'SHPathPrepareForWriteA'{$ENDIF});
end.
|
unit Script.WordsInterfaces;
interface
uses
Core.Obj,
Script.Interfaces
;
type
TscriptContext = class(TCoreObject)
private
f_Log : IscriptLog;
protected
procedure Cleanup; override;
public
constructor Create(const aLog: IscriptLog);
procedure Log(const aString: String);
{* - Выводит сообщение в лог. }
end;//TscriptContext
TscriptCompileContext = class(TscriptContext)
end;//TscriptCompileContext
IscriptWord = interface
procedure DoIt(aContext: TscriptContext);
{* - собственно процедура для выполнения слова словаря. }
end;//IscriptWord
implementation
constructor TscriptContext.Create(const aLog: IscriptLog);
begin
inherited Create;
f_Log := aLog;
end;
procedure TscriptContext.Log(const aString: String);
{* - Выводит сообщение в лог. }
begin
if (f_Log <> nil) then
f_Log.Log(aString);
end;
procedure TscriptContext.Cleanup;
begin
f_Log := nil;
inherited;
end;
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Decorators.RepeatUntilSuccess;
interface
uses
System.JSON,
Behavior3, Behavior3.Core.Decorator, Behavior3.Core.BaseNode, Behavior3.Core.Tick;
type
(**
* RepeatUntilSuccess is a decorator that repeats the tick signal until the
* node child returns `SUCCESS`, `RUNNING` or `ERROR`. Optionally, a maximum
* number of repetitions can be defined.
*
* @module b3
* @class RepeatUntilSuccess
* @extends Decorator
**)
TB3RepeatUntilSuccess = class(TB3Decorator)
private
protected
public
// maxLoop** (*Integer*) Maximum number of repetitions. Default to -1 (infinite)
MaxLoop: Integer;
constructor Create; override;
(**
* Open method.
* @method open
* @param {Tick} tick A tick instance.
**)
procedure Open(Tick: TB3Tick); override;
(**
* Tick method.
* @method tick
* @param {Tick} tick A tick instance.
* @return {Constant} A state constant.
**)
function Tick(Tick: TB3Tick): TB3Status; override;
procedure Load(JsonNode: TJSONValue); override;
end;
implementation
{ TB3RepeatUntilSuccess }
uses
Behavior3.Helper, Behavior3.Core.BehaviorTree;
constructor TB3RepeatUntilSuccess.Create;
begin
inherited;
(**
* Node name. Default to `RepeatUntilSuccess`.
* @property {String} name
* @readonly
**)
Name := 'RepeatUntilSuccess';
(**
* Node title. Default to `Repeat Until Success`.
* @property {String} title
* @readonly
**)
Title := 'Repeat Until Success';
(**
* Node parameters.
* @property {String} parameters
* @readonly
**)
MaxLoop := -1;
end;
procedure TB3RepeatUntilSuccess.Open(Tick: TB3Tick);
begin
Tick.Blackboard.&Set('i', 0, Tick.Tree.Id, Id);
end;
function TB3RepeatUntilSuccess.Tick(Tick: TB3Tick): TB3Status;
var
I: Integer;
Status: TB3Status;
begin
if not Assigned(Child) then
begin
Result := Behavior3.Error;
Exit;
end;
I := Tick.Blackboard.Get('i', Tick.tree.id, Id).AsInteger;
Status := Behavior3.Error;
while (MaxLoop < 0) or (I < MaxLoop) do
begin
Status := Child._Execute(Tick);
if Status = Behavior3.Failure then
Inc(I)
else
Break;
end;
Tick.Blackboard.&Set('i', I, Tick.Tree.Id, Id);
Result := Status;
end;
procedure TB3RepeatUntilSuccess.Load(JsonNode: TJSONValue);
begin
inherited;
MaxLoop := LoadProperty(JsonNode, 'maxLoop', MaxLoop);
end;
end.
|
unit DBErrFo;
interface
uses
Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGrids, DB, DBTables, StdCtrls, AppEvnts, DBClient;
type
TForm1 = class(TForm)
Memo1: TMemo;
Label1: TLabel;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
Button1: TButton;
Button2: TButton;
cds: TClientDataSet;
ApplicationEvents1: TApplicationEvents;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ApplicationEvents1Exception(Sender: TObject; E: Exception);
private
{ Private declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
cds.FieldByName ('Name').Value := 'something';
end;
procedure TForm1.Button2Click(Sender: TObject);
var
S: String;
begin
s := cds.FieldByName ('Name').Value;
cds.Insert;
cds.FieldByName ('Name').Value := s;
cds.Post;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
cds.Open;
end;
procedure TForm1.ApplicationEvents1Exception(Sender: TObject;
E: Exception);
begin
if E is EDbClient then
begin
Memo1.Lines.Add('Error: ' + (E.Message));
Memo1.Lines.Add(' Error Code: ' +
IntToStr(EDbClient (E).ErrorCode));
end
else
Memo1.Lines.Add('Generic Error: ' + (E.Message));
end;
end.
|
program decline;
(* calculates and prints depreciation schedule for an asset *)
var
cost,salvage,book,loss,totaldep,rate,ysum,diff : real;
life,year : 0 .. 9999;
mode: 1 .. 3; (* number of method chosen *)
begin
(* user input *)
write('cost of asset? ');
read(cost);
write('salvage value? ');
read(salvage);
write('life in years? ');
read(life);
writeln('method of depreciation: ');
write('1=straight line, 2=declining, 3=sum of years? ');
read(mode);
(* headings *)
writeln;
writeln('years': 10,'annual': 10, 'total': 10, 'book': 10);
writeln(' ': 10, 'depreciation':20, 'value': 10);
writeln;
(* initialization *)
book := cost;
loss := 0; totaldep:= 0;
(* loss is depreciation this year,
totaldep is total depreciation to date *)
year := 0;
rate := 2 / life;
ysum := life*(life+1)/2;
diff := cost - salvage;
repeat (* main loop *)
(* sum of years *)
writeln(year:10,loss:10:2,totaldep: 10:2,book: 10:2);
case mode of
1: loss := diff / life;
2: begin
loss := rate * book;
if (book-loss) < salvage then
loss := book - salvage;
(* correction for overshoot in mode 2 only *)
end;
3: loss := (life-year)/ysum*diff;
end; (* of case *)
book := book - loss;
totaldep := totaldep + loss;
year := year + 1;
until year > life;
writeln('end of job.');
end. |
{ Subroutine SST_EXP_EVAL (EXP,NVAL_ERR)
*
* Evaluate a compiled expression. This means determining its data type, and
* value if known at compile time. EXP is the expression to evaluate. If
* NVAL_ERR is TRUE, then it will be considered an error if the expression can
* not be evaluated to a constant value.
}
module sst_EXP_EVAL;
define sst_exp_eval;
%include 'sst2.ins.pas';
procedure sst_exp_eval ( {evaluate compiled expression}
in out exp: sst_exp_t; {expression, fills in value and data type}
in nval_err: boolean); {unknown value at compile time is err if TRUE}
const
max_msg_parms = 1; {max paramters we can pass to a message}
var
term_p: sst_exp_term_p_t; {points to current term in expression}
dt_p, dt2_p: sst_dtype_p_t; {scratch data type pointers}
dt_exp_p: sst_dtype_p_t; {points to base dtype descriptor of exp}
dt_term_p: sst_dtype_p_t; {points to base dtype descriptor of term}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
label
dtype_mismatch, bad_operator, not_readable, leave;
begin
if exp.val_eval then goto leave; {expression already evaluated before ?}
sst_term_eval (exp.term1, nval_err); {evaluate first term}
exp.dtype_p := exp.term1.dtype_p; {init expression data type from first term}
if exp.term1.next_p = nil {this is a simple expression ?}
then exp.dtype_hard := exp.term1.dtype_hard {copy hard/soft flag from term 1}
else exp.dtype_hard := false; {compound exp always have soft data type}
exp.val_fnd := exp.term1.val_fnd; {get constant value exists flag from term 1}
if exp.val_fnd
then begin {first term has a known constant value}
exp.val := exp.term1.val; {copy whole value descriptor from term}
end
else begin {first term is not a known constant}
exp.val.dtype := exp.term1.val.dtype; {only need base data type ID}
end
;
exp.rwflag := exp.term1.rwflag; {promote read/write permission flag}
if {compound exp, but first term not readable ?}
(not (sst_rwflag_read_k in exp.rwflag)) and
(exp.term1.next_p <> nil)
then begin
term_p := addr(exp.term1); {set pointer to offending term}
goto not_readable;
end;
exp.val_eval := true; {flag expression as evaluated}
term_p := exp.term1.next_p; {set pointer for next term to process}
{
* The expression value and data type have been initialized to the value and
* data type of the first term. We will loop back here each new term and
* accumulate the resulting expression value and data type in EXP. Once we
* encounter a term that does not have a constant value, then we stop trying
* to resolve the constant value of the expression, but continue resolving
* the data type.
}
while term_p <> nil do begin {once for each remaining term in expression}
with term_p^: term do begin {TERM is abbreviation for current term}
sst_term_eval (term, nval_err); {evaluate this term}
exp.val_fnd := exp.val_fnd and term.val_fnd; {TRUE if still have known value}
if not (sst_rwflag_read_k in term.rwflag) {term not readable ?}
then goto not_readable;
exp.rwflag := {expressions with > 1 term are not writeable}
exp.rwflag - [sst_rwflag_write_k];
dt_exp_p := exp.dtype_p; {find pointer to base expression data type}
while dt_exp_p^.dtype = sst_dtype_copy_k do begin
dt_exp_p := dt_exp_p^.copy_dtype_p;
end;
dt_term_p := term.dtype_p; {find pointer to base term data type}
while dt_term_p^.dtype = sst_dtype_copy_k do begin
dt_term_p := dt_term_p^.copy_dtype_p;
end;
case exp.val.dtype of {cases for raw expression data type so far}
{
********************************************
*
* Existing expression type is INTEGER.
}
sst_dtype_int_k: begin
case term.val.dtype of {cases for data type of new term}
{
* INTEGER op INTEGER
}
sst_dtype_int_k: begin
case term.op2 of
sst_op2_add_k: begin {+}
exp.dtype_p := sst_dtype_int_max_p;
if exp.val_fnd then begin
exp.val.int_val := exp.val.int_val + term.val.int_val;
end;
end;
sst_op2_sub_k: begin {-}
exp.dtype_p := sst_dtype_int_max_p;
if exp.val_fnd then begin
exp.val.int_val := exp.val.int_val - term.val.int_val;
end;
end;
sst_op2_mult_k: begin {*}
exp.dtype_p := sst_dtype_int_max_p;
if exp.val_fnd then begin
exp.val.int_val := exp.val.int_val * term.val.int_val;
end;
end;
sst_op2_div_k: begin {divide, floating point}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.int_val / term.val.int_val;
end;
end;
sst_op2_divi_k: begin {divide, integer}
exp.dtype_p := sst_dtype_int_max_p;
if exp.val_fnd then begin
exp.val.int_val := exp.val.int_val div term.val.int_val;
end;
end;
sst_op2_rem_k: begin {remainder}
exp.dtype_p := sst_dtype_int_max_p;
if exp.val_fnd then begin
exp.val.int_val := exp.val.int_val mod term.val.int_val;
end;
end;
sst_op2_pwr_k: begin {**}
exp.dtype_p := sst_dtype_int_max_p;
if exp.val_fnd then begin
exp.val.int_val := exp.val.int_val ** term.val.int_val;
end;
end;
sst_op2_btand_k: begin {bitwise AND}
exp.dtype_p := sst_dtype_int_max_p;
if exp.val_fnd then begin
exp.val.int_val := exp.val.int_val & term.val.int_val;
end;
end;
sst_op2_btor_k: begin {bitwise OR}
exp.dtype_p := sst_dtype_int_max_p;
if exp.val_fnd then begin
exp.val.int_val := exp.val.int_val ! term.val.int_val;
end;
end;
sst_op2_eq_k: begin {= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val = term.val.int_val;
end;
end;
sst_op2_ne_k: begin {<> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val <> term.val.int_val;
end;
end;
sst_op2_ge_k: begin {>= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val >= term.val.int_val;
end;
end;
sst_op2_gt_k: begin {> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val > term.val.int_val;
end;
end;
sst_op2_le_k: begin {<= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val <= term.val.int_val;
end;
end;
sst_op2_lt_k: begin {< comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val < term.val.int_val;
end;
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is integer case}
{
* INTEGER op FLOATING POINT
}
sst_dtype_float_k: begin
case term.op2 of
sst_op2_add_k: begin {+}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.int_val + term.val.float_val;
end;
end;
sst_op2_sub_k: begin {-}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.int_val - term.val.float_val;
end;
end;
sst_op2_mult_k: begin {*}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.int_val * term.val.float_val;
end;
end;
sst_op2_div_k: begin {divide, floating point}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.int_val / term.val.float_val;
end;
end;
sst_op2_pwr_k: begin {**}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.int_val ** term.val.float_val;
end;
end;
sst_op2_eq_k: begin {= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val = term.val.float_val;
end;
end;
sst_op2_ne_k: begin {<> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val <> term.val.float_val;
end;
end;
sst_op2_ge_k: begin {>= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val >= term.val.float_val;
end;
end;
sst_op2_gt_k: begin {> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val > term.val.float_val;
end;
end;
sst_op2_le_k: begin {<= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val <= term.val.float_val;
end;
end;
sst_op2_lt_k: begin {< comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.int_val < term.val.float_val;
end;
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is floating point case}
{
* INTEGER op SET
}
sst_dtype_set_k: begin
case term.op2 of
sst_op2_in_k: begin {check for is member of SET}
exp.dtype_p := sst_dtype_bool_p;
exp.val_fnd := false; {we don't evaluate this case currently}
end; {end of INTEGER op SET case}
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is a SET case}
{
* INTEGER op <incompatible data type>
}
otherwise
goto dtype_mismatch;
end; {end of term data type cases}
end; {end of old expression is INTEGER case}
{
********************************************
*
* Existing expression type is ENUMERATED TYPE.
}
sst_dtype_enum_k: begin
case dt_term_p^.dtype of {cases for data type of new term}
{
* ENUMERATED op ENUMERATED
}
sst_dtype_enum_k: begin
if dt_term_p^.enum_first_p <> dt_exp_p^.enum_first_p
then goto dtype_mismatch; {not of same enumerated type ?}
case term.op2 of
sst_op2_eq_k: begin {= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.enum_p = term.val.enum_p;
end;
end;
sst_op2_ne_k: begin {<> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.enum_p <> term.val.enum_p;
end;
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is ENUMERATED case}
{
* ENUMERATED op SET
}
sst_dtype_set_k: begin
case term.op2 of
sst_op2_in_k: begin {check for is member of SET}
exp.dtype_p := sst_dtype_bool_p;
exp.val_fnd := false; {we don't evaluate this case currently}
end; {end of ENUMERATED op SET case}
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is a SET case}
{
* ENUMERATED op <incompatible data type>
}
otherwise
goto dtype_mismatch;
end; {end of term data type cases}
end; {end of old expression is ENUMERATED case}
{
********************************************
*
* Existing expression type is FLOATING POINT.
}
sst_dtype_float_k: begin
case term.val.dtype of {cases for data type of new term}
{
* FLOAT op INTEGER
}
sst_dtype_int_k: begin
case term.op2 of
sst_op2_add_k: begin {+}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val + term.val.int_val;
end;
end;
sst_op2_sub_k: begin {-}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val - term.val.int_val;
end;
end;
sst_op2_mult_k: begin {*}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val * term.val.int_val;
end;
end;
sst_op2_div_k: begin {divide, floating point}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val / term.val.int_val;
end;
end;
sst_op2_pwr_k: begin {**}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val ** term.val.int_val;
end;
end;
sst_op2_eq_k: begin {= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val = term.val.int_val;
end;
end;
sst_op2_ne_k: begin {<> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val <> term.val.int_val;
end;
end;
sst_op2_ge_k: begin {>= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val >= term.val.int_val;
end;
end;
sst_op2_gt_k: begin {> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val > term.val.int_val;
end;
end;
sst_op2_le_k: begin {<= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val <= term.val.int_val;
end;
end;
sst_op2_lt_k: begin {< comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val < term.val.int_val;
end;
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is integer case}
{
* FLOAT op FLOAT
}
sst_dtype_float_k: begin
case term.op2 of
sst_op2_add_k: begin {+}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val + term.val.float_val;
end;
end;
sst_op2_sub_k: begin {-}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val - term.val.float_val;
end;
end;
sst_op2_mult_k: begin {*}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val * term.val.float_val;
end;
end;
sst_op2_div_k: begin {divide, floating point}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val / term.val.float_val;
end;
end;
sst_op2_pwr_k: begin {**}
exp.dtype_p := sst_dtype_float_max_p;
if exp.val_fnd then begin
exp.val.float_val := exp.val.float_val ** term.val.float_val;
end;
end;
sst_op2_eq_k: begin {= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val = term.val.float_val;
end;
end;
sst_op2_ne_k: begin {<> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val <> term.val.float_val;
end;
end;
sst_op2_ge_k: begin {>= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val >= term.val.float_val;
end;
end;
sst_op2_gt_k: begin {> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val > term.val.float_val;
end;
end;
sst_op2_le_k: begin {<= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val <= term.val.float_val;
end;
end;
sst_op2_lt_k: begin {< comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.float_val < term.val.float_val;
end;
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is FLOATING POINT case}
{
* FLOATING POINT op <incompatible data type>
}
otherwise
goto dtype_mismatch;
end; {end of term data type cases}
end; {end of old expression is FLOAT case}
{
********************************************
*
* Existing expression type is BOOLEAN.
}
sst_dtype_bool_k: begin
case term.val.dtype of {cases for data type of new term}
{
* BOOLEAN op BOOLEAN
}
sst_dtype_bool_k: begin
case term.op2 of
sst_op2_eq_k: begin {= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.bool_val = term.val.bool_val;
end;
end;
sst_op2_ne_k: begin {<> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.bool_val <> term.val.bool_val;
end;
end;
sst_op2_andthen_k, {logical AND, first arg evaluated first}
sst_op2_and_k: begin {logical AND}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.bool_val and term.val.bool_val;
end;
end;
sst_op2_orelse_k, {logical OR, first arg evaluated first}
sst_op2_or_k: begin {logical OR}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.bool_val or term.val.bool_val;
end;
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is BOOLEAN case}
{
* BOOLEAN op SET
}
sst_dtype_set_k: begin
case term.op2 of
sst_op2_in_k: begin {check for is member of SET}
exp.dtype_p := sst_dtype_bool_p;
exp.val_fnd := false; {we don't evaluate this case currently}
end; {end of BOOLEAN op SET case}
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is a SET case}
{
* BOOLEAN op <incompatible data type>
}
otherwise
goto dtype_mismatch;
end; {end of term data type cases}
end; {end of old expression is BOOLEAN case}
{
********************************************
*
* Existing expression type is CHARACTER.
}
sst_dtype_char_k: begin
case term.val.dtype of {cases for data type of new term}
{
* CHARACTER op CHARACTER
}
sst_dtype_char_k: begin
case term.op2 of
sst_op2_eq_k: begin {= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.char_val = term.val.char_val;
end;
end;
sst_op2_ne_k: begin {<> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.char_val <> term.val.char_val;
end;
end;
sst_op2_ge_k: begin {>= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.char_val >= term.val.char_val;
end;
end;
sst_op2_gt_k: begin {> comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.char_val > term.val.char_val;
end;
end;
sst_op2_le_k: begin {<= comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.char_val <= term.val.char_val;
end;
end;
sst_op2_lt_k: begin {< comparison}
exp.dtype_p := sst_dtype_bool_p;
if exp.val_fnd then begin
exp.val.bool_val := exp.val.char_val < term.val.char_val;
end;
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is CHAR case}
{
* CHARACTER op SET
}
sst_dtype_set_k: begin
case term.op2 of
sst_op2_in_k: begin {check for is member of SET}
exp.dtype_p := sst_dtype_bool_p;
exp.val_fnd := false; {we don't evaluate this case currently}
end; {end of CHARACTER op SET case}
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is a SET case}
{
* CHAR op <incompatible data type>
}
otherwise
goto dtype_mismatch;
end; {end of term data type cases}
end; {end of old expression is CHAR case}
{
********************************************
*
* Existing expression type is RECORD.
}
sst_dtype_rec_k: begin
if dt_term_p <> dt_exp_p {term not same record type as expression ?}
then goto dtype_mismatch;
case term.op2 of
sst_op2_eq_k, {= comparison}
sst_op2_ne_k: begin {<> comparison}
exp.dtype_p := sst_dtype_bool_p;
exp.val_fnd := false;
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end;
{
********************************************
*
* Existing expression type is ARRAY.
}
sst_dtype_array_k: begin
if dt_term_p <> dt_exp_p {term not same record type as expression ?}
then goto dtype_mismatch;
case term.op2 of
sst_op2_eq_k, {= comparison}
sst_op2_ne_k: begin {<> comparison}
exp.dtype_p := sst_dtype_bool_p;
exp.val_fnd := false;
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end;
{
********************************************
*
* Existing expression type is SET.
}
sst_dtype_set_k: begin
case term.val.dtype of {cases for data type of new term}
{
* SET op SET
}
sst_dtype_set_k: begin
sst_set_dtypes_combine (dt_exp_p^, dt_term_p^, dt_p); {make composite data type}
if dt_p = nil {sets have incompatible data types ?}
then goto dtype_mismatch;
case term.op2 of
sst_op2_union_k,
sst_op2_isect_k,
sst_op2_remov_k: begin
exp.dtype_p := dt_p;
exp.val_fnd := false; {we don't evaluate this case currently}
end;
sst_op2_eq_k,
sst_op2_ne_k,
sst_op2_subset_k,
sst_op2_subset_eq_k,
sst_op2_superset_k,
sst_op2_superset_eq_k: begin
exp.dtype_p := sst_dtype_bool_p;
exp.val_fnd := false; {we don't evaluate this case currently}
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of SET op SET case}
{
* SET op <incompatible data type>
}
otherwise
goto dtype_mismatch;
end; {end of term data type cases}
end; {end of old expression is SET case}
{
********************************************
*
* Existing expression type is POINTER TYPE.
}
sst_dtype_pnt_k: begin
case term.val.dtype of {cases for data type of new term}
{
* POINTER op POINTER
}
sst_dtype_pnt_k: begin
if {neither is a NIL pointer ?}
(dt_exp_p^.pnt_dtype_p <> nil) and
(dt_term_p^.pnt_dtype_p <> nil)
then begin {need to check if pointing to same data type}
dt_p := dt_exp_p^.pnt_dtype_p; {find expressions's base pointed to data type}
while dt_p^.dtype = sst_dtype_copy_k do begin
dt_p := dt_p^.copy_dtype_p;
end;
dt2_p := dt_term_p^.pnt_dtype_p; {find term's base pointed to data type}
while dt2_p^.dtype = sst_dtype_copy_k do begin
dt2_p := dt2_p^.copy_dtype_p;
end;
if dt_p <> dt2_p
then goto dtype_mismatch; {not pointing to same data type}
end;
case term.op2 of
sst_op2_eq_k, sst_op2_ne_k: begin {= or <> comparison}
exp.dtype_p := sst_dtype_bool_p;
exp.val_fnd := false; {can't resolve constant value at compile time}
end;
otherwise
goto bad_operator;
end; {end of operator cases}
end; {end of term is POINTER case}
{
* POINTER op <incompatible data type>
}
otherwise
goto dtype_mismatch;
end; {end of term data type cases}
end; {end of old expression is POINTER case}
{
********************************************
*
* Data type of existing expression is illegal or unimplemented.
}
otherwise
sys_msg_parm_int (msg_parm[1], ord(dt_exp_p^.dtype));
syo_error (term.str_h, 'sst', 'dtype_unexpected_exp', msg_parm, 1);
end; {end of previous expression data type cases}
end; {done with TERM abbreviation}
term_p := term_p^.next_p; {point to next term in expression}
sst_dtype_resolve ( {resolve base data types of expression}
exp.dtype_p^, dt_p, exp.val.dtype);
if {data type is a set with fully known dtype ?}
(dt_p^.dtype = sst_dtype_set_k) and
(dt_p^.set_dtype_final)
then begin
exp.dtype_hard := true;
end;
end; {back and process next term in expression}
leave: {common exit point}
if nval_err and (not exp.val_fnd) then begin {need value but not possible ?}
syo_error (exp.str_h, 'sst', 'exp_not_const_val', nil, 0);
end;
return;
{
* The data type of the expression so far and the new term are incompatible.
}
dtype_mismatch:
syo_error (term_p^.str_h, 'sst', 'dtype_term_mismatch', nil, 0);
{
* The operator is incompatible with the data type of the expression and term.
}
bad_operator:
syo_error (term_p^.str_h, 'sst', 'operator_mismatch', nil, 0);
{
* The current term is not readable. It is pointed to by TERM_P.
}
not_readable:
syo_error (term_p^.str_h, 'sst', 'term_not_readable', nil, 0);
end;
|
unit SmSActivate;
interface
uses
System.SysUtils, System.Classes, HTTPSend, ssl_openssl;
const
URL = 'http://sms-activate.ru/stubs/handler_api.php?';
RUS = '0';
UKR = '1';
type
TLogEvent = procedure(txt: string) of object;
TSMSActivate = class
private
FOnLog: TLogEvent;
FId, FBalance, FNumber, FCode: string;
Fkey, FCountry: string;
HTTP: THTTPSend;
FHTML: TStringList;
function Pars(Str, s1, s2: string): string;
function HTTPGet(URL: string): string;
protected
public
function getBalance: string; // узнать баланс
function getNumbersStatus(service: string): string; // запрос на сводобные номера
function getNumber(service: string): Boolean; // заказать номер
function setStatus(status, Id: string): Boolean; // изменения статуса активации
function getStatus(Id: string): Boolean; // получить состояния активации
constructor Create(key: string);
destructor Destroy;
property Balance: string read FBalance write FBalance;
property Id: string read FId write FId;
property Number: string read FNumber write FNumber;
property Code: string read FCode write FCode;
property Country: string read FCountry write FCountry;
property OnLog: TLogEvent read FOnLog write FOnLog;
end;
implementation
{ TSMSActivate }
constructor TSMSActivate.Create(key: string);
begin
Self.Fkey := trim(key);
FHTML := TStringList.Create;
HTTP := THTTPSend.Create;
HTTP.AddPortNumberToHost := false;
HTTP.UserAgent := 'Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1';
HTTP.Protocol := '1.1';
HTTP.Timeout := 10000;
end;
destructor TSMSActivate.Destroy;
begin
try
setStatus('6', FId);
finally
FHTML.Free;
HTTP.Free;
end;
end;
function TSMSActivate.getBalance: string; // узнать баланс
var
Str: array of string;
begin
HTTPGet(URL + 'api_key=' + Fkey + '&action=getBalance');
if Pos('ACCESS_BALANCE', FHTML.Text) <> 0 then
begin
FBalance := Pars(FHTML.Text, 'ACCESS_BALANCE:', #13);
Result := FBalance;
end
else
begin
Result := 'ERROR';
end;
end;
function TSMSActivate.getNumbersStatus(service: string): string; // запрос на сводобные номера
begin
HTTPGet(URL + 'api_key=' + Fkey + '&action=getNumbersStatus&country=' + FCountry);
if Pos('vk', FHTML.Text) <> 0 then
begin
Result := Pars(FHTML.Text, trim(service) + '_0":"', '",');
end
else
begin
Result := '0';
end;
end;
function TSMSActivate.getNumber(service: string): Boolean;
begin
HTTPGet(URL + 'api_key=' + Fkey + '&action=getNumber&service=' + trim(service) + '&ref=instacash&country=' +
FCountry);
if Pos('ACCESS_NUMBER', FHTML.Text) <> 0 then
begin
FId := trim(Pars(FHTML.Text, 'ACCESS_NUMBER:', ':'));
FNumber := trim(Pars(FHTML.Text + '@', Id + ':', '@'));
Result := True;
end
else
begin
Result := false;
end;
end;
function TSMSActivate.getStatus(Id: string): Boolean;
var
Count: integer;
begin
Count := 0;
FCode := '';
repeat
inc(Count);
HTTPGet(URL + 'api_key=' + Fkey + '&action=getStatus&id=' + Id);
if Pos('STATUS_OK', FHTML.Text) <> 0 then
begin
FCode := trim(Pars(FHTML.Text + '@', 'STATUS_OK:', '@'));
Result := True;
Break;
end;
Sleep(1000);
until (trim(FHTML.Text) = 'STATUS_OK') or (Count = 15) and (HTTP.ResultCode = 200);
end;
function TSMSActivate.setStatus(status, Id: string): Boolean;
begin
HTTPGet(URL + 'api_key=' + Fkey + '&action=setStatus&status=' + status + '&id=' + Id);
if Pos('ACCESS', FHTML.Text) <> 0 then
begin
Result := True;
end
else
begin
Result := false;
end;
end;
function TSMSActivate.HTTPGet(URL: string): string;
var
rez: TStringList;
begin
repeat
FHTML.Clear;
HTTP.Document.Clear;
HTTP.Headers.Clear;
HTTP.HTTPMethod('GET', trim(URL));
rez := TStringList.Create;
rez.LoadFromStream(HTTP.Document);
Result := rez.Text;
FHTML.Text := rez.Text;
rez.Free;
if Assigned(FOnLog) then
FOnLog(IntToStr(HTTP.ResultCode) + ' GET :' + URL + ' RESPONS : ' + trim(FHTML.Text));
Sleep(500);
until HTTP.ResultCode = 200;
end;
function TSMSActivate.Pars(Str, s1, s2: string): string;
begin
Result := '';
if (s1 > '') and (Pos(s1, Str) <> 0) then
begin
Delete(Str, 1, Pos(s1, Str) + Length(s1) - 1);
Result := Str;
end;
if (s2 > '') and (Pos(s2, Str) <> 0) then
begin
Result := Copy(Str, 1, Pos(s2, Str) - 1);
end;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Ani, FMX.Objects, System.Math, duck,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.ListBox, FMX.Layouts;
type
TForm1 = class(TForm)
Rectangle1: TRectangle;
Circle1: TCircle;
FloatAnimation1: TFloatAnimation;
Button1: TButton;
Panel1: TPanel;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
ListBoxItem5: TListBoxItem;
SpeedButton1: TSpeedButton;
Text1: TText;
procedure FloatAnimation1Process(Sender: TObject);
procedure FloatAnimation1Finish(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FX,FY:Single;
procedure GlobalMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.FloatAnimation1Finish(Sender: TObject);
begin
Circle1.Visible := False;
end;
procedure TForm1.FloatAnimation1Process(Sender: TObject);
begin
Circle1.Width := Circle1.Height;
Circle1.Position.X := FX-(Circle1.Width/2);;
Circle1.Position.Y := FY-(Circle1.Height/2);;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Self.duck.all.has('OnMouseDown').each(
procedure(obj: TObject)
begin
TControl(obj).ClipChildren := True;
TControl(obj).OnMouseDown := GlobalMouseDown;
end
);
end;
procedure TForm1.GlobalMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
Circle1.Parent := TControl(Sender);
Circle1.Position.X := X-(Circle1.Width/2);
FX := X;
Circle1.Position.Y := Y-(Circle1.Height/2);
FY := Y;
Circle1.Width := 0;
Circle1.Height := 0;
Circle1.Visible := True;
FloatAnimation1.StopValue := Max(TControl(Sender).Width,TControl(Sender).Height)*2;
end;
end.
|
unit fmuPrintBuffer;
interface
uses
// VCL
Windows, Forms, ComCtrls, StdCtrls, Controls, Classes, SysUtils, Messages,
Buttons, ExtCtrls,
// This
untPages, untUtil, untDriver, Spin;
type
{ TfmPrintBuffer }
TfmPrintBuffer = class(TPage)
Memo: TMemo;
btnReadPrintBufferLineNumber: TButton;
btnClearPrintBuffer: TButton;
btnReadPrintBuffer: TButton;
btnReadPrintBufferLine: TButton;
lblLineNumber: TLabel;
lblPrintBufferFormat: TLabel;
cbPrintBufferFormat: TComboBox;
btnClear: TButton;
btnStop: TButton;
seLineNumber: TSpinEdit;
procedure btnReadPrintBufferLineNumberClick(Sender: TObject);
procedure btnClearPrintBufferClick(Sender: TObject);
procedure btnReadPrintBufferClick(Sender: TObject);
procedure btnReadPrintBufferLineClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
private
FStopFlag: Boolean;
end;
implementation
{$R *.DFM}
{ TfmPrintBuffer }
procedure TfmPrintBuffer.btnClearPrintBufferClick(Sender: TObject);
begin
EnableButtons(False);
try
Check(Driver.ClearPrintBuffer);
finally
EnableButtons(True);
btnStop.Enabled := False;
end;
end;
procedure TfmPrintBuffer.btnReadPrintBufferLineNumberClick(Sender: TObject);
begin
EnableButtons(False);
try
Memo.Clear;
Check(Driver.ReadPrintBufferLineNumber);
Memo.Lines.Add('Количество строк в буфере печати : ' + IntToStr(Driver.PrintBufferLineNumber));
Memo.Lines.Add('Количество напечатаных строк : ' + IntToStr(Driver.LineNumber));
finally
EnableButtons(True);
btnStop.Enabled := False;
end;
end;
procedure TfmPrintBuffer.btnReadPrintBufferLineClick(Sender: TObject);
begin
EnableButtons(False);
try
Memo.Clear;
Driver.LineNumber := seLineNumber.Value;
Driver.PrintBufferFormat := cbPrintBufferFormat.ItemIndex;
Check(Driver.ReadPrintBufferLine);
Memo.Lines.Add(Driver.StringForPrinting);
finally
EnableButtons(True);
btnStop.Enabled := False;
end;
end;
procedure TfmPrintBuffer.btnReadPrintBufferClick(Sender: TObject);
var
i: Integer;
begin
EnableButtons(False);
FStopFlag := False;
btnStop.Enabled := True;
try
Memo.Clear;
Driver.PrintBufferFormat := cbPrintBufferFormat.ItemIndex;
Check(Driver.ReadPrintBufferLineNumber);
for i := 0 to Driver.PrintBufferLineNumber-1 do
begin
if FStopFlag then Break;
Driver.LineNumber := i;
Check(Driver.ReadPrintBufferLine);
Memo.Lines.Add(Format('%.3d: %s', [i, Driver.StringForPrinting]));
Application.ProcessMessages;
end;
finally
EnableButtons(True);
btnStop.Enabled := False;
end;
end;
procedure TfmPrintBuffer.FormCreate(Sender: TObject);
begin
cbPrintBufferFormat.ItemIndex := 2;
end;
procedure TfmPrintBuffer.btnStopClick(Sender: TObject);
begin
FStopFlag := True;
end;
procedure TfmPrintBuffer.btnClearClick(Sender: TObject);
begin
Memo.Clear;
end;
end.
|
unit uLayoutMyExpress;
interface
uses
Contnrs, ACBrTXTClass, ACBrUtil, Controls;
type
TTipoItem = (
tiMercadoriaRevenda, { *** } // 00 – Mercadoria para Revenda
tiMateriaPrima, { ******** } // 01 – Matéria-Prima;
tiEmbalagem, { *********** } // 02 – Embalagem;
tiProdutoProcesso, { ***** } // 03 – Produto em Processo;
tiProdutoAcabado, { ****** } // 04 – Produto Acabado;
tiSubproduto, { ********** } // 05 – Subproduto;
tiProdutoIntermediario, {* } // 06 – Produto Intermediário;
tiMaterialConsumo, { ***** } // 07 – Material de Uso e Consumo;
tiAtivoImobilizado, { **** } // 08 – Ativo Imobilizado;
tiServicos, { ************ } // 09 – Serviços;
tiOutrosInsumos, { ******* } // 10 – Outros Insumos;
tiOutras { *************** } // 99 – Outras
);
TPosseItem = (
piInformante, { *********** } // 0- Item de propriedade do informante e em seu poder;
piInformanteNoTerceiro, { * } // 1- Item de propriedade do informante em posse de terceiros;
piTerceiroNoInformante { ** } // 2- Item de propriedade de terceiros em posse do informante
);
MyExpressUtil = class
private
class function PosseItemToStr(AValue: TPosseItem): string;
class function TipoItemToStr(AValue: TTipoItem): string;
public
class function StrToTipoItem(AValue: string): TTipoItem;
class function StrToPosseItem(AValue: string): TPosseItem;
end;
TItemCampos = class
private
fCODIGO: string;
fDESCRICAO: string;
fEAN: string;
fUNIDADE: string;
fTIPO_ITEM: TTipoItem;
FNCM: string;
FEX_IPI: string;
FCOD_GEN: string;
FALIQ_ICMS: Currency;
FQUANTIDADE: Double;
FVL_UNIT: Currency;
FPOSSE_ITEM: TPosseItem;
FDESCRICAO_CPL: string;
procedure SetCODIGO(const Value: string);
procedure setUNIDADE(const Value: string);
procedure SetDESCRICAO(const Value: string);
procedure SetEAN(const Value: string);
procedure SetNCM(const Value: string);
procedure SetEX_IPI(const Value: string);
procedure SetCOD_GEN(const Value: string);
procedure SetDESCRICAO_CPL(const Value: string);
public
property CODIGO: string read fCODIGO write SetCODIGO;
property DESCRICAO: string read fDESCRICAO write SetDESCRICAO;
property EAN: string read fEAN write SetEAN;
property UNIDADE: string read fUNIDADE write setUNIDADE;
property TIPO_ITEM: TTipoItem read fTIPO_ITEM write fTIPO_ITEM;
property NCM: string read FNCM write SetNCM;
property EX_IPI: string read FEX_IPI write SetEX_IPI;
property COD_GEN: string read FCOD_GEN write SetCOD_GEN;
property ALIQ_ICMS: Currency read FALIQ_ICMS write FALIQ_ICMS;
property QUANTIDADE: Double read FQUANTIDADE write FQUANTIDADE;
property VL_UNIT: Currency read FVL_UNIT write FVL_UNIT;
property POSSE_ITEM: TPosseItem read FPOSSE_ITEM write FPOSSE_ITEM;
property DESCRICAO_CPL: string read FDESCRICAO_CPL write SetDESCRICAO_CPL;
end;
TItemInventario = class
private
List: TObjectList;
function GetCountItems: Integer;
function GetItem(Index: Integer): TItemCampos;
procedure SetItem(Index: Integer; const Value: TItemCampos);
protected
function Add(AObject: TItemCampos): Integer; overload;
public
constructor Create(AOwnObjects: Boolean = True);
destructor Destroy; override;
property Items[Index: Integer]: TItemCampos read GetItem write SetItem;
property Count: Integer read GetCountItems;
function Add: TItemCampos; overload;
procedure Delete(Index: Integer);
procedure Clear;
end;
TInventarioMyExpress = class
private
ACBrTXT: TACBrTXTClass;
FArquivo: AnsiString;
FInicializado: Boolean;
FPath: AnsiString;
FLinhasBuffer: Integer;
fCNPJ: string;
fDT_INVENTARIO: TDate;
FHoje: TDate;
FITENS_INVENT: TItemInventario;
procedure SetPath(const Value: AnsiString);
procedure SetLinhasBuffer(const Value: Integer);
procedure SetArquivo(const Value: AnsiString);
procedure Error(const MsnError: string);
public
constructor Create;
destructor Destroy; override;
procedure IniciaGeracao;
property LinhasBuffer: Integer read FLinhasBuffer write SetLinhasBuffer;
property Path: AnsiString read FPath write SetPath;
property Arquivo: AnsiString read FArquivo write SetArquivo;
property Hoje: TDate read FHoje write FHoje;
property CNPJ: string read fCNPJ write fCNPJ;
property DT_INVENTARIO: TDate read fDT_INVENTARIO write fDT_INVENTARIO;
property ITENS_INVENT: TItemInventario read FITENS_INVENT write FITENS_INVENT;
end;
TProdutosCampos = class
private
FUNIDADE: string;
FDESCRICAO: string;
FEAN: string;
FPRODUTO_FORN: string;
FCNPJ_CPF_FORN: string;
FCODIGO_PRODUTO: string;
FTIPO_ITEM: TTipoItem;
FCNPJ_FORN: string;
FUNID_CONVERSAO: string;
FFATOR_CONVERSAO: Double;
procedure SetCODIGO_PRODUTO(const Value: string);
procedure SetEAN(const Value: string);
procedure SetPRODUTO_FORN(const Value: string);
procedure SetUNIDADE(const Value: string);
procedure SetDESCRICAO(const Value: string);
procedure SetCNPJ_FORN(const Value: string);
procedure SetUNID_CONVERSAO(const Value: string);
public
property CNPJ_FORN: string read FCNPJ_FORN write SetCNPJ_FORN;
property PRODUTO_FORN: string read FPRODUTO_FORN write SetPRODUTO_FORN;
property CODIGO_PRODUTO: string read FCODIGO_PRODUTO write SetCODIGO_PRODUTO;
property DESCRICAO: string read FDESCRICAO write SetDESCRICAO;
property EAN: string read FEAN write SetEAN;
property UNIDADE: string read FUNIDADE write SetUNIDADE;
property TIPO_ITEM: TTipoItem read FTIPO_ITEM write FTIPO_ITEM;
property UNID_CONVERSAO: string read FUNID_CONVERSAO write SetUNID_CONVERSAO;
property FATOR_CONVERSAO: Double read FFATOR_CONVERSAO write FFATOR_CONVERSAO;
end;
TProdutosList = class
private
List: TObjectList;
function GetCountItems: Integer;
function GetItem(Index: Integer): TProdutosCampos;
procedure SetItem(Index: Integer; const Value: TProdutosCampos);
protected
function Add(AObject: TProdutosCampos): Integer; overload;
public
constructor Create(AOwnObjects: Boolean = True);
destructor Destroy; override;
property Items[Index: Integer]: TProdutosCampos read GetItem write SetItem;
property Count: Integer read GetCountItems;
function Add: TProdutosCampos; overload;
procedure Delete(Index: Integer);
procedure Clear;
end;
TProdutosMyExpress = class
private
ACBrTXT: TACBrTXTClass;
FInicializado: Boolean;
FArquivo: AnsiString;
FPath: AnsiString;
FLinhasBuffer: Integer;
fCNPJ: string;
fDT_INVENTARIO: TDate;
FHoje: TDate;
FLISTA_DE_PRODUTOS: TProdutosList;
procedure SetArquivo(const Value: AnsiString);
procedure SetLinhasBuffer(const Value: Integer);
procedure SetPath(const Value: AnsiString);
procedure Error(const MsnError: string);
public
constructor Create;
destructor Destroy; override;
procedure IniciaGeracao;
property LinhasBuffer: Integer read FLinhasBuffer write SetLinhasBuffer;
property Path: AnsiString read FPath write SetPath;
property Arquivo: AnsiString read FArquivo write SetArquivo;
property Hoje: TDate read FHoje write FHoje;
property CNPJ: string read fCNPJ write fCNPJ;
property DT_GERACAO: TDate read fDT_INVENTARIO write fDT_INVENTARIO;
property LISTA_DE_PRODUTOS: TProdutosList read FLISTA_DE_PRODUTOS write FLISTA_DE_PRODUTOS;
end;
implementation
uses
SysUtils, DateUtils;
{ TInventarioMyExpress }
constructor TInventarioMyExpress.Create;
begin
ACBrTXT := TACBrTXTClass.create;
FITENS_INVENT := TItemInventario.Create;
FLinhasBuffer := 1000;
FPath := ExtractFilePath(ParamStr(0));
ACBrTXT.Delimitador := '|';
ACBrTXT.CurMascara := '#0.00';
ACBrTXT.TrimString := True;
FInicializado := False;
FHoje := Date;
ACBrTXT.OnError := Error;
end;
destructor TInventarioMyExpress.Destroy;
begin
ACBrTXT.Free;
FITENS_INVENT.Free;
inherited Destroy;
end;
procedure TInventarioMyExpress.Error(const MsnError: string);
begin
raise Exception.Create(ACBrStr(MsnError));
end;
procedure TInventarioMyExpress.IniciaGeracao;
var
Linha: string;
intCont: Integer;
begin
if FInicializado then
Exit;
if (Trim(FArquivo) = EmptyStr) or (Trim(FPath) = EmptyStr) then
raise Exception.Create(ACBrStr('Caminho ou nome do arquivo não informado!'));
ACBrTXT.NomeArquivo := FPath + FArquivo;
ACBrTXT.Reset; // Apaga o Arquivo e limpa memória
ACBrTXT.Check(fDT_INVENTARIO > 0, 'CHECAGEM INICIAL: Informe a data '
+ 'do inventário no arquivo!');
ACBrTXT.Check(fDT_INVENTARIO <= FHoje, 'CHECAGEM INICIAL: A data final "%s" '
+ 'não pode ser superior a data atual "%s"!',
[DateToStr(fDT_INVENTARIO), DateToStr(FHoje)]);
ACBrTXT.Check(DateOf(EndOfTheMonth(fDT_INVENTARIO)) = DateOf(fDT_INVENTARIO),
'CHECAGEM ' + 'INICIAL: A data final deve corresponder ao último dia do mês '
+ 'informado!');
ACBrTXT.Check(fCNPJ <> EmptyStr, 'CHECAGEM ' +
'INICIAL: CNPJ da empresa não foi informado!');
FInicializado := True;
if FInicializado then
with ACBrTXT do
begin
Linha := LFill('00');
Linha := Linha + LFill(fCNPJ, 18);
Linha := Linha + LFill(FormatDateTime('dd/mm/yyyy', DT_INVENTARIO), 10);
if Linha[1] = ACBrTXT.Delimitador then
Linha := Copy(Linha, 2, Length(Linha));
Add(Linha, False);
for intCont := 0 to Pred(FITENS_INVENT.Count) do
begin
Linha := LFill('01');
Linha := Linha + LFill(FITENS_INVENT.Items[intCont].CODIGO);
Linha := Linha + LFill(FITENS_INVENT.Items[intCont].DESCRICAO);
Linha := Linha + LFill(FITENS_INVENT.Items[intCont].EAN);
Linha := Linha + LFill(FITENS_INVENT.Items[intCont].UNIDADE);
Linha := Linha + LFill(MyExpressUtil.TipoItemToStr(FITENS_INVENT.Items[intCont].TIPO_ITEM));
Linha := Linha + LFill(FITENS_INVENT.Items[intCont].NCM);
Linha := Linha + LFill(FITENS_INVENT.Items[intCont].EX_IPI);
Linha := Linha + LFill(FITENS_INVENT.Items[intCont].COD_GEN);
Linha := Linha + DFill(FITENS_INVENT.Items[intCont].ALIQ_ICMS);
Linha := Linha + DFill(FITENS_INVENT.Items[intCont].QUANTIDADE, 5);
Linha := Linha + DFill(FITENS_INVENT.Items[intCont].VL_UNIT, 5);
Linha := Linha + LFill(MyExpressUtil.PosseItemToStr(FITENS_INVENT.Items[intCont].POSSE_ITEM));
if FITENS_INVENT.Items[intCont].DESCRICAO_CPL <> EmptyStr then
Linha := Linha + LFill(FITENS_INVENT.Items[intCont].DESCRICAO_CPL);
if Linha[1] = ACBrTXT.Delimitador then
Linha := Copy(Linha, 2, Length(Linha));
Add(Linha, False);
end;
SaveToFile;
end;
end;
procedure TInventarioMyExpress.SetArquivo(const Value: AnsiString);
var
lPath: AnsiString;
begin
if FArquivo = Value then
Exit;
FArquivo := ExtractFileName(Value);
lPath := ExtractFilePath(Value);
if lPath <> EmptyStr then
FPath := lPath;
end;
procedure TInventarioMyExpress.SetLinhasBuffer(const Value: Integer);
begin
if FLinhasBuffer = Value then
Exit;
FLinhasBuffer := Value;
ACBrTXT.LinhasBuffer := FLinhasBuffer;
end;
procedure TInventarioMyExpress.SetPath(const Value: AnsiString);
begin
FPath := PathWithDelim(Value);
end;
{ TItemCampos }
procedure TItemCampos.SetCODIGO(const Value: string);
begin
if fCODIGO = Value then
Exit;
fCODIGO := Value;
if Length(Trim(fCODIGO)) > 60 then
fCODIGO := Copy(fCODIGO, 1, 60);
end;
procedure TItemCampos.SetCOD_GEN(const Value: string);
begin
if FCOD_GEN = Value then
Exit;
FCOD_GEN := Value;
if Length(Trim(FCOD_GEN)) > 2 then
FCOD_GEN := Copy(FCOD_GEN, 1, 2);
end;
procedure TItemCampos.SetDESCRICAO(const Value: string);
begin
if fDESCRICAO = Value then
Exit;
fDESCRICAO := Value;
if Length(Trim(fDESCRICAO)) > 120 then
fDESCRICAO := Copy(fDESCRICAO, 1, 120);
end;
procedure TItemCampos.SetDESCRICAO_CPL(const Value: string);
begin
if FDESCRICAO_CPL = Value then
Exit;
FDESCRICAO_CPL := Value;
if Length(Trim(FDESCRICAO_CPL)) > 120 then
FDESCRICAO_CPL := Copy(FDESCRICAO_CPL, 1, 120);
end;
procedure TItemCampos.SetEAN(const Value: string);
begin
if fEAN = Value then
Exit;
fEAN := Value;
if Length(Trim(fEAN)) > 20 then
fEAN := Copy(fEAN, 1, 20);
end;
procedure TItemCampos.SetEX_IPI(const Value: string);
begin
if FEX_IPI = Value then
Exit;
FEX_IPI := Value;
if Length(Trim(FEX_IPI)) > 3 then
FEX_IPI := Copy(FEX_IPI, 1, 3);
end;
procedure TItemCampos.SetNCM(const Value: string);
begin
if FNCM = Value then
Exit;
FNCM := OnlyNumber(Value);
if Length(Trim(FNCM)) > 8 then
FNCM := Copy(FNCM, 1, 8);
end;
procedure TItemCampos.setUNIDADE(const Value: string);
begin
if fUNIDADE = Value then
Exit;
fUNIDADE := Value;
if Length(Trim(fUNIDADE)) > 6 then
fUNIDADE := Copy(fUNIDADE, 1, 6);
end;
{ TProdutosMyExpress }
constructor TProdutosMyExpress.Create;
begin
ACBrTXT := TACBrTXTClass.create;
FLISTA_DE_PRODUTOS := TProdutosList.Create;
FLinhasBuffer := 1000;
FPath := ExtractFilePath(ParamStr(0));
ACBrTXT.Delimitador := '|';
ACBrTXT.CurMascara := '#0.00';
ACBrTXT.TrimString := True;
FInicializado := False;
FHoje := Date;
ACBrTXT.OnError := Error;
end;
destructor TProdutosMyExpress.Destroy;
begin
ACBrTXT.Free;
FLISTA_DE_PRODUTOS.Free;
inherited Destroy;
end;
procedure TProdutosMyExpress.Error(const MsnError: string);
begin
raise Exception.Create(ACBrStr(MsnError));
end;
procedure TProdutosMyExpress.IniciaGeracao;
var
Linha: string;
intCont: Integer;
begin
if FInicializado then
Exit;
if (Trim(FArquivo) = EmptyStr) or (Trim(FPath) = EmptyStr) then
raise Exception.Create(ACBrStr('Caminho ou nome do arquivo não informado!'));
ACBrTXT.NomeArquivo := FPath + FArquivo;
ACBrTXT.Reset; // Apaga o Arquivo e limpa memória
ACBrTXT.Check(fDT_INVENTARIO > 0, 'CHECAGEM INICIAL: Informe a data '
+ 'do inventário no arquivo!');
ACBrTXT.Check(fDT_INVENTARIO <= FHoje, 'CHECAGEM INICIAL: A data final "%s" '
+ 'não pode ser superior a data atual "%s"!',
[DateToStr(fDT_INVENTARIO), DateToStr(FHoje)]);
ACBrTXT.Check(fCNPJ <> EmptyStr, 'CHECAGEM ' +
'INICIAL: CNPJ da empresa não foi informado!');
FInicializado := True;
if FInicializado then
with ACBrTXT do
begin
Linha := LFill('00');
Linha := Linha + LFill(fCNPJ, 18);
Linha := Linha + LFill(FormatDateTime('dd/mm/yyyy', DT_GERACAO), 10);
if Linha[1] = ACBrTXT.Delimitador then
Linha := Copy(Linha, 2, Length(Linha));
Add(Linha, False);
for intCont := 0 to Pred(FLISTA_DE_PRODUTOS.Count) do
begin
Linha := LFill('01');
Linha := Linha + LFill(FLISTA_DE_PRODUTOS.Items[intCont].CNPJ_FORN);
Linha := Linha + LFill(FLISTA_DE_PRODUTOS.Items[intCont].PRODUTO_FORN);
Linha := Linha + LFill(FLISTA_DE_PRODUTOS.Items[intCont].CODIGO_PRODUTO);
Linha := Linha + LFill(FLISTA_DE_PRODUTOS.Items[intCont].DESCRICAO);
Linha := Linha + LFill(FLISTA_DE_PRODUTOS.Items[intCont].EAN);
Linha := Linha + LFill(FLISTA_DE_PRODUTOS.Items[intCont].UNIDADE);
Linha := Linha + LFill(MyExpressUtil.TipoItemToStr(FLISTA_DE_PRODUTOS.Items[intCont].TIPO_ITEM));
if Linha[1] = ACBrTXT.Delimitador then
Linha := Copy(Linha, 2, Length(Linha));
Add(Linha, False);
if (FLISTA_DE_PRODUTOS.Items[intCont].UNID_CONVERSAO <> EmptyStr) and
(FLISTA_DE_PRODUTOS.Items[intCont].FATOR_CONVERSAO > 0) then
begin
Linha := LFill('03');
Linha := Linha + LFill(FLISTA_DE_PRODUTOS.Items[intCont].UNID_CONVERSAO);
Linha := Linha + DFill(FLISTA_DE_PRODUTOS.Items[intCont].FATOR_CONVERSAO, 6);
if Linha[1] = ACBrTXT.Delimitador then
Linha := Copy(Linha, 2, Length(Linha));
Add(Linha, False);
end;
end;
SaveToFile;
end;
end;
procedure TProdutosMyExpress.SetArquivo(const Value: AnsiString);
var
lPath: AnsiString;
begin
if FArquivo = Value then
Exit;
FArquivo := ExtractFileName(Value);
lPath := ExtractFilePath(Value);
if lPath <> EmptyStr then
FPath := lPath;
end;
procedure TProdutosMyExpress.SetLinhasBuffer(const Value: Integer);
begin
if FLinhasBuffer = Value then
Exit;
FLinhasBuffer := Value;
ACBrTXT.LinhasBuffer := FLinhasBuffer;
end;
procedure TProdutosMyExpress.SetPath(const Value: AnsiString);
begin
FPath := PathWithDelim(Value);
end;
{ TProdutosCampos }
procedure TProdutosCampos.SetCNPJ_FORN(const Value: string);
begin
FCNPJ_FORN := OnlyNumber(Value);
end;
procedure TProdutosCampos.SetCODIGO_PRODUTO(const Value: string);
begin
if FCODIGO_PRODUTO = Value then
Exit;
FCODIGO_PRODUTO := Value;
if Length(Trim(FCODIGO_PRODUTO)) > 60 then
FCODIGO_PRODUTO := Copy(FCODIGO_PRODUTO, 1, 60);
end;
procedure TProdutosCampos.SetDESCRICAO(const Value: string);
begin
if FDESCRICAO = Value then
Exit;
FDESCRICAO := Value;
if Length(Trim(FDESCRICAO)) > 120 then
FDESCRICAO := Copy(FDESCRICAO, 1, 120);
end;
procedure TProdutosCampos.SetEAN(const Value: string);
begin
if FEAN = Value then
Exit;
FEAN := Value;
if Length(Trim(FEAN)) > 20 then
FEAN := Copy(FEAN, 1, 20);
end;
procedure TProdutosCampos.SetPRODUTO_FORN(const Value: string);
begin
if PRODUTO_FORN = Value then
Exit;
FPRODUTO_FORN := Value;
if Length(Trim(FPRODUTO_FORN)) > 60 then
FPRODUTO_FORN := Copy(FPRODUTO_FORN, 1, 60);
end;
procedure TProdutosCampos.SetUNIDADE(const Value: string);
begin
if FUNIDADE = Value then
Exit;
FUNIDADE := Value;
if Length(Trim(FUNIDADE)) > 6 then
fUNIDADE := Copy(FUNIDADE, 1, 6);
end;
procedure TProdutosCampos.SetUNID_CONVERSAO(const Value: string);
begin
if FUNID_CONVERSAO = Value then
Exit;
FUNID_CONVERSAO := Value;
if Length(Trim(FUNID_CONVERSAO)) > 6 then
FUNID_CONVERSAO := Copy(FUNID_CONVERSAO, 1, 6);
end;
{ TProdutosList }
function TProdutosList.Add: TProdutosCampos;
begin
Result := TProdutosCampos.Create;
Add(Result);
end;
function TProdutosList.Add(AObject: TProdutosCampos): Integer;
begin
Result := List.Add(AObject);
end;
procedure TProdutosList.Clear;
begin
List.Clear;
end;
constructor TProdutosList.Create(AOwnObjects: Boolean);
begin
List := TObjectList.Create(AOwnObjects);
end;
procedure TProdutosList.Delete(Index: Integer);
begin
List.Delete(Index);
end;
destructor TProdutosList.Destroy;
begin
List.Free;
inherited Destroy;
end;
function TProdutosList.GetCountItems: Integer;
begin
Result := List.Count;
end;
function TProdutosList.GetItem(Index: Integer): TProdutosCampos;
begin
Result := TProdutosCampos(List[Index]);
end;
procedure TProdutosList.SetItem(Index: Integer;
const Value: TProdutosCampos);
begin
List[Index] := Value;
end;
{ TItemInventario }
function TItemInventario.Add: TItemCampos;
begin
Result := TItemCampos.Create;
Add(Result);
end;
function TItemInventario.Add(AObject: TItemCampos): Integer;
begin
Result := List.Add(AObject);
end;
procedure TItemInventario.Clear;
begin
List.Clear;
end;
constructor TItemInventario.Create(AOwnObjects: Boolean);
begin
List := TObjectList.Create(AOwnObjects);
end;
procedure TItemInventario.Delete(Index: Integer);
begin
List.Delete(Index);
end;
destructor TItemInventario.Destroy;
begin
List.Free;
inherited Destroy;
end;
function TItemInventario.GetCountItems: Integer;
begin
Result := List.Count;
end;
function TItemInventario.GetItem(Index: Integer): TItemCampos;
begin
Result := TItemCampos(List[Index]);
end;
procedure TItemInventario.SetItem(Index: Integer;
const Value: TItemCampos);
begin
List[Index] := Value;
end;
{ MyExpressUtil }
class function MyExpressUtil.PosseItemToStr(AValue: TPosseItem): string;
begin
Result := FormatFloat('0', Integer(AValue));
end;
class function MyExpressUtil.StrToPosseItem(AValue: string): TPosseItem;
begin
Result := TPosseItem(StrToIntDef(AValue, 0));
end;
class function MyExpressUtil.StrToTipoItem(AValue: string): TTipoItem;
begin
if AValue = '99' then
Result := tiOutras
else
Result := TTipoItem(StrToIntDef(AValue, 0));
end;
class function MyExpressUtil.TipoItemToStr(AValue: TTipoItem): string;
begin
if AValue = tiOutras then
Result := '99'
else
Result := FormatFloat('00', Integer(AValue));
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StPQueue.pas 4.04 *}
{*********************************************************}
{* SysTools: Priority Queue Classes *}
{*********************************************************}
{$I StDefine.inc}
{Notes:
Based on the double-ended heap (deap) described in Horowitz and Sahni,
Data Structures and Algorithms in C.
The deap was first reported in:
Svante Carlsson, "The Deap - a double-ended heap to implement double-
ended priority queues", Information Processing Letters, 26,
pp. 33-36, 1987.
A deap is a complete binary tree. The root node holds no data. Its
left subtree is a min heap. Its right subtree is a max heap. If the right
subtree is not empty, let i be any node in the left subtree. Let j be
the node at the corresponding position in the right subtree. If such a
j does not exist, let j be the node in the right subtree at the position
corresponding to i's parent. The deap has the property that the data in
node i is less than or equal to the data in node j.
Insertion is an O(log2(n)) operation. Deletion of the min or max node
is also an O(log2(n)) operation.
Data elements in the deap are pointers, which can point to any record
structure or class, or can contain any data type of 4 bytes or less.
The deap needs an ordering relationship, so it is essential to assign
to the Compare property inherited from the TStContainer class.
STPQUEUE uses the DisposeData procedure of TStContainer to determine
how to free elements in the collection. By default, it does nothing.
In 16-bit programs the deap is limited to 16380 elements. In 32-bit
programs the limit is set by memory usage or performance.
}
unit StPQueue;
interface
uses
Windows, SysUtils, Classes,
StConst, StBase;
type
{first actual element is at index 2}
{.Z+}
TStPQData = array[2..(StMaxBlockSize div SizeOf(Pointer))+1] of Pointer;
PStPQData = ^TStPQData;
{.Z-}
TStPQueue = class(TStContainer)
{.Z+}
protected {private}
pqData : PStPQData; {data - the complete binary tree}
pqCapacity : Integer; {max elements currently possible}
pqDelta : Integer; {delta elements to grow when needed}
procedure ForEachPointer(Action : TIteratePointerFunc; OtherData : Pointer);
override;
function StoresPointers : Boolean;
override;
procedure Expand(Need : Integer);
procedure InsertMin(I : Integer; Data : Pointer);
procedure InsertMax(I : Integer; Data : Pointer);
procedure ModifiedInsert(I : Integer; Data : Pointer);
{.Z-}
public
constructor Create(InitCapacity, Delta : Integer);
virtual;
{-Initialize an empty PQueue of given capacity. If it overflows
grow the PQueue by Delta elements}
destructor Destroy;
override;
{-Free a PQueue}
procedure LoadFromStream(S : TStream);
override;
{-Create a PQueue and its data from a stream}
procedure StoreToStream(S : TStream);
override;
{-Write a PQueue and its data to a stream}
procedure Clear;
override;
{-Remove all data from container but leave it instantiated and
with its current capacity}
procedure Insert(Data : Pointer);
{-Add a new node}
function DeleteMin : Pointer;
{-Remove the minimum node and return its Pointer}
function DeleteMax : Pointer;
{-Remove the maximum node and return its Pointer}
procedure Assign(Source : TPersistent);
override;
{-Assign another container's contents to this one. Only SysTools
containers that store pointers are allowed.}
procedure Join(Q : TStPQueue);
{-Add PQueue Q into this one and dispose Q}
function Iterate(Action : TIteratePointerFunc;
OtherData : Pointer) : Pointer;
{-Call Action for all the nodes or until Action returns false. Note
that the nodes are visited in no particular order.}
function Test : Boolean;
{-Determine whether deap properties are currently valid (for debugging)}
end;
{.Z+}
TStPQueueClass = class of TStPQueue;
{.Z-}
implementation
{$IFDEF ThreadSafe}
var
ClassCritSect : TRTLCriticalSection;
{$ENDIF}
type
TStoreInfo = record
Wtr : TWriter;
SDP : TStoreDataProc;
end;
function AssignData(Container : TStContainer;
Data, OtherData : Pointer) : Boolean; far;
begin
TStPQueue(OtherData).Insert(Data);
AssignData := True;
end;
function DestroyNode(Container : TStContainer;
Data, OtherData : Pointer) : Boolean; far;
begin
if Assigned(Data) then
Container.DoDisposeData(Data);
DestroyNode := True;
end;
procedure EnterClassCS;
begin
{$IFDEF ThreadSafe}
EnterCriticalSection(ClassCritSect);
{$ENDIF}
end;
function JoinData(Container : TStContainer;
Data, OtherData : Pointer) : Boolean; far;
begin
TStPQueue(OtherData).Insert(Data);
JoinData := True;
end;
procedure LeaveClassCS;
begin
{$IFDEF ThreadSafe}
LeaveCriticalSection(ClassCritSect);
{$ENDIF}
end;
function log2(I : Integer) : Integer;
{-Return the Integer below log2(I)}
begin
Result := 0;
while (I > 1) do begin
Inc(Result);
I := I shr 1;
end;
end;
function StoreNode(Container : TStContainer;
Data, OtherData : Pointer) : Boolean; far;
begin
StoreNode := True;
with TStoreInfo(OtherData^) do
SDP(Wtr, Data);
end;
procedure TStPQueue.Assign(Source : TPersistent);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if not AssignPointers(Source, AssignData) then
inherited Assign(Source);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStPQueue.Clear;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if conNodeProt = 0 then
ForEachPointer(StPQueue.DestroyNode, nil);
FCount := 0;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
constructor TStPQueue.Create(InitCapacity, Delta : Integer);
begin
if (InitCapacity < 2) or (Delta < 1) then
RaiseContainerError(stscBadSize);
FCount := 0;
{ensure that Expand creates initial capacity InitCapacity}
pqCapacity := -Delta;
pqDelta := Delta;
pqData := nil;
CreateContainer(TStNode, 0);
Expand(InitCapacity);
end;
function TStPQueue.DeleteMin : Pointer;
var
I, j, n : Integer;
Temp : Pointer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if (FCount < 1) then begin
{deap is empty}
DeleteMin := nil;
exit;
end;
{return min element}
DeleteMin := pqData^[2];
{save last element and reset (helps debugging)}
Temp := pqData^[FCount+1];
pqData^[FCount+1] := nil;
{decrement count, n is index of new last element}
n := FCount;
dec(FCount);
if (FCount > 0) then begin
{move empty min-root down to an appropriate leaf}
I := 2;
while (I shl 1 <= n) do begin
{find child with smaller key}
j := I shl 1;
if (j+1 <= n) then
if (DoCompare(pqData^[j], pqData^[j+1]) > 0) then
Inc(j);
pqData^[I] := pqData^[j];
I := j;
end;
{insert the old last element at the given leaf position}
ModifiedInsert(I, Temp);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TStPQueue.DeleteMax : Pointer;
var
I, j, n : Integer;
Temp : Pointer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if (FCount < 1) then begin
{deap is empty}
DeleteMax := nil;
exit;
end;
{return max element}
if (FCount = 1) then
DeleteMax := pqData^[2]
else
DeleteMax := pqData^[3];
{save last element and reset (helps debugging)}
Temp := pqData^[FCount+1];
pqData^[FCount+1] := nil;
{decrement count, n is index of new last element}
n := FCount;
dec(FCount);
if (FCount > 0) then begin
{move empty max-root down to an appropriate leaf}
I := 3;
while (I shl 1 <= n) do begin
{find child with larger key}
j := I shl 1;
if (j+1 <= n) then
if (DoCompare(pqData^[j], pqData^[j+1]) < 0) then
Inc(j);
pqData^[I] := pqData^[j];
I := j;
end;
{insert the old last element at the given leaf position}
ModifiedInsert(I, Temp);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
destructor TStPQueue.Destroy;
begin
if (pqData <> nil) then begin
Clear;
FreeMem(pqData, pqCapacity*SizeOf(Pointer));
end;
IncNodeProtection;
inherited Destroy;
end;
procedure TStPQueue.Expand(Need : Integer);
var
NewCapacity : Integer;
Size : Integer;
NewData : PStPQData;
begin
if Need > pqCapacity then begin
{determine new capacity}
NewCapacity := pqCapacity+pqDelta;
if (NewCapacity < Need) then
NewCapacity := Need;
{make sure it's feasible to allocate it}
Size := Integer(NewCapacity)*SizeOf(Pointer);
{if Size > MaxBlockSize then}
{RaiseContainerError(stscBadSize);}
{allocate new data}
GetMem(NewData, Size);
{copy old data to it and free old data}
if (pqData <> nil) then begin
move(pqData^, NewData^, pqCapacity*SizeOf(Pointer));
FreeMem(pqData, pqCapacity*SizeOf(Pointer));
end;
{update instance variables}
pqData := NewData;
pqCapacity := NewCapacity;
end;
end;
procedure TStPQueue.ForEachPointer(Action : TIteratePointerFunc; OtherData : Pointer);
var
I : Integer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{first element is 2, last is FCount+1}
for I := 2 to FCount+1 do
if not Action(Self, pqData^[I], OtherData) then
Exit;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStPQueue.Insert(Data : Pointer);
var
I, n, p : Integer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{adding an element, make sure there's space}
Inc(FCount);
Expand(FCount);
if (FCount = 1) then
{insert into empty deap}
pqData^[2] := Data
else begin
{n is the actual array index}
n := FCount+1;
{determine whether n is in the min or max subtree}
p := n;
while (p > 3) do
p := p shr 1;
if (p = 2) then begin
{n is a position on the min side}
{I is its partner on the max side}
I := (n+(1 shl (log2(n)-1))) shr 1;
if (DoCompare(Data, pqData^[I]) > 0) then begin
pqData^[n] := pqData^[I];
InsertMax(I, Data);
end else
InsertMin(n, Data);
end else begin
{n is a position on the max side}
{I is its partner on the min side}
I := n-(1 shl (log2(n)-1));
if (DoCompare(Data, pqData^[I]) < 0) then begin
pqData^[n] := pqData^[I];
InsertMin(I, Data);
end else
InsertMax(n, Data);
end;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStPQueue.InsertMin(I : Integer; Data : Pointer);
{-Insert into min-heap rooted at node 2}
var
j : Integer;
begin
while (I > 2) and (DoCompare(Data, pqData^[I shr 1]) < 0) do begin
j := I shr 1;
pqData^[I] := pqData^[j];
I := j;
end;
pqData^[I] := Data;
end;
procedure TStPQueue.InsertMax(I : Integer; Data : Pointer);
{-Insert into max-heap rooted at node 3}
var
j : Integer;
begin
while (I > 3) and (DoCompare(Data, pqData^[I shr 1]) > 0) do begin
j := I shr 1;
pqData^[I] := pqData^[j];
I := j;
end;
pqData^[I] := Data;
end;
function TStPQueue.Iterate(Action : TIteratePointerFunc;
OtherData : Pointer) : Pointer;
var
I : Integer;
begin
Iterate := nil;
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{first element is 2, last is FCount+1}
for I := 2 to FCount+1 do
if not Action(Self, pqData^[I], OtherData) then begin
Iterate := pqData^[I];
Exit;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStPQueue.Join(Q : TStPQueue);
begin
{$IFDEF ThreadSafe}
EnterClassCS;
EnterCS;
Q.EnterCS;
try
{$ENDIF}
if (not Assigned(Q)) then
RaiseContainerError(stscBadType);
Q.ForEachPointer(JoinData, Self);
Q.IncNodeProtection;
Q.Free;
{$IFDEF ThreadSafe}
finally
Q.LeaveCS;
LeaveCS;
LeaveClassCS;
end;
{$ENDIF}
end;
procedure TStPQueue.LoadFromStream(S : TStream);
var
Data : Pointer;
Reader : TReader;
StreamedClass : TPersistentClass;
StreamedClassName : string;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Clear;
Reader := TReader.Create(S, 1024);
try
with Reader do begin
StreamedClassName := ReadString;
StreamedClass := GetClass(StreamedClassName);
if (StreamedClass = nil) then
RaiseContainerErrorFmt(stscUnknownClass, [StreamedClassName]);
if (not IsOrInheritsFrom(StreamedClass, Self.ClassType)) or
(not IsOrInheritsFrom(TStPQueue, StreamedClass)) then
RaiseContainerError(stscWrongClass);
ReadListBegin;
while not EndOfList do begin
Data := DoLoadData(Reader);
Insert(Data);
end;
ReadListEnd;
end;
finally
Reader.Free;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStPQueue.ModifiedInsert(I : Integer; Data : Pointer);
{-Special insert after a delete. I is the actual array index where
insertion of Data occurs. Tree does not grow.}
var
p, j : Integer;
begin
if (I > 1) then begin
{determine whether I is in the min or max subtree}
p := I;
while (p > 3) do
p := p shr 1;
if (p = 2) then begin
{I is a position on the min side}
{j is its partner on the max side}
j := I+(1 shl (log2(I)-1));
if (j > FCount+1) then
j := j shr 1;
if (j < 3) then
{empty max heap}
pqData^[I] := Data
else if (DoCompare(Data, pqData^[j]) > 0) then begin
pqData^[I] := pqData^[j];
InsertMax(j, Data);
end else
InsertMin(I, Data);
end else begin
{I is a position on the max side}
{j is its partner on the min side}
j := I-(1 shl (log2(I)-1));
{check its children too to preserve deap property}
if (j shl 1 <= FCount+1) then begin
j := j shl 1;
if (j+1 <= FCount+1) then
if (DoCompare(pqData^[j], pqData^[j+1]) < 0) then
Inc(j);
end;
if (DoCompare(Data, pqData^[j]) < 0) then begin
pqData^[I] := pqData^[j];
InsertMin(j, Data);
end else
InsertMax(I, Data);
end;
end;
end;
function TStPQueue.StoresPointers : Boolean;
begin
StoresPointers := True;
end;
procedure TStPQueue.StoreToStream(S : TStream);
var
Writer : TWriter;
StoreInfo : TStoreInfo;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Writer := TWriter.Create(S, 1024);
try
with Writer do begin
WriteString(Self.ClassName);
WriteListBegin;
StoreInfo.Wtr := Writer;
StoreInfo.SDP := StoreData;
Iterate(StoreNode, @StoreInfo);
WriteListEnd;
end;
finally
Writer.Free;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TStPQueue.Test : Boolean;
var
I, i2, j, n, p : Integer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Test := True;
if (FCount = 0) then
exit;
n := FCount+1;
{start with each leaf node}
for I := (1 shl log2(n)) to n do begin
p := I;
while (p > 3) do
p := p shr 1;
if (p = 2) then begin
{I is a position on the min side}
{test min-heap condition}
i2 := I;
while (i2 shr 1 >= 2) do begin
j := i2 shr 1;
if (DoCompare(pqData^[j], pqData^[i2]) > 0) then begin
Test := false;
{writeln('min: j=', j, ' i2=', i2,
' d[j]=', Integer(pqData^[j]), ' d[i2]=', Integer(pqData^[i2]));}
exit;
end;
i2 := j;
end;
{test deap condition}
if n >= 3 then begin
j := I+(1 shl (log2(I)-1));
if (j > n) then
j := j shr 1;
if (DoCompare(pqData^[I], pqData^[j]) > 0) then begin
Test := false;
{writeln('deap: j=', j, ' I=', I,
' d[j]=', Integer(pqData^[j]), ' d[I]=', Integer(pqData^[I]));}
exit;
end;
end;
end else begin
{I is a position on the max side}
{test max-heap condition}
i2 := I;
while (i2 shr 1 >= 3) do begin
j := i2 shr 1;
if (DoCompare(pqData^[j], pqData^[i2]) < 0) then begin
Test := false;
{writeln('max: j=', j, ' i2=', i2,
' d[j]=', Integer(pqData^[j]), ' d[i2]=', Integer(pqData^[i2]));}
exit;
end;
i2 := j;
end;
end;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
{$IFDEF ThreadSafe}
initialization
Windows.InitializeCriticalSection(ClassCritSect);
finalization
Windows.DeleteCriticalSection(ClassCritSect);
{$ENDIF}
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 ClpSecP521R1Point;
{$I ..\..\..\..\Include\CryptoLib.inc}
interface
uses
ClpNat,
ClpECPoint,
ClpSecP521R1Field,
ClpISecP521R1Point,
ClpISecP521R1FieldElement,
ClpIECFieldElement,
ClpIECInterface,
ClpCryptoLibTypes;
resourcestring
SOneOfECFieldElementIsNil = 'Exactly One of the Field Elements is Nil';
type
TSecP521R1Point = class sealed(TAbstractFpPoint, ISecP521R1Point)
strict protected
function Detach(): IECPoint; override;
public
/// <summary>
/// Create a point which encodes without point compression.
/// </summary>
/// <param name="curve">
/// the curve to use
/// </param>
/// <param name="x">
/// affine x co-ordinate
/// </param>
/// <param name="y">
/// affine y co-ordinate
/// </param>
constructor Create(const curve: IECCurve; const x, y: IECFieldElement);
overload; deprecated 'Use ECCurve.createPoint to construct points';
/// <summary>
/// Create a point that encodes with or without point compresion.
/// </summary>
/// <param name="curve">
/// the curve to use
/// </param>
/// <param name="x">
/// affine x co-ordinate
/// </param>
/// <param name="y">
/// affine y co-ordinate
/// </param>
/// <param name="withCompression">
/// if true encode with point compression
/// </param>
constructor Create(const curve: IECCurve; const x, y: IECFieldElement;
withCompression: Boolean); overload;
deprecated
'Per-point compression property will be removed, see GetEncoded(boolean)';
constructor Create(const curve: IECCurve; const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>;
withCompression: Boolean); overload;
function Add(const b: IECPoint): IECPoint; override;
function Negate(): IECPoint; override;
function Twice(): IECPoint; override;
function TwicePlus(const b: IECPoint): IECPoint; override;
function ThreeTimes(): IECPoint; override;
end;
implementation
uses
// included here to avoid circular dependency :)
ClpSecP521R1FieldElement;
{ TSecP521R1Point }
constructor TSecP521R1Point.Create(const curve: IECCurve;
const x, y: IECFieldElement);
begin
Create(curve, x, y, false);
end;
constructor TSecP521R1Point.Create(const curve: IECCurve;
const x, y: IECFieldElement; withCompression: Boolean);
begin
Inherited Create(curve, x, y, withCompression);
if ((x = Nil) <> (y = Nil)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SOneOfECFieldElementIsNil);
end;
end;
constructor TSecP521R1Point.Create(const curve: IECCurve;
const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean);
begin
Inherited Create(curve, x, y, zs, withCompression);
end;
function TSecP521R1Point.Add(const b: IECPoint): IECPoint;
var
Lcurve: IECCurve;
X1, Y1, X2, Y2, Z1, Z2, X3, Y3, Z3: ISecP521R1FieldElement;
t1, t2, t3, t4, U2, S2, U1, S1, H, R, HSquared, G, V: TCryptoLibUInt32Array;
Z1IsOne, Z2IsOne: Boolean;
zs: TCryptoLibGenericArray<IECFieldElement>;
begin
if (IsInfinity) then
begin
result := b;
Exit;
end;
if (b.IsInfinity) then
begin
result := Self as IECPoint;
Exit;
end;
if ((Self as IECPoint) = b) then
begin
result := Twice();
Exit;
end;
Lcurve := curve;
X1 := RawXCoord as ISecP521R1FieldElement;
Y1 := RawYCoord as ISecP521R1FieldElement;
X2 := b.RawXCoord as ISecP521R1FieldElement;
Y2 := b.RawYCoord as ISecP521R1FieldElement;
Z1 := RawZCoords[0] as ISecP521R1FieldElement;
Z2 := b.RawZCoords[0] as ISecP521R1FieldElement;
t1 := TNat.Create(17);
t2 := TNat.Create(17);
t3 := TNat.Create(17);
t4 := TNat.Create(17);
Z1IsOne := Z1.IsOne;
if (Z1IsOne) then
begin
U2 := X2.x;
S2 := Y2.x;
end
else
begin
S2 := t3;
TSecP521R1Field.Square(Z1.x, S2);
U2 := t2;
TSecP521R1Field.Multiply(S2, X2.x, U2);
TSecP521R1Field.Multiply(S2, Z1.x, S2);
TSecP521R1Field.Multiply(S2, Y2.x, S2);
end;
Z2IsOne := Z2.IsOne;
if (Z2IsOne) then
begin
U1 := X1.x;
S1 := Y1.x;
end
else
begin
S1 := t4;
TSecP521R1Field.Square(Z2.x, S1);
U1 := t1;
TSecP521R1Field.Multiply(S1, X1.x, U1);
TSecP521R1Field.Multiply(S1, Z2.x, S1);
TSecP521R1Field.Multiply(S1, Y1.x, S1);
end;
H := TNat.Create(17);
TSecP521R1Field.Subtract(U1, U2, H);
R := t2;
TSecP521R1Field.Subtract(S1, S2, R);
// Check if b = Self or b = -Self
if (TNat.IsZero(17, H)) then
begin
if (TNat.IsZero(17, R)) then
begin
// Self = b, i.e. Self must be doubled
result := Twice();
Exit;
end;
// Self = -b, i.e. the result is the point at infinity
result := Lcurve.Infinity;
Exit;
end;
HSquared := t3;
TSecP521R1Field.Square(H, HSquared);
G := TNat.Create(17);
TSecP521R1Field.Multiply(HSquared, H, G);
V := t3;
TSecP521R1Field.Multiply(HSquared, U1, V);
TSecP521R1Field.Multiply(S1, G, t1);
X3 := TSecP521R1FieldElement.Create(t4);
TSecP521R1Field.Square(R, X3.x);
TSecP521R1Field.Add(X3.x, G, X3.x);
TSecP521R1Field.Subtract(X3.x, V, X3.x);
TSecP521R1Field.Subtract(X3.x, V, X3.x);
Y3 := TSecP521R1FieldElement.Create(G);
TSecP521R1Field.Subtract(V, X3.x, Y3.x);
TSecP521R1Field.Multiply(Y3.x, R, t2);
TSecP521R1Field.Subtract(t2, t1, Y3.x);
Z3 := TSecP521R1FieldElement.Create(H);
if (not(Z1IsOne)) then
begin
TSecP521R1Field.Multiply(Z3.x, Z1.x, Z3.x);
end;
if (not(Z2IsOne)) then
begin
TSecP521R1Field.Multiply(Z3.x, Z2.x, Z3.x);
end;
zs := TCryptoLibGenericArray<IECFieldElement>.Create(Z3);
result := TSecP521R1Point.Create(Lcurve, X3, Y3, zs, IsCompressed)
as IECPoint;
end;
function TSecP521R1Point.Detach: IECPoint;
begin
result := TSecP521R1Point.Create(Nil, AffineXCoord, AffineYCoord) as IECPoint;
end;
function TSecP521R1Point.Negate: IECPoint;
begin
if (IsInfinity) then
begin
result := Self as IECPoint;
Exit;
end;
result := TSecP521R1Point.Create(curve, RawXCoord, RawYCoord.Negate(),
RawZCoords, IsCompressed) as IECPoint;
end;
function TSecP521R1Point.ThreeTimes: IECPoint;
begin
if ((IsInfinity) or (RawYCoord.IsZero)) then
begin
result := Self as IECPoint;
Exit;
end;
// NOTE: Be careful about recursions between TwicePlus and ThreeTimes
result := Twice().Add(Self as IECPoint);
end;
function TSecP521R1Point.Twice: IECPoint;
var
Lcurve: IECCurve;
Y1, X1, Z1, X3, Y3, Z3: ISecP521R1FieldElement;
Y1Squared, Z1Squared, T, M, S, t1, t2: TCryptoLibUInt32Array;
Z1IsOne: Boolean;
begin
if (IsInfinity) then
begin
result := Self as IECPoint;
Exit;
end;
Lcurve := curve;
Y1 := RawYCoord as ISecP521R1FieldElement;
if (Y1.IsZero) then
begin
result := Lcurve.Infinity;
Exit;
end;
X1 := RawXCoord as ISecP521R1FieldElement;
Z1 := RawZCoords[0] as ISecP521R1FieldElement;
t1 := TNat.Create(17);
t2 := TNat.Create(17);
Y1Squared := TNat.Create(17);
TSecP521R1Field.Square(Y1.x, Y1Squared);
T := TNat.Create(17);
TSecP521R1Field.Square(Y1Squared, T);
Z1IsOne := Z1.IsOne;
Z1Squared := Z1.x;
if (not(Z1IsOne)) then
begin
Z1Squared := t2;
TSecP521R1Field.Square(Z1.x, Z1Squared);
end;
TSecP521R1Field.Subtract(X1.x, Z1Squared, t1);
M := t2;
TSecP521R1Field.Add(X1.x, Z1Squared, M);
TSecP521R1Field.Multiply(M, t1, M);
TNat.AddBothTo(17, M, M, M);
TSecP521R1Field.Reduce23(M);
S := Y1Squared;
TSecP521R1Field.Multiply(Y1Squared, X1.x, S);
TNat.ShiftUpBits(17, S, 2, 0);
TSecP521R1Field.Reduce23(S);
TNat.ShiftUpBits(17, T, 3, 0, t1);
TSecP521R1Field.Reduce23(t1);
X3 := TSecP521R1FieldElement.Create(T);
TSecP521R1Field.Square(M, X3.x);
TSecP521R1Field.Subtract(X3.x, S, X3.x);
TSecP521R1Field.Subtract(X3.x, S, X3.x);
Y3 := TSecP521R1FieldElement.Create(S);
TSecP521R1Field.Subtract(S, X3.x, Y3.x);
TSecP521R1Field.Multiply(Y3.x, M, Y3.x);
TSecP521R1Field.Subtract(Y3.x, t1, Y3.x);
Z3 := TSecP521R1FieldElement.Create(M);
TSecP521R1Field.Twice(Y1.x, Z3.x);
if (not(Z1IsOne)) then
begin
TSecP521R1Field.Multiply(Z3.x, Z1.x, Z3.x);
end;
result := TSecP521R1Point.Create(Lcurve, X3, Y3,
TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed)
as IECPoint;
end;
function TSecP521R1Point.TwicePlus(const b: IECPoint): IECPoint;
var
Y1: IECFieldElement;
begin
if ((Self as IECPoint) = b) then
begin
result := ThreeTimes();
Exit;
end;
if (IsInfinity) then
begin
result := b;
Exit;
end;
if (b.IsInfinity) then
begin
result := Twice();
Exit;
end;
Y1 := RawYCoord;
if (Y1.IsZero) then
begin
result := b;
Exit;
end;
result := Twice().Add(b);
end;
end.
|
unit UDemo;
interface
uses
SysUtils, Types, UITypes, Classes, Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSBaseControl,
FMX.TMSGridOptions, FMX.TMSGridData, FMX.TMSGrid, FMX.Edit, FMX.TMSGridCell,
FMX.TMSCustomGrid, FMX.StdCtrls;
type
TForm719 = class(TForm)
TMSFMXGrid1: TTMSFMXGrid;
Panel1: TPanel;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
CheckBox4: TCheckBox;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
procedure FormCreate(Sender: TObject);
procedure CheckBox1Change(Sender: TObject);
procedure CheckBox2Change(Sender: TObject);
procedure CheckBox3Change(Sender: TObject);
procedure CheckBox4Change(Sender: TObject);
procedure RadioButton1Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure InitGrid;
end;
var
Form719: TForm719;
implementation
{$R *.fmx}
procedure TForm719.CheckBox1Change(Sender: TObject);
begin
if checkbox1.IsChecked then
begin
if TMSFMXGrid1.FixedRightColumns = 0 then
TMSFMXGrid1.ColumnCount := TMSFMXGrid1.ColumnCount + 1;
TMSFMXGrid1.FixedRightColumns := 1
end
else
begin
if TMSFMXGrid1.FixedRightColumns = 1 then
TMSFMXGrid1.ColumnCount := TMSFMXGrid1.ColumnCount - 1;
TMSFMXGrid1.FixedRightColumns := 0;
end;
end;
procedure TForm719.CheckBox2Change(Sender: TObject);
begin
if checkbox2.IsChecked then
begin
if TMSFMXGrid1.FixedFooterRows = 0 then
TMSFMXGrid1.RowCount := TMSFMXGrid1.RowCount + 1;
TMSFMXGrid1.FixedFooterRows := 1
end
else
begin
if TMSFMXGrid1.FixedFooterRows = 1 then
TMSFMXGrid1.RowCount := TMSFMXGrid1.RowCount - 1;
TMSFMXGrid1.FixedFooterRows := 0;
end;
end;
procedure TForm719.CheckBox3Change(Sender: TObject);
begin
if checkbox3.IsChecked then
begin
TMSFMXGrid1.FreezeColumns := 2;
end
else
begin
TMSFMXGrid1.FreezeColumns := 0;
end;
end;
procedure TForm719.CheckBox4Change(Sender: TObject);
begin
if checkbox4.IsChecked then
begin
TMSFMXGrid1.FreezeRows := 2;
end
else
begin
TMSFMXGrid1.FreezeRows := 0;
end;
end;
procedure TForm719.FormCreate(Sender: TObject);
begin
InitGrid;
end;
procedure TForm719.InitGrid;
begin
TMSFMXGrid1.IOOffset := Point(1,1);
TMSFMXGrid1.ColumnCount := 50;
TMSFMXGrid1.RowCount := 115;
TMSFMXGrid1.LinearFill(false);
TMSFMXGrid1.LoadFromCSV('..\..\cars.csv');
TMSFMXGrid1.ColumnWidths[1] := 100;
TMSFMXGrid1.AutoNumberCol(0);
TMSFMXGrid1.SelectionMode := smCellRange;
TMSFMXGrid1.Cells[1,0] := 'Brand';
TMSFMXGrid1.Cells[2,0] := 'Type';
TMSFMXGrid1.Cells[3,0] := 'CC';
TMSFMXGrid1.Cells[4,0] := 'Hp';
TMSFMXGrid1.Cells[5,0] := 'Cyl';
TMSFMXGrid1.Cells[6,0] := 'Kw';
TMSFMXGrid1.Cells[7,0] := 'Price';
TMSFMXGrid1.Cells[8,0] := 'Country';
end;
procedure TForm719.RadioButton1Change(Sender: TObject);
begin
if radiobutton1.IsChecked then
TMSFMXGrid1.ScrollMode := smCellScrolling
else
TMSFMXGrid1.ScrollMode := smPixelScrolling;
end;
end.
|
unit DW.OSDevice.Posix;
{*******************************************************}
{ }
{ Kastri }
{ }
{ Delphi Worlds Cross-Platform Library }
{ }
{ Copyright 2020-2021 Dave Nottage under MIT license }
{ which is located in the root folder of this library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.Classes;
type
TPosixOSDevice = record
public
class procedure GetEnvironmentVars(const AVars: TStrings); static;
end;
implementation
uses
// Posix
Posix.Unistd, Posix.Dlfcn;
{ TPosixOSDevice }
class procedure TPosixOSDevice.GetEnvironmentVars(const AVars: TStrings);
var
LEnv: PMarshaledAString;
LVar: string;
begin
AVars.BeginUpdate;
try
AVars.Clear;
LEnv := environ;
while LEnv^ <> nil do
begin
LVar := string(PAnsiChar(LEnv^));
AVars.Add(LVar);
Inc(LEnv);
end;
finally
AVars.EndUpdate;
end;
end;
end.
|
unit uServicos;
interface
uses
System.SysUtils, Vcl.Dialogs;
type
TServicos = class
strict private
FValor1: Double;
FValor2: Double;
procedure SetValor1(const Value: Double);
procedure SetValor2(const Value: Double);
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
function Somar:Double;
function Dividir:Double;
property Valor1 : Double read FValor1 write SetValor1;
property Valor2 : Double read FValor2 write SetValor2;
end;
implementation
{ TServicos }
function TServicos.Dividir: Double;
begin
Result := 0;
try
Result := (FValor1 / FValor2);
except
on e: EZeroDivide do
Showmessage('Divisão por Zero');
end;
end;
procedure TServicos.SetValor1(const Value: Double);
begin
FValor1 := Value;
end;
procedure TServicos.SetValor2(const Value: Double);
begin
FValor2 := Value;
end;
function TServicos.Somar: Double;
begin
REsult := FValor1 + FValor2;
end;
end.
|
unit ddTableRow;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "dd"
// Модуль: "w:/common/components/rtl/Garant/dd/ddTableRow.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::dd::ddCommon::TddTableRow
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
uses
ddBase,
ddDocumentAtom,
ddTableCell,
ddCellList,
ddCellsPropertyList,
ddRowProperty,
Classes,
ddCustomDestination,
k2Interfaces
;
type
TddTableRow = class(TddDocumentAtom)
private
// private fields
f_CellList : TddCellList;
f_CellProps : TddCellsPropertyList;
f_TAP : TddRowProperty;
{* Поле для свойства TAP}
f_RTFLikeWidth : Boolean;
{* Поле для свойства RTFLikeWidth}
f_CellPropsCompleate : Boolean;
{* Поле для свойства CellPropsCompleate}
private
// private methods
procedure DoApplyCellProps(aCellProps: TddCellsPropertyList);
protected
// property methods
procedure pm_SetTAP(aValue: TddRowProperty);
function pm_GetLastCell: TddTableCell;
function pm_GetLastCellProperty: TddCellProperty; virtual;
function pm_GetCellWidthBySpan(anIndex: Integer): Integer;
function pm_GetCellCountBySpan: Integer;
function pm_GetCellWidth(anIndex: Integer): Integer;
procedure pm_SetCellWidth(anIndex: Integer; aValue: Integer);
function pm_GetCellSpan(anIndex: Integer): Integer;
function pm_GetCellCount: Integer;
function pm_GetCells(anIndex: Integer): TddTableCell;
function pm_GetCellPropBySpan(anIndex: Integer): TddCellProperty;
function pm_GetCellPropByPos(aPos: Integer): TddCellProperty;
function pm_GetCellByPos(aPos: Integer): TddTableCell; virtual;
protected
// realized methods
procedure Write2Generator(const Generator: Ik2TagGenerator;
aNeedProcessRow: Boolean;
LiteVersion: Boolean); override;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure DoClose; override;
public
// overridden public methods
procedure Assign(Source: TPersistent); override;
procedure Clear; override;
constructor Create(anOwner: TObject;
aDetination: TddCustomDestination); override;
public
// public methods
procedure AddCell(aCell: TddTableCell);
procedure AddCellAndPara(const OnlyCell: Boolean = False);
procedure AddEmptyCell;
procedure AddCellProp(aCellProps: TddCellProperty);
procedure ApplyCellProps;
function CellIndexBySpan(anIndex: Integer): Integer;
procedure ClearCellProps;
procedure DeleteCell(anIndex: Integer);
function GetLastNonClosedCell: TddTableCell;
procedure CloneCell(aCellProp: TddCellProperty);
function GetLastNonClosedCellOrAddNew: TddTableCell;
{* Проверяет не закрыта ли предыдущая ячейка, а если закрыта открывает новую. }
function IsCellPropsInit: Boolean;
procedure ApplyExternalCellPropsDef(aRow: TddTableRow);
public
// public properties
property TAP: TddRowProperty
read f_TAP
write pm_SetTAP;
property RTFLikeWidth: Boolean
read f_RTFLikeWidth
write f_RTFLikeWidth;
property LastCell: TddTableCell
read pm_GetLastCell;
property LastCellProperty: TddCellProperty
read pm_GetLastCellProperty;
property CellWidthBySpan[anIndex: Integer]: Integer
read pm_GetCellWidthBySpan;
property CellCountBySpan: Integer
read pm_GetCellCountBySpan;
property CellWidth[anIndex: Integer]: Integer
read pm_GetCellWidth
write pm_SetCellWidth;
property CellSpan[anIndex: Integer]: Integer
read pm_GetCellSpan;
property CellCount: Integer
read pm_GetCellCount;
property Cells[anIndex: Integer]: TddTableCell
read pm_GetCells;
default;
property CellPropBySpan[anIndex: Integer]: TddCellProperty
read pm_GetCellPropBySpan;
property CellPropByPos[aPos: Integer]: TddCellProperty
read pm_GetCellPropByPos;
property CellByPos[aPos: Integer]: TddTableCell
read pm_GetCellByPos;
property CellPropsCompleate: Boolean
read f_CellPropsCompleate
write f_CellPropsCompleate;
end;//TddTableRow
implementation
uses
SysUtils,
k2Tags,
evdTypes,
l3Math,
RTFtypes,
evdFrame_Const,
ddTable,
l3Const,
ddTextParagraph,
Math
;
// start class TddTableRow
procedure TddTableRow.DoApplyCellProps(aCellProps: TddCellsPropertyList);
//#UC START# *51E657D90184_4FACE1370377_var*
var
i : Integer;
l_Cell : TddTableCell;
//#UC END# *51E657D90184_4FACE1370377_var*
begin
//#UC START# *51E657D90184_4FACE1370377_impl*
for i := 0 to aCellProps.Hi do
begin
l_Cell := Cells[i];
if l_Cell = nil then Break;
l_Cell.Props := aCellProps[i];
end; // for i := 0 to aCellProps.Hi do
//#UC END# *51E657D90184_4FACE1370377_impl*
end;//TddTableRow.DoApplyCellProps
procedure TddTableRow.AddCell(aCell: TddTableCell);
//#UC START# *518A4EF70329_4FACE1370377_var*
//#UC END# *518A4EF70329_4FACE1370377_var*
begin
//#UC START# *518A4EF70329_4FACE1370377_impl*
aCell.anIndex := f_CellList.Add(aCell);
//#UC END# *518A4EF70329_4FACE1370377_impl*
end;//TddTableRow.AddCell
procedure TddTableRow.AddCellAndPara(const OnlyCell: Boolean = False);
//#UC START# *518A4F30003C_4FACE1370377_var*
var
l_Cell : TddTableCell;
l_Property : TddTextParagraph;
//#UC END# *518A4F30003C_4FACE1370377_var*
begin
//#UC START# *518A4F30003C_4FACE1370377_impl*
l_Cell := TddTableCell.Create(Self, f_Destination);
try
// Нужно ли добавить абзац
if not OnlyCell then
begin
l_Property := TddTextParagraph.Create(l_Cell, f_Destination);
try
l_Property.PAP.InTable := True;
l_Cell.Add(l_Property);
finally
FreeAndNil(l_Property);
end;
end; // not OnlyCell
AddCell(l_Cell);
finally
FreeAndNil(l_Cell);
end;
//#UC END# *518A4F30003C_4FACE1370377_impl*
end;//TddTableRow.AddCellAndPara
procedure TddTableRow.AddEmptyCell;
//#UC START# *518A4F52010F_4FACE1370377_var*
var
l_Cell: TddTableCell;
//#UC END# *518A4F52010F_4FACE1370377_var*
begin
//#UC START# *518A4F52010F_4FACE1370377_impl*
l_Cell := TddTableCell.Create(Self, f_Destination);
try
AddCell(l_Cell);
finally
FreeAndNil(l_Cell);
end;
//#UC END# *518A4F52010F_4FACE1370377_impl*
end;//TddTableRow.AddEmptyCell
procedure TddTableRow.AddCellProp(aCellProps: TddCellProperty);
//#UC START# *518A4F870014_4FACE1370377_var*
var
l_Cell: TddCellProperty;
//#UC END# *518A4F870014_4FACE1370377_var*
begin
//#UC START# *518A4F870014_4FACE1370377_impl*
if f_CellPropsCompleate then
ClearCellProps;
l_Cell:= TddCellProperty.Create(nil);
try
l_Cell.Assign(aCellProps);
f_CellProps.Add(l_Cell);
finally
FreeAndNil(l_Cell);
end;
//#UC END# *518A4F870014_4FACE1370377_impl*
end;//TddTableRow.AddCellProp
procedure TddTableRow.ApplyCellProps;
//#UC START# *518A4FB1034A_4FACE1370377_var*
//#UC END# *518A4FB1034A_4FACE1370377_var*
begin
//#UC START# *518A4FB1034A_4FACE1370377_impl*
DoApplyCellProps(f_CellProps);
//#UC END# *518A4FB1034A_4FACE1370377_impl*
end;//TddTableRow.ApplyCellProps
function TddTableRow.CellIndexBySpan(anIndex: Integer): Integer;
//#UC START# *518A4FCE02FC_4FACE1370377_var*
var
l_SpanIndex: Integer;
l_CellIndex: Integer;
i, j: Integer;
//#UC END# *518A4FCE02FC_4FACE1370377_var*
begin
//#UC START# *518A4FCE02FC_4FACE1370377_impl*
l_SpanIndex:= -1;
l_CellIndex:= 0;
Result:= -1;
for l_CellIndex:= 0 to Pred(CellCount) do
begin
for j:= 1 to CellSpan[l_CellIndex] do
begin
Inc(l_SpanIndex);
if l_SpanIndex = anIndex then
begin
Result := l_CellIndex;
Break;
end;
end;
end; // while
if Result = -1 then
begin
l_SpanIndex:= -1;
l_CellIndex:= 0;
Result:= -1;
for l_CellIndex := 0 to Pred(CellCount) do
for j := 1 to CellSpan[l_CellIndex] do
begin
Inc(l_SpanIndex);
if l_SpanIndex = anIndex then
begin
Result := l_CellIndex;
Break;
end;
end;
end;
//#UC END# *518A4FCE02FC_4FACE1370377_impl*
end;//TddTableRow.CellIndexBySpan
procedure TddTableRow.ClearCellProps;
//#UC START# *518A4FF703E6_4FACE1370377_var*
//#UC END# *518A4FF703E6_4FACE1370377_var*
begin
//#UC START# *518A4FF703E6_4FACE1370377_impl*
f_CellProps.Clear;
f_CellPropsCompleate := False;
//#UC END# *518A4FF703E6_4FACE1370377_impl*
end;//TddTableRow.ClearCellProps
procedure TddTableRow.DeleteCell(anIndex: Integer);
//#UC START# *518A501003AE_4FACE1370377_var*
var
l_CP: TddCellProperty;
//#UC END# *518A501003AE_4FACE1370377_var*
begin
//#UC START# *518A501003AE_4FACE1370377_impl*
l_CP:= Cells[anIndex].Props;
if (l_CP <> nil) and (CellCount > 1) then
begin
if anIndex > 0 then
begin
Cells[anIndex].Props.Border.Frames[bpLeft].Assign(Cells[anIndex-1].Props.Border.Frames[bpLeft]);
Cells[anIndex-1].Props.Assign(Cells[anIndex].Props);
end // if anIndex > 0 then
else
Cells[anIndex + 1].Props.Border.Frames[bpLeft].Assign(Cells[anIndex].Props.Border.Frames[bpLeft]);
f_CellList.Delete(anIndex);
end;
//#UC END# *518A501003AE_4FACE1370377_impl*
end;//TddTableRow.DeleteCell
function TddTableRow.GetLastNonClosedCell: TddTableCell;
//#UC START# *51960AF50141_4FACE1370377_var*
//#UC END# *51960AF50141_4FACE1370377_var*
begin
//#UC START# *51960AF50141_4FACE1370377_impl*
Result := pm_GetLastCell;
if (Result <> nil) and Result.Closed then
Result := nil;
//#UC END# *51960AF50141_4FACE1370377_impl*
end;//TddTableRow.GetLastNonClosedCell
procedure TddTableRow.CloneCell(aCellProp: TddCellProperty);
//#UC START# *519C8B33037C_4FACE1370377_var*
//#UC END# *519C8B33037C_4FACE1370377_var*
begin
//#UC START# *519C8B33037C_4FACE1370377_impl*
AddCellAndPara;
LastCellProperty.RowSpan:= Pred(aCellProp.RowSpan);
LastCellProperty.CellSpan:= aCellProp.CellSpan;
LastCellProperty.Width:= aCellProp.Width;
// Нельзя так присваивать рамки!
LastCellProperty.Border.Assign(aCellProp.Border);
LastCellProperty.VMerged:= True;
//#UC END# *519C8B33037C_4FACE1370377_impl*
end;//TddTableRow.CloneCell
function TddTableRow.GetLastNonClosedCellOrAddNew: TddTableCell;
//#UC START# *519C95060331_4FACE1370377_var*
//#UC END# *519C95060331_4FACE1370377_var*
begin
//#UC START# *519C95060331_4FACE1370377_impl*
Result := LastCell;
if Result.Closed then
begin
AddCellAndPara(True);
Result := LastCell;
end; //if l_OutCell.Closed then
//#UC END# *519C95060331_4FACE1370377_impl*
end;//TddTableRow.GetLastNonClosedCellOrAddNew
function TddTableRow.IsCellPropsInit: Boolean;
//#UC START# *51E64E830070_4FACE1370377_var*
//#UC END# *51E64E830070_4FACE1370377_var*
begin
//#UC START# *51E64E830070_4FACE1370377_impl*
Result := f_CellProps.Count > 0;
//#UC END# *51E64E830070_4FACE1370377_impl*
end;//TddTableRow.IsCellPropsInit
procedure TddTableRow.ApplyExternalCellPropsDef(aRow: TddTableRow);
//#UC START# *51E64F4B039E_4FACE1370377_var*
//#UC END# *51E64F4B039E_4FACE1370377_var*
begin
//#UC START# *51E64F4B039E_4FACE1370377_impl*
DoApplyCellProps(aRow.f_CellProps);
//#UC END# *51E64F4B039E_4FACE1370377_impl*
end;//TddTableRow.ApplyExternalCellPropsDef
procedure TddTableRow.pm_SetTAP(aValue: TddRowProperty);
//#UC START# *518A479603CD_4FACE1370377set_var*
//#UC END# *518A479603CD_4FACE1370377set_var*
begin
//#UC START# *518A479603CD_4FACE1370377set_impl*
f_TAP.Assign(aValue);
//#UC END# *518A479603CD_4FACE1370377set_impl*
end;//TddTableRow.pm_SetTAP
function TddTableRow.pm_GetLastCell: TddTableCell;
//#UC START# *518A4B370328_4FACE1370377get_var*
//#UC END# *518A4B370328_4FACE1370377get_var*
begin
//#UC START# *518A4B370328_4FACE1370377get_impl*
if f_CellList.Count = 0 then
Result:= nil //AddCellAndPara;
else
Result := f_CellList.Last;
//#UC END# *518A4B370328_4FACE1370377get_impl*
end;//TddTableRow.pm_GetLastCell
function TddTableRow.pm_GetLastCellProperty: TddCellProperty;
//#UC START# *518A4B72006B_4FACE1370377get_var*
//#UC END# *518A4B72006B_4FACE1370377get_var*
begin
//#UC START# *518A4B72006B_4FACE1370377get_impl*
if LastCell = nil then
AddCellAndPara;
Result:= LastCell.Props;
//#UC END# *518A4B72006B_4FACE1370377get_impl*
end;//TddTableRow.pm_GetLastCellProperty
function TddTableRow.pm_GetCellWidthBySpan(anIndex: Integer): Integer;
//#UC START# *518A4BB402CE_4FACE1370377get_var*
var
l_CellIndex: Integer;
//#UC END# *518A4BB402CE_4FACE1370377get_var*
begin
//#UC START# *518A4BB402CE_4FACE1370377get_impl*
Result := 0;
l_CellIndex := CellIndexBySpan(anIndex);
if l_CellIndex > -1 then
Result := CellWidth[l_CellIndex] div CellSpan[l_CellIndex];
//#UC END# *518A4BB402CE_4FACE1370377get_impl*
end;//TddTableRow.pm_GetCellWidthBySpan
function TddTableRow.pm_GetCellCountBySpan: Integer;
//#UC START# *518A4C320198_4FACE1370377get_var*
var
i: Integer;
//#UC END# *518A4C320198_4FACE1370377get_var*
begin
//#UC START# *518A4C320198_4FACE1370377get_impl*
Result := 0;
for i := 0 to CellCount - 1 do
Inc(Result, CellSpan[i]);
//#UC END# *518A4C320198_4FACE1370377get_impl*
end;//TddTableRow.pm_GetCellCountBySpan
function TddTableRow.pm_GetCellWidth(anIndex: Integer): Integer;
//#UC START# *518A4C67024C_4FACE1370377get_var*
//#UC END# *518A4C67024C_4FACE1370377get_var*
begin
//#UC START# *518A4C67024C_4FACE1370377get_impl*
Result := Cells[anIndex].Props.Width;
//#UC END# *518A4C67024C_4FACE1370377get_impl*
end;//TddTableRow.pm_GetCellWidth
procedure TddTableRow.pm_SetCellWidth(anIndex: Integer; aValue: Integer);
//#UC START# *518A4C67024C_4FACE1370377set_var*
//#UC END# *518A4C67024C_4FACE1370377set_var*
begin
//#UC START# *518A4C67024C_4FACE1370377set_impl*
Cells[anIndex].Props.Width:= aValue;
//#UC END# *518A4C67024C_4FACE1370377set_impl*
end;//TddTableRow.pm_SetCellWidth
function TddTableRow.pm_GetCellSpan(anIndex: Integer): Integer;
//#UC START# *518A4CA40030_4FACE1370377get_var*
//#UC END# *518A4CA40030_4FACE1370377get_var*
begin
//#UC START# *518A4CA40030_4FACE1370377get_impl*
Result := Cells[anIndex].Props.CellSpan;
//#UC END# *518A4CA40030_4FACE1370377get_impl*
end;//TddTableRow.pm_GetCellSpan
function TddTableRow.pm_GetCellCount: Integer;
//#UC START# *518A4CFA00C4_4FACE1370377get_var*
//#UC END# *518A4CFA00C4_4FACE1370377get_var*
begin
//#UC START# *518A4CFA00C4_4FACE1370377get_impl*
if (Self <> nil) AND (f_CellList <> nil) then
Result:= f_CellList.Count
else
Result:= 0;
//#UC END# *518A4CFA00C4_4FACE1370377get_impl*
end;//TddTableRow.pm_GetCellCount
function TddTableRow.pm_GetCells(anIndex: Integer): TddTableCell;
//#UC START# *518A4D6A039D_4FACE1370377get_var*
//#UC END# *518A4D6A039D_4FACE1370377get_var*
begin
//#UC START# *518A4D6A039D_4FACE1370377get_impl*
if (anIndex >= 0) and (anIndex < f_CellList.Count) then
Result := f_CellList.Items[anIndex]
else
Result := nil;
//#UC END# *518A4D6A039D_4FACE1370377get_impl*
end;//TddTableRow.pm_GetCells
function TddTableRow.pm_GetCellPropBySpan(anIndex: Integer): TddCellProperty;
//#UC START# *518A4DE0032A_4FACE1370377get_var*
var
l_CellIndex: Integer;
//#UC END# *518A4DE0032A_4FACE1370377get_var*
begin
//#UC START# *518A4DE0032A_4FACE1370377get_impl*
Result := nil;
l_CellIndex := CellIndexBySpan(anIndex);
if l_CellIndex > -1 then
Result := Cells[l_CellIndex].Props;
//#UC END# *518A4DE0032A_4FACE1370377get_impl*
end;//TddTableRow.pm_GetCellPropBySpan
function TddTableRow.pm_GetCellPropByPos(aPos: Integer): TddCellProperty;
//#UC START# *518A4E390255_4FACE1370377get_var*
var
i: Integer;
W, Delta: LongInt;
//#UC END# *518A4E390255_4FACE1370377get_var*
begin
//#UC START# *518A4E390255_4FACE1370377get_impl*
W := 0;
Result := nil;
for i:= 0 to f_CellList.Hi do
begin
if (i > 0) and RTFLikeWidth then
Delta:= Cells[i].Props.Width-Cells[Pred(i)].Props.Width
else
Delta:= Cells[i].Props.Width;
if (aPos > W) and (aPos <= (W+ l3MulDiv(Delta, 105, 100))) then
begin
Result:= Cells[i].Props;
Result.Index:= i;
Break;
end
else
Inc(W, Delta);
end;
//#UC END# *518A4E390255_4FACE1370377get_impl*
end;//TddTableRow.pm_GetCellPropByPos
function TddTableRow.pm_GetCellByPos(aPos: Integer): TddTableCell;
//#UC START# *5190964701FB_4FACE1370377get_var*
var
i: Integer;
Delta: LongInt;
//#UC END# *5190964701FB_4FACE1370377get_var*
begin
//#UC START# *5190964701FB_4FACE1370377get_impl*
Result := nil;
for i := 0 to f_CellList.Hi do
begin
if i > 0 then
Delta := Cells[Pred(i)].Props.Width
else
Delta := 0;
if InRange(aPos, Delta, Cells[i].Props.Width) then
begin
Result := Cells[i];
Break;
end; // InRange
end; // for i
//#UC END# *5190964701FB_4FACE1370377get_impl*
end;//TddTableRow.pm_GetCellByPos
procedure TddTableRow.Write2Generator(const Generator: Ik2TagGenerator;
aNeedProcessRow: Boolean;
LiteVersion: Boolean);
//#UC START# *518A504F00F5_4FACE1370377_var*
var
i : Integer;
j : Integer;
l_Cell : TddTableCell;
l_Item : TddDocumentAtom;
l_Delta : Integer;
l_Width : Integer;
//#UC END# *518A504F00F5_4FACE1370377_var*
begin
//#UC START# *518A504F00F5_4FACE1370377_impl*
Generator.StartDefaultChild;
try
if not LiteVersion then
TAP.Border.Write2Generator(Generator);
for i := 0 to f_CellList.Hi do
begin
l_Cell := Cells[i];
Generator.StartDefaultChild;
try
if l_Cell.Props.VMergeFirst then
Generator.AddIntegerAtom(k2_tiMergeStatus, Ord(ev_msHead))
else
if l_Cell.Props.VMerged then
Generator.AddIntegerAtom(k2_tiMergeStatus, Ord(ev_msContinue));
if not LiteVersion then
if l_Cell.Props.PatternBackColor <> propUndefined then
Generator.AddIntegerAtom(k2_tiBackColor, l_Cell.Props.PatternBackColor);
if (i > 0) then
l_Delta := CellWidth[Pred(i)]
else
l_Delta := TAP.Left;
l_Width := l_Cell.Props.Width - l_Delta;
Generator.AddIntegerAtom(k2_tiWidth, l_Width);
if not LiteVersion then
begin
Generator.AddIntegerAtom(k2_tiLeftIndent, l_Cell.Props.LeftPad);
Generator.AddIntegerAtom(k2_tiRightIndent, l_Cell.Props.RightPad);
Generator.AddIntegerAtom(k2_tiSpaceBefore, l_Cell.Props.TopPad);
Generator.AddIntegerAtom(k2_tiSpaceAfter, l_Cell.Props.BottomPad);
end;
if l_Cell.Props.Border.IsFramed then
l_Cell.Props.Border.Write2Generator(Generator)
else
Generator.AddIntegerAtom(k2_tiFrame, evd_fvEmpty);
Generator.AddIntegerAtom(k2_tiVerticalAligment, Ord(l_Cell.Props.Just));
if not l_Cell.Props.VMerged then
begin
if l_Cell.Count = 0 then
l_Cell.AddParagraph;
for j := 0 to l_Cell.Hi do
begin
l_Item := l_Cell.Items[j];
if (l_Item.AtomType = dd_docTable) then
TddTable(l_Item).AdjustWidth(l_Width - l_Cell.Props.LeftPad - l_Cell.Props.RightPad);
l_Item.Write2Generator(Generator, aNeedProcessRow, LiteVersion);
end; // for j:= 0 to l_Cell.Hi do
end;
finally
Generator.Finish;
end;
end; {for i}
finally
Generator.Finish;
end;
//#UC END# *518A504F00F5_4FACE1370377_impl*
end;//TddTableRow.Write2Generator
procedure TddTableRow.Assign(Source: TPersistent);
//#UC START# *478CF34E02CE_4FACE1370377_var*
var
i: Integer;
l_Cell: TddtableCell;
//#UC END# *478CF34E02CE_4FACE1370377_var*
begin
//#UC START# *478CF34E02CE_4FACE1370377_impl*
if (Source Is TddTableRow) then
begin
f_TAP.Assign(TddTableRow(Source).TAP);
for i:= 0 to TddTableRow(Source).f_CellList.Hi do
begin
l_Cell:= TddTableCell.Create(Self, f_Destination);
try
l_Cell.Assign(TddTableRow(Source)[i]);
l_Cell.Clear;
f_CellList.Add(l_Cell);
finally
FreeAndNil(l_Cell)
end;
end;
end
else
inherited Assign(Source);
//#UC END# *478CF34E02CE_4FACE1370377_impl*
end;//TddTableRow.Assign
procedure TddTableRow.Cleanup;
//#UC START# *479731C50290_4FACE1370377_var*
//#UC END# *479731C50290_4FACE1370377_var*
begin
//#UC START# *479731C50290_4FACE1370377_impl*
FreeAndNil(f_CellProps);
FreeAndNil(f_CellList);
FreeAndNil(f_TAP);
f_CellPropsCompleate := False;
inherited;
//#UC END# *479731C50290_4FACE1370377_impl*
end;//TddTableRow.Cleanup
procedure TddTableRow.Clear;
//#UC START# *518A48F500CF_4FACE1370377_var*
var
i: Integer;
//#UC END# *518A48F500CF_4FACE1370377_var*
begin
//#UC START# *518A48F500CF_4FACE1370377_impl*
inherited;
f_TAP.Clear;
ClearCellProps;
//f_CellList.Clear;
//#UC END# *518A48F500CF_4FACE1370377_impl*
end;//TddTableRow.Clear
procedure TddTableRow.DoClose;
//#UC START# *518A4950037A_4FACE1370377_var*
var
i: Integer;
//#UC END# *518A4950037A_4FACE1370377_var*
begin
//#UC START# *518A4950037A_4FACE1370377_impl*
for i:= 0 to Pred(CellCount) do
Cells[i].Closed:= True;
//#UC END# *518A4950037A_4FACE1370377_impl*
end;//TddTableRow.DoClose
constructor TddTableRow.Create(anOwner: TObject;
aDetination: TddCustomDestination);
//#UC START# *51E91BA80051_4FACE1370377_var*
//#UC END# *51E91BA80051_4FACE1370377_var*
begin
//#UC START# *51E91BA80051_4FACE1370377_impl*
inherited Create(anOwner, aDetination);
AtomType:= dd_docTableRow;
f_CellPropsCompleate := False;
f_CellList := TddCellList.Make;
f_TAP:= TddRowProperty.Create(nil);
f_RTFLikeWidth := False;
f_CellProps := TddCellsPropertyList.Make;
//#UC END# *51E91BA80051_4FACE1370377_impl*
end;//TddTableRow.Create
end. |
unit TasksPanelKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы TasksPanel }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Common\TasksPanelKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "TasksPanelKeywordsPack" MUID: (7508C2F22B0F)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3IntfUses
{$If Defined(Nemesis)}
, nscTasksPanelView
{$IfEnd} // Defined(Nemesis)
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TasksPanel_Form
, tfwControlString
{$If NOT Defined(NoVCL)}
, kwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
, tfwScriptingInterfaces
, tfwPropertyLike
, TypInfo
, tfwTypeInfo
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
;
type
Tkw_Form_TasksPanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы TasksPanel
----
*Пример использования*:
[code]
'aControl' форма::TasksPanel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_TasksPanel
Tkw_TasksPanel_Control_tpvMain = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола tpvMain
----
*Пример использования*:
[code]
контрол::tpvMain TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_TasksPanel_Control_tpvMain
Tkw_TasksPanel_Control_tpvMain_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола tpvMain
----
*Пример использования*:
[code]
контрол::tpvMain:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_TasksPanel_Control_tpvMain_Push
TkwEnTasksPanelTpvMain = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_TasksPanel.tpvMain }
private
function tpvMain(const aCtx: TtfwContext;
aen_TasksPanel: Ten_TasksPanel): TnscTasksPanelView;
{* Реализация слова скрипта .Ten_TasksPanel.tpvMain }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnTasksPanelTpvMain
function Tkw_Form_TasksPanel.GetString: AnsiString;
begin
Result := 'en_TasksPanel';
end;//Tkw_Form_TasksPanel.GetString
class function Tkw_Form_TasksPanel.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::TasksPanel';
end;//Tkw_Form_TasksPanel.GetWordNameForRegister
function Tkw_TasksPanel_Control_tpvMain.GetString: AnsiString;
begin
Result := 'tpvMain';
end;//Tkw_TasksPanel_Control_tpvMain.GetString
class procedure Tkw_TasksPanel_Control_tpvMain.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTasksPanelView);
end;//Tkw_TasksPanel_Control_tpvMain.RegisterInEngine
class function Tkw_TasksPanel_Control_tpvMain.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::tpvMain';
end;//Tkw_TasksPanel_Control_tpvMain.GetWordNameForRegister
procedure Tkw_TasksPanel_Control_tpvMain_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('tpvMain');
inherited;
end;//Tkw_TasksPanel_Control_tpvMain_Push.DoDoIt
class function Tkw_TasksPanel_Control_tpvMain_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::tpvMain:push';
end;//Tkw_TasksPanel_Control_tpvMain_Push.GetWordNameForRegister
function TkwEnTasksPanelTpvMain.tpvMain(const aCtx: TtfwContext;
aen_TasksPanel: Ten_TasksPanel): TnscTasksPanelView;
{* Реализация слова скрипта .Ten_TasksPanel.tpvMain }
begin
Result := aen_TasksPanel.tpvMain;
end;//TkwEnTasksPanelTpvMain.tpvMain
class function TkwEnTasksPanelTpvMain.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_TasksPanel.tpvMain';
end;//TkwEnTasksPanelTpvMain.GetWordNameForRegister
function TkwEnTasksPanelTpvMain.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTasksPanelView);
end;//TkwEnTasksPanelTpvMain.GetResultTypeInfo
function TkwEnTasksPanelTpvMain.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnTasksPanelTpvMain.GetAllParamsCount
function TkwEnTasksPanelTpvMain.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_TasksPanel)]);
end;//TkwEnTasksPanelTpvMain.ParamsTypes
procedure TkwEnTasksPanelTpvMain.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству tpvMain', aCtx);
end;//TkwEnTasksPanelTpvMain.SetValuePrim
procedure TkwEnTasksPanelTpvMain.DoDoIt(const aCtx: TtfwContext);
var l_aen_TasksPanel: Ten_TasksPanel;
begin
try
l_aen_TasksPanel := Ten_TasksPanel(aCtx.rEngine.PopObjAs(Ten_TasksPanel));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_TasksPanel: Ten_TasksPanel : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(tpvMain(aCtx, l_aen_TasksPanel));
end;//TkwEnTasksPanelTpvMain.DoDoIt
initialization
Tkw_Form_TasksPanel.RegisterInEngine;
{* Регистрация Tkw_Form_TasksPanel }
Tkw_TasksPanel_Control_tpvMain.RegisterInEngine;
{* Регистрация Tkw_TasksPanel_Control_tpvMain }
Tkw_TasksPanel_Control_tpvMain_Push.RegisterInEngine;
{* Регистрация Tkw_TasksPanel_Control_tpvMain_Push }
TkwEnTasksPanelTpvMain.RegisterInEngine;
{* Регистрация en_TasksPanel_tpvMain }
TtfwTypeRegistrator.RegisterType(TypeInfo(Ten_TasksPanel));
{* Регистрация типа Ten_TasksPanel }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTasksPanelView));
{* Регистрация типа TnscTasksPanelView }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
end.
|
Program MTYPE;
// ====================================================================
// Mystic BBS Software Copyright 1997-2013 By James Coyle
// ====================================================================
//
// This file is part of Mystic BBS.
//
// Mystic BBS 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 3 of the License, or
// (at your option) any later version.
//
// Mystic BBS 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 Mystic BBS. If not, see <http://www.gnu.org/licenses/>.
//
// ====================================================================
{$I M_OPS.PAS}
// Add screen pause option
// Add delay option similar to Mystic
// Processing formatting MCI codes, etc
Uses
f_Output,
f_Strings,
m_DateTime,
m_Term_Ansi;
Var
Screen : TOutput;
Terminal : TTermAnsi;
Buffer : Array[1..4096] of Char;
dFile : File;
Ext : String[4];
Code : String[2];
dRead : LongInt;
Old : Boolean;
Str : String;
A : Word;
Ch : Char;
Done : Boolean;
Function GetChar : Char;
Begin
If A = dRead Then Begin
BlockRead (dFile, Buffer, SizeOf(Buffer), dRead);
A := 0;
If dRead = 0 Then Begin
Done := True;
Buffer[1] := #26;
End;
End;
Inc (A);
GetChar := Buffer[A];
End;
Function Ansi_Color (B : Byte) : String;
Var
S : String;
Begin
S := '';
Ansi_Color := '';
Case B of
00: S := #27 + '[0;30m';
01: S := #27 + '[0;34m';
02: S := #27 + '[0;32m';
03: S := #27 + '[0;36m';
04: S := #27 + '[0;31m';
05: S := #27 + '[0;35m';
06: S := #27 + '[0;33m';
07: S := #27 + '[0;37m';
08: S := #27 + '[1;30m';
09: S := #27 + '[1;34m';
10: S := #27 + '[1;32m';
11: S := #27 + '[1;36m';
12: S := #27 + '[1;31m';
13: S := #27 + '[1;35m';
14: S := #27 + '[1;33m';
15: S := #27 + '[1;37m';
End;
If B in [00..07] Then B := (Screen.TextAttr SHR 4) and 7 + 16;
Case B of
16: S := S + #27 + '[40m';
17: S := S + #27 + '[44m';
18: S := S + #27 + '[42m';
19: S := S + #27 + '[46m';
20: S := S + #27 + '[41m';
21: S := S + #27 + '[45m';
22: S := S + #27 + '[43m';
23: S := S + #27 + '[47m';
End;
Ansi_Color := S;
End;
Procedure OutStr (S: String);
Begin
Terminal.ProcessBuf(S[1], Length(S));
End;
Var
BaudEmu : LongInt;
Begin
WriteLn;
If ParamCount < 1 Then Begin
WriteLn('MTYPE [filename] [delay]');
Exit;
End;
Assign (dFile, ParamStr(1));
Reset (dFile, 1);
If IoResult <> 0 Then Begin
WriteLn('MTYPE: File ' + ParamStr(1) + ' not found.');
Exit;
End;
Screen := TOutput.Create(True);
Terminal := TTermAnsi.Create(Screen);
BaudEmu := strS2I(ParamStr(2));
Done := False;
A := 0;
dRead := 0;
Ch := #0;
While Not Done Do Begin
Ch := GetChar;
If BaudEmu > 0 Then Begin
Screen.BufFlush;
If A MOD BaudEmu = 0 Then WaitMS(6);
End;
WaitMS(BaudEmu);
If Ch = #26 Then
Break
Else
If Ch = #10 Then Begin
Terminal.Process(#10);
End Else
If Ch = '|' Then Begin
Code := GetChar;
Code := Code + GetChar;
If Code = '00' Then OutStr(Ansi_Color(0)) Else
If Code = '01' Then OutStr(Ansi_Color(1)) Else
If Code = '02' Then OutStr(Ansi_Color(2)) Else
If Code = '03' Then OutStr(Ansi_Color(3)) Else
If Code = '04' Then OutStr(Ansi_Color(4)) Else
If Code = '05' Then OutStr(Ansi_Color(5)) Else
If Code = '06' Then OutStr(Ansi_Color(6)) Else
If Code = '07' Then OutStr(Ansi_Color(7)) Else
If Code = '08' Then OutStr(Ansi_Color(8)) Else
If Code = '09' Then OutStr(Ansi_Color(9)) Else
If Code = '10' Then OutStr(Ansi_Color(10)) Else
If Code = '11' Then OutStr(Ansi_Color(11)) Else
If Code = '12' Then OutStr(Ansi_Color(12)) Else
If Code = '13' Then OutStr(Ansi_Color(13)) Else
If Code = '14' Then OutStr(Ansi_Color(14)) Else
If Code = '15' Then OutStr(Ansi_Color(15)) Else
If Code = '16' Then OutStr(Ansi_Color(16)) Else
If Code = '17' Then OutStr(Ansi_Color(17)) Else
If Code = '18' Then OutStr(Ansi_Color(18)) Else
If Code = '19' Then OutStr(Ansi_Color(19)) Else
If Code = '20' Then OutStr(Ansi_Color(20)) Else
If Code = '21' Then OutStr(Ansi_Color(21)) Else
If Code = '22' Then OutStr(Ansi_Color(22)) Else
If Code = '23' Then OutStr(Ansi_Color(23)) Else
Begin
Terminal.Process('|');
Dec (A, 2);
Continue;
End;
End Else
Terminal.Process(Ch);
End;
Close (dFile);
Terminal.Free;
Screen.Free;
End.
|
{$I tdl_dire.inc}
unit tdl_audi;
{
Auditing routines for tracking user activity
}
interface
uses
DOS,
objects,
tdl_glob,
tdl_conf;
type
PAuditRec=^TAuditRec;
TAuditRec=record
titleID:word;
titleHash:MD5hash;
startTime,
endTime:DateTime;
minsActive:word;
end;
PAuditLog=^TAuditLog;
TAuditLog=object(TObject)
PUBLIC
Entry:TAuditRec;
totalEntries:word;
{Creates new audit log if absent or empty, opens existing log if present}
Constructor Init(auditLogPath:PathStr);
Destructor Done; VIRTUAL;
{Creates new entry using system time}
function newEntry(tID:word):boolean;
{Functions for seeking/iterating through all audit log entries.
Data returned via this object's .Entry public variable.}
function getFirst:boolean;
function getNext:boolean;
function getLast:boolean;
{Records return from launched program}
function closeEntry:boolean;
PRIVATE
curEntry:word;
fpath:string;
aStream:PDOSStream;
end;
var
auditLog:PAuditLog;
implementation
uses
support,
tdl_inde;
Constructor TAuditLog.Init;
var
l:longint;
begin
if not Inherited Init then fail;
if config=nil then fail;
fpath:=auditLogPath;
{register index as a stream on disk}
if fileExists(fpath)
then aStream:=new(pDOSStream,init(fpath,stOpen))
else aStream:=new(pDOSStream,init(fpath,stCreate));
{$IFDEF DEBUG}
if aStream^.status<>stOK then stCheck(data);
{$ENDIF}
totalEntries:=aStream^.getsize div sizeof(TAuditRec);
end;
Destructor TAuditLog.Done;
begin
dispose(aStream,done);
Inherited Done;
end;
procedure grabTime(var tempDateTime:DateTime);
var
y,mo,d,dow,h,mi,s,s100:word;
begin
getdate(y,mo,d,dow);
gettime(h,mi,s,s100);
with tempDateTime do begin
year:=y;
month:=mo;
day:=d;
hour:=h;
min:=mi;
sec:=s;
end;
end;
Function TAuditLog.newEntry(tID:word):boolean;
var
tmpEntry:TAuditRec;
tDT:DateTime;
ttbuf:PTitleStruct;
begin
{prepare an audit log entry}
fillchar(tmpEntry,sizeof(tmpEntry),0);
grabTime(tDT);
with tmpEntry do begin
titleID:=tID;
startTime:=tDT;
endTime:=startTime;
titles^.retrieve(tID,ttbuf);
titleHash:=ttbuf^.hash
end;
{seek to the end}
aStream^.seek(aStream^.getsize);
aStream^.write(tmpEntry,sizeof(tmpEntry));
newEntry:=(aStream^.status=stOK);
end;
{Functions for seeking/iterating through all audit log entries.
Data returned via this object's .Entry public variable.}
Function TAuditLog.getFirst:boolean;
begin
aStream^.seek(0);
aStream^.read(Entry,sizeof(Entry));
getFirst:=(aStream^.status=stOK);
end;
Function TAuditLog.getNext:boolean;
begin
aStream^.read(Entry,sizeof(Entry));
getNext:=(aStream^.status=stOK);
end;
Function TAuditLog.getLast:boolean;
begin
aStream^.seek(aStream^.getsize-sizeof(Entry));
aStream^.read(Entry,sizeof(Entry));
getLast:=(aStream^.status=stOK);
end;
{Records return from launched program}
Function TAuditLog.closeEntry;
var
tDT:DateTime;
begin
getLast;
grabTime(tDT);
entry.endTime:=tDT;
Entry.minsActive:=0; {this will be populated later by a call to a monitoring TSR}
{seek to the beginning of the last entry}
aStream^.seek(aStream^.getsize-sizeof(Entry));
{update the last entry}
aStream^.write(Entry,sizeof(Entry));
totalEntries:=aStream^.getsize div sizeof(TAuditRec);
closeEntry:=(aStream^.status=stOK);
end;
end.
|
program parcial;
const
dimF = 16;
dimC = 7300;
type
rangoCod = 1..16;
str40 = String[40];
plan = record
codigoPlan : rangoCod;
costoTotal : Real;
cantSesiones : Integer;
end;
cliente = record // se dispone
nombre : str40;
dni : Integer;
ciudadOrigen : str40;
codigoPlan : rangoCod;
finalizo : Integer;
end;
lista = ^nodo;
nodo = record
datos : cliente;
sig : lista;
end;
vCliente = array[1..7300] of cliente; // se dispone
vPlanes = array[1..dimF] of plan;
vContador = array[1..dimF] of Integer;
procedure CargargarVectorClientes(var vc:vCliente); // se dispone
begin
end;
procedure agregarAdelante(var l:lista; c: cliente);
var
nue: lista;
begin
new(nue);
nue^.datos:= c;
nue^.sig:= l;
l:= nue;
end;
procedure leerPlan(var p:plan);
begin
with p do
begin
write('Ingrese CODIGO PLAN: ');
readln(codigoPlan);
write('Ingrese COSTO TOTAL: ');
readln(costoTotal);
write('Ingres CANT DE SECCIONES: ');
readln(cantSesiones);
writeln('-------------------------');
end;
end;
procedure cargarVectorPlanes(var vp: vPlanes);
var
i: Integer;
p: plan;
begin
for i := 1 to dimF do
begin
leerPlan(p);
vp[p.codigoPlan]:= p;
end;
end;
procedure calcularGanancias(vcont: vContador; vp: vPlanes; var sumaTotal: Real);
var
i: Integer;
begin
for i := 1 to dimF do
begin
sumaTotal:= sumaTotal + (vcont[i] * vp[i].costoTotal);
end;
end;
function cumpleConcidicion(finalizo: Integer; cantSesiones: Integer): Boolean;
begin
cumpleConcidicion:= finalizo = cantSesiones;
end;
procedure procesarInfo(vc: vCliente; vp: vPlanes; var vcont: vContador; var l:lista);
var
i: Integer;
sumaTotal: Real;
begin
for i := 1 to dimC do
begin
vcont[vc[i].codigoPlan]:= vcont[vc[i].codigoPlan] + 1;
if (cumpleConcidicion(vc[i].finalizo, vp[vc[i].codigoPlan].cantSesiones)) then
agregarAdelante(l, vc[i]);
end;
calcularGanancias(vcont, vp, sumaTotal);
writeln('La ganancia TOTAL DEL CENTRO ES: ', sumaTotal);
end;
var
vp: vPlanes;
vc: vCliente;
vcont: vContador;
l: lista;
begin
l:= nil;
CargargarVectorClientes(vc);
cargarVectorPlanes(vp);
procesarInfo(vc,vp,vcont,l);
end. |
unit StyleEditorNavigatorKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы StyleEditorNavigator }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Settings\Forms\StyleEditorNavigatorKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "StyleEditorNavigatorKeywordsPack" MUID: (4ABA14480078_Pack)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, StyleEditorNavigator_Form
, tfwPropertyLike
, nscTreeViewWithAdapterDragDrop
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, tfwControlString
, kwBynameControlPush
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *4ABA14480078_Packimpl_uses*
//#UC END# *4ABA14480078_Packimpl_uses*
;
type
TkwStyleEditorNavigatorFormStyleTreeView = {final} class(TtfwPropertyLike)
{* Слово скрипта .TStyleEditorNavigatorForm.StyleTreeView }
private
function StyleTreeView(const aCtx: TtfwContext;
aStyleEditorNavigatorForm: TStyleEditorNavigatorForm): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TStyleEditorNavigatorForm.StyleTreeView }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwStyleEditorNavigatorFormStyleTreeView
Tkw_Form_StyleEditorNavigator = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы StyleEditorNavigator
----
*Пример использования*:
[code]форма::StyleEditorNavigator TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_StyleEditorNavigator
Tkw_StyleEditorNavigator_Control_StyleTreeView = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола StyleTreeView
----
*Пример использования*:
[code]контрол::StyleTreeView TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_StyleEditorNavigator_Control_StyleTreeView
Tkw_StyleEditorNavigator_Control_StyleTreeView_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола StyleTreeView
----
*Пример использования*:
[code]контрол::StyleTreeView:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_StyleEditorNavigator_Control_StyleTreeView_Push
function TkwStyleEditorNavigatorFormStyleTreeView.StyleTreeView(const aCtx: TtfwContext;
aStyleEditorNavigatorForm: TStyleEditorNavigatorForm): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TStyleEditorNavigatorForm.StyleTreeView }
begin
Result := aStyleEditorNavigatorForm.StyleTreeView;
end;//TkwStyleEditorNavigatorFormStyleTreeView.StyleTreeView
class function TkwStyleEditorNavigatorFormStyleTreeView.GetWordNameForRegister: AnsiString;
begin
Result := '.TStyleEditorNavigatorForm.StyleTreeView';
end;//TkwStyleEditorNavigatorFormStyleTreeView.GetWordNameForRegister
function TkwStyleEditorNavigatorFormStyleTreeView.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTreeViewWithAdapterDragDrop);
end;//TkwStyleEditorNavigatorFormStyleTreeView.GetResultTypeInfo
function TkwStyleEditorNavigatorFormStyleTreeView.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwStyleEditorNavigatorFormStyleTreeView.GetAllParamsCount
function TkwStyleEditorNavigatorFormStyleTreeView.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TStyleEditorNavigatorForm)]);
end;//TkwStyleEditorNavigatorFormStyleTreeView.ParamsTypes
procedure TkwStyleEditorNavigatorFormStyleTreeView.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству StyleTreeView', aCtx);
end;//TkwStyleEditorNavigatorFormStyleTreeView.SetValuePrim
procedure TkwStyleEditorNavigatorFormStyleTreeView.DoDoIt(const aCtx: TtfwContext);
var l_aStyleEditorNavigatorForm: TStyleEditorNavigatorForm;
begin
try
l_aStyleEditorNavigatorForm := TStyleEditorNavigatorForm(aCtx.rEngine.PopObjAs(TStyleEditorNavigatorForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aStyleEditorNavigatorForm: TStyleEditorNavigatorForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(StyleTreeView(aCtx, l_aStyleEditorNavigatorForm));
end;//TkwStyleEditorNavigatorFormStyleTreeView.DoDoIt
function Tkw_Form_StyleEditorNavigator.GetString: AnsiString;
begin
Result := 'StyleEditorNavigatorForm';
end;//Tkw_Form_StyleEditorNavigator.GetString
class procedure Tkw_Form_StyleEditorNavigator.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TStyleEditorNavigatorForm);
end;//Tkw_Form_StyleEditorNavigator.RegisterInEngine
class function Tkw_Form_StyleEditorNavigator.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::StyleEditorNavigator';
end;//Tkw_Form_StyleEditorNavigator.GetWordNameForRegister
function Tkw_StyleEditorNavigator_Control_StyleTreeView.GetString: AnsiString;
begin
Result := 'StyleTreeView';
end;//Tkw_StyleEditorNavigator_Control_StyleTreeView.GetString
class procedure Tkw_StyleEditorNavigator_Control_StyleTreeView.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop);
end;//Tkw_StyleEditorNavigator_Control_StyleTreeView.RegisterInEngine
class function Tkw_StyleEditorNavigator_Control_StyleTreeView.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::StyleTreeView';
end;//Tkw_StyleEditorNavigator_Control_StyleTreeView.GetWordNameForRegister
procedure Tkw_StyleEditorNavigator_Control_StyleTreeView_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('StyleTreeView');
inherited;
end;//Tkw_StyleEditorNavigator_Control_StyleTreeView_Push.DoDoIt
class function Tkw_StyleEditorNavigator_Control_StyleTreeView_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::StyleTreeView:push';
end;//Tkw_StyleEditorNavigator_Control_StyleTreeView_Push.GetWordNameForRegister
initialization
TkwStyleEditorNavigatorFormStyleTreeView.RegisterInEngine;
{* Регистрация StyleEditorNavigatorForm_StyleTreeView }
Tkw_Form_StyleEditorNavigator.RegisterInEngine;
{* Регистрация Tkw_Form_StyleEditorNavigator }
Tkw_StyleEditorNavigator_Control_StyleTreeView.RegisterInEngine;
{* Регистрация Tkw_StyleEditorNavigator_Control_StyleTreeView }
Tkw_StyleEditorNavigator_Control_StyleTreeView_Push.RegisterInEngine;
{* Регистрация Tkw_StyleEditorNavigator_Control_StyleTreeView_Push }
TtfwTypeRegistrator.RegisterType(TypeInfo(TStyleEditorNavigatorForm));
{* Регистрация типа TStyleEditorNavigatorForm }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop));
{* Регистрация типа TnscTreeViewWithAdapterDragDrop }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
unit untTestParams;
interface
uses
// VCL
Sysutils, Classes, Forms, Dialogs;
type
TTestParams = class(TComponent)
private
FParamsLoaded: Boolean;
FSlipDiscountCharge: TStringList;
FSlipClose: TStringList;
FSlipConfigure: TStringList;
FSlipOpen: TStringList;
FSlipRegistration: TStringList;
procedure SaveToFile(FileName: string);
procedure LoadFromFile(FileName: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LoadState;
procedure SaveState;
property ParamsLoaded: Boolean read FParamsLoaded;
published
property SlipClose: TStringList read FSlipClose write FSlipClose;
property SlipOpen: TStringList read FSlipOpen write FSlipClose;
property SlipDiscountCharge: TStringList read FSlipDiscountCharge write FSlipClose;
property SlipConfigure: TStringList read FSlipConfigure write FSlipClose;
property SlipRegistration: TStringList read FSlipRegistration write FSlipClose;
end;
function TestParams:TTestParams;
procedure FreeTestParams;
var
FTestParams: TTestParams;
implementation
function TestParams:TTestParams;
begin
if FTestParams = nil then
FTestParams := TTestParams.Create(nil);
Result := FTestParams;
end;
procedure FreeTestParams;
begin
FTestParams.Free;
end;
function GetParamsFileName: string;
begin
Result := ChangeFileExt(Application.ExeName, '.dat');
end;
{ TTestParams }
constructor TTestParams.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSlipOpen := TStringList.Create;
FSlipClose := TStringList.Create;
FSlipConfigure := TStringList.Create;
FSlipDiscountCharge := TStringList.Create;
FSlipRegistration := TStringList.Create;
FParamsLoaded := False;
LoadState;
end;
destructor TTestParams.Destroy;
begin
SaveState;
FSlipOpen.Free;
FSlipClose.Free;
FSlipConfigure.Free;
FSlipDiscountCharge.Free;
FSlipRegistration.Free;
inherited Destroy;
end;
procedure TTestParams.LoadFromFile(FileName: string);
begin
if FileName = '' then Exit;
if not FileExists(FileName) then Exit;
FParamsLoaded := True;
try
ReadComponentResFile(FileName, Self)
except
FParamsLoaded := False;
end;
if (FSlipOpen.Text = '') or (FSlipClose.Text = '') or
(FSlipConfigure.Text = '') or (FSlipDiscountCharge.Text = '') or
(FSlipDiscountCharge.Text = '') or (FSlipRegistration.Text = '') then
FParamsLoaded := False;
end;
procedure TTestParams.LoadState;
begin
try
LoadFromFile(GetParamsFileName);
except
end;
end;
procedure TTestParams.SaveState;
begin
try
SaveToFile(GetParamsFileName);
except
end;
end;
procedure TTestParams.SaveToFile(FileName: string);
begin
if FileName = '' then Exit;
if FileExists(FileName) then DeleteFile(PChar(FileName));
try
WriteComponentResFile(FileName, Self);
except
end;
end;
end.
|
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Franšois Piette
Description: TTrackDataSet keep track of TDataSet insert, delete and update.
See Quick Referece below.
Creation: April 1, 1999
Version: 1.04
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list midware@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1999-2007 by Franšois PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software and or any
derived or altered versions for any purpose, excluding commercial
applications. You can use this software for personal use only.
You may distribute it freely untouched.
The following restrictions applies:
1. The origin of this software must not be misrepresented, you
must not claim that you wrote the original software.
2. If you use this software in a product, an acknowledgment in
the product documentation and displayed on screen is required.
The text must be: "This product is based on MidWare. Freeware
source code is available at http://www.overbyte.be."
3. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
4. This notice may not be removed or altered from any source
distribution and must be added to the product documentation.
Quick Reference:
TTrackDataSet component is use to track changes (edit, insert, delete)
made in a TDataSet (TTable, TQuery or any other TDataSet descendent).
It does it by installing event handler to the TDataSet to be informed
about changes. Event handled are BeforeDelete, BeforeEdit, BeforeInsert,
AfterDelete and AfterPost. Those event once captured by TTrackDataSet
can still be used because the component relay them to other events.
TTrackDataSet component use a TTrackData object to hold fields content
and definition. TTrackData object mainly consist of a TList used to hold
a list of all data fields from TDataSet. Elements of the list are pointers
to TTrackDataField.
Before any change is made to a TDataSet, TTrackDataSet component record
all field values into a TTrackData, accessible thru DataBefore property.
After any changes are posted, TTrackDataSet component record new values
into a second TTrackData, accessible thru DataAfter property. And then fire
the OnDataChanged event. Operation done is saved in Operation property.
From the OnDataChanged event, the programmer can get the operation done
(insert, delete or update) in the Operation property, the data
before the operation in DataBefore property and data after the operation in
DataAfter property. At that point, those informations may be save to build
a log file to later undo the changes, or apply them again (to implement
brielcase model for example).
Updates:
Sep 15, 2001 V1.01 Delphi 6
Aug 28, 2004 V1.02 Use MWDefs.inc. Removed unused units.
Better NULL field support. Thanks to Stefan Frank
<stefan_frank@yahoo.com> for his code.
Aug 31, 2004 V1.03 Forward orginal events BeforeDelete, BeforeEdit,
BeforeInsert, AfterDelete, AfterPost, AfterCancel. Thanks to
Mauricio Virtual <mauricio@virtual.inf.br> for hos code.
Aug 13, 2010 V1.04 Adapted for Delphi XE
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteTrackDs;
{$I OverbyteMwDefs.inc}
interface
uses
Windows, SysUtils, Classes, Controls, db;
const
AppSrvClientVersion = 104;
CopyRight : String = ' TTrackData (c) 1999-2010 F. Piette V1.04 ';
type
TTrackDataSetOperation = (tdsoNone, tdsoInsert, tdsoDelete, tdsoUpdate);
const
TrackDataSetOperationName : array [TTrackDataSetOperation] of String =
('tdsoNone', 'tdsoInsert', 'tdsoDelete', 'tdsoUpdate');
type
ETrackDataSetException = class(EXception);
TTrackDataSetNotifyEvent = procedure (Sender : TObject; DataSet : TDataSet) of object;
// TTrackDataField is used to hold all informations from a dataset field
TTrackDataField = class(TObject)
DataPtr : PByte; // Pointer to buffer holding data
DataSize : Integer; // Size of data buffer
DataType : TFieldType; // Field datatype
FieldName : String; // Field name
Changed : Boolean; // Changed flag, updated by compare method
IsNull : Boolean; // = TRUE if field is empty { SF New }
function AsString : String;
end;
TTrackDataFieldClass = class of TTrackDataField;
// TTrackDataItem is an enu¨eration of all items that can be included in
// convertion from TTrackDataField to string (AsString method).
TTrackDataItem = (tdiData, tdiDataSize, tdiDataType,
tdiFieldName, tdiChanged);
TTrackDataItems = set of TTrackDataItem;
// TTrackData is an object used to hold data fields from a dataset record
// It is a kind of record duplicate, but no tied to any database system
TTrackData = class(TObject)
protected
FFieldClass : TTrackDataFieldClass; // Class to be used for fields
FFields : TList; // A list for all TTrackDataField
function GetFieldCount : Integer;
function GetField(nIndex : Integer) : TTrackDataField;
public
constructor Create; virtual;
destructor Destroy; override;
// Clear the list, freeing memory
procedure Clear;
// Add a field to the list. Data is copied to a TTrackDataField
function Add(DataSetField : TField) : Integer;
// Delete a field from list, releasing used memory
procedure Delete(Index : Integer);
// Convert to string representation, with a set of items to take care of
function AsString(How : TTrackDataItems) : String;
// Find a field by name
function FieldByName(const FieldName : String) : TTrackDataField;
// Compare this TTrackData with an other one, updating both Changed flags
// Returns TRUE if both are excatly matching.
function Compare(Other : TTrackData) : Boolean;
// Returns the number of field added to the list
property FieldCount : Integer read GetFieldCount;
// Give access to a field (TTrackDataField) from the list
property Fields[nIndex : Integer] : TTrackDataField read GetField;
end;
TCustomTrackDataSet = class(TComponent)
protected
FTracking : Boolean;
FDataSet : TDataSet;
FOperation : TTrackDataSetOperation;
FDataBefore : TTrackData;
FDataAfter : TTrackData;
FBeforeDelete : TTrackDataSetNotifyEvent;
FBeforeEdit : TTrackDataSetNotifyEvent;
FBeforeInsert : TTrackDataSetNotifyEvent;
FAfterDelete : TTrackDataSetNotifyEvent;
FAfterPost : TTrackDataSetNotifyEvent;
FAfterCancel : TTrackDataSetNotifyEvent;
FOnDataChanging : TNotifyEvent;
FOnDataChanged : TNotifyEvent;
FOldBeforeDelete : TDataSetNotifyEvent;
FOldBeforeEdit : TDataSetNotifyEvent;
FOldBeforeInsert : TDataSetNotifyEvent;
FOldAfterDelete : TDataSetNotifyEvent;
FOldAfterPost : TDataSetNotifyEvent;
FOldAfterCancel : TDataSetNotifyEvent;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure TriggerBeforeDelete(DataSet: TDataSet); virtual;
procedure TriggerBeforeEdit(DataSet: TDataSet); virtual;
procedure TriggerBeforeInsert(DataSet: TDataSet); virtual;
procedure TriggerAfterDelete(DataSet: TDataSet); virtual;
procedure TriggerAfterPost(DataSet: TDataSet); virtual;
procedure TriggerAfterCancel(DataSet: TDataSet); virtual;
procedure TriggerDataChanging; virtual;
procedure TriggerDataChanged; virtual;
procedure TriggerOldBeforeDelete(DataSet: TDataSet); virtual;
procedure TriggerOldBeforeEdit(DataSet: TDataSet); virtual;
procedure TriggerOldBeforeInsert(DataSet: TDataSet); virtual;
procedure TriggerOldAfterDelete(DataSet: TDataSet); virtual;
procedure TriggerOldAfterPost(DataSet: TDataSet); virtual;
procedure TriggerOldAfterCancel(DataSet: TDataSet); virtual;
procedure DataSetBeforeDelete(DataSet: TDataSet); virtual;
procedure DataSetBeforeEdit(DataSet: TDataSet); virtual;
procedure DataSetBeforeInsert(DataSet: TDataSet); virtual;
procedure DataSetAfterDelete(DataSet: TDataSet); virtual;
procedure DataSetAfterPost(DataSet: TDataSet); virtual;
procedure DataSetAfterCancel(DataSet: TDataSet); virtual;
procedure SetDataSet(NewValue : TDataSet); virtual;
function GetTracking : Boolean; virtual;
procedure SetTracking(NewValue : Boolean);
procedure SaveRecord(Dst : TTrackData); virtual;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
// Start tracking data set. It attach event handlers to TDataSet, deleting
// existing event handlers.
procedure TrackOn; virtual;
// Stop tracking data set. Remove all event handlers from TDataSet. Do
// not restore event handlers that was installed before TrackOn call.
procedure TrackOff; virtual;
// Detach a TTrackData (such as DataBefore or DataAfter) from the
// component. Programmer then becomes responsible for freeing it when is
// is no more needed or he will experience memory leaks.
procedure Detach(TrackData : TTrackData); virtual;
// Check or set component tracking activity
property Active : Boolean read GetTracking
write SetTracking;
// Current operation
property Operation : TTrackDataSetOperation read FOperation;
// Data before the operation
property DataBefore : TTrackData read FDataBefore;
// Data after the operation
property DataAfter : TTrackData read FDataAfter;
// Tracket TDataSet (TTable, TQuery or any other TDataSet)
property DataSet : TDataSet read FDataSet
write SetDataSet;
// OnDataChanging is fired when change are about to be made
property OnDataChanging : TNotifyEvent read FOnDataChanging
write FOnDataChanging;
// OnDataChanged is fired when an operation is done (insert, delete, update)
property OnDataChanged : TNotifyEvent read FOnDataChanged
write FOnDataChanged;
// Event triggered when TDataSet.BeforeDelete is triggered
property BeforeDelete: TTrackDataSetNotifyEvent read FBeforeDelete
write FBeforeDelete;
// Event triggered when TDataSet.BeforeEdit is triggered
property BeforeEdit: TTrackDataSetNotifyEvent read FBeforeEdit
write FBeforeEdit;
// Event triggered when TDataSet.BeforeInsert is triggered
property BeforeInsert: TTrackDataSetNotifyEvent read FBeforeInsert
write FBeforeInsert;
// Event triggered when TDataSet.AfterDelete is triggered
property AfterDelete: TTrackDataSetNotifyEvent read FAfterDelete
write FAfterDelete;
// Event triggered when TDataSet.AfterPost is triggered
property AfterPost: TTrackDataSetNotifyEvent read FAfterPost
write FAfterPost;
// Event triggered when TDataSet.AfterCancel is triggered
property AfterCancel: TTrackDataSetNotifyEvent read FAfterCancel
write FAfterCancel;
end;
TTrackDataSet = class(TCustomTrackDataSet)
published
property DataSet;
property OnDataChanging;
property OnDataChanged;
property BeforeDelete;
property BeforeEdit;
property BeforeInsert;
property AfterDelete;
property AfterPost;
property AfterCancel;
end;
implementation
function DoubleQuote(Value : AnsiString) : AnsiString; forward;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTrackDataField.AsString : String;
var
J, N : Integer;
const
HexDigit : array [0..15] of Char =
('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
BooleanToStr : array [Boolean] of String = ('FALSE', 'TRUE');
type
PDateTimeRec = ^TDateTimeRec;
PDateTime = ^TDateTime;
begin
case DataType of
ftString :
Result := '''' + String(DoubleQuote(PAnsiChar(DataPtr))) + '''';
ftInteger, ftAutoInc:
Result := IntToStr(PInteger(DataPtr)^);
ftSmallInt: { SF New }
Result := IntToStr(PSmallInt(DataPtr)^);
ftBoolean:
Result := BooleanToStr[DataPtr^ <> 0];
ftFloat, ftCurrency:
Result := FloatToStr(PDouble(DataPtr)^);
ftDate:
Result := FormatDateTime('YYYYMMDD',
PDateTimeRec(DataPtr)^.Date - DateDelta);
ftTime:
Result := FormatDateTime('HHNNSS',
PDateTimeRec(DataPtr)^.Time / MSecsPerDay);
ftDateTime :
if PDateTime(DataPtr)^ = 0 then
Result := '00000000 000000'
else
Result := FormatDateTime('YYYYMMDD HHNNSS',
(PDateTimeRec(DataPtr)^.DateTime / MSecsPerDay) - DateDelta);
ftBlob, ftMemo, ftGraphic :
begin
// We have binary data. Every control code if outputed like
// an hex number, including quote and dollars sign
// We will do a first pass to now how many hex char we have
// Two passes are needed because long string handling is very
// slow if adding one char at a time
N := 0;
for J := 0 to DataSize - 1 do begin
if AnsiChar(DataPtr[J]) in [#0..#31, '$', ''''] then
Inc(N);
end;
// Now we can adjust result size
SetLength(Result, 2 + DataSize + N + N);
// And do the second pass to set result value
Result[1] := '''';
N := 2;
for J := 0 to DataSize - 1 do begin
if AnsiChar(DataPtr[J]) in [#0..#31, '$', ''''] then begin
Result[N] := '$';
Inc(N);
Result[N] := HexDigit[Ord(DataPtr[J]) shr 4];
Inc(N);
Result[N] := HexDigit[Ord(DataPtr[J]) and 15];
end
else
Result[N] := Char(AnsiChar(DataPtr[J]));
Inc(N);
end;
Result[N] := '''';
end;
else
raise ETrackDataSetException.Create(
'TTrackDataField.AsString: ' +
'unsupported field type for field ''' +
FieldName + '''');
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TTrackData.Create;
begin
inherited Create;
FFieldClass := TTrackDataField;
FFields := TList.Create;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TTrackData.Destroy;
begin
if Assigned(FFields) then begin
FFields.Clear;
// Delete the list
FFields.Destroy;
FFields := nil;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTrackData.Clear;
var
Index : Integer;
begin
// Delete all items from the list
for Index := FieldCount - 1 downto 0 do
Delete(Index);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTrackData.GetFieldCount : Integer;
begin
if Assigned(FFields) then
Result := FFields.Count
else
Result := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTrackData.GetField(nIndex : Integer) : TTrackDataField;
begin
if (nIndex < 0) or (nIndex >= FieldCount) then
raise ETrackDataSetException.Create('TTrackData.GetField: Index out of range');
Result := FFields.Items[nIndex];
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTrackData.FieldByName(const FieldName : String) : TTrackDataField;
var
Index : Integer;
begin
for Index := FieldCount - 1 downto 0 do begin
Result := FFields.Items[Index];
if CompareText(Result.FieldName, FieldName) = 0 then
Exit;
end;
raise ETrackDataSetException.Create('TTrackData.FieldByName: Field ''' +
FieldName + ''' doesn''t exists.');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTrackData.AsString(How : TTrackDataItems) : String;
var
Index : Integer;
Field : TTrackDataField;
Count : Integer;
I : Integer;
const
HexDigit : array [0..15] of char =
('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
BooleanToStr : array [Boolean] of string = ('FALSE', 'TRUE');
type
PDateTimeRec = ^TDateTimeRec;
begin
// Empty How means all informations
if How = [] then
How := [tdiData, tdiDataSize, tdiDataType, tdiFieldName];
Result := '';
I := 0;
Count := FieldCount - 1;
for Index := 0 to Count do begin
Field := Fields[Index];
if (tdiChanged in How) and (not Field.Changed) then
continue;
if I > 0 then
Result := Result + ';';
if tdiFieldName in How then
Result := Result + Field.FieldName + ':';
if tdiDataSize in How then
Result := Result + IntToStr(Field.DataSize) + ':';
if tdiDataType in How then
Result := Result + IntToStr(Ord(Field.DataType)) + ':';
if tdiData in How then
Result := Result + Field.AsString;
Inc(I);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// Update Changed flag by comparing with other TTrackData
// Returns TRUE if ALL fields are the same
// If field counts are not equals, return FALSE and flag all fields
// as changed.
// Do not check field names (speed !). They should not change anyway.
function TTrackData.Compare(Other : TTrackData) : Boolean;
var
Index : Integer;
Field1 : TTrackDataField;
Field2 : TTrackDataField;
Count : Integer;
I : Integer;
P, Q : PByte;
begin
Count := FieldCount - 1;
if Count <> (Other.FieldCount - 1) then begin
Result := FALSE;
for Index := 0 to Count do
Fields[Index].Changed := TRUE;
Exit;
end;
Result := TRUE;
for Index := 0 to Count do begin
Field1 := Fields[Index];
Field2 := Other.Fields[Index];
Field1.Changed := FALSE;
Field2.Changed := FALSE;
if (Field1.DataSize <> Field2.DataSize) or
{ (Field1.DataType <> Field2.DataType) then begin SF Old }
(Field1.DataType <> Field2.DataType) or { SF New }
(Field1.IsNull <> Field2.IsNull) then begin { SF New }
// Size or type not the same, consider as changed
Field1.Changed := TRUE;
Field2.Changed := TRUE;
Result := FALSE;
end
else begin
// Size and type are the same, compare data (binary compare)
P := Field1.DataPtr;
Q := Field2.DataPtr;
I := 0;
while I < Field1.DataSize do begin
if P^ <> Q^ then begin
Field1.Changed := TRUE;
Field2.Changed := TRUE;
Result := FALSE;
break;
end;
Inc(P);
Inc(Q);
Inc(I);
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TTrackData.Add(DataSetField : TField) : Integer;
var
Field : TTrackDataField;
BlobStream : TStream;
begin
if not Assigned(DataSetField) then
raise ETrackDataSetException.Create('TTrackData.Add: Field not assigned');
// Allocate a new data record
Field := FFieldClass.Create;
// Append the record to the list
Result := FFields.Add(Field);
// Copy data from field to allocated record
Field.DataType := DataSetField.DataType;
Field.FieldName := DataSetField.FieldName;
Field.Changed := FALSE;
if DataSetField.IsBlob then begin
BlobStream := DataSetField.DataSet.CreateBlobStream(DataSetField, bmRead);
try
Field.DataSize := BlobStream.Size;
if Field.DataSize > 0 then begin
// Allocate memory to hold data
Field.DataPtr := AllocMem(Field.DataSize);
// Get data into allocated memory
BlobStream.ReadBuffer(Field.DataPtr^, Field.DataSize);
end;
finally
BlobStream.Free;
end;
end
else begin
// Copy field info and data to record
Field.DataSize := DataSetField.DataSize;
if Field.DataSize > 0 then begin
// Allocate memory to hold data
Field.DataPtr := AllocMem(Field.DataSize);
// Get data into allocated memory
{ SF Old DataSetField.GetData(Field.data); }
{ SF New } Field.IsNull := not DataSetField.GetData(Field.DataPtr);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TTrackData.Delete(Index : Integer);
var
Field : TTrackDataField;
begin
if (Index < 0) or (Index >= FFields.Count) then
raise ETrackDataSetException.Create('TTrackData.Delete: Index out of range');
Field := FFields.Items[Index];
if Field.DataSize > 0 then
FreeMem(Field.DataPtr);
Field.Destroy;
FFields.Delete(Index);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TCustomTrackDataSet.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FDataBefore := TTrackData.Create;
FDataAfter := TTrackData.Create;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TCustomTrackDataSet.Destroy;
begin
if Assigned(FDataBefore) then begin
FDataBefore.Destroy;
FDataBefore := nil;
end;
if Assigned(FDataAfter) then begin
FDataAfter.Destroy;
FDataAfter := nil;
end;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.SetDataSet(NewValue : TDataSet);
begin
if NewValue = FDataSet then
Exit;
TrackOff;
FDataSet := NewValue;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomTrackDataSet.GetTracking : Boolean;
begin
Result := FTracking;
end;
{$IFDEF NEVER}
var
Temp : TDataSetNotifyEvent;
begin
if not Assigned(FDataSet) then
Result := FALSE
else begin
Temp := DataSetBeforeDelete;
Result := (@FDataSet.BeforeDelete = @Temp);
if Result then begin
Temp := DataSetBeforeInsert;
Result := (@FDataSet.BeforeInsert = @Temp);
end
else if Result then begin
Temp := DataSetBeforeEdit;
Result := (@FDataSet.BeforeEdit = @Temp);
end
else if Result then begin
Temp := DataSetAfterDelete;
Result := (@FDataSet.AfterDelete = @Temp);
end
else if Result then begin
Temp := DataSetAfterPost;
Result := (@FDataSet.AfterPost = @Temp);
end
else if Result then begin
Temp := DataSetAfterCancel;
Result := (@FDataSet.AfterCancel = @Temp);
end;
end;
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.SetTracking(NewValue : Boolean);
begin
if NewValue then
TrackOn
else
TrackOff;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.Detach(TrackData : TTrackData);
begin
if TrackData = FDataBefore then
FDataBefore := nil
else if TrackData = FDataAfter then
FDataAfter := nil;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TrackOn;
begin
if not Assigned(FDataSet) then
raise ETrackDataSetException.Create(
'TrackOn failed: Dataset property is unassigned');
if not FTracking then begin
FTracking := TRUE;
FOldBeforeDelete := FDataSet.BeforeDelete;
FOldBeforeEdit := FDataSet.BeforeEdit;
FOldBeforeInsert := FDataSet.BeforeInsert;
FOldAfterDelete := FDataSet.AfterDelete;
FOldAfterPost := FDataSet.AfterPost;
FOldAfterCancel := FDataSet.AfterCancel;
FDataSet.BeforeDelete := DataSetBeforeDelete;
FDataSet.BeforeEdit := DataSetBeforeEdit;
FDataSet.BeforeInsert := DataSetBeforeInsert;
FDataSet.AfterDelete := DataSetAfterDelete;
FDataSet.AfterPost := DataSetAfterPost;
FDataSet.AfterCancel := DataSetAfterCancel;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TrackOff;
var
Temp : TDataSetNotifyEvent;
begin
FOperation := tdsoNone;
if FTracking then begin
FTracking := FALSE;
if not Assigned(FDataSet) then
Exit;
// We will check that all event handlers are still untouched before
// restoring the saved values. The is to protect the programmer
// against his own logic errors :-)
Temp := DataSetBeforeDelete;
if @FDataSet.BeforeDelete <> @Temp then
raise ETrackDataSetException.Create(
'TrackOff failed: Dataset BeforeDelete events modifyed');
Temp := DataSetBeforeEdit;
if @FDataSet.BeforeEdit <> @Temp then
raise ETrackDataSetException.Create(
'TrackOff failed: Dataset BeforeEdit events modifyed');
Temp := DataSetBeforeInsert;
if @FDataSet.BeforeInsert <> @Temp then
raise ETrackDataSetException.Create(
'TrackOff failed: Dataset BeforeInsert events modifyed');
Temp := DataSetAfterDelete;
if @FDataSet.AfterDelete <> @Temp then
raise ETrackDataSetException.Create(
'TrackOff failed: Dataset AfterDelete events modifyed');
Temp := DataSetAfterPost;
if @FDataSet.AfterPost <> @Temp then
raise ETrackDataSetException.Create(
'TrackOff failed: Dataset AfterPost events modifyed');
Temp := DataSetAfterCancel;
if @FDataSet.AfterCancel <> @Temp then
raise ETrackDataSetException.Create(
'TrackOff failed: Dataset AfterCancel events modifyed');
FDataSet.BeforeDelete := FOldBeforeDelete;
FDataSet.BeforeEdit := FOldBeforeEdit;
FDataSet.BeforeInsert := FOldBeforeInsert;
FDataSet.AfterDelete := FOldAfterDelete;
FDataSet.AfterPost := FOldAfterPost;
FDataSet.AfterCancel := FOldAfterCancel;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerBeforeDelete(DataSet: TDataSet);
begin
if Assigned(FBeforeDelete) then
FBeforeDelete(Self, DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerBeforeEdit(DataSet: TDataSet);
begin
if Assigned(FBeforeEdit) then
FBeforeEdit(Self, DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerBeforeInsert(DataSet: TDataSet);
begin
if Assigned(FBeforeInsert) then
FBeforeInsert(Self, DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerAfterDelete(DataSet: TDataSet);
begin
if Assigned(FAfterDelete) then
FAfterDelete(Self, DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerAfterCancel(DataSet: TDataSet);
begin
if Assigned(FAfterCancel) then
FAfterCancel(Self, DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerAfterPost(DataSet: TDataSet);
begin
if Assigned(FAfterPost) then
FAfterPost(Self, DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerDataChanging;
begin
if Assigned(FOnDataChanging) then
FOnDataChanging(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerDataChanged;
begin
if Assigned(FOnDataChanged) then
FOnDataChanged(Self);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerOldAfterCancel(DataSet: TDataSet);
begin
if Assigned(FOldAfterCancel) then
FOldAfterCancel(DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerOldAfterDelete(DataSet: TDataSet);
begin
if Assigned(FOldAfterDelete) then
FOldAfterDelete(DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerOldAfterPost(DataSet: TDataSet);
begin
if Assigned(FOldAfterPost) then
FOldAfterPost(DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerOldBeforeDelete(DataSet: TDataSet);
begin
if Assigned(FOldBeforeDelete) then
FOldBeforeDelete(DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerOldBeforeEdit(DataSet: TDataSet);
begin
if Assigned(FOldBeforeEdit) then
FOldBeforeEdit(DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.TriggerOldBeforeInsert(DataSet: TDataSet);
begin
if Assigned(FOldBeforeInsert) then
FOldBeforeInsert(DataSet);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.DataSetBeforeDelete(DataSet: TDataSet);
begin
TriggerOldBeforeDelete(DataSet); // Trigger original event
TriggerBeforeDelete(DataSet);
TriggerDataChanging;
FOperation := tdsoDelete;
SaveRecord(FDataBefore);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.DataSetBeforeEdit(DataSet: TDataSet);
begin
TriggerOldBeforeEdit(DataSet); // Trigger original event
TriggerBeforeEdit(DataSet);
TriggerDataChanging;
FOperation := tdsoUpdate;
SaveRecord(FDataBefore);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.DataSetBeforeInsert(DataSet: TDataSet);
begin
TriggerOldBeforeInsert(DataSet); //Trigger original event
TriggerBeforeInsert(DataSet);
TriggerDataChanging;
FOperation := tdsoInsert;
FDataBefore.Clear;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.DataSetAfterDelete(DataSet: TDataSet);
begin
FDataAfter.Clear;
TriggerDataChanged;
TriggerAfterDelete(DataSet);
FOperation := tdsoNone;
TriggerOldAfterDelete(DataSet); // Trigger original event
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.DataSetAfterPost(DataSet: TDataSet);
begin
SaveRecord(FDataAfter);
TriggerDataChanged;
TriggerAfterPost(DataSet);
FOperation := tdsoNone;
TriggerOldAfterPost(DataSet); // Trigger original event
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.DataSetAfterCancel(DataSet: TDataSet);
begin
FDataBefore.Clear;
TriggerAfterCancel(DataSet);
FOperation := tdsoNone;
TriggerOldAfterCancel(DataSet); // Trigger original event
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.SaveRecord(Dst : TTrackData);
var
Index : Integer;
begin
if not Assigned(Dst) then
Exit;
Dst.Clear;
for Index := 0 to FDataSet.FieldCount - 1 do
Dst.Add(FDataSet.Fields[Index]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomTrackDataSet.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then begin
if AComponent = FDataSet then begin
FDataSet := nil;
TrackOff;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function DoubleQuote(Value : AnsiString) : AnsiString;
var
I : Integer;
begin
Result := '';
for I := 1 to Length(Value) do begin
if Value[I] = '''' then
Result := Result + ''''''
else
Result := Result + Value[I];
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit evNSRCWriterTypes;
// Модуль: "w:\common\components\gui\Garant\Everest\evNSRCWriterTypes.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "evNSRCWriterTypes" MUID: (4BAC9A2A03A8)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, evdTypes
;
type
TevNSRCParaStyle = {$IfDef XE4}record{$Else}object{$EndIf}
public
Letter: AnsiChar;
ParaLI: Integer;
ParaWC: Integer;
ParaFI: Integer;
IsDecorPara: Boolean;
PrintFontSize: Integer;
StyleID: Integer;
public
function EQ(const anOther: TevNSRCParaStyle): Boolean;
{* Функция проверки эквивалентности }
procedure Clear;
end;//TevNSRCParaStyle
TevNSRCParaParas = {$IfDef XE4}record{$Else}object{$EndIf}
public
Justification: TevIndentType;
Width: Integer;
FirstIndent: Integer;
LeftIndent: Integer;
Style: TevNSRCParaStyle;
public
procedure Clear;
end;//TevNSRCParaParas
implementation
uses
l3ImplUses
, l3Base
, l3Const
//#UC START# *4BAC9A2A03A8impl_uses*
//#UC END# *4BAC9A2A03A8impl_uses*
;
function TevNSRCParaStyle.EQ(const anOther: TevNSRCParaStyle): Boolean;
{* Функция проверки эквивалентности }
//#UC START# *4BACA14E0110_4BAC9A7301E3_var*
//#UC END# *4BACA14E0110_4BAC9A7301E3_var*
begin
//#UC START# *4BACA14E0110_4BAC9A7301E3_impl*
Result :=
(Self.Letter = anOther.Letter) AND
(Self.ParaLI = anOther.ParaLI) AND
(Self.ParaWC = anOther.ParaWC) AND
(Self.ParaFI = anOther.ParaFI) AND
(Self.IsDecorPara = anOther.IsDecorPara) AND
(Self.PrintFontSize = anOther.PrintFontSize) AND
(Self.StyleID = anOther.StyleID);
//#UC END# *4BACA14E0110_4BAC9A7301E3_impl*
end;//TevNSRCParaStyle.EQ
procedure TevNSRCParaStyle.Clear;
//#UC START# *4BACA4BF01A5_4BAC9A7301E3_var*
//#UC END# *4BACA4BF01A5_4BAC9A7301E3_var*
begin
//#UC START# *4BACA4BF01A5_4BAC9A7301E3_impl*
l3FillChar(Self, SizeOf(Self));
//#UC END# *4BACA4BF01A5_4BAC9A7301E3_impl*
end;//TevNSRCParaStyle.Clear
procedure TevNSRCParaParas.Clear;
//#UC START# *4BACA4D403D4_4BAC9ADB0162_var*
//#UC END# *4BACA4D403D4_4BAC9ADB0162_var*
begin
//#UC START# *4BACA4D403D4_4BAC9ADB0162_impl*
Justification := ev_itNone;
FirstIndent := l3NilLong;
Width := l3NilLong;
LeftIndent := l3NilLong;
//#UC END# *4BACA4D403D4_4BAC9ADB0162_impl*
end;//TevNSRCParaParas.Clear
end.
|
unit FFSLOGTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TFFSLOGRecord = record
PLogID: Integer;
PDateStamp: String[20];
PUserID: String[10];
PRecordType: String[10];
PLogMessage: String[100];
End;
TFFSLOGBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TFFSLOGRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIFFSLOG = (FFSLOGPrimaryKey);
TFFSLOGTable = class( TDBISAMTableAU )
private
FDFLogID: TAutoIncField;
FDFDateStamp: TStringField;
FDFUserID: TStringField;
FDFRecordType: TStringField;
FDFLogMessage: TStringField;
procedure SetPDateStamp(const Value: String);
function GetPDateStamp:String;
procedure SetPUserID(const Value: String);
function GetPUserID:String;
procedure SetPRecordType(const Value: String);
function GetPRecordType:String;
procedure SetPLogMessage(const Value: String);
function GetPLogMessage:String;
procedure SetEnumIndex(Value: TEIFFSLOG);
function GetEnumIndex: TEIFFSLOG;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TFFSLOGRecord;
procedure StoreDataBuffer(ABuffer:TFFSLOGRecord);
property DFLogID: TAutoIncField read FDFLogID;
property DFDateStamp: TStringField read FDFDateStamp;
property DFUserID: TStringField read FDFUserID;
property DFRecordType: TStringField read FDFRecordType;
property DFLogMessage: TStringField read FDFLogMessage;
property PDateStamp: String read GetPDateStamp write SetPDateStamp;
property PUserID: String read GetPUserID write SetPUserID;
property PRecordType: String read GetPRecordType write SetPRecordType;
property PLogMessage: String read GetPLogMessage write SetPLogMessage;
published
property Active write SetActive;
property EnumIndex: TEIFFSLOG read GetEnumIndex write SetEnumIndex;
end; { TFFSLOGTable }
procedure Register;
implementation
procedure TFFSLOGTable.CreateFields;
begin
FDFLogID := CreateField( 'LogID' ) as TAutoIncField;
FDFDateStamp := CreateField( 'DateStamp' ) as TStringField;
FDFUserID := CreateField( 'UserID' ) as TStringField;
FDFRecordType := CreateField( 'RecordType' ) as TStringField;
FDFLogMessage := CreateField( 'LogMessage' ) as TStringField;
end; { TFFSLOGTable.CreateFields }
procedure TFFSLOGTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TFFSLOGTable.SetActive }
procedure TFFSLOGTable.SetPDateStamp(const Value: String);
begin
DFDateStamp.Value := Value;
end;
function TFFSLOGTable.GetPDateStamp:String;
begin
result := DFDateStamp.Value;
end;
procedure TFFSLOGTable.SetPUserID(const Value: String);
begin
DFUserID.Value := Value;
end;
function TFFSLOGTable.GetPUserID:String;
begin
result := DFUserID.Value;
end;
procedure TFFSLOGTable.SetPRecordType(const Value: String);
begin
DFRecordType.Value := Value;
end;
function TFFSLOGTable.GetPRecordType:String;
begin
result := DFRecordType.Value;
end;
procedure TFFSLOGTable.SetPLogMessage(const Value: String);
begin
DFLogMessage.Value := Value;
end;
function TFFSLOGTable.GetPLogMessage:String;
begin
result := DFLogMessage.Value;
end;
procedure TFFSLOGTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LogID, AutoInc, 0, N');
Add('DateStamp, String, 20, N');
Add('UserID, String, 10, N');
Add('RecordType, String, 10, N');
Add('LogMessage, String, 100, N');
end;
end;
procedure TFFSLOGTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LogID, Y, Y, N, Y');
end;
end;
procedure TFFSLOGTable.SetEnumIndex(Value: TEIFFSLOG);
begin
case Value of
FFSLOGPrimaryKey : IndexName := '';
end;
end;
function TFFSLOGTable.GetDataBuffer:TFFSLOGRecord;
var buf: TFFSLOGRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLogID := DFLogID.Value;
buf.PDateStamp := DFDateStamp.Value;
buf.PUserID := DFUserID.Value;
buf.PRecordType := DFRecordType.Value;
buf.PLogMessage := DFLogMessage.Value;
result := buf;
end;
procedure TFFSLOGTable.StoreDataBuffer(ABuffer:TFFSLOGRecord);
begin
DFDateStamp.Value := ABuffer.PDateStamp;
DFUserID.Value := ABuffer.PUserID;
DFRecordType.Value := ABuffer.PRecordType;
DFLogMessage.Value := ABuffer.PLogMessage;
end;
function TFFSLOGTable.GetEnumIndex: TEIFFSLOG;
var iname : string;
begin
result := FFSLOGPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := FFSLOGPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'FFS Tables', [ TFFSLOGTable, TFFSLOGBuffer ] );
end; { Register }
function TFFSLOGBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..5] of string = ('LOGID','DATESTAMP','USERID','RECORDTYPE','LOGMESSAGE' );
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 TFFSLOGBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftAutoInc;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
end;
end;
function TFFSLOGBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLogID;
2 : result := @Data.PDateStamp;
3 : result := @Data.PUserID;
4 : result := @Data.PRecordType;
5 : result := @Data.PLogMessage;
end;
end;
end.
|
unit View.PesquisarPessoas;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky,
dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, dxSkinscxPCPainter, dxLayoutContainer, dxLayoutControl, dxLayoutcxEditAdapters, cxContainer, cxEdit,
cxGroupBox, cxCheckBox, cxTextEdit, cxMaskEdit, System.Actions, Vcl.ActnList, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, dxLayoutControlAdapters, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxCheckListBox, cxRadioGroup, cxDropDownEdit, dxmdaset, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light,
dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Control.Bases,
DAO.Conexao;
type
TView_PesquisarPessoas = class(TForm)
lcPesquisaGroup_Root: TdxLayoutGroup;
lcPesquisa: TdxLayoutControl;
actPesquisar: TActionList;
tvPesquisa: TcxGridDBTableView;
lvPesquisa: TcxGridLevel;
grdPesquisa: TcxGrid;
lcPesquisaItem2: TdxLayoutItem;
actSelecionar: TAction;
actFechar: TAction;
cxButton2: TcxButton;
lcPesquisaItem4: TdxLayoutItem;
lcPesquisaGroup1: TdxLayoutAutoCreatedGroup;
cxButton3: TcxButton;
lcPesquisaItem5: TdxLayoutItem;
dsPesquisa: TDataSource;
textEditPesquisar: TcxTextEdit;
dxLayoutItem1: TdxLayoutItem;
actionLocalizar: TAction;
cxButton1: TcxButton;
dxLayoutItem2: TdxLayoutItem;
qryPesquisa: TdxMemData;
procedure actFecharExecute(Sender: TObject);
procedure actSelecionarExecute(Sender: TObject);
procedure tvPesquisaCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
procedure grdPesquisaEnter(Sender: TObject);
procedure grdPesquisaExit(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actionLocalizarExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FConexao: TConexao;
procedure PopulaPesquisa;
public
{ Public declarations }
sSQL : String;
sWhere: String;
bOpen: boolean;
end;
var
View_PesquisarPessoas: TView_PesquisarPessoas;
fdQuery: TFDQuery;
implementation
{$R *.dfm}
uses Common.Utils, Global.Parametros, Data.SisGeF;
procedure TView_PesquisarPessoas.actFecharExecute(Sender: TObject);
begin
ModalResult := mrClose;
end;
procedure TView_PesquisarPessoas.actionLocalizarExecute(Sender: TObject);
begin
PopulaPesquisa;
end;
procedure TView_PesquisarPessoas.actSelecionarExecute(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TView_PesquisarPessoas.FormCreate(Sender: TObject);
begin
FConexao := TConexao.Create;
end;
procedure TView_PesquisarPessoas.FormDestroy(Sender: TObject);
begin
FConexao.Free;
end;
procedure TView_PesquisarPessoas.FormShow(Sender: TObject);
begin
if bOpen then
begin
actionLocalizarExecute(Sender);
end;
end;
procedure TView_PesquisarPessoas.grdPesquisaEnter(Sender: TObject);
begin
if not qryPesquisa.IsEmpty then
begin
cxButton2.Default := True;
end
else
begin
cxButton2.Default := False;
end;
end;
procedure TView_PesquisarPessoas.grdPesquisaExit(Sender: TObject);
begin
cxButton2.Default := False;
end;
procedure TView_PesquisarPessoas.PopulaPesquisa;
var
sConsulta: String;
sWhere1: String;
begin
try
sConsulta := '';
sWhere1 := '';
if textEditPesquisar.Text = '' then
begin
sConsulta := sSQL;
end
else
begin
sWhere1 := StringReplace(swhere,'param',textEditPesquisar.Text,[rfReplaceAll]);
if TUtils.ENumero(textEditPesquisar.Text) then
begin
sWhere1 := StringReplace(swhere1,'paraN',textEditPesquisar.Text,[rfReplaceAll]);
end
else
begin
sWhere1 := StringReplace(swhere1,'paraN','0',[rfReplaceAll]);
end;
sConsulta := sSQL + sWhere1;
end;
fdQuery := FConexao.ReturnQuery;
fdQuery.SQL.Text := sConsulta;
fdQuery.Open();
if qryPesquisa.Active then qryPesquisa.Close;
if not fdQuery.IsEmpty then
begin
qryPesquisa.CreateFieldsFromDataSet(fdQuery);
qryPesquisa.LoadFromDataSet(fdQuery);
qryPesquisa.First;
tvPesquisa.ClearItems;
tvPesquisa.DataController.CreateAllItems;
grdPesquisa.SetFocus;
end;
finally
fdQuery.Close;
fdQuery.Connection.Close;
fdQuery.Free;
end;
end;
procedure TView_PesquisarPessoas.tvPesquisaCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
actSelecionarExecute(Sender);
end;
end.
|
unit cCadDepartamento;
interface
uses System.Classes, Vcl.Controls,
Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils;
// LISTA DE UNITS
type
TDepartamento = class
private
// VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE
ConexaoDB: TFDConnection;
F_cod_departamento: Integer;
F_nome_departamento: string;
F_sigla: string;
public
constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE
destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA
function Inserir: Boolean;
function Atualizar: Boolean;
function Apagar: Boolean;
function Selecionar(id: Integer): Boolean;
published
// VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE
// PARA FORNECER INFORMAÇÕESD EM RUMTIME
property cod_departamento: Integer read F_cod_departamento
write F_cod_departamento;
property nome_departamento: string read F_nome_departamento
write F_nome_departamento;
property sigla: string read F_sigla
write F_sigla;
end;
implementation
{$REGION 'Constructor and Destructor'}
constructor TDepartamento.Create;
begin
ConexaoDB := aConexao;
end;
destructor TDepartamento.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'CRUD'}
function TDepartamento.Apagar: Boolean;
var
Qry: TFDQuery;
begin
if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' +
IntToStr(F_cod_departamento) + #13 + 'Descrição: ' + F_nome_departamento,
mtConfirmation, [mbYes, mbNo], 0) = mrNO then
begin
Result := false;
Abort;
end;
Try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM tb_departamento WHERE cod_departamento=:cod_departamento; ');
Qry.ParamByName('cod_departamento').AsInteger := F_cod_departamento;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
Finally
if Assigned(Qry) then
FreeAndNil(Qry)
End;
end;
function TDepartamento.Atualizar: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE tb_departamento '+
' SET nome_departamento=:nome_departamento , sigla =:sigla WHERE cod_departamento=:cod_departamento');
Qry.ParamByName('cod_departamento').AsInteger := F_cod_departamento;
Qry.ParamByName('nome_departamento').AsString := F_nome_departamento;
Qry.ParamByName('sigla').AsString := F_sigla;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TDepartamento.Inserir: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO tb_departamento '+
'(nome_departamento,sigla) VALUES(:nome_departamento,:sigla) ');
Qry.ParamByName('nome_departamento').AsString := Self.F_nome_departamento;
Qry.ParamByName('sigla').AsString := Self.F_sigla;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TDepartamento.Selecionar(id: Integer): Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT cod_departamento, nome_departamento,sigla '+
'FROM tb_departamento WHERE cod_departamento=:cod_departamento ');
Qry.ParamByName('cod_departamento').AsInteger := id;
try
Qry.Open;
Self.F_cod_departamento := Qry.FieldByName('cod_departamento').AsInteger;
Self.F_nome_departamento := Qry.FieldByName('nome_departamento').AsString;
Self.F_sigla := Qry.FieldByName('sigla').AsString;
Except
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
{$ENDREGION}
end.
|
{* Given the side a of a square, find the perimeter *
* P of the square *
* P = 4 * a *}
unit Unit1;
interface
type
TSquare = class
function Square(a: Integer): Integer;
end;
implementation
{ TSquare }
function TSquare.Square(a: Integer): Integer;
begin
Result := Abs(4 * a);
end;
end.
|
unit HGM.Controls.EditPanel;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, HGM.Common;
type
TOnPressEnter = procedure(Sender:TObject; var AllowNext:Boolean) of object;
TEditPanel = class(TPanel)
private
FEdit:TEdit;
FLabel:TLabel;
FEnterColor:TColor;
FLeaveColor:TColor;
FEnter:Boolean;
FErrorColor:TColor;
FOnPressEnter:TOnPressEnter;
procedure EditKeyPress(Sender: TObject; var Key: Char);
procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure OnPanelEnter(Sender:TObject);
procedure OnPanelExit(Sender:TObject);
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure EditMouseEnter(Sender:TObject);
procedure EditMouseLeave(Sender:TObject);
procedure SetEnterColor(const Value: TColor);
procedure UpdateColor;
function GetEditWidth: Integer;
procedure SetEditWidth(const Value: Integer);
procedure UpdateLableSise;
function GetCaption: string;
procedure SetCaption(const Value: string);
procedure SetupInternalLabel;
procedure SetupInternalEdit;
function GetLabelWidth: Integer;
procedure SetLabelWidth(const Value: Integer);
function GetLabelFont: TFont;
procedure SetLabelFont(const Value: TFont);
function GetText: string;
procedure SetText(const Value: string);
function GetTextHint: string;
procedure SetTextHint(const Value: string);
function GetEditFont: TFont;
procedure SetEditFont(const Value: TFont);
procedure SetLeaveColor(const Value: TColor);
function GetAlignment: TAlignment;
procedure SetAlignment(const Value: TAlignment);
function GetLayout: TTextLayout;
procedure SetLayout(const Value: TTextLayout);
protected
procedure SetParent(AParent:TWinControl); override;
// property ShowCaption:Boolean; reintroduce;
public
constructor Create(AOwner: TComponent); override;
procedure ErrorFlash;
published
property Caption:string read GetCaption write SetCaption;
property EnterColor:TColor read FEnterColor write SetEnterColor;
property LeaveColor:TColor read FLeaveColor write SetLeaveColor;
property EditWidth:Integer read GetEditWidth write SetEditWidth;
property LebelWidth:Integer read GetLabelWidth write SetLabelWidth;
property LabelFont:TFont read GetLabelFont write SetLabelFont;
property EditFont:TFont read GetEditFont write SetEditFont;
property Text:string read GetText write SetText;
property TextHint:string read GetTextHint write SetTextHint;
property OnPressEnter:TOnPressEnter read FOnPressEnter write FOnPressEnter;
property Alignment:TAlignment read GetAlignment write SetAlignment;
property VerticalAlignment:TTextLayout read GetLayout write SetLayout;
property ErrorColor:TColor read FErrorColor write FErrorColor;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents(PackageName, [TEditPanel]);
end;
{ TEditPanel }
procedure TEditPanel.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var Frm: TCustomForm;
begin
if Key in [VK_UP] then
begin
Key:=0;
Frm:=GetParentForm(TCustomForm(Self));
if not (Frm = nil) then SendMessage(Frm.Handle, WM_NEXTDLGCTL, 1, 0);
end
else
if Key in [VK_DOWN] then
begin
Key:=0;
Frm:=GetParentForm(Self);
if not (Frm = nil) then SendMessage(Frm.Handle, WM_NEXTDLGCTL, 0, 0);
end;
end;
procedure TEditPanel.EditKeyPress(Sender: TObject; var Key: Char);
var AllowNext:Boolean;
var Frm: TCustomForm;
begin
if Key = #13 then
begin
Key:=#0;
AllowNext:=True;
if Assigned(FOnPressEnter) then FOnPressEnter(Sender, AllowNext);
if AllowNext then
begin
Frm:=GetParentForm(Self);
if not (Frm = nil) then SendMessage(Frm.Handle, WM_NEXTDLGCTL, 0, 0);
end;
end;
end;
procedure TEditPanel.SetupInternalEdit;
begin
//if Assigned(FEdit) then Exit;
FEdit:=TEdit.Create(Self);
FEdit.Parent:=Self;
FEdit.AutoSize:=False;
FEdit.Width:=200;
FEdit.AlignWithMargins:=True;
FEdit.Margins.Left:=5;
FEdit.Margins.Top:=10;
FEdit.Margins.Right:=10;
FEdit.Margins.Bottom:=10;
FEdit.Align:=alNone;
FEdit.Name:=Name+'FEdit';
FEdit.Text:='Текст';
FEdit.OnKeyDown:=EditKeyDown;
FEdit.OnKeyPress:=EditKeyPress;
FEdit.OnEnter:=EditMouseEnter;
FEdit.OnExit:=EditMouseLeave;
FEdit.Visible:=True;
end;
procedure TEditPanel.SetupInternalLabel;
begin
//if Assigned(FLabel) then Exit;
FLabel:=TLabel.Create(Self);
FLabel.Parent:=Self;
FLabel.AutoSize:=False;
FLabel.AlignWithMargins:=True;
FLabel.Margins.Left:=5;
FLabel.Margins.Top:=10;
FLabel.Margins.Right:=0;
FLabel.Margins.Bottom:=10;
FLabel.Align:=alNone;
FLabel.Alignment:=taLeftJustify;
FLabel.WordWrap:=True;
FLabel.Font.Color:=clGray;
FLabel.Layout:=tlCenter;
FLabel.Name:=Name+'FLabel';
FLabel.Caption:='Заголовок';
FLabel.OnClick:=OnPanelEnter;
FLabel.Width:=200;
FLabel.Visible:=True;
end;
constructor TEditPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEdit:=nil;
FLabel:=nil;
FErrorColor:=$000033CC;
Color:=clWhite;
FEnter:=False;
FEnterColor:=$0095E7FA;
FLeaveColor:=Color;
UpdateColor;
Width:=420;
BevelOuter:=bvNone;
ShowCaption:=False;
ParentBackground:=False;
OnEnter:=OnPanelEnter;
OnClick:=OnPanelEnter;
OnExit:=OnPanelExit;
SetupInternalLabel;
SetupInternalEdit;
VerticalAlignment:=tlCenter;
Alignment:=taLeftJustify;
Caption:='Заголовок';
Text:='';
TextHint:='';
UpdateLableSise;
end;
procedure TEditPanel.SetParent(AParent: TWinControl);
begin
inherited SetParent(AParent);
end;
procedure TEditPanel.SetText(const Value: string);
begin
FEdit.Text:=Value;
end;
procedure TEditPanel.SetTextHint(const Value: string);
begin
FEdit.TextHint:=Value;
end;
procedure TEditPanel.EditMouseEnter(Sender: TObject);
begin
FEnter:=True;
UpdateColor;
end;
procedure TEditPanel.EditMouseLeave(Sender: TObject);
begin
FEnter:=False;
UpdateColor;
end;
procedure TEditPanel.ErrorFlash;
var DefColor:TColor;
begin
DefColor:=Color;
Color:=FErrorColor;
Repaint;
Sleep(70);
Color:=DefColor;
Repaint;
Sleep(70);
Color:=FErrorColor;
Repaint;
Sleep(70);
Color:=DefColor;
Repaint;
end;
function TEditPanel.GetAlignment: TAlignment;
begin
Result:=FLabel.Alignment;
end;
function TEditPanel.GetCaption: string;
begin
Result:=FLabel.Caption;
end;
function TEditPanel.GetEditFont: TFont;
begin
Result:=FEdit.Font;
end;
function TEditPanel.GetEditWidth: Integer;
begin
Result:=FEdit.Width;
end;
function TEditPanel.GetLabelFont: TFont;
begin
Result:=FLabel.Font;
end;
function TEditPanel.GetLabelWidth: Integer;
begin
Result:=FLabel.Width;
end;
function TEditPanel.GetLayout: TTextLayout;
begin
Result:=FLabel.Layout;
end;
function TEditPanel.GetText: string;
begin
Result:=FEdit.Text;
end;
function TEditPanel.GetTextHint: string;
begin
Result:=FEdit.TextHint;
end;
procedure TEditPanel.OnPanelEnter(Sender: TObject);
begin
EditMouseEnter(Sender);
FEdit.SetFocus;
end;
procedure TEditPanel.OnPanelExit(Sender: TObject);
begin
EditMouseLeave(Sender);
end;
procedure TEditPanel.SetAlignment(const Value: TAlignment);
begin
FLabel.Alignment:=Value;
UpdateLableSise;
end;
procedure TEditPanel.SetCaption(const Value: string);
begin
FLabel.Caption:=Value;
end;
procedure TEditPanel.SetEditFont(const Value: TFont);
begin
FEdit.Font:=Value;
end;
procedure TEditPanel.SetEditWidth(const Value: Integer);
begin
FEdit.Width:=Value;
UpdateLableSise;
end;
procedure TEditPanel.SetEnterColor(const Value: TColor);
begin
FEnterColor:=Value;
UpdateColor;
end;
procedure TEditPanel.SetLabelFont(const Value: TFont);
begin
FLabel.Font:=Value;
end;
procedure TEditPanel.SetLabelWidth(const Value: Integer);
begin
FLabel.Width:=Value;
UpdateLableSise;
end;
procedure TEditPanel.SetLayout(const Value: TTextLayout);
begin
FLabel.Layout:=Value;
end;
procedure TEditPanel.SetLeaveColor(const Value: TColor);
begin
FLeaveColor:=Value;
UpdateColor;
end;
procedure TEditPanel.UpdateColor;
begin
case FEnter of
True: Color:=FEnterColor;
False:Color:=FLeaveColor;
end;
end;
procedure TEditPanel.UpdateLableSise;
begin
if (not Assigned(FLabel)) or (not Assigned(FEdit)) then Exit;
FLabel.Top:=FLabel.Margins.Top;
FLabel.Height:=Height - (FLabel.Margins.Top + FLabel.Margins.Bottom);
FLabel.Left:=FLabel.Margins.Left;
FEdit.Left:=FLabel.Left + FLabel.Width + FEdit.Margins.Left;
FEdit.Top:=FEdit.Margins.Top;
FEdit.Height:=Self.Height-(FEdit.Margins.Top + FEdit.Margins.Bottom);
Refresh;
end;
procedure TEditPanel.WMSize(var Message: TWMSize);
begin
UpdateLableSise;
end;
end.
|
Program Graphics;
{$apptype GUI}
Uses WinCrt, Graph;
Var GrDriver, GrMode: Integer;
{These vars are needed to initialize the graphics}
ch : char;
Begin
// ClrScr;
GrDriver := 0;
GrMode := 0;
//ShowWindow(GetActiveWindow,0);
InitGraph (GrDriver, GrMode, '');
{InitGraph is used to initialize the graphics mode}
If GraphResult <> 0 Then
{If an error occurs, print an error message}
Begin
WriteLn ('Couldn''t initialize graphics!');
Halt (0); {This will halt the program}
End;
Line (0, 0, 640, 480);
{Draw a line from point 0, 0 to 640, 480 on the screen}
{This line will be drawn from the top left corner}
{to the bottom right corner of the screen.}
Repeat
ch := ReadKey;
Until ch = #27;
{Repeat until ESC (chr value 27) is pressed}
CloseGraph;
{CloseGraph is used to clear the graph-memory
once the program is done.}
End.
|
unit KM_HandAI_Ext;
interface
uses
Windows, System.SysUtils,
KM_Consts, KM_Terrain,
ExtAIInfo, ExtAINetServer, ExtAIMsgActions, ExtAIMsgEvents, ExtAIMsgStates;
type
// Main AI class in the hands
TKMHandAI = class
protected
fHandIndex: TKMHandIndex;
public
constructor Create(aHandIndex: TKMHandIndex);
property HandIndex: TKMHandIndex read fHandIndex;
end;
// Special class for ExtAI in the hands
THandAI_Ext = class(TKMHandAI)
private
// Actions, Events, States
fActions: TExtAIMsgActions;
fEvents: TExtAIMsgEvents;
fStates: TExtAIMsgStates;
// ExtAI info, IDs, client server etc.
fExtAI: TExtAIInfo;
// Process actions
procedure GroupOrderAttackUnit(aGroupID, aUnitID: Integer);
procedure GroupOrderWalk(aGroupID, aX, aY, aDir: Integer);
procedure Log(aLog: UnicodeString);
// Process requests for states
{
TGroupOrderAttackUnit = procedure(aGroupID, aUnitID: Integer) of object;
TGroupOrderWalk = procedure(aGroupID, aX, aY, aDir: Integer) of object;
TLog = procedure(aLog: string) of object;
// Definition of states between ExtAI Client and KP Server
TTerrainSize = procedure(aX, aY: Word) of object;
TTerrainPassability = procedure(aPassability: TBoolArr) of object;
TTerrainFertility = procedure(aFertility: TBoolArr) of object;
}
public
constructor Create(aHandIndex: TKMHandIndex; aExtAI: TExtAIInfo);
destructor Destroy(); override;
// Actions, Events, States
property Actions: TExtAIMsgActions read fActions;
property Events: TExtAIMsgEvents read fEvents;
property States: TExtAIMsgStates read fStates;
procedure ConnectCallbacks(aExtAI: TExtAIInfo = nil);
procedure DisconnectCallbacks();
procedure MissionStart();
procedure MissionEnd();
procedure UpdateState(aTick: Cardinal);
end;
implementation
uses
ExtAILog;
{ TKMHandAI }
constructor TKMHandAI.Create(aHandIndex: TKMHandIndex);
begin
Inherited Create;
fHandIndex := aHandIndex;
end;
{ THandAI_Ext }
constructor THandAI_Ext.Create(aHandIndex: TKMHandIndex; aExtAI: TExtAIInfo);
begin
Inherited Create(aHandIndex);
// Declare main classes of Actions, Events and States
fActions := TExtAIMsgActions.Create();
fEvents := TExtAIMsgEvents.Create();
fStates := TExtAIMsgStates.Create();
// Prepare callbacks for actions
fActions.OnGroupOrderAttackUnit := GroupOrderAttackUnit;
fActions.OnGroupOrderWalk := GroupOrderWalk;
fActions.OnLog := Log;
// Connect callbacks
ConnectCallbacks(aExtAI);
gLog.Log('THandAIExt-Create: HandIndex = %d', [fHandIndex]);
end;
destructor THandAI_Ext.Destroy();
begin
DisconnectCallbacks();
fActions.Free;
fEvents.Free;
fStates.Free;
gLog.Log('THandAIExt-Destroy: HandIndex = %d', [fHandIndex]);
Inherited;
end;
procedure THandAI_Ext.ConnectCallbacks(aExtAI: TExtAIInfo = nil);
begin
if (aExtAI <> nil) then
begin
fExtAI := aExtAI;
fExtAI.HandIdx := fHandIndex;
end;
if (fExtAI <> nil) AND (fExtAI.ServerClient <> nil) then
begin
fExtAI.ServerClient.OnAction := fActions.ReceiveAction;
fExtAI.ServerClient.OnState := fStates.ReceiveState;
fStates.OnSendState := fExtAI.ServerClient.AddScheduledMsg;
fEvents.OnSendEvent := fExtAI.ServerClient.AddScheduledMsg;
end;
end;
procedure THandAI_Ext.DisconnectCallbacks();
begin
if (fExtAI <> nil) AND (fExtAI.ServerClient <> nil) then
begin
fExtAI.ServerClient.OnAction := nil;
fExtAI.ServerClient.OnState := nil;
fStates.OnSendState := nil;
fEvents.OnSendEvent := nil;
end;
end;
// Process actions (Check if the parameters are correct and create new GIP command)
procedure THandAI_Ext.GroupOrderAttackUnit(aGroupID, aUnitID: Integer);
begin
// Check if the parameters are correct
// Process the action
gLog.Log('THandAIExt-GroupOrderAttackUnit');
end;
procedure THandAI_Ext.GroupOrderWalk(aGroupID, aX, aY, aDir: Integer);
begin
// Check if the parameters are correct
// Process the action
gLog.Log('THandAIExt-GroupOrderWalk');
end;
procedure THandAI_Ext.Log(aLog: UnicodeString);
begin
gLog.Log(aLog);
end;
// Process events (or call directly for example HandAI_ext.Events.TickW(...))
procedure THandAI_Ext.MissionStart();
begin
Events.MissionStartW();
end;
procedure THandAI_Ext.MissionEnd();
begin
Events.MissionEndW();
end;
procedure THandAI_Ext.UpdateState(aTick: Cardinal);
begin
if (fExtAI = nil) OR (fExtAI.ServerClient = nil) then
begin
DisconnectCallbacks();
Exit;
end;
if (aTick = FIRST_TICK) then
States.TerrainSizeW(gTerrain.MapX, gTerrain.MapY); // Send terrain in the first tick (just for testing)
Events.TickW(aTick);
end;
// Process states (or call directly for example HandAI_ext.States.TerrainSizeW(...))
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StExpLog.pas 4.04 *}
{*********************************************************}
{* SysTools: Exception Logging *}
{*********************************************************}
{$I StDefine.inc}
unit StExpLog;
interface
uses
Windows, SysUtils, Classes, StBase;
type
TStOnExceptionFilter = procedure(Sender : TObject; E : Exception;
var PutInLog : Boolean) of object;
TStExceptionLog = class(TStComponent)
strict private class var
ExpLog : TStExceptionLog;
strict private
{ Property variables }
FEnabled : Boolean;
FFileName : TFileName;
FRipInfo : string;
{ Event variables }
FOnExceptionFilter : TStOnExceptionFilter;
public
constructor Create(Owner : TComponent); override;
destructor Destroy; override;
procedure DoExceptionFilter(E : Exception; var PutInLog : Boolean); virtual;
published
{ Published properties }
property Enabled : Boolean read FEnabled write FEnabled default True;
property FileName : TFileName read FFileName write FFileName;
property RipInfo : string read FRipInfo write FRipInfo;
{ Published events }
property OnExceptionFilter : TStOnExceptionFilter
read FOnExceptionFilter write FOnExceptionFilter;
end;
implementation
{ TStExceptionLog }
constructor TStExceptionLog.Create(Owner : TComponent);
begin
inherited Create(Owner);
ExpLog := Self;
FEnabled := True;
end;
destructor TStExceptionLog.Destroy;
begin
ExpLog := nil;
inherited;
end;
procedure TStExceptionLog.DoExceptionFilter(E : Exception; var PutInLog : Boolean);
begin
if Assigned(FOnExceptionFilter) then
FOnExceptionFilter(Self, E, PutInLog);
end;
end.
|
unit SoundLib;
interface
uses
Windows, DirectSound, SysUtils;
const
skClass = -1;
skUser = 5;
type
ESoundError = class(Exception);
function InitSoundLibrary(focus : hWnd) : boolean;
procedure DoneSoundLibrary;
function GetDSoundInstance : IDirectSound;
// function GetLibStatus : integer;
procedure InitDSoundEngine(Wnd : HWND);
procedure DoneDSoundEngine;
procedure EnableSounds;
procedure DisableSounds;
function LoadSoundFromFile(const FileName : string) : boolean;
function LoadSoundFromModule(Handle : HModule; const ResName : string) : boolean;
function LoadSoundFromResName(const ResName : string) : boolean;
procedure UnloadSound(const Name : string);
procedure UnloadAllSounds;
function SoundLength(const Name : string; Kind : integer) : integer;
procedure PlaySound(const Name : string; Kind : integer; Looped : boolean; pan, volume : single; startofs : integer);
procedure StopSound(const Name : string; Kind : integer);
procedure PauseSound(const Name : string; Kind : integer);
procedure ResumeSound(const Name : string; Kind : integer);
procedure SetSoundPan(const Name : string; Kind : integer; pan : single);
procedure SetSoundVolume(const Name : string; Kind : integer; volume : single);
procedure StopAllSounds;
procedure PauseAllSounds;
procedure ResumeAllSounds;
implementation
uses
Classes, ActiveX,
MapStringToObject, WaveLow, LowStuff;
var
SoundMap : TMapStringToObject = nil;
gInstanceList : TList = nil;
SoundsEnabled : boolean = false;
{ DirectSound DLL dirty stuff}
// const
// SoundLibraryPath = 'SoundLib.dll';
type
TReadCallback = procedure(Data : pointer; Size : DWORD; UserData : pointer); stdcall;
TSoundBuffer = IDirectSoundBuffer;
{
type
TInitSoundEngine = function(Wnd : HWND) : BOOL; cdecl;
TDoneSoundEngine = procedure; cdecl;
TCreateSound = function(var Buffer : TSoundBuffer; Size, Freq, Bits, Align : DWORD; Stereo : BOOL) : BOOL; cdecl;
TFillSound = function(Buffer : TSoundBuffer; Size : DWORD; ReadData : TReadCallback; UserData : pointer) : BOOL; cdecl;
TStopsSound = procedure(Buffer : TSoundBuffer); cdecl;
TPlaysSound = procedure(Buffer : TSoundBuffer; LoopIt, RestartIt : BOOL; Pan, Volume, StartOfs : integer); cdecl;
TDuplicateSound = procedure(Buffer : TSoundBuffer; var Clone : TSoundBuffer); cdecl;
TSetsSoundPan = procedure(Buffer : TSoundBuffer; Pan : integer); cdecl;
TSetsSoundVolume = procedure(Buffer : TSoundBuffer; Volume : integer); cdecl;
TGetDSound = function : IDirectSound; cdecl;
TGetLibStatus = function : integer; cdecl;
var
hLibrary : THandle = 0;
function LoadSoundLib(Wnd : HWND) : BOOL; cdecl; forward;
var
InitSoundEngine : TInitSoundEngine = LoadSoundLib;
DoneSoundEngine : TDoneSoundEngine = nil;
CreateSound : TCreateSound = nil;
FillSound : TFillSound = nil;
StopsSound : TStopsSound = nil;
PlaysSound : TPlaysSound = nil;
DuplicateSound : TDuplicateSound = nil;
SetsSoundPan : TSetsSoundPan = nil;
SetsSoundVolume : TSetsSoundVolume = nil;
GetDSound : TGetDSound = nil;
LibStatus : TGetLibStatus = nil;
} //.rag
function LoadSoundLib(Wnd : HWND) : BOOL; cdecl;
begin
{hLibrary := LoadLibrary(SoundLibraryPath);
if hLibrary <> 0
then
begin
InitSoundEngine := GetProcAddress(hLibrary, 'InitSoundEngine');
DoneSoundEngine := GetProcAddress(hLibrary, 'DoneSoundEngine');
CreateSound := GetProcAddress(hLibrary, 'CreateSound');
FillSound := GetProcAddress(hLibrary, 'FillSound');
StopsSound := GetProcAddress(hLibrary, 'StopsSound');
PlaysSound := GetProcAddress(hLibrary, 'PlaysSound');
DuplicateSound := GetProcAddress(hLibrary, 'DuplicateSound');
SetsSoundPan := GetProcAddress(hLibrary, 'SetsSoundPan');
SetsSoundVolume := GetProcAddress(hLibrary, 'SetsSoundVolume');
GetDSound := GetProcAddress(hLibrary, 'GetDSound');
LibStatus := GetProcAddress(hLibrary, 'GetStatus');
Result := Assigned(InitSoundEngine) and
Assigned(DoneSoundEngine) and
Assigned(CreateSound) and
Assigned(FillSound) and
Assigned(StopsSound) and
Assigned(PlaysSound) and
Assigned(DuplicateSound) and
Assigned(GetDSound) and
InitSoundEngine(Wnd);
if not Result
then FreeLibrary(hLibrary);}//.rag
Result := InitSoundEngine(Wnd);
{ end
else
Result := false;}//.rag
end;
{ REAL thing }
type
TSoundState = (sstStopped, sstPlaying, sstPaused);
TSoundInfo =
class
public
constructor Create(aSound : IDirectSoundBuffer; const aName : string; aKind, Length : integer);
destructor Destroy; override;
public
function Clone(aKind : integer) : TSoundInfo;
public
procedure Play(aLooped : boolean; pan, volume : single; startofs : integer);
procedure SetPan(pan : single);
procedure SetVolume(volume : single);
procedure Stop;
procedure Pause;
procedure Resume;
private
fState : TSoundState;
fLooped : boolean;
fPan : integer;
fVolume : integer;
fSound : IDirectSoundBuffer;
fName : string;
fKind : integer;
fLength : integer;
public
property Name : string read fName;
property Kind : integer read fKind;
property Length : integer read fLength;
end;
const
MaxPan = 10000;
MaxVolume = 10000;
constructor TSoundInfo.Create(aSound : IDirectSoundBuffer; const aName : string; aKind, Length : integer);
begin
inherited Create;
fSound := aSound;
fState := sstStopped;
fName := aName;
fKind := aKind;
fLength := Length;
end;
destructor TSoundInfo.Destroy;
begin
Stop;
inherited;
end;
function TSoundInfo.Clone(aKind : integer) : TSoundInfo;
var
NewSound : TSoundBuffer;
begin
if SoundsEnabled
then
begin
DuplicateSound(fSound, NewSound);
if NewSound <> nil
then Result := TSoundInfo.Create(NewSound, fName, aKind, fLength)
else Result := nil;
end
else result := nil;
end;
procedure TSoundInfo.Play(aLooped : boolean; pan, volume : single; startofs : integer);
begin
fPan := trunc(pan * MaxPan);
fVolume := trunc((volume - 1) * MaxVolume);
PlaysSound(fSound, aLooped, true, fPan, fVolume, startofs);
fLooped := aLooped;
fState := sstPlaying;
end;
procedure TSoundInfo.SetPan(pan : single);
begin
fPan := trunc(pan * MaxPan);
SetsSoundPan(fSound, fPan);
end;
procedure TSoundInfo.SetVolume(volume : single);
begin
fVolume := trunc((volume - 1) * MaxVolume);
SetsSoundVolume(fSound, fVolume);
end;
procedure TSoundInfo.Stop;
begin
StopsSound(fSound);
fState := sstStopped;
end;
procedure TSoundInfo.Pause;
begin
if fState = sstPlaying
then
begin
StopsSound(fSound);
if not fLooped
then fState := sstStopped
else fState := sstPaused;
end;
end;
procedure TSoundInfo.Resume;
begin
if fState = sstPaused
then
begin
PlaysSound(fSound, fLooped, true, fPan, fVolume, 0);
fState := sstPlaying;
end;
end;
// ListUtils
procedure ClearList(aList : TList);
var
i : integer;
begin
if aList <> nil
then
begin
for i := 0 to pred(aList.Count) do
TObject(aList[i]).Free;
aList.Clear;
end;
end;
procedure FreeList(var aList : TList);
begin
ClearList(aList);
aList.Free;
aList := nil;
end;
// Sound library
function InitSoundLibrary(focus : hWnd) : boolean;
begin
if InitSoundEngine(focus)
then
begin
SoundMap := TMapStringToObject.Create(mmOwn);
gInstanceList := TList.Create;
SoundsEnabled := true;
end
else SoundsEnabled := false;
Result := SoundsEnabled;
end;
procedure DoneSoundLibrary;
begin
FreeList(gInstanceList);
SoundMap.Free;
{if hLibrary <> 0
then
begin
DoneSoundEngine;
FreeLibrary(hLibrary);
end;}//.rag
DoneSoundEngine;
end;
function GetDSoundInstance : IDirectSound;
// var
// ds : integer; //.rag
begin
try
(* ds := GetLibStatus;
if ds <> 0
then result := IDirectSound(ds)
else result := nil;
{
if assigned(GetDSound)
then result := GetDSound
else result := nil;
}
*) result := GetDSound;
except
result := nil;
end;
end;
{ function GetLibStatus : integer;
begin
if assigned(LibStatus)
then result := LibStatus
else result := -1;
end;
}
procedure InitDSoundEngine( Wnd : HWND );
begin
{if assigned(InitSoundEngine)
then}//.RAG
begin
InitSoundEngine( Wnd );
EnableSounds;
end;
end;
procedure DoneDSoundEngine;
begin
{if assigned(DoneSoundEngine)
then}//.rag
begin
DisableSounds;
UnloadAllSounds;
DoneSoundEngine;
end
end;
procedure EnableSounds;
begin
SoundsEnabled := SoundMap <> nil;
end;
procedure DisableSounds;
begin
StopAllSounds;
SoundsEnabled := false;
end;
// Read callback
procedure ReadData(Data : pointer; Size : DWORD; UserData : pointer); stdcall;
var
S : TStream absolute UserData;
begin
S.Read(Data^, Size);
end;
function ReadSoundFromStream(Stream : TStream; const Name : string; out SndLen : integer) : TSoundBuffer;
var
Header : TWaveHeader;
dLen : integer;
begin
try
Stream.Read(Header, sizeof(Header));
with Header do
begin
GetDataFromStream(Stream, dLen);
if not CreateSound(Result, dLen, nSamplesPerSec, nBitsPerSample, nBlockAlign, nChannels > 1)
then raise Exception.Create('Cannot load sound : ' + Name);
if not FillSound(Result, dLen, ReadData, Stream)
then
begin
Result := nil;
raise Exception.Create('Cannot read sound data from ' + Name);
end;
SndLen := dLen;
end;
except
Result := nil;
end;
end;
function LoadSoundFromFile(const FileName : string) : boolean;
var
Sound : TSoundBuffer;
Stream : TStream;
SndLen : integer;
begin
if SoundMap <> nil
then
if SoundMap[FileName] = nil
then
if FileExists(FileName)
then
try
Stream := TFileStream.Create(FileName, fmOpenRead);
try
Sound := ReadSoundFromStream(Stream, FileName, SndLen);
if Sound <> nil
then
begin
SoundMap[FileName] := TSoundInfo.Create(Sound, FileName, skClass, SndLen);
Result := true;
end
else Result := false;
finally
Stream.Free;
end;
except
Result := false;
end
else Result := false
else Result := true
else Result := false;
end;
function LoadSoundFromModule(Handle : HModule; const ResName : string) : boolean;
var
Sound : TSoundBuffer;
Stream : TStream;
SndLen : integer;
begin
if SoundMap <> nil
then
if SoundMap[ResName] = nil
then
try
Stream := TResourceStream.Create(Handle, ResName, RT_RCDATA);
try
Sound := ReadSoundFromStream(Stream, ResName, SndLen);
if Sound <> nil
then
begin
SoundMap[ResName] := TSoundInfo.Create(Sound, ResName, skClass, SndLen);
Result := true;
end
else Result := false;
finally
Stream.Free;
end;
except
Result := false;
end
else Result := true
else Result := false;
end;
function LoadSoundFromResName(const ResName : string) : boolean;
begin
Result := LoadSoundFromModule(hInstance, ResName);
end;
procedure UnloadSound(const Name : string);
begin
if SoundMap <> nil
then SoundMap.Remove(Name);
end;
procedure UnloadAllSounds;
begin
StopAllSounds;
if SoundMap <> nil
then SoundMap.Clear;
end;
// Utils
function GetExistingSoundInstance(const Name : string; Kind : integer) : TSoundInfo;
var
i : integer;
Instance : TSoundInfo;
begin
if gInstanceList <> nil
then
begin
i := 0;
Result := nil;
while (i < gInstanceList.Count) and (Result = nil) do
begin
Instance := gInstanceList[i];
if (Instance.Name = Name) and (Instance.Kind = Kind)
then Result := Instance;
inc(i);
end;
end
else
Result := nil;
end;
function GetSoundInstance(const Name : string; Kind : integer) : TSoundInfo;
var
SoundClass : TSoundInfo;
begin
Result := GetExistingSoundInstance(Name, Kind);
if Result = nil
then
begin
SoundClass := TSoundInfo(SoundMap[Name]);
if SoundClass <> nil
then
begin
Result := SoundClass.Clone(Kind);
if Result <> nil
then gInstanceList.Add(Result);
end;
end;
end;
procedure FreeSoundInstance(const Name : string; Kind : integer);
var
Instance : TSoundInfo;
begin
Instance := GetExistingSoundInstance(Name, Kind);
if Instance <> nil
then
begin
Instance.Stop;
gInstanceList.Remove(Instance);
Instance.Free;
end;
end;
function SoundLength(const Name : string; Kind : integer) : integer;
var
Sound : TSoundInfo;
begin
Sound := GetSoundInstance(Name, Kind);
if Sound <> nil
then Result := Sound.Length
else raise ESoundError.Create('Sound ' + Name + ' not loaded');
end;
// Sound control
procedure PlaySound(const Name : string; Kind : integer; Looped : boolean; pan, volume : single; startofs : integer);
var
Sound : TSoundInfo;
begin
if SoundsEnabled and (Name<>'')
then
begin
Sound := GetSoundInstance(Name, Kind);
if Sound <> nil
then Sound.Play(Looped, pan, volume, startofs)
else raise ESoundError.Create('Sound ' + Name + ' not loaded');
end;
end;
procedure StopSound(const Name : string; Kind : integer);
begin
if SoundsEnabled
then FreeSoundInstance(Name, Kind);
end;
procedure PauseSound(const Name : string; Kind : integer);
var
Sound : TSoundInfo;
begin
if SoundsEnabled
then
begin
Sound := GetSoundInstance(Name, Kind);
if Sound <> nil
then Sound.Pause;
end;
end;
procedure ResumeSound(const Name : string; Kind : integer);
var
Sound : TSoundInfo;
begin
if SoundsEnabled
then
begin
Sound := GetSoundInstance(Name, Kind);
if Sound <> nil
then Sound.Resume;
end;
end;
procedure SetSoundPan(const Name : string; Kind : integer; pan : single);
var
Sound : TSoundInfo;
begin
if SoundsEnabled
then
begin
Sound := GetSoundInstance(Name, Kind);
if Sound <> nil
then Sound.SetPan(pan);
end;
end;
procedure SetSoundVolume(const Name : string; Kind : integer; volume : single);
var
Sound : TSoundInfo;
begin
if SoundsEnabled
then
begin
Sound := GetSoundInstance(Name, Kind);
if Sound <> nil
then Sound.SetVolume(volume);
end;
end;
procedure StopAllSounds;
begin
if SoundsEnabled
then ClearList(gInstanceList);
end;
procedure PauseAllSounds;
var
i : integer;
begin
if SoundsEnabled and (gInstanceList <> nil)
then
for i := 0 to pred(gInstanceList.Count) do
TSoundInfo(gInstanceList[i]).Pause;
end;
procedure ResumeAllSounds;
var
i : integer;
begin
if SoundsEnabled and (gInstanceList <> nil)
then
for i := 0 to pred(gInstanceList.Count) do
TSoundInfo(gInstanceList[i]).Resume;
end;
end.
|
(******************************************************************)
(* SFX for DelZip v1.8 *)
(* Copyright 2002-2004, 2008 *)
(* *)
(* written by Markus Stephany *)
(* modified by Russell Peters, Roger Aelbrecht
Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht,
Eric W. Engler and Chris Vleghert.
This file is part of TZipMaster Version 1.9.
TZipMaster is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TZipMaster 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TZipMaster. If not, see <http://www.gnu.org/licenses/>.
contact: problems@delphizip.org (include ZipMaster in the subject).
updates: http://www.delphizip.org
DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip
modified 30-Jan-2008
---------------------------------------------------------------------------*)
unit ZMSFXVars19;
{
contains all global variables used
by delzip sfx.
}
interface
uses
Windows, ZMSFXDefs19, ZMSFXInt19, ZMSFXStructs19;
var
// the sfx file haeder read from InFile
VRec_SFXHeader: TSFXFileHeader;
{ TSFXFileHeader strings }
// caption of the main dialog
VStr_SFX_Caption,
// message to show before opening the main dialog
VStr_SFX_StartMsg,
// command line read from the special header
VStr_SFX_CmdLine,
// default extract path used if reading path from registry failed
VStr_SFX_RegFailPath,
// the default-directory stored in the special header
VStr_SFX_Path: string;
// may 08, 2002: paramstr(0) replacement
VStr_ExeName: string;
{zip processing stuff }
// crc32 table for unzipping
VArr_CRC32Table: TCRC32Table;
// Running CRC (32 bit) value
VDW_CRC32Val: Cardinal;
// encryption key
VArr_CryptKey: array[0..2] of longint;
// archived file packed size
VInt_BytesToGo: Int64;//longint;
// protect from bombs
VInt_MaxWrite: Int64;
// input file (i myself)
VH_InFile: THandle = INVALID_HANDLE_VALUE;
// file to be written
VH_OutFile: THandle = INVALID_HANDLE_VALUE;
// central zip file header
VRec_ZipHeader: TZ64CentralEntry;
// file being extracted
VStr_CurrentFile: string;
// handle of the main window
VH_MainWnd: hWnd;
// password from input box
VStr_Password: AnsiString = '';
// actual extract path
VStr_ExtractPath: string = '';
// current file position
VDW_CurrentFilePos: Int64;//Cardinal;
// position of the TSFXFileHeader/ start of zip archive in the file
VInt_FileBegin: {Int64;//}longint;
// cancelled by user (WM_CLOSE during Extract)
VBool_Cancelled: boolean;
// possibly moved offset is stored here (wrong sfx creation)
VDW_OffsetDelta: Int64;//cardinal;
// shell image list handle
VH_ShellImageList: THandle;
// check volatile extract directory deletion
VBool_CheckDeleteVolatilePath: Boolean = False;
VStr_VolatilePath: string;
VStr_VolatilePath_Unexpanded: string;
// currently open file
VStr_OutFile: string='';
// detached archive support
VH_TempFile: THandle = INVALID_HANDLE_VALUE; // temp file for spanning archive data
VStr_TempFile: string = ''; // dito
VInt_SpanType: integer = 0; // 0: not spanned, 1 (SFXSpanTypeSpanned): disk spanning, 2 (SFXSpanTypeMultiVol): multiple archives in one directory (xyz001.zip, xyz002.zip ...)
VStr_DetachName: string; // name of the detached archive the sfx belongs to
VStr_DetachExt: string; // file ext of the detached archive the sfx belongs to
VBool_FixedDrive: boolean; // is drive fixed or removable
VStr_SourceDir: string; // source directory of the spanned archives
// multi-language support
// VRec_Strings: PWord = nil; // pointer to table of strings
VP_SBuf: pByte = nil;
// VRec_SHeader: TSFXStringsHeader;
// VInt_LangOfs: longint = 0; // offset of Langs header
// VP_Langs: PSFXStringsHeader = nil; // pointer to available languages
VInt_CP: Integer = 0; // selected codepage
VInt_CurLang: integer = 0; // selected language entry
// VRec_Langs: PSFXStringsEntry = nil; // pointer to available languages
// VStr_Lang: string = ''; // the selected langauge
// VInt_CmdLineSize: integer = 0;
{$ifdef DEBUG_SFX}
Test_Stub_Size: Integer = 0;
{$ENDIF}
VInt_LastSeq: Integer = -1;
implementation
end.
|
Program FuncionDelete;
//tiene la misma funcion que el delete en pascal
Var
s,saux:string;
inicio,cantidad,salida,i:integer;
Begin
Repeat
Write('Introduzca string a borrar => '); Readln(s);
Write('Introduzca posicion de inicio => '); Readln(inicio);
Write('Introduzca cantidad de caracteres a eliminar => '); Readln(cantidad);
saux:='';
if(inicio <= length(s)) then
begin
for i:=1 to (inicio-1) do
saux:= saux + s[i];
if((inicio+cantidad) <= length(s)) then
for i:= (inicio+cantidad) to length(s) do
saux:= saux + s[i];
s:= saux;
end;
writeln('La string resultante es ', s);
Write('Escriba 1 para salir => '); Readln(salida);
until (salida=1);
End. |
unit RxSystemServices;
{$mode objfpc}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs;
type
TRxServiceType = (sstAll, sstService, sstDrivers);
TRxServiceStatus = (sssAll, sssActive, sssInactive);
TRxServiceState = (srsStoped, //SERVICE_STOPPED : S := 'Сервис не запущен'
srsStartPending, //SERVICE_START_PENDING : S := 'Сервис в процессе запуска';
srsStopPending, //SERVICE_STOP_PENDING : S := 'Сервис в процессе завершения';
srsRunning, //SERVICE_RUNNING : S := 'Сервис запущен';
srsContinuePending, //SERVICE_CONTINUE_PENDING : S := 'Сервис в процессе запуска после временной оснановки';
srsPausePending, //SERVICE_PAUSE_PENDING : S := 'Сервис в процессе временной оснановки';
srsPaused //SERVICE_PAUSED : S := 'Сервис временно оснановлен';
);
TRxServiceItem = record
Name:string;
Description:string;
Status:TRxServiceState;
end;
type
{ TRxSystemServices }
TRxSystemServices = class(TComponent)
private
FItemCount: integer;
FServerName: string;
FServiceStatus: TRxServiceStatus;
FServiceType: TRxServiceType;
function GetItems(Index: integer): TRxServiceItem;
procedure SetItemCount(const AValue: integer);
procedure SetItems(Index: integer; const AValue: TRxServiceItem);
procedure SetServerName(const AValue: string);
procedure SetServiceStatus(const AValue: TRxServiceStatus);
procedure SetServiceType(const AValue: TRxServiceType);
protected
procedure ClearItems;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Items[Index:integer]:TRxServiceItem read GetItems write SetItems;
property ItemCount:integer read FItemCount write SetItemCount;
published
property ServerName:string read FServerName write SetServerName;
property ServiceType:TRxServiceType read FServiceType write SetServiceType; //(sstAll, sstService, sstDrivers);
property ServiceStatus:TRxServiceStatus read FServiceStatus write SetServiceStatus; //(sssAll, sssActive, sssInactive);
end;
implementation
{ TRxSystemServices }
procedure TRxSystemServices.SetServerName(const AValue: string);
begin
if FServerName=AValue then exit;
FServerName:=AValue;
end;
function TRxSystemServices.GetItems(Index: integer): TRxServiceItem;
begin
end;
procedure TRxSystemServices.SetItemCount(const AValue: integer);
begin
if FItemCount=AValue then exit;
FItemCount:=AValue;
end;
procedure TRxSystemServices.SetItems(Index: integer;
const AValue: TRxServiceItem);
begin
end;
procedure TRxSystemServices.SetServiceStatus(const AValue: TRxServiceStatus);
begin
if FServiceStatus=AValue then exit;
FServiceStatus:=AValue;
end;
procedure TRxSystemServices.SetServiceType(const AValue: TRxServiceType);
begin
if FServiceType=AValue then exit;
FServiceType:=AValue;
end;
procedure TRxSystemServices.ClearItems;
begin
FItemCount:=0;
end;
constructor TRxSystemServices.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TRxSystemServices.Destroy;
begin
ClearItems;
inherited Destroy;
end;
end.
|
unit Fields;
interface
uses
// VCL
Classes, SysUtils;
type
TField = class;
TFields = class(TComponent)
private
function GetCount: Integer;
function GetField(Index: Integer): TField;
public
procedure Clear;
procedure SetDefaults;
function Add: TField;
procedure SaveToStream(Dst: TStream);
procedure LoadFromStream(Src: TStream);
property Count: Integer read GetCount;
property Items[Index: Integer]: TField read GetField; default;
end;
TField = class(TComponent)
private
FValue: string;
FCaption: string;
FMinValue: Integer;
FMaxValue: Integer;
FRowNumber: Integer;
FFieldNumber: Integer;
FTableNumber: Integer;
FPropertyName: string;
FDefaultValue: string;
function GetAsString: string;
procedure SetAsString(const Value: string);
public
procedure SaveToStream(Stream: TStream);
procedure LoadFromStream(Stream: TStream);
published
property Caption: string read FCaption write FCaption;
property AsString: string read GetAsString write SetAsString;
property PropertyName: string read FPropertyName write FPropertyName;
property DefaultValue: string read FDefaultValue write FDefaultValue;
property MinValue: Integer read FMinValue write FMinValue;
property MaxValue: Integer read FMaxValue write FMaxValue;
property TableNumber: Integer read FTableNumber write FTableNumber;
property RowNumber: Integer read FRowNumber write FRowNumber;
property FieldNumber: Integer read FFieldNumber write FFieldNumber;
end;
implementation
{ TFields }
function TFields.Add: TField;
begin
Result := TField.Create(Self);
end;
procedure TFields.Clear;
begin
DestroyComponents;
end;
function TFields.GetCount: Integer;
begin
Result := ComponentCount;
end;
function TFields.GetField(Index: Integer): TField;
begin
Result := Components[Index] as TField;
end;
procedure TFields.LoadFromStream(Src: TStream);
var
i: Integer;
begin
for i := 0 to Count-1 do
begin
if Src.Position < Src.Size then
Items[i].LoadFromStream(Src);
end;
end;
procedure TFields.SaveToStream(Dst: TStream);
var
i: Integer;
begin
for i := 0 to Count-1 do
Items[i].SaveToStream(Dst);
end;
procedure TFields.SetDefaults;
var
i: Integer;
begin
for i := 0 to Count-1 do
Items[i].AsString := Items[i].DefaultValue;
end;
{ TField }
function TField.GetAsString: string;
begin
Result := FValue;
end;
procedure TField.LoadFromStream(Stream: TStream);
begin
Stream.ReadComponent(Self);
end;
procedure TField.SaveToStream(Stream: TStream);
begin
Stream.WriteComponent(Self);
end;
procedure TField.SetAsString(const Value: string);
var
S: string;
begin
if (StrToInt(Value) < MinValue)or(StrToInt(Value) > MaxValue) then
begin
S := 'Неверное значение поля "%s" (%s).'#13#10;
S := S + 'Значения поля должны находиться в диапазоне %d..%d.';
S := Format(S, [Caption, Value, MinValue, MaxValue]);
raise Exception.Create(S);
end;
FValue := Value;
end;
end.
|
unit UpgradeFacTask;
interface
uses
Tasks, Kernel, Accounts, CacheAgent, BackupInterfaces, Inventions, FacIds;
type
TMetaUpgradeFacTask =
class(TMetaTask)
private
fFacId : TFacId;
public
property FacId : integer read fFacId write fFacId;
end;
TUpgradeFacTask =
class(TAtomicTask)
public
Upgraded : boolean;
public
function Execute : TTaskResult; override;
private
procedure MsgUpgradedFac(var Msg : TMsgFacUpgraded); message msgKernel_FacUpgraded;
end;
procedure RegisterBackup;
implementation
uses
TaskUtils, ResidentialTasks, ClassStorage;
// TUpgradeFacTask
procedure TUpgradeFacTask.MsgUpgradedFac(var Msg : TMsgFacUpgraded);
begin
if (Msg.Fac <> nil) and (Msg.Fac.MetaFacility.FacId = TMetaUpgradeFacTask(MetaTask).FacId)
then
Upgraded := True;
end;
function TUpgradeFacTask.Execute : TTaskResult;
//var
//Msg : TBlockOverloadedMsg;
begin
{Msg.Msg := msgBlockOverloaded;
Fac.CurrBlock.Dispatch(Msg);
if Msg.Result = 1
then
result := trFinished
else
begin}
if Upgraded
then result := trFinished
else result := trContinue;
//end;
end;
procedure RegisterBackup;
begin
RegisterClass(TUpgradeFacTask);
end;
end.
|
unit account;
interface
type
IAccountModel = interface
['{3ADB0592-AC32-44C0-B276-46184083B3C2}']
function id: String; overload;
function id(const AValue: String): IAccountModel; overload;
function name: String; overload;
function name(const AValue: String): IAccountModel; overload;
function email: String; overload;
function email(const AValue: String): IAccountModel; overload;
function password: String; overload;
function password(const AValue: String): IAccountModel; overload;
end;
TAccountModel = class(TInterfacedObject, IAccountModel)
private
FID: String;
FName: String;
FEmail: String;
FPassword: String;
function id: String; overload;
function id(const AValue: String): IAccountModel; overload;
function name: String; overload;
function name(const AValue: String): IAccountModel; overload;
function email: String; overload;
function email(const AValue: String): IAccountModel; overload;
function password: String; overload;
function password(const AValue: String): IAccountModel; overload;
public
class function New: IAccountModel;
end;
implementation
function TAccountModel.email: String;
begin
result := FEmail;
end;
function TAccountModel.email(const AValue: String): IAccountModel;
begin
FEmail := AValue;
result := Self;
end;
function TAccountModel.id(const AValue: String): IAccountModel;
begin
FID := AValue;
result := Self;
end;
function TAccountModel.id: String;
begin
result := FID;
end;
function TAccountModel.name(const AValue: String): IAccountModel;
begin
FName := AValue;
result := Self;
end;
function TAccountModel.name: String;
begin
result := FName;
end;
class function TAccountModel.New: IAccountModel;
begin
result := Self.Create;
end;
function TAccountModel.password: String;
begin
result := FPassword;
end;
function TAccountModel.password(const AValue: String): IAccountModel;
begin
FPassword := AValue;
result := Self;
end;
end.
|
unit nsPrimAdapterNode;
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\Tree\nsPrimAdapterNode.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TnsPrimAdapterNode" MUID: (4ADDF4110392)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3IntfUses
, nsPrimNode
, BaseTreeSupportUnit
, l3IID
, l3TreeInterfaces
;
type
TnsPrimAdapterNode = {abstract} class(TnsPrimNode)
private
f_AdapterNode: INode;
protected
procedure Cleanup; override;
{* Функция очистки полей объекта. }
function COMQueryInterface(const IID: Tl3GUID;
out Obj): Tl3HResult; override;
{* Реализация запроса интерфейса }
function GetIsSame(const aNode: Il3SimpleNode): Boolean; override;
function GetLevelForParent(const aNode: Il3SimpleNode): Integer; override;
procedure ClearFields; override;
public
constructor Create(const aNode: INode;
aNumInParent: Integer); reintroduce;
protected
property AdapterNode: INode
read f_AdapterNode
write f_AdapterNode;
end;//TnsPrimAdapterNode
implementation
uses
l3ImplUses
, SysUtils
, l3InterfacesMisc
//#UC START# *4ADDF4110392impl_uses*
//#UC END# *4ADDF4110392impl_uses*
;
constructor TnsPrimAdapterNode.Create(const aNode: INode;
aNumInParent: Integer);
//#UC START# *4AE02DE00365_4ADDF4110392_var*
//#UC END# *4AE02DE00365_4ADDF4110392_var*
begin
//#UC START# *4AE02DE00365_4ADDF4110392_impl*
inherited Create(aNumInParent);
AdapterNode := aNode;
//#UC END# *4AE02DE00365_4ADDF4110392_impl*
end;//TnsPrimAdapterNode.Create
procedure TnsPrimAdapterNode.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4ADDF4110392_var*
//#UC END# *479731C50290_4ADDF4110392_var*
begin
//#UC START# *479731C50290_4ADDF4110392_impl*
AdapterNode := nil;
inherited;
//#UC END# *479731C50290_4ADDF4110392_impl*
end;//TnsPrimAdapterNode.Cleanup
function TnsPrimAdapterNode.COMQueryInterface(const IID: Tl3GUID;
out Obj): Tl3HResult;
{* Реализация запроса интерфейса }
//#UC START# *4A60B23E00C3_4ADDF4110392_var*
var
l_AdapterNode : INode;
//#UC END# *4A60B23E00C3_4ADDF4110392_var*
begin
//#UC START# *4A60B23E00C3_4ADDF4110392_impl*
if IID.EQ(INode) then
begin
l_AdapterNode := AdapterNode;
if (l_AdapterNode = nil) then
Result.SetNOINTERFACE
else
begin
Result.SetOk;
INode(Obj) := l_AdapterNode;
end;//l_AdapterNode = nil
end//IID.EQ(INode)
else
begin
Result := inherited COMQueryInterface(IID, Obj);
if Result.fail then
begin
l_AdapterNode := AdapterNode;
if (l_AdapterNode = nil) then
Result.SetNOINTERFACE
else
Result := Tl3HResult_C(l_AdapterNode.QueryInterface(IID.IID, Obj));
end;//l3IFail(Result)
end;//IID.EQ(INode)
//#UC END# *4A60B23E00C3_4ADDF4110392_impl*
end;//TnsPrimAdapterNode.COMQueryInterface
function TnsPrimAdapterNode.GetIsSame(const aNode: Il3SimpleNode): Boolean;
//#UC START# *54C78D9201B9_4ADDF4110392_var*
var
l_MyAdapterNode : INode;
l_AdapterNode : INode;
//#UC END# *54C78D9201B9_4ADDF4110392_var*
begin
//#UC START# *54C78D9201B9_4ADDF4110392_impl*
Result := inherited GetIsSame(aNode);
if not Result then
begin
l_MyAdapterNode := AdapterNode;
if (l_MyAdapterNode <> nil) AND
Supports(aNode, INode, l_AdapterNode) then
try
Result := l3IEQ(l_MyAdapterNode, l_AdapterNode);
if not Result then
Result := l_MyAdapterNode.IsSameNode(l_AdapterNode);
finally
l_AdapterNode := nil;
end;//try..finally
end;//not Result
//#UC END# *54C78D9201B9_4ADDF4110392_impl*
end;//TnsPrimAdapterNode.GetIsSame
function TnsPrimAdapterNode.GetLevelForParent(const aNode: Il3SimpleNode): Integer;
//#UC START# *54C78EA30198_4ADDF4110392_var*
var
l_Parent : INode;
l_Node : INode;
//#UC END# *54C78EA30198_4ADDF4110392_var*
begin
//#UC START# *54C78EA30198_4ADDF4110392_impl*
l_Node := AdapterNode;
if (l_Node <> nil) and Supports(aNode, INode, l_Parent) then
begin
try
Result := l_Node.GetLevel - l_Parent.GetLevel;
finally
l_Parent := nil;
end;//try..finally
end//l_Node <> nil..
else
Result := 0
//#UC END# *54C78EA30198_4ADDF4110392_impl*
end;//TnsPrimAdapterNode.GetLevelForParent
procedure TnsPrimAdapterNode.ClearFields;
begin
AdapterNode := nil;
inherited;
end;//TnsPrimAdapterNode.ClearFields
end.
|
unit controlPosition;
interface
uses Forms,IniFiles, Classes, Controls, SysUtils;
procedure ReadControlPlacement(const form : TForm);
procedure WriteControlPlacement(const form : TForm);
implementation
procedure ReadControlPlacement(const form : TForm);
var
iniFile : TIniFile;
idx : integer;
// ctrl : TControl;
Left,Top,Width,Height: Integer;
procedure ReadControl(Ctrl: TControl);
begin
Top := iniFile.ReadInteger(ctrl.Name,'Top',ctrl.Top);
Left := iniFile.ReadInteger(ctrl.Name,'Left',ctrl.Left);
Width := iniFile.ReadInteger(ctrl.Name,'Width',ctrl.Width);
Height := iniFile.ReadInteger(ctrl.Name,'Height',ctrl.Height);
ctrl.SetBounds(Left,Top,Width,Height);
end;
begin
iniFile := TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini'));
try
ReadControl(form);
for idx := 0 to -1 + form.ControlCount do
begin
if form.Components[idx] is TControl then
ReadControl(TControl(form.Components[idx]));
end;
finally
FreeAndNil(iniFile);
end;
end; (*ReadControlPlacement*)
procedure WriteControlPlacement(const form : TForm);
var
iniFile : TIniFile;
idx : integer;
// ctrl : TControl;
procedure WriteControl(Ctrl: TControl);
begin
iniFile.WriteInteger(ctrl.Name,'Top',ctrl.Top);
iniFile.WriteInteger(ctrl.Name,'Left',ctrl.Left);
iniFile.WriteInteger(ctrl.Name,'Width',ctrl.Width);
iniFile.WriteInteger(ctrl.Name,'Height',ctrl.Height);
end;
begin
iniFile := TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini'));
try
WriteControl(form);
for idx := 0 to -1 + form.ComponentCount do
begin
if form.Components[idx] is TControl then
WriteControl(TControl(form.Components[idx]));
end;
finally
FreeAndNil(iniFile);
end;
end; (*WriteControlPlacement*)
end.
|
unit DT_DbInfo;
// TDbInfo работает с INI-файлами.
// С основном только читает, менять может только номера версий.
// Номера версий читает либо из файла ARCHI.VERSION (если он имеется),
// либо из файлов BASE.INI в папках семейств и папке MAIN (если отсутствует файл ARCHI.VERSION).
// Таким образом наличие-отсутствие файла ARCHI.VERSION является признаком того, где хранятся
// сведения о версиях.
// Порядок правильного использования:
// 1. Create(ArchiIniFileName)
// 2. ActiveFamily := ...
// 3. Передача объекта в другие функции
{ $Id: DT_DbInfo.pas,v 1.7 2015/04/07 07:37:09 lukyanets Exp $ }
// $Log: DT_DbInfo.pas,v $
// Revision 1.7 2015/04/07 07:37:09 lukyanets
// Изолируем HT
//
// Revision 1.6 2014/05/26 16:06:18 lulin
// {RequestLink:537249703}
//
// Revision 1.4 2014/05/26 15:59:51 lulin
// {RequestLink:537249703}
//
// Revision 1.3 2014/05/23 16:31:10 lulin
// {RequestLink:537249703}
//
// Revision 1.2 2014/02/13 10:53:57 lulin
// - рефакторим безликие списки.
//
// Revision 1.1 2011/12/12 13:58:35 fireton
// - DbReformer и DbInfo переехали в DT
//
// Revision 1.12 2009/03/05 09:04:48 narry
// - рефакторинг
//
// Revision 1.11 2009/02/09 10:54:17 fireton
// - версия базы 131
//
// Revision 1.10 2007/04/18 11:39:42 narry
// - процедура создания произвольной пустой базы
//
// Revision 1.9 2005/12/12 08:22:36 step
// Учтено изменение версии БД
//
// Revision 1.8 2005/12/09 14:03:18 step
// new: property HomesFolder
//
// Revision 1.7 2005/09/20 14:40:21 step
// учтено изменение версии БД
//
// Revision 1.6 2005/04/07 18:49:10 step
// добавлена проверка версии БД
//
// Revision 1.5 2005/02/08 16:54:18 step
// изменен алгоритм чтения-записи номера версии
//
// Revision 1.4 2004/12/23 11:47:19 lulin
// - rename unit: User_Cfg -> l3IniFile.
//
// Revision 1.3 2004/05/26 09:57:38 step
// исправление TDbInfo.Data
//
// Revision 1.2 2004/05/25 15:44:46 step
// изменен порядок нумерации версий
//
// Revision 1.1 2004/05/07 17:43:34 step
// куча мелких исправлений
//
interface
uses
Classes,
Contnrs,
SysUtils,
l3IniFile,
Ht_Const,
l3ProtoObject,
dtFamilyInfo,
dtFamilyInfoList
;
type
(* TFamilyInfo = class(Tl3ProtoObject)
Number: Integer;
Name: string;
Path: string;
DocGroup: Integer;
Attributes: Integer;
end;*)
TDbInfo = class(Tl3ProtoObject)
private
f_ArchiIni: string;
f_ActiveFamilyIndex: Integer;
f_FamiliesData: TdtFamilyInfoList;
f_MainFolderPath: string;
f_HomesFolderPath: string;
f_DbRootFolderPath: string;
f_ShareFolderPath: string;
procedure GetFamiliesData(aIniFile: TCfgList);
procedure GetMainFolderPath(aIniFile: TCfgList);
procedure GetHomesFolderPath(aIniFile: TCfgList);
procedure GetDbRootPath(aIniFile: TCfgList);
procedure GetSharePath(aIniFile: TCfgList);
function FamilyBaseIni: string;
function MainFolderBaseIni: string;
function ArchiVersionIni: string;
function GetActiveFamily: string;
procedure SetActiveFamily(const aFamilyName: string);
function GetFamilyFolderVersion: Integer;
procedure SetFamilyFolderVersion(aVersionNum: Integer);
function GetMainFolderVersion: Integer;
procedure SetMainFolderVersion(aVersionNum: Integer);
function GetFamilyFolder: string;
protected
procedure ReadAllPaths;
public
constructor Create(aArchiIni: string);
constructor Make(const aBaseRootFolder: String; const aHomesFolder: String = ''; const aMainFolder: String = ''; const
aShareFolder: String = '');
procedure Cleanup; override;
// сведения о текущем состоянии для показа юзеру
function Data: string;
// имена семейств
procedure GetFamilyNames(aList: TStrings);
// проверка БД на "старость"
procedure CheckFolderVersions; // выбрасывает исключение
// папки (только чтение)
property RootFolder: string read f_DbRootFolderPath;
property ShareFolder: string read f_ShareFolderPath;
property MainFolder: string read f_MainFolderPath;
property HomesFolder: string read f_HomesFolderPath;
property FamilyFolder: string read GetFamilyFolder;
// версии
property MainFolderVersion: Integer read GetMainFolderVersion write SetMainFolderVersion;
property FamilyFolderVersion: Integer read GetFamilyFolderVersion write SetFamilyFolderVersion;
property ActiveFamily: string read GetActiveFamily write SetActiveFamily;
end;
EDBInfoError = class(Exception);
implementation
uses
Ht_Dll,
Windows,
StrUtils,
Dialogs,
IniFiles,
l3Base, l3FileUtils,
daInterfaces,
dt_Const, dt_Types;
const
BAD_VERSION = 0;
(*
// Версии папок БД, с которыми тулза умеет работать.
c_DocBaseVersion = 114;
c_AdminBaseVersion = 113;
*)
{ TDbInfo }
constructor TDbInfo.Create(aArchiIni: string);
begin
if FileExists(aArchiIni) then
f_ArchiIni := aArchiIni
else
raise EDBInfoError.CreateFmt('Файл %s не найден.', [aArchiIni]);
f_FamiliesData := TdtFamilyInfoList.Create;
f_ActiveFamilyIndex := -1;
ReadAllPaths;
f_ActiveFamilyIndex := 0;
end;
constructor TDbInfo.Make(const aBaseRootFolder: String; const aHomesFolder: String = ''; const aMainFolder: String =
''; const aShareFolder: String = '');
begin
f_FamiliesData := TdtFamilyInfoList.Create;
f_ActiveFamilyIndex := 0;
f_DbRootFolderPath:= aBaseRootFolder;
f_HomesFolderPath := IfThen(aHomesFolder = '', ConcatDirName(aBaseRootFolder, 'HOMES'), aHomesFolder);
f_MainFolderPath := IfThen(aMainFolder = '', ConcatDirName(aBaseRootFolder, 'MAIN'), aMainFolder);
f_ShareFolderPath := IfThen(aShareFolder = '', ConcatDirName(aBaseRootFolder, 'SHARE'), aShareFolder);
GetFamiliesData(nil);
end;
procedure TDbInfo.Cleanup;
begin
FreeAndNil(f_FamiliesData);
inherited;
end;
function TDbInfo.FamilyBaseIni: string;
begin
Result := ConcatDirName(f_FamiliesData[f_ActiveFamilyIndex].Path, 'base.ini');
end;
function TDbInfo.GetFamilyFolderVersion: Integer;
var
l_IniFile: TIniFile;
l_IniFileName: string;
begin
Result := BAD_VERSION;
l_IniFileName := FamilyBaseIni;
if FileExists(l_IniFileName) then
begin
l_IniFile := TIniFile.Create(l_IniFileName);
try
Result := l_IniFile.ReadInteger('Tables', 'Version', BAD_VERSION);
finally
FreeAndNil(l_IniFile);
end;
end
else
begin
l_IniFileName := ArchiVersionIni;
if FileExists(l_IniFileName) then
begin
l_IniFile := TIniFile.Create(l_IniFileName);
try
Result := l_IniFile.ReadInteger('Version', 'Db', BAD_VERSION);
finally
FreeAndNil(l_IniFile);
end;
end;
end;
if Result = BAD_VERSION then
raise EDBInfoError.Create('Не найден файл с данными о текущей версии таблиц в папке GARANT.');
end;
procedure TDbInfo.GetFamilyNames(aList: TStrings);
var
I: Integer;
begin
if aList = nil then
Exit;
aList.Clear;
for I := 0 to f_FamiliesData.Count - 1 do
aList.Add(f_FamiliesData[I].Name);
end;
procedure TDbInfo.GetFamiliesData(aIniFile: TCfgList);
const
c_BadStr = '';
c_BadNum = -1;
c_Prefix = 'Family';
var
l_SectionNames: TStringList;
I: Integer;
l_FamilyNum: Integer;
l_FamilyInfo: TdtFamilyInfo;
begin
f_FamiliesData.Clear;
if aIniFile <> nil then
begin
// ищем секции [FamilyN] в Archi.ini(ServerConfin.ini)
// Если такие найдутся, то данные по базам документов берем оттуда
l_SectionNames := TStringList.Create;
try
aIniFile.GetSectionNameList(l_SectionNames);
for I := 0 to l_SectionNames.Count - 1 do
begin
if AnsiStartsText(c_Prefix, l_SectionNames[I]) then
begin
l_FamilyNum := StrToIntDef(Copy(l_SectionNames[I],
Length(c_Prefix) + 1,
MaxInt),
c_BadNum);
if l_FamilyNum <> c_BadNum then
begin
aIniFile.Section := l_SectionNames[I];
l_FamilyInfo := TdtFamilyInfo.Create;
try
l_FamilyInfo.Number := l_FamilyNum;
l_FamilyInfo.Name := aIniFile.ReadParamStrDef('Name', c_BadStr);
l_FamilyInfo.Path := aIniFile.ReadParamStrDef('Path', c_BadStr);
l_FamilyInfo.DocGroup := aIniFile.ReadParamIntDef('DocGroup', c_BadNum);
l_FamilyInfo.Attributes := aIniFile.ReadParamIntDef('Attributes', c_BadNum);
if (l_FamilyInfo.Name = c_BadStr)
or (l_FamilyInfo.Path = c_BadStr)
or (l_FamilyInfo.DocGroup = c_BadNum)
or (l_FamilyInfo.Attributes = c_BadNum)
then
FreeAndNil(l_FamilyInfo)
else
f_FamiliesData.Add(l_FamilyInfo);
finally
FreeAndNil(l_FamilyInfo);
end;//try..finally
end;
end;
end;
finally
FreeAndNil(l_SectionNames);
end;
end; // aIniFile <> nil
// Если же секции [FamilyN] в Archi.ini(ServerConfin.ini) не найдены,
// то данные по базам документов берутся из таблицы Family. Но поскольку
// содердимое этой таблицы уже окаменело, то можно использовать константы.
if f_FamiliesData.Count = 0 then
begin
l_FamilyInfo := TdtFamilyInfo.Create;
try
l_FamilyInfo.Number := 1;
l_FamilyInfo.Name := 'Garant';
l_FamilyInfo.Path := ConcatDirName(f_DbRootFolderPath, 'Garant\');
l_FamilyInfo.DocGroup := 1;
l_FamilyInfo.Attributes := 1;
f_FamiliesData.Add(l_FamilyInfo);
finally
FreeAndNil(l_FamilyInfo);
end;//try..finally
end;
end;
function TDbInfo.MainFolderBaseIni: string;
begin
Result := ConcatDirName(f_MainFolderPath, 'base.ini');
end;
procedure TDbInfo.ReadAllPaths;
const
c_BadStr = '';
var
l_CfgList: TCfgList;
l_ServerCfgIni: string;
begin
// сначала читаем локальный инишник
l_CfgList := TCfgList.Create(f_ArchiIni);
try
l_CfgList.InitSubsts('FamilyConst');
l_CfgList.Section := 'ServerConfig';
l_ServerCfgIni := l_CfgList.ReadParamStrDef('ServerConfigINI', c_BadStr);
// если локальный инишник содержит сведения о сетевом инишнике, то переключаем на сетевой
if l_ServerCfgIni <> c_BadStr then
begin
l3Free(l_CfgList);
l_CfgList := TCfgList.Create(l_ServerCfgIni);
l_CfgList.InitSubsts('FamilyConst');
end;
// собственно refresh
GetDbRootPath(l_CfgList);
GetFamiliesData(l_CfgList);
GetSharePath(l_CfgList);
GetMainFolderPath(l_CfgList);
GetHomesFolderPath(l_CfgList);
finally
l3Free(l_CfgList);
end;
end;
procedure TDbInfo.GetMainFolderPath(aIniFile: TCfgList);
const
c_BadStr = '';
begin
aIniFile.Section := 'BaseDocPath';
f_MainFolderPath := aIniFile.ReadParamStrDef('TablePath', c_BadStr);
if f_MainFolderPath = c_BadStr then
raise EDBInfoError.Create('Не указан путь к папке Main.');
if not DirectoryExists(f_MainFolderPath) then
raise EDBInfoError.CreateFmt('Папка %s не найдена.', [f_MainFolderPath]);
end;
procedure TDbInfo.GetDbRootPath(aIniFile: TCfgList);
const
c_BadStr = '';
begin
aIniFile.Section := 'FamilyConst';
f_DbRootFolderPath := aIniFile.ReadParamStrDef('FamilyPath', c_BadStr);
if f_DbRootFolderPath = c_BadStr then
raise EDBInfoError.Create('Не указана FamilyConst.');
if not DirectoryExists(f_DbRootFolderPath) then
raise EDBInfoError.CreateFmt('Папка %s не найдена.', [f_DbRootFolderPath]);
end;
function TDbInfo.ArchiVersionIni: string;
begin
Result := ConcatDirName(f_DbRootFolderPath, 'archi.version');
end;
function TDbInfo.GetFamilyFolder: string;
begin
Result := f_FamiliesData[f_ActiveFamilyIndex].Path;
end;
procedure TDbInfo.SetFamilyFolderVersion(aVersionNum: Integer);
var
l_IniFile: TIniFile;
begin
l_IniFile := TIniFile.Create(FamilyBaseIni);
try
l_IniFile.WriteInteger('Tables', 'Version', aVersionNum);
finally
FreeAndNil(l_IniFile);
end;
end;
procedure TDbInfo.GetSharePath(aIniFile: TCfgList);
const
c_BadStr = '';
begin
aIniFile.Section := 'BaseDocPath';
f_ShareFolderPath := aIniFile.ReadParamStrDef('LockPath', c_BadStr);
if f_ShareFolderPath = c_BadStr then
raise EDBInfoError.Create('Не указан LockPath.');
if not DirectoryExists(f_ShareFolderPath) then
raise EDBInfoError.CreateFmt('Папка %s не найдена.', [f_ShareFolderPath]);
end;
function TDbInfo.GetActiveFamily: string;
begin
Result := f_FamiliesData[f_ActiveFamilyIndex].Name;
end;
procedure TDbInfo.SetActiveFamily(const aFamilyName: string);
var
I: Integer;
l_Found: Integer;
begin
l_Found := -1;
for I := 0 to f_FamiliesData.Count - 1 do
if AnsiCompareText(aFamilyName, f_FamiliesData[I].Name) = 0 then
begin
l_Found := I;
Break;
end;
if l_Found > -1 then
f_ActiveFamilyIndex := l_Found
else
raise EDBInfoError.CreateFmt('Неверное имя семейства: %s', [aFamilyName]);
end;
function TDbInfo.GetMainFolderVersion: Integer;
var
l_IniFile: TIniFile;
l_IniFileName: string;
begin
Result := BAD_VERSION;
l_IniFileName := MainFolderBaseIni;
if FileExists(l_IniFileName) then
begin
l_IniFile := TIniFile.Create(l_IniFileName);
try
Result := l_IniFile.ReadInteger('Tables', 'Version', BAD_VERSION);
finally
FreeAndNil(l_IniFile);
end;
end
else
begin
l_IniFileName := ArchiVersionIni;
if FileExists(l_IniFileName) then
begin
l_IniFile := TIniFile.Create(l_IniFileName);
try
Result := l_IniFile.ReadInteger('Version', 'Db', BAD_VERSION);
finally
FreeAndNil(l_IniFile);
end;
end;
end;
if Result = BAD_VERSION then
raise EDBInfoError.Create('Не найден файл с данными о текущей версии таблиц в папке MAIN.');
end;
procedure TDbInfo.SetMainFolderVersion(aVersionNum: Integer);
var
l_IniFile: TIniFile;
begin
l_IniFile := TIniFile.Create(MainFolderBaseIni);
try
l_IniFile.WriteInteger('Tables', 'Version', aVersionNum);
finally
FreeAndNil(l_IniFile);
end;
end;
function TDbInfo.Data: string;
begin
Result :=
'База документов:' + #13#10 +
' Расположение: ' + FamilyFolder + #13#10 +
' Версия: ' + IntToStr(FamilyFolderVersion) + #13#10 +
'Административная база:' + #13#10 +
' Расположение: '+ MainFolder + #13#10 +
' Версия: ' + IntToStr(MainFolderVersion);
end;
procedure TDbInfo.CheckFolderVersions;
const
c_ErrMessage = 'Папка %s содержит данные версии %d.'#13#10 +
'Программа может обрабатывать данные только версии %d.';
begin
if (FamilyFolderVersion <> c_DocBaseVersion) then
raise EDBInfoError.CreateFmt(c_ErrMessage, [FamilyFolder, FamilyFolderVersion, c_DocBaseVersion]);
if (MainFolderVersion <> c_AdminBaseVersion) then
raise EDBInfoError.CreateFmt(c_ErrMessage, [MainFolder, MainFolderVersion, c_AdminBaseVersion]);
end;
procedure TDbInfo.GetHomesFolderPath(aIniFile: TCfgList);
const
c_BadStr = '';
begin
aIniFile.Section := 'BaseDocPath';
f_HomesFolderPath := aIniFile.ReadParamStrDef('HomeDirPath', c_BadStr);
if f_HomesFolderPath = c_BadStr then
raise EDBInfoError.Create('Не указан путь к папке Homes.');
if not DirectoryExists(f_HomesFolderPath) then
raise EDBInfoError.CreateFmt('Папка %s не найдена.', [f_HomesFolderPath]);
end;
end.
|
namespace Sugar.Echoes.WP8.Test;
interface
uses
Sugar.Echoes.WP8.Test.Resources;
type
/// <summary>
/// Provides access to string resources.
/// </summary>
LocalizedStrings = public class
private
class var _localizedResources: AppResources := new AppResources();
public
property LocalizedResources: AppResources read _localizedResources;
end;
implementation
end. |
unit BufferProviders;
interface
uses
Buffer;
type
CBufferProvider = class of TBufferProvider;
TBufferProvider =
class
function CreateBitmap : TBuffer; virtual; abstract;
end;
function GetProvider( id : integer ) : TBufferProvider;
procedure RegisterProvider( id : integer; Provider : CBufferProvider );
implementation
function GetProvider( id : integer ) : TBufferProvider;
begin
Result := nil;
//
end;
procedure RegisterProvider( id : integer; Provider : CBufferProvider );
begin
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2014 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clSshSocket;
interface
{$I ..\common\clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils, Windows,
{$ELSE}
System.Classes, System.SysUtils, Winapi.Windows,
{$ENDIF}
clSocket, clUtils, clSshPacket, clSshKeyExchanger, clConfig, clSshConfig,
clCryptCipher, clCryptMac, clSshCompression, clSshAuth, clCryptHash, clCryptRandom, clSshUserIdentity;
type
TclSshState = (sshVersionExchange, sshKeyExchangeInit, sshKeyGuess, sshKeyExchange, sshNewKeys,
sshAuthenticateInit, sshAuthenticate, sshChannelOpen, sshChannelRequest, sshData, sshDisconnect,
sshChannelClose);
TclVerifySshPeerEvent = procedure(Sender: TObject; const AHost, AKeyType, AFingerPrint, AHostKey: string;
var AVerified: Boolean) of object;
//TODO max batchsize checking
TclSshNetworkStream = class(TclNetworkStream)
private
FSshAction: TclNetworkStreamAction;
FIsAdjustLocalWinSize: Boolean;
FIsAdjustRemoteWinSize: Boolean;
FReadData: TStream;
FWriteData: TStream;
FWriteSize: Integer;
FWritePacketLength: Integer;
FReadPacketLength: Integer;
FReadDataFilled: Boolean;
FState: TclSshState;
FPacket: TclPacket;
FWritePacket: TclPacket;
FSshAgent: string;
FKex: TclSshKeyExchanger;
FSeqi: Integer;
FSeqo: Integer;
FConfig: TclConfig;
FSessionId: TclByteArray;
FIVc2s: TclByteArray;
FIVs2c: TclByteArray;
FEc2s: TclByteArray;
FEs2c: TclByteArray;
FMACc2s: TclByteArray;
FMACs2c: TclByteArray;
FS2ccipher: TclCipher;
FC2scipher: TclCipher;
FS2cmac: TclMac;
FC2smac: TclMac;
FMac_buf: TclByteArray;
FDeflater: TclCompression;
FInflater: TclCompression;
FAuth: TclSshUserAuth;
FAuthMethods: string;
FTargetName: string;
FIdentity: TclSshUserIdentity;
FV_S: TclByteArray;
FV_C: TclByteArray;
FI_C: TclByteArray;
FI_S: TclByteArray;
FChannelId: Integer;
FRecipientId: Integer;
FChannelType: string;
FSubSystem: string;
FLocalWindowSizeMax: Integer;
FLocalWindowSize: Integer;
FLocalPacketSize: Integer;
FRemoteWindowSize: Integer;
FRemotePacketSize: Integer;
FLastErrorText: string;
FLastErrorCode: Integer;
FMoreDataNeeded: Boolean;
FRandom: TclRandom;
FCipher_size: Integer;
FOnVerifyPeer: TclVerifySshPeerEvent;
procedure RaiseSshError(const AErrorMsg: string; AErrorCode: Integer);
procedure DoUpdateProgress(ABytesProceed: Int64);
procedure DoStreamReady;
procedure ResetSsh;
procedure Init;
procedure ClearSshAction;
procedure SetSshAction(Action: TclNetworkStreamAction);
function FillBuffer(ASource: TStream): Boolean;
procedure EncodePacket(APack: TclPacket);
procedure SendKexInit(ADestination: TStream);
procedure UpdateKeys(AKex: TclSshKeyExchanger);
procedure CheckHost(const AHost: string; AKex: TclSshKeyExchanger);
function ProcessVersionExchange(ASource: TStream): Boolean;
function ProcessKeyExchangeInit: Boolean;
function ProcessKeyExchange: Boolean;
function ProcessNewKeys: Boolean;
function ProcessAuthenticateInit: Boolean;
function ProcessAuthenticate: Boolean;
function ProcessChannelOpenConfirmation: Boolean;
function ProcessChannelOpenFailure: Boolean;
function ProcessChannelOpenSuccess: Boolean;
function ProcessChannelFailure: Boolean;
function ProcessChannelData(ADestination: TStream): Boolean;
function ProcessChannelDataEx(ADestination: TStream): Boolean;
function ProcessChannel(ADestination: TStream): Boolean;
function ProcessData(ASource, ADestination: TStream): Boolean;
function FillPacket(ASource: TStream; APack: TclPacket): Integer;
procedure PreparePacket(ADestination: TStream; APack: TclPacket);
procedure PrepareVersionExchange(ADestination: TStream);
procedure PrepareKeyExchangeInit(ADestination: TStream);
procedure PrepareKeyGuess(ADestination: TStream);
procedure PrepareKeyExchange(ADestination: TStream);
procedure PrepareNewKeys(ADestination: TStream);
procedure PrepareAuthenticateInit(ADestination: TStream);
procedure PrepareAuthenticate(ADestination: TStream);
procedure PrepareChannelOpen(ADestination: TStream);
procedure PrepareChannelRequest(ADestination: TStream);
procedure PrepareChannelData(ASource, ADestination: TStream);
procedure PrepareDisconnect(ADestination: TStream);
procedure PrepareChannelClose(ADestination: TStream);
procedure PrepareData(ASource, ADestination: TStream);
function WriteData(ASource: TStream; ALength: Integer): Boolean;
public
constructor Create(AConfig: TclConfig);
destructor Destroy; override;
procedure Assign(ASource: TclNetworkStream); override;
procedure Close(ANotifyPeer: Boolean); override;
procedure StreamReady; override;
function Read(AData: TStream): Boolean; override;
function Write(AData: TStream): Boolean; override;
function GetReadBatchSize: Integer; override;
function GetWriteBatchSize: Integer; override;
procedure UpdateProgress(ABytesProceed: Int64); override;
procedure InitClientSession; override;
procedure InitServerSession; override;
property RecipientId: Integer read FRecipientId;
property SessionId: TclByteArray read FSessionId;
property SshAgent: string read FSshAgent write FSshAgent;
property Identity: TclSshUserIdentity read FIdentity write FIdentity;
property ChannelType: string read FChannelType write FChannelType;
property SubSystem: string read FSubSystem write FSubSystem;
property TargetName: string read FTargetName write FTargetName;
property OnVerifyPeer: TclVerifySshPeerEvent read FOnVerifyPeer write FOnVerifyPeer;
end;
implementation
uses
clSocketUtils, clSshUtils, clTranslator{$IFDEF LOGGER}, clLogger, clWUtils{$ENDIF};
{ TclSshNetworkStream }
procedure TclSshNetworkStream.Assign(ASource: TclNetworkStream);
var
src: TclSshNetworkStream;
begin
inherited Assign(ASource);
if (ASource is TclSshNetworkStream) then
begin
src := ASource as TclSshNetworkStream;
FSshAgent := src.SshAgent;
FIdentity := src.Identity;
FChannelType := src.ChannelType;
FSubSystem := src.SubSystem;
end;
end;
procedure TclSshNetworkStream.CheckHost(const AHost: string; AKex: TclSshKeyExchanger);
var
verified: Boolean;
begin
//TODO implement host checking, HostKeyRepository
verified := True;
if Assigned(OnVerifyPeer) then
begin
OnVerifyPeer(Self, AHost, AKex.GetKeyType(), AKex.GetFingerPrint(), BytesToHex(AKex.GetHostKey()), verified);
end;
if (not verified) then
begin
RaiseSshError(HostKeyRejected, HostKeyRejectedCode);
end;
end;
procedure TclSshNetworkStream.ClearSshAction;
begin
FSshAction := saNone;
end;
procedure TclSshNetworkStream.Close(ANotifyPeer: Boolean);
begin
inherited Close(ANotifyPeer);
try
if (ANotifyPeer) then
begin
if (FState > sshChannelRequest) then
begin
FState := sshChannelClose;
end else
begin
FState := sshDisconnect;
end;
if (not WriteData(nil, 0)) then
begin
SetNextAction(saWrite);
end;
end;
except
on EclSocketError do;
end;
ResetSsh();
end;
constructor TclSshNetworkStream.Create(AConfig: TclConfig);
begin
inherited Create();
FReadData := TMemoryStream.Create();
FWriteData := TMemoryStream.Create();
FPacket := TclPacket.Create();
FWritePacket := TclPacket.Create();
FConfig := AConfig;
FSeqi := 0;
FSeqo := 0;
FSshAgent := DefaultSshAgent;
FIdentity := nil;
FChannelType := '';
FSubSystem := '';
FTargetName := '';
FRandom := TclRandom(FConfig.CreateInstance('random'));
end;
destructor TclSshNetworkStream.Destroy;
begin
FRandom.Free();
FKex.Free();
FS2ccipher.Free();
FC2scipher.Free();
FS2cmac.Free();
FC2smac.Free();
FDeflater.Free();
FInflater.Free();
FAuth.Free();
FWritePacket.Free();
FPacket.Free();
FWriteData.Free();
FReadData.Free();
inherited Destroy();
end;
procedure TclSshNetworkStream.DoStreamReady;
begin
inherited StreamReady();
end;
procedure TclSshNetworkStream.DoUpdateProgress(ABytesProceed: Int64);
begin
inherited UpdateProgress(ABytesProceed);
end;
procedure TclSshNetworkStream.EncodePacket(APack: TclPacket);
var
mac, buf: TclByteArray;
pad: Integer;
begin
{$IFNDEF DELPHI2005}mac := nil; buf := nil;{$ENDIF}
if (FDeflater <> nil) then
begin
APack.SetIndex(FDeflater.Compress(APack.Buffer, 5, APack.GetIndex()));
end;
if (FC2scipher <> nil) then
begin
APack.Padding(FRandom, FC2scipher.getIVSize());
pad := APack.Buffer[4];
FRandom.Fill(APack.Buffer, APack.GetIndex() - pad, pad);
end else
begin
APack.Padding(FRandom, 8);
end;
SetLength(mac, 0);
if (FC2smac <> nil) then
begin
FC2smac.Update(FSeqo);
FC2smac.Update(APack.Buffer, 0, APack.GetIndex());
mac := FC2smac.Digest();
end;
if (FC2scipher <> nil) then
begin
buf := APack.Buffer;
FC2scipher.Update(buf, 0, APack.GetIndex());
end;
if (Length(mac) > 0) then
begin
APack.PutByte(mac);
end;
end;
function TclSshNetworkStream.FillBuffer(ASource: TStream): Boolean;
var
oldPos: Int64;
uncompress_len: Integer;
ind, pad, bufType, reason_code: Integer;
res, foo, description, language_tag: TclByteArray;
begin
{$IFNDEF DELPHI2005}res := nil; foo := nil; description := nil; language_tag := nil;{$ENDIF}
oldPos := ASource.Position;
Result := False;
repeat
if ((ASource.Position + FCipher_size) >= ASource.Size) then
begin
ASource.Position := oldPos;
Exit;
end;
if (FReadPacketLength < 0) then
begin
FPacket.Init();
ASource.Read(FPacket.Buffer[FPacket.GetIndex()], FCipher_size);
FPacket.SetIndex(FPacket.GetIndex() + FCipher_size);
if (FS2ccipher <> nil) then
begin
FS2ccipher.Update(FPacket.Buffer, 0, FCipher_size);
end;
ind := 0;
FReadPacketLength := Integer(ByteArrayReadDWord(FPacket.Buffer, ind));
FReadPacketLength := FReadPacketLength - 4 - FCipher_size + 8;
if (FReadPacketLength < 0) or ((FPacket.GetIndex() + FReadPacketLength) > Length(FPacket.Buffer)) then
begin
RaiseSshError(InvalidPacketSize, InvalidPacketSizeCode);
end;
end else
begin
ASource.Seek(FCipher_size, soCurrent);
end;
if ((ASource.Position + FReadPacketLength - 4) > ASource.Size) then
begin
ASource.Position := oldPos;
Exit;
end;
if (FReadPacketLength > 0) then
begin
if (not FReadDataFilled) then
begin
ASource.Read(FPacket.Buffer[FPacket.GetIndex()], FReadPacketLength);
FPacket.SetIndex(FPacket.GetIndex() + FReadPacketLength);
if (FS2ccipher <> nil) then
begin
FS2ccipher.Update(FPacket.Buffer, FCipher_size, FReadPacketLength);
end;
FReadDataFilled := True;
end else
begin
ASource.Seek(FReadPacketLength, soCurrent);
end;
end;
if (FS2cmac <> nil) then
begin
if ((ASource.Position + Length(FMac_buf)) > ASource.Size) then
begin
ASource.Position := oldPos;
Exit;
end;
FS2cmac.Update(FSeqi);
FS2cmac.Update(FPacket.Buffer, 0, FPacket.GetIndex());
res := FS2cmac.Digest();
ASource.Read(FMac_buf[0], Length(FMac_buf));
if (not ByteArrayEquals(res, FMac_buf)) then
begin
RaiseSshError(MacError, MacErrorCode);
end;
end;
Inc(FSeqi);
FReadPacketLength := -1;
FReadDataFilled := False;
if (FInflater <> nil) then
begin
pad := FPacket.Buffer[4];
uncompress_len := FPacket.GetIndex() - 5 - pad;
foo := FInflater.Uncompress(FPacket.Buffer, 5, uncompress_len);
if (Length(foo) > 0) then
begin
FPacket.Buffer := foo;
FPacket.SetIndex(5 + uncompress_len);
end else
begin
Break;
end;
end;
bufType := FPacket.Buffer[5] and $ff;
if (bufType = SSH_MSG_DISCONNECT) then
begin
FPacket.Rewind();
FPacket.GetInt();
FPacket.GetShort();
reason_code := FPacket.GetInt();
description := FPacket.GetString();
language_tag := FPacket.GetString();
RaiseSshError(DisconnectOccurred, reason_code);
end else
if (bufType = SSH_MSG_IGNORE) then
begin
if (ASource.Position >= ASource.Size) then Break;
end else
if (bufType = SSH_MSG_DEBUG) then
begin
FPacket.Rewind();
FPacket.GetInt();
FPacket.GetShort();
if (ASource.Position >= ASource.Size) then Break;
end else
if (bufType = SSH_MSG_CHANNEL_WINDOW_ADJUST) then
begin
FPacket.Rewind();
FPacket.GetInt();
FPacket.GetShort();
ind := FPacket.GetInt();
if (ind = FChannelId) then
begin
Inc(FRemoteWindowSize, FPacket.GetInt());
end;
if (FIsAdjustRemoteWinSize) then
begin
if (not WriteData(nil, 0)) then
begin
SetSshAction(saWrite);
end;
Break;
end else
if (ASource.Position >= ASource.Size) then
begin
Break;
end;
end else
begin
Result := True;
Break;
end;
until False;
FPacket.Rewind();
end;
function TclSshNetworkStream.FillPacket(ASource: TStream; APack: TclPacket): Integer;
begin
APack.Init();
ASource.Read(APack.Buffer[0], ASource.Size);
APack.SetOffSet(5);
APack.GetByte();
APack.GetInt();
Result := APack.GetInt();
APack.Init();
APack.SetIndex(ASource.Size);
end;
function TclSshNetworkStream.GetReadBatchSize: Integer;
begin
Result := inherited GetReadBatchSize();
if (FS2ccipher <> nil) then
begin
Result := Result + FS2ccipher.GetIVSize() * 2;
end;
if (FS2cmac <> nil) then
begin
Result := Result + FS2cmac.GetBlockSize() * 2;
end;
end;
function TclSshNetworkStream.GetWriteBatchSize: Integer;
begin
Result := inherited GetWriteBatchSize();
if (FC2scipher <> nil) then
begin
Result := Result + FC2scipher.GetIVSize() * 2;
end;
if (FC2smac <> nil) then
begin
Result := Result + FC2smac.GetBlockSize() * 2;
end;
end;
procedure TclSshNetworkStream.Init;
begin
FMoreDataNeeded := False;
FReadData.Size := 0;
FWriteData.Size := 0;
FLastErrorText := UnknownError;
FLastErrorCode := UnknownErrorCode;
FWritePacketLength := 0;
ResetSsh();
end;
procedure TclSshNetworkStream.InitClientSession;
begin
Init();
SetNextAction(saRead);
end;
procedure TclSshNetworkStream.InitServerSession;
begin
Assert(False, 'Not implemented');
end;
procedure TclSshNetworkStream.PrepareAuthenticate(ADestination: TStream);
var
pp: TclPacket;
authResult: TclSshAuthResult;
authList, regAuth: TStrings;
regAuthMethods: string;
i: Integer;
begin
pp := nil;
try
if (FAuth = nil) then
begin
authList := nil;
regAuth := nil;
try
authList := TStringList.Create();
regAuth := TStringList.Create();
regAuthMethods := FConfig.GetConfig('auth.method');
ExtractQuotedWords(regAuthMethods, regAuth, ',', [], [], True);
ExtractQuotedWords(LowerCase(FAuthMethods), authList, ',', [], [], True);
for i := 0 to regAuth.Count - 1 do
begin
if (authList.IndexOf(regAuth[i]) > -1) then
begin
FAuth := TclSshUserAuth(FConfig.CreateInstance(regAuth[i]));
if (FAuth = nil) then
begin
RaiseSshError(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode);
end;
if not FAuth.Init(FConfig, FIdentity, FSessionId) then
begin
FreeAndNil(FAuth);
end else
begin
Break;
end;
end;
end;
finally
regAuth.Free();
authList.Free();
end;
if (FAuth = nil) then
begin
RaiseSshError(AuthMethodError, AuthMethodErrorCode);
end;
authResult := FAuth.Authenticate(nil, pp);
end else
begin
authResult := FAuth.Authenticate(FPacket, pp);
end;
if (pp <> nil) then
begin
PreparePacket(ADestination, pp);
SetSshAction(saRead);
end;
case (authResult) of
sarSuccess:
begin
FState := sshChannelOpen;
SetSshAction(saWrite);
end;
sarFail:
begin
RaiseSshError(UserAuthError, UserAuthErrorCode);
end
else
begin
FAuthMethods := FAuth.Methods;
FState := sshAuthenticate;
SetSshAction(saRead);
end;
end;
finally
pp.Free();
end;
end;
procedure TclSshNetworkStream.PrepareAuthenticateInit(ADestination: TStream);
var
pp: TclPacket;
authResult: TclSshAuthResult;
begin
pp := nil;
try
if (FAuth = nil) then
begin
FAuth := TclUserAuthNone.Create();
FAuth.Init(FConfig, FIdentity, FSessionId);
authResult := FAuth.Authenticate(nil, pp);
end else
begin
authResult := FAuth.Authenticate(FPacket, pp);
end;
if (pp <> nil) then
begin
PreparePacket(ADestination, pp);
SetSshAction(saRead);
end;
case (authResult) of
sarSuccess:
begin
FState := sshChannelOpen;
SetSshAction(saWrite);
end;
sarFail:
begin
FAuthMethods := FAuth.Methods;
if (Trim(FAuthMethods) = '') and (Pos('password', FConfig.GetConfig('auth.method')) > 0) then
begin
FAuthMethods := 'password';
end;
FreeAndNil(FAuth);
FState := sshAuthenticate;
SetSshAction(saWrite);
end
else
begin
FState := sshAuthenticateInit;
SetSshAction(saRead);
end;
end;
finally
pp.Free();
end;
end;
procedure TclSshNetworkStream.PrepareChannelClose(ADestination: TStream);
begin
FPacket.Reset();
FPacket.PutByte(SSH_MSG_CHANNEL_CLOSE);
FPacket.PutInt(FRecipientId);
PreparePacket(ADestination, FPacket);
end;
procedure TclSshNetworkStream.PrepareChannelData(ASource, ADestination: TStream);
var
len, s, blockSize: Integer;
command: Byte;
begin
if (FIsAdjustLocalWinSize) then
begin
FIsAdjustLocalWinSize := False;
FPacket.Reset();
FPacket.PutByte(SSH_MSG_CHANNEL_WINDOW_ADJUST);
FPacket.PutInt(FRecipientId);
FPacket.PutInt(FLocalWindowSizeMax - FLocalWindowSize);
FLocalWindowSize := FLocalWindowSizeMax;
PreparePacket(ADestination, FPacket);
end else
if ((ASource <> nil) or FIsAdjustRemoteWinSize) then
begin
if (not FIsAdjustRemoteWinSize) then
begin
ASource.Position := 0;
FWritePacketLength := FillPacket(ASource, FWritePacket);
end;
if (FRemoteWindowSize >= FWritePacketLength) then
begin
Dec(FRemoteWindowSize, FWritePacketLength);
PreparePacket(ADestination, FWritePacket);
FIsAdjustRemoteWinSize := False;
end else
begin
if (FRemoteWindowSize > 0) then
begin
len := FRemoteWindowSize;
blockSize := 0;
if (FC2smac <> nil) then
begin
blockSize := FC2smac.GetBlockSize();
end;
s := FWritePacket.Shift(len, blockSize);
command := FWritePacket.Buffer[5];
Dec(FWritePacketLength, len);
FRemoteWindowSize := 0;
PreparePacket(ADestination, FWritePacket);
FWritePacket.Unshift(command, FRecipientId, s, FWritePacketLength);
end;
FIsAdjustRemoteWinSize := True;
SetSshAction(saRead);
end;
end;
end;
procedure TclSshNetworkStream.PrepareChannelOpen(ADestination: TStream);
var
pp: TclPacket;
begin
pp := TclPacket.Create(100);
try
pp.Reset();
pp.PutByte(SSH_MSG_CHANNEL_OPEN);
pp.PutString(TclTranslator.GetBytes(FChannelType));
pp.PutInt(FChannelId);
pp.PutInt(FLocalWindowSize);
pp.PutInt(FLocalPacketSize);
PreparePacket(ADestination, pp);
SetSshAction(saRead);
FState := sshChannelRequest;
finally
pp.Free();
end;
end;
procedure TclSshNetworkStream.PrepareChannelRequest(ADestination: TStream);
var
pp: TclPacket;
begin
pp := TclPacket.Create(100);
try
pp.Reset();
pp.PutByte(SSH_MSG_CHANNEL_REQUEST);
pp.PutInt(FRecipientId);
pp.PutString(TclTranslator.GetBytes('subsystem'));
pp.PutByte(1);
pp.PutString(TclTranslator.GetBytes(FSubSystem));
PreparePacket(ADestination, pp);
SetSshAction(saRead);
FState := sshChannelRequest;
finally
pp.Free();
end;
end;
procedure TclSshNetworkStream.PrepareData(ASource, ADestination: TStream);
begin
if ((ADestination.Size - ADestination.Position) > 0) then Exit;
ClearSshAction();
case FState of
sshVersionExchange: PrepareVersionExchange(ADestination);
sshKeyExchangeInit: PrepareKeyExchangeInit(ADestination);
sshKeyGuess: PrepareKeyGuess(ADestination);
sshKeyExchange: PrepareKeyExchange(ADestination);
sshNewKeys: PrepareNewKeys(ADestination);
sshAuthenticateInit: PrepareAuthenticateInit(ADestination);
sshAuthenticate: PrepareAuthenticate(ADestination);
sshChannelOpen: PrepareChannelOpen(ADestination);
sshChannelRequest: PrepareChannelRequest(ADestination);
sshData: PrepareChannelData(ASource, ADestination);
sshDisconnect: PrepareDisconnect(ADestination);
sshChannelClose: PrepareChannelClose(ADestination);
end;
end;
procedure TclSshNetworkStream.PrepareDisconnect(ADestination: TStream);
begin
FPacket.Reset();
FPacket.putByte(SSH_MSG_DISCONNECT);
FPacket.PutInt(3);
FPacket.PutString(TclTranslator.GetBytes(FLastErrorText));
FPacket.PutString(TclTranslator.GetBytes('en'));
PreparePacket(ADestination, FPacket);
end;
procedure TclSshNetworkStream.PrepareKeyExchange(ADestination: TStream);
var
pp: TclPacket;
begin
if (FKex.GetState() = FPacket.Buffer[5]) then
begin
pp := nil;
if (not FKex.Next(FPacket, pp)) then
begin
RaiseSshError(KexNextError, KexNextErrorCode);
end;
if (pp <> nil) then
begin
PreparePacket(ADestination, pp);
SetSshAction(saRead);
end;
end;
if (FKex.GetState() = STATE_END) then
begin
FState := sshNewKeys;
end;
SetSshAction(saWrite);
end;
procedure TclSshNetworkStream.PrepareKeyExchangeInit(ADestination: TStream);
var
j, len: Integer;
begin
j := FPacket.GetInt();
if (j <> FPacket.GetLength()) then
begin
FPacket.GetByte();
len := FPacket.GetIndex() - 5;
end else
begin
len := j - 1 - FPacket.GetByte();
end;
FI_S := System.Copy(FPacket.Buffer, FPacket.GetOffSet(), len);
SendKexInit(ADestination);
SetSshAction(saWrite);
FState := sshKeyGuess;
end;
procedure TclSshNetworkStream.PrepareKeyGuess(ADestination: TStream);
var
guess: TStrings;
pp: TclPacket;
begin
guess := TclSshKeyExchanger.Guess(FI_S, FI_C);
try
if (guess = nil) then
begin
RaiseSshError(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode);
end;
FreeAndNil(FKex);
FKex := TclSshKeyExchanger(FConfig.CreateInstance(guess[PROPOSAL_KEX_ALGS]));
if (FKex = nil) then
begin
RaiseSshError(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode);
end;
FKex.GuessAlgorithms := guess;
pp := nil;
FKex.Init(FConfig, FV_S, FV_C, FI_S, FI_C, pp);
if (pp <> nil) then
begin
PreparePacket(ADestination, pp);
end;
SetSshAction(saRead);
FState := sshKeyExchange;
finally
guess.Free();
end;
end;
procedure TclSshNetworkStream.PrepareNewKeys(ADestination: TStream);
begin
CheckHost(TargetName, FKex);
FPacket.Reset();
FPacket.PutByte(SSH_MSG_NEWKEYS);
PreparePacket(ADestination, FPacket);
SetSshAction(saRead);
end;
procedure TclSshNetworkStream.PreparePacket(ADestination: TStream; APack: TclPacket);
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'PreparePacket (before encode), index='
+ IntToStr(APack.GetIndex())
+ ', S=' + IntToStr(APack.GetOffSet()),
PclChar(APack.Buffer), Length(APack.Buffer));{$ENDIF}
ADestination.Size := 0;
EncodePacket(APack);
ADestination.Write(APack.Buffer[0], APack.GetIndex());
Inc(FSeqo);
ADestination.Position := 0;
end;
procedure TclSshNetworkStream.PrepareVersionExchange(ADestination: TStream);
var
b: Byte;
begin
FV_C := TclTranslator.GetBytes('SSH-2.0-' + SshAgent);
ADestination.Size := 0;
ADestination.Write(FV_C[0], Length(FV_C));
b := $a;
ADestination.Write(b, SizeOf(b));
ADestination.Position := 0;
SetSshAction(saRead);
FState := sshKeyExchangeInit;
end;
function TclSshNetworkStream.ProcessAuthenticate: Boolean;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessAuthenticate', nil);{$ENDIF}
Result := WriteData(nil, 0);
if (not Result) then
begin
SetSshAction(saWrite);
end;
end;
function TclSshNetworkStream.ProcessAuthenticateInit: Boolean;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessAuthenticateInit', nil);{$ENDIF}
Result := WriteData(nil, 0);
if (not Result) then
begin
SetSshAction(saWrite);
end;
end;
function TclSshNetworkStream.ProcessChannelData(ADestination: TStream): Boolean;
var
i: Integer;
start, length: TclIntArray;
foo: TclByteArray;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessChannelData', nil);{$ENDIF}
{$IFNDEF DELPHI2005}foo := nil; start := nil; length := nil;{$ENDIF}
FPacket.GetInt();
FPacket.GetByte();
FPacket.GetByte();
i := FPacket.GetInt();
if (i <> FChannelId) then
begin
SetSshAction(saRead);
Result := False;
Exit;
end;
SetLength(start, 1);
SetLength(length, 1);
foo := FPacket.GetString(start, length);
ADestination.Write(foo[start[0]], length[0]);
Dec(FLocalWindowSize, length[0]);
if (FLocalWindowSize < FLocalWindowSizeMax div 2) then
begin
FIsAdjustLocalWinSize := True;
SetSshAction(saWrite);
Result := False;
Exit;
end;
FState := sshData;
Result := True;
end;
function TclSshNetworkStream.ProcessChannelDataEx(ADestination: TStream): Boolean;
var
i: Integer;
start, length: TclIntArray;
foo: TclByteArray;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessChannelDataEx', nil);{$ENDIF}
{$IFNDEF DELPHI2005}foo := nil; start := nil; length := nil;{$ENDIF}
FPacket.GetInt();
FPacket.GetByte();
FPacket.GetByte();
i := FPacket.GetInt();
if (i <> FChannelId) then
begin
SetSshAction(saRead);
Result := False;
Exit;
end;
SetLength(start, 1);
SetLength(length, 1);
foo := FPacket.GetString(start, length);
Dec(FLocalWindowSize, length[0]);
if (FLocalWindowSize < FLocalWindowSizeMax div 2) then
begin
FIsAdjustLocalWinSize := True;
SetSshAction(saWrite);
Result := False;
Exit;
end;
FState := sshData;
Result := True;
end;
function TclSshNetworkStream.ProcessChannelFailure: Boolean;
var
i: Integer;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessChannelFailure', nil);{$ENDIF}
Result := False;
FPacket.GetInt();
FPacket.GetShort();
i := FPacket.GetInt();
if (i <> FChannelId) then
begin
SetSshAction(saRead);
Exit;
end;
RaiseSshError(RequestSubsystemError, RequestSubsystemErrorCode);
end;
function TclSshNetworkStream.ProcessChannelOpenConfirmation: Boolean;
var
i: Integer;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessChannelOpenConfirmation', nil);{$ENDIF}
FPacket.GetInt();
FPacket.GetShort();
i := FPacket.GetInt();
if (i <> FChannelId) then
begin
SetSshAction(saRead);
Result := False;
Exit;
end;
FRecipientId := FPacket.GetInt();
FRemoteWindowSize := FPacket.GetInt();
FRemotePacketSize := FPacket.GetInt();
FState := sshChannelRequest;
Result := WriteData(nil, 0);
if (not Result) then
begin
SetSshAction(saWrite);
end;
end;
function TclSshNetworkStream.ProcessChannelOpenFailure: Boolean;
var
i, reason_code: Integer;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessChannelOpenFailure', nil);{$ENDIF}
Result := False;
FPacket.GetInt();
FPacket.GetShort();
i := FPacket.GetInt();
if (i <> FChannelId) then
begin
SetSshAction(saRead);
Exit;
end;
reason_code := FPacket.GetInt();
RaiseSshError(ChannelOpenError, reason_code);
end;
function TclSshNetworkStream.ProcessChannelOpenSuccess: Boolean;
var
i: Integer;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessChannelOpenSuccess', nil);{$ENDIF}
FPacket.GetInt();
FPacket.GetShort();
i := FPacket.GetInt();
if (i <> FChannelId) then
begin
SetSshAction(saRead);
Result := False;
Exit;
end;
FState := sshData;
DoStreamReady();
Result := True;
end;
function TclSshNetworkStream.ProcessChannel(ADestination: TStream): Boolean;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessChannel, FPacket.Buffer[5] = ' + IntToStr(FPacket.Buffer[5]), nil);{$ENDIF}
Result := True;
case FPacket.Buffer[5] of
SSH_MSG_CHANNEL_OPEN_CONFIRMATION: Result := ProcessChannelOpenConfirmation();
SSH_MSG_CHANNEL_OPEN_FAILURE: Result := ProcessChannelOpenFailure();
SSH_MSG_CHANNEL_SUCCESS: Result := ProcessChannelOpenSuccess();
SSH_MSG_CHANNEL_FAILURE: Result := ProcessChannelFailure();
SSH_MSG_CHANNEL_DATA: Result := ProcessChannelData(ADestination);
SSH_MSG_CHANNEL_EXTENDED_DATA: Result := ProcessChannelDataEx(ADestination);
//SSH_MSG_CHANNEL_OPEN
//SSH_MSG_CHANNEL_REQUEST
//SSH_MSG_CHANNEL_EOF
//SSH_MSG_CHANNEL_CLOSE
end;
end;
function TclSshNetworkStream.ProcessData(ASource, ADestination: TStream): Boolean;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessData', nil);{$ENDIF}
Result := True;
ClearSshAction();
if (sshVersionExchange = FState) then
begin
if (not ProcessVersionExchange(ASource)) then
begin
Result := False;
end;
end else
begin
if (not FillBuffer(ASource)) then
begin
SetSshAction(saRead);
Result := False;
Exit;
end;
case FState of
sshKeyExchangeInit: Result := ProcessKeyExchangeInit();
sshKeyExchange: Result := ProcessKeyExchange();
sshNewKeys: Result := ProcessNewKeys();
sshAuthenticateInit: Result := ProcessAuthenticateInit();
sshAuthenticate: Result := ProcessAuthenticate();
sshChannelOpen, sshChannelRequest, sshData: Result := ProcessChannel(ADestination);
//SSH_MSG_KEXINIT
//SSH_MSG_NEWKEYS
//SSH_MSG_GLOBAL_REQUEST
//SSH_MSG_REQUEST_SUCCESS
//SSH_MSG_REQUEST_FAILURE
end;
end;
end;
function TclSshNetworkStream.ProcessKeyExchange: Boolean;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessKeyExchange', nil);{$ENDIF}
if (FKex.GetState() <> FPacket.Buffer[5]) then
begin
RaiseSshError(InvalidKexProtocol, FPacket.Buffer[5]);
end;
Result := WriteData(nil, 0);
if (not Result) then
begin
SetSshAction(saWrite);
end;
end;
function TclSshNetworkStream.ProcessKeyExchangeInit: Boolean;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessKeyExchangeInit', nil);{$ENDIF}
if (FPacket.Buffer[5] <> SSH_MSG_KEXINIT) then
begin
RaiseSshError(InvalidProtocol, FPacket.Buffer[5]);
end;
Result := WriteData(nil, 0);
if (not Result) then
begin
SetSshAction(saWrite);
end;
end;
function TclSshNetworkStream.ProcessNewKeys: Boolean;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessNewKeys', nil);{$ENDIF}
if (FPacket.Buffer[5] = SSH_MSG_NEWKEYS) then
begin
UpdateKeys(FKex);
end else
begin
RaiseSshError(InvalidNewKeysProtocol, FPacket.Buffer[5]);
end;
FState := sshAuthenticateInit;
Result := WriteData(nil, 0);
if (not Result) then
begin
SetSshAction(saWrite);
end;
end;
function TclSshNetworkStream.ProcessVersionExchange(ASource: TStream): Boolean;
var
i: Integer;
b: Byte;
oldPos: Int64;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ProcessVersionExchange', nil);{$ENDIF}
oldPos := ASource.Position;
i := 0;
while (i < Length(FPacket.Buffer)) do
begin
if (ASource.Read(b, SizeOf(b)) <> SizeOf(b)) then
begin
ASource.Position := oldPos;
SetSshAction(saRead);
Result := False;
Exit;
end;
FPacket.Buffer[i] := b;
Inc(i);
if (b = 10) then Break;
end;
if (FPacket.Buffer[i - 1] = 10) then
begin
Dec(i);
if (FPacket.Buffer[i - 1] = 13) then
begin
Dec(i);
end;
end;
if (i = Length(FPacket.Buffer)) or
(i < 7) or // SSH-1.99 or SSH-2.0
((FPacket.Buffer[4] = 31) and (FPacket.Buffer[6] <> 39)) // SSH-1.5
then
begin
RaiseSshError(InvalidVersion, InvalidVersionCode);
end;
FV_S := System.Copy(FPacket.Buffer, 0, i);
Result := WriteData(nil, 0);
if (not Result) then
begin
SetSshAction(saWrite);
end;
end;
procedure TclSshNetworkStream.RaiseSshError(const AErrorMsg: string; AErrorCode: Integer);
begin
FLastErrorText := AErrorMsg;
FLastErrorCode := AErrorCode;
raise EclSshError.Create(AErrorMsg, AErrorCode);
end;
function TclSshNetworkStream.Read(AData: TStream): Boolean;
var
oldPos, curPos: Int64;
begin
Result := True;
oldPos := -1;
if (AData <> nil) then
begin
oldPos := AData.Position;
end;
try
if (FMoreDataNeeded or (FReadData.Size <= 0)) then
begin
curPos := FReadData.Position;
FReadData.Seek(0, soEnd);
Result := inherited Read(FReadData);
FReadData.Position := curPos;
end;
FMoreDataNeeded := not ProcessData(FReadData, AData);
if ((FReadData.Size - FReadData.Position) <= 0) then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'Read ((FReadData.Size - readData.Position) <= 0): ' + IntToStr(FReadData.Size));{$ENDIF}
FReadData.Size := 0;
end;
HasReadData := (FReadData.Size > 0);
finally
if (oldPos > -1) then
begin
DoUpdateProgress(AData.Position - oldPos);
end;
end;
SetNextAction(FSshAction);
end;
procedure TclSshNetworkStream.ResetSsh;
begin
FIsAdjustLocalWinSize := False;
FIsAdjustRemoteWinSize := False;
FState := sshVersionExchange;
FPacket.Init();
FWritePacket.Init();
FChannelId := 0;
FRecipientId := -1;
FLocalWindowSizeMax := $100000;
FLocalWindowSize := $100000;
FLocalPacketSize := $4000;
FRemoteWindowSize := 0;
FRemotePacketSize := 0;
FreeAndNil(FKex);
SetLength(FSessionId, 0);
FreeAndNil(FAuth);
FSeqi := 0;
FSeqo := 0;
SetLength(FIVc2s, 0);
SetLength(FIVs2c, 0);
SetLength(FEc2s, 0);
SetLength(FEs2c, 0);
SetLength(FMACc2s, 0);
SetLength(FMACs2c, 0);
FreeAndNil(FS2ccipher);
FreeAndNil(FC2scipher);
FreeAndNil(FS2cmac);
FreeAndNil(FC2smac);
SetLength(FMac_buf, 0);
FreeAndNil(FDeflater);
FreeAndNil(FInflater);
FAuthMethods := '';
FReadPacketLength := -1;
FReadDataFilled := False;
SetLength(FV_S, 0);
SetLength(FV_C, 0);
SetLength(FI_C, 0);
SetLength(FI_S, 0);
FCipher_size := 8;
end;
procedure TclSshNetworkStream.SendKexInit(ADestination: TStream);
begin
FPacket.Reset();
FPacket.PutByte(SSH_MSG_KEXINIT);
FRandom.Fill(FPacket.Buffer, FPacket.GetIndex(), 16);
FPacket.Skip(16);
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('kex')));
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('server.hostkey')));
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('cipher.c2s')));
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('cipher.s2c')));
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('mac.c2s')));
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('mac.s2c')));
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('compression.c2s')));
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('compression.s2c')));
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('lang.c2s')));
FPacket.PutString(TclTranslator.GetBytes(FConfig.GetConfig('lang.s2c')));
FPacket.PutByte(0);//TODO KEX First Packet Follows, probably, set it to 1 (true)
FPacket.PutInt(0);
FPacket.SetOffSet(5);
SetLength(FI_C, FPacket.GetLength());
FPacket.GetByte(FI_C);
PreparePacket(ADestination, FPacket);
end;
procedure TclSshNetworkStream.SetSshAction(Action: TclNetworkStreamAction);
begin
if (saNone = FSshAction) then
begin
FSshAction := Action;
end;
end;
procedure TclSshNetworkStream.StreamReady;
begin
end;
procedure TclSshNetworkStream.UpdateKeys(AKex: TclSshKeyExchanger);
var
K, H, foo: TclByteArray;
hash: TclHash;
guess: TStrings;
j: Integer;
s: string;
begin
{$IFNDEF DELPHI2005}K := nil; H := nil; foo := nil;{$ENDIF}
K := AKex.GetK();
H := AKex.GetH();
hash := AKex.GetHash();
guess := AKex.GuessAlgorithms;
if (Length(FSessionId) = 0) then
begin
FSessionId := H;
end;
FPacket.Init();
FPacket.PutMPInt(K);
FPacket.PutByte(H);
FPacket.PutByte($41);
FPacket.PutByte(FSessionId);
hash.Update(FPacket.Buffer, 0, FPacket.GetIndex());
FIVc2s := hash.Digest();
j := FPacket.GetIndex() - Length(FSessionId) - 1;
FPacket.Buffer[j] := FPacket.Buffer[j] + 1;
hash.Update(FPacket.Buffer, 0, FPacket.GetIndex());
FIVs2c := hash.Digest();
FPacket.Buffer[j] := FPacket.Buffer[j] + 1;
hash.Update(FPacket.Buffer, 0, FPacket.GetIndex());
FEc2s := hash.Digest();
FPacket.Buffer[j] := FPacket.Buffer[j] + 1;
hash.Update(FPacket.Buffer, 0, FPacket.GetIndex());
FEs2c := hash.Digest();
FPacket.Buffer[j] := FPacket.Buffer[j] + 1;
hash.Update(FPacket.Buffer, 0, FPacket.GetIndex());
FMACc2s := hash.Digest();
FPacket.Buffer[j] := FPacket.Buffer[j] + 1;
hash.Update(FPacket.Buffer, 0, FPacket.GetIndex());
FMACs2c := hash.Digest();
FreeAndNil(FS2ccipher);
FS2ccipher := TclCipher(FConfig.CreateInstance(guess[PROPOSAL_ENC_ALGS_STOC]));
if (FS2ccipher = nil) then
begin
RaiseSshError(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode);
end;
while (FS2ccipher.GetBlockSize() > Length(FEs2c)) do
begin
FPacket.Init();
FPacket.PutMPInt(K);
FPacket.PutByte(H);
FPacket.PutByte(FEs2c);
hash.Update(FPacket.Buffer, 0, FPacket.GetIndex());
foo := hash.Digest();
SetLength(FEs2c, Length(FEs2c) + Length(foo));
System.Move(foo[0], FEs2c[Length(FEs2c) - Length(foo)], Length(foo));
end;
FS2ccipher.Init(cmDecrypt, FEs2c, FIVs2c);
FCipher_size := FS2ccipher.GetIVSize();
FreeAndNil(FS2cmac);
FS2cmac := TclMac(FConfig.CreateInstance(guess[PROPOSAL_MAC_ALGS_STOC]));
if (FS2cmac = nil) then
begin
RaiseSshError(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode);
end;
FS2cmac.Init(FMACs2c, 0, FS2cmac.GetBlockSize());
SetLength(FMac_buf, FS2cmac.GetBlockSize());
FreeAndNil(FC2scipher);
FC2scipher := TclCipher(FConfig.CreateInstance(guess[PROPOSAL_ENC_ALGS_CTOS]));
if (FC2scipher = nil) then
begin
RaiseSshError(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode);
end;
while (FC2scipher.GetBlockSize() > Length(FEc2s)) do
begin
FPacket.Init();
FPacket.PutMPInt(K);
FPacket.PutByte(H);
FPacket.PutByte(FEc2s);
hash.Update(FPacket.Buffer, 0, FPacket.GetIndex());
foo := hash.Digest();
SetLength(FEc2s, Length(FEc2s) + Length(foo));
System.Move(foo[0], FEc2s[Length(FEc2s) - Length(foo)], Length(foo));
end;
FC2scipher.Init(cmEncrypt, FEc2s, FIVc2s);
FreeAndNil(FC2smac);
FC2smac := TclMac(FConfig.CreateInstance(guess[PROPOSAL_MAC_ALGS_CTOS]));
if (FC2smac = nil) then
begin
RaiseSshError(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode);
end;
FC2smac.Init(FMACc2s, 0, FC2smac.GetBlockSize());
if (guess[PROPOSAL_COMP_ALGS_CTOS] <> 'none') then
begin
s := FConfig.GetConfig(guess[PROPOSAL_COMP_ALGS_CTOS]);
if (s <> '') then
begin
FreeAndNil(FDeflater);
FDeflater := TclCompression(FConfig.CreateInstance(s));
if (FDeflater = nil) then
begin
RaiseSshError(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode);
end;
FDeflater.Init(ctDeflater, 6); //TODO add compression level to config
end;
end else
begin
FreeAndNil(FDeflater);
end;
if (guess[PROPOSAL_COMP_ALGS_STOC] <> 'none') then
begin
s := FConfig.GetConfig(guess[PROPOSAL_COMP_ALGS_STOC]);
if (s <> '') then
begin
FreeAndNil(FInflater);
FInflater := TclCompression(FConfig.CreateInstance(s));
if (FInflater = nil) then
begin
RaiseSshError(AlgorithmNegotiationError, AlgorithmNegotiationErrorCode);
end;
FInflater.Init(ctInflater, 0);
end;
end else
begin
FreeAndNil(FInflater);
end;
end;
procedure TclSshNetworkStream.UpdateProgress(ABytesProceed: Int64);
begin
end;
function TclSshNetworkStream.Write(AData: TStream): Boolean;
begin
Result := True;
if (AData <> nil) then
begin
while (Result and (AData.Position < AData.Size)) do
begin
if (FWriteData.Size = 0) then
begin
FWriteSize := GetBatchSize();
if (FWriteSize > AData.Size - AData.Position) then
begin
FWriteSize := Integer(AData.Size - AData.Position);
end;
Result := WriteData(AData, FWriteSize);
if (Result) then
begin
DoUpdateProgress(FWriteSize);
end;
end else
begin
Result := WriteData(nil, 0);
if (Result) then
begin
DoUpdateProgress(FWriteSize);
end;
end;
end;
end else
begin
Result := WriteData(AData, 0);
end;
SetNextAction(FSshAction);
end;
function TclSshNetworkStream.WriteData(ASource: TStream; ALength: Integer): Boolean;
begin
PrepareData(ASource, FWriteData);
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'WriteData, FWriteData.Position=%d, FWriteData.Size=%d', nil,
[FWriteData.Position, FWriteData.Size]);{$ENDIF}
Result := inherited Write(FWriteData);
if (Result) then
begin
FWriteData.Size := 0;
end;
end;
end.
|
unit ufrmPenjualan;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDefault, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxCheckBox, cxStyles, cxCustomData,
cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData,
System.ImageList, Vcl.ImgList, Datasnap.DBClient, Datasnap.Provider,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView,
cxGrid, cxClasses, System.Actions, Vcl.ActnList, dxBar, dxBarExtItems,
cxBarEditItem, dxBarExtDBItems, Vcl.ExtCtrls, dxStatusBar,
cxDBExtLookupComboBox, cxCurrencyEdit, cxContainer, Vcl.ComCtrls, dxCore,
cxDateUtils, cxGridLevel, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit,
cxMemo, cxMaskEdit, cxCalendar, cxTextEdit, Vcl.StdCtrls, ClientModule,
uPenjualan, uDBUtils, uAppUtils, Vcl.Menus, cxCalc, dxBarBuiltInMenu, cxPC,
cxButtons, uReport, uInterface,uDMReport,Data.FireDACJSONReflect,
uReturSupplier, uSupplier, ufrmPembayaranPOS, System.StrUtils;
type
TfrmPenjualan = class(TfrmDefault)
pnlInput: TPanel;
pgcHeader: TPageControl;
tsHeader: TTabSheet;
lblNoBukti: TLabel;
lblTglBukti: TLabel;
lblSupplier: TLabel;
lblKeterangan: TLabel;
lblPembeli: TLabel;
edNoBukti: TcxTextEdit;
edTglBukti: TcxDateEdit;
memKeterangan: TcxMemo;
cbbSalesman: TcxExtLookupComboBox;
cbbPembeli: TcxExtLookupComboBox;
pgcDetail: TPageControl;
tsDetailPenerimaan: TTabSheet;
cxGridDBPenjualan: TcxGrid;
cxGridTablePenjualan: TcxGridTableView;
cxgrdclmnGridTablePenjualanColumnSKU: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnNama: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnSatuan: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnHarga: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnQty: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnDiskon: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnPPN: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnSubTotalRp: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnDiskonRp: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnPPNRp: TcxGridColumn;
cxgrdclmnGridTablePenjualanColumnTotal: TcxGridColumn;
cxgrdlvlPenerimaanBarang: TcxGridLevel;
lblJthTempo: TLabel;
edJthTempo: TcxDateEdit;
cxgrdclmnGridTablePenjualanColumnKonversi: TcxGridColumn;
pmHarga: TPopupMenu;
Umum1: TMenuItem;
Bengkel1: TMenuItem;
Keliling1: TMenuItem;
Grosir1: TMenuItem;
lblJenisPembayaran: TLabel;
cbbJenisPembayaran: TcxComboBox;
lblTempo: TLabel;
edTempo: TcxCalcEdit;
btnInvoice: TcxButton;
lblFee: TLabel;
cbbFee: TcxComboBox;
cxgrdclmnGridTablePenjualanColumnJenisHarga: TcxGridColumn;
pnlPLU: TPanel;
lblPLU: TLabel;
edPLUNama: TcxTextEdit;
edPLU: TcxTextEdit;
edKodePembeli: TcxTextEdit;
lblDeposit: TLabel;
edDeposit: TcxCurrencyEdit;
procedure ActionBaruExecute(Sender: TObject);
procedure ActionHapusExecute(Sender: TObject);
procedure ActionRefreshExecute(Sender: TObject);
procedure ActionSimpanExecute(Sender: TObject);
procedure actNextTransactionExecute(Sender: TObject);
procedure Bengkel1Click(Sender: TObject);
procedure cxgrdclmnGridTablePenjualanColumnSatuanPropertiesInitPopup(
Sender: TObject);
procedure cxgrdclmnGridTablePenjualanColumnNamaPropertiesValidate(
Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
procedure cxgrdclmnGridTablePenjualanColumnQtyPropertiesValidate(
Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
procedure cxgrdclmnGridTablePenjualanColumnDiskonPropertiesValidate(
Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
procedure cxgrdclmnGridTablePenjualanColumnPPNPropertiesValidate(
Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
procedure cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift:
TShiftState; var AHandled: Boolean);
procedure Grosir1Click(Sender: TObject);
procedure Keliling1Click(Sender: TObject);
procedure Umum1Click(Sender: TObject);
procedure edTempoPropertiesChange(Sender: TObject);
procedure edTglBuktiPropertiesChange(Sender: TObject);
procedure cbbJenisPembayaranPropertiesChange(Sender: TObject);
procedure edKodePembeliKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
procedure edPLUKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure cbbPembeliPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
private
fCDSNama: tclientDataSet;
FCDSPembeli: TClientDataset;
FCDSSalesman: TClientDataset;
fCDSSKU: tclientDataSet;
FInfix: string;
FPenjualan: TPenjualan;
function GetBaris(AID : String): Integer;
function GetCDSPembeli: TClientDataset;
function GetCDSSalesman: TClientDataset;
function GetPenjualan: TPenjualan;
procedure HitungNilaiNilaiPerBaris(dNilai: Double; Acolumn : Integer);
procedure InisialisasiCBBSalesman;
procedure InisialisasiCBBPembeli;
procedure InisialisasiCBBSKU;
procedure InisialisasiCBBUOM;
function IsBisaSimpan: Boolean;
function IsPenjualanItemValid: Boolean;
function IsPLUKetemu(AKode : String; var AQtyInput : Double): Boolean;
{ Private declarations }
protected
function getDefaultHarga: string; virtual;
function JenisPenjualan: string; virtual;
function JenisPembayaran: string; virtual;
procedure LoadDataPembeli(AKode : String);
procedure SetHarga(AJenisHarga : String);
procedure SetInfix; virtual;
property CDSPembeli: TClientDataset read GetCDSPembeli write FCDSPembeli;
property CDSSalesman: TClientDataset read GetCDSSalesman write FCDSSalesman;
property Infix: string read FInfix write FInfix;
public
procedure CetakSlip; override;
procedure LoadData(AID : String); stdcall;
property Penjualan: TPenjualan read GetPenjualan write FPenjualan;
{ Public declarations }
end;
var
frmPenjualan: TfrmPenjualan;
implementation
uses
uModel, ufrmCustomerInvoice, System.Math;
{$R *.dfm}
procedure TfrmPenjualan.cbbJenisPembayaranPropertiesChange(Sender: TObject);
begin
inherited;
if cbbJenisPembayaran.Text = 'CASH' then
begin
edTempo.Text := '0';
edTempo.Enabled := False;
end else begin
edTempo.Enabled := True;
end;
end;
procedure TfrmPenjualan.cbbPembeliPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
inherited;
edKodePembeli.Text := FCDSPembeli.FieldByName('kode').AsString;
edKodePembeli.SetFocus;
end;
procedure TfrmPenjualan.cxgrdclmnGridTablePenjualanColumnDiskonPropertiesValidate(
Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
var
dNilai: Double;
begin
inherited;
dNilai := DisplayValue;
HitungNilaiNilaiPerBaris(dNilai, cxgrdclmnGridTablePenjualanColumnDiskon.Index);
end;
procedure TfrmPenjualan.cxgrdclmnGridTablePenjualanColumnNamaPropertiesValidate(
Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
var
dDiskon: Double;
dQty: Double;
iBaris: Integer;
lDSt: TDataset;
begin
inherited;
iBaris := cxGridTablePenjualan.DataController.FocusedRecordIndex;
lDSt := (TcxExtLookupComboBoxProperties(cxgrdclmnGridTablePenjualanColumnNama.Properties)).Dataset;
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnSKU.Index,lDSt.FieldByName('barang').AsString);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnSatuan.Index,lDSt.FieldByName('uom').AsString);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnHarga.Index,lDSt.FieldByName(getDefaultHarga).AsString);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnJenisHarga.Index,getDefaultHarga);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnKonversi.Index,lDSt.FieldByName('konversi').AsFloat);
dQty := cxGridTablePenjualan.GetDouble(iBaris, cxgrdclmnGridTablePenjualanColumnQty.Index);
if dQty = 0 then
dQty := 1;
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnQty.Index,dQty);
dDiskon := cxGridTablePenjualan.GetDouble(iBaris, cxgrdclmnGridTablePenjualanColumnDiskon.Index);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnDiskon.Index, dDiskon);
HitungNilaiNilaiPerBaris(dDiskon, cxgrdclmnGridTablePenjualanColumnDiskon.Index);
end;
procedure TfrmPenjualan.cxgrdclmnGridTablePenjualanColumnPPNPropertiesValidate(
Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
var
dNilai: Double;
begin
inherited;
dNilai := DisplayValue;
HitungNilaiNilaiPerBaris(dNilai, cxgrdclmnGridTablePenjualanColumnPPN.Index);
end;
procedure TfrmPenjualan.cxgrdclmnGridTablePenjualanColumnQtyPropertiesValidate(
Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
var
dNilai: Double;
begin
inherited;
dNilai := DisplayValue;
HitungNilaiNilaiPerBaris(dNilai, cxgrdclmnGridTablePenjualanColumnQty.Index);
end;
procedure TfrmPenjualan.cxgrdclmnGridTablePenjualanColumnSatuanPropertiesInitPopup(
Sender: TObject);
var
i: Integer;
lBrg: TBarang;
lObject: TObject;
sIDBarang: string;
begin
inherited;
sIDBarang := cxGridTablePenjualan.GetString(cxGridTablePenjualan.DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnSKU.Index);
if sIDBarang = '' then
Exit;
with (TcxExtLookupComboBoxProperties(cxgrdclmnGridTablePenjualanColumnSatuan.Properties).View as TcxGridDBTableView).DataController.Filter do
begin
BeginUpdate;
lBrg := TBarang.Create;
TDBUtils.LoadFromDB(lBrg, sIDBarang);
try
Root.Clear;
Root.BoolOperatorKind := fboOr;
for i := 0 to lBrg.BarangSatuanItems.Count - 1 do
begin
lObject := (TcxExtLookupComboBoxProperties(cxgrdclmnGridTablePenjualanColumnSatuan.Properties).View as TcxGridDBTableView).Columns[1];
Root.AddItem(lObject, foEqual,lBrg.BarangSatuanItems[i].UOM.ID, lBrg.BarangSatuanItems[i].UOM.ID);
end;
DataController.Filter.Active := True;
finally
EndUpdate;
lBrg.Free;
end;
end;
end;
procedure TfrmPenjualan.edTempoPropertiesChange(Sender: TObject);
begin
inherited;
edJthTempo.Date := edTglBukti.Date + edTempo.Value;
end;
procedure TfrmPenjualan.edTglBuktiPropertiesChange(Sender: TObject);
begin
inherited;
edJthTempo.Date := edTglBukti.Date + edTempo.Value;
end;
procedure TfrmPenjualan.ActionBaruExecute(Sender: TObject);
begin
inherited;
SetInfix;
with ClientDataModule.ServerPenjualanClient do
begin
edTglBukti.Date := Now;
edJthTempo.Date := edTglBukti.Date + 7;
edNoBukti.Text := GenerateNoBukti(edTglBukti.Date, ClientDataModule.Cabang.Kode + Infix);
memKeterangan.Clear;
cxGridTablePenjualan.ClearRows;
edKodePembeli.Text := '';
cbbPembeli.EditValue := null;
edDeposit.Value := 0;
edKodePembeli.SetFocus;
FreeAndNil(FPenjualan);
end;
end;
procedure TfrmPenjualan.ActionHapusExecute(Sender: TObject);
begin
inherited;
if not TAppUtils.Confirm('Anda Yakin Akan Menghapus Data ?') then
Exit;
if ClientModule.ClientDataModule.ServerPenjualanClient.Delete(Penjualan) then
ActionBaruExecute(Sender);
end;
procedure TfrmPenjualan.ActionRefreshExecute(Sender: TObject);
var
lcds: TClientDataSet;
lDS: TDataset;
begin
inherited;
if chkKonsolidasi1.Checked then
lDS := ClientDataModule.ServerLaporanClient.RetrivePenjualan(dtpAwal.DateTime, dtpAkhir.DateTime, nil)
else
lDS := ClientDataModule.ServerLaporanClient.RetrivePenjualan(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang);
lcds := TDBUtils.DSToCDS(lDS, Self);
if lcds <> nil then
begin
lcds.Filter := 'jenispenjualan = ' + QuotedStr(JenisPenjualan);
lcds.Filtered := True;
end;
cxGridDBTableOverview.SetDataset(lcds, True);
cxGridDBTableOverview.SetVisibleColumns(['id','cabangid','jenispenjualan', 'salesmanid'], False);
cxGridDBTableOverview.ApplyBestFit();
end;
procedure TfrmPenjualan.ActionSimpanExecute(Sender: TObject);
var
I: Integer;
IsBerhasilSimpan: Boolean;
lDibayar: Double;
lPenjualanItem: TPenjualanItem;
begin
inherited;
if not ValidateEmptyCtrl([1], True) then
Exit;
if not IsPenjualanItemValid then
Exit;
if Penjualan.ID = '' then
edNoBukti.Text := ClientModule.ClientDataModule.ServerPenjualanClient.GenerateNoBukti(edTglBukti.Date, ClientDataModule.Cabang.Kode + Infix);
Penjualan.NoBukti := edNoBukti.Text;
Penjualan.Cabang := TCabang.CreateID(ClientDataModule.Cabang.ID);
Penjualan.JatuhTempo := edJthTempo.Date;
Penjualan.TglBukti := edTglBukti.Date;
Penjualan.JenisPenjualan := JenisPenjualan;
Penjualan.JenisPembayaran:= cbbJenisPembayaran.Properties.Items[cbbJenisPembayaran.ItemIndex];
Penjualan.Salesman := TSupplier.CreateID(cbbSalesman.EditValue);
Penjualan.Pembeli := TSupplier.CreateID(cbbPembeli.EditValue);
Penjualan.Gudang := TGudang.CreateID(ClientDataModule.SettingApp.GudangPenjualan.ID);
Penjualan.Kasir := 'AKU';
Penjualan.Keterangan := memKeterangan.Text;
Penjualan.Fee := cbbFee.Properties.Items[cbbFee.ItemIndex];
Penjualan.TermOfPayment := Floor(edTempo.Value);
Penjualan.PenjualanItems.Clear;
for I := 0 to cxGridTablePenjualan.DataController.RecordCount - 1 do
begin
lPenjualanItem := TPenjualanItem.Create;
lPenjualanItem.Barang := TBarang.CreateID(cxGridTablePenjualan.GetString(i, cxgrdclmnGridTablePenjualanColumnSKU.Index));
lPenjualanItem.Diskon := cxGridTablePenjualan.GetDouble(i, cxgrdclmnGridTablePenjualanColumnDiskon.Index);
lPenjualanItem.Harga := cxGridTablePenjualan.GetDouble(i, cxgrdclmnGridTablePenjualanColumnHarga.Index);
lPenjualanItem.PPN := cxGridTablePenjualan.GetDouble(i, cxgrdclmnGridTablePenjualanColumnPPN.Index);
lPenjualanItem.Qty := cxGridTablePenjualan.GetDouble(i, cxgrdclmnGridTablePenjualanColumnQty.Index);
lPenjualanItem.UOM := TUOM.CreateID(cxGridTablePenjualan.GetString(i, cxgrdclmnGridTablePenjualanColumnSatuan.Index));
lPenjualanItem.Konversi := cxGridTablePenjualan.GetDouble(i, cxgrdclmnGridTablePenjualanColumnKonversi.Index);
lPenjualanItem.JenisHarga:= cxGridTablePenjualan.GetString(i, cxgrdclmnGridTablePenjualanColumnJenisHarga.Index);
lPenjualanItem.Penjualan := Penjualan;
Penjualan.PenjualanItems.Add(lPenjualanItem);
end;
IsBerhasilSimpan := False;
if cbbJenisPembayaran.Text = 'CASH' then
begin
lDibayar := TfrmPembayaranPOS.Bayar(Penjualan.Total);
if lDibayar <> 0 then
begin
IsBerhasilSimpan := ClientModule.ClientDataModule.ServerPenjualanClient.SaveToDBDibayar(Penjualan,lDibayar);
end;
end else if cbbJenisPembayaran.Text = 'DEPOSIT' then
begin
if not IsBisaSimpan then
Exit;
IsBerhasilSimpan := ClientModule.ClientDataModule.ServerPenjualanClient.Save(Penjualan);
end else
IsBerhasilSimpan := ClientModule.ClientDataModule.ServerPenjualanClient.Save(Penjualan);
if IsBerhasilSimpan then
begin
CetakSlip;
ActionBaruExecute(Sender);
end;
end;
procedure TfrmPenjualan.actNextTransactionExecute(Sender: TObject);
begin
inherited;
if FPenjualan = nil then
Exit;
frmCustomerInvoice := TfrmCustomerInvoice.Create(Application);
frmCustomerInvoice.ActionBaruExecute(Sender);
frmCustomerInvoice.LoadDataCI(FPenjualan.NoBukti);
end;
procedure TfrmPenjualan.Bengkel1Click(Sender: TObject);
begin
inherited;
SetHarga('bengkel');
end;
procedure TfrmPenjualan.CetakSlip;
var
lcds: TFDJSONDataSets;
begin
with dmReport do
begin
AddReportVariable('UserCetak', UserAplikasi.UserName);
if cxPCData.ActivePageIndex = 0 then
lcds := ClientDataModule.ServerPenjualanClient.RetrieveCDSlip(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang, '%')
else
lcds := ClientDataModule.ServerPenjualanClient.RetrieveCDSlip(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang, Penjualan.NoBukti);
// if JenisPenjualan = 'SALESMAN'then
// ExecuteReport('Reports/Slip_Penjualan' ,
// lcds
//
// )
// else
ExecuteReport('Reports/Slip_Penjualan_POS' ,lcds, True);
end;
end;
procedure TfrmPenjualan.cxGridDBTableOverviewCellDblClick(Sender:
TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
inherited;
LoadData(cxGridDBTableOverview.DS.FieldByName('ID').AsString);
cxPCData.ActivePageIndex := 1;
end;
procedure TfrmPenjualan.edKodePembeliKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
//var
// lPembeli: TSupplier;
begin
inherited;
if Key = VK_RETURN then
begin
LoadDataPembeli(edKodePembeli.Text);
edPLU.SetFocus;
end;
end;
procedure TfrmPenjualan.edPLUKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
var
dDiskon: Double;
dQty: Double;
dQTYInput: Double;
iBaris: Integer;
begin
inherited;
if Key = VK_RETURN then
begin
if trim(edPLU.Text) = '' then
begin
btnSave.SetFocus;
end else begin
if not IsPLUKetemu(trim(edPLU.Text), dQTYInput) then
Exit;
iBaris := GetBaris(fCDSSKU.FieldByName('id').AsString);
if iBaris < 0 then
begin
cxGridTablePenjualan.DataController.RecordCount := cxGridTablePenjualan.DataController.RecordCount + 1;
iBaris := cxGridTablePenjualan.DataController.RecordCount - 1;
end;
cxGridTablePenjualan.DataController.FocusedRecordIndex := iBaris;
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnNama.Index,fCDSSKU.FieldByName('ID').AsString);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnSKU.Index,fCDSSKU.FieldByName('barang').AsString);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnSatuan.Index,fCDSSKU.FieldByName('uom').AsString);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnHarga.Index,fCDSSKU.FieldByName(getDefaultHarga).AsString);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnJenisHarga.Index,getDefaultHarga);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnKonversi.Index,fCDSSKU.FieldByName('konversi').AsFloat);
dQty := cxGridTablePenjualan.GetDouble(iBaris, cxgrdclmnGridTablePenjualanColumnQty.Index);
dDiskon := cxGridTablePenjualan.GetDouble(iBaris, cxgrdclmnGridTablePenjualanColumnDiskon.Index);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnQty.Index, dQty + dQTYInput);
cxGridTablePenjualan.SetValue(iBaris, cxgrdclmnGridTablePenjualanColumnDiskon.Index, dDiskon);
HitungNilaiNilaiPerBaris(dDiskon, cxgrdclmnGridTablePenjualanColumnDiskon.Index);
edPLU.Text := '';
end;
end;
end;
procedure TfrmPenjualan.FormShow(Sender: TObject);
begin
inherited;
InisialisasiCBBSalesman;
InisialisasiCBBPembeli;
InisialisasiCBBSKU;
InisialisasiCBBUOM;
ActionBaruExecute(Sender);
IsLangsungPrint := True;
cbbJenisPembayaran.ItemIndex := cbbJenisPembayaran.Properties.Items.IndexOf(JenisPembayaran);
cbbJenisPembayaran.Enabled := False;
cbbFee.ItemIndex := 0;
CDSSalesman.Filter := ' nama = ' + QuotedStr('Point Of Sales');
CDSSalesman.Filtered := True;
try
cbbSalesman.EditValue := CDSSalesman.FieldByName('ID').AsString;
cbbSalesman.Enabled := False;
finally
CDSSalesman.Filtered := False;
end;
end;
function TfrmPenjualan.GetBaris(AID : String): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to cxGridTablePenjualan.DataController.RecordCount - 1 do
begin
if cxGridTablePenjualan.DataController.Values[i,cxgrdclmnGridTablePenjualanColumnNama.Index] = AID then
begin
Result := i;
Exit;
end;
end;
end;
function TfrmPenjualan.GetCDSPembeli: TClientDataset;
var
sSQL: string;
begin
if FCDSPembeli = nil then
begin
sSQL := 'select * from vbusinesspartner where is_pembeli = 1';
FCDSPembeli := TDBUtils.OpenDataset(sSQL, Self);
end;
Result := FCDSPembeli;
end;
function TfrmPenjualan.GetCDSSalesman: TClientDataset;
var
sSQL: string;
begin
if FCDSSalesman = nil then
begin
sSQL := 'select Nama,Kode,ID from vbusinesspartner where is_salesman = 1';
FCDSSalesman := TDBUtils.OpenDataset(sSQL);
end;
Result := FCDSSalesman;
end;
function TfrmPenjualan.getDefaultHarga: string;
begin
Result := 'keliling';
end;
function TfrmPenjualan.GetPenjualan: TPenjualan;
begin
if FPenjualan =nil then
FPenjualan := TPenjualan.Create;
Result := FPenjualan
end;
procedure TfrmPenjualan.Grosir1Click(Sender: TObject);
begin
inherited;
SetHarga('grosir');
end;
procedure TfrmPenjualan.HitungNilaiNilaiPerBaris(dNilai: Double; Acolumn :
Integer);
var
dDiskon: Double;
dHarga: Double;
dPPN: Double;
dQty: Double;
begin
dHarga := 0;
dQty := 0;
dDiskon := 0;
dPPN := 0;
// Exit;
with cxGridTablePenjualan do
begin
if Acolumn = cxgrdclmnGridTablePenjualanColumnHarga.Index then
begin
dHarga := dNilai;
dQty := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnQty.Index);
dDiskon := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnDiskon.Index);
dPPN := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnPPN.Index);
end else if Acolumn = cxgrdclmnGridTablePenjualanColumnQty.Index then
begin
dHarga := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnHarga.Index);
dQty := dNilai;
dDiskon := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnDiskon.Index);
dPPN := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnPPN.Index);
end else if Acolumn = cxgrdclmnGridTablePenjualanColumnDiskon.Index then
begin
dHarga := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnHarga.Index);
dQty := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnQty.Index);
dDiskon := dNilai;
dPPN := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnPPN.Index);
end else if Acolumn = cxgrdclmnGridTablePenjualanColumnPPN.Index then
begin
dHarga := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnHarga.Index);
dQty := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnQty.Index);
dDiskon := GetDouble(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnDiskon.Index);
dPPN := dNilai;
end;
SetValue(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnSubTotalRp.Index, dHarga * dQty);
SetValue(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnDiskonRp.Index, dHarga * dDiskon / 100 * dQty);
SetValue(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnPPNRp.Index, dHarga * (100 - dDiskon) / 100 * dQty * dPPN / 100);
SetValue(DataController.FocusedRecordIndex, cxgrdclmnGridTablePenjualanColumnTotal.Index, dHarga * (100 - dDiskon) / 100 * dQty * (dPPN + 100) / 100);
end;
end;
procedure TfrmPenjualan.InisialisasiCBBSalesman;
begin
// sSQL := 'select Nama,Kode,ID from vbusinesspartner where is_salesman = 1';
// CDSSalesman := TDBUtils.OpenDataset(sSQL);
cbbSalesman.Properties.LoadFromCDS(CDSSalesman,'ID','Nama',['ID'],Self);
cbbSalesman.Properties.SetMultiPurposeLookup;
end;
procedure TfrmPenjualan.InisialisasiCBBPembeli;
begin
cbbPembeli.Properties.LoadFromCDS(CDSPembeli,'ID','Nama',['ID','is_pembeli','is_salesman','is_supplier'],Self);
cbbPembeli.Properties.SetMultiPurposeLookup;
end;
procedure TfrmPenjualan.InisialisasiCBBSKU;
var
sSQL: string;
begin
// sSQL := 'select sku, Nama,ID from TBarang';
sSQL := 'select b.nama, b.sku, c.uom as satuan, a.hargajual as Umum,' +
' a.hargajualbengkel as bengkel,' +
' a.hargajualkeliling as keliling, a.hargajualgrosir as grosir, ' +
' a.konversi, a.id, a.barang, a.uom, a.barcode' +
' from tbarangsatuanitem a' +
' inner join tbarang b on a.barang = b.id ' +
' inner join tuom c on a.uom = c.id ' +
' order by b.nama';
fCDSSKU := TDBUtils.OpenDataset(sSQL);
TcxExtLookupComboBoxProperties(cxGridTablePenjualan.Columns[cxgrdclmnGridTablePenjualanColumnNama.Index].Properties).LoadFromCDS(FCDSSKU,'ID','Nama',['ID'],Self);
TcxExtLookupComboBoxProperties(cxGridTablePenjualan.Columns[cxgrdclmnGridTablePenjualanColumnNama.Index].Properties).SetMultiPurposeLookup();
TcxExtLookupComboBoxProperties(cxGridTablePenjualan.Columns[cxgrdclmnGridTablePenjualanColumnNama.Index].Properties).cxDBTableGrid.SetVisibleColumns(['barang','uom','id','KONVERSI'], FALSE);
TcxExtLookupComboBoxProperties(cxGridTablePenjualan.Columns[cxgrdclmnGridTablePenjualanColumnNama.Index].Properties).cxDBTableGrid.ApplyBestFit();
sSQL := 'select Nama,sku, ID from TBarang';
fCDSNama := TDBUtils.OpenDataset(sSQL);
TcxExtLookupComboBoxProperties(cxGridTablePenjualan.Columns[cxgrdclmnGridTablePenjualanColumnSKU.Index].Properties).LoadFromCDS(FCDSNama,'ID','SKU',['ID'],Self);
TcxExtLookupComboBoxProperties(cxGridTablePenjualan.Columns[cxgrdclmnGridTablePenjualanColumnSKU.Index].Properties).SetMultiPurposeLookup;
end;
procedure TfrmPenjualan.InisialisasiCBBUOM;
var
lCDSUOM: TClientDataSet;
sSQL: string;
begin
sSQL := 'select uom,ID from TUOM';
lCDSUOM := TDBUtils.OpenDataset(sSQL);
TcxExtLookupComboBoxProperties(cxGridTablePenjualan.Columns[cxgrdclmnGridTablePenjualanColumnSatuan.Index].Properties).LoadFromCDS(lCDSUOM,'ID','UOM',['ID'],Self);
TcxExtLookupComboBoxProperties(cxGridTablePenjualan.Columns[cxgrdclmnGridTablePenjualanColumnSatuan.Index].Properties).SetMultiPurposeLookup;
end;
function TfrmPenjualan.IsBisaSimpan: Boolean;
var
dBelanjaHarian: Double;
dDeposit: Double;
begin
Result := False;
dBelanjaHarian := ClientDataModule.ServerPenjualanClient.GetPenjualanPeriode(Penjualan.Pembeli, Penjualan.TglBukti, Penjualan.TglBukti, Penjualan.NoBukti);
dDeposit := ClientDataModule.ServerPenjualanClient.GetSaldoDeposit(Penjualan.Pembeli, Penjualan.NoBukti);
if Penjualan.Total > dDeposit then
begin
TAppUtils.Warning('Penjualan Melebihi Sisa Deposit' + #13 +
'Sisa Deposit Rp ' + FormatFloat(',0.##;(,0.##)', dDeposit));
Exit;
end else if Penjualan.Total > ClientDataModule.SettingApp.MaxBelanjaSantri then
begin
TAppUtils.Warning('Penjualan Melebihi Kuota Perhari'+ #13 +
'Max Belanja Per Hari Rp ' + FormatFloat(',0.##;(,0.##)', ClientDataModule.SettingApp.MaxBelanjaSantri));
Exit;
end else if (Penjualan.Total + dBelanjaHarian) > ClientDataModule.SettingApp.MaxBelanjaSantri then
begin
TAppUtils.Warning('Penjualan Periode ' + TAppUtils.QuotDLong(Penjualan.TglBukti) + ' Melebihi Kuota'+ #13 +
'Total Belanja Hari Ini Rp ' + FormatFloat(',0.##;(,0.##)', Penjualan.Total + dBelanjaHarian) + #13 +
'Kelebihan Rp ' + FormatFloat(',0.##;(,0.##)', Penjualan.Total + dBelanjaHarian - ClientDataModule.SettingApp.MaxBelanjaSantri));
Exit;
end;
Result := True;
end;
function TfrmPenjualan.IsPenjualanItemValid: Boolean;
var
I: Integer;
j: Integer;
begin
Result := False;
for I := 0 to cxGridTablePenjualan.DataController.RecordCount - 1 do
begin
cxGridTablePenjualan.DataController.FocusedRecordIndex := i;
if cxGridTablePenjualan.GetString(i,cxgrdclmnGridTablePenjualanColumnNama.Index) = '' then
begin
TAppUtils.Warning('Barang Belum Diisi');
Exit;
end;
if cxGridTablePenjualan.GetDouble(i,cxgrdclmnGridTablePenjualanColumnQty.Index) <= 0 then
begin
TAppUtils.Warning('Qty Harus >= 0');
Exit;
end;
for j := i + 1 to cxGridTablePenjualan.DataController.RecordCount - 1 do
begin
if cxGridTablePenjualan.GetString(i,cxgrdclmnGridTablePenjualanColumnNama.Index) =
cxGridTablePenjualan.GetString(j,cxgrdclmnGridTablePenjualanColumnNama.Index)then
begin
TAppUtils.Warning('Ada Barang Dan Satuan Double');
Exit;
end;
end;
end;
Result := True;
end;
function TfrmPenjualan.IsPLUKetemu(AKode : String; var AQtyInput : Double):
Boolean;
var
sFieldName: string;
sKode: string;
sQty: string;
begin
sQty := LeftStr(AKode, Pos('*',AKode)-1);
AQtyInput := StrToFloatDef(sQty,1);
sKode := StringReplace(AKode,sQty+'*','',[rfReplaceAll]);
Result := False;
fCDSSKU.First;
while not fCDSSKU.Eof do
begin
if Length(AKode) > 6 then
sFieldName := 'barcode'
else
sFieldName := 'sku';
if fCDSSKU.FieldByName(sFieldName).AsString = SKode then
begin
Result := True;
Exit;
end;
fCDSSKU.Next;
end;
end;
function TfrmPenjualan.JenisPenjualan: string;
begin
Result := 'SALESMAN';
end;
function TfrmPenjualan.JenisPembayaran: string;
begin
Result := 'DEPOSIT';
end;
procedure TfrmPenjualan.Keliling1Click(Sender: TObject);
begin
inherited;
SetHarga('keliling');
end;
procedure TfrmPenjualan.LoadData(AID : String);
var
i: Integer;
begin
try
with ClientDataModule.ServerPenjualanClient do
begin
FreeAndNil(FPenjualan);
FPenjualan := Retrieve(AID);
if FPenjualan = nil then
Exit;
if FPenjualan.ID = '' then
Exit;
edNoBukti.Text := Penjualan.NoBukti;
edTglBukti.Date:= Penjualan.TglBukti;
if Penjualan.Pembeli.ID <> '' then
cbbPembeli.EditValue := Penjualan.Pembeli.ID;
if Penjualan.Salesman.ID <> '' then
cbbSalesman.EditValue := Penjualan.Salesman.ID;
memKeterangan.Lines.Text := Penjualan.Keterangan;
edTempo.Value := Penjualan.TermOfPayment;
cbbJenisPembayaran.ItemIndex := cbbJenisPembayaran.Properties.Items.IndexOf(Penjualan.JenisPembayaran);
cbbFee.ItemIndex := cbbFee.Properties.Items.IndexOf(Penjualan.Fee);
cxGridTablePenjualan.ClearRows;
for i := 0 to Penjualan.PenjualanItems.Count - 1 do
begin
cxGridTablePenjualan.DataController.RecordCount := i + 1;
cxGridTablePenjualan.SetValue(i, cxgrdclmnGridTablePenjualanColumnSKU.Index, FPenjualan.PenjualanItems[i].Barang.ID);
cxGridTablePenjualan.SetValue(i, cxgrdclmnGridTablePenjualanColumnNama.Index, FPenjualan.PenjualanItems[i].BarangSatuangItemID);
cxGridTablePenjualan.SetValue(i, cxgrdclmnGridTablePenjualanColumnSatuan.Index, FPenjualan.PenjualanItems[i].UOM.ID);
cxGridTablePenjualan.SetDouble(i, cxgrdclmnGridTablePenjualanColumnHarga.Index, FPenjualan.PenjualanItems[i].Harga);
cxGridTablePenjualan.SetDouble(i, cxgrdclmnGridTablePenjualanColumnQty.Index, FPenjualan.PenjualanItems[i].Qty);
cxGridTablePenjualan.SetDouble(i, cxgrdclmnGridTablePenjualanColumnDiskon.Index,FPenjualan.PenjualanItems[i].Diskon);
cxGridTablePenjualan.SetDouble(i, cxgrdclmnGridTablePenjualanColumnPPN.Index, FPenjualan.PenjualanItems[i].PPN);
cxGridTablePenjualan.SetDouble(i, cxgrdclmnGridTablePenjualanColumnKonversi.Index, FPenjualan.PenjualanItems[i].Konversi);
cxGridTablePenjualan.SetValue(i, cxgrdclmnGridTablePenjualanColumnJenisHarga.Index, FPenjualan.PenjualanItems[i].JenisHarga);
cxGridTablePenjualan.DataController.FocusedRecordIndex := i;
HitungNilaiNilaiPerBaris(FPenjualan.PenjualanItems[i].PPN, cxgrdclmnGridTablePenjualanColumnPPN.Index);
end;
end;
// Result := True;
except
raise
end;
end;
procedure TfrmPenjualan.LoadDataPembeli(AKode : String);
var
lPembeli: TSupplier;
begin
FCDSPembeli.First;
while not FCDSPembeli.Eof do
begin
if FCDSPembeli.FieldByName('kode').AsString = AKode then
begin
cbbPembeli.EditValue := FCDSPembeli.FieldByName('ID').AsString;
lPembeli := TSupplier.CreateID(cbbPembeli.EditValue);
try
edDeposit.Value := ClientDataModule.ServerPenjualanClient.GetSaldoDeposit(lPembeli, edNoBukti.Text);
finally
lPembeli.Free;
end;
end;
FCDSPembeli.Next;
end;
end;
procedure TfrmPenjualan.SetHarga(AJenisHarga : String);
var
dHarga: Double;
dst: tclientDataSet;
iBaris: Integer;
lCDS: tclientDataSet;
begin
lCDS := TClientDataSet.Create(Self);
try
iBaris := cxGridTablePenjualan.FocusedIndex;
dst := tclientDataSet(((TcxExtLookupComboBoxProperties(cxgrdclmnGridTablePenjualanColumnNama.Properties).View) as TcxGridDBTableView).DataController.DataSource.DataSet);
lCDS.CloneCursor(dst, False);
lCDS.Filter := 'id = ' + QuotedStr(cxGridTablePenjualan.GetString(iBaris,cxgrdclmnGridTablePenjualanColumnNama.Index ));
lCDS.Filtered :=True;
dHarga := lCDS.FieldByName(AJenisHarga).AsFloat;
cxGridTablePenjualan.DataController.Values[iBaris, cxgrdclmnGridTablePenjualanColumnHarga.Index] := dHarga;
cxGridTablePenjualan.DataController.Values[iBaris, cxgrdclmnGridTablePenjualanColumnJenisHarga.Index] := AJenisHarga;
HitungNilaiNilaiPerBaris(dHarga, cxgrdclmnGridTablePenjualanColumnHarga.Index);
finally
end;
end;
procedure TfrmPenjualan.SetInfix;
begin
Infix := '/SLS';
end;
procedure TfrmPenjualan.Umum1Click(Sender: TObject);
begin
inherited;
SetHarga('umum');
end;
end.
|
unit GX_CompRename;
(* Things left to consider:
* - Search a new component's ancestors to get an alternate rename rule
* - Remove timer hack somehow?
* - Allow explicit %d rename rules to apply before the rename dialog shows
*)
{$I GX_CondDefine.inc}
interface
uses
Classes, Controls, Forms, StdCtrls, ExtCtrls, ToolsAPI,
GX_Experts, GX_ConfigurationInfo, GX_EditorChangeServices, Contnrs,
GX_BaseForm;
type
TCompRenameExpert = class;
TIsValidComponentName = function (const OldName, NewName: WideString; var Reason: WideString): Boolean of object;
// Simple rename dialog that shows the old and new component name
TfmCompRename = class(TfmBaseForm)
lblOldName: TLabel;
edtOldName: TEdit;
lblNewName: TLabel;
edtNewName: TEdit;
btnCancel: TButton;
btnOK: TButton;
lblReason: TLabel;
btnSettings: TButton;
procedure FormCreate(Sender: TObject);
procedure edtNewNameChange(Sender: TObject);
procedure btnSettingsClick(Sender: TObject);
private
FIsValidComponentName: TIsValidComponentName;
FProperties: TObjectList;
function GetNewName: WideString;
function GetOldName: WideString;
procedure SetNewName(const Value: WideString);
procedure SetOldName(const Value: WideString);
procedure AddComponentProperty(const PropertyName, Value: WideString);
function GetComponentProperty(Index: Integer): WideString;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
property OldName: WideString read GetOldName write SetOldName;
property NewName: WideString read GetNewName write SetNewName;
function Execute: TModalResult;
procedure SetRuleSelection(SelStart, SelEnd: Integer);
property OnIsValidComponentName: TIsValidComponentName read FIsValidComponentName write FIsValidComponentName;
end;
TCompRenameNotifier = class(TInterfacedObject, IGxEditorNotification)
private
FChangeServiceNotifierIndex: Integer;
FClient: TCompRenameExpert;
protected
// IGxEditorNotification
procedure NewModuleOpened(const Module: IOTAModule);
procedure SourceEditorModified(const SourceEditor: IOTASourceEditor);
procedure FormEditorModified(const FormEditor: IOTAFormEditor);
procedure ComponentRenamed(const FormEditor: IOTAFormEditor;
Component: IOTAComponent; const OldName, NewName: string);
function EditorKeyPressed(const SourceEditor: IOTASourceEditor; CharCode: Word; KeyData: Integer): Boolean;
function GetIndex: Integer;
protected
procedure Attach;
public
constructor Create(const Client: TCompRenameExpert);
destructor Destroy; override;
procedure Detach;
end;
TCompRenameExpert = class(TGX_Expert)
private
FCompRenameNotifier: TCompRenameNotifier;
FRenameRuleList: TStringList;
FShowDialog: Boolean;
FAutoAddClasses: Boolean;
FComponentNames: TStringList;
FFormNames: TStringList;
FTimer: TTimer;
FTimerCount: Integer;
FFormEditor: IOTAFormEditor;
function DoRename(const Component: IOTAComponent; UseRules: Boolean): TModalResult;
protected
procedure AddNewClass(const AClassName: WideString);
procedure DoOnTimer(Sender: TObject);
function GetClassRenameRule(const AClassName: WideString): WideString;
procedure InternalLoadSettings(Settings: TExpertSettings); override;
procedure InternalSaveSettings(Settings: TExpertSettings); override;
procedure ComponentRenamed(const FormEditor: IOTAFormEditor;
Component: IOTAComponent; const OldName, NewName: WideString);
procedure FormEditorModified(const FormEditor: IOTAFormEditor);
function IsValidComponentName(const OldName, NewName: WideString; var Reason: WideString): Boolean;
procedure AddNotifier;
procedure RemoveNotifier;
function IsDefaultComponentName(Component: IOTAComponent; const NewName: WideString): Boolean;
public
constructor Create; override;
destructor Destroy; override;
procedure Execute(Sender: TObject); override;
procedure Configure; override;
function GetActionCaption: string; override;
function GetDefaultShortCut: TShortCut; override;
class function GetName: string; override;
function HasConfigOptions: Boolean; override;
procedure SetActive(New: Boolean); override;
function IsDefaultActive: Boolean; override;
function HasDesignerMenuItem: Boolean; override;
end;
implementation
{$R *.dfm}
uses
SysUtils, Windows, Menus, GX_CompRenameConfig, GX_OtaUtils, GX_GenericUtils,
GX_IdeUtils, Graphics, GX_GxUtils;
resourcestring
SPropertyNotFound = 'Property not found';
var
PrivateCompRenameExpert: TCompRenameExpert;
{ TfmCompRename }
function TfmCompRename.Execute: TModalResult;
begin
ActiveControl := edtNewName;
lblReason.Top := btnOK.Top + Round((btnOK.Height / 2) - (lblReason.Height / 2));
Result := ShowModal;
end;
function TfmCompRename.GetNewName: WideString;
begin
Result := Trim(edtNewName.Text);
end;
function TfmCompRename.GetOldName: WideString;
begin
Result := Trim(edtOldName.Text);
end;
procedure TfmCompRename.SetNewName(const Value: WideString);
begin
edtNewName.Text := Value;
edtNewName.Modified := False;
end;
procedure TfmCompRename.SetOldName(const Value: WideString);
begin
edtOldName.Text := Value;
end;
procedure TfmCompRename.edtNewNameChange(Sender: TObject);
var
OldName: WideString;
NewName: WideString;
Reason: WideString;
begin
if Assigned(FIsValidComponentName) then
begin
OldName := edtOldName.Text;
NewName := edtNewName.Text;
btnOK.Enabled := FIsValidComponentName(OldName, NewName, Reason);
if btnOK.Enabled then
lblReason.Visible := False
else
begin
lblReason.Caption := Reason;
lblReason.Visible := True;
end;
end
else
btnOK.Enabled := IsValidIdent(edtNewName.Text);
end;
procedure TfmCompRename.SetRuleSelection(SelStart, SelEnd: Integer);
begin
edtNewName.SelStart := SelStart;
if SelEnd > SelStart then
edtNewName.SelLength := SelEnd - SelStart;
end;
procedure TfmCompRename.AddComponentProperty(const PropertyName, Value: WideString);
var
Lbl: TLabel;
Edit: TEdit;
begin
if Trim(PropertyName) <> '' then
begin
Lbl := TLabel.Create(Self);
Lbl.Parent := Self;
Lbl.Top := (FProperties.Count + 1) * (lblNewName.Top - lblOldName.Top) + lblNewName.Top;
Lbl.Left := lblNewName.Left;
Lbl.Caption := Trim(PropertyName);
Edit := TEdit.Create(Self);
Edit.Parent := Self;
Edit.Top := (FProperties.Count + 1) * (edtNewName.Top - edtOldName.Top) + edtNewName.Top;
Edit.Left := edtNewName.Left;
Edit.Width := edtNewName.Width;
Edit.Text := Value;
Edit.TabOrder := FProperties.Count + 2;
FProperties.Add(Edit);
Height := Height + 24;
if Edit.Text = SPropertyNotFound then begin
Edit.ReadOnly := True;
Edit.Color := clBtnFace;
Edit.TabStop := False;
Lbl.Font.Color := clGrayText;
end;
end;
end;
function TfmCompRename.GetComponentProperty(Index: Integer): WideString;
begin
if (Index >=0) and (Index < FProperties.Count) then
Result := (FProperties[Index] as TEdit).Text
else
raise Exception.Create('Invalid property index in TfmCompRename.GetComponentProperty');
end;
constructor TfmCompRename.Create(Owner: TComponent);
begin
inherited;
FProperties := TObjectList.Create(False);
end;
destructor TfmCompRename.Destroy;
begin
FreeAndNil(FProperties);
inherited;
end;
{ TCompRenameNotifier }
procedure TCompRenameNotifier.Attach;
begin
Assert(FChangeServiceNotifierIndex = -1);
FChangeServiceNotifierIndex := GxEditorChangeServices.AddNotifier(Self);
end;
procedure TCompRenameNotifier.ComponentRenamed(const FormEditor: IOTAFormEditor;
Component: IOTAComponent; const OldName, NewName: string);
begin
if Assigned(FClient) then
FClient.ComponentRenamed(FormEditor, Component, OldName, NewName);
end;
constructor TCompRenameNotifier.Create(const Client: TCompRenameExpert);
begin
inherited Create;
if Assigned(Client) then
begin
FClient := Client;
FChangeServiceNotifierIndex := -1;
Attach;
end;
end;
destructor TCompRenameNotifier.Destroy;
begin
Detach;
FClient := nil;
inherited Destroy;
end;
procedure TCompRenameNotifier.Detach;
begin
GxEditorChangeServices.RemoveNotifierIfNecessary(FChangeServiceNotifierIndex);
end;
function TCompRenameNotifier.EditorKeyPressed(
const SourceEditor: IOTASourceEditor; CharCode: Word; KeyData: Integer): Boolean;
begin
Result := False;
// Nothing
end;
procedure TCompRenameNotifier.FormEditorModified(const FormEditor: IOTAFormEditor);
begin
if Assigned(FClient) then
FClient.FormEditorModified(FormEditor);
end;
function TCompRenameNotifier.GetIndex: Integer;
begin
Result := FChangeServiceNotifierIndex;
end;
procedure TCompRenameNotifier.NewModuleOpened(const Module: IOTAModule);
begin // FI:W519
// Nothing
end;
procedure TCompRenameNotifier.SourceEditorModified(const SourceEditor: IOTASourceEditor);
begin // FI:W519
// Nothing
end;
{ TCompRenameExpert }
procedure TCompRenameExpert.AddNewClass(const AClassName: WideString);
begin
Assert(Assigned(FRenameRuleList));
// Classname already in list?
if FRenameRuleList.IndexOfName(AClassName) < 0 then
begin
// No -> add "TClass=Class" as new entry
FRenameRuleList.Add(AClassName+'='+Copy(AClassName, 2, Length(AClassName)-1));
SaveSettings;
end;
end;
procedure TCompRenameExpert.Execute(Sender: TObject);
var
SelCount: Integer;
CurrentComponent: IOTAComponent;
i: Integer;
begin
if not GxOtaFormEditorHasSelectedComponent then
Configure
else
begin
if not GxOtaTryGetCurrentFormEditor(FFormEditor) then
Exit;
SelCount := FFormEditor.GetSelCount;
for i := 0 to SelCount - 1 do
begin
CurrentComponent := FFormEditor.GetSelComponent(i);
if DoRename(CurrentComponent, False) = mrCancel then
Break;
end;
end;
end;
procedure TCompRenameExpert.Configure;
var
Dialog: TfmCompRenameConfig;
begin
Dialog := TfmCompRenameConfig.Create(nil);
try
Dialog.chkShowDialog.Checked := FShowDialog;
Dialog.chkAutoAdd.Checked := FAutoAddClasses;
SetFormIcon(Dialog);
FRenameRuleList.Sort;
Dialog.ValueList.Assign(FRenameRuleList);
if Dialog.Execute then
begin
FShowDialog := Dialog.chkShowDialog.Checked;
FAutoAddClasses := Dialog.chkAutoAdd.Checked;
FRenameRuleList.Assign(Dialog.ValueList);
SaveSettings;
end;
finally
FreeAndNil(Dialog);
end;
end;
procedure TCompRenameExpert.ComponentRenamed(const FormEditor: IOTAFormEditor;
Component: IOTAComponent; const OldName, NewName: WideString);
begin
// Bug: Delphi 8 can not set string properties on components
if RunningDelphi8 then
Exit;
if (not Assigned(FRenameRuleList)) or (FRenameRuleList.Count < 1) then
Exit;
if Active and Assigned(FormEditor) and (OldName = '') and (NewName > '') then
begin
// If the form being edited isn't the active designer, assume some
// automated tool is doing the editing, and GExperts ignores the change
if FormEditor.FileName <> GxOtaGetCurrentSourceFile then
Exit;
// Don't change the names of components that are not a default component
// name based on the class. This prevents renaming pasted components.
if Assigned(Component) and IsDefaultComponentName(Component, NewName) then
begin
FComponentNames.Add(NewName);
FFormNames.Add(FormEditor.FileName);
FTimerCount := 0;
FTimer.Enabled := True;
end;
end;
end;
constructor TCompRenameExpert.Create;
begin
inherited Create;
PrivateCompRenameExpert := Self;
FComponentNames := TStringList.Create;
FFormNames := TStringList.Create;
FRenameRuleList := TStringList.Create;
FTimer := TTimer.Create(nil);
FTimer.Enabled := False;
FTimer.Interval := 100;
FTimer.OnTimer := DoOnTimer;
AddNotifier;
end;
destructor TCompRenameExpert.Destroy;
var
i: Integer;
begin
PrivateCompRenameExpert := nil;
RemoveNotifier;
FreeAndNil(FTimer);
if Assigned(FRenameRuleList) then
begin
for i := 0 to FRenameRuleList.Count -1 do
begin
FRenameRuleList.Objects[i].Free;
FRenameRuleList.Objects[i] := nil;
end;
end;
FreeAndNil(FRenameRuleList);
FreeAndNil(FComponentNames);
FreeAndNil(FFormNames);
inherited;
end;
function TCompRenameExpert.DoRename(const Component: IOTAComponent; UseRules: Boolean): TModalResult;
var
i: Integer;
Pipe1Pos: Integer;
Pipe2Pos: Integer;
PlaceHolderPos: Integer;
ClassName: WideString;
RenameRule: WideString;
CompName: WideString;
PropName: WideString;
PropValue: String;
UsePropValue: Boolean;
SearchName: WideString;
Reason: WideString;
Dialog: TfmCompRename;
ShowDialog: Boolean;
OtherProps: TStringList;
Index: Integer;
begin
Assert(Assigned(Component));
Assert(Assigned(FFormEditor));
Result := mrOk;
// Get the component class name
ClassName := Component.GetComponentType;
// Get the desired rename rule for this class
RenameRule := GetClassRenameRule(ClassName);
if RenameRule = '' then
begin
if FAutoAddClasses then
begin
AddNewClass(ClassName);
RenameRule := GetClassRenameRule(ClassName);
end;
end;
Pipe2Pos := -1;
Pipe1Pos := Pos(WideString('|'), RenameRule);
if Pipe1Pos > 0 then begin
Delete(RenameRule, Pipe1Pos, 1);
Pipe2Pos := LastCharPos(RenameRule, '|');
if (Pipe2Pos >= Pipe1Pos) then
Delete(RenameRule, Pipe2Pos, 1);
end;
PlaceHolderPos := Pos(WideString('%d'), RenameRule);
if PlaceHolderPos > 0 then
Delete(RenameRule, PlaceHolderPos, 2);
CompName := GxOtaGetComponentName(Component);
if CompName = '' then
Exit;
ShowDialog := FShowDialog;
if not UseRules and (Length(RenameRule) > 0) then
begin
ShowDialog := True;
UseRules := IsDefaultComponentName(Component, CompName);
end;
if not UseRules or (Length(RenameRule) > 0) then
begin
if ShowDialog or not UseRules then
begin
Dialog := TfmCompRename.Create(nil);
try
Dialog.OnIsValidComponentName := IsValidComponentName;
Dialog.OldName := CompName;
Index := FRenameRuleList.IndexOfName(Component.GetComponentType);
if Index <> -1 then
begin
OtherProps := FRenameRuleList.Objects[Index] as TStringList;
if Assigned(OtherProps) then
begin
for i := 0 to OtherProps.Count - 1 do
begin
UsePropValue := False;
PropName := OtherProps.Names[i];
if PropName = '' then
PropName := OtherProps[i];
// Consolidate with code below
if GxOtaPropertyExists(Component, PropName) then
begin
if UseRules then
begin
PropValue := OtherProps.Values[PropName];
if PropValue <> '' then
begin
PropValue := AnsiDequotedStr(PropValue, #39);
if (PropValue= #39#39) then
PropValue := '';
UsePropValue := True;
end;
end;
if UsePropValue then
Dialog.AddComponentProperty(PropName, PropValue)
else
Dialog.AddComponentProperty(PropName,
GxOtaGetComponentPropertyAsString(Component, PropName, True));
end
else
Dialog.AddComponentProperty(PropName, SPropertyNotFound);
end;
end
end
else
OtherProps := nil;
if UseRules then
begin
Dialog.NewName := RenameRule;
if Pipe1Pos > 0 then
Dialog.SetRuleSelection(Pipe1Pos - 1, Pipe2Pos - 1)
else
Dialog.SetRuleSelection(Length(RenameRule), Length(RenameRule));
end
else
begin
Dialog.NewName := CompName;
Dialog.SetRuleSelection(0, Length(CompName));
end;
Result := Dialog.Execute;
if Result = mrOk then
begin
CompName := Dialog.NewName;
GxOtaSetComponentName(Component, CompName);
if Assigned(OtherProps) then
begin
for i := 0 to OtherProps.Count - 1 do
begin
PropName := OtherProps.Names[i];
if PropName = '' then
PropName := OtherProps[i];
if GxOtaPropertyExists(Component, PropName) then
GxOtaSetComponentPropertyAsString(Component, PropName,
Dialog.GetComponentProperty(i));
end;
end;
end;
finally
FreeAndNil(Dialog);
end;
end
else
begin
// Try to find a new name without user interaction
CompName := '';
if PlaceHolderPos > 0 then
Insert('%d', RenameRule, PlaceHolderPos)
else
RenameRule := RenameRule + '%d';
for i := 1 to 100 do
begin
SearchName := Format(RenameRule, [i]);
if GxOtaComponentsAreEqual(Component, FFormEditor.FindComponent(SearchName)) then
Exit; // The component already matches the rename rule's result
if IsValidComponentName(CompName, SearchName, Reason) then
begin
CompName := SearchName;
Break;
end;
end;
if Length(CompName) > 0 then
GxOtaSetComponentName(Component, CompName);
if UseRules then
begin
Index := FRenameRuleList.IndexOfName(Component.GetComponentType);
if Index <> -1 then
begin
OtherProps := FRenameRuleList.Objects[Index] as TStringList;
if Assigned(OtherProps) then
begin
for i := 0 to OtherProps.Count - 1 do
begin
PropName := OtherProps.Names[i];
if (PropName <> '') and GxOtaPropertyExists(Component, PropName) then
begin
PropValue := OtherProps.Values[PropName];
if PropValue <> '' then
begin
PropValue := AnsiDequotedStr(PropValue, #39);
if (PropValue= #39#39) then
PropValue := '';
GxOtaSetComponentPropertyAsString(Component, PropName, PropValue);
end;
end;
end;
end
end;
end;
end;
end
end;
procedure TCompRenameExpert.DoOnTimer(Sender: TObject);
var
i: Integer;
FormName: WideString;
SearchName: WideString;
Component: IOTAComponent;
begin
FTimer.Enabled := False;
try
if (GxOtaGetCurrentFormEditor = nil) then
Exit;
Assert(FFormNames.Count = FComponentNames.Count);
for i := 0 to FComponentNames.Count - 1 do
begin
// Try to locate the component with given name
FormName := FFormNames[i];
SearchName := FComponentNames[i];
if (FormName = '') or (SearchName = '') then
Break;
FFormEditor := GxOtaGetFormEditorForFileName(FormName);
if not Assigned(FFormEditor) then
Break;
Component := FFormEditor.FindComponent(SearchName);
if Assigned(Component) then
begin
if GxOtaIsInheritedComponent(Component) then
Break;
if DoRename(Component, True) = mrCancel then
Break;
end;
end;
finally
FFormEditor := nil;
Component := nil;
FComponentNames.Clear;
FFormNames.Clear;
end;
end;
procedure TCompRenameExpert.FormEditorModified(const FormEditor: IOTAFormEditor);
begin // FI:W519
// Nothing
end;
function TCompRenameExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Rename Components...';
begin
Result := SMenuCaption;
end;
function TCompRenameExpert.GetClassRenameRule(const AClassName: WideString): WideString;
begin
Assert(Assigned(FRenameRuleList));
Result := FRenameRuleList.Values[AClassName];
end;
function TCompRenameExpert.GetDefaultShortCut: TShortCut;
begin
Result := Menus.ShortCut(VK_F2, [ssShift]);
end;
class function TCompRenameExpert.GetName: string;
begin
Result := 'RenameComponents';
end;
function TCompRenameExpert.HasConfigOptions: Boolean;
begin
Result := True;
end;
function TCompRenameExpert.HasDesignerMenuItem: Boolean;
begin
Result := True;
end;
procedure TCompRenameExpert.InternalLoadSettings(Settings: TExpertSettings);
var
OtherProps: TStringList;
i: Integer;
begin
inherited InternalLoadSettings(Settings);
Assert(Assigned(FRenameRuleList));
FShowDialog := Settings.ReadBool('ShowDialog', False);
FAutoAddClasses := Settings.ReadBool('AutoAdd', True);
if Settings.SectionExists('Items') then
Settings.ReadStrings('Items', FRenameRuleList)
else
Settings.ReadStrings('', FRenameRuleList);
FRenameRuleList.Sort;
OtherProps := nil;
for i := 0 to FRenameRuleList.Count - 1 do
begin
if not Assigned(OtherProps) then
OtherProps := TStringList.Create;
Settings.ReadStrings(FRenameRuleList.Names[i], OtherProps);
if OtherProps.Count > 0 then
begin
FRenameRuleList.Objects[i] := OtherProps;
OtherProps := nil;
end;
end;
FreeAndNil(OtherProps);
end;
procedure TCompRenameExpert.InternalSaveSettings(Settings: TExpertSettings);
var
i: Integer;
OtherProps: TStringList;
cnt: integer;
begin
inherited InternalSaveSettings(Settings);
Assert(Assigned(FRenameRuleList));
if Settings.ValueExists('Count') then begin
// clean up old entries that were directly in the section, we now write
// to a subsection
cnt := Settings.ReadInteger('Count', 0);
for i := 0 to cnt - 1 do begin
Settings.DeleteKey(Format('Item%d', [i]));
end;
Settings.DeleteKey('Count');
end;
Settings.WriteStrings('Items', FRenameRuleList);
Settings.WriteBool('ShowDialog', FShowDialog);
Settings.WriteBool('AutoAdd', FAutoAddClasses);
for i := 0 to FRenameRuleList.Count - 1 do
begin
OtherProps := FRenameRuleList.Objects[i] as TStringList;
if Assigned(OtherProps) then
Settings.WriteStrings(FRenameRuleList.Names[i], OtherProps);
end;
end;
function TCompRenameExpert.IsValidComponentName(const OldName, NewName: WideString; var Reason: WideString): Boolean;
resourcestring
InalidIdent = 'Invalid identifier';
DuplicateName = 'Duplicate name';
var
FoundComponent: IOTAComponent;
FoundName: WideString;
begin
Reason := '';
FoundName := '';
Result := IsValidIdent(NewName);
if not Result then
Reason := InalidIdent;
if Result and Assigned(FFormEditor) then
begin
FoundComponent := FFormEditor.FindComponent(NewName);
if Assigned(FoundComponent) then
FoundName := GxOtaGetComponentName(FoundComponent);
Result := (not Assigned(FoundComponent)) or (FoundName = OldName);
if not Result then
Reason := DuplicateName;
end;
end;
procedure TCompRenameExpert.SetActive(New: Boolean);
begin
if New <> Active then
begin
inherited SetActive(New);
if New then
AddNotifier
else
RemoveNotifier;
end;
end;
procedure TCompRenameExpert.AddNotifier;
begin
if not Assigned(FCompRenameNotifier) then
FCompRenameNotifier := TCompRenameNotifier.Create(Self);
end;
procedure TCompRenameExpert.RemoveNotifier;
begin
if Assigned(FCompRenameNotifier) then
begin
FCompRenameNotifier.Detach;
FCompRenameNotifier := nil;
end;
end;
function TCompRenameExpert.IsDefaultComponentName(Component: IOTAComponent; const NewName: WideString): Boolean;
var
Prefix: WideString;
Suffix: WideString;
begin
Assert(Assigned(Component));
Result := False;
Prefix := Component.GetComponentType;
if (Length(Prefix) > 1) and (Prefix[1] = 'T') then
Prefix := Copy(Prefix, 2, 999);
if not StrBeginsWith(Prefix, NewName) then
Exit;
Suffix := Copy(NewName, Length(Prefix) + 1, 999);
if StrToIntDef(Suffix, -999) <> -999 then
Result := True;
end;
function TCompRenameExpert.IsDefaultActive: Boolean;
begin
// IDE Bug: This expert does not work under Delphi 8
Result := not RunningDelphi8;
end;
procedure TfmCompRename.FormCreate(Sender: TObject);
begin
SetModalFormPopupMode(Self);
lblReason.Font.Color := clRed;
end;
procedure TfmCompRename.btnSettingsClick(Sender: TObject);
begin
Assert(Assigned(PrivateCompRenameExpert));
PrivateCompRenameExpert.Configure;
end;
initialization
RegisterGX_Expert(TCompRenameExpert);
end.
|
unit eeprom;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
main_engine,dialogs,file_engine;
const
SERIAL_BUFFER_LENGTH=40;
type
eeprom_class=class
constructor create(address_bits,data_bits:byte;cmd_read,cmd_write,cmd_erase:string;cmd_lock:string='';cmd_unlock:string='';enable_multi_read:boolean=false;reset_delay:byte=0);
destructor free;
public
procedure set_cs_line(state:byte);
procedure set_clock_line(state:byte);
procedure write_bit(valor:byte);
function readbit:byte;
procedure reset;
function get_rom_addr:pbyte;
private
nombre:string;
default_data_size:integer;
default_value:dword;
addrspace:array[0..$ff] of word;
// runtime state
serial_count:integer;
serial_buffer:array[0..SERIAL_BUFFER_LENGTH] of char;
read_address,clock_count,reset_counter:integer;
data_buffer:dword;
reset_line,clock_line,latch:byte;
locked,sending:boolean;
//interface
address_bits:byte; // EEPROM has 2^address_bits cells
data_bits:byte; // every cell has this many bits (8 or 16)
cmd_read:string; // read command string, e.g. "0110"
cmd_write:string; // write command string, e.g. "0111"
cmd_erase:string; // erase command string, or 0 if n/a
cmd_lock:string; // lock command string, or 0 if n/a
cmd_unlock:string; // unlock command string, or 0 if n/a
enable_multi_read:boolean; // set to 1 to enable multiple values to be read from one read command
reset_delay:byte; // number of times eeprom_read_bit() should return 0 after a reset,
// before starting to return 1.
procedure write(latch:byte);
end;
var
eeprom_0:eeprom_class;
implementation
uses init_games;
constructor eeprom_class.create(address_bits,data_bits:byte;cmd_read,cmd_write,cmd_erase:string;cmd_lock:string='';cmd_unlock:string='';enable_multi_read:boolean=false;reset_delay:byte=0);
var
f:integer;
begin
self.address_bits:=address_bits;
self.data_bits:=data_bits;
self.cmd_read:=cmd_read;
self.cmd_write:=cmd_write;
self.cmd_erase:=cmd_erase;
self.cmd_lock:=cmd_lock;
self.cmd_unlock:=cmd_unlock;
self.enable_multi_read:=enable_multi_read;
self.reset_delay:=reset_delay;
//Sacar el nombre de la maquina...
for f:=0 to games_cont do begin
if games_desc[f].grid=main_vars.tipo_maquina then begin
self.nombre:=directory.Arcade_nvram+games_desc[f].name+'.nv';
break
end;
end;
fillchar(self.addrspace[0],$100*2,0);
if read_file_size(self.nombre,f) then read_file(self.nombre,@self.addrspace,f);
end;
destructor eeprom_class.free;
var
size:dword;
begin
size:=((1 shl self.address_bits)*self.data_bits) div 8;
if self.data_bits=8 then size:=size*2;
write_file(self.nombre,@self.addrspace,size);
end;
function eeprom_class.get_rom_addr:pbyte;
begin
get_rom_addr:=@self.addrspace[0];
end;
procedure eeprom_class.reset;
begin
default_data_size:=0;
default_value:=0;
serial_count:=0;
data_buffer:=0;
read_address:=0;
clock_count:=0;
latch:=0;
reset_line:=CLEAR_LINE;
clock_line:=CLEAR_LINE;
sending:=false;
locked:=false;
reset_counter:=0;
end;
function command_match(buf:pchar;cmd:pchar;len:integer):boolean;
var
b,c:char;
begin
if (cmd^=chr(0)) then begin
command_match:=false;
exit;
end;
if (len=0) then begin
command_match:=false;
exit;
end;
while (len>0) do begin
b:=buf^;
c:=cmd^;
if ((b=chr(0)) or (c=chr(0))) then begin
command_match:=(b=c);
exit;
end;
case c of
'0','1':begin
if (b<>c) then begin
command_match:=false;
exit;
end;
inc(buf);
len:=len-1;
inc(cmd);
end;
'X','x':begin
inc(buf);
len:=len-1;
inc(cmd);
end;
'*':begin
{ c = cmd[1];
switch( c ) {
case '0':
case '1':
if (b == c) { cmd++; }
// else { buf++; len--; }
// break;
// default: return false;
// }
end;
end;
end;
command_match:=(cmd^=chr(0));
end;
procedure eeprom_class.write(latch:byte);
var
i,address,data:word;
command:array[0..SERIAL_BUFFER_LENGTH] of char;
begin
if (serial_count>=(SERIAL_BUFFER_LENGTH-1)) then begin
MessageDlg('Buffer eeprom superado', mtInformation,[mbOk], 0);
exit;
end;
if latch<>0 then serial_buffer[serial_count]:='1'
else serial_buffer[serial_count]:='0';
serial_count:=serial_count+1;
serial_buffer[serial_count]:=chr(0); // nul terminate so we can treat it as a string
if (serial_count>address_bits) then begin
for i:=0 to length(self.cmd_read) do command[i]:=self.cmd_read[i+1];
//READ Command
if command_match(@serial_buffer,@command,serial_count-address_bits) then begin
address:=0;
for i:=serial_count-address_bits to (serial_count-1) do begin
address:=address shl 1;
if (serial_buffer[i]='1') then address:=address or 1;
end;
if (data_bits=16) then data_buffer:=(addrspace[address] shr 8) or ((addrspace[address] and $ff) shl 8)
else data_buffer:=addrspace[address] and $ff;
read_address:=address;
clock_count:=0;
sending:=true;
serial_count:=0;
end;
//ERASE Command
for i:=0 to length(self.cmd_erase) do command[i]:=self.cmd_erase[i+1];
if command_match(@serial_buffer,@command,serial_count-address_bits) then begin
address:=0;
for i:=serial_count-address_bits to (serial_count-1) do begin
address:=address shl 1;
if (serial_buffer[i]='1') then address:=address or 1;
end;
if not(locked) then begin
if (data_bits=16) then addrspace[address]:=$FFFF
else addrspace[address]:=$FF;
end else begin
MessageDlg('Comando ERASE eeprom bloqueada', mtInformation,[mbOk], 0);
end;
serial_count:=0;
end;
//WRITE Command
for i:=0 to length(self.cmd_write) do command[i]:=self.cmd_write[i+1];
if command_match(@serial_buffer,@command,serial_count-(address_bits+data_bits)) then begin
address:=0;
for i:=serial_count-data_bits-address_bits to (serial_count-data_bits-1) do begin
address:=address shl 1;
if (serial_buffer[i]='1') then address:=address or 1;
end;
data:=0;
for i:=serial_count-data_bits to (serial_count-1) do begin
data:=data shl 1;
if (serial_buffer[i]='1') then data:=data or 1;
end;
if not(locked) then begin
if (data_bits=16) then addrspace[address]:=(data shr 8) or ((data and $ff) shl 8)
else addrspace[address]:=data;
end else begin
MessageDlg('Comando WRITE eeprom bloqueada', mtInformation,[mbOk], 0);
end;
serial_count:=0;
end;
//LOCK Command
end else begin
if self.cmd_lock<>'' then begin
for i:=0 to length(self.cmd_lock) do command[i]:=self.cmd_lock[i+1];
if (command_match(@serial_buffer,@command,serial_count)) then begin
locked:=true;
serial_count:=0;
end;
end else begin
//UNLOCK Command
if self.cmd_unlock<>'' then begin
for i:=0 to length(self.cmd_unlock) do command[i]:=self.cmd_unlock[i+1];
if (command_match(@serial_buffer,@command,serial_count)) then begin
locked:=false;
serial_count:=0;
end;
end;
end;
end;
end;
procedure eeprom_class.set_cs_line(state:byte);
begin
reset_line:=state;
if (reset_line<>CLEAR_LINE) then begin
//if (serial_count<>0) then MessageDlg('Comando CS serial count<>0', mtInformation,[mbOk], 0);
serial_count:=0;
sending:=false;
reset_counter:=reset_delay; // delay a little before returning setting data to 1 (needed by wbeachvl)
end;
end;
procedure eeprom_class.set_clock_line(state:byte);
begin
if ((state=PULSE_LINE) or ((clock_line=CLEAR_LINE) and (state<>CLEAR_LINE))) then begin
if (reset_line=CLEAR_LINE) then begin
if sending then begin
if ((clock_count=data_bits) and enable_multi_read) then begin
//read_address:=(read_address+1) and ((1 shl address_bits)-1);
//if (data_bits=16) then data_buffer:=addrspace[0]->read_word(m_read_address * 2);
// else data_buffer:=addrspace[0]->read_byte(m_read_address);
//m_clock_count = 0;
MessageDlg('Eeprom comando multi-read', mtInformation,[mbOk], 0);
end;
data_buffer:=(data_buffer shl 1) or 1;
clock_count:=clock_count+1;
end else begin
write(self.latch);
end;
end;
end;
clock_line:=state;
end;
procedure eeprom_class.write_bit(valor:byte);
begin
self.latch:=valor;
end;
function eeprom_class.readbit:byte;
var
res:byte;
begin
if sending then begin
res:=(data_buffer shr data_bits) and 1;
end else begin
if (reset_counter>0) then begin
// this is needed by wbeachvl
reset_counter:=reset_counter-1;
res:=0;
end else begin
res:=1;
end;
end;
readbit:=res;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Effects,
FMX.Objects, FMX.Layouts, FMX.ListBox, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Edit, Controller.Interfaces,
Controller.Observer.Interfaces;
type
TForm1 = class(TForm, iObserverItem)
Layout1: TLayout;
Layout2: TLayout;
Rectangle3: TRectangle;
Layout3: TLayout;
Rectangle1: TRectangle;
Layout4: TLayout;
Layout5: TLayout;
Layout6: TLayout;
Rectangle2: TRectangle;
ShadowEffect1: TShadowEffect;
Layout7: TLayout;
Rectangle4: TRectangle;
ShadowEffect2: TShadowEffect;
Layout8: TLayout;
Rectangle5: TRectangle;
ListBox1: TListBox;
Edit1: TEdit;
Button1: TButton;
procedure Edit1KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
FVenda : iControllerVenda;
procedure VenderItem;
function UpdateItem(Value : TRecordItem) : iObserverItem;
public
end;
var
Form1: TForm1;
implementation
uses
Controller.Vendas, Unit2;
{$R *.fmx}
procedure TForm1.Button1Click(Sender: TObject);
begin
Form2.ExibirForm(FVenda);
end;
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
begin
if KeyChar = #0 then
VenderItem;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FVenda := TControllerVendas.New;
FVenda.ObserverItem.Add(Self);
end;
function TForm1.UpdateItem(Value: TRecordItem): iObserverItem;
begin
ShowMessage(Value.Descricao);
// ListBox1.Items.Add(Value.Descricao);
end;
procedure TForm1.VenderItem;
begin
FVenda
.Item
.Codigo(StrToInt(Edit1.Text))
.Vender;
end;
end.
|
{Realizar un programa que lea información de los candidatos ganadores de las últimas elecciones a
intendente de la provincia de Buenos Aires. Para cada candidato se lee: localidad, apellido del
candidato, cantidad de votos obtenidos, y cantidad de votantes de la localidad. La lectura finaliza al
leer la localidad ‘Zárate’, que debe procesarse. Informar:
◦ el intendente que obtuvo la mayor cantidad de votos en la elección.
◦ el intendente que obtuvo el mayor porcentaje de votos de la elección.
}
program ejercicio5;
type
str40= String[40];
candidato = record
localidad : str40;
apellido: str40;
cantVotos: Integer;
cantvotante: Integer;
end;
procedure leerCandidato(var c: candidato);
begin
write('Ingrese la LOCALIDAD del candidato: ');
readln(c.localidad);
write('Ingrese el APELLIDO del candidato: ');
readln(c.apellido);
write('Ingrese la CANTIDAD DE VOTOS: ');
readln(c.cantVotos);
write('Ingrese la CANTIDAD DE VOTANTES: ');
readln(c.cantvotante);
writeln('----------------------------------');
end;
procedure mayorVotos(c:candidato; var max:Integer; var apellidoMax: str40);
begin
if (c.cantVotos >= max) then
begin
max:=c.cantVotos;
apellidoMax:= c.apellido;
end;
end;
procedure mayorPorcentaje(c:candidato; var porcentaje: Real; var apellidoMaxPorcen: str40; var maxPorcentaje: Real);
begin
porcentaje:= (c.cantVotos * c.cantvotante) / 100;
if (porcentaje >= maxPorcentaje ) then
begin
maxPorcentaje:= porcentaje;
apellidoMaxPorcen:= c.apellido;
end;
end;
var
c: candidato;
max: Integer;
apellidoMax, apellidoMaxPorcen: str40;
porcentaje, maxPorcentaje: Real;
begin
max:= -1;
maxPorcentaje:= -1;
porcentaje:= 0;
repeat
leerCandidato(c);
mayorVotos(c,max,apellidoMax);
mayorPorcentaje(c, porcentaje, apellidoMaxPorcen, maxPorcentaje);
until c.apellido = 'zarate';
writeln('El intendente que obtuvo mayor cantidad de votos en las elecciones es: ', apellidoMax);
writeln('El intendente que obtuvo el mayor porcentaje de votos de las elecciones es: ', apellidoMaxPorcen);
readln();
end. |
unit vtImageForm;
{ $Id: vtImageForm.pas,v 1.4 2007/12/12 11:52:08 voba Exp $ }
// $Log: vtImageForm.pas,v $
// Revision 1.4 2007/12/12 11:52:08 voba
// - cc
//
// Revision 1.3 2007/12/12 11:02:03 voba
// - убрал EraseBackground
//
// Revision 1.2 2007/12/12 07:45:54 voba
// - bug fix
//
// Revision 1.1 2007/12/11 15:57:15 voba
// no message
//
interface
uses
Consts, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TvtCustomImage = class(TGraphicControl)
private
FPicture: TPicture;
FAutoSize: Boolean;
FIncrementalDisplay: Boolean;
FTransparent: Boolean;
FDrawing: Boolean;
function GetCanvas: TCanvas;
procedure PictureChanged(Sender: TObject);
procedure SetAutoSize(Value: Boolean);
procedure SetPicture(Value: TPicture);
procedure SetTransparent(Value: Boolean);
protected
function DoPaletteChange: Boolean;
function GetPalette: HPALETTE; override;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Canvas: TCanvas read GetCanvas;
property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
property IncrementalDisplay: Boolean read FIncrementalDisplay write FIncrementalDisplay default False;
property Picture: TPicture read FPicture write SetPicture;
property Transparent: Boolean read FTransparent write SetTransparent default False;
end;
TvtWndProcEvent = procedure(var Message: TMessage) of object;
TvtBeforeWndProcEvent = procedure(var Message: TMessage; var ProcessMessage: boolean) of object;
TvtCaptureMessageClass = class(TComponent)
private
FOnWndProc: TvtWndProcEvent;
FOnBeforeWndProc: TvtBeforeWndProcEvent;
FEnabled: Boolean;
FWndHandle: HWnd;
FWndHandlerPtr: Pointer;
FOldWndHandler: Pointer; {Restore to this when this component is destroyed }
FWinControl: TWinControl;
procedure SetWndHandle(Value: Hwnd);
procedure SetWndControl(Value: TWinControl);
procedure SetEnabled(aValue: Boolean);
procedure StartSubClass;
procedure EndSubClass;
protected
procedure WndProc(var Message: TMessage); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure NewWndProc(var Message: TMessage);
property WindowHandle: HWnd read FWndHandle write SetWndHandle;
property WinControl: TWinControl read FWinControl write SetWndControl;
property Enabled: Boolean read FEnabled write SetEnabled;
property OnWndProc: TvtWndProcEvent read FOnWndProc write FOnWndProc;
property OnBeforeWndProc: TvtBeforeWndProcEvent read FOnBeforeWndProc write FOnBeforeWndProc;
end;
TvtCustomImageForm = class(TvtCustomImage)
private
fDragged : Boolean;
fDragTolerance : Integer;
fTransparentColor : TColor;
fRegion : HRgn;
fCaptionBarControl : TControl;
fCaptureMessageClass : TvtCaptureMessageClass;
LastFocusRect : TRect;
function GetPicture: TPicture;
procedure SetPicture(Value: TPicture);
procedure SetCaptionBarControl(Value: TControl);
protected
DraggingForm: Boolean;
procedure DestroyWnd;
procedure Paint; override;
function GetTransparentColor: TColor;
procedure DrawFocusRect(DC: HDC; FocusRect: TRect); virtual;
procedure FormMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); virtual;
procedure SetParent(Value:TWinControl); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure BeforeFormWndProc(var Message: TMessage; var ProcessMessage: Boolean);
procedure AfterFormWndProc(var Message: TMessage); virtual;
procedure MouseLoop(X, Y: Integer); virtual;
procedure MouseLoop_MouseMove(X, Y: Integer;
aCursorPos: TPoint;
var FirstTime : Boolean;
var FocusRect : TRect;
OriginalRect :TRect); virtual;
procedure MouseLoop_MouseUp(X, Y: Integer;
ACursorPos: TPoint;
OriginalRect, FocusRect: TRect); virtual;
function GetDragFullWindows: Boolean; virtual;
public
constructor Create(Aowner:TComponent); override;
destructor Destroy; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure ApplyBitmapRegion; virtual;
property CaptionBarControl: TControl
read FCaptionBarControl
write SetCaptionBarControl;
property DragTolerance: Integer
read FDragTolerance
write FDragTolerance
default 5;
property Picture: TPicture
read GetPicture
write SetPicture;
property TransparentColor: TColor
read FTransparentColor
write FTransparentColor
default clNone;
property Dragged : Boolean
read fDragged
write fDragged
default True;
end;
TvtImageForm = class(TvtCustomImageForm)
published
property Dragged;
property Align;
property AutoSize;
property Picture;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property CaptionBarControl;
property DragTolerance;
property TransparentColor;
end;
implementation
uses
StdCtrls;
function vtCreateRegionFromBitmap(aBitmap: TBitmap; TransColor: TColor): HRgn;
var
lBitmap: TBitmap;
Rgn1, Rgn2: HRgn;
Col, StartCol, Row: integer;
Line: PByteArray;
lIsTrueColorBmp : boolean;
const
cBool2Color : array[boolean] of TColor = (clBlack, clWhite);
cBitMask: array[0..7] of byte = (128, 64, 32, 16, 8, 4, 2, 1);
function ColToColor(Col: integer): TColor;
begin
if lIsTrueColorBmp then
Result := Line[Col * 3] * 256 * 256 + Line[Col * 3 + 1] * 256 + Line[Col * 3 + 2]
else
Result := cBool2Color[(Line[Col div 8] and cBitMask[Col mod 8]) = 0];
end;
begin
Result := 0;
if (aBitmap <> nil) and (aBitmap.Width = 0) or (aBitmap.Height = 0) then Exit;
Rgn1 := 0;
lBitmap := TBitmap.Create;
try
lBitmap.Assign(aBitmap);
lIsTrueColorBmp := (lBitmap.PixelFormat = Graphics.pf24bit);
if not lIsTrueColorBmp then
begin
lBitmap.Mask(TransColor);
TransColor := clBlack;
end;
with lBitmap do
begin
for Row := 0 to Pred(lBitmap.Height) do
begin
Line:= ScanLine[Row];
Col := 0;
while Col < lBitmap.Width do
begin
while (Col < lBitmap.Width) and (ColToColor(Col) = TransColor) do inc(Col);
if Col >= lBitmap.Width then Continue;
StartCol := Col;
while (Col < lBitmap.Width) and (ColToColor(Col) <> TransColor) do inc(Col);
if Col >= lBitmap.Width then Col := lBitmap.Width;
if Rgn1 = 0 then
Rgn1 := CreateRectRgn(StartCol, Row, Col, Row + 1)
else
begin
Rgn2 := CreateRectRgn(StartCol, Row, Col, Row + 1);
if (Rgn2 <> 0) then
CombineRgn(Rgn1, Rgn1, Rgn2, RGN_OR);
Deleteobject(Rgn2);
end;
end;
end;
end;
Result := Rgn1;
finally
lBitmap.Free;
end;
end;
{TvtCustomImage}
constructor TvtCustomImage.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable];
FPicture := TPicture.Create;
FPicture.OnChange := PictureChanged;
Height := 105;
Width := 105;
end;
destructor TvtCustomImage.Destroy;
begin
FPicture.Free;
inherited Destroy;
end;
function TvtCustomImage.GetPalette: HPALETTE;
begin
if FPicture.Graphic = nil then
Result := 0
else
Result := FPicture.Graphic.Palette
end;
procedure TvtCustomImage.Paint;
var
Save: Boolean;
begin
if csDesigning in ComponentState then
with inherited Canvas do
begin
Pen.Style := psDash;
Brush.Style := bsClear;
Rectangle(0, 0, Width, Height);
end;
Save := FDrawing;
FDrawing := True;
try
with inherited Canvas do
StretchDraw(Rect(0, 0, Picture.Width, Picture.Height), Picture.Graphic);
finally
FDrawing := Save;
end;
end;
function TvtCustomImage.DoPaletteChange: Boolean;
var
lParentForm: TCustomForm;
lGraphic : TGraphic;
begin
Result := False;
lGraphic := Picture.Graphic;
if Visible and (not (csLoading in ComponentState)) and (lGraphic <> nil) and
(lGraphic.PaletteModified) then
begin
if (lGraphic.Palette = 0) then
lGraphic.PaletteModified := False
else
begin
lParentForm := GetParentForm(Self);
if Assigned(lParentForm) and lParentForm.Active and lParentform.HandleAllocated then
begin
if FDrawing then
lParentForm.Perform(wm_QueryNewPalette, 0, 0)
else
PostMessage(lParentForm.Handle, wm_QueryNewPalette, 0, 0);
Result := True;
lGraphic.PaletteModified := False;
end;
end;
end;
end;
function TvtCustomImage.GetCanvas: TCanvas;
var
lBitmap: TBitmap;
begin
if Picture.Graphic = nil then
begin
lBitmap := TBitmap.Create;
try
lBitmap.Width := Width;
lBitmap.Height := Height;
Picture.Graphic := lBitmap;
finally
lBitmap.Free;
end;
end;
if Picture.Graphic is TBitmap then
Result := TBitmap(Picture.Graphic).Canvas
else
raise EInvalidOperation.Create(SImageCanvasNeedsBitmap);
end;
procedure TvtCustomImage.SetAutoSize(Value: Boolean);
begin
FAutoSize := Value;
PictureChanged(Self);
end;
procedure TvtCustomImage.SetPicture(Value: TPicture);
begin
FPicture.Assign(Value);
end;
procedure TvtCustomImage.SetTransparent(Value: Boolean);
begin
if Value <> FTransparent then
begin
FTransparent := Value;
PictureChanged(Self);
end;
end;
procedure TvtCustomImage.PictureChanged(Sender: TObject);
var
G: TGraphic;
begin
if AutoSize and (Picture.Width > 0) and (Picture.Height > 0) then
SetBounds(Left, Top, Picture.Width, Picture.Height);
G := Picture.Graphic;
if G <> nil then
begin
if not ((G is TMetaFile) or (G is TIcon)) then
G.Transparent := FTransparent;
if (not G.Transparent) and ((G.Width >= Width)
and (G.Height >= Height)) then
ControlStyle := ControlStyle + [csOpaque]
else
ControlStyle := ControlStyle - [csOpaque];
if DoPaletteChange and FDrawing then Update;
end
else
ControlStyle := ControlStyle - [csOpaque];
if not FDrawing then Invalidate;
end;
constructor TvtCustomImageForm.Create(Aowner:TComponent);
begin
inherited;
FDragTolerance := 5;
//FRegion := 0;
Align := alClient;
FTransparentColor := clNone;
FCaptureMessageClass := nil;
fDragged := True;
end;
destructor TvtCustomImageForm.Destroy;
begin
if FRegion <> 0 then DeleteObject(FRegion);
if FCaptureMessageClass <> nil then FCaptureMessageClass.Free;
// FCaptureMessageClass:= nil;
inherited Destroy;
end;
procedure TvtCustomImageForm.DestroyWnd;
begin
if FRegion <> 0 then
begin
SetWindowRgn(GetParentForm(self).Handle, 0, False);
DeleteObject(FRegion);
FRegion := 0;
end;
end;
// 10/26/98 - Added check to use windows setting for dragging of form when UseWindowsDrag is set.
function TvtCustomImageForm.GetDragFullWindows: Boolean;
var
s: integer;
begin
s:= 0;
if fDragged then
SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, Pointer(@s), 0);
Result := s <> 0;
end;
procedure TvtCustomImageForm.BeforeFormWndProc(var Message: TMessage; var ProcessMessage: Boolean);
begin
ProcessMessage := Message.Msg <> WM_ERASEBKGND;
end;
procedure TvtCustomImageForm.AfterFormWndProc(var Message: TMessage);
var
lControl: TControl;
ClickOrMouseDownAssigned:Boolean;
begin
if not (csDesigning in componentstate) then
case Message.Msg of
WM_DESTROY: DestroyWnd;
WM_LBUTTONDOWN: //Needed to capture mouse messages from caption control
with TWMMouse(Message) do
begin
lControl := Parent.ControlAtPos(Point(XPos, YPos), True);
ClickOrMouseDownAssigned := Assigned(TButton(lControl).OnClick) or
Assigned(TButton(lControl).OnMouseDown);
if ((FCaptionBarControl <> nil) and not ClickOrMouseDownAssigned) or
((FCaptionBarControl <> nil) and (lControl = CaptionBarControl)) or
((FCaptionBarControl = nil) and (lControl = self)) then
FormMouseDown(mbLeft, KeysToShiftState(Keys), XPos, YPos);
end;
end; //case Message.Msg of ...
end;
procedure TvtCustomImageForm.FormMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
p: TPoint;
ParentForm: TCustomForm;
begin
if (FCaptionBarControl <> nil) then
with FCaptionBarControl do
if not (PtinRect(Rect(Left, Top, Width + Left, Height + Top), Point(x, y))) then
Exit;
if ssLeft in Shift then
begin
ParentForm := GetParentForm(self);
if TForm(ParentForm).FormStyle = fsMDIChild then
begin
p := ClientToScreen(Point(x,y));
p.x := p.x - ParentForm.left;
p.y := p.y - ParentForm.Top;
end
else
p := Point(x, y);
MouseLoop(p.x, p.y)
end
else
SendMessage(Parent.Handle, WM_SYSCOMMAND, SC_KEYMENU, 0);
end;
procedure TvtCustomImageForm.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FCaptionBarControl) then
fCaptionBarControl := nil;
end;
procedure TvtCustomImageForm.MouseLoop(X, Y: Integer);
var
ACursor : TPoint;
Msg : TMsg;
FirstTime : Boolean;
OriginalRect, FocusRect: TRect;
begin
FirstTime := True;
with Parent do OriginalRect := Rect(Left, Top, Left + Width, Top + Height);
FocusRect := Rect(0, 0, 0, 0);
with GetParentForm(self) do
begin
SetCapture(Handle);
try
while GetCapture = Handle do
begin
GetCursorPos(ACursor);
case Integer(GetMessage(Msg, 0, 0, 0)) of
-1: Break;
0: begin
PostQuitMessage(Msg.WParam);
Break;
end;
end;
case Msg.Message of
WM_MOUSEMOVE :
MouseLoop_MouseMove(X, Y, ACursor, FirstTime, FocusRect, OriginalRect);
WM_LBUTTONUP :
begin
MouseLoop_MouseUp(X, Y, ACursor, OriginalRect, FocusRect);
TranslateMessage(Msg); // So OnMouseUp fires
DispatchMessage(Msg);
if GetCapture = Handle then ReleaseCapture;
end;
else
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
end;
finally
if GetCapture = Handle then ReleaseCapture;
end;
end;
end;
procedure TvtCustomImageForm.MouseLoop_MouseMove(X, Y: Integer; ACursorPos: TPoint;
var FirstTime: Boolean;
var FocusRect: TRect;
OriginalRect:TRect);
var
DC: HDC;
p: TPoint;
Msg: TMsg;
PaintFocusRect: TRect;
begin
p := ClientToScreen(Point(x, y));
if (Abs(ACursorPos.X - p.x) <= DragTolerance) and
(Abs(ACursorPos.Y - p.y) <= DragTolerance) then
Exit;
with GetParentForm(self) do
begin
if not GetDragFullWindows then
begin
DC := GetDC(0);
try
if FirstTime then
DraggingForm := True
else
begin
DrawFocusRect(DC, LastFocusRect); { Hide previous focus rect }
end;
FocusRect := Rect(ACursorPos.x - x, ACursorPos.y - y, ACursorPos.x - x + Width, ACursorPos.y - y + Height);
if TForm(GetParentForm(self)).FormStyle = fsMDIChild then
begin
PaintFocusRect:= FocusRect;
PaintFocusRect.Left:= PaintFocusRect.Left + ClientToScreen(Point(0,0)).x - Left;
PaintFocusRect.Top:= PaintFocusRect.Top+ ClientToScreen(Point(0,0)).y - Top;
PaintFocusRect.Right:= PaintFocusRect.Left+ Width;
PaintFocusRect.Bottom:= PaintFocusRect.Top + Height;
end
else
PaintFocusRect:= FocusRect;
DrawFocusRect(DC, PaintFocusRect);
LastFocusRect:= PaintFocusRect;
FirstTime:= False;
finally
ReleaseDC(0, DC);
end;
end
else
begin
DraggingForm := True;
sleep(10);
while PeekMessage(Msg, Handle, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE) do;
GetCursorPos(ACursorPos);
SetWindowPos(Handle, 0, ACursorPos.x - x, ACursorPos.y - y, 0, 0,
SWP_NOZORDER or SWP_NOSIZE or SWP_NOACTIVATE);
end;
end;
end;
procedure TvtCustomImageForm.MouseLoop_MouseUp(X, Y: Integer; ACursorPos: TPoint;
OriginalRect, FocusRect: TRect);
var
DC: HDC;
begin
if not DraggingForm then Exit;
DraggingForm:= False;
with GetParentForm(self) do
begin
if not GetDragFullWindows then
begin
DC := GetDC(0);
try
DrawFocusRect(DC, LastFocusRect);
finally
ReleaseDC(0, DC);
end;
SetWindowPos(Handle, 0, FocusRect.Left, FocusRect.top, 0, 0, SWP_NOZORDER or SWP_NOSIZE or SWP_NOACTIVATE or SWP_SHOWWINDOW);
if GetCapture = Handle then ReleaseCapture;
end;
end;
end;
procedure TvtCustomImageForm.SetParent(Value: TWinControl);
begin
if (Value <> nil) and not (Value is TCustomForm) then
Value := GetParentForm(Value);
inherited SetParent(value);
if Parent <> nil then
SetWindowLong(Parent.Handle, GWL_STYLE, GetWindowLong(Parent.Handle, GWL_STYLE) and not WS_CLIPCHILDREN);
if Value <> Nil then TForm(Value).BorderStyle := bsNone;
if (Value<>nil) and
(FCaptureMessageClass = nil) and
not (csDesigning in ComponentState) then
begin
fCaptureMessageClass := TvtCaptureMessageClass.Create(Owner);
fCaptureMessageClass.WindowHandle := Value.Handle;
fCaptureMessageClass.Enabled := True;
fCaptureMessageClass.OnBeforeWndProc := BeforeFormWndProc;
fCaptureMessageClass.OnWndProc := AfterFormWndProc;
end;
end;
procedure TvtCustomImageForm.ApplyBitmapRegion;
begin
SetWindowRgn(GetParentForm(self).Handle, 0, False);
if FRegion <> 0 then DeleteObject(FRegion);
FRegion := vtCreateRegionFromBitmap(Picture.Bitmap, GetTransparentColor);
if not (csDesigning in ComponentState) then
SetWindowRgn(GetParentForm(self).Handle, FRegion, True);
end;
function TvtCustomImageForm.GetPicture: TPicture;
begin
Result := inherited Picture;
end;
procedure TvtCustomImageForm.Paint;
begin
if FRegion = 0 then ApplyBitmapRegion;
Inherited;
end;
function TvtCustomImageForm.GetTransparentColor: TColor;
begin
Result := fTransparentColor;
if FTransparentColor=clNone then
begin
if (Picture.Bitmap <> Nil) then
Result := Picture.Bitmap.Canvas.Pixels[0,Picture.Bitmap.height-1]
end
else
Result := fTransparentColor;
end;
procedure TvtCustomImageForm.SetPicture(Value: TPicture);
begin
inherited Picture := Value;
if (Value <> nil) and (Value.Width > 0) and (Value.height > 0) then
begin
(Parent as TCustomForm).ClientWidth := Value.Width;
(Parent as TCustomForm).ClientHeight := Value.Height;
end;
Invalidate;
end;
procedure TvtCustomImageForm.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited;
// Added to support autosizing of the form
if AutoSize then
with GetParentForm(self) do
begin
ClientWidth := AWidth;
ClientHeight := AHeight;
end;
end;
procedure TvtCustomImageForm.DrawFocusRect(DC: HDC; FocusRect: TRect);
begin
Windows.DrawFocusRect(DC, FocusRect);
InflateRect(FocusRect, -1, -1);
Windows.DrawFocusRect(DC, FocusRect);
InflateRect(FocusRect, -1, -1);
Windows.DrawFocusRect(DC, FocusRect);
end;
procedure TvtCustomImageForm.SetCaptionBarControl(Value: TControl);
begin
if Value <> FCaptionBarControl then
FCaptionBarControl:= Value;
end;
{TvtCaptureMessageClass}
constructor TvtCaptureMessageClass.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOldWndHandler := nil;
FWndHandlerPtr := nil;
FWinControl := nil;
FWndHandle := 0;
FEnabled := false;
end;
destructor TvtCaptureMessageClass.Destroy;
begin
Enabled := False;
inherited Destroy;
end;
procedure TvtCaptureMessageClass.EndSubClass;
begin
if IsWindow(FWndHandle) then
begin
SetWindowLong(FWndHandle, GWL_WNDPROC, LongInt(FOldWndHandler));
FOldWndHandler := nil;
end;
if FWndHandlerPtr <> nil then
FreeObjectInstance(FWndHandlerPtr);
fEnabled := false;
end;
procedure TvtCaptureMessageClass.NewWndProc(var Message: TMessage);
begin
WndProc(Message);
end;
procedure TvtCaptureMessageClass.SetEnabled(aValue: Boolean);
begin
if fEnabled <> aValue then
begin
fEnabled := aValue;
if fEnabled then
StartSubClass
else
EndSubClass;
end;
end;
procedure TvtCaptureMessageClass.SetWndControl(Value: TWinControl);
begin
if Value <> FWinControl then
if Value is TWinControl then
begin
FWinControl := Value;
WindowHandle := FWinControl.Handle;
end;
end;
procedure TvtCaptureMessageClass.SetWndHandle(Value: Hwnd);
begin
if FWndHandle <> 0 then EndSubClass;
FWndHandle := Value;
if (FWndHandle <> 0) and FEnabled then StartSubClass;
end;
procedure TvtCaptureMessageClass.StartSubClass;
begin
if IsWindow(FWndHandle) then
begin
FOldWndHandler := Pointer(GetWindowLong(FWndHandle, GWL_WNDPROC));
FWndHandlerPtr := MakeObjectInstance(NewWndProc);
if FWndHandlerPtr = nil then
raise EOutOfResources.Create('OutOfResources');
SetWindowLong(FWndHandle, GWL_WNDPROC, LongInt(FWndHandlerPtr));
FEnabled := true;
end;
end;
procedure TvtCaptureMessageClass.WndProc(var Message: TMessage);
var
lProcessMessage : Boolean;
begin
if Assigned(FOnBeforeWndProc) then
begin
FOnBeforeWndProc(Message, lProcessMessage);
if not lProcessMessage then exit;
end;
with Message do
Result := CallWindowProc(FOldWndHandler, FWndHandle, Msg, wParam, lParam);
if Assigned(FOnWndProc) then FOnWndProc(Message);
end;
end.
|
unit Model.EntregadoresExpressas;
interface
uses
Common.ENum, FireDAC.Comp.Client, DAO.Conexao, System.SysUtils;
type
TEntregadoresExpressas = class
private
FCadastro: Integer;
FEntregador: Integer;
FFantasia: String;
FAgente: Integer;
FData: TDateTime;
FChave: String;
FGrupo: Integer;
FVerba: Double;
FExecutor: String;
FManutencao: TDateTime;
FAcao: TAcao;
FConexao : TConexao;
FTabela: Integer;
FCliente: Integer;
FAtivo: Integer;
FID: Integer;
function Inserir(): Boolean;
function Alterar(): Boolean;
function Excluir(): Boolean;
procedure SetCadastro(const value: Integer);
procedure SetEntregador(const value: Integer);
procedure SetFantasia(const value: String);
procedure SetAgente(const value: Integer);
procedure SetData(const value: TDateTime);
procedure SetChave(const value: String);
procedure SetGrupo(const value: Integer);
procedure SetVerba(const value: Double);
procedure SetExecutor(const value: String);
procedure SetManutencao(const value: TDateTime);
procedure SetAcao(const value: TAcao);
procedure SetTabela(const Value: Integer);
procedure SetCliente(const Value: Integer);
procedure setAtivo(const Value: Integer);
procedure SetID(const Value: Integer);
public
constructor Create;
property ID: Integer read FID write SetID;
property Cadastro: Integer read FCadastro write SetCadastro;
property Entregador: Integer read FEntregador write SetEntregador;
property Fantasia: String read FFantasia write SetFantasia;
property Agente: Integer read FAgente write SetAgente;
property Data: TDateTime read FData write SetData;
property Chave: String read FChave write SetChave;
property Grupo: Integer read FGrupo write SetGrupo;
property Verba: Double read FVerba write SetVerba;
property Executor: String read FExecutor write SetExecutor;
property Tabela: Integer read FTabela write SetTabela;
property Cliente: Integer read FCliente write SetCliente;
property Ativo: Integer read FAtivo write setAtivo;
property Manutencao: TDateTime read FManutencao write SetManutencao;
property Acao: TAcao read FAcao write SetAcao;
function Localizar(aParam: array of variant): TFDQuery;
function LocalizarExato(aParam: array of variant): boolean;
function Gravar(): Boolean;
function GetField(sField: String; sKey: String; sKeyValue: String): String;
function EntregadorExiste(iTipo, iCliente, iEntregador: Integer; sERP: String): Boolean;
function SetupModel(FDEntregadores: TFDQuery): Boolean;
procedure ClearModel;
end;
const
TABLENAME = 'tbcodigosentregadores';
SQLINSERT = 'INSERT INTO ' + TABLENAME + '(COD_CADASTRO, COD_ENTREGADOR, NOM_FANTASIA, COD_AGENTE, DAT_CODIGO, ' +
'DES_CHAVE, COD_GRUPO, VAL_VERBA, NOM_EXECUTANTE, DOM_ATIVO, DAT_MANUTENCAO, COD_TABELA, COD_CLIENTE) ' +
'VALUES ' +
'(:COD_CADASTRO, :COD_ENTREGADOR, :NOM_FANTASIA, :COD_AGENTE, :DAT_CODIGO, :DES_CHAVE, :COD_GRUPO, ' +
':VAL_VERBA, :NOM_EXECUTANTE, :COM_ATIVO, :DAT_MANUTENCAO, :COD_TABELA, :COD_CLIENTE);';
SQLUPDATE = 'UPDATE ' + TABLENAME + ' SET ' +
'COD_CADASTRO = :COD_CADASTRO, COD_ENTREGADOR = :COD_ENTREGADOR, ' +
'NOM_FANTASIA = :NOM_FANTASIA, COD_AGENTE = :COD_AGENTE, DAT_CODIGO = :DAT_CODIGO, DES_CHAVE = :DES_CHAVE, ' +
'COD_GRUPO = :COD_GRUPO, VAL_VERBA = :VAL_VERBA, NOM_EXECUTANTE = :NOM_EXECUTANTE, ' +
'DOM_ATIVO = :DOM_ATIVO, DAT_MANUTENCAO = :DAT_MANUTENCAO, COD_TABELA = :COD_TABELA, COD_CLIENTE = :COD_CLIENTE ' +
'WHERE ID_ENTREGADOR = :ID;';
implementation
{ TEntregadoresExpressas }
uses Control.Sistema;
function TEntregadoresExpressas.Alterar: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL(SQLUPDATE, [Self.Cadastro, Self.Entregador, Self.Fantasia, Self.Agente, Self.Data, Self.Chave, Self.Grupo, Self.Verba, Self.Executor,
Self.Ativo, Self.Manutencao, Self.Tabela, Self.Cliente, Self.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
procedure TEntregadoresExpressas.ClearModel;
begin
ID := 0;
Cadastro := 0;
Entregador := 0;
Fantasia := '';
Agente := 0;
Data := StrToDate('31/12/1899');
Chave := '';
Grupo := 0;
Verba := 0;
Executor := '';
Manutencao := StrToDateTime('31/12/1899 23:59:59');
Tabela := 0;
end;
constructor TEntregadoresExpressas.Create;
begin
FConexao := TSistemaControl.GetInstance().Conexao;
end;
function TEntregadoresExpressas.EntregadorExiste(iTipo, iCliente, iEntregador: Integer; sERP: String): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
if iTipo = 1 then
begin
FDQuery.SQL.Add('select cod_cliente, cod_entregador from ' + TABLENAME + ' where cod_cliente = :cliente and cod_entregador = :entregador;');
FDQuery.ParamByName('cliente').AsInteger := iCliente;
FDQuery.ParamByName('entregador').AsInteger := iEntregador;
FDQuery.Open();
if FDQuery.IsEmpty then
begin
Exit;
end;
Result := True;
end
else if iTipo = 2 then
begin
FDQuery.SQL.Add('select cod_cliente, des_chave from ' + TABLENAME + ' where cod_cliente = :cliente and des_chave = :chave;');
FDQuery.ParamByName('cliente').AsInteger := iCliente;
FDQuery.ParamByName('chave').AsString := sERP;
FDQuery.Open();
if FDQuery.IsEmpty then
begin
Exit;
end;
Result := True;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TEntregadoresExpressas.Excluir: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_entregador = :id',
[Self.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TEntregadoresExpressas.GetField(sField, sKey, sKeyValue: String): String;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.SQL.Text := 'select ' + sField + ' from ' + TABLENAME + ' where ' + sKey + ' = ' + sKeyValue;
FDQuery.Open();
if not FDQuery.IsEmpty then Result := FDQuery.FieldByName(sField).AsString;
finally
FDQuery.Free;
end;
end;
function TEntregadoresExpressas.Gravar: Boolean;
begin
Result := False;
case FAcao of
Common.ENum.tacIncluir: Result := Inserir();
Common.ENum.tacAlterar: Result := Alterar();
Common.ENum.tacExcluir: Result := Excluir();
end;
end;
function TEntregadoresExpressas.Inserir: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL(SQLINSERT, [Self.Cadastro, Self.Entregador, Self.Fantasia, Self.Agente, Self.Data, Self.Chave, Self.Grupo,
Self.Verba, Self.Executor, Self.Ativo, Self.Manutencao, Self.Tabela, Self.Cliente]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TEntregadoresExpressas.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_entregador = :id');
FDQuery.ParamByName('id').AsInteger := aParam[1];
end;
if aParam[0] = 'CADASTRO' then
begin
FDQuery.SQL.Add('WHERE COD_CADASTRO = :COD_CADASTRO');
FDQuery.ParamByName('COD_CADASTRO').AsInteger := aParam[1];
end;
if aParam[0] = 'ENTREGADOR' then
begin
FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :COD_ENTREGADOR');
FDQuery.ParamByName('COD_ENTREGADOR').AsInteger := aParam[1];
end;
if aParam[0] = 'AGENTE' then
begin
FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE');
FDQuery.ParamByName('COD_AGENTE').AsInteger := aParam[1];
end;
if aParam[0] = 'DATA' then
begin
FDQuery.SQL.Add('WHERE DAT_CODIGO = :DAT_CODIGO');
FDQuery.ParamByName('DAT_CODIGO').AsDate := aParam[1];
end;
if aParam[0] = 'FANTASIA' then
begin
FDQuery.SQL.Add('WHERE NOM_FANTASIA = :NOM_FANTASIA');
FDQuery.ParamByName('NOM_FANTASIA').AsString := aParam[1];
end;
if aParam[0] = 'CHAVE' then
begin
FDQuery.SQL.Add('WHERE DES_CHAVE = :DES_CHAVE');
FDQuery.ParamByName('DES_CHAVE').AsString := aParam[1];
end;
if aParam[0] = 'CHAVECLIENTE' then
begin
FDQuery.SQL.Add('WHERE DES_CHAVE = :DES_CHAVE AND COD_CLIENTE = :COD_CLIENTE');
FDQuery.ParamByName('DES_CHAVE').AsString := aParam[1];
FDQuery.ParamByName('COD_CLIENTE').AsInteger := aParam[2];
end;
if aParam[0] = 'ENTREGADORCLIENTE' then
begin
FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :COD_ENTREGADOR AND COD_CLIENTE = :COD_CLIENTE');
FDQuery.ParamByName('COD_ENTREGADOR').AsInteger := aParam[1];
FDQuery.ParamByName('COD_CLIENTE').AsInteger := aParam[2];
end;
if aParam[0] = 'CLIENTE' then
begin
FDQuery.SQL.Add('WHERE COD_CLIENTE = :COD_CLIENTE');
FDQuery.ParamByName('COD_CLIENTE').AsInteger := 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;
if not FDQuery.IsEmpty then
begin
if aParam[0] <> 'APOIO' then SetupModel(FDQuery);
end
else
begin
ClearModel;
end;
Result := FDQuery;
end;
function TEntregadoresExpressas.LocalizarExato(aParam: array of variant): boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'CADASTRO' then
begin
FDQuery.SQL.Add('WHERE COD_CADASTRO = :COD_CADASTRO');
FDQuery.ParamByName('COD_CADASTRO').AsInteger := aParam[1];
end;
if aParam[0] = 'ENTREGADOR' then
begin
FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :COD_ENTREGADOR');
FDQuery.ParamByName('COD_ENTREGADOR').AsInteger := aParam[1];
end;
if aParam[0] = 'AGENTE' then
begin
FDQuery.SQL.Add('WHERE COD_AGENTE = :COD_AGENTE');
FDQuery.ParamByName('COD_AGENTE').AsInteger := aParam[1];
end;
if aParam[0] = 'DATA' then
begin
FDQuery.SQL.Add('WHERE DAT_CODIGO = :DAT_CODIGO');
FDQuery.ParamByName('DAT_CODIGO').AsDate := aParam[1];
end;
if aParam[0] = 'FANTASIA' then
begin
FDQuery.SQL.Add('WHERE NOM_FANTASIA = :NOM_FANTASIA');
FDQuery.ParamByName('NOM_FANTASIA').AsString := aParam[1];
end;
if aParam[0] = 'CHAVE' then
begin
FDQuery.SQL.Add('WHERE DES_CHAVE = :DES_CHAVE');
FDQuery.ParamByName('DES_CHAVE').AsString := aParam[1];
end;
if aParam[0] = 'CHAVECLIENTE' then
begin
FDQuery.SQL.Add('WHERE DES_CHAVE = :DES_CHAVE AND COD_CLIENTE = :COD_CLIENTE');
FDQuery.ParamByName('DES_CHAVE').AsString := aParam[1];
FDQuery.ParamByName('COD_CLIENTE').AsInteger := aParam[2];
end;
if aParam[0] = 'ENTREGADORCLIENTE' then
begin
FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :COD_ENTREGADOR AND COD_CLIENTE = :COD_CLIENTE');
FDQuery.ParamByName('COD_ENTREGADOR').AsInteger := aParam[1];
FDQuery.ParamByName('COD_CLIENTE').AsInteger := aParam[2];
end;
if aParam[0] = 'CLIENTE' then
begin
FDQuery.SQL.Add('WHERE COD_CLIENTE = :COD_CLIENTE');
FDQuery.ParamByName('COD_CLIENTE').AsInteger := 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;
if not FDQuery.IsEmpty then
begin
if aParam[0] <> 'APOIO' then SetupModel(FDQuery);
end
else
begin
ClearModel;
Exit;
end;
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
procedure TEntregadoresExpressas.SetAcao(const value: TAcao);
begin
Facao := value;
end;
procedure TEntregadoresExpressas.SetAgente(const value: Integer);
begin
FAgente := value;
end;
procedure TEntregadoresExpressas.setAtivo(const Value: Integer);
begin
FAtivo := Value;
end;
procedure TEntregadoresExpressas.SetCadastro(const value: Integer);
begin
FCadastro := value;
end;
procedure TEntregadoresExpressas.SetChave(const value: String);
begin
FChave := value;
end;
procedure TEntregadoresExpressas.SetCliente(const Value: Integer);
begin
FCliente := Value;
end;
procedure TEntregadoresExpressas.SetData(const value: TDateTime);
begin
FData := value;
end;
procedure TEntregadoresExpressas.SetEntregador(const value: Integer);
begin
FEntregador := value;
end;
procedure TEntregadoresExpressas.SetExecutor(const value: String);
begin
FExecutor := value;
end;
procedure TEntregadoresExpressas.SetFantasia(const value: String);
begin
FFantasia := value;
end;
procedure TEntregadoresExpressas.SetGrupo(const value: Integer);
begin
FGrupo := value;
end;
procedure TEntregadoresExpressas.SetID(const Value: Integer);
begin
FID := Value;
end;
procedure TEntregadoresExpressas.SetManutencao(const value: TDateTime);
begin
FManutencao := value;
end;
procedure TEntregadoresExpressas.SetTabela(const Value: Integer);
begin
FTabela := Value;
end;
function TEntregadoresExpressas.SetupModel(FDEntregadores: TFDQuery): Boolean;
begin
try
Result := False;
ID := FDEntregadores.FieldByName('id_entregador').AsInteger;
Cadastro := FDEntregadores.FieldByName('cod_cadastro').AsInteger;
Entregador := FDEntregadores.FieldByName('cod_entregador').AsInteger;
Fantasia := FDEntregadores.FieldByName('nom_fantasia').AsString;
Agente := FDEntregadores.FieldByName('cod_agente').AsInteger;
Data := FDEntregadores.FieldByName('dat_codigo').AsDateTime;
Chave := FDEntregadores.FieldByName('des_chave').AsString;
Grupo := FDEntregadores.FieldByName('cod_grupo').AsInteger;
Verba := FDEntregadores.FieldByName('val_verba').AsFloat;
Executor := FDEntregadores.FieldByName('nom_executante').AsString;
Manutencao := FDEntregadores.FieldByName('dat_manutencao').AsDateTime;
Tabela := FDEntregadores.FieldByName('cod_tabela').AsInteger;
finally
Result := True;
end;
end;
procedure TEntregadoresExpressas.SetVerba(const value: Double);
begin
FVerba := value;
end;
end.
|
unit modShapes;
interface
const
MAX = 10;
type
pointRec = record
x : integer;
y : integer;
end;
shape = class
visible : boolean;
procedure move(mx, my : integer); virtual; abstract; (* abstract methods have no definition *)
procedure write; virtual;
end;
shapes = array[1..MAX] of shape;
line = class(shape)
private
startP, endP : PointRec;
public
constructor init(startP, endP : pointRec);
procedure move(mx, my : integer); virtual;
procedure write; virtual;
end;
rectangle = class(shape)
private
p0, p1, p2, p3 : pointRec;
public
constructor init(lt, rb : pointRec);
procedure move(mx, my, : integer); virtual;
procedure write; virtual;
end;
circle = class(shape)
private
center : pointRec;
radius : integer;
public
constructor init(c : pointRec;
r : integer);
procedure move(mx, my : integer); virtual;
procedure write; virtual;
end;
picture = class(shape)
private
shapes : shapeArray;
numShapes : integer;
public
constructor init;
procedure move(mx, my : integer); virtual;
procedure add(s : shape);
procedure write; virtual;
end;
implementation
procedure addToPoint(var p : pointRec; x, y : integer);
begin
p.x := p.x + x;
p.y := p.y + y;
end;
(***************Line***************)
constructor lineObj.init(startP, endP : PointRec);
begin
self.startP := startP;
self.endP := endP;
visible := TRUE;
end;
procedure lineObj.move(mx, my : integer);
begin
addToPoint(startP, mx, my);
addToPoint(endP, mx, my);
end;
procedure line.write;
begin
writeLn('Line from ', startP. x, ',', startP.y, ') to (', endP.x, ',' endP.y, ')');
end;
(************************RECTANGLE*****************)
constructor rectangle.init(lt, rb : PointRec);
begin
p0 := lt;
p2 := rb;
p1.x := p2.x;
p1.y := p0.y;
p3.x := p0.x;
p3.y := p2.y;
end;
procedure rectangle.move(mx, my : integer);
begin
addToPoint(p0, mx, my);
addToPoint(p1, mx, my);
addToPoint(p2, mx, my);
addToPoint(p3, mx, my);
end;
procedure rectangle.write;
begin
writeLn('Rectangle: ');
writeLn('(', p0.x,',', p0.y,')');
end;
(*********************Circle****************************)
constructor circle.init(c: pointRec; r : integer);
begin
self.center := c;
self.radius := r;
visible := TRUE;
end;
procedure circle.move(mx, my : integer),
begin
addToPoint(center, mx, my);
end;
procedure circle.write;
begin
writeLn('Circle with center: (', center.x, ',', center.y, ') radius: ', radius);
end;
(********************PICTURE**************************)
constructor picture.init;
begin
numShapes := 0;
visible := TRUE;
end;
procedure picture.move(mx, my : integer);
var i : integer;
begin
for i := 1 to numShapes do
shapes[i].move(mx, my);
end;
procedure picture.add(s : shape);
begin
if numShapes >= MAX then begin
writeLn('Picture is full');
halt;
end;
if s = self then begin
writeLn('Cannot add picture to itself');
halt;
end;
inc(numShapes);
shapes[numShapes] := s;
end;
procedure picture.write
var i : integer;
begin
writeLn('Picture with ', numShapes, ' shapes: ');
for i := 1 to numShapes do
shapes[i].write;
end;
begin
end. |
unit gradcustomcontrol;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, Graphics;
type
{ TGradCustomControl }
TGradCustomControl = class(TCustomControl)
protected
FBuffer: TBitmap;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ChangeBounds(ALeft, ATop, AWidth, AHeight: integer;
KeepBase: boolean); override;
procedure Paint; override;
procedure PaintTo(ACanvas: TCanvas; X, Y: Integer); overload;
procedure _Paint(ACanvas: TCanvas); virtual; abstract;
end;
implementation
{ TGradCustomControl }
constructor TGradCustomControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBuffer := TBitmap.Create;
end;
destructor TGradCustomControl.Destroy;
begin
FBuffer.Free;
inherited Destroy;
end;
procedure TGradCustomControl.ChangeBounds(ALeft, ATop, AWidth,
AHeight: integer; KeepBase: boolean);
begin
FBuffer.SetSize(AWidth, AHeight);
_Paint(FBuffer.Canvas);
inherited ChangeBounds(ALeft, ATop, AWidth, AHeight, KeepBase);
end;
procedure TGradCustomControl.Paint;
begin
if not HasParent then
Exit;
Canvas.Draw(0,0, FBuffer);
inherited Paint;
end;
procedure TGradCustomControl.PaintTo(ACanvas: TCanvas; X, Y: Integer);
begin
ACanvas.Draw(0,0, FBuffer);
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clImapUtils;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils;
{$ELSE}
System.Classes, System.SysUtils;
{$ENDIF}
type
TclImap4ConnectionState = (csNonAuthenticated, csAuthenticated, csSelected);
TclMailMessageFlag = (mfAnswered, mfFlagged, mfDeleted, mfSeen, mfDraft, mfRecent);
TclMailMessageFlags = set of TclMailMessageFlag;
TclSetFlagsMethod = (fmReplace, fmAdd, fmRemove);
TclImap4MailBoxInfo = class
private
FName: string;
FRecentMessages: Integer;
FFirstUnseen: Integer;
FExistsMessages: Integer;
FReadOnly: Boolean;
FFlags: TclMailMessageFlags;
FChangeableFlags: TclMailMessageFlags;
FUIDValidity: string;
FUIDNext: Integer;
FUnseenMessages: Integer;
public
constructor Create;
procedure Clear; virtual;
procedure Assign(ASource: TclImap4MailBoxInfo); virtual;
property Name: string read FName write FName;
property ExistsMessages: Integer read FExistsMessages write FExistsMessages;
property RecentMessages: Integer read FRecentMessages write FRecentMessages;
property UnseenMessages: Integer read FUnseenMessages write FUnseenMessages;
property FirstUnseen: Integer read FFirstUnseen write FFirstUnseen;
property ReadOnly: Boolean read FReadOnly write FReadOnly;
property Flags: TclMailMessageFlags read FFlags write FFlags;
property ChangeableFlags: TclMailMessageFlags read FChangeableFlags write FChangeableFlags;
property UIDValidity: string read FUIDValidity write FUIDValidity;
property UIDNext: Integer read FUIDNext write FUIDNext;
end;
function GetStrByImapMessageFlags(AFlags: TclMailMessageFlags): string;
function GetImapMessageFlagsByStr(const AText: string): TclMailMessageFlags;
function ExtractMessageSize(const ASource: string): Int64;
procedure ParseMailboxInfo(const AMailBoxInfo: string; var ASeparator: Char; var AName: string);
function DateTimeToImapTime(ADate: TDateTime): string;
function IsInState(ACurrentState: TclImap4ConnectionState;
ACheckStates: array of TclImap4ConnectionState): Boolean;
implementation
uses
clUtils;
function GetStrByImapMessageFlags(AFlags: TclMailMessageFlags): string;
const
flagLexems: array[TclMailMessageFlag] of string =
('\Answered', '\Flagged', '\Deleted', '\Seen', '\Draft', '\Recent');
var
flag: TclMailMessageFlag;
begin
Result := '';
for flag := Low(TclMailMessageFlag) to High(TclMailMessageFlag) do
begin
if (flag in AFlags) then
begin
Result := Result + ' ' + flagLexems[flag];
end;
end;
Result := Trim(Result);
end;
function GetImapMessageFlagsByStr(const AText: string): TclMailMessageFlags;
begin
Result := [];
if (System.Pos('\ANSWERED', AText) > 0) then
Result := Result + [mfAnswered];
if (System.Pos('\FLAGGED', AText) > 0) then
Result := Result + [mfFlagged];
if (System.Pos('\DELETED', AText) > 0) then
Result := Result + [mfDeleted];
if (System.Pos('\SEEN', AText) > 0) then
Result := Result + [mfSeen];
if (System.Pos('\DRAFT', AText) > 0) then
Result := Result + [mfDraft];
if (System.Pos('\RECENT', AText) > 0) then
Result := Result + [mfRecent];
end;
function ExtractMessageSize(const ASource: string): Int64;
var
indEnd, indStart: Integer;
begin
Result := 0;
indEnd := RTextPos('}', ASource);
if (indEnd = 0) then Exit;
indStart := RTextPos('{', ASource, indEnd);
if (indStart = 0) then Exit;
Result := StrToInt64Def(system.Copy(ASource, indStart + 1, indEnd - indStart - 1), 0);
end;
procedure ParseMailboxInfo(const AMailBoxInfo: string; var ASeparator: Char; var AName: string);
var
ind: Integer;
begin
ASeparator := #0;
AName := '';
ind := System.Pos(')', AMailBoxInfo);
if (ind > 0) then
begin
AName := Trim(System.Copy(AMailBoxInfo, ind + 1, MaxInt));
if (AName <> '') and (AName[1] = '"') then
begin
if ((AName[2] = '\') and (Length(AName) > 2) and (AName[3] <> '"')) then
begin
ASeparator := AName[3];
end else
begin
ASeparator := AName[2];
end;
end;
ind := System.Pos(' ', AName);
if (ind > 0) then
begin
AName := Trim(System.Copy(AName, ind + 1, MaxInt));
end;
AName := ExtractQuotedString(AName, '"');
end;
end;
function DateTimeToImapTime(ADate: TDateTime): string;
var
Year, Month, Day, Hour, Min, Sec, MSec: Word;
MonthName: String;
begin
DecodeDate(ADate, Year, Month, Day);
DecodeTime(ADate, Hour, Min, Sec, MSec);
MonthName := cMonths[Month];
Result := Format('%d-%s-%d %d:%.2d:%.2d %s', [Day, MonthName, Year, Hour, Min, Sec, TimeZoneBiasString]);
end;
function IsInState(ACurrentState: TclImap4ConnectionState;
ACheckStates: array of TclImap4ConnectionState): Boolean;
var
i: Integer;
begin
for i := Low(ACheckStates) to High(ACheckStates) do
begin
Result := (ACurrentState = ACheckStates[i]);
if Result then Exit;
end;
Result := False;
end;
{ TclImap4MailBoxInfo }
procedure TclImap4MailBoxInfo.Assign(ASource: TclImap4MailBoxInfo);
begin
Assert(ASource <> nil);
FName := ASource.Name;
FRecentMessages := ASource.RecentMessages;
FFirstUnseen := ASource.FirstUnseen;
FExistsMessages := ASource.ExistsMessages;
FReadOnly := ASource.ReadOnly;
FFlags := ASource.Flags;
FChangeableFlags := ASource.ChangeableFlags;
FUIDValidity := ASource.UIDValidity;
FUIDNext := ASource.UIDNext;
FUnseenMessages := ASource.UnseenMessages;
end;
procedure TclImap4MailBoxInfo.Clear;
begin
FName := '';
FRecentMessages := 0;
FUnseenMessages := 0;
FFirstUnseen := 0;
FExistsMessages := 0;
FReadOnly := False;
FFlags := [];
FChangeableFlags := [];
FUIDValidity := '';
FUIDNext := 0;
end;
constructor TclImap4MailBoxInfo.Create;
begin
inherited Create();
Clear();
end;
end.
|
unit ssClientDataSet;
interface
uses
Windows, Messages, SysUtils, Classes, DB,
{$IFNDEF NODESIGN}DesignEditors, DSDesign,{$ENDIF}
DBClient;
type
TssClientDataSet = class(TClientDataSet)
private
FMacros: TParams;
procedure SetMacros(const Value: TParams);
protected
procedure OpenCursor(InfoQuery: Boolean); override;
public
procedure FetchMacros;
procedure SendMacros;
procedure Execute; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Macros: TParams read FMacros write SetMacros;
end;
{$IFNDEF NODESIGN}
TssCDSEditor = class(TComponentEditor)
public
function GetVerb(Index: Integer): string; override;
function GetVerbCount: integer; override;
procedure ExecuteVerb(Index: Integer); override;
end;
{$ENDIF}
implementation
uses Variants;
{ TssClientDataSet }
//==============================================================================================
constructor TssClientDataSet.Create(AOwner: TComponent);
begin
inherited;
FMacros := TParams.Create(Self);
end;
//==============================================================================================
destructor TssClientDataSet.Destroy;
begin
FreeAndNil(FMacros);
inherited;
end;
//==============================================================================================
procedure TssClientDataSet.Execute;
begin
if FMacros.Count > 0 then SendMacros;
inherited;
end;
//==============================================================================================
procedure TssClientDataSet.FetchMacros;
var
OwnerData, FData: OleVariant;
S: Variant;
begin
OwnerData := NULL;
//FData := IssSrvDisp(AppServer).AS_GetMacros(ProviderName, OwnerData);
S := AppServer;
FData := S.AS_GetMacros(ProviderName, OwnerData);
UnpackParams(FData, FMacros);
end;
//==============================================================================================
procedure TssClientDataSet.OpenCursor(InfoQuery: Boolean);
begin
if FMacros.Count>0 then SendMacros;
inherited;
end;
//==============================================================================================
procedure TssClientDataSet.SendMacros;
var
FData: OleVariant;
S: Variant;
begin
FData := PackageParams(FMacros);
//IssSrvDisp(AppServer).AS_SetMacros(ProviderName, FData);
S := AppServer;
S.AS_SetMacros(ProviderName, FData);
end;
//==============================================================================================
procedure TssClientDataSet.SetMacros(const Value: TParams);
begin
FMacros.Assign(Value);
end;
{ TssCDSEditor }
{$IFNDEF NODESIGN}
//==============================================================================================
procedure TssCDSEditor.ExecuteVerb(Index: Integer);
begin
case Index of
//0: ShowFieldsEditor(Designer, TDataSet(Component), TDSDesigner);
1: TssClientDataSet(Component).FetchParams;
2: TssClientDataSet(Component).FetchMacros;
end;
end;
//==============================================================================================
function TssCDSEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := 'Fields Editor...';
1: Result := 'Fetch Params';
2: Result := 'Fetch Macros';
end;
end;
//==============================================================================================
function TssCDSEditor.GetVerbCount: integer;
begin
Result := 3;
end;
{$ENDIF}
end.
|
Unit l3MinMax;
interface
{ Библиотека "L3 (Low Level Library)" }
{ Автор: Люлин А.В. © }
{ Модуль: l3MinMax - }
{ Начат: 01.12.95 16:28 }
{ $Id: l3MinMax.pas,v 1.9 2016/03/23 14:36:16 lulin Exp $ }
// $Log: l3MinMax.pas,v $
// Revision 1.9 2016/03/23 14:36:16 lulin
// - вычищаем.
//
// Revision 1.8 2014/05/20 16:49:24 lulin
// - пытаемся восстановить компилируемость под XE.
//
// Revision 1.7 2013/04/08 14:50:41 lulin
// - портируем.
//
// Revision 1.6 2011/09/07 12:47:02 fireton
// - Min64 и Max64
//
// Revision 1.5 2007/12/05 15:38:06 lulin
// - удалены ненужные файлы.
//
// Revision 1.4 2001/10/26 13:10:27 law
// - new procs: MinIntValue и MaxIntValue.
//
// Revision 1.3 2000/12/15 15:19:01 law
// - вставлены директивы Log.
//
(*uses
l3Types
;*)
function Max(A, B: LongInt): LongInt;
function Max64(A, B: Int64): Int64;
function Min(A, B: LongInt): LongInt;
function Min64(A, B: Int64): Int64;
function ULongComp(A, B: LongInt): ShortInt;
{-сравнивает два длинных целых без учета знака}
function CardinalDec(A: Cardinal; Delta: Cardinal): Cardinal;
{-}
function MinIntValue(const Data: array of Integer): Integer;
{-}
function MaxIntValue(const Data: array of Integer): Integer;
{-}
function MaxFloat(const Values: array of Extended): Extended;
(*
function Min(X, Y: Integer): Integer;
function Max(X, Y: Integer): Integer;
function MaxWord(X, Y: Word): Word;
function MinWord(X, Y: Word): Word;
function MaxLong(A, B: LongInt): LongInt;
function MinLong(A, B: LongInt): LongInt;
function BComp(const P1,P2; Len: Word): Boolean;
*)
implementation
function CardinalDec(A: Cardinal; Delta: Cardinal): Cardinal;
{-}
begin
if (A > Delta) then
Result := A - Delta
else
Result := 0;
end;
function Min(A, B: LongInt): LongInt;
begin
if (A < B) then
Result := A
else
Result := B;
end;
function Min64(A, B: Int64): Int64;
begin
if (A < B) then
Result := A
else
Result := B;
end;
function Max(A, B: LongInt): LongInt;
begin
if (A > B) then
Result := A
else
Result := B;
end;
function Max64(A, B: Int64): Int64;
begin
if (A > B) then
Result := A
else
Result := B;
end;
{$IfDef Win32}
function ULongComp(A, B: LongInt): ShortInt;
{eax, edx}
register;
{-сравнивает два длинных целых без учета знака}
asm
xor ecx, ecx
cmp eax, edx
je @@ret
jb @@Dec
inc ecx
jmp @@ret
@@Dec:
dec ecx
@@ret:
mov eax, ecx
end;
{$Else Win32}
function ULongComp(A, B: LongInt): ShortInt;
assembler;
{-сравнивает два длинных целых без учета знака}
asm
xor cl, cl
db $66; mov ax, word ptr ss:[A]
db $66; mov dx, word ptr ss:[B]
db $66; cmp ax, dx
je @@ret
jb @@Dec
inc cl
jmp @@ret
@@Dec:
dec cl
@@ret:
mov al, cl
end;{asm}
{$EndIf Win32}
function MinIntValue(const Data: array of Integer): Integer;
var
I: Integer;
begin
Result := Data[Low(Data)];
for I := Low(Data) + 1 to High(Data) do
if Result > Data[I] then
Result := Data[I];
end;
function MaxIntValue(const Data: array of Integer): Integer;
var
I: Integer;
begin
Result := Data[Low(Data)];
for I := Low(Data) + 1 to High(Data) do
if Result < Data[I] then
Result := Data[I];
end;
(*function Min(X, Y: Integer): Integer;
{$IFDEF WIN32}
begin
if (X < Y) then Result := X else Result := Y;
end;
{$ELSE WIN32}
assembler;
asm
MOV AX,X
CMP AX,Y
JLE @@1
MOV AX,Y
@@1:
end;
{$ENDIF WIN32}
function Max(X, Y: Integer): Integer;
{$IFDEF WIN32}
begin
if (X > Y) then Result := X else Result := Y;
end;
{$ELSE WIN32}
assembler;
asm
MOV AX,X
CMP AX,Y
JGE @@1
MOV AX,Y
@@1:
end;
{$ENDIF WIN32}
function MinWord(X, Y: Word): Word;
{$IFDEF WIN32}
begin
if (X < Y) then Result := X else Result := Y;
end;
{$ELSE WIN32}
assembler;
asm
MOV AX,X
CMP AX,Y
JBE @@1
MOV AX,Y
@@1:
end;
{$ENDIF WIN32}
function MaxWord(X, Y: Word): Word;
{$IFDEF WIN32}
begin
if (X > Y) then Result := X else Result := Y;
end;
{$ELSE WIN32}
assembler;
asm
MOV AX,X
CMP AX,Y
JAE @@1
MOV AX,Y
@@1:
end;
{$ENDIF WIN32}
{
function MaxLong(A, B: LongInt): LongInt; assembler;
asm
MOV DX, Word(A+2)
MOV AX, Word(A)
CMP DX, Word(B+2)
JL @yes
JG @no
CMP AX, Word(B)
JGE @no
@yes:
MOV DX, Word(B+2)
MOV AX, Word(B)
@no:
end;
function MinLong(A, B: LongInt): LongInt; assembler;
asm
MOV DX, Word(A+2)
MOV AX, Word(A)
CMP DX, Word(B+2)
JG @yes
JL @no
CMP AX, Word(B)
JLE @no
@yes:
MOV DX, Word(B+2)
MOV AX, Word(B)
@no:
end;
}
function MinLong(A, B: LongInt): LongInt;
begin
if (A < B) then MinLong := A else MinLong := B;
end;
function MaxLong(A, B: LongInt): LongInt;
begin
if (A > B) then MaxLong := A else MaxLong := B;
end;
function BComp(const P1,P2; Len: Word): Boolean;
var
S1 : PAnsiChar;
S2 : PAnsiChar;
i : integer;
begin
Result := true;
S1 := PAnsiChar(@P1); S2 := PAnsiChar(@P2);
for i := 0 to Len-1 do
if (S1[i]<>S2[i]) then begin
Result := false;
Exit;
end;
end;
*)
function MaxFloat(const Values: array of Extended): Extended;
var
I: Cardinal;
begin
Result := Values[0];
for I := 0 to High(Values) do
if Values[I] > Result then Result := Values[I];
end;
end.
|
unit uSelfDialogBox;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TfDialogBox }
TfDialogBox = class(TForm)
btnYes: TButton;
btnNo: TButton;
Label1: TLabel;
procedure btnYesClick(Sender: TObject);
private
{ private declarations }
function yesClicked:boolean;
public
{ public declarations }
property isYesClicked : boolean read yesClicked;
procedure showDialog(p_label :string);
end;
var
fDialogBox: TfDialogBox;
v_yesClicked :boolean;
implementation
{$R *.lfm}
{ TfDialogBox }
procedure TfDialogBox.btnYesClick(Sender: TObject);
begin
v_yesClicked :=true;
close;
end;
function TfDialogBox.yesClicked: boolean;
begin
result := v_yesClicked ;
end;
procedure TfDialogBox.showDialog(p_label: string);
begin
Label1.Caption:=p_label;
Visible:=true;
end;
end.
|
unit define_stock_info;
interface
type
TStockInfoType = (inf_Undefine,
inf_EPS, // earnings per share
inf_PE_LYR, // price earning ratio
inf_PE_TTM, // price earning ratio
inf_GeneralCapital,
inf_NAPS, // 每股净资产 net asset per share
inf_PB, // 市净率
inf_Flow,
inf_DPS,
inf_PS
);
const
StockInfoKeyWord: array[TStockInfoType] of String = ('',
'每股收益',
'静态市盈率', // 市盈率LYR 静态市盈率 市盈率TTM 动态市盈率
'动态市盈率', // 市盈率LYR 静态市盈率 市盈率TTM 动态市盈率
'总股本', // capitalization
'每股净资产',
'市净率', // 每股股价与每股净资产的比率
'流通股本', // capital stock in circulation / Flow of equity
'每股股息', // Dividend Per Share
'市销率' // 市销率( Price-to-sales,PS), PS = 总市值 除以主营业务收入或者 PS=股价 除以每股销售额
);
implementation
end.
|
unit frmInIOCPWebQueryScores;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, iocp_sockets, iocp_managers, iocp_server,
http_base, http_objects, fmIOCPSvrInfo;
type
TFormInIOCPWebQueryScores = class(TForm)
InIOCPServer1: TInIOCPServer;
InHttpDataProvider1: TInHttpDataProvider;
btnStart: TButton;
btnStop: TButton;
FrameIOCPSvrInfo1: TFrameIOCPSvrInfo;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure InHttpDataProvider1Get(Sender: TObject; Request: THttpRequest;
Response: THttpResponse);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure InHttpDataProvider1Accept(Sender: TObject; Request: THttpRequest;
var Accept: Boolean);
procedure InIOCPServer1AfterOpen(Sender: TObject);
private
{ Private declarations }
FAppDir: String;
FWebSitePath: String;
public
{ Public declarations }
end;
var
FormInIOCPWebQueryScores: TFormInIOCPWebQueryScores;
implementation
uses
iocp_log, iocp_utils, iocp_msgPacks, http_utils;
type
// 准考证号
TExamNumber = string[10];
// 成绩记录
PStudentScores = ^TStudentScores;
TStudentScores = record
ExamNo: TExamNumber; // 准考证号
Scores: AnsiString; // JSON 格式的成绩单
end;
// 三个字符的类型
PThreadChars = ^TThreadChars;
TThreadChars = array[0..2] of AnsiChar;
var
// 分数数组
FScores: array of TStudentScores;
procedure LoadFromTextFile(const FileName: string);
procedure ExtractString(var Scores, LeftValue: AnsiString);
var
i: Integer;
begin
// 提取左侧内容
i := Pos(#9, Scores);
if (i > 0) then
begin
LeftValue := Copy(Scores, 1, i - 1);
Delete(Scores, 1, i);
end else
begin
LeftValue := Scores;
Scores := '';
end;
end;
procedure WriteData(const S: AnsiString; var ToBuf: PAnsiChar; ItemType: Integer);
begin
// 写字段或字段值
if (Length(S) > 0) then
begin
System.Move(S[1], ToBuf^, Length(S));
Inc(ToBuf, Length(S));
end;
case ItemType of
0: // 字段
PThreadChars(ToBuf)^ := AnsiString('":"');
1: // 值
PThreadChars(ToBuf)^ := AnsiString('","')
else // 结束
PThreadChars(ToBuf)^ := AnsiString('"}]');
end;
Inc(ToBuf, 3); // 前移 3 字节
end;
var
i: Integer;
LeftVal, S: AnsiString;
Student: PStudentScores;
p: PAnsiChar;
Strs: TStrings;
begin
// 从以 TAB 分隔的文本文件读入成绩(不带标题)
// 字段:准考证号 姓名 语文 数学 总分 等级
// JSON: [{"ExamNo":"123456789","name":"..","chinese":"80","maths":"90","total":"170","level":"AAAA"}]
Strs := TStringList.Create;
try
Strs.LoadFromFile(FileName);
// 设置数组长度(每行一条记录)
SetLength(FScores, Strs.Count);
for i := 0 to Strs.Count - 1 do
begin
S := Trim(Strs[i]);
if (Length(S) = 0) or (S[1] = '/') then // 为空或注解
Continue;
Student := @FScores[i];
SetLength(Student^.Scores, Length(S) * 5); // 预设 JSON 空间
p := PAnsiChar(Student^.Scores); // 写入的地址
// 开始
PThreadChars(p)^ := AnsiString('[{"');
Inc(p, 3); // 前移 3 字节
// 内容不多,逐一提取字段内容,加入
// 1. 准考证号
WriteData('examNo', p, 0);
ExtractString(S, LeftVal);
Student^.ExamNo := LeftVal;
WriteData(LeftVal, p, 1);
// 2. 姓名
WriteData('name', p, 0);
ExtractString(S, LeftVal);
WriteData(LeftVal, p, 1);
// 3. 语文
WriteData('chinese', p, 0);
ExtractString(S, LeftVal);
WriteData(LeftVal, p, 1);
// 4. 数学
WriteData('maths', p, 0);
ExtractString(S, LeftVal);
WriteData(LeftVal, p, 1);
// 5. 总分
WriteData('total', p, 0);
ExtractString(S, LeftVal);
WriteData(LeftVal, p, 1);
// 6. 等级
WriteData('level', p, 0);
ExtractString(S, LeftVal);
WriteData(LeftVal, p, 2); // 结束
// 删除多余的空间
Delete(FScores[i].Scores, Integer(p - PAnsiChar(FScores[i].Scores)) + 1, 999);
end;
finally
Strs.Free;
end;
end;
{$R *.dfm}
procedure TFormInIOCPWebQueryScores.btnStartClick(Sender: TObject);
begin
iocp_log.TLogThread.InitLog; // 开启日志
// 从以 TAB 分隔的文本文件读入成绩
// 考生数量、成绩单都相对固定,不用数据库,直接使用数组保存成绩。
LoadFromTextFile(FWebSitePath + 'scores.txt');
InIOCPServer1.Active := True; // 开启服务
FrameIOCPSvrInfo1.Start(InIOCPServer1); // 开始统计
end;
procedure TFormInIOCPWebQueryScores.btnStopClick(Sender: TObject);
begin
InIOCPServer1.Active := False; // 停止服务
FrameIOCPSvrInfo1.Stop; // 停止统计
iocp_log.TLogThread.StopLog; // 停止日志
if (FScores <> nil) then // 释放数组
SetLength(FScores, 0);
end;
procedure TFormInIOCPWebQueryScores.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
btnStopClick(nil);
end;
procedure TFormInIOCPWebQueryScores.FormCreate(Sender: TObject);
begin
FAppDir := ExtractFilePath(Application.ExeName); // 本地路径
FWebSitePath := FAppDir + AddBackslash(InHttpDataProvider1.RootDirectory); // 网站路径
MyCreateDir(FAppDir + 'log'); // 日志路径
end;
procedure TFormInIOCPWebQueryScores.InHttpDataProvider1Accept(Sender: TObject;
Request: THttpRequest; var Accept: Boolean);
begin
// 在此判断是否接受请求:
// Request.Method: 方法
// Request.URI:路径/资源
IF (Request.Method = hmGet) then
Accept := True // Request.URI = '/QueryScores'; // 允许
else
Accept := False; // 拒绝
end;
procedure TFormInIOCPWebQueryScores.InHttpDataProvider1Get(Sender: TObject;
Request: THttpRequest; Response: THttpResponse);
var
i: Integer;
ExamNo: TExamNumber;
Scores: PStudentScores;
begin
// Get: 查询准考证号,返回 JSON 数据(这种情况无需加锁)
if (Request.URI = '/queryScores.do') then
begin
// 查询成绩
ExamNo := Request.Params.AsString['exam_no'];
Memo1.Lines.Add('准考证号=' + ExamNo);
if (Length(ExamNo) > 0) then
for i := 0 to High(FScores) do
begin
Scores := @FScores[i];
if (Scores^.ExamNo = ExamNo) then // 找到记录
begin
Response.SetContent(Scores^.Scores); // 发送 JSON 成绩
Exit;
end;
end;
// 考生不存在!
Response.SetContent('NOT_EXISTS');
end else
if (Request.URI = '/return') then
begin
// 重定位
Response.Redirect('/');
end else
if (Request.URI = '/query.htm') then
begin
// 返回查询页
Response.TransmitFile(FWebSitePath + 'query.htm');
end else
if (Request.URI = '/favicon.ico') then
begin
Response.StatusCode := 204; // 没有东西
end else
begin
// 返回首页
Memo1.Lines.Add('传入参数,x=' + Request.Params.AsString['x']);
Response.TransmitFile(FWebSitePath + 'index.htm');
end;
end;
procedure TFormInIOCPWebQueryScores.InIOCPServer1AfterOpen(Sender: TObject);
begin
btnStart.Enabled := not InIOCPServer1.Active;
btnStop.Enabled := InIOCPServer1.Active;
end;
end.
|
unit define_dealstore_header;
interface
uses
define_price;
type
// ================================================================
// header define
// ================================================================
TStore_Signature = packed record // 6
Signature : Word;
DataVer1 : Byte;
DataVer2 : Byte;
DataVer3 : Byte;
// 字节存储顺序 java 和 delphi 不同
// 00
// 01
BytesOrder : Byte;
end;
// SizeMode = 0 -- 未定义
// [ 一段一段 表明自己的 begin -- end 无明显 pagesize 区分]
// SizeMode = 01 -- 流式存储
// SizeMode = 02 -- 4 2^(2 )
// SizeMode = 03 -- 8 2^(3 )
// SizeMode = 04 -- 16 2^(4 )
// SizeMode = 05 -- 32 2^(5 )
// SizeMode = 06 -- 64 2^(6 )
// SizeMode = 10 -- 1k
// SizeMode = 16 -- 64k
// -------------------------
// SizeMode = 19 -- 512k
// SizeMode = 20 -- 1m
// SizeMode = 30 -- 1G
// -------------------------
TStore_SizeMode = packed record
Value : Byte;
end;
// java 存 int 和 delphi 纯 integer 字节存储顺序是反的
TStore_Common_Header_V1 = packed record
Signature : TStore_Signature; // 6
HeadSize : Byte; // 1 -- 7
StoreSizeMode : TStore_SizeMode; // 1 -- 8 page size mode
{ 表明是什么数据 }
DataType : Word; // 2 -- 10
DataMode : Byte; // 1 -- 11
RecordSizeMode : TStore_SizeMode; // 1 -- 12
RecordCount : integer; // 4 -- 16
CompressFlag : Byte; // 1 -- 17
EncryptFlag : Byte; // 1 -- 18
DataSourceId : Word; // 2 -- 20
end;
TStore_Quote_M1_Header_V1 = packed record
CommonHeader : TStore_Common_Header_V1;
Code : array[0..11] of AnsiChar; // 12 - 32
StorePriceFactor : Word; // 2 - 34
end;
PStore_Weight_Header_V1 = ^TStore_Weight_Header_V1;
TStore_Weight_Header_V1 = packed record
CommonHeader : TStore_Common_Header_V1;
Code : array[0..11] of AnsiChar; // 12 - 32
end;
// 日交易明细
TStore_Quote_M2_Header_V1 = packed record
CommonHeader : TStore_Common_Header_V1;
Code : array[0..11] of AnsiChar; // 12 - 32
// ----------------------------------------------------
StorePriceFactor : Word; // 2 - 34
FirstDealDate : Word;
LastDealDate : Word;
end;
// 日线
PStore_Quote_M1_Day_Header_V1 = ^TStore_Quote_M1_Day_Header_V1;
TStore_Quote_M1_Day_Header_V1 = packed record
BaseHeader : TStore_Quote_M1_Header_V1; // 34
FirstDealDate : Word; // 2 - 36
LastDealDate : Word; // 2 - 38
EndDealDate : Word; // 2 - 40
end;
PStore_Quote_M1_Day_Header_V1Rec = ^TStore_Quote_M1_Day_Header_V1Rec;
TStore_Quote_M1_Day_Header_V1Rec = packed record
Header: TStore_Quote_M1_Day_Header_V1;
Reserve: array[0..64 - SizeOf(TStore_Quote_M1_Day_Header_V1) - 1] of Byte;
end;
PStore_Quote_M1_Minute_Header_V1 = ^TStore_Quote_M1_Minute_Header_V1;
TStore_Quote_M1_Minute_Header_V1 = packed record
BaseHeader : TStore_Quote_M1_Header_V1; // 34
Minute : integer;
FirstDealDateTime : TDateTime; // 需要这个吗 ??
LastDealDateTime : TDateTime;
end;
PStore_Quote_M1_Minute_Header_V1Rec = ^TStore_Quote_M1_Minute_Header_V1Rec;
TStore_Quote_M1_Minute_Header_V1Rec = packed record
Header: TStore_Quote_M1_Minute_Header_V1;
Reserve: array[0..64 - SizeOf(TStore_Quote_M1_Minute_Header_V1) - 1] of Byte;
end;
// 日交易明细 1min
TStore_Quote_M1_Time_Header_V1 = packed record
BaseHeader : TStore_Quote_M1_Header_V1; // 34
FirstDealDate : Word; // 2 - 36
LastDealDate : Word; // 2 - 38
DateTimeInterval : Word; // 2 - 40
///昨收盘
PreClosePrice : TStore_Price; // 4 - 44
///涨停板价
UpperLimitPrice : TStore_Price; // 4 - 48
///跌停板价
LowerLimitPrice : TStore_Price; // 4 - 52
// 这里不需要做统计 放到 日线数据里去吧
//PriceRange : TStore_PriceRange;
//DealAmount : Int64; // 成交金额 // 8 - 62
//DealVolume : Int64; // 成交量 // 8 - 70
end;
PStore_Quote_M2_Detail_Header_V1 = ^TStore_Quote_M2_Detail_Header_V1;
TStore_Quote_M2_Detail_Header_V1 = packed record
BaseHeader: TStore_Quote_M2_Header_V1;
end;
PStore_Quote_M2_Detail_Header_V1Rec = ^TStore_Quote_M2_Detail_Header_V1Rec;
TStore_Quote_M2_Detail_Header_V1Rec = packed record
Header: TStore_Quote_M2_Detail_Header_V1;
Reserve: array[0..64 - SizeOf(TStore_Quote_M2_Detail_Header_V1) - 1] of Byte;
end;
PStore_Weight_Header_V1Rec = ^TStore_Weight_Header_V1Rec;
TStore_Weight_Header_V1Rec = packed record
Header: TStore_Weight_Header_V1;
Reserve: array[0..64 - SizeOf(TStore_Weight_Header_V1) - 1] of Byte;
end;
PStore_Stock_Weight = ^TStore_Stock_Weight;
TStore_Stock_Weight = packed record // 16
Value : double; // 8
PackedValue : LongWord; // 4
StartDate : Word; // 2
EndDate : Word; // 2
end;
PStore_Stock_WeightRec = ^TStore_Stock_WeightRec;
TStore_Stock_WeightRec = packed record
WeightData : TStore_Stock_Weight;
Reserve: array[0..32 - SizeOf(TStore_Stock_Weight) - 1] of Byte;
end;
const
DataType_Stock = 1;
DataType_Futures = 2;
DataType_DBItem = 3;
DataMode_DayData = 1; // 日线数据 M1
// M1 Stock
// M1 CTP
// 5秒
// 15秒
// 1分钟
// 5分钟
// 10分钟
// 15分钟
// 30分钟
// 60分钟
DataMode_DayDetailDataM1 = 2; // 日明细 M1 --
DataMode_DayDetailDataM2 = 3; // 日明细 M2
DataMode_DayInstant = 4;
DataMode_DayValue = 5;
DataMode_WeightData = 6;
DataMode_MinuteData = 7;
// 日线不需要 实时不需要 DataType_QuoteRangeData 需要
// 0.1 秒为单位 ???
// 600 -- 1分钟
// 36000 < 65565 -- 1小时 < 一天
// 9:00 -- 15:00 -- 7 * 36000 [可以使用 Integer 不需要 double]
// 一旦大于 36000 则使用新的 单位 方式
DateTimeInterval_1Sec = 1 * 10;
DateTimeInterval_5Sec = 5 * DateTimeInterval_1Sec;
DateTimeInterval_15Sec = 15 * DateTimeInterval_1Sec;
DateTimeInterval_1Min = 1 * 60 * 10;
DateTimeInterval_5Min = 5 * DateTimeInterval_1Min;
DateTimeInterval_10Min = 10 * DateTimeInterval_1Min;
DateTimeInterval_15Min = 15 * DateTimeInterval_1Min;
DateTimeInterval_20Min = 20 * DateTimeInterval_1Min;
DateTimeInterval_30Min = 30 * DateTimeInterval_1Min;
DateTimeInterval_60Min = 60 * DateTimeInterval_1Min; // 36000
implementation
end.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2016 * }
{ *********************************************************** }
unit tfMD5;
{$I TFL.inc}
{$IFDEF TFL_CPUX86_WIN32}
{$DEFINE CPUX86_WIN32}
{$ENDIF}
{$IFDEF TFL_CPUX64_WIN64}
{$DEFINE CPUX64_WIN64}
{$ENDIF}
interface
uses tfTypes;
type
PMD5Alg = ^TMD5Alg;
TMD5Alg = record
private type
TData = record
Digest: TMD5Digest;
Block: array[0..63] of Byte; // 512-bit message block
Count: UInt64; // number of bytes processed
end;
private
FVTable: Pointer;
FRefCount: Integer;
FData: TData;
procedure Compress;
public
class procedure Init(Inst: PMD5Alg);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class procedure Update(Inst: PMD5Alg; Data: PByte; DataSize: Cardinal);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class procedure Done(Inst: PMD5Alg; PDigest: PMD5Digest);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetDigestSize(Inst: PMD5Alg): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetBlockSize(Inst: PMD5Alg): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function Duplicate(Inst: PMD5Alg; var DupInst: PMD5Alg): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
end;
function GetMD5Algorithm(var Inst: PMD5Alg): TF_RESULT;
implementation
uses tfRecords;
const
MD5VTable: array[0..9] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@HashAlgRelease,
@TMD5Alg.Init,
@TMD5Alg.Update,
@TMD5Alg.Done,
@TMD5Alg.Init,
@TMD5Alg.GetDigestSize,
@TMD5Alg.GetBlockSize,
@TMD5Alg.Duplicate
);
function GetMD5Algorithm(var Inst: PMD5Alg): TF_RESULT;
var
P: PMD5Alg;
begin
try
New(P);
P^.FVTable:= @MD5VTable;
P^.FRefCount:= 1;
TMD5Alg.Init(P);
if Inst <> nil then HashAlgRelease(Inst);
Inst:= P;
Result:= TF_S_OK;
except
Result:= TF_E_OUTOFMEMORY;
end;
end;
{$IFDEF CPUX86_WIN32}
procedure TMD5Alg.Compress;
asm
PUSH ESI
PUSH EDI
PUSH EBX
LEA EDI,[EAX].TMD5Alg.FData.Block
MOV EAX,[EDI - 16] // A:= FData.Digest[0];
MOV EBX,[EDI - 12] // B:= FData.Digest[1];
MOV ECX,[EDI - 8] // C:= FData.Digest[2];
MOV EDX,[EDI - 4] // D:= FData.Digest[3];
// function FF(A, B, C, D, X, S: UInt32): UInt32; inline;
// begin
// Result:= A + ((B and (C xor D)) xor D) + X;
// Result:= Rol32(Result, S) + B;
// end;
// A:= FF(A, B, C, D, Block[ 0] + $D76AA478, 7); { 1 }
MOV ESI,ECX
ADD EAX,[EDI]
XOR ESI,EDX
AND ESI,EBX
XOR ESI,EDX
LEA EAX,[EAX + ESI + $D76AA478]
ROL EAX,7
ADD EAX,EBX
// D:= FF(D, A, B, C, Block[ 1] + $E8C7B756, 12); { 2 }
MOV ESI,EBX
ADD EDX,[EDI + 4]
XOR ESI,ECX
AND ESI,EAX
XOR ESI,ECX
LEA EDX,[EDX + ESI + $E8C7B756]
ROL EDX,12
ADD EDX,EAX
// C:= FF(C, D, A, B, Block[ 2] + $242070DB, 17); { 3 }
MOV ESI,EAX
ADD ECX,[EDI + 8]
XOR ESI,EBX
AND ESI,EDX
XOR ESI,EBX
LEA ECX,[ECX + ESI + $242070DB]
ROL ECX,17
ADD ECX,EDX
// B:= FF(B, C, D, A, Block[ 3] + $C1BDCEEE, 22); { 4 }
MOV ESI,EDX
ADD EBX,[EDI + 12]
XOR ESI,EAX
AND ESI,ECX
XOR ESI,EAX
LEA EBX,[EBX + ESI + $C1BDCEEE]
ROL EBX,22
ADD EBX,ECX
// A:= FF(A, B, C, D, Block[ 4] + $F57C0FAF, 7); { 5 }
MOV ESI,ECX
ADD EAX,[EDI + 16]
XOR ESI,EDX
AND ESI,EBX
XOR ESI,EDX
LEA EAX,[EAX + ESI + $F57C0FAF]
ROL EAX,7
ADD EAX,EBX
// D:= FF(D, A, B, C, Block[ 5] + $4787C62A, 12); { 6 }
MOV ESI,EBX
ADD EDX,[EDI + 20]
XOR ESI,ECX
AND ESI,EAX
XOR ESI,ECX
LEA EDX,[EDX + ESI + $4787C62A]
ROL EDX,12
ADD EDX,EAX
// C:= FF(C, D, A, B, Block[ 6] + $A8304613, 17); { 7 }
MOV ESI,EAX
ADD ECX,[EDI + 24]
XOR ESI,EBX
AND ESI,EDX
XOR ESI,EBX
LEA ECX,[ECX + ESI + $A8304613]
ROL ECX,17
ADD ECX,EDX
// B:= FF(B, C, D, A, Block[ 7] + $FD469501, 22); { 8 }
MOV ESI,EDX
ADD EBX,[EDI + 28]
XOR ESI,EAX
AND ESI,ECX
XOR ESI,EAX
LEA EBX,[EBX + ESI + $FD469501]
ROL EBX,22
ADD EBX,ECX
// A:= FF(A, B, C, D, Block[ 8] + $698098D8, 7); { 9 }
MOV ESI,ECX
ADD EAX,[EDI + 32]
XOR ESI,EDX
AND ESI,EBX
XOR ESI,EDX
LEA EAX,[EAX + ESI + $698098D8]
ROL EAX,7
ADD EAX,EBX
// D:= FF(D, A, B, C, Block[ 9] + $8B44F7AF, 12); { 10 }
MOV ESI,EBX
ADD EDX,[EDI + 36]
XOR ESI,ECX
AND ESI,EAX
XOR ESI,ECX
LEA EDX,[EDX + ESI + $8B44F7AF]
ROL EDX,12
ADD EDX,EAX
// C:= FF(C, D, A, B, Block[10] + $FFFF5BB1, 17); { 11 }
MOV ESI,EAX
ADD ECX,[EDI + 40]
XOR ESI,EBX
AND ESI,EDX
XOR ESI,EBX
LEA ECX,[ECX + ESI + $FFFF5BB1]
ROL ECX,17
ADD ECX,EDX
// B:= FF(B, C, D, A, Block[11] + $895CD7BE, 22); { 12 }
MOV ESI,EDX
ADD EBX,[EDI + 44]
XOR ESI,EAX
AND ESI,ECX
XOR ESI,EAX
LEA EBX,[EBX + ESI + $895CD7BE]
ROL EBX,22
ADD EBX,ECX
// A:= FF(A, B, C, D, Block[12] + $6B901122, 7); { 13 }
MOV ESI,ECX
ADD EAX,[EDI + 48]
XOR ESI,EDX
AND ESI,EBX
XOR ESI,EDX
LEA EAX,[EAX + ESI + $6B901122]
ROL EAX,7
ADD EAX,EBX
// D:= FF(D, A, B, C, Block[13] + $FD987193, 12); { 14 }
MOV ESI,EBX
ADD EDX,[EDI + 52]
XOR ESI,ECX
AND ESI,EAX
XOR ESI,ECX
LEA EDX,[EDX + ESI + $FD987193]
ROL EDX,12
ADD EDX,EAX
// C:= FF(C, D, A, B, Block[14] + $A679438E, 17); { 15 }
MOV ESI,EAX
ADD ECX,[EDI + 56]
XOR ESI,EBX
AND ESI,EDX
XOR ESI,EBX
LEA ECX,[ECX + ESI + $A679438E]
ROL ECX,17
ADD ECX,EDX
// B:= FF(B, C, D, A, Block[15] + $49B40821, 22); { 16 }
MOV ESI,EDX
ADD EBX,[EDI + 60]
XOR ESI,EAX
AND ESI,ECX
XOR ESI,EAX
LEA EBX,[EBX + ESI + $49B40821]
ROL EBX,22
ADD EBX,ECX
//function GG(A, B, C, D, X, S: UInt32): UInt32; inline;
//begin
// Result:= A + ((D and (B xor C)) xor C) + X;
// Result:= Rol32(Result, S) + B;
//end;
// A:= GG(A, B, C, D, Block[ 1] + $F61E2562, 5); { 17 }
MOV ESI,EBX
ADD EAX,[EDI + 4]
XOR ESI,ECX
AND ESI,EDX
XOR ESI,ECX
LEA EAX,[EAX + ESI + $F61E2562]
ROL EAX,5
ADD EAX,EBX
// D:= GG(D, A, B, C, Block[ 6] + $C040B340, 9); { 18 }
MOV ESI,EAX
ADD EDX,[EDI + 24]
XOR ESI,EBX
AND ESI,ECX
XOR ESI,EBX
LEA EDX,[EDX + ESI + $C040B340]
ROL EDX,9
ADD EDX,EAX
// C:= GG(C, D, A, B, Block[11] + $265E5A51, 14); { 19 }
MOV ESI,EDX
ADD ECX,[EDI + 44]
XOR ESI,EAX
AND ESI,EBX
XOR ESI,EAX
LEA ECX,[ECX + ESI + $265E5A51]
ROL ECX,14
ADD ECX,EDX
// B:= GG(B, C, D, A, Block[ 0] + $E9B6C7AA, 20); { 20 }
MOV ESI,ECX
ADD EBX,[EDI]
XOR ESI,EDX
AND ESI,EAX
XOR ESI,EDX
LEA EBX,[EBX + ESI + $E9B6C7AA]
ROL EBX,20
ADD EBX,ECX
// A:= GG(A, B, C, D, Block[ 5] + $D62F105D, 5); { 21 }
MOV ESI,EBX
ADD EAX,[EDI + 20]
XOR ESI,ECX
AND ESI,EDX
XOR ESI,ECX
LEA EAX,[EAX + ESI + $D62F105D]
ROL EAX,5
ADD EAX,EBX
// D:= GG(D, A, B, C, Block[10] + $02441453, 9); { 22 }
MOV ESI,EAX
ADD EDX,[EDI + 40]
XOR ESI,EBX
AND ESI,ECX
XOR ESI,EBX
LEA EDX,[EDX + ESI + $02441453]
ROL EDX,9
ADD EDX,EAX
// C:= GG(C, D, A, B, Block[15] + $D8A1E681, 14); { 23 }
MOV ESI,EDX
ADD ECX,[EDI + 60]
XOR ESI,EAX
AND ESI,EBX
XOR ESI,EAX
LEA ECX,[ECX + ESI + $D8A1E681]
ROL ECX,14
ADD ECX,EDX
// B:= GG(B, C, D, A, Block[ 4] + $E7D3FBC8, 20); { 24 }
MOV ESI,ECX
ADD EBX,[EDI + 16]
XOR ESI,EDX
AND ESI,EAX
XOR ESI,EDX
LEA EBX,[EBX + ESI + $E7D3FBC8]
ROL EBX,20
ADD EBX,ECX
// A:= GG(A, B, C, D, Block[ 9] + $21E1CDE6, 5); { 25 }
MOV ESI,EBX
ADD EAX,[EDI + 36]
XOR ESI,ECX
AND ESI,EDX
XOR ESI,ECX
LEA EAX,[EAX + ESI + $21E1CDE6]
ROL EAX,5
ADD EAX,EBX
// D:= GG(D, A, B, C, Block[14] + $C33707D6, 9); { 26 }
MOV ESI,EAX
ADD EDX,[EDI + 56]
XOR ESI,EBX
AND ESI,ECX
XOR ESI,EBX
LEA EDX,[EDX + ESI + $C33707D6]
ROL EDX,9
ADD EDX,EAX
// C:= GG(C, D, A, B, Block[ 3] + $F4D50D87, 14); { 27 }
MOV ESI,EDX
ADD ECX,[EDI + 12]
XOR ESI,EAX
AND ESI,EBX
XOR ESI,EAX
LEA ECX,[ECX + ESI + $F4D50D87]
ROL ECX,14
ADD ECX,EDX
// B:= GG(B, C, D, A, Block[ 8] + $455A14ED, 20); { 28 }
MOV ESI,ECX
ADD EBX,[EDI + 32]
XOR ESI,EDX
AND ESI,EAX
XOR ESI,EDX
LEA EBX,[EBX + ESI + $455A14ED]
ROL EBX,20
ADD EBX,ECX
// A:= GG(A, B, C, D, Block[13] + $A9E3E905, 5); { 29 }
MOV ESI,EBX
ADD EAX,[EDI + 52]
XOR ESI,ECX
AND ESI,EDX
XOR ESI,ECX
LEA EAX,[EAX + ESI + $A9E3E905]
ROL EAX,5
ADD EAX,EBX
// D:= GG(D, A, B, C, Block[ 2] + $FCEFA3F8, 9); { 30 }
MOV ESI,EAX
ADD EDX,[EDI + 8]
XOR ESI,EBX
AND ESI,ECX
XOR ESI,EBX
LEA EDX,[EDX + ESI + $FCEFA3F8]
ROL EDX,9
ADD EDX,EAX
// C:= GG(C, D, A, B, Block[ 7] + $676F02D9, 14); { 31 }
MOV ESI,EDX
ADD ECX,[EDI + 28]
XOR ESI,EAX
AND ESI,EBX
XOR ESI,EAX
LEA ECX,[ECX + ESI + $676F02D9]
ROL ECX,14
ADD ECX,EDX
// B:= GG(B, C, D, A, Block[12] + $8D2A4C8A, 20); { 32 }
MOV ESI,ECX
ADD EBX,[EDI + 48]
XOR ESI,EDX
AND ESI,EAX
XOR ESI,EDX
LEA EBX,[EBX + ESI + $8D2A4C8A]
ROL EBX,20
ADD EBX,ECX
//function HH(A, B, C, D, X, S: UInt32): UInt32; inline;
//begin
// Result:= A + (B xor C xor D) + X;
// Result:= Rol32(Result, S) + B;
//end;
// A:= HH(A, B, C, D, Block[ 5] + $FFFA3942, 4); { 33 }
MOV ESI,ECX
ADD EAX,[EDI + 20]
XOR ESI,EDX
XOR ESI,EBX
LEA EAX,[EAX + ESI + $FFFA3942]
ROL EAX,4
ADD EAX,EBX
// D:= HH(D, A, B, C, Block[ 8] + $8771F681, 11); { 34 }
MOV ESI,EBX
ADD EDX,[EDI + 32]
XOR ESI,ECX
XOR ESI,EAX
LEA EDX,[EDX + ESI + $8771F681]
ROL EDX,11
ADD EDX,EAX
// C:= HH(C, D, A, B, Block[11] + $6D9D6122, 16); { 35 }
MOV ESI,EAX
ADD ECX,[EDI + 44]
XOR ESI,EBX
XOR ESI,EDX
LEA ECX,[ECX + ESI + $6D9D6122]
ROL ECX,16
ADD ECX,EDX
// B:= HH(B, C, D, A, Block[14] + $FDE5380C, 23); { 36 }
MOV ESI,EDX
ADD EBX,[EDI + 56]
XOR ESI,EAX
XOR ESI,ECX
LEA EBX,[EBX + ESI + $FDE5380C]
ROL EBX,23
ADD EBX,ECX
// A:= HH(A, B, C, D, Block[ 1] + $A4BEEA44, 4); { 37 }
MOV ESI,ECX
ADD EAX,[EDI + 4]
XOR ESI,EDX
XOR ESI,EBX
LEA EAX,[EAX + ESI + $A4BEEA44]
ROL EAX,4
ADD EAX,EBX
// D:= HH(D, A, B, C, Block[ 4] + $4BDECFA9, 11); { 38 }
MOV ESI,EBX
ADD EDX,[EDI + 16]
XOR ESI,ECX
XOR ESI,EAX
LEA EDX,[EDX + ESI + $4BDECFA9]
ROL EDX,11
ADD EDX,EAX
// C:= HH(C, D, A, B, Block[ 7] + $F6BB4B60, 16); { 39 }
MOV ESI,EAX
ADD ECX,[EDI + 28]
XOR ESI,EBX
XOR ESI,EDX
LEA ECX,[ECX + ESI + $F6BB4B60]
ROL ECX,16
ADD ECX,EDX
// B:= HH(B, C, D, A, Block[10] + $BEBFBC70, 23); { 40 }
MOV ESI,EDX
ADD EBX,[EDI + 40]
XOR ESI,EAX
XOR ESI,ECX
LEA EBX,[EBX + ESI + $BEBFBC70]
ROL EBX,23
ADD EBX,ECX
// A:= HH(A, B, C, D, Block[13] + $289B7EC6, 4); { 41 }
MOV ESI,ECX
ADD EAX,[EDI + 52]
XOR ESI,EDX
XOR ESI,EBX
LEA EAX,[EAX + ESI + $289B7EC6]
ROL EAX,4
ADD EAX,EBX
// D:= HH(D, A, B, C, Block[ 0] + $EAA127FA, 11); { 42 }
MOV ESI,EBX
ADD EDX,[EDI]
XOR ESI,ECX
XOR ESI,EAX
LEA EDX,[EDX + ESI + $EAA127FA]
ROL EDX,11
ADD EDX,EAX
// C:= HH(C, D, A, B, Block[ 3] + $D4EF3085, 16); { 43 }
MOV ESI,EAX
ADD ECX,[EDI + 12]
XOR ESI,EBX
XOR ESI,EDX
LEA ECX,[ECX + ESI + $D4EF3085]
ROL ECX,16
ADD ECX,EDX
// B:= HH(B, C, D, A, Block[ 6] + $04881D05, 23); { 44 }
MOV ESI,EDX
ADD EBX,[EDI + 24]
XOR ESI,EAX
XOR ESI,ECX
LEA EBX,[EBX + ESI + $04881D05]
ROL EBX,23
ADD EBX,ECX
// A:= HH(A, B, C, D, Block[ 9] + $D9D4D039, 4); { 45 }
MOV ESI,ECX
ADD EAX,[EDI + 36]
XOR ESI,EDX
XOR ESI,EBX
LEA EAX,[EAX + ESI + $D9D4D039]
ROL EAX,4
ADD EAX,EBX
// D:= HH(D, A, B, C, Block[12] + $E6DB99E5, 11); { 46 }
MOV ESI,EBX
ADD EDX,[EDI + 48]
XOR ESI,ECX
XOR ESI,EAX
LEA EDX,[EDX + ESI + $E6DB99E5]
ROL EDX,11
ADD EDX,EAX
// C:= HH(C, D, A, B, Block[15] + $1FA27CF8, 16); { 47 }
MOV ESI,EAX
ADD ECX,[EDI + 60]
XOR ESI,EBX
XOR ESI,EDX
LEA ECX,[ECX + ESI + $1FA27CF8]
ROL ECX,16
ADD ECX,EDX
// B:= HH(B, C, D, A, Block[ 2] + $C4AC5665, 23); { 48 }
MOV ESI,EDX
ADD EBX,[EDI + 8]
XOR ESI,EAX
XOR ESI,ECX
LEA EBX,[EBX + ESI + $C4AC5665]
ROL EBX,23
ADD EBX,ECX
//function II(A, B, C, D, X, S: UInt32): UInt32; inline;
//begin
// Result:= A + (C xor (B or not D)) + X;
// Result:= Rol32(Result, S) + B;
//end;
// A:= II(A, B, C, D, Block[ 0] + $F4292244, 6); { 49 }
MOV ESI,EDX
NOT ESI
ADD EAX,[EDI]
OR ESI,EBX
XOR ESI,ECX
LEA EAX,[EAX + ESI + $F4292244]
ROL EAX,6
ADD EAX,EBX
// D:= II(D, A, B, C, Block[ 7] + $432AFF97, 10); { 50 }
MOV ESI,ECX
NOT ESI
ADD EDX,[EDI + 28]
OR ESI,EAX
XOR ESI,EBX
LEA EDX,[EDX + ESI + $432AFF97]
ROL EDX,10
ADD EDX,EAX
// C:= II(C, D, A, B, Block[14] + $AB9423A7, 15); { 51 }
MOV ESI,EBX
NOT ESI
ADD ECX,[EDI + 56]
OR ESI,EDX
XOR ESI,EAX
LEA ECX,[ECX + ESI + $AB9423A7]
ROL ECX,15
ADD ECX,EDX
// B:= II(B, C, D, A, Block[ 5] + $FC93A039, 21); { 52 }
MOV ESI,EAX
NOT ESI
ADD EBX,[EDI + 20]
OR ESI,ECX
XOR ESI,EDX
LEA EBX,[EBX + ESI + $FC93A039]
ROL EBX,21
ADD EBX,ECX
// A:= II(A, B, C, D, Block[12] + $655B59C3, 6); { 53 }
MOV ESI,EDX
NOT ESI
ADD EAX,[EDI + 48]
OR ESI,EBX
XOR ESI,ECX
LEA EAX,[EAX + ESI + $655B59C3]
ROL EAX,6
ADD EAX,EBX
// D:= II(D, A, B, C, Block[ 3] + $8F0CCC92, 10); { 54 }
MOV ESI,ECX
NOT ESI
ADD EDX,[EDI + 12]
OR ESI,EAX
XOR ESI,EBX
LEA EDX,[EDX + ESI + $8F0CCC92]
ROL EDX,10
ADD EDX,EAX
// C:= II(C, D, A, B, Block[10] + $FFEFF47D, 15); { 55 }
MOV ESI,EBX
NOT ESI
ADD ECX,[EDI + 40]
OR ESI,EDX
XOR ESI,EAX
LEA ECX,[ECX + ESI + $FFEFF47D]
ROL ECX,15
ADD ECX,EDX
// B:= II(B, C, D, A, Block[ 1] + $85845DD1, 21); { 56 }
MOV ESI,EAX
NOT ESI
ADD EBX,[EDI + 4]
OR ESI,ECX
XOR ESI,EDX
LEA EBX,[EBX + ESI + $85845DD1]
ROL EBX,21
ADD EBX,ECX
// A:= II(A, B, C, D, Block[ 8] + $6FA87E4F, 6); { 57 }
MOV ESI,EDX
NOT ESI
ADD EAX,[EDI + 32]
OR ESI,EBX
XOR ESI,ECX
LEA EAX,[EAX + ESI + $6FA87E4F]
ROL EAX,6
ADD EAX,EBX
// D:= II(D, A, B, C, Block[15] + $FE2CE6E0, 10); { 58 }
MOV ESI,ECX
NOT ESI
ADD EDX,[EDI + 60]
OR ESI,EAX
XOR ESI,EBX
LEA EDX,[EDX + ESI + $FE2CE6E0]
ROL EDX,10
ADD EDX,EAX
// C:= II(C, D, A, B, Block[ 6] + $A3014314, 15); { 59 }
MOV ESI,EBX
NOT ESI
ADD ECX,[EDI + 24]
OR ESI,EDX
XOR ESI,EAX
LEA ECX,[ECX + ESI + $A3014314]
ROL ECX,15
ADD ECX,EDX
// B:= II(B, C, D, A, Block[13] + $4E0811A1, 21); { 60 }
MOV ESI,EAX
NOT ESI
ADD EBX,[EDI + 52]
OR ESI,ECX
XOR ESI,EDX
LEA EBX,[EBX + ESI + $4E0811A1]
ROL EBX,21
ADD EBX,ECX
// A:= II(A, B, C, D, Block[ 4] + $F7537E82, 6); { 61 }
MOV ESI,EDX
NOT ESI
ADD EAX,[EDI + 16]
OR ESI,EBX
XOR ESI,ECX
LEA EAX,[EAX + ESI + $F7537E82]
ROL EAX,6
ADD EAX,EBX
// D:= II(D, A, B, C, Block[11] + $BD3AF235, 10); { 62 }
MOV ESI,ECX
NOT ESI
ADD EDX,[EDI + 44]
OR ESI,EAX
XOR ESI,EBX
LEA EDX,[EDX + ESI + $BD3AF235]
ROL EDX,10
ADD EDX,EAX
// C:= II(C, D, A, B, Block[ 2] + $2AD7D2BB, 15); { 63 }
MOV ESI,EBX
NOT ESI
ADD ECX,[EDI + 8]
OR ESI,EDX
XOR ESI,EAX
LEA ECX,[ECX]
LEA ECX,[ECX + ESI + $2AD7D2BB]
ROL ECX,15
ADD ECX,EDX
// B:= II(B, C, D, A, Block[ 9] + $EB86D391, 21); { 64 }
MOV ESI,EAX
NOT ESI
ADD EBX,[EDI + 36]
OR ESI,ECX
XOR ESI,EDX
LEA EBX,[EBX + ESI + $EB86D391]
ROL EBX,21
ADD EBX,ECX
ADD [EDI - 16],EAX // Inc(FData.Digest[0], A);
ADD [EDI - 12],EBX // Inc(FData.Digest[1], B);
ADD [EDI - 8],ECX // Inc(FData.Digest[2], C);
ADD [EDI - 4],EDX // Inc(FData.Digest[3], D);
// FillChar(Block, SizeOf(Block), 0);
XOR EAX,EAX
MOV [EDI],EAX
MOV [EDI + 4],EAX
MOV [EDI + 8],EAX
MOV [EDI + 12],EAX
MOV [EDI + 16],EAX
MOV [EDI + 20],EAX
MOV [EDI + 24],EAX
MOV [EDI + 28],EAX
MOV [EDI + 32],EAX
MOV [EDI + 36],EAX
MOV [EDI + 40],EAX
MOV [EDI + 44],EAX
MOV [EDI + 48],EAX
MOV [EDI + 52],EAX
MOV [EDI + 56],EAX
MOV [EDI + 60],EAX
POP EBX
POP EDI
POP ESI
end;
{$ELSE}
{$IFDEF CPUX64_WIN64}
procedure TMD5Alg.Compress;{$IFDEF FPC}assembler; nostackframe;{$ENDIF}
asm
{$IFNDEF FPC}
.NOFRAME
{$ENDIF}
PUSH RSI
PUSH RDI
PUSH RBX
LEA RDI,[RCX].TMD5Alg.FData.Block
MOV RAX,[RDI - 16] // A:= FData.Digest[0];
MOV RBX,[RDI - 12] // B:= FData.Digest[1];
MOV RCX,[RDI - 8] // C:= FData.Digest[2];
MOV RDX,[RDI - 4] // D:= FData.Digest[3];
// function FF(A, B, C, D, X, S: UInt32): UInt32; inline;
// begin
// Result:= A + ((B and (C xor D)) xor D) + X;
// Result:= Rol32(Result, S) + B;
// end;
// A:= FF(A, B, C, D, Block[ 0] + $D76AA478, 7); { 1 }
MOV ESI,ECX
ADD EAX,[RDI]
XOR ESI,EDX
AND ESI,EBX
XOR ESI,EDX
LEA EAX,[RAX + RSI + $D76AA478]
ROL EAX,7
ADD EAX,EBX
// D:= FF(D, A, B, C, Block[ 1] + $E8C7B756, 12); { 2 }
MOV ESI,EBX
ADD EDX,[RDI + 4]
XOR ESI,ECX
AND ESI,EAX
XOR ESI,ECX
LEA EDX,[RDX + RSI + $E8C7B756]
ROL EDX,12
ADD EDX,EAX
// C:= FF(C, D, A, B, Block[ 2] + $242070DB, 17); { 3 }
MOV ESI,EAX
ADD ECX,[RDI + 8]
XOR ESI,EBX
AND ESI,EDX
XOR ESI,EBX
LEA ECX,[RCX + RSI + $242070DB]
ROL ECX,17
ADD ECX,EDX
// B:= FF(B, C, D, A, Block[ 3] + $C1BDCEEE, 22); { 4 }
MOV ESI,EDX
ADD EBX,[RDI + 12]
XOR ESI,EAX
AND ESI,ECX
XOR ESI,EAX
LEA EBX,[RBX + RSI + $C1BDCEEE]
ROL EBX,22
ADD EBX,ECX
// A:= FF(A, B, C, D, Block[ 4] + $F57C0FAF, 7); { 5 }
MOV ESI,ECX
ADD EAX,[RDI + 16]
XOR ESI,EDX
AND ESI,EBX
XOR ESI,EDX
LEA EAX,[RAX + RSI + $F57C0FAF]
ROL EAX,7
ADD EAX,EBX
// D:= FF(D, A, B, C, Block[ 5] + $4787C62A, 12); { 6 }
MOV ESI,EBX
ADD EDX,[RDI + 20]
XOR ESI,ECX
AND ESI,EAX
XOR ESI,ECX
LEA EDX,[RDX + RSI + $4787C62A]
ROL EDX,12
ADD EDX,EAX
// C:= FF(C, D, A, B, Block[ 6] + $A8304613, 17); { 7 }
MOV ESI,EAX
ADD ECX,[RDI + 24]
XOR ESI,EBX
AND ESI,EDX
XOR ESI,EBX
LEA ECX,[RCX + RSI + $A8304613]
ROL ECX,17
ADD ECX,EDX
// B:= FF(B, C, D, A, Block[ 7] + $FD469501, 22); { 8 }
MOV ESI,EDX
ADD EBX,[RDI + 28]
XOR ESI,EAX
AND ESI,ECX
XOR ESI,EAX
LEA EBX,[RBX + RSI + $FD469501]
ROL EBX,22
ADD EBX,ECX
// A:= FF(A, B, C, D, Block[ 8] + $698098D8, 7); { 9 }
MOV ESI,ECX
ADD EAX,[RDI + 32]
XOR ESI,EDX
AND ESI,EBX
XOR ESI,EDX
LEA EAX,[RAX + RSI + $698098D8]
ROL EAX,7
ADD EAX,EBX
// D:= FF(D, A, B, C, Block[ 9] + $8B44F7AF, 12); { 10 }
MOV ESI,EBX
ADD EDX,[RDI + 36]
XOR ESI,ECX
AND ESI,EAX
XOR ESI,ECX
LEA EDX,[RDX + RSI + $8B44F7AF]
ROL EDX,12
ADD EDX,EAX
// C:= FF(C, D, A, B, Block[10] + $FFFF5BB1, 17); { 11 }
MOV ESI,EAX
ADD ECX,[RDI + 40]
XOR ESI,EBX
AND ESI,EDX
XOR ESI,EBX
LEA ECX,[RCX + RSI + $FFFF5BB1]
ROL ECX,17
ADD ECX,EDX
// B:= FF(B, C, D, A, Block[11] + $895CD7BE, 22); { 12 }
MOV ESI,EDX
ADD EBX,[RDI + 44]
XOR ESI,EAX
AND ESI,ECX
XOR ESI,EAX
LEA EBX,[RBX + RSI + $895CD7BE]
ROL EBX,22
ADD EBX,ECX
// A:= FF(A, B, C, D, Block[12] + $6B901122, 7); { 13 }
MOV ESI,ECX
ADD EAX,[RDI + 48]
XOR ESI,EDX
AND ESI,EBX
XOR ESI,EDX
LEA EAX,[RAX + RSI + $6B901122]
ROL EAX,7
ADD EAX,EBX
// D:= FF(D, A, B, C, Block[13] + $FD987193, 12); { 14 }
MOV ESI,EBX
ADD EDX,[RDI + 52]
XOR ESI,ECX
AND ESI,EAX
XOR ESI,ECX
LEA EDX,[RDX + RSI + $FD987193]
ROL EDX,12
ADD EDX,EAX
// C:= FF(C, D, A, B, Block[14] + $A679438E, 17); { 15 }
MOV ESI,EAX
ADD ECX,[RDI + 56]
XOR ESI,EBX
AND ESI,EDX
XOR ESI,EBX
LEA ECX,[RCX + RSI + $A679438E]
ROL ECX,17
ADD ECX,EDX
// B:= FF(B, C, D, A, Block[15] + $49B40821, 22); { 16 }
MOV ESI,EDX
ADD EBX,[RDI + 60]
XOR ESI,EAX
AND ESI,ECX
XOR ESI,EAX
LEA EBX,[RBX + RSI + $49B40821]
ROL EBX,22
ADD EBX,ECX
//function GG(A, B, C, D, X, S: UInt32): UInt32; inline;
//begin
// Result:= A + ((D and (B xor C)) xor C) + X;
// Result:= Rol32(Result, S) + B;
//end;
// A:= GG(A, B, C, D, Block[ 1] + $F61E2562, 5); { 17 }
MOV ESI,EBX
ADD EAX,[RDI + 4]
XOR ESI,ECX
AND ESI,EDX
XOR ESI,ECX
LEA EAX,[RAX + RSI + $F61E2562]
ROL EAX,5
ADD EAX,EBX
// D:= GG(D, A, B, C, Block[ 6] + $C040B340, 9); { 18 }
MOV ESI,EAX
ADD EDX,[RDI + 24]
XOR ESI,EBX
AND ESI,ECX
XOR ESI,EBX
LEA EDX,[RDX + RSI + $C040B340]
ROL EDX,9
ADD EDX,EAX
// C:= GG(C, D, A, B, Block[11] + $265E5A51, 14); { 19 }
MOV ESI,EDX
ADD ECX,[RDI + 44]
XOR ESI,EAX
AND ESI,EBX
XOR ESI,EAX
LEA ECX,[RCX + RSI + $265E5A51]
ROL ECX,14
ADD ECX,EDX
// B:= GG(B, C, D, A, Block[ 0] + $E9B6C7AA, 20); { 20 }
MOV ESI,ECX
ADD EBX,[RDI]
XOR ESI,EDX
AND ESI,EAX
XOR ESI,EDX
LEA EBX,[RBX + RSI + $E9B6C7AA]
ROL EBX,20
ADD EBX,ECX
// A:= GG(A, B, C, D, Block[ 5] + $D62F105D, 5); { 21 }
MOV ESI,EBX
ADD EAX,[RDI + 20]
XOR ESI,ECX
AND ESI,EDX
XOR ESI,ECX
LEA EAX,[RAX + RSI + $D62F105D]
ROL EAX,5
ADD EAX,EBX
// D:= GG(D, A, B, C, Block[10] + $02441453, 9); { 22 }
MOV ESI,EAX
ADD EDX,[RDI + 40]
XOR ESI,EBX
AND ESI,ECX
XOR ESI,EBX
LEA EDX,[RDX + RSI + $02441453]
ROL EDX,9
ADD EDX,EAX
// C:= GG(C, D, A, B, Block[15] + $D8A1E681, 14); { 23 }
MOV ESI,EDX
ADD ECX,[RDI + 60]
XOR ESI,EAX
AND ESI,EBX
XOR ESI,EAX
LEA ECX,[RCX + RSI + $D8A1E681]
ROL ECX,14
ADD ECX,EDX
// B:= GG(B, C, D, A, Block[ 4] + $E7D3FBC8, 20); { 24 }
MOV ESI,ECX
ADD EBX,[RDI + 16]
XOR ESI,EDX
AND ESI,EAX
XOR ESI,EDX
LEA EBX,[RBX + RSI + $E7D3FBC8]
ROL EBX,20
ADD EBX,ECX
// A:= GG(A, B, C, D, Block[ 9] + $21E1CDE6, 5); { 25 }
MOV ESI,EBX
ADD EAX,[RDI + 36]
XOR ESI,ECX
AND ESI,EDX
XOR ESI,ECX
LEA EAX,[RAX + RSI + $21E1CDE6]
ROL EAX,5
ADD EAX,EBX
// D:= GG(D, A, B, C, Block[14] + $C33707D6, 9); { 26 }
MOV ESI,EAX
ADD EDX,[RDI + 56]
XOR ESI,EBX
AND ESI,ECX
XOR ESI,EBX
LEA EDX,[RDX + RSI + $C33707D6]
ROL EDX,9
ADD EDX,EAX
// C:= GG(C, D, A, B, Block[ 3] + $F4D50D87, 14); { 27 }
MOV ESI,EDX
ADD ECX,[RDI + 12]
XOR ESI,EAX
AND ESI,EBX
XOR ESI,EAX
LEA ECX,[RCX + RSI + $F4D50D87]
ROL ECX,14
ADD ECX,EDX
// B:= GG(B, C, D, A, Block[ 8] + $455A14ED, 20); { 28 }
MOV ESI,ECX
ADD EBX,[RDI + 32]
XOR ESI,EDX
AND ESI,EAX
XOR ESI,EDX
LEA EBX,[RBX + RSI + $455A14ED]
ROL EBX,20
ADD EBX,ECX
// A:= GG(A, B, C, D, Block[13] + $A9E3E905, 5); { 29 }
MOV ESI,EBX
ADD EAX,[RDI + 52]
XOR ESI,ECX
AND ESI,EDX
XOR ESI,ECX
LEA EAX,[RAX + RSI + $A9E3E905]
ROL EAX,5
ADD EAX,EBX
// D:= GG(D, A, B, C, Block[ 2] + $FCEFA3F8, 9); { 30 }
MOV ESI,EAX
ADD EDX,[RDI + 8]
XOR ESI,EBX
AND ESI,ECX
XOR ESI,EBX
LEA EDX,[RDX + RSI + $FCEFA3F8]
ROL EDX,9
ADD EDX,EAX
// C:= GG(C, D, A, B, Block[ 7] + $676F02D9, 14); { 31 }
MOV ESI,EDX
ADD ECX,[RDI + 28]
XOR ESI,EAX
AND ESI,EBX
XOR ESI,EAX
LEA ECX,[RCX + RSI + $676F02D9]
ROL ECX,14
ADD ECX,EDX
// B:= GG(B, C, D, A, Block[12] + $8D2A4C8A, 20); { 32 }
MOV ESI,ECX
ADD EBX,[RDI + 48]
XOR ESI,EDX
AND ESI,EAX
XOR ESI,EDX
LEA EBX,[RBX + RSI + $8D2A4C8A]
ROL EBX,20
ADD EBX,ECX
//function HH(A, B, C, D, X, S: UInt32): UInt32; inline;
//begin
// Result:= A + (B xor C xor D) + X;
// Result:= Rol32(Result, S) + B;
//end;
// A:= HH(A, B, C, D, Block[ 5] + $FFFA3942, 4); { 33 }
MOV ESI,ECX
ADD EAX,[RDI + 20]
XOR ESI,EDX
XOR ESI,EBX
LEA EAX,[RAX + RSI + $FFFA3942]
ROL EAX,4
ADD EAX,EBX
// D:= HH(D, A, B, C, Block[ 8] + $8771F681, 11); { 34 }
MOV ESI,EBX
ADD EDX,[RDI + 32]
XOR ESI,ECX
XOR ESI,EAX
LEA EDX,[RDX + RSI + $8771F681]
ROL EDX,11
ADD EDX,EAX
// C:= HH(C, D, A, B, Block[11] + $6D9D6122, 16); { 35 }
MOV ESI,EAX
ADD ECX,[RDI + 44]
XOR ESI,EBX
XOR ESI,EDX
LEA ECX,[RCX + RSI + $6D9D6122]
ROL ECX,16
ADD ECX,EDX
// B:= HH(B, C, D, A, Block[14] + $FDE5380C, 23); { 36 }
MOV ESI,EDX
ADD EBX,[RDI + 56]
XOR ESI,EAX
XOR ESI,ECX
LEA EBX,[RBX + RSI + $FDE5380C]
ROL EBX,23
ADD EBX,ECX
// A:= HH(A, B, C, D, Block[ 1] + $A4BEEA44, 4); { 37 }
MOV ESI,ECX
ADD EAX,[RDI + 4]
XOR ESI,EDX
XOR ESI,EBX
LEA EAX,[RAX + RSI + $A4BEEA44]
ROL EAX,4
ADD EAX,EBX
// D:= HH(D, A, B, C, Block[ 4] + $4BDECFA9, 11); { 38 }
MOV ESI,EBX
ADD EDX,[RDI + 16]
XOR ESI,ECX
XOR ESI,EAX
LEA EDX,[RDX + RSI + $4BDECFA9]
ROL EDX,11
ADD EDX,EAX
// C:= HH(C, D, A, B, Block[ 7] + $F6BB4B60, 16); { 39 }
MOV ESI,EAX
ADD ECX,[RDI + 28]
XOR ESI,EBX
XOR ESI,EDX
LEA ECX,[RCX + RSI + $F6BB4B60]
ROL ECX,16
ADD ECX,EDX
// B:= HH(B, C, D, A, Block[10] + $BEBFBC70, 23); { 40 }
MOV ESI,EDX
ADD EBX,[RDI + 40]
XOR ESI,EAX
XOR ESI,ECX
LEA EBX,[RBX + RSI + $BEBFBC70]
ROL EBX,23
ADD EBX,ECX
// A:= HH(A, B, C, D, Block[13] + $289B7EC6, 4); { 41 }
MOV ESI,ECX
ADD EAX,[RDI + 52]
XOR ESI,EDX
XOR ESI,EBX
LEA EAX,[RAX + RSI + $289B7EC6]
ROL EAX,4
ADD EAX,EBX
// D:= HH(D, A, B, C, Block[ 0] + $EAA127FA, 11); { 42 }
MOV ESI,EBX
ADD EDX,[RDI]
XOR ESI,ECX
XOR ESI,EAX
LEA EDX,[RDX + RSI + $EAA127FA]
ROL EDX,11
ADD EDX,EAX
// C:= HH(C, D, A, B, Block[ 3] + $D4EF3085, 16); { 43 }
MOV ESI,EAX
ADD ECX,[RDI + 12]
XOR ESI,EBX
XOR ESI,EDX
LEA ECX,[RCX + RSI + $D4EF3085]
ROL ECX,16
ADD ECX,EDX
// B:= HH(B, C, D, A, Block[ 6] + $04881D05, 23); { 44 }
MOV ESI,EDX
ADD EBX,[RDI + 24]
XOR ESI,EAX
XOR ESI,ECX
LEA EBX,[RBX + RSI + $04881D05]
ROL EBX,23
ADD EBX,ECX
// A:= HH(A, B, C, D, Block[ 9] + $D9D4D039, 4); { 45 }
MOV ESI,ECX
ADD EAX,[RDI + 36]
XOR ESI,EDX
XOR ESI,EBX
LEA EAX,[RAX + RSI + $D9D4D039]
ROL EAX,4
ADD EAX,EBX
// D:= HH(D, A, B, C, Block[12] + $E6DB99E5, 11); { 46 }
MOV ESI,EBX
ADD EDX,[RDI + 48]
XOR ESI,ECX
XOR ESI,EAX
LEA EDX,[RDX + RSI + $E6DB99E5]
ROL EDX,11
ADD EDX,EAX
// C:= HH(C, D, A, B, Block[15] + $1FA27CF8, 16); { 47 }
MOV ESI,EAX
ADD ECX,[RDI + 60]
XOR ESI,EBX
XOR ESI,EDX
LEA ECX,[RCX + RSI + $1FA27CF8]
ROL ECX,16
ADD ECX,EDX
// B:= HH(B, C, D, A, Block[ 2] + $C4AC5665, 23); { 48 }
MOV ESI,EDX
ADD EBX,[RDI + 8]
XOR ESI,EAX
XOR ESI,ECX
LEA EBX,[RBX + RSI + $C4AC5665]
ROL EBX,23
ADD EBX,ECX
//function II(A, B, C, D, X, S: UInt32): UInt32; inline;
//begin
// Result:= A + (C xor (B or not D)) + X;
// Result:= Rol32(Result, S) + B;
//end;
// A:= II(A, B, C, D, Block[ 0] + $F4292244, 6); { 49 }
MOV ESI,EDX
NOT ESI
ADD EAX,[RDI]
OR ESI,EBX
XOR ESI,ECX
LEA EAX,[RAX + RSI + $F4292244]
ROL EAX,6
ADD EAX,EBX
// D:= II(D, A, B, C, Block[ 7] + $432AFF97, 10); { 50 }
MOV ESI,ECX
NOT ESI
ADD EDX,[RDI + 28]
OR ESI,EAX
XOR ESI,EBX
LEA EDX,[RDX + RSI + $432AFF97]
ROL EDX,10
ADD EDX,EAX
// C:= II(C, D, A, B, Block[14] + $AB9423A7, 15); { 51 }
MOV ESI,EBX
NOT ESI
ADD ECX,[RDI + 56]
OR ESI,EDX
XOR ESI,EAX
LEA ECX,[RCX + RSI + $AB9423A7]
ROL ECX,15
ADD ECX,EDX
// B:= II(B, C, D, A, Block[ 5] + $FC93A039, 21); { 52 }
MOV ESI,EAX
NOT ESI
ADD EBX,[RDI + 20]
OR ESI,ECX
XOR ESI,EDX
LEA EBX,[RBX + RSI + $FC93A039]
ROL EBX,21
ADD EBX,ECX
// A:= II(A, B, C, D, Block[12] + $655B59C3, 6); { 53 }
MOV ESI,EDX
NOT ESI
ADD EAX,[RDI + 48]
OR ESI,EBX
XOR ESI,ECX
LEA EAX,[RAX + RSI + $655B59C3]
ROL EAX,6
ADD EAX,EBX
// D:= II(D, A, B, C, Block[ 3] + $8F0CCC92, 10); { 54 }
MOV ESI,ECX
NOT ESI
ADD EDX,[RDI + 12]
OR ESI,EAX
XOR ESI,EBX
LEA EDX,[RDX + RSI + $8F0CCC92]
ROL EDX,10
ADD EDX,EAX
// C:= II(C, D, A, B, Block[10] + $FFEFF47D, 15); { 55 }
MOV ESI,EBX
NOT ESI
ADD ECX,[RDI + 40]
OR ESI,EDX
XOR ESI,EAX
LEA ECX,[RCX + RSI + $FFEFF47D]
ROL ECX,15
ADD ECX,EDX
// B:= II(B, C, D, A, Block[ 1] + $85845DD1, 21); { 56 }
MOV ESI,EAX
NOT ESI
ADD EBX,[RDI + 4]
OR ESI,ECX
XOR ESI,EDX
LEA EBX,[RBX + RSI + $85845DD1]
ROL EBX,21
ADD EBX,ECX
// A:= II(A, B, C, D, Block[ 8] + $6FA87E4F, 6); { 57 }
MOV ESI,EDX
NOT ESI
ADD EAX,[RDI + 32]
OR ESI,EBX
XOR ESI,ECX
LEA EAX,[RAX + RSI + $6FA87E4F]
ROL EAX,6
ADD EAX,EBX
// D:= II(D, A, B, C, Block[15] + $FE2CE6E0, 10); { 58 }
MOV ESI,ECX
NOT ESI
ADD EDX,[RDI + 60]
OR ESI,EAX
XOR ESI,EBX
LEA EDX,[RDX + RSI + $FE2CE6E0]
ROL EDX,10
ADD EDX,EAX
// C:= II(C, D, A, B, Block[ 6] + $A3014314, 15); { 59 }
MOV ESI,EBX
NOT ESI
ADD ECX,[RDI + 24]
OR ESI,EDX
XOR ESI,EAX
LEA ECX,[RCX + RSI + $A3014314]
ROL ECX,15
ADD ECX,EDX
// B:= II(B, C, D, A, Block[13] + $4E0811A1, 21); { 60 }
MOV ESI,EAX
NOT ESI
ADD EBX,[RDI + 52]
OR ESI,ECX
XOR ESI,EDX
LEA EBX,[RBX + RSI + $4E0811A1]
ROL EBX,21
ADD EBX,ECX
// A:= II(A, B, C, D, Block[ 4] + $F7537E82, 6); { 61 }
MOV ESI,EDX
NOT ESI
ADD EAX,[RDI + 16]
OR ESI,EBX
XOR ESI,ECX
LEA EAX,[RAX + RSI + $F7537E82]
ROL EAX,6
ADD EAX,EBX
// D:= II(D, A, B, C, Block[11] + $BD3AF235, 10); { 62 }
MOV ESI,ECX
NOT ESI
ADD EDX,[RDI + 44]
OR ESI,EAX
XOR ESI,EBX
LEA EDX,[RDX + RSI + $BD3AF235]
ROL EDX,10
ADD EDX,EAX
// C:= II(C, D, A, B, Block[ 2] + $2AD7D2BB, 15); { 63 }
MOV ESI,EBX
NOT ESI
ADD ECX,[RDI + 8]
OR ESI,EDX
XOR ESI,EAX
LEA ECX,[RCX + RSI + $2AD7D2BB]
ROL ECX,15
ADD ECX,EDX
// B:= II(B, C, D, A, Block[ 9] + $EB86D391, 21); { 64 }
MOV ESI,EAX
NOT ESI
ADD EBX,[RDI + 36]
OR ESI,ECX
XOR ESI,EDX
LEA EBX,[RBX + RSI + $EB86D391]
ROL EBX,21
ADD EBX,ECX
ADD [RDI - 16],EAX // Inc(FData.Digest[0], A);
ADD [RDI - 12],EBX // Inc(FData.Digest[1], B);
ADD [RDI - 8],ECX // Inc(FData.Digest[2], C);
ADD [RDI - 4],EDX // Inc(FData.Digest[3], D);
// FillChar(Block, SizeOf(Block), 0);
XOR RAX,RAX
MOV [RDI],RAX
MOV [RDI + 8],RAX
MOV [RDI + 16],RAX
MOV [RDI + 24],RAX
MOV [RDI + 32],RAX
MOV [RDI + 40],RAX
MOV [RDI + 48],RAX
MOV [RDI + 56],RAX
POP RBX
POP RDI
POP RSI
end;
{$ELSE}
function Rol32(Value, Shift: UInt32): UInt32; inline;
begin
Result:= (Value shr (32 - Shift)) or (Value shl Shift);
end;
function FF(A, B, C, D, X, S: UInt32): UInt32; inline;
begin
// Result:= Rol32(A + ((B and C) or (not B and D)) + X, S) + B;
// Result:= Rol32(A + ((B and (C xor D)) xor D) + X, S) + B;
Result:= A + ((B and (C xor D)) xor D) + X;
Result:= Rol32(Result, S) + B;
end;
function GG(A, B, C, D, X, S: UInt32): UInt32; inline;
begin
// Result:= Rol32(A + ((B and D) or (C and not D)) + X, S) + B;
// Result:= Rol32(A + ((D and (B xor C)) xor C) + X, S) + B;
Result:= A + ((D and (B xor C)) xor C) + X;
Result:= Rol32(Result, S) + B;
end;
function HH(A, B, C, D, X, S: UInt32): UInt32; inline;
begin
// Result:= Rol32(A + (B xor C xor D) + X, S) + B;
Result:= A + (B xor C xor D) + X;
Result:= Rol32(Result, S) + B;
end;
function II(A, B, C, D, X, S: UInt32): UInt32; inline;
begin
// Result:= Rol32(A + (C xor (B or not D)) + X, S) + B;
Result:= A + (C xor (B or not D)) + X;
Result:= Rol32(Result, S) + B;
end;
procedure TMD5Alg.Compress;
var
A, B, C, D: UInt32;
Block: array[0..15] of UInt32;
begin
Move(FData.Block, Block, SizeOf(Block));
A:= FData.Digest[0];
B:= FData.Digest[1];
C:= FData.Digest[2];
D:= FData.Digest[3];
{round 1}
A:= FF(A, B, C, D, Block[ 0] + $D76AA478, 7); { 1 }
D:= FF(D, A, B, C, Block[ 1] + $E8C7B756, 12); { 2 }
C:= FF(C, D, A, B, Block[ 2] + $242070DB, 17); { 3 }
B:= FF(B, C, D, A, Block[ 3] + $C1BDCEEE, 22); { 4 }
A:= FF(A, B, C, D, Block[ 4] + $F57C0FAF, 7); { 5 }
D:= FF(D, A, B, C, Block[ 5] + $4787C62A, 12); { 6 }
C:= FF(C, D, A, B, Block[ 6] + $A8304613, 17); { 7 }
B:= FF(B, C, D, A, Block[ 7] + $FD469501, 22); { 8 }
A:= FF(A, B, C, D, Block[ 8] + $698098D8, 7); { 9 }
D:= FF(D, A, B, C, Block[ 9] + $8B44F7AF, 12); { 10 }
C:= FF(C, D, A, B, Block[10] + $FFFF5BB1, 17); { 11 }
B:= FF(B, C, D, A, Block[11] + $895CD7BE, 22); { 12 }
A:= FF(A, B, C, D, Block[12] + $6B901122, 7); { 13 }
D:= FF(D, A, B, C, Block[13] + $FD987193, 12); { 14 }
C:= FF(C, D, A, B, Block[14] + $A679438E, 17); { 15 }
B:= FF(B, C, D, A, Block[15] + $49B40821, 22); { 16 }
{round 2}
A:= GG(A, B, C, D, Block[ 1] + $F61E2562, 5); { 17 }
D:= GG(D, A, B, C, Block[ 6] + $C040B340, 9); { 18 }
C:= GG(C, D, A, B, Block[11] + $265E5A51, 14); { 19 }
B:= GG(B, C, D, A, Block[ 0] + $E9B6C7AA, 20); { 20 }
A:= GG(A, B, C, D, Block[ 5] + $D62F105D, 5); { 21 }
D:= GG(D, A, B, C, Block[10] + $02441453, 9); { 22 }
C:= GG(C, D, A, B, Block[15] + $D8A1E681, 14); { 23 }
B:= GG(B, C, D, A, Block[ 4] + $E7D3FBC8, 20); { 24 }
A:= GG(A, B, C, D, Block[ 9] + $21E1CDE6, 5); { 25 }
D:= GG(D, A, B, C, Block[14] + $C33707D6, 9); { 26 }
C:= GG(C, D, A, B, Block[ 3] + $F4D50D87, 14); { 27 }
B:= GG(B, C, D, A, Block[ 8] + $455A14ED, 20); { 28 }
A:= GG(A, B, C, D, Block[13] + $A9E3E905, 5); { 29 }
D:= GG(D, A, B, C, Block[ 2] + $FCEFA3F8, 9); { 30 }
C:= GG(C, D, A, B, Block[ 7] + $676F02D9, 14); { 31 }
B:= GG(B, C, D, A, Block[12] + $8D2A4C8A, 20); { 32 }
{round 3}
A:= HH(A, B, C, D, Block[ 5] + $FFFA3942, 4); { 33 }
D:= HH(D, A, B, C, Block[ 8] + $8771F681, 11); { 34 }
C:= HH(C, D, A, B, Block[11] + $6D9D6122, 16); { 35 }
B:= HH(B, C, D, A, Block[14] + $FDE5380C, 23); { 36 }
A:= HH(A, B, C, D, Block[ 1] + $A4BEEA44, 4); { 37 }
D:= HH(D, A, B, C, Block[ 4] + $4BDECFA9, 11); { 38 }
C:= HH(C, D, A, B, Block[ 7] + $F6BB4B60, 16); { 39 }
B:= HH(B, C, D, A, Block[10] + $BEBFBC70, 23); { 40 }
A:= HH(A, B, C, D, Block[13] + $289B7EC6, 4); { 41 }
D:= HH(D, A, B, C, Block[ 0] + $EAA127FA, 11); { 42 }
C:= HH(C, D, A, B, Block[ 3] + $D4EF3085, 16); { 43 }
B:= HH(B, C, D, A, Block[ 6] + $04881D05, 23); { 44 }
A:= HH(A, B, C, D, Block[ 9] + $D9D4D039, 4); { 45 }
D:= HH(D, A, B, C, Block[12] + $E6DB99E5, 11); { 46 }
C:= HH(C, D, A, B, Block[15] + $1FA27CF8, 16); { 47 }
B:= HH(B, C, D, A, Block[ 2] + $C4AC5665, 23); { 48 }
{round 4}
A:= II(A, B, C, D, Block[ 0] + $F4292244, 6); { 49 }
D:= II(D, A, B, C, Block[ 7] + $432AFF97, 10); { 50 }
C:= II(C, D, A, B, Block[14] + $AB9423A7, 15); { 51 }
B:= II(B, C, D, A, Block[ 5] + $FC93A039, 21); { 52 }
A:= II(A, B, C, D, Block[12] + $655B59C3, 6); { 53 }
D:= II(D, A, B, C, Block[ 3] + $8F0CCC92, 10); { 54 }
C:= II(C, D, A, B, Block[10] + $FFEFF47D, 15); { 55 }
B:= II(B, C, D, A, Block[ 1] + $85845DD1, 21); { 56 }
A:= II(A, B, C, D, Block[ 8] + $6FA87E4F, 6); { 57 }
D:= II(D, A, B, C, Block[15] + $FE2CE6E0, 10); { 58 }
C:= II(C, D, A, B, Block[ 6] + $A3014314, 15); { 59 }
B:= II(B, C, D, A, Block[13] + $4E0811A1, 21); { 60 }
A:= II(A, B, C, D, Block[ 4] + $F7537E82, 6); { 61 }
D:= II(D, A, B, C, Block[11] + $BD3AF235, 10); { 62 }
C:= II(C, D, A, B, Block[ 2] + $2AD7D2BB, 15); { 63 }
B:= II(B, C, D, A, Block[ 9] + $EB86D391, 21); { 64 }
Inc(FData.Digest[0], A);
Inc(FData.Digest[1], B);
Inc(FData.Digest[2], C);
Inc(FData.Digest[3], D);
FillChar(FData.Block, SizeOf(FData.Block), 0);
FillChar(Block, SizeOf(Block), 0);
end;
{$ENDIF}
{$ENDIF}
class procedure TMD5Alg.Init(Inst: PMD5Alg);
begin
Inst.FData.Digest[0]:= $67452301; // load magic initialization constants
Inst.FData.Digest[1]:= $EFCDAB89;
Inst.FData.Digest[2]:= $98BADCFE;
Inst.FData.Digest[3]:= $10325476;
FillChar(Inst.FData.Block, SizeOf(Inst.FData.Block), 0);
Inst.FData.Count:= 0;
end;
class procedure TMD5Alg.Update(Inst: PMD5Alg; Data: PByte; DataSize: Cardinal);
var
Cnt, Ofs: Cardinal;
begin
while DataSize > 0 do begin
Ofs:= Cardinal(Inst.FData.Count) and $3F;
Cnt:= $40 - Ofs;
if Cnt > DataSize then Cnt:= DataSize;
Move(Data^, PByte(@Inst.FData.Block)[Ofs], Cnt);
if (Cnt + Ofs = $40) then Inst.Compress;
Inc(Inst.FData.Count, Cnt);
Dec(DataSize, Cnt);
Inc(Data, Cnt);
end;
end;
class procedure TMD5Alg.Done(Inst: PMD5Alg; PDigest: PMD5Digest);
var
Ofs: Cardinal;
begin
Ofs:= Cardinal(Inst.FData.Count) and $3F;
Inst.FData.Block[Ofs]:= $80;
if Ofs >= 56 then
Inst.Compress;
Inst.FData.Count:= Inst.FData.Count shl 3;
PUInt32(@Inst.FData.Block[56])^:= UInt32(Inst.FData.Count);
PUInt32(@Inst.FData.Block[60])^:= UInt32(Inst.FData.Count shr 32);
Inst.Compress;
Move(Inst.FData.Digest, PDigest^, SizeOf(TMD5Digest));
Init(Inst);
end;
class function TMD5Alg.GetDigestSize(Inst: PMD5Alg): Integer;
begin
Result:= SizeOf(TMD5Digest);
end;
class function TMD5Alg.GetBlockSize(Inst: PMD5Alg): Integer;
begin
Result:= 64;
end;
class function TMD5Alg.Duplicate(Inst: PMD5Alg; var DupInst: PMD5Alg): TF_RESULT;
begin
Result:= GetMD5Algorithm(DupInst);
if Result = TF_S_OK then
DupInst.FData:= Inst.FData;
end;
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals 5.00 }
{ File name: flcTCPTests.pas }
{ File version: 5.11 }
{ Description: TCP tests. }
{ }
{ Copyright: Copyright (c) 2007-2020, David J Butler }
{ All rights reserved. }
{ This file is licensed under the BSD License. }
{ See http://www.opensource.org/licenses/bsd-license.php }
{ Redistribution and use in source and binary forms, with }
{ or without modification, are permitted provided that }
{ the following conditions are met: }
{ Redistributions of source code must retain the above }
{ copyright notice, this list of conditions and the }
{ following disclaimer. }
{ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND }
{ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED }
{ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED }
{ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A }
{ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL }
{ THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, }
{ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR }
{ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, }
{ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF }
{ USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) }
{ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER }
{ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING }
{ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE }
{ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE }
{ POSSIBILITY OF SUCH DAMAGE. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ }
{ Revision history: }
{ }
{ 2010/12/15 0.01 Test for TLS client/server. }
{ 2011/01/02 0.02 Test for large buffers. }
{ 2011/04/22 0.03 Simple buffer tests. }
{ 2011/04/22 4.04 Test for multiple connections. }
{ 2011/10/13 4.05 SSL3 tests. }
{ 2012/04/19 4.06 Test for stopping and restarting client. }
{ 2015/04/26 4.07 Test for worker thread and blocking interface. }
{ 2016/01/08 5.08 Update for Fundamentals 5. }
{ 2018/09/08 5.09 Server tests with high connection count. }
{ 2019/04/16 5.10 Shutdown test. }
{ 2020/05/11 5.11 Move tests out into seperate units. }
{ }
{ Todo: }
{ - Test case socks proxy }
{ - Test case buffer full/empty events }
{ - Test case deferred shutdown }
{ - Test case throttling }
{ - Test case read/write rate reporting }
{ - Test case multiple proxies }
{ - Test case writing large chunks }
{ - Test case performance }
{ - Test case stress test (throughput and number of connections) }
{ - See SSL3 test case }
{******************************************************************************}
{$INCLUDE flcTCPTest.inc}
unit flcTCPTests;
interface
{ }
{ Test }
{ }
{$IFDEF TCP_TEST}
procedure Test;
{$ENDIF}
implementation
uses
flcTCPTest_Buffer
{$IFDEF TCPCLIENT_TEST},
flcTCPTest_Client
{$ENDIF}
{$IFDEF TCPCLIENT_TEST_TLS},
flcTCPTest_ClientTLS
{$ENDIF}
{$IFDEF TCPSERVER_TEST},
flcTCPTest_Server
{$ENDIF}
{$IFDEF TCPSERVER_TEST_TLS},
flcTCPTest_ServerTLS
{$ENDIF}
{$IFDEF TCPCLIENTSERVER_TEST},
flcTCPTest_ClientServer
{$ENDIF}
{$IFDEF TCPCLIENTSERVER_TEST_TLS},
flcTCPTest_ClientServerTLS
{$ENDIF}
;
{$IFDEF TCP_TEST}
{$ASSERTIONS ON}
procedure Test_Buffer;
begin
flcTCPTest_Buffer.Test;
end;
{$IFDEF TCPCLIENT_TEST}
procedure Test_Client;
begin
flcTCPTest_Client.Test;
{$IFDEF TCPCLIENT_TEST_TLS}
flcTCPTest_ClientTLS.Test;
{$ENDIF}
end;
{$ENDIF}
{$IFDEF TCPSERVER_TEST}
procedure Test_Server;
begin
flcTCPTest_Server.Test;
{$IFDEF TCPSERVER_TEST_TLS}
flcTCPTest_ServerTLS.Test;
{$ENDIF}
end;
{$ENDIF}
{$IFDEF TCPCLIENTSERVER_TEST}
procedure Test_ClientServer;
begin
flcTCPTest_ClientServer.Test;
{$IFDEF TCPCLIENTSERVER_TEST_TLS}
flcTCPTest_ClientServerTLS.Test;
{$ENDIF}
end;
{$ENDIF}
procedure Test;
begin
Test_Buffer;
{$IFDEF TCPSERVER_TEST}
Test_Server;
{$ENDIF}
{$IFDEF TCPCLIENT_TEST}
Test_Client;
{$ENDIF}
{$IFDEF TCPCLIENTSERVER_TEST}
Test_ClientServer;
{$ENDIF}
end;
{$ENDIF}
end.
|
unit akEMail;
interface
uses Windows;
resourcestring
exMailClientErr = 'Unable to open mail client (%d).'#$0A'Message to "%s" was not created.';
// Показывает диаложик отправки сообщения
function DlgSendEmail(const RecipName, RecipAddress, Subject, Text: string; ShortText: string = ''; showErr: Boolean = false): Boolean;
function SendEmail(const RecipName, RecipAddress, Subject, Text, Attachment: string): Boolean;
implementation
uses Mapi, Forms, SysUtils, akDataUtils, akSysCover;
function SendEmail(const RecipName, RecipAddress, Subject, Text, Attachment: string): Boolean;
var
MapiMessage: TMapiMessage;
MapiFileDesc: TMapiFileDesc;
MapiRecipDesc: TMapiRecipDesc;
begin
with MapiRecipDesc do
begin
ulReserved := 0;
ulRecipClass := MAPI_TO;
lpszName := PChar(RecipName);
lpszAddress := PChar(RecipAddress);
ulEIDSize := 0;
lpEntryID := nil;
end;
with MapiFileDesc do
begin
ulReserved:= 0;
flFlags:= 0;
nPosition:= 0;
lpszPathName:= PChar(Attachment);
lpszFileName:= nil;
lpFileType:= nil;
end;
with MapiMessage do
begin
ulReserved := 0;
lpszSubject := PChar(Subject);
lpszNoteText := PChar(Text);
lpszMessageType := nil;
lpszDateReceived := nil;
lpszConversationID := nil;
flFlags := 0;
lpOriginator := nil;
nRecipCount := 1;
lpRecips := @MapiRecipDesc;
if length(Attachment) > 0 then
begin
nFileCount:= 1;
lpFiles := @MapiFileDesc;
end
else
begin
nFileCount:= 0;
lpFiles:= nil;
end;
end;
Result:= MapiSendMail(0, 0, MapiMessage, MAPI_LOGON_UI or
MAPI_NEW_SESSION, 0) = SUCCESS_SUCCESS;
end;
function DlgSendEmail(const RecipName, RecipAddress, Subject, Text: string; ShortText: string; showErr: Boolean): Boolean;
var
MapiMessage: TMapiMessage;
MapiRecipDesc: TMapiRecipDesc;
i: integer;
per: DWORD;
msg, txt: string;
begin
txt := iifs(ShortText = '', Text, ShortText);
ZeroMemory(@MapiRecipDesc, SizeOf(MapiRecipDesc));
ZeroMemory(@MapiMessage, SizeOf(MapiMessage));
with MapiRecipDesc do
begin
ulRecipClass := MAPI_TO;
lpszName := PChar(RecipName);
lpszAddress := PChar(RecipAddress);
end;
with MapiMessage do
begin
lpszSubject := PChar(Subject);
lpszNoteText := PChar(Text);
nRecipCount := 1;
lpRecips := @MapiRecipDesc;
end;
per := GetTickCount;
i := MapiSendMail(0, Application.Handle, MapiMessage, MAPI_DIALOG or MAPI_LOGON_UI or
MAPI_NEW_SESSION, 0); result := i = SUCCESS_SUCCESS;
if (i = MAPI_USER_ABORT) and (GetTickCount - per <= 1000) then
begin
msg := format('mailto:%s?subject=%s&body=%s', [RecipAddress, Subject, txt]);
msg := StringReplace(msg, ' ', '%20', [rfReplaceAll]);
msg := StringReplace(msg, #$0A, '%0A', [rfReplaceAll]);
msg := StringReplace(msg, #$0D, '%0D', [rfReplaceAll]);
TryOpenUrl(msg);
end
else
if (showErr) and (not Result) then
MessageBox(0, PChar(Format(exMailClientErr, [i, RecipName])), 'Error', MB_OK or MB_ICONERROR);
end;
end.
|
unit ExtAIBaseDelphi;
interface
uses
Windows, Classes, Generics.Collections,
System.SysUtils,
ExtAILog, ExtAINetClient, ExtAIActions, ExtAIEvents, ExtAIStates;
type
// The main thread of ExtAI, communication interface and parent of every ExtAI
TExtAIBaseDelphi = class(TThread)
private
// Thread variables
fID: Word;
fActive: Boolean;
fClient: TExtAINetClient;
fLog: TExtAILog;
procedure ClientStatusMessage(const aMsg: String);
protected
fActions: TExtAIActions;
fEvents: TExtAIEvents;
fStates: TExtAIStates;
// Thread loop
procedure Execute(); override;
// Game Events
procedure OnMissionStart(); virtual;
procedure OnMissionEnd(); virtual;
procedure OnTick(aTick: Cardinal); virtual;
procedure OnPlayerVictory(aHandIndex: SmallInt); virtual;
procedure OnPlayerDefeated(aHandIndex: SmallInt); virtual;
// Log
procedure Log(const aText: String; const aArgs: array of const); overload;
procedure Log(const aText: String); overload;
public
constructor Create(aLog: TExtAILog; const aID: Word; const aAuthor, aName, aDescription: UnicodeString; const aVersion: Cardinal);
destructor Destroy(); override;
property ID: Word read fID;
property Actions: TExtAIActions read fActions;
property States: TExtAIStates read fStates;
property Client: TExtAINetClient read fClient;
procedure TerminateSimulation();
end;
implementation
{ TExtAIBaseDelphi }
constructor TExtAIBaseDelphi.Create(aLog: TExtAILog; const aID: Word; const aAuthor, aName, aDescription: UnicodeString; const aVersion: Cardinal);
begin
Inherited Create(False); // Create thread and start Execution
FreeOnTerminate := False;
Priority := tpLower;
fActive := True;
fID := aID;
fClient := TExtAINetClient.Create(aID, aAuthor, aName, aDescription, aVersion);
fLog := aLog;
fActions := TExtAIActions.Create(fClient);
fEvents := TExtAIEvents.Create();
fStates := TExtAIStates.Create(fClient);
fClient.OnNewEvent := fEvents.Msg.ReceiveEvent;
fClient.OnNewState := fStates.Msg.ReceiveState;
fClient.OnStatusMessage := ClientStatusMessage;
fEvents.Msg.OnMissionStart := OnMissionStart;
fEvents.Msg.OnMissionEnd := OnMissionEnd;
fEvents.Msg.OnTick := OnTick;
fEvents.Msg.OnPlayerVictory := OnPlayerVictory;
fEvents.Msg.OnPlayerDefeated := OnPlayerDefeated;
Log('TExtAIBaseDelphi-Create ID = %d', [fID]);
end;
destructor TExtAIBaseDelphi.Destroy();
begin
if Client.Connected then
Client.Disconnect();
Log('TExtAIBaseDelphi-Destroy ID = %d', [fID]);
fClient.Free;
fActions.Free;
fEvents.Free;
fStates.Free;
Inherited;
end;
procedure TExtAIBaseDelphi.Execute();
begin
Log('TExtAIBaseDelphi-Execute: Start');
while fActive do
begin
fClient.ProcessReceivedMessages();
Sleep(10);
end;
Log('TExtAIBaseDelphi-Execute: End');
end;
procedure TExtAIBaseDelphi.TerminateSimulation();
begin
fActive := False;
end;
procedure TExtAIBaseDelphi.ClientStatusMessage(const aMsg: String);
begin
Log(aMsg);
end;
procedure TExtAIBaseDelphi.Log(const aText: String; const aArgs: array of const);
begin
Log(Format(aText,aArgs));
end;
procedure TExtAIBaseDelphi.Log(const aText: String);
begin
if Assigned(fLog) then
fLog.Log(aText);
end;
// Dummy Events so user does not have to define the methods in child class and can choose just the necessary
procedure TExtAIBaseDelphi.OnMissionStart(); begin end;
procedure TExtAIBaseDelphi.OnMissionEnd(); begin end;
procedure TExtAIBaseDelphi.OnTick(aTick: Cardinal); begin end;
procedure TExtAIBaseDelphi.OnPlayerVictory(aHandIndex: SmallInt); begin end;
procedure TExtAIBaseDelphi.OnPlayerDefeated(aHandIndex: SmallInt); begin end;
end.
|
// AKTools akCustomProject unit.
// Базовый модуль для VCL-проектов.
//=============================================================================
////////////////////////////////////////////////////////////////////////////////
// Модуль проектов // by Dmitry Kudinov //
// Проект есть ветвь реестра с записями о настройке программы. Проект состоит
// из отдельных папок (folders). Эти папки инкупсулированы в классы.
// TCustomProjectFolder является предком этих классов. Для того, чтобы создать
// ветвь проекта необходимо перекрыть класс TCustomProjectFolder и сделать две
// вещи:
// - вынести все свойства, которые необходимы сохранить, в раздел published.
// В процедуре сохранения этих свойств установить свойство Modify = true,
// а значения по умолчанию установить в конструкторе
// - перекрыть виртуальную функцию GetFolderName, которая должна возвращать
// имя ветки реестра. Это имя является относительным путем от пути основного
// проекта (который задается в классе TProjectManager)
// Класс TProjectManager представляет собой список проектов приложения.
// Инициализация этого списка заключается в указании пути к реестру, к тором
// будут храниться все папки приложения. Переменная этого класса одна на прилоение.
// Помещать потомок TCustomProjectFolder в TProjectManager не нужно, т.к. он
// туда помещается в конструкторе.
// $Id: UCustomProject.pas,v 1.1.1.1 2000/03/29 11:04:04 dima Exp $
////////////////////////////////////////////////////////////////////////////////
unit akCustomProject;
interface
uses Windows, SysUtils, Classes, Registry, TypInfo, Forms, ExtCtrls;
type
TPlacementCallbackProc = procedure(Registry: TRegistry) of object;
// Предок всех проектов - одна папка из настроек реестра
TCustomProjectFolder = class(TPersistent)
private
FModify: boolean;
FLoading: boolean;
procedure WriteRegistryInfo(Instance: TPersistent; ARegistry: TRegistry);
procedure ReadRegistryInfo(Instance: TPersistent; ARegistry: TRegistry);
protected
function GetFolderName: string; virtual; abstract;
procedure AfterWriting(ARegistry: TRegistry); virtual;
procedure AfterReading(ARegistry: TRegistry); virtual;
public
constructor Create;
destructor Destroy; override;
property Modify: boolean read FModify write FModify;
property Loading: boolean read FLoading;
end;
// Список папок проекта
TProjectManager = class(TList)
private
FPath: string;
procedure SetPath(const Value: string);
public
destructor Destroy; override;
procedure Clear; override;
procedure WriteFolders;
procedure ReadFolders;
procedure WriteFormPlacement(Form: TForm; Proc: TPlacementCallbackProc = nil);
procedure ReadFormPlacement(Form: TForm; Proc: TPlacementCallbackProc = nil);
property Path: string read FPath write SetPath;
end;
var
ProjectManager: TProjectManager;
implementation
////////////////////////////////////////////////////////////////////////////////
// =============================================================================
// TCustomProjectFolder
// =============================================================================
////////////////////////////////////////////////////////////////////////////////
procedure TCustomProjectFolder.AfterReading(ARegistry: TRegistry);
begin
end;
procedure TCustomProjectFolder.AfterWriting(ARegistry: TRegistry);
begin
end;
constructor TCustomProjectFolder.Create;
begin
FModify := false;
ProjectManager.Add(Self);
FLoading := false;
end;
destructor TCustomProjectFolder.Destroy;
begin
ProjectManager.Remove(Self);
inherited;
end;
procedure TCustomProjectFolder.ReadRegistryInfo(Instance: TPersistent; ARegistry: TRegistry);
var
PropertyCount, i, IntValue: integer;
PL: PPropList;
StrValue, OldPath: string;
FloatValue: double;
begin
with ARegistry do
begin
PL := nil;
try
PropertyCount := GetTypeData(Instance.ClassInfo).PropCount;
GetMem(PL, PropertyCount * SizeOf(PPropInfo));
GetPropInfos(Instance.ClassInfo, PL);
for i := 0 to PropertyCount - 1 do
begin
if Integer(PL[i]^.StoredProc) = 1 then
begin
case PL[i]^.PropType^.Kind of
tkInteger, tkEnumeration:
begin
try
IntValue := ReadInteger(PL^[i].Name);
SetOrdProp(Instance, PL^[i], IntValue);
except
IntValue := GetOrdProp(Instance, PL^[i]);
WriteInteger(PL^[i].Name, IntValue);
end;
end;
tkString, tkLString:
begin
StrValue := ReadString(PL^[i].Name);
if StrValue <> '' then
begin
SetStrProp(Instance, PL^[i], StrValue);
end
else
begin
StrValue := GetStrProp(Instance, PL^[i]);
WriteString(PL^[i].Name, StrValue);
end;
end;
tkFloat:
begin
try
FloatValue := ReadFloat(PL^[i].Name);
SetFloatProp(Instance, PL^[i], FloatValue);
except
FloatValue := GetFloatProp(Instance, PL^[i]);
WriteFloat(PL^[i].Name, FloatValue);
end;
end;
tkSet:
begin
try
StrValue := ReadString(PL^[i].Name);
SetSetProp(Instance, PL^[i], '[' + StrValue + ']');
except
StrValue := GetSetProp(Instance, PL^[i]);
WriteString(PL^[i].Name, StrValue);
end;
end;
tkClass:
begin
OldPath := '\' + CurrentPath;
try
OpenKey(OldPath + '\' + PL^[i].Name, false);
ReadRegistryInfo(TPersistent(GetObjectProp(Instance, PL^[i])), ARegistry);
finally
OpenKey(OldPath, false);
end;
end;
end;
end;
end;
finally
if PL <> nil then FreeMem(PL);
end;
end;
end;
procedure TCustomProjectFolder.WriteRegistryInfo(Instance: TPersistent; ARegistry: TRegistry);
var
PropertyCount, i: integer;
PL: PPropList;
OldPath: string;
begin
PL := nil;
with ARegistry do
begin
try
PropertyCount := GetTypeData(Instance.ClassInfo).PropCount;
GetMem(PL, PropertyCount * SizeOf(PPropInfo));
GetPropInfos(Instance.ClassInfo, PL);
for i := 0 to PropertyCount - 1 do
begin
if Integer(PL[i]^.StoredProc) = 1 then
begin
case PL[i]^.PropType^.Kind of
tkInteger, tkEnumeration: WriteInteger(PL^[i].Name, GetOrdProp(Instance, PL^[i]));
tkString, tkLString: WriteString(PL^[i].Name, GetStrProp(Instance, PL^[i]));
tkFloat: WriteFloat(PL^[i].Name, GetFloatProp(Instance, PL^[i]));
tkSet: WriteString(PL^[i].Name, GetSetProp(Instance, PL^[i]));
tkClass:
begin
OldPath := '\' + CurrentPath;
try
OpenKey(OldPath + '\' + PL^[i].Name, true);
WriteRegistryInfo(TPersistent(GetObjectProp(Instance, PL^[i])), ARegistry);
finally
OpenKey(OldPath, false);
end;
end;
end;
end;
end;
FModify := false;
finally
if PL <> nil then FreeMem(PL);
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// =============================================================================
// TProjectManager
// =============================================================================
////////////////////////////////////////////////////////////////////////////////
procedure TProjectManager.Clear;
var
i: integer;
begin
for i := 0 to Count - 1 do
TCustomProjectFolder(Items[i]).Free;
inherited Clear;
end;
destructor TProjectManager.Destroy;
begin
WriteFolders;
inherited;
end;
procedure TProjectManager.ReadFormPlacement(Form: TForm; Proc: TPlacementCallbackProc);
var
WP: TWindowPlacement;
Reg: TRegistry;
begin
if FPath = '' then exit;
Reg := TRegistry.Create;
with Reg do
begin
try
RootKey := HKEY_CURRENT_USER;
OpenKey(Path + 'Forms\' + Form.ClassName, true);
try
ReadBinaryData('Placement', WP, SizeOf(TWindowPlacement));
if WP.showCmd = SW_MAXIMIZE then
Form.WindowState := wsMaximized
else
SetWindowPlacement(Form.Handle, @WP);
except
end;
if Assigned(Proc) then Proc(Reg);
finally
Free;
end;
end;
end;
procedure TProjectManager.ReadFolders;
var
i: integer;
Registry: TRegistry;
begin
if FPath = '' then exit;
Registry := TRegistry.Create;
try
Registry.RootKey := HKEY_CURRENT_USER;
for i := 0 to Count - 1 do
begin
with TCustomProjectFolder(Items[i]) do
begin
FLoading := true;
try
Registry.OpenKey(FPath + GetFolderName, true);
ReadRegistryInfo(TCustomProjectFolder(Items[i]), Registry);
AfterReading(Registry);
finally
FLoading := false;
end;
end;
end;
finally
Registry.Free;
end;
end;
procedure TProjectManager.SetPath(const Value: string);
begin
if FPath <> Value then
begin
FPath := Value;
if FPath[Length(FPath)] <> '\' then FPath := FPath + '\';
end;
end;
procedure TProjectManager.WriteFolders;
var
i: integer;
Registry: TRegistry;
begin
if FPath = '' then exit;
Registry := TRegistry.Create;
try
Registry.RootKey := HKEY_CURRENT_USER;
for i := 0 to Count - 1 do
begin
with TCustomProjectFolder(Items[i]) do
begin
if FModify then
begin
Registry.OpenKey(FPath + GetFolderName, true);
WriteRegistryInfo(TCustomProjectFolder(Items[i]), Registry);
AfterWriting(Registry);
end;
end;
end;
finally
Registry.Free;
end;
end;
procedure TProjectManager.WriteFormPlacement(Form: TForm; Proc: TPlacementCallbackProc);
var
WP: TWindowPlacement;
Reg: TRegistry;
begin
if FPath = '' then exit;
Reg := TRegistry.Create;
with Reg do
begin
try
RootKey := HKEY_CURRENT_USER;
OpenKey(Path + 'Forms\' + Form.ClassName, true);
try
GetWindowPlacement(Form.Handle, @WP);
WriteBinaryData('Placement', WP, SizeOf(TWindowPlacement));
except
end;
if Assigned(Proc) then Proc(Reg);
finally
Free;
end;
end;
end;
initialization
ProjectManager := TProjectManager.Create;
finalization
ProjectManager.Free;
end.
|
unit AddRectangularAvoidanceZoneUnit;
interface
uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit;
type
TAddRectangularAvoidanceZone = class(TBaseExample)
public
function Execute: NullableString;
end;
implementation
uses TerritoryContourUnit, AvoidanceZoneUnit;
function TAddRectangularAvoidanceZone.Execute: NullableString;
var
ErrorString: String;
AvoidanceZone: TAvoidanceZone;
Territory: TTerritoryContour;
NewAvoidanceZone: TAvoidanceZone;
TerritoryName, TerritoryColor: String;
begin
Result := NullableString.Null;
TerritoryName := 'Rect Territory';
TerritoryColor := 'ff0000';
Territory := TTerritoryContour.MakeRectangularContour(
43.5166885350291, -109.3798828125, 46.9802523552188, -101.865234375);
AvoidanceZone := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory);
try
NewAvoidanceZone := Route4MeManager.AvoidanceZone.Add(AvoidanceZone, ErrorString);
try
WriteLn('');
if (NewAvoidanceZone <> nil) then
begin
WriteLn('AddRectangularAvoidanceZone executed successfully');
WriteLn(Format('Territory ID: %s', [NewAvoidanceZone.TerritoryId.Value]));
Result := NewAvoidanceZone.TerritoryId;
end
else
WriteLn(Format('AddRectangularAvoidanceZone error: "%s"', [ErrorString]));
finally
FreeAndNil(NewAvoidanceZone);
end;
finally
FreeAndNil(AvoidanceZone);
end;
end;
end.
|
unit DictionInterfaces;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Diction"
// Автор: Люлин А.В.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Diction/DictionInterfaces.pas"
// Начат: 14.11.2008 13:50
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ControllerInterfaces::Category>> F1 Встроенные продукты::Diction::Diction::DictionInterfaces
//
// Интерфейсы для работы с толковым словарём
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
bsTypes,
DocumentAndListInterfaces,
CommonDictionInterfaces
{$If not defined(NoVCM)}
,
vcmControllers
{$IfEnd} //not NoVCM
,
QueryCardInterfaces,
DictionInterfacesPrim,
vcmInterfaces {a}
;
type
IdsDiction = interface(IdsCommonDiction)
{* Список толкований }
['{D97C5B61-097A-4C19-95EF-1C5820AD89EB}']
function pm_GetLanguage: TbsLanguage;
procedure pm_SetLanguage(aValue: TbsLanguage);
property Language: TbsLanguage
read pm_GetLanguage
write pm_SetLanguage;
end;//IdsDiction
IbsDictionListener = interface(IbsCommonDictionListener)
{* Слушатель событий бизнес объекта формы список толкований }
['{A9A4196C-CD68-47BA-8DED-97CC7084AB53}']
procedure UpdateLanguage(aLanguage: TbsLanguage);
{* обновить язык списка толкований }
end;//IbsDictionListener
IsdsDiction = interface(IsdsCommonDiction)
{* Толковый словарь }
['{5F50593A-39D2-4EC7-9410-0A4FEE1DB991}']
function pm_GetTranslationForms: Integer;
function pm_GetDefaultLanguage: TbsLanguage;
function pm_GetDsTranslate(aLanguageId: Integer): IdsDictionDocument;
procedure OpenLiteratureList;
{* открыть список литературы для толкового словаря }
function IsShowLiteratureList: Boolean;
property TranslationForms: Integer
read pm_GetTranslationForms;
{* количество форм с переводом (по количеству возможных языков) }
property DefaultLanguage: TbsLanguage
read pm_GetDefaultLanguage;
{* язык по умолчанию, используется для установки фиктивной закладки толкового словаря }
property dsTranslate[aLanguageId: Integer]: IdsDictionDocument
read pm_GetDsTranslate;
{* получить бизнес объект для указанного языка }
end;//IsdsDiction
IdDiction = interface(IdCommonDiction)
{* Данные толкового словаря }
['{9BE60C81-85BB-4DBB-AC9A-CA023E09BA3C}']
function pm_GetLanguages: TbsLanguages;
procedure pm_SetLanguages(aValue: TbsLanguages);
function pm_GetRefTranslationCount: Integer;
function pm_GetIsShowLiteratureList: Boolean;
procedure pm_SetIsShowLiteratureList(aValue: Boolean);
function pm_GetRefTranslation(aIndex: Integer): IvcmFormDataSourceRef;
property Languages: TbsLanguages
read pm_GetLanguages
write pm_SetLanguages;
property refTranslationCount: Integer
read pm_GetRefTranslationCount;
property IsShowLiteratureList: Boolean
read pm_GetIsShowLiteratureList
write pm_SetIsShowLiteratureList;
property refTranslation[aIndex: Integer]: IvcmFormDataSourceRef
read pm_GetRefTranslation;
end;//IdDiction
IdeDiction = interface(IdeCommonDiction)
{* Данные для сборки Толковый словарь }
['{A16C999F-97F3-416A-A277-572CDB3E8896}']
function pm_GetDictLanguage: TbsLanguage;
procedure pm_SetDictLanguage(aValue: TbsLanguage);
property DictLanguage: TbsLanguage
read pm_GetDictLanguage
write pm_SetDictLanguage;
end;//IdeDiction
{$IfEnd} //not Admin AND not Monitorings
implementation
end. |
// Current identifier location editor expert
// Contributed to GExperts by Max Vlasov <maksee@mail.ru>
// Additional edits by Erik Berry
unit GX_ePrevNextIdentifier;
interface
uses
Classes, StdCtrls, Controls, Forms, GX_BaseForm, GX_EditorExpert, GX_ConfigurationInfo;
type
TViewChangeType = (vctScrollIfNeeded, vctScrollCenter);
TBaseIdentExpert = class(TEditorExpert)
private
FSource: string;
FPosition: Integer;
procedure SetPosition(Value: Integer);
protected
// Source and Position are valid only inside InternalExecute
property Source: string read FSource;
property Position: Integer read FPosition write SetPosition;
procedure InternalExecute; virtual; abstract;
public
procedure Execute(Sender: TObject); override;
function HasConfigOptions: Boolean; override;
procedure Configure; override;
end;
TPrevIdentExpert = class(TBaseIdentExpert)
private
Previous: Boolean;
protected
function FindIdentAction(const Source: string; Pos: Integer;
var FoundPos: Integer; var Ident: string): Boolean;
procedure InternalExecute; override;
procedure InternalLoadSettings(Settings: TExpertSettings); override;
procedure InternalSaveSettings(Settings: TExpertSettings); override;
class function ConfigurationKey: string; override;
public
class function GetName: string; override;
constructor Create; override;
function GetDefaultShortCut: TShortCut; override;
function GetDisplayName: string; override;
function GetHelpString: string; override;
end;
TNextIdentExpert = class(TPrevIdentExpert)
protected
class function ConfigurationKey: string; override;
public
class function GetName: string; override;
constructor Create; override;
function GetDefaultShortCut: TShortCut; override;
function GetDisplayName: string; override;
function GetHelpString: string; override;
end;
TfmPrevNextConfig = class(TfmBaseForm)
gbxPrevNextOptions: TGroupBox;
btnOK: TButton;
btnCancel: TButton;
chkCenterMatch: TCheckBox;
end;
implementation
{$R *.dfm}
uses
SysUtils, Windows, ToolsAPI,
GX_GenericUtils, GX_OtaUtils, GX_EditReader;
resourcestring
SIdentHelpString =
' This expert detects the identifier under the cursor and ' +
'allow you to quickly jump to the %s occurrence ' +
'of that identifier in the same file.';
var
// This is *local* and used by both the prevident
// and the nextident expert...
ViewChangeType: TViewChangeType = vctScrollIfNeeded;
function CurrentIdent(const Source: string; CurPos: Integer;
var Pos, Len: Integer): Boolean;
begin
Result := False;
while CurPos >= 1 do
if IsCharIdentifier(Source[CurPos]) then
begin
Dec(CurPos);
Result := True;
end
else if (not Result) and (CurPos >= 2) then
if IsCharIdentifier(Source[CurPos - 1]) then
begin
Dec(CurPos, 2);
Result := True;
end
else
Break
else
Break;
if Result then
begin
Pos := CurPos + 1;
Inc(CurPos, 2);
while (CurPos >= 1) and (CurPos <= Length(Source)) do
if IsCharIdentifier(Source[CurPos]) then
Inc(CurPos)
else
Break;
Len := CurPos - Pos;
end;
end;
function FindIdentAtPos(const Source: string; CurPos: Integer; Prev: Boolean;
var Pos: Integer; var Ident: string): Boolean;
var
StartPos: Integer;
Id: string;
Len: Integer;
begin
Result := False;
if CurrentIdent(Source, CurPos, StartPos, Len) then
begin
Id := Copy(Source, StartPos, Len);
Result := FindTextIdent(Id, Source, StartPos, Prev, Pos);
Ident := Id;
end;
end;
{ TBaseIdentExpert }
procedure TBaseIdentExpert.SetPosition(Value: Integer);
var
EditPos: TOTAEditPos;
CharPos: TOTACharPos;
LinePos: TPoint;
EditView: IOTAEditView;
begin
FPosition := Value;
LinePos := CharPosToLinePos(FPosition, FSource);
CharPos.Line := LinePos.Y;
CharPos.CharIndex := LinePos.X - 1;
EditView := GxOtaGetTopMostEditView;
EditView.ConvertPos(False, EditPos, CharPos);
case ViewChangeType of
vctScrollCenter: GxOtaGotoEditPos(EditPos);
vctScrollIfNeeded:
begin
EditView.CursorPos := EditPos;
EditView.MoveViewToCursor;
EditView.Paint;
end;
end;
end;
procedure TBaseIdentExpert.Execute;
var
EditRead: TEditReader;
SourceEditor: IOTASourceEditor;
CharPos: TOTACharPos;
begin
FSource := '';
FPosition := -1;
if not GxOtaTryGetCurrentSourceEditor(SourceEditor) then
Exit;
EditRead := TEditReader.Create(SourceEditor.FileName);
try
FSource := EditRead.GetText;
CharPos := EditRead.GetCurrentCharPos;
FPosition := LinePosToCharPos(Point(CharPos.CharIndex + 1, CharPos.Line), FSource);
finally
FreeAndNil(EditRead);
end;
InternalExecute;
end;
function TBaseIdentExpert.HasConfigOptions: Boolean;
begin
Result := True;
end;
procedure TBaseIdentExpert.Configure;
var
Dlg: TfmPrevNextConfig;
begin
Dlg := TfmPrevNextConfig.Create(nil);
try
Dlg.chkCenterMatch.Checked := ViewChangeType = vctScrollCenter;
if Dlg.ShowModal = mrOk then
begin
if Dlg.chkCenterMatch.Checked then
ViewChangeType := vctScrollCenter
else
ViewChangeType := vctScrollIfNeeded;
SaveSettings;
end;
finally
FreeAndNil(Dlg);
end;
end;
{ TPrevIdentExpert }
constructor TPrevIdentExpert.Create;
begin
inherited Create;
Previous := True;
end;
procedure TPrevIdentExpert.InternalExecute;
var
FoundPos: Integer;
Ident: string;
begin
if FindIdentAction(Source, Position, FoundPos, Ident) then
Position := FoundPos
else
MessageBeep($FFFFFFFF);
end;
function TPrevIdentExpert.FindIdentAction(const Source: string; Pos: Integer;
var FoundPos: Integer; var Ident: string): Boolean;
begin
Result := FindIdentAtPos(Source, Pos, Previous, FoundPos, Ident);
end;
function TPrevIdentExpert.GetHelpString: string;
begin
Result := Format(SIdentHelpString, ['previous']);
end;
function TPrevIdentExpert.GetDefaultShortCut: TShortCut;
begin
Result := scCtrl + scAlt + VK_UP;
end;
function TPrevIdentExpert.GetDisplayName: string;
begin
Result := 'Previous Identifier Reference';
end;
class function TPrevIdentExpert.GetName: string;
begin
Result := 'PreviousIdent';
end;
class function TPrevIdentExpert.ConfigurationKey: string;
begin
Result := 'PrevIdentifier';
end;
procedure TPrevIdentExpert.InternalLoadSettings(Settings: TExpertSettings);
begin
inherited InternalLoadSettings(Settings);
// Do not localize any of the below items.
ViewChangeType := TViewChangeType(Settings.ReadEnumerated('ViewChangeType', TypeInfo(TViewChangeType), Ord(vctScrollCenter)));
end;
procedure TPrevIdentExpert.InternalSaveSettings(Settings: TExpertSettings);
begin
inherited InternalSaveSettings(Settings);
// Do not localize any of the below items.
Settings.WriteEnumerated('ViewChangeType', TypeInfo(TViewChangeType), Ord(ViewChangeType));
end;
{ TNextIdentExpert }
class function TNextIdentExpert.ConfigurationKey: string;
begin
Result := 'NextIdentifier';
end;
constructor TNextIdentExpert.Create;
begin
inherited Create;
Previous := False;
end;
function TNextIdentExpert.GetDefaultShortCut: TShortCut;
begin
Result := scCtrl + scAlt + VK_DOWN;
end;
function TNextIdentExpert.GetDisplayName: string;
begin
Result := 'Next Identifier Reference';
end;
function TNextIdentExpert.GetHelpString: string;
begin
Result := Format(SIdentHelpString, ['next']);
end;
class function TNextIdentExpert.GetName: string;
begin
Result := 'NextIdent';
end;
initialization
RegisterEditorExpert(TPrevIdentExpert);
RegisterEditorExpert(TNextIdentExpert);
end.
|
(*---------------------------------------------------------*)
(* Different Array implementations *)
(* Neuhold Michael *)
(* 28.11.2018 *)
(* 1. static array with fixed size *)
(* 2. array with fixed size on heap *)
(* 3. array with size defined at runtime on heap *)
(*---------------------------------------------------------*)
PROGRAM Arrays;
CONST
max = 50;
TYPE
IntArray = ARRAY [0..max-1] OF INTEGER; (* v1, v2 - fixed size *)
DynamicIntArray = ARRAY [0..0] OF INTEGER; (* v3 - flexible length *)
VAR
ia: IntArray; (* v1 static, fixed size *)
i,n: INTEGER;
iaPtr: ^IntArray; (* v2 dynamic, fixed size *)
diaPtr: ^DynamicIntArray; (* v3 dynamic, flexible size *)
BEGIN
(* v1: static array, fixed size *)
FOR i := 0 TO max-1 DO BEGIN
ia[i] := i; (* set *)
Write(ia[i],' '); (* get *)
END;
WriteLn; WriteLn;
(* v2: dynamic array, fixed size *)
New(iaPtr);
FOR i := 0 TO max-1 DO BEGIN
iaPtr^[i] := i; (* set *)
Write(iaPtr^[i],' '); (* get *)
END;
Dispose(iaPtr);
WriteLn; WriteLn;
(* v3: dynamic array, flexible size *)
Write('Size of Array?');
ReadLn(n);
GetMem(diaPtr,n * SizeOf(INTEGER));
FOR i := 0 TO n-1 DO BEGIN
(*$R-*)
diaPtr^[i] := i; (* set *)
Write(diaPtr^[i],' '); (* get *)
(*$R+*)
END;
FreeMem(diaPtr,n * SizeOf(INTEGER));
WriteLn; WriteLn;
END. |
unit vtOutlinerWithDragDropRes;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "VT"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/gui/Garant/VT/vtOutlinerWithDragDropRes.pas"
// Начат: 10.03.2010 21:43
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::VT::Outliner::vtOutlinerWithDragDropRes
//
// Ресурсы для TvtOutlinerWithDragDrop
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\VT\vtDefine.inc}
interface
uses
l3StringIDEx
;
var
{ Локализуемые строки TreeViewMessages }
str_nsc_MultiSelectDraggingText : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_MultiSelectDraggingText'; rValue : 'Всего: %d');
{ 'Всего: %d' }
implementation
uses
l3MessageID
;
initialization
// Инициализация str_nsc_MultiSelectDraggingText
str_nsc_MultiSelectDraggingText.Init;
end. |
unit evActionInterfaces;
{ Библиотека "Эверест" }
{ Автор: Люлин А.В. © }
{ Модуль: evActionInterfaces - }
{ Начат: 04.10.2001 10:57 }
{ $Id: evActionInterfaces.pas,v 1.4 2001/12/28 12:31:07 law Exp $ }
// $Log: evActionInterfaces.pas,v $
// Revision 1.4 2001/12/28 12:31:07 law
// - new prop: в описание операции добавлено свойство ShortCut.
//
// Revision 1.3 2001/10/10 10:56:39 law
// - new behavior: заточка под Action от Delphi 6.0.
//
// Revision 1.2 2001/10/04 12:42:36 law
// - new behavior: сделан котнроль за сохранением свойств Category и AutoCheck.
//
// Revision 1.1 2001/10/04 09:57:07 law
// - new behavior: сделана возможность определения парамеров операций по умолчанию.
//
{$I evDefine.inc }
interface
uses
Classes,
l3Types
;
type
IevExtActionDescriptor = interface(IUnknown)
['{56C53192-60C6-4B33-A816-05B361065209}']
// property methods
function pm_GetHint: String;
{-}
function pm_GetCaption: String;
{-}
function pm_GetAutoCheck: Bool;
{-}
function pm_GetGroupIndex: Integer;
{-}
function pm_GetShortCut: TShortCut;
{-}
// public properties
property Hint: String
read pm_GetHint;
{-}
property Caption: String
read pm_GetCaption;
{-}
property AutoCheck: Bool
read pm_GetAutoCheck;
{-}
property GroupIndex: Integer
read pm_GetGroupIndex;
{-}
property ShortCut: TShortCut
read pm_GetShortCut;
{-}
end;//IevExtActionDescriptor
implementation
end.
|
{*
* Copyright © 2008 Kristian Høgsberg
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*}
{** \file wayland-util.pas
*
* \brief Utility classes, functions, and macros.
*}
unit wayland_util;
{$mode objfpc}{$H+}
{$packrecords c}
{$linklib wayland-client}
interface
uses
Classes, SysUtils, ctypes;
type
PPwl_interface = ^Pwl_interface;
Pwl_interface = ^Twl_interface;
Pwl_message = ^ Twl_message;
Twl_message = record
name: PChar;
signature: PChar;
types: PPwl_interface;
end;
Twl_interface = record
name: PChar;
version: cint;
method_count: cint;
methods: Pwl_message;
event_count: cint;
events: Pwl_message;
end;
Pwl_list = ^Twl_list;
{ Twl_list }
Twl_list = object
prev,
next: Pwl_list;
procedure Init;
procedure Insert(element: Pwl_list);
procedure Remove(element: Pwl_list); static;
function Length: cint;
function Empty: Boolean;
procedure InsertList(other: Pwl_list);
end;
Pwl_argument = ^Twl_argument;
Twl_argument = record
case integer of
0: (i: cint32);
1: (u: cuint32);
2: (f: cint32);
3: (s: PChar);
4: (o : Pointer {wl_object});
5: (n: cuint32);
6: (a: Pointer {wl_array});
7: (h: cuint32);
end;
Pwl_array = ^Twl_array;
Twl_array = object
size: csize_t;
alloc: csize_t;
data: Pointer;
function GetAsDWord(var AIndex: Integer; var AValue: DWord; AIncIndex: Boolean): Boolean;
end;
wl_dispatcher_func_t = function (arg0: Pointer; arg1: Pointer; arg2: cuint32;
{const} message: Pwl_message;
argument: Pwl_argument): cint; cdecl;
wl_log_func_t = procedure (char :pchar; va_list: Pointer); cdecl; // not sure how to use va_list, it's a record type afaik.
Twl_iterator_result = (
//** Stop the iteration */
WL_ITERATOR_STOP = 0,
//** Continue the iteration */
WL_ITERATOR_CONTINUE = 1);
procedure wl_list_init(list: Pwl_list); cdecl; external;
procedure wl_list_insert(list: Pwl_list; elm: Pwl_list); cdecl; external;
procedure wl_list_remove(element: Pwl_list); cdecl; external;
function wl_list_length(list: Pwl_list): cint; cdecl; external;
function wl_list_empty(list: Pwl_list):cint; cdecl; external;
procedure wl_list_insert_list(list: Pwl_list; other: Pwl_list); cdecl; external;
procedure wl_array_init(&array: Pwl_array); cdecl; external;
procedure wl_array_release(&array: Pwl_array); cdecl; external;
function wl_array_add(&array: Pwl_array; size: csize_t): Pointer; cdecl; external;
function wl_array_copy(&array: Pwl_array; source: Pwl_array): Integer; cdecl; external;
implementation
{ Twl_array }
function Twl_array.GetAsDWord(var AIndex: Integer; var AValue: DWord;
AIncIndex: Boolean): Boolean;
var
lCount: csize_t;
begin
Result := False;
lCount := size div sizeof(DWord);
if AIndex>= lCount then
Exit;
Result := True;
AValue := PDword(data)[AIndex];
if AIncIndex then
Inc(AIndex);
end;
{ Twl_list }
procedure Twl_list.Init;
begin
wl_list_init(@Self);
end;
procedure Twl_list.Insert(element: Pwl_list);
begin
wl_list_insert(@Self, element);
end;
procedure Twl_list.Remove(element: Pwl_list);
begin
wl_list_remove(element);
end;
function Twl_list.Length: cint;
begin
Result := wl_list_length(@Self);
end;
function Twl_list.Empty: Boolean;
begin
Result := wl_list_empty(@Self) <> 0;
end;
procedure Twl_list.InsertList(other: Pwl_list);
begin
wl_list_insert_list(@Self, other);
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
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 3 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, see <http://www.gnu.org/licenses/>.
}
unit OraMaterializedView;
interface
uses Classes, SysUtils, Ora, OraStorage, OraGrants, OraSynonym, DB,DBQuery,
Forms, Dialogs, VirtualTable;
type
TMaterializedView = class(TObject)
private
FOWNER,
FNAME,
FSQL_QUERY: string;
FMODE: TMVRefreshMode;
FWHEN: TMVWhenMethods;
FSTART_TIME,
FSTART_DATE,
FNEXT_TIME,
FNEXT_DATE : string;
FREFRESH_TYPE: TMVRefreshType;
FPARALLEL: string;
FALLOW_UPDATES: boolean;
FPREBUILT_OPTION: string;
FENABLE_ROW_MOVEMENT,
FENABLE_QUERY_REWRITE,
FCOMPRESS: boolean;
FBUILT_TYPE: TMVBuiltType;
FINDEX_TABLESPACE: string;
FUSE_DEFAULT_ROLLBACK_SEGMENT: boolean;
FROLLBACK_SEGMENT_LOCATION: TMVSegmentLocation;
FROLLBACK_SEGMENT_NAME: string;
FCACHE : boolean;
FLOGGING: TLoggingType;
FPhsicalAttributes : TPhsicalAttributes;
FOraSession: TOraSession;
public
property OWNER: string read FOWNER write FOWNER;
property NAME: string read FNAME write FNAME;
property SQL_QUERY: string read FSQL_QUERY write FSQL_QUERY;
property MODE: TMVRefreshMode read FMODE write FMODE;
property WHEN: TMVWhenMethods read FWHEN write FWHEN;
property START_TIME: string read FSTART_TIME write FSTART_TIME;
property START_DATE: string read FSTART_DATE write FSTART_DATE;
property NEXT_TIME: string read FNEXT_TIME write FNEXT_TIME;
property NEXT_DATE: string read FNEXT_DATE write FNEXT_DATE;
property REFRESH_TYPE: TMVRefreshType read FREFRESH_TYPE write FREFRESH_TYPE;
property PARALLEL: string read FPARALLEL write FPARALLEL;
property ALLOW_UPDATES: boolean read FALLOW_UPDATES write FALLOW_UPDATES;
property PREBUILT_OPTION: string read FPREBUILT_OPTION write FPREBUILT_OPTION;
property ENABLE_ROW_MOVEMENT: boolean read FENABLE_ROW_MOVEMENT write FENABLE_ROW_MOVEMENT;
property ENABLE_QUERY_REWRITE: boolean read FENABLE_QUERY_REWRITE write FENABLE_QUERY_REWRITE;
property COMPRESS: boolean read FCOMPRESS write FCOMPRESS;
property BUILT_TYPE: TMVBuiltType read FBUILT_TYPE write FBUILT_TYPE;
property INDEX_TABLESPACE: string read FINDEX_TABLESPACE write FINDEX_TABLESPACE;
property USE_DEFAULT_ROLLBACK_SEGMENT: boolean read FUSE_DEFAULT_ROLLBACK_SEGMENT write FUSE_DEFAULT_ROLLBACK_SEGMENT;
property ROLLBACK_SEGMENT_LOCATION: TMVSegmentLocation read FROLLBACK_SEGMENT_LOCATION write FROLLBACK_SEGMENT_LOCATION;
property ROLLBACK_SEGMENT_NAME: string read FROLLBACK_SEGMENT_NAME write FROLLBACK_SEGMENT_NAME;
property CACHE : boolean read FCACHE write FCACHE;
property LOGGING: TLoggingType read FLOGGING write FLOGGING;
property PhsicalAttributes : TPhsicalAttributes read FPhsicalAttributes write FPhsicalAttributes;
property OraSession: TOraSession read FOraSession write FOraSession;
constructor Create;
destructor Destroy; override;
function GetDDL: string;
function CreateView(ViewScript: string) : boolean;
function ValidateQuery(Query: string) : boolean;
end;
implementation
uses Util, frmSchemaBrowser, OraScripts, Languages;
resourcestring
strMaterializedViewCreated = 'Matetialized View %s has been created.';
strMaterializedViewValidate = 'Query parsed OK.';
constructor TMaterializedView.Create;
begin
inherited;
end;
destructor TMaterializedView.destroy;
begin
inherited;
end;
function TMaterializedView.GetDDL: string;
var
s: string;
begin
result := '';
with self do
begin
result := 'CREATE MATERIALIZED VIEW '+FOWNER+'.'+FNAME;
if FPREBUILT_OPTION = 'Reduced Precision' then
result := result + ln + 'ON PREBUILT TABLE WITH REDUCED PRECISION';
if FPREBUILT_OPTION = 'No Reduced Precision' then
result := result + ln + 'ON PREBUILT TABLE WITHOUT REDUCED PRECISION';
if FPREBUILT_OPTION = '' then
begin
result := result + ln + GenerateStorage(FPhsicalAttributes) ;
if FLOGGING = ltLogging then
result := result + ln +' LOGGING';
if FLOGGING = ltNoLogging then
result := result +ln + ' NOLOGGING';
if FENABLE_ROW_MOVEMENT then
result := result + ln + ' ENABLE ROW MOVEMENT';
if FCACHE then
result := result + ln +' CACHE'
else
result := result + ln +' NOCACHE';
if FCOMPRESS then
result := result + ln +' COMPRESS'
else
result := result + ln +' NOCOMPRESS';
if isNullorZero(FPARALLEL,'0') then
result := result + ln +' PARALLEL '+FPARALLEL
else
result := result + ln +' NOPARALLEL ';
if FBUILT_TYPE = btImmediate then
result := result + ln +' BUILD IMMEDIATE';
if FBUILT_TYPE = btDeferred then
result := result + ln +' BUILD DEFERRED';
end;
if FINDEX_TABLESPACE <> '' then
result := result + ln +' USING INDEX TABLESPACE '+FINDEX_TABLESPACE;
if FMODE = rmNever then
result := result + ln +' NEVER REFRESH'
else
begin
result := result + ln +' REFRESH';
if FMODE = rmFast then result := result + ' FAST';
if FMODE = rmComplete then result := result + ' COMPLETE';
if FMODE = rmForce then result := result + ' FORCE';
if FWHEN = wmOnDemand then result := result + ln + ' ON DEMAND';
if FWHEN = wmOnCommit then result := result + ln + ' ON COMMIT';
if FSTART_TIME <> '' then
result := result + ln + ' START WITH TO_DATE('+str(FSTART_DATE+' '+FSTART_TIME)+','+str('dd.mm.yyyy hh24:mi:ss')+')';
if FNEXT_TIME <> '' then
result := result + ln + ' NEXT TO_DATE('+str(FNEXT_DATE+' '+FNEXT_TIME)+','+str('dd.mm.yyyy hh24:mi:ss')+')';
if FREFRESH_TYPE = rtRowid then result := result + ln + ' WITH ROWID';
if FREFRESH_TYPE = rtPrimaryKey then result := result + ln + ' WITH PRIMARY KEY';
if FUSE_DEFAULT_ROLLBACK_SEGMENT then
s := ' DEFAULT' else s := '';
if FROLLBACK_SEGMENT_LOCATION = stMaster then
result := result + ln + ' USING '+s+' MASTER ROLLBACK SEGMENT';
if FROLLBACK_SEGMENT_LOCATION = stLocal then
result := result + ln + ' USING '+s+' LOCAL ROLLBACK SEGMENT';
if FROLLBACK_SEGMENT_NAME <> '' then
result := result + ' '+FROLLBACK_SEGMENT_NAME;
end; //rmNever
if FALLOW_UPDATES then
result := result + ln +' FOR UPDATE';
if FENABLE_QUERY_REWRITE then
result := result + ln +' ENABLE QUERY REWRITE'
else
result := result + ln +' DISABLE QUERY REWRITE';
result := result + ln +' as '
+ ln +FSQL_QUERY;
end; //self
end; //GetDDL
function TMaterializedView.CreateView(ViewScript: string) : boolean;
begin
result := false;
if FNAME = '' then exit;
result := ExecSQL(ViewScript, Format(ChangeSentence('strMaterializedViewCreated',strMaterializedViewCreated),[FNAME]), FOraSession);
end;
function TMaterializedView.ValidateQuery(Query: string) : boolean;
begin
result := false;
if Query = '' then exit;
result := ExecSQL(Query, ChangeSentence('strMaterializedViewValidate',strMaterializedViewValidate), FOraSession);
end;
end.
|
unit CacheServerRDO;
interface
uses
SyncObjs, RDOInterfaces;
const
MaxWorlds = 20;
ConnectionTime = 5*1000;
ProxyTimeOut = 1*60*1000;
type
IWorldProxy =
interface
procedure Lock;
procedure Unlock;
function GetName : string;
function IsConnected : boolean;
function GetCache(Id, kind, info : integer) : string;
function RenewCache(Agent, ObjId : string) : string;
function GetMSVersion : integer;
property Name : string read GetName;
property MSVersion : integer read GetMSVersion;
end;
TCSWorldProxy =
class(TInterfacedObject, IWorldProxy)
public
constructor Create(aName : string; aProxy : OleVariant; MSVer : integer);
destructor Destroy; override;
private
fName : string;
fProxy : OleVariant;
fCriticalSec : TCriticalSection;
fConnected : boolean;
fMSVersion : integer;
public
procedure Lock;
procedure Unlock;
function GetName : string;
function IsConnected : boolean;
function GetCache(Id, kind, info : integer) : string;
function RenewCache(Agent, ObjId : string) : string;
function GetMSVersion : integer;
public
property Name : string read GetName;
private
procedure Disconnect(const Conn : IRDOConnection);
end;
TWorldProxiyArray = array[0..MaxWorlds] of IWorldProxy;
TWorldProxies =
class
public
constructor Create;
destructor Destroy; override;
private
fCount : integer;
fWorlds : TWorldProxiyArray;
fCriticalSec : TCriticalSection;
public
procedure Lock;
procedure Unlock;
function IniRDOForWorld(const Name : string; index : integer) : IWorldProxy;
function GetCSWorldProxy(Name : string) : IWorldProxy;
public
property Proxies[index :string] : IWorldProxy read GeTCSWorldProxy; default;
end;
var
WorldProxies : TWorldProxies = nil;
implementation
uses
Windows, SysUtils, ActiveX, ComObj, Registry, CacheRegistryKeys, Collection,
CacheObjects, CacheCommon, WinSockRDOConnection, RDOObjectProxy;
// TCSWorldProxy
constructor TCSWorldProxy.Create(aName : string; aProxy : OleVariant; MSVer : integer);
begin
inherited Create;
fName := aName;
fProxy := aProxy;
fCriticalSec := TCriticalSection.Create;
fConnected := true;
fMSVersion := MSVer;
end;
destructor TCSWorldProxy.Destroy;
begin
fCriticalSec.Free;
inherited;
end;
procedure TCSWorldProxy.Lock;
begin
fCriticalSec.Enter;
end;
procedure TCSWorldProxy.Unlock;
begin
fCriticalSec.Leave;
end;
function TCSWorldProxy.IsConnected : boolean;
begin
result := fConnected;
end;
function TCSWorldProxy.GetName : string;
begin
result := fName;
end;
function TCSWorldProxy.GetCache(Id, kind, info : integer) : string;
begin
try
Lock;
try
result := fProxy.IPC_GetCache(fName, Id, kind, info);
finally
Unlock;
end;
except
result := resError;
end;
end;
function TCSWorldProxy.RenewCache(Agent, ObjId : string) : string;
begin
try
Lock;
try
result := fProxy.IPC_RenewCache(fName, Agent, ObjId);
finally
Unlock;
end;
except
result := resError;
end;
end;
function TCSWorldProxy.GetMSVersion : integer;
begin
result := fMSVersion;
end;
procedure TCSWorldProxy.Disconnect(const Conn : IRDOConnection);
begin
fConnected := false;
end;
// TWorldProxies
constructor TWorldProxies.Create;
begin
inherited Create;
fCriticalSec := TCriticalSection.Create;
end;
destructor TWorldProxies.Destroy;
begin
fCriticalSec.Free;
inherited;
end;
procedure TWorldProxies.Lock;
begin
fCriticalSec.Enter;
end;
procedure TWorldProxies.Unlock;
begin
fCriticalSec.Leave;
end;
function TWorldProxies.IniRDOForWorld(const Name : string; index : integer) : IWorldProxy;
var
ServerAddr : string;
ServerPort : integer;
ClientConn : IRDOConnectionInit;
Proxy : OleVariant;
Reg : TRegistry;
WorldProxy : TCSWorldProxy;
MSVer : integer;
begin
try
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey(WorldsKey + Name, false)
then
begin
ServerAddr := 'localhost';
ServerPort := 6000;
MSVer := Reg.ReadInteger('Version');
ClientConn := TWinSockRDOConnection.Create('MS Cnx');
ClientConn.Server := ServerAddr;
ClientConn.Port := ServerPort;
if ClientConn.Connect(ConnectionTime)
then
begin
Proxy := TRDOObjectProxy.Create as IDispatch;
Proxy.SetConnection(ClientConn);
Proxy.TimeOut := ProxyTimeOut;
Proxy.BindTo(WSObjectCacherName);
WorldProxy := TCSWorldProxy.Create(Name, Proxy, MSVer);
(ClientConn as IRDOConnection).OnDisconnect := WorldProxy.Disconnect;
result := WorldProxy;
{ $IFDEF CACHESERVER} // >> ??
// Add a new world RDO proxy
fWorlds[index] := result;
if index = fCount
then inc(fCount);
{ $ENDIF}
end
else result := nil;
end
else result := nil;
except
result := nil;
end;
end;
function TWorldProxies.GetCSWorldProxy(Name : string) : IWorldProxy;
var
i : integer;
begin
try
Name := uppercase(Name);
Lock;
try
i := 0;
while (i < fCount) and (fWorlds[i].Name <> Name) do
inc(i);
if (i < fCount) and fWorlds[i].IsConnected
then result := fWorlds[i]
else result := IniRDOForWorld(Name, i)
finally
Unlock;
end;
except
result := nil;
end;
end;
initialization
if WorldProxies = nil
then WorldProxies := TWorldProxies.Create;
finalization
{ $IFDEF CACHESERVER}
WorldProxies.Free; // >> Why it crashes if it is working within an OLE-Automation dll?
WorldProxies := nil;
{ $ENDIF}
end.
|
unit DW.Firebase.InstanceId.iOS;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.TypInfo,
// Mac
Macapi.ObjectiveC,
// iOS
iOSapi.Foundation,
// DW
DW.Firebase.InstanceId;
type
TPlatformFirebaseInstanceId = class;
ITokenRefreshNotification = interface(NSObject)
['{93CAC2BE-AF2C-4934-AC49-D1D0381EE355}']
procedure onTokenRefresh(notification: Pointer); cdecl;
end;
TTokenRefreshNotificationListener = class(TOCLocal)
private
FFirebaseInstanceId: TPlatformFirebaseInstanceId;
protected
function GetObjectiveCClass: PTypeInfo; override;
public
constructor Create(const AFirebaseInstanceId: TPlatformFirebaseInstanceId);
procedure onTokenRefresh(notification: Pointer); cdecl;
end;
TPlatformFirebaseInstanceId = class(TCustomPlatformFirebaseInstanceId)
private
FTokenRefreshListener: TTokenRefreshNotificationListener;
protected
function Start: Boolean; override;
function GetToken: string; override;
procedure HandleTokenRefresh;
public
constructor Create(const AFirebaseInstanceId: TFirebaseInstanceId); override;
end;
implementation
uses
// RTL
System.Classes, System.SysUtils,
// Mac
Macapi.Helpers, Macapi.ObjCRuntime,
// iOS
iOSapi.Helpers,
// DW
DW.iOSapi.Firebase;
{ TTokenRefreshNotificationListener }
constructor TTokenRefreshNotificationListener.Create(const AFirebaseInstanceId: TPlatformFirebaseInstanceId);
begin
inherited Create;
FFirebaseInstanceId := AFirebaseInstanceId;
end;
function TTokenRefreshNotificationListener.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(ITokenRefreshNotification);
end;
procedure TTokenRefreshNotificationListener.onTokenRefresh(notification: Pointer);
begin
FFirebaseInstanceId.HandleTokenRefresh;
end;
{ TPlatformFirebaseInstanceId }
constructor TPlatformFirebaseInstanceId.Create(const AFirebaseInstanceId: TFirebaseInstanceId);
var
LName: Pointer;
begin
inherited;
FTokenRefreshListener := TTokenRefreshNotificationListener.Create(Self);
LName := NSObjectToID(kFIRInstanceIdTokenRefreshNotification);
TiOSHelper.DefaultNotificationCenter.addObserver(FTokenRefreshListener.GetObjectID, sel_getUid('onTokenRefresh:'), LName, nil);
end;
function TPlatformFirebaseInstanceId.Start: Boolean;
begin
Result := False;
try
TFIRApp.OCClass.configure;
Result := True;
except
on E: Exception do
DoException(E)
end;
end;
function TPlatformFirebaseInstanceId.GetToken: string;
begin
Result := NSStrToStr(TFIRInstanceId.Wrap(TFIRInstanceId.OCClass.instanceID).token);
end;
procedure TPlatformFirebaseInstanceId.HandleTokenRefresh;
begin
TThread.Queue(nil,
procedure
begin
DoTokenRefresh(GetToken);
end
);
end;
end.
|
unit uThread;
interface
uses
Classes, Windows, SysUtils, Registry;
type
TRunThread = class(TThread)
private
FFileName: String;
procedure SetFileName(const Value: String);
{ Private declarations }
protected
procedure Execute; override;
public
property FileName: String read FFileName write SetFileName;
end;
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 TRunThread.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.
}
{ TRunThread }
function ExecAndWait(const ExeName, Params: string;
Timeout: Cardinal = MaxInt): Cardinal;
var
sui: TStartupInfo;
ExitCode: Cardinal;
pi: TProcessInformation;
begin
ZeroMemory(@sui, SizeOf(sui));
sui.cb := SizeOf(sui);
Win32Check(CreateProcess(PChar(ExeName), PChar(Params), nil, nil, False, 0,
nil, nil, sui, pi));
try
CloseHandle(pi.hThread);
if WaitForSingleObject(pi.hProcess, Timeout) = WAIT_OBJECT_0 then
Win32Check(GetExitCodeProcess(pi.hProcess, ExitCode));
Result := ExitCode;
finally
CloseHandle(pi.hProcess);
end;
end;
const
RegPath = 'Software\Barbaris\Starter';
procedure TRunThread.Execute;
var
Reg: TRegistry;
FileName: String;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKeyReadOnly(RegPath) then
begin
FileName := Reg.ReadString('FileName');
end;
Reg.CloseKey;
finally
Reg.Free;
end;
if FileName = '' then
Exit;
while True do
ExecAndWait(FileName, '');
end;
procedure TRunThread.SetFileName(const Value: String);
begin
FFileName := Value;
end;
end.
|
unit Validacoes;
interface
uses
System.Classes, System.Generics.Collections, RTTIUtils, System.SysUtils;
type
TValidacoes = class(TObject)
private
FList : TList<String>;
FResult : TProc<String>;
public
constructor Create;
destructor Destroy; override;
function AddValidacao ( aValue : String ) : TValidacoes;
function ResultDisplay ( aValue : TProc<String>) : TValidacoes;
procedure Validar ( aValue : String );
procedure Mensagem( aValue : String );
procedure ValorNulo ( aValue : String);
procedure CFOP ( aValue : String );
procedure ST ( aValue : String );
procedure NCM ( aValue : String);
end;
implementation
uses
Vcl.Dialogs;
{ TValidacoes }
function TValidacoes.AddValidacao(aValue: String) : TValidacoes;
begin
Result := Self;
FList.Add(aValue);
end;
procedure TValidacoes.CFOP(aValue: String);
begin
FResult('CFOP: ' + aValue + ' OK!');
end;
constructor TValidacoes.Create;
begin
FList := TList<String>.Create;
end;
destructor TValidacoes.Destroy;
begin
FList.Free;
inherited;
end;
procedure TValidacoes.Mensagem(aValue: String);
begin
FResult('Mensagem: ' + aValue + ' OK!');
end;
procedure TValidacoes.NCM(aValue: String);
begin
FResult('NCM: ' + aValue + ' OK!');
end;
function TValidacoes.ResultDisplay(aValue: TProc<String>): TValidacoes;
begin
Result := Self;
FResult := aValue;
end;
procedure TValidacoes.ST(aValue: String);
begin
FResult('ST: ' + aValue + ' OK!');
end;
procedure TValidacoes.Validar(aValue: String);
var
I: Integer;
begin
for I := 0 to Pred(FList.Count) do
TRTTIUtils.ExecutarMetodo<TValidacoes>(Self, FList[I], aValue);
end;
procedure TValidacoes.ValorNulo(aValue: String);
begin
if aValue = '' then
FResult('Valor não pode ser Nulo' + ' ERROR!!!!!');
FResult(aValue + ' OK!');
end;
end.
|
unit TableToolsTestPrim;
// Модуль: "w:\common\components\gui\Garant\Daily\TableToolsTestPrim.pas"
// Стереотип: "TestCase"
// Элемент модели: "TTableToolsTestPrim" MUID: (4CE38AD60265)
{$Include w:\common\components\gui\sdotDefine.inc}
interface
{$If Defined(nsTest) AND NOT Defined(NoVCM)}
uses
l3IntfUses
, TextViaEditorProcessor
, evEditorInterfaces
, PrimTextLoad_Form
;
type
TTableToolsTestPrim = {abstract} class(TTextViaEditorProcessor)
protected
procedure ApplyTools(const aRange: IedRange); virtual; abstract;
{* Вызвать инструмент для таблицы }
procedure CheckOperation(aForm: TPrimTextLoadForm); virtual; abstract;
{* Проверка после применения инструмента. }
procedure Process(aForm: TPrimTextLoadForm); override;
{* Собственно процесс обработки текста }
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TTableToolsTestPrim
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM)
implementation
{$If Defined(nsTest) AND NOT Defined(NoVCM)}
uses
l3ImplUses
, TestFrameWork
, vcmBase
, SysUtils
{$If NOT Defined(NoVCL)}
, Forms
{$IfEnd} // NOT Defined(NoVCL)
, l3Base
//#UC START# *4CE38AD60265impl_uses*
//#UC END# *4CE38AD60265impl_uses*
;
procedure TTableToolsTestPrim.Process(aForm: TPrimTextLoadForm);
{* Собственно процесс обработки текста }
//#UC START# *4BE13147032C_4CE38AD60265_var*
//#UC END# *4BE13147032C_4CE38AD60265_var*
begin
//#UC START# *4BE13147032C_4CE38AD60265_impl*
ApplyTools(aForm.Text.Range);
CheckOperation(aForm);
//#UC END# *4BE13147032C_4CE38AD60265_impl*
end;//TTableToolsTestPrim.Process
function TTableToolsTestPrim.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'Everest';
end;//TTableToolsTestPrim.GetFolder
function TTableToolsTestPrim.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '4CE38AD60265';
end;//TTableToolsTestPrim.GetModelElementGUID
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoVCM)
end.
|
unit CleanArch_EmbrConf.test;
interface
uses
CleanArch_EmbrConf.Controller.ParkinLot,
DUnitX.TestFramework,
System.SysUtils, CleanArch_EmbrConf.Core.Entity.Interfaces;
type
[TestFixture]
TMyTestObject = class
private
FController : iController;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[test]
procedure ShouldEnterParkingLot;
[test]
procedure ShoudGetParkingLot;
[test]
procedure ShoudlBeClosed;
end;
implementation
procedure TMyTestObject.Setup;
begin
FController := TController.New;
end;
procedure TMyTestObject.ShoudGetParkingLot;
var
lParking: iParkingLot;
begin
lParking := FController.GetParkingLot.Execute('shopping');
Assert.IsTrue(lParking.Code = 'shopping');
end;
procedure TMyTestObject.ShoudlBeClosed;
var
lParkingLot, lParkingLotBeforeEnter, lParkingLotAfterEnter: iParkingLot;
begin
lParkingLot := FController.EnterParkingLot.Code('shopping').Plate('MMM-0001')
.Data(FormatDateTime('hh:mm:ss', now)).Execute;
Assert.IsTrue(lParkingLot.Code = 'shopping');
lParkingLotBeforeEnter := FController.GetParkingLot.Execute('shopping');
Assert.IsTrue(lParkingLotBeforeEnter.Code = 'shopping');
lParkingLotAfterEnter := FController.GetParkingLot.Execute('shopping');
Assert.IsTrue(lParkingLotAfterEnter.Code = 'shopping');
end;
procedure TMyTestObject.ShouldEnterParkingLot;
var
lParkingLot, lParkingLotEnter: iParkingLot;
begin
lParkingLot := FController.EnterParkingLot.Code('shopping').Plate('MMM-0001')
.Data(FormatDateTime('dd/mm/yyyy hh:mm:ss', now)).Execute;
lParkingLotEnter := FController.GetParkingLot.Execute('shopping');
Assert.IsTrue(lParkingLotEnter.OccupiedSpaces >= 0);
end;
procedure TMyTestObject.TearDown;
begin
end;
initialization
TDUnitX.RegisterTestFixture(TMyTestObject);
end.
|
// Reports of memory leaks for old versions of Delphi
// Must be the FIRST module in dpr-file uses list
unit uLostMemory;
interface
implementation
uses SysUtils, uLog;
var
HPs : THeapStatus;
HPe : THeapStatus;
Lost: Integer;
initialization
HPs := getHeapStatus;
finalization
HPe := getHeapStatus;
Lost := HPe.TotalAllocated - HPs.TotalAllocated;
if (Lost > 0) then Log.Log(format('Утечка памяти: %d байт.',[Lost]), True);
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 ClpDerStringBase;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpIAsn1String,
ClpAsn1Object,
ClpStringUtils,
ClpIDerStringBase;
type
TDerStringBase = class abstract(TAsn1Object, IAsn1String, IDerStringBase)
strict protected
constructor Create();
function Asn1GetHashCode(): Int32; override;
public
function GetString(): String; virtual; abstract;
function ToString(): String; override;
end;
implementation
{ TDerStringBase }
function TDerStringBase.Asn1GetHashCode: Int32;
begin
Result := TStringUtils.GetStringHashCode(GetString());
end;
constructor TDerStringBase.Create;
begin
Inherited Create();
end;
function TDerStringBase.ToString: String;
begin
Result := GetString();
end;
end.
|
unit vcmFormHandler;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "VCM$Visual"
// Модуль: "w:/common/components/gui/Garant/VCM/implementation/Visual/vcmFormHandler.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::VCM$Visual::Visual::TvcmFormHandler
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc}
interface
{$If not defined(NoVCM)}
uses
vcmExternalInterfaces,
Classes,
vcmEntityForm,
l3ProtoObject,
Forms
;
{$IfEnd} //not NoVCM
{$If not defined(NoVCM)}
type
TvcmFormHandler = class(Tl3ProtoObject, IvcmFormHandler)
private
// private fields
f_Hint : IvcmCString;
f_Form : TvcmEntityForm;
f_Handler : TNotifyEvent;
protected
// realized methods
function Get_Handler: TNotifyEvent;
function Get_Hint: IvcmCString;
function Get_Form: TCustomForm;
function CanHaveCloseButtonInNavigator: Boolean;
function CanHaveOwnCloseButtonInNavigator: Boolean;
public
// public methods
constructor Create(aForm: TvcmEntityForm;
aHandler: TNotifyEvent;
const aHint: IvcmCString); reintroduce;
class function Make(aForm: TvcmEntityForm;
aHandler: TNotifyEvent;
const aHint: IvcmCString): IvcmFormHandler; reintroduce; virtual;
end;//TvcmFormHandler
{$IfEnd} //not NoVCM
implementation
{$If not defined(NoVCM)}
// start class TvcmFormHandler
constructor TvcmFormHandler.Create(aForm: TvcmEntityForm;
aHandler: TNotifyEvent;
const aHint: IvcmCString);
//#UC START# *47D0E6DC0152_47D0E1C9021A_var*
//#UC END# *47D0E6DC0152_47D0E1C9021A_var*
begin
//#UC START# *47D0E6DC0152_47D0E1C9021A_impl*
Assert(aForm <> nil);
Assert(Assigned(aHandler));
inherited Create;
f_Form := aForm;
f_Handler := aHandler;
f_Hint := aHint;
//#UC END# *47D0E6DC0152_47D0E1C9021A_impl*
end;//TvcmFormHandler.Create
class function TvcmFormHandler.Make(aForm: TvcmEntityForm;
aHandler: TNotifyEvent;
const aHint: IvcmCString): IvcmFormHandler;
var
l_Inst : TvcmFormHandler;
begin
l_Inst := Create(aForm, aHandler, aHint);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
function TvcmFormHandler.Get_Handler: TNotifyEvent;
//#UC START# *47D0DE680250_47D0E1C9021Aget_var*
//#UC END# *47D0DE680250_47D0E1C9021Aget_var*
begin
//#UC START# *47D0DE680250_47D0E1C9021Aget_impl*
Result := f_Handler;
//#UC END# *47D0DE680250_47D0E1C9021Aget_impl*
end;//TvcmFormHandler.Get_Handler
function TvcmFormHandler.Get_Hint: IvcmCString;
//#UC START# *47D0DE7E02BB_47D0E1C9021Aget_var*
//#UC END# *47D0DE7E02BB_47D0E1C9021Aget_var*
begin
//#UC START# *47D0DE7E02BB_47D0E1C9021Aget_impl*
Result := f_Hint;
//#UC END# *47D0DE7E02BB_47D0E1C9021Aget_impl*
end;//TvcmFormHandler.Get_Hint
function TvcmFormHandler.Get_Form: TCustomForm;
//#UC START# *47D0DE9902DE_47D0E1C9021Aget_var*
//#UC END# *47D0DE9902DE_47D0E1C9021Aget_var*
begin
//#UC START# *47D0DE9902DE_47D0E1C9021Aget_impl*
Result := f_Form;
//#UC END# *47D0DE9902DE_47D0E1C9021Aget_impl*
end;//TvcmFormHandler.Get_Form
function TvcmFormHandler.CanHaveCloseButtonInNavigator: Boolean;
//#UC START# *4F619C980151_47D0E1C9021A_var*
//#UC END# *4F619C980151_47D0E1C9021A_var*
begin
//#UC START# *4F619C980151_47D0E1C9021A_impl*
Result := f_Form.CanHaveCloseButtonInNavigator;
//#UC END# *4F619C980151_47D0E1C9021A_impl*
end;//TvcmFormHandler.CanHaveCloseButtonInNavigator
function TvcmFormHandler.CanHaveOwnCloseButtonInNavigator: Boolean;
//#UC START# *4F6A0EA503A9_47D0E1C9021A_var*
//#UC END# *4F6A0EA503A9_47D0E1C9021A_var*
begin
//#UC START# *4F6A0EA503A9_47D0E1C9021A_impl*
Result := f_Form.CanHaveOwnCloseButtonInNavigator;
//#UC END# *4F6A0EA503A9_47D0E1C9021A_impl*
end;//TvcmFormHandler.CanHaveOwnCloseButtonInNavigator
{$IfEnd} //not NoVCM
end. |
{*******************************************************************************
作者: dmzn@163.com 2011-11-21
描述: 商品退换代理
*******************************************************************************}
unit UFrameReportProductRetun;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrameBase, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, Menus, StdCtrls,
cxButtons, cxLabel, cxRadioGroup, Grids, UGridPainter, UGridExPainter,
ExtCtrls, cxMaskEdit, cxButtonEdit, cxDropDownEdit, cxCalendar,
UImageButton;
type
TfFrameReportProductReturn = class(TfFrameBase)
GridList: TDrawGridEx;
Panel2: TPanel;
LabelHint: TLabel;
EditTime: TcxComboBox;
EditS: TcxDateEdit;
EditE: TcxDateEdit;
Label1: TLabel;
ImageButton1: TImageButton;
procedure EditNowPropertiesEditValueChanged(Sender: TObject);
procedure BtnSearchClick(Sender: TObject);
private
{ Private declarations }
FPainter: TGridPainter;
//绘制对象
procedure LoadProductReturn;
//退货记录
public
{ Public declarations }
procedure OnCreateFrame; override;
procedure OnDestroyFrame; override;
class function FrameID: integer; override;
end;
implementation
{$R *.dfm}
uses
IniFiles, ULibFun, UDataModule, DB, UMgrControl, USysConst, USysDB, USysFun;
class function TfFrameReportProductReturn.FrameID: integer;
begin
Result := cFI_FrameReportRT;
end;
procedure TfFrameReportProductReturn.OnCreateFrame;
var nIni: TIniFile;
begin
Name := MakeFrameName(FrameID);
FPainter := TGridPainter.Create(GridList);
with FPainter do
begin
HeaderFont.Style := HeaderFont.Style + [fsBold];
//粗体
AddHeader('序号', 50);
AddHeader('款式名称', 50);
AddHeader('颜色', 50);
AddHeader('尺码', 50);
AddHeader('件数', 50);
AddHeader('会员名称', 50);
AddHeader('营销员', 50);
AddHeader('营销时间', 50);
end;
nIni := TIniFile.Create(gPath + sFormConfig);
try
LoadDrawGridConfig(Name, GridList, nIni);
AdjustLabelCaption(LabelHint, GridList);
Width := GetGridHeaderWidth(GridList);
EditTime.ItemIndex := 0;
BtnSearch.Top := EditTime.Top + Trunc((EditTime.Height - BtnSearch.Height) / 2);
finally
nIni.Free;
end;
end;
procedure TfFrameReportProductReturn.OnDestroyFrame;
var nIni: TIniFile;
begin
nIni := TIniFile.Create(gPath + sFormConfig);
try
SaveDrawGridConfig(Name, GridList, nIni);
finally
nIni.Free;
end;
FPainter.Free;
end;
//------------------------------------------------------------------------------
//Desc: 时间变动
procedure TfFrameReportProductReturn.EditNowPropertiesEditValueChanged(Sender: TObject);
var nS,nE: TDate;
begin
GetDateInterval(EditTime.ItemIndex, nS, nE);
EditS.Date := nS;
EditE.Date := nE;
end;
procedure TfFrameReportProductReturn.LoadProductReturn;
var nStr,nHint: string;
nDS: TDataSet;
nIdx,nInt,nNum: Integer;
nData: TGridDataArray;
begin
nStr := 'Select dt.*,StyleName,ColorName,SizeName,M_Name, ' +
'S_Man,S_Date From $DT dt ' +
' Left Join $PT pt On pt.ProductID=dt.D_Product ' +
' Left Join $ST st On st.StyleID=pt.StyleID ' +
' Left Join $CR cr On cr.ColorID=pt.ColorID ' +
' Left Join $SZ sz On sz.SizeID=pt.SizeID ' +
' Left Join $SL sl On sl.S_ID=dt.D_SaleID ' +
' Left Join $MM mm On mm.M_ID=dt.D_Member ' +
'Where S_TerminalID=''$ID'' And (S_Date>=''$KS'' And S_Date<''$JS'') ' +
'Order By S_Date DESC';
nStr := MacroValue(nStr, [MI('$DT', sTable_SaleDtl),
MI('$PT', sTable_DL_Product), MI('$ST', sTable_DL_Style),
MI('$CR', sTable_DL_Color), MI('$SZ', sTable_DL_Size),
MI('$SL', sTable_Sale), MI('$MM', sTable_Member),
MI('$ID', gSysParam.FTerminalID),
MI('$KS', Date2Str(EditS.Date)), MI('$JS', Date2Str(EditE.Date + 1))]);
//xxxxx
nDS := FDM.LockDataSet(nStr, nHint);
try
if not Assigned(nDS) then
begin
ShowDlg(nHint, sWarn); Exit;
end;
FPainter.ClearData;
if nDS.RecordCount < 1 then Exit;
with nDS do
begin
nNum := 0;
nInt := 1;
First;
while not Eof do
begin
SetLength(nData, 8);
for nIdx:=Low(nData) to High(nData) do
begin
nData[nIdx].FText := '';
nData[nIdx].FCtrls := nil;
nData[nIdx].FAlign := taCenter;
end;
nData[0].FText := IntToStr(nInt);
Inc(nInt);
nData[1].FText := FieldByName('StyleName').AsString;
nData[2].FText := FieldByName('ColorName').AsString;
nData[3].FText := FieldByName('SizeName').AsString;
nData[4].FText := FieldByName('D_Number').AsString;
nNum := nNum + FieldByName('D_Number').AsInteger;
nData[5].FText := FieldByName('M_Name').AsString;
nData[6].FText := FieldByName('S_Man').AsString;
nData[7].FText := DateTime2Str(FieldByName('S_Date').AsDateTime);
FPainter.AddData(nData);
Next;
end;
end;
SetLength(nData, 8);
for nIdx:=Low(nData) to High(nData) do
begin
nData[nIdx].FText := '';
nData[nIdx].FCtrls := nil;
nData[nIdx].FAlign := taCenter;
end;
nData[0].FText := Format('总计: %d笔', [nInt - 1]);
nData[4].FText := Format('%d件', [nNum]);
FPainter.AddData(nData);
finally
FDM.ReleaseDataSet(nDS);
end;
end;
//Desc: 查询
procedure TfFrameReportProductReturn.BtnSearchClick(Sender: TObject);
begin
BtnSearch.Enabled := False;
try
LoadProductReturn;
finally
BtnSearch.Enabled := True;
end;
end;
initialization
gControlManager.RegCtrl(TfFrameReportProductReturn, TfFrameReportProductReturn.FrameID);
end.
|
program QueueV3;
(*
procedures:
1. init
2. enqueue
3. dequeue
*)
uses crt;
const size = 10;
type
queueType = record
front, rear : Integer;
data : array[1..size] of Integer;
isFull, isEmpty : boolean;
end;
var q : queueType;
response : string;
x : Integer;
procedure init(var q : queueType);
var i : Integer;
begin
q.front := 1;
q.rear := 0;
q.isFull := False;
q.isEmpty := True;
for i := 1 to size do
q.data[i] := 0;
end;
procedure enqueue(var q : queueType; x : Integer);
begin
if not q.isFull then
begin
{if (q.rear = size) then
q.rear := 1
else
q.rear := q.rear + 1;}
q.rear := q.rear mod size + 1; // when rear = 10(size) and u need to enqueue, enqueue location = 1
q.data[q.rear] := x;
q.isFull := (q.front = q.rear mod size + 1);
//if (q.front = q.rear mod 10 + 1) then //(q.front=q.rear+1) or (q.rear = size)
//q.isFull := true;
q.isEmpty := False;
end;
end;
procedure dequeue(var q : queueType; var x : Integer);
begin
if not q.isEmpty then
begin
x := q.data[q.front];
q.data[q.front] := 0; // clear that space
{if q.front = size then
q.front := 1
else
q.front := q.front + 1;}
q.front := q.front mod size + 1;
q.isEmpty := (q.front = q.rear mod size + 1);
q.isFull := False;
end;
end;
procedure printQueue(q : queueType);
var i : Integer;
begin
for i := 1 to size do
WriteLn('|':4, i, '| ', q.data[i]:5);
WriteLn('Front: ', q.front, ' Rear: ', q.rear);
end;
begin
writeln('Queue:');
init(q);
repeat
WriteLn;
writeln('1.Enqueue data') ;
writeln('2.Dequeue data');
write('> ');
readln(response);
if response = '1' then
begin
if not q.isFull then
begin
write('Enter the data to enqueue > ');
readln(x);
enqueue(q, x);
end
else
begin
TextColor(Red);
writeln('Stack overflow may occur :)');
TextColor(lightgray);
end;
end
else if response = '2' then
begin
if not q.isEmpty then
begin
dequeue(q, x);
writeln('Dequeued data is ', x);
end
else
begin
TextColor(Red);
WriteLn('Stack underflow may occur :/');
TextColor(lightgray);
end;
end;
printQueue(q);
until upcase(response) = 'EXIT';
end. |
unit FlagFile;
interface
uses
betterobject, systemx, classes, ExceptionsX, sysutils, typex;
type
ILockFile = IHolder<TFileStream>;
TFlagFileHandler = class(TSharedObject)
public
class function TryHoldFlag(sFile: string): ILockFile;
class function AssertFlagHold(sFile: string): ILockFile;
end;
implementation
{ TFlagFileHandler }
class function TFlagFileHandler.AssertFlagHold(sFile: string): ILockFile;
begin
result := TryHoldFlag(sFile);
if result = nil then
raise ECritical.create('Could not hold lock file, another process might be running! '+sFile);
end;
class function TFlagFileHandler.TryHoldFlag(sFile: string): ILockFile;
begin
try
result := nil;
var fs := TFileStream.create(sFile, fmCReate);
result := Tholder<TfileStream>.create;
result.o := fs;
except
result := nil;
end;
end;
end.
|
unit TTSCAPTIONTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSCAPTIONRecord = record
PLenderNum: String[4];
PLoan: String[20];
PCIF: String[20];
PLender: String[20];
PBorrower: String[20];
PBoldLoan: String[20];
PBranch: String[20];
PDivision: String[20];
PCollateral: String[20];
PCoMaker: String[20];
End;
TTTSCAPTIONBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSCAPTIONRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSCAPTION = (TTSCAPTIONPrimaryKey);
TTTSCAPTIONTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFLoan: TStringField;
FDFCIF: TStringField;
FDFLender: TStringField;
FDFBorrower: TStringField;
FDFBoldLoan: TStringField;
FDFBranch: TStringField;
FDFDivision: TStringField;
FDFCollateral: TStringField;
FDFCoMaker: TStringField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPLoan(const Value: String);
function GetPLoan:String;
procedure SetPCIF(const Value: String);
function GetPCIF:String;
procedure SetPLender(const Value: String);
function GetPLender:String;
procedure SetPBorrower(const Value: String);
function GetPBorrower:String;
procedure SetPBoldLoan(const Value: String);
function GetPBoldLoan:String;
procedure SetPBranch(const Value: String);
function GetPBranch:String;
procedure SetPDivision(const Value: String);
function GetPDivision:String;
procedure SetPCollateral(const Value: String);
function GetPCollateral:String;
procedure SetPCoMaker(const Value: String);
function GetPCoMaker:String;
procedure SetEnumIndex(Value: TEITTSCAPTION);
function GetEnumIndex: TEITTSCAPTION;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSCAPTIONRecord;
procedure StoreDataBuffer(ABuffer:TTTSCAPTIONRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFLoan: TStringField read FDFLoan;
property DFCIF: TStringField read FDFCIF;
property DFLender: TStringField read FDFLender;
property DFBorrower: TStringField read FDFBorrower;
property DFBoldLoan: TStringField read FDFBoldLoan;
property DFBranch: TStringField read FDFBranch;
property DFDivision: TStringField read FDFDivision;
property DFCollateral: TStringField read FDFCollateral;
property DFCoMaker: TStringField read FDFCoMaker;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PLoan: String read GetPLoan write SetPLoan;
property PCIF: String read GetPCIF write SetPCIF;
property PLender: String read GetPLender write SetPLender;
property PBorrower: String read GetPBorrower write SetPBorrower;
property PBoldLoan: String read GetPBoldLoan write SetPBoldLoan;
property PBranch: String read GetPBranch write SetPBranch;
property PDivision: String read GetPDivision write SetPDivision;
property PCollateral: String read GetPCollateral write SetPCollateral;
property PCoMaker: String read GetPCoMaker write SetPCoMaker;
published
property Active write SetActive;
property EnumIndex: TEITTSCAPTION read GetEnumIndex write SetEnumIndex;
end; { TTTSCAPTIONTable }
procedure Register;
implementation
procedure TTTSCAPTIONTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFLoan := CreateField( 'Loan' ) as TStringField;
FDFCIF := CreateField( 'CIF' ) as TStringField;
FDFLender := CreateField( 'Lender' ) as TStringField;
FDFBorrower := CreateField( 'Borrower' ) as TStringField;
FDFBoldLoan := CreateField( 'BoldLoan' ) as TStringField;
FDFBranch := CreateField( 'Branch' ) as TStringField;
FDFDivision := CreateField( 'Division' ) as TStringField;
FDFCollateral := CreateField( 'Collateral' ) as TStringField;
FDFCoMaker := CreateField( 'CoMaker' ) as TStringField;
end; { TTTSCAPTIONTable.CreateFields }
procedure TTTSCAPTIONTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSCAPTIONTable.SetActive }
procedure TTTSCAPTIONTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSCAPTIONTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSCAPTIONTable.SetPLoan(const Value: String);
begin
DFLoan.Value := Value;
end;
function TTTSCAPTIONTable.GetPLoan:String;
begin
result := DFLoan.Value;
end;
procedure TTTSCAPTIONTable.SetPCIF(const Value: String);
begin
DFCIF.Value := Value;
end;
function TTTSCAPTIONTable.GetPCIF:String;
begin
result := DFCIF.Value;
end;
procedure TTTSCAPTIONTable.SetPLender(const Value: String);
begin
DFLender.Value := Value;
end;
function TTTSCAPTIONTable.GetPLender:String;
begin
result := DFLender.Value;
end;
procedure TTTSCAPTIONTable.SetPBorrower(const Value: String);
begin
DFBorrower.Value := Value;
end;
function TTTSCAPTIONTable.GetPBorrower:String;
begin
result := DFBorrower.Value;
end;
procedure TTTSCAPTIONTable.SetPBoldLoan(const Value: String);
begin
DFBoldLoan.Value := Value;
end;
function TTTSCAPTIONTable.GetPBoldLoan:String;
begin
result := DFBoldLoan.Value;
end;
procedure TTTSCAPTIONTable.SetPBranch(const Value: String);
begin
DFBranch.Value := Value;
end;
function TTTSCAPTIONTable.GetPBranch:String;
begin
result := DFBranch.Value;
end;
procedure TTTSCAPTIONTable.SetPDivision(const Value: String);
begin
DFDivision.Value := Value;
end;
function TTTSCAPTIONTable.GetPDivision:String;
begin
result := DFDivision.Value;
end;
procedure TTTSCAPTIONTable.SetPCollateral(const Value: String);
begin
DFCollateral.Value := Value;
end;
function TTTSCAPTIONTable.GetPCollateral:String;
begin
result := DFCollateral.Value;
end;
procedure TTTSCAPTIONTable.SetPCoMaker(const Value: String);
begin
DFCoMaker.Value := Value;
end;
function TTTSCAPTIONTable.GetPCoMaker:String;
begin
result := DFCoMaker.Value;
end;
procedure TTTSCAPTIONTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('Loan, String, 20, N');
Add('CIF, String, 20, N');
Add('Lender, String, 20, N');
Add('Borrower, String, 20, N');
Add('BoldLoan, String, 20, N');
Add('Branch, String, 20, N');
Add('Division, String, 20, N');
Add('Collateral, String, 20, N');
Add('CoMaker, String, 20, N');
end;
end;
procedure TTTSCAPTIONTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum, Y, Y, N, N');
end;
end;
procedure TTTSCAPTIONTable.SetEnumIndex(Value: TEITTSCAPTION);
begin
case Value of
TTSCAPTIONPrimaryKey : IndexName := '';
end;
end;
function TTTSCAPTIONTable.GetDataBuffer:TTTSCAPTIONRecord;
var buf: TTTSCAPTIONRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PLoan := DFLoan.Value;
buf.PCIF := DFCIF.Value;
buf.PLender := DFLender.Value;
buf.PBorrower := DFBorrower.Value;
buf.PBoldLoan := DFBoldLoan.Value;
buf.PBranch := DFBranch.Value;
buf.PDivision := DFDivision.Value;
buf.PCollateral := DFCollateral.Value;
buf.PCoMaker := DFCoMaker.Value;
result := buf;
end;
procedure TTTSCAPTIONTable.StoreDataBuffer(ABuffer:TTTSCAPTIONRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFLoan.Value := ABuffer.PLoan;
DFCIF.Value := ABuffer.PCIF;
DFLender.Value := ABuffer.PLender;
DFBorrower.Value := ABuffer.PBorrower;
DFBoldLoan.Value := ABuffer.PBoldLoan;
DFBranch.Value := ABuffer.PBranch;
DFDivision.Value := ABuffer.PDivision;
DFCollateral.Value := ABuffer.PCollateral;
DFCoMaker.Value := ABuffer.PCoMaker;
end;
function TTTSCAPTIONTable.GetEnumIndex: TEITTSCAPTION;
var iname : string;
begin
result := TTSCAPTIONPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSCAPTIONPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSCAPTIONTable, TTTSCAPTIONBuffer ] );
end; { Register }
function TTTSCAPTIONBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..10] of string = ('LENDERNUM','LOAN','CIF','LENDER','BORROWER','BOLDLOAN'
,'BRANCH','DIVISION','COLLATERAL','COMAKER' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 10) and (flist[x] <> s) do inc(x);
if x <= 10 then result := x else result := 0;
end;
function TTTSCAPTIONBuffer.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;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
end;
end;
function TTTSCAPTIONBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PLoan;
3 : result := @Data.PCIF;
4 : result := @Data.PLender;
5 : result := @Data.PBorrower;
6 : result := @Data.PBoldLoan;
7 : result := @Data.PBranch;
8 : result := @Data.PDivision;
9 : result := @Data.PCollateral;
10 : result := @Data.PCoMaker;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.