text stringlengths 14 6.51M |
|---|
unit steCache;
(*
+--------------------------+
| ┏━┓╺┳╸┏━╸ Simple |
| ┗━┓ ┃ ┣╸ Template |
| ┃ ┃ ┃ Engine |
| ┗━┛ ╹ ┗━╸ for Free Pascal |
+ -------------------------+
*)
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, syncobjs, steParser;
// fast in-memory cache without locks, everyting prealoaded at startup (no refresh)
// intended to be used at production
type
TSTECache = class
protected
FCache : TStringList;
FParser : TSTEParser;
FBaseDirectory : string;
FFileNameMask : string;
procedure Preload;
function Prepare(const AFullFileName : string; DoCheckFileExists : boolean = true; AChangeDateTime : TDateTime = 0) : TSTEParsedTemplateData; virtual;
public
property BaseDirectory : string read FBaseDirectory;
constructor Create(const ABaseDir, AFileNameMask: string); virtual;
destructor Destroy; override;
function Get(const AFileName : string) : TSTEParsedTemplateData; virtual;
end;
// Refreshable and lazy-loaded (by file change date) variant
// intended to be used for development / debug
type
TSTERefreshableCache = class(TSTECache)
protected
FLock : TCriticalSection;
public
LoadOnDemand : boolean;
function Get(const AFileName : string) : TSTEParsedTemplateData; override;
constructor Create(const ABaseDir, AFileNameMask: string); override;
destructor Destroy; override;
end;
implementation
uses
LazFileUtils, FileUtil;
procedure TSTECache.Preload;
var
files : TStringList;
i : integer;
relPath : string;
begin
files := FindAllFiles(FBaseDirectory, FFileNameMask);
try
for i := 0 to files.Count-1 do begin
relPath := LazFileUtils.CreateRelativePath(files.Strings[i], FBaseDirectory);
FCache.AddObject(relPath, Prepare(files.Strings[i], true) );
end;
finally
//files.SaveToFile('full-path-list.txt');
//FCache.SaveToFile('cache-list.txt');
files.Free;
end;
end;
function TSTECache.Prepare(const AFullFileName : string; DoCheckFileExists : boolean; AChangeDateTime : TDateTime) : TSTEParsedTemplateData;
var
content : string;
begin
if DoCheckFileExists and ( not FileExistsUTF8(AFullFileName) ) then
content := format('*** template not found: %s ***', [AFullFileName])
else
content := ReadFileToString(AFullFileName);
Result := TSTEParsedTemplateData.Create;
try
FParser.PrepareTemplate(content, Result );
if AChangeDateTime <> 0 then
Result.ChangeDateTime := FileDateToDateTime(FileAge(AFullFileName))
except
FreeAndNil(Result);
raise;
end;
end;
constructor TSTECache.Create(const ABaseDir, AFileNameMask : string);
begin
FBaseDirectory := ABaseDir;
if not FilenameIsAbsolute(FBaseDirectory) then
FBaseDirectory := ExpandFileNameUTF8
(
FBaseDirectory,
IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0)))
);
FBaseDirectory := IncludeTrailingPathDelimiter( FBaseDirectory );
FFileNameMask := AFileNameMask;
FParser := TSTEParser.Create;
FCache := TStringList.Create;
FCache.OwnsObjects := true;
if FFileNameMask <> '' then
Preload;
end;
destructor TSTECache.Destroy;
begin
FCache.Free;
FParser.Free;
inherited Destroy;
end;
function TSTECache.Get(const AFileName : string) : TSTEParsedTemplateData;
var
idx : integer;
begin
Result := nil;
idx := FCache.IndexOf(AFileName);
if idx <> -1 then
Result := TSTEParsedTemplateData(FCache.Objects[idx]);
end;
function TSTERefreshableCache.Get(const AFileName : string) : TSTEParsedTemplateData;
var
idx : integer;
ChangedAt : TDateTime;
begin
Result := nil;
FLock.Enter;
try
// find item
idx := FCache.IndexOf(AFileName);
if idx = -1 then begin // -------------- miss
if LoadOnDemand then begin
Result := Prepare(FBaseDirectory + AFileName, true);
FCache.AddObject(AFileName, Result);
end;
end else begin // -------------- hit
Result := TSTEParsedTemplateData( FCache.Objects[idx] );
ChangedAt := FileDateToDateTime(FileAge(FBaseDirectory + AFileName));
if ( ChangedAt > Result.ChangeDateTime) then begin // need to refresh ???
Result.Free;
// create new
Result := Prepare(FBaseDirectory + AFileName, false, ChangedAt);
FCache.Objects[idx] := Result;
end;
end;
finally
FLock.Leave;
end;
end;
constructor TSTERefreshableCache.Create(const ABaseDir, AFileNameMask : string);
begin
inherited Create(ABaseDir, AFileNameMask);
LoadOnDemand := true;
FLock := TCriticalSection.Create;
end;
destructor TSTERefreshableCache.Destroy;
begin
FLock.Free;
inherited Destroy;
end;
end.
|
unit badlands_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m6502,m68000,main_engine,controls_engine,gfx_engine,rom_engine,
pal_engine,sound_engine,ym_2151,atari_mo,file_engine;
function iniciar_badlands:boolean;
implementation
const
badlands_rom:array[0..3] of tipo_roms=(
(n:'136074-1008.20f';l:$10000;p:0;crc:$a3da5774),(n:'136074-1006.27f';l:$10000;p:$1;crc:$aa03b4f3),
(n:'136074-1009.17f';l:$10000;p:$20000;crc:$0e2e807f),(n:'136074-1007.24f';l:$10000;p:$20001;crc:$99a20c2c));
badlands_sound:tipo_roms=(n:'136074-1018.9c';l:$10000;p:$0;crc:$a05fd146);
badlands_back:array[0..5] of tipo_roms=(
(n:'136074-1012.4n';l:$10000;p:0;crc:$5d124c6c),(n:'136074-1013.2n';l:$10000;p:$10000;crc:$b1ec90d6),
(n:'136074-1014.4s';l:$10000;p:$20000;crc:$248a6845),(n:'136074-1015.2s';l:$10000;p:$30000;crc:$792296d8),
(n:'136074-1016.4u';l:$10000;p:$40000;crc:$878f7c66),(n:'136074-1017.2u';l:$10000;p:$50000;crc:$ad0071a3));
badlands_mo:array[0..2] of tipo_roms=(
(n:'136074-1010.14r';l:$10000;p:0;crc:$c15f629e),(n:'136074-1011.10r';l:$10000;p:$10000;crc:$fb0b6717),
(n:'136074-1019.14t';l:$10000;p:$20000;crc:$0e26bff6));
badlands_proms:array[0..2] of tipo_roms=(
(n:'74s472-136037-101.7u';l:$200;p:0;crc:$2964f76f),(n:'74s472-136037-102.5l';l:$200;p:$200;crc:$4d4fec6c),
(n:'74s287-136037-103.4r';l:$100;p:$400;crc:$6c5ccf08));
badlands_mo_config:atari_motion_objects_config=(
gfxindex:1; // index to which gfx system */
bankcount:1; // number of motion object banks */
linked:false; // are the entries linked? */
split:true; // are the entries split? */
reverse:false; // render in reverse order? */
swapxy:false; // render in swapped X/Y order? */
nextneighbor:false; // does the neighbor bit affect the next object? */
slipheight:0; // pixels per SLIP entry (0 for no-slip) */
slipoffset:0; // pixel offset for SLIPs */
maxperline:0; // maximum number of links to visit/scanline (0=all) */
palettebase:$80; // base palette entry */
maxcolors:$80; // maximum number of colors */
transpen:0; // transparent pen index */
link_entry:(0,0,0,$03f); // mask for the link */
code_entry:(data_lower:($0fff,0,0,0);data_upper:(0,0,0,0)); // mask for the code index */
color_entry:(data_lower:(0,0,0,$0007);data_upper:(0,0,0,0)); // mask for the color */
xpos_entry:(0,0,0,$ff80); // mask for the X position */
ypos_entry:(0,$ff80,0,0); // mask for the Y position */
width_entry:(0,0,0,0); // mask for the width, in tiles*/
height_entry:(0,$000f,0,0); // mask for the height, in tiles */
hflip_entry:(0,0,0,0); // mask for the horizontal flip */
vflip_entry:(0,0,0,0); // mask for the vertical flip */
priority_entry:(0,0,0,$0008); // mask for the priority */
neighbor_entry:(0,0,0,0); // mask for the neighbor */
absolute_entry:(0,0,0,0);// mask for absolute coordinates */
special_entry:(0,0,0,0); // mask for the special value */
specialvalue:0; // resulting value to indicate "special" */
);
var
rom:array[0..$1ffff] of word;
ram:array[0..$fff] of word;
eeprom_ram:array[0..$fff] of byte;
sound_rom:array[0..3,0..$fff] of byte;
pedal1,pedal2,sound_bank,playfield_tile_bank,soundlatch,mainlatch:byte;
write_eeprom,main_pending,sound_pending:boolean;
pant_bl:array [0..((512*256)-1)] of word;
procedure update_video_badlands;
procedure put_gfx_bl(pos_x,pos_y,nchar,color:word;ngfx:byte;pant_dest:pword);
var
x,y:byte;
temp,temp2:pword;
pos:pbyte;
begin
pos:=gfx[ngfx].datos;
inc(pos,nchar*8*8);
for y:=0 to 7 do begin
temp:=punbuf;
for x:=0 to 7 do begin
temp^:=gfx[ngfx].colores[pos^+color];
inc(pos);
inc(temp);
end;
temp2:=pant_dest;
inc(temp2,((pos_y+y)*512)+pos_x);
copymemory(temp2,punbuf,8*2);
end;
end;
var
f,color,x,y,nchar,atrib:word;
pant1,pant2:array[0..((512*256)-1)] of word;
cont:dword;
repaint:boolean;
begin
repaint:=false;
for f:=0 to $7ff do begin
x:=f mod 64;
y:=f div 64;
atrib:=ram[f];
if (atrib and $1000)<>0 then nchar:=(atrib and $1fff)+(playfield_tile_bank shl 12)
else nchar:=(atrib and $1fff);
color:=(atrib shr 13) and 7;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
put_gfx_bl(x*8,y*8,nchar,color shl 4,0,@pant_bl);
gfx[0].buffer[f]:=false;
repaint:=true;
end;
end;
if repaint then begin
for cont:=0 to ((512*256)-1) do begin
atrib:=pant_bl[cont];
if (atrib and 8)<>0 then begin
pant1[cont]:=paleta[0];
pant2[cont]:=paleta[atrib];
end else begin
pant1[cont]:=paleta[atrib];
pant2[cont]:=paleta[MAX_COLORES];
end;
end;
putpixel(0,0,512*256,@pant1,1);
putpixel(0,0,512*256,@pant2,2);
end;
actualiza_trozo(0,0,512,256,1,0,0,512,256,3);
atari_mo_0.draw(0,0,0);
actualiza_trozo(0,0,512,256,2,0,0,512,256,3);
atari_mo_0.draw(0,0,1);
actualiza_trozo_final(0,0,336,240,3);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
end;
procedure eventos_badlands;
begin
if event.arcade then begin
//Audio CPU
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 or 1) else marcade.in0:=(marcade.in0 and $fe);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 or 2) else marcade.in0:=(marcade.in0 and $fd);
//Buttons
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
//Pedals
if arcade_input.but1[0] then marcade.in2:=(marcade.in2 or 1) else marcade.in2:=(marcade.in2 and $fe);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 or 2) else marcade.in2:=(marcade.in2 and $fd);
end;
end;
procedure badlands_principal;
var
frame_m,frame_s:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=m6502_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 261 do begin
//main
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//sound
m6502_0.run(frame_s);
frame_s:=frame_s+m6502_0.tframes-m6502_0.contador;
case f of
0,64,128,192:m6502_0.change_irq(ASSERT_LINE);
239:begin //VBLANK
update_video_badlands;
m68000_0.irq[1]:=ASSERT_LINE;
marcade.in1:=marcade.in1 or $40;
end;
261:marcade.in1:=marcade.in1 and $bf;
end;
end;
if (marcade.in2 and 1)=0 then pedal1:=pedal1-1;
if (marcade.in2 and 2)=0 then pedal2:=pedal2-1;
eventos_badlands;
video_sync;
end;
end;
function badlands_getword(direccion:dword):word;
begin
case direccion of
0..$3ffff:badlands_getword:=rom[direccion shr 1];
$fc0000..$fc1fff:badlands_getword:=$feff or ($100*byte(sound_pending));
$fd0000..$fd1fff:badlands_getword:=$ff00 or eeprom_ram[(direccion and $1fff) shr 1];
$fe4000..$fe5fff:badlands_getword:=marcade.in1; //in1
$fe6000:badlands_getword:=$ff00 or analog.c[0].x[0]; //in2
$fe6002:badlands_getword:=$ff00 or analog.c[0].x[1]; //in3
$fe6004:badlands_getword:=pedal1; //pedal1
$fe6006:badlands_getword:=pedal2; //pedal2
$fea000..$febfff:begin
badlands_getword:=mainlatch shl 8;
main_pending:=false;
m68000_0.irq[2]:=CLEAR_LINE;
end;
$ffc000..$ffc3ff:badlands_getword:=buffer_paleta[(direccion and $3ff) shr 1];
$ffe000..$ffffff:badlands_getword:=ram[(direccion and $1fff) shr 1];
end;
end;
procedure badlands_putword(direccion:dword;valor:word);
procedure cambiar_color(numero:word);
var
color:tcolor;
i:byte;
tmp_color:word;
begin
numero:=numero shr 1;
tmp_color:=(buffer_paleta[numero*2] and $ff00) or (buffer_paleta[(numero*2)+1] shr 8);
i:=(tmp_color shr 15) and 1;
color.r:=pal6bit(((tmp_color shr 9) and $3e) or i);
color.g:=pal6bit(((tmp_color shr 4) and $3e) or i);
color.b:=pal6bit(((tmp_color shl 1) and $3e) or i);
set_pal_color(color,numero);
if numero<$80 then buffer_color[(numero shr 4) and 7]:=true;
end;
begin
case direccion of
0..$3ffff:; //ROM
$fc0000..$fc1fff:begin
m6502_0.change_reset(PULSE_LINE);
sound_bank:=0;
ym2151_0.reset;
end;
$fd0000..$fd1fff:if write_eeprom then begin
eeprom_ram[(direccion and $1fff) shr 1]:=valor;
write_eeprom:=false;
end;
$fe0000..$fe1fff:; //WD
$fe2000..$fe3fff:m68000_0.irq[1]:=CLEAR_LINE;
$fe8000..$fe9fff:begin
soundlatch:=valor shr 8;
m6502_0.change_nmi(ASSERT_LINE);
sound_pending:=true;
end;
$fec000..$fedfff:begin
playfield_tile_bank:=valor and 1;
fillchar(gfx[0].buffer,$800,1);
end;
$fee000..$feffff:write_eeprom:=true;
$ffc000..$ffc3ff:if buffer_paleta[(direccion and $3ff) shr 1]<>valor then begin
buffer_paleta[(direccion and $3ff) shr 1]:=valor;
cambiar_color((direccion and $3ff) shr 1);
end;
$ffe000..$ffefff:if ram[(direccion and $fff) shr 1]<>valor then begin
ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $fff) shr 1]:=true;
end;
$fff000..$ffffff:ram[(direccion and $1fff) shr 1]:=valor;
end;
end;
function badlands_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$1fff,$4000..$ffff:badlands_snd_getbyte:=mem_snd[direccion];
$2000..$27ff:if (direccion and $1)<>0 then badlands_snd_getbyte:=ym2151_0.status;
$2800..$29ff:case (direccion and 6) of
2:begin
badlands_snd_getbyte:=soundlatch;
sound_pending:=false;
m6502_0.change_nmi(CLEAR_LINE);
end;
4:badlands_snd_getbyte:=marcade.in0 or $10 or ($20*byte(main_pending)) or ($40*(byte(not(sound_pending))));
6:m6502_0.change_irq(CLEAR_LINE);
end;
$3000..$3fff:badlands_snd_getbyte:=sound_rom[sound_bank,direccion and $fff];
end;
end;
procedure badlands_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$1fff:mem_snd[direccion]:=valor;
$2000..$27ff:case (direccion and 1) of
0:ym2151_0.reg(valor);
1:ym2151_0.write(valor);
end;
$2800..$29ff:if (direccion and 6)=6 then m6502_0.change_irq(CLEAR_LINE);
$2a00..$2bff:case (direccion and 6) of
2:begin
mainlatch:=valor;
m68000_0.irq[2]:=ASSERT_LINE;
main_pending:=true;
end;
4:begin
sound_bank:=(valor shr 6) and 3;
if (valor and 1)=0 then ym2151_0.reset;
end;
end;
$3000..$ffff:; //ROM
end;
end;
procedure badlands_sound_update;
begin
ym2151_0.update;
end;
//Main
procedure reset_badlands;
begin
m68000_0.reset;
m6502_0.reset;
YM2151_0.reset;
reset_audio;
marcade.in0:=0;
marcade.in1:=$ffbf;
marcade.in2:=0;
write_eeprom:=false;
sound_pending:=false;
main_pending:=false;
soundlatch:=0;
mainlatch:=0;
playfield_tile_bank:=0;
sound_bank:=0;
pedal1:=$80;
pedal2:=$80;
end;
procedure cerrar_badlands;
var
nombre:string;
begin
nombre:='badlands.nv';
write_file(Directory.Arcade_nvram+nombre,@eeprom_ram,$1000);
end;
function iniciar_badlands:boolean;
var
memoria_temp:array[0..$5ffff] of byte;
f:dword;
longitud:integer;
const
pc_x:array[0..15] of dword=(0, 4, 8, 12, 16, 20, 24, 28,
32, 36, 40, 44, 48, 52, 56, 60);
pc_y:array[0..7] of dword=(0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8);
ps_y:array[0..7] of dword=(0*8, 8*8, 16*8, 24*8, 32*8, 40*8, 48*8, 56*8);
begin
llamadas_maquina.bucle_general:=badlands_principal;
llamadas_maquina.reset:=reset_badlands;
llamadas_maquina.close:=cerrar_badlands;
llamadas_maquina.fps_max:=59.922743;
iniciar_badlands:=false;
iniciar_audio(true);
//Chars
screen_init(1,512,256,false);
screen_init(2,512,256,true);
//Final
screen_init(3,512,256,false,true);
iniciar_video(336,240);
//Main CPU
m68000_0:=cpu_m68000.create(14318180 div 2,262,TCPU_68000);
m68000_0.change_ram16_calls(badlands_getword,badlands_putword);
//Sound CPU
m6502_0:=cpu_m6502.create(14318180 div 8,262,TCPU_M6502);
m6502_0.change_ram_calls(badlands_snd_getbyte,badlands_snd_putbyte);
m6502_0.init_sound(badlands_sound_update);
//Sound Chips
ym2151_0:=ym2151_chip.create(14318180 div 4);
//cargar roms
if not(roms_load16w(@rom,badlands_rom)) then exit;
//cargar sonido
if not(roms_load(@memoria_temp,badlands_sound)) then exit;
copymemory(@mem_snd[$4000],@memoria_temp[$4000],$c000);
for f:=0 to 3 do copymemory(@sound_rom[f,0],@memoria_temp[f*$1000],$1000);
//convertir gfx
if not(roms_load(@memoria_temp,badlands_back)) then exit;
for f:=0 to $5ffff do memoria_temp[f]:=not(memoria_temp[f]);
init_gfx(0,8,8,$3000);
gfx_set_desc_data(4,0,32*8,0,1,2,3);
convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false);
//eeprom
if read_file_size(Directory.Arcade_nvram+'badlands.nv',longitud) then read_file(Directory.Arcade_nvram+'badlands.nv',@eeprom_ram,longitud)
else fillchar(eeprom_ram[0],$1000,$ff);
//atari mo
if not(roms_load(@memoria_temp,badlands_mo)) then exit;
for f:=0 to $2ffff do memoria_temp[f]:=not(memoria_temp[f]);
init_gfx(1,16,8,$c00);
gfx[1].trans[0]:=true;
gfx_set_desc_data(4,0,64*8,0,1,2,3);
convert_gfx(1,0,@memoria_temp,@pc_x,@ps_y,false,false);
atari_mo_0:=tatari_mo.create(nil,@ram[$1000 shr 1],badlands_mo_config,3,336+8,240+8);
//Init Analog
init_analog(m68000_0.numero_cpu,m68000_0.clock);
analog_0(50,10,$0,$ff,$0,false,true,true,true);
//final
reset_badlands;
iniciar_badlands:=true;
end;
end.
|
unit Injector;
interface
type
TInjector = class
strict private
type
TInjection = packed record
JMP: byte;
Offset: integer;
end;
PWin9xDebugThunk = ^TWin9xDebugThunk;
TWin9xDebugThunk = packed record
PUSH: byte;
Addr: pointer;
JMP: byte;
Offset: integer;
end;
PAbsoluteIndirectJmp = ^TAbsoluteIndirectJmp;
TAbsoluteIndirectJmp = packed record
OpCode: word;
Addr: PPointer;
end;
private
FFromAddr: pointer;
FToAddr: pointer;
FInjection: TInjection;
class function IsWin9xDebugThunk(const AAddr: pointer): boolean; static;
public
constructor Create(const AFromAddr, AToAddr: pointer);
destructor Destroy; override;
procedure Enable;
procedure Disable;
class function GetActualAddr(AAddr: pointer): pointer; static;
class function GetAddressOf(const AAddr: pointer; const AOffsetInBytes: integer): pointer; overload;
class function GetAddressOf(const AAddr: pointer; const ASignature: array of byte): pointer; overload;
class function GetAddresOfByACallNearRel(const AAddr: pointer; const AOffsetInBytes: integer): pointer; overload;
class function GetAddresOfByACallNearRel(const AAddr: pointer; const ASignature: array of byte): pointer; overload;
class function IsValidCall(const AAddr: pointer): boolean; overload;
class function IsValidCall(const AAddr: pointer; const AOffsetInBytes: integer): boolean; overload;
class function IsValidCall(const AAddr: pointer; const ASignature: array of byte): boolean; overload;
end;
implementation
uses
SysUtils, Windows;
{ TMocker }
constructor TInjector.Create(const AFromAddr, AToAddr: pointer);
begin
FFromAddr := AFromAddr;
FToAddr := AToAddr;
Enable;
end;
destructor TInjector.Destroy;
begin
try
Disable;
finally
inherited;
end;
end;
procedure TInjector.Disable;
var
LNumBytesWritten: DWord;
begin
if FInjection.JMP <> 0 then begin
WriteProcessMemory(GetCurrentProcess, GetActualAddr(FFromAddr), @FInjection, SizeOf(TInjection), LNumBytesWritten);
end;
end;
procedure TInjector.Enable;
var
LActualAddr: pointer;
LProtect: DWord;
begin
if Assigned(FFromAddr) then begin
LActualAddr := GetActualAddr(FFromAddr);
if VirtualProtect(LActualAddr, SizeOf(TInjection), PAGE_EXECUTE_READWRITE, LProtect) then begin //Request virtual memory write permission
FInjection := TInjection(LActualAddr^); //disassembling first 5 bytes
if (TInjection(LActualAddr^).JMP = $C3) then raise Exception.Create('Can''t hack actual address.'); //Check for a RET instruction. Very small routine may abut another instruction :/
TInjection(LActualAddr^).JMP := $E9; //overriding first byte with a JMP instruction
TInjection(LActualAddr^).Offset := Integer(FToAddr) - (Integer(LActualAddr) + SizeOf(TInjection)); //make jump offset to new proc
VirtualProtect(LActualAddr, SizeOf(TInjection), LProtect, @LProtect); //Restore virtual memory protection
FlushInstructionCache(GetCurrentProcess, LActualAddr, SizeOf(TInjection)); //flush physical memory
end;
end;
end;
class function TInjector.GetActualAddr(AAddr: pointer): pointer;
begin
if (AAddr <> nil) then begin
if (Win32Platform <> VER_PLATFORM_WIN32_NT) and IsWin9xDebugThunk(AAddr) then
AAddr := PWin9xDebugThunk(AAddr).Addr;
if (PAbsoluteIndirectJmp(AAddr).OpCode = $25FF) then
Result := PAbsoluteIndirectJmp(AAddr).Addr^
else
Result := AAddr;
end else Result := nil;
end;
class function TInjector.GetAddressOf(const AAddr: pointer;
const AOffsetInBytes: integer): pointer;
var
LActualAddr: PByteArray;
begin
LActualAddr := GetActualAddr(AAddr);
Inc(PByte(LActualAddr), AOffsetInBytes);
Result := Pointer(Integer(@LActualAddr[5]) + PInteger(@LActualAddr[1])^);
end;
class function TInjector.GetAddresOfByACallNearRel(const AAddr: pointer;
const AOffsetInBytes: integer): pointer;
begin
if not IsValidCall(AAddr, AOffsetInBytes) then
raise Exception.Create('Offset to address isn''t a valid call');
Result := GetAddressOf(AAddr, AOffsetInBytes);
end;
class function TInjector.GetAddresOfByACallNearRel(const AAddr: pointer;
const ASignature: array of byte): pointer;
begin
if not IsValidCall(AAddr, ASignature) then
raise Exception.Create('Offset to address isn''t a valid call');
Result := GetAddressOf(AAddr, ASignature);
end;
class function TInjector.GetAddressOf(const AAddr: pointer;
const ASignature: array of byte): pointer;
var
LActualAddr: PByteArray;
begin
LActualAddr := GetActualAddr(AAddr);
while not CompareMem(LActualAddr, @ASignature, Length(ASignature)) do
Inc(PByte(LActualAddr));
Result := Pointer(Integer(@LActualAddr[5]) + PInteger(@LActualAddr[1])^);
end;
class function TInjector.IsValidCall(const AAddr: pointer;
const AOffsetInBytes: integer): boolean;
var
LActualAddr: PByteArray;
begin
LActualAddr := GetActualAddr(AAddr);
Inc(PByte(LActualAddr), AOffsetInBytes);
Result := IsValidCall(LActualAddr);
end;
class function TInjector.IsValidCall(const AAddr: pointer): boolean;
begin
Result := PByteArray(AAddr)^[0] = $E8;
end;
class function TInjector.IsWin9xDebugThunk(const AAddr: pointer): boolean;
begin
Result := (AAddr <> nil)
and (PWin9xDebugThunk(AAddr).PUSH = $68)
and (PWin9xDebugThunk(AAddr).JMP = $E9);
end;
class function TInjector.IsValidCall(const AAddr: pointer;
const ASignature: array of byte): boolean;
var
LActualAddr: PByteArray;
begin
LActualAddr := GetActualAddr(AAddr);
while not CompareMem(LActualAddr, @ASignature, Length(ASignature)) do
Inc(PByte(LActualAddr));
Result := IsValidCall(LActualAddr);
end;
end.
|
unit nscStatusBarItemDef;
// Модуль: "w:\common\components\gui\Garant\Nemesis\nscStatusBarItemDef.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TnscStatusBarItemDef" MUID: (4FEC3C34003F)
{$Include w:\common\components\gui\Garant\Nemesis\nscDefine.inc}
interface
{$If Defined(Nemesis)}
uses
l3IntfUses
, l3CacheableBase
, nscNewInterfaces
, l3Interfaces
, nscStatusBarOperationDefsList
;
type
TnscStatusBarItemDef = class(Tl3CacheableBase, InscStatusBarItemDef)
private
f_ShowCaption: Boolean;
f_Caption: Il3CString;
f_UseTooltip: Boolean;
f_RequireAutoPopup: Boolean;
f_AutoPopupTimeout: Cardinal;
f_ToolTipKind: TnscToolTipKind;
f_Enabled: Boolean;
f_SubscribedList: TnscStatusBarOperationDefsList;
protected
function Get_Caption: Il3CString;
function Get_UseToolTip: Boolean;
function Get_RequireAutoPopup: Boolean;
function Get_AutoPopupTimeout: Cardinal;
function Get_TootTipKind: TnscToolTipKind;
function Get_ShowCaption: Boolean;
function Get_Enabled: Boolean;
procedure Set_Enabled(aValue: Boolean);
function Get_SubscribedList: InscStatusBarItemDefsList;
procedure SubscribeOnNotification(const aServer: InscStatusBarItemDef);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aShowCaption: Boolean;
const aCaption: Il3CString;
aUseTooltip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind); reintroduce;
class function Make(aShowCaption: Boolean;
const aCaption: Il3CString;
aUseTooltip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarItemDef; reintroduce;
end;//TnscStatusBarItemDef
{$IfEnd} // Defined(Nemesis)
implementation
{$If Defined(Nemesis)}
uses
l3ImplUses
, l3Base
//#UC START# *4FEC3C34003Fimpl_uses*
//#UC END# *4FEC3C34003Fimpl_uses*
;
constructor TnscStatusBarItemDef.Create(aShowCaption: Boolean;
const aCaption: Il3CString;
aUseTooltip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind);
//#UC START# *4FEC3D23013F_4FEC3C34003F_var*
//#UC END# *4FEC3D23013F_4FEC3C34003F_var*
begin
//#UC START# *4FEC3D23013F_4FEC3C34003F_impl*
inherited Create;
f_ShowCaption := aShowCaption;
f_Caption := aCaption;
f_UseToolTip := aUseToolTip;
f_RequireAutoPopup := aRequireAutoPopup;
f_AutoPopupTimeout := anAutoPopupTimeout;
f_ToolTipKind := aToolTipKind;
f_Enabled := False;
//#UC END# *4FEC3D23013F_4FEC3C34003F_impl*
end;//TnscStatusBarItemDef.Create
class function TnscStatusBarItemDef.Make(aShowCaption: Boolean;
const aCaption: Il3CString;
aUseTooltip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarItemDef;
var
l_Inst : TnscStatusBarItemDef;
begin
l_Inst := Create(aShowCaption, aCaption, aUseTooltip, aRequireAutoPopup, anAutoPopupTimeout, aToolTipKind);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TnscStatusBarItemDef.Make
function TnscStatusBarItemDef.Get_Caption: Il3CString;
//#UC START# *4980370D001D_4FEC3C34003Fget_var*
//#UC END# *4980370D001D_4FEC3C34003Fget_var*
begin
//#UC START# *4980370D001D_4FEC3C34003Fget_impl*
Result := f_Caption;
//#UC END# *4980370D001D_4FEC3C34003Fget_impl*
end;//TnscStatusBarItemDef.Get_Caption
function TnscStatusBarItemDef.Get_UseToolTip: Boolean;
//#UC START# *4980371E0167_4FEC3C34003Fget_var*
//#UC END# *4980371E0167_4FEC3C34003Fget_var*
begin
//#UC START# *4980371E0167_4FEC3C34003Fget_impl*
Result := f_UseTooltip;
//#UC END# *4980371E0167_4FEC3C34003Fget_impl*
end;//TnscStatusBarItemDef.Get_UseToolTip
function TnscStatusBarItemDef.Get_RequireAutoPopup: Boolean;
//#UC START# *4980372D0191_4FEC3C34003Fget_var*
//#UC END# *4980372D0191_4FEC3C34003Fget_var*
begin
//#UC START# *4980372D0191_4FEC3C34003Fget_impl*
Result := f_RequireAutoPopup;
//#UC END# *4980372D0191_4FEC3C34003Fget_impl*
end;//TnscStatusBarItemDef.Get_RequireAutoPopup
function TnscStatusBarItemDef.Get_AutoPopupTimeout: Cardinal;
//#UC START# *4980373B02B6_4FEC3C34003Fget_var*
//#UC END# *4980373B02B6_4FEC3C34003Fget_var*
begin
//#UC START# *4980373B02B6_4FEC3C34003Fget_impl*
Result := f_AutoPopupTimeout;
//#UC END# *4980373B02B6_4FEC3C34003Fget_impl*
end;//TnscStatusBarItemDef.Get_AutoPopupTimeout
function TnscStatusBarItemDef.Get_TootTipKind: TnscToolTipKind;
//#UC START# *4980374B0266_4FEC3C34003Fget_var*
//#UC END# *4980374B0266_4FEC3C34003Fget_var*
begin
//#UC START# *4980374B0266_4FEC3C34003Fget_impl*
Result := f_TooltipKind;
//#UC END# *4980374B0266_4FEC3C34003Fget_impl*
end;//TnscStatusBarItemDef.Get_TootTipKind
function TnscStatusBarItemDef.Get_ShowCaption: Boolean;
//#UC START# *4ADC59C6003B_4FEC3C34003Fget_var*
//#UC END# *4ADC59C6003B_4FEC3C34003Fget_var*
begin
//#UC START# *4ADC59C6003B_4FEC3C34003Fget_impl*
Result := f_ShowCaption;
//#UC END# *4ADC59C6003B_4FEC3C34003Fget_impl*
end;//TnscStatusBarItemDef.Get_ShowCaption
function TnscStatusBarItemDef.Get_Enabled: Boolean;
//#UC START# *4BCEAF1A00EE_4FEC3C34003Fget_var*
//#UC END# *4BCEAF1A00EE_4FEC3C34003Fget_var*
begin
//#UC START# *4BCEAF1A00EE_4FEC3C34003Fget_impl*
Result := f_Enabled;
//#UC END# *4BCEAF1A00EE_4FEC3C34003Fget_impl*
end;//TnscStatusBarItemDef.Get_Enabled
procedure TnscStatusBarItemDef.Set_Enabled(aValue: Boolean);
//#UC START# *4BCEAF1A00EE_4FEC3C34003Fset_var*
//#UC END# *4BCEAF1A00EE_4FEC3C34003Fset_var*
begin
//#UC START# *4BCEAF1A00EE_4FEC3C34003Fset_impl*
f_Enabled := aValue;
//#UC END# *4BCEAF1A00EE_4FEC3C34003Fset_impl*
end;//TnscStatusBarItemDef.Set_Enabled
function TnscStatusBarItemDef.Get_SubscribedList: InscStatusBarItemDefsList;
//#UC START# *5060385E0190_4FEC3C34003Fget_var*
//#UC END# *5060385E0190_4FEC3C34003Fget_var*
begin
//#UC START# *5060385E0190_4FEC3C34003Fget_impl*
Result := f_SubscribedList;
//#UC END# *5060385E0190_4FEC3C34003Fget_impl*
end;//TnscStatusBarItemDef.Get_SubscribedList
procedure TnscStatusBarItemDef.SubscribeOnNotification(const aServer: InscStatusBarItemDef);
//#UC START# *5060388903AB_4FEC3C34003F_var*
//#UC END# *5060388903AB_4FEC3C34003F_var*
begin
//#UC START# *5060388903AB_4FEC3C34003F_impl*
if not Assigned(f_SubscribedList) then
f_SubscribedList := TnscStatusBarOperationDefsList.Create;
f_SubscribedList.Add(aServer);
//#UC END# *5060388903AB_4FEC3C34003F_impl*
end;//TnscStatusBarItemDef.SubscribeOnNotification
procedure TnscStatusBarItemDef.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4FEC3C34003F_var*
//#UC END# *479731C50290_4FEC3C34003F_var*
begin
//#UC START# *479731C50290_4FEC3C34003F_impl*
f_Caption := nil;
l3Free(f_SubscribedList);
inherited;
//#UC END# *479731C50290_4FEC3C34003F_impl*
end;//TnscStatusBarItemDef.Cleanup
{$IfEnd} // Defined(Nemesis)
end.
|
//Exercicio 78: Modifique o problema anterior para permitir que o usuário possa em caso de erro ter três tentivas.
// Na terceira tentativa o algoritmo deve terminar avisando ao usuário a razão da interrupção.
{ Solução em Portugol
Algoritmo Exercicio 78;
Var
vet: vetor[1..10000] de real;
maior: Real;
N,i,quantidade_maior,tentativas: inteiro;
Inicio
exiba("Programa que lê N números, diz qual o maior deles e quantas vezes foi digitado.");
exiba("Digite a quantidade de números que serão lidos: ");
leia(N);
tentativas <- 0;
enquanto(N <= 0 e tentativas < 3)faça
tentativas <- tentativas + 1;
exiba("Digite um número positivo.");
leia(N):
fimenquanto;
quantidade_maior <- 0;
se(tentativas <= 3 e N > 0)
então Inicio
para i <- 1 até N faça
exiba("Digite o ",i,"º número:");
leia(vet[i]);
se(i = 1)
então Inicio
maior <- vet[i];
quantidade_maior <- 1;
Fim
senão se(vet[i] = maior)
então quantidade_maior <- quantidade_maior + 1
senão se(vet[i] > maior)
então Inicio
maior <- vet[i];
quantidade_maior <- 1;
Fim;
fimse;
fimse;
fimse;
fimpara;
exiba("O maior número é: ",maior," e aparece ",quantidade_maior," vezes.");
Fim
senão exiba("Você ultrapassou o número de tentativas possíveis. Programa finalizado.");
Fim.
}
// Solução em Pascal
Program Exercicio78;
uses crt;
var
vet: array[1..10000] of real;
maior: Real;
N,i,quantidade_maior,tentativas: integer;
begin
clrscr;
writeln('Programa que lê N números, diz qual o maior deles e quantas vezes foi digitado.');
WriteLn('Digite a quantidade de números que serão lidos: ');
readln(N);
tentativas := 0;
while((N <= 0) and (tentativas < 3))do
Begin
tentativas := tentativas + 1;
writeln('Digite um número positivo.');
readln(N);
End;
quantidade_maior := 0;
if((tentativas <= 3) and (N > 0))
then Begin
for i := 1 to N do
Begin
WriteLn('Digite o ',i,'º número:');
Readln(vet[i]);
if(i = 1)
then Begin
maior := vet[i];
quantidade_maior := 1;
End
else if(vet[i] = maior)
then quantidade_maior := quantidade_maior + 1
else if(vet[i] > maior)
then Begin
maior := vet[i];
quantidade_maior := 1;
End;
End;
WriteLn('O maior número é: ',maior:0:2,' e aparece ',quantidade_maior,' vezes.')
End
else writeln('Você ultrapassou o número de tentativas possíveis. Programa finalizado.');
repeat until keypressed;
end. |
unit fmQuickMessage;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
System.RegularExpressions, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls,
System.StrUtils, Winapi.ActiveX, ADC.Types, ADC.Common, ADC.GlobalVar, ADC.NetInfo, ADC.ADObject,
ADC.AD, ActiveDS_TLB, ADC.LDAP, Vcl.ExtCtrls, tdMessageSend;
type
TForm_QuickMessage = class(TForm)
Memo_ProcessOutput: TMemo;
ComboBox_Computer: TComboBox;
Button_Send: TButton;
Button_Cancel: TButton;
Edit_Recipient: TEdit;
Label_Computer: TLabel;
Label_Recipient: TLabel;
Button_GetIP: TButton;
Memo_MessageText: TMemo;
Label_MessageText: TLabel;
Label_SymbolCount: TLabel;
Label_Output: TLabel;
procedure Button_GetIPClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Memo_MessageTextChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button_CancelClick(Sender: TObject);
procedure Button_SendClick(Sender: TObject);
private
FCallingForm: TForm;
FObj: TADObject;
FMsgSend: TMessageSendThread;
procedure SetADObject(const Value: TADObject);
procedure SetCallingForm(const Value: TForm);
procedure ClearTextFields;
procedure OnMessageSendOutput(ASender: TThread; AOutput: string);
procedure OnMessageSendException(ASender: TThread; AMessage: string);
procedure OnMessageSendTerminate(Sender: TObject);
function GetUserWorkstations(ARootDSE: IADs; ADN: string): string; overload;
function GetUserWorkstations(ALDAP: PLDAP; ADN: string): string; overload;
public
procedure AddHostName(AValue: string);
property CallingForm: TForm write SetCallingForm;
property ADObject: TADObject write SetADObject;
end;
var
Form_QuickMessage: TForm_QuickMessage;
implementation
{$R *.dfm}
procedure TForm_QuickMessage.AddHostName(AValue: string);
var
i: Integer;
infoIP: PIPAddr;
infoDHCP: PDHCPInfo;
fqdn: string;
begin
if not AValue.IsEmpty then
begin
i := ComboBox_Computer.Items.IndexOf(AValue);
if i < 0 then
begin
i := ComboBox_Computer.Items.Add(AValue);
end;
ComboBox_Computer.ItemIndex := i;
end;
end;
procedure TForm_QuickMessage.Button_CancelClick(Sender: TObject);
begin
Close;
end;
procedure TForm_QuickMessage.Button_GetIPClick(Sender: TObject);
var
regEx: TRegEx;
pcName: string;
infoIP: PIPAddr;
infoDHCP: PDHCPInfo;
begin
if ComboBox_Computer.Text = ''
then Exit;
regEx := TRegEx.Create('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', [roNone]);
if regEx.IsMatch(ComboBox_Computer.Text)
then pcName := ComboBox_Computer.Text
else pcName := LowerCase(ComboBox_Computer.Text + '.' + SelectedDC.DomainDnsName);
New(infoIP);
New(infoDHCP);
GetIPAddress(pcName, infoIP);
// GetDHCPInfo(pcName, infoDHCP);
GetDHCPInfoEx(pcName, infoDHCP);
ComboBox_Computer.Text := IfThen(
infoIP^.v4.IsEmpty,
infoDHCP^.IPAddress.v4,
infoIP^.v4
);
Dispose(infoIP);
Dispose(infoDHCP);
end;
procedure TForm_QuickMessage.Button_SendClick(Sender: TObject);
var
msgParam: TMessageSendParam;
msgText: string;
begin
{ Заменяем все переводы строк на пробелы }
// msgText := Memo_MessageText.Lines.Text;
// msgText := TRegEx.Replace(msgText, '[\r\n]', ' ');
// msgText := TRegEx.Replace(msgText, '\s{2,}', ' ');
// msgText := Trim(msgText);
with msgParam do
begin
ExeName := apPsE_Executable;
Process_ShowWindow := apPsE_ShowOutput;
Process_Timeout := apPsE_WaitingTime;
UseCredentials := apPsE_RunAs;
User := apPsE_User;
Password := apPsE_Password;
Message_Text := Memo_MessageText.Text;
Message_Recipient := ComboBox_Computer.Text;
Message_Timeout := apPsE_DisplayTime;
end;
FMsgSend := TMessageSendThread.Create(msgParam, csQuickMessage);
FMsgSend.Priority := tpNormal;
FMsgSend.OnTerminate := OnMessageSendTerminate;
FMsgSend.OnException := OnMessageSendException;
FMsgSend.OnProcessOutput := OnMessageSendOutput;
FMsgSend.Start;
end;
procedure TForm_QuickMessage.ClearTextFields;
begin
Edit_Recipient.Clear;
ComboBox_Computer.Clear;
Memo_MessageText.Clear;
Label_SymbolCount.Caption := Format('(%d/%d)', [0, Memo_MessageText.MaxLength]);
Memo_ProcessOutput.Clear;
end;
procedure TForm_QuickMessage.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if FMsgSend <> nil then
begin
if FMsgSend.hProcess <> 0
then TerminateProcess(FMsgSend.hProcess, 0);
FreeThreadManually(FMsgSend);
end;
ClearTextFields;
FObj := nil;
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
end;
end;
procedure TForm_QuickMessage.FormCreate(Sender: TObject);
begin
ClearTextFields;
end;
function TForm_QuickMessage.GetUserWorkstations(ARootDSE: IADs;
ADN: string): string;
var
hRes: HRESULT;
pObj: IADs;
v: OleVariant;
DomainHostName: string;
begin
Result := '';
v := ARootDSE.Get('dnsHostName');
DomainHostName := VariantToStringWithDefault(v, '');
VariantClear(v);
hRes := ADsOpenObject(
PChar('LDAP://' + DomainHostName + '/' + ADN),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IADs,
@pObj
);
if Succeeded(hRes) then
try
v := pObj.Get('userWorkstations');
Result := VarToStr(v);
VariantClear(v);
except
end;
pObj := nil;
end;
function TForm_QuickMessage.GetUserWorkstations(ALDAP: PLDAP;
ADN: string): string;
var
ldapBase: AnsiString;
attrArray: array of PAnsiChar;
returnCode: ULONG;
searchResult: PLDAPMessage;
ldapEntry: PLDAPMessage;
ldapValue: PPAnsiChar;
begin
SetLength(attrArray, 2);
attrArray[0] := PAnsiChar('userWorkstations');
attrArray[1] := nil;
ldapBase := ADN;
returnCode := ldap_search_ext_s(
ALDAP,
PAnsiChar(ldapBase),
LDAP_SCOPE_BASE,
nil,
PAnsiChar(@attrArray[0]),
0,
nil,
nil,
nil,
0,
searchResult
);
if (returnCode = LDAP_SUCCESS) and (ldap_count_entries(ALDAP, searchResult) > 0 ) then
begin
ldapEntry := ldap_first_entry(ALDAP, searchResult);
ldapValue := ldap_get_values(ALDAP, ldapEntry, attrArray[0]);
if ldapValue <> nil
then Result := ldapValue^
else Result := '';
ldap_value_free(ldapValue);
end;
if searchResult <> nil
then ldap_msgfree(searchResult);
end;
procedure TForm_QuickMessage.Memo_MessageTextChange(Sender: TObject);
begin
Label_SymbolCount.Caption := Format('(%d/%d)', [Length(Memo_MessageText.Text), Memo_MessageText.MaxLength]);
end;
procedure TForm_QuickMessage.OnMessageSendException(ASender: TThread;
AMessage: string);
var
MsgBoxParam: TMsgBoxParams;
begin
with MsgBoxParam do
begin
cbSize := SizeOf(MsgBoxParam);
hwndOwner := Self.Handle;
hInstance := 0;
lpszCaption := PChar(APP_TITLE);
lpszIcon := MAKEINTRESOURCE(32513);
dwStyle := MB_OK or MB_ICONERROR;
dwContextHelpId := 0;
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
MsgBoxParam.lpszText := PChar(AMessage);
end;
MessageBoxIndirect(MsgBoxParam);
end;
procedure TForm_QuickMessage.OnMessageSendOutput(ASender: TThread;
AOutput: string);
begin
Memo_ProcessOutput.Lines.Text := AOutput;
end;
procedure TForm_QuickMessage.OnMessageSendTerminate(Sender: TObject);
begin
end;
procedure TForm_QuickMessage.SetADObject(const Value: TADObject);
var
infoIP: PIPAddr;
infoDHCP: PDHCPInfo;
begin
ComboBox_Computer.Items.Clear;
FObj := Value;
if FObj <> nil then
begin
case FObj.ObjectType of
otWorkstation, otDomainController, otRODomainController: begin
New(infoIP);
New(infoDHCP);
GetIPAddress(FObj.dNSHostName, infoIP);
// GetDHCPInfo(FObj.dNSHostName, infoDHCP);
GetDHCPInfoEx(FObj.dNSHostName, infoDHCP);
if not infoIP^.v4.IsEmpty
then ComboBox_Computer.Items.Add(infoIP^.v4)
else if not infoDHCP^.IPAddress.v4.IsEmpty
then ComboBox_Computer.Items.Add(infoDHCP^.IPAddress.v4);
ComboBox_Computer.Items.Add(FObj.name);
Dispose(infoIP);
Dispose(infoDHCP);
end;
otUser: begin
case apAPI of
ADC_API_LDAP: begin
ComboBox_Computer.Items.DelimitedText := GetUserWorkstations(LDAPBinding, FObj.distinguishedName);
end;
ADC_API_ADSI: begin
ComboBox_Computer.Items.DelimitedText := GetUserWorkstations(ADSIBinding, FObj.distinguishedName);
end;
end;
end;
end;
if ComboBox_Computer.Items.Count > 0
then ComboBox_Computer.ItemIndex := 0;
end;
end;
procedure TForm_QuickMessage.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
if FCallingForm <> nil
then FCallingForm.Enabled := False;
end;
end.
|
unit UGitIgnore;
interface
uses Classes;
type
// checks if a filename matches a pattern from the .gitignore file
TGitIgnore = class(TStringList)
public
procedure Clean;
function LoadIgnoreFile(const filename:string):Boolean;
function MatchPattern(const filename:string):Boolean;
end;
implementation
uses SysUtils;
{**************************************************************************
* NAME: StrMatch
* DESC: Vergleicht 2 Strings unter Berücksichtigung von Wildcards.
*
* based on component TWildMatch from Elliott Shevin (shevine @ aol.com)
*
* Beispiel:
* StrMatch('Hallo Welt!','H?llo W*') ==> True
* StrMatch('Hello World!','H?llo W*') ==> True
* StrMatch('Hello World!','H?llo W*d!') ==> True
* StrMatch('Hello World!','H?llo W*d') ==> False
*
* PARAMS: SearchString: string;
* Der zu suchende String
* Mask: string;
* Der String mit den Wildcards
* CaseSensitive: boolean;
* Berücksichtigung von Groß/Kleinschreibung.
* RESULT: True, falls die Strings übereinstimmen.
*************************************************************************}
function StrMatch(const SearchString, Mask : string; const CaseSensitive: Boolean = True) : boolean;
const
WildCardString = '*';
WildCardChar = '?';
var
s, m : string;
ss : string[1];
c : char;
begin
s := SearchString;
m := Mask;
if not CaseSensitive then
begin
s := Uppercase(s);
m := Uppercase(m);
end;
// Compare the two strings one character at a time until one or the
// other is exhausted. For each character that matches, we truncate
// both strings at the left.
while (Length(s) > 0) and (Length(m) > 0) do
begin
// Take the first character from the mask.
ss := Copy(m,1,1);
c := ss[1];
if c = WildCardChar then
begin
// If the next mask character is wildchar, count the two characters
// as matching; lop them off both strings.
Delete(s,1,1);
Delete(m,1,1);
end
else if c = WildCardString then
begin
// If the next character is a WildString, lop it off the
// mask string, since it matches whatever follows.
// Then keep calling this routine recursively
// to see if what's left of the search string matches what
// remains of the mask. If it doesn't, truncate the search
// string at the left (the WildString character matches
// those bytes, too) and repeat until either there's a match
// or the search string is exhausted, which means the
// WildString character has eaten the entire remaining
// search string.
Delete(m,1,1);
while (not StrMatch(s,m,CaseSensitive)) and (Length(s) > 0) do
Delete(s,1,1);
end
else if Copy(s,1,1) = Copy(m,1,1) then
begin
// Any other character must be an exact match. If not,
// clear the search string to stop the loop, as a match
// failure has been detected. This will be sealed below
// because the search string is null but the mask string
// is not.
Delete(s,1,1);
Delete(m,1,1);
end
else
s := '';
end;
// If the loop is ended, the strings have matched if they
// are now both reduced to null or if the match string
// is reduced to a single WildString character.
Result := ((Length(s) = 0) and (Length(m) = 0)) or (m = WildCardString);
end;
{ TGitIgnore }
procedure TGitIgnore.Clean;
var
i : Integer;
s : string;
begin
for i := Count - 1 downto 0 do
begin
s := Strings[i];
if (s = '') or (s[1]='#') then
delete(i);
end;
end;
function TGitIgnore.LoadIgnoreFile(const filename: string): Boolean;
begin
Result := FileExists(filename);
if Result then
LoadFromFile(filename);
end;
function TGitIgnore.MatchPattern(const filename: string): Boolean;
var
i : Integer;
pattern : string;
begin
for i := Count - 1 downto 0 do
begin
pattern := Strings[i];
if StrMatch(filename, pattern, False) then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
end.
|
{!DOCTOPIC}{
Type » TByteArray
}
{!DOCREF} {
@method: function TByteArray.Len(): Int32;
@desc: Returns the length of the array. Same as 'Length(arr)'
}
function TByteArray.Len(): Int32;
begin
Result := Length(Self);
end;
{!DOCREF} {
@method: function TByteArray.IsEmpty(): Boolean;
@desc: Returns True if the array is empty. Same as 'Length(arr) = 0'
}
function TByteArray.IsEmpty(): Boolean;
begin
Result := Length(Self) = 0;
end;
{!DOCREF} {
@method: procedure TByteArray.Append(const Value:Byte);
@desc: Add another item to the array
}
procedure TByteArray.Append(const Value:Byte);
var
l:Int32;
begin
l := Length(Self);
SetLength(Self, l+1);
Self[l] := Value;
end;
{!DOCREF} {
@method: procedure TByteArray.Insert(idx:Int32; Value:Byte);
@desc:
Inserts a new item `value` in the array at the given position. If position `idx` is greater then the length,
it will append the item `value` to the end. If it's less then 0 it will substract the index from the length of the array.[br]
`Arr.Insert(0, x)` inserts at the front of the list, and `Arr.Insert(length(a), x)` is equivalent to `Arr.Append(x)`.
}
procedure TByteArray.Insert(idx:Int32; Value:Byte);
var l:Int32;
begin
l := Length(Self);
if (idx < 0) then
idx := math.modulo(idx,l);
if (l <= idx) then begin
self.append(value);
Exit();
end;
SetLength(Self, l+1);
MemMove(Self[idx], self[idx+1], (L-Idx)*SizeOf(Byte));
Self[idx] := value;
end;
{!DOCREF} {
@method: procedure TByteArray.Del(idx:Int32);
@desc: Removes the element at the given index c'idx'
}
procedure TByteArray.Del(idx:Int32);
var i,l:Int32;
begin
l := Length(Self);
if (l <= idx) or (idx < 0) then
Exit();
if (L-1 <> idx) then
MemMove(Self[idx+1], self[idx], (L-Idx)*SizeOf(Byte));
SetLength(Self, l-1);
end;
{!DOCREF} {
@method: procedure TByteArray.Remove(Value:Byte);
@desc: Removes the first element from left which is equal to c'Value'
}
procedure TByteArray.Remove(Value:Byte);
begin
Self.Del( Self.Find(Value) );
end;
{!DOCREF} {
@method: function TByteArray.Pop(): Byte;
@desc: Removes and returns the last item in the array
}
function TByteArray.Pop(): Byte;
var H:Int32;
begin
H := high(Self);
Result := Self[H];
SetLength(Self, H);
end;
{!DOCREF} {
@method: function TByteArray.PopLeft(): Byte;
@desc: Removes and returns the first item in the array
}
function TByteArray.PopLeft(): Byte;
begin
Result := Self[0];
MemMove(Self[1], Self[0], SizeOf(Byte)*Length(Self));
SetLength(Self, High(self));
end;
{!DOCREF} {
@method: function TByteArray.Slice(Start,Stop: Int32; Step:Int32=1): TByteArray;
@desc:
Slicing similar to slice in Python, tho goes from 'start to and including stop'
Can be used to eg reverse an array, and at the same time allows you to c'step' past items.
You can give it negative start, and stop, then it will wrap around based on length(..)
If c'Start >= Stop', and c'Step <= -1' it will result in reversed output.
[note]Don't pass positive c'Step', combined with c'Start > Stop', that is undefined[/note]
}
function TByteArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): TByteArray;
begin
if (Start = DefVar64) then
if Step < 0 then Start := -1
else Start := 0;
if (Stop = DefVar64) then
if Step > 0 then Stop := -1
else Stop := 0;
if Step = 0 then Exit;
try Result := exp_slice(Self, Start,Stop,Step);
except SetLength(Result,0) end;
end;
{!DOCREF} {
@method: procedure TByteArray.Extend(Arr:TByteArray);
@desc: Extends the array with an array
}
procedure TByteArray.Extend(Arr:TByteArray);
var L:Int32;
begin
L := Length(Self);
SetLength(Self, Length(Arr) + L);
MemMove(Arr[0],Self[L],Length(Arr)*SizeOf(Byte));
end;
{!DOCREF} {
@method: function TByteArray.Find(Value:Byte): Int32;
@desc: Searces for the given value and returns the first position from the left.
}
function TByteArray.Find(Value:Byte): Int32;
begin
Result := exp_Find(Self,TByteArray([Value]));
end;
{!DOCREF} {
@method: function TByteArray.Find(Sequence:TByteArray): Int32; overload;
@desc: Searces for the given sequence and returns the first position from the left.
}
function TByteArray.Find(Sequence:TByteArray): Int32; overload;
begin
Result := exp_Find(Self,Sequence);
end;
{!DOCREF} {
@method: function TByteArray.FindAll(Value:Byte): TIntArray;
@desc: Searces for the given value and returns all the position where it was found.
}
function TByteArray.FindAll(Value:Byte): TIntArray;
begin
Result := exp_FindAll(Self,TByteArray([value]));
end;
{!DOCREF} {
@method: function TByteArray.FindAll(Sequence:TByteArray): TIntArray; overload;
@desc: Searces for the given sequence and returns all the position where it was found.
}
function TByteArray.FindAll(Sequence:TByteArray): TIntArray; overload;
begin
Result := exp_FindAll(Self,sequence);
end;
{!DOCREF} {
@method: function TByteArray.Contains(val:Byte): Boolean;
@desc: Checks if the arr contains the given value c'val'
}
function TByteArray.Contains(val:Byte): Boolean;
begin
Result := Self.Find(val) <> -1;
end;
{!DOCREF} {
@method: function TByteArray.Count(val:Byte): Int32;
@desc: Counts all the occurances of val
}
function TByteArray.Count(val:Byte): Int32;
begin
Result := Length(Self.FindAll(val));
end;
{!DOCREF} {
@method: procedure TByteArray.Sort(key:TSortKey=sort_Default);
@desc:
Sorts the array
Supports the keys: c'sort_Default'
}
procedure TByteArray.Sort(key:TSortKey=sort_Default);
begin
case key of
sort_default: se.SortTBA(Self);
else
WriteLn('TSortKey not supported');
end;
end;
{!DOCREF} {
@method: function TByteArray.Sorted(key:TSortKey=sort_Default): TByteArray;
@desc:
Sorts and returns a copy of the array.
Supports the keys: c'sort_Default'
}
function TByteArray.Sorted(Key:TSortKey=sort_Default): TByteArray;
begin
Result := Copy(Self);
case key of
sort_default: se.SortTBA(Result);
else
WriteLn('TSortKey not supported');
end;
end;
{!DOCREF} {
@method: function TByteArray.Reversed(): TByteArray;
@desc:
Creates a reversed copy of the array
}
function TByteArray.Reversed(): TByteArray;
begin
Result := Self.Slice(,,-1);
end;
{!DOCREF} {
@method: procedure TByteArray.Reverse();
@desc: Reverses the array
}
procedure TByteArray.Reverse();
begin
Self := Self.Slice(,,-1);
end;
{=============================================================================}
// The functions below this line is not in the standard array functionality
//
// By "standard array functionality" I mean, functions that all standard
// array types should have.
{=============================================================================}
{!DOCREF} {
@method: function TByteArray.Sum(): Int32;
@desc: Adds up the TIA and returns the sum
}
function TByteArray.Sum(): Int32;
begin
Result := exp_SumPtr(PChar(Self),SizeOf(Byte),Length(Self),True);
end;
{!DOCREF} {
@method: function TByteArray.Sum64(): Int64;
@desc: Adds up the TBA and returns the sum
}
function TByteArray.Sum64(): Int64;
begin
Result := exp_SumPtr(PChar(Self),SizeOf(Byte),Length(Self),True);
end;
{!DOCREF} {
@method: function TByteArray.Mean(): Extended;
@desc:Returns the mean value of the array. Use round, trunc or floor to get an c'Int' value.
}
function TByteArray.Mean(): Extended;
begin
Result := Self.Sum64() / Length(Self);
end;
{!DOCREF} {
@method: function TByteArray.Stdev(): Extended;
@desc: Returns the standard deviation of the array
}
function TByteArray.Stdev(): Extended;
var
i:Int32;
avg:Extended;
square:TExtArray;
begin
avg := Self.Mean();
SetLength(square,Length(Self));
for i:=0 to High(self) do Square[i] := Sqr(Self[i] - avg);
Result := sqrt(square.Mean());
end;
{!DOCREF} {
@method: function TByteArray.Variance(): Extended;
@desc:
Return the sample variance.
Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the array. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.
}
function TByteArray.Variance(): Extended;
var
avg:Extended;
i:Int32;
begin
avg := Self.Mean();
for i:=0 to High(Self) do
Result := Result + Sqr(Self[i] - avg);
Result := Result / length(self);
end;
{!DOCREF} {
@method: function TByteArray.Mode(): Byte;
@desc:
Returns the sample mode of the array, which is the most frequently occurring value in the array.
When there are multiple values occurring equally frequently, mode returns the smallest of those values.
}
function TByteArray.Mode(): Byte;
var
arr:TByteArray;
cur:Byte;
i,hits,best: Int32;
begin
arr := self.sorted();
cur := arr[0];
hits := 1;
best := 0;
for i:=1 to High(Arr) do
begin
if (cur <> arr[i]) then
begin
if (hits > best) then
begin
best := hits;
Result := cur;
end;
hits := 0;
cur := Arr[I];
end;
Inc(hits);
end;
if (hits > best) then Result := cur;
end;
{!DOCREF} {
@method: function TByteArray.VarMin(): Byte;
@desc: Returns the minimum value in the array
}
function TByteArray.VarMin(): Byte;
var _:Byte;
begin
se.MinMaxTBA(Self,Result,_);
end;
{!DOCREF} {
@method: function TByteArray.VarMax(): Byte;
@desc: Returns the maximum value in the array
}
function TByteArray.VarMax(): Byte;
var _:Byte;
begin
se.MinMaxTBA(Self,_,Result);
end;
{!DOCREF} {
@method: function TByteArray.ArgMin(): Int32;
@desc: Returns the index containing the smallest element in the array.
}
function TByteArray.ArgMin(): Int32;
var
mat:T2DByteArray;
begin
SetLength(Mat,1);
mat[0] := Self;
Result := exp_ArgMin(mat).x;
end;
{!DOCREF} {
@method: function TByteArray.ArgMin(n:int32): TIntArray; overload;
@desc: Returns the n-indices containing the smallest element in the array.
}
function TByteArray.ArgMin(n:Int32): TIntArray; overload;
var
i: Int32;
_:TIntArray;
mat:TByteMatrix;
begin
SetLength(Mat,1);
mat[0] := Self;
se.TPASplitAxis(mat.ArgMin(n), Result, _);
end;
{!DOCREF} {
@method: function TByteArray.ArgMin(Lo,Hi:int32): Int32; overload;
@desc: Returns the index containing the smallest element in the array within the lower and upper bounds c'lo, hi'.
}
function TByteArray.ArgMin(lo,hi:Int32): Int32; overload;
var
B: TBox;
mat:T2DByteArray;
begin
SetLength(Mat,1);
mat[0] := Self;
B := [lo,0,hi,0];
Result := exp_ArgMin(mat,B).x;
end;
{!DOCREF} {
@method: function TByteArray.ArgMax(): Int32;
@desc: Returns the index containing the largest element in the array.
}
function TByteArray.ArgMax(): Int32;
var
mat:T2DByteArray;
begin
SetLength(Mat,1);
mat[0] := Self;
Result := exp_ArgMax(mat).x;
end;
{!DOCREF} {
@method: function TByteArray.ArgMax(n:int32): TIntArray; overload;
@desc: Returns the n-indices containing the largest element in the array.
}
function TByteArray.ArgMax(n:Int32): TIntArray; overload;
var
i: Int32;
_:TIntArray;
mat:TByteMatrix;
begin
SetLength(Mat,1);
mat[0] := Self;
se.TPASplitAxis(mat.ArgMax(n), Result, _);
end;
{!DOCREF} {
@method: function TByteArray.ArgMax(Lo,Hi:int32): Int32; overload;
@desc: Returns the index containing the largest element in the array within the lower and upper bounds c'lo, hi'.
}
function TByteArray.ArgMax(lo,hi:Int32): Int32; overload;
var
B: TBox;
mat:T2DByteArray;
begin
SetLength(Mat,1);
mat[0] := Self;
B := [lo,0,hi,0];
Result := exp_ArgMax(mat,B).x;
end;
{=============================================================================}
//
//
{=============================================================================}
{!DOCREF} {
@method: function TByteArray.AsString(): String;
@desc: It converts the TBA to a string, by calling `chr()` on each index. Result will be forumlated as a propper string, EG:` Result := 'asd'`
}
function TByteArray.AsString(): String;
var i:Int32;
begin
SetLength(Result,Length(Self));
for i:=0 to High(Self) do
Result[i+1] := chr(Self[i]);
end;
{!DOCREF} {
@method: procedure TByteArray.FromString(str:String);
@desc: It converts the string to a TBA, by calling `ord()` on each index.
}
procedure TByteArray.FromString(str:String);
var i:Int32;
begin
SetLength(Self,Length(Str));
for i:=1 to Length(Str) do
Self[i-1] := ord(Str[i]);
end;
|
// Original Author: Piotr Likus
// Replace Components log window
unit GX_ReplaceCompLog;
interface
uses
Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls,
GX_ReplaceCompData, GX_BaseForm;
type
TfmReplaceCompLog = class(TfmBaseForm)
pnlHeader: TPanel;
lblDest: TLabel;
edtDestClassName: TEdit;
edtSourceClassName: TEdit;
lblSource: TLabel;
pnlLog: TPanel;
pnlBottom: TPanel;
pnlDetails: TPanel;
lbxPreviewItems: TListBox;
lvLogItems: TListView;
Splitter: TSplitter;
dlgGetExportFile: TSaveDialog;
pnlButtons: TPanel;
pnlButtonsRight: TPanel;
btnSaveAs: TButton;
btnCopy: TButton;
btnClose: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure lvLogItemsClick(Sender: TObject);
procedure lvLogItemsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
procedure btnCloseClick(Sender: TObject);
procedure btnCopyClick(Sender: TObject);
procedure btnSaveAsClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FConfigData: TReplaceCompData;
FLogEvents: TCompRepEventList;
FFocusedItem: TListItem;
function ConfigurationKey: string;
procedure LoadSettings;
procedure SaveSettings;
procedure LoadAll;
procedure AddLogEvent(AEvent: TCompRepEvent);
procedure LoadItems;
procedure UpdatePreviewPanel;
function GetFocusedItem: TListItem;
function GetFocusedEvent: TCompRepEvent;
procedure LoadPreviewItems(AEvent: TCompRepEvent);
procedure SaveToClipboard;
procedure GetSelectedItems(Items: TList);
procedure FormatEventsAsTabs(EventList: TList; OutList: TStringList);
procedure FormatEventsAsCSV(EventList: TList; OutList: TStringList);
procedure SaveAsCSV(const AFileName: string);
procedure SaveAsXML(const AFileName: string);
public
constructor Create(Owner: TComponent; ConfigData: TReplaceCompData;
const SourceClassName, DestClassName: string; LogEvents: TCompRepEventList); reintroduce;
end;
implementation
uses
SysUtils, Clipbrd, Gx_GenericUtils, GX_ReplaceCompUtils, GX_ConfigurationInfo;
{$R *.dfm}
{ TfmReplaceCompLog }
constructor TfmReplaceCompLog.Create(Owner: TComponent;
ConfigData: TReplaceCompData;
const SourceClassName, DestClassName: string; LogEvents: TCompRepEventList);
begin
inherited Create(Owner);
FConfigData := ConfigData;
FLogEvents := LogEvents;
edtSourceClassName.Text := SourceClassName;
edtDestClassName.Text := DestClassName;
LoadSettings;
end;
function TfmReplaceCompLog.ConfigurationKey: string;
begin
Result := FConfigData.RootConfigurationKey + PathDelim + Self.ClassName+'.Window';
end;
procedure TfmReplaceCompLog.LoadSettings;
var
Settings: TGExpertsSettings;
i: Integer;
begin
// Do not localize.
Settings := TGExpertsSettings.Create;
try
Settings.LoadForm(Self, ConfigurationKey + '\Window');
pnlBottom.Height := Settings.ReadInteger(ConfigurationKey + '\Window', 'ListSplitter',
pnlBottom.Height);
for i := 0 to lvLogItems.Columns.Count-1 do
lvLogItems.Columns[i].Width :=
Settings.ReadInteger(ConfigurationKey + '\Window', 'Col'+IntToStr(i)+'.Width',
lvLogItems.Columns[i].Width);
finally
FreeAndNil(Settings);
end;
EnsureFormVisible(Self);
end;
procedure TfmReplaceCompLog.SaveSettings;
var
Settings: TGExpertsSettings;
i: Integer;
begin
// Do not localize.
Settings := TGExpertsSettings.Create;
try
if not (WindowState in [wsMinimized, wsMaximized]) then
begin
Settings.SaveForm(Self, ConfigurationKey + '\Window');
Settings.WriteInteger(ConfigurationKey + '\Window', 'ListSplitter', pnlBottom.Height);
end;
for i := 0 to lvLogItems.Columns.Count-1 do
Settings.WriteInteger(ConfigurationKey + '\Window', 'Col'+IntToStr(i)+'.Width',
lvLogItems.Columns[i].Width);
finally
FreeAndNil(Settings);
end;
end;
procedure TfmReplaceCompLog.FormClose(Sender: TObject; var Action: TCloseAction);
begin
SaveSettings;
end;
procedure TfmReplaceCompLog.FormShow(Sender: TObject);
begin
LoadAll;
end;
procedure TfmReplaceCompLog.LoadAll;
begin
LoadItems;
if lvLogItems.Items.Count>0 then
lvLogItems.Selected := lvLogItems.Items[0];
end;
procedure TfmReplaceCompLog.LoadItems;
var
i: Integer;
begin
lvLogItems.Items.Clear;
UpdatePreviewPanel;
lvLogItems.Items.BeginUpdate;
try
for i := 0 to FLogEvents.Count-1 do
AddLogEvent(FLogEvents[i]);
finally
lvLogItems.Items.EndUpdate;
end;
end;
procedure TfmReplaceCompLog.AddLogEvent(AEvent: TCompRepEvent);
var
ListItem: TListItem;
begin
ListItem := lvLogItems.Items.Add;
ListItem.Caption := DateTimeToStr(AEvent.When);
if AEvent.IsError then
ListItem.SubItems.Add('!')
else
ListItem.SubItems.Add('');
ListItem.SubItems.Add(AEvent.ObjectText);
ListItem.SubItems.Add(AEvent.FlatText);
ListItem.Data := AEvent;
end;
procedure TfmReplaceCompLog.lvLogItemsClick(Sender: TObject);
begin
UpdatePreviewPanel;
end;
procedure TfmReplaceCompLog.UpdatePreviewPanel;
var
Event: TCompRepEvent;
begin
Event := GetFocusedEvent;
if Event = nil then
begin
lbxPreviewItems.Color := clBtnFace;
Exit;
end
else
begin
lbxPreviewItems.Color := clWindow;
LoadPreviewItems(Event);
end;
end;
procedure TfmReplaceCompLog.LoadPreviewItems(AEvent: TCompRepEvent);
resourcestring
SLayout =
'Event: %EventType%'+#10+
'Message:'+#10+
'%Text%'+#10+
'FileName: %FileName%'+#10+
'Object: %ObjectClass%, %ObjectSearchName%; Component: %ComponentName%'+#10+
'%ErrorPart%'+
'Context: %Context%'+#10+
'Child stack: %ChildStack%';
var
Items: TStringList;
EventText: string;
begin
lbxPreviewItems.Clear;
EventText := AEvent.FormatEventAsText(SLayout);
Items := TStringList.Create;
try
Items.Text := EventText;
lbxPreviewItems.Items.AddStrings(Items);
finally
FreeAndNil(Items);
end;
end;
function TfmReplaceCompLog.GetFocusedEvent: TCompRepEvent;
var
Item: TListItem;
begin
Item := GetFocusedItem;
if Assigned(Item) then
Result := TCompRepEvent(Item.Data)
else
Result := nil;
end;
function TfmReplaceCompLog.GetFocusedItem: TListItem;
begin
if lvLogItems.Items.IndexOf(FFocusedItem) >= 0 then
Result := FFocusedItem
else
Result := nil;
end;
procedure TfmReplaceCompLog.lvLogItemsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
begin
FFocusedItem := Item;
UpdatePreviewPanel;
end;
procedure TfmReplaceCompLog.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfmReplaceCompLog.btnCopyClick(Sender: TObject);
begin
SaveToClipboard;
end;
procedure TfmReplaceCompLog.GetSelectedItems(Items: TList);
var
i: Integer;
begin
Items.Clear;
for i := 0 to lvLogItems.Items.Count-1 do
if lvLogItems.Items[i].Selected then
Items.Add(lvLogItems.Items[i].Data);
end;
procedure TfmReplaceCompLog.SaveToClipboard;
var
List: TList;
StrList: TStringList;
begin
List := TList.Create;
try
GetSelectedItems(List);
StrList := TStringList.Create;
try
FormatEventsAsTabs(List, StrList);
ClipBoard.AsText := StrList.Text;
finally
FreeAndNil(StrList);
end;
finally
FreeAndNil(List);
end;
end;
procedure TfmReplaceCompLog.FormatEventsAsTabs(EventList: TList;
OutList: TStringList);
resourcestring
SLayout =
'%When%'#9'%EventType%'#9'%FlatText%'#9'%FileName%'#9+
'%ObjectClass%'#9'%ObjectSearchName%'#9'%ComponentName%'#9+
'%ErrorPart%'#9+
'%FlatContext%'#9+'%ChildStack%';
var
i: Integer;
Line: string;
begin
for i := 0 to EventList.Count-1 do
begin
Line := TCompRepEvent(EventList[i]).FormatEventAsText(SLayout);
OutList.Add(Line);
end;
end;
procedure TfmReplaceCompLog.SaveAsCSV(const AFileName: string);
var
List: TList;
StrList: TStringList;
begin
List := TList.Create;
try
GetSelectedItems(List);
StrList := TStringList.Create;
try
FormatEventsAsCSV(List, StrList);
StrList.SaveToFile(AFileName);
finally
FreeAndNil(StrList);
end;
finally
FreeAndNil(List);
end;
end;
procedure TfmReplaceCompLog.FormatEventsAsCSV(EventList: TList;
OutList: TStringList);
var
i: Integer;
Line: string;
Event: TCompRepEvent;
begin
for i := 0 to EventList.Count-1 do
begin
Line := '';
Event := TCompRepEvent(EventList[i]);
Line := CSVAddItem(Line, DateTimeToStr(Event.When));
Line := CSVAddItem(Line, Event.EventType);
Line := CSVAddItem(Line, Event.FlatText);
Line := CSVAddItem(Line, Event.FileName);
Line := CSVAddItem(Line, Event.ObjectClass);
Line := CSVAddItem(Line, Event.ObjectSearchName);
Line := CSVAddItem(Line, Event.ComponentName);
Line := CSVAddItem(Line, FlatLine(Event.FormatEventAsText('%ErrorPart%')));
Line := CSVAddItem(Line, FlatLine(Event.Context));
Line := CSVAddItem(Line, Event.StackText);
OutList.Add(Line);
end;
end;
procedure TfmReplaceCompLog.SaveAsXML(const AFileName: string);
var
List: TList;
begin
List := TList.Create;
try
GetSelectedItems(List);
FLogEvents.SaveAsXML(AFileName, List);
finally
FreeAndNil(List);
end;
end;
procedure TfmReplaceCompLog.btnSaveAsClick(Sender: TObject);
begin
if dlgGetExportFile.Execute then
begin
if Pos('XML', UpperCase(ExtractFileExt(dlgGetExportFile.FileName)))>0 then
SaveAsXML(dlgGetExportFile.FileName)
else
SaveAsCSV(dlgGetExportFile.FileName);
end;
end;
procedure TfmReplaceCompLog.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Key = Ord('A')) and (Shift = [ssCtrl]) then
begin
ListViewSelectAll(lvLogItems);
Key := 0;
end;
end;
end.
|
unit udmConfigSMTP;
interface
uses
Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS;
type
TdmConfigSMTP = class(TdmPadrao)
qryManutencaoCODIGO: TStringField;
qryManutencaoHOST: TStringField;
qryManutencaoPORTA: TIntegerField;
qryManutencaoUSUARIO: TStringField;
qryManutencaoSSL: TStringField;
qryManutencaoTLS: TStringField;
qryManutencaoENVIARPDF: TStringField;
qryManutencaoCONFIRMACAO: TStringField;
qryManutencaoAGUARDAR: TStringField;
qryManutencaoEMAIL: TStringField;
qryManutencaoSENHA: TStringField;
qryManutencaoNOME: TStringField;
qryLocalizacaoCODIGO: TStringField;
qryLocalizacaoHOST: TStringField;
qryLocalizacaoPORTA: TIntegerField;
qryLocalizacaoUSUARIO: TStringField;
qryLocalizacaoSSL: TStringField;
qryLocalizacaoTLS: TStringField;
qryLocalizacaoENVIARPDF: TStringField;
qryLocalizacaoCONFIRMACAO: TStringField;
qryLocalizacaoAGUARDAR: TStringField;
qryLocalizacaoEMAIL: TStringField;
qryLocalizacaoSENHA: TStringField;
qryLocalizacaoNOME: TStringField;
qryManutencaoOPERADOR: TStringField;
qryManutencaoDT_ALTERACAO: TDateTimeField;
qryLocalizacaoOPERADOR: TStringField;
qryLocalizacaoDT_ALTERACAO: TDateTimeField;
protected
procedure MontaSQLBusca(DataSet: TDataSet = nil); override;
procedure MontaSQLRefresh; override;
private
FCodigo: string;
function GetSQL_DEFAULT: string;
public
property Codigo: string read FCodigo write FCodigo;
function LocalizarEmails(DataSet: TDataSet = nil) : boolean;
end;
const
SQL_DEFAULT =
'SELECT ' +
' SMTP.CODIGO, ' +
' SMTP.HOST, ' +
' SMTP.PORTA, ' +
' SMTP.USUARIO, ' +
' SMTP.SSL, ' +
' SMTP.TLS, ' +
' SMTP.ENVIARPDF, ' +
' SMTP.CONFIRMACAO, ' +
' SMTP.AGUARDAR, ' +
' SMTP.EMAIL, ' +
' SMTP.SENHA, ' +
' SMTP.NOME, ' +
' SMTP.OPERADOR, ' +
' SMTP.DT_ALTERACAO ' +
'FROM CONFIGSMTP SMTP ';
var
dmConfigSMTP: TdmConfigSMTP;
implementation
{$R *.dfm}
{ TdmConfigSMTP }
function TdmConfigSMTP.LocalizarEmails(DataSet: TDataSet): boolean;
begin
if DataSet = nil then
DataSet := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add(' WHERE SMTP.CODIGO CONTAINING :CODIGO');
Params[0].AsString := FCodigo;
Open;
Result := not IsEmpty;
end;
end;
procedure TdmConfigSMTP.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE SMTP.CODIGO = :CODIGO');
Params[0].AsString := FCodigo;
end;
end;
procedure TdmConfigSMTP.MontaSQLRefresh;
begin
inherited;
with qryManutencao do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('ORDER BY SMTP.CODIGO');
end;
end;
function TdmConfigSMTP.GetSQL_DEFAULT: string;
begin
result := SQL_DEFAULT;
end;
end.
|
unit VGSceneAndWinControlPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\VGSceneAndWinControlPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "VGSceneAndWinControlPack" MUID: (551D4A0E03DD)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoVGScene) AND NOT Defined(NoScripts)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoVGScene) AND NOT Defined(NoScripts)}
uses
l3ImplUses
{$If NOT Defined(NoVCL)}
, Controls
{$IfEnd} // NOT Defined(NoVCL)
, tfwClassLike
, vgObject
, tfwScriptingInterfaces
, TypInfo
, vg_controls
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *551D4A0E03DDimpl_uses*
//#UC END# *551D4A0E03DDimpl_uses*
;
type
TkwPopControlFindVGControlByName = {final} class(TtfwClassLike)
{* Слово скрипта pop:Control:FindVGControlByName }
private
function FindVGControlByName(const aCtx: TtfwContext;
aControl: TWinControl;
const aName: AnsiString): TvgObject;
{* Реализация слова скрипта pop:Control:FindVGControlByName }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopControlFindVGControlByName
function TkwPopControlFindVGControlByName.FindVGControlByName(const aCtx: TtfwContext;
aControl: TWinControl;
const aName: AnsiString): TvgObject;
{* Реализация слова скрипта pop:Control:FindVGControlByName }
//#UC START# *551D4AA003A2_551D4AA003A2_47E124E90272_Word_var*
function DoFindVGObject(aVgControl: TvgObject; const aName: AnsiString): TvgObject;
var
I: Integer;
begin
if SameText(aVgControl.Name, aName) or
((aVgControl is TvgTextControl) and
SameText((aVgControl as TvgTextControl).Text, aName)) then
begin
Result := aVgControl;
Exit;
end else
Result := nil;
for I := 0 to aVgControl.ChildrenCount - 1 do
begin
Result := DoFindVGObject(aVgControl.Children[I], aName);
if Assigned(Result) then
Exit;
end;
end;
function DoFindWinControl(aControl: TWinControl; const aName: AnsiString): TvgObject;
var
I: Integer;
begin
for I := 0 to aControl.ControlCount - 1 do
if aControl.Controls[I] is TWinControl then
begin
Result := DoFindWinControl(aControl.Controls[I] as TWinControl, aName);
if Assigned(Result) then
Exit;
end;
for I := 0 to aControl.ComponentCount - 1 do
if aControl.Components[I] is TvgObject then
begin
Result := DoFindVGObject(aControl.Components[I] as TvgObject, aName);
if Assigned(Result) then
Exit;
end else
if aControl.Components[I] is TWinControl then
begin
Result := DoFindWinControl(aControl.Components[I] as TWinControl, aName);
if Assigned(Result) then
Exit;
end;
Result := nil;
end;
//#UC END# *551D4AA003A2_551D4AA003A2_47E124E90272_Word_var*
begin
//#UC START# *551D4AA003A2_551D4AA003A2_47E124E90272_Word_impl*
Result := DoFindWinControl(aControl, aName);
//#UC END# *551D4AA003A2_551D4AA003A2_47E124E90272_Word_impl*
end;//TkwPopControlFindVGControlByName.FindVGControlByName
class function TkwPopControlFindVGControlByName.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Control:FindVGControlByName';
end;//TkwPopControlFindVGControlByName.GetWordNameForRegister
function TkwPopControlFindVGControlByName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvgObject);
end;//TkwPopControlFindVGControlByName.GetResultTypeInfo
function TkwPopControlFindVGControlByName.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopControlFindVGControlByName.GetAllParamsCount
function TkwPopControlFindVGControlByName.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TWinControl), @tfw_tiString]);
end;//TkwPopControlFindVGControlByName.ParamsTypes
procedure TkwPopControlFindVGControlByName.DoDoIt(const aCtx: TtfwContext);
var l_aControl: TWinControl;
var l_aName: AnsiString;
begin
try
l_aControl := TWinControl(aCtx.rEngine.PopObjAs(TWinControl));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aControl: TWinControl : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aName := aCtx.rEngine.PopDelphiString;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aName: AnsiString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(FindVGControlByName(aCtx, l_aControl, l_aName));
end;//TkwPopControlFindVGControlByName.DoDoIt
initialization
TkwPopControlFindVGControlByName.RegisterInEngine;
{* Регистрация pop_Control_FindVGControlByName }
{$If NOT Defined(NoVCL)}
TtfwTypeRegistrator.RegisterType(TypeInfo(TWinControl));
{* Регистрация типа TWinControl }
{$IfEnd} // NOT Defined(NoVCL)
TtfwTypeRegistrator.RegisterType(TypeInfo(TvgObject));
{* Регистрация типа TvgObject }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа AnsiString }
{$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoScripts)
end.
|
unit DAO.CadastroGeral;
interface
uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema, Model.CadastroGeral;
type
TCadastroGeralDAO = class
private
FConexao: TConexao;
public
constructor Create;
function GetId(): Integer;
function Inserir(ACadastros: TCadastroGeral): Boolean;
function Alterar(ACadastros: TCadastroGeral): Boolean;
function Excluir(ACadastros: TCadastroGeral): Boolean;
function Pesquisar(aParam: array of variant): TFDQuery;
end;
const
TABLENAME = 'cadastro_geral';
implementation
{ TCadastroGeralDAO }
function TCadastroGeralDAO.Alterar(ACadastros: TCadastroGeral): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('update ' + TABLENAME + ' set ' +
'cod_tipo_cadastro = :cod_tipo_cadastro, cod_pessoa = :cod_pessoa, nom_nome_razao = :nom_nome_razao, ' +
'nom_fantasia = :nom_fantasia, num_cpf_cnpj = :num_cpf_cnpj, num_rg_ie = :num_rg_ie, ' +
'des_expedidor = :des_expedidor, dat_emissao_rg = :dat_emissao_rg, uf_expedidor_rg = :uf_expedidor_rg, ' +
'dat_nascimento = :dat_nascimento, nom_pai = :nom_pai, nom_mae = :nom_mae, ' +
'des_naturalidade = :des_naturalidade, uf_naturalidade = :uf_naturalidade, num_suframa = :num_suframa, ' +
'num_cnae = :num_cnae, num_crt = :num_crt, cod_seguranca_cnh = :cod_seguranca_cnh, ' +
'num_registro_cnh = :num_registro_cnh, dat_validade_cnh = :dat_validade_cnh, des_categoria = :des_categoria, ' +
'dat_emissao_cnh = :dat_emissao_cnh, dat_primeira_cnh = :dat_primeira_cnh, uf_cnh = :uf_cnh, ' +
'cod_sexo = :cod_sexo, des_estado_civil = :des_estado_civil, dat_cadastro = :dat_cadastro, ' +
'cod_usuario = :cod_usuario, des_imagem = :des_imagem, des_log = :des_log ' +
'where id_cadastro = :id_cadastro;',
[aCadastros.Tipo, aCadastros.Pessoa, aCadastros.Nome, aCadastros.Alias, aCadastros.CPFCNPJ,
aCadastros.RGIE, aCadastros.Expedidor, aCadastros.DataRG, aCadastros.UFRG, aCadastros.Nascimento,
aCadastros.NomePai, aCadastros.NomeMae, aCadastros.Naturalidade, aCadastros.UFNaturalidade, aCadastros.SUFRAMA,
aCadastros.CNAE, aCadastros.CRT, aCadastros.CodigoSegurancaCNH, aCadastros.RegistroCNH, aCadastros.ValidadeCNH,
aCadastros.CategoriaCNH, aCadastros.DataEmissaoCNH, aCadastros.PrimeiraCNH, aCadastros.UFCNH, aCadastros.Sexo,
aCadastros.EstadoCivil, aCadastros.DataCadastro, aCadastros.Usuario, aCadastros.Imagem, aCadastros.Log,
aCadastros.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
constructor TCadastroGeralDAO.Create;
begin
FConexao := Tconexao.Create;
end;
function TCadastroGeralDAO.Excluir(ACadastros: TCadastroGeral): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_cadastro = :id_cadastro', [ACadastros.ID]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TCadastroGeralDAO.GetId: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(id_cadastro),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroGeralDAO.Inserir(ACadastros: TCadastroGeral): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
ACadastros.ID := GetId();
FDQuery.ExecSQL('insert into ' + TABLENAME +
'(id_cadastro, cod_tipo_cadastro, cod_pessoa, nom_nome_razao, nom_fantasia, num_cpf_cnpj, num_rg_ie, ' +
'des_expedidor, dat_emissao_rg, uf_expedidor_rg, dat_nascimento, nom_pai, nom_mae, des_naturalidade, ' +
'uf_naturalidade, num_suframa, num_cnae, num_crt, cod_seguranca_cnh, num_registro_cnh, dat_validade_cnh, ' +
'des_categoria, dat_emissao_cnh, dat_primeira_cnh, uf_cnh, cod_sexo, des_estado_civil, dat_cadastro, '+
'cod_usuario, des_imagem, des_log) ' +
'values ' +
'(:id_cadastro, :cod_tipo_cadastro, :cod_pessoa, :nom_nome_razao, :nom_fantasia, :num_cpf_cnpj, :num_rg_ie, ' +
':des_expedidor, :dat_emissao_rg, :uf_expedidor_rg, :dat_nascimento, :nom_pai, :nom_mae, :des_naturalidade, ' +
':uf_naturalidade,:num_suframa,:num_cnae, :num_crt, :cod_seguranca_cnh, :num_registro_cnh, :dat_validade_cnh, ' +
':des_categoria, :dat_emissao_cnh, :dat_primeira_cnh, :uf_cnh, :cod_sexo, :des_estado_civil, :dat_cadastro, '+
':cod_usuario, :des_imagem, :des_log);',
[aCadastros.ID, aCadastros.Tipo, aCadastros.Pessoa, aCadastros.Nome, aCadastros.Alias, aCadastros.CPFCNPJ,
aCadastros.RGIE, aCadastros.Expedidor, aCadastros.DataRG, aCadastros.UFRG, aCadastros.Nascimento,
aCadastros.NomePai, aCadastros.NomeMae, aCadastros.Naturalidade, aCadastros.UFNaturalidade, aCadastros.SUFRAMA,
aCadastros.CNAE, aCadastros.CRT, aCadastros.CodigoSegurancaCNH, aCadastros.RegistroCNH, aCadastros.ValidadeCNH,
aCadastros.CategoriaCNH, aCadastros.DataEmissaoCNH, aCadastros.PrimeiraCNH, aCadastros.UFCNH, aCadastros.Sexo,
aCadastros.EstadoCivil, aCadastros.DataCadastro, aCadastros.Usuario, aCadastros.Imagem, aCadastros.Log]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TCadastroGeralDAO.Pesquisar(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_cadastro = :id_cadastro');
FDQuery.ParamByName('id_cadastro').AsInteger := aParam[1];
end;
if aParam[0] = 'RG' then
begin
FDQuery.SQL.Add('where um_rg_ie = :um_rg_ie');
FDQuery.ParamByName('um_rg_ie').AsString := aParam[1];
end;
if aParam[0] = 'CPFCNPJ' then
begin
FDQuery.SQL.Add('where num_cpf_cnpj = :num_cpf_cnpj');
FDQuery.ParamByName('num_cpf_cnpj').AsString := aParam[1];
end;
if aParam[0] = 'SEGCNH' then
begin
FDQuery.SQL.Add('where cod_seguranca_cnh = :cod_seguranca_cnh');
FDQuery.ParamByName('cod_seguranca_cnh').AsString := aParam[1];
end;
if aParam[0] = 'REGISTROCNH' then
begin
FDQuery.SQL.Add('where num_registro_cnh = :num_registro_cnh');
FDQuery.ParamByName('num_registro_cnh').AsString := aParam[1];
end;
if aParam[0] = 'NOME' then
begin
FDQuery.SQL.Add('where nom_nome_razao LIKE :nom_nome_razao');
FDQuery.ParamByName('nom_nome_razao').AsString := aParam[1];
end;
if aParam[0] = 'ALIAS' then
begin
FDQuery.SQL.Add('where nom_fantasia LIKE :nom_fantasia');
FDQuery.ParamByName('nom_fantasia').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
Result := FDQuery;
end;
end.
|
inherited dmProtEnt: TdmProtEnt
OldCreateOrder = True
inherited qryManutencao: TIBCQuery
KeyFields = 'ID_PROT'
KeyGenerator = 'GEN_PROTENT'
GeneratorMode = gmInsert
SQLInsert.Strings = (
'INSERT INTO STWPROTENT'
' (ID_PROT, CGC, EMISSAO, STATUS, DT_BAIXA, OPERADOR, DT_ALTERAC' +
'AO, DT_RECEBIMENTO, RECEBEDOR, OBS, OBS_ENVIO)'
'VALUES'
' (:ID_PROT, :CGC, :EMISSAO, :STATUS, :DT_BAIXA, :OPERADOR, :DT_' +
'ALTERACAO, :DT_RECEBIMENTO, :RECEBEDOR, :OBS, :OBS_ENVIO)')
SQLDelete.Strings = (
'DELETE FROM STWPROTENT'
'WHERE'
' ID_PROT = :Old_ID_PROT')
SQLUpdate.Strings = (
'UPDATE STWPROTENT'
'SET'
' ID_PROT = :ID_PROT, CGC = :CGC, EMISSAO = :EMISSAO, STATUS = :' +
'STATUS, DT_BAIXA = :DT_BAIXA, OPERADOR = :OPERADOR, DT_ALTERACAO' +
' = :DT_ALTERACAO, DT_RECEBIMENTO = :DT_RECEBIMENTO, RECEBEDOR = ' +
':RECEBEDOR, OBS = :OBS, OBS_ENVIO = :OBS_ENVIO'
'WHERE'
' ID_PROT = :Old_ID_PROT')
SQLRefresh.Strings = (
'SELECT ID_PROT, CGC, EMISSAO, STATUS, DT_BAIXA, OPERADOR, DT_ALT' +
'ERACAO, DT_RECEBIMENTO, RECEBEDOR, OBS, OBS_ENVIO FROM STWPROTEN' +
'T'
'WHERE'
' ID_PROT = :Old_ID_PROT')
SQLLock.Strings = (
'SELECT NULL FROM STWPROTENT'
'WHERE'
'ID_PROT = :Old_ID_PROT'
'FOR UPDATE WITH LOCK')
SQLRecCount.Strings = (
'SELECT COUNT(*) FROM ('
'SELECT 1 AS C FROM STWPROTENT'
''
') q')
SQL.Strings = (
'SELECT'
' PROT.ID_PROT,'
' PROT.CGC,'
' PROT.EMISSAO,'
' PROT.STATUS,'
' PROT.DT_BAIXA,'
' PROT.OPERADOR,'
' PROT.DT_ALTERACAO,'
' PROT.DT_RECEBIMENTO,'
' PROT.RECEBEDOR,'
' PROT.OBS,'
' PROT.OBS_ENVIO,'
' CLI.NOME NM_CLIENTE'
'FROM STWPROTENT PROT'
'LEFT JOIN STWOPETCLI CLI '
'ON PROT.CGC = CLI.CGC')
IndexFieldNames = 'ID_PROT'
object qryManutencaoID_PROT: TIntegerField
FieldName = 'ID_PROT'
Required = True
end
object qryManutencaoCGC: TStringField
FieldName = 'CGC'
Size = 18
end
object qryManutencaoEMISSAO: TDateTimeField
FieldName = 'EMISSAO'
end
object qryManutencaoSTATUS: TStringField
FieldName = 'STATUS'
Size = 2
end
object qryManutencaoDT_BAIXA: TDateTimeField
FieldName = 'DT_BAIXA'
end
object qryManutencaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryManutencaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryManutencaoDT_RECEBIMENTO: TDateTimeField
FieldName = 'DT_RECEBIMENTO'
end
object qryManutencaoRECEBEDOR: TStringField
FieldName = 'RECEBEDOR'
Size = 60
end
object qryManutencaoOBS: TStringField
FieldName = 'OBS'
Size = 120
end
object qryManutencaoNM_CLIENTE: TStringField
FieldName = 'NM_CLIENTE'
ReadOnly = True
Size = 40
end
object qryManutencaoOBS_ENVIO: TStringField
FieldName = 'OBS_ENVIO'
Size = 240
end
end
inherited qryLocalizacao: TIBCQuery
SQLInsert.Strings = (
'INSERT INTO STWPROTENT'
' (ID_PROT, CGC, EMISSAO, STATUS, DT_BAIXA, OPERADOR, DT_ALTERAC' +
'AO, DT_RECEBIMENTO, RECEBEDOR, OBS, OBS_ENVIO)'
'VALUES'
' (:ID_PROT, :CGC, :EMISSAO, :STATUS, :DT_BAIXA, :OPERADOR, :DT_' +
'ALTERACAO, :DT_RECEBIMENTO, :RECEBEDOR, :OBS, :OBS_ENVIO)')
SQLDelete.Strings = (
'DELETE FROM STWPROTENT'
'WHERE'
' ID_PROT = :Old_ID_PROT')
SQLUpdate.Strings = (
'UPDATE STWPROTENT'
'SET'
' ID_PROT = :ID_PROT, CGC = :CGC, EMISSAO = :EMISSAO, STATUS = :' +
'STATUS, DT_BAIXA = :DT_BAIXA, OPERADOR = :OPERADOR, DT_ALTERACAO' +
' = :DT_ALTERACAO, DT_RECEBIMENTO = :DT_RECEBIMENTO, RECEBEDOR = ' +
':RECEBEDOR, OBS = :OBS, OBS_ENVIO = :OBS_ENVIO'
'WHERE'
' ID_PROT = :Old_ID_PROT')
SQLRefresh.Strings = (
'SELECT ID_PROT, CGC, EMISSAO, STATUS, DT_BAIXA, OPERADOR, DT_ALT' +
'ERACAO, DT_RECEBIMENTO, RECEBEDOR, OBS, OBS_ENVIO FROM STWPROTEN' +
'T'
'WHERE'
' ID_PROT = :ID_PROT')
SQLLock.Strings = (
'SELECT NULL FROM STWPROTENT'
'WHERE'
'ID_PROT = :Old_ID_PROT'
'FOR UPDATE WITH LOCK')
SQLRecCount.Strings = (
'SELECT COUNT(*) FROM ('
'SELECT 1 AS C FROM STWPROTENT'
''
') q')
SQL.Strings = (
'SELECT'
' PROT.ID_PROT,'
' PROT.CGC,'
' PROT.EMISSAO,'
' PROT.STATUS,'
' PROT.DT_BAIXA,'
' PROT.OPERADOR,'
' PROT.DT_ALTERACAO,'
' PROT.DT_RECEBIMENTO,'
' PROT.RECEBEDOR,'
' PROT.OBS,'
' PROT.OBS_ENVIO,'
' CLI.NOME NM_CLIENTE'
'FROM STWPROTENT PROT'
'LEFT JOIN STWOPETCLI CLI '
'ON PROT.CGC = CLI.CGC')
object qryLocalizacaoID_PROT: TIntegerField
FieldName = 'ID_PROT'
Required = True
end
object qryLocalizacaoCGC: TStringField
FieldName = 'CGC'
Size = 18
end
object qryLocalizacaoEMISSAO: TDateTimeField
FieldName = 'EMISSAO'
end
object qryLocalizacaoSTATUS: TStringField
FieldName = 'STATUS'
Size = 2
end
object qryLocalizacaoDT_BAIXA: TDateTimeField
FieldName = 'DT_BAIXA'
end
object qryLocalizacaoOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryLocalizacaoDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryLocalizacaoDT_RECEBIMENTO: TDateTimeField
FieldName = 'DT_RECEBIMENTO'
end
object qryLocalizacaoRECEBEDOR: TStringField
FieldName = 'RECEBEDOR'
Size = 60
end
object qryLocalizacaoOBS: TStringField
FieldName = 'OBS'
Size = 120
end
object qryLocalizacaoNM_CLIENTE: TStringField
FieldName = 'NM_CLIENTE'
ReadOnly = True
Size = 40
end
object qryLocalizacaoOBS_ENVIO: TStringField
FieldName = 'OBS_ENVIO'
Size = 240
end
end
object qryProtEnt: TIBCQuery
SQLInsert.Strings = (
'INSERT INTO STWPROTENT'
' (ID_PROT, CGC, EMISSAO, STATUS, DT_BAIXA, OPERADOR, DT_ALTERAC' +
'AO, DT_RECEBIMENTO, RECEBEDOR, OBS, OBS_ENVIO)'
'VALUES'
' (:ID_PROT, :CGC, :EMISSAO, :STATUS, :DT_BAIXA, :OPERADOR, :DT_' +
'ALTERACAO, :DT_RECEBIMENTO, :RECEBEDOR, :OBS, :OBS_ENVIO)')
SQLDelete.Strings = (
'DELETE FROM STWPROTENT'
'WHERE'
' ID_PROT = :Old_ID_PROT')
SQLUpdate.Strings = (
'UPDATE STWPROTENT'
'SET'
' ID_PROT = :ID_PROT, CGC = :CGC, EMISSAO = :EMISSAO, STATUS = :' +
'STATUS, DT_BAIXA = :DT_BAIXA, OPERADOR = :OPERADOR, DT_ALTERACAO' +
' = :DT_ALTERACAO, DT_RECEBIMENTO = :DT_RECEBIMENTO, RECEBEDOR = ' +
':RECEBEDOR, OBS = :OBS, OBS_ENVIO = :OBS_ENVIO'
'WHERE'
' ID_PROT = :Old_ID_PROT')
SQLRefresh.Strings = (
'SELECT ID_PROT, CGC, EMISSAO, STATUS, DT_BAIXA, OPERADOR, DT_ALT' +
'ERACAO, DT_RECEBIMENTO, RECEBEDOR, OBS, OBS_ENVIO FROM STWPROTEN' +
'T'
'WHERE'
' ID_PROT = :ID_PROT')
SQLLock.Strings = (
'SELECT NULL FROM STWPROTENT'
'WHERE'
'ID_PROT = :Old_ID_PROT'
'FOR UPDATE WITH LOCK')
SQLRecCount.Strings = (
'SELECT COUNT(*) FROM ('
'SELECT 1 AS C FROM STWPROTENT'
''
') q')
SQL.Strings = (
'SELECT'
' PROT.ID_PROT,'
' PROT.CGC,'
' PROT.EMISSAO,'
' PROT.STATUS,'
' PROT.DT_BAIXA,'
' PROT.OPERADOR,'
' PROT.DT_ALTERACAO,'
' PROT.DT_RECEBIMENTO,'
' PROT.RECEBEDOR,'
' PROT.OBS,'
' PROT.OBS_ENVIO,'
' CLI.NOME NM_CLIENTE'
'FROM STWPROTENT PROT'
'LEFT JOIN STWOPETCLI CLI '
'ON PROT.CGC = CLI.CGC')
AutoCommit = False
Left = 64
Top = 168
object qryProtEntID_PROT: TIntegerField
FieldName = 'ID_PROT'
end
object qryProtEntCGC: TStringField
FieldName = 'CGC'
Size = 18
end
object qryProtEntEMISSAO: TDateTimeField
FieldName = 'EMISSAO'
end
object qryProtEntSTATUS: TStringField
FieldName = 'STATUS'
Size = 2
end
object qryProtEntDT_BAIXA: TDateTimeField
FieldName = 'DT_BAIXA'
end
object qryProtEntOPERADOR: TStringField
FieldName = 'OPERADOR'
end
object qryProtEntDT_ALTERACAO: TDateTimeField
FieldName = 'DT_ALTERACAO'
end
object qryProtEntDT_RECEBIMENTO: TDateTimeField
FieldName = 'DT_RECEBIMENTO'
end
object qryProtEntRECEBEDOR: TStringField
FieldName = 'RECEBEDOR'
Size = 60
end
object qryProtEntOBS: TStringField
FieldName = 'OBS'
Size = 120
end
object qryProtEntNM_CLIENTE: TStringField
FieldName = 'NM_CLIENTE'
ProviderFlags = []
Size = 40
end
object qryProtEntOBS_ENVIO: TStringField
FieldName = 'OBS_ENVIO'
Size = 240
end
end
end
|
{*******************************************************************************
作者: dmzn@163.com 2011-11-21
描述: 产品销售
*******************************************************************************}
unit UFrameProductSale;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrameBase, USkinManager, UGridPainter, UGridExPainter,
cxButtons, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, ExtCtrls, UImageButton, cxTextEdit, StdCtrls, Grids;
type
PMemberInfo = ^TMemberInfo;
TMemberInfo = record
FID: string; //编号
FCard: string; //卡号
FName: string; //姓名
FMoney: Double; //消费金额
FZheKou: Double; //折扣比例
end;
PProductItem = ^TProductItem;
TProductItem = record
FProductID: string; //产品号
FBrandName: string; //品牌
FStyleName: string; //款式
FColorName: string; //颜色
FSizeName: string; //大小
FNumSale: Integer; //销售件数
FNumStore: Integer; //库存件数
FPriceSale: Double; //销售价
FPriceOld: Double; //原价
FPriceMember: Double; //会员价
FPriceIn: Double; //进货价
FSelected: Boolean; //选中
end;
TfFrameProductSale = class(TfFrameBase)
GridList: TDrawGridEx;
PanelT: TPanel;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
EditName: TcxTextEdit;
EditID: TcxTextEdit;
EditMoney: TcxTextEdit;
EditZhekou: TcxTextEdit;
LabelHint: TLabel;
PanelB: TPanel;
BtnJZ: TImageButton;
BtnCancel: TImageButton;
BtnGetPrd: TImageButton;
BtnMember: TImageButton;
BtnCode: TImageButton;
BtnTH: TImageButton;
procedure BtnExitClick(Sender: TObject);
procedure PanelBResize(Sender: TObject);
procedure BtnGetPrdClick(Sender: TObject);
procedure BtnMemberClick(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure BtnCodeClick(Sender: TObject);
procedure BtnJZClick(Sender: TObject);
procedure BtnTHClick(Sender: TObject);
private
{ Private declarations }
FSkinItem: TSkinItem;
//皮肤对象
FPainter: TGridPainter;
//绘图对象
FMember: TMemberInfo;
//会员信息
FProducts: TList;
//销售清单
procedure AddProduct(const nProduct: TProductItem);
//销售商品
procedure LoadProductToList;
//显示清单
procedure MemberInfo(const nInit: Boolean);
//会员信息
procedure OnBtnClick(Sender: TObject);
//点击按钮
public
{ Public declarations }
procedure OnCreateFrame; override;
procedure OnDestroyFrame; override;
class function FrameID: integer; override;
end;
procedure ClearProductList(const nList: TList; const nFree: Boolean);
//清空清单
implementation
{$R *.dfm}
uses
IniFiles, ULibFun, USkinFormBase, UDataModule, DB, UMgrControl, USysConst,
USysDB, USysFun, UFormProductGet, UFormProductConfirm, UFormMemberGet,
UFormProductCode, UFormProductJZ, UFormProductTH, UFrameSummary;
class function TfFrameProductSale.FrameID: integer;
begin
Result := cFI_FrameProductSale;
end;
procedure TfFrameProductSale.OnCreateFrame;
var nIni: TIniFile;
nIdx,nH,nInt: Integer;
begin
Name := MakeFrameName(FrameID);
FProducts := TList.Create;
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;
MemberInfo(True);
//xxxx
nIni := TIniFile.Create(gPath + sFormConfig);
try
LoadDrawGridConfig(Name, GridList, nIni);
AdjustLabelCaption(LabelHint, GridList);
Width := GetGridHeaderWidth(GridList);
finally
nIni.Free;
end;
FSkinItem := gSkinManager.GetSkin('FormDialog');
if not Assigned(FSkinItem) then
raise Exception.Create('读取皮肤信息失败');
//xxxxx
nH := 0;
for nIdx:=PanelB.ControlCount-1 downto 0 do
if PanelB.Controls[nIdx] is TImageButton then
if TSkinFormBase.LoadImageButton(PanelB.Controls[nIdx] as TImageButton, FSkinItem) then
begin
nInt := (PanelB.Controls[nIdx] as TImageButton).PicNormal.Height;
if nInt > nH then nH := nInt;
end;
if nH > 0 then
PanelB.Height := nH + 32;
//xxxxx
for nIdx:=PanelB.ControlCount-1 downto 0 do
if PanelB.Controls[nIdx] is TImageButton then
begin
nH := (PanelB.Controls[nIdx] as TImageButton).Height;
(PanelB.Controls[nIdx] as TImageButton).Top := Trunc((PanelB.Height - nH) / 2);
end;
end;
procedure TfFrameProductSale.OnDestroyFrame;
var nIni: TIniFile;
begin
nIni := TIniFile.Create(gPath + sFormConfig);
try
SaveDrawGridConfig(Name, GridList, nIni);
finally
nIni.Free;
end;
FPainter.Free;
ClearProductList(FProducts, True);
end;
procedure TfFrameProductSale.BtnExitClick(Sender: TObject);
begin
Close;
end;
//Desc: 按钮位置
procedure TfFrameProductSale.PanelBResize(Sender: TObject);
const cInt = 12;
begin
BtnCancel.Left := BtnJZ.Left + BtnJZ.Width + cInt;
BtnTH.Left := PanelB.Width - 85 - BtnTH.Width;
BtnCode.Left := BtnTH.Left - cInt - BtnCode.Width;
BtnMember.Left := BtnCode.Left - cInt - BtnMember.Width;
BtnGetPrd.Left := BtnMember.Left - cInt - BtnGetPrd.Width;
end;
//------------------------------------------------------------------------------
//Desc: 清理产品清单
procedure ClearProductList(const nList: TList; const nFree: Boolean);
var nIdx: Integer;
begin
for nIdx:=nList.Count - 1 downto 0 do
begin
Dispose(PProductItem(nList[nIdx]));
nList.Delete(nIdx);
end;
if nFree then
nList.Free;
//xxxxx
end;
//Desc: 显示会员信息
procedure TfFrameProductSale.MemberInfo(const nInit: Boolean);
var nIdx: Integer;
begin
if nInit then
with FMember do
begin
FID := '';
FName := '';
FMoney := 0;
FZheKou := 10;
end;
with FMember do
begin
if FID = '' then EditID.Text := '无' else EditID.Text := FID;
if FName = '' then EditName.Text := '无' else EditName.Text := FName;
if FMoney <= 0 then
EditMoney.Text := '无'
else EditMoney.Text := Format('¥%.2f元', [FMoney]);
if FZheKou >= 10 then
EditZhekou.Text := '无'
else EditZhekou.Text := Format('%f折', [FZheKou]);
for nIdx:=0 to FProducts.Count - 1 do
with PProductItem(FProducts[nIdx])^ do
begin
if FZheKou < 10 then
FPriceMember := FPriceSale * FZheKou / 10
else FPriceMember := FPriceSale;
end;
end;
end;
//Desc: 载入产品列表到界面
procedure TfFrameProductSale.LoadProductToList;
var nStr: string;
nVal: Double;
nBtn: TcxButton;
nIdx,nInt,nNum: Integer;
nData: TGridDataArray;
begin
nInt := 1;
FPainter.ClearData;
for nIdx:=0 to FProducts.Count - 1 do
with PProductItem(FProducts[nIdx])^ do
begin
SetLength(nData, 9);
for nNum:=Low(nData) to High(nData) do
begin
nData[nNum].FText := '';
nData[nNum].FCtrls := nil;
nData[nNum].FAlign := taCenter;
end;
nData[0].FText := IntToStr(nInt);
Inc(nInt);
nStr := Format('%s_%s_%s', [FStyleName, FColorName, FSizeName]);
nData[1].FText := nStr;
nData[2].FText := Format('%.2f', [FPriceOld]);
nData[3].FText := Format('%.2f', [FPriceSale]);
if FMember.FID = '' then
nData[4].FText := '0.00'
else nData[4].FText := Format('%.2f', [FPriceMember]);
nData[5].FText := IntToStr(FNumSale);
nVal := Float2Float(FNumSale * FPriceMember, 100);
nData[6].FText := Format('%.2f', [nVal]);
with nData[7] do
begin
FCtrls := TList.Create;
nBtn := TcxButton.Create(Self);
FCtrls.Add(nBtn);
with nBtn do
begin
Caption := '调整';
Width := 35;
Height := 18;
OnClick := OnBtnClick;
Tag := FPainter.DataCount;
end;
nBtn := TcxButton.Create(Self);
FCtrls.Add(nBtn);
with nBtn do
begin
Caption := '作废';
Width := 35;
Height := 18;
OnClick := OnBtnClick;
Tag := FPainter.DataCount;
end;
end;
nData[8].FText := IntToStr(nIdx);
FPainter.AddData(nData);
end;
//----------------------------------------------------------------------------
if FProducts.Count < 1 then Exit;
SetLength(nData, 7);
for nIdx:=Low(nData) to High(nData) do
begin
nData[nIdx].FText := '';
nData[nIdx].FCtrls := nil;
nData[nIdx].FAlign := taCenter;
end;
nNum := 0;
nVal := 0;
for nIdx:=FProducts.Count - 1 downto 0 do
with PProductItem(FProducts[nIdx])^ do
begin
nNum := nNum + FNumSale;
if FMember.FID = '' then
nVal := nVal + Float2Float(FNumSale * FPriceSale, 100)
else nVal := nVal + Float2Float(FNumSale * FPriceMember, 100);
end;
nData[0].FText := '合计:';
nData[5].FText := Format('%d', [nNum]);
nData[6].FText := Format('¥%.2f', [nVal]);
FPainter.AddData(nData);
end;
//Desc: 添加产品项
procedure TfFrameProductSale.AddProduct(const nProduct: TProductItem);
var nItem: PProductItem;
begin
New(nItem);
FProducts.Add(nItem);
with nItem^ do
begin
nItem^ := nProduct;
if FloatRelation(FPriceSale, FPriceOld, rtGreater) or (FPriceOld <= 0) then
FPriceOld := FPriceSale;
//涨价等
if FMember.FZheKou < 10 then
FPriceMember := FPriceSale * FMember.FZheKou / 10
else FPriceMember := FPriceSale;
end;
LoadProductToList;
end;
//Desc: 选择商品
procedure TfFrameProductSale.BtnGetPrdClick(Sender: TObject);
var nItem: TProductItem;
begin
if ShowGetProductForm(@nItem) and ShowSaleProductConfirm(@nItem) then
AddProduct(nItem);
//xxxxx
end;
//Desc: 按钮
procedure TfFrameProductSale.OnBtnClick(Sender: TObject);
var nTag: Integer;
begin
nTag := TComponent(Sender).Tag;
if Sender = FPainter.Data[nTag][7].FCtrls[0] then
begin
nTag := StrToInt(FPainter.Data[nTag][8].FText);
if ShowSaleProductConfirm(FProducts[nTag]) then
LoadProductToList;
//xxxxx
end else //调整
if Sender = FPainter.Data[nTag][7].FCtrls[1] then
begin
nTag := StrToInt(FPainter.Data[nTag][8].FText);
PProductItem(FProducts[nTag]).FNumSale := 0;
LoadProductToList;
end; //作废
end;
//Desc: 选择会员
procedure TfFrameProductSale.BtnMemberClick(Sender: TObject);
begin
if ShowGetMember(@FMember) then
begin
MemberInfo(False);
LoadProductToList;
end;
end;
//Desc: 清除本次销售
procedure TfFrameProductSale.BtnCancelClick(Sender: TObject);
var nStr: string;
begin
if FPainter.DataCount > 0 then
begin
nStr := '确定要取消本次销售吗?';
if not QueryDlg(nStr, sAsk) then Exit;
end;
MemberInfo(True);
ClearProductList(FProducts, False);
LoadProductToList;
end;
//Desc: 输入条码
procedure TfFrameProductSale.BtnCodeClick(Sender: TObject);
var nItem: TProductItem;
begin
while True do
begin
if ShowGetProductByCode(@nItem) then
begin
if nItem.FPriceSale > 0 then
AddProduct(nItem)
else ShowMsg('零售价无效', sHint);
end else Break;
end;
end;
//------------------------------------------------------------------------------
//Desc: 结帐
procedure TfFrameProductSale.BtnJZClick(Sender: TObject);
var nIdx,nNum: Integer;
begin
nNum := 0;
for nIdx:=FProducts.Count - 1 downto 0 do
nNum := nNum + PProductItem(FProducts[nIdx]).FNumSale;
//xxxxx
if nNum < 1 then
begin
ShowMsg('没有需要结帐的商品', sHint); Exit;
end;
if ShowProductJZ(FProducts, @FMember) then
begin
SetTendayLoadFlag(False);
MemberInfo(True);
ClearProductList(FProducts, False);
LoadProductToList;
end;
end;
//Desc: 退货
procedure TfFrameProductSale.BtnTHClick(Sender: TObject);
var nIdx,nNum: Integer;
begin
nNum := 0;
for nIdx:=FProducts.Count - 1 downto 0 do
nNum := nNum + PProductItem(FProducts[nIdx]).FNumSale;
//xxxxx
if nNum < 1 then
begin
ShowMsg('没有需要退货的商品', sHint); Exit;
end;
if ShowProductTH(FProducts, @FMember) then
begin
SetTendayLoadFlag(False);
MemberInfo(True);
ClearProductList(FProducts, False);
LoadProductToList;
end;
end;
initialization
gControlManager.RegCtrl(TfFrameProductSale, TfFrameProductSale.FrameID);
end.
|
unit uCRUDFaturamento;
interface
uses
FireDAC.Comp.Client, System.SysUtils;
type
TCRUDFaturamento = class(TObject)
private
FConexao : TFDConnection;
FQuery : TFDQuery;
FFat_Valor: Double;
FFat_Ano: String;
procedure SetFat_Ano(const Value: String);
procedure SetFat_Valor(const Value: Double);
public
constructor Create(poConexao : TFDConnection);
destructor Destroy; override;
procedure pcdGravaFaturamento;
procedure pcdExcluiFaturamento;
function fncRetornaValorFaturadoANO(pdAno:String): Double;
published
property Fat_Ano : String read FFat_Ano write SetFat_Ano;
property Fat_Valor : Double read FFat_Valor write SetFat_Valor;
end;
implementation
{ TCRUDFaturamento }
constructor TCRUDFaturamento.Create(poConexao: TFDConnection);
begin
FConexao := poConexao;
FQuery := TFDQuery.Create(nil);
FQuery.Connection := FConexao;
FQuery.Close;
end;
destructor TCRUDFaturamento.Destroy;
begin
if Assigned(FQuery) then
FreeAndNil(FQuery);
inherited;
end;
function TCRUDFaturamento.fncRetornaValorFaturadoANO(pdAno: String): Double;
begin
Result := 0;
FQuery.Close;
FQuery.SQL.Clear;
FQuery.SQL.Add('SELECT FAT_VALOR FROM FATURAMENTO WHERE FAT_ANO = :FAT_ANO');
FQuery.ParamByName('FAT_ANO').AsString := pdAno;
FQuery.Open;
Result := FQuery.FieldByName('FAT_VALOR').AsFloat;
end;
procedure TCRUDFaturamento.pcdExcluiFaturamento;
begin
FQuery.Close;
FQuery.SQL.Clear;
FQuery.SQL.Add('DELETE FROM FATURAMENTO WHERE FAT_ANO = :FAT_ANO');
FQuery.ParamByName('FAT_ANO').AsString := FFat_Ano;
FQuery.ExecSQL;
end;
procedure TCRUDFaturamento.pcdGravaFaturamento;
begin
FQuery.Close;
FQuery.SQL.Clear;
FQuery.SQL.Add('INSERT INTO FATURAMENTO (FAT_ANO, FAT_VALOR) VALUES (:FAT_ANO, :FAT_VALOR)');
FQuery.ParamByName('FAT_ANO').AsString := FFat_Ano;
FQuery.ParamByName('FAT_VALOR').AsFloat := FFat_Valor;
FQuery.ExecSQL;
end;
procedure TCRUDFaturamento.SetFat_Ano(const Value: String);
begin
FFat_Ano := Value;
end;
procedure TCRUDFaturamento.SetFat_Valor(const Value: Double);
begin
FFat_Valor := Value;
end;
end.
|
unit MegaWarehouse;
interface
uses
Warehouses, Kernel, Surfaces, WorkCenterBlock, BackupInterfaces, CacheAgent,
Protocol;
type
TMetaMegaStorage =
class(TMetaWarehouse)
public
constructor Create(anId : string;
aCapacities : array of TFluidValue;
theOverPrice : TPercent;
aBlockClass : CBlock);
end;
TMegaStorage =
class(TWarehouse)
private
fWareInputs : array[0..31] of TInputData;
fWareOutputs : array[0..31] of TOutputData;
published
procedure RDOSelectWare(index : integer; value : wordbool);
protected
function GetVisualClassId : TVisualClassId; override;
end;
procedure RegisterBackup;
implementation
uses
ClassStorage, StdFluids, Collection, ModelServerCache;
// TMetaMegaStorage
constructor TMetaMegaStorage.Create(anId : string;
aCapacities : array of TFluidValue;
theOverPrice : TPercent;
aBlockClass : CBlock);
var
Sample : TMegaStorage;
i : integer;
count : integer;
Fluid : TMetaFluid;
Fluids : TCollection;
begin
inherited Create(anId, aCapacities, aBlockClass);
Sample := nil;
count := TheClassStorage.ClassCount[tidClassFamily_Fluids];
Fluids := TCollection.Create(count, rkUse);
// Collect Fluids
for i := 0 to pred(count) do
begin
Fluid := TMetaFluid(TheClassStorage.ClassByIdx[tidClassFamily_Fluids, i]);
if Fluid.StorageVol > 0
then Fluids.Insert(Fluid);
end;
// Register Inputs
for i := 0 to pred(Fluids.Count) do
begin
Fluid := TMetaFluid(Fluids[i]);
NewMetaInput(
Fluid.Id,
Fluid.Id,
Fluid.StorageVol,
sizeof(Sample.fWareInputs[i]),
Sample.Offset(Sample.fWareInputs[i]));
end;
// Register Outputs
for i := 0 to pred(Fluids.Count) do
begin
Fluid := TMetaFluid(Fluids[i]);
NewMetaOutput(
Fluid.Id,
Fluid.Id,
Fluid.StorageVol,
sizeof(Sample.fWareOutputs[i]),
Sample.Offset(Sample.fWareOutputs[i]));
end;
// Register Wares
for i := 0 to pred(Fluids.Count) do
begin
Fluid := TMetaFluid(Fluids[i]);
RegisterWare(Fluid.Id, round(100/Fluids.Count), 0, theOverPrice, Fluid.StorageVol);
end;
end;
// TMegaStorage
procedure TMegaStorage.RDOSelectWare(index : integer; value : wordbool);
var
Input : TPullInput;
begin
if Facility.CheckOpAuthenticity
then
begin
Input := TPullInput(Inputs[TMetaWarehouse(MetaBlock).Wares[index].MetaInput.Index]);
Input.Selected := value;
ModelServerCache.InvalidateCache(Facility, false);
Facility.Town.MapRefresh.RefeshFacility(Facility, fchStructure);
end;
end;
function TMegaStorage.GetVisualClassId : TVisualClassId;
begin
result := 0;
end;
// Register backup
procedure RegisterBackup;
begin
BackupInterfaces.RegisterClass(TMegaStorage);
end;
end.
|
unit Generator;
{$MODE objfpc}{$J-}{$H+}
interface
function CreateText(): string;
implementation
function CreateText(): string;
begin
result := 'Hello World';
end;
begin
end.
|
program Seminar2 (input, output);
{ zweite Programmvariante für das Seminarproblem }
const
MAXTEILNEHMER = 12;
TAGE = 31;
MONATE = 12;
MINJAHR = 1900;
MAXJAHR = 2010;
type
tTag = 1..TAGE;
tMonat = 1..MONATE;
tJahr = MINJAHR..MAXJAHR;
tNatZahlPlus = 1..maxint;
tNatZahl = 0..maxint;
tStatus = (aktiv, passiv);
tIndex = 1..MAXTEILNEHMER;
tString = string [20];
tSeminarStudent =
record
Name : tString;
Geburtstag : { Verschachtelte record-Zuweisung, daher : statt = }
record
Tag : tTag;
Monat : tMonat;
Jahr : tJahr;
end; { Geburstag }
MatrikelNr : tNatZahlPlus;
Status : tStatus;
end; { tSeminarStudent }
tTeilnehmerfeld = array [tIndex] of tSeminarStudent;
var
TeilnehmerFeld : tTeilnehmerfeld;
AnzStud : tNatZahl;
i : tIndex;
Status : char; { Zeichen zum Einlesen des Studentenstatus. Muss vom Typ char sein, um eingelesen werden zu koennen. 'a' entspricht aktiv, 'p' entspricht passiv }
begin
write ('Wie viele Studenten nahmen am Seminar teil? ');
readln (AnzStud);
if AnzStud > MAXTEILNEHMER then
begin
writeln ('Bitte hoestens ', MAXTEILNEHMER, ' Eingaben!');
AnzStud := MAXTEILNEHMER;
end;
writeln ('Geben Sie Name, Matr.Nr. und Aktivitaet der ', AnzStud:3, ' Teilnehmer ein:'); { :3 bei AnzStud ist die Feldbreite }
{ Eingabe der Daten }
for i := 1 to AnzStud do
begin
write ('Name: ');
readln (TeilnehmerFeld[i].Name);
write ('Matr.Nr.: ');
readln (TeilnehmerFeld[i].MatrikelNr);
write ('a - aktiv, p - passiv: ');
readln (Status);
if Status = 'a' then
TeilnehmerFeld[i].Status := aktiv
else
TeilnehmerFeld[i].Status := passiv
end; { Eingabe }
{ Scheine ausgeben }
writeln;
for i := 1 to AnzStud do
begin
if TeilnehmerFeld[i].Status = aktiv then
begin
writeln ('Der Student ', TeilnehmerFeld[i].Name);
write ('mit der Matrikel-Nr. ');
writeln (TeilnehmerFeld[i].MatrikelNr);
writeln ('hat mit Erfolg am Seminar teilgenommen.');
writeln;
end
end;
writeln ('Liste aller aktiven Seminar-Teilnehmer');
writeln ('--------------------------------------');
for i := 1 to AnzStud do
if TeilnehmerFeld[i].Status = aktiv then
writeln (TeilnehmerFeld[i].Name);
writeln;
writeln ('Liste aller Zuhoerer im Seminar');
writeln ('-------------------------------');
for i := 1 to AnzStud do
if TeilnehmerFeld[i].Status = passiv then
writeln (TeilnehmerFeld[i].Name);
writeln;
end. { Seminar2 }
|
unit dcListBox;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, dbctrls, datacontroller,db;
type
TdcListBox = class(TListBox)
private
{ Private declarations }
fdcLink : TdcLink;
FMaxLength: integer;
fTranData: String;
OldReadonly : boolean;
FReadOnly: boolean;
procedure DoEnter;
procedure DoExit;
procedure DoOnChange;
procedure SetMaxLength(const Value: integer);
procedure SetReadOnly(const Value: boolean);
protected
{ Protected declarations }
// std data awareness
function GetDataSource:TDataSource;
procedure SetDataSource(value:Tdatasource);
function GetDataField:string;
procedure SetDataField(value:string);
// data controller
function GetDataController:TDataController;
procedure SetDataController(value:TDataController);
procedure ReadData(sender:TObject);
procedure WriteData(sender:TObject);
procedure ClearData(sender:TObject);
public
{ Public declarations }
constructor Create(AOwner:Tcomponent);override;
destructor Destroy;override;
property TranData : String read fTranData;
published
{ Published declarations }
property DataController : TDataController read GetDataController write setDataController;
property DataField : String read GetDataField write SetDataField;
property DataSource : TDataSource read getDataSource write SetDatasource;
property MaxLength : integer read FMaxLength write SetMaxLength;
property ReadOnly:boolean read FReadOnly write SetReadOnly;
end;
procedure Register;
implementation
constructor TdcListBox.Create(AOwner:Tcomponent);
begin
inherited;
fdclink := tdclink.create(self);
fdclink.OnReadData := ReadData;
fdclink.OnWriteData := WriteData;
fdclink.OnClearData := ClearData;
end;
destructor TdcListBox.Destroy;
begin
fdclink.Free;
inherited;
end;
procedure TdcListBox.SetDataController(value:TDataController);
begin
fdcLink.datacontroller := value;
end;
function TdcListBox.GetDataController:TDataController;
begin
result := fdcLink.DataController;
end;
procedure TdcListBox.SetDataSource(value:TDataSource);
begin
end;
function TdcListBox.GetDataField:string;
begin
result := fdclink.FieldName;
end;
function TdcListBox.GetDataSource:TDataSource;
begin
result := fdclink.DataSource;
end;
procedure TdcListBox.SetDataField(value:string);
begin
fdclink.FieldName := value;
end;
procedure TdcListBox.ReadData;
begin
if assigned(fdclink.Field) then
begin
maxlength := fdclink.Field.Size;
text := trim(fdclink.Field.DisplayText);
end;
end;
procedure TdcListBox.WriteData;
var olddata : string;
begin
if assigned(fdclink.Field) then
begin
olddata := fdclink.Field.AsString;
if trim(text) <> trim(olddata) then
begin
if trim(text) = '' then fTranData := '~' else fTranData := trim(text);
end;
if fdclink.DataSource.DataSet.State in [dsedit,dsinsert] then fdclink.field.asstring := text;
end;
end;
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TdcListBox]);
end;
procedure TdcListBox.ClearData(sender: TObject);
begin
if fdclink.Field <> nil then
begin
maxlength := fdclink.Field.Size;
text := trim(fdclink.Field.DefaultExpression);
end;
end;
procedure TdcListBox.DoOnChange;
begin
fdclink.BeginEdit;
inherited;
end;
procedure TdcListBox.DoEnter;
begin
OldReadOnly := ReadOnly;
if assigned(DataController) then
begin
ReadOnly := DataController.ReadOnly;
end;
inherited;
end;
procedure TdcListBox.DoExit;
begin
ReadOnly := OldReadOnly;
inherited;
end;
procedure TdcListBox.SetMaxLength(const Value: integer);
begin
FMaxLength := Value;
end;
procedure TdcListBox.SetReadOnly(const Value: boolean);
begin
FReadOnly := Value;
end;
end.
|
unit K612077455;
{* [Requestlink:612077455] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K612077455.pas"
// Стереотип: "TestCase"
// Элемент модели: "K612077455" MUID: (565457BD01C9)
// Имя типа: "TK612077455"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, RTFtoEVDWriterTest
;
type
TK612077455 = class(TRTFtoEVDWriterTest)
{* [Requestlink:612077455] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK612077455
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *565457BD01C9impl_uses*
//#UC END# *565457BD01C9impl_uses*
;
function TK612077455.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.12';
end;//TK612077455.GetFolder
function TK612077455.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '565457BD01C9';
end;//TK612077455.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK612077455.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
// @davidberneda
// 2017
unit TeePEG_Rules;
{$DEFINE TRACE}
{
"Parsing Expression Grammars" (PEG)
Implementation for: Mr. Bryan Ford baford@mit.edu
http://bford.info/pub/lang/peg.pdf
}
interface
uses
Classes;
type
TRule=class;
TStackItem=record
Position : Integer;
Rules : Array of TRule;
end;
TParser=class
private
FPosition : Integer;
protected
procedure Match(const ARule:TRule; const ALength:Integer);
function Push:Integer;
procedure Pop;
public
Stack : Array of TStackItem;
Text : String;
function EndOfFile: Boolean; {$IFDEF INLINE}inline;{$ENDIF}
property Position:Integer read FPosition write FPosition;
end;
TRule=class
protected
function Match(const AParser:TParser):Boolean; virtual; abstract;
public
function AsString:String; virtual; abstract;
end;
TOperator=class(TRule)
public
Rule : TRule;
Constructor Create(const ARule:TRule);
function AsString:String; override;
end;
TPredicate=class(TOperator)
end;
{ &e }
TAndPredicate=class(TPredicate)
protected
function Match(const AParser:TParser):Boolean; override;
public
function AsString:String; override;
end;
{ !e }
TNotPredicate=class(TPredicate)
protected
function Match(const AParser:TParser):Boolean; override;
public
function AsString:String; override;
end;
TCharacterRule=class(TRule)
protected
InSet : Boolean;
end;
{ 'x' }
TCharacter=class(TCharacterRule)
protected
function Match(const AParser:TParser):Boolean; override;
public
Character : Char;
Constructor Create(const AChar:Char);
function AsString:String; override;
end;
{ n-m }
TCharacterRange=class(TCharacterRule)
protected
function Match(const AParser:TParser):Boolean; override;
public
Start,
Finish : Char;
Constructor Create(const AStart,AFinish:Char);
function AsString:String; override;
end;
{ 'abc' }
TString=class(TRule)
protected
function Match(const AParser:TParser):Boolean; override;
public
Text : String;
Constructor Create(const AText:String);
function AsString:String; override;
end;
{ . }
TAnyCharacter=class(TRule)
protected
function Match(const AParser:TParser):Boolean; override;
public
function AsString:String; override;
end;
TRuleArray=Array of TRule;
TChoice=class(TRule)
private
function ToString(const Separator:String):String;
protected
procedure Add(const AItems: array of TRule);
public
Items : TRuleArray;
Constructor Create(const AItems:Array of TRule);
end;
{ e1 e2 }
TSequence=class(TChoice)
protected
function Match(const AParser:TParser):Boolean; override;
public
function AsString:String; override;
end;
{ e1 / e2 }
TPrioritized=class(TChoice)
protected
function Match(const AParser:TParser):Boolean; override;
public
function AsString:String; override;
end;
{ [abcA-ZQRS_] }
TCharacterSet=class(TPrioritized)
protected
constructor InnerCreate;
public
Constructor Create(const AItems: array of TCharacterRule);
function AsString:String; override;
end;
{ e* }
TZeroOrMore=class(TOperator)
protected
function Match(const AParser:TParser):Boolean; override;
public
function AsString:String; override;
end;
{ e+ }
TOneOrMore=class(TOperator)
protected
function Match(const AParser:TParser):Boolean; override;
public
function AsString:String; override;
end;
{ e? }
TOptional=class(TOperator) // Zero or One
protected
function Match(const AParser:TParser):Boolean; override;
public
function AsString:String; override;
end;
TNamedRule=class(TOperator)
protected
function Match(const AParser:TParser):Boolean; override;
public
Name : String;
Constructor Create(const AName:String; const ARule:TRule);
function AsString:String; override;
end;
var
SingleQuote,
DoubleQuote : TCharacter;
{$IFDEF TRACE}
PEG_Log : TStrings;
{$ENDIF}
implementation
uses
SysUtils;
procedure Trace(const ARule:TRule; const AStart:Integer; const AParser: TParser);
begin
{$IFDEF TRACE}
if PEG_Log<>nil then
PEG_Log.Add(IntToStr(AParser.Position)+' { '+
Copy(AParser.Text,AStart,AParser.Position-AStart)+' } '+
ARule.ClassName+': '+ARule.AsString);
{$ENDIF}
end;
{ TParser }
function TParser.EndOfFile: Boolean;
begin
result:=FPosition>Length(Text);
end;
{ TSequenceRule }
function TSequence.AsString: String;
begin
result:=ToString(' ');
end;
function TSequence.Match(const AParser:TParser): Boolean;
var t : Integer;
tmp : Integer;
begin
tmp:=AParser.Push;
for t:=Low(Items) to High(Items) do
if not Items[t].Match(AParser) then
begin
result:=False;
AParser.Pop;
Exit;
end;
result:=True;
Trace(Self,tmp,AParser);
end;
procedure TParser.Match(const ARule: TRule; const ALength: Integer);
var L,tmp : Integer;
begin
L:=High(Stack);
tmp:=Length(Stack[L].Rules);
SetLength(Stack[L].Rules,tmp+1);
Stack[L].Rules[tmp]:=ARule;
Inc(FPosition,ALength);
end;
procedure TParser.Pop;
var H : Integer;
begin
H:=High(Stack);
if H<0 then
raise Exception.Create('Error: Parser Stack empty');
FPosition:=Stack[H].Position;
SetLength(Stack,H);
end;
function TParser.Push: Integer;
var L : Integer;
begin
L:=Length(Stack);
SetLength(Stack,L+1);
Stack[L].Position:=Position;
result:=Position;
end;
{ TOperator }
Constructor TOperator.Create(const ARule: TRule);
begin
inherited Create;
Rule:=ARule;
end;
function TOperator.AsString: String;
begin
if (Rule is TChoice) and (Length(TChoice(Rule).Items)>1) then
result:='('+Rule.AsString+')'
else
result:=Rule.AsString;
end;
{ TCharacter }
Constructor TCharacter.Create(const AChar: Char);
begin
inherited Create;
Character:=AChar;
end;
function ToString(const C:Char):String;
begin
if C=SingleQuote.Character then
result:=C
else
if C='[' then
result:='\['
else
if C=']' then
result:='\]'
else
if (C<' ') or (C>'z') then
case C of
#9: result:='\t';
#10: result:='\n';
#13: result:='\r';
else
result:='#'+IntToStr(Ord(C))
end
else
if C='\' then
result:='\\'
else
result:=C;
end;
function TCharacter.AsString: String;
begin
if Character=SingleQuote.Character then
if InSet then
result:=SingleQuote.Character
else
result:='['+SingleQuote.Character+']'
else
if InSet then
result:=ToString(Character)
else
result:=SingleQuote.Character+ToString(Character)+SingleQuote.Character;
end;
function TCharacter.Match(const AParser: TParser): Boolean;
begin
result:=AParser.Text[AParser.Position]=Character;
if result then
begin
AParser.Match(Self,1);
Trace(Self,AParser.Position-1,AParser);
end;
end;
{ TString }
Constructor TString.Create(const AText: String);
begin
inherited Create;
Text:=AText;
end;
function TString.AsString: String;
var t : Integer;
begin
result:='’';
for t:=1 to Length(Text) do
result:=result+ToString(Text[t]);
result:=result+'’';
end;
function TString.Match(const AParser: TParser): Boolean;
var t : Integer;
begin
// if AParser.Remain<Length(Text) then
// result:=False
//else
begin
for t:=1 to Length(Text) do
if AParser.Text[AParser.FPosition+t-1]<>Text[t] then
begin
result:=False;
Exit;
end;
result:=True;
AParser.Match(Self,Length(Text));
Trace(Self,AParser.Position-Length(Text),AParser);
end;
end;
{ TChoice }
constructor TChoice.Create(const AItems: array of TRule);
begin
inherited Create;
Add(AItems);
end;
procedure TChoice.Add(const AItems: array of TRule);
var t : Integer;
begin
SetLength(Items,Length(AItems));
for t:=Low(AItems) to High(AItems) do
Items[t-Low(AItems)]:=AItems[t];
end;
function TChoice.ToString(const Separator: String): String;
var L,
t : Integer;
begin
result:='';
L:=Length(Items);
for t:=Low(Items) to High(Items) do
begin
if t>Low(Items) then
result:=result+Separator;
if (Separator=' ') and (Items[t] is TChoice) and (L>1) then
result:=result+'('+Items[t].AsString+')'
else
result:=result+Items[t].AsString;
end;
end;
{ TCharacterRange }
constructor TCharacterRange.Create(const AStart, AFinish: Char);
begin
inherited Create;
Start:=AStart;
Finish:=AFinish;
end;
function TCharacterRange.AsString: String;
begin
if InSet then
result:=''
else
result:='[';
result:=result+Start+'-'+Finish;
if not InSet then
result:=result+']';
end;
function TCharacterRange.Match(const AParser: TParser): Boolean;
var tmp : Char;
begin
tmp:=AParser.Text[AParser.Position];
result:=(tmp>=Start) and (tmp<=Finish);
if result then
begin
AParser.Match(Self,1);
Trace(Self,AParser.Position-1,AParser);
end;
end;
{ TAnyCharacter }
function TAnyCharacter.AsString: String;
begin
result:='.';
end;
function TAnyCharacter.Match(const AParser: TParser): Boolean;
begin
result:=not AParser.EndOfFile;
if result then
begin
AParser.Match(Self,1);
Trace(Self,AParser.Position-1,AParser);
end;
end;
{ TZeroOrMore }
function TZeroOrMore.AsString: String;
begin
result:=inherited AsString+'*';
end;
function TZeroOrMore.Match(const AParser: TParser): Boolean;
var tmp : Integer;
begin
result:=True;
tmp:=AParser.Position;
repeat
until not Rule.Match(AParser);
Trace(Self,tmp,AParser);
end;
{ TOneOrMore }
function TOneOrMore.AsString: String;
begin
result:=inherited AsString+'+';
end;
function TOneOrMore.Match(const AParser: TParser): Boolean;
var tmp : Integer;
begin
tmp:=AParser.Position;
result:=Rule.Match(AParser);
if result then
begin
repeat
until not Rule.Match(AParser);
Trace(Self,tmp,AParser);
end;
end;
{ TPrioritized }
function TPrioritized.AsString: String;
begin
result:=ToString(' / ');
end;
function TPrioritized.Match(const AParser: TParser): Boolean;
var tmp : Integer;
t : Integer;
begin
for t:=Low(Items) to High(Items) do
begin
tmp:=AParser.Push;
if Items[t].Match(AParser) then
begin
result:=True;
Trace(Self,tmp,AParser);
Exit;
end
else
AParser.Pop;
end;
result:=False;
end;
{ TNotPredicate }
function TNotPredicate.AsString: String;
begin
result:='!'+inherited AsString;
end;
function TNotPredicate.Match(const AParser: TParser): Boolean;
var tmp : Integer;
begin
tmp:=AParser.Push;
result:=not Rule.Match(AParser);
if result then
Trace(Self,tmp,AParser)
else
AParser.Pop;
end;
{ TAndPredicate }
function TAndPredicate.AsString: String;
begin
result:='&'+inherited AsString;
end;
function TAndPredicate.Match(const AParser: TParser): Boolean;
var tmp : Integer;
begin
tmp:=AParser.Push;
result:=Rule.Match(AParser);
Trace(Self,tmp,AParser);
AParser.Pop;
end;
{ TNamedRule }
function TNamedRule.AsString: String;
begin
result:=Name;
end;
constructor TNamedRule.Create(const AName: String; const ARule: TRule);
begin
inherited Create(ARule);
Name:=AName;
end;
function TNamedRule.Match(const AParser: TParser): Boolean;
var tmp : Integer;
begin
tmp:=AParser.Position;
result:=Rule.Match(AParser);
if result then
Trace(Self,tmp,AParser);
end;
{ TOptional }
function TOptional.AsString: String;
begin
result:=inherited AsString+'?';
end;
function TOptional.Match(const AParser: TParser): Boolean;
var tmp : Integer;
begin
tmp:=AParser.Position;
result:=True;
if Rule.Match(AParser) then
Trace(Self,tmp,AParser);
end;
{ TCharacterSet }
function TCharacterSet.AsString: String;
begin
result:='['+ToString('')+']';
end;
constructor TCharacterSet.InnerCreate;
begin
end;
constructor TCharacterSet.Create(const AItems: array of TCharacterRule);
var t : Integer;
begin
InnerCreate;
SetLength(Items,Length(AItems));
for t:=Low(AItems) to High(AItems) do
begin
AItems[t].InSet:=True;
Items[t-Low(AItems)]:=AItems[t];
end;
end;
initialization
// There are different single quotes:
// ’ = #146
// ´ = #180
// ' = #39
// ` = #96
SingleQuote:=TCharacter.Create(#146);
DoubleQuote:=TCharacter.Create('"');
finalization
DoubleQuote.Free;
SingleQuote.Free;
end.
|
unit phys_units_lib;
//вводим здесь единицы измерения, причем различаем базовые и производные,
//масштабируемые (почти все) и с нулевой точкой (температуры),
//а также нелинейные (децибелы разные и пр)
//хотелось бы сохранить связь с ConvUtils, чтобы по-новой столько не вводить
//разных единиц.
//по сути, проводим связи между TConvFamily, т.е регистрируем каждую из них с
//"формулой" типа M*L/T^2 (это сила, напр. кг*м/с^2), а потом по формуле можем найти
//нужное, на лету создать новое семейство (если не было таких) и конкр. юнит.
interface
uses classes,VariantWrapper,ConvUtils,sysUtils,linear_eq,simple_parser_lib,streaming_class_lib;
type
TUnitsWithExponent = class;
TUnitsWithExponentMergeProc = function (value: TUnitsWithExponent; i,j: Integer) : Real of object;
TShowName = function (const value: TConvType): string;
TExponents = array of Real;
TUnitsWithExponent = class(TPersistent) //хватило бы и record'а и указателей и GetMem/FreeMem,
private
UnitTypes: TConvTypeArray;
Exponents: TExponents;
fCount: Integer;
procedure Merge(value: TUnitsWithExponent; proc: TUnitsWithExponentMergeProc);
function MergeMul(value: TUnitsWithExponent; i,j: Integer): Real;
function MergeDiv(value: TUnitsWithExponent; i,j: Integer): Real;
function ShowSomething(proc: TShowName): string;
protected
procedure AddBaseUnit(ConvType: TConvType; Exponent: Real);
function AddArbitraryUnit(ConvType: TConvType; Exponent: Real): Real;
public
procedure Clear;
procedure Assign(source: TPersistent); override;
function TakeFromString(formula: string; out modifier: string): Real;
procedure DoPower(Exponent: Real);
function SameFamily(value: TUnitsWithExponent): Boolean;
procedure Multiply(value: TUnitsWithExponent);
procedure Divide(right: TUnitsWithExponent);
function AsString: string;
function ShowFormula: string;
function isAffine: Boolean;
end;
TprefixEntry=class
public
multiplier: Real;
name: string;
modifier: string;
end;
TOldUnitPrefixes = class(TComponent)
private
flang: string;
fMaxLen: Integer;
fPrefixes: TStringList; //чтобы по имени приставки найти множитель
fPreferredPrefixes: TList;
//а как насчет тупо степени десятки изобразить?
procedure ReadList(Reader: TReader);
protected
procedure DefineProperties(Filer: TFiler); override;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
function FindUnitWithPrefix(str: string; out CType: TConvType): boolean;
function PrefixDescrToMultiplier(term: string; var modifier: string; out CType: TConvType): Real;
procedure Assimilate(source: TOldUnitPrefixes);
published
property lang: string read flang write flang;
end;
TAbstractSavedConvFamily=class(TComponent)
private
flang: string;
fStrBaseUnit: string; //вообще, TConvType умеет записываться символьно,
//однако на момент считывания BaseUnit мы еще можем не знать такого юнита
fBaseConvType: TConvType;
fConvFamily: TConvFamily;
fErrorList: TStrings;
procedure ReadUnits(Reader: TReader);
protected
procedure DefineProperties(Filer: TFiler); override;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
published
property Lang: string write flang;
property BaseUnit: string write fStrBaseUnit;
end;
TBaseConvFamily=class(TAbstractSavedConvFamily)
private
fLetter: string;
fAffine: boolean;
published
property letter: string write fLetter;
property IsAffine: Boolean read fAffine write fAffine;
end;
TDerivedConvFamily=class(TAbstractSavedConvFamily)
private
fStrFormula: string;
fFormula: TUnitsWithExponent;
public
constructor Create(owner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
published
property formula: string write fStrFormula;
end;
//пока что здесь - конкретный тип, для представления размерности данных
TVariantWithUnit=class(TAbstractWrapperData)
private
ConvType: TConvType;
function IsAffine(out i: Integer): Boolean; //удобнее всего
public
instance: Variant; //та переменная, которую мы оборачиваем
ExplicitConversion: boolean; //флаг, что величину "насильно" привели к данному виду
constructor Create(text: string); overload;
constructor CreateFromVariant(source: Variant; aConvType: TConvType);
procedure Assign(source: TPersistent); overload; override;
procedure Assign(str: string); reintroduce; overload;
procedure Negate; override; //взять обратный знак
procedure DoAdd(value: TAbstractWrapperData); override;
procedure DoMultiply(Right: TAbstractWrapperData); override;
procedure DoInverse;
procedure DoDivide(Right: TAbstractWrapperData); override;
procedure DoPower(pow: Real);
function AsString: string; override;
procedure Conversion(DestConv: TConvType);
published
property isExplicitlyConverted: boolean read ExplicitConversion;
end;
TVariantWithUnitType = class (TAbstractWrapperVariantType)
public
procedure Cast(var Dest: TVarData; const Source: TVarData); override;
procedure CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType); override;
function CompareOp(const Left, Right: TVarData; const Operator: Integer): Boolean; override;
end;
TVariantWithUnitVarData = record
VType: TVarType;
Reserved1, Reserved2, Reserved3: Word;
Data: TVariantWithUnit;
Reserved4: LongInt;
end;
TaffineUnitEntry = record
ConvType: TConvType;
BaseConvType: TConvType;
multiplier: Real;
end;
TFundamentalPhysConstants = class(TComponent)
private
fNames: array of string;
fDescriptions: array of string;
fValues: array of Variant;
fenabled: array of Boolean;
fcount: Integer;
fsolver: IAbstractSLEQ;
fActuallyUsedCount: Integer;
fActualIndex: array of Integer;
fLang: string;
function getName(i: Integer): string;
function getDescription(i: Integer): string;
function getEnabled(i: Integer): boolean;
procedure setEnabled(i: Integer; avalue: boolean);
function Recalculate: Boolean;
procedure ReadData(reader: TReader);
protected
procedure DefineProperties(filer: TFiler); override;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure Add(aname,adescr: string; aValue: Variant; aEnabled: boolean=false);
function GetVar(i: Integer): Variant;
function GetActualIndex(i: Integer): Integer;
property Count: Integer read fCount;
property Names[i: Integer]: string read getName;
property Descriptions[i: Integer]: string read getDescription;
property Enabled[i: Integer]: Boolean read getEnabled write setEnabled;
property Solver: IAbstractSLEQ read fsolver;
property ActuallyUsedCount: Integer read fActuallyUsedCount;
published
property Lang: string read fLang write fLang;
end;
TConvTypeAffine = class(TConvTypeInfo)
private
fOffset,fFactor: Real;
public
constructor Create(const AConvFamily: TConvFamily; const ADescription: string; offset,factor: Real); //reintroduce;
function ToCommon(const AValue: Double): Double; override;
function FromCommon(const AValue: Double): Double; override;
end;
TOldPhysUnitParser = class(TSimpleParser)
private
public
function getPhysUnit: TConvType;
function getVariantNum: Variant;
end;
EOldPhysUnitError = class (Exception);
PUnitMultipliersArray = ^TUnitMultipliersArray;
TUnitMultipliersArray = array [0..255] of Real;
TLogConversionDetailsProc = procedure (line: string); //цвет сами придумаем
//этот вариант для регистрации вручную, formula - что-то вроде 'M*L/T^2'
function RegisterDerivedConversionFamily(formula: TUnitsWithExponent): TDerivedConvFamily;
function ConvTypeToBaseFamilyLetter(const value: TConvType): string;
//тип VariantWithUnit
function VariantWithUnit: TVarType;
//конструкторы и пр.
procedure VarWithUnitCreateInto(var ADest: Variant; const AData: TVariantWithUnit);
function VarWithUnitCreate(text: string): Variant;
function VarWithUnitCreateFromVariant(source: Variant; ConvType: TConvType): Variant;
function IsVarWithUnit(V: Variant): Boolean;
function IsDimensionless(V: Variant): boolean;
function TryVarWithUnitCreate(text: string; out Res: Variant): boolean;
function VarWithUnitConvert(source: Variant; DestConvType: TConvType; explicit: boolean=false): Variant; overload;
function VarWithUnitConvert(source: Variant; UnitName: string): Variant; overload;
function VarWithUnitGetNumberIn(source: Variant; UnitName: TConvType): Variant;
function VarWithUnitGetNumber(source: Variant): Variant;
function StrToConvType(str: string): TConvType;
function StrToConvFamily(str: string): TConvFamily;
function VarWithUnitPower(source: Variant; pow: Real): Variant;
function VarWithUnitSqrt(source: Variant): Variant;
function VarWithUnitAbs(source: Variant): Variant;
function VarWithUnitArg(source: Variant): Variant;
function VarWithUnitRe(source: Variant): Variant;
function VarWithUnitIm(source: Variant): Variant;
function IsVarWithUnitSameFamily(v1,v2: Variant): Boolean;
function VarWithUnitGetConvType(source: Variant): TConvType;
function VarWithUnitGetConvFamily(source: Variant): TConvFamily;
function VarWithUnitFindGoodPrefix(source: Variant): Variant;
function NameToFamily(const Ident: string; var Int: Longint): Boolean;
function FamilyToName(Int: LongInt; var Ident: string): Boolean;
function NameToConv(const Ident: string; var Int: LongInt): Boolean;
function ConvToName(Int: LongInt; var Ident: string): Boolean;
procedure InitializePhysUnitLib;
procedure FinalizePhysUnitLib;
var UnityPhysConstants: TFundamentalPhysConstants;
LogConversionDetailsProc: TLogConversionDetailsProc;
LogConversionErrorProc: TLogConversionDetailsProc;
LogConversionWarningProc: TLogConversionDetailsProc;
cbDimensionless,cbAngle: TConvFamily;
duUnity,auDMS,auRadian: TConvType;
PhysUnitLanguage: string;
UnitPrefixes: TOldUnitPrefixes;
implementation
uses StdConvs,math,VarCmplx,strUtils,variants,
set_english_locale_if_not_sure,expression_lib,Contnrs;
var BaseFamilyEntries: TObjectList;
DerivedFamilyEntries: TObjectList;
VarWithUnitType: TVariantWithUnitType;
AffineUnits: array of TAffineUnitEntry;
default_dir: string;
ListOfUnitsWithAllowedPrefixes: TBucketList;
all_the_possible_units: TStringList;
resourcestring
ConvFamilyNeitherBaseNorDerived = 'Размерность %s не является ни базовой, ни производной';
function IndexOfBaseFamily(Family: TConvFamily): Integer;
var i: Integer;
begin
for i:=0 to BaseFamilyEntries.Count-1 do
if (BaseFamilyEntries[i] as TBaseConvFamily).fConvFamily=Family then begin
Result:=i;
Exit;
end;
Result:=-1;
end;
function ConvTypeToBaseFamilyLetter(const value: TConvType): string;
var i: Integer;
begin
i:=IndexOfBaseFamily(ConvTypeToFamily(value));
if i>=0 then
Result:=TBaseConvFamily(BaseFamilyEntries[i]).fLetter
else
Raise EOldPhysUnitError.CreateFMT('ConvTypeToBaseFamilyLetter: family %s not found among base families',[ConvFamilyToDescription(ConvTypeToFamily(value))]);
//этот код вообще не используется пока
end;
function RegisterDerivedConversionFamily(formula: TUnitsWithExponent): TDerivedConvFamily;
begin
Result:=TDerivedConvFamily.Create(nil);
Result.fConvFamily:=RegisterConversionFamily(formula.ShowFormula);
Result.fBaseConvType:=RegisterConversionType(Result.fConvFamily,formula.AsString,1);
Result.fFormula.Assign(formula);
DerivedFamilyEntries.Add(Result);
end;
function IndexOfDerivedFamily(Family: TConvFamily): Integer;
var i: Integer;
begin
for i:=0 to DerivedFamilyEntries.Count-1 do
if TDerivedConvFamily(DerivedFamilyEntries[i]).fConvFamily=Family then begin
Result:=i;
Exit;
end;
Result:=-1;
end;
function FindPhysUnit(ConvType: TConvType): TUnitsWithExponent;
var i: Integer;
ConvFamily: TConvFamily;
begin
Result:=TUnitsWithExponent.Create;
ConvFamily:=ConvTypeToFamily(ConvType);
for i:=0 to BaseFamilyEntries.Count-1 do
if TBaseConvFamily(BaseFamilyEntries[i]).fConvFamily=ConvFamily then begin
Result.AddBaseUnit(TBaseConvFamily(BaseFamilyEntries[i]).fBaseConvType,1);
Exit;
end;
//среди базовых не нашли, поищем в производных
for i:=0 to DerivedFamilyEntries.Count-1 do
if TDerivedConvFamily(DerivedFamilyEntries[i]).fConvFamily=ConvFamily then begin
Result.Assign(TDerivedConvFamily(DerivedFamilyEntries[i]).fformula);
Exit;
end;
Raise EOldPhysUnitError.CreateFMT(ConvFamilyNeitherBaseNorDerived,[ConvTypeToDescription(ConvType)]);
//так будет, если одну из станд. разм. не объявить в текст. файле.
end;
function FormulaToConvType(formula: TUnitsWithExponent): TConvType;
var i: Integer;
begin
if (formula.fCount=1) and (formula.Exponents[0]=1) then begin //базовая величина
for i:=0 to BaseFamilyEntries.Count-1 do
if TBaseConvFamily(BaseFamilyEntries[i]).fConvFamily=ConvTypeToFamily(formula.UnitTypes[0]) then begin
Result:=TBaseConvFamily(BaseFamilyEntries[i]).fBaseConvType;
Exit;
end
end
else
for i:=0 to DerivedFamilyEntries.Count-1 do
if TDerivedConvFamily(DerivedFamilyEntries[i]).fformula.SameFamily(formula) then begin
Result:=TDerivedConvFamily(DerivedFamilyEntries[i]).fBaseConvType;
Exit;
end;
//если не найдено подх. семейства - мы создадим такое семейство и такой юнит!
Result:=RegisterDerivedConversionFamily(formula).fBaseConvType;
end;
function StrToConvType(str: string): TConvType;
var f: TUnitsWithExponent;
multiplier: Real;
BaseConvType: TConvType;
modifier: string;
begin
f:=TUnitsWithExponent.Create;
try
multiplier:=f.TakeFromString(str,modifier);
BaseConvType:=FormulaToConvType(f); //эта штука может создать на лету новую единицу
if not DescriptionToConvType(str+modifier,Result) then begin
multiplier:=multiplier*ConvertFrom(BaseConvType,1);
Result:=RegisterConversionType(ConvTypeToFamily(BaseConvType),str+modifier,multiplier);
end;
finally
f.Free;
end;
end;
function StrToConvFamily(str: string): TConvFamily;
begin
if not DescriptionToConvFamily(str,Result) then
Raise EOldPhysUnitError.CreateFmt('Couldn''t find conversion family %s',[str]);
end;
(*
TUnitsWithExponent
*)
procedure TUnitsWithExponent.Clear;
begin
fCount:=0;
SetLength(UnitTypes,0);
SetLength(Exponents,0);
end;
procedure TUnitsWithExponent.AddBaseUnit(ConvType: TConvType; Exponent: Real);
begin
inc(fCount);
if Length(UnitTypes)<fCount then begin
SetLength(UnitTypes,Length(UnitTypes)*2+1);
SetLength(Exponents,Length(Exponents)*2+1);
end;
UnitTypes[fCount-1]:=ConvType;
Exponents[fCount-1]:=Exponent;
end;
function TUnitsWithExponent.AddArbitraryUnit(ConvType: TConvType; Exponent: Real): Real;
var f: TConvFamily;
i: Integer;
u: TUnitsWithExponent;
begin
f:=ConvTypeToFamily(ConvType);
i:=IndexOfBaseFamily(f);
if i>=0 then begin
u:=TUnitsWithExponent.Create;
try
u.AddBaseUnit(TBaseConvFamily(BaseFamilyEntries[i]).fBaseConvType,Exponent);
Multiply(u);
if ConvType=TBaseConvFamily(BaseFamilyEntries[i]).fBaseConvType then
Result:=1
else
Result:=Power(Convert(1,ConvType,TBaseConvFamily(BaseFamilyEntries[i]).fBaseConvType),Exponent);
finally
u.Free;
end;
end
else begin
//скребем по derived, находим и помножаем на его unit
i:=IndexOfDerivedFamily(f);
if i=-1 then Raise EOldPhysUnitError.CreateFmt(ConvFamilyNeitherBaseNorDerived,[ConvFamilyToDescription(f)]);
u:=TUnitsWithExponent.Create;
try
u.Assign(TDerivedConvFamily(DerivedFamilyEntries[i]).fformula);
u.DoPower(Exponent); //возвести в нужную степень (может даже нулевую)
Multiply(u); //в этих формулах не должны появляться новые множители
if ConvType=TDerivedConvFamily(DerivedFamilyEntries[i]).fBaseConvType then
Result:=1
else
Result:=Power(Convert(1,ConvType,TDerivedConvFamily(DerivedFamilyEntries[i]).fBaseConvType),Exponent);
finally
u.Free;
end;
end;
end;
procedure TUnitsWithExponent.DoPower(Exponent: Real);
var i: Integer;
begin
for i:=0 to fcount-1 do
Exponents[i]:=Exponents[i]*Exponent;
end;
function TUnitsWithExponent.TakeFromString(formula: string; out modifier: string): Real;
var p: TSimpleParser;
term: string;
convType: TConvType;
ch: char;
pow: Real;
isDivide: Boolean;
nextDivide: Boolean;
mul: Real;
begin
Clear;
modifier:='';
p:=TSimpleParser.Create(formula);
Result:=1;
isDivide:=false;
nextDivide:=false;
try
while not p.eof do begin
term:=p.getPhysUnitIdent;
mul:=UnitPrefixes.PrefixDescrToMultiplier(term,Modifier,ConvType);
pow:=1;
if not p.eof then begin
ch:=p.getChar;
if ch='^' then begin
pow:=p.getFloat;
if (not p.eof) then begin
if (p.NextChar<>'*') and (p.NextChar<>'/') then Raise EOldPhysUnitError.CreateFmt('Syntax error in unit %s',[formula]);
nextDivide:=(p.getChar='/');
end;
end
else nextDivide:=(ch='/');
end;
if IsDivide then pow:=-pow;
Result:=Result*AddArbitraryUnit(ConvType,pow)*Power(mul,pow);
IsDivide:=nextDivide;
// чтобы он к примеру Джоули преобр. в кг*м^2/с^2
end;
finally
p.Free;
if modifier<>'' then modifier:='\'+modifier;
end;
end;
procedure TUnitsWithExponent.Assign(source: TPersistent);
var s: TUnitsWithExponent absolute source;
begin
if source is TUnitsWithExponent then begin
Exponents:=Copy(s.Exponents);
UnitTypes:=Copy(s.UnitTypes);
fCount:=s.fCount;
end
else inherited Assign(source);
end;
function TUnitsWithExponent.SameFamily(value: TUnitsWithExponent): Boolean;
var i: Integer;
begin
if fcount=value.fCount then begin
Result:=true;
for i:=0 to fCount-1 do
if (ConvTypeToFamily(UnitTypes[i])<>ConvTypeToFamily(value.UnitTypes[i])) or (Exponents[i]<>value.Exponents[i]) then begin
Result:=false;
Exit;
end;
end
else Result:=false;
end;
procedure TUnitsWithExponent.Merge(value: TUnitsWithExponent; proc: TUnitsWithExponentMergeProc);
var i,j,k: Integer;
L1,L2: Integer;
ResultUnits: TConvTypeArray;
ResultExponents: TExponents;
first,second: TConvFamily;
begin
//оба списка отсортированы по нарастанию unitTypes
//точнее, TConvFamily соотв. unitTypes
//по сути, осуществляем слияние
i:=0;
j:=0;
k:=0;
L1:=fcount;
L2:=value.fCount;
SetLength(ResultUnits,L1+L2); //наихудший сценарий
SetLength(ResultExponents,L1+L2);
while (i<L1) and (j<L2) do begin
first:=ConvTypeToFamily(UnitTypes[i]);
second:=ConvTypeToFamily(value.UnitTypes[j]);
if first=second then begin
ResultUnits[k]:=UnitTypes[i];
ResultExponents[k]:=proc(value,i,j);
inc(i);
inc(j);
if ResultExponents[k]<>0 then inc(k);
end
else if IndexOfBaseFamily(first)>IndexOfBaseFamily(second) then begin
//UnitTypes[j] не было в исх. списке - надо добавить на подх. место
ResultUnits[k]:=value.UnitTypes[j];
ResultExponents[k]:=proc(value,-1,j);
inc(j);
inc(k);
end
else begin
ResultUnits[k]:=UnitTypes[i];
ResultExponents[k]:=Exponents[i];
inc(i);
inc(k);
end;
end;
while i<L1 do begin //хвосты доделываем
ResultUnits[k]:=UnitTypes[i];
ResultExponents[k]:=Exponents[i];
inc(i);
inc(k);
end;
while j<L2 do begin //и еще один хвост
ResultUnits[k]:=value.UnitTypes[j];
ResultExponents[k]:=proc(value,-1,j);
inc(j);
inc(k);
end;
SetLength(ResultUnits,k);
SetLength(ResultExponents,k);
UnitTypes:=Copy(ResultUnits);
Exponents:=Copy(ResultExponents);
fCount:=k;
end;
function TUnitsWithExponent.MergeMul(value: TUnitsWithExponent; i,j: Integer): Real;
begin
if i=-1 then Result:=value.exponents[j]
else Result:=Exponents[i]+value.exponents[j];
end;
function TUnitsWithExponent.MergeDiv(value: TUnitsWithExponent; i,j: Integer): Real;
begin
if i=-1 then Result:=-value.exponents[j]
else Result:=Exponents[i]-value.exponents[j];
end;
procedure TUnitsWithExponent.Multiply(value: TUnitsWithExponent);
begin
Merge(value,MergeMul);
end;
procedure TUnitsWithExponent.Divide(right: TUnitsWithExponent);
begin
Merge(right,MergeDiv);
end;
function TUnitsWithExponent.ShowSomething(proc: TShowName): string;
var i: Integer;
begin
Result:='';
for i:=0 to fCount-1 do begin
if Exponents[i]=1 then
Result:=Result+proc(UnitTypes[i])
else begin
Result:=Result+'('+proc(UnitTypes[i])+')^';
if Exponents[i]<0 then
Result:=Result+'('+FloatToStr(Exponents[i])+')'
else
Result:=Result+FloatToStr(Exponents[i]);
end;
if i<fCount-1 then Result:=Result+'*';
end;
end;
function TUnitsWithExponent.ShowFormula: string;
begin
Result:=ShowSomething(ConvTypeToBaseFamilyLetter);
end;
function TUnitsWithExponent.AsString: string;
begin
result:=ShowSomething(ConvTypeToDescription);
end;
function TUnitsWithExponent.isAffine: Boolean;
var i,j: Integer;
begin
Result:=false;
for i:=0 to fCount-1 do begin
j:=IndexOfBaseFamily(ConvTypeToFamily(UnitTypes[i]));
Result:=Result or TBaseConvFamily(BaseFamilyEntries[j]).isAffine;
if Result=true then break;
end;
end;
(*
TVariantWithUnit
*)
constructor TVariantWithUnit.Create(text: string);
begin
Create;
Assign(text);
end;
constructor TVariantWithUnit.CreateFromVariant(source: Variant; aConvType: TConvType);
begin
Create;
instance:=source;
ConvType:=aConvType;
end;
procedure TVariantWithUnit.Assign(source: TPersistent);
var s: TVariantWithUnit absolute source;
begin
if source is TVariantWithUnit then begin
instance:=s.instance; //variant'ы - они умные, скопируются
ConvType:=s.ConvType;
end
else inherited Assign(source);
end;
function GetAffineWithMultiplier(BaseConvType: TConvType; mul: Real): TConvType;
var i,L: Integer;
str: string;
begin
L:=Length(AffineUnits);
for i:=0 to L-1 do
if (AffineUnits[i].BaseConvType=BaseConvType) and (abs(AffineUnits[i].multiplier-mul)<1e-5) then begin
Result:=AffineUnits[i].ConvType;
Exit;
end;
//раз нет, придется создать
SetLength(AffineUnits,L+1);
str:=ConvTypeToDescription(BaseConvType);
if mul<>0 then
str:=Format('%s{%g}',[str,mul])
else
str:=str+'{dif}';
Result:=RegisterConversionType(ConvTypeToFamily(BaseConvType),str,1.0/0.0);
//никогда мы не должны пользоваться ConversionFactor'ом получившейся единицы!
AffineUnits[L].ConvType:=Result;
AffineUnits[L].BaseConvType:=BaseConvType;
AffineUnits[L].multiplier:=mul;
end;
procedure TVariantWithUnit.Conversion(DestConv: TConvType);
var j,i,b: Integer; //inst - это мы
offset,k,mul: Real; //dest - это тоже мы, но позже
formula: TUnitsWithExponent;
new_formula: TUnitsWithExponent;
addition: Variant;
pow: Real;
buConvType: TConvType;
s: string;
resourcestring
ToConvertFromAToB = 'Для преобразования из [%s] в [%s] выражение домножено на %s';
IncorrectUnitConversion = 'Некорректное приведение типов: [%s] в [%s]';
begin
buConvType:=ConvType;
ConvType:=DestConv;
if IsAffine(j) then
DestConv:=AffineUnits[j].BaseConvType;
ConvType:=buConvType;
if IsAffine(j) then begin
if CompatibleConversionTypes(ConvType,DestConv) then begin
offset:=Convert(0,AffineUnits[j].BaseConvType,DestConv);
k:=Convert(1,AffineUnits[j].BaseConvType,DestConv)-offset;
mul:=AffineUnits[j].multiplier;
instance:=instance*k+offset*mul;
ConvType:=DestConv;
IsAffine(j);
ConvType:=GetAffineWithMultiplier(AffineUnits[j].BaseConvType,mul);
Exit;
end
else begin
new_formula:=FindPhysUnit(ConvType);
Conversion(new_formula.UnitTypes[0]); //проще говоря, в кельвины
new_formula.Free;
end;
end;
//на этой стадии у нас уже не афинная величина, а самая простая (мы так считаем)
if (ConvType<>DestConv) then begin
if instance=0 then
ConvType:=DestConv
else if CompatibleConversionTypes(ConvType,DestConv) then begin
instance:=instance*Convert(1,ConvType,DestConv);
ConvType:=DestConv;
end
else begin
//попробуем выразить, зная, что c=1, h=1 и т.д.
buConvType:=ConvType;
new_formula:=nil;
formula:=FindPhysUnit(ConvType); //это наша родная
try
Conversion(FormulaToConvType(formula)); //всяческие электронвольты приводим к СИ
try
new_formula:=FindPhysUnit(DestConv);
formula.Divide(new_formula);
addition:=0.0;
for i:=0 to formula.fCount-1 do begin
j:=IndexOfBaseFamily(ConvTypeToFamily(formula.UnitTypes[i]));
addition:=addition+UnityPhysConstants.GetVar(j)*formula.Exponents[i];
end;
if VarManySolutionsIsNumber(addition) then begin //успех!
instance:=instance*Exp(-addition);
ConvType:=FormulaToConvType(new_formula);
Conversion(DestConv); //теперь сделается как надо!
if Assigned(LogConversionDetailsProc) then begin
//разоблачение фокуса - на что мы помножили и поделили
for i:=0 to UnityPhysConstants.ActuallyUsedCount-1 do begin
pow:=0.0;
for j:=0 to formula.fCount-1 do begin
b:=IndexOfBaseFamily(ConvTypeToFamily(formula.UnitTypes[j]));
pow:=pow-UnityPhysConstants.Solver.getInvMatrix(i,b)*formula.Exponents[j];
end;
if abs(pow)>0.001 then begin
if Length(s)>0 then s:=s+'*';
if abs(pow-1)>1e-19 then
s:=s+'('+UnityPhysConstants.Names[UnityPhysConstants.GetActualIndex(i)]+')^'+Format('%2.2g' ,[pow])
else
s:=s+UnityPhysConstants.Names[UnityPhysConstants.GetActualIndex(i)];
end;
end;
LogConversionDetailsProc(Format(ToConvertFromAToB,[ConvTypeToDescription(buConvType),ConvTypeToDescription(DestConv),s]));
end;
end
else Raise EOldphysUnitError.CreateFmt(IncorrectUnitConversion,[ConvTypeToDescription(buConvType),ConvTypeToDescription(DestConv)]);
finally
new_formula.Free;
end;
finally
formula.Free;
end;
end;
end;
end;
procedure TVariantWithUnit.Negate;
var i: Integer;
tmp: Variant;
begin
tmp:=instance; //все-таки счетчик ссылок- не самая надежная вещь, при
instance:=-tmp; //instance:=-instance течет память
if IsAffine(i) then
ConvType:=GetAffineWithMultiplier(AffineUnits[i].BaseConvType,-AffineUnits[i].multiplier);
end;
function TVariantWithUnit.IsAffine (out i: Integer): Boolean;
var findex: Integer;
begin
findex:=indexOfBaseFamily(ConvTypeToFamily(convType));
Result:=(findex>=0) and TBaseConvFamily(BaseFamilyEntries[findex]).isAffine;
if Result then begin
Result:=false;
for findex:=0 to Length(AffineUnits)-1 do
if AffineUnits[findex].ConvType=convType then begin
Result:=true;
i:=findex;
Exit;
end;
end;
end;
procedure TVariantWithUnit.DoAdd(value: TAbstractWrapperData);
var v: TVariantWithUnit absolute value;
j,k: Integer;
offset,mul: Real;
begin
if value is TVariantWithUnit then
if CompatibleConversionTypes(v.ConvType,ConvType) then
if IsAffine(j) and v.IsAffine(k) then begin
//преобр правую часть в тип левой части
offset:=Convert(0,AffineUnits[k].BaseConvType,AffineUnits[j].BaseConvType);
mul:=Convert(1,AffineUnits[k].BaseConvType,AffineUnits[j].BaseConvType)-offset;
instance:=instance+mul*v.instance+offset*AffineUnits[k].multiplier;
mul:=AffineUnits[j].multiplier+AffineUnits[k].multiplier; //получивш. множитель
ConvType:=GetAffineWithMultiplier(AffineUnits[j].BaseConvType,mul);
end
else
instance:=instance+v.instance*Convert(1,v.ConvType,ConvType)
else if instance=0 then begin
instance:=v.instance;
ConvType:=v.ConvType;
end
else begin
v.Conversion(ConvType);
instance:=instance+v.instance;
end
else inherited; //не знаю пока, пригодится ли эта строчка хоть раз?
end;
procedure TVariantWithUnit.DoMultiply(Right: TAbstractWrapperData);
var v: TVariantWithUnit absolute Right;
UL,UR: TUnitsWithExponent;
j,k: Integer;
begin
if Right is TVariantWithUnit then begin
UL:=FindPhysUnit(ConvType);
try
UR:=FindPhysUnit(v.ConvType);
try
if IsAffine(j) then
if v.ConvType=duUnity then begin
instance:=instance*v.instance;
ConvType:=GetAffineWithMultiplier(AffineUnits[j].BaseConvType,AffineUnits[j].multiplier*v.instance);
end
else begin //разрушаем эту афинную иддилию (где здесь сдвоенные согласные - ума не приложу)
//преобразуем в Кельвины, а точнее, в базовую величину семейства
Conversion(UL.UnitTypes[0]);
//и остатки
if v.IsAffine(k) then begin
v.Conversion(UR.UnitTypes[0]);
v.IsAffine(k);
UL.Multiply(Ur);
instance:=instance*v.instance*Convert(1,AffineUnits[k].BaseConvType,FormulaToConvType(Ur));
ConvType:=FormulaToConvType(UL);
end
else begin
UL.Multiply(Ur);
instance:=instance*v.instance*Convert(1,v.ConvType,FormulaToConvType(Ur));
ConvType:=FormulaToConvType(UL);
end;
end
else
if v.IsAffine(j) then
if ConvType=duUnity then begin
ConvType:=GetAffineWithMultiplier(AffineUnits[j].BaseConvType,AffineUnits[j].multiplier*instance);
instance:=instance*v.instance;
end
else begin //еще одно "разрушение" афинных величин
v.Conversion(UR.UnitTypes[0]);
//но сейчас ConvType может показывать на K{0}, а не K
//а указать нужно именно K
v.IsAffine(k);
//и остатки
UL.Multiply(Ur);
instance:=instance*v.instance*Convert(1,AffineUnits[k].BaseConvType,FormulaToConvType(Ur));
ConvType:=FormulaToConvType(UL);
end
else begin
//основная процедура
if ConvType<>FormulaToConvType(UL) then
Conversion(FormulaToConvType(UL));
UL.Multiply(Ur);
instance:=instance*v.instance;
instance:=instance*Convert(1,v.ConvType,FormulaToConvType(Ur));
ConvType:=FormulaToConvType(UL);
if IsAffine(j) then
ConvType:=GetAffineWithMultiplier(AffineUnits[j].BaseConvType,0);
end;
finally
Ur.Free;
end;
finally
UL.Free;
end;
end
else inherited;
end;
procedure TVariantWithUnit.DoInverse;
var j: Integer;
U: TUnitsWithExponent;
begin
U:=FindPhysUnit(ConvType);
try
if IsAffine(j) then begin
//прикрываем эту лавочку - преобр. в кельвины (точнее, в баз. величину семейства)
Conversion(U.UnitTypes[0]);
instance:=1/instance;
U.DoPower(-1);
ConvType:=FormulaToConvType(U);
end
else begin
//преобр. в тот тип, который нам положен по формуле
Conversion(FormulaToConvType(U));
instance:=1/instance;
U.DoPower(-1);
ConvType:=FormulaToConvType(U);
end;
finally
U.Free;
end;
end;
procedure TVariantWithUnit.DoDivide(Right: TAbstractWrapperData);
var tmp: TVariantWithUnit;
begin
tmp:=TVariantWithUnit.Create;
tmp.Assign(Right);
tmp.DoInverse;
DoMultiply(tmp);
tmp.Free;
end;
procedure TVariantWithUnit.DoPower(pow: Real);
var U: TUnitsWithExponent;
bt: TConvType;
begin
U:=FindPhysUnit(ConvType);
try
bt:=FormulaToConvType(U);
// instance:=instance*Convert(1,ConvType,bt); //перешли в базовый тип
Conversion(bt);
if VarIsComplex(instance) then
instance:=VarComplexPower(instance,pow)
else
instance:=Power(instance,pow);
U.DoPower(pow);
ConvType:=FormulaToConvType(U);
finally
U.Free;
end;
end;
procedure TVariantWithUnit.Assign(str: string);
var unitStr: string;
i: Integer;
val: Extended;
begin
for i:=1 to Length(str) do
if (str[i]='.') or (str[i]=',') then str[i]:=DecimalSeparator;
i:=Length(str);
while (i>=1) and (str[i]<>' ') do dec(i);
if i=0 then begin
//либо только ед. измерения, без числа,
//либо тот или иной Variant, но мы заранее не знаем, какой.
//в этом проблема всех этих произволов. Попробуем в комплексную вел. преобразовать что ль
instance:=VarComplexCreate(str);
instance:=VarComplexSimplify(instance);
ConvType:=duUnity; //безразм.
end
else begin
//посерединке пробел
//либо часть справа от пробела-ед. изм., либо например разделенные действ и мним. части
if AnsiUppercase(str[Length(str)])='I' then begin
Instance:=VarComplexCreate(str);
ConvType:=duUnity;
end
else begin
if TryStrToFloat(LeftStr(str,i-1),val) then
instance:=val
else
instance:=VarComplexCreate(LeftStr(str,i-1));
unitStr:=RightStr(str,Length(str)-i);
ConvType:=StrToConvType(unitStr);
end;
end;
end;
function TVariantWithUnit.AsString: string;
var deg,min: Variant;
s: string;
d: extended;
i: Integer;
begin
if ConvType=auDMS then begin
if instance<0 then begin
Result:='-';
instance:=-instance;
end;
instance:=instance+1/7200000;
deg:=Floor(instance);
s:=deg;
Result:=Result+s+'°';
min:=Floor((instance-deg)*60);
s:=min;
Result:=Result+s+'''';
deg:=(instance-deg-min/60)*3600;
if VarIsNumeric(deg) then begin
d:=deg;
s:=Format('%2.2f',[d]);
end
else s:=deg;
Result:=Result+s+'"';
end
else begin
// if VarIsNumeric(instance) then
// Result:=ConvUnitToStr(instance,ConvType)
// else begin
Result:=instance;
s:=ConvTypeToDescription(ConvType);
i:=Pos('\',s);
if i>0 then
s:=LeftStr(s,i-1);
if s<>'' then Result:=Result+' '+s;
// end;
end;
end;
(*
TVariantWithUnitType
*)
procedure TVariantWithUnitType.Cast(var Dest: TVarData; const Source: TVarData);
begin
//строку преобразуем по всем правилам, а любые другие Variant'ы "оборачиваем" безразм.
VarDataClear(Dest);
if VarDataIsStr(Source) then
TWrapperVarData(Dest).Data:=TVariantWithUnit.Create(VarDataToStr(Source))
else
TWrapperVarData(Dest).Data:=TVariantWithUnit.CreateFromVariant(Variant(source),duUnity);
Dest.VType:=VariantWithUnit;
end;
procedure TVariantWithUnitType.CastTo(var Dest: TVarData; const Source: TVarData; const AVarType: TVarType);
var tmp: Variant;
begin
if Source.VType = VarType then begin
case AVarType of
varOleStr:
VarDataFromOleStr(Dest, TWrapperVarData(Source).data.AsString);
varString:
VarDataFromStr(Dest, TWrapperVarData(Source).data.AsString);
else
with TVariantWithUnitVarData(Source).Data do begin
tmp:=VarWithUnitConvert(Variant(source),duUnity);
VarDataCastTo(Dest,TVarData(TVariantWithUnitVarData(tmp).Data.instance),AVarType);
end;
end;
end
else inherited; //нам дали пустой variant скорее всего
end;
function TVariantWithUnitType.CompareOp(const Left, Right: TVarData; const Operator: Integer): Boolean;
var L,R: TVariantWithUnit;
begin
Result:=false;
L:=TVariantWithUnitVarData(Left).Data;
R:=TVariantWithUnitVarData(Right).Data;
R.Conversion(L.ConvType); //при сравнении ожидаем, что их по кр. мере можно сравнивать!
case operator of
opCmpEQ: Result:=(L.instance=R.instance);
opCmpNE: Result:=(L.instance<>R.instance);
opCmpLT: Result:=(L.instance<R.instance);
opCmpLE: Result:=(L.instance<=R.instance);
opCmpGT: Result:=(L.instance>R.instance);
opCmpGE: Result:=(L.instance>=R.instance);
end;
end;
(*
TFundamentalPhysConstants
*)
constructor TFundamentalPhysConstants.Create(Owner: TComponent);
begin
inherited Create(Owner);
fsolver:=TSimpleGaussLEQ.Create;
fsolver.SetTolerance(1e-19);
recalculate;
end;
destructor TFundamentalPhysConstants.Destroy;
begin
//debug purpose
//Heisenbug: now it works without error
Finalize(fValues);
fsolver:=nil;
inherited Destroy;
end;
function TFundamentalPhysConstants.getName(i: Integer): string;
begin
Result:=fNames[i];
end;
function TFundamentalPhysConstants.getDescription(i: Integer): string;
begin
Result:=fDescriptions[i];
end;
function TFundamentalPhysConstants.getEnabled(i: Integer): Boolean;
begin
Result:=fEnabled[i];
end;
function TFundamentalPhysConstants.GetActualIndex(i: Integer): Integer;
begin
Result:=fActualIndex[i];
end;
resourcestring
NonConsistentConstraints = 'Добавление условия %s=1 приводит к противоречию';
procedure TFundamentalPhysConstants.setEnabled(i: Integer; aValue: Boolean);
begin
if aValue<>fEnabled[i] then begin
fEnabled[i]:=aValue;
if not Recalculate then begin
fEnabled[i]:=not aValue;
Raise EOldPhysUnitError.CreateFMT(NonConsistentConstraints,[fNames[i]]);
end;
end;
end;
procedure TFundamentalPhysConstants.Add(aName,aDescr: string; aValue: Variant; aEnabled: Boolean=false);
var L: Integer;
begin
inc(fCount);
L:=Length(fNames);
if L<fCount then L:=2*fCount;
SetLength(fNames,L);
SetLength(fDescriptions,L);
SetLength(fValues,L);
SetLength(fEnabled,L);
fNames[fCount-1]:=aName;
fDescriptions[fCount-1]:=aDescr;
fValues[fCount-1]:=aValue;
if aEnabled then begin
fEnabled[fCount-1]:=true;
if not Recalculate then begin
fEnabled[fCount-1]:=false;
Raise EOldPhysUnitError.CreateFmt(NonConsistentConstraints,[aName]);
end;
end;
end;
function TFundamentalPhysConstants.GetVar(i: Integer): Variant;
begin
Result:=fsolver.GetVariable(i);
end;
function TFundamentalPhysConstants.Recalculate: Boolean;
var BaseUnitsCount,EqsCount,i,j,ind: Integer;
formula: TUnitsWithExponent;
V: TVariantWithUnit;
begin
BaseUnitsCount:=BaseFamilyEntries.Count;
EqsCount:=0;
fActuallyUsedCount:=0;
SetLength(fActualIndex,fcount);
fsolver.SetDimensions(BaseUnitsCount,0);
for j:=0 to fCount-1 do
if fenabled[j] then begin
inc(EqsCount);
fsolver.SetDimensions(BaseUnitsCount,EqsCount);
V:=TVariantWithUnitVarData(fvalues[j]).Data;
formula:=FindPhysUnit(V.ConvType);
for i:=0 to formula.fCount-1 do begin
ind:=IndexOfBaseFamily(ConvTypeToFamily(formula.UnitTypes[i]));
fsolver.Matrix[ind,EqsCount-1]:=formula.Exponents[i];
end;
fsolver.Matrix[BaseUnitsCount,EqsCount-1]:=Ln(V.instance);
formula.Free;
inc(fActuallyUsedCount);
fActualIndex[fActuallyUsedCount-1]:=j;
end;
fsolver.InvertMatrix;
Result:=(fsolver.GetStatus<>slNoSolution);
end;
procedure TFundamentalPhysConstants.DefineProperties(filer: TFiler);
begin
filer.DefineProperty('constants',ReadData,nil,false);
end;
procedure TFundamentalPhysConstants.ReadData(reader: TReader);
var p: TSimpleParser;
aname,adescr: string;
aunit: Variant;
aenabled: boolean;
expr: TVariantExpression;
begin
reader.ReadListBegin;
p:=TSimpleParser.Create;
expr:=TVariantExpression.Create(nil);
while not reader.EndOfList do begin
p.AssignString(reader.ReadString);
aname:=p.getString;
expr.SetString(p.getString);
aunit:=expr.GetVariantValue;
adescr:=p.getString;
if not p.eof then
aenabled:=(p.getInt=1)
else
aenabled:=false;
Add(aname,adescr,aunit,aenabled);
end;
p.Free;
expr.Free;
reader.ReadListEnd;
end;
(*
Initialization
*)
function VariantWithUnit: TVarType;
begin
Result:=VarWithUnitType.VarType;
end;
(*
конструкторы
*)
procedure VarWithUnitCreateInto(var ADest: Variant; const Adata: TVariantWithUnit);
begin
VarClear(ADest);
TWrapperVarData(ADest).VType:=VariantWithUnit;
TWrapperVarData(ADest).Data:=Adata;
end;
function VarWithUnitCreate(text: string): Variant;
begin
VarWithUnitCreateInto(Result,TVariantWithUnit.Create(text));
end;
function TryVarWithUnitCreate(text: string; out Res: Variant): boolean;
begin
Result:=false;
try
VarWithUnitCreateInto(Res,TVariantWithUnit.Create(text));
Result:=true;
except
on E: Exception do
Res:=E.Message;
end;
end;
function TryVarWithUnitConvert(source: Variant; DestConvType: TConvType; out Res: Variant): boolean;
begin
Result:=false;
try
Res:=VarWithUnitConvert(source,DestConvType);
Result:=true;
except
on E: Exception do
Res:=E.Message;
end;
end;
function IsVarWithUnitSameFamily(v1,v2: Variant): Boolean;
var dat1: TVariantWithUnitVarData absolute v1;
dat2: TVariantWithUnitVarData absolute v2;
fam1,fam2: TConvFamily;
begin
if not IsVarWithUnit(v1) then
fam1:=cbDimensionless
else
fam1:=ConvTypeToFamily(dat1.Data.ConvType);
if not IsVarWithUnit(v2) then
fam2:=cbDimensionless
else
fam2:=ConvTypeToFamily(dat2.Data.ConvType);
Result:=(fam1=fam2);
end;
function VarWithUnitCreateFromVariant(source: Variant; ConvType: TConvType): Variant;
resourcestring
AlreadyHasDimension = '%s уже имеет размерность';
begin
if IsVarWithUnit(source) then
if TVariantWithUnitVarData(source).Data.ConvType=duUnity then begin
Result:=source;
TVariantWithUnitVarData(Result).Data.ConvType:=ConvType;
end
else
Raise EOldPhysUnitError.CreateFmt(AlreadyHasDimension,[source])
else
VarWithUnitCreateInto(Result,TVariantWithUnit.CreateFromVariant(source,ConvType));
end;
function IsVarWithUnit(V: Variant): boolean;
begin
Result:=(TWrapperVarData(V).VType=VariantWithUnit);
end;
function Isdimensionless(V: Variant): boolean;
begin
Result:=(TVarData(V).VType=VariantWithUnit) and
(TVariantWithUnitVarData(V).Data.ConvType=duUnity);
end;
function VarWithUnitConvert(source: Variant; DestConvType: TConvType; explicit: boolean=false): Variant;
var inst,dest: TVariantWithUnit;
begin
if not IsVarWithUnit(source) then
source:=VarWithUnitCreateFromVariant(source,duUnity);
inst:=TVariantWithUnitVarData(source).Data;
dest:=TVariantWithUnit.Create;
try
dest.Assign(inst);
dest.Conversion(DestConvType);
dest.ExplicitConversion:=explicit;
VarWithUnitCreateInto(Result,dest);
except //эта хреновина замаскировала ошибку!
dest.Free;
raise;
end;
end;
function VarWithUnitConvert(source: Variant; UnitName: string): Variant;
begin
Result:=VarWithUnitConvert(source,StrToConvType(UnitName));
end;
function VarWithUnitGetNumberIn(source: Variant; UnitName: TConvType): Variant;
var tmp: Variant;
begin
tmp:=VarWithUnitConvert(source,UnitName);
Result:=TVariantWithUnitVarData(tmp).Data.instance;
end;
function VarWithUnitGetNumber(source: Variant): Variant;
begin
if IsVarWithUnit(source) then
Result:=TVariantWithUnitVarData(source).Data.instance
else
Result:=source;
end;
function VarWithUnitGetConvType(source: Variant): TConvType;
begin
if IsVarWithUnit(source) then
Result:=TVariantWithUnitVarData(source).Data.ConvType
else
Result:=duUnity;
end;
function VarWithUnitGetConvFamily(source: Variant): TConvFamily;
begin
Result:=ConvTypeToFamily(VarWithUnitGetConvType(source));
end;
function VarWithUnitPower(source: Variant; pow: Real): Variant;
begin
Result:=source;
TVariantWithUnitVarData(Result).Data.DoPower(pow);
end;
function VarWithUnitSqrt(source: Variant): Variant;
begin
Result:=VarWithUnitPower(source,0.5);
end;
function VarWithUnitAbs(source: Variant): Variant;
begin
if IsVarWithUnit(source) then begin
Result:=source;
TVariantWithUnitVarData(Result).Data.instance:=VarComplexAbs(TVariantWithUnitVarData(source).Data.instance)
end
else
Result:=VarWithUnitCreateFromVariant(VarComplexAbs(source),duUnity);
end;
function VarWithUnitArg(source: Variant): Variant;
begin
if isVarWithUnit(source) then
Result:=VarWithUnitCreateFromVariant(VarComplexAngle(TVariantWithUnitVarData(source).Data.instance),auRadian)
else
Result:=VarWithUnitCreateFromVariant(VarComplexAngle(source),auRadian);
end;
function VarWithUnitRe(source: Variant): Variant;
begin
if isVarWithUnit(source) then begin
Result:=source;
TVariantWithUnitVarData(Result).Data.instance:=TVariantWithUnitVarData(Result).Data.instance.Real
end
else
Result:=VarWithUnitCreateFromVariant(source.Re,duUnity);
end;
function VarWithUnitIm(source: Variant): Variant;
begin
if isVarWithUnit(source) then begin
Result:=source;
TVariantWithUnitVarData(Result).Data.instance:=TVariantWithUnitVarData(Result).Data.instance.Imaginary
end
else
Result:=VarWithUnitCreateFromVariant(source.Im,duUnity);
end;
function VarGetLength(source: Variant): Real;
begin
if VarIsNumeric(source) then result:=abs(source)
else if VarIsComplex(source) then Result:=VarComplexAbs(source)
else Raise Exception.Create('can''t get length of variable');
end;
function VarWithUnitFindGoodPrefix(source: Variant): Variant;
var v: TVariantWithUnitVarData absolute source;
ConvWithoutPrefix: TConvType;
v1: Variant;
vdat: TVariantWithUnitVarData absolute v1;
i: Integer;
Ampl: Real;
s: string;
InitConvType: TConvType;
inst: Variant;
// nam: convtype;
begin
if not IsVarWithUnit(source) then begin
Result:=source;
Exit;
end;
//афинные величины, будь они неладны
if v.Data.IsAffine(i) then
if AffineUnits[i].BaseConvType=v.Data.ConvType then
InitConvType:=AffineUnits[i].BaseConvType
else begin
Result:=source;
Exit;
end
else
InitConvType:=v.Data.ConvType;
//из 0.0001 г получит 100 мкг и т.д
if ListOfUnitsWithAllowedPrefixes.Exists(Pointer(InitConvType)) then
v1:=source
else begin
s:=ConvTypeToDescription(InitConvType);
i:=Pos('\',s);
if i>0 then
s:=LeftStr(s,i-1);
if UnitPrefixes.FindUnitWithPrefix(s,ConvWithoutPrefix) and
ListOfUnitsWithAllowedPrefixes.Exists(Pointer(ConvWithoutPrefix)) then
v1:=VarWithUnitConvert(source,ConvWithoutPrefix)
else begin
Result:=source;
Exit;
end;
end;
//если дошли до этого места, то все в порядке, можно дописать префикс.
Ampl:=VarGetLength(vdat.Data.instance);
i:=UnitPrefixes.fPreferredPrefixes.Count-1;
while (i>=0) and (Ampl<TPrefixEntry(UnitPrefixes.fPreferredPrefixes[i]).multiplier) do
dec(i);
// if i<0 then i:=0;
if i>=0 then begin
// Result:=VarWithUnitCreateFromVariant(
// vdat.Data.instance/TPrefixEntry(UnitPrefixes.fPreferredPrefixes[i]).multiplier,
// StrToConvType(TPrefixEntry(UnitPrefixes.fPreferredPrefixes[i]).name+ConvTypeToDescription(vdat.Data.ConvType)))
inst:=vdat.Data.instance/TPrefixEntry(UnitPrefixes.fPreferredPrefixes[i]).multiplier;
Result:=VarWithUnitCreateFromVariant(inst,
StrToConvType(TPrefixEntry(UnitPrefixes.fPreferredPrefixes[i]).name+ConvTypeToDescription(vdat.Data.ConvType)))
end
else
Result:=source;
end;
(*
General procedures
*)
function NameToFamily(const Ident: string; var Int: Longint): Boolean;
var id: string;
convfam: TConvFamily;
begin
id:=Ident;
Result:=DescriptionToConvFamily(id,convfam);
Int:=convfam;
end;
function FamilyToName(Int: LongInt; var Ident: string): Boolean;
begin
Ident:=ConvFamilyToDescription(Int);
Result:=true;
end;
function NameToConv(const Ident: string; var Int: LongInt): Boolean;
var convtype: TConvType;
begin
Result:=DescriptionToConvType(Ident,convtype);
Int:=convtype;
end;
function ConvToName(Int: LongInt; var Ident: string): Boolean;
begin
Ident:=ConvTypeToDescription(Int);
Result:=true;
end;
procedure NewConvFamilies;
var comp: TComponent;
consts: TFundamentalPhysConstants absolute comp;
abstr: TAbstractSavedConvFamily absolute comp;
baseconv: TBaseConvFamily absolute comp;
der: TDerivedConvFamily absolute comp;
fileStream: TFileStream;
BinStream: TMemoryStream;
sr: TSearchRec;
i,j,L: Integer;
types: TConvTypeArray;
begin
all_the_possible_units:=TStringList.Create;
all_the_possible_units.Sorted:=true;
if FindFirst(Default_Dir+'*.txt',0,sr)=0 then begin
repeat
fileStream:=TFileStream.Create(Default_dir+sr.Name,fmOpenRead);
fileStream.Seek(0, soFromBeginning);
binStream:=TMemoryStream.Create;
while FileStream.Position<FileStream.Size do
ObjectTextToBinary(FileStream,BinStream);
BinStream.Seek(0, soFromBeginning);
while BinStream.Position<BinStream.Size do begin
// try
comp:=BinStream.ReadComponent(nil);
if (comp is TFundamentalPhysConstants) and
(AnsiUppercase(consts.Lang)=AnsiUppercase(PhysUnitLanguage)) then begin
UnityPhysConstants.Free;
UnityPhysConstants:=consts;
end
else if (comp is TAbstractSavedconvFamily) then begin
if Assigned(LogConversionErrorProc) then
for i:=0 to abstr.fErrorList.Count-1 do
LogConversionErrorProc(abstr.fErrorList[i]);
if (comp is TBaseConvFamily) then begin
i:=IndexOfBaseFamily(baseconv.fConvFamily);
if (i>=0) then
if (AnsiUppercase(PhysUnitLanguage)=AnsiUppercase(baseconv.flang)) or (AnsiUppercase(baseconv.flang)='ANY') then
BaseFamilyEntries[i]:=baseconv
else baseconv.Free
else
BaseFamilyEntries.Add(baseconv);
end
else if (comp is TDerivedConvFamily) then begin
i:=IndexOfDerivedFamily(der.fConvFamily);
if (i>=0) then
if (AnsiUppercase(PhysUnitLanguage)=Uppercase(der.flang)) or (AnsiUpperCase(der.flang)='ANY') then
DerivedFamilyEntries[i]:=der
else der.Free
else
DerivedFamilyEntries.Add(der);
end;
end
else if (comp is TOldUnitPrefixes) then begin
UnitPrefixes.Assimilate(comp as TOldUnitPrefixes); //comp уничтожается при этом
end
else
comp.Free;
// except
// on E: Exception do
// raise E;
// end;
end;
BinStream.Free;
FileStream.Free;
until FindNext(sr)<>0
end;
for i:=0 to BaseFamilyEntries.Count-1 do
if TBaseConvFamily(BaseFamilyEntries[i]).fAffine then begin
GetConvTypes(TBaseConvFamily(BaseFamilyEntries[i]).fConvFamily,Types);
L:=Length(AffineUnits);
SetLength(AffineUnits,L+Length(Types));
for j:=0 to Length(Types)-1 do begin
AffineUnits[L+j].ConvType:=Types[j];
AffineUnits[L+j].BaseConvType:=Types[j];
AffineUnits[L+j].multiplier:=1;
end;
end;
FreeAndNil(all_the_possible_units);
end;
(*
TBaseConvFamily
*)
constructor TAbstractSavedConvFamily.Create(Owner: TComponent);
begin
inherited Create(Owner);
fErrorList:=TStringList.Create;
end;
destructor TAbstractSavedConvFamily.Destroy;
begin
fErrorList.Free;
inherited Destroy;
end;
procedure TAbstractSavedConvFamily.DefineProperties(Filer: TFiler);
begin
Filer.DefineProperty('Units',ReadUnits,nil,true);
end;
procedure TAbstractSavedConvFamily.ReadUnits(Reader: TReader);
var p: TSimpleParser;
varexpr: TVariantExpression;
UnitName: string;
Multiplier,Offset: Real;
prefixOk: Boolean;
err_family_name: string;
err_obj: TConvType;
resourcestring
UnitNotFound = 'Единица измерения %s не найдена или дублируется';
CheckForAmbiguityFail = 'Нельзя зарегистрировать величину %s.%s, т.к она может совпасть с %s.%s';
procedure CheckForAmbiguity;
var possible_units: TStrings;
i,j: Integer;
cur: string;
begin
if prefixOK then begin
possible_units:=TStringList.Create;
for i:=0 to UnitPrefixes.fPrefixes.Count-1 do begin
cur:=UnitPrefixes.fPrefixes[i]+unitname;
if all_the_possible_units.Find(cur,j) then begin
//это еще не криминал сам по себе - если 2 величины дадут тот же результат,
//то пусть живут
err_obj:=TConvType(all_the_possible_units.Objects[j]);
err_family_name:=ConvFamilyToDescription(ConvTypeToFamily(err_obj));
ferrorlist.Add(format(CheckForAmbiguityFail,[name,unitname,err_family_name,all_the_possible_units[j]]));
break;
end;
// else
possible_units.AddObject(cur,TObject(fBaseConvType));
end;
all_the_possible_units.AddStrings(possible_units);
possible_units.Free;
end
else begin
if all_the_possible_units.Find(unitname,j) then begin
err_obj:=TConvType(all_the_possible_units.Objects[j]);
err_family_name:=ConvFamilyToDescription(ConvTypeToFamily(TConvType(all_the_possible_units.Objects[j])));
ferrorlist.Add(format(CheckForAmbiguityFail,[name,unitname,err_family_name,all_the_possible_units[j]]));
end;
// else
all_the_possible_units.AddObject(unitname,TObject(fBaseConvType));
end;
end;
begin
if not DescriptionToConvFamily(name,fConvFamily) then
fConvFamily:=RegisterConversionFamily(name);
varexpr:=TVariantExpression.Create(nil);
Reader.ReadListBegin;
p:=TSimpleParser.Create;
while not Reader.EndOfList do begin
prefixOk:=false;
p.AssignString(Reader.ReadString);
UnitName:=p.getString;
varexpr.SetString(p.getString);
Multiplier:=varexpr.getVariantValue;
if not p.eof then begin
if Uppercase(p.getString)='PREFIXOK' then
prefixOk:=true
else
p.PutBack;
if not p.eof then begin
varexpr.SetString(p.getString);
offset:=varExpr.getVariantValue;
prefixOK:=(not p.eof) and (UpperCase(p.getString)='PREFIXOK');
RegisterConversionType(TconvTypeAffine.Create(fConvFamily,UnitName,offset,multiplier),fBaseConvType);
CheckForAmbiguity;
//baseconvtype здесь подставлен, чтобы лишнюю перем. не вводить, знач. мы игнорируем
if prefixOK then ListOfUnitsWithAllowedPrefixes.Add(Pointer(fBaseConvType),nil);
end
else begin
fBaseConvType:=RegisterConversionType(fConvFamily,UnitName,multiplier); //можно префикс ставить
CheckForAmbiguity;
if prefixOk then ListOfUnitsWithAllowedPrefixes.Add(Pointer(fBaseConvType),nil);
end;
end
else begin
fBaseConvType:=RegisterConversionType(fConvFamily,UnitName,multiplier);
CheckForAmbiguity;
end;
end;
p.Free;
varexpr.Free;
Reader.ReadListEnd;
//на этом этапе уже должен считаться baseType
// fBaseConvType:=StrToConvType(fStrBaseUnit);
if not DescriptionToConvType(fStrBaseUnit,fBaseConvType) then
Raise Exception.CreateFMT(UnitNotFound,[fStrBaseUnit]);
//регистрацию оставим для Loaded
end;
constructor TDerivedConvFamily.Create(owner: TComponent);
begin
inherited Create(Owner);
fformula:=TUnitsWithExponent.Create;
end;
destructor TDerivedConvFamily.Destroy;
begin
fformula.Free;
inherited Destroy;
end;
procedure TDerivedConvFamily.Loaded;
var mul: Real;
modifier: string;
resourcestring
NonCoherentUnit = '%s должна быть когерентной (с единичным безразмерным множителем) производной величиной';
CaseAmbiguity = 'в основной единице измерения данной размерности %s не должно быть приставок м/М';
begin
mul:=fformula.TakeFromString(fStrFormula,modifier);
if abs(mul-1)>1e-10 then
Raise Exception.CreateFMT(NonCoherentUnit,[fStrFormula]);
// if modifier<>'' then Raise Exception.CreateFMT(CaseAmbiguity,[fStrFormula]);
end;
(*
TConvTypeAffine
*)
constructor TConvTypeAffine.Create(const AConvFamily: TConvFamily; const ADescription: string; offset,factor: Real);
begin
inherited Create(AConvFamily,ADescription);
foffset:=offset;
ffactor:=factor;
end;
function TConvTypeAffine.ToCommon(const AValue: Double): Double;
begin
Result:=foffset+AValue*ffactor;
end;
function TConvTypeAffine.FromCommon(const AValue: Double): Double;
begin
Result:=(AValue-foffset)/ffactor;
end;
(*
TUnitPrefixes
*)
procedure TOldUnitPrefixes.DefineProperties(Filer: TFiler);
begin
filer.DefineProperty('list',ReadList,nil,true);
end;
constructor TOldUnitPrefixes.Create(Owner: TComponent);
begin
inherited Create(Owner);
fPrefixes:=TStringList.Create;
fPrefixes.Sorted:=true;
fPrefixes.Duplicates:=dupError;
fPrefixes.CaseSensitive:=true;
fPreferredPrefixes:=TList.Create;
end;
destructor TOldUnitPrefixes.Destroy;
var i: Integer;
begin
for i:=0 to fPrefixes.Count-1 do
fPrefixes.Objects[i].Free;
fPrefixes.Free;
fPreferredPrefixes.Free;
inherited Destroy;
end;
function UnitPrefixesSortCompare(Item1,Item2: Pointer): Integer;
var p1: TPrefixEntry absolute Item1;
p2: TPrefixEntry absolute Item2;
begin
if p1.multiplier<p2.multiplier then result:=-1
else if p1.multiplier>p2.multiplier then result:=1
else Result:=0;
end;
procedure TOldUnitPrefixes.ReadList(Reader: TReader);
var p: TSimpleParser;
pname,pdescr: string;
pmult: Real;
pIsPreferred: boolean;
PrefixEntry: TPrefixEntry;
expr: TVariantExpression;
begin
p:=TSimpleParser.Create;
expr:=TVariantExpression.Create(nil);
Reader.ReadListBegin;
while not Reader.EndOfList do begin
p.AssignString(Reader.ReadString);
pname:=p.getString;
pdescr:=p.getString;
expr.SetString(p.getString);
pmult:=expr.getValue;
pIsPreferred:=(not p.eof) and (UpperCase(p.getString)='PREFERRED');
fMaxLen:=Max(fMaxLen,Length(pname));
PrefixEntry:=TPrefixEntry.Create;
PrefixEntry.name:=pname;
PrefixEntry.multiplier:=pmult;
fPrefixes.AddObject(pname,PrefixEntry); //описания пока игнорируем
if pIsPreferred then
fPreferredPrefixes.Add(PrefixEntry);
end;
fPreferredPrefixes.Sort(UnitPrefixesSortCompare);
Reader.ReadListEnd;
p.Free;
expr.Free;
end;
procedure TOldUnitPrefixes.Assimilate(source: TOldUnitPrefixes);
var i,j: Integer;
begin
for i:=0 to source.fPrefixes.Count-1 do
if not fPrefixes.Find(source.fPrefixes[i],j) then
fPrefixes.AddObject(source.fPrefixes[i],source.fPrefixes.Objects[i])
else begin
fPreferredPrefixes.Remove(fPrefixes.Objects[j]);
fPrefixes.Objects[j].Free;
fPrefixes.Objects[j]:=source.fPrefixes.Objects[i];
fPreferredPrefixes.Add(fPrefixes.Objects[j]);
end;
if source.lang=PhysUnitLanguage then begin
fPreferredPrefixes.Clear;
for i:=0 to source.fPreferredPrefixes.Count-1 do
fPreferredPrefixes.Add(source.fPreferredPrefixes[i]);
end;
fMaxLen:=Max(fMaxLen,source.fMaxLen);
source.fPrefixes.Clear;
source.Free;
end;
function TOldUnitPrefixes.FindUnitWithPrefix(str: string; out CType: TConvType): boolean;
var i,j: Integer;
begin
for i:=1 to min(Length(str),fMaxLen) do
if fPrefixes.Find(LeftStr(str,i),j) and
DescriptionToConvType(RightStr(str,Length(str)-i),CType) and
ListOfUnitsWithAllowedPrefixes.Exists(Pointer(CType)) then begin
Result:=true;
Exit;
end;
// Result:=(str<>'') and DescriptionToConvType(str,CType);
Result:=DescriptionToConvType(str,CType);
end;
function TOldUnitPrefixes.PrefixDescrToMultiplier(term: string; var modifier: string; out CType: TConvType): Real;
var i,j,index: Integer;
resourcestring
IsNotCorrectUnit = '%s не является единицей измерения';
begin
// - дает на выходе множитель для данного префикса
// - добавляет к modifier символы l и u - lower/upper case
// - указывает единицу измерения в CType
for i:=1 to min(Length(term),fMaxLen) do begin
if fPrefixes.Find(LeftStr(term,i),index) and
DescriptionToConvType(RightStr(term,Length(term)-i),Ctype) and
ListOfUnitsWithAllowedPrefixes.Exists(Pointer(CType)) then begin
Result:=(fPrefixes.Objects[index] as TPrefixEntry).multiplier;
for j:=1 to i do
if AnsiUppercase(term[j])=term[j] then
modifier:=modifier+'u'
else
modifier:=modifier+'l';
Exit;
end;
end;
Result:=1;
if not DescriptionToConvType(term,CType) then
Raise EOldPhysUnitError.CreateFmt(IsNotCorrectUnit,[term]);
end;
(*
TOldPhysUnitParser
*)
function TOldPhysUnitParser.getPhysUnit: TConvType;
var id: string;
InitPos,tempPos: Integer;
CType: TConvType;
ch: char;
begin
//хитрость в том, чтобы найти окончание.
//скажем, 1 км*2 - здесь ед. изм "км"
//но в 1 Н*м - "Н*м".
skip_spaces;
InitPos:=_pos; //fBackupPos будет меняться внутри цикла
TempPos:=_pos;
while not eof do begin
id:=GetPhysUnitIdent;
//хотя у нас есть безразмерная величина, принимать
//пустое место за нее не имеем права!
if (id='') or not UnitPrefixes.FindUnitWithPrefix(id,CType) then begin
_pos:=TempPos;
break;
end
else begin
if eof then break;
TempPos:=_pos;
ch:=GetChar;
if ch='^' then begin
GetFloat;
TempPos:=_pos;
if eof then break;
ch:=GetChar;
end;
if eof or ((ch<>'*') and (ch<>'/')) then begin
_pos:=TempPos;
break;
end;
end;
end;
fBackupPos:=InitPos;
if _pos<>InitPos then
Result:=StrToConvType(MidStr(_str,InitPos,_pos-InitPos))
else
Result:=CIllegalConvType;
end;
function TOldPhysUnitParser.getVariantNum: Variant;
var Ch: char;
state: Integer;
deg,min: Integer;
sec: Real;
function TryExponent: Boolean;
begin
Result:=(ch='e') or (ch='E');
if Result then begin
inc(_pos);
if _pos>Length(_str) then begin
putBack;
Raise EParserError.CreateFmt(UnexpectedEndOfString,[GetString]);
end;
ch:=_str[_pos];
if (ch='-') or (ch='+') then state:=4
else if IsNumberSymbol(ch) then state:=5
else begin
putBack;
Raise EParserError.CreateFmt(UnknownSymbolAfterExponent,[GetString]);
end;
end;
end;
procedure TryImaginary;
begin
if (ch='i') or (ch='I') or (ch='j') or (ch='J') then
inc(_pos);
end;
begin
Result:=Unassigned;
//в самом числе не может содержаться никаких пробелов!
skip_spaces;
fBackupPos:=_pos;
state:=0;
while (_pos<=Length(_str)) do begin
Ch:=_str[_pos];
case state of
0: begin
if IsNumberSymbol(ch) then state:=1 else begin
putBack;
Raise EParserError.CreateFmt(DigitExpected,[GetString]);
end;
end;
1: begin
if not IsNumberSymbol(ch) then
if (ch='.') or (ch=',') then begin
state:=2;
_str[_pos]:=DecimalSeparator;
end
else if (ch='d') or (ch='D') or (ch='°') then begin
deg:=StrToInt(MidStr(_str,fBackupPos,_pos-fBackupPos));
getChar;
min:=getInt;
if getChar<>'''' then Raise EParserError.Create(MinutesExpected);
sec:=getFloat;
ch:=getChar;
if (ch<>'"') and (getChar<>'''') then Raise EParserError.Create(SecondsExpected);
Result:=VarWithUnitCreateFromVariant(deg+min/60+sec/3600,auDMS);
Exit;
end
else if not TryExponent then begin
TryImaginary;
break;
end;
end;
2: if IsNumberSymbol(ch) then state:=3 else begin
putBack;
Raise EParserError.CreateFmt(DigitExpectedAfterDecimalSeparator,[GetString]);
end;
3: if not IsNumberSymbol(ch) then
if not TryExponent then begin
TryImaginary;
break;
end;
4: if IsNumberSymbol(ch) then state:=5 else begin
putBack;
Raise EParserError.CreateFmt(DigitExpectedAfterExponent,[GetString]);
end;
5: if not IsNumberSymbol(ch) then begin
TryImaginary;
break;
end;
end;
inc(_pos);
end;
if state=0 then Raise EParserError.Create('getVariantNum: empty expression');
if state=2 then begin
PutBack;
Raise EParserError.CreateFmt(DigitExpectedAfterDecimalSeparator,[GetString]);
end;
if state=4 then begin
PutBack;
Raise EParserError.CreateFmt(DigitExpectedAfterExponent,[GetString]);
end;
if (UpperCase(_str[_pos-1])='I') or (UpperCase(_str[_pos-1])='J') then
Result:=VarComplexCreate(0,StrToFloat(MidStr(_str,fBackupPos,_pos-fBackupPos-1)))
else
Result:=StrToFloat(MidStr(_str,fBackupPos,_pos-fBackupPos));
end;
procedure InitializePhysUnitLib;
var nodim: TDerivedConvFamily;
begin
//новый тип Variant'а
FreeAndNil(UnitPrefixes);
UnitPrefixes:=TOldUnitPrefixes.Create(nil);
BaseFamilyEntries:=TObjectList.create;
DerivedFamilyEntries:=TObjectList.Create;
//ключевые типы, их нужно задать в коде
UnityPhysConstants:=TFundamentalPhysConstants.Create(nil);
//пусть пустой, но он нам нужен, чтобы не проверять на nil
nodim:=TDerivedConvFamily.Create(nil);
cbDimensionless:=RegisterConversionFamily('Dimensionless');
duUnity:=RegisterConversionType(cbDimensionless,'',1);
nodim.fConvFamily:=cbDimensionless;
nodim.fBaseConvType:=duUnity;
nodim.Lang:='Any';
DerivedFamilyEntries.Add(nodim);
cbAngle:=RegisterConversionFamily('Angle');
auDMS:=RegisterConversionType(cbAngle,'dms',pi/180);
auRadian:=RegisterConversionType(cbAngle,'rad',1);
ListOfUnitsWithAllowedPrefixes.Add(Pointer(auRadian),nil);
default_dir:=GetCurrentDir+'\data\PhysUnits\';
NewConvFamilies;
end;
procedure FinalizePhysUnitLib;
var i: Integer;
begin
FreeAndNil(UnityPhysConstants);
if Assigned(DerivedFamilyEntries) then
for i:=0 to DerivedFamilyEntries.Count-1 do
UnregisterConversionFamily(TDerivedConvFamily(DerivedFamilyEntries[i]).fConvFamily);
if Assigned(DerivedFamilyEntries) then
for i:=0 to BaseFamilyEntries.Count-1 do
UnregisterConversionFamily(TBaseConvFamily(BaseFamilyEntries[i]).fConvFamily);
SetLength(AffineUnits,0);
FreeAndNil(DerivedFamilyEntries);
FreeAndNil(BaseFamilyEntries);
FreeAndNil(UnitPrefixes);
end;
initialization
RegisterClasses([TBaseConvFamily,TDerivedConvFamily,TFundamentalPhysConstants,TOldUnitPrefixes]);
RegisterIntegerConsts(TypeInfo(TConvFamily),NameToFamily,FamilyToName);
RegisterIntegerConsts(TypeInfo(TConvType),NameToConv,ConvToName);
GConvUnitToStrFmt:='%g %s';
UnitPrefixes:=TOldUnitPrefixes.Create(nil);
VarWithUnitType:=TVariantWithUnitType.Create;
PhysUnitLanguage:='English';
ListOfUnitsWithAllowedPrefixes:=TBucketList.Create;
finalization
ListOfUnitsWithAllowedPrefixes.Free;
FinalizePhysUnitLib;
FreeAndNil(VarWithUnitType);
FreeAndNil(UnitPrefixes);
end.
|
unit AnimationCtrl;
interface
uses
Windows,
Classes, Controls;
type
TAnimationControl =
class( TWinControl )
public
constructor Create( aOwner : TComponent ); override;
destructor Destroy; override;
protected
procedure CreateParams( var Params : TCreateParams ); override;
private
procedure Open( aFilename : string );
procedure Play( aFrom, aTo, aRep : integer );
procedure Stop;
procedure Close;
procedure Seek( aFrame : integer );
private
fCentered : boolean;
fTransparent : boolean;
fAutoPlay : boolean;
fUseTimers : boolean;
fFileName : string;
private
procedure SetFileName( aFileName : string );
public
property FileName : string read fFileName write SetFileName;
end;
implementation
uses
Messages, SysUtils, CommCtrl;
const
AnimateClass = 'SysAnimate32';
const
ACS_CENTER = $0001;
ACS_TRANSPARENT = $0002;
ACS_AUTOPLAY = $0004;
ACS_TIMER = $0008; // don't use threads... use timers
const
ACM_OPENA = WM_USER + 100;
ACM_OPENW = WM_USER + 103;
ACM_OPEN = ACM_OPENA;
const
ACM_PLAY = WM_USER + 101;
ACM_STOP = WM_USER + 102;
const
ACN_START = 1;
ACN_STOP = 2;
type
EAnimControl = class(Exception);
constructor TAnimationControl.Create( aOwner : TComponent );
begin
inherited;
Width := 100;
Height := 100;
fCentered := true;
fTransparent := true;
fAutoPlay := true;
end;
destructor TAnimationControl.Destroy;
begin
inherited;
end;
procedure TAnimationControl.CreateParams(var Params: TCreateParams);
begin
InitCommonControls;
inherited CreateParams( Params );
CreateSubClass( Params, AnimateClass );
with Params do
begin
if fCentered
then Style := Style or ACS_CENTER;
if fTransparent
then Style := Style or ACS_TRANSPARENT;
if fAutoPlay
then Style := Style or ACS_AUTOPLAY;
if fUseTimers
then Style := Style or ACS_TIMER;
end;
end;
procedure TAnimationControl.Open( aFilename : string );
begin
if SendMessage( Handle, ACM_OPEN, 0, longint(pchar(aFileName)) ) = 0
then raise EAnimControl.Create( 'Cannot open animation' );
end;
procedure TAnimationControl.Play( aFrom, aTo, aRep : integer );
begin
if SendMessage( Handle, ACM_PLAY, aRep, MakeLong(aFrom, aTo) ) = 0
then raise EAnimControl.Create( 'Cannot play animation' );
end;
procedure TAnimationControl.Stop;
begin
if SendMessage( Handle, ACM_STOP, 0, 0 ) = 0
then raise EAnimControl.Create( 'Cannot stop animation' );
end;
procedure TAnimationControl.Close;
begin
if SendMessage( Handle, ACM_OPEN, 0, 0 ) = 0
then raise EAnimControl.Create( 'Cannot close animation' );
end;
procedure TAnimationControl.Seek( aFrame : integer );
begin
Play( aFrame, aFrame, 1 );
end;
procedure TAnimationControl.SetFileName( aFileName : string );
begin
fFileName := aFileName;
Open( fFileName );
end;
end.
|
unit uFormMessage;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uFormBasic, System.ImageList,
Vcl.ImgList, cxImageList, cxGraphics,
System.Actions, Vcl.ActnList, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore,
dxSkinsDefaultPainters, cxImage, cxTextEdit, cxMemo, dxGDIPlusClasses,
Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Imaging.pngimage, cxLabel;
type
TypeMessage = (tmWarning, tmError, tmInformation, tmQuestion, tmFactory);
TypeButton = (tbYes, tbNo, tbOK, tbCancel);
TfrmMessage = class(TfrmBasic)
ActionList: TActionList;
cxImageList: TcxImageList;
cxImage: TcxImage;
cxMemo: TcxMemo;
actYes: TAction;
actNo: TAction;
actCancel: TAction;
btnYes: TButton;
btnNo: TButton;
btnCancel: TButton;
SpeedButton: TSpeedButton;
actPrinScreen: TAction;
actOpenImage: TAction;
actOK: TAction;
Bevel1: TBevel;
cxTitle: TcxLabel;
procedure actYesExecute(Sender: TObject);
procedure actNoExecute(Sender: TObject);
procedure actCancelExecute(Sender: TObject);
procedure actOKExecute(Sender: TObject);
procedure actPrinScreenExecute(Sender: TObject);
procedure actOpenImageExecute(Sender: TObject);
private
FoTypeMessage: TypeMessage;
FbShowCancel: Boolean;
function LoadImageNameFromResource: string;
function ShowInternalMessage(const pTypeMessage: TMsgDlgType;
const psMessage: string; const pbShowCancel: boolean = False): integer;
procedure SetTypeMessage(const poTypeMEssage: TMsgDlgType; const
pbShowCancel: Boolean);
procedure SetImage;
procedure SetTitle;
procedure SetMessage(const psMessage: string);
procedure SetButton;
procedure HideButtons;
procedure RestoreButtonActions;
public
class function ShowError(const psMensagem: string): integer;
class procedure ShowErrorDefault(const psMessage: string = '');
class function ShowQuestion(const psMensagem: string; const pbShowCancel:
boolean = False): integer;
class function ShowAtention(const psMensagem: string): Integer;
class function ShowInformation(const psMensagem: string): Integer;
class function ShowFactory(const psMensagem: string): Integer;
end;
var
frmMessage: TfrmMessage;
implementation
{$R *.dfm}
{ TfrmMessage }
procedure TfrmMessage.actCancelExecute(Sender: TObject);
begin
inherited;
Close;
ModalResult := mrCancel;
end;
procedure TfrmMessage.actNoExecute(Sender: TObject);
begin
inherited;
Close;
ModalResult := mrNo;
end;
procedure TfrmMessage.actOKExecute(Sender: TObject);
begin
inherited;
Close;
ModalResult := mrOk;
end;
procedure TfrmMessage.actOpenImageExecute(Sender: TObject);
begin
inherited;
//
end;
procedure TfrmMessage.actPrinScreenExecute(Sender: TObject);
begin
inherited;
//
end;
procedure TfrmMessage.actYesExecute(Sender: TObject);
begin
inherited;
Close;
ModalResult := mrYes;
end;
procedure TfrmMessage.HideButtons;
begin
btnYes.Hide;
btnNo.Hide;
btnCancel.Hide;
SpeedButton.Hide;
end;
function TfrmMessage.LoadImageNameFromResource:
string;
begin
case FoTypeMessage of
tmWarning: Result := 'tmWarning';
tmError: Result := 'tmError';
tmInformation: Result := 'tmInformation';
tmQuestion: Result := 'tmQuestion';
else
Result := 'tmFactory';
end;
end;
procedure TfrmMessage.RestoreButtonActions;
begin
btnYes.Action := actYes;
btnNo.Action := actNo;
btnCancel.Action := actCancel;
end;
procedure TfrmMessage.SetButton;
begin
RestoreButtonActions;
HideButtons;
case FoTypeMessage of
tmError:
begin
btnCancel.Action := actOK;
btnCancel.Show;
btnCancel.Default := True;
SpeedButton.Show;
end;
tmWarning,
tmInformation,
tmFactory:
begin
btnCancel.Action := actOK;
btnCancel.Show;
btnCancel.Default := True;
end
else
begin
btnYes.Show;
btnNo.Show;
btnNo.Default := True;
btnCancel.Show;
if not FbShowCancel then
begin
btnYes.Hide;
btnNo.Action := actYes;
btnNo.Default := False;
btnCancel.Action := actNo;
btnCancel.Default := True;
end;
end;
end;
end;
procedure TfrmMessage.SetImage;
var
sResourceName: string;
oPngImage: TPngImage;
begin
oPngImage := TPngImage.Create;
try
sResourceName := LoadImageNameFromResource;
try
oPngImage.LoadFromResourceName(HInstance, sResourceName);
cxImage.Picture.Graphic := oPngImage;
except
//
end;
finally
oPngImage.Free;
end;
end;
procedure TfrmMessage.SetMessage(const psMessage: string);
begin
cxMemo.Lines.Clear;
cxMemo.Lines.Text := psMessage;
end;
procedure TfrmMessage.SetTitle;
begin
Caption := 'Factory ERP';
case FoTypeMessage of
tmWarning: cxTitle.Caption := 'Atenção';
tmError: cxTitle.Caption := 'Erro';
tmInformation: cxTitle.Caption := 'Informação';
tmQuestion: cxTitle.Caption := 'Pergunta'
else
cxTitle.Caption := 'Factory';
end;
end;
procedure TfrmMessage.SetTypeMessage(const poTypeMessage: TMsgDlgType; const
pbShowCancel: Boolean);
begin
case poTypeMessage of
TMsgDlgType.mtWarning: FoTypeMessage := tmWarning;
TMsgDlgType.mtError: FoTypeMessage := tmError;
TMsgDlgType.mtInformation: FoTypeMessage := tmInformation;
TMsgDlgType.mtConfirmation: FoTypeMessage := tmQuestion
else
FoTypeMessage := tmFactory;
end;
FbShowCancel := pbShowCancel;
end;
class function TfrmMessage.ShowAtention(const psMensagem: string): Integer;
begin
Result := frmMessage.ShowInternalMessage(mtWarning, psMensagem);
end;
class function TfrmMessage.ShowError(const psMensagem: string): integer;
begin
Result := frmMessage.ShowInternalMessage(mtError, psMensagem);
end;
class procedure TfrmMessage.ShowErrorDefault(const psMessage: string);
begin
frmMessage.ShowInternalMessage(mtError, psMessage);
end;
class function TfrmMessage.ShowFactory(const psMensagem: string): Integer;
begin
Result := frmMessage.ShowInternalMessage(mtCustom, psMensagem);
end;
class function TfrmMessage.ShowInformation(const psMensagem: string): Integer;
begin
Result := frmMessage.ShowInternalMessage(mtInformation, psMensagem);
end;
function TfrmMessage.ShowInternalMessage(const pTypeMessage: TMsgDlgType; const
psMessage: string;
const pbShowCancel: boolean): integer;
begin
try
if not Assigned(frmMessage) then
frmMessage := TfrmMessage.Create(Application);
frmMessage.SetTypeMessage(pTypeMessage, pbShowCancel);
frmMessage.SetImage;
frmMessage.SetTitle;
frmMessage.SetButton;
frmMessage.SetMessage(psMessage);
frmMessage.ShowModal;
Result := frmMessage.ModalResult;
finally
FreeAndNil(frmMessage);
end;
end;
class function TfrmMessage.ShowQuestion(const psMensagem: string; const
pbShowCancel: boolean): integer;
begin
Result := frmMessage.ShowInternalMessage(mtConfirmation, psMensagem,
pbShowCancel);
end;
end.
|
{************************************}
{ }
{ ATImageBox Component }
{ Copyright (C) Alexey Torgashin }
{ http://www.uvviewsoft.com }
{ }
{************************************}
{$BOOLEVAL OFF} //Short boolean evaluation required
{$I ATImageBoxOptions.inc} //ATImageBox options
unit ATImageBox;
interface
uses
Windows, Messages, Classes, Controls, Graphics,
StdCtrls, ExtCtrls,
{$ifdef TNT} TntGraphics, {$endif}
Forms;
const
cViewerDefaultResampleDelay = 300;
cViewerImageScales: array[1 .. 33] of Integer = (
1, 2, 4, 7, 10, 15, 20, 25, 30,
40, 50, 60, 70, 80, 90, 100,
125, 150, 175, 200, 250, 300, 350, 400, 450, 500,
600, 700, 800, 1000, 1200, 1400, 1600);
type
TPictureWide = {$ifdef TNT}TTntPicture{$else}TPicture{$endif};
TATScrollAltEvent = procedure(Sender: TObject; Inc: Boolean) of object;
TATOnAfterPaint = procedure(Sender: TObject; aCanvas: TCanvas; const aDrawRec: TRect) of object;
type
TATImage = class(TGraphicControl)
private
FPicture: TPictureWide;
FOnPaint: TNotifyEvent;
FOnProgress: TProgressEvent;
FOnAfterPaint: TATOnAfterPaint;
FStretch: Boolean;
FCenter: Boolean;
FIncrementalDisplay: Boolean;
FTransparent: Boolean;
FResample: Boolean;
FResampleBackColor: TColor;
FDrawing: Boolean;
FProportional: Boolean;
FTimer: TTimer; //Helper timer to do resampling after a delay
procedure PictureChanged(Sender: TObject);
procedure SetCenter(Value: Boolean);
procedure SetPicture(Value: TPictureWide);
procedure SetStretch(Value: Boolean);
procedure SetTransparent(Value: Boolean);
procedure SetProportional(Value: Boolean);
procedure SetResample(Value: Boolean);
procedure TimerTimer(Sender: TObject);
procedure PaintResampled;
function GetResampleDelay: Integer;
procedure SetResampleDelay(AValue: Integer);
protected
function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override;
function DestRect: TRect;
function DoPaletteChange: Boolean;
function GetPalette: HPALETTE; override;
procedure Paint; override;
procedure Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string); dynamic;
procedure DoExtraPaint(const aRect: TRect);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property Anchors;
property AutoSize;
property Center: Boolean read FCenter write SetCenter default False;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property IncrementalDisplay: Boolean read FIncrementalDisplay write FIncrementalDisplay default False;
property ParentShowHint;
property Picture: TPictureWide read FPicture write SetPicture;
property PopupMenu;
property Proportional: Boolean read FProportional write SetProportional default false;
property ShowHint;
property Stretch: Boolean read FStretch write SetStretch default False;
property Transparent: Boolean read FTransparent write SetTransparent default False;
property Resample: Boolean read FResample write SetResample default False;
property ResampleDelay: Integer read GetResampleDelay write SetResampleDelay default cViewerDefaultResampleDelay;
property ResampleBackColor: TColor read FResampleBackColor write FResampleBackColor default clWhite;
property Visible;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
property OnProgress: TProgressEvent read FOnProgress write FOnProgress;
property OnStartDock;
property OnStartDrag;
property OnAfterPaint: TATOnAfterPaint read FOnAfterPaint write FOnAfterPaint;
end;
type
TATImageBox = class(TScrollBox)
private
FFocusable: Boolean;
FIsGif: Boolean;
FImageGif: TImage;
FImage: TATImage;
FImageLabel: TLabel;
FImageWidth: Integer;
FImageHeight: Integer;
FImageFit,
FImageFitOnlyBig,
FImageFitWidth,
FImageFitHeight,
FImageCenter: Boolean;
FImageScale: Integer;
FImageKeepPosition: Boolean;
FImageDrag: Boolean;
FImageDragCursor: TCursor;
FImageScaleCursor: TCursor;
FImageDragging: Boolean;
FImageDraggingPoint: TPoint;
FImageMouseDown: Boolean;
FOnScroll: TNotifyEvent;
FOnScrollAlt: TATScrollAltEvent;
FOnOptionsChange: TNotifyEvent;
procedure DoScroll;
procedure DoScrollAlt(AInc: Boolean);
procedure DoOptionsChange;
procedure MouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure MouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure UpdateImagePosition(AResetPosition: Boolean = False);
procedure UpdateImageLabelPosition;
procedure SetImageFit(AValue: Boolean);
procedure SetImageFitOnlyBig(AValue: Boolean);
procedure SetImageFitWidth(AValue: Boolean);
procedure SetImageFitHeight(AValue: Boolean);
procedure SetImageCenter(AValue: Boolean);
procedure SetImageScale(AValue: Integer);
procedure ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure ImagePaint(Sender: TObject);
procedure ImageProgress(Sender: TObject;
Stage: TProgressStage; PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string);
function GetOnAfterPaint: TATOnAfterPaint;
procedure SetOnAfterPaint(Value: TATOnAfterPaint);
public
constructor Create(AOwner: TComponent); override;
procedure LoadFromFile(const FN: string);
procedure LoadBitmap(ABitmap: TBitmap; ATransp: Boolean);
procedure LoadPicture(APicture: TPicture);
procedure Unload;
procedure UpdateInfo;
function CurrentPicture: TPicture;
procedure IncreaseImageScale(AIncrement: Boolean);
property Image: TATImage read FImage;
property ImageLabel: TLabel read FImageLabel;
property ImageWidth: Integer read FImageWidth;
property ImageHeight: Integer read FImageHeight;
property ImageScale: Integer read FImageScale write SetImageScale;
protected
procedure WMHScroll(var Msg: TMessage); message WM_HSCROLL;
procedure WMVScroll(var Msg: TMessage); message WM_VSCROLL;
procedure WMGetDlgCode(var Message: TMessage); message WM_GETDLGCODE;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Resize; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
published
property Focusable: Boolean read FFocusable write FFocusable default True;
property ImageFitToWindow: Boolean read FImageFit write SetImageFit default False;
property ImageFitOnlyBig: Boolean read FImageFitOnlyBig write SetImageFitOnlyBig default True;
property ImageFitWidth: Boolean read FImageFitWidth write SetImageFitWidth default False;
property ImageFitHeight: Boolean read FImageFitHeight write SetImageFitHeight default False;
property ImageCenter: Boolean read FImageCenter write SetImageCenter default True;
property ImageKeepPosition: Boolean read FImageKeepPosition write FImageKeepPosition default True;
property ImageDrag: Boolean read FImageDrag write FImageDrag default True;
property ImageDragCursor: TCursor read FImageDragCursor write FImageDragCursor default crSizeAll;
property ImageScaleCursor: TCursor read FImageScaleCursor write FImageScaleCursor default crSizeNS;
property OnScroll: TNotifyEvent read FOnScroll write FOnScroll;
property OnScrollAlt: TATScrollAltEvent read FOnScrollAlt write FOnScrollAlt;
property OnOptionsChange: TNotifyEvent read FOnOptionsChange write FOnOptionsChange;
property OnAfterPaint: TATOnAfterPaint read GetOnAfterPaint write SetOnAfterPaint;
end;
procedure Register;
implementation
uses
SysUtils
{$ifdef GIF} , GifImage {$endif};
{ Constants }
const
cImageLineSize = 50; //Line size: pixels to scroll by arrows and mouse sheel
cImageGapSize = 20; //Gap size: PgUp/PgDn/Home/End scroll by control size minus gap size
{ Helper functions }
function IMax(N1, N2: Integer): Integer;
begin
if N1 >= N2 then
Result := N1
else
Result := N2;
end;
function IMin(N1, N2: Integer): Integer;
begin
if N1 <= N2 then
Result := N1
else
Result := N2;
end;
{
We need to "fix" icon sizes. Icon should be drawn once before its sizes are to be read.
http://qc.codegear.com/wc/qcmain.aspx?d=6018
}
procedure FixIcon(AIcon: TIcon);
var
Bmp: TBitmap;
begin
try
Bmp:= TBitmap.Create;
try
Bmp.PixelFormat := pf24bit;
Bmp.Canvas.Draw(0, 0, AIcon);
finally
Bmp.Free;
end;
except
end;
end;
{
Scaling doesn't work with icons. So, we need to convert icon to a bitmap,
preferrably with PixelFormat = pf24bit.
}
function FixImageFormat(AImage: TATImage; ABackColor: TColor): Boolean;
var
bmp: TBitmap;
begin
Result := True;
with AImage.Picture do
if (not (Graphic is TBitmap)) or ((TBitmap(Graphic).PixelFormat <> pf24Bit)) then
try
bmp := TBitmap.Create;
try
bmp.PixelFormat := pf24bit;
bmp.Width := Graphic.Width;
bmp.Height := Graphic.Height;
bmp.Canvas.Brush.Color:= ABackColor;
bmp.Canvas.FillRect(Rect(0, 0, bmp.Width, bmp.Height));
bmp.Canvas.Draw(0, 0, Graphic);
AImage.Picture.Graphic := bmp;
finally
bmp.Free;
end;
except
Result := False;
end;
end;
{ TATImage }
constructor TATImage.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable];
FPicture := TPictureWide.Create;
FPicture.OnChange := PictureChanged;
FPicture.OnProgress := Progress;
Height := 105;
Width := 105;
FTimer := TTimer.Create(Self);
FTimer.Enabled := False;
FTimer.Interval := cViewerDefaultResampleDelay;
FTimer.OnTimer := TimerTimer;
FResampleBackColor := clWhite;
FOnAfterPaint := nil;
end;
destructor TATImage.Destroy;
begin
FPicture.Free;
inherited Destroy;
end;
function TATImage.GetPalette: HPALETTE;
begin
Result := 0;
if FPicture.Graphic <> nil then
Result := FPicture.Graphic.Palette;
end;
function TATImage.DestRect: TRect;
var
w, h, cw, ch: Integer;
xyaspect: Double;
begin
w := Picture.Width;
h := Picture.Height;
cw := ClientWidth;
ch := ClientHeight;
if Stretch or (Proportional and ((w > cw) or (h > ch))) then
begin
if Proportional and (w > 0) and (h > 0) then
begin
xyaspect := w / h;
if w > h then
begin
w := cw;
h := Trunc(cw / xyaspect);
if h > ch then // woops, too big
begin
h := ch;
w := Trunc(ch * xyaspect);
end;
end
else
begin
h := ch;
w := Trunc(ch * xyaspect);
if w > cw then // woops, too big
begin
w := cw;
h := Trunc(cw / xyaspect);
end;
end;
end
else
begin
w := cw;
h := ch;
end;
end;
with Result do
begin
Left := 0;
Top := 0;
Right := w;
Bottom := h;
end;
if Center then
OffsetRect(Result, (cw - w) div 2, (ch - h) div 2);
end;
procedure TATImage.Paint;
var
Save: Boolean;
tmpRect: TRect;
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
tmpRect := DestRect;
//Do the standard rendering
with inherited Canvas do
StretchDraw(tmpRect, Picture.Graphic);
DoExtraPaint(tmpRect);
//Do the delayed resampling rendering
if FResample
//Do not resample metafiles:
and not (Picture.Graphic is TMetafile)
(*ifdef GIF}
//Do not resample *animated* GIF images:
and not ((Picture.Graphic is TGifImage) and ((Picture.Graphic as TGifImage).Images.Count > 1))
endif}*) then
begin
FTimer.Enabled := False;
FTimer.Enabled := True;
end;
finally
FDrawing := Save;
end;
end;
procedure TATImage.DoExtraPaint(const aRect: TRect);
begin
if Assigned(FOnAfterPaint) then
FOnAfterPaint(Self, inherited Canvas, aRect);
end;
procedure TATImage.PaintResampled;
var
Bmp: TBitmap;
tmpRect: TRect;
begin
Bmp := TBitmap.Create;
try
with Bmp do
begin
PixelFormat := pf24bit;
Width := Picture.Width;
Height := Picture.Height;
Canvas.Brush.Color := FResampleBackColor;
Canvas.FillRect(Rect(0, 0, Width, Height));
Canvas.Draw(0, 0, Picture.Graphic);
end;
with inherited Canvas do
begin
tmpRect := DestRect;
SetStretchBltMode(Handle, STRETCH_HALFTONE);
SetBrushOrgEx(Handle, 0, 0, nil);
StretchBlt(
Handle,
tmpRect.Left, tmpRect.Top, tmpRect.Right - tmpRect.Left, tmpRect.Bottom - tmpRect.Top,
Bmp.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height,
SRCCOPY);
end;
finally
Bmp.Free;
end;
if Assigned(FOnPaint) then
FOnPaint(Self);
DoExtraPaint(tmpRect);
end;
function TATImage.DoPaletteChange: Boolean;
var
ParentForm: TCustomForm;
Tmp: TGraphic;
begin
Result := False;
Tmp := Picture.Graphic;
if Visible and (not (csLoading in ComponentState)) and (Tmp <> nil) and
(Tmp.PaletteModified) then
begin
if (Tmp.Palette = 0) then
Tmp.PaletteModified := False
else
begin
ParentForm := GetParentForm(Self);
if Assigned(ParentForm) and ParentForm.Active and Parentform.HandleAllocated then
begin
if FDrawing then
ParentForm.Perform(wm_QueryNewPalette, 0, 0)
else
PostMessage(ParentForm.Handle, wm_QueryNewPalette, 0, 0);
Result := True;
Tmp.PaletteModified := False;
end;
end;
end;
end;
procedure TATImage.Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string);
begin
if FIncrementalDisplay and RedrawNow then
begin
if DoPaletteChange then Update
else Paint;
end;
if Assigned(FOnProgress) then FOnProgress(Sender, Stage, PercentDone, RedrawNow, R, Msg);
end;
procedure TATImage.SetCenter(Value: Boolean);
begin
if FCenter <> Value then
begin
FCenter := Value;
PictureChanged(Self);
end;
end;
procedure TATImage.SetPicture(Value: TPictureWide);
begin
FPicture.Assign(Value);
end;
procedure TATImage.SetStretch(Value: Boolean);
begin
if Value <> FStretch then
begin
FStretch := Value;
PictureChanged(Self);
end;
end;
procedure TATImage.SetTransparent(Value: Boolean);
begin
if Value <> FTransparent then
begin
FTransparent := Value;
PictureChanged(Self);
end;
end;
procedure TATImage.SetProportional(Value: Boolean);
begin
if FProportional <> Value then
begin
FProportional := Value;
PictureChanged(Self);
end;
end;
procedure TATImage.SetResample(Value: Boolean);
begin
//Resampling works only under WinNT, since
//STRETCH_HALFTONE doesn't work under Win9x
if Win32Platform = VER_PLATFORM_WIN32_NT then
if Value <> FResample then
begin
FResample := Value;
PictureChanged(Self);
end;
end;
procedure TATImage.PictureChanged(Sender: TObject);
var
G: TGraphic;
D : TRect;
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;
D := DestRect;
if (not G.Transparent) and (D.Left <= 0) and (D.Top <= 0) and
(D.Right >= Width) and (D.Bottom >= Height) then
ControlStyle := ControlStyle + [csOpaque]
else // picture might not cover entire clientrect
ControlStyle := ControlStyle - [csOpaque];
if DoPaletteChange and FDrawing then Update;
end
else ControlStyle := ControlStyle - [csOpaque];
if not FDrawing then Invalidate;
end;
function TATImage.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean;
begin
Result := True;
if not (csDesigning in ComponentState) or (Picture.Width > 0) and
(Picture.Height > 0) then
begin
if Align in [alNone, alLeft, alRight] then
NewWidth := Picture.Width;
if Align in [alNone, alTop, alBottom] then
NewHeight := Picture.Height;
end;
end;
procedure TATImage.TimerTimer(Sender: TObject);
begin
FTimer.Enabled := False;
PaintResampled;
end;
function TATImage.GetResampleDelay: Integer;
begin
Result := FTimer.Interval;
end;
procedure TATImage.SetResampleDelay(AValue: Integer);
begin
FTimer.Interval := AValue;
end;
{ TATImageBox }
constructor TATImageBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//Init inherited properties
AutoScroll := False;
DoubleBuffered := True; //To remove flicker when new image is loaded
HorzScrollBar.Tracking := True;
VertScrollBar.Tracking := True;
//Init fields
FFocusable:= True;
FImageFit := False;
FImageFitOnlyBig := True;
FImageFitWidth := False;
FImageFitHeight := False;
FImageCenter := True;
FImageWidth := 0;
FImageHeight := 0;
FImageScale := 100;
FImageKeepPosition := True;
FImageDrag := True;
FImageDragCursor := crSizeAll;
FImageScaleCursor := crSizeNS;
FImageDragging := False;
FImageDraggingPoint := Point(0, 0);
FImageMouseDown := False;
//Init objects
FImageGif := TImage.Create(Self);
with FImageGif do
begin
Parent := Self;
Align := alClient;
AutoSize := False;
Center := True;
Proportional := True;
end;
FImage := TATImage.Create(Self);
with FImage do
begin
Parent := Self;
Align := alNone;
AutoSize := False;
IncrementalDisplay := True;
OnMouseDown := ImageMouseDown;
OnMouseUp := ImageMouseUp;
OnMouseMove := ImageMouseMove;
OnPaint := ImagePaint;
OnProgress := ImageProgress;
end;
FImageLabel := TLabel.Create(Self);
with FImageLabel do
begin
Parent := Self;
Visible := False;
Brush.Style := bsClear;
Font.Style := [fsBold];
Font.Color := clWhite;
Caption := '';
end;
//Init event handlers
OnMouseWheelUp := MouseWheelUp;
OnMouseWheelDown := MouseWheelDown;
end;
procedure TATImageBox.DoScroll;
begin
UpdateImageLabelPosition;
if Assigned(FOnScroll) then
FOnScroll(Self);
end;
procedure TATImageBox.DoScrollAlt(AInc: Boolean);
begin
if Assigned(FOnScrollAlt) then
FOnScrollAlt(Self, AInc);
end;
procedure TATImageBox.WMHScroll(var Msg: TMessage);
begin
inherited;
DoScroll;
end;
procedure TATImageBox.WMVScroll(var Msg: TMessage);
begin
inherited;
DoScroll;
end;
procedure TATImageBox.MouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
if (Shift = []) then
begin
with VertScrollBar do
Position := Position - cImageLineSize;
DoScroll;
end
else
if (Shift = [ssShift]) then
begin
with HorzScrollBar do
Position := Position - cImageLineSize;
DoScroll;
end
else
if (Shift = [ssCtrl]) or FImageMouseDown then
begin
IncreaseImageScale(True);
FImageDragging := False;
if FImageMouseDown then
Screen.Cursor := FImageScaleCursor;
end;
Handled := True;
end;
procedure TATImageBox.MouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
if (Shift = []) then
begin
with VertScrollBar do
Position := Position + cImageLineSize;
DoScroll;
end
else
if (Shift = [ssShift]) then
begin
with HorzScrollBar do
Position := Position + cImageLineSize;
DoScroll;
end
else
if (Shift = [ssCtrl]) or FImageMouseDown then
begin
IncreaseImageScale(False);
FImageDragging := False;
if FImageMouseDown then
Screen.Cursor := FImageScaleCursor;
end;
Handled := True;
end;
procedure TATImageBox.WMGetDlgCode(var Message: TMessage);
begin
Message.Result := DLGC_WANTARROWS;
end;
procedure TATImageBox.KeyDown(var Key: Word; Shift: TShiftState);
function PageSize(AClientSize: Integer): Integer;
begin
Result := IMax(AClientSize - cImageGapSize, AClientSize div 3 * 2);
end;
begin
case Key of
VK_LEFT:
begin
if Shift = [] then
begin
with HorzScrollBar do
Position := Position - cImageLineSize;
DoScroll;
Key := 0;
end
else
if Shift = [ssCtrl] then
begin
with HorzScrollBar do
Position := 0;
DoScroll;
Key := 0;
end
else
if Shift = [ssAlt] then
begin
DoScrollAlt(False);
Key := 0;
end;
end;
VK_RIGHT:
begin
if Shift = [] then
begin
with HorzScrollBar do
Position := Position + cImageLineSize;
DoScroll;
Key := 0;
end
else
if Shift = [ssCtrl] then
begin
with HorzScrollBar do
Position := Range;
DoScroll;
Key := 0;
end
else
if Shift = [ssAlt] then
begin
DoScrollAlt(True);
Key := 0;
end;
end;
VK_HOME:
if Shift = [] then
begin
with HorzScrollBar do
Position := Position - PageSize(ClientWidth);
DoScroll;
Key := 0;
end;
VK_END:
if Shift = [] then
begin
with HorzScrollBar do
Position := Position + PageSize(ClientWidth);
DoScroll;
Key := 0;
end;
VK_UP:
begin
if Shift = [] then
begin
with VertScrollBar do
Position := Position - cImageLineSize;
DoScroll;
Key := 0;
end
else
if Shift = [ssCtrl] then
begin
with VertScrollBar do
Position := 0;
DoScroll;
Key := 0;
end;
end;
VK_DOWN:
begin
if Shift = [] then
begin
with VertScrollBar do
Position := Position + cImageLineSize;
DoScroll;
Key := 0;
end
else
if Shift = [ssCtrl] then
begin
with VertScrollBar do
Position := Range;
DoScroll;
Key := 0;
end;
end;
VK_PRIOR:
if Shift = [] then
begin
with VertScrollBar do
Position := Position - PageSize(ClientHeight);
DoScroll;
Key := 0;
end;
VK_NEXT:
if Shift = [] then
begin
with VertScrollBar do
Position := Position + PageSize(ClientHeight);
DoScroll;
Key := 0;
end;
end;
end;
procedure TATImageBox.UpdateImagePosition(AResetPosition: Boolean = False);
var
AKeepPosition: Boolean;
AWidth, AHeight,
ANewWidth, ANewHeight,
ANewLeft, ANewTop,
AScrollMaxX, AScrollMaxY: Integer;
ARatio, AImageRatio,
ACenterRatioX, ACenterRatioY: Double;
begin
AKeepPosition := FImageKeepPosition and (not AResetPosition);
AWidth := ClientWidth;
AHeight := ClientHeight;
//Save center position, need to restore it later
ACenterRatioX := 0;
ACenterRatioY := 0;
if FImage.Width > 0 then
begin
if FImage.Left >= 0 then
ACenterRatioX := (AWidth div 2 - FImage.Left) / FImage.Width
else
ACenterRatioX := (AWidth div 2 + HorzScrollBar.Position) / FImage.Width;
end;
if FImage.Height > 0 then
begin
if FImage.Top >= 0 then
ACenterRatioY := (AHeight div 2 - FImage.Top) / FImage.Height
else
ACenterRatioY := (AHeight div 2 + VertScrollBar.Position) / FImage.Height;
end;
//Set controls params
if not AKeepPosition then
begin
HorzScrollBar.Position := 0;
VertScrollBar.Position := 0;
end;
AutoScroll := not FImageFit;
FImage.AutoSize := (not FImageFit) and (FImageScale = 100);
FImage.Stretch := not FImage.AutoSize;
{
//Note: commented, because we convert icon to bitmap in UpdateInfo.
//Work around VCL draw bug for icons:
if FImageIsIcon then
begin
FImage.AutoSize := False;
FImage.Stretch := True;
FImage.Width := FImageWidth;
FImage.Height := FImageHeight;
end;
}
//Fit and recalculate ImageScale
FImage.Left := 0;
FImage.Top := 0;
AWidth := ClientWidth;
AHeight := ClientHeight;
if FImageFit then
begin
{
//Note: code commented in as it causes wrong scaling sometimes.
//If image is already fit, don't scale it:
if (FImage.Width = AWidth) and
(FImage.Height = AHeight) then
begin
ANewWidth := FImage.Width;
ANewHeight := FImage.Height;
end
else
}
//Need to scale
begin
ANewWidth := FImageWidth;
ANewHeight := FImageHeight;
if FImageFitOnlyBig and
(FImageWidth <= AWidth) and (FImageHeight <= AHeight) then
begin
FImageScale := 100;
end
else
begin
if (AWidth > 0) and (AHeight > 0) and
(FImageWidth > 0) and (FImageHeight > 0) then
begin
ARatio := AWidth / AHeight;
AImageRatio := FImageWidth / FImageHeight;
if ((ARatio >= AImageRatio) and (not FImageFitWidth)) or FImageFitHeight then
begin
//fit height
if FImageFitOnlyBig and (AHeight >= FImageHeight) then begin end
else
begin
ANewHeight := AHeight;
ANewWidth := Trunc(ANewHeight * AImageRatio);
FImageScale := AHeight * 100 div FImageHeight;
end;
end
else
begin
//fit width
if FImageFitOnlyBig and (AWidth >= FImageWidth) then begin end
else
begin
ANewWidth := AWidth;
ANewHeight := Trunc(ANewWidth / AImageRatio);
FImageScale := AWidth * 100 div FImageWidth;
end;
end;
end;
end
end
end //if FImageFit
else
begin
ANewWidth := Round(FImageWidth * FImageScale / 100);
ANewHeight := Round(FImageHeight * FImageScale / 100);
end;
//Update image position
ANewLeft := 0;
ANewTop := 0;
if FImageCenter then
begin
if AWidth > ANewWidth then
ANewLeft := (AWidth - ANewWidth) div 2;
if AHeight > ANewHeight then
ANewTop := (AHeight - ANewHeight) div 2;
end;
FImage.SetBounds(
ANewLeft - HorzScrollBar.Position,
ANewTop - VertScrollBar.Position,
ANewWidth,
ANewHeight);
//Restore saved center position
if AKeepPosition then
begin
if ANewLeft = 0 then
begin
AScrollMaxX := IMax(ANewWidth - AWidth, 0);
HorzScrollBar.Position :=
IMin(AScrollMaxX, Trunc(ACenterRatioX * ANewWidth) - AWidth div 2);
end
else
HorzScrollBar.Position := 0;
if ANewTop = 0 then
begin
AScrollMaxY := IMax(ANewHeight - AHeight, 0);
VertScrollBar.Position :=
IMin(AScrollMaxY, Trunc(ACenterRatioY * ANewHeight) - AHeight div 2);
end
else
VertScrollBar.Position := 0;
end;
//adjust range
HorzScrollbar.Range := ANewWidth;
VertScrollbar.Range := ANewHeight;
DoScroll;
end;
procedure TATImageBox.UpdateImageLabelPosition;
begin
FImageLabel.Left := 0;
FImageLabel.Top := 0;
end;
procedure TATImageBox.SetImageFit(AValue: Boolean);
begin
if AValue <> FImageFit then
begin
FImageFit := AValue;
if not FImageFit then
FImageScale := 100;
UpdateImagePosition(True);
end;
end;
procedure TATImageBox.SetImageFitOnlyBig(AValue: Boolean);
begin
if AValue <> FImageFitOnlyBig then
begin
FImageFitOnlyBig := AValue;
UpdateImagePosition(True);
end;
end;
procedure TATImageBox.SetImageCenter(AValue: Boolean);
begin
if AValue <> FImageCenter then
begin
FImageCenter := AValue;
UpdateImagePosition(True);
end;
end;
procedure TATImageBox.UpdateInfo;
begin
FImageWidth := 0;
FImageHeight := 0;
FImageScale := 100;
FImage.Visible := not FIsGif;
FImageGif.Visible := FIsGif;
if FIsGif and Assigned(FImageGif.Picture) and Assigned(FImageGif.Picture.Graphic) then
begin
FImageWidth := FImageGif.Picture.Width;
FImageHeight := FImageGif.Picture.Height;
end
else
if Assigned(FImage.Picture) and Assigned(FImage.Picture.Graphic) then
begin
if FImage.Picture.Graphic is TIcon then
begin
FImage.Transparent := False; //Icons are converted to bitmap in FixImageFormat,
//so we must clear the Transparent property,
//otherwise bitmap will look incorrectly a little
FixIcon(FImage.Picture.Graphic as TIcon);
FixImageFormat(FImage, Color);
end;
FImageWidth := FImage.Picture.Width;
FImageHeight := FImage.Picture.Height;
UpdateImagePosition(True);
end;
end;
procedure TATImageBox.Resize;
begin
inherited;
UpdateImagePosition;
end;
procedure TATImageBox.SetImageScale(AValue: Integer);
begin
Assert(
(AValue >= 0) and (AValue < MaxShort),
'Invalid scale value');
if FImageScale <> AValue then
begin
FImageScale := AValue;
FImageFit := False;
UpdateImagePosition;
DoOptionsChange;
end;
end;
procedure TATImageBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
if FFocusable then
SetFocus;
end;
procedure TATImageBox.ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if FFocusable then
SetFocus;
if (Button = mbLeft) then
begin
FImageMouseDown := True;
if FImageDrag then
begin
FImageDragging := True;
FImageDraggingPoint := Point(X, Y);
Screen.Cursor := FImageDragCursor;
end;
end;
end;
procedure TATImageBox.ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if (Button = mbLeft) then
begin
FImageMouseDown := False;
FImageDragging := False;
Screen.Cursor := crDefault;
end;
end;
procedure TATImageBox.ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if FImageDrag and FImageDragging then
begin
HorzScrollBar.Position := HorzScrollBar.Position + (FImageDraggingPoint.X - X);
VertScrollBar.Position := VertScrollBar.Position + (FImageDraggingPoint.Y - Y);
DoScroll;
end;
end;
procedure TATImageBox.IncreaseImageScale(AIncrement: Boolean);
var
i: Integer;
begin
if FIsGif then Exit;
if AIncrement then
begin
for i := Low(cViewerImageScales) to High(cViewerImageScales) do
if cViewerImageScales[i] > ImageScale then
begin
ImageScale := cViewerImageScales[i];
Break
end;
end
else
begin
for i := High(cViewerImageScales) downto Low(cViewerImageScales) do
if cViewerImageScales[i] < ImageScale then
begin
ImageScale := cViewerImageScales[i];
Break
end;
end;
end;
procedure TATImageBox.DoOptionsChange;
begin
if Assigned(FOnOptionsChange) then
FOnOptionsChange(Self);
end;
procedure TATImageBox.ImageProgress(Sender: TObject;
Stage: TProgressStage; PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string);
begin
if FImage.IncrementalDisplay then
begin
Update;
Invalidate;
end;
end;
function TATImageBox.GetOnAfterPaint: TATOnAfterPaint;
begin
Result := FImage.OnAfterPaint;
end;
procedure TATImageBox.SetOnAfterPaint(Value: TATOnAfterPaint);
begin
FImage.OnAfterPaint := Value;
end;
type
TLabelCracker = class(TLabel);
procedure TATImageBox.ImagePaint(Sender: TObject);
begin
//Debug:
//MessageBeep(MB_OK);
//Need to repaint the label since it's overdrawn by resampled image:
if FImageLabel.Visible then
TLabelCracker(FImageLabel).Paint;
end;
{ Registration }
procedure Register;
begin
RegisterComponents('Samples', [TATImageBox]);
end;
procedure TATImageBox.SetImageFitWidth(AValue: Boolean);
begin
if AValue <> FImageFitWidth then
begin
FImageFitWidth := AValue;
if AValue then
FImageFitHeight := False;
UpdateImagePosition(True);
end;
end;
procedure TATImageBox.SetImageFitHeight(AValue: Boolean);
begin
if AValue <> FImageFitHeight then
begin
FImageFitHeight := AValue;
if AValue then
FImageFitWidth := False;
UpdateImagePosition(True);
end;
end;
procedure TATImageBox.Unload;
begin
FImage.Picture := nil;
FImageGif.Picture := nil;
FIsGif := False;
UpdateInfo;
end;
procedure TATImageBox.LoadBitmap(ABitmap: TBitmap; ATransp: Boolean);
begin
Unload;
FIsGif := False;
FImage.Picture.Assign(ABitmap);
FImage.Transparent := ATransp;
UpdateInfo;
end;
procedure TATImageBox.LoadPicture(APicture: TPicture);
begin
Unload;
FIsGif := False;
FImage.Picture.Assign(APicture);
UpdateInfo;
end;
procedure TATImageBox.LoadFromFile(const FN: string);
begin
Unload;
FIsGif := UpperCase(ExtractFileExt(FN)) = '.GIF';
if FIsGif then
FImageGif.Picture.LoadFromFile(FN)
else
FImage.Picture.LoadFromFile(FN);
UpdateInfo;
end;
function TATImageBox.CurrentPicture: TPicture;
begin
if FIsGif then
Result := FImageGif.Picture
else
Result := FImage.Picture;
end;
end.
|
unit RotaImg;
{$mode objfpc}{$H+}
interface
uses
ExtCtrls, Graphics;
//rotar imagen en sentido antihorario 90 grados
procedure RotateBitmap90(const bitmap: TBitmap);
//rotar imagen en sentido horario 90 grados
procedure RotateBitmap180(const bitmap: TBitmap);
implementation
uses
IntfGraphics, LCLType;
procedure RotateBitmap90(const bitmap: TBitmap);
var
tmp: TBitmap;
src, dst: TLazIntfImage;
ImgHandle, ImgMaskHandle: HBitmap;
i, j, w, h: integer;
begin
tmp := TBitmap.create;
tmp.Width := Bitmap.Height;
tmp.Height := Bitmap.Width;
dst := TLazIntfImage.Create(0, 0);
dst.LoadFromBitmap(tmp.Handle, tmp.MaskHandle);
src := TLazIntfImage.Create(0, 0);
src.LoadFromBitmap(bitmap.Handle, bitmap.MaskHandle);
w := bitmap.width - 1;
h := bitmap.height - 1;
for i := 0 to w do
for j := 0 to h do
dst.Colors[j, w - i] := src.Colors[i, j];
dst.CreateBitmaps(ImgHandle, ImgMaskHandle, false);
tmp.Handle := ImgHandle;
tmp.MaskHandle := ImgMaskHandle;
dst.Free;
bitmap.Assign(tmp);
tmp.Free;
src.Free;
end;
procedure RotateBitmap180(const bitmap: TBitmap);
var
tmp: TBitmap;
src, dst: TLazIntfImage;
ImgHandle, ImgMaskHandle: HBitmap;
i, j, w, h: integer;
begin
tmp := TBitmap.create;
tmp.Width := Bitmap.Height;
tmp.Height := Bitmap.Width;
dst := TLazIntfImage.Create(0, 0);
dst.LoadFromBitmap(tmp.Handle, tmp.MaskHandle);
src := TLazIntfImage.Create(0, 0);
src.LoadFromBitmap(bitmap.Handle, bitmap.MaskHandle);
w := bitmap.width - 1;
h := bitmap.height - 1;
for i := 0 to w do
for j := 0 to h do
dst.Colors[h - j, i] := src.Colors[i, j];
dst.CreateBitmaps(ImgHandle, ImgMaskHandle, false);
tmp.Handle := ImgHandle;
tmp.MaskHandle := ImgMaskHandle;
dst.Free;
bitmap.Assign(tmp);
tmp.Free;
src.Free;
end;
end.
|
unit RDOUtils;
interface
uses
Windows, RDOQueries, SocketComp;
const
UnknownPriority = MAXLONG;
// String scanning utilities
function KeyWordPos( KeyWord : string; Text : string ) : integer;
procedure SkipSpaces( StringText : string; var ScanPos : integer );
function ReadIdent( StringText : string; var ScanPos : integer ) : string;
function ReadNumber( StringText : string; var ScanPos : integer ) : string;
function ReadLiteral( StringText : string; var ScanPos : integer ) : string;
function EndOfStringText( ScanPos, StringLen : integer ) : boolean;
// RDO string encoding utilities
function RDOStrEncode( str : string ) : string;
function RDOStrDecode( str : string ) : string;
function RDOWideStrEncode( str : widestring ) : widestring;
function RDOWideStrDecode( str : widestring ) : widestring;
function WideStrToStr( widestr : widestring ) : string;
function StrToWideStr( str : string ) : widestring;
// Conversion utilities
function GetVariantFromStr( VarAsStr : string ) : variant;
function GetStrFromVariant( aVariant : variant; out IllegalVType : boolean ) : string;
function GetTypeIdFromVariant( aVariant : variant; out IllegalVType : boolean ) : string;
function PriorityIdToPriority( PriorityId : char ) : integer;
function PriorityToPriorityId( Priority : integer ) : char;
// Query text manipulation
function GetQueryText( var RawText : string ) : string;
procedure SendQuery(Query : TRDOQuery; Socket : TCustomWinSocket);
function GetQueryErrorCode( Query : TRDOQuery ) : integer;
implementation
uses
SysUtils, RDOProtocol, ErrorCodes;
// Support routines
function IsDigit( aChar : char ) : boolean;
begin
Result := aChar in [ '0' .. '9' ]
end;
function IsHexaDigit( aChar : char ) : boolean;
begin
Result := ( aChar in [ '0' .. '9' ] ) or ( aChar in [ 'A' .. 'F' ] ) or ( aChar in [ 'a' .. 'f' ] )
end;
function IsLetter( aChar : char ) : boolean;
begin
Result := ( aChar in [ 'A' .. 'Z' ] ) or ( aChar in [ 'a' .. 'z' ] )
end;
function IsValidFirstIdentChar( aChar : char ) : boolean;
begin
Result := IsLetter( aChar ) or ( aChar = '_' )
end;
function IsValidIdentChar( aChar : char ) : boolean;
begin
Result := IsLetter( aChar ) or IsDigit( aChar ) or ( aChar = '_' )
end;
// String scanning utilities
function KeyWordPos( KeyWord : string; Text : string ) : integer;
var
TextIdx : integer;
TextLen : integer;
KeyWordIdx : integer;
KeyWordLen : integer;
KeyWrdPos : integer;
EndOfLiteral : boolean;
begin
KeyWrdPos := 0;
TextIdx := 1;
TextLen := Length( Text );
KeyWordLen := Length( KeyWord );
while ( TextIdx <= TextLen ) and ( KeyWrdPos = 0 ) do
if UpCase( Text[ TextIdx ] ) = UpCase( KeyWord[ 1 ] )
then
begin
KeyWordIdx := 2;
while ( KeyWordIdx <= KeyWordLen ) and ( UpCase( Text[ TextIdx + KeyWordIdx - 1 ] ) = UpCase( KeyWord[ KeyWordIdx ] ) ) do
inc( KeyWordIdx );
if KeyWordIdx > KeyWordLen
then
KeyWrdPos := TextIdx
else
inc( TextIdx )
end
else
if Text[ TextIdx ] = LiteralDelim
then
repeat
inc( TextIdx );
while ( TextIdx <= TextLen ) and ( Text[ TextIdx ] <> LiteralDelim ) do
inc( TextIdx );
inc( TextIdx );
if ( TextIdx <= TextLen ) and ( Text[ TextIdx ] = LiteralDelim )
then
EndOfLiteral := false
else
EndOfLiteral := true;
until EndOfLiteral
else
inc( TextIdx );
Result := KeyWrdPos
end;
function ReadIdent( StringText : string; var ScanPos : integer ) : string;
var
StringLen : integer;
begin
Result := '';
StringLen := Length( StringText );
if not EndOfStringText( ScanPos, StringLen ) and IsValidFirstIdentChar( StringText[ ScanPos ] )
then
begin
Result := StringText[ ScanPos ];
inc( ScanPos );
while not EndOfStringText( ScanPos, StringLen ) and IsValidIdentChar( StringText[ ScanPos ] ) do
begin
Result := Result + StringText[ ScanPos ];
inc( ScanPos )
end
end
end;
function ReadNumber( StringText : string; var ScanPos : integer ) : string;
var
StringLen : integer;
begin
Result := '';
StringLen := Length( StringText );
if not EndOfStringText( ScanPos, StringLen )
then
if IsDigit( StringText[ ScanPos ] )
then
begin
Result := StringText[ ScanPos ];
inc( ScanPos );
while not EndOfStringText( ScanPos, StringLen ) and IsDigit( StringText[ ScanPos ] ) do
begin
Result := Result + StringText[ ScanPos ];
inc( ScanPos )
end
end
else
if StringText[ ScanPos ] = '$'
then
begin
inc( ScanPos );
while not EndOfStringText( ScanPos, StringLen ) and IsHexaDigit( StringText[ ScanPos ] ) do
begin
Result := Result + StringText[ ScanPos ];
inc( ScanPos )
end
end
end;
function ReadLiteral( StringText : string; var ScanPos : integer ) : string;
var
Delimiter : char;
StringLen : integer;
EndOfLiteral : boolean;
begin
Result := '';
StringLen := Length( StringText );
if not EndOfStringText( ScanPos, StringLen )
then
begin
Delimiter := StringText[ ScanPos ];
if ( Delimiter = Quote ) or ( Delimiter = LiteralDelim )
then
begin
if not EndOfStringText( ScanPos, StringLen )
then
begin
inc( ScanPos );
repeat
while not EndOfStringText( ScanPos, StringLen ) and ( StringText[ ScanPos ] <> Delimiter ) do
begin
Result := Result + StringText[ ScanPos ];
inc( ScanPos )
end;
EndOfLiteral := true;
if not EndOfStringText( ScanPos, StringLen )
then
begin
inc( ScanPos );
if not EndOfStringText( ScanPos, StringLen ) and ( StringText[ ScanPos ] = Delimiter )
then
begin
EndOfLiteral := false;
inc( ScanPos );
Result := Result + Delimiter
end
end;
until EndOfLiteral;
end
end
else
if IsDigit( Delimiter )
then
Result := ReadNumber( StringText, ScanPos )
else
if IsValidFirstIdentChar( Delimiter )
then
Result := ReadIdent( StringText, ScanPos )
end
end;
procedure SkipSpaces( StringText : string; var ScanPos : integer );
var
StringLen : integer;
begin
StringLen := Length( StringText );
while not EndOfStringText( ScanPos, StringLen ) and ( StringText[ ScanPos ] in WhiteSpace ) do
inc( ScanPos )
end;
function EndOfStringText( ScanPos, StringLen : integer ) : boolean;
begin
Result := ScanPos > StringLen
end;
// RDO string encoding utilities
function RDOStrEncode( str : string ) : string;
var
i : integer;
begin
for i := length(str) downto 1 do
if str[i] = LiteralDelim
then insert( LiteralDelim, str, i );
result := str;
end;
function RDOStrDecode( str : string ) : string;
var
i : integer;
begin
for i := length(str) downto 2 do
if (str[i] = LiteralDelim) and (str[pred(i)] = LiteralDelim)
then delete( str, i, 1 );
result := str;
end;
function WideStrToStr( widestr : widestring ) : string;
begin
result := widestr;
end;
function xWideStrToStr( widestr : widestring ) : string;
var
i : integer;
begin
setlength( result, 2*length(widestr) );
for i := 1 to length(widestr) do
begin
result[2*pred(i) + 1] := char(hi(word(widestr[i])));
result[2*pred(i) + 2] := char(lo(word(widestr[i])));
end;
end;
function StrToWideStr( str : string ) : widestring;
begin
result := str;
end;
function xStrToWideStr( str : string ) : widestring;
var
i : integer;
begin
setlength( result, length(str) div 2 + length(str) mod 2 );
for i := 1 to length(result) do
word(result[i]) := (word(str[2*pred(i) + 1]) shl 8 or byte(str[2*pred(i) + 2]));
end;
function RDOWideStrEncode( str : widestring ) : widestring;
var
i : integer;
begin
for i := length( str ) downto 1 do
if str[ i ] = LiteralDelim
then insert( LiteralDelim, str, i );
result := str;
end;
function RDOWideStrDecode( Str : widestring ) : widestring;
var
i : integer;
begin
for i := length( Str ) downto 2 do
if ( str[ i ] = LiteralDelim ) and ( str[ pred( i ) ] = LiteralDelim )
then delete( str, i, 1 );
result := str;
end;
// Variant to and from text conversion utilities
function GetVariantFromStr( VarAsStr : string ) : variant;
var
TypeId : char;
begin
if VarAsStr <> ''
then
begin
TypeId := VarAsStr[ 1 ];
Delete( VarAsStr, 1, 1 );
if Length( VarAsStr ) <> 0
then
Result := VarAsStr
else
Result := '';
case TypeId of
OrdinalId:
if Result <> ''
then
VarCast( Result, Result, varInteger )
else
Result := 0;
SingleId:
if Result <> ''
then
VarCast( Result, Result, varSingle )
else
Result := 0;
DoubleId:
if Result <> ''
then
VarCast( Result, Result, varDouble )
else
Result := 0;
StringId:
Result := RDOStrDecode( Result );
OLEStringId:
Result := StrToWideStr( RDOStrDecode( Result ) );
VariantId:
TVarData( Result ).VType := varVariant;
VoidId:
Result := UnAssigned
else
raise Exception.Create( '' )
end
end
else
Result := UnAssigned
end;
function GetStrFromVariant( aVariant : variant; out IllegalVType : boolean ) : string;
begin
IllegalVType := false;
try
case TVarData( aVariant ).VType and varTypeMask of
varSmallint, varInteger, varError, varBoolean, varByte:
Result := OrdinalId + VarAsType( aVariant, varString );
varSingle:
Result := SingleId + VarAsType( aVariant, varString );
varDouble, varDate, varCurrency:
Result := DoubleId + VarAsType( aVariant, varString );
varString:
Result := StringId + RDOStrEncode( aVariant );
varOleStr:
Result := OLEStringId + RDOStrEncode( WideStrToStr( aVariant ) );
varVariant:
Result := VariantId + VarAsType( aVariant, varString );
varEmpty:
Result := VoidId
else
begin
Result := #0;
IllegalVType := true
end
end
except
IllegalVType := true
end
end;
function GetTypeIdFromVariant( aVariant : variant; out IllegalVType : boolean ) : string;
begin
IllegalVType := false;
try
case TVarData( aVariant ).VType and varTypeMask of
varSmallint, varInteger, varError, varBoolean, varByte:
Result := OrdinalId;
varSingle:
Result := SingleId;
varDouble, varDate, varCurrency:
Result := DoubleId;
varOleStr, varString:
Result := StringId;
varVariant:
Result := VariantId;
varEmpty:
Result := VoidId
else
begin
Result := #0;
IllegalVType := true
end
end
except
IllegalVType := true
end
end;
function PriorityIdToPriority( PriorityId : char ) : integer;
begin
case PriorityId of
NormPrio:
Result := THREAD_PRIORITY_NORMAL;
AboveNormPrio:
Result := THREAD_PRIORITY_ABOVE_NORMAL;
BelowNormPrio:
Result := THREAD_PRIORITY_BELOW_NORMAL;
HighestPrio:
Result := THREAD_PRIORITY_HIGHEST;
IdlePrio:
Result := THREAD_PRIORITY_IDLE;
LowestPrio:
Result := THREAD_PRIORITY_LOWEST;
TimeCritPrio:
Result := THREAD_PRIORITY_TIME_CRITICAL
else
Result := MAXLONG
end
end;
function PriorityToPriorityId( Priority : integer ) : char;
begin
case Priority of
THREAD_PRIORITY_LOWEST:
Result := LowestPrio;
THREAD_PRIORITY_BELOW_NORMAL:
Result := BelowNormPrio;
THREAD_PRIORITY_NORMAL:
Result := NormPrio;
THREAD_PRIORITY_HIGHEST:
Result := HighestPrio;
THREAD_PRIORITY_ABOVE_NORMAL:
Result := AboveNormPrio;
THREAD_PRIORITY_TIME_CRITICAL:
Result := TimeCritPrio;
THREAD_PRIORITY_IDLE:
Result := IdlePrio
else
Result := NormPrio
end
end;
// Query text manipulation
function GetQueryText( var RawText : string ) : string;
var
SemiColIdx : integer;
begin
SemiColIdx := KeyWordPos( QueryTerm, RawText );
if SemiColIdx <> 0
then
begin
Result := Copy( RawText, 1, SemiColIdx );
Delete( RawText, 1, SemiColIdx )
end
else
Result := ''
end;
procedure SendQuery(Query : TRDOQuery; Socket : TCustomWinSocket);
var
Stream : TQueryStream;
begin
Stream := TQueryStream.Create;
try
Query.Write(Stream);
Stream.Send(Socket);
finally
Stream.Free;
end;
end;
function GetQueryErrorCode( Query : TRDOQuery ) : integer;
var
idx : integer;
begin
if Query = nil
then result := errNoError
else
if Query.QKind <> qkError
then result := errNoError
else
try
idx := 0;
if Query.ParamCount > 0
then result := Query.PopParam(idx)
else result := errUnknownError;
except
result := errUnknownError
end;
end;
end.
|
unit SearchOption_Intf;
interface
const
GUID_ISearchOptionPart: TGUID = '{C2436293-51A4-4D4B-8104-E0C6B77AC78B}';
type
ISearchOptionPart = interface
['{C2436293-51A4-4D4B-8104-E0C6B77AC78B}'] // Ctrl + Shift + G
function GetValues(key: String): String;
procedure SetValues(key, val: String);
function InsertPartToQuery(tagQuery, key: String; currIndex: Integer): String;
function IsUse: Boolean;
end;
ILogData = interface
['{FF5EFD1C-F749-4593-80D8-3CE08101BEA8}']
function GetDate: String;
function GetMsg: String;
end;
TLogDataEvent = procedure(Sender: TObject; logData: ILogData) of object;
TAbsSearchOptionPart = class(TInterfacedObject, ISearchOptionPart)
protected
FUse: Boolean;
function InsertPartToQueryByBoolean(tagQuery: String; val: Boolean; currIndex: Integer): String;
function IsUseToString: String;
public
constructor Create; virtual;
function GetValues(key: String): String; virtual; abstract;
procedure SetValues(key, val: String); virtual; abstract;
function InsertPartToQuery(tagQuery, key: String; currIndex: Integer): String; virtual;
function IsUse: Boolean; virtual;
procedure SetUse(val: Boolean); virtual;
end;
TJournalData = class(TInterfacedObject, ILogData)
private
FDate: String;
FMsg: String;
protected
procedure Init(date, msg: String);
public
constructor Create(date, msg: String); overload;
constructor Create(datemsg: String); overload;
function GetDate: String;
function GetMsg: String;
end;
implementation
uses
SysUtils, System.Classes;
{ TAbsSearchOptionPart }
constructor TAbsSearchOptionPart.Create;
begin
FUse := false;
end;
function TAbsSearchOptionPart.InsertPartToQuery(tagQuery, key: String;
currIndex: Integer): String;
var
sTemp: String;
sVal: String;
begin
sVal := GetValues( key );
if (sVal = 'true') or (sVal = 'false') then
sTemp := InsertPartToQueryByBoolean( tagQuery, StrToBool( sVal), currIndex )
else
sTemp := StringReplace( tagQuery, '{' + IntToStr( currIndex ) + '}', sVal, [ rfReplaceAll, rfIgnoreCase ] );
result := sTemp;
end;
function TAbsSearchOptionPart.IsUse: Boolean;
begin
result := FUse;
end;
function TAbsSearchOptionPart.IsUseToString: String;
begin
if IsUse = true then
result := 'true'
else
result := 'false';
end;
function TAbsSearchOptionPart.InsertPartToQueryByBoolean(tagQuery: String; val: Boolean;
currIndex: Integer): String;
var
sRightBracket1: String;
sRightBracket2: String;
sTemp: String;
begin
if val = true then
begin
sRightBracket1 := 't}';
sRightBracket2 := 'f}';
end
else
begin
sRightBracket1 := 'f}';
sRightBracket2 := 't}';
end;
sTemp := StringReplace( tagQuery, '{' + IntToStr( currIndex ) + sRightBracket1, '', [ rfReplaceAll, rfIgnoreCase ] );
sTemp := StringReplace( sTemp, '{/' + IntToStr( currIndex ) + sRightBracket1, '', [ rfReplaceAll, rfIgnoreCase ] );
sTemp := StringReplace( sTemp, '{' + IntToStr( currIndex ) + sRightBracket2, '/*', [ rfReplaceAll, rfIgnoreCase ] );
sTemp := StringReplace( sTemp, '{/' + IntToStr( currIndex ) + sRightBracket2, '*/', [ rfReplaceAll, rfIgnoreCase ] );
result := sTemp;
end;
procedure TAbsSearchOptionPart.SetUse(val: Boolean);
begin
FUse := val;
end;
{ TJournalData }
constructor TJournalData.Create(date, msg: String);
begin
Init( date, msg );
end;
constructor TJournalData.Create(datemsg: String);
var
sList: TStringList;
begin
sList := TStringList.Create;
sList.Delimiter := '|';
sList.StrictDelimiter := true;
sList.DelimitedText := datemsg;
Init( Trim( sList[ 0 ] ), Trim( sList[ 1 ] ) );
sList.Free;
end;
function TJournalData.GetDate: String;
begin
result := FDate;
end;
function TJournalData.GetMsg: String;
begin
result := FMsg;
end;
procedure TJournalData.Init(date, msg: String);
begin
FDate := date;
FMsg := msg;
end;
end.
|
unit uMT2GlobalVar;
interface
uses Classes, uMT2Classes, Generics.Collections;
const
cnstSummaryFile = 'MT2SummaryList.txt';
cstCL_OpenStatus = '<IMG SRC="idx:0"><IND x="20">Open';
cstCL_ClosedStatus = '<IMG SRC="idx:1"><IND x="20">Closed';
clOrange = $000080FF;
cstImageStorageURL = '\\FILESRVR1\Common\Images\TV2\';
cstAttachmentStorageURL = '\\FILESRVR1\Applications\Network Applications\MT2\Attachments\';
cstAttachmentStorageURLTemp = '\\FILESRVR1\Applications\Network Applications\MT2\Attachments\Temp\';
cstRootInvoiceURL = '\\RPRTSRVR\pdf_invoices\Additional\';
//cstAttachmentStorageURL = 'D:\Attach\';
UseDB = 'Use [MTTest];' ;
cnstDomain = 'wddc.com';
NewColor = '#FE8000';
InProgressColor='#0080FF';
OnHoldColor='#F20000';
WaitingForClientColor='#BF0060';
CompleteColor='#74D810';
StatusColors : array [0..4] of String = (NewColor,InProgressColor,OnHoldColor,WaitingForClientColor,CompleteColor);
var
stlGV_Callers : TStringList;
bGV_AutoPrint : Boolean; //this is a local (user) setting to determine whether to print logs or not
sGV_Log_Summary : String;
stlGV_Log_Summary_List : TStringList;
stlGV_LogImageList : TStringList;
sGV_OLEFileAdded : String;
rGV_MTUser : TMTUser;
stlGV_ActiveCtgy : TStringList;
stlGV_AllCtgy : TStringList;
stlGV_CLDept : TStringList;
stlGV_DeptEmail : TStringList;
lstGV_UnAckList : TList<TMTNotification>;
dtGV_LastUpdateCheck : TDateTime;
implementation
end.
|
unit DiscountForma;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OkCancel_frame, StdCtrls, DBCtrlsEh, Mask, DBLookupEh, System.UITypes,
DB, FIBDataSet, pFIBDataSet, ExtCtrls, DBCtrls, FIBQuery, DBGridEh,
Vcl.Buttons, CnErrorProvider, pFIBQuery, FIBDatabase, pFIBDatabase,
PropFilerEh, PropStorageEh;
type
TDiscountForm = class(TForm)
srcService: TDataSource;
dsluService: TpFIBDataSet;
mmoNotice: TDBMemoEh;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
cbAll: TCheckBox;
pnlService: TPanel;
Label1: TLabel;
luOnOffService: TDBLookupComboboxEh;
deStart: TDBDateTimeEditEh;
deStop: TDBDateTimeEditEh;
edtnumValue: TDBNumberEditEh;
btnOk: TBitBtn;
btnCancel: TBitBtn;
cnErrors: TCnErrorProvider;
lbl1: TLabel;
lcbSrvType: TDBLookupComboboxEh;
dsSrvType: TpFIBDataSet;
srcSrvType: TDataSource;
pnlSrvType: TPanel;
qDiscount: TpFIBQuery;
trRead: TpFIBTransaction;
trReadQ: TpFIBTransaction;
trWriteQ: TpFIBTransaction;
PropStorageEh: TPropStorageEh;
procedure cbAllClick(Sender: TObject);
procedure srcDiscountStateChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnOkClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FNotChangeHistory: Boolean;
FDiscount_ID: Integer;
FCustomer_ID: Integer;
procedure Save;
procedure Save2DB;
function CheckDataAndOk: Boolean;
public
{ Public declarations }
property customer_id: Integer read FCustomer_ID write FCustomer_ID;
property Discount_ID: Integer read FDiscount_ID write FDiscount_ID;
end;
function AddEditDiscount(aDISCOUNT_ID: Integer; const aCUSTOMER_ID: Integer): Boolean;
implementation
uses System.DateUtils, DM, CF, AtrCommon, PrjConst;
function AddEditDiscount(aDISCOUNT_ID: Integer; const aCUSTOMER_ID: Integer): Boolean;
begin
with TDiscountForm.Create(application) do
try
customer_id := aCUSTOMER_ID;
Discount_ID := aDISCOUNT_ID;
Result := (ShowModal = mrOk);
finally
free;
end;
end;
{$R *.dfm}
procedure TDiscountForm.cbAllClick(Sender: TObject);
begin
pnlService.Visible := not cbAll.Checked;
pnlSrvType.Visible := cbAll.Checked;
end;
procedure TDiscountForm.srcDiscountStateChange(Sender: TObject);
begin
btnOk.Enabled := not((Sender as TDataSource).DataSet.State = dsBrowse);
end;
procedure TDiscountForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
dmMain.SetIniValue('DISCOUNT', edtnumValue.Value);
Action := caFree;
end;
procedure TDiscountForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then
Save;
end;
procedure TDiscountForm.FormShow(Sender: TObject);
var
y, m, d: Word;
v: Double;
begin
FNotChangeHistory := not((dmMain.AllowedAction(rght_Customer_History)) or (dmMain.AllowedAction(rght_Customer_full)));
cbAll.Checked := False;
dsluService.Open;
dsSrvType.Open;
cbAll.Checked := True;
// edtnumValue.Value := 0.5;
luOnOffService.Value := -1;
lcbSrvType.Value := -1;
DecodeDate(Now(), y, m, d);
deStart.Value := EncodeDate(y, m, 1);
d := DaysInMonth(Now());
deStop.Value := EncodeDate(y, m, d);
if FDiscount_ID <> -1 then begin
qDiscount.ParamByName('DISCOUNT_ID').Value := FDiscount_ID;
with qDiscount do begin
Transaction.StartTransaction;
ExecQuery;
if not FN('SERV_ID').IsNull then
cbAll.Checked := (FN('SERV_ID').AsInteger = -1);
if not FN('FACTOR_VALUE').IsNull then
edtnumValue.Value := FN('FACTOR_VALUE').AsFloat;
if not FN('SERV_ID').IsNull then
luOnOffService.Value := FN('SERV_ID').AsInteger;
if not FN('SRV_TYPE').IsNull then
lcbSrvType.Value := FN('SRV_TYPE').AsInteger;
if not FN('DATE_FROM').IsNull then
deStart.Value := FN('DATE_FROM').AsDate;
if not FN('DATE_TO').IsNull then
deStop.Value := FN('DATE_TO').AsDate;
if not FN('NOTICE').IsNull then
mmoNotice.Lines.Text := FN('NOTICE').AsString;
Close;
Transaction.Rollback;
end;
end
else begin
if not TryStrToFloat(dmMain.GetIniValue('DISCOUNT'), v) then
v := 0.5;
edtnumValue.Value := v;
end;
end;
procedure TDiscountForm.Save;
begin
if CheckDataAndOk then begin
Save2DB;
ModalResult := mrOk;
end;
end;
procedure TDiscountForm.Save2DB;
var
All: Boolean;
i: Integer;
begin
with qDiscount do begin
SQL.Text := 'execute procedure Discount_IU ' +
'(:Discount_Id, :Customer_Id, :Date_From, :Date_To, :Factor_Value, :Serv_Id, :Srv_Type, :Notice)';
if FDiscount_ID = -1 then
ParamByName('Discount_Id').Clear;
ParamByName('Customer_Id').AsInteger := FCustomer_ID;
ParamByName('Factor_Value').AsFloat := edtnumValue.Value;
ParamByName('Date_From').AsDate := deStart.Value;
ParamByName('Date_To').AsDate := deStop.Value;
if cbAll.Checked then begin
ParamByName('Serv_Id').AsInteger := -1;
ParamByName('Srv_Type').AsInteger := lcbSrvType.Value
end
else begin
ParamByName('Serv_Id').AsInteger := luOnOffService.Value;
ParamByName('Srv_Type').AsInteger := -1;
end;
ParamByName('Notice').AsString := mmoNotice.Lines.Text;
Transaction := trWriteQ;
end;
All := False;
if Assigned(CustomersForm) and (FDiscount_ID = -1) then
if (CustomersForm.dbgCustomers.SelectedRows.Count > 0) then
All := (MessageDlg(rsProcessAllSelectedRows, mtConfirmation, [mbYes, mbNo], 0) = mrYes);
if All then begin
for i := 0 to CustomersForm.dbgCustomers.SelectedRows.Count - 1 do begin
CustomersForm.dbgCustomers.DataSource.DataSet.Bookmark := CustomersForm.dbgCustomers.SelectedRows[i];
qDiscount.ParamByName('Customer_Id').AsInteger := CustomersForm.dbgCustomers.DataSource.DataSet['CUSTOMER_ID'];
try
qDiscount.Transaction.StartTransaction;
qDiscount.ExecQuery;
qDiscount.Transaction.Commit;
except
ShowMessage(rsErrorSave + ' ' + format(rsAccountWT,
[CustomersForm.dbgCustomers.DataSource.DataSet.FieldByName('ACCOUNT_NO').AsString]));
end;
CustomersForm.dsCustomers.Refresh;
end;
end
else begin
try
qDiscount.ParamByName('Customer_Id').AsInteger := FCustomer_ID;
if FDiscount_ID <> -1 then
qDiscount.ParamByName('Discount_Id').AsInteger := FDiscount_ID;
qDiscount.Transaction.StartTransaction;
qDiscount.ExecQuery;
qDiscount.Transaction.Commit;
except
ShowMessage(rsErrorSave);
end;
end;
end;
procedure TDiscountForm.btnOkClick(Sender: TObject);
begin
Save;
end;
function TDiscountForm.CheckDataAndOk: Boolean;
var
allOk: Boolean;
VD: TDateTime;
begin
allOk := True;
if (not TryStrToDate(deStart.Text, VD)) then begin
allOk := False;
cnErrors.SetError(deStart, rsInputIncorrect, iaMiddleLeft, bsNeverBlink);
end
else begin
cnErrors.Dispose(deStart);
if FNotChangeHistory and (VarToDateTime(deStart.Value) < dmMain.CurrentMonth) then begin
allOk := False;
cnErrors.SetError(deStart, rsSuspiciousDate, iaMiddleLeft, bsNeverBlink);
end
else
cnErrors.Dispose(deStart);
end;
if (not TryStrToDate(deStop.Text, VD)) then begin
allOk := False;
cnErrors.SetError(deStop, rsInputIncorrect, iaMiddleLeft, bsNeverBlink);
end
else begin
cnErrors.Dispose(deStop);
if FNotChangeHistory and (VarToDateTime(deStop.Value) < dmMain.CurrentMonth) then begin
allOk := False;
cnErrors.SetError(deStop, rsSuspiciousDate, iaMiddleLeft, bsNeverBlink);
end
else
cnErrors.Dispose(deStop);
end;
cnErrors.Dispose(luOnOffService);
cnErrors.Dispose(lcbSrvType);
if cbAll.Checked then begin
if lcbSrvType.Text = '' then begin
allOk := False;
cnErrors.SetError(lcbSrvType, rsERROR_NOT_FILL_ALL, iaMiddleLeft, bsNeverBlink);
end
end
else begin
if luOnOffService.Text = '' then begin
allOk := False;
cnErrors.SetError(luOnOffService, rsERROR_NOT_FILL_ALL, iaMiddleLeft, bsNeverBlink);
end
end;
if edtnumValue.Text = '' then begin
allOk := False;
cnErrors.SetError(edtnumValue, rsERROR_NOT_FILL_ALL, iaMiddleLeft, bsNeverBlink);
end
else
cnErrors.Dispose(edtnumValue);
Result := allOk;
end;
end.
|
unit Constants;
interface
uses Classes, IdGlobal, SysUtils;
type
MsgType = (
MsgTypeInvalid = 0, //Недопустимый тип пакета
MsgTypePing = 1,
MsgTypePong,
MsgTypeConfirm,
MsgTypeHello, //Запрос соединения
MsgTypeError, //Ошибка
MsgTypeBadSession, //Неактивная сессия
MsgTypeAccept, //- принятие запроса на соединение с сервером
MsgTypeLogon, //принятие логина и пароля
MsgTypeNoLogon, //отклонение логина и пароля
MsgTypeCommand, // Комманда
MsgTypeVersionErr, //не допустимая версия клиента
MsgTypeEvent, //Событие
MsgTypeCount, // кол-во частей строки
MsgTypeSetKopState,
MsgTypeSetZoneState,
MsgTypeSetZonesStates,
MsgTypeGetHistory,
MsgTypeDataPack,
MsgTypeLastPacket
);
type TEventTypes = (
EvTypeBegin,
EvTypeFire, //тип события Пожар
EvTypeHiJack, //тип события Тевога принуждение
EvTypeAlarm, //тип события Тревога
EvTypeDamageDevice, //тип события АварияУстройства
EvTypeDamageLink, //тип события АварияУстройства
EvTypeDamagePower, //тип события АварияУстройства
EvTypeTestDown, //тип события Пропуск теста
EvTypePreAlarm, //тип события Сработка
EvTypeTestUp, //тип события Тест
EvTypeError, //тип события Ошибка
EvTypeAttention, //тип события Внимание
EvTypeRepairDevice, //устранение аварии устройства
EvTypeRepairLink, //устранение аварии связи
EvTypeRepairPower, //устранение аварии питания
EvTypeArm, //тип события Взят
EvTypeDisArm, //тип события Снят
EvTypePatrol, //тип события патруль
EvTypeDropAlarm, //тип события сброс тревоги
EvTypeDropDamageDevice, //тип события сброс аварии устройства
EvTypeDropDamageLink, //тип события сброс аварии связи
EvTypeDropDamagePower, //тип события сброс аварии питания
EvTypeCommand, //тип события команда
EvTypeQueryToArm, //тип события запрос на взятие
EvTypeQueryToDisArm, //тип события запрос на снятие
EvTypeMessage, //тип события Сообщение
EvTypeLast);
type TEventSet = set of TEventTypes;
type CmdTypesToApp = ( // типы команд приложению
CmdFirst = 0,
CmdReloadData, // перегрузка данных
CmdResetConn, // переподключиться к серверу
CmdCloseApp,
CmdBackStart,
CmdDelAlarm,
CmdAddAlarm,
CmdLast); // завершить работу
type TMobiCodes = (
meNone, //нет события
meUserLogon, //Авторизация пользователя
meUserLogOut, //ВыходПользователя
meDamage, //Авария
meDamageRepair, //Устранение аварии
meAlarm, //Тревожная кнопка
meLowBattery, //Низкий заряд батареи
meLowBatteryRepair, //Восстановление после разряда батареи
meLocation, //локация
meDamageLink, //авария связи
meDamageLinkRepair, //устранение аварии связи
meApplicationConnected,
meApplicationDisConnected,
meAlarmsOn,
meDamagesOn,
meAlarmsOff,
meDamagesOff,
meTaskConfirmByGBR,
meTaskConfirmByTech,
meTaskExecByTech,
meTaskMovedByTech,
meTaskDropByTech,
meCmdGBRTaskUpdate,
meCmdGBRAlamUpdate,
meCmdTechTaskUpdate
);
type TMobiSet = set of TMobiCodes;
type SysCodes = (
EventTypeBegin,
EventTypeSystemStart, //Сброс процессора(при загрузке)
EventTypeConfigChanged, //Изменены настройки
EventTypeFirmwareUpdated, //Обновлена прошивка
EventTypeChanellChanged, //Переключение канала связи
EventTypePowerSwitchToBackup, //переход на АКБ
EventTypePowerSwitchToMain, //переход на основное питание
EventTypeGuardSensorSet, //Взят шлейф
EventTypeGuardSensorUnset, //Снят шлейф
EventTypeGuardSensorAlarm, //Тревога шлейф
EventTypeGuardSensorNoSetAlarm, //Тревога не взят
EventTypeGuardSensorNoSet, //Не взят
EventTypeGuardSensorNoUnset, //Не снят
EventTypeAlarmSensorAlarm, //Тревога шлейфа
EventTypeAlarmSensorRestore, //Восстановление шлейфа
EventTypeAlarmPowerOn, //Тревога включения питания
EventTypeFireSensorDefectShort, //Неисправность КЗ пожарного шлейфа
EventTypeFireSensorDefectBreak, //Неисправность Обрыв пожарного шлейфа
EventTypeSmokeSensorAlarm, //Срабатывание дымового датчика
EventTypeFireSensorAlarm, //Срабатывание пожарного датчика
EventTypeFireShort, //Пожар КЗ
EventTypeFireBreak, //Пожар обрыв
EventTypeFireRestore, //Восстановление пожарного датчика
EventTypeSensorBadReset, //Неудачное перевзятие шлейфа
EventTypeSensorSetNotAvailable, //Не взят (не доступно)
EventTypeSensorUnsetNotAvailable, //Не снят (не доступно)
EventTypeCaseOpened, //Корпус вскрыт
EventTypeCaseClosed, //Корпус закрыт
EventTypePatrulAlarm, //Срабатывание датчика отметки патруля
EventTypePatrulRestore, //Восстановление датчика отметки патруля
EventTypeOutputShort, //Обрыв выхода
EventTypeOutputRestore, //Восстановление выхода
EventTypeBackupChanellError, //Ошибка проверки резервного канала
EventTypeArmed, //Взят
EventTypeDisArmed, //Снят
EventTypeAlarm, //Тревога
EventTypeDamageSensor, //Неисправность ШС
EventTypeAlarmForce, //Тревога принуждение
EventTypeDamageBattery, //Разряд АКБ
EventTypeRestoreBattery, //Восстановление АКБ
EventTypeDamagePower, //Отключение 220
EventTypeRestorePower, //Восстановление 220
EventTypeTest, //Тест периодический
EventTypeTestLoss, //Пропуск теста
EventTypeAttention, //Внимание
EventTypePatrol, //Отметка наряда
EventTypeNotice, //Извещение
EventTypeError, //Ошибка
EventTypeCaution, //Предупреждение
EventTypeCommand, //Команда
EventTypeDamageDevice, //Авария оборудования
EventTypeRestoreDevice, //Устранение аварии оборудования
EventTypeDamageLink, //Авария связи
EventTypeRestoreLink, //Устранение аварии связи
EventTypeArmedByDuty, //Взят оператором
EventTypeDisArmedByDuty, //Снят оператором
EventTypeConnectPC, //Подключился АРМ
EventTypeDisConnectPC, //Отключился АРМ
EventTypeArmedByQuery, //Взят при опросе
EventTypeDisArmedByQuery, //Снят при опросе
EventTypeAlarmByQuery, //Тревога при опросе
EventTypeDamageByQuery, //Авария при опросе
EventTypeDrawDown, //Сработка
EventTypeArmQueryDenied, //Запрос на взятие отклонен
EventTypeDisarmQueryDenied, //Запрос на снятие отклонен
EventTypeCmdArm, //Взять под охрану
EventTypeCmdDisArm, //Снять с охраны
EventTypeCmdQueryStatus, //Запросить состояние
EventTypeCmdNotExecute, //Команда не выполнена
EventTypeSessionStart, //Старт сессии
EventTypeIPChange, //Смена IP адреса
EventTypeAlarmDroped, //Сброс тревоги
EventTypeDamageDeviceDroped, //Сброс аварии оборудования
EventTypeDamageLinkDroped, //Сброс аварии связи
EventTypeDamagePowerDroped, //Сброс аварии питания
EventTypeTestLossDroped, //Сброс пропуска теста
EventTypeCmdAlarmDrop, //Сбросить тревогу/аварию
EventTypeDeviceNotActive, //Прибор не активен
EventTypeQueryToArm, //Запрос на взятие
EventTypeQueryToDisarm, //Запрос на снятие
EventTypeStatusGet, //Получено состояние
EventTypeKeyNotFound, //Идентификатор не опознан
EventTypeCmdChangeSim, //Команда сменить СИМ
EventTypeServiceMessage, //Служебное
EventTypeAlarmToLong, //Перевод тревоги в долговременную
EventTypeChangeData, //Изменение данных
EventTypeTechnologyRestore, //Восстановление технологического ШС
EventTypeTechnologyAlarm, //Нарушение технологического ШС
EventTypeCmdGetConfig, //Получить конфигурацию с прибора
EventTypeCmdQueryHistory, //Запрос истории
EventTypeCmdArmGroup, //Взять под охрану группой
EventTypeCmdDisArmGroup, //Снять с охраны группой
EventTypeCmdGetFirmware, //Получить прошивку с прибора
EventTypeCmdSetFirmware, //Записать прошивку в прибор
EventTypeCmdSetConfig, //Записать конфигурацию в прибор
EventTypeConfigGet, //Получена конфигурация прибора
EventTypeFirmwareGet, //Получена прошивка прибора
EventTypeFirmwareUploaded, //Прошивка записана в прибор
EventTypeConfigUploaded, //Конфигурация записана в прибор
EventTypeConfigPartUploaded, //Получена часть прошивки/конфигурации
EventTypeCmdQueryHistoryObject, //Запрос истории по объекту
EventTypeCmdDropDamageDevice, //Сбросить аварию оборудования
EventTypeCmdDropDamageLink, //Сбросить аварию связи
EventTypeCmdDropDamagePower, //Сбросить аварию питания
EventTypeCmdDropTestLoss, //Сбросить пропуск теста
EventTypeAlertSendedMobiApp, //Уведомление на моб. приложение отправлено
EventTypeCmdPartArm, //Взять раздел (группу разделов)
EventTypeCmdPartDisarm, //Снять раздел (группу разделов)
EventTypePartArmed, //Взятие раздела
EventTypePartDisarmed //Снятие раздела
);
type TEventCodeSet = set of byte;
type DevClasses = (
DevClassNone,
DevClassPrd,
DevClassPpk,
DevClassZone,
DevClassRelay,
DevClassControl,
DevClassSystem,
DevClassGroup,
DevClassApplication,
DevClassSection,
DevClassDriverGSM,
DevClassDriverInet,
DevClassWebDriver,
DevClassDriverOrion,
DevClassDriverRadio,
DevClassRadioPcn,
DevClassRadioRX,
DevClassCore,
DevClassWebCore,
DevClassARM_DPCO,
DevClassDutyRaport,
DevClassOperManager,
DevClassDriver1C,
DevClassFrigateOutdoor,
DevClassServerPritok,
DevClassServerProton,
DevClassServerAndromeda,
DevClassRadioPcnProton,
DevClassRadioRXProton
);
type TUserRole = (
RoleBegin,
RoleAdmin,
RoleDuty,
RoleTech,
RoleMobiUser,
RoleGBR
);
const
PCN_TYPE_FRIGATE = Byte(DevClassCore);
PCN_TYPE_FRIGATE_WEB = Byte(DevClassWebCore);
PCN_TYPE_PRITOK = Byte(DevClassServerPritok);
PCN_TYPE_PROTON = Byte(DevClassServerProton);
PCN_TYPE_DRIVER_1C = Byte(DevClassDriver1C);
PCN_TYPE_FRIGATE_OUTDOOR = Byte(DevClassFrigateOutdoor);
PCN_TYPE_ANDROMEDA = Byte(DevClassServerAndromeda);
ORION_EC_ARM_SENSOR = 1024;
ORION_EC_DISARM_SENSOR = 1109;
InvalidID = -1;
InvalidUID = '';
BadSession = 0;
UnixStartDate: TDateTime = 25569.0;
PcnStateDown = 0;
PcnStateWork = 1;
PcnStateUnknow = 3;
tbADRESES = 'ADRESES';
tbALARMS = 'ALARMS';
tbCOLORS = 'COLORS';
tbCOMBINE = 'COMBINE';
tbRX = 'CONTROLS';
tbCUST = 'CUST';
tbDEVICES = 'DEVICES';
tbDISTRICTS = 'DISTRICTS';
tbEVENT_CODES = 'EVENT_CODES';
tbGROUPS = 'GROUPS';
tbLARS_CODES = 'LARS_CODES';
tbLOCALS = 'LOCALS';
tbOBJ_EVENTS = 'OBJ_EVENTS';
tbOBJ_LINKS = 'OBJ_LINKS';
tbORGS = 'ORGS';
tbPHONES = 'PHONES';
tbREPORTS = 'REPORTS';
tbSCRIPTS = 'SCRIPTS';
tbSCRIPTS_CMD = 'SCRIPTS_CMD';
tbSECTIONS = 'SECTIONS';
tbSECTION_ZONES = 'SECTION_ZONES';
tbSETTINGS = 'SETTINGS';
tbSTREETS = 'STREETS';
tbTEST = 'TESTS';
tbTIMESPACES = 'TIMESPACES';
tbXO = 'XO';
tbXO_KEYS = 'XO_KEYS';
tbXO_USERS = 'XO_USERS';
tbZONE_TIMESPACES = 'ZONE_TIMESPACES';
tbZONE_XO = 'ZONE_XO';
tbZONE_XO_KEYS = 'ZONE_XO_KEYS';
tbDEV_STATES = 'DEV_STATES';
PultTypeRadioDriver = 400;
PultTypeGSM = 401;
PultTypeInet = 402;
PultTypePcnProton = 403;
PultTypePcnLars = 404;
PultTypeRadioProton = 405;
PultTypeRadioProtonOnLars = 406;
PultTypeRadioLars = 407;
PultTypeMobiDriver = 408;
AppTypeCore = 600;
AppTypeDPCO = 601;
AppTypePritok = 602;
AppTypeWebCore = 603;
AppTypeOperData = 604;
AppTypeAndromeda = 605;
AppTypeFrigateOutDoor = 606;
AppTypeRaport = 607;
AppTypeDriverDB = 608;
IoModeWrite = 1;
IoModeRead = 0;
// PCN_TYPE_FRIGATE = 0;
// PCN_TYPE_FRIGATE_WEB = 1;
// PCN_TYPE_PRITOK = 2;
// PCN_TYPE_PROTON = 3;
// PCN_TYPE_DB_DRIVER = 4;
// PCN_TYPE_FRIGATE_OUTDOOR = 5;
// PCN_TYPE_ANDROMEDA = 6;
ORG_TYPE_ORG = 0;
ORG_TYPE_KONTR = 1;
ORG_TYPE_SUPPORT = 2;
TrueBit = 1;
FalseBit = 0;
StateOff = 0;
StateOnn = 1;
COMMAND_GET = 'GET';
COMMAND_POST = 'POST';
MESSAGE_NONE = 'none';
MESSAGE_HELLO = 'hello';
MESSAGE_GOODBYE = 'goodbye';
MESSAGE_PING = 'ping';
MESSAGE_PONG = 'pong';
MESSAGE_SETDATA = 'set_data';
MESSAGE_QUERY_DATA = 'query_data';
MESSAGE_ERROR = 'error';
MESSAGE_NOTREADY = 'not_ready';
MESSAGE_CONFIRM = 'confirm';
MESSAGE_ACCEPT = 'accept';
MESSAGE_EVENT = 'event';
MESSAGE_ADD_ALARM = 'add_alarm';
MESSAGE_DEL_ALARM = 'del_alarm';
MESSAGE_UP_STATE = 'up_state';
MESSAGE_SEND_MAIL = 'send_mail';
MESSAGE_RESET = 'reset';
MESSAGE_MOBILOC = 'mobi_loc';
MESSAGE_COMMAND = 'command';
MESSAGE_HISTORY = 'history';
MESSAGE_TASK = 'task';
MESSAGE_UPDATE_DATA = 'update_data';
MESSAGE_UPDATE_OK = 'update_ok';
KEY_REC_COUNT = 'rec_count';
KEY_ARRAY = 'array';
KEY_SES_UID = 'ses_uid';
KEY_UID = 'uid';
KEY_MES_TYPE = 'mes_type';
KEY_MES_TEXT = 'mes_text';
KEY_CLIENT_TYPE = 'client_type';
KEY_CLIENT_CLASS = 'client_class';
KEY_DATAVERS = 'data_vers';
KEY_USER_ID = 'user_id';
KEY_DATA = 'data';
KEY_DEV_CLASS = 'dev_class';
KEY_DEV_ID = 'dev_id';
KEY_DEV_UID = 'dev_uid';
KEY_GEAR_ID = 'gear_id';
KEY_ROUTE_ID = 'route_id';
KEY_RX_TYPE = 'rx_type';
KEY_RX_ID = 'rx_id';
KEY_ADD_INFO = 'add_info';
KEY_COMMANDS = 'commands';
KEY_EVENTS = 'events';
KEY_MAIN = 'main';
KEY_NAME = 'name';
KEY_ID = 'id';
KEY_ID_CUST = 'id_cust';
KEY_XO_ID = 'xo_id';
KEY_SYS_MES = 'sys_mes';
KEY_CODE_ID = 'code_id';
KEY_SIGNAL = 'signal';
KEY_DATE_TIME = 'date_time';
KEY_CHANGES = 'changes';
KEY_COM_PORT = 'com_port';
KEY_RATE = 'rate';
KEY_LOC = 'loc';
KEY_LAT = 'lat';
KEY_LON = 'lon';
KEY_SPEED = 'spd';
KEY_OBJECT_ID = 'object_id';
KEY_ZONE_ID = 'zone_id';
KEY_TECH_ID = 'tech_id';
KEY_TRANSFER_TIME = 'transfer_time';
KEY_CONFIRM_TIME = 'confirm_time';
KEY_EXEC_TIME = 'exec_time';
KEY_TITLE = 'title';
KEY_CUST_ID = 'cust_id';
KEY_CUST_NAME = 'cust_name';
KEY_ADDR = 'addr';
KEY_STATUS = 'status';
KEY_DESCR = 'descr';
KEY_DT = 'dt';
KEY_ANSWER = 'answer';
KEY_CUST = 'cust';
KEY_PCN = 'pcn';
KEY_PCN_ID = 'pcn_id';
KEY_PCN_TYPE = 'pcn_type';
KEY_DB_HOST = 'db_host';
KEY_DB_BASE = 'db_base';
KEY_DB_USER = 'db_user';
KEY_DB_PASS = 'db_pass';
KEY_DB_PORT = 'db_port';
KEY_SET_CONFIG = 'ppkop_set_config';
KEY_SET_FIRMWARE = 'ppkop_set_firmware';
KEY_CONFIG = 'ppkop_config';
KEY_FIRMWARE = 'ppkop_firmware';
KEY_DEST_UID = 'dest_uid';
CLIENT_CORE = 'main_core';
CLIENT_MONITOR = '1c_monitor';
CLIENT_RAPORT = '1c_raport';
CLIENT_RADIODRV = 'radio_drv';
CLIENT_INETDRV = 'inet_drv';
CLIENT_GSMDRV = 'gsm_drv';
CLIENT_OPER = '1c_oper';
CLIENT_COORDINATOR = '1c_coordinator';
CLIENT_GBR = 'gbr';
CLIENT_TECH = 'tech';
CLIENT_USER = 'user';
CLIENT_KEYBOARD = 'keyboard';
CLIENT_WEB_CORE = 'web_core';
MO_EVENT_CLASS_ALARM = 0;
MO_EVENT_CLASS_DAMAGE = 1;
MO_EVENT_CLASS_DAMAGE_REPAIR = 2;
MO_EVENT_CLASS_USER_LOGON = 3;
MO_EVENT_CLASS_USER_LOGOUT = 4;
MO_EVENT_CLASS_MESSAGE = 5;
MO_EVENT_CLASS_LOCATION = 6;
MO_EVENT_CLASS_COMMAND = 7;
MO_TYPE_GEAR = 1;
MO_TYPE_DEVICE = 2;
MO_TYPE_USER = 3;
MO_TYPE_APP = 4;
MO_TYPE_ROUTE = 5;
MO_APP_GBR = 0;
MO_APP_TECH = 1;
MO_APP_INNER = 2;
TASK_STATUS_NEW = 0;
TASK_STATUS_CONFIRM = 1;
TASK_STATUS_EXEC = 2;
TASK_STATUS_MOVED = 3;
TASK_STATUS_SENDED = 4;
TASK_STATUS_CANCELED = 5;
TASK_STATUS_CLOSED = 6;
TASK_STATUS_UNKNOW = 7;
GBR_TASK_STATUS_NEW = 0;
GBR_TASK_STATUS_TX = 1;
GBR_TASK_STATUS_RX = 2;
GBR_TASK_STATUS_ARRIVAL = 3;
GBR_TASK_STATUS_CLOSED = 4;
GBR_TASK_TYPE_ALARM_PCN = 0;
GBR_TASK_TYPE_ALARM_ANY = 1;
GBR_TASK_TYPE_MOVE_XO = 2;
GBR_TASK_TYPE_GUARD_CHECK = 3;
GBR_TASK_TYPE_HOME_POINT = 4;
GBR_TASK_TYPE_TECH_TO_OBJ = 5;
GBR_TASK_TYPE_TECH_TO_HOME = 6;
GBR_TASK_TYPE_GO_TO_ADRES = 7;
GBR_TASK_TYPE_LUNCH = 8;
GBR_TASK_TYPE_ANY = 9;
KEY_TYPE_GOOGLE_FCM = 0;
KEY_TYPE_GOOGLE_GEO = 1;
KEY_TYPE_2GIS = 2;
GEOCODER_TYPE_GOOGLE = 0;
GEOCODER_TYPE_YANDEX = 1;
GEOCODER_TYPE_2GIS = 3;
GEOCODER_TYPE_OSM = 4;
GEOCODER_TYPE_SPUTNIK = 5;
GBROn = 'on';
GBROff = 'off';
StyleArmed = 'green';
StyleDisarmed = 'blue';
StyleAlarm = 'red';
StyleUnknown = 'gray';
PRITOK_STATE_ARMED = 2;
PRITOK_STATE_DISARMED = 3;
PRITOK_STATE_ALARM = 7;
ORION_EVENTS_OFFSET = 1000; // смещение кодов событий Орион
DevTypeOrionPrd = 107; //код типа оборудования "Передатчик Орион"
MaxMaskZoneCnt = 63; // максимальное количество зон для группового взятия/снятия
EvSetStateChange = [MO_EVENT_CLASS_ALARM, MO_EVENT_CLASS_DAMAGE, MO_EVENT_CLASS_DAMAGE_REPAIR, MO_EVENT_CLASS_USER_LOGON,
MO_EVENT_CLASS_USER_LOGOUT];
ESetRed = [EvTypeFire, EvTypeHiJack, EvTypeAlarm, EvTypeDamageDevice, EvTypeDamageLink, EvTypeDamagePower, EvTypeTestDown, EvTypePreAlarm];
ESetGreen = [EvTypeTestUp, EvTypeRepairDevice, EvTypeRepairLink, EvTypeRepairPower, EvTypeArm];
ESetBlue = [EvTypeDisArm];
ESetDamage = [EvTypeDamageDevice, EvTypeDamageLink, EvTypeDamagePower, EvTypeTestDown];
implementation
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uDatabaseWatchService.pas }
{ Описание: Базовая реализация IDatabaseWatchService }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uDatabaseWatchService;
interface
uses
SysUtils, Classes, uServices, uInterfaceListExt;
type
TDatabaseWatchService = class(TInterfacedObject, IDatabaseWatchService)
private
FWatchList: IInterfaceListExt;
public
constructor Create;
procedure AddRecordWatch(AWatchParams: IRecordWatchParameters); stdcall;
procedure AddTableWatch(AWatchParams: ITableWatchParameters); stdcall;
end;
implementation
constructor TDatabaseWatchService.Create;
begin
inherited Create;
FWatchList := CreateInterfaceListExt();
end;
{
**************************** TDatabaseWatchService *****************************
}
procedure TDatabaseWatchService.AddRecordWatch(AWatchParams:
IRecordWatchParameters);
begin
// TODO -cMM : Interface wizard: Implement interface method
end;
procedure TDatabaseWatchService.AddTableWatch(AWatchParams:
ITableWatchParameters);
begin
// TODO -cMM : Interface wizard: Implement interface method
end;
end.
|
program Ch1;
{$mode objfpc}
uses
SysUtils,Math,GVector;
type
TVec = specialize TVector<Integer>;
var
I:Integer;
Vec:TVec;
function DivisorsSum(N:Integer):Integer;
var
I:Integer;
begin
Result := 0;
I := 1;
while(I < (N div 2+1)) do
begin
if(N mod I = 0) then Result := Result + I;
Inc(I);
end;
end;
function AbundantOddNumbers:TVec;
var
I:Integer;
begin
I := 1;
Result := TVec.Create;
repeat
if((DivisorsSum(I) > I) and (I mod 2 <> 0)) then
Result.PushBack(I);
Inc(I);
until(Result.Size = 20);
end;
begin
Vec := AbundantOddNumbers;
for I := 0 to Pred(Vec.Size) do
Write(Vec[I], ' ');
FreeAndNil(Vec);
end.
|
//****************************************************************
//
// Inventory Control
//
// Copyright (c) 2002-2015 Failproof Manufacturing Systems.
//
//****************************************************************
//
// Change History
//
// 06/25/2015 David Verespey Create Form
//
unit ForecastCamexreport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, History, Datamodule,ADOdb,ComObj,strutils,dateutils;
type
TColNum = 1..256; // Excel columns only go up to IV
TColString = string[2];
TForecastCAMEXReport = class(TObject)
private
function IntToXlCol(ColNum: TColNum): TColString;
//function XlColToInt(const Col: TColString): TColNum;
public
function Execute:boolean;
end;
implementation
function TForecastCAMEXReport.IntToXlCol(ColNum: TColNum): TColString;
const
Letters: array[0..MaxLetters] of char
='ZABCDEFGHIJKLMNOPQRSTUVWXYZ';
var
nQuot, nMod: integer;
Begin
if ColNum <= MaxLetters then
begin
Result[0] := Chr(1);
Result[1] := Letters[ColNum];
end
else
begin
nQuot := ((ColNum - 1) * 10083) shr 18;
nMod := ColNum - (nQuot * MaxLetters);
Result[0] := Chr(2);
Result[1] := Letters[nQuot];
Result[2] := Letters[nMod];
end;
end;
// Turns a column identifier into the corresponding integer,
// A=1, ..., AA = 27, ..., IV = 256
//function TForecastCAMEXReport.XlColToInt(const Col: TColString): TColNum;
//const
// ASCIIOffset = Ord('A') - 1;
//var
// Len: cardinal;
//begin
// Len := Length(Col);
// Result := Ord(UpCase(Col[Len])) - ASCIIOffset;
// if (Len > 1) then
// Inc(Result, (Ord(UpCase(Col[1])) - ASCIIOffset) *
//MaxLetters);
//end;
function TForecastCAMEXReport.Execute:boolean;
var
excel: variant;
mySheet: variant;
lastsupplier,lastsuppliercode,lastsupplierdirectory,lastpart: string;
firstpart: boolean;
i,weekoffset, weekrow, daterow, rowoffset, startrow,startcol,maxweekoffset:integer;
begin
result:=false;
try
Data_Module.LogActLog('CAMEXFC','Start order file creation');
excel:=Unassigned;
lastsupplier:='';
weekrow:=2;
daterow:=3;
startrow:=4;
startcol:=2;
weekoffset:=0;
rowoffset:=0;
maxweekoffset:=0;
firstpart:=true;
// Get non-ordered orders
Data_Module.Inv_DataSet.Close;
Data_Module.Inv_DataSet.Filter:='';
Data_Module.Inv_DataSet.Filtered:=FALSE;
Data_Module.Inv_DataSet.CommandType := CmdStoredProc;
Data_Module.Inv_DataSet.CommandText := 'dbo.REPORT_ForecastCAMEXReport;1';
Data_Module.Inv_DataSet.Parameters.Clear;
Data_Module.Inv_DataSet.Parameters.AddParameter.Name := '@WeekDate';
Data_Module.Inv_DataSet.Parameters.ParamValues['@WeekDate'] := formatdatetime('yyyymmdd',now);
Data_Module.Inv_DataSet.Open;
lastpart:=Data_Module.Inv_DataSet.FieldByName('Part Number').AsString;
if Data_Module.Inv_DataSet.recordcount > 0 then
begin
while not Data_Module.Inv_DataSet.Eof do
begin
if lastpart <> Data_Module.Inv_DataSet.FieldByName('Part Number').AsString then
begin
lastpart:=Data_Module.Inv_DataSet.FieldByName('Part Number').AsString;
if firstpart then
begin
mysheet.Cells[weekrow,startcol+weekoffset+1].value:='Total';
maxweekoffset:=weekoffset;
firstpart:=false;
end;
//Sum Formula
mysheet.Range[IntToXlCol(startcol+weekoffset+1)+IntToStr(startrow+rowoffset)].Formula:='=SUM(B'+IntToStr(startrow+rowoffset)+':'+IntToXlCol(startcol+weekoffset)+IntToStr(startrow+rowoffset)+')';
INC(rowoffset);
weekoffset:=0;
end;
//check for supplier change and save file
if lastsupplier <> Data_Module.Inv_DataSet.FieldByName('Supplier Name').AsString then
begin
if not VarIsEmpty(excel) then
begin
// TODO! Add totals macros at bottom of page
rowoffset:=rowoffset+2;
mysheet.Cells[startrow+rowoffset,1].value := 'Total';
for i:=0 to maxweekoffset+1 do
begin
mysheet.Range[IntToXlCol(startcol+i)+IntToStr(startrow+rowoffset)].Formula:='=SUM('+IntToXlCol(startcol+i)+IntToStr(startrow)+':'+IntToXlCol(startcol+i)+IntToStr(startrow+rowoffset-1)+')';
end;
// Create file in directory specified for each supplier
// Use supplier name+WeekDate for filename
try
if FileExists(lastsupplierdirectory+'\'+ANSIReplaceStr(lastsupplier,'/','')+'-'+lastsuppliercode+'-'+'CFForecast') then
DeleteFile(lastsupplierdirectory+'\'+ANSIReplaceStr(lastsupplier,'/','')+'-'+lastsuppliercode+'-'+'CFForecast');
excel.ActiveWorkbook.SaveAs(lastsupplierdirectory+'/'+ANSIReplaceStr(lastsupplier,'/','')+'-'+lastsuppliercode+'-'+'CFForecast');
Data_Module.LogActLog('CAMEXFC','Create camex forecast file '+lastsupplierdirectory+'/'+ANSIReplaceStr(lastsupplier,'/','')+'-'+lastsuppliercode+'-'+'CFForecast');
except
on e:exception do
begin
Data_Module.LogActLog('ERROR','Failed on delete and save excel files, '+e.message+', for supplier('+Data_Module.Inv_DataSet.FieldbyName('Directory').AsString+'\'+ANSIReplaceStr(Data_Module.Inv_DataSet.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_DataSet.fieldbyname('Supplier Code').AsString+'-'+'CFForecast'+')');
end;
end;
excel.Workbooks.Close;
excel.Quit;
excel:=Unassigned;
end;
lastsupplier := Data_Module.Inv_DataSet.FieldByName('Supplier Name').AsString;
lastsuppliercode := Data_Module.Inv_DataSet.fieldbyname('Supplier Code').AsString;
lastsupplierdirectory := Data_Module.Inv_DataSet.FieldbyName('Directory').AsString;
//open new file
excel := createOleObject('Excel.Application');
excel.visible := False;
excel.DisplayAlerts := False;
excel.workbooks.open(Data_Module.TemplateDir+'ForecastCamexTemplate.xls');
mysheet := excel.workSheets[1];
Data_Module.LogActLog('CAMEXFC','Create CAmex excel file for supplier, '+lastsupplier);
firstpart:=TRUE;
lastpart:=Data_Module.Inv_DataSet.FieldByName('Part Number').AsString;
weekoffset:=0;
rowoffset:=0;
end;
if firstpart then
begin
// do data and week headers
mysheet.Cells[weekrow,startcol+weekoffset].value := 'Week '+ Data_Module.Inv_DataSet.FieldByName('IN_WEEK_NUMBER').AsString;
mysheet.Cells[daterow,startcol+weekoffset].value := Data_Module.Inv_DataSet.FieldByName('VC_WEEK_DATE').AsString;
end;
if weekoffset=0 then
mysheet.Cells[startrow+rowoffset,1].value := lastpart;
mysheet.Cells[startrow+rowoffset,startcol+weekoffset].value := Data_Module.Inv_DataSet.FieldByName('Qty').AsString;
INC(weekoffset);
Data_Module.Inv_DataSet.Next;
end;
if not VarIsEmpty(excel) then
begin
// TODO! Add totals macros at bottom of page
rowoffset:=rowoffset+2;
mysheet.Cells[startrow+rowoffset,1].value := 'Total';
for i:=0 to maxweekoffset do
begin
mysheet.Range[IntToXlCol(startcol+i)+IntToStr(startrow+rowoffset)].Formula:='=SUM('+IntToXlCol(startcol+i)+IntToStr(startrow)+':'+IntToXlCol(startcol+i)+IntToStr(startrow+rowoffset-1)+')';
end;
// Create file in directory specified for each supplier
// Use supplier name+WeekDate for filename
try
if FileExists(lastsupplierdirectory+'\'+ANSIReplaceStr(lastsupplier,'/','')+'-'+lastsuppliercode+'-'+'CFForecast') then
DeleteFile(lastsupplierdirectory+'\'+ANSIReplaceStr(lastsupplier,'/','')+'-'+lastsuppliercode+'-'+'CFForecast');
excel.ActiveWorkbook.SaveAs(lastsupplierdirectory+'/'+ANSIReplaceStr(lastsupplier,'/','')+'-'+lastsuppliercode+'-'+'CFForecast');
Data_Module.LogActLog('CAMEXFC','Create camex forecast file '+lastsupplierdirectory+'/'+ANSIReplaceStr(lastsupplier,'/','')+'-'+lastsuppliercode+'-'+'CFForecast');
except
on e:exception do
begin
Data_Module.LogActLog('ERROR','Failed on delete and save excel files, '+e.message+', for supplier('+Data_Module.Inv_DataSet.FieldbyName('Directory').AsString+'\'+ANSIReplaceStr(Data_Module.Inv_DataSet.fieldbyname('Supplier Name').AsString,'/','')+'-'+Data_Module.Inv_DataSet.fieldbyname('Supplier Code').AsString+'-'+'CFForecast'+')');
end;
end;
excel.Workbooks.Close;
excel.Quit;
excel:=Unassigned;
end;
end
else
begin
Data_Module.LogActLog('CAMEXFC','No Camex forecast records found');
end;
Data_Module.LogActLog('CAMEXFC','Camex forecast file generation complete');
result:=true;
except
on e:exception do
begin
Data_Module.LogActLog('ERROR','Unable to create camex forecast files, '+e.message);
Data_Module.LogActLog('CAMEXFC','Failed on CAMEX forecast create');
if not VarIsEmpty(excel) then
begin
excel.Workbooks.Close;
excel.Quit;
excel:=Unassigned;
end;
end;
end;
end;
end.
|
unit ce_shortcutseditor;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils, FileUtil, TreeFilterEdit, Forms, Controls, Menus, Graphics,
ExtCtrls, LCLProc, ComCtrls, StdCtrls, Buttons, LCLType,
ce_observer, ce_interfaces, ce_common, ce_writableComponent;
type
TShortcutItem = class(TCollectionItem)
private
fIdentifier: string;
fData: TShortcut;
fDeclarator: ICEEditableShortCut;
property declarator: ICEEditableShortCut read fDeclarator write fDeclarator;
published
property identifier: string read fIdentifier write fIdentifier;
property data: TShortcut read fData write fData;
public
function combination: string;
procedure assign(aValue: TPersistent); override;
end;
TShortCutCollection = class(TWritableLfmTextComponent)
private
fItems: TCollection;
procedure setItems(aValue: TCollection);
function getCount: Integer;
function getItem(index: Integer): TShortcutItem;
published
property items: TCollection read fItems write setItems;
public
constructor create(AOwner: TComponent); override;
destructor destroy; override;
procedure assign(aValue: TPersistent); override;
//
function findIdentifier(const identifier: string): boolean;
function findShortcut(aShortcut: Word): boolean;
//
property count: Integer read getCount;
property item[index: Integer]: TShortcutItem read getItem; default;
end;
{ TCEShortcutEditor }
TCEShortcutEditor = class(TFrame, ICEEditableOptions)
btnClear: TSpeedButton;
shortcutCatcher: TEdit;
Panel1: TPanel;
fltItems: TTreeFilterEdit;
Panel2: TPanel;
schrtText: TStaticText;
btnActivate: TSpeedButton;
tree: TTreeView;
procedure btnActivateClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure LabeledEdit1KeyDown(Sender: TObject; var Key: Word;Shift: TShiftState);
procedure shortcutCatcherExit(Sender: TObject);
procedure shortcutCatcherMouseLeave(Sender: TObject);
procedure treeSelectionChanged(Sender: TObject);
private
fObservers: TCEEditableShortCutSubject;
fShortcuts: TShortCutCollection;
fBackup: TShortCutCollection;
fHasChanged: boolean;
//
function optionedWantCategory(): string;
function optionedWantEditorKind: TOptionEditorKind;
function optionedWantContainer: TPersistent;
procedure optionedEvent(anEvent: TOptionEditorEvent);
function optionedOptionsModified: boolean;
//
function findCategory(const aName: string; aData: Pointer): TTreeNode;
function findCategory(const aShortcutItem: TShortcutItem): string;
function sortCategories(Cat1, Cat2: TTreeNode): integer;
procedure receiveShortcuts;
procedure updateEditCtrls;
procedure sendShortcuts;
protected
procedure UpdateShowing; override;
public
constructor create(TheOwner: TComponent); override;
destructor destroy; override;
end;
implementation
{$R *.lfm}
var
CEShortcutEditor: TCEShortcutEditor;
{$REGION TShortCutCollection ---------------------------------------------------}
function TShortcutItem.combination: string;
begin
result := ShortCutToText(fData);
end;
procedure TShortcutItem.assign(aValue: TPersistent);
var
src: TShortcutItem;
begin
if aValue is TShortcutItem then
begin
src := TShortcutItem(aValue);
fData:= src.fData;
fIdentifier:= src.fIdentifier;
fDeclarator := src.fDeclarator;
end
else inherited;
end;
constructor TShortCutCollection.create(AOwner: TComponent);
begin
inherited;
fItems := TCollection.Create(TShortcutItem);
end;
destructor TShortCutCollection.destroy;
begin
fItems.Free;
inherited;
end;
procedure TShortCutCollection.assign(aValue: TPersistent);
begin
if aValue is TShortCutCollection then
fItems.Assign(TShortCutCollection(aValue).fItems)
else
inherited;
end;
procedure TShortCutCollection.setItems(aValue: TCollection);
begin
fItems.Assign(aValue);
end;
function TShortCutCollection.getCount: Integer;
begin
exit(fItems.Count);
end;
function TShortCutCollection.getItem(index: Integer): TShortcutItem;
begin
exit(TShortcutItem(fItems.Items[index]));
end;
function TShortCutCollection.findIdentifier(const identifier: string): boolean;
var
i: Integer;
begin
result := false;
for i := 0 to count-1 do
if item[i].identifier = identifier then
exit(true);
end;
function TShortCutCollection.findShortcut(aShortcut: Word): boolean;
var
i: Integer;
begin
result := false;
for i := 0 to count-1 do
if item[i].data = aShortcut then
exit(true);
end;
{$ENDREGION}
{$REGION Standard Comp/Object things -------------------------------------------}
constructor TCEShortcutEditor.create(TheOwner: TComponent);
var
png: TPortableNetworkGraphic;
begin
inherited;
fObservers := TCEEditableShortCutSubject.create;
fShortcuts := TShortCutCollection.create(self);
fBackup := TShortCutCollection.create(self);
//
png := TPortableNetworkGraphic.Create;
try
png.LoadFromLazarusResource('clean');
btnClear.Glyph.Assign(png);
finally
png.free;
end;
//
EntitiesConnector.addObserver(self);
end;
destructor TCEShortcutEditor.destroy;
begin
fObservers.Free;
inherited;
end;
procedure TCEShortcutEditor.UpdateShowing;
var
png : TPortableNetworkGraphic;
begin
inherited;
if not visible then exit;
//
png := TPortableNetworkGraphic.Create;
try
png.LoadFromLazarusResource('keyboard_pencil');
btnActivate.Glyph.Assign(png);
finally
png.free;
end;
end;
{$ENDREGION}
{$REGION ICEEditableOptions ----------------------------------------------------}
function TCEShortcutEditor.optionedWantCategory(): string;
begin
exit('Shortcuts');
end;
function TCEShortcutEditor.optionedWantEditorKind: TOptionEditorKind;
begin
exit(oekControl);
end;
function TCEShortcutEditor.optionedWantContainer: TPersistent;
begin
receiveShortcuts;
exit(self);
end;
procedure TCEShortcutEditor.optionedEvent(anEvent: TOptionEditorEvent);
begin
case anEvent of
oeeSelectCat: receiveShortcuts;
oeeCancel:
begin
fShortcuts.assign(fBackup);
sendShortcuts;
fHasChanged := false;
end;
oeeAccept:
begin
fBackup.assign(fShortcuts);
sendShortcuts;
fHasChanged := false;
end;
end;
end;
function TCEShortcutEditor.optionedOptionsModified: boolean;
begin
exit(fHasChanged);
end;
{$ENDREGION}
{$REGION shortcut editor things ------------------------------------------------}
procedure TCEShortcutEditor.treeSelectionChanged(Sender: TObject);
begin
updateEditCtrls;
end;
procedure TCEShortcutEditor.shortcutCatcherExit(Sender: TObject);
begin
shortcutCatcher.Enabled := false;
updateEditCtrls;
end;
procedure TCEShortcutEditor.shortcutCatcherMouseLeave(Sender: TObject);
begin
shortcutCatcher.Enabled := false;
updateEditCtrls;
end;
procedure TCEShortcutEditor.btnActivateClick(Sender: TObject);
begin
if tree.Selected = nil then exit;
if tree.Selected.Level = 0 then exit;
if tree.Selected.Data = nil then exit;
//
shortcutCatcher.Enabled := not shortcutCatcher.Enabled;
end;
procedure TCEShortcutEditor.btnClearClick(Sender: TObject);
begin
if tree.Selected = nil then exit;
if tree.Selected.Level = 0 then exit;
if tree.Selected.Data = nil then exit;
//
if TShortcutItem(tree.Selected.Data).data <> 0 then
begin
TShortcutItem(tree.Selected.Data).data := 0;
fHasChanged := true;
end;
//
updateEditCtrls;
end;
procedure TCEShortcutEditor.LabeledEdit1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
sh: TShortCut;
begin
if tree.Selected = nil then exit;
if tree.Selected.Level = 0 then exit;
if tree.Selected.Data = nil then exit;
//
if Key = VK_RETURN then
shortcutCatcher.Enabled := false
else
begin
sh := Shortcut(Key, Shift);
if TShortcutItem(tree.Selected.Data).data <> sh then
begin
TShortcutItem(tree.Selected.Data).data := sh;
fHasChanged := true;
end;
end;
//
updateEditCtrls;
end;
procedure TCEShortcutEditor.updateEditCtrls;
begin
schrtText.Caption := '';
//
if tree.Selected = nil then exit;
if tree.Selected.Level = 0 then exit;
if tree.Selected.Data = nil then exit;
//
schrtText.Caption := TShortcutItem(tree.Selected.Data).combination;
shortcutCatcher.Text := '';
end;
function TCEShortcutEditor.findCategory(const aName: string; aData: Pointer): TTreeNode;
var
i: integer;
begin
result := nil;
for i:= 0 to tree.Items.Count-1 do
if tree.Items[i].Text = aName then
if tree.Items[i].Data = aData then
exit(tree.Items[i]);
end;
function TCEShortcutEditor.findCategory(const aShortcutItem: TShortcutItem): string;
var
i, j: integer;
begin
result := '';
for i := 0 to tree.Items.Count-1 do
for j:= 0 to tree.Items.Item[i].Count-1 do
if tree.Items.Item[i].Items[j].Data = Pointer(aShortcutItem) then
exit(tree.Items.Item[i].Text);
end;
function TCEShortcutEditor.sortCategories(Cat1, Cat2: TTreeNode): integer;
begin
result := CompareText(Cat1.Text, Cat2.Text);
end;
procedure TCEShortcutEditor.receiveShortcuts;
var
i: Integer;
obs: ICEEditableShortCut;
cat: string;
sht: word;
idt: string;
itm: TShortcutItem;
procedure addItem();
var
prt: TTreeNode;
begin
// root category
if cat = '' then exit;
if idt = '' then exit;
prt := findCategory(cat, obs);
if prt = nil then
prt := tree.Items.AddObject(nil, cat, obs);
// item as child
itm := TShortcutItem(fShortcuts.items.Add);
itm.identifier := idt;
itm.data:= sht;
itm.declarator := obs;
tree.Items.AddChildObject(prt, idt, itm);
cat := '';
idt := '';
end;
begin
tree.Items.Clear;
fShortcuts.items.Clear;
fBackup.items.Clear;
cat := '';
idt := '';
for i:= 0 to fObservers.observersCount-1 do
begin
obs := fObservers.observers[i] as ICEEditableShortCut;
if obs.scedWantFirst then
begin
while obs.scedWantNext(cat, idt, sht) do
addItem();
addItem();
end;
end;
tree.Items.SortTopLevelNodes(@sortCategories);
fBackup.Assign(fShortcuts);
end;
procedure TCEShortcutEditor.sendShortcuts;
var
i: integer;
shc: TShortcutItem;
cat: string;
begin
for i := 0 to fShortcuts.count-1 do
begin
shc := fShortcuts[i];
cat := findCategory(shc);
if cat = '' then
continue;
if shc.declarator = nil then
continue;
shc.declarator.scedSendItem(cat, shc.identifier, shc.data);
end;
end;
{$ENDREGION}
initialization
CEShortcutEditor := TCEShortcutEditor.Create(nil);
finalization
CEShortcutEditor.Free;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
function f(x:double):double; //Исследуемая функция
begin
f:=x+cos(x)*sin(2*x)-3/7;
end;
procedure TForm1.Button1Click(Sender: TObject); //Метод хорд
//Вторая производная отрицательна на итервале
var
a,b,x,eps,min:double;
n:integer;
work:boolean;
begin
eps:=StrToFloat(edit1.Text);
a:=0.1;
b:=0.2;
work:=true;
min:=1+2*cos(b)*cos(2*b)-sin(b)*sin(2*b); //Минимум производной
x:=b;
n:=0;
while work do
begin
inc(n);
x:=a-(f(a)*(x-a))/(f(x)-f(a));
if (abs(f(x))/min)<eps then work:=false;
end;
label1.Caption:='x= '+FloatToStr(x)+', n= '+IntToStr(n);
end;
Function fi(x,maxF:double):double;
begin
fi:=x-f(x)/(0.9*maxF); //L=maxF
end;
procedure TForm1.Button2Click(Sender: TObject); //Метод итераций
var
a,b,x,eps,maxF,minF,q,x1:double;
n:integer;
work:boolean;
begin
eps:=StrToFloat(edit2.Text);
a:=0.1;
b:=0.2;
work:=true;
minF:=1+2*cos(b)*cos(2*b)-sin(b)*sin(2*b); //минимум производной
maxF:=1+2*cos(a)*cos(2*a)-sin(a)*sin(2*a); //максимум производной
if (1/9)>abs(1-minf/(0.9*maxf)) then q:=1/9
else q:=abs(1-minf/(0.9*maxf));
x:=b;
n:=0;
while work do
begin
inc(n);
x1:=x;
x:=fi(x,maxF);
if (abs(x1-x)*q/(1-q))<eps then work:=false;
end;
label2.Caption:='x= '+FloatToStr(x)+', n= '+IntToStr(n);
end;
end.
|
unit BitStream_lib;
interface
uses classes;
type
TBitStream=class(TStream)
private
fStream: TStream;
fBitBuffer: Integer;
fcapacity: Integer;
public
constructor Create(stream: Tstream);
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
end;
TWriteBitStream=class(TBitStream)
public
destructor Destroy; override;
procedure WriteBits(source: Integer; count: Integer);
// procedure WriteBitsUnsigned(source: Cardinal; count: Integer);
end;
TReadBitStream=class(TBitStream)
public
function ReadBitsSigned(out dest: Integer; count: Integer): Integer;
function ReadBitsUnsigned(out dest: Cardinal; count: Integer): Integer;
end;
implementation
(*
TBitStream
*)
constructor TBitStream.Create(stream: TStream);
begin
inherited Create;
fStream:=stream;
end;
function TBitStream.Read(var Buffer; count: Integer): Integer;
begin
Result:=fstream.Read(Buffer, count);
end;
function TBitStream.Write(const Buffer; count: Integer): Integer;
begin
Result:=fstream.Write(Buffer,count);
end;
(*
TWriteBitStream
*)
procedure TWriteBitStream.WriteBits(source: Integer; count: Integer);
var mask: Integer;
begin
if count<1 then Exit;
//записывает от 0 до 32 бит в вых. поток
mask:=(1 shl count)-1;
source:=source and mask;
if fcapacity+count<32 then begin
fBitBuffer:=(fBitBuffer shl count) or source;
inc(fCapacity,count);
end
else begin
fBitBuffer:=(fBitBuffer shl (32-fcapacity)) or (source shr (count+fcapacity-32));
//теперь fBitBuffer полон!
fStream.Write(fBitBuffer,SizeOf(fBitBuffer));
mask:=mask shr (32-fcapacity);
fBitBuffer:=source and mask;
fCapacity:=fcapacity+count-32;
end;
end;
destructor TWriteBitStream.Destroy;
begin
//нужно дописать последние байты
fBitBuffer:=fBitBuffer shl (32-fcapacity);
fStream.Write(fBitBuffer,SizeOf(fBitBuffer));
inherited Destroy;
end;
(*
TReadBitStream
*)
function TReadBitStream.ReadBitsSigned(out dest: Integer; count: Integer): Integer;
var mask: Integer;
item: Integer;
bucount: Integer;
begin
dest:=0;
Result:=0;
bucount:=count;
if fCapacity<count then begin
mask:=(1 shl fCapacity)-1; //уж сколько есть, столько и возьмем
dest:=fBitBuffer and (mask shl (32-fCapacity));
//сейчас нужен arithmetic shift right (sar)
//dest:=dest sar (32-count)
// dest:=dest shr (32-count);
dest:=dest div (1 shl (32-count));
if count=1 then dest:=-dest;
Result:=fCapacity;
count:=count-fCapacity;
fCapacity:=fstream.Read(fBitBuffer,SizeOf(fBitBuffer))*8;
//если fCapacity<count, нам остается лишь смириться
if fCapacity<count then count:=fCapacity;
end;
mask:=(1 shl count)-1;
item:=fBitBuffer and (mask shl (32-count));
//сейчас по-хорошему нужно провернуть arithmetic shift right
//dest:=dest sar (32-count);
// dest:=dest shr (32-count);
if count=bucount then begin
item:=item div (1 shl (32-count));
if count=1 then item:=-item;
end
else
item:=item shr (32-count);
dest:=dest or item;
fBitBuffer:=fBitBuffer shl count;
dec(fCapacity,count);
Result:=Result+Count;
end;
function TReadBitStream.ReadBitsUnsigned(out dest: Cardinal; count: Integer): Integer;
var mask: Integer;
item: Cardinal;
begin
dest:=0;
Result:=0;
if fCapacity<count then begin
mask:=(1 shl fCapacity)-1; //уж сколько есть, столько и возьмем
dest:=fBitBuffer and (mask shl (32-fCapacity));
//сейчас нужен arithmetic shift right (sar)
//dest:=dest sar (32-count)
// dest:=dest shr (32-count);
dest:=dest shr (1 shl (32-count));
Result:=fCapacity;
count:=count-fCapacity;
fCapacity:=fstream.Read(fBitBuffer,SizeOf(fBitBuffer))*8;
//если fCapacity<count, нам остается лишь смириться
if fCapacity<count then count:=fCapacity;
end;
mask:=(1 shl count)-1;
item:=fBitBuffer and (mask shl (32-count));
//сейчас по-хорошему нужно провернуть arithmetic shift right
//dest:=dest sar (32-count);
// dest:=dest shr (32-count);
item:=item shr (32-count);
dest:=dest or item;
fBitBuffer:=fBitBuffer shl count;
dec(fCapacity,count);
Result:=Result+Count;
end;
end.
|
unit sieve1899;
//---------------------- COMMON INTERFACE --------------------------------------
{$i '../inc/header.inc'}
//---------------------- IMPLEMENTATION ----------------------------------------
procedure benchmark;
var
count : word absolute $e0;
i : word absolute $e2;
k : word absolute $e4;
prime : word absolute $e6;
bi : byte absolute $e8;
flags : array [0..8191] of boolean absolute $a000;
begin
for bi := 9 downto 0 do begin
fillchar(flags, sizeof(flags), true);
i:=0; count := 0;
while i <= 8191 do begin
if flags[i] then begin
prime := (i * 2) + 3;
k := prime + i;
while (k <= 8191) do begin
flags[k] := false;
inc(k, prime);
end;
inc(count);
end;
inc(i);
end;
end;
end;
//---------------------- COMMON PROCEDURE --------------------------------------
{$i '../inc/run.inc'}
//---------------------- INITIALIZATION ----------------------------------------
initialization
name := #$5d'Sieve 1899 10x'~;
end.
|
{
fpvectorial.pas
Vector graphics document
License: The same modified LGPL as the Free Pascal RTL
See the file COPYING.modifiedLGPL for more details
AUTHORS: Felipe Monteiro de Carvalho
Pedro Sol Pegorini L de Lima
}
unit fpvectorial;
{$ifdef fpc}
{$mode delphi}
{$endif}
interface
uses
Classes, SysUtils;
type
TvVectorialFormat = (
{ Multi-purpose document formats }
vfPDF, vfPostScript, vfSVG, vfCorelDrawCDR, vfWindowsMetafileWMF,
{ CAD formats }
vfDXF,
{ GCode formats }
vfGCodeAvisoCNCPrototipoV5, vfGCodeAvisoCNCPrototipoV6);
const
{ Default extensions }
STR_PDF_EXTENSION = '.pdf';
type
TSegmentType = (
st2DLine, st2DBezier,
st3DLine, st3DBezier);
TPathSegment = record
SegmentType: TSegmentType;
X, Y, Z: Double; // Z is ignored in 2D segments
X2, Y2, Z2: Double; // Z is ignored in 2D segments
X3, Y3, Z3: Double; // Z is ignored in 2D segments
end;
TPath = record
Len: Integer;
// ToDo: make the array dynamic
Points: array[0..255] of TPathSegment;
end;
PPath = ^TPath;
type
TvCustomVectorialWriter = class;
TvCustomVectorialReader = class;
{ TvVectorialDocument }
TvVectorialDocument = class
private
FPaths: TFPList;
FTmpPath: TPath;
procedure RemoveCallback(data, arg: pointer);
function CreateVectorialWriter(AFormat: TvVectorialFormat): TvCustomVectorialWriter;
function CreateVectorialReader(AFormat: TvVectorialFormat): TvCustomVectorialReader;
public
Name: string;
Width, Height: Double; // in millimeters
{ Base methods }
constructor Create;
destructor Destroy; override;
procedure WriteToFile(AFileName: string; AFormat: TvVectorialFormat);
procedure WriteToStream(AStream: TStream; AFormat: TvVectorialFormat);
procedure WriteToStrings(AStrings: TStrings; AFormat: TvVectorialFormat);
procedure ReadFromFile(AFileName: string; AFormat: TvVectorialFormat);
procedure ReadFromStream(AStream: TStream; AFormat: TvVectorialFormat);
procedure ReadFromStrings(AStrings: TStrings; AFormat: TvVectorialFormat);
{ Data reading methods }
function GetPath(ANum: Cardinal): TPath;
function GetPathCount: Integer;
{ Data removing methods }
procedure Clear;
procedure RemoveAllPaths;
{ Data writing methods }
procedure AddPath(APath: TPath);
procedure StartPath(AX, AY: Double);
procedure AddLineToPath(AX, AY: Double); overload;
procedure AddLineToPath(AX, AY, AZ: Double); overload;
procedure AddBezierToPath(AX1, AY1, AX2, AY2, AX3, AY3: Double); overload;
procedure AddBezierToPath(AX1, AY1, AZ1, AX2, AY2, AZ2, AX3, AY3, AZ3: Double); overload;
procedure EndPath();
{ properties }
property PathCount: Integer read GetPathCount;
property Paths[Index: Cardinal]: TPath read GetPath;
end;
{@@ TvVectorialReader class reference type }
TvVectorialReaderClass = class of TvCustomVectorialReader;
{ TvCustomVectorialReader }
TvCustomVectorialReader = class
public
{ General reading methods }
procedure ReadFromFile(AFileName: string; AData: TvVectorialDocument); virtual;
procedure ReadFromStream(AStream: TStream; AData: TvVectorialDocument); virtual;
procedure ReadFromStrings(AStrings: TStrings; AData: TvVectorialDocument); virtual;
end;
{@@ TvVectorialWriter class reference type }
TvVectorialWriterClass = class of TvCustomVectorialWriter;
{@@ TvCustomVectorialWriter }
{ TvCustomVectorialWriter }
TvCustomVectorialWriter = class
public
{ General writing methods }
procedure WriteToFile(AFileName: string; AData: TvVectorialDocument); virtual;
procedure WriteToStream(AStream: TStream; AData: TvVectorialDocument); virtual;
procedure WriteToStrings(AStrings: TStrings; AData: TvVectorialDocument); virtual;
end;
{@@ List of registered formats }
TvVectorialFormatData = record
ReaderClass: TvVectorialReaderClass;
WriterClass: TvVectorialWriterClass;
ReaderRegistered: Boolean;
WriterRegistered: Boolean;
Format: TvVectorialFormat;
end;
var
GvVectorialFormats: array of TvVectorialFormatData;
procedure RegisterVectorialReader(
AReaderClass: TvVectorialReaderClass;
AFormat: TvVectorialFormat);
procedure RegisterVectorialWriter(
AWriterClass: TvVectorialWriterClass;
AFormat: TvVectorialFormat);
implementation
{@@
Registers a new reader for a format
}
procedure RegisterVectorialReader(
AReaderClass: TvVectorialReaderClass;
AFormat: TvVectorialFormat);
var
i, len: Integer;
FormatInTheList: Boolean;
begin
len := Length(GvVectorialFormats);
FormatInTheList := False;
{ First search for the format in the list }
for i := 0 to len - 1 do
begin
if GvVectorialFormats[i].Format = AFormat then
begin
if GvVectorialFormats[i].ReaderRegistered then
raise Exception.Create('RegisterVectorialReader: Reader class for format ' {+ AFormat} + ' already registered.');
GvVectorialFormats[i].ReaderRegistered := True;
GvVectorialFormats[i].ReaderClass := AReaderClass;
FormatInTheList := True;
Break;
end;
end;
{ If not already in the list, then add it }
if not FormatInTheList then
begin
SetLength(GvVectorialFormats, len + 1);
GvVectorialFormats[len].ReaderClass := AReaderClass;
GvVectorialFormats[len].WriterClass := nil;
GvVectorialFormats[len].ReaderRegistered := True;
GvVectorialFormats[len].WriterRegistered := False;
GvVectorialFormats[len].Format := AFormat;
end;
end;
{@@
Registers a new writer for a format
}
procedure RegisterVectorialWriter(
AWriterClass: TvVectorialWriterClass;
AFormat: TvVectorialFormat);
var
i, len: Integer;
FormatInTheList: Boolean;
begin
len := Length(GvVectorialFormats);
FormatInTheList := False;
{ First search for the format in the list }
for i := 0 to len - 1 do
begin
if GvVectorialFormats[i].Format = AFormat then
begin
if GvVectorialFormats[i].WriterRegistered then
raise Exception.Create('RegisterVectorialWriter: Writer class for format ' + {AFormat +} ' already registered.');
GvVectorialFormats[i].WriterRegistered := True;
GvVectorialFormats[i].WriterClass := AWriterClass;
FormatInTheList := True;
Break;
end;
end;
{ If not already in the list, then add it }
if not FormatInTheList then
begin
SetLength(GvVectorialFormats, len + 1);
GvVectorialFormats[len].ReaderClass := nil;
GvVectorialFormats[len].WriterClass := AWriterClass;
GvVectorialFormats[len].ReaderRegistered := False;
GvVectorialFormats[len].WriterRegistered := True;
GvVectorialFormats[len].Format := AFormat;
end;
end;
{ TsWorksheet }
{@@
Helper method for clearing the records in a spreadsheet.
}
procedure TvVectorialDocument.RemoveCallback(data, arg: pointer);
begin
if data <> nil then FreeMem(data);
end;
{@@
Constructor.
}
constructor TvVectorialDocument.Create;
begin
inherited Create;
FPaths := TFPList.Create;
end;
{@@
Destructor.
}
destructor TvVectorialDocument.Destroy;
begin
Clear;
FPaths.Free;
inherited Destroy;
end;
{@@
Clears the list of Vectors and releases their memory.
}
procedure TvVectorialDocument.RemoveAllPaths;
begin
FPaths.ForEachCall(RemoveCallback, nil);
FPaths.Clear;
end;
procedure TvVectorialDocument.AddPath(APath: TPath);
var
Path: PPath;
Len: Integer;
begin
Len := SizeOf(TPath);
//WriteLn(':>TvVectorialDocument.AddPath 1 Len = ', Len);
Path := GetMem(Len);
//WriteLn(':>TvVectorialDocument.AddPath 2');
Move(APath, Path^, Len);
//WriteLn(':>TvVectorialDocument.AddPath 3');
FPaths.Add(Path);
//WriteLn(':>TvVectorialDocument.AddPath 4');
end;
{@@
Starts writing a Path in multiple steps.
Should be followed by zero or more calls to AddPointToPath
and by a call to EndPath to effectively add the data.
@see StartPath, AddPointToPath
}
procedure TvVectorialDocument.StartPath(AX, AY: Double);
begin
FTmpPath.Len := 1;
FTmpPath.Points[0].SegmentType := st2DLine;
FTmpPath.Points[0].X := AX;
FTmpPath.Points[0].Y := AY;
end;
{@@
Adds one more point to the end of a Path being
writing in multiple steps.
Does nothing if not called between StartPath and EndPath.
Can be called multiple times to add multiple points.
@see StartPath, EndPath
}
procedure TvVectorialDocument.AddLineToPath(AX, AY: Double);
var
L: Integer;
begin
L := FTmpPath.Len;
Inc(FTmpPath.Len);
FTmpPath.Points[L].SegmentType := st2DLine;
FTmpPath.Points[L].X := AX;
FTmpPath.Points[L].Y := AY;
end;
procedure TvVectorialDocument.AddLineToPath(AX, AY, AZ: Double);
var
L: Integer;
begin
L := FTmPPath.Len;
Inc(FTmPPath.Len);
FTmPPath.Points[L].SegmentType := st3DLine;
FTmPPath.Points[L].X := AX;
FTmPPath.Points[L].Y := AY;
FTmPPath.Points[L].Z := AZ;
end;
procedure TvVectorialDocument.AddBezierToPath(AX1, AY1, AX2, AY2, AX3,
AY3: Double);
var
L: Integer;
begin
L := FTmPPath.Len;
Inc(FTmPPath.Len);
FTmPPath.Points[L].SegmentType := st2DBezier;
FTmPPath.Points[L].X := AX3;
FTmPPath.Points[L].Y := AY3;
FTmPPath.Points[L].X2 := AX1;
FTmPPath.Points[L].Y2 := AY1;
FTmPPath.Points[L].X3 := AX2;
FTmPPath.Points[L].Y3 := AY2;
end;
procedure TvVectorialDocument.AddBezierToPath(AX1, AY1, AZ1, AX2, AY2, AZ2,
AX3, AY3, AZ3: Double);
begin
end;
{@@
Finishes writing a Path, which was created in multiple
steps using StartPath and AddPointToPath,
to the document.
Does nothing if there wasn't a previous correspondent call to
StartPath.
@see StartPath, AddPointToPath
}
procedure TvVectorialDocument.EndPath();
begin
if FTmPPath.Len = 0 then Exit;
AddPath(FTmPPath);
FTmPPath.Len := 0;
end;
{@@
Convenience method which creates the correct
writer object for a given vector graphics document format.
}
function TvVectorialDocument.CreateVectorialWriter(AFormat: TvVectorialFormat): TvCustomVectorialWriter;
var
i: Integer;
begin
Result := nil;
for i := 0 to Length(GvVectorialFormats) - 1 do
if GvVectorialFormats[i].Format = AFormat then
begin
Result := GvVectorialFormats[i].WriterClass.Create;
Break;
end;
if Result = nil then raise Exception.Create('Unsuported vector graphics format.');
end;
{@@
Convenience method which creates the correct
reader object for a given vector graphics document format.
}
function TvVectorialDocument.CreateVectorialReader(AFormat: TvVectorialFormat): TvCustomVectorialReader;
var
i: Integer;
begin
Result := nil;
for i := 0 to Length(GvVectorialFormats) - 1 do
if GvVectorialFormats[i].Format = AFormat then
begin
Result := GvVectorialFormats[i].ReaderClass.Create;
Break;
end;
if Result = nil then raise Exception.Create('Unsuported vector graphics format.');
end;
{@@
Writes the document to a file.
If the file doesn't exist, it will be created.
}
procedure TvVectorialDocument.WriteToFile(AFileName: string; AFormat: TvVectorialFormat);
var
AWriter: TvCustomVectorialWriter;
begin
AWriter := CreateVectorialWriter(AFormat);
try
AWriter.WriteToFile(AFileName, Self);
finally
AWriter.Free;
end;
end;
{@@
Writes the document to a stream
}
procedure TvVectorialDocument.WriteToStream(AStream: TStream; AFormat: TvVectorialFormat);
var
AWriter: TvCustomVectorialWriter;
begin
AWriter := CreateVectorialWriter(AFormat);
try
AWriter.WriteToStream(AStream, Self);
finally
AWriter.Free;
end;
end;
procedure TvVectorialDocument.WriteToStrings(AStrings: TStrings;
AFormat: TvVectorialFormat);
var
AWriter: TvCustomVectorialWriter;
begin
AWriter := CreateVectorialWriter(AFormat);
try
AWriter.WriteToStrings(AStrings, Self);
finally
AWriter.Free;
end;
end;
{@@
Reads the document from a file.
Any current contents will be removed.
}
procedure TvVectorialDocument.ReadFromFile(AFileName: string;
AFormat: TvVectorialFormat);
var
AReader: TvCustomVectorialReader;
begin
Self.Clear;
AReader := CreateVectorialReader(AFormat);
try
AReader.ReadFromFile(AFileName, Self);
finally
AReader.Free;
end;
end;
{@@
Reads the document from a stream.
Any current contents will be removed.
}
procedure TvVectorialDocument.ReadFromStream(AStream: TStream;
AFormat: TvVectorialFormat);
var
AReader: TvCustomVectorialReader;
begin
Self.Clear;
AReader := CreateVectorialReader(AFormat);
try
AReader.ReadFromStream(AStream, Self);
finally
AReader.Free;
end;
end;
procedure TvVectorialDocument.ReadFromStrings(AStrings: TStrings;
AFormat: TvVectorialFormat);
var
AReader: TvCustomVectorialReader;
begin
Self.Clear;
AReader := CreateVectorialReader(AFormat);
try
AReader.ReadFromStrings(AStrings, Self);
finally
AReader.Free;
end;
end;
function TvVectorialDocument.GetPath(ANum: Cardinal): TPath;
begin
if ANum >= FPaths.Count then raise Exception.Create('TvVectorialDocument.GetPath: Path number out of bounds');
if FPaths.Items[ANum] = nil then raise Exception.Create('TvVectorialDocument.GetPath: Invalid Path number');
Result := PPath(FPaths.Items[ANum])^;
end;
function TvVectorialDocument.GetPathCount: Integer;
begin
Result := FPaths.Count;
end;
{@@
Clears all data in the document
}
procedure TvVectorialDocument.Clear;
begin
RemoveAllPaths();
end;
{ TvCustomVectorialReader }
procedure TvCustomVectorialReader.ReadFromFile(AFileName: string; AData: TvVectorialDocument);
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone);
try
ReadFromStream(FileStream, AData);
finally
FileStream.Free;
end;
end;
procedure TvCustomVectorialReader.ReadFromStream(AStream: TStream;
AData: TvVectorialDocument);
var
AStringStream: TStringStream;
AStrings: TStringList;
begin
AStringStream := TStringStream.Create('');
AStrings := TStringList.Create;
try
AStringStream.CopyFrom(AStream, AStream.Size);
AStringStream.Seek(0, soFromBeginning);
AStrings.Text := AStringStream.DataString;
ReadFromStrings(AStrings, AData);
finally
AStringStream.Free;
AStrings.Free;
end;
end;
procedure TvCustomVectorialReader.ReadFromStrings(AStrings: TStrings;
AData: TvVectorialDocument);
var
AStringStream: TStringStream;
begin
AStringStream := TStringStream.Create('');
try
AStringStream.WriteString(AStrings.Text);
AStringStream.Seek(0, soFromBeginning);
ReadFromStream(AStringStream, AData);
finally
AStringStream.Free;
end;
end;
{ TsCustomSpreadWriter }
{@@
Default file writting method.
Opens the file and calls WriteToStream
@param AFileName The output file name.
If the file already exists it will be replaced.
@param AData The Workbook to be saved.
@see TsWorkbook
}
procedure TvCustomVectorialWriter.WriteToFile(AFileName: string; AData: TvVectorialDocument);
var
OutputFile: TFileStream;
begin
OutputFile := TFileStream.Create(AFileName, fmCreate or fmOpenWrite);
try
WriteToStream(OutputFile, AData);
finally
OutputFile.Free;
end;
end;
procedure TvCustomVectorialWriter.WriteToStream(AStream: TStream;
AData: TvVectorialDocument);
begin
end;
procedure TvCustomVectorialWriter.WriteToStrings(AStrings: TStrings;
AData: TvVectorialDocument);
begin
end;
finalization
SetLength(GvVectorialFormats, 0);
end.
|
unit IngDatos;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Provider, DB, DBClient, ActnMan, wwrcdpnl, TypInfo, JvComponent,
JvEnterTab;
type
TFIngDat = class(TForm)
DCds: TDataSource;
Cds: TClientDataSet;
DspIng: TDataSetProvider;
JvEnterAsTab1: TJvEnterAsTab;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CdsAfterPost(DataSet: TDataSet);
procedure CdsAfterDelete(DataSet: TDataSet);
procedure Reconciliar(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
private
{ Private declarations }
FConfirmaGrabacion: boolean;
FAutoInsert: boolean;
FMayusculas: boolean;
FConfirmaBorrar: boolean;
FBusNom: string;
FBusCod: string;
FCampoActivo: TWinControl;
FNoCerrar: boolean;
FPrimeraVez: boolean;
procedure SetAutoInsert(const Value: boolean);
procedure SetBusCod(const Value: string);
procedure SetBusNom(const Value: string);
procedure SetCampoActivo(const Value: TWinControl);
procedure SetConfirmaBorrar(const Value: boolean);
procedure SetConfirmaGrabacion(const Value: boolean);
procedure SetMayusculas(const Value: boolean);
procedure SetNoCerrar(const Value: boolean);
procedure SetPrimeraVez(const Value: boolean);
procedure AplicarCambios( DataSet: TDataSet );
public
{ Public declarations }
procedure CreateWnd; override;
procedure SetAcciones( Am: TActionmanager ); virtual;
published
property CampoActivo: TWinControl read FCampoActivo write SetCampoActivo;
property ConfirmaGrabacion: boolean read FConfirmaGrabacion write SetConfirmaGrabacion;
property ConfirmaBorrar: boolean read FConfirmaBorrar write SetConfirmaBorrar;
property AutoInsert: boolean read FAutoInsert write SetAutoInsert;
property Mayusculas: boolean read FMayusculas write SetMayusculas;
property BusCod: string read FBusCod write SetBusCod;
property BusNom: string read FBusNom write SetBusNom;
property NoCerrar: boolean read FNoCerrar write SetNoCerrar;
property PrimeraVez: boolean read FPrimeraVez write SetPrimeraVez;
end;
var
FIngDat: TFIngDat;
implementation
uses
Reconciliar;
{$R *.dfm}
{ TFIngDat }
procedure TFIngDat.SetAcciones(Am: TActionmanager);
var
x: integer;
PropInfo: PPropInfo;
begin
for x:=0 to Am.ActionCount -1 do
if Am.Actions[ x ].Category = 'Dataset' then
begin
PropInfo := GetPropInfo( Am.Actions[ x ], 'DataSource' );
if PropInfo <> nil then
SetObjectProp( Am.Actions[ x ], PropInfo, DCds );
end;
end;
procedure TFIngDat.FormCreate(Sender: TObject);
begin
inherited;
if Assigned( DCds.DataSet ) then
begin
FNoCerrar := ( DCds.DataSet.Active = true );
if not ( DCds.DataSet.Active ) then
DCds.DataSet.open;
if FAutoInsert then
DCds.DataSet.Append;
end;
end;
procedure TFIngDat.FormDestroy(Sender: TObject);
begin
Cds.close;
inherited;
end;
procedure TFIngDat.SetAutoInsert(const Value: boolean);
begin
FAutoInsert := Value;
end;
procedure TFIngDat.SetBusCod(const Value: string);
begin
FBusCod := Value;
end;
procedure TFIngDat.SetBusNom(const Value: string);
begin
FBusNom := Value;
end;
procedure TFIngDat.SetCampoActivo(const Value: TWinControl);
begin
FCampoActivo := Value;
end;
procedure TFIngDat.SetConfirmaBorrar(const Value: boolean);
begin
FConfirmaBorrar := Value;
end;
procedure TFIngDat.SetConfirmaGrabacion(const Value: boolean);
begin
FConfirmaGrabacion := Value;
end;
procedure TFIngDat.SetMayusculas(const Value: boolean);
begin
FMayusculas := Value;
end;
procedure TFIngDat.CreateWnd;
begin
inherited;
FPrimeraVez := true;
FMayusculas := true;
FConfirmaGrabacion := false;
FConfirmaBorrar := false;
FAutoInsert := true;
end;
procedure TFIngDat.FormClose(Sender: TObject; var Action: TCloseAction);
begin
try
if ( Assigned( DCds.DataSet )) and not ( FNoCerrar ) then
DCds.DataSet.Close;
except
end;
inherited;
Action := caFree;
Self := nil;
end;
procedure TFIngDat.SetNoCerrar(const Value: boolean);
begin
FNoCerrar := Value;
end;
procedure TFIngDat.SetPrimeraVez(const Value: boolean);
begin
FPrimeraVez := Value;
end;
procedure TFIngDat.CdsAfterPost(DataSet: TDataSet);
begin
AplicarCambios( DataSet );
end;
procedure TFIngDat.AplicarCambios( DataSet: TDataSet );
begin
TClientDataSet( DataSet ).ApplyUpdates( -1 );
end;
procedure TFIngDat.CdsAfterDelete(DataSet: TDataSet);
begin
AplicarCambios( DataSet );
end;
procedure TFIngDat.Reconciliar(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
begin
Action := HandleReconcileError(DataSet, UpdateKind, E);
end;
end.
|
unit Swift_UViewer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, VirtualTrees, SWIFT_UMsgFormat, SWIFT_UUtils;
const
cSequenceTags: array [0..10] of string = (
'15A', '15B', '15C', '15D', '15E', '15F', '15G', '15H', '15I', '16R', '16S');
type
TSwiftData = packed record
TagName, TagValue: String;
Editable, MultiLine: Boolean;
LineCount: Integer;
end;
PSwiftData = ^TSwiftData;
TfSwiftView = class(TFrame)
pnlTop: TPanel;
pnlView: TPanel;
pnlEditor: TPanel;
lbl1: TLabel;
edtSender: TEdit;
lbl2: TLabel;
edtReciever: TEdit;
VST: TVirtualStringTree;
lblTagName: TLabel;
edtTagValue: TEdit;
mmoTagValue: TMemo;
procedure VSTChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
procedure VSTInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure VSTMeasureItem(Sender: TBaseVirtualTree; TargetCanvas: TCanvas;
Node: PVirtualNode; var NodeHeight: Integer);
procedure VSTGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure VSTPaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
procedure VSTBeforeCellPaint(Sender: TBaseVirtualTree;
TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect);
procedure mmoTagValueChange(Sender: TObject);
private
{ Swift сообщение }
FSwiftMessage: TSwiftMessage;
FMsgText: string;
FMsgType: Integer;
{ Getters and Setters }
procedure SetMsgText(aValue: string);
function GetMsgText: string;
procedure UpdateFromNode;
procedure FillData;
procedure BuildTree(aBlock: TSwiftBlock4);
function GetNodeData(const ANode: PVirtualNode): PSwiftData;
public
procedure Init;
property MsgText: string read GetMsgText write SetMsgText;
property MsgType: Integer read FMsgType write FMsgType;
end;
implementation
uses
Math, RegularExpressions, StrUtils;
{$R *.dfm}
function TfSwiftView.GetNodeData(const ANode: PVirtualNode): PSwiftData;
begin
// Для более короткого доступа к данным узла дерева
Result := VST.GetNodeData(Anode);
end;
procedure TfSwiftView.Init;
begin
VST.NodeDataSize := SizeOf(TSwiftData);
end;
procedure TfSwiftView.mmoTagValueChange(Sender: TObject);
var
Data: PSwiftData;
SwiftField: TSwiftField;
IsValid: Boolean;
begin
Data := GetNodeData(VST.FocusedNode);
if SameText(TCustomEdit(Sender).Text, Data.TagValue) then Exit;
// Валидация
IsValid := False;
{ TODO: поиск поля не работает!!! }
SwiftField := FSwiftMessage.Block4.GetFieldBy(Data.TagName);
if Assigned(SwiftField) then begin
SwiftField.Tag.Value := TCustomEdit(Sender).Text;
IsValid := SwiftField.Valid;
end;
if IsValid then begin
TEdit(Sender).Color := clWhite;
Data^.TagValue := TCustomEdit(Sender).Text;
VST.Refresh;
end else begin
TEdit(Sender).Color := clYellow;
end;
end;
procedure TfSwiftView.VSTBeforeCellPaint(Sender: TBaseVirtualTree;
TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect);
var
BgColor: TColor;
begin
if GetNodeData(Node).Editable then
BgColor := clWhite
else
BgColor := clBtnFace;
with TargetCanvas do begin
Brush.Color := BgColor;
FillRect(CellRect);
end;
end;
procedure TfSwiftView.VSTChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
begin
// при изменении узла дерева
UpdateFromNode;
end;
procedure TfSwiftView.VSTGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TSwiftData);
end;
procedure TfSwiftView.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
var
sText: string;
begin
if Column = 0 then
CellText := GetNodeData(Node).TagName
else if Column = 1 then
CellText := GetNodeData(Node).TagValue
end;
procedure TfSwiftView.VSTInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
begin
if GetNodeData(Node).MultiLine then
Include(InitialStates, ivsMultiline)
else begin
Exclude(InitialStates, ivsMultiline);
// НЕ ЗАБЫВАЙТЕ ВЫПОЛНЯТЬ ЭТО:
Node.States := Node.States - [vsMultiline];
// Это выключит многострочность для узлов, где она раньше была.
end;
end;
procedure TfSwiftView.VSTMeasureItem(Sender: TBaseVirtualTree;
TargetCanvas: TCanvas; Node: PVirtualNode; var NodeHeight: Integer);
begin
if GetNodeData(Node).MultiLine then begin
NodeHeight := VST.ComputeNodeHeight(TargetCanvas, Node, 0) + 4;
NodeHeight := GetNodeData(Node).LineCount * 18;
NodeHeight := Max(18, NodeHeight);
end else NodeHeight := 18;
end;
procedure TfSwiftView.VSTPaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
var
FontColor: TColor;
begin
// if not GetNodeData(Node).Editable then
// FontColor := clBlack
// else
// FontColor := clBlack;
// if (vsSelected in Node.States) and (Sender.Focused) then
// FontColor := clHighlightText;
// TargetCanvas.Font.Color := FontColor;
end;
function TfSwiftView.GetMsgText: string;
begin
// TODO Строим текст по дереву
Result := FMsgText;
end;
procedure TfSwiftView.FillData;
begin
// Отправитель и Получатель
edtSender.Text := FSwiftMessage.Block1.Sender;
edtReciever.Text := FSwiftMessage.Block2.Reciever;
// строим дерево полей
BuildTree(FSwiftMessage.Block4);
VST.FullExpand(nil);
end;
procedure TfSwiftView.BuildTree(aBlock: TSwiftBlock4);
var
eTmpTag: TSwiftTag;
I: Integer;
eNode, eSeqNode, eSubNode, eRoot: PVirtualNode;
eIsEditable: Boolean;
eData: PSwiftData;
function IsEditable(aName: string): Boolean;
var
I: Integer;
begin
Result := False;
if Length(cEditableFields) = 0 then Exit;
for I := 0 to High(cEditableFields) do
if TRegEx.IsMatch(aName, cEditableFields[ I ]) then begin
Result := True;
Break;
end;
end;
function GetLineCount(aText: string): Integer;
var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.Text := aText;
Result := SL.Count;
finally
SL.Free;
end;
end;
begin
with VST do begin
NodeDataSize := SizeOf(TSwiftData);
aBlock.RecreateTags;
eRoot := RootNode;
eNode := nil;
eSeqNode := nil;
eSubNode := nil;
for I := 0 to aBlock.Count - 1 do begin
eTmpTag := aBlock.Tags[ I ];
// последовательность в корень
if MatchText(eTmpTag.Name, cSequenceTags) then begin
// начало последовательности
if (MatchText(eTmpTag.Name, ['15A', '15B', '16R'])) then begin
if (eSeqNode <> nil) then begin
eSubNode := AddChild(eSeqNode);
eNode := eSubNode;
end else begin
eSeqNode := AddChild(eRoot);
eNode := eSeqNode;
end;
end;
// конец последовательности
if (SameText(eTmpTag.Name, '16S')) then begin
if (eSubNode <> nil) then begin
// добавим
eNode := AddChild(eSubNode);
eSubNode := nil;
end else if (eSeqNode <> nil) then begin
eNode := AddChild(eSeqNode);
eSeqNode := nil;
end;
end;
end else begin
if (eSubNode <> nil) then begin
// добавим
eNode := AddChild(eSubNode);
end else if (eSeqNode <> nil) then begin
eNode := AddChild(eSeqNode);
end;
end;
eData := GetNodeData(eNode);
eData^.TagName := eTmpTag.Name;
eData^.TagValue := eTmpTag.Value;
eData^.Editable := IsEditable(eTmpTag.FullName);
eData^.MultiLine := Pos(#$D#$A, eTmpTag.Value) > 0;
eData^.LineCount := GetLineCount(eTmpTag.Value);
end;
end;
end;
procedure TfSwiftView.SetMsgText(aValue: string);
begin
FMsgText := aValue;
if FMsgText > '' then begin
FSwiftMessage := TSwift.Load(FMsgType, FMsgText);
if Assigned(FSwiftMessage) then
FillData;
end;
end;
procedure TfSwiftView.UpdateFromNode;
var
Data: PSwiftData;
begin
with VST do
if FocusedNode = nil then begin
PnlEditor.Visible := False;
end else begin
Data := GetNodeData(FocusedNode);
PnlEditor.Visible := True;
lblTagName.Caption := Data.TagName;
lblTagName.Enabled := True;
if Data.MultiLine then begin
mmoTagValue.Text := Data.TagValue;
mmoTagValue.Visible := True;
edtTagValue.Visible := False;
mmoTagValue.Enabled := Data.Editable;
end else begin
edtTagValue.Text := Data.TagValue;
mmoTagValue.Visible := False;
edtTagValue.Visible := True;
edtTagValue.Enabled := Data.Editable;
end;
end;
end;
end.
|
unit JukeBox;
interface
uses
VoyagerInterfaces, Classes, Controls;
type
IPlayList =
interface
function SelectedFile : string;
procedure SelectNextFile;
procedure Reset;
procedure JumpToFile( index : integer );
procedure AddFile ( filename : string );
procedure AddDir ( path : string );
procedure DelFile ( index : integer );
end;
type
TJukeBox =
class( TInterfacedObject, IMetaURLHandler, IURLHandler )
public
destructor Destroy; override;
// IMetaURLHandler
private
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL( URL : TURL ) : THandlingAbility;
function Instantiate : IURLHandler;
// IURLHandler
private
function HandleURL( URL : TURL ) : TURLHandlingResult;
function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler( URLHandler : IMasterURLHandler );
private
fMasterURLHandler : IMasterURLHandler;
fPlayList : IPlayList;
end;
const
tidMetaHandler_JukeBox = 'JukeBox';
const
evnGetPlaylist = 5600;
implementation
uses
MP3Handler, Events, URLParser, SysUtils, MPlayer;
destructor TJukeBox.Destroy;
begin
inherited;
end;
function TJukeBox.getName : string;
begin
result := tidMetaHandler_JukeBox;
end;
function TJukeBox.getOptions : TURLHandlerOptions;
begin
result := [hopCacheable, hopNonVisual];
end;
function TJukeBox.getCanHandleURL( URL : TURL ) : THandlingAbility;
begin
result := 0;
end;
function TJukeBox.Instantiate : IURLHandler;
begin
result := self;
end;
function TJukeBox.HandleURL( URL : TURL ) : TURLHandlingResult;
var
action : string;
begin
action := URLParser.GetURLAction( URL );
if action = htmlAction_Play
then
begin
fMasterURLHandler.HandleURL( '?frame_Id=MP3Handler&frame_Action=Play&MediaId=MainSoundTrack&MediaURL=' + fPlayList.SelectedFile );
result := urlHandled;
end
else
if action = htmlAction_Stop
then
begin
fMasterURLHandler.HandleURL( '?frame_Id=MP3Handler&frame_Action=Stop&MediaId=MainSoundTrack' );
result := urlHandled;
end
else result := urlNotHandled;
end;
function TJukeBox.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
var
MediaStatusInfo : TMediaStatusInfo absolute info;
begin
case EventId of
evnMediaStatusChanged :
if (MediaStatusInfo.MediaId = uppercase('MainSoundTrack')) and (MediaStatusInfo.Status = nvSuccessful)
then
begin
fPlayList.SelectNextFile;
fMasterURLHandler.HandleURL( '?frame_Id=MP3Handler&frame_Action=Play&MediaId=MainSoundTrack&MediaURL=' + fPlayList.SelectedFile );
result := evnHandled;
end
else result := evnNotHandled;
else
result := evnNotHandled;
end;
end;
function TJukeBox.getControl : TControl;
begin
result := nil;
end;
procedure TJukeBox.setMasterURLHandler( URLHandler : IMasterURLHandler );
begin
fMasterURLHandler := URLHandler;
fMasterURLHandler.HandleEvent( evnGetPlayList, fPlayList );
end;
end.
|
unit Events;
interface
uses
VoyagerInterfaces;
const
evnNothing = 0;
evnCriticalError = 1;
evnTaskStart = 2;
evnTaskProgress = 3;
evnTaskEnd = 4;
evnStop = 5;
evnPause = 6;
evnResume = 7;
evnHandlerExposed = 8;
evnHandlerUnexposed = 9;
evnAnswerPrivateCache = 10;
evnAnswerClassesPath = 11;
evnSystemBusy = 12;
evnSystemIdle = 14;
evnGoBack = 15;
evnGoForward = 16;
evnRefresh = 17;
evnStopNavigation = 18;
evnAnswerPendingMail = 19;
evnShutDown = 20;
evnKeyCommand = 21;
evnGlassBuildings = 22;
evnAnimateBuildings = 23;
evnShowCars = 24;
evnShowPlanes = 25;
evnTranspOverlays = 26;
evnSoundsEnabled = 27;
evnSetSoundVolume = 28;
evnHideShowFacility = 29;
evnShowAllFacilities = 30;
evnHideAllFacilities = 31;
evnLanguageSet = 32;
const
keyCmdESC = 1;
keyCmdKeyN = 2;
keyCmdKeyS = 3;
keyCmdKeyW = 4;
keyCmdKeyE = 5;
keyCmdKeyNE = 6;
keyCmdKeySE = 7;
keyCmdKeySW = 8;
keyCmdKeyNW = 9;
keyCmdFullScreen = 10;
keyHidden = 77;
keySetSeason0 = 12;
keySetSeason1 = 13;
keySetSeason2 = 14;
keySetSeason3 = 15;
keyGMClient = 20;
type
TEvnTaskStartInfo =
record
Carrier : IURLHandler;
TaskName : string;
TaskDesc : string;
cancel : boolean;
end;
TEvnTaskProgressInfo =
record
Carrier : IURLHandler;
TaskName : string;
TaskDesc : string;
Progress : integer;
end;
TEvnTaskEndInfo =
record
Carrier : IURLHandler;
TaskName : string;
end;
type
THideShowFacilityData =
record
show : boolean;
facid : byte;
end;
implementation
end.
|
unit CriminalViewer;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
FramedButton, GradientBox, StdCtrls, ExtCtrls, PercentEdit, MarqueeCtrl,
VoyagerInterfaces, VoyagerServerInterfaces,
ColoredGauge, CrimeMainViewer, InternationalizerComponent;
const
SkillSlots = 12;
type
TCriminalView = class(TForm)
lbName: TLabel;
GradientBox1: TGradientBox;
btFire: TFramedButton;
btTrain: TFramedButton;
btMove: TFramedButton;
btHistory: TFramedButton;
SalaryBar: TPercentEdit;
lbSalary: TLabel;
SalaryValue: TLabel;
lbRole: TLabel;
cbRole: TComboBox;
Panel3: TPanel;
Panel4: TPanel;
StatusMarquee: TMarquee;
Image: TImage;
SkillName5: TLabel;
SkillBar5: TColorGauge;
SkillVal5: TLabel;
SkillName6: TLabel;
SkillVal6: TLabel;
SkillBar6: TColorGauge;
SkillVal7: TLabel;
SkillBar7: TColorGauge;
SkillName8: TLabel;
SkillVal8: TLabel;
SkillBar8: TColorGauge;
SkillName1: TLabel;
SkillVal1: TLabel;
SkillBar1: TColorGauge;
SkillName2: TLabel;
SkillVal2: TLabel;
SkillBar2: TColorGauge;
SkillName3: TLabel;
SkillVal3: TLabel;
SkillBar3: TColorGauge;
CloseBtn: TFramedButton;
SkillName9: TLabel;
SkillVal9: TLabel;
SkillBar9: TColorGauge;
SkillName10: TLabel;
SkillBar10: TColorGauge;
SkillVal10: TLabel;
SkillName11: TLabel;
SkillVal11: TLabel;
SkillBar11: TColorGauge;
SkillName12: TLabel;
SkillVal12: TLabel;
SkillBar12: TColorGauge;
SkillName7: TLabel;
SkillName4: TLabel;
SkillVal4: TLabel;
SkillBar4: TColorGauge;
StatusTimer: TTimer;
InternationalizerComponent1: TInternationalizerComponent;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CloseBtnClick(Sender: TObject);
procedure btFireClick(Sender: TObject);
procedure cbRoleChange(Sender: TObject);
procedure btHistoryClick(Sender: TObject);
procedure btTrainClick(Sender: TObject);
procedure SalaryBarChange(Sender: TObject);
procedure StatusTimerTimer(Sender: TObject);
private
SkillNames : array[0..SkillSlots - 1] of TLabel;
SkillValues : array[0..SkillSlots - 1] of TLabel;
SkillBars : array[0..SkillSlots - 1] of TColorGauge;
private
fClientView : IClientView;
fMasterURLHandler : IMasterURLHandler;
fIllSystem : olevariant;
fProperties : TStringList;
fLeader : TStringList;
fTeam : TStringList;
fTeamMember : boolean;
fOnTeamModified : TOnTeamModified;
fMainView : TCrimeMainView;
fSourceImg : TBitmap;
fBltScan : integer;
fLastPict : string;
private
procedure SetProperties( Prop : TStringList );
public
property ClientView : IClientView write fClientView;
property MasterURLHandler : IMasterURLHandler write fMasterURLHandler;
property IllSystem : olevariant write fIllSystem;
property Properties : TStringList write SetProperties;
property Leader : TStringList write fLeader;
property Team : TStringList write fTeam;
property TeamMember : boolean read fTeamMember write fTeamMember;
property OnTeamModified : TOnTeamModified write fOnTeamModified;
property MainView : TCrimeMainView write fMainView;
private
procedure threadedFire( const parms : array of const );
procedure syncFire( const parms : array of const );
end;
var
CriminalView: TCriminalView;
implementation
{$R *.DFM}
uses
MetaCrime, ClassStorage, Events, JPGtoBMP, Threads, HistoryDialog, CrimeTrainingDialog, CrimeProtocol;
procedure TCriminalView.SetProperties( Prop : TStringList );
var
i : integer;
MA : TMetaAttribute;
cache : string;
State : TCriminalState;
begin
try
fProperties.Free;
fProperties := TStringList.Create;
fProperties.Assign( Prop );
for i := 0 to pred(TheClassStorage.ClassCount['Attribute']) do
begin
MA := TMetaAttribute(TheClassStorage.ClassByIdx['Attribute', i]);
if i < SkillSlots
then
begin
SkillNames[i].Caption := MA.Name;
SkillNames[i].Hint := MA.Desc;
SkillValues[i].Caption := Prop.Values[IntToStr(i)] + '%';
SkillBars[i].Position := StrToInt(Prop.Values[IntToStr(i)]);
SkillNames[i].Visible := true;
SkillValues[i].Visible := true;
SkillBars[i].Visible := true;
end;
end;
for i := TheClassStorage.ClassCount['Attribute'] to pred(SkillSlots) do
begin
SkillNames[i].Visible := false;
SkillValues[i].Visible := false;
SkillBars[i].Visible := false;
end;
cbRole.Items.Clear;
for i := 0 to pred(TheClassStorage.ClassCount['Role']) do
begin
cbRole.Items.Add( TMetaRole(TheClassStorage.ClassByIdx['Role', i]).Name );
end;
cbRole.ItemIndex := cbRole.Items.IndexOf( fProperties.Values['Role'] );
//cbRole.ItemIndex := cbRole.Items.IndexOf(fTeam.Values['Role'+ IntToStr(fTeam.IndexOf())]);
{
for i := 1 to 8 do
begin
cbRole.Items.Clear;
end;
}
fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, cache );
if fProperties.Values['Picture'] <> fLastPict
then
try
Image.Picture.Bitmap := TBitmap.Create;
Image.Picture.Bitmap.PixelFormat := pf24bit;
Image.Picture.Bitmap.Width := Image.Width;
Image.Picture.Bitmap.Height := Image.Height;
with Image.Picture.Bitmap.Canvas do
begin
Pen.Style := psClear;
Brush.Color := $00004080;
Rectangle( 0, 0, Image.Picture.Bitmap.Width + 1, Image.Picture.Bitmap.Height + 1 );
end;
TVFilter( Image.Picture.Bitmap, $00243940 );
fSourceImg.Free;
fSourceImg := TBitmap.Create;
fSourceImg.PixelFormat := pf24bit;
fSourceImg.Width := Image.Width;
fSourceImg.Height := Image.Height;
LoadJPGToBMP( cache + tidPath_IBImages + fProperties.Values['Picture'] + '.jpg', fSourceImg );
TVFilter( fSourceImg, $00243940 );
fBltScan := 1;
fLastPict := fProperties.Values['Picture'];
except
end;
State := TCriminalState(StrToInt(fProperties.Values['State']));
StatusMarquee.ForeColor := StateColors[State];
case State of
tcsInTeamTraining :
StatusMarquee.Caption := StateLabels[State] + ': ' + fProperties.Values['TrainingClass'];
else
StatusMarquee.Caption := StateLabels[State];
end;
SalaryValue.Caption := fProperties.Values['SalaryPerc'] + '% ($' + IntToStr(round(StrToFloat(fProperties.Values['Salary']))) + '/h)';
SalaryBar.Value := StrToInt(fProperties.Values['SalaryPerc']);
lbName.Caption := fProperties.Values['Name'];
btTrain.Enabled := State in [tcsNoState, tcsOnTheMarket, tcsOnTheMarketHidden, tcsInTeamStandBy];
SalaryBar.Visible := fTeamMember;
SalaryValue.Visible := fTeamMember;
lbSalary.Visible := fTeamMember;
btFire.Visible := fTeamMember;
btTrain.Visible := fTeamMember;
btMove.Visible := fTeamMember;
//btHistory.Visible := fTeamMember;
cbRole.Visible := fTeamMember;
lbRole.Visible := fTeamMember;
except
end;
end;
procedure TCriminalView.FormCreate(Sender: TObject);
begin
SkillNames[0] := SkillName1;
SkillNames[1] := SkillName2;
SkillNames[2] := SkillName3;
SkillNames[3] := SkillName4;
SkillNames[4] := SkillName5;
SkillNames[5] := SkillName6;
SkillNames[6] := SkillName7;
SkillNames[7] := SkillName8;
SkillNames[8] := SkillName9;
SkillNames[9] := SkillName10;
SkillNames[10] := SkillName11;
SkillNames[11] := SkillName12;
SkillValues[0] := SkillVal1;
SkillValues[1] := SkillVal2;
SkillValues[2] := SkillVal3;
SkillValues[3] := SkillVal4;
SkillValues[4] := SkillVal5;
SkillValues[5] := SkillVal6;
SkillValues[6] := SkillVal7;
SkillValues[7] := SkillVal8;
SkillValues[8] := SkillVal9;
SkillValues[9] := SkillVal10;
SkillValues[10] := SkillVal11;
SkillValues[11] := SkillVal12;
SkillBars[0] := SkillBar1;
SkillBars[1] := SkillBar2;
SkillBars[2] := SkillBar3;
SkillBars[3] := SkillBar4;
SkillBars[4] := SkillBar5;
SkillBars[5] := SkillBar6;
SkillBars[6] := SkillBar7;
SkillBars[7] := SkillBar8;
SkillBars[8] := SkillBar9;
SkillBars[9] := SkillBar10;
SkillBars[10] := SkillBar11;
SkillBars[11] := SkillBar12;
end;
procedure TCriminalView.FormShow(Sender: TObject);
begin
Top := 3;
Left := 400;
if fTeam <> nil
then
begin
SalaryBar.MidValue := 100;
end;
end;
procedure TCriminalView.CloseBtnClick(Sender: TObject);
begin
Close;
end;
procedure TCriminalView.btFireClick(Sender: TObject);
begin
Fork( threadedFire, priNormal, [fProperties.Values['Name'], fTeam.Values['Name'], fLeader.Values['Name']] );
end;
procedure TCriminalView.threadedFire( const parms : array of const );
var
name, team, leader : string;
ErrorCode : TErrorCode;
begin
try
name := parms[0].vPChar;
team := parms[1].vPChar;
leader := parms[2].vPChar;
ErrorCode := fIllSystem.RDOFireCriminal( leader, team, name );
Join( syncFire, [name, ErrorCode] );
except
end;
end;
procedure TCriminalView.syncFire( const parms : array of const );
var
name : string absolute parms[0].vPChar;
begin
if assigned(fOnTeamModified)
then fOnTeamModified;
if fProperties.Values['Name'] = name
then Close;
end;
procedure TCriminalView.cbRoleChange(Sender: TObject);
var
ErrorCode : TErrorCode;
begin
try
ErrorCode := fIllSystem.RDOChangeRole( fLeader.Values['Name'], fTeam.Values['Name'], fProperties.Values['Name'], cbRole.Text );
if (ErrorCode = CRIME_NOERROR) and assigned(fOnTeamModified)
then fOnTeamModified;
except
end;
end;
procedure TCriminalView.btHistoryClick(Sender: TObject);
begin
HistoryDlg.Team := fTeam;
HistoryDlg.Leader := fLeader;
HistoryDlg.Criminal := fProperties;
HistoryDlg.IllSystem := fIllSystem;
HistoryDlg.MasterURLHandler := fMasterURLHandler;
HistoryDlg.ClientView := fClientView;
HistoryDlg.ShowModal;
end;
procedure TCriminalView.btTrainClick(Sender: TObject);
begin
CrimeTrainingDlg.Team := fTeam;
CrimeTrainingDlg.Leader := fLeader;
CrimeTrainingDlg.Criminal := fProperties;
CrimeTrainingDlg.IllSystem := fIllSystem;
CrimeTrainingDlg.MasterURLHandler := fMasterURLHandler;
CrimeTrainingDlg.ClientView := fClientView;
if (CrimeTrainingDlg.ShowModal = mrOk) and assigned(fOnTeamModified)
then fOnTeamModified;
end;
procedure TCriminalView.SalaryBarChange(Sender: TObject);
begin
SalaryValue.Caption := IntToStr(SalaryBar.Value) + '%';
end;
procedure TCriminalView.StatusTimerTimer(Sender: TObject);
const
Step = 10;
var
R : TRect;
begin
StatusMarquee.Tick;
if fBltScan > 0
then
if fBltScan + Step <= fSourceImg.Height
then
begin
R := Rect(0, 0, fSourceImg.Width, fBltScan);
Image.Picture.Bitmap.Canvas.CopyRect( R, fSourceImg.Canvas, R );
with Image.Picture.Bitmap.Canvas do
begin
Pen.Color := clGray;
Brush.Color := clGray;
Rectangle( 0, fBltScan - 2, Image.Picture.Bitmap.Width, fBltScan - 1 );
Pen.Color := clSilver;
Brush.Color := clSilver;
Rectangle( 0, fBltScan - 1, Image.Picture.Bitmap.Width, fBltScan );
Pen.Color := clWhite;
Brush.Color := clWhite;
Rectangle( 0, fBltScan, Image.Picture.Bitmap.Width, fBltScan + 1 );
end;
inc( fBltScan, Step );
end
else
begin
R := Rect(0, 0, fSourceImg.Width, fSourceImg.Height);
Image.Picture.Bitmap.Canvas.CopyRect( R, fSourceImg.Canvas, R );
fBltScan := 0;
end;
end;
end.
|
{ Subroutine SST_FLAG_USED_SYMBOL (SYM)
*
* Flag the indicated symbol as used. Also, follow all symbols it eventually
* references and flag them all as used. SYM is the symbol descriptor of the
* top level symbol to follow.
}
module sst_FLAG_USED_SYMBOL;
define sst_flag_used_symbol;
%include 'sst2.ins.pas';
procedure sst_flag_used_symbol ( {flag symbols eventually used from this sym}
in out sym: sst_symbol_t); {descriptor for top symbol to follow}
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
sym_p: sst_symbol_p_t; {scratch pointer to a symbol}
pos: string_hash_pos_t; {position handle into hash table}
name_p: univ_ptr; {unused subroutine argument}
sym_pp: sst_symbol_pp_t; {pointer to hash table user data area}
found: boolean; {TRUE if hash table entry was found}
msg_parm: {references to paramters for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
begin
sym.flags := sym.flags + {flag this symbol as used}
[sst_symflag_used_k];
if {don't process this symbol any further ?}
(sst_symflag_followed_k in sym.flags) or {already did this symbol ?}
(sst_symflag_following_k in sym.flags) {already working on this symbol ?}
then return;
sym.flags := sym.flags + [sst_symflag_following_k]; {now working on this symbol}
case sym.symtype of {what kind of symbol is this ?}
{
*************************************
*
* Symbol is a constant.
}
sst_symtype_const_k: begin
sst_flag_used_exp (sym.const_exp_p^); {declare nested symbols in expression}
end;
{
*************************************
*
* Symbol is the value of an enumerated type.
}
sst_symtype_enum_k: begin
sst_flag_used_dtype (sym.enum_dtype_p^); {make sure parent data type is used}
end;
{
*************************************
*
* Symbol is a data type.
}
sst_symtype_dtype_k: begin
sst_flag_used_dtype (sym.dtype_dtype_p^); {declare nested symbols in dtype}
end; {end of symbol is data type case}
{
*************************************
*
* Symbol is a field of a record.
}
sst_symtype_field_k: begin
sst_flag_used_dtype (sym.field_parent_p^); {flag symbols used by whole record}
sst_flag_used_dtype (sym.field_dtype_p^); {flag symbols used by this field}
end;
{
*************************************
*
* Symbol is a variable.
}
sst_symtype_var_k: begin
if sym.var_com_p <> nil then begin {variable is in a common block ?}
if {not currently working on the common block ?}
(not (sst_symflag_following_k in sym.var_com_p^.flags))
then begin
sym.flags := sym.flags - [sst_symflag_following_k]; {not working on this sym}
sst_flag_used_symbol (sym.var_com_p^); {process the common block}
return;
end;
end; {done handling variable is in common block}
sst_flag_used_dtype (sym.var_dtype_p^); {declare nested symbols in data type}
if sym.var_val_p <> nil then begin {initial value expression exists ?}
sst_flag_used_exp (sym.var_val_p^); {flag symbols in initial value exp as used}
end;
end;
{
*************************************
*
* Symbol is an abbreviation.
}
sst_symtype_abbrev_k: begin
sst_flag_used_var (sym.abbrev_var_p^);
end;
{
*************************************
*
* Symbol is a routine name.
}
sst_symtype_proc_k: begin
sst_flag_used_rout (sym.proc); {declare nested symbols in routine}
end;
{
*************************************
*
* Symbol is a common block name.
}
sst_symtype_com_k: begin
sym_p := sym.com_first_p; {init current symbol to first in com block}
while sym_p <> nil do begin {once for each symbol in common block}
sst_flag_used_symbol (sym_p^); {flag this variable as used}
sym_p := sym_p^.var_next_p; {advance to next variable in common block}
end; {back and process this new variable}
end;
{
*************************************
*
* Symbol is a module name.
}
sst_symtype_module_k: begin
string_hash_pos_first (sym.module_scope_p^.hash_h, pos, found); {get starting pos}
while found do begin {once for each symbol in module's scope}
string_hash_ent_atpos (pos, name_p, sym_pp); {get pointer to user data area}
sym_p := sym_pp^; {get pointer to symbol descriptor}
if
(sst_symflag_global_k in sym_p^.flags) and {symbol is globally known ?}
(sst_symflag_def_k in sym_p^.flags) and {actually defined ?}
(not (sst_symflag_extern_k in sym_p^.flags)) {comes from this module ?}
then begin
sst_flag_used_symbol (sym_p^); {flag symbol as used}
end;
string_hash_pos_next (pos, found); {advance to next symbol in this scope}
end;
end;
{
*************************************
*
* Symbol types that require no special processing.
}
sst_symtype_prog_k: ;
sst_symtype_label_k: ;
otherwise
sys_msg_parm_int (msg_parm[1], ord(sym.symtype));
sys_message_bomb ('sst', 'symbol_type_unknown', msg_parm, 1);
end; {end of symbol type cases}
sym.flags := sym.flags + {all done following this symbol}
[sst_symflag_followed_k];
sym.flags := sym.flags - {this symbol no longer in process}
[sst_symflag_following_k, sst_symflag_following_dt_k];
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.Controls.Presentation,
FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Edit, FMX.Layouts,
FMX.ListBox;
type
TForm1 = class(TForm)
Log: TMemo;
Edit1: TEdit;
Layout1: TLayout;
btnGetInfo: TButton;
chkbxFormat: TCheckBox;
Layout2: TLayout;
Label1: TLabel;
lblFileSystemSize: TLabel;
Label2: TLabel;
lblFileSystemFreeSize: TLabel;
ComboBox1: TComboBox;
procedure btnGetInfoClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
private
List: TStringList;
procedure AddList(Name, Path: string);
{ Private declarations }
public
{ Public declarations }
end;
{ Class helper iOS and OSx }
TMacHelper = class
protected
class function GetFileSytemSizeByKey(sKey: string): Int64;
public
class function GetFileSystemSize: Int64;
class function GetFileSystemFreeSize: Int64;
end;
TByptesHelper = class
public
class function FormatBytesToStr(Bytes: Int64): string;
end;
var
Form1: TForm1;
implementation
uses
Macapi.ObjectiveC
{$IFDEF IOS}
, iOSapi.Foundation
{$ELSE}
, Macapi.Foundation
{$ENDIF IOS}
, System.Math
, System.IOUtils;
{$R *.fmx}
procedure TForm1.FormCreate(Sender: TObject);
begin
List := TStringList.Create;
ComboBox1.Items.Clear;
Self.AddList('/', '/');
Self.AddList('GetTempPath', TPath.GetTempPath);
Self.AddList('GetHomePath', TPath.GetHomePath);
Self.AddList('GetDocumentsPath', TPath.GetDocumentsPath);
Self.AddList('GetSharedDocumentsPath', TPath.GetSharedDocumentsPath);
Self.AddList('GetLibraryPath', TPath.GetLibraryPath);
Self.AddList('GetCachePath', TPath.GetCachePath);
Self.AddList('GetPublicPath', TPath.GetPublicPath);
Self.AddList('GetPicturesPath', TPath.GetPicturesPath);
Self.AddList('GetSharedPicturesPath', TPath.GetSharedPicturesPath);
Self.AddList('GetCameraPath', TPath.GetCameraPath);
Self.AddList('GetSharedCameraPath', TPath.GetSharedCameraPath);
Self.AddList('GetMusicPath', TPath.GetMusicPath);
Self.AddList('GetSharedMusicPath', TPath.GetSharedMusicPath);
Self.AddList('GetMoviesPath', TPath.GetMoviesPath);
Self.AddList('GetSharedMoviesPath', TPath.GetSharedMoviesPath);
Self.AddList('GetAlarmsPath', TPath.GetAlarmsPath);
Self.AddList('GetSharedAlarmsPath', TPath.GetSharedAlarmsPath);
Self.AddList('GetDownloadsPath', TPath.GetDownloadsPath);
Self.AddList('GetSharedDownloadsPath', TPath.GetSharedDownloadsPath);
Self.AddList('GetRingtonesPath', TPath.GetRingtonesPath);
Self.AddList('GetSharedRingtonesPath', TPath.GetSharedRingtonesPath);
ComboBox1.ItemIndex := 0;
end;
procedure TForm1.AddList(Name, Path: string);
begin
ComboBox1.Items.Add(Name);
List.Add(Path);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeAndNil(List);
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
Edit1.Text := List[ComboBox1.ItemIndex];
end;
procedure TForm1.btnGetInfoClick(Sender: TObject);
var
iSize: Int64;
begin
Log.Lines.Clear;
iSize := TMacHelper.GetFileSystemSize;
if chkbxFormat.IsChecked then
lblFileSystemSize.Text := TByptesHelper.FormatBytesToStr(iSize)
else
lblFileSystemSize.Text := iSize.ToString;
iSize := TMacHelper.GetFileSystemFreeSize;
if chkbxFormat.IsChecked then
lblFileSystemFreeSize.Text := TByptesHelper.FormatBytesToStr(iSize)
else
lblFileSystemFreeSize.Text := iSize.ToString;
end;
{ TMacHelper }
class function TMacHelper.GetFileSystemFreeSize: Int64;
begin
Result := Self.GetFileSytemSizeByKey('NSFileSystemFreeSize')
end;
class function TMacHelper.GetFileSystemSize: Int64;
begin
Result := Self.GetFileSytemSizeByKey('NSFileSystemSize')
end;
class function TMacHelper.GetFileSytemSizeByKey(sKey: string): Int64;
var
Dict: NSDictionary;
P: Pointer;
FolderName: string;
const
_FolderName = '/';
_FoundationFwk: string = '/System/Library/Frameworks/Foundation.framework/Foundation'; //unit iOSapi.Foundation;
begin
Result := 0;
FolderName := Form1.Edit1.Text;
Form1.Log.Lines.Add(FolderName);
Dict := TNSFileManager.Wrap(TNSFileManager.OCClass.defaultManager).attributesOfFileSystemForPath(NSStr(FolderName), nil);
if Dict = nil then
Exit;
P := Dict.objectForKey((CocoaNSStringConst(_FoundationFwk, sKey) as ILocalObject).GetObjectID);
if Assigned(P) then
Result := TNSNumber.Wrap(P).unsignedLongLongValue;
end;
{ TByptesHelper }
class function TByptesHelper.FormatBytesToStr(Bytes: Int64): string;
const
Description: Array [0..8] of string = ('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
Kilo = 1000;
var
i: Integer;
iValue: Extended;
begin
i := 0;
while Bytes > Power(Kilo, i + 1) do
Inc(i);
Result := FormatFloat('###0.##', Bytes / IntPower(Kilo, i)) + ' ' + Description[i];
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clDnsQuery;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes,
{$ELSE}
System.Classes,
{$ENDIF}
clDnsMessage, clUdpClient, clSocketUtils, clIpAddress;
type
TclHostInfo = class
private
FIPAddress: string;
FName: string;
public
constructor Create(const AIPAddress, AName: string);
property Name: string read FName;
property IPAddress: string read FIPAddress;
end;
TclHostList = class
private
FList: TList;
function GetCount: Integer;
function GetItem(Index: Integer): TclHostInfo;
protected
procedure Clear;
procedure Add(AItem: TclHostInfo);
procedure Insert(Index: Integer; AItem: TclHostInfo);
public
constructor Create;
destructor Destroy; override;
function ItemByName(const AName: string): TclHostInfo;
property Items[Index: Integer]: TclHostInfo read GetItem; default;
property Count: Integer read GetCount;
end;
TclMailServerInfo = class(TclHostInfo)
private
FPreference: Integer;
public
constructor Create(const AIPAddress, AName: string; APreference: Integer);
property Preference: Integer read FPreference;
end;
TclMailServerList = class(TclHostList)
private
function GetItem(Index: Integer): TclMailServerInfo;
procedure AddSorted(AItem: TclMailServerInfo);
public
property Items[Index: Integer]: TclMailServerInfo read GetItem; default;
end;
TclDnsQuery = class(TclUdpClient)
private
FQuery: TclDnsMessage;
FResponse: TclDnsMessage;
FMailServers: TclMailServerList;
FNameServers: TStrings;
FHosts: TclHostList;
FIsRecursiveDesired: Boolean;
FAliases: TStrings;
FMaxRecursiveQueries: Integer;
FUseRecursiveQueries: Boolean;
FAutodetectServer: Boolean;
FHostsIPv6: TclHostList;
FRootNameServers: TStrings;
procedure FillAInfo(ARecordList: TclDnsRecordList);
procedure FillMXInfo;
procedure FillNSInfo(ARecordList: TclDnsRecordList);
function FillHostInfo: TclHostInfo;
procedure FillAliasInfo;
function ExtractTxtInfo: string;
function GetPreferredMX: TclMailServerInfo;
function GetEmailDomain(const AEmail: string): string;
function GetArpaIPAddress(const AIP: string): string;
function GetArpaIPv6Address(Addr: TclIPAddress6): string;
procedure InternalResolveIP(const AHost, ADns: string; AQuery, AResponse: TclDnsMessage; IsIPv6: Boolean);
procedure InternalResolve(AQuery, AResponse: TclDnsMessage);
procedure ResolveRecursive(AQuery, AResponse: TclDnsMessage; ANestLevel: Integer);
function ExtractPrimaryName(ARecordList: TclDnsRecordList; const Alias: string): string;
procedure SetRootNameServers(const Value: TStrings);
protected
function GetDefaultPort: Integer; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class procedure GetDnsList(AList: TStrings);
procedure Clear;
procedure Resolve; overload;
procedure Resolve(AQuery, AResponse: TclDnsMessage); overload;
function ResolveMX(const AEmail: string): TclMailServerInfo;
function ResolveIP(const AHost: string): TclHostInfo;
function ResolveIPv6(const AHost: string): TclHostInfo;
function ResolveHost(const AIPAddress: string): TclHostInfo;
function ResolveNS(const AHost: string): string;
function ResolveTXT(const AHost: string): string;
function ResolveCName(const AHost: string): string;
property Query: TclDnsMessage read FQuery;
property Response: TclDnsMessage read FResponse;
property MailServers: TclMailServerList read FMailServers;
property Hosts: TclHostList read FHosts;
property HostsIPv6: TclHostList read FHostsIPv6;
property NameServers: TStrings read FNameServers;
property Aliases: TStrings read FAliases;
published
property Port default DefaultDnsPort;
property DatagramSize default 512;
property IsRecursiveDesired: Boolean read FIsRecursiveDesired write FIsRecursiveDesired default True;
property UseRecursiveQueries: Boolean read FUseRecursiveQueries write FUseRecursiveQueries default False;
property MaxRecursiveQueries: Integer read FMaxRecursiveQueries write FMaxRecursiveQueries default 4;
property AutodetectServer: Boolean read FAutodetectServer write FAutodetectServer default True;
property RootNameServers: TStrings read FRootNameServers write SetRootNameServers;
end;
{$IFDEF DEMO}
{$IFNDEF IDEDEMO}
var
IsDnsDemoDisplayed: Boolean = False;
{$ENDIF}
{$ENDIF}
implementation
uses
{$IFNDEF DELPHIXE2}
Windows, SysUtils, Registry{$IFDEF DEMO}, Forms{$ENDIF},
{$ELSE}
Winapi.Windows, System.SysUtils, System.Win.Registry{$IFDEF DEMO}, Vcl.Forms{$ENDIF},
{$ENDIF}
clSocket, clUtils{$IFDEF LOGGER}, clLogger{$ENDIF};
{ TclDnsQuery }
procedure TclDnsQuery.Clear;
begin
Query.Clear();
Response.Clear();
Hosts.Clear();
HostsIPv6.Clear();
MailServers.Clear();
NameServers.Clear();
Aliases.Clear();
end;
constructor TclDnsQuery.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FRootNameServers := TStringList.Create();
FQuery := TclDnsMessage.Create();
FResponse := TclDnsMessage.Create();
FHosts := TclHostList.Create();
FHostsIPv6 := TclHostList.Create();
FMailServers := TclMailServerList.Create();
FNameServers := TStringList.Create();
FAliases := TStringList.Create();
IsRecursiveDesired := True;
MaxRecursiveQueries := 4;
DatagramSize := 512;
AutodetectServer := True;
end;
destructor TclDnsQuery.Destroy;
begin
FAliases.Free();
FNameServers.Free();
FMailServers.Free();
FHostsIPv6.Free();
FHosts.Free();
FResponse.Free();
FQuery.Free();
FRootNameServers.Free();
inherited Destroy();
end;
procedure TclDnsQuery.Resolve;
begin
Resolve(Query, Response);
end;
procedure TclDnsQuery.SetRootNameServers(const Value: TStrings);
begin
FRootNameServers.Assign(Value);
end;
procedure TclDnsQuery.Resolve(AQuery, AResponse: TclDnsMessage);
var
i: Integer;
oldServer: string;
begin
if AutodetectServer and (Server = '') and (RootNameServers.Count = 0) then
begin
GetDnsList(RootNameServers);
end;
if (Server = '') and (RootNameServers.Count > 0) then
begin
for i := 0 to RootNameServers.Count - 1 do
begin
Server := RootNameServers[i];
try
ResolveRecursive(AQuery, AResponse, 0);
Server := RootNameServers[i];
Break;
except
on EclSocketError do
begin
Server := '';
end;
end;
end;
end else
begin
oldServer := Server;
try
ResolveRecursive(AQuery, AResponse, 0);
finally
Server := oldServer;
end;
end;
end;
function TclDnsQuery.ExtractPrimaryName(ARecordList: TclDnsRecordList; const Alias: string): string;
var
i: Integer;
begin
for i := 0 to ARecordList.Count - 1 do
begin
if (ARecordList[i] is TclDnsCNAMERecord) then
begin
if (ARecordList[i].Name = Alias) then
begin
Result := TclDnsCNAMERecord(ARecordList[i]).PrimaryName;
Exit;
end;
end;
end;
Result := '';
end;
function TclDnsQuery.ResolveCName(const AHost: string): string;
var
rec: TclDnsRecord;
begin
Clear();
Query.Header.IsQuery := True;
Query.Header.IsRecursionDesired := IsRecursiveDesired;
rec := TclDnsCNAMERecord.Create();
Query.Queries.Add(rec);
rec.Name := AHost;
rec.RecordClass := rcInternet;
Resolve();
FillAInfo(Response.AdditionalRecords);
FillNSInfo(Response.NameServers);
FillAliasInfo();
Result := ExtractPrimaryName(Response.Answers, AHost);
if (Result = '') then
begin
Result := ExtractPrimaryName(Response.AdditionalRecords, AHost);
end;
if (Result = '') then
begin
Result := AHost;
end;
end;
function TclDnsQuery.ResolveMX(const AEmail: string): TclMailServerInfo;
var
rec: TclDnsRecord;
begin
Clear();
Query.Header.IsQuery := True;
Query.Header.IsRecursionDesired := IsRecursiveDesired;
rec := TclDnsMXRecord.Create();
Query.Queries.Add(rec);
rec.Name := GetEmailDomain(AEmail);
rec.RecordClass := rcInternet;
Resolve();
FillAInfo(Response.AdditionalRecords);
FillNSInfo(Response.NameServers);
FillAliasInfo();
FillMXInfo();
Result := GetPreferredMX();
end;
function TclDnsQuery.GetEmailDomain(const AEmail: string): string;
var
ind: Integer;
begin
Result := AEmail;
ind := system.Pos('@', Result);
if (ind > 0) then
begin
system.Delete(Result, 1, ind);
end;
end;
function TclDnsQuery.GetArpaIPAddress(const AIP: string): string;
begin
Result := AIP;
if (system.Pos('in-addr.arpa', LowerCase(Result)) = 0) and (WordCount(Result, ['.']) = 4) then
begin
Result := ExtractWord(4, Result, ['.']) + '.' + ExtractWord(3, Result, ['.']) + '.' +
ExtractWord(2, Result, ['.']) + '.' + ExtractWord(1, Result, ['.']) + '.in-addr.arpa';
end;
end;
function TclDnsQuery.GetArpaIPv6Address(Addr: TclIPAddress6): string;
var
i: Integer;
b: Byte;
begin
Result := '';
for i := 0 to 15 do
begin
b := Byte(Addr.Address.AddressIn6.sin6_addr.s6_addr_[i]);
Result := Result + IntToHex(b shr 4, 1) + '.';
Result := Result + IntToHex(b and $f, 1) + '.';
end;
Result := Result + 'ip6.arpa';
end;
function TclDnsQuery.GetDefaultPort: Integer;
begin
Result := DefaultDnsPort;
end;
class procedure TclDnsQuery.GetDnsList(AList: TStrings);
procedure ExtractDnsNames(const AValue: string; AList: TStrings);
var
i: Integer;
s: string;
begin
for i := 1 to WordCount(AValue, [' ', ',']) do
begin
s := ExtractWord(i, AValue, [' ', ',']);
if AList.IndexOf(s) < 0 then
begin
AList.Add(s);
end;
end;
end;
var
i: Integer;
reg: TRegistry;
names: TStrings;
val: string;
begin
reg := nil;
names := nil;
try
reg := TRegistry.Create();
names := TStringList.Create();
reg.RootKey := HKEY_LOCAL_MACHINE;
if (reg.OpenKeyReadOnly('SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\')) then
begin
reg.GetKeyNames(names);
for i := 0 to names.Count - 1 do
begin
reg.CloseKey();
if reg.OpenKeyReadOnly('SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\' + names[i]) then
begin
val := reg.ReadString('DhcpNameServer');
if (val <> '') then
begin
ExtractDnsNames(val, AList);
end else
begin
val := reg.ReadString('NameServer');
if (val <> '') then
begin
ExtractDnsNames(val, AList);
end;
end;
reg.CloseKey();
end;
end;
end;
finally
names.Free();
reg.Free();
end;
end;
procedure TclDnsQuery.FillMXInfo;
var
i: Integer;
aInfo: TclHostInfo;
mxInfo: TclMailServerInfo;
mxRec: TclDnsMXRecord;
s: string;
begin
for i := 0 to Response.Answers.Count - 1 do
begin
if (Response.Answers[i] is TclDnsMXRecord) then
begin
mxRec := Response.Answers[i] as TclDnsMXRecord;
aInfo := Hosts.ItemByName(mxRec.MailServer);
s := '';
if (aInfo <> nil) then
begin
s := aInfo.IPAddress;
end;
mxInfo := TclMailServerInfo.Create(s, mxRec.MailServer, mxRec.Preference);
MailServers.AddSorted(mxInfo);
end;
end;
end;
function TclDnsQuery.GetPreferredMX: TclMailServerInfo;
begin
if (MailServers.Count > 0) then
begin
Result := MailServers[0];
end else
begin
Result := nil;
end;
end;
procedure TclDnsQuery.InternalResolve(AQuery, AResponse: TclDnsMessage);
var
queryStream, replyStream: TStream;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if not IsDnsDemoDisplayed then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsDnsDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'InternalResolve');{$ENDIF}
queryStream := nil;
replyStream := nil;
try
Open();
queryStream := TMemoryStream.Create();
AQuery.Build(queryStream);
queryStream.Position := 0;
SendPacket(queryStream);
replyStream := TMemoryStream.Create();
ReceivePacket(replyStream);
replyStream.Position := 0;
AResponse.Parse(replyStream);
finally
replyStream.Free();
queryStream.Free();
Close();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InternalResolve'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InternalResolve', E); raise; end; end;{$ENDIF}
end;
procedure TclDnsQuery.InternalResolveIP(const AHost, ADns: string; AQuery, AResponse: TclDnsMessage; IsIPv6: Boolean);
const
aRecClass: array[Boolean] of TclDnsRecordClass_ = (TclDnsARecord, TclDnsAAAARecord);
var
rec: TclDnsRecord;
begin
Server := ADns;
AQuery.Header.IsQuery := True;
AQuery.Header.IsRecursionDesired := IsRecursiveDesired;
rec := aRecClass[IsIPv6].Create();
AQuery.Queries.Add(rec);
rec.Name := AHost;
rec.RecordClass := rcInternet;
Resolve(AQuery, AResponse);
end;
function TclDnsQuery.ResolveIP(const AHost: string): TclHostInfo;
begin
Clear();
InternalResolveIP(AHost, Server, Query, Response, False);
FillAInfo(Response.Answers);
FillNSInfo(Response.NameServers);
FillAliasInfo();
if (Hosts.Count > 0) then
begin
Result := Hosts[0];
end else
begin
Result := nil;
end;
end;
function TclDnsQuery.ResolveIPv6(const AHost: string): TclHostInfo;
begin
Clear();
InternalResolveIP(AHost, Server, Query, Response, True);
FillAInfo(Response.Answers);
FillNSInfo(Response.NameServers);
FillAliasInfo();
if (HostsIPv6.Count > 0) then
begin
Result := HostsIPv6[0];
end else
begin
Result := nil;
end;
end;
procedure TclDnsQuery.FillNSInfo(ARecordList: TclDnsRecordList);
var
i: Integer;
begin
for i := 0 to ARecordList.Count - 1 do
begin
if (ARecordList[i] is TclDnsNSRecord) then
begin
NameServers.Add((ARecordList[i] as TclDnsNSRecord).NameServer);
end;
end;
end;
function TclDnsQuery.ExtractTxtInfo: string;
var
i, cnt: Integer;
rec: TclDnsTXTRecord;
begin
Result := '';
cnt := 0;
for i := 0 to Response.Answers.Count - 1 do
begin
if (Response.Answers[i] is TclDnsTXTRecord) then
begin
rec := TclDnsTXTRecord(Response.Answers[i]);
if Length(Result) > 0 then
begin
Result := Result + ',';
end;
Result := Result + GetQuotedString(rec.Text);
Inc(cnt);
end;
end;
if (cnt = 1) then
begin
Result := ExtractQuotedString(Result);
end;
end;
function TclDnsQuery.ResolveHost(const AIPAddress: string): TclHostInfo;
var
rec: TclDnsRecord;
addr: TclIPAddress6;
begin
Clear();
Query.Header.IsQuery := True;
Query.Header.IsRecursionDesired := IsRecursiveDesired;
rec := TclDnsPTRRecord.Create();
Query.Queries.Add(rec);
rec.RecordClass := rcInternet;
addr := TclIPAddress6.Create();
try
if addr.Parse(AIPAddress) and addr.IsIpV6 then
begin
rec.Name := GetArpaIPv6Address(addr);
end else
begin
rec.Name := GetArpaIPAddress(AIPAddress);
end;
finally
addr.Free();
end;
Resolve();
Result := FillHostInfo();
FillAInfo(Response.AdditionalRecords);
FillNSInfo(Response.NameServers);
FillAliasInfo();
if (Result <> nil) then
begin
Result.FIPAddress := AIPAddress;
end;
end;
function TclDnsQuery.FillHostInfo: TclHostInfo;
var
i: Integer;
ptrRec: TclDnsPTRRecord;
begin
Result := nil;
for i := 0 to Response.Answers.Count - 1 do
begin
if (Response.Answers[i] is TclDnsPTRRecord) then
begin
ptrRec := (Response.Answers[i] as TclDnsPTRRecord);
Result := TclHostInfo.Create(ptrRec.Name, ptrRec.DomainName);
Hosts.Add(Result);
end;
end;
end;
procedure TclDnsQuery.FillAInfo(ARecordList: TclDnsRecordList);
var
i: Integer;
aRec: TclDnsARecord;
av6Rec: TclDnsAAAARecord;
begin
for i := 0 to ARecordList.Count - 1 do
begin
if (ARecordList[i] is TclDnsARecord) then
begin
aRec := (ARecordList[i] as TclDnsARecord);
Hosts.Add(TclHostInfo.Create(aRec.IPAddress, aRec.Name));
end;
if (ARecordList[i] is TclDnsAAAARecord) then
begin
av6Rec := (ARecordList[i] as TclDnsAAAARecord);
HostsIPv6.Add(TclHostInfo.Create(av6Rec.IPv6Address, av6Rec.Name));
end;
end;
end;
function TclDnsQuery.ResolveNS(const AHost: string): string;
var
rec: TclDnsRecord;
begin
Clear();
Query.Header.IsQuery := True;
Query.Header.IsRecursionDesired := IsRecursiveDesired;
rec := TclDnsNSRecord.Create();
Query.Queries.Add(rec);
rec.Name := AHost;
rec.RecordClass := rcInternet;
Resolve();
FillNSInfo(Response.Answers);
FillAliasInfo();
FillAInfo(Response.AdditionalRecords);
if (NameServers.Count > 0) then
begin
Result := NameServers[0];
end else
begin
Result := '';
end;
end;
procedure TclDnsQuery.ResolveRecursive(AQuery, AResponse: TclDnsMessage; ANestLevel: Integer);
var
i: Integer;
nameServer: string;
rec: TclDnsRecord;
resolveIPRequest, resolveIPResponse: TclDnsMessage;
begin
if (ANestLevel > MaxRecursiveQueries) then Exit;
InternalResolve(AQuery, AResponse);
if (not UseRecursiveQueries) then Exit;
if (AResponse.Answers.Count > 0) then Exit;
for i := 0 to AResponse.NameServers.Count - 1 do
begin
try
if (AResponse.NameServers[i] is TclDnsNSRecord) then
begin
nameServer := TclDnsNSRecord(AResponse.NameServers[i]).NameServer;
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'NS: ' + nameServer);{$ENDIF}
rec := AResponse.AdditionalRecords.FindItem(nameServer, DnsRecordTypes[rtARecord]);
if ((rec <> nil) and (rec is TclDnsARecord)) then
begin
Server := TclDnsARecord(rec).IPAddress;
end else
begin
resolveIPRequest := nil;
resolveIPResponse := nil;
try
resolveIPRequest := TclDnsMessage.Create();
resolveIPResponse := TclDnsMessage.Create();
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'before InternalResolveIP');{$ENDIF}
InternalResolveIP(nameServer, '', resolveIPRequest, resolveIPResponse, False);
if ((resolveIPResponse.Answers.Count > 0) and (resolveIPResponse.Answers[0] is TclDnsARecord)) then
begin
Server := TclDnsARecord(resolveIPResponse.Answers[0]).IPAddress;
end else
begin
Continue;
end;
finally
resolveIPResponse.Free();
resolveIPRequest.Free();
end;
end;
resolveIPResponse := TclDnsMessage.Create();
try
ResolveRecursive(AQuery, resolveIPResponse, ANestLevel + 1);
AResponse.Assign(resolveIPResponse);
finally
resolveIPResponse.Free();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ResolveRecursive record resolved');{$ENDIF}
Break;
end;
except
on EclSocketError do
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'ResolveRecursive resolve error, next name server attempt');{$ENDIF}
end;
end;
end;
end;
function TclDnsQuery.ResolveTXT(const AHost: string): string;
var
rec: TclDnsRecord;
begin
Clear();
Query.Header.IsQuery := True;
Query.Header.IsRecursionDesired := IsRecursiveDesired;
rec := TclDnsTXTRecord.Create();
Query.Queries.Add(rec);
rec.Name := AHost;
rec.RecordClass := rcInternet;
Resolve();
FillAInfo(Response.AdditionalRecords);
FillNSInfo(Response.NameServers);
FillAliasInfo();
Result := ExtractTxtInfo();
end;
procedure TclDnsQuery.FillAliasInfo;
procedure ExtractAliases(ARecordList: TclDnsRecordList);
var
i: Integer;
begin
for i := 0 to ARecordList.Count - 1 do
begin
if (ARecordList[i] is TclDnsCNAMERecord) then
begin
Aliases.Add(ARecordList[i].Name);
end;
end;
end;
begin
ExtractAliases(Response.Answers);
ExtractAliases(Response.AdditionalRecords);
end;
{ TclHostList }
procedure TclHostList.Add(AItem: TclHostInfo);
begin
FList.Add(AItem);
end;
procedure TclHostList.Clear;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Items[i].Free();
end;
FList.Clear();
end;
constructor TclHostList.Create;
begin
inherited Create();
FList := TList.Create();
end;
destructor TclHostList.Destroy;
begin
Clear();
FList.Free();
inherited Destroy();
end;
function TclHostList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TclHostList.GetItem(Index: Integer): TclHostInfo;
begin
Result := TclHostInfo(FList[Index]);
end;
procedure TclHostList.Insert(Index: Integer; AItem: TclHostInfo);
begin
FList.Insert(Index, AItem);
end;
function TclHostList.ItemByName(const AName: string): TclHostInfo;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
if SameText(Items[i].Name, AName) then
begin
Result := Items[i];
Exit;
end;
end;
Result := nil;
end;
{ TclMailServerList }
procedure TclMailServerList.AddSorted(AItem: TclMailServerInfo);
var
ind: Integer;
begin
ind := 0;
while (ind < Count) do
begin
if (Items[ind].Preference > AItem.Preference) then
begin
Break;
end;
Inc(ind);
end;
Insert(ind, AItem);
end;
function TclMailServerList.GetItem(Index: Integer): TclMailServerInfo;
begin
Result := (inherited Items[Index] as TclMailServerInfo);
end;
{ TclHostInfo }
constructor TclHostInfo.Create(const AIPAddress, AName: string);
begin
inherited Create();
FIPAddress := AIPAddress;
FName := AName;
end;
{ TclMailServerInfo }
constructor TclMailServerInfo.Create(const AIPAddress, AName: string; APreference: Integer);
begin
inherited Create(AIPAddress, AName);
FPreference := APreference;
end;
end.
|
unit View.ImportacaoAssinaturas;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Actions, Vcl.ActnList, Vcl.ExtCtrls, Vcl.Buttons, System.ImageList,
Vcl.ImgList, Vcl.ComCtrls, Vcl.WinXPickers, Vcl.WinXCtrls, Controller.ListagemAssinantesJornal,
System.DateUtils;
type
Tview_ImportacaoAssinaturas = class(TForm)
actionListImportacao: TActionList;
actionImportar: TAction;
panelTitle: TPanel;
lblTitle: TLabel;
panelButtonImportar: TPanel;
panelButtonSair: TPanel;
speedButtonImportar: TSpeedButton;
speedButtonSair: TSpeedButton;
actSair: TAction;
lblArquivo: TLabel;
editArquivo: TEdit;
actAbrirArquivo: TAction;
lblData: TLabel;
dateTimePickerData: TDateTimePicker;
lblNotice: TLabel;
speedButtonArquivo: TSpeedButton;
imageLogo: TImage;
procedure FormShow(Sender: TObject);
procedure actSairExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure actAbrirArquivoExecute(Sender: TObject);
procedure actionImportarExecute(Sender: TObject);
private
{ Private declarations }
procedure ImportData;
procedure ClearForm;
function ValidateProcess(): Boolean;
public
{ Public declarations }
end;
var
view_ImportacaoAssinaturas: Tview_ImportacaoAssinaturas;
implementation
{$R *.dfm}
uses dataModule, System.Threading, Common.Utils;
procedure Tview_ImportacaoAssinaturas.actAbrirArquivoExecute(Sender: TObject);
begin
if Data_Module.FileOpenDialog.Execute then
begin
editArquivo.Text := Data_Module.FileOpenDialog.FileName;
end;
end;
procedure Tview_ImportacaoAssinaturas.actionImportarExecute(Sender: TObject);
begin
ImportData;
end;
procedure Tview_ImportacaoAssinaturas.actSairExecute(Sender: TObject);
begin
Self.Close;
end;
procedure Tview_ImportacaoAssinaturas.ClearForm;
begin
editArquivo.Clear;
dateTimePickerData.Date := IncDay(Now(),1);
editArquivo.SetFocus;
lblNotice.Visible := False;
end;
procedure Tview_ImportacaoAssinaturas.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
view_ImportacaoAssinaturas := Nil;
end;
procedure Tview_ImportacaoAssinaturas.FormShow(Sender: TObject);
begin
lblTitle.Caption := Self.Caption;
ClearForm;
end;
procedure Tview_ImportacaoAssinaturas.ImportData;
var
FListagem: TListagemAssinantesJornalControl;
begin
if not ValidateProcess() then Exit;
if TUtils.Dialog( 'Importar', 'Confirma a importação do arquivo ?',3) = IDOK then
begin
lblNotice.Visible := True;
lblNotice.Refresh;
FListagem := TListagemAssinantesJornalControl.Create;
if not FListagem.ImportData(editArquivo.Text, dateTimePickerData.Date) then
begin
TUtils.Dialog('Atenção', 'Operação NÃO foi concluída!', 2);
end
else
begin
TUtils.Dialog('Sucesso', 'Operação concluída!', 1);
end;
ClearForm;
FListagem.Free;
end;
end;
function Tview_ImportacaoAssinaturas.ValidateProcess: Boolean;
begin
Result := False;
if editArquivo.Text = '' then
begin
TUtils.Dialog('Atenção', 'Informe o arquivo de planilha a ser importado!', 0);
editArquivo.SetFocus;
Exit;
end;
Result := True;
end;
end.
|
unit Control.Modulos;
interface
uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Control.Sistema, Model.Modulos;
type
TModulosControl = class
private
FModulos : TModulos;
public
constructor Create();
destructor Destroy(); override;
property Modulos: TModulos read FModulos write FModulos;
function ValidaCampos(): Boolean;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
end;
implementation
{ TModulosControl }
constructor TModulosControl.Create;
begin
FModulos := TModulos.Create;
end;
destructor TModulosControl.Destroy;
begin
FModulos.Free;
inherited;
end;
function TModulosControl.Gravar: Boolean;
begin
Result := False;
if not ValidaCampos() then Exit;
Result := FModulos.Gravar();
end;
function TModulosControl.Localizar(aParam: array of variant): TFDQuery;
begin
Result := FModulos.Localizar(aParam);
end;
function TModulosControl.ValidaCampos: Boolean;
var
FDQuery : TFDQuery;
aParam: Array of variant;
begin
try
Result := False;
FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery;
if FModulos.Codigo = 0 then
begin
Application.MessageBox('Informe um código para o módulo!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if FModulos.Sistema = 0 then
begin
Application.MessageBox('Informe um código do sistema!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
SetLength(aParam,3);
aParam[0] := 'MODULO';
aParam[1] := FModulos.Sistema;
aParam[2] := FModulos.Codigo;
FDQuery := FModulos.Localizar(aParam);
Finalize(aParam);
if FDQuery.RecordCount >= 1 then
begin
if FModulos.Acao = tacIncluir then
begin
Application.MessageBox('Módulo já cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING);
FDQuery.Close;
Exit;
end;
end
else
begin
if (FModulos.Acao = tacAlterar) or (FModulos.Acao = tacExcluir) then
begin
Application.MessageBox('Módulo não cadastrado!', 'Atenção', MB_OK + MB_ICONWARNING);
FDQuery.Close;
Exit;
end;
end;
if FModulos.Descricao.IsEmpty then
begin
Application.MessageBox('Informe uma descrição para o módulo!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
finally
FDQuery.Free;
end;
end;
end.
|
program Power (Input, Output);
{Program to compute power using recursion}
var
Number : Integer;
{**********************************************************************}
function Power (X : real; N : Integer) : Real;
{ Function computes X^N using recursive calls to itself }
var
temp : real;
begin {Power}
if N = 0 then
Power := 1
else if (N div 2) = 0 then
begin
temp := Power(X, N-1);
Power := temp * temp;
end { if N div 2 = 0 }
else
begin
temp := Power(X, N-1);
Power := temp * N;
end; { else }
end; { Function Power }
{**********************************************************************}
begin {Main Program}
{1.0 Read Number}
Write ('Enter X: ');
Readln (X);
Write ('Enter N: ');
Readln (N);
writeln('The value of X^N is ', Power(X, N):9);
end. {Main Program}
|
unit uServer;
interface
uses idHTTP;
type
TServer = class(TObject)
private
FURL: string;
FS: TidHTTP;
public
function Get(AURL: string): string;
constructor Create;
destructor Destroy; override;
end;
function IsInternetConnected: Boolean;
//var
// Server: TServer;
implementation
uses Forms, Windows, SysUtils, Wininet, uMain, uBox;
{ TServer }
function IsInternetConnected: Boolean;
var
ConnectionType: DWORD ;
begin
Result := False;
try
ConnectionType := INTERNET_CONNECTION_MODEM
+ INTERNET_CONNECTION_LAN
+ INTERNET_CONNECTION_PROXY;
Result := InternetGetConnectedState(@ConnectionType, 0);
except end;
end;
constructor TServer.Create;
begin
FS := TidHTTP.Create(nil);
FURL := 'http://hod.rlgclub.ru/hodserver/';
end;
destructor TServer.Destroy;
begin
FS.Free;
inherited;
end;
function TServer.Get(AURL: string): string;
begin
if not IsInternetConnected then
begin
Result := '';
Exit;
end;
try
Result := Trim(FS.Get(FURL + AURL));
except
on E: Exception do Result := '';
end;
end;
//initialization finalization
// Server.Free;
end.
|
unit GX_MacroLibrary;
{$I GX_CondDefine.inc}
interface
uses
Windows, SysUtils, Classes,
GX_Experts, GX_ConfigurationInfo, GX_KbdShortCutBroker,
Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Menus, OmniXML,
ComCtrls, GX_IdeDock, ActnList, ImgList, ToolWin, ToolsAPI;
type
TMacroInfo = class(TObject)
private
FStream: TMemoryStream;
FTimeStamp: TDateTime;
FName: string;
FDescription: string;
procedure SetStream(const Value: TStream);
function GetStream: TStream;
public
constructor Create;
destructor Destroy; override;
procedure SaveToFile(const FileName: string);
procedure LoadFromFile(const FileName: string);
procedure SaveToXML(Node: IXMLElement);
procedure LoadFromXML(Node: IXMLElement);
property TimeStamp: TDateTime read FTimeStamp write FTimeStamp;
property Name: string read FName write FName;
property Description: string read FDescription write FDescription;
property Stream: TStream read GetStream write SetStream;
end;
TMacroLibExpert = class;
TfmMacroLibrary = class(TfmIdeDockForm)
lvMacros: TListView;
Toolbar: TToolBar;
tbnClear: TToolButton;
tbnCopy: TToolButton;
Actions: TActionList;
actEditCopy: TAction;
actEditClear: TAction;
actViewToolbar: TAction;
tbnDelete: TToolButton;
mnuMacroPop: TPopupMenu;
mitClear: TMenuItem;
mitCopy: TMenuItem;
actEditDelete: TAction;
mitDelete: TMenuItem;
mitSep1: TMenuItem;
mitShowToolbar: TMenuItem;
actViewDescription: TAction;
mitShowDescription: TMenuItem;
actViewStyleLargeIcon: TAction;
actViewStyleSmallIcon: TAction;
actViewStyleList: TAction;
actViewStyleDetails: TAction;
mitViewStyle: TMenuItem;
mitLargeIcons: TMenuItem;
mitSmallIcons: TMenuItem;
mitList: TMenuItem;
mitDetails: TMenuItem;
mitSep4: TMenuItem;
ilLarge: TImageList;
ilSmall: TImageList;
actFileSave: TAction;
actFileLoad: TAction;
tbnSep3: TToolButton;
tbnSave: TToolButton;
tbnLoad: TToolButton;
mitSep2: TMenuItem;
mitLoadmacro: TMenuItem;
mitSavemacro: TMenuItem;
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
actEditSuspend: TAction;
btnSuspend: TToolButton;
tbnSep4: TToolButton;
mitSep3: TMenuItem;
mitSuspend: TMenuItem;
tbnSep2: TToolButton;
tbnRecord: TToolButton;
tbnPlayback: TToolButton;
tbnSep1: TToolButton;
actRecord: TAction;
actPlayback: TAction;
mitRename: TMenuItem;
pnlDescription: TPanel;
tbnSep5: TToolButton;
tbnHelp: TToolButton;
actHelp: TAction;
actEditRename: TAction;
mmoMacroDescription: TMemo;
lblMacroDesc: TLabel;
Splitter: TSplitter;
actPromptForName: TAction;
mitPromptforName: TMenuItem;
mitSep5: TMenuItem;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lvMacrosDblClick(Sender: TObject);
procedure actEditCopyExecute(Sender: TObject);
procedure actEditClearExecute(Sender: TObject);
procedure actEditDeleteExecute(Sender: TObject);
procedure actViewToolbarExecute(Sender: TObject);
procedure lvMacrosKeyPress(Sender: TObject; var Key: Char);
procedure ActionsUpdate(Action: TBasicAction; var Handled: Boolean);
procedure lvMacrosEdited(Sender: TObject; Item: TListItem; var S: String);
procedure lvMacrosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure mmoMacroDescriptionChange(Sender: TObject);
procedure lvMacrosChange(Sender: TObject; Item: TListItem; Change: TItemChange);
procedure actViewDescriptionExecute(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure actViewStyleExecute(Sender: TObject);
procedure actFileSaveExecute(Sender: TObject);
procedure actFileLoadExecute(Sender: TObject);
procedure actEditSuspendExecute(Sender: TObject);
procedure actRecordExecute(Sender: TObject);
procedure actPlaybackExecute(Sender: TObject);
procedure actEditRenameExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actHelpExecute(Sender: TObject);
procedure lvMacrosInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String);
procedure actPromptForNameExecute(Sender: TObject);
private
FDataList: TList;
FSBWidth: Integer;
FSuspended: Boolean;
FShortCut: IGxKeyboardShortCut;
FPromptForName: Boolean;
procedure InsertMacro(Index: Integer; Info: TMacroInfo);
procedure ClearDataList;
procedure LoadMacros;
procedure SaveMacros;
procedure CopyMacroToPlayback;
procedure UpdateMemoState;
procedure ResizeColumns;
procedure InstallKeyboardBindings;
procedure RemoveKeyboardBindings;
function MacroInfoForItem(Item: TListItem): TMacroInfo;
function MacroInfoFromPointer(Ptr: Pointer): TMacroInfo;
function RegistryKey: string;
function HaveSelectedMacro: Boolean;
function SelectedMacroIndex: Integer;
procedure SelectMacro(Index: Integer);
procedure SelectFirstMacro;
procedure SetDescriptionVisible(const Value: Boolean);
function GetDescriptionVisible: Boolean;
property DescriptionVisible: Boolean read GetDescriptionVisible write SetDescriptionVisible;
procedure RecordShortcutCallback(Sender: TObject);
protected
procedure AddToMacroLibrary(CR: IOTARecord);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SaveSettings;
procedure LoadSettings;
end;
TMacroLibExpert = class(TGX_Expert)
private
FStoragePath: string;
function GetStorageFile: string;
protected
procedure InternalLoadSettings(Settings: TExpertSettings); override;
public
constructor Create; override;
destructor Destroy; override;
function GetActionCaption: string; override;
class function GetName: string; override;
function GetBitmapFileName: string; override;
procedure Execute(Sender: TObject); override;
procedure Configure; override;
function HasConfigOptions: Boolean; override;
property StorageFile: string read GetStorageFile;
function IsDefaultActive: Boolean; override;
end;
var
fmMacroLibrary: TfmMacroLibrary = nil;
MacroLibExpert: TMacroLibExpert = nil;
implementation
{$R *.dfm}
uses
ActiveX,
GX_GxUtils, GX_GenericUtils, GX_OtaUtils,
GX_SharedImages, GX_XmlUtils,
GX_MacroLibraryNamePrompt, GX_MacroLibraryConfig, Math, GX_IdeUtils,
GX_MessageBox;
type
TIDEMacroBugMessage = class(TGxMsgBoxAdaptor)
protected
function GetMessage: string; override;
end;
const
MacroLibraryStorageFileName = 'MacroLibrary.xml';
RegistrySection = 'Settings';
KeyboardMacrosElement = 'KeyboardMacros';
KeyboardMacroElement = 'KeyboardMacro';
NameAttribute = 'Name';
DateAttribute = 'Date';
DescriptionElement = 'Description';
MacroElement = 'Macro';
resourcestring
SMacroLibCaption = 'Macro &Library';
const
UnknownName = 'Unknown';
NameColMinMidth = 100;
{ Utility functions }
procedure EncodeStream(Stream: TStream; var Str: string);
var
Buffer: Byte;
begin
Str := '';
Stream.Position := 0;
while Stream.Read(Buffer, 1) = 1 do
Str := Str + Format('%2.2x', [Buffer]);
end;
procedure DecodeString(const Str: string; Stream: TStream);
var
Buffer: Byte;
HexStr: string;
i: Integer;
begin
i := 1;
while i < Length(Str) do
begin
HexStr := '$' + Copy(Str, i, 2);
Buffer := StrToIntDef(HexStr, $00);
Stream.Write(Buffer, 1);
Inc(i, 2);
end;
Stream.Position := 0;
end;
{ TMacroInfo }
constructor TMacroInfo.Create;
begin
inherited;
FStream := TMemoryStream.Create;
end;
destructor TMacroInfo.Destroy;
begin
FreeAndNil(FStream);
inherited;
end;
function TMacroInfo.GetStream: TStream;
begin
Result := FStream;
end;
procedure TMacroInfo.LoadFromFile(const FileName: string);
var
Doc: IXMLDocument;
begin
Doc := CreateXMLDoc;
Doc.PreserveWhiteSpace := True;
if FileExists(FileName) then
if Doc.Load(FileName) then
LoadFromXML(Doc.DocumentElement);
end;
procedure TMacroInfo.LoadFromXML(Node: IXmlElement);
var
StreamStr: string;
MS: TMemoryStream;
A, N: IXMLNode;
begin
// Name
A := Node.Attributes.GetNamedItem(NameAttribute);
if Assigned(A) then
Name := A.NodeValue
else
Name := UnknownName;
// Date
A := Node.Attributes.GetNamedItem(DateAttribute);
if Assigned(A) then
TimeStamp := IsoStringToDateTimeDef(A.NodeValue, Now)
else
TimeStamp := Now;
// Description
N := Node.SelectSingleNode(DescriptionElement);
if Assigned(N) then
Description := N.Text;
// Stream
N := Node.SelectSingleNode(MacroElement);
if Assigned(N) then
StreamStr := N.Text
else
StreamStr := '54504F5200'; // An empty macro stream
MS := TMemoryStream.Create;
try
DecodeString(StreamStr, MS);
Stream := MS;
finally
FreeAndNil(MS);
end;
end;
procedure TMacroInfo.SaveToFile(const FileName: string);
var
Doc: IXMLDocument;
Root: IXMLElement;
begin
Doc := CreateXMLDoc;
Doc.PreserveWhiteSpace := True;
AddXMLHeader(Doc);
Root := Doc.CreateElement(KeyboardMacroElement);
SaveToXML(Root);
Doc.AppendChild(Root);
Doc.Save(FileName, ofFlat);
end;
procedure TMacroInfo.SaveToXML(Node: IXMLElement);
var
StreamStr: string;
E: IXMLElement;
begin
Node.SetAttribute(NameAttribute, Name);
Node.SetAttribute(DateAttribute, IsoDateTimeToStr(TimeStamp));
E := Node.OwnerDocument.CreateElement(DescriptionElement);
E.Text := Description;
Node.AppendChild(E);
E := Node.OwnerDocument.CreateElement(MacroElement);
EncodeStream(Stream, StreamStr);
E.Text := StreamStr;
Node.AppendChild(E);
end;
procedure TMacroInfo.SetStream(const Value: TStream);
begin
Value.Position := 0;
FStream.LoadFromStream(Value);
FStream.Position := 0;
end;
{ TfmMacroLibrary }
procedure TfmMacroLibrary.RecordShortcutCallback(Sender: TObject);
var
KS: IOTAKeyboardServices;
begin
KS := GxOtaGetKeyboardServices;
Assert(Assigned(KS));
if not KS.CurrentPlayback.IsPlaying then
if KS.CurrentRecord.IsRecording then
begin
KS.ResumeRecord;
// Add to macro library
if Assigned(fmMacroLibrary) and MacroLibExpert.Active and not fmMacroLibrary.FSuspended then
fmMacroLibrary.AddToMacroLibrary(KS.CurrentRecord);
end else
KS.ResumeRecord;
end;
procedure TfmMacroLibrary.ClearDataList;
var
i: Integer;
begin
lvMacros.Items.Clear;
mmoMacroDescription.Lines.Text := '';
if Assigned(FDataList) then
begin
for i := 0 to FDataList.Count - 1 do
MacroInfoFromPointer(FDataList[i]).Free;
FDataList.Clear;
end;
UpdateMemoState;
end;
procedure TfmMacroLibrary.SaveSettings;
var
Settings: TGExpertsSettings;
begin
// Do not localize.
Settings := TGExpertsSettings.Create(AddSlash(ConfigInfo.GExpertsIdeRootRegistryKey) + RegistryKey);
try
Settings.SaveForm(Self, 'Window');
Settings.WriteInteger('Window', 'ViewStyle', Integer(lvMacros.ViewStyle));
Settings.WriteBool(RegistrySection, 'Suspended', FSuspended);
Settings.WriteBool('Window', 'ViewToolbar', Toolbar.Visible);
Settings.WriteBool(RegistrySection, 'ViewDescription', DescriptionVisible);
Settings.WriteInteger('Window', 'DescriptionSize', pnlDescription.Height);
Settings.WriteBool(RegistrySection, 'PromptForName', FPromptForName);
finally
FreeAndNil(Settings);
end;
end;
procedure TfmMacroLibrary.LoadSettings;
var
Settings: TGExpertsSettings;
begin
// Do not localize.
Settings := TGExpertsSettings.Create(AddSlash(ConfigInfo.GExpertsIdeRootRegistryKey) + RegistryKey);
try
Settings.LoadForm(Self, 'Window');
FSuspended := Settings.ReadBool(RegistrySection, 'Suspended', False);
//lvMacros.ViewStyle := TViewStyle(RegIni.ReadEnumerated(RegistrySection, 'ViewStyle', TypeInfo(TViewStyle), Integer(vsReport)));
Toolbar.Visible := Settings.ReadBool('Window', 'ViewToolbar', True);
DescriptionVisible := Settings.ReadBool(RegistrySection, 'ViewDescription', True);
pnlDescription.Height := Settings.ReadInteger('Window', 'DescriptionSize', pnlDescription.Height);
FPromptForName := Settings.ReadBool(RegistrySection, 'PromptForName', False);
finally
FreeAndNil(Settings);
end;
EnsureFormVisible(Self);
end;
procedure TfmMacroLibrary.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TfmMacroLibrary.lvMacrosDblClick(Sender: TObject);
begin
actPlayback.Execute;
end;
procedure TfmMacroLibrary.SaveMacros;
var
Doc: IXMLDocument;
Root: IXMLElement;
i: Integer;
Info: TMacroInfo;
MacroItem: IXMLElement;
begin
// We are calling SaveMacros from the destructor where
// we may be in a forced clean-up due to an exception.
if ExceptObject <> nil then
Exit;
Doc := CreateXMLDoc;
Doc.PreserveWhiteSpace := True;
AddXMLHeader(Doc);
Root := Doc.CreateElement(KeyboardMacrosElement);
Doc.AppendChild(Root);
for i := 0 to FDataList.Count - 1 do
begin
Info := MacroInfoFromPointer(FDataList[i]);
MacroItem := Doc.CreateElement(KeyboardMacroElement);
Info.SaveToXML(MacroItem);
Root.AppendChild(MacroItem);
end;
if PrepareDirectoryForWriting(ExtractFileDir(MacroLibExpert.StorageFile)) then
Doc.Save(MacroLibExpert.StorageFile, ofFlat);
end;
procedure TfmMacroLibrary.LoadMacros;
var
i: Integer;
Info: TMacroInfo;
Doc: IXMLDocument;
Nodes: IXMLNodeList;
begin
ClearDataList;
Doc := CreateXMLDoc;
Doc.PreserveWhiteSpace := True;
if FileExists(MacroLibExpert.StorageFile) then begin
Doc.Load(MacroLibExpert.StorageFile);
Nodes := Doc.DocumentElement.SelectNodes(KeyboardMacroElement);
for i := 0 to Nodes.Length - 1 do
begin
// Create and populate the macro info object
Info := TMacroInfo.Create;
Info.LoadFromXML(Nodes.Item[i] as IXMLElement);
FDataList.Add(Info);
// Add it to the list view
InsertMacro(-1, Info);
end;
SelectFirstMacro;
end;
end;
constructor TfmMacroLibrary.Create(AOwner: TComponent);
resourcestring
SLoadingFailed = 'Loading of stored macros failed.';
begin
inherited;
FSuspended := False;
FDataList := TList.Create;
LoadSettings;
FSBWidth := GetSystemMetrics(SM_CXVSCROLL);
ResizeColumns;
CenterForm(Self);
InstallKeyboardBindings;
Assert(Assigned(MacroLibExpert));
MacroLibExpert.SetFormIcon(Self);
// Since we do not require macros, continue in the event of an error
try
LoadMacros;
except
on E: Exception do
begin
GxLogAndShowException(E, SLoadingFailed);
// Swallow exceptions
end;
end;
end;
destructor TfmMacroLibrary.Destroy;
begin
RemoveKeyboardBindings;
SaveMacros;
ClearDataList;
FreeAndNil(FDataList);
SaveSettings;
inherited;
fmMacroLibrary := nil;
end;
procedure TfmMacroLibrary.actEditCopyExecute(Sender: TObject);
begin
CopyMacroToPlayback;
end;
procedure TfmMacroLibrary.actEditClearExecute(Sender: TObject);
resourcestring
SClearConfirm = 'Delete all macros from the library?';
begin
if MessageDlg(SClearConfirm, mtConfirmation, [mbOK, mbCancel], 0) = mrOK then
ClearDataList;
end;
procedure TfmMacroLibrary.lvMacrosKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
actEditCopy.Execute;
end;
procedure TfmMacroLibrary.ActionsUpdate(Action: TBasicAction; var Handled: Boolean);
begin
actEditClear.Enabled := lvMacros.Items.Count > 0;
actEditDelete.Enabled := HaveSelectedMacro;
actEditCopy.Enabled := HaveSelectedMacro;
actEditRename.Enabled := HaveSelectedMacro;
actFileSave.Enabled := HaveSelectedMacro;
actEditSuspend.Checked := FSuspended;
actRecord.Checked := GxOtaEditorIsRecordingMacro;
actViewToolbar.Checked := Toolbar.Visible;
actViewDescription.Checked := DescriptionVisible;
actViewStyleLargeIcon.Checked := lvMacros.ViewStyle = vsIcon;
actViewStyleSmallIcon.Checked := lvMacros.ViewStyle = vsSmallIcon;
actViewStyleList.Checked := lvMacros.ViewStyle = vsList;
actViewStyleDetails.Checked := lvMacros.ViewStyle = vsReport;
actPromptForName.Checked := FPromptForName;
end;
procedure TfmMacroLibrary.actViewToolbarExecute(Sender: TObject);
begin
Toolbar.Visible := not Toolbar.Visible;
end;
procedure TfmMacroLibrary.CopyMacroToPlayback;
var
OldInfo: TMacroInfo;
Index: Integer;
Stream: IStream;
KS: IOTAKeyboardServices;
begin
Index := SelectedMacroIndex;
if Index <> -1 then
begin
OldInfo := MacroInfoFromPointer(FDataList[Index]);
OldInfo.Stream.Position := 0;
Stream := TStreamAdapter.Create(OldInfo.Stream);
KS := GxOtaGetKeyboardServices;
Assert(Assigned(KS));
if not KS.CurrentPlayback.IsPlaying and not KS.CurrentRecord.IsRecording then
begin
try
KS.CurrentPlayback.Clear;
KS.CurrentPlayback.ReadFromStream(Stream);
except
Application.HandleException(Self);
end;
end;
lvMacros.Items.Delete(Index);
FDataList.Delete(Index);
FDataList.Insert(0, OldInfo);
InsertMacro(0, OldInfo);
SelectFirstMacro;
GxOtaShowCurrentSourceEditor;
end;
end;
procedure TfmMacroLibrary.lvMacrosEdited(Sender: TObject; Item: TListItem; var S: String);
begin
if Assigned(Item) then
MacroInfoForItem(Item).Name := S;
end;
procedure TfmMacroLibrary.actEditDeleteExecute(Sender: TObject);
var
Index : Integer;
begin
Index := SelectedMacroIndex;
if Index <> -1 then
begin
lvMacros.Items.Delete(Index);
MacroInfoFromPointer(FDataList[Index]).Free;
FDataList.Delete(Index);
mmoMacroDescription.Lines.Text := '';
if Assigned(lvMacros.ItemFocused) then
SelectMacro(lvMacros.ItemFocused.Index);
UpdateMemoState;
end;
end;
procedure TfmMacroLibrary.lvMacrosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Key = VK_F2) and HaveSelectedMacro then
lvMacros.Selected.EditCaption;
end;
procedure TfmMacroLibrary.mmoMacroDescriptionChange(Sender: TObject);
begin
if HaveSelectedMacro then
MacroInfoForItem(lvMacros.Selected).Description := mmoMacroDescription.Lines.Text;
end;
procedure TfmMacroLibrary.lvMacrosChange(Sender: TObject; Item: TListItem; Change: TItemChange);
begin
if (Change = ctState) and Assigned(Item) and Item.Selected then
if Assigned(Item) then
mmoMacroDescription.Text := MacroInfoForItem(Item).Description;
UpdateMemoState;
end;
procedure TfmMacroLibrary.UpdateMemoState;
begin
if not HaveSelectedMacro then
mmoMacroDescription.Text := '';
mmoMacroDescription.ReadOnly := (lvMacros.Items.Count = 0) or not HaveSelectedMacro;
end;
procedure TfmMacroLibrary.actViewDescriptionExecute(Sender: TObject);
begin
DescriptionVisible := not DescriptionVisible;
end;
procedure TfmMacroLibrary.FormResize(Sender: TObject);
begin
inherited;
ResizeColumns;
lvMacros.Invalidate;
end;
procedure TfmMacroLibrary.actViewStyleExecute(Sender: TObject);
begin
if Sender is TComponent then
begin
case TComponent(Sender).Tag of
1: lvMacros.ViewStyle := vsIcon;
2: lvMacros.ViewStyle := vsSmallIcon;
3: lvMacros.ViewStyle := vsList;
else lvMacros.ViewStyle := vsReport;
end;
end;
end;
procedure TfmMacroLibrary.actFileSaveExecute(Sender: TObject);
var
Index: Integer;
Info: TMacroInfo;
begin
Index := SelectedMacroIndex;
if Index <> -1 then
begin
Info := MacroInfoFromPointer(FDataList[Index]);
dlgSave.FileName := Info.Name;
if dlgSave.Execute then
begin
if Pos(UnknownName, Info.Name) = 1 then
begin
Info.Name := ChangeFileExt(ExtractFileName(dlgSave.FileName), '');
lvMacros.Selected.Caption := Info.Name;
end;
Info.SaveToFile(dlgSave.FileName);
end;
end;
end;
procedure TfmMacroLibrary.actFileLoadExecute(Sender: TObject);
var
Info: TMacroInfo;
begin
if dlgOpen.Execute then
begin
Info := TMacroInfo.Create;
FDataList.Insert(0, Info);
Info.LoadFromFile(dlgOpen.FileName);
InsertMacro(0, Info);
SelectFirstMacro;
end;
end;
procedure TfmMacroLibrary.ResizeColumns;
var
ColWidth: Integer;
begin
ColWidth := Max(lvMacros.Width - fSBWidth - 6 - lvMacros.Columns[1].MinWidth, NameColMinMidth);
lvMacros.Columns[0].MaxWidth := ColWidth;
lvMacros.Columns[0].MinWidth := ColWidth;
lvMacros.Columns[0].Width := ColWidth;
end;
procedure TfmMacroLibrary.actEditSuspendExecute(Sender: TObject);
begin
FSuspended := not FSuspended;
end;
procedure TfmMacroLibrary.InstallKeyboardBindings;
begin
Assert(not Assigned(FShortCut));
FShortCut := GxKeyboardShortCutBroker.RequestOneKeyShortCut(RecordShortcutCallback, ShortCut(Ord('R'), [ssCtrl, ssShift]));
end;
procedure TfmMacroLibrary.RemoveKeyboardBindings;
begin
FShortCut := nil;
end;
function TfmMacroLibrary.MacroInfoForItem(Item: TListItem): TMacroInfo;
begin
Assert(Assigned(Item));
Assert(Assigned(Item.Data));
Result := MacroInfoFromPointer(Item.Data);
end;
function TfmMacroLibrary.MacroInfoFromPointer(Ptr: Pointer): TMacroInfo;
begin
Assert(Assigned(Ptr));
Result := TObject(Ptr) as TMacroInfo;
end;
function TfmMacroLibrary.RegistryKey: string;
begin
Result := TMacroLibExpert.GetName;
end;
function TfmMacroLibrary.HaveSelectedMacro: Boolean;
begin
Result := Assigned(lvMacros.Selected);
end;
function TfmMacroLibrary.SelectedMacroIndex: Integer;
begin
Result := -1;
if HaveSelectedMacro then
Result := lvMacros.Selected.Index;
end;
procedure TfmMacroLibrary.SelectMacro(Index: Integer);
begin
if (Index >= 0) and (Index < lvMacros.Items.Count) then
begin
lvMacros.Selected := lvMacros.Items[Index];
lvMacros.ItemFocused := lvMacros.Selected;
end;
end;
procedure TfmMacroLibrary.SelectFirstMacro;
begin
SelectMacro(0);
end;
procedure TfmMacroLibrary.actRecordExecute(Sender: TObject);
var
KS : IOTAKeyboardServices;
begin
KS := GxOtaGetKeyboardServices;
if not Assigned(KS) then
Exit;
GxOtaFocusCurrentIDEEditControl;
if not KS.CurrentPlayback.IsPlaying then
begin
if KS.CurrentRecord.IsRecording then
begin
// Stop recording
KS.ResumeRecord;
// Add to macro library
AddToMacroLibrary(KS.CurrentRecord);
end else
begin
// Start recording
KS.ResumeRecord;
GxOtaShowCurrentSourceEditor;
end;
end;
end;
procedure TfmMacroLibrary.actPlaybackExecute(Sender: TObject);
begin
actEditCopy.Execute;
GxOtaFocusCurrentIDEEditControl;
GxOtaGetKeyboardServices.ResumePlayback;
end;
procedure TfmMacroLibrary.actPromptForNameExecute(Sender: TObject);
begin
FPromptForName := not FPromptForName;
end;
procedure TfmMacroLibrary.AddToMacroLibrary(CR: IOTARecord);
var
Stream: IStream;
Info: TMacroInfo;
MacroName: string;
MacroDesc: string;
begin
MacroName := UnknownName + Format('%2.2d', [FDataList.Count]);
MacroDesc := '';
if FPromptForName then begin
if not TfmMacroLibraryNamePrompt.Execute(Self, MacroName, MacroDesc, FPromptForName) then
Exit;
end;
Info := TMacroInfo.Create;
FDataList.Insert(0, Info);
Info.Name := MacroName;
Info.Description := MacroDesc;
Info.TimeStamp := Now;
Stream := TStreamAdapter.Create(Info.Stream);
CR.WriteToStream(Stream);
InsertMacro(0, Info);
SelectFirstMacro;
SaveMacros;
end;
procedure TfmMacroLibrary.FormCreate(Sender: TObject);
begin
inherited;
SetToolbarGradient(ToolBar);
//lvMacros.DoubleBuffered := True; // Causing D2005 paint issues for docked/pinned windows
end;
procedure TfmMacroLibrary.InsertMacro(Index: Integer; Info: TMacroInfo);
var
MacroItem : TListItem;
begin
MacroItem := lvMacros.Items.AddItem(nil, Index);
MacroItem.ImageIndex := 0;
MacroItem.Caption := Info.Name;
MacroItem.SubItems.Add(DateTimeToStr(Info.TimeStamp));
MacroItem.Data := Info;
end;
procedure TfmMacroLibrary.lvMacrosInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String);
begin
InfoTip := MacroInfoForItem(Item).Description;
end;
procedure TfmMacroLibrary.actHelpExecute(Sender: TObject);
begin
GxContextHelp(Self, 44);
end;
procedure TfmMacroLibrary.actEditRenameExecute(Sender: TObject);
begin
if Assigned(lvMacros.Selected) then
lvMacros.Selected.EditCaption;
end;
procedure TfmMacroLibrary.SetDescriptionVisible(const Value: Boolean);
begin
pnlDescription.Visible := Value;
Splitter.Visible := Value;
end;
function TfmMacroLibrary.GetDescriptionVisible: Boolean;
begin
Result := pnlDescription.Visible;
end;
{ TMacroLibExpert }
constructor TMacroLibExpert.Create;
begin
inherited;
FStoragePath := ConfigInfo.ConfigPath;
FreeAndNil(MacroLibExpert);
MacroLibExpert := Self;
end;
destructor TMacroLibExpert.Destroy;
begin
FreeAndNil(fmMacroLibrary);
MacroLibExpert := nil;
inherited;
end;
function TMacroLibExpert.GetActionCaption: string;
begin
Result := SMacroLibCaption;
end;
class function TMacroLibExpert.GetName: string;
begin
Result := 'MacroLibrary';
end;
procedure TMacroLibExpert.Execute(Sender: TObject);
begin
// If the form does not exist, create it
if fmMacroLibrary = nil then
fmMacroLibrary := TfmMacroLibrary.Create(nil);
IdeDockManager.ShowForm(fmMacroLibrary);
fmMacroLibrary.SelectFirstMacro;
fmMacroLibrary.lvMacros.SetFocus;
if RunningRS2009 then
ShowGxMessageBox(TIDEMacroBugMessage);
end;
procedure TMacroLibExpert.InternalLoadSettings(Settings: TExpertSettings);
begin
inherited;
// This procedure is only called once, so it is safe to
// register the form for docking here.
if Active then
IdeDockManager.RegisterDockableForm(TfmMacroLibrary, fmMacroLibrary, 'fmMacroLibrary');
if (fmMacroLibrary = nil) then
fmMacroLibrary := TfmMacroLibrary.Create(nil);
end;
function TMacroLibExpert.GetBitmapFileName: string;
begin
Result := 'MacroLibrary'; // Do not localize.
end;
function TMacroLibExpert.GetStorageFile: string;
begin
Result := FStoragePath + MacroLibraryStorageFileName;
end;
function TMacroLibExpert.HasConfigOptions: Boolean;
begin
Result := True;
end;
procedure TMacroLibExpert.Configure;
begin
if TfmGxMacroLibraryConfig.Execute(fmMacroLibrary.FPromptForName) then
fmMacroLibrary.SaveSettings;
end;
function TMacroLibExpert.IsDefaultActive: Boolean;
begin
Result := not RunningRS2009;
end;
{ TIDEMacroBugMessage }
function TIDEMacroBugMessage.GetMessage: string;
begin
Result := 'RAD Studio 2009 and RAD Studio 2010 before update 2 have bugs preventing record and playback of macros using this tool. See QC 78289 for more details: http://qc.embarcadero.com/wc/qcmain.aspx?d=78289';
end;
initialization
RegisterGX_Expert(TMacroLibExpert);
end.
|
unit nscFormsPageControl;
// Библиотека : "Визуальные компоненты проекта Немезис"
// Автор : Р. Лукьянец.
// Начат : 06.12.2006 г.
// Назначение : Компонент с вкладками-формами
// Версия : $Id: nscFormsPageControl.pas,v 1.3 2012/03/15 10:55:12 lulin Exp $
// $Log: nscFormsPageControl.pas,v $
// Revision 1.3 2012/03/15 10:55:12 lulin
// {RequestLink:344754050}
//
// Revision 1.2 2009/01/12 11:12:06 oman
// - new: Обрабатываем в дочерней зоне (К-113508400)
//
// Revision 1.1 2009/01/12 10:07:19 oman
// - new: Готовим компонент для дочерней зоны (К-113508400)
//
//
interface
uses
classes,
vcmExternalInterfaces,
vtNavigatorFormList,
nscPageControl
;
type
TnscFormsPageControl = class(TnscPageControl,
IvcmOperationsProvider,
IvcmCloseFormHandlerWatcher)
protected
private
f_List: TvtNavigatorFormList;
private
procedure CloseChildExecute(const aParams : IvcmExecuteParamsPrim);
{-}
procedure CloseChildTest(const aParams : IvcmTestParamsPrim);
{-}
function HandlerList: TvtNavigatorFormList;
{-}
function GetCloseHandler: IvcmFormHandler;
{-}
protected
// IvcmOperationsProvider
procedure ProvideOps(const aPublisher : IvcmOperationsPublisher);
{* - предоставить список доступных операций. }
// IvcmCloseFormHandlerWatcher
procedure SetWatch(const aHandler: IvcmFormHandler);
{-}
protected
procedure Cleanup;
override;
{-}
public
procedure Notification(AComponent : TComponent;
Operation : TOperation);
override;
{-}
end;//TnscFormsPageControl
implementation
uses
SysUtils,
Forms,
vtNavigatorForm,
vtNavigatorFormListPrim
;
const
vcm_deEnclosedForms = 'EnclosedForms';
vcm_doCloseChild = 'CloseChild';
{ TnscFormsPageControl }
procedure TnscFormsPageControl.Cleanup;
begin
FreeAndNil(f_List);
inherited;
end;
procedure TnscFormsPageControl.CloseChildExecute(
const aParams: IvcmExecuteParamsPrim);
begin
GetCloseHandler.Handler(GetCloseHandler.Form);
end;
procedure TnscFormsPageControl.CloseChildTest(
const aParams: IvcmTestParamsPrim);
begin
if aParams.Op.Flag[vcm_ofEnabled] then
aParams.Op.Flag[vcm_ofEnabled] := (GetCloseHandler <> nil);
end;
function TnscFormsPageControl.GetCloseHandler: IvcmFormHandler;
var
l_Index : Integer;
begin
Result := nil;
if Assigned(f_List) and (ActivePage <> nil) and (ActivePage.ControlCount > 0) and
HandlerList.FindData(TvtFormHandlerID_C(ActivePage.Controls[0]), l_Index) then
Result := HandlerList.Items[l_Index].CloseHandler
else
Result := nil;
end;
function TnscFormsPageControl.HandlerList: TvtNavigatorFormList;
begin
if f_List = nil then
f_List := TvtNavigatorFormList.Create;
Result := f_List;
end;
procedure TnscFormsPageControl.Notification(AComponent: TComponent;
Operation: TOperation);
var
l_Item : Integer;
begin
inherited Notification(aComponent, Operation);
if (Operation = opRemove) then
begin
if Assigned(f_List) and HandlerList.FindData(TvtFormHandlerID_C(aComponent), l_Item) then
begin
AComponent.RemoveFreeNotification(Self);
HandlerList.Delete(l_Item);
end;//if HandlerList.FindData(l_Form, l_Item) then
end;//if (Operation = opRemove) then
end;
procedure TnscFormsPageControl.ProvideOps(
const aPublisher: IvcmOperationsPublisher);
begin
aPublisher.PublishOp(vcm_deEnclosedForms, vcm_doCloseChild, CloseChildExecute, CloseChildTest);
end;
procedure TnscFormsPageControl.SetWatch(const aHandler: IvcmFormHandler);
var
l_Class: TvtNavigatorForm;
begin
l_Class := TvtNavigatorForm.Create(aHandler);
try
HandlerList.Add(l_Class);
aHandler.Form.FreeNotification(Self);
finally
FreeAndNil(l_Class);
end;//try..finally
end;
end.
|
unit TelnetForma;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, SynEditHighlighter, StdCtrls, OverbyteIcsWndControl,
OverbyteIcsTnCnx, ExtCtrls, Mask, DBCtrlsEh, ActnList, System.Actions, PropFilerEh, PropStorageEh;
type
TTelnetForm = class(TForm)
pnlControl: TPanel;
HostLabel: TLabel;
InfoLabel: TLabel;
PortLabel: TLabel;
Label1: TLabel;
HostEdit: TEdit;
ConnectButton: TButton;
DisconnectButton: TButton;
PortEdit: TEdit;
DataEdit: TEdit;
SendButton: TButton;
btnClose: TButton;
lbl6: TLabel;
cbbEOL: TDBComboBoxEh;
actlst1: TActionList;
actShowControl: TAction;
DisplayMemo: TDBMemoEh;
PropStorageEh: TPropStorageEh;
procedure FormCreate(Sender: TObject);
procedure DisplayMemoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DisplayMemoKeyPress(Sender: TObject; var Key: Char);
procedure SendButtonClick(Sender: TObject);
procedure ConnectButtonClick(Sender: TObject);
procedure DisconnectButtonClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cbbEOLChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure actShowControlExecute(Sender: TObject);
procedure btn2Click(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
tlntExecuted : Boolean;
fEOL : Integer;
fExitOnExucute : Boolean;
TnCnx: TTnCnx;
function Connect(const host, port: string):boolean;
procedure SendText(const text : string);
procedure SetEOL(value : integer);
procedure SetOnExit(value : Boolean);
procedure TnCnxDataAvailable(Sender: TTnCnx; Buffer: Pointer;
Len: Integer);
procedure TnCnxSessionClosed(Sender: TTnCnx; Error: Word);
procedure TnCnxSessionConnected(Sender: TTnCnx; Error: Word);
public
property telnet_EOL : Integer write SetEOL;
property ExitOnExucute : Boolean write SetOnExit;
{ Public declarations }
end;
function telnet(const host:string='localhost'; const port:string='telnet';const commands : string=''; const EOL_CHR:Integer = 0;const ExExit : Boolean = False):string;
implementation
uses StrUtils, OverbyteIcsWSocket;
{$R *.dfm}
const
Telnet_wait = 500;
CR = #13;
LF = #10;
function CharToCode(const str : String) : string;
begin
Result := str;
Result := ReplaceStr(Result,'\n',CR+LF);
Result := ReplaceStr(Result,'\r',CR+LF);
Result := ReplaceStr(Result,'\p',#32);
end;
function telnet(const host:string='localhost'; const port:string='telnet';const commands : string=''; const EOL_CHR:Integer = 0;const ExExit : Boolean = False):string;
begin
Result := '';
with TTelnetForm.Create(Application) do
try
telnet_EOL := EOL_CHR;
ExitOnExucute := ExExit;
HostEdit.Text := host;
PortEdit.Text := Port;
DataEdit.Text := commands;
pnlControl.Visible := not ExExit;
if showmodal = mrOk
then begin
Result := DisplayMemo.Text;
end;
finally
Free;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{* Display a message in the memo field, breaking with CR *}
procedure MemoAddLines(Memo : TDBMemoEh; const Msg : String);
var
Start, Stop : Integer;
begin
if Memo.Lines.Count = 0 then Memo.Lines.Add('');
//Memo.Lines.Text := Memo.Lines.Text+msg;
//Exit;
Start := 1;
Stop := Pos(CR, Msg);
if Stop = 0 then
Stop := Length(Msg) + 1;
while Start <= Length(Msg) do begin
Memo.Lines.Strings[Memo.Lines.Count - 1] :=
Memo.Lines.Strings[Memo.Lines.Count - 1] +
Copy(Msg, Start, Stop - Start);
if Msg[Stop] = CR then begin
Memo.Lines.Add('');
SendMessage(Memo.Handle, WM_KEYDOWN, VK_UP, 1);
end;
Start := Stop + 1;
if Start > Length(Msg) then
Break;
if Msg[Start] = LF then
Start := Start + 1;
Stop := Start;
while (Msg[Stop] <> CR) and (Stop <= Length(Msg)) do
Stop := Stop + 1;
end;
end;
procedure TTelnetForm.actShowControlExecute(Sender: TObject);
begin
pnlControl.Visible := True;
end;
procedure TTelnetForm.btnCloseClick(Sender: TObject);
begin
if TnCnx.State = wsConnected then TnCnx.Close;
end;
procedure TTelnetForm.btn2Click(Sender: TObject);
begin
DisplayMemo.SetFocus;
if connect(HostEdit.Text, PortEdit.Text)
then SendText(DataEdit.Text);
end;
procedure TTelnetForm.DisconnectButtonClick(Sender: TObject);
begin
TnCnx.Close;
end;
procedure TTelnetForm.DisplayMemoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
Key := 0;
end;
procedure TTelnetForm.DisplayMemoKeyPress(Sender: TObject; var Key: Char);
begin
if TnCnx.State = wsConnected
then begin
TnCnx.Send(@Key, 1);
if Key = CR then begin
{ Send a LF after CR key }
if fEOL = 0 then begin
Key := LF;
TnCnx.Send(@Key, 1);
end;
end;
Key := #0;
end;
end;
procedure TTelnetForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(TnCnx)
then begin
if TnCnx.State = wsConnected then TnCnx.Close;
FreeAndNil(TnCnx);
end;
end;
procedure TTelnetForm.FormCreate(Sender: TObject);
begin
//TnCnx
TnCnx := TTnCnx.Create(Self);
TnCnx.Name := 'TnCnx';
TnCnx.Port := '23';
TnCnx.Location := 'TNCNX';
TnCnx.TermType := 'VT100';
TnCnx.LocalEcho := False;
TnCnx.SocketFamily := sfIPv4;
TnCnx.OnSessionConnected := TnCnxSessionConnected;
TnCnx.OnSessionClosed := TnCnxSessionClosed;
TnCnx.OnDataAvailable := TnCnxDataAvailable;
telnet_EOL := 0;
fExitOnExucute := False;
end;
procedure TTelnetForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN)
then btnCloseClick(Sender);
end;
procedure TTelnetForm.FormShow(Sender: TObject);
begin
if fExitOnExucute
then begin
DisplayMemo.SetFocus;
if connect(HostEdit.Text, PortEdit.Text)
then begin
Sleep(1000);
Application.ProcessMessages;
SendText(DataEdit.Text);
end;
end;
end;
procedure TTelnetForm.SendButtonClick(Sender: TObject);
begin
SendText(DataEdit.Text);
end;
procedure TTelnetForm.TnCnxDataAvailable(Sender: TTnCnx; Buffer: Pointer;
Len: Integer);
var
Data : AnsiString;
begin
if Len <= 0 then Exit;
SetLength(Data, Len);
Move(Buffer^, Data[1], Len);
MemoAddLines(DisplayMemo, String(Data));
tlntExecuted:=(Length(Data)>0);
end;
procedure TTelnetForm.TnCnxSessionClosed(Sender: TTnCnx; Error: Word);
begin
InfoLabel.Caption := 'Disconnected';
ConnectButton.Enabled := TRUE;
DisconnectButton.Enabled := FALSE;
SendButton.Enabled := FALSE;
if pnlControl.Visible then ActiveControl := ConnectButton;
end;
procedure TTelnetForm.TnCnxSessionConnected(Sender: TTnCnx; Error: Word);
begin
if Error <> 0 then begin
DisplayMemo.Lines.Add('Unable to connect. Error #' + IntToStr(Error));
Exit;
end;
DisplayMemo.Clear;
InfoLabel.Caption := 'Connected';
ConnectButton.Enabled := FALSE;
DisconnectButton.Enabled := TRUE;
SendButton.Enabled := True;
ActiveControl := DisplayMemo;
end;
procedure TTelnetForm.cbbEOLChange(Sender: TObject);
begin
fEOL := cbbEOL.Value;
end;
function TTelnetForm.Connect(const host, port: string):boolean;
var
i : Integer;
begin
TnCnx.Host := Host;
TnCnx.Port := Port;
TnCnx.TermType := 'VT100';
TnCnx.LocalEcho := FALSE;
TnCnx.Connect;
i:=0;
tlntExecuted := False;
while (TnCnx.State <> wsConnected) and (i<Telnet_wait) do begin
Sleep(10);
Application.ProcessMessages;
Inc(i);
end;
Result := (TnCnx.State = wsConnected);
end;
procedure TTelnetForm.ConnectButtonClick(Sender: TObject);
begin
if (HostEdit.Text = '') or (PortEdit.Text = '') then
exit;
connect(HostEdit.Text, PortEdit.Text);
fExitOnExucute := False;
end;
procedure TTelnetForm.SetEOL(value : integer);
begin
fEOL := value;
cbbEOL.Value := fEOL;
end;
procedure TTelnetForm.SetOnExit(value : boolean);
begin
fExitOnExucute := value;
end;
procedure TTelnetForm.SendText(const text:string);
var
cmd : string;
commands : TStrings;
i : Integer;
w : Integer;
begin
if TnCnx.State <> wsConnected
then begin
DisplayMemo.Lines.Add('*** NOT CONNECTED ***');
Exit;
end;
cmd := Text;
cmd := CharToCode(cmd);
commands := TStringList.Create;
try
commands.Text := cmd;
for i := 0 to commands.Count - 1 do begin
cmd := commands[i];
if cmd = 'wait' then begin
Sleep(1000);
Continue;
end;
case fEOL of
1 : cmd := cmd + LF+CR;
2 : cmd := cmd + LF;
3 : cmd := cmd + CR;
else cmd := cmd + CR+LF;
end;
if TnCnx.State = wsConnected
then begin
tlntExecuted := False;
w := 0;
TnCnx.SendStr(cmd);
while (not tlntExecuted) and (w<Telnet_wait) do begin
Sleep(10);
Application.ProcessMessages;
Inc(w);
end;
//if (i<(commands.Count - 1)) then sleep(500);
end;
end;
finally
commands.Free;
end;
end;
end.
|
unit HelpCnst;
{ $Id: HelpCnst.pas,v 1.3 2005/07/01 10:27:07 voba Exp $ }
interface
const
hcSetAbolished = 321; { Снять с контроля }
hcDocSample = 140; { Выборки документов }
hcStyleDesigner = 78; { Дизайнер стилей }
hcAddDoc = 353; { Добавить }
hcSearchAttr = 138; { Запрос на поиск (Атрибуты) }
hcSearchClass = 162; { -*- Классы }
hcSearchKey = 158; { -*- Ключи }
hcSearchSpec = 347; { -*- Специальный }
hcSearchText = 348; { -*- Текст }
hcDocInfo = 133; { Инфо о документе }
hcTuning = 53; { Настройки }
hcNewDoc = 351; { Новый документ }
hcSaveDocSample = 355; { Сохранить выборку док-тов }
hcStatistic = 136; { Статистика }
hcSearchStat = 115; { Статистика по поиску }
hcTypeFilter = 109; { Фильтр типов }
hcExport = 105; { Экспорт }
implementation
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.123 2/8/05 5:27:06 PM RLebeau
Bug fix for ReadLn().
Added try..finally block to ReadLnSplit().
Rev 1.122 1/27/05 3:09:30 PM RLebeau
Updated AllData() to call ReadFromSource() directly instead of using
CheckForDataOnSource(), since ReadFromSource() can return a disconnect
conditon. When data is in the InputBuffer, Connected() always return True
even if the socket is actually disconnected.
Rev 1.121 12/21/04 3:21:40 AM RLebeau
Removed compiler warning
Rev 1.120 17/12/2004 17:11:28 ANeillans
Compiler fix
Rev 1.119 12/12/04 2:23:52 PM RLebeau
Added WriteRFCStrings() method
Rev 1.118 12/11/2004 9:04:50 PM DSiders
Fixed comparison error in WaitFor.
Rev 1.117 12/10/04 2:00:24 PM RLebeau
Updated WaitFor() to not return more data than actually needed.
Updated AllData() to not concatenate the Result on every iteration of the
loop.
Rev 1.116 11/29/04 10:37:18 AM RLebeau
Updated write buffering methods to prevent Access Violations when used
incorrectly.
Rev 1.115 11/4/04 12:41:08 PM RLebeau
Bug fix for ReadLn()
Rev 1.114 10/26/2004 8:43:00 PM JPMugaas
Should be more portable with new references to TIdStrings and TIdStringList.
Rev 1.113 27.08.2004 21:58:18 Andreas Hausladen
Speed optimization ("const" for string parameters)
Rev 1.112 8/2/04 5:49:20 PM RLebeau
Moved ConnectTimeout over from TIdIOHandlerSocket
Rev 1.111 2004.08.01 19:36:14 czhower
Code optimization to WriteFile
Rev 1.110 7/24/04 12:53:54 PM RLebeau
Compiler fix for WriteFile()
Rev 1.109 7/23/04 6:39:14 PM RLebeau
Added extra exception handling to WriteFile()
Rev 1.108 7/21/2004 5:45:10 PM JPMugaas
Updated with Remy's change. This should work better and fix a problem with
looping with ReadStream and ReadUntilDisconnect.
Rev 1.107 7/21/2004 12:22:18 PM BGooijen
Reverted back 2 versions
Rev 1.104 6/29/04 12:16:16 PM RLebeau
Updated ReadChar() to call ReadBytes() directly instead of ReadString()
Rev 1.103 6/17/04 3:01:56 PM RLebeau
Changed ReadStream() to not extract too many bytes from the InputBuffer when
an error occurs
Rev 1.102 6/12/04 11:36:44 AM RLebeau
Changed ReadString() to pass the ABytes parameter to ReadBytes() instead of
the LBuf length
Rev 1.100 6/10/2004 6:52:12 PM JPMugaas
Regeneration to fix a bug in the package generator that I created. OOPS!!!
Rev 1.99 6/9/04 7:36:26 PM RLebeau
ReadString() bug fix
Rev 1.98 07/06/2004 20:55:36 CCostelloe
Fix for possible memory leak.
Rev 1.97 5/29/04 10:46:24 PM RLebeau
Updated AllData() to only append values to the result when there is actual
data in the buffer.
Rev 1.96 29/05/2004 21:07:40 CCostelloe
Bug fix (may need more investigation)
Rev 1.95 2004.05.20 1:39:54 PM czhower
Last of the IdStream updates
Rev 1.94 2004.05.20 12:34:22 PM czhower
Removed more non .NET compatible stream read and writes
Rev 1.93 2004.05.20 11:39:02 AM czhower
IdStreamVCL
Rev 1.92 5/3/2004 12:57:00 PM BGooijen
Fixes for 0-based
Rev 1.91 2004.05.03 11:15:44 AM czhower
Changed Find to IndexOf and made 0 based to be consistent.
Rev 1.90 4/24/04 12:40:04 PM RLebeau
Added Write() overload for Char type.
Rev 1.89 4/18/2004 11:58:00 PM BGooijen
ReadBytes with count=-1 reads everything available, ( and waits ReadTimeOut
time for data)
Rev 1.88 4/18/04 2:44:24 PM RLebeau
Read/write support for Int64 values
Rev 1.87 2004.04.18 12:51:58 AM czhower
Big bug fix with server disconnect and several other bug fixed that I found
along the way.
Rev 1.86 2004.04.16 11:30:28 PM czhower
Size fix to IdBuffer, optimizations, and memory leaks
Rev 1.85 2004.04.08 7:06:46 PM czhower
Peek support.
Rev 1.84 2004.04.08 3:56:28 PM czhower
Fixed bug with Intercept byte count. Also removed Bytes from Buffer.
Rev 1.83 2004.04.08 2:08:00 AM czhower
Saved before checkin this time...
Rev 1.82 7/4/2004 4:08:46 PM SGrobety
Re-introduce the IOHandler.MaxCapturedLines property
Rev 1.81 2004.04.07 3:59:46 PM czhower
Bug fix for WriteDirect.
Rev 1.79 2004.03.07 11:48:38 AM czhower
Flushbuffer fix + other minor ones found
Rev 1.78 2004.03.03 11:54:58 AM czhower
IdStream change
Rev 1.77 2004.03.02 2:47:08 PM czhower
.Net overloads
Rev 1.76 2004.03.01 5:12:28 PM czhower
-Bug fix for shutdown of servers when connections still existed (AV)
-Implicit HELP support in CMDserver
-Several command handler bugs
-Additional command handler functionality.
Rev 1.75 2004.02.03 4:16:44 PM czhower
For unit name changes.
Rev 1.74 2004.01.21 9:36:00 PM czhower
.Net overload
Rev 1.73 2004.01.21 12:19:58 AM czhower
.Readln overload for .net
Rev 1.72 2004.01.20 10:03:26 PM czhower
InitComponent
Rev 1.71 1/11/2004 5:51:04 PM BGooijen
Added AApend parameter to ReadBytes
Rev 1.70 12/30/2003 7:17:56 PM BGooijen
.net
Rev 1.69 2003.12.28 1:05:54 PM czhower
.Net changes.
Rev 1.68 2003.12.28 11:53:28 AM czhower
Removed warning in .net.
Rev 1.67 2003.11.29 10:15:30 AM czhower
InternalBuffer --> InputBuffer for consistency.
Rev 1.66 11/23/03 1:46:28 PM RLebeau
Removed "var" specifier from TStrings parameter of ReadStrings().
Rev 1.65 11/4/2003 10:27:56 PM DSiders
Removed exceptions moved to IdException.pas.
Rev 1.64 2003.10.24 10:44:52 AM czhower
IdStream implementation, bug fixes.
Rev 1.63 10/22/03 2:05:40 PM RLebeau
Fix for TIdIOHandler::Write(TStream) where it was not reading the stream into
the TIdBytes correctly.
Rev 1.62 10/19/2003 5:55:44 PM BGooijen
Fixed todo in PerformCapture
Rev 1.61 2003.10.18 12:58:50 PM czhower
Added comment
Rev 1.60 2003.10.18 12:42:04 PM czhower
Intercept.Disconnect is now called
Rev 1.59 10/15/2003 7:39:28 PM DSiders
Added a formatted resource string for the exception raised in
TIdIOHandler.MakeIOHandler.
Rev 1.58 2003.10.14 1:26:50 PM czhower
Uupdates + Intercept support
Rev 1.57 2003.10.11 5:48:22 PM czhower
-VCL fixes for servers
-Chain suport for servers (Super core)
-Scheduler upgrades
-Full yarn support
Rev 1.56 9/10/2003 1:50:38 PM SGrobety
Removed all "const" keywords from boolean parameter interfaces. Might trigger
changes in other units.
Rev 1.55 10/5/2003 10:39:56 PM BGooijen
Write buffering
Rev 1.54 10/4/2003 11:03:12 PM BGooijen
ReadStream, and functions with network ordering
Rev 1.53 10/4/2003 7:10:46 PM BGooijen
ReadXXXXX
Rev 1.52 10/4/2003 3:55:02 PM BGooijen
ReadString, and some Write functions
Rev 1.51 04/10/2003 13:38:32 HHariri
Write(Integer) support
Rev 1.50 10/3/2003 12:09:30 AM BGooijen
DotNet
Rev 1.49 2003.10.02 8:29:14 PM czhower
Changed names of byte conversion routines to be more readily understood and
not to conflict with already in use ones.
Rev 1.48 2003.10.02 1:18:50 PM czhower
Changed read methods to be overloaded and more consistent. Will break some
code, but nearly all code that uses them is Input.
Rev 1.47 2003.10.02 10:16:26 AM czhower
.Net
Rev 1.46 2003.10.01 9:11:16 PM czhower
.Net
Rev 1.45 2003.10.01 2:46:36 PM czhower
.Net
Rev 1.42 2003.10.01 11:16:32 AM czhower
.Net
Rev 1.41 2003.10.01 1:37:34 AM czhower
.Net
Rev 1.40 2003.10.01 1:12:34 AM czhower
.Net
Rev 1.39 2003.09.30 1:22:56 PM czhower
Stack split for DotNet
Rev 1.38 2003.09.18 5:17:58 PM czhower
Implemented OnWork
Rev 1.37 2003.08.21 10:43:42 PM czhower
Fix to ReadStream from Doychin
Rev 1.36 08/08/2003 17:32:26 CCostelloe
Removed "virtual" from function ReadLnSplit
Rev 1.35 07/08/2003 00:25:08 CCostelloe
Function ReadLnSplit added
Rev 1.34 2003.07.17 1:05:12 PM czhower
More IOCP improvements.
Rev 1.33 2003.07.14 11:00:50 PM czhower
More IOCP fixes.
Rev 1.32 2003.07.14 12:54:30 AM czhower
Fixed graceful close detection if it occurs after connect.
Rev 1.31 2003.07.10 7:40:24 PM czhower
Comments
Rev 1.30 2003.07.10 4:34:56 PM czhower
Fixed AV, added some new comments
Rev 1.29 7/1/2003 5:50:44 PM BGooijen
Fixed ReadStream
Rev 1.28 6/30/2003 10:26:08 AM BGooijen
forgot to remove some code regarding to TIdBuffer.Find
Rev 1.27 6/29/2003 10:56:26 PM BGooijen
Removed .Memory from the buffer, and added some extra methods
Rev 1.26 2003.06.25 4:30:00 PM czhower
Temp hack fix for AV problem. Working on real solution now.
Rev 1.25 23/6/2003 22:33:14 GGrieve
fix CheckForDataOnSource - specify timeout
Rev 1.24 23/6/2003 06:46:52 GGrieve
allow block on checkForData
Rev 1.23 6/4/2003 1:07:08 AM BGooijen
changed comment
Rev 1.22 6/3/2003 10:40:34 PM BGooijen
FRecvBuffer bug fixed, it was freed, but never recreated, resulting in an AV
Rev 1.21 2003.06.03 6:28:04 PM czhower
Made check for data virtual
Rev 1.20 2003.06.03 3:43:24 PM czhower
Resolved InputBuffer inconsistency. Added new method and renamed old one.
Rev 1.19 5/25/2003 03:56:04 AM JPMugaas
Updated for unit rename.
Rev 1.18 2003.04.17 11:01:12 PM czhower
Rev 1.17 4/16/2003 3:29:30 PM BGooijen
minor change in ReadBuffer
Rev 1.16 4/1/2003 7:54:24 PM BGooijen
ReadLn default terminator changed to LF
Rev 1.15 3/27/2003 3:24:06 PM BGooijen
MaxLine* is now published
Rev 1.14 2003.03.25 7:42:12 PM czhower
try finally to WriteStrings
Rev 1.13 3/24/2003 11:01:36 PM BGooijen
WriteStrings is now buffered to increase speed
Rev 1.12 3/19/2003 1:02:32 PM BGooijen
changed class function ConstructDefaultIOHandler a little (default parameter)
Rev 1.11 3/13/2003 10:18:16 AM BGooijen
Server side fibers, bug fixes
Rev 1.10 3/5/2003 11:03:06 PM BGooijen
Added Intercept here
Rev 1.9 2/25/2003 11:02:12 PM BGooijen
InputBufferToStream now accepts a bytecount
Rev 1.8 2003.02.25 1:36:00 AM czhower
Rev 1.7 12-28-2002 22:28:16 BGooijen
removed warning, added initialization and finalization part.
Rev 1.6 12-16-2002 20:43:28 BGooijen
Added class function ConstructIOHandler(....), and removed some comments
Rev 1.5 12-15-2002 23:02:38 BGooijen
added SendBufferSize
Rev 1.4 12-15-2002 20:50:32 BGooijen
FSendBufferSize was not initialized
Rev 1.3 12-14-2002 22:14:54 BGooijen
improved method to detect timeouts in ReadLn.
Rev 1.2 12/11/2002 04:09:28 AM JPMugaas
Updated for new API.
Rev 1.1 2002.12.07 12:25:56 AM czhower
Rev 1.0 11/13/2002 08:44:50 AM JPMugaas
}
unit IdIOHandler;
interface
{$I IdCompilerDefines.inc}
uses
Classes,
IdException,
IdAntiFreezeBase, IdBuffer, IdBaseComponent, IdComponent, IdGlobal, IdExceptionCore,
IdIntercept, IdResourceStringsCore, IdStream;
const
GRecvBufferSizeDefault = 32 * 1024;
GSendBufferSizeDefault = 32 * 1024;
IdMaxLineLengthDefault = 16 * 1024;
// S.G. 6/4/2004: Maximum number of lines captured
// S.G. 6/4/2004: Default to "unlimited"
Id_IOHandler_MaxCapturedLines = -1;
type
EIdIOHandler = class(EIdException);
EIdIOHandlerRequiresLargeStream = class(EIdIOHandler);
EIdIOHandlerStreamDataTooLarge = class(EIdIOHandler);
TIdIOHandlerClass = class of TIdIOHandler;
{
How does this fit in in the hierarchy against TIdIOHandlerSocket
Destination - Socket - otehr file descendats it
TIdIOHandler should only implement an interface. No default functionality
except very simple read/write functions such as ReadCardinal, etc. Functions
that cannot really be optimized beyond their default implementations.
Some default implementations offer basic non optmized implementations.
Yes, I know this comment conflicts. Its being worked on.
}
TIdIOHandler = class(TIdComponent)
private
FLargeStream: Boolean;
protected
FClosedGracefully: Boolean;
FConnectTimeout: Integer;
FDestination: string;
FHost: string;
// IOHandlers typically receive more data than they need to complete each
// request. They store this extra data in InputBuffer for future methods to
// use. InputBuffer is what collects the input and keeps it if the current
// method does not need all of it.
//
FInputBuffer: TIdBuffer;
FIntercept: TIdConnectionIntercept;
FMaxCapturedLines: Integer;
FMaxLineAction: TIdMaxLineAction;
FMaxLineLength: Integer;
FOpened: Boolean;
FPort: Integer;
FReadLnSplit: Boolean;
FReadLnTimedOut: Boolean;
FReadTimeOut: Integer;
//TODO:
FRecvBufferSize: Integer;
FSendBufferSize: Integer;
FWriteBuffer: TIdBuffer;
FWriteBufferThreshold: Integer;
FDefStringEncoding : TIdTextEncoding;
{$IFDEF STRING_IS_ANSI}
FDefAnsiEncoding : TIdTextEncoding;
{$ENDIF}
procedure SetDefStringEncoding(const AEncoding : TIdTextEncoding);
{$IFDEF STRING_IS_ANSI}
procedure SetDefAnsiEncoding(const AEncoding: TIdTextEncoding);
{$ENDIF}
//
procedure BufferRemoveNotify(ASender: TObject; ABytes: Integer);
function GetDestination: string; virtual;
procedure InitComponent; override;
procedure InterceptReceive(var VBuffer: TIdBytes);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure PerformCapture(const ADest: TObject; out VLineCount: Integer;
const ADelim: string; AUsesDotTransparency: Boolean; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
); virtual;
procedure RaiseConnClosedGracefully;
procedure SetDestination(const AValue: string); virtual;
procedure SetHost(const AValue: string); virtual;
procedure SetPort(AValue: Integer); virtual;
procedure SetIntercept(AValue: TIdConnectionIntercept); virtual;
// This is the main Read function which all other default implementations
// use.
function ReadFromSource(ARaiseExceptionIfDisconnected: Boolean = True;
ATimeout: Integer = IdTimeoutDefault;
ARaiseExceptionOnTimeout: Boolean = True): Integer;
function ReadDataFromSource(var VBuffer: TIdBytes): Integer; virtual; abstract;
function WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; virtual; abstract;
function SourceIsAvailable: Boolean; virtual; abstract;
function CheckForError(ALastResult: Integer): Integer; virtual; abstract;
procedure RaiseError(AError: Integer); virtual; abstract;
public
procedure AfterAccept; virtual;
function Connected: Boolean; virtual;
destructor Destroy; override;
// CheckForDisconnect allows the implementation to check the status of the
// connection at the request of the user or this base class.
procedure CheckForDisconnect(ARaiseExceptionIfDisconnected: Boolean = True;
AIgnoreBuffer: Boolean = False); virtual; abstract;
// Does not wait or raise any exceptions. Just reads whatever data is
// available (if any) into the buffer. Must NOT raise closure exceptions.
// It is used to get avialable data, and check connection status. That is
// it can set status flags about the connection.
function CheckForDataOnSource(ATimeout: Integer = 0): Boolean; virtual;
procedure Close; virtual;
procedure CloseGracefully; virtual;
class function MakeDefaultIOHandler(AOwner: TComponent = nil)
: TIdIOHandler;
class function MakeIOHandler(ABaseType: TIdIOHandlerClass;
AOwner: TComponent = nil): TIdIOHandler;
class procedure RegisterIOHandler;
class procedure SetDefaultClass;
function WaitFor(const AString: string; ARemoveFromBuffer: Boolean = True;
AInclusive: Boolean = False; AByteEncoding: TIdTextEncoding = nil;
ATimeout: Integer = IdTimeoutDefault
{$IFDEF STRING_IS_ANSI}; AAnsiEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
// This is different than WriteDirect. WriteDirect goes
// directly to the network or next level. WriteBuffer allows for buffering
// using WriteBuffers. This should be the only call to WriteDirect
// unless the calls that bypass this are aware of WriteBuffering or are
// intended to bypass it.
procedure Write(const ABuffer: TIdBytes; const ALength: Integer = -1; const AOffset: Integer = 0); overload; virtual;
// This is the main write function which all other default implementations
// use. If default implementations are used, this must be implemented.
procedure WriteDirect(const ABuffer: TIdBytes; const ALength: Integer = -1; const AOffset: Integer = 0);
//
procedure Open; virtual;
function Readable(AMSec: Integer = IdTimeoutDefault): Boolean; virtual;
//
// Optimal Extra Methods
//
// These methods are based on the core methods. While they can be
// overridden, they are so simple that it is rare a more optimal method can
// be implemented. Because of this they are not overrideable.
//
//
// Write Methods
//
// Only the ones that have a hope of being better optimized in descendants
// have been marked virtual
procedure Write(const AOut: string; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
); overload; virtual;
procedure WriteLn(AEncoding: TIdTextEncoding = nil); overload;
procedure WriteLn(const AOut: string; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
); overload; virtual;
procedure WriteLnRFC(const AOut: string = ''; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
); virtual;
procedure Write(AValue: TStrings; AWriteLinesCount: Boolean = False;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
); overload; virtual;
procedure Write(AValue: Byte); overload;
procedure Write(AValue: Char; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
); overload;
procedure Write(AValue: LongWord; AConvert: Boolean = True); overload;
procedure Write(AValue: LongInt; AConvert: Boolean = True); overload;
procedure Write(AValue: Word; AConvert: Boolean = True); overload;
procedure Write(AValue: SmallInt; AConvert: Boolean = True); overload;
procedure Write(AValue: Int64; AConvert: Boolean = True); overload;
procedure Write(AStream: TStream; ASize: TIdStreamSize = 0;
AWriteByteCount: Boolean = False); overload; virtual;
procedure WriteRFCStrings(AStrings: TStrings; AWriteTerminator: Boolean = True;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
// Not overloaded because it does not have a unique type for source
// and could be easily unresolvable with future additions
function WriteFile(const AFile: String; AEnableTransferFile: Boolean = False): Int64; virtual;
//
// Read methods
//
function AllData(AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string; virtual;
function InputLn(const AMask: string = ''; AEcho: Boolean = True;
ATabWidth: Integer = 8; AMaxLineLength: Integer = -1;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; AAnsiEncoding: TIdTextEncoding = nil{$ENDIF}
): string; virtual;
// Capture
// Not virtual because each calls PerformCapture which is virtual
procedure Capture(ADest: TStream; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
); overload; // .Net overload
procedure Capture(ADest: TStream; ADelim: string;
AUsesDotTransparency: Boolean = True; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
); overload;
procedure Capture(ADest: TStream; out VLineCount: Integer;
const ADelim: string = '.'; AUsesDotTransparency: Boolean = True;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
); overload;
procedure Capture(ADest: TStrings; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
); overload; // .Net overload
procedure Capture(ADest: TStrings; const ADelim: string;
AUsesDotTransparency: Boolean = True; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
); overload;
procedure Capture(ADest: TStrings; out VLineCount: Integer;
const ADelim: string = '.'; AUsesDotTransparency: Boolean = True;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
); overload;
//
// Read___
// Cannot overload, compiler cannot overload on return values
//
procedure ReadBytes(var VBuffer: TIdBytes; AByteCount: Integer; AAppend: Boolean = True); virtual;
// ReadLn
function ReadLn(AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string; overload; // .Net overload
function ReadLn(ATerminator: string; AByteEncoding: TIdTextEncoding
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string; overload;
function ReadLn(ATerminator: string; ATimeout: Integer = IdTimeoutDefault;
AMaxLineLength: Integer = -1; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string; overload; virtual;
//RLebeau: added for RFC 822 retrieves
function ReadLnRFC(var VMsgEnd: Boolean; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string; overload;
function ReadLnRFC(var VMsgEnd: Boolean; const ALineTerminator: string;
const ADelim: string = '.'; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string; overload;
function ReadLnWait(AFailCount: Integer = MaxInt;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string; virtual;
// Added for retrieving lines over 16K long}
function ReadLnSplit(var AWasSplit: Boolean; ATerminator: string = LF;
ATimeout: Integer = IdTimeoutDefault; AMaxLineLength: Integer = -1;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
// Read - Simple Types
function ReadChar(AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): Char;
function ReadByte: Byte;
function ReadString(ABytes: Integer; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
function ReadLongWord(AConvert: Boolean = True): LongWord;
function ReadLongInt(AConvert: Boolean = True): LongInt;
function ReadInt64(AConvert: Boolean = True): Int64;
function ReadWord(AConvert: Boolean = True): Word;
function ReadSmallInt(AConvert: Boolean = True): SmallInt;
//
procedure ReadStream(AStream: TStream; AByteCount: TIdStreamSize = -1;
AReadUntilDisconnect: Boolean = False); virtual;
procedure ReadStrings(ADest: TStrings; AReadLinesCount: Integer = -1;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
);
//
procedure Discard(AByteCount: Int64);
procedure DiscardAll;
//
// WriteBuffering Methods
//
procedure WriteBufferCancel; virtual;
procedure WriteBufferClear; virtual;
procedure WriteBufferClose; virtual;
procedure WriteBufferFlush; overload; //.Net overload
procedure WriteBufferFlush(AByteCount: Integer); overload; virtual;
procedure WriteBufferOpen; overload; //.Net overload
procedure WriteBufferOpen(AThreshold: Integer); overload; virtual;
function WriteBufferingActive: Boolean;
//
// InputBuffer Methods
//
function InputBufferIsEmpty: Boolean;
//
// These two are direct access and do no reading of connection
procedure InputBufferToStream(AStream: TStream; AByteCount: Integer = -1);
function InputBufferAsString(AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
//
// Properties
//
property ConnectTimeout: Integer read FConnectTimeout write FConnectTimeout default 0;
property ClosedGracefully: Boolean read FClosedGracefully;
// TODO: Need to name this consistent. Originally no access was allowed,
// but new model requires it for writing. Will decide after next set
// of changes are complete what to do with Buffer prop.
//
// Is used by SuperCore
property InputBuffer: TIdBuffer read FInputBuffer;
//currently an option, as LargeFile support changes the data format
property LargeStream: Boolean read FLargeStream write FLargeStream;
property MaxCapturedLines: Integer read FMaxCapturedLines write FMaxCapturedLines default Id_IOHandler_MaxCapturedLines;
property Opened: Boolean read FOpened;
property ReadTimeout: Integer read FReadTimeOut write FReadTimeOut default IdTimeoutDefault;
property ReadLnTimedout: Boolean read FReadLnTimedout ;
property WriteBufferThreshold: Integer read FWriteBufferThreshold;
property DefStringEncoding : TIdTextEncoding read FDefStringEncoding write SetDefStringEncoding;
{$IFDEF STRING_IS_ANSI}
property DefAnsiEncoding : TIdTextEncoding read FDefAnsiEncoding write SetDefAnsiEncoding;
{$ENDIF}
//
// Events
//
property OnWork;
property OnWorkBegin;
property OnWorkEnd;
published
property Destination: string read GetDestination write SetDestination;
property Host: string read FHost write SetHost;
property Intercept: TIdConnectionIntercept read FIntercept write SetIntercept;
property MaxLineLength: Integer read FMaxLineLength write FMaxLineLength default IdMaxLineLengthDefault;
property MaxLineAction: TIdMaxLineAction read FMaxLineAction write FMaxLineAction;
property Port: Integer read FPort write SetPort;
// RecvBufferSize is used by some methods that read large amounts of data.
// RecvBufferSize is the amount of data that will be requested at each read
// cycle. RecvBuffer is used to receive then send to the Intercepts, after
// that it goes to InputBuffer
property RecvBufferSize: Integer read FRecvBufferSize write FRecvBufferSize
default GRecvBufferSizeDefault;
// SendBufferSize is used by some methods that have to break apart large
// amounts of data into smaller pieces. This is the buffer size of the
// chunks that it will create and use.
property SendBufferSize: Integer read FSendBufferSize write FSendBufferSize
default GSendBufferSizeDefault;
end;
implementation
uses
//facilitate inlining only.
{$IFDEF DOTNET}
{$IFDEF USE_INLINE}
System.IO,
{$ENDIF}
{$ENDIF}
{$IFDEF WIN32_OR_WIN64}
Windows,
{$ENDIF}
{$IFDEF USE_VCL_POSIX}
{$IFDEF DARWIN}
Macapi.CoreServices,
{$ENDIF}
{$ENDIF}
IdStack, IdStackConsts, IdResourceStrings, SysUtils;
var
GIOHandlerClassDefault: TIdIOHandlerClass = nil;
GIOHandlerClassList: TList = nil;
{ TIdIOHandler }
procedure TIdIOHandler.Close;
//do not do FInputBuffer.Clear; here.
//it breaks reading when remote connection does a disconnect
begin
try
if Intercept <> nil then begin
Intercept.Disconnect;
end;
finally
FOpened := False;
WriteBufferClear;
end;
end;
destructor TIdIOHandler.Destroy;
begin
Close;
FreeAndNil(FInputBuffer);
FreeAndNil(FWriteBuffer);
inherited Destroy;
end;
procedure TIdIOHandler.AfterAccept;
begin
//
end;
procedure TIdIOHandler.Open;
begin
FOpened := False;
FClosedGracefully := False;
WriteBufferClear;
FInputBuffer.Clear;
FOpened := True;
end;
procedure TIdIOHandler.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, OPeration);
if (Operation = opRemove) and (AComponent = FIntercept) then begin
FIntercept := nil;
end;
end;
procedure TIdIOHandler.SetIntercept(AValue: TIdConnectionIntercept);
begin
if (AValue <> FIntercept) then begin
// remove self from the Intercept's free notification list
if Assigned(FIntercept) then begin
FIntercept.RemoveFreeNotification(Self);
end;
FIntercept := AValue;
// add self to the Intercept's free notification list
if Assigned(FIntercept) then begin
FIntercept.FreeNotification(Self);
end;
end;
end;
class procedure TIdIOHandler.SetDefaultClass;
begin
GIOHandlerClassDefault := Self;
RegisterIOHandler;
end;
procedure TIdIOHandler.SetDefStringEncoding(const AEncoding: TIdTextEncoding);
var
LEncoding: TIdTextEncoding;
begin
if FDefStringEncoding <> AEncoding then
begin
LEncoding := AEncoding;
EnsureEncoding(LEncoding);
FDefStringEncoding := LEncoding;
end;
end;
{$IFDEF STRING_IS_ANSI}
procedure TIdIOHandler.SetDefAnsiEncoding(const AEncoding: TIdTextEncoding);
var
LEncoding: TIdTextEncoding;
begin
if FDefAnsiEncoding <> AEncoding then
begin
LEncoding := AEncoding;
EnsureEncoding(LEncoding, encOSDefault);
FDefAnsiEncoding := LEncoding;
end;
end;
{$ENDIF}
class function TIdIOHandler.MakeDefaultIOHandler(AOwner: TComponent = nil): TIdIOHandler;
begin
Result := GIOHandlerClassDefault.Create(AOwner);
end;
class procedure TIdIOHandler.RegisterIOHandler;
begin
if GIOHandlerClassList = nil then begin
GIOHandlerClassList := TList.Create;
end;
{$IFNDEF DOTNET_EXCLUDE}
//TODO: Reenable this. Dot net wont allow class references as objects
// Use an array?
if GIOHandlerClassList.IndexOf(Self) = -1 then begin
GIOHandlerClassList.Add(Self);
end;
{$ENDIF}
end;
{
Creates an IOHandler of type ABaseType, or descendant.
}
class function TIdIOHandler.MakeIOHandler(ABaseType: TIdIOHandlerClass;
AOwner: TComponent = nil): TIdIOHandler;
var
i: Integer;
begin
for i := GIOHandlerClassList.Count - 1 downto 0 do begin
if TIdIOHandlerClass(GIOHandlerClassList.Items[i]).InheritsFrom(ABaseType) then begin
Result := TIdIOHandlerClass(GIOHandlerClassList.Items[i]).Create;
Exit;
end;
end;
raise EIdException.CreateFmt(RSIOHandlerTypeNotInstalled, [ABaseType.ClassName]);
end;
function TIdIOHandler.GetDestination: string;
begin
Result := FDestination;
end;
procedure TIdIOHandler.SetDestination(const AValue: string);
begin
FDestination := AValue;
end;
procedure TIdIOHandler.BufferRemoveNotify(ASender: TObject; ABytes: Integer);
begin
DoWork(wmRead, ABytes);
end;
procedure TIdIOHandler.WriteBufferOpen(AThreshold: Integer);
begin
if FWriteBuffer <> nil then begin
FWriteBuffer.Clear;
end else begin
FWriteBuffer := TIdBuffer.Create;
end;
FWriteBufferThreshold := AThreshold;
end;
procedure TIdIOHandler.WriteBufferClose;
begin
try
WriteBufferFlush;
finally FreeAndNil(FWriteBuffer); end;
end;
procedure TIdIOHandler.WriteBufferFlush(AByteCount: Integer);
var
LBytes: TIdBytes;
begin
if FWriteBuffer <> nil then begin
if FWriteBuffer.Size > 0 then begin
FWriteBuffer.ExtractToBytes(LBytes, AByteCount);
WriteDirect(LBytes);
end;
end;
end;
procedure TIdIOHandler.WriteBufferClear;
begin
if FWriteBuffer <> nil then begin
FWriteBuffer.Clear;
end;
end;
procedure TIdIOHandler.WriteBufferCancel;
begin
WriteBufferClear;
WriteBufferClose;
end;
procedure TIdIOHandler.Write(const AOut: string; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
begin
if AOut <> '' then begin
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ASrcEncoding := iif(ASrcEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
Write(
ToBytes(AOut, -1, 1, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}
)
);
end;
end;
procedure TIdIOHandler.Write(AValue: Byte);
begin
Write(ToBytes(AValue));
end;
procedure TIdIOHandler.Write(AValue: Char; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
begin
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ASrcEncoding := iif(ASrcEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
Write(
ToBytes(AValue, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}
)
);
end;
procedure TIdIOHandler.Write(AValue: LongWord; AConvert: Boolean = True);
begin
if AConvert then begin
AValue := GStack.HostToNetwork(AValue);
end;
Write(ToBytes(AValue));
end;
procedure TIdIOHandler.Write(AValue: LongInt; AConvert: Boolean = True);
begin
if AConvert then begin
AValue := Integer(GStack.HostToNetwork(LongWord(AValue)));
end;
Write(ToBytes(AValue));
end;
procedure TIdIOHandler.Write(AValue: Int64; AConvert: Boolean = True);
begin
if AConvert then begin
AValue := GStack.HostToNetwork(AValue);
end;
Write(ToBytes(AValue));
end;
procedure TIdIOHandler.Write(AValue: TStrings; AWriteLinesCount: Boolean = False;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
var
i: Integer;
LBufferingStarted: Boolean;
begin
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ASrcEncoding := iif(ASrcEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
LBufferingStarted := not WriteBufferingActive;
if LBufferingStarted then begin
WriteBufferOpen;
end;
try
if AWriteLinesCount then begin
Write(AValue.Count);
end;
for i := 0 to AValue.Count - 1 do begin
WriteLn(AValue.Strings[i], AByteEncoding
{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}
);
end;
if LBufferingStarted then begin
WriteBufferClose;
end;
except
if LBufferingStarted then begin
WriteBufferCancel;
end;
raise;
end;
end;
procedure TIdIOHandler.Write(AValue: Word; AConvert: Boolean = True);
begin
if AConvert then begin
AValue := GStack.HostToNetwork(AValue);
end;
Write(ToBytes(AValue));
end;
procedure TIdIOHandler.Write(AValue: SmallInt; AConvert: Boolean = True);
begin
if AConvert then begin
AValue := SmallInt(GStack.HostToNetwork(Word(AValue)));
end;
Write(ToBytes(AValue));
end;
function TIdIOHandler.ReadString(ABytes: Integer; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
var
LBytes: TIdBytes;
begin
if ABytes > 0 then begin
ReadBytes(LBytes, ABytes, False);
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
Result := BytesToString(LBytes, 0, ABytes, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end else begin
Result := '';
end;
end;
procedure TIdIOHandler.ReadStrings(ADest: TStrings; AReadLinesCount: Integer = -1;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
);
var
i: Integer;
begin
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
if AReadLinesCount < 0 then begin
AReadLinesCount := ReadLongInt;
end;
for i := 0 to AReadLinesCount - 1 do begin
ADest.Add(ReadLn(AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
));
end;
end;
function TIdIOHandler.ReadWord(AConvert: Boolean = True): Word;
var
LBytes: TIdBytes;
begin
ReadBytes(LBytes, SizeOf(Word), False);
Result := BytesToWord(LBytes);
if AConvert then begin
Result := GStack.NetworkToHost(Result);
end;
end;
function TIdIOHandler.ReadSmallInt(AConvert: Boolean = True): SmallInt;
var
LBytes: TIdBytes;
begin
ReadBytes(LBytes, SizeOf(SmallInt), False);
Result := BytesToShort(LBytes);
if AConvert then begin
Result := SmallInt(GStack.NetworkToHost(Word(Result)));
end;
end;
function TIdIOHandler.ReadChar(AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): Char;
var
I, J, NumChars, NumBytes: Integer;
LBytes: TIdBytes;
{$IFDEF DOTNET}
LChars: array[0..1] of Char;
{$ELSE}
LChars: TIdWideChars;
{$IFDEF STRING_IS_ANSI}
LWTmp: TIdUnicodeString;
LATmp: TIdBytes;
{$ENDIF}
{$ENDIF}
begin
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
// 2 Chars to handle UTF-16 surrogates
NumBytes := AByteEncoding.GetMaxByteCount(2);
SetLength(LBytes, NumBytes);
{$IFNDEF DOTNET}
SetLength(LChars, 2);
{$ENDIF}
NumChars := 0;
if NumBytes > 0 then
begin
for I := 1 to NumBytes do
begin
LBytes[I-1] := ReadByte;
NumChars := AByteEncoding.GetChars(LBytes, 0, I, LChars, 0);
if NumChars > 0 then begin
// RLebeau 10/19/2012: when Indy switched to its own UTF-8 implementation
// to avoid the MB_ERR_INVALID_CHARS flag on Windows, it accidentally broke
// this loop! Since this is not commonly used, this was not noticed until
// now. On Windows at least, GetChars() now returns >0 for an invalid
// sequence, so we have to check if any of the returned characters are the
// Unicode U+FFFD character, indicating bad data...
for J := 0 to NumChars-1 do begin
if LChars[J] = TIdWideChar($FFFD) then begin
// keep reading...
NumChars := 0;
Break;
end;
end;
if NumChars > 0 then begin
Break;
end;
end;
end;
end;
{$IFDEF STRING_IS_UNICODE}
// RLebeau: if the bytes were decoded into surrogates, the second
// surrogate is lost here, as it can't be returned unless we cache
// it somewhere for the the next ReadChar() call to retreive. Just
// raise an error for now. Users will have to update their code to
// read surrogates differently...
Assert(NumChars = 1);
Result := LChars[0];
{$ELSE}
// RLebeau: since we can only return an AnsiChar here, let's convert
// the decoded characters, surrogates and all, into their Ansi
// representation. This will have the same problem as above if the
// conversion results in a multibyte character sequence...
SetString(LWTmp, PWideChar(LChars), NumChars);
LATmp := ADestEncoding.GetBytes(LWTmp); // convert to Ansi
Assert(Length(LATmp) = 1);
Result := Char(LATmp[0]);
{$ENDIF}
end;
function TIdIOHandler.ReadByte: Byte;
var
LBytes: TIdBytes;
begin
ReadBytes(LBytes, 1, False);
Result := LBytes[0];
end;
function TIdIOHandler.ReadLongInt(AConvert: Boolean): LongInt;
var
LBytes: TIdBytes;
begin
ReadBytes(LBytes, SizeOf(LongInt), False);
Result := BytesToLongInt(LBytes);
if AConvert then begin
Result := LongInt(GStack.NetworkToHost(LongWord(Result)));
end;
end;
function TIdIOHandler.ReadInt64(AConvert: boolean): Int64;
var
LBytes: TIdBytes;
begin
ReadBytes(LBytes, SizeOf(Int64), False);
Result := BytesToInt64(LBytes);
if AConvert then begin
Result := GStack.NetworkToHost(Result);
end;
end;
function TIdIOHandler.ReadLongWord(AConvert: Boolean): LongWord;
var
LBytes: TIdBytes;
begin
ReadBytes(LBytes, SizeOf(LongWord), False);
Result := BytesToLongWord(LBytes);
if AConvert then begin
Result := GStack.NetworkToHost(Result);
end;
end;
function TIdIOHandler.ReadLn(AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
Result := ReadLn(LF, IdTimeoutDefault, -1, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
function TIdIOHandler.ReadLn(ATerminator: string; AByteEncoding: TIdTextEncoding
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
Result := ReadLn(ATerminator, IdTimeoutDefault, -1, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
function TIdIOHandler.ReadLn(ATerminator: string; ATimeout: Integer = IdTimeoutDefault;
AMaxLineLength: Integer = -1; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
var
LInputBufferSize: Integer;
LStartPos: Integer;
LTermPos: Integer;
LReadLnStartTime: LongWord;
LTerm, LResult: TIdBytes;
begin
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
if AMaxLineLength < 0 then begin
AMaxLineLength := MaxLineLength;
end;
// User may pass '' if they need to pass arguments beyond the first.
if ATerminator = '' then begin
ATerminator := LF;
end;
LTerm := ToBytes(ATerminator, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
FReadLnSplit := False;
FReadLnTimedOut := False;
LTermPos := -1;
LStartPos := 0;
LReadLnStartTime := Ticks;
repeat
LInputBufferSize := FInputBuffer.Size;
if LInputBufferSize > 0 then begin
if LStartPos < LInputBufferSize then begin
LTermPos := FInputBuffer.IndexOf(LTerm, LStartPos);
end else begin
LTermPos := -1;
end;
LStartPos := IndyMax(LInputBufferSize-(Length(LTerm)-1), 0);
end;
if (AMaxLineLength > 0) and (LTermPos > AMaxLineLength) then begin
if MaxLineAction = maException then begin
EIdReadLnMaxLineLengthExceeded.Toss(RSReadLnMaxLineLengthExceeded);
end;
FReadLnSplit := True;
Result := FInputBuffer.ExtractToString(AMaxLineLength, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
Exit;
end
// ReadFromSource blocks - do not call unless we need to
else if LTermPos = -1 then begin
// RLebeau 11/19/08: this is redundant, since it is the same
// logic as above and should have been handled there...
{
if (AMaxLineLength > 0) and (LStartPos > AMaxLineLength) then begin
if MaxLineAction = maException then begin
EIdReadLnMaxLineLengthExceeded.Toss(RSReadLnMaxLineLengthExceeded);
end;
FReadLnSplit := True;
Result := FInputBuffer.Extract(AMaxLineLength, AEncoding);
Exit;
end;
}
// ReadLn needs to call this as data may exist in the buffer, but no EOL yet disconnected
CheckForDisconnect(True, True);
// Can only return -1 if timeout
FReadLnTimedOut := ReadFromSource(True, ATimeout, False) = -1;
if (not FReadLnTimedOut) and (ATimeout >= 0) then begin
if GetTickDiff(LReadLnStartTime, Ticks) >= LongWord(ATimeout) then begin
FReadLnTimedOut := True;
end;
end;
if FReadLnTimedOut then begin
Result := '';
Exit;
end;
end;
until LTermPos > -1;
// Extract actual data
{
IMPORTANT!!!
When encoding from UTF8 to Unicode or ASCII, you will not always get the same
number of bytes that you input so you may have to recalculate LTermPos since
that was based on the number of bytes in the input stream. If do not do this,
you will probably get an incorrect result or a range check error since the
string is shorter then the original buffer position.
JPM
}
// RLebeau 11/19/08: this is no longer needed as the terminator is encoded to raw bytes now ...
{
Result := FInputBuffer.Extract(LTermPos + Length(ATerminator), AEncoding);
LTermPos := IndyMin(LTermPos, Length(Result));
if (ATerminator = LF) and (LTermPos > 0) then begin
if Result[LTermPos] = CR then begin
Dec(LTermPos);
end;
end;
SetLength(Result, LTermPos);
}
FInputBuffer.ExtractToBytes(LResult, LTermPos + Length(LTerm));
if (ATerminator = LF) and (LTermPos > 0) then begin
if LResult[LTermPos-1] = Ord(CR) then begin
Dec(LTermPos);
end;
end;
Result := BytesToString(LResult, 0, LTermPos, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
function TIdIOHandler.ReadLnRFC(var VMsgEnd: Boolean;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
Result := ReadLnRFC(VMsgEnd, LF, '.', AByteEncoding {do not localize}
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
function TIdIOHandler.ReadLnRFC(var VMsgEnd: Boolean; const ALineTerminator: string;
const ADelim: String = '.'; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
begin
Result := ReadLn(ALineTerminator, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
// Do not use ATerminator since always ends with . (standard)
if Result = ADelim then
begin
VMsgEnd := True;
Exit;
end;
if TextStartsWith(Result, '..') then begin {do not localize}
Delete(Result, 1, 1);
end;
VMsgEnd := False;
end;
function TIdIOHandler.ReadLnSplit(var AWasSplit: Boolean; ATerminator: string = LF;
ATimeout: Integer = IdTimeoutDefault; AMaxLineLength: Integer = -1;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
var
FOldAction: TIdMaxLineAction;
begin
FOldAction := MaxLineAction;
MaxLineAction := maSplit;
try
Result := ReadLn(ATerminator, ATimeout, AMaxLineLength, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
AWasSplit := FReadLnSplit;
finally
MaxLineAction := FOldAction;
end;
end;
function TIdIOHandler.ReadLnWait(AFailCount: Integer = MaxInt;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
var
LAttempts: Integer;
begin
// MtW: this is mostly used when empty lines could be sent.
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
Result := '';
LAttempts := 0;
while LAttempts < AFailCount do
begin
Result := Trim(ReadLn(AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
));
if Length(Result) > 0 then begin
Exit;
end;
if ReadLnTimedOut then begin
raise EIdReadTimeout.Create(RSReadTimeout);
end;
Inc(LAttempts);
end;
raise EIdReadLnWaitMaxAttemptsExceeded.Create(RSReadLnWaitMaxAttemptsExceeded);
end;
function TIdIOHandler.ReadFromSource(ARaiseExceptionIfDisconnected: Boolean;
ATimeout: Integer; ARaiseExceptionOnTimeout: Boolean): Integer;
var
LByteCount: Integer;
LLastError: Integer;
LBuffer: TIdBytes;
begin
if ATimeout = IdTimeoutDefault then begin
// MtW: check for 0 too, for compatibility
if (ReadTimeout = IdTimeoutDefault) or (ReadTimeout = 0) then begin
ATimeout := IdTimeoutInfinite;
end else begin
ATimeout := ReadTimeout;
end;
end;
Result := 0;
// Check here as this side may have closed the socket
CheckForDisconnect(ARaiseExceptionIfDisconnected);
if SourceIsAvailable then begin
repeat
LByteCount := 0;
if Readable(ATimeout) then begin
if Opened then begin
// No need to call AntiFreeze, the Readable does that.
if SourceIsAvailable then begin
// TODO: Whey are we reallocating LBuffer every time? This
// should be a one time operation per connection.
// RLebeau: because the Intercept does not allow the buffer
// size to be specified, and the Intercept could potentially
// resize the buffer...
SetLength(LBuffer, RecvBufferSize);
try
LByteCount := ReadDataFromSource(LBuffer);
if LByteCount > 0 then begin
SetLength(LBuffer, LByteCount);
if Intercept <> nil then begin
Intercept.Receive(LBuffer);
LByteCount := Length(LBuffer);
end;
// Pass through LBuffer first so it can go through Intercept
//TODO: If not intercept, we can skip this step
InputBuffer.Write(LBuffer);
end;
finally
LBuffer := nil;
end;
end
else if ARaiseExceptionIfDisconnected then begin
EIdClosedSocket.Toss(RSStatusDisconnected);
end;
end
else if ARaiseExceptionIfDisconnected then begin
EIdNotConnected.Toss(RSNotConnected);
end;
if LByteCount < 0 then
begin
LLastError := CheckForError(LByteCount);
FClosedGracefully := True;
Close;
// Do not raise unless all data has been read by the user
if InputBufferIsEmpty and ARaiseExceptionIfDisconnected then begin
RaiseError(LLastError);
end;
LByteCount := 0;
end
else if LByteCount = 0 then begin
FClosedGracefully := True;
end;
// Check here as other side may have closed connection
CheckForDisconnect(ARaiseExceptionIfDisconnected);
Result := LByteCount;
end else begin
// Timeout
if ARaiseExceptionOnTimeout then begin
EIdReadTimeout.Toss(RSReadTimeout);
end;
Result := -1;
Break;
end;
until (LByteCount <> 0) or (not SourceIsAvailable);
end
else if ARaiseExceptionIfDisconnected then begin
raise EIdNotConnected.Create(RSNotConnected);
end;
end;
function TIdIOHandler.CheckForDataOnSource(ATimeout: Integer = 0): Boolean;
var
LPrevSize: Integer;
begin
Result := False;
// RLebeau - Connected() might read data into the InputBuffer, thus
// leaving no data for ReadFromSource() to receive a second time,
// causing a result of False when it should be True instead. So we
// save the current size of the InputBuffer before calling Connected()
// and then compare it afterwards....
LPrevSize := InputBuffer.Size;
if Connected then begin
// return whether at least 1 byte was received
Result := (InputBuffer.Size > LPrevSize) or (ReadFromSource(False, ATimeout, False) > 0);
end;
end;
procedure TIdIOHandler.Write(AStream: TStream; ASize: TIdStreamSize = 0;
AWriteByteCount: Boolean = FALSE);
var
LBuffer: TIdBytes;
LStreamPos: TIdStreamSize;
LBufSize: Integer;
// LBufferingStarted: Boolean;
begin
if ASize < 0 then begin //"-1" All from current position
LStreamPos := AStream.Position;
ASize := AStream.Size - LStreamPos;
//todo is this step required?
AStream.Position := LStreamPos;
end
else if ASize = 0 then begin //"0" ALL
ASize := AStream.Size;
AStream.Position := 0;
end;
//else ">0" number of bytes
// RLebeau 3/19/2006: DO NOT ENABLE WRITE BUFFERING IN THIS METHOD!
//
// When sending large streams, especially with LargeStream enabled,
// this can easily cause "Out of Memory" errors. It is the caller's
// responsibility to enable/disable write buffering as needed before
// calling one of the Write() methods.
//
// Also, forcing write buffering in this method is having major
// impacts on TIdFTP, TIdFTPServer, and TIdHTTPServer.
if AWriteByteCount then begin
if LargeStream then begin
Write(Int64(ASize));
end else begin
{$IFDEF STREAM_SIZE_64}
if ASize > High(Integer) then begin
EIdIOHandlerRequiresLargeStream.Toss(RSRequiresLargeStream);
end;
{$ENDIF}
Write(Integer(ASize));
end;
end;
BeginWork(wmWrite, ASize);
try
SetLength(LBuffer, FSendBufferSize);
while ASize > 0 do begin
LBufSize := IndyMin(ASize, Length(LBuffer));
// Do not use ReadBuffer. Some source streams are real time and will not
// return as much data as we request. Kind of like recv()
// NOTE: We use .Size - size must be supported even if real time
LBufSize := TIdStreamHelper.ReadBytes(AStream, LBuffer, LBufSize);
if LBufSize <= 0 then begin
raise EIdNoDataToRead.Create(RSIdNoDataToRead);
end;
Write(LBuffer, LBufSize);
// RLebeau: DoWork() is called in WriteDirect()
//DoWork(wmWrite, LBufSize);
Dec(ASize, LBufSize);
end;
finally
EndWork(wmWrite);
LBuffer := nil;
end;
end;
procedure TIdIOHandler.ReadBytes(var VBuffer: TIdBytes; AByteCount: Integer; AAppend: Boolean = True);
begin
Assert(FInputBuffer<>nil);
if AByteCount > 0 then begin
// Read from stack until we have enough data
while FInputBuffer.Size < AByteCount do begin
// RLebeau: in case the other party disconnects
// after all of the bytes were transmitted ok.
// No need to throw an exception just yet...
if ReadFromSource(False) > 0 then begin
if FInputBuffer.Size >= AByteCount then begin
Break; // we have enough data now
end;
end;
CheckForDisconnect(True, True);
end;
FInputBuffer.ExtractToBytes(VBuffer, AByteCount, AAppend);
end else if AByteCount < 0 then begin
ReadFromSource(False, ReadTimeout, False);
CheckForDisconnect(True, True);
FInputBuffer.ExtractToBytes(VBuffer, -1, AAppend);
end;
end;
procedure TIdIOHandler.WriteLn(AEncoding: TIdTextEncoding = nil);
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
WriteLn('', AEncoding{$IFDEF STRING_IS_ANSI}, nil{$ENDIF});
end;
procedure TIdIOHandler.WriteLn(const AOut: string;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
begin
// Do as one write so it only makes one call to network
Write(AOut + EOL, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}
);
end;
procedure TIdIOHandler.WriteLnRFC(const AOut: string = '';
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
begin
if TextStartsWith(AOut, '.') then begin {do not localize}
WriteLn('.' + AOut, AByteEncoding {do not localize}
{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}
);
end else begin
WriteLn(AOut, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}
);
end;
end;
function TIdIOHandler.Readable(AMSec: Integer): Boolean;
begin
// In case descendant does not override this or other methods but implements the higher level
// methods
Result := False;
end;
procedure TIdIOHandler.SetHost(const AValue: string);
begin
FHost := AValue;
end;
procedure TIdIOHandler.SetPort(AValue: Integer);
begin
FPort := AValue;
end;
function TIdIOHandler.Connected: Boolean;
begin
CheckForDisconnect(False);
Result :=
(
(
// Set when closed properly. Reflects actual socket state.
(not ClosedGracefully)
// Created on Open. Prior to Open ClosedGracefully is still false.
and (FInputBuffer <> nil)
)
// Buffer must be empty. Even if closed, we are "connected" if we still have
// data
or (not InputBufferIsEmpty)
)
and Opened;
end;
// TODO: move this into IdGlobal.pas
procedure AdjustStreamSize(const AStream: TStream; const ASize: TIdStreamSize);
var
LStreamPos: TIdStreamSize;
begin
LStreamPos := AStream.Position;
AStream.Size := ASize;
// Must reset to original value in cases where size changes position
if AStream.Position <> LStreamPos then begin
AStream.Position := LStreamPos;
end;
end;
procedure TIdIOHandler.ReadStream(AStream: TStream; AByteCount: TIdStreamSize;
AReadUntilDisconnect: Boolean);
var
i: Integer;
LBuf: TIdBytes;
LByteCount, LPos: TIdStreamSize;
{$IFNDEF STREAM_SIZE_64}
LTmp: Int64;
{$ENDIF}
const
cSizeUnknown = -1;
begin
Assert(AStream<>nil);
if (AByteCount = cSizeUnknown) and (not AReadUntilDisconnect) then begin
// Read size from connection
if LargeStream then begin
{$IFDEF STREAM_SIZE_64}
LByteCount := ReadInt64;
{$ELSE}
LTmp := ReadInt64;
if LTmp > MaxInt then begin
EIdIOHandlerStreamDataTooLarge.Toss(RSDataTooLarge);
end;
LByteCount := TIdStreamSize(LTmp);
{$ENDIF}
end else begin
LByteCount := ReadLongInt;
end;
end else begin
LByteCount := AByteCount;
end;
// Presize stream if we know the size - this reduces memory/disk allocations to one time
// Have an option for this? user might not want to presize, eg for int64 files
if LByteCount > -1 then begin
LPos := AStream.Position;
if (High(TIdStreamSize) - LPos) < LByteCount then begin
EIdIOHandlerStreamDataTooLarge.Toss(RSDataTooLarge);
end;
AdjustStreamSize(AStream, LPos + LByteCount);
end;
if (LByteCount <= cSizeUnknown) and (not AReadUntilDisconnect) then begin
AReadUntilDisconnect := True;
end;
if AReadUntilDisconnect then begin
BeginWork(wmRead);
end else begin
BeginWork(wmRead, LByteCount);
end;
try
// If data already exists in the buffer, write it out first.
// should this loop for all data in buffer up to workcount? not just one block?
if FInputBuffer.Size > 0 then begin
if AReadUntilDisconnect then begin
i := FInputBuffer.Size;
end else begin
i := IndyMin(FInputBuffer.Size, LByteCount);
Dec(LByteCount, i);
end;
FInputBuffer.ExtractToStream(AStream, i);
end;
// RLebeau - don't call Connected() here! ReadBytes() already
// does that internally. Calling Connected() here can cause an
// EIdConnClosedGracefully exception that breaks the loop
// prematurely and thus leave unread bytes in the InputBuffer.
// Let the loop catch the exception before exiting...
SetLength(LBuf, RecvBufferSize); // preallocate the buffer
repeat
if AReadUntilDisconnect then begin
i := Length(LBuf);
end else begin
i := IndyMin(LByteCount, Length(LBuf));
if i < 1 then begin
Break;
end;
end;
//TODO: Improve this - dont like the use of the exception handler
//DONE -oAPR: Dont use a string, use a memory buffer or better yet the buffer itself.
try
try
ReadBytes(LBuf, i, False);
except
on E: Exception do begin
// RLebeau - ReadFromSource() inside of ReadBytes()
// could have filled the InputBuffer with more bytes
// than actually requested, so don't extract too
// many bytes here...
i := IndyMin(i, FInputBuffer.Size);
FInputBuffer.ExtractToBytes(LBuf, i, False);
if (E is EIdConnClosedGracefully) and AReadUntilDisconnect then begin
Break;
end else begin
// TODO: check for socket error 10054 when AReadUntilDisconnect is True
raise;
end;
end;
end;
TIdAntiFreezeBase.DoProcess;
finally
if i > 0 then begin
TIdStreamHelper.Write(AStream, LBuf, i);
if not AReadUntilDisconnect then begin
Dec(LByteCount, i);
end;
end;
end;
until False;
finally
EndWork(wmRead);
if AStream.Size > AStream.Position then begin
AStream.Size := AStream.Position;
end;
LBuf := nil;
end;
end;
procedure TIdIOHandler.Discard(AByteCount: Int64);
var
LSize: Integer;
begin
Assert(AByteCount >= 0);
if AByteCount > 0 then
begin
BeginWork(wmRead, AByteCount);
try
repeat
LSize := iif(AByteCount < MaxInt, Integer(AByteCount), MaxInt);
if not InputBufferIsEmpty then begin
LSize := IndyMin(LSize, FInputBuffer.Size);
FInputBuffer.Remove(LSize);
Dec(AByteCount, LSize);
if AByteCount < 1 then begin
Break;
end;
end;
// RLebeau: in case the other party disconnects
// after all of the bytes were transmitted ok.
// No need to throw an exception just yet...
if ReadFromSource(False) < 1 then begin
CheckForDisconnect(True, True);
end;
until False;
finally
EndWork(wmRead);
end;
end;
end;
procedure TIdIOHandler.DiscardAll;
begin
BeginWork(wmRead);
try
// If data already exists in the buffer, discard it first.
FInputBuffer.Clear;
// RLebeau - don't call Connected() here! ReadBytes() already
// does that internally. Calling Connected() here can cause an
// EIdConnClosedGracefully exception that breaks the loop
// prematurely and thus leave unread bytes in the InputBuffer.
// Let the loop catch the exception before exiting...
repeat
//TODO: Improve this - dont like the use of the exception handler
try
if ReadFromSource(False) > 0 then begin
FInputBuffer.Clear;
end else begin;
CheckForDisconnect(True, True);
end;
except
on E: Exception do begin
// RLebeau - ReadFromSource() could have filled the
// InputBuffer with more bytes...
FInputBuffer.Clear;
if E is EIdConnClosedGracefully then begin
Break;
end else begin
raise;
end;
end;
end;
TIdAntiFreezeBase.DoProcess;
until False;
finally
EndWork(wmRead);
end;
end;
procedure TIdIOHandler.RaiseConnClosedGracefully;
begin
(* ************************************************************* //
------ If you receive an exception here, please read. ----------
If this is a SERVER
-------------------
The client has disconnected the socket normally and this exception is used to notify the
server handling code. This exception is normal and will only happen from within the IDE, not
while your program is running as an EXE. If you do not want to see this, add this exception
or EIdSilentException to the IDE options as exceptions not to break on.
From the IDE just hit F9 again and Indy will catch and handle the exception.
Please see the FAQ and help file for possible further information.
The FAQ is at http://www.nevrona.com/Indy/FAQ.html
If this is a CLIENT
-------------------
The server side of this connection has disconnected normaly but your client has attempted
to read or write to the connection. You should trap this error using a try..except.
Please see the help file for possible further information.
// ************************************************************* *)
raise EIdConnClosedGracefully.Create(RSConnectionClosedGracefully);
end;
function TIdIOHandler.InputBufferAsString(AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
begin
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
Result := FInputBuffer.ExtractToString(FInputBuffer.Size, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
function TIdIOHandler.AllData(AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
var
LBytes: Integer;
begin
Result := '';
BeginWork(wmRead);
try
if Connected then
begin
try
try
repeat
LBytes := ReadFromSource(False, 250, False);
until LBytes = 0; // -1 on timeout
finally
if not InputBufferIsEmpty then begin
Result := InputBufferAsString(AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
end;
except end;
end;
finally
EndWork(wmRead);
end;
end;
procedure TIdIOHandler.PerformCapture(const ADest: TObject;
out VLineCount: Integer; const ADelim: string;
AUsesDotTransparency: Boolean; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
);
var
s: string;
LStream: TStream;
LStrings: TStrings;
begin
VLineCount := 0;
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ADestEncoding := iif(ADestEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
LStream := nil;
LStrings := nil;
if ADest is TStrings then begin
LStrings := TStrings(ADest);
end
else if ADest is TStream then begin
LStream := TStream(ADest);
end
else begin
EIdObjectTypeNotSupported.Toss(RSObjectTypeNotSupported);
end;
BeginWork(wmRead);
try
repeat
s := ReadLn(AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
if s = ADelim then begin
Exit;
end;
// S.G. 6/4/2004: All the consumers to protect themselves against memory allocation attacks
if FMaxCapturedLines > 0 then begin
if VLineCount > FMaxCapturedLines then begin
raise EIdMaxCaptureLineExceeded.Create(RSMaximumNumberOfCaptureLineExceeded);
end;
end;
// For RFC retrieves that use dot transparency
// No length check necessary, if only one byte it will be byte x + #0.
if AUsesDotTransparency then begin
if TextStartsWith(s, '..') then begin
Delete(s, 1, 1);
end;
end;
// Write to output
Inc(VLineCount);
if LStrings <> nil then begin
LStrings.Add(s);
end
else if LStream <> nil then begin
WriteStringToStream(LStream, s+EOL, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
until False;
finally
EndWork(wmRead);
end;
end;
function TIdIOHandler.InputLn(const AMask: String = ''; AEcho: Boolean = True;
ATabWidth: Integer = 8; AMaxLineLength: Integer = -1;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; AAnsiEncoding: TIdTextEncoding = nil{$ENDIF}
): String;
var
i: Integer;
LChar: Char;
LTmp: string;
begin
Result := '';
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
AAnsiEncoding := iif(AAnsiEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
if AMaxLineLength < 0 then begin
AMaxLineLength := MaxLineLength;
end;
repeat
LChar := ReadChar(AByteEncoding
{$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF}
);
i := Length(Result);
if i <= AMaxLineLength then begin
case LChar of
BACKSPACE:
begin
if i > 0 then begin
SetLength(Result, i - 1);
if AEcho then begin
Write(BACKSPACE + ' ' + BACKSPACE, AByteEncoding
{$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF}
);
end;
end;
end;
TAB:
begin
if ATabWidth > 0 then begin
i := ATabWidth - (i mod ATabWidth);
LTmp := StringOfChar(' ', i);
Result := Result + LTmp;
if AEcho then begin
Write(LTmp, AByteEncoding
{$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF}
);
end;
end else begin
Result := Result + LChar;
if AEcho then begin
Write(LChar, AByteEncoding
{$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF}
);
end;
end;
end;
LF: ;
CR: ;
#27: ; //ESC - currently not supported
else
Result := Result + LChar;
if AEcho then begin
if Length(AMask) = 0 then begin
Write(LChar, AByteEncoding
{$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF}
);
end else begin
Write(AMask, AByteEncoding
{$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF}
);
end;
end;
end;
end;
until LChar = LF;
// Remove CR trail
i := Length(Result);
while (i > 0) and CharIsInSet(Result, i, EOL) do begin
Dec(i);
end;
SetLength(Result, i);
if AEcho then begin
WriteLn(AByteEncoding);
end;
end;
//TODO: Add a time out (default to infinite) and event to pass data
//TODO: Add a max size argument as well.
//TODO: Add a case insensitive option
function TIdIOHandler.WaitFor(const AString: string; ARemoveFromBuffer: Boolean = True;
AInclusive: Boolean = False; AByteEncoding: TIdTextEncoding = nil;
ATimeout: Integer = IdTimeoutDefault
{$IFDEF STRING_IS_ANSI}; AAnsiEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
var
LBytes: TIdBytes;
LPos: Integer;
begin
Result := '';
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
AAnsiEncoding := iif(AAnsiEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
LBytes := ToBytes(AString, AByteEncoding
{$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF}
);
LPos := 0;
repeat
LPos := InputBuffer.IndexOf(LBytes, LPos);
if LPos <> -1 then begin
if ARemoveFromBuffer and AInclusive then begin
Result := InputBuffer.ExtractToString(LPos+Length(LBytes), AByteEncoding
{$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF}
);
end else begin
Result := InputBuffer.ExtractToString(LPos, AByteEncoding
{$IFDEF STRING_IS_ANSI}, AAnsiEncoding{$ENDIF}
);
if ARemoveFromBuffer then begin
InputBuffer.Remove(Length(LBytes));
end;
if AInclusive then begin
Result := Result + AString;
end;
end;
Exit;
end;
LPos := IndyMax(0, InputBuffer.Size - (Length(LBytes)-1));
ReadFromSource(True, ATimeout, True);
until False;
end;
procedure TIdIOHandler.Capture(ADest: TStream; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
);
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
Capture(ADest, '.', True, AByteEncoding {do not localize}
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
procedure TIdIOHandler.Capture(ADest: TStream; out VLineCount: Integer;
const ADelim: string = '.'; AUsesDotTransparency: Boolean = True;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
);
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
PerformCapture(ADest, VLineCount, ADelim, AUsesDotTransparency, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
procedure TIdIOHandler.Capture(ADest: TStream; ADelim: string;
AUsesDotTransparency: Boolean = True; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
);
var
LLineCount: Integer;
begin
PerformCapture(ADest, LLineCount, '.', AUsesDotTransparency, AByteEncoding {do not localize}
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
procedure TIdIOHandler.Capture(ADest: TStrings; out VLineCount: Integer;
const ADelim: string = '.'; AUsesDotTransparency: Boolean = True;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
);
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
PerformCapture(ADest, VLineCount, ADelim, AUsesDotTransparency, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
procedure TIdIOHandler.Capture(ADest: TStrings; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
);
var
LLineCount: Integer;
begin
PerformCapture(ADest, LLineCount, '.', True, AByteEncoding {do not localize}
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
procedure TIdIOHandler.Capture(ADest: TStrings; const ADelim: string;
AUsesDotTransparency: Boolean = True; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
);
var
LLineCount: Integer;
begin
PerformCapture(ADest, LLineCount, ADelim, AUsesDotTransparency, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end;
procedure TIdIOHandler.InputBufferToStream(AStream: TStream; AByteCount: Integer = -1);
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
FInputBuffer.ExtractToStream(AStream, AByteCount);
end;
function TIdIOHandler.InputBufferIsEmpty: Boolean;
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
Result := FInputBuffer.Size = 0;
end;
procedure TIdIOHandler.Write(const ABuffer: TIdBytes; const ALength: Integer = -1;
const AOffset: Integer = 0);
var
LLength: Integer;
begin
LLength := IndyLength(ABuffer, ALength, AOffset);
if LLength > 0 then begin
if FWriteBuffer = nil then begin
WriteDirect(ABuffer, LLength, AOffset);
end else begin
// Write Buffering is enabled
FWriteBuffer.Write(ABuffer, LLength, AOffset);
if (FWriteBuffer.Size >= WriteBufferThreshold) and (WriteBufferThreshold > 0) then begin
repeat
WriteBufferFlush(WriteBufferThreshold);
until FWriteBuffer.Size < WriteBufferThreshold;
end;
end;
end;
end;
procedure TIdIOHandler.WriteRFCStrings(AStrings: TStrings; AWriteTerminator: Boolean = True;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
var
i: Integer;
begin
AByteEncoding := iif(AByteEncoding, FDefStringEncoding);
{$IFDEF STRING_IS_ANSI}
ASrcEncoding := iif(ASrcEncoding, FDefAnsiEncoding, encOSDefault);
{$ENDIF}
for i := 0 to AStrings.Count - 1 do begin
WriteLnRFC(AStrings[i], AByteEncoding
{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}
);
end;
if AWriteTerminator then begin
WriteLn('.', AByteEncoding
{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}
);
end;
end;
function TIdIOHandler.WriteFile(const AFile: String; AEnableTransferFile: Boolean): Int64;
var
//TODO: There is a way in linux to dump a file to a socket as well. use it.
LStream: TStream;
{$IFDEF WIN32_OR_WIN64}
LOldErrorMode : Integer;
{$ENDIF}
begin
Result := 0;
{$IFDEF WIN32_OR_WIN64}
LOldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
{$ENDIF}
if not FileExists(AFile) then begin
raise EIdFileNotFound.CreateFmt(RSFileNotFound, [AFile]);
end;
LStream := TIdReadFileExclusiveStream.Create(AFile);
try
Write(LStream);
Result := LStream.Size;
finally
FreeAndNil(LStream);
end;
{$IFDEF WIN32_OR_WIN64}
finally
SetErrorMode(LOldErrorMode)
end;
{$ENDIF}
end;
function TIdIOHandler.WriteBufferingActive: Boolean;
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
Result := FWriteBuffer <> nil;
end;
procedure TIdIOHandler.CloseGracefully;
begin
FClosedGracefully := True
end;
procedure TIdIOHandler.InterceptReceive(var VBuffer: TIdBytes);
begin
if Intercept <> nil then begin
Intercept.Receive(VBuffer);
end;
end;
procedure TIdIOHandler.InitComponent;
begin
inherited InitComponent;
FRecvBufferSize := GRecvBufferSizeDefault;
FSendBufferSize := GSendBufferSizeDefault;
FMaxLineLength := IdMaxLineLengthDefault;
FMaxCapturedLines := Id_IOHandler_MaxCapturedLines;
FLargeStream := False;
FReadTimeOut := IdTimeoutDefault;
FInputBuffer := TIdBuffer.Create(BufferRemoveNotify);
FDefStringEncoding := IndyASCIIEncoding;
{$IFDEF STRING_IS_ANSI}
FDefAnsiEncoding := IndyOSDefaultEncoding;
{$ENDIF}
end;
procedure TIdIOHandler.WriteBufferFlush;
begin
WriteBufferFlush(-1);
end;
procedure TIdIOHandler.WriteBufferOpen;
begin
WriteBufferOpen(-1);
end;
procedure TIdIOHandler.WriteDirect(const ABuffer: TIdBytes; const ALength: Integer = -1;
const AOffset: Integer = 0);
var
LTemp: TIdBytes;
LPos: Integer;
LSize: Integer;
LByteCount: Integer;
LLastError: Integer;
begin
// Check if disconnected
CheckForDisconnect(True, True);
if Intercept <> nil then begin
// TODO: pass offset/size parameters to the Intercept
// so that a copy is no longer needed here
LTemp := ToBytes(ABuffer, ALength, AOffset);
Intercept.Send(LTemp);
LSize := Length(LTemp);
LPos := 0;
end else begin
LTemp := ABuffer;
LSize := IndyLength(LTemp, ALength, AOffset);
LPos := AOffset;
end;
while LSize > 0 do
begin
LByteCount := WriteDataToTarget(LTemp, LPos, LSize);
if LByteCount < 0 then
begin
LLastError := CheckForError(LByteCount);
FClosedGracefully := True;
Close;
RaiseError(LLastError);
end;
// TODO - Have a AntiFreeze param which allows the send to be split up so that process
// can be called more. Maybe a prop of the connection, MaxSendSize?
TIdAntiFreezeBase.DoProcess(False);
if LByteCount = 0 then begin
FClosedGracefully := True;
end;
// Check if other side disconnected
CheckForDisconnect;
DoWork(wmWrite, LByteCount);
Inc(LPos, LByteCount);
Dec(LSize, LByteCount);
end;
end;
initialization
finalization
FreeAndNil(GIOHandlerClassList)
end.
|
{====================================================}
{ }
{ EldoS Visual Components }
{ }
{ Copyright (c) 1998-2003, EldoS Corporation }
{ }
{====================================================}
{$include elpack2.inc}
{$ifdef ELPACK_SINGLECOMP}
{$I ElPack.inc}
{$else}
{$ifdef LINUX}
{$I ../ElPack.inc}
{$else}
{$I ..\ElPack.inc}
{$endif}
{$endif}
unit ElDailyTip;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms,
ExtCtrls, ElPopBtn, StdCtrls, ElTools, Graphics, ElBtnCtl, ElStrUtils, ElStrPool,
{$ifdef VCL_6_USED}
Types,
{$endif}
ElXPThemedControl,
{$ifdef ELPACK_USE_STYLEMANAGER}
ElStyleMan,
{$endif}
TypInfo,
ElHTMLLbl,
HTMLRender,
ElCheckCtl,
ElCLabel;
type
TElDailyTipForm = class(TForm)
OkBtn : TElPopupButton;
NextBtn : TElPopupButton;
Panel1 : TPanel;
Panel2 : TPanel;
Image1 : TImage;
Panel3 : TPanel;
Panel4 : TPanel;
Label1 : TLabel;
Panel5 : TPanel;
TipNumLabel : TLabel;
TipText: TElHTMLLabel;
NextTimeCB: TElCheckBox;
procedure NextBtnClick(Sender : TObject);
private
MinNum,
CurNum,
MaxNum : integer;
FStringPool : TElstringPool;
public
{ Public declarations }
end;
TElDailyTipDialog = class(TComponent)
private
FShowNextTime : Boolean;
FStartID : Integer;
FEndID : Integer;
FShowTipNumber : boolean;
FStringPool : TElStringPool;
FIsHTML : boolean;
FOnImageNeeded: TElHTMLImageNeededEvent;
FOnLinkClick: TElHTMLLinkClickEvent;
FLinkColor: TColor;
FLinkStyle: TFontStyles;
procedure SetStringPool(newValue : TElstringPool);
procedure SetStartID(newValue : Integer);
procedure SetEndID(newValue : Integer);
procedure SetIsHTML(newValue : boolean);
protected
FUseXPThemes: Boolean;
{$IFDEF ELPACK_USE_STYLEMANAGER}
FStyleManager: TElStyleManager;
FStyleName: string;
{$endif}
{$ifdef ELPACK_USE_STYLEMANAGER}
procedure SetStyleManager(Value: TElStyleManager);
procedure SetStyleName(const Value: string);
{$endif}
procedure SetLinkColor(newValue : TColor); virtual;
procedure SetLinkStyle(newValue : TFontStyles); virtual;
public
procedure Execute;
constructor Create(AOwner : TComponent); override;
procedure Notification(AComponent : TComponent; operation : TOperation); override;
published
property ShowNextTime : Boolean read FShowNextTime write FShowNextTime;
property StartID : Integer read FStartID write SetStartID default 10001;
property EndID : Integer read FEndID write SetEndID default 10001;
property ShowTipNumber : boolean read FShowTipNumber write FShowTipNumber default true;
property StringPool : TElStringPool read FStringPool write SetStringPool;
property IsHTML : boolean read FIsHTML write SetIsHTML;
property OnImageNeeded: TElHTMLImageNeededEvent read FOnImageNeeded write
FOnImageNeeded;
property OnLinkClick: TElHTMLLinkClickEvent read FOnLinkClick write
FOnLinkClick;
property LinkColor: TColor read FLinkColor write SetLinkColor;
property LinkStyle: TFontStyles read FLinkStyle write SetLinkStyle;
{$ifdef ELPACK_USE_STYLEMANAGER}
property StyleManager: TElStyleManager read FStyleManager write SetStyleManager;
property StyleName: string read FStyleName write SetStyleName;
{$endif}
property UseXPThemes: Boolean read FUseXPThemes write FUseXPThemes default true;
end;
var
ElDailyTipForm : TElDailyTipForm;
implementation
procedure TElDailyTipDialog.SetIsHTML(newValue : boolean);
begin
FIsHTmL := newValue;
end;
procedure TElDailyTipDialog.Notification(AComponent : TComponent; operation : TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = FStringPool then StringPool := nil;
end;
end;
procedure TElDailyTipDialog.SetStringPool(newValue : TElstringPool);
begin
if FStringPool <> newValue then
begin
{$ifdef VCL_5_USED}
if FStringPool <> nil then
if not (csDestroying in FStringPool.ComponentState) then
FStringPool.RemoveFreeNotification(Self);
{$endif}
FStringPool := NewValue;
if FStringPool <> nil then FStringPool.FreeNotification(Self);
end;
end;
constructor TElDailyTipDialog.Create(AOwner : TComponent);
begin
inherited;
FStartID := 10001;
FEndID := 10001;
FShowTipNumber := true;
FUseXPThemes := true;
end; {Create}
procedure TElDailyTipDialog.SetStartID(newValue : Integer);
begin
if (FStartID <> newValue) and (newValue >= 0) then
begin
FStartID := newValue;
end; {if}
end; {SetStartID}
procedure TElDailyTipDialog.SetEndID(newValue : Integer);
begin
if (FEndID <> newValue) and (newValue >= FStartID) then
begin
FEndID := newValue;
end; {if}
end; {SetEndID}
procedure TElDailyTipDialog.Execute;
var i : integer;
PropInfo : PPropInfo;
begin
ElDailyTipForm := TElDailyTipForm.Create(nil);
Randomize;
try
with ElDailyTipForm do
begin
if Assigned(Self.FStringPool) then
begin
MinNum := 0;
MaxNum := Self.FStringPool.Items.Count - 1;
end
else
begin
MinNum := Min(FStartID, FEndID);
MaxNum := Max(FStartID, FEndID);
end;
CurNum := MinNum + Random(MaxNum - MinNum);
TipNumLabel.Caption := Format('Tip #%d', [CurNum - MinNum + 1]);
TipNumLabel.Visible := FShowTipNumber;
if Assigned(Self.FStringPool) then
TipText.Caption := Self.FStringPool.Items[CurNum]
else
TipText.Caption := LoadStr(CurNum);
TipText.IsHTML := IsHTML;
TipText.LinkColor := LinkColor;
TipText.LinkStyle := LinkStyle;
TipText.OnLinkClick := FOnLinkClick;
TipText.OnImageNeeded := FOnImageNeeded;
NextTimeCB.Checked := FShowNextTime;
FStringPool := Self.FStringPool;
{$IFDEF ELPACK_USE_STYLEMANAGER}
for i := 0 to ComponentCount - 1 do
begin
PropInfo := TypInfo.GetPropInfo(Components[i], 'StyleManager');
if PropInfo <> nil then
SetObjectProp(Components[i], PropInfo, Self.StyleManager);
PropInfo := TypInfo.GetPropInfo(Components[i], 'StyleName');
if PropInfo <> nil then
SetStrProp(Components[i], PropInfo, Self.StyleName);
end;
{$ENDIF}
for i := 0 to ComponentCount - 1 do
begin
PropInfo := TypInfo.GetPropInfo(Components[i].ClassInfo, 'UseXPThemes');
if PropInfo <> nil then
SetOrdProp(Components[i], PropInfo, Ord(UseXPThemes));
end;
ShowModal;
FShowNextTime := NextTimeCB.Checked;
end; // with
finally
ElDailyTipForm.Free;
end;
end; {Execute}
procedure TElDailyTipDialog.SetLinkColor(newValue : TColor);
{ Sets data member FLinkColor to newValue. }
begin
if (FLinkColor <> newValue) then
begin
FLinkColor := newValue;
if IsHTML then
begin
FIsHTML := false;
IsHTML := true;
end;
end; { if }
end; { SetLinkColor }
procedure TElDailyTipDialog.SetLinkStyle(newValue : TFontStyles);
{ Sets data member FLinkStyle to newValue. }
begin
if (FLinkStyle <> newValue) then
begin
FLinkStyle := newValue;
if IsHTML then
begin
FIsHTML := false;
IsHTML := true;
end;
end; { if }
end; { SetLinkStyle }
{$ifdef ELPACK_USE_STYLEMANAGER}
procedure TElDailyTipDialog.SetStyleManager(Value: TElStyleManager);
begin
if FStyleManager <> Value then
begin
{$ifdef VCL_5_USED}
if (FStyleManager <> nil) then
if not (csDestroying in FStyleManager.ComponentState) then
FStyleManager.RemoveFreeNotification(Self);
{$endif}
FStyleManager := Value;
if FStyleManager <> nil then
FStyleManager.FreeNotification(Self);
end;
end;
procedure TElDailyTipDialog.SetStyleName(const Value: string);
begin
if FStyleName <> Value then
FStyleName := Value;
end;
{$endif}
{$R *.DFM}
procedure TElDailyTipForm.NextBtnClick(Sender : TObject);
begin
Inc(CurNum);
if CurNum > MaxNum then CurNum := MinNum;
if Assigned(FStringPool) then
TipText.Caption := FStringPool.Items[CurNum]
else
TipText.Caption := LoadStr(CurNum);
TipNumLabel.Caption := Format('Tip #%d', [CurNum - MinNum + 1]);
end;
end.
|
unit doubledragon_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
hd6309,m680x,m6809,nz80,ym_2151,msm5205,main_engine,controls_engine,
gfx_engine,oki6295,rom_engine,pal_engine,sound_engine;
function iniciar_ddragon:boolean;
implementation
const
//Double Dragon
ddragon_rom:array[0..3] of tipo_roms=(
(n:'21j-1-5.26';l:$8000;p:$0;crc:$42045dfd),(n:'21j-2-3.25';l:$8000;p:$8000;crc:$5779705e),
(n:'21j-3.24';l:$8000;p:$10000;crc:$3bdea613),(n:'21j-4-1.23';l:$8000;p:$18000;crc:$728f87b9));
ddragon_sub:tipo_roms=(n:'63701.bin';l:$4000;p:$c000;crc:$f5232d03);
ddragon_snd:tipo_roms=(n:'21j-0-1';l:$8000;p:$8000;crc:$9efa95bb);
ddragon_char:tipo_roms=(n:'21j-5';l:$8000;p:0;crc:$7a8b8db4);
ddragon_tiles:array[0..3] of tipo_roms=(
(n:'21j-8';l:$10000;p:0;crc:$7c435887),(n:'21j-9';l:$10000;p:$10000;crc:$c6640aed),
(n:'21j-i';l:$10000;p:$20000;crc:$5effb0a0),(n:'21j-j';l:$10000;p:$30000;crc:$5fb42e7c));
ddragon_sprites:array[0..7] of tipo_roms=(
(n:'21j-a';l:$10000;p:0;crc:$574face3),(n:'21j-b';l:$10000;p:$10000;crc:$40507a76),
(n:'21j-c';l:$10000;p:$20000;crc:$bb0bc76f),(n:'21j-d';l:$10000;p:$30000;crc:$cb4f231b),
(n:'21j-e';l:$10000;p:$40000;crc:$a0a0c261),(n:'21j-f';l:$10000;p:$50000;crc:$6ba152f6),
(n:'21j-g';l:$10000;p:$60000;crc:$3220a0b6),(n:'21j-h';l:$10000;p:$70000;crc:$65c7517d));
ddragon_adpcm:array[0..1] of tipo_roms=(
(n:'21j-6';l:$10000;p:0;crc:$34755de3),(n:'21j-7';l:$10000;p:$10000;crc:$904de6f8));
//Double Dragon II
ddragon2_rom:array[0..3] of tipo_roms=(
(n:'26a9-04.bin';l:$8000;p:$0;crc:$f2cfc649),(n:'26aa-03.bin';l:$8000;p:$8000;crc:$44dd5d4b),
(n:'26ab-0.bin';l:$8000;p:$10000;crc:$49ddddcd),(n:'26ac-0e.63';l:$8000;p:$18000;crc:$57acad2c));
ddragon2_sub:tipo_roms=(n:'26ae-0.bin';l:$10000;p:$0;crc:$ea437867);
ddragon2_snd:tipo_roms=(n:'26ad-0.bin';l:$8000;p:$0;crc:$75e36cd6);
ddragon2_char:tipo_roms=(n:'26a8-0e.19';l:$10000;p:0;crc:$4e80cd36);
ddragon2_tiles:array[0..1] of tipo_roms=(
(n:'26j4-0.bin';l:$20000;p:0;crc:$a8c93e76),(n:'26j5-0.bin';l:$20000;p:$20000;crc:$ee555237));
ddragon2_sprites:array[0..5] of tipo_roms=(
(n:'26j0-0.bin';l:$20000;p:0;crc:$db309c84),(n:'26j1-0.bin';l:$20000;p:$20000;crc:$c3081e0c),
(n:'26af-0.bin';l:$20000;p:$40000;crc:$3a615aad),(n:'26j2-0.bin';l:$20000;p:$60000;crc:$589564ae),
(n:'26j3-0.bin';l:$20000;p:$80000;crc:$daf040d6),(n:'26a10-0.bin';l:$20000;p:$a0000;crc:$6d16d889));
ddragon2_adpcm:array[0..1] of tipo_roms=(
(n:'26j6-0.bin';l:$20000;p:0;crc:$a84b2a29),(n:'26j7-0.bin';l:$20000;p:$20000;crc:$bc6a48d5));
//Dip
ddragon_dip_a:array [0..4] of def_dip=(
(mask:$7;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$1;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(dip_val:$3;dip_name:'1C 5C'),(),(),(),(),(),(),(),())),
(mask:$38;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$8;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$38;dip_name:'1C 1C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 5C'),(),(),(),(),(),(),(),())),
(mask:$40;name:'Cabinet';number:2;dip:((dip_val:$40;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Flip Screen';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
ddragon_dip_b:array [0..4] of def_dip=(
(mask:$3;name:'Difficulty';number:4;dip:((dip_val:$1;dip_name:'Easy'),(dip_val:$3;dip_name:'Medium'),(dip_val:$2;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$4;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$10;dip_name:'20k'),(dip_val:$00;dip_name:'40k'),(dip_val:$30;dip_name:'30k 60k+'),(dip_val:$20;dip_name:'20k 80k+'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Lives';number:4;dip:((dip_val:$c0;dip_name:'2'),(dip_val:$80;dip_name:'3'),(dip_val:$40;dip_name:'4'),(dip_val:$0;dip_name:'Infinite'),(),(),(),(),(),(),(),(),(),(),(),())),());
ddragon2_dip_b:array [0..5] of def_dip=(
(mask:$3;name:'Difficulty';number:4;dip:((dip_val:$1;dip_name:'Easy'),(dip_val:$3;dip_name:'Medium'),(dip_val:$2;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$4;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Hurricane Kick';number:2;dip:((dip_val:$0;dip_name:'Easy'),(dip_val:$8;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Timer';number:4;dip:((dip_val:$0;dip_name:'60'),(dip_val:$10;dip_name:'65'),(dip_val:$30;dip_name:'70'),(dip_val:$20;dip_name:'80'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Lives';number:4;dip:((dip_val:$c0;dip_name:'1'),(dip_val:$80;dip_name:'2'),(dip_val:$40;dip_name:'3'),(dip_val:$0;dip_name:'4'),(),(),(),(),(),(),(),(),(),(),(),())),());
CPU_SYNC=4;
var
rom:array[0..5,0..$3fff] of byte;
tipo_video,fg_mask,banco_rom,soundlatch,dd_sub_port:byte;
scroll_x,scroll_y:word;
adpcm_mem:array[0..$1ffff] of byte;
adpcm_data:array[0..1] of byte;
adpcm_pos,adpcm_end:array[0..1] of dword;
ddragon_scanline:array[0..271] of word;
adpcm_ch,adpcm_idle:array [0..1] of boolean;
procedure update_video_ddragon;
var
x,y,color,f,nchar,pos:word;
atrib:byte;
procedure draw_sprites;
var
size,x,y,nchar:word;
f,color,atrib:byte;
flipx,flipy:boolean;
begin
for f:=0 to $3f do begin
atrib:=memoria[$2801+(f*5)];
if (atrib and $80)<>0 then begin // visible
x:=240-memoria[$2804+(f*5)]+((atrib and 2) shl 7);
y:=240-memoria[$2800+(f*5)]+ ((atrib and 1) shl 8);
size:=(atrib and $30) shr 4;
flipx:=(atrib and 8)<>0;
flipy:=(atrib and 4)<>0;
if tipo_video<>0 then begin
color:=((memoria[$2802+(f*5)] shr 5) shl 4)+$80;
nchar:=memoria[$2803+(f*5)]+((memoria[$2802+(f*5)] and $1f) shl 8);
end else begin
color:=(((memoria[$2802+(f*5)] shr 4) and $07) shl 4)+$80;
nchar:=memoria[$2803+(f*5)]+((memoria[$2802+(f*5)] and $0f) shl 8);
end;
nchar:=nchar and not(size);
case size of
0:begin // normal
put_gfx_sprite(nchar,color,flipx,flipy,2);
actualiza_gfx_sprite(x,y,4,2);
end;
1:begin // double y
put_gfx_sprite_diff(nchar,color,flipx,flipy,2,0,0);
put_gfx_sprite_diff(nchar+1,color,flipx,flipy,2,0,16);
actualiza_gfx_sprite_size(x,y-16,4,16,32);
end;
2:begin // double x
put_gfx_sprite_diff(nchar,color,flipx,flipy,2,0,0);
put_gfx_sprite_diff(nchar+1,color,flipx,flipy,2,16,0);
actualiza_gfx_sprite_size(x-16,y,4,32,16);
end;
3:begin
put_gfx_sprite_diff(nchar,color,flipx,flipy,2,0,0);
put_gfx_sprite_diff(nchar+1,color,flipx,flipy,2,16,0);
put_gfx_sprite_diff(nchar+2,color,flipx,flipy,2,0,16);
put_gfx_sprite_diff(nchar+3,color,flipx,flipy,2,16,16);
actualiza_gfx_sprite_size(x-16,y-16,4,32,32);
end;
end;
end; //visible
end; //for
end;
begin
for f:=$0 to $3ff do begin
x:=f mod 32;
y:=f div 32;
//background
pos:=(x and $0f)+((y and $0f) shl 4)+((x and $10) shl 4)+((y and $10) shl 5);
atrib:=memoria[(pos*2)+$3000];
color:=(atrib and $38) shr 3;
if (gfx[1].buffer[pos] or buffer_color[color+8]) then begin
nchar:=memoria[(pos*2)+$3001]+((atrib and $7) shl 8);
put_gfx_flip(x*16,y*16,nchar,$100+(color shl 4),2,1,(atrib and $40)<>0,(atrib and $80)<>0);
gfx[1].buffer[pos]:=false;
end;
//foreground
atrib:=memoria[$1800+(f*2)];
color:=(atrib and $e0) shr 5;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
nchar:=memoria[$1801+(f*2)]+((atrib and fg_mask) shl 8);
put_gfx_trans(x*8,y*8,nchar,color shl 4,1,0);
gfx[0].buffer[f]:=false;
end;
end;
scroll_x_y(2,4,scroll_x,scroll_y);
draw_sprites;
actualiza_trozo(0,0,256,256,1,0,0,256,256,4);
actualiza_trozo_final(0,8,256,240,4);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
end;
procedure eventos_ddragon;
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.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);
if arcade_input.but2[0] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
//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.coin[0] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40);
if arcade_input.coin[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80);
if arcade_input.but2[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4);
end;
end;
procedure ddragon_principal;
var
f,l:word;
frame_m,frame_s,frame_snd:single;
h:byte;
begin
init_controls(false,false,false,true);
frame_m:=hd6309_0.tframes;
frame_s:=m6800_0.tframes;
frame_snd:=m6809_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 271 do begin
for h:=1 to CPU_SYNC do begin
//main
hd6309_0.run(frame_m);
frame_m:=frame_m+hd6309_0.tframes-hd6309_0.contador;
//sub
m6800_0.run(frame_s);
frame_s:=frame_s+m6800_0.tframes-m6800_0.contador;
//snd
m6809_0.run(frame_snd);
frame_snd:=frame_snd+m6809_0.tframes-m6809_0.contador;
end;
//video
case ddragon_scanline[f] of
$8:marcade.in2:=marcade.in2 and $f7;
$f8:begin
marcade.in2:=marcade.in2 or 8;
hd6309_0.change_nmi(ASSERT_LINE);
update_video_ddragon;
end;
end;
if f<>0 then l:=f-1 else l:=271;
if (((ddragon_scanline[l] and $8)=0) and ((ddragon_scanline[f] and $8)<>0)) then hd6309_0.change_firq(ASSERT_LINE);
end;
eventos_ddragon;
video_sync;
end;
end;
procedure cambiar_color(pos:word);
var
tmp_color:byte;
color:tcolor;
begin
tmp_color:=buffer_paleta[pos];
color.r:=pal4bit(tmp_color);
color.g:=pal4bit(tmp_color shr 4);
tmp_color:=buffer_paleta[pos+$200];
color.b:=pal4bit(tmp_color);
set_pal_color(color,pos);
case pos of
0..127:buffer_color[pos shr 4]:=true;
256..383:buffer_color[((pos shr 4) and $7)+8]:=true;
end;
end;
function ddragon_getbyte(direccion:word):byte;
begin
case direccion of
$0..$fff,$1800..$1fff,$2800..$37ff,$8000..$ffff:ddragon_getbyte:=memoria[direccion];
$1000..$13ff:ddragon_getbyte:=buffer_paleta[direccion and $3ff];
$2000..$27ff:if ((m6800_0.get_halt<>CLEAR_LINE) or (m6800_0.get_reset<>CLEAR_LINE)) then ddragon_getbyte:=mem_misc[$8000+(direccion and $1ff)]
else ddragon_getbyte:=$ff;
$3800:ddragon_getbyte:=marcade.in0;
$3801:ddragon_getbyte:=marcade.in1;
$3802:ddragon_getbyte:=marcade.in2 or ($10*byte(not(((m6800_0.get_halt<>CLEAR_LINE) or (m6800_0.get_reset<>CLEAR_LINE)))));
$3803:ddragon_getbyte:=marcade.dswa;
$3804:ddragon_getbyte:=marcade.dswb;
$380b:begin
hd6309_0.change_nmi(CLEAR_LINE);
ddragon_getbyte:=$ff;
end;
$380c:begin
hd6309_0.change_firq(CLEAR_LINE);
ddragon_getbyte:=$ff;
end;
$380d:begin
hd6309_0.change_irq(CLEAR_LINE);
ddragon_getbyte:=$ff;
end;
$380e:begin
m6809_0.change_irq(ASSERT_LINE);
ddragon_getbyte:=soundlatch;
end;
$380f:begin
m6800_0.change_nmi(ASSERT_LINE);
ddragon_getbyte:=$ff;
end;
$4000..$7fff:ddragon_getbyte:=rom[banco_rom,direccion and $3fff];
end;
end;
procedure ddragon_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$fff,$2800..$2fff:memoria[direccion]:=valor;
$1000..$13ff:if buffer_paleta[direccion and $3ff]<>valor then begin
buffer_paleta[direccion and $3ff]:=valor;
cambiar_color(direccion and $1ff);
end;
$1800..$1fff:if memoria[direccion]<>valor then begin
gfx[0].buffer[(direccion and $7ff) shr 1]:=true;
memoria[direccion]:=valor;
end;
$2000..$27ff:if ((m6800_0.get_halt<>CLEAR_LINE) or (m6800_0.get_reset<>CLEAR_LINE)) then mem_misc[$8000+(direccion and $1ff)]:=valor;
$3000..$37ff:if memoria[direccion]<>valor then begin
gfx[1].buffer[(direccion and $7ff) shr 1]:=true;
memoria[direccion]:=valor;
end;
$3808:begin
scroll_x:=(scroll_x and $ff) or ((valor and $1) shl 8);
scroll_y:=(scroll_y and $ff) or ((valor and $2) shl 7);
main_screen.flip_main_screen:=(valor and 4)=0;
if (valor and $8)<>0 then m6800_0.change_reset(CLEAR_LINE)
else m6800_0.change_reset(ASSERT_LINE);
if (valor and $10)<>0 then m6800_0.change_halt(ASSERT_LINE)
else m6800_0.change_halt(CLEAR_LINE);
banco_rom:=(valor and $e0) shr 5;
end;
$3809:scroll_x:=(scroll_x and $100) or valor;
$380a:scroll_y:=(scroll_y and $100) or valor;
$380b:hd6309_0.change_nmi(CLEAR_LINE);
$380c:hd6309_0.change_firq(CLEAR_LINE);
$380d:hd6309_0.change_irq(CLEAR_LINE);
$380e:begin
soundlatch:=valor;
m6809_0.change_irq(ASSERT_LINE);
end;
$380f:m6800_0.change_nmi(ASSERT_LINE);
$4000..$ffff:; //ROM
end;
end;
function ddragon_sub_getbyte(direccion:word):byte;
begin
case direccion of
$0..$1e:ddragon_sub_getbyte:=0;
$1f..$fff,$8000..$81ff,$c000..$ffff:ddragon_sub_getbyte:=mem_misc[direccion];
end;
end;
procedure ddragon_sub_putbyte(direccion:word;valor:byte);
begin
case direccion of
$17:begin
if (valor and 1)=0 then m6800_0.change_nmi(CLEAR_LINE);
if (((valor and 2)<>0) and ((dd_sub_port and $2)<>0)) then hd6309_0.change_irq(ASSERT_LINE);
dd_sub_port:=valor;
end;
$1f..$fff,$8000..$81ff:mem_misc[direccion]:=valor;
$c000..$ffff:; //ROM
end;
end;
function ddragon_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$fff,$8000..$ffff:ddragon_snd_getbyte:=mem_snd[direccion];
$1000:begin
ddragon_snd_getbyte:=soundlatch;
m6809_0.change_irq(CLEAR_LINE);
end;
$1800:ddragon_snd_getbyte:=byte(adpcm_idle[0]) or (byte(adpcm_idle[1]) shl 1);
$2801:ddragon_snd_getbyte:=ym2151_0.status;
end;
end;
procedure ddragon_snd_putbyte(direccion:word;valor:byte);
var
adpcm_chip:byte;
begin
case direccion of
0..$fff:mem_snd[direccion]:=valor;
$2800:ym2151_0.reg(valor);
$2801:ym2151_0.write(valor);
$3800..$3807:begin
adpcm_chip:=direccion and $1;
case ((direccion and $7) shr 1) of
3:begin
adpcm_idle[adpcm_chip]:=true;
if adpcm_chip=0 then msm5205_0.reset_w(1)
else msm5205_1.reset_w(1);
end;
2:adpcm_pos[adpcm_chip]:=(valor and $7f)*$200;
1:adpcm_end[adpcm_chip]:=(valor and $7f)*$200;
0:begin
adpcm_idle[adpcm_chip]:=false;
if adpcm_chip=0 then msm5205_0.reset_w(0)
else msm5205_1.reset_w(0);
end;
end;
end;
$8000..$ffff:; //ROM
end;
end;
procedure ym2151_snd_irq(irqstate:byte);
begin
m6809_0.change_firq(irqstate);
end;
procedure snd_adpcm0;
begin
if ((adpcm_pos[0]>=adpcm_end[0]) or (adpcm_pos[0]>=$10000)) then begin
adpcm_idle[0]:=true;
msm5205_0.reset_w(1);
end else if not(adpcm_ch[0]) then begin
msm5205_0.data_w(adpcm_data[0] and $0f);
adpcm_ch[0]:=true;
end else begin
adpcm_ch[0]:=false;
adpcm_data[0]:=adpcm_mem[adpcm_pos[0]];
adpcm_pos[0]:=(adpcm_pos[0]+1) and $ffff;
msm5205_0.data_w(adpcm_data[0] shr 4);
end;
end;
procedure snd_adpcm1;
begin
if ((adpcm_pos[1]>=adpcm_end[1]) or (adpcm_pos[1]>=$10000)) then begin
adpcm_idle[1]:=true;
msm5205_1.reset_w(1);
end else if not(adpcm_ch[1]) then begin
msm5205_1.data_w(adpcm_data[1] and $0f);
adpcm_ch[1]:=true;
end else begin
adpcm_ch[1]:=false;
adpcm_data[1]:=adpcm_mem[adpcm_pos[1]+$10000];
adpcm_pos[1]:=(adpcm_pos[1]+1) and $ffff;
msm5205_1.data_w(adpcm_data[1] shr 4);
end;
end;
procedure ddragon_sound_update;
begin
ym2151_0.update;
end;
//Double Dragon II
procedure ddragon2_principal;
var
f,l:word;
frame_m,frame_s,frame_snd:single;
h:byte;
begin
init_controls(false,false,false,true);
frame_m:=hd6309_0.tframes;
frame_s:=z80_0.tframes;
frame_snd:=z80_1.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 271 do begin
for h:=1 to CPU_SYNC do begin
//main
hd6309_0.run(frame_m);
frame_m:=frame_m+hd6309_0.tframes-hd6309_0.contador;
//sub
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
//snd
z80_1.run(frame_snd);
frame_snd:=frame_snd+z80_1.tframes-z80_1.contador;
end;
//video
case ddragon_scanline[f] of
$8:marcade.in2:=marcade.in2 and $f7;
$f8:begin
hd6309_0.change_nmi(ASSERT_LINE);
update_video_ddragon;
marcade.in2:=marcade.in2 or 8;
end;
end;
if f<>0 then l:=f-1 else l:=271;
if (((ddragon_scanline[l] and $8)=0) and ((ddragon_scanline[f] and $8)<>0)) then hd6309_0.change_firq(ASSERT_LINE);
end;
eventos_ddragon;
video_sync;
end;
end;
function ddragon2_getbyte(direccion:word):byte;
begin
case direccion of
$0..$1fff,$2800..$37ff,$8000..$ffff:ddragon2_getbyte:=memoria[direccion];
$2000..$27ff:if ((z80_0.get_halt<>CLEAR_LINE) or (z80_0.get_reset<>CLEAR_LINE)) then ddragon2_getbyte:=mem_misc[$c000+(direccion and $1ff)]
else ddragon2_getbyte:=$ff;
$3800:ddragon2_getbyte:=marcade.in0;
$3801:ddragon2_getbyte:=marcade.in1;
$3802:ddragon2_getbyte:=marcade.in2 or $10*byte(not(((z80_0.get_halt<>CLEAR_LINE) or (z80_0.get_reset<>CLEAR_LINE))));
$3803:ddragon2_getbyte:=marcade.dswa;
$3804:ddragon2_getbyte:=marcade.dswb;
$380b:begin
hd6309_0.change_nmi(CLEAR_LINE);
ddragon2_getbyte:=$ff;
end;
$380c:begin
hd6309_0.change_firq(CLEAR_LINE);
ddragon2_getbyte:=$ff;
end;
$380d:begin
hd6309_0.change_irq(CLEAR_LINE);
ddragon2_getbyte:=$ff;
end;
$380e:begin
z80_1.change_nmi(ASSERT_LINE);
ddragon2_getbyte:=soundlatch;
end;
$380f:begin
z80_0.change_nmi(ASSERT_LINE);
ddragon2_getbyte:=$ff;
end;
$3c00..$3fff:ddragon2_getbyte:=buffer_paleta[direccion and $3ff];
$4000..$7fff:ddragon2_getbyte:=rom[banco_rom,direccion and $3fff];
end;
end;
procedure ddragon2_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$17ff,$2800..$2fff:memoria[direccion]:=valor;
$1800..$1fff:if memoria[direccion]<>valor then begin
gfx[0].buffer[(direccion and $7ff) shr 1]:=true;
memoria[direccion]:=valor;
end;
$2000..$27ff:if ((z80_0.get_halt<>CLEAR_LINE) or (z80_0.get_reset<>CLEAR_LINE)) then mem_misc[$c000+(direccion and $1ff)]:=valor;
$3000..$37ff:if memoria[direccion]<>valor then begin
gfx[1].buffer[(direccion and $7ff) shr 1]:=true;
memoria[direccion]:=valor;
end;
$3808:begin
scroll_x:=(scroll_x and $ff) or ((valor and $1) shl 8);
scroll_y:=(scroll_y and $ff) or ((valor and $2) shl 7);
main_screen.flip_main_screen:=(valor and 4)=0;
if (valor and $8)<>0 then z80_0.change_reset(CLEAR_LINE)
else z80_0.change_reset(ASSERT_LINE);
if (valor and $10)<>0 then z80_0.change_halt(ASSERT_LINE)
else z80_0.change_halt(CLEAR_LINE);
banco_rom:=(valor and $e0) shr 5;
end;
$3809:scroll_x:=(scroll_x and $100) or valor;
$380a:scroll_y:=(scroll_y and $100) or valor;
$380b:hd6309_0.change_nmi(CLEAR_LINE);
$380c:hd6309_0.change_firq(CLEAR_LINE);
$380d:hd6309_0.change_irq(CLEAR_LINE);
$380e:begin
soundlatch:=valor;
z80_1.change_nmi(ASSERT_LINE);
end;
$380f:z80_0.change_nmi(ASSERT_LINE);
$3c00..$3fff:if buffer_paleta[direccion and $3ff]<>valor then begin
buffer_paleta[direccion and $3ff]:=valor;
cambiar_color(direccion and $1ff);
end;
$4000..$ffff:; //ROM
end;
end;
function ddragon2_sub_getbyte(direccion:word):byte;
begin
if direccion<$c400 then ddragon2_sub_getbyte:=mem_misc[direccion];
end;
procedure ddragon2_sub_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$bfff:; //ROM
$c000..$c3ff:mem_misc[direccion]:=valor;
$d000:z80_0.change_nmi(CLEAR_LINE);
$e000:hd6309_0.change_irq(ASSERT_LINE);
end;
end;
function ddragon2_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$87ff:ddragon2_snd_getbyte:=mem_snd[direccion];
$8801:ddragon2_snd_getbyte:=ym2151_0.status;
$9800:ddragon2_snd_getbyte:=oki_6295_0.read;
$a000:begin
ddragon2_snd_getbyte:=soundlatch;
z80_1.change_nmi(CLEAR_LINE);
end;
end;
end;
procedure ddragon2_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7fff:; //ROM
$8000..$87ff:mem_snd[direccion]:=valor;
$8800:ym2151_0.reg(valor);
$8801:ym2151_0.write(valor);
$9800:oki_6295_0.write(valor);
end;
end;
procedure ym2151_snd_irq_dd2(irqstate:byte);
begin
z80_1.change_irq(irqstate);
end;
procedure dd2_sound_update;
begin
ym2151_0.update;
oki_6295_0.update;
end;
//Main
procedure reset_ddragon;
begin
hd6309_0.reset;
ym2151_0.reset;
case main_vars.tipo_maquina of
92,247:begin
m6800_0.reset;
m6809_0.reset;
msm5205_0.reset;
msm5205_1.reset;
end;
96:begin
z80_0.reset;
z80_1.reset;
oki_6295_0.reset;
end;
end;
reset_audio;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$e7;
soundlatch:=0;
banco_rom:=0;
dd_sub_port:=0;
scroll_x:=0;
scroll_y:=0;
adpcm_idle[0]:=false;
adpcm_idle[1]:=false;
adpcm_ch[0]:=true;
adpcm_ch[1]:=true;
adpcm_data[0]:=0;
adpcm_data[1]:=0;
end;
function iniciar_ddragon:boolean;
var
f:word;
memoria_temp:array[0..$bffff] of byte;
const
pc_x:array[0..7] of dword=(1, 0, 8*8+1, 8*8+0, 16*8+1, 16*8+0, 24*8+1, 24*8+0);
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);
procedure extract_chars(num:word);
begin
init_gfx(0,8,8,num);
gfx[0].trans[0]:=true;
gfx_set_desc_data(4,0,32*8,0,2,4,6);
convert_gfx(0,0,@memoria_temp,@pc_x,@pt_y,false,false);
end;
procedure extract_tiles(num:word);
begin
init_gfx(1,16,16,num);
gfx_set_desc_data(4,0,64*8,$20000*8+0,$20000*8+4,0,4);
convert_gfx(1,0,@memoria_temp,@pt_x,@pt_y,false,false);
end;
procedure extract_sprites(num:word;pos:byte);
begin
init_gfx(2,16,16,num);
gfx[2].trans[0]:=true;
gfx_set_desc_data(4,0,64*8,pos*$10000*8+0,pos*$10000*8+4,0,4);
convert_gfx(2,0,@memoria_temp,@pt_x,@pt_y,false,false);
end;
begin
case main_vars.tipo_maquina of
92,247:llamadas_maquina.bucle_general:=ddragon_principal;
96:llamadas_maquina.bucle_general:=ddragon2_principal;
end;
llamadas_maquina.reset:=reset_ddragon;
llamadas_maquina.fps_max:=6000000/384/272;
iniciar_ddragon:=false;
iniciar_audio(false);
screen_init(1,256,256,true);
screen_init(2,512,512);
screen_mod_scroll(2,512,256,511,512,256,511);
screen_init(4,512,512,false,true);
iniciar_video(256,240);
case main_vars.tipo_maquina of
92,247:begin
//Main CPU
hd6309_0:=cpu_hd6309.create(12000000,272*CPU_SYNC,TCPU_HD6309);
hd6309_0.change_ram_calls(ddragon_getbyte,ddragon_putbyte);
//Sub CPU
m6800_0:=cpu_m6800.create(6000000+(6000000*byte(main_vars.tipo_maquina=247)),272*CPU_SYNC,TCPU_HD63701);
m6800_0.change_ram_calls(ddragon_sub_getbyte,ddragon_sub_putbyte);
//Sound CPU
m6809_0:=cpu_m6809.Create(1500000,272*CPU_SYNC,TCPU_M6809);
m6809_0.change_ram_calls(ddragon_snd_getbyte,ddragon_snd_putbyte);
m6809_0.init_sound(ddragon_sound_update);
//Sound Chips
ym2151_0:=ym2151_chip.create(3579545);
ym2151_0.change_irq_func(ym2151_snd_irq);
msm5205_0:=MSM5205_chip.create(375000,MSM5205_S48_4B,1,snd_adpcm0);
msm5205_1:=MSM5205_chip.create(375000,MSM5205_S48_4B,1,snd_adpcm1);
//Main roms
if not(roms_load(@memoria_temp,ddragon_rom)) then exit;
//Pongo las ROMs en su banco
copymemory(@memoria[$8000],@memoria_temp,$8000);
for f:=0 to 5 do copymemory(@rom[f,0],@memoria_temp[$8000+(f*$4000)],$4000);
//Sub roms
if not(roms_load(@mem_misc,ddragon_sub)) then exit;
//Sound roms
if not(roms_load(@mem_snd,ddragon_snd)) then exit;
if not(roms_load(@adpcm_mem,ddragon_adpcm)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,ddragon_char)) then exit;
extract_chars($400);
//convertir tiles
if not(roms_load(@memoria_temp,ddragon_tiles)) then exit;
extract_tiles($800);
//convertir sprites
if not(roms_load(@memoria_temp,ddragon_sprites)) then exit;
extract_sprites($1000,4);
tipo_video:=0;
fg_mask:=$3;
//DIP
marcade.dswa:=$ff;
marcade.dswb:=$ff;
marcade.dswa_val:=@ddragon_dip_a;
marcade.dswb_val:=@ddragon_dip_b;
end;
96:begin
//Main CPU
hd6309_0:=cpu_hd6309.create(12000000,272*CPU_SYNC,TCPU_HD6309);
hd6309_0.change_ram_calls(ddragon2_getbyte,ddragon2_putbyte);
//Sub CPU
z80_0:=cpu_z80.create(4000000,272*CPU_SYNC);
z80_0.change_ram_calls(ddragon2_sub_getbyte,ddragon2_sub_putbyte);
//Sound CPU
z80_1:=cpu_z80.create(3579545,272*CPU_SYNC);
z80_1.change_ram_calls(ddragon2_snd_getbyte,ddragon2_snd_putbyte);
z80_1.init_sound(dd2_sound_update);
//Sound Chips
ym2151_0:=ym2151_chip.create(3579545);
ym2151_0.change_irq_func(ym2151_snd_irq_dd2);
oki_6295_0:=snd_okim6295.Create(1056000,OKIM6295_PIN7_HIGH);
//Cargar ADPCM ROMS
if not(roms_load(oki_6295_0.get_rom_addr,ddragon2_adpcm)) then exit;
//Main roms
if not(roms_load(@memoria_temp,ddragon2_rom)) then exit;
//Pongo las ROMs en su banco
copymemory(@memoria[$8000],@memoria_temp,$8000);
for f:=0 to 5 do copymemory(@rom[f,0],@memoria_temp[$8000+(f*$4000)],$4000);
//Sub roms
if not(roms_load(@mem_misc,ddragon2_sub)) then exit;
//Sound roms
if not(roms_load(@mem_snd,ddragon2_snd)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,ddragon2_char)) then exit;
extract_chars($800);
//convertir tiles
if not(roms_load(@memoria_temp,ddragon2_tiles)) then exit;
extract_tiles($800);
//convertir sprites
if not(roms_load(@memoria_temp,ddragon2_sprites)) then exit;
extract_sprites($1800,6);
tipo_video:=1;
fg_mask:=$7;
//DIP
marcade.dswa:=$ff;
marcade.dswb:=$96;
marcade.dswa_val:=@ddragon_dip_a;
marcade.dswb_val:=@ddragon2_dip_b;
end;
end;
//init scanlines
for f:=8 to $ff do ddragon_scanline[f-8]:=f; //08,09,0A,0B,...,FC,FD,FE,FF
for f:=$e8 to $ff do ddragon_scanline[f+$10]:=f+$100; //E8,E9,EA,EB,...,FC,FD,FE,FF
//final
reset_ddragon;
iniciar_ddragon:=true;
end;
end.
|
Unit PointList;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
(*
Simplefy inserting, appending, popping etc when working with TPoints. While
still keeping optimal speed.
*)
{$mode objfpc}{$H+}
{$macro on}
{$modeswitch advancedrecords}
{$inline on}
interface
uses
CoreTypes, Math;
const
LMINSIZE = 1024;
type
TPointList = record
private
_High: Integer;
_Length: Integer;
_Arr: TPointArray;
function Get(Index:Integer): TPoint; Inline;
procedure Put(Index:Integer; const Value: TPoint); Inline;
public
(*
Initalize
*)
procedure Init;
(*
Initalize with your own TPA
*)
procedure InitWith(TPA:TPointArray);
(*
Release the array
*)
procedure Free;
(*
Indexing the array.
*)
property Point[Index : Integer]: TPoint read Get write Put;
(*
Same as initlaize, tho the pourpose is not the same.
*)
procedure Reset; Inline;
(*
Check if we can give it a new size.. It's manly used internally, but can be used elsewere..
Note: NewSize = The highest index. (Not same as the normal SetLength).
*)
procedure CheckResize(NewSize:Integer); Inline;
(*
Check if it's time to give it a new upper size.. Faster then calling CheckResize.
*)
procedure CheckResizeHigh(NewSize:Integer); Inline;
(*
Check if it's time to give it a new lower size.. Faster then calling CheckResize.
*)
procedure CheckResizeLow(NewSize:Integer); Inline;
(*
Returns a copy of the TPA/Array.
*)
function Clone: TPointArray; Inline;
(*
Returns a (partial) copy of the TPA/Array.
*)
procedure CopyTo(var Arr:TPointArray; Start, Stop: Integer); Inline;
(*
Returns the last item
*)
function Peek: TPoint; Inline;
(*
Remove the last item, and return what it was. It also downsizes the array if
possible.
*)
function Pop: TPoint; Inline;
(*
Remove the last item, and return what it was.
*)
function FastPop: TPoint; Inline;
(*
Insert a item at the given position. It resizes the array if needed.
*)
procedure Insert(const Item: TPoint; Index:Integer); Inline;
(*
Appends the item to the last position in the array. Resizes if needed.
*)
procedure Append(const Item: TPoint); Inline;
(*
Appends the item to the last position in the array. Resizes if needed.
*)
procedure Append(const X,Y: Integer); Inline; overload;
(*
Extend the current array with the given TPA.
*)
procedure Extend(const TPA: TPointArray); Inline;
(*
Remove the first item from the lists whos value is `Value`.
*)
procedure Remove(const Item: TPoint); Inline;
(*
Remove the given index from the array.
*)
procedure Delete(const Index: Integer); Inline;
(*
Remove the given indices from the array.
*)
procedure DeleteEx(const Indices: TIntArray); Inline;
(*
Offset each point in the list by X,Y.
*)
procedure Offset(X,Y:Integer); Inline;
(*
Swaps to items of specified indexes.
*)
procedure Swap(Index1, Index2: Integer); Inline;
(*
Check if the array is empty or not.
*)
function IsEmpty: Boolean; Inline;
(*
Check if the array has items or not.
*)
function NotEmpty: Boolean; Inline;
(*
Returns the length of the array including the overhead.
*)
function GetLength: Integer; Inline;
(*
Returns the size, in a way it's the same as `Length(Arr)`.
*)
function GetSize: Integer; Inline;
(*
Returns the highest index, in a way it's the same as `High(Arr)`.
*)
function GetHigh: Integer; Inline;
(*
It sets the overhead length down to the highest index + 1.
It's used before a call to an external function, EG before using: GetTPABounds.
*)
procedure Fit; Inline;
end;
//--------------------------------------------------
implementation
procedure TPointList.Init;
begin
_High := -1;
_Length := LMINSIZE;
SetLength(_Arr, _Length);
end;
procedure TPointList.InitWith(TPA:TPointArray);
begin
_Arr := TPA;
_High := High(_Arr);
_Length := Length(_Arr);
if _Length < LMINSIZE then
begin
_Length := LMINSIZE;
SetLength(_Arr, _Length);
end;
end;
procedure TPointList.Free;
begin
_High := -1;
_Length := 0;
SetLength(_Arr, 0);
end;
procedure TPointList.Reset;
begin
_High := -1;
_Length := LMINSIZE;
SetLength(_Arr, _Length);
end;
procedure TPointList.CheckResize(NewSize:Integer);
begin
if NewSize < LMINSIZE then
begin
if _Length > LMINSIZE then
SetLength(_Arr, LMINSIZE);
_Length := LMINSIZE;
_High := NewSize;
Exit;
end;
_High := NewSize;
case (_High >= _Length) of
False:
if ((_Length div 2) > _High) then
begin
_Length := _Length div 2;
SetLength(_Arr, _Length);
end;
True:
begin
_Length := _Length + _Length;
SetLength(_Arr, _Length);
end;
end;
end;
procedure TPointList.CheckResizeHigh(NewSize:Integer);
begin
_High := NewSize;
if (_High >= _Length) then
begin
_Length := _Length + _Length;
SetLength(_Arr, _Length);
end;
end;
procedure TPointList.CheckResizeLow(NewSize:Integer);
begin
if NewSize < LMINSIZE then
begin
if _Length > LMINSIZE then
SetLength(_Arr, LMINSIZE);
_Length := LMINSIZE;
_High := NewSize;
Exit;
end;
_High := NewSize;
if ((_Length div 2) > _High) then
begin
_Length := _Length div 2;
SetLength(_Arr, _Length);
end;
end;
function TPointList.Clone: TPointArray;
begin
if _High > -1 then
begin
Result := Copy(_Arr, 0, _High + 1);
SetLength(Result, _High+1);
end;
end;
procedure TPointList.CopyTo(var Arr:TPointArray; Start, Stop: Integer);
var i:Integer;
begin
if _High > -1 then
begin
Stop := Min(Stop, _High);
SetLength(Arr, (Stop - Start) + 1);
for i := Start to Stop do
Arr[i-Start] := _Arr[i];
end;
end;
function TPointList.Peek: TPoint;
begin
Result := _Arr[_High];
end;
function TPointList.Pop: TPoint;
begin
Result := _Arr[_High];
Dec(_High);
CheckResizeLow(_High);
end;
function TPointList.FastPop: TPoint;
begin
Result := _Arr[_High];
Dec(_High);
end;
procedure TPointList.Insert(const Item: TPoint; Index:Integer);
var i:Integer;
begin
CheckResizeHigh(_high+1);
if Index > _High then //Remove old crap.. and resize
begin
SetLength(_Arr, _high);
CheckResizeHigh(Index);
end;
for i:=_high-1 downto Index do
_Arr[i+1] := _Arr[i];
_Arr[Index] := Item;
end;
procedure TPointList.Append(const Item: TPoint);
begin
Inc(_High);
CheckResizeHigh(_High);
_Arr[_High] := Item;
end;
procedure TPointList.Append(const X,Y: Integer);
begin
Inc(_High);
CheckResizeHigh(_High);
_Arr[_High].x := X;
_Arr[_High].y := Y;
end;
procedure TPointList.Extend(const TPA: TPointArray);
var
i,_h,h:Integer;
begin
H := Length(TPA);
if (H = 0) then Exit;
_h := _High + 1;
CheckResizeHigh(H + _h);
for i := 0 to H-1 do
_Arr[i+_h] := TPA[i];
end;
procedure TPointList.Remove(const Item: TPoint);
var
i,j:Integer;
hit:Boolean;
begin
if (_High = -1) then Exit;
hit := False;
j := 0;
for i := 0 to _High do
begin
if Not(hit) and (_Arr[i].X = Item.X) and (_Arr[i].Y = Item.Y) then
begin
hit := True;
j := i;
end else if (hit) then
begin
_Arr[j] := _Arr[i];
Inc(j);
end;
end;
if (hit) then
CheckResizeLow(_High - 1);
end;
procedure TPointList.Delete(const Index: Integer);
var
i,j:Integer;
begin
if (_High = -1) then Exit;
if (Index > _High) or (Index < 0) then Exit;
j := 0;
for i:=Index to _High do
begin
if (i=Index) then
begin
j := i;
end else
begin
_Arr[j] := _Arr[i];
Inc(j);
end;
end;
CheckResizeLow(_High - 1);
end;
procedure TPointList.DeleteEx(const Indices: TIntArray);
var
i,len,lo:Integer;
Del:TBoolArray;
begin
if (_High = -1) then Exit;
Lo := _High;
SetLength(Del, _High+1);
for i := 0 to High(Indices) do
if ((Indices[i] > -1) and (Indices[i] <= _High)) then
begin
Del[Indices[i]] := True;
if (Indices[i] < Lo) then Lo := Indices[i];
end;
len := 0;
for i:=Lo to _high do
if not(Del[i]) then
begin
_Arr[len] := _Arr[i];
Inc(len);
end;
SetLength(Del, 0);
CheckResizeLow(_High - (High(Indices)-len));
end;
procedure TPointList.Offset(X,Y:Integer);
var i: Integer;
begin
if (_High = -1) then Exit;
for i:=0 to _High do
begin
_Arr[i].x := _Arr[i].x + X;
_Arr[i].y := _Arr[i].y + Y;
end;
end;
//Private - Use: TPointList.Point[Index];
function TPointList.Get(Index:Integer): TPoint;
begin
Result := _Arr[Index];
end;
//Private - Use: TPointList.Point[Index] := Value;
procedure TPointList.Put(Index:Integer; const Value: TPoint);
begin
_Arr[Index] := Value;
end;
procedure TPointList.Swap(Index1, Index2: Integer);
var Tmp:TPoint;
begin
Tmp := _Arr[Index1];
_Arr[Index1] := _Arr[Index2];
_Arr[Index2] := Tmp;
end;
function TPointList.IsEmpty: Boolean;
begin
Result := _High < 0;
end;
function TPointList.NotEmpty: Boolean;
begin
Result := _High > -1;
end;
function TPointList.GetLength: Integer;
begin
Result := _Length;
end;
function TPointList.GetHigh: Integer;
begin
Result := _High;
end;
function TPointList.GetSize: Integer;
begin
Result := _High + 1;
end;
procedure TPointList.Fit;
begin
_Length := _High + 1;
SetLength(_Arr, _Length);
end;
end.
|
unit Main;
interface
uses
Windows, MMSystem, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
IniFiles, Misc, SensorFrame, DdhAppX, Menus, SyncObjs, ConvTP, ExtCtrls,
NMUDP, DataTypes, StdCtrls;
type
TMainThread = class;
TFormMain = class(TForm)
AppExt: TDdhAppExt;
PopupMenu: TPopupMenu;
pmiClose: TMenuItem;
pmiAbout: TMenuItem;
N1: TMenuItem;
pmiStop: TMenuItem;
pmiStart: TMenuItem;
NMUDP: TNMUDP;
N2: TMenuItem;
pmiShowHide: TMenuItem;
pmiReadOnly: TMenuItem;
PnlCmd: TPanel;
memoEcho: TMemo;
Panel1: TPanel;
edCmd: TEdit;
BtnSend: TButton;
Label1: TLabel;
pmiRestart: TMenuItem;
cbUseCheckSum: TCheckBox;
WatchdogTimer: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure pmiCloseClick(Sender: TObject);
procedure pmiAboutClick(Sender: TObject);
procedure AppExtTrayDefault(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure NMUDPInvalidHost(var handled: Boolean);
procedure NMUDPBufferInvalid(var handled: Boolean;
var Buff: array of Char; var length: Integer);
procedure pmiReadOnlyClick(Sender: TObject);
procedure BtnSendClick(Sender: TObject);
procedure BtnClearClick(Sender: TObject);
procedure pmiRestartClick(Sender: TObject);
procedure cbUseCheckSumClick(Sender: TObject);
procedure ThdTerminated(Sender: TObject);
procedure WatchdogTimerTimer(Sender: TObject);
procedure Start(Sender:TObject);
procedure Stop(Sender:TObject);
private
Period,Rate,PeriodMSec:Double;
Hz:Integer;
NoDataCounter:Integer;
ShowInfo:Boolean;
{ Private declarations }
function Get_FrameSensor(i: Integer): TFrameSensor;
procedure Set_SensorsReadOnly(const Value: Boolean);
procedure NextTimeEventAfter(mSecs:Cardinal);
procedure AddEchoText(const S:String);
procedure SetCaption(S:TCaption);
function ReadCaption:TCaption;
public
{ Public declarations }
Ini:TIniFile;
Thd:TMainThread;
Sensors:TList;
uTimerID:UINT;
OldCnt:Int64;
NotFirst:Boolean;
LogFileName:String;
property FrameSensor[i:Integer]:TFrameSensor read Get_FrameSensor;
property SensorsReadOnly:Boolean write Set_SensorsReadOnly;
end;
TMainThread=class(TThread)
Sensors:TList;
ComPort:String;
ComSpeed:Integer;
DelayBeforeCommandTX:Integer;
DelayBeforeResultRX:Integer;
CS:TCriticalSection;
sCmd,sUserResp:String;
Completed:Boolean;
constructor Create;
procedure Execute;override;
destructor Destroy;override;
private
hCom:THandle;
dcb:TDCB;
function getComChar:Char;
function Query(const Cmd:String):String;
procedure putComString(const Buffer:String);
procedure putComBuf(const Buffer; Length:Cardinal);
procedure ShowUserResp;
end;
var
FormMain: TFormMain;
implementation
{$R *.DFM}
const
dtOneSecond=1/SecsPerDay;
var
SleepIsPrecise:Boolean;
const
Section='config';
procedure FNTimeCallBack(uTimerID,uMessage:UINT;dwUser,dw1,dw2:DWORD);stdcall;
var
Self:TFormMain absolute dwUser;
begin
Self.TimerTimer(Self);
end;
function CheckSumIsValid(const S:String):Boolean;
var
SCS:String;
L:Integer;
begin
Result:=False; L:=Length(S);
if L<3 then exit;
SCS:=StrCheckSum(S[1],L-2);
Result:=(SCS[1]=S[L-1]) and (SCS[2]=S[L]);
end;
function ascii_to_hex(c:Char):Byte;
begin
if c<='9' then Result:=Ord(c)-Ord('0')
else if c<='F' then Result:=10+Ord(c)-Ord('A')
else Result:=10+Ord(c)-Ord('a');
end;
function FromHexStr(const Hex:String; Digits:Integer):Longword;
var
i:Integer;
begin
Result:=0;
for i:=1 to Digits
do Result:=(Result shl 4) or ascii_to_hex(Hex[i]);
end;
function MakeLangId(p,s:Word):Cardinal;
begin
Result:=(s shl 10) or p;
end;
function GetErrorMsg(ErrorId:Cardinal):String;
const
BufSize=1024;
var
lpMsgBuf:PChar;
begin
GetMem(lpMsgBuf,BufSize);
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM,
nil,
ErrorId,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
lpMsgBuf,
BufSize,
nil
);
Result:=lpMsgBuf;
// Free the buffer.
FreeMem(lpMsgBuf,BufSize);
end;
procedure TFormMain.FormCreate(Sender: TObject);
var
i,Count,W,H:Integer;
SF:TFrameSensor;
hSysMenu:Integer;
IniFileName:String;
begin
InitFormattingVariables;
W:=0;
H:=0;
try
if ParamCount=1
then IniFileName:=ExpandFileName(ParamStr(1))
else IniFileName:=Misc.GetModuleFullName+'.ini';
addEchoText(IniFileName);
Ini:=TIniFile.Create(IniFileName);
LogFileName:=ChangeFileExt(IniFileName,'.log');
Sensors:=TList.Create;
Count:=Ini.ReadInteger(Section,'SensorCount',0);
for i:=1 to Count do begin
SF:=TFrameSensor.Create(Self);
SF.Name:='';
SF.LoadFromIniSection(Ini,'Sensor'+IntToStr(i));
Sensors.Add(SF);
SF.Top:=H;
SF.Left:=0;
SF.Parent:=Self;
W:=SF.Width;
Inc(H,SF.Height);
end;
ClientWidth:=W;
if H>ClientHeight then ClientHeight:=H;
pmiReadOnly.Enabled:=Ini.ReadInteger(Section,'ReadOnly',1)=0;
SetCaption(ReadCaption);
hSysMenu:=GetSystemMenu(Handle,False);
EnableMenuItem(hSysMenu,SC_CLOSE,MF_BYCOMMAND or MF_DISABLED or MF_GRAYED);
WriteToLog(LogFileName,LogMsg(Now,'ЗАПУСК Ldr7017'));
if Ini.ReadInteger(Section,'AutoStart',0)<>0 then begin
ShowWindow(Application.Handle,0);
Start(Self);
end
else Visible:=True;
except
Application.MessageBox(
'Исключительная ситуация при инициализации программы опроса датчиков',
'',MB_ICONHAND or MB_OK
);
Application.Terminate;
end;
NextTimeEventAfter(100);
end;
procedure TFormMain.FormDestroy(Sender: TObject);
var
i:Integer;
SF:TFrameSensor;
begin
Stop(Self);
timeKillEvent(uTimerID);
if Sensors<>nil then begin
for i:=0 to Sensors.Count-1 do begin
SF:=TFrameSensor(Sensors[i]);
SF.WriteToIni(Ini);
end;
Sensors.Free;
end;
WriteToLog(LogFileName,LogMsg(Now,'ОСТАНОВ Ldr7017'));
Ini.Free;
end;
procedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose:=Application.Terminated;
end;
procedure TFormMain.pmiCloseClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TFormMain.pmiAboutClick(Sender: TObject);
begin
Application.MessageBox(
'СКУ'#13#13+
'Программа опроса модулей аналогового ввода'#13#13+
'(c) 2000-2002 ООО "Компания Телекомнур"'#13+
'e-mail: test@mail.rb.ru',
'О программе',
MB_ICONINFORMATION or MB_OK or MB_TOPMOST);
end;
procedure TFormMain.AppExtTrayDefault(Sender: TObject);
begin
if Application.Active then Visible:=not Visible else Visible:=TRUE;
SetForegroundWindow(Handle);
end;
procedure TFormMain.Start;
var
i:Integer;
begin
for i:=0 to Sensors.Count-1 do begin
if not FrameSensor[i].Validate then begin
FormMain.Show; exit;
end;
end;
if Thd<>nil then Stop(Self);
Thd:=TMainThread.Create;
Thd.ComPort:=Ini.ReadString(Section,'ComPort','COM1');
Thd.ComSpeed:=Ini.ReadInteger(Section,'ComSpeed',9600);
Thd.DelayBeforeCommandTX:=Ini.ReadInteger(Section,'DelayBeforeCommandTX',10);
Thd.DelayBeforeResultRX:=Ini.ReadInteger(Section,'DelayBeforeResultRX',10);
SleepIsPrecise:=Ini.ReadInteger(Section,'SleepIsPrecise',0)<>0;
Thd.Sensors:=Sensors;
Thd.OnTerminate:=ThdTerminated;
Thd.Resume;
Hz:=Ini.ReadInteger(Section,'Hz',1);
Period:=dtOneSecond/Hz;
Rate:=1/Period;
PeriodMSec:=Period*MSecsPerDay;
SetCaption(ReadCaption+' (частота '+IntToStr(Hz)+' Гц)');
pmiStart.Visible:=False;
pmiStop.Visible:=True;
pmiRestart.Visible:=True;
end;
procedure TFormMain.Stop;
begin
if (Sender<>Thd) and (Thd<>nil) then begin
if not Thd.Completed then begin
Thd.Terminate;
Thd.WaitFor;
TerminateThread(Thd.Handle,0);
end;
Thd.Free;
Thd:=nil;
end;
pmiStart.Visible:=True;
pmiStop.Visible:=False;
pmiRestart.Visible:=False;
end;
procedure TFormMain.WatchdogTimerTimer(Sender: TObject);
begin
// Если более 30-ти секунд нет данных с датчиков, то, возможно, произошел
// сбой - перезапускаем поток опроса датчиков
Inc(NoDataCounter);
if NoDataCounter>=30 then begin
Stop(Self); Start(Self);
NoDataCounter:=0;
// WriteToLog(LogFileName,LogMsg(Now,'АВТОРЕСТАРТ потока опроса'));
end;
ShowInfo:=True; // раз в секунду обновляем экранную информацию
end;
procedure TFormMain.TimerTimer(Sender: TObject);
type
TCharArray=packed array [0..15] of Char;
const
FirstTime:Boolean=True;
var
FS:TFrameSensor;
i,j:Integer;
Cnt:Int64;
fCnt:Double;
Adr:TAddress;
CharBuf:TCharArray;
Buf:TSclRec absolute CharBuf;
NowTime:TDateTime;
ST:TSystemTime;
begin
NowTime:=Now;
fCnt:=Frac(NowTime)*Rate;
i:=Round((1-Frac(fCnt))*0.8*PeriodMSec);
if i=0 then i:=1;
NextTimeEventAfter(i);
Cnt:=Trunc(fCnt);//Round
if NotFirst=False then begin
NotFirst:=True;
OldCnt:=Cnt;
exit;
end
else if OldCnt=Cnt then exit;
OldCnt:=Cnt;
DateTimeToSystemTime(Trunc(NowTime)+Cnt*Period,ST);
with Buf.Time do begin
Year:=ST.wYear-1900;
Month:=ST.wMonth;
Day:=ST.wDay;
Hour:=ST.wHour;
Min:=ST.wMinute;
Sec:=ST.wSecond;
Sec100:=Trunc(ST.wMilliseconds*0.1);
end;
for i:=0 to Sensors.Count-1 do begin
FS:=TFrameSensor(Sensors[i]);
if FS.MeasureCnt<>0 then NoDataCounter:=0;
FS.TimerProc(fCnt/FS.Period);
if ShowInfo then FS.ShowInfo;
end;
ShowInfo:=False;
for i:=0 to Sensors.Count-1 do begin
FS:=TFrameSensor(Sensors[i]);
if not FS.ReadyForOutput then continue;
Buf.Number:=FS.NetNumber;
Buf.p:=FS.X;
for j:=0 to FS.AdrList.Count-1 do begin
Adr:=TAddress(FS.AdrList[j]);
NMUDP.RemoteHost:=Adr.Host;
NMUDP.RemotePort:=Adr.Port;
NMUDP.SendBuffer(CharBuf,SizeOf(CharBuf));
end;
FS.ReadyForOutput:=False;
end;
end;
procedure TFormMain.NMUDPInvalidHost(var handled: Boolean);
begin
handled:=True;
end;
procedure TFormMain.NMUDPBufferInvalid(var handled: Boolean;
var Buff: array of Char; var length: Integer);
begin
handled:=true;
end;
function TFormMain.Get_FrameSensor(i: Integer): TFrameSensor;
begin
Result:=TFrameSensor(Sensors[i]);
end;
procedure TFormMain.pmiReadOnlyClick(Sender: TObject);
var
ReadOnly:Boolean;
begin
ReadOnly:=not pmiReadOnly.Checked or
(Application.MessageBox(
'Вы действительно хотите изменить настройки?',
'Подтверждение',
MB_ICONQUESTION or MB_YESNO or MB_TOPMOST or MB_DEFBUTTON2
)<>ID_YES);
if ReadOnly<>pmiReadOnly.Checked then begin
pmiReadOnly.Checked:=ReadOnly;
SensorsReadOnly:=ReadOnly;
WriteToLog(LogFileName,LogMsg(Now,'ReadOnly:='+IntToStr(Integer(ReadOnly))));
end;
end;
procedure TFormMain.Set_SensorsReadOnly(const Value: Boolean);
var
i:Integer;
begin
for i:=0 to Sensors.Count-1 do FrameSensor[i].Enabled:=not Value;
if Value then begin
PnlCmd.Visible:=False;
Width:=Width-PnlCmd.Width;
end
else begin
Width:=Width+PnlCmd.Width;
PnlCmd.Visible:=True;
end;
end;
procedure TFormMain.NextTimeEventAfter(mSecs: Cardinal);
begin
uTimerID:=timeSetEvent(mSecs,5,@FNTimeCallBack,Cardinal(Self),TIME_ONESHOT);
end;
procedure TFormMain.BtnSendClick(Sender: TObject);
var
sCmd:String;
begin
if Thd<>nil then begin
Thd.CS.Acquire;
sCmd:=Thd.sCmd;
if sCmd='' then begin
sCmd:=edCmd.Text;
if cbUseCheckSum.Checked
then sCmd:=sCmd+StrCheckSum(sCmd[1],Length(sCmd));
Thd.sCmd:=sCmd;
AddEchoText('< '+sCmd+#13#10);
end;
Thd.CS.Release;
end;
end;
procedure TFormMain.AddEchoText(const S: String);
begin
memoEcho.SelStart:=0; memoEcho.SelText:=S; memoEcho.SelLength:=0;
end;
procedure TFormMain.BtnClearClick(Sender: TObject);
begin
memoEcho.Lines.Clear;
edCmd.SetFocus;
end;
procedure TFormMain.pmiRestartClick(Sender: TObject);
begin
if pmiStop.Visible then pmiStop.Click;
if pmiStart.Visible then pmiStart.Click;
end;
procedure TFormMain.SetCaption(S: TCaption);
begin
Caption:=S;
Application.Title:=S;
AppExt.TrayHint:=S;
end;
function TFormMain.ReadCaption: TCaption;
begin
Result:=Ini.ReadString(Section,'AppTitle','Ldr7017');
end;
procedure TFormMain.cbUseCheckSumClick(Sender: TObject);
begin
edCmd.SetFocus;
end;
procedure TFormMain.ThdTerminated(Sender: TObject);
begin
Stop(Thd);
end;
{ TMainThread }
constructor TMainThread.Create;
begin
inherited Create(True);
Priority:=tpTimeCritical;
CS:=TCriticalSection.Create;
end;
destructor TMainThread.Destroy;
begin
CloseHandle(hCom);
CS.Free;
inherited;
end;
procedure TMainThread.Execute;
var
i,err:Integer;
iVal:Integer;
SF:TFrameSensor;
sTmp:String;
Value:Double;
CTO:COMMTIMEOUTS;
NoSensorsOn:Boolean;
ComError:Boolean;
begin
hCom := CreateFile(PChar(ComPort),
GENERIC_READ or GENERIC_WRITE,
0, // comm devices must be opened w/exclusive-access
nil, // no security attrs
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
0, // not overlapped I/O
0 // hTemplate must be NULL for comm devices
);
FillChar(CTO,SizeOf(CTO),0);
CTO.ReadTotalTimeoutConstant:=100;
ComError:=(hCom = INVALID_HANDLE_VALUE) or
not GetCommState(hCom,dcb) or
not SetCommTimeouts(hCom,CTO);
if not ComError then begin
dcb.BaudRate := ComSpeed;
dcb.ByteSize := 8;
dcb.StopBits := ONESTOPBIT;
dcb.Flags := 0;
dcb.Parity := NOPARITY;
end;
if ComError or not SetCommState(hCom,dcb)
then begin
sUserResp:=ComPort+' init error : '+GetErrorMsg(GetLastError());
Synchronize(ShowUserResp);
Completed:=True;
exit;
end;
// EscapeCommFunction(hCom,SETDTR);
i:=0;
NoSensorsOn:=True;
repeat
CS.Acquire;
if sCmd<>'' then begin
sTmp:=sCmd;
CS.Release;
sTmp:=Query(sTmp);
if sTmp<>'' then begin
sUserResp:=sTmp+#13#10;
Synchronize(ShowUserResp);
end;
CS.Acquire;
sCmd:='';
end;
CS.Release;
if i=0 then begin
i:=Sensors.Count;
if NoSensorsOn then Sleep(100);
NoSensorsOn:=True;
end;
Dec(i);
SF:=TFrameSensor(Sensors[i]);
SF.CS.Acquire;
if SF.isSensorOn then begin
NoSensorsOn:=False;
if SF.CounterPoll=0 then begin
SF.CounterPoll:=SF.Period;
sTmp:=SF.QueryCmd;
SF.CS.Release;
sTmp:=Query(sTmp);
// sUserResp:=SF.QueryCmd+'->'+sTmp+#13#10;
// Synchronize(ShowUserResp);
SF.CS.Acquire;
SF.IsErrADCComm:=False;
SF.IsErrADCRange:=False;
SF.IsErrAnalog:=False;
Inc(SF.ShowQueryCnt);
if CheckSumIsValid(sTmp) and (sTmp[1]='>') then begin
Inc(SF.ShowResponseCnt);
if Length(sTmp)=1+4+2 then begin // hexadeciaml format
iVal:=SmallInt(FromHexStr(Copy(sTmp,2,4),4));
Value:=iVal*(1/32768)*SF.PhysScale;
if (iVal=-32768) or (iVal=32767) then err:=-1
else err:=0;
end
else begin
Val(Copy(sTmp,2,Length(sTmp)-3),Value,err);
if err=0 then begin
if (Value<=-SF.PhysScale) or (SF.PhysScale<=Value) then err:=-1;
end;
end;
if err<=0 then begin
SF.IsErrADCRange:=err=-1;
Inc(SF.ShowMeasureCnt);
SF.ShowSumX:=SF.ShowSumX+Value;
end;
if err=0 then begin
Value:=Value*SF.CoeffK+SF.CoeffB;
if Value<SF.Xm then SF.IsErrAnalog:=True
else begin
Inc(SF.MeasureCnt);
SF.SumX:=SF.SumX+Value;
end;
end;
end
else if sTmp='' then SF.IsErrADCComm:=True;
end; // end if CounterPoll=0
Dec(SF.CounterPoll);
end;
SF.CS.Release;
until Terminated;
// EscapeCommFunction(hCom,CLRDTR);
Completed:=True;
end;
function TMainThread.getComChar: Char;
var
i:Cardinal;
begin
// EscapeCommFunction(hCom,SETRTS);
Result:=#0;
ReadFile(hCom,Result,1,i,nil);
end;
procedure TMainThread.putComBuf(const Buffer; Length: Cardinal);
var
i:Cardinal;
begin
// EscapeCommFunction(hCom,CLRRTS);
WriteFile(hCom,Buffer,Length,i,nil);
end;
procedure TMainThread.putComString(const Buffer: String);
begin
if Buffer<>'' then putComBuf(Buffer[1],Length(Buffer));
end;
function TMainThread.Query(const Cmd: String): String;
var
c:Char;
begin
Result:='';
Sleep(DelayBeforeCommandTX);
PurgeComm(hCom,PURGE_TXCLEAR or PURGE_TXABORT);
putComString(Cmd+#13);
PurgeComm(hCom,PURGE_RXCLEAR or PURGE_RXABORT);
Sleep(DelayBeforeResultRX);
repeat
c:=getComChar;
if (c=#13) or (c=#0) or (c=#255) then break
else Result:=Result+c;
until False;
end;
procedure TMainThread.ShowUserResp;
begin
// Вывод результатов опросов
FormMain.AddEchoText(sUserResp);
sUserResp:='';
end;
end.
|
unit http_intf;
interface
uses
System.JSON;
type
IHttpResponse = interface
['{0D13866C-0872-4F1D-BAEF-3C552828F92A}']
function statusCode: integer; overload;
function statusCode(const AValue: integer): IHttpResponse; overload;
function body: TJsonObject; overload;
function body(const AValue: TJsonObject): IHttpResponse; overload;
end;
IHttpRequest = interface
['{0D13866C-0872-4F1D-BAEF-3C552828F92A}']
function body: TJsonObject; overload;
function body(const AValue: TJsonObject): IHttpRequest; overload;
end;
THttpResponse = class(TInterfacedObject, IHttpResponse)
private
FStatusCode: integer;
FBody: TJsonObject;
function statusCode: integer; overload;
function statusCode(const AValue: integer): IHttpResponse; overload;
function body: TJsonObject; overload;
function body(const AValue: TJsonObject): IHttpResponse; overload;
public
destructor Destroy; override;
class function New: IHttpResponse;
end;
THttpRequest = class(TInterfacedObject, IHttpRequest)
private
FBody: TJsonObject;
function body: TJsonObject; overload;
function body(const AValue: TJsonObject): IHttpRequest; overload;
public
destructor Destroy; override;
class function New: IHttpRequest;
end;
implementation
function THttpResponse.body(const AValue: TJsonObject): IHttpResponse;
begin
FBody := AValue;
result := self;
end;
destructor THttpResponse.Destroy;
begin
FBody.DisposeOf;
inherited;
end;
function THttpResponse.body: TJsonObject;
begin
result := FBody;
end;
class function THttpResponse.New: IHttpResponse;
begin
result := self.Create;
end;
function THttpResponse.statusCode(const AValue: integer): IHttpResponse;
begin
FStatusCode := AValue;
result := self;
end;
function THttpResponse.statusCode: integer;
begin
result := FStatusCode;
end;
function THttpRequest.body: TJsonObject;
begin
result := FBody;
end;
function THttpRequest.body(const AValue: TJsonObject): IHttpRequest;
begin
FBody := AValue;
result := self;
end;
destructor THttpRequest.Destroy;
begin
FBody.free;
//
inherited;
end;
class function THttpRequest.New: IHttpRequest;
begin
result := self.Create;
end;
end.
|
{ *************************************************************************** }
{ }
{ }
{ Copyright (C) Amarildo Lacerda }
{ }
{ https://github.com/amarildolacerda }
{ }
{ }
{ *************************************************************************** }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{ *************************************************************************** }
unit System.ThreadSafe;
interface
uses Classes, System.Generics.Collections, System.Json;
type
IObjectLock = Interface
['{172D89AE-268F-4312-BEF6-4F1A1B6A0F12}']
procedure Lock;
procedure UnLock;
End;
TObjectLock = class(TInterfacedObject, IObjectLock)
private
FLock: TObject;
protected
procedure Lock; virtual;
procedure UnLock; virtual;
public
constructor create; virtual;
destructor destroy; override;
end;
TThreadSafeList = TThreadList;
/// Rename only
TThreadSafeStringList = class(TObjectLock)
private
FList: TStringList;
function Getitems(AIndex: integer): string;
procedure Setitems(AIndex: integer; const AValue: string);
function GetDelimitedText: string;
function GetDelimiter: Char;
procedure SetDelimitedText(const AValue: string);
procedure SetDelimiter(const AValue: Char);
function GetCommaText: string;
procedure SetCommaText(const AValue: string);
function GetQuoteChar: Char;
procedure SetQuoteChar(const AValue: Char);
function GetValues(AName: string): String;
procedure SetValues(AName: string; const Value: String);
function GetNames(AIndex: integer): String;
procedure SetNames(AIndex: integer; const Value: String);
function GetValueFromIndex(idx: integer): string;
procedure SetValueFromIndex(idx: integer; const Value: string);
public
constructor create; override;
destructor destroy; override;
procedure Clear;
function Count: integer;
function IndexOf(const AText: string): integer;
function IndexOfName(const AText: string): integer;
procedure Add(const AText: string; const ADupl: boolean = true);
procedure Delete(const AIndex: integer);
procedure Remove(const AText: string);
function LockList: TStringList;
procedure UnlockList; inline;
property Items[AIndex: integer]: string read Getitems
write Setitems; default;
property Delimiter: Char read GetDelimiter write SetDelimiter;
property DelimitedText: string read GetDelimitedText write SetDelimitedText;
function Text: string;
property CommaText: string read GetCommaText write SetCommaText;
property QuoteChar: Char read GetQuoteChar write SetQuoteChar;
procedure Assing(AStrings: TStrings);
procedure AssingTo(AStrings: TStrings);
procedure AddTo(AStrings: TStrings);
property Values[AName: string]: String read GetValues write SetValues;
property Names[AIndex: integer]: String read GetNames write SetNames;
property ValueFromIndex[idx: integer]: string read GetValueFromIndex
write SetValueFromIndex;
end;
TThreadSafeObjectList<T: Class> = class(TObjectLock)
private
FList: TObjectList<T>;
function Getitems(AIndex: integer): T;
procedure Setitems(AIndex: integer; const AValue: T);
protected
FItemClass: TClass;
public
constructor create; overload; override;
constructor create(AClass: TClass); overload; virtual;
destructor destroy; override;
procedure Push(AValue: T);
procedure Pop;
function Peek: T;
function Extract: T;
function LockList: TObjectList<T>;
procedure UnlockList;
procedure Clear;
function Add(AValue: T): integer; overload;
function Count: integer;
property Items[AIndex: integer]: T read Getitems write Setitems; default;
function IndexOf(AValue: T): integer;
procedure Delete(AIndex: integer);
procedure Remove(AValue: T);
function Add: T; overload; virtual;
function ToJson: string; overload;
function ToJsonArray: TJsonArray;
end;
TThreadSafeInterfaceList<T: IInterface> = class(TObjectLock)
private
FOwned: boolean;
FList: TList<T>;
function Getitems(AIndex: integer): T;
procedure Setitems(AIndex: integer; const AValue: T);
public
procedure Insert(AIndex: integer; AValue: T);
function Add(AValue: T): integer;
function IndexOf(AValue: T): integer;
procedure Delete(AIndex: integer);
procedure Remove(AValue: T);
constructor create(AOwned: boolean = true); virtual;
function Count: integer;
procedure Clear;
function LockList: TList<T>;
procedure UnlockList;
property Items[AIndex: integer]: T read Getitems write Setitems;
end;
implementation
uses REST.Json;
constructor TThreadSafeStringList.create;
begin
inherited create;
FList := TStringList.create;
end;
destructor TThreadSafeStringList.destroy;
begin
FList.Free;
inherited;
end;
function TThreadSafeStringList.LockList: TStringList;
begin
Lock;
result := FList;
end;
procedure TThreadSafeStringList.Remove(const AText: string);
var
i: integer;
begin
i := IndexOf(AText);
if i >= 0 then
Delete(i);
end;
procedure TThreadSafeStringList.UnlockList;
begin
UnLock;
end;
procedure TThreadSafeStringList.Add(const AText: string;
const ADupl: boolean = true);
begin
Lock;
try
begin
if (not ADupl) and (FList.IndexOf(AText) >= 0) then
Exit;
FList.Add(AText);
end;
finally
UnLock;
end;
end;
procedure TThreadSafeStringList.Delete(const AIndex: integer);
begin
try
LockList.Delete(AIndex);
finally
UnlockList;
end;
end;
function TThreadSafeStringList.Count: integer;
begin
try
result := LockList.Count;
finally
UnlockList;
end;
end;
function TThreadSafeStringList.Getitems(AIndex: integer): string;
begin
try
result := LockList.Strings[AIndex];
finally
UnlockList;
end;
end;
function TThreadSafeStringList.GetNames(AIndex: integer): String;
begin
with LockList do
try
result := Names[AIndex];
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.Setitems(AIndex: integer; const AValue: string);
begin
try
LockList.Strings[AIndex] := AValue;
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.SetNames(AIndex: integer; const Value: String);
var
sValue: String;
begin
Lock;
try
sValue := FList.ValueFromIndex[AIndex];
FList[AIndex] := Value + '=' + sValue;
finally
UnLock;
end;
end;
function TThreadSafeStringList.Text: string;
begin
try
result := LockList.Text;
finally
UnlockList;
end;
end;
function TThreadSafeStringList.GetDelimitedText: string;
begin
try
result := LockList.DelimitedText;
finally
UnlockList;
end;
end;
function TThreadSafeStringList.GetDelimiter: Char;
begin
try
result := LockList.Delimiter;
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.SetDelimitedText(const AValue: string);
begin
try
LockList.DelimitedText := AValue;
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.SetDelimiter(const AValue: Char);
begin
try
LockList.Delimiter := AValue;
finally
UnlockList;
end;
end;
function TThreadSafeStringList.GetCommaText: string;
var
f: TStrings;
i: integer;
begin
f := LockList;
try
result := '';
for i := 0 to f.Count - 1 do
begin
if i > 0 then
result := result + ',';
result := result + QuoteChar + f[i] + QuoteChar;
end;
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.SetCommaText(const AValue: string);
begin
try
LockList.CommaText := AValue;
finally
UnlockList;
end;
end;
function TThreadSafeStringList.GetQuoteChar: Char;
begin
try
result := LockList.QuoteChar;
finally
UnlockList;
end;
end;
function TThreadSafeStringList.GetValueFromIndex(idx: integer): string;
begin
with LockList do
try
result := ValueFromIndex[idx];
finally
UnlockList;
end;
end;
function TThreadSafeStringList.GetValues(AName: string): String;
begin
with LockList do
try
result := Values[AName];
finally
UnlockList;
end;
end;
function TThreadSafeStringList.IndexOf(const AText: string): integer;
begin
with LockList do
try
result := IndexOf(AText);
finally
UnlockList;
end;
end;
function TThreadSafeStringList.IndexOfName(const AText: string): integer;
begin
try
result := LockList.IndexOfName(AText);
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.SetQuoteChar(const AValue: Char);
begin
try
LockList.QuoteChar := AValue;
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.SetValueFromIndex(idx: integer;
const Value: string);
begin
with LockList do
try
ValueFromIndex[idx] := Value;
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.SetValues(AName: string; const Value: String);
begin
with LockList do
try
Values[AName] := Value;
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.AddTo(AStrings: TStrings);
begin
try
AStrings.AddStrings(LockList);
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.Assing(AStrings: TStrings);
begin
with LockList do
try
Assign(AStrings);
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.AssingTo(AStrings: TStrings);
begin
try
AStrings.Assign(LockList);
finally
UnlockList;
end;
end;
procedure TThreadSafeStringList.Clear;
begin
try
LockList.Clear;
finally
UnlockList;
end;
end;
{ TObjectLocked }
constructor TObjectLock.create;
begin
inherited;
FLock := TObject.create;
end;
destructor TObjectLock.destroy;
begin
FLock.Free;
inherited;
end;
procedure TObjectLock.Lock;
begin
System.TMonitor.Enter(FLock); // Bloqueia o objeto
end;
procedure TObjectLock.UnLock;
begin
System.TMonitor.Exit(FLock); // Libera o objeto
end;
{ TThreadObjectList }
function TThreadSafeObjectList<T>.Add(AValue: T): integer;
begin
with LockList do
try
result := FList.Count;
FList.Add(AValue);
finally
UnlockList;
end;
end;
function TThreadSafeObjectList<T>.Add: T;
begin
result := T(FItemClass.NewInstance);
Add(result);
end;
procedure TThreadSafeObjectList<T>.Clear;
begin
with LockList do
try
Clear;
finally
UnlockList;
end;
end;
function TThreadSafeObjectList<T>.Count: integer;
begin
with LockList do
try
result := FList.Count;
finally
UnlockList;
end;
end;
constructor TThreadSafeObjectList<T>.create(AClass: TClass);
begin
create;
FItemClass := AClass;
end;
constructor TThreadSafeObjectList<T>.create;
begin
inherited;
FList := TObjectList<T>.create;
end;
procedure TThreadSafeObjectList<T>.Delete(AIndex: integer);
begin
with LockList do
try
Delete(AIndex);
finally
UnlockList;
end;
end;
destructor TThreadSafeObjectList<T>.destroy;
begin
FList.Free;
inherited;
end;
function TThreadSafeObjectList<T>.Extract: T;
begin
result := nil;
if Count > 0 then
result := Items[Count - 1];
end;
function TThreadSafeObjectList<T>.Getitems(AIndex: integer): T;
begin
with LockList do
try
result := FList.Items[AIndex];
finally
UnlockList;
end;
end;
function TThreadSafeObjectList<T>.IndexOf(AValue: T): integer;
begin
with LockList do
try
result := FList.IndexOf(AValue);
finally
UnlockList;
end;
end;
function TThreadSafeObjectList<T>.LockList: TObjectList<T>;
begin
Lock;
result := FList;
end;
function TThreadSafeObjectList<T>.Peek: T;
begin
result := nil;
if Count > 0 then
result := Items[Count - 1];
end;
procedure TThreadSafeObjectList<T>.Pop;
var
o: TObject;
begin
if Count > 0 then
begin
with LockList do
try
o := Items[Count - 1];
Delete(Count - 1);
if (not FList.OwnsObjects) and assigned(o) then
o.DisposeOf;
finally
UnlockList;
end;
end;
end;
procedure TThreadSafeObjectList<T>.Push(AValue: T);
begin
Add(AValue);
end;
procedure TThreadSafeObjectList<T>.Remove(AValue: T);
var
i: integer;
begin
i := IndexOf(AValue);
if i >= 0 then
Delete(i);
end;
procedure TThreadSafeObjectList<T>.Setitems(AIndex: integer; const AValue: T);
begin
with LockList do
try
FList.Items[AIndex] := AValue;
finally
UnlockList;
end;
end;
function TThreadSafeObjectList<T>.ToJson: string;
var
j: TJsonArray;
begin
j := self.ToJsonArray;
try
result := j.ToJson;
finally
j.Free;
end;
end;
function TThreadSafeObjectList<T>.ToJsonArray: TJsonArray;
var
i: integer;
ob: T;
begin
result := TJsonArray.create;
with LockList do
try
for i := 0 to Count - 1 do
begin
ob := Items[i];
result.Add(TJson.ObjectToJsonObject(ob));
end;
finally
UnlockList;
end;
end;
procedure TThreadSafeObjectList<T>.UnlockList;
begin
UnLock;
end;
{ TInterfaceThreadSafeList<T> }
function TThreadSafeInterfaceList<T>.Add(AValue: T): integer;
begin
result := -1;
Lock;
try
FList.Add(AValue);
result := FList.Count - 1;
finally
UnLock;
end;
end;
procedure TThreadSafeInterfaceList<T>.Clear;
var
ob: IInterface;
i: integer;
begin
with LockList do
try
try
for i := Count - 1 downto 0 do
begin
ob := Items[i];
Delete(i);
if FOwned then
ob := nil;
end;
finally
Clear; // garantir que todos os itens foram excluidos... redundante
end;
finally
UnlockList;
end;
end;
function TThreadSafeInterfaceList<T>.Count: integer;
begin
with LockList do
try
result := Count;
finally
UnlockList;
end;
end;
constructor TThreadSafeInterfaceList<T>.create(AOwned: boolean = true);
begin
inherited create;
FOwned := AOwned;
FList := TList<T>.create;
end;
procedure TThreadSafeInterfaceList<T>.Delete(AIndex: integer);
var
ob: T;
begin
Lock;
try
ob := FList.Items[AIndex];
FList.Delete(AIndex);
if FOwned then
ob := nil;
finally
UnLock;
end;
end;
function TThreadSafeInterfaceList<T>.Getitems(AIndex: integer): T;
begin
with LockList do
try
result := T(Items[AIndex]);
finally
UnlockList;
end;
end;
function TThreadSafeInterfaceList<T>.LockList: TList<T>;
begin
Lock;
result := FList;
end;
procedure TThreadSafeInterfaceList<T>.Remove(AValue: T);
var
i: integer;
begin
i := IndexOf(AValue);
if i >= 0 then
Delete(i);
end;
procedure TThreadSafeInterfaceList<T>.Setitems(AIndex: integer;
const AValue: T);
begin
with LockList do
try
FList.Items[AIndex] := T;
finally
UnlockList;
end;
end;
procedure TThreadSafeInterfaceList<T>.UnlockList;
begin
UnLock;
end;
function TThreadSafeInterfaceList<T>.IndexOf(AValue: T): integer;
var
i: integer;
ob1, ob2: TObject;
begin
result := -1;
ob2 := AValue as TObject;
Lock;
try
for i := 0 to FList.Count - 1 do
begin
ob1 := FList.Items[i] as TObject;
if ob1.Equals(ob2) then
begin
result := i;
Exit;
end;
end;
finally
UnLock;
end;
end;
procedure TThreadSafeInterfaceList<T>.Insert(AIndex: integer; AValue: T);
begin
Lock;
try
FList.Insert(AIndex, AValue);
finally
UnLock;
end;
end;
end.
|
{
id:rz019291
PROG:rockers
LANG:PASCAL
}
{
USER: r z [rz109291]
TASK: rockers
LANG: PASCAL
Compiling...
Compile: OK
Executing...
Test 1: TEST OK [0.000 secs, 392 KB]
Test 2: TEST OK [0.000 secs, 392 KB]
Test 3: TEST OK [0.000 secs, 392 KB]
Test 4: TEST OK [0.000 secs, 392 KB]
Test 5: TEST OK [0.000 secs, 392 KB]
Test 6: TEST OK [0.000 secs, 392 KB]
Test 7: TEST OK [0.000 secs, 392 KB]
Test 8: TEST OK [0.000 secs, 392 KB]
Test 9: TEST OK [0.000 secs, 392 KB]
Test 10: TEST OK [0.000 secs, 392 KB]
Test 11: TEST OK [0.000 secs, 392 KB]
Test 12: TEST OK [0.000 secs, 392 KB]
All tests OK.
Your program ('rockers') produced all correct answers! This is your
submission #4 for this problem. Congratulations!
}
var
f:array[0..30,0..30,0..30]of longint;//f[i,j,k]表示用i个歌曲制造j张光盘还剩下k分钟时的用歌曲的数目
i,j,k,n,m,t:longint;
a:array[0..100]of longint;
function max(a,b:longint):longint;
begin
if a>b then exit(a);
exit(b);
end;
begin
assigN(input,'rockers.in');reset(input);assign(output,'rockers.out');rewrite(output);
readln(n,t,m);
for i:=1 to n do
begin
inc(j);
read(a[j]);
if a[j]>t then dec(j);
end;
n:=j;
for i:=1 to n do//n首歌
for j:=0 to m do//m张CD
for k:=0 to t do//一张CD可以容纳t分钟
if a[i]<=k then
f[i,j,k]:=max(f[i-1,j,k-a[i]]+1,f[i-1,j,k])
//f[i-1,j,k-a[i]]+1 表示i-1首歌,制造j张CD,还有k-a[i]]分钟最多可以制造f[i-1,j,k-a[i]]再加上第i首歌
//或者不用第i首歌,则剩下i-1首歌,制造j张CD,还有k分钟的状态f[i-1,j,k]
else
if j>0 then
f[i,j,k]:=max(f[i-1,j-1,t-a[i]]+1,f[i-1,j,k])
//如果剩下的k分钟装不下第i首歌,则考虑如果有CD的情况
//f[i-1,j-1,t-a[i]]+1 表示i-1首歌,制造j-1张CD,还有t-a[i]分钟最多可以制造f[i-1,j-1,t-a[i]]再加上第i首歌
//f[i-1,j,k] 同上
else
f[i,j,k]:=f[i-1,j,k];//f[i-1,j,k] 同上
writelN(f[n,m,0]);
close(input);close(output);
end.
|
{
Inno Setup Preprocessor
Copyright (C) 2001-2002 Alex Yackimoff
$Id: IsppPreprocess.pas,v 1.3 2010/12/30 15:26:34 mlaan Exp $
}
unit IsppPreprocess;
interface
uses
CompPreprocInt;
function ISPreprocessScript(var Params: TPreprocessScriptParams): Integer; stdcall;
implementation
uses
SysUtils, CmnFunc2, PathFunc,
IsppBase, IsppTranslate, IsppSessions, IsppIntf, IsppIdentMan, IsppVarUtils;
//type TPreprocProtectedMethods = class(TPreprocessor);
var
BuiltinsDir: string;
procedure ReadScript(const Params: TPreprocessScriptParams;
const Preprocessor: TPreprocessor);
procedure BuiltIns;
function Escape(const S: string): string;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(S) do
begin
Result := Result + S[I];
if S[I] = '\' then Result := Result + '\';
end;
end;
const
SBuiltins = 'ISPPBuiltins.iss';
var
BuiltinsFileName: string;
begin
if FileExists(BuiltinsDir + SBuiltins) then
begin
BuiltinsFileName := BuiltinsDir + SBuiltins;
if not GetOption(Preprocessor.FOptions.ParserOptions.Options, 'P') then
BuiltinsFileName := Escape(BuiltinsFileName);
Preprocessor.IncludeFile(BuiltinsFileName, False);
//Preprocessor.IncludeFile('D:\PROGRA~1\INNOSE~1\BUILTINS.ISS', False);
{TPreprocProtectedMethods(Preprocessor).InternalAddLine
(Format('#include "%s"', [BuiltinsFileName]), 0, Word(-1), False)}
end
else
Preprocessor.IssueMessage(SBuiltins + ' file was not found', imtWarning);
end;
var
I: Integer;
LineText: PChar;
LineTextStr: String;
begin
BuiltIns;
I := 0;
while True do
begin
LineText := Params.LineInProc(Params.CompilerData, 0, I);
if LineText = nil then
Break;
LineTextStr := LineText;
Preprocessor.QueueLine(LineTextStr);
Inc(I);
end;
end;
function CleanupProc(CleanupProcData: Pointer): Integer; stdcall;
begin
if PopPreproc = nil then
Result := 0
else
Result := 1; { should never get here }
end;
function DecodeStringOptions(const S: String; var Options: TOptions): Boolean;
var
I: Integer;
begin
Options := [];
Result := True;
for I := 1 to Length(S) do begin
case S[I] of
'a'..'z': Include(Options, Ord(S[I]) - Ord('a'));
else
Result := False;
end;
end;
end;
function ISPreprocessScript(var Params: TPreprocessScriptParams): Integer; stdcall;
const
Delta = Ord('a');
DefaultOptions: TIsppOptions =
(ParserOptions: (Options: [Ord('b') - Delta, Ord('p') - Delta]);
Options: [Ord('c') - Delta, Ord('e') - Delta]; VerboseLevel: 0;
InlineStart: '{#'; InlineEnd: '}'; SpanSymbol: #0);
var
ISPPOptions: TIsppOptions;
IncludePath, Definitions: string;
Preprocessor: TPreprocessor;
V: TIsppVariant;
function ParseOption(const OptName, OptValue: String): Boolean;
begin
Result := True;
if OptName = 'ISPP:ParserOptions' then
Result := DecodeStringOptions(OptValue, ISPPOptions.ParserOptions.Options)
else if OptName = 'ISPP:Options' then
Result := DecodeStringOptions(OptValue, ISPPOptions.Options)
else if OptName = 'ISPP:VerboseLevel' then
ISPPOptions.VerboseLevel := StrToIntDef(OptValue, 0)
else if OptName = 'ISPP:InlineStart' then
ISPPOptions.InlineStart := AnsiString(OptValue)
else if OptName = 'ISPP:InlineEnd' then
ISPPOptions.InlineEnd := AnsiString(OptValue)
else if OptName = 'ISPP:IncludePath' then
IncludePath := OptValue
else if OptName = 'ISPP:Definitions' then
Definitions := OptValue
else
Result := False;
end;
function ParseOptions(P: PChar): Boolean;
var
EqPos: PChar;
OptName: String;
begin
Result := True;
if P = nil then
Exit;
while P^ <> #0 do begin
EqPos := StrScan(P, '=');
if EqPos = nil then begin
Result := False;
Break;
end;
SetString(OptName, P, EqPos - P);
P := EqPos + 1;
if not ParseOption(OptName, P) then begin
Result := False;
Break;
end;
Inc(P, StrLen(P) + 1);
end;
end;
procedure ParseDefinitions(Definitions: PChar; VarMan: TIdentManager);
procedure ParseDefinition(const S: string);
var
I: Integer;
Name, V: string;
Value: TIsppVariant;
begin
Value := NULL;
I := Pos('=', S);
if I > 0 then
begin
Name := Copy(S, 1, I - 1);
V := Copy(S, I + 1, MaxInt);
if V <> '' then
MakeStr(Value, V)
end
else
Name := Trim(S);
VarMan.DefineVariable(Name, -1, Value, dsPublic);
end;
const
QuoteChar = Char('"');
Delimiter = Char(';');
var
P: PChar;
S: string;
begin
if Definitions = nil then Exit;
while CharInSet(Definitions^, [#1..' ']) do Inc(Definitions);
while Definitions^ <> #0 do
begin
if Definitions^ = QuoteChar then
S := AnsiExtractQuotedStr(Definitions, QuoteChar)
else
begin
P := Definitions;
while (Definitions^ > ' ') and (Definitions^ <> Delimiter) do Inc(Definitions);
SetString(S, P, Definitions - P);
end;
ParseDefinition(S);
while CharInSet(Definitions^, [#1..' ']) do Inc(Definitions);
if Definitions^ = Delimiter then
repeat
Inc(Definitions);
until not CharInSet(Definitions^, [#1..' ']);
end;
end;
var
SourcePath, CompilerPath, LineFilename, LineText: string;
LineNumber: Integer;
begin
if (Params.Size <> SizeOf(Params)) or
(Params.InterfaceVersion <> 1) then
begin
Result := ispeInvalidParam;
Exit;
end;
SourcePath := Params.SourcePath;
CompilerPath := Params.CompilerPath;
ISPPOptions := DefaultOptions;
IncludePath := RemoveBackslashUnlessRoot(CompilerPath);
Definitions := '';
if not ParseOptions(Params.Options) then
begin
Result := ispeInvalidParam;
Exit;
end;
BuiltinsDir := Params.CompilerPath;
{ Hack: push a dummy item onto the stack to defer deletion of temp. files }
PushPreproc(nil);
try
Preprocessor := TPreprocessor.Create(Params, nil, ISPPOptions, SourcePath,
CompilerPath, Params.Filename);
try
Preprocessor.IssueMessage('Preprocessing', imtStatus);
Preprocessor.IncludePath := IncludePath;
MakeStr(V, SourcePath);
Preprocessor.VarMan.DefineVariable('SourcePath', -1, V, dsPublic);
MakeStr(V, CompilerPath);
Preprocessor.VarMan.DefineVariable('CompilerPath', -1, V, dsPublic);
MakeInt(V, Params.CompilerBinVersion);
Preprocessor.VarMan.DefineVariable('Ver', -1, V, dsPublic);
ParseDefinitions(PChar(Definitions), Preprocessor.VarMan);
ReadScript(Params, Preprocessor);
Preprocessor.Stack.Resolved;
Preprocessor.IssueMessage('Preprocessed', imtStatus);
Preprocessor.IssueMessage('', imtBlank);
if not GetOption(Preprocessor.FOptions.Options, 'C') then
Result := ispeSilentAbort
else
begin
while Preprocessor.GetNext(LineFilename, LineNumber, LineText) do
Params.LineOutProc(Params.CompilerData, PChar(LineFilename),
LineNumber, PChar(LineText));
Result := ispeSuccess;
end;
finally
Preprocessor.Free;
end;
except
on E: EPreprocError do {preprocessor (syntax most likely) error}
begin
Params.ErrorProc(Params.CompilerData, PChar('[ISPP] ' + E.Message),
PChar(E.FileName), E.LineNumber, E.ColumnNumber);
Result := ispePreprocessError;
end;
on E: Exception do
begin
Params.ErrorProc(Params.CompilerData,
PChar(Format('Unexpected exception of class %s in ISPP.' +
#13#10#13#10'%s.', [E.ClassName, E.Message])), nil, 0, 0);
Result := ispePreprocessError;
end;
end;
if Result = ispeSuccess then
Params.PreprocCleanupProc := CleanupProc
else
PopPreproc;
end;
end.
|
unit QCCBlock;
{$I CSXGuard.inc}
interface
procedure SVC_SendCvarValue; cdecl;
procedure SVC_SendCvarValue2; cdecl;
implementation
uses CvarDef, MsgAPI, SysUtils, Common;
procedure QCC_Print(const CVar, Status: String; const IsQCC2: Boolean = False);
begin
if IsQCC2 then
Print('QCC2 "', [PRINT_PREFIX])
else
Print('QCC "', [PRINT_PREFIX]);
Print(CVar, CMD_COLOR_R, CMD_COLOR_G, CMD_COLOR_B, []);
Print('": ', Status, [PRINT_LINE_BREAK]);
end;
procedure SVC_SendCvarValue; cdecl;
var
Name, NameLC: String;
I: LongWord;
begin
MSG_SaveReadCount;
Name := MSG_ReadString;
if Enabled and BlockCVarQueries then
begin
if QCC_Count = 0 then
begin
if LogBlocks or LogDeveloper then
QCC_Print(Name, 'Blocked');
Exit;
end;
NameLC := LowerCase(Name);
for I := 1 to QCC_Count do
if StrComp(PChar(NameLC), @QCC[I]) = 0 then
begin
if LogBlocks or LogDeveloper then
QCC_Print(Name, 'Blocked');
Exit;
end;
if LogDeveloper then
QCC_Print(Name, 'Not blocked');
end;
MSG_RestoreReadCount;
SVC_SendCvarValue_Orig;
end;
procedure SVC_SendCvarValue2; cdecl;
var
Name, NameLC: String;
I: LongWord;
begin
MSG_SaveReadCount;
MSG_ReadLong;
Name := MSG_ReadString;
if Enabled and BlockCVarQueries then
begin
if QCC_Count = 0 then
begin
if LogBlocks or LogDeveloper then
QCC_Print(Name, 'Blocked', True);
Exit;
end;
NameLC := LowerCase(Name);
for I := 1 to QCC_Count do
if StrComp(PChar(NameLC), @QCC[I]) = 0 then
begin
if LogBlocks or LogDeveloper then
QCC_Print(Name, 'Blocked', True);
Exit;
end;
if LogDeveloper then
QCC_Print(Name, 'Not blocked', True);
end;
MSG_RestoreReadCount;
SVC_SendCvarValue2_Orig;
end;
end.
|
{$REGION 'Copyright (C) CMC Development Team'}
{ **************************************************************************
Copyright (C) 2015 CMC Development Team
CMC is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
CMC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CMC. If not, see <http://www.gnu.org/licenses/>.
************************************************************************** }
{ **************************************************************************
Additional Copyright (C) for this modul:
Chromaprint: Audio fingerprinting toolkit
Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com>
Lomont FFT: Fast Fourier Transformation
Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/
************************************************************************** }
{$ENDREGION}
{$REGION 'Notes'}
{ **************************************************************************
See CP.Chromaprint.pas for more information
************************************************************************** }
unit CP.Def;
{$IFDEF FPC}
{$MODE delphi}
{$ENDIF}
interface
uses
Classes, SysUtils;
const
CHROMAPRINT_VERSION_MAJOR = 1;
CHROMAPRINT_VERSION_MINOR = 2;
CHROMAPRINT_VERSION_PATCH = 0;
kMinSampleRate = integer(1000);
kMaxBufferSize = integer(1024 * 16);
// Resampler configuration
kResampleFilterLength = integer(16);
kResamplePhaseCount = integer(10);
kResampleLinear = integer(0);
kResampleCutoff = 0.8;
NUM_BANDS = 12;
cSAMPLE_RATE = 11025;
cFRAME_SIZE = 4096;
cOVERLAP = cFRAME_SIZE - cFRAME_SIZE div 3;
cMIN_FREQ = 28;
cMAX_FREQ = 3520;
Math_Pi: double = 3.1415926535897931;
TwoMath_Pi: double = 6.2831853071795862;
type
TUINT32Array = array of UINT32;
PUINT32Array = ^TUINT32Array;
TSmallintArray = array of smallint;
TDoubleArray = array of double;
PDoubleArray = ^TDoubleArray;
TSingleArray = array of single;
PSingleArray = ^TSingleArray;
PINT32 = array of INT32;
TChromaprintAlgorithm = (CHROMAPRINT_ALGORITHM_TEST1 = 0, CHROMAPRINT_ALGORITHM_TEST2, CHROMAPRINT_ALGORITHM_TEST3, CHROMAPRINT_ALGORITHM_TEST4,
CHROMAPRINT_ALGORITHM_DEFAULT = CHROMAPRINT_ALGORITHM_TEST2);
implementation
end.
|
unit Unit10;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TForm10 = class(TForm)
Image1: TImage;
LabeledEdit1: TLabeledEdit;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form10: TForm10;
implementation
{$R *.dfm}
// usando ACBR
uses ACBrDelphiZXingQRCode;
// se nao usa ACBR, pode usar o component original : https://github.com/debenu/DelphiZXingQRCode/
procedure QrCodeToCanvas(AWidth, AHeight: Integer; ATexto:String; ACanvas: TCanvas);
var
bitmap: TBitmap;
qr: TDelphiZXingQRCode;
r: Integer;
c: Integer;
scala: Double;
begin
bitmap := TBitmap.create;
try
qr := TDelphiZXingQRCode.create;
try
qr.Data := ATexto;
// ajuta o tamanho do bitmap para o tamanho do qrcode
bitmap.SetSize(qr.Rows, qr.Columns);
// copia o qrcode para o bitmap
for r := 0 to qr.Rows - 1 do
for c := 0 to qr.Columns - 1 do
if qr.IsBlack[r, c] then
bitmap.Canvas.Pixels[c, r] := clBlack
else
bitmap.Canvas.Pixels[c, r] := clWhite;
// prepara para redimensionar o qrcode para o tamanho do canvas
if (AWidth < bitmap.Height) then
begin
scala := AWidth / bitmap.Width;
end
else
begin
scala := AHeight / bitmap.Height;
end;
// transfere o bitmap para a imagem
ACanvas.StretchDraw(Rect(0, 0, Trunc(scala * bitmap.Width),
Trunc(scala * bitmap.Height)), bitmap);
finally
qr.Free;
end;
finally
bitmap.Free;
end;
end;
// transferindo o QRCode para a imagem (Canvas)
procedure TForm10.Button1Click(Sender: TObject);
begin
QrCodeToCanvas(Image1.Width, Image1.Height,LabeledEdit1.Text, Image1.Canvas);
end;
end.
|
unit ZombieAction;
interface
type
{$SCOPEDENUMS ON}
TZombieAction = (Stance = 0, Lurch, Slam, Bite, Block, Hitndie, Criticaldeath);
{$SCOPEDENUMS OFF}
const
ZombieAnimationAction : array[0..6] of string =
(
'stance', 'lurch', 'slam', 'bite',
'block', 'hitndie', 'criticaldeath'
) ;
ZombieAnimationSelected = 'selected';
ZombieAnimationDestination = 'destination';
implementation
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals TLS }
{ File name: flcTLSHandshake.pas }
{ File version: 5.04 }
{ Description: TLS handshake protocol }
{ }
{ Copyright: Copyright (c) 2008-2020, David J Butler }
{ All rights reserved. }
{ Redistribution and use in source and binary forms, with }
{ or without modification, are permitted provided that }
{ the following conditions are met: }
{ Redistributions of source code must retain the above }
{ copyright notice, this list of conditions and the }
{ following disclaimer. }
{ 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: }
{ }
{ 2008/01/18 0.01 Initial development: Headers }
{ 2010/11/26 0.02 Initial development: Messages }
{ 2016/01/08 0.03 String changes }
{ 2018/07/17 5.04 Revised for Fundamentals 5. }
{ }
{******************************************************************************}
{$INCLUDE flcTLS.inc}
unit flcTLSHandshake;
interface
uses
{ Utils }
flcStdTypes,
{ Cipher }
flcCipherRSA,
{ TLS }
flcTLSProtocolVersion,
flcTLSAlgorithmTypes,
flcTLSRandom,
flcTLSCipherSuite,
flcTLSSessionID,
flcTLSKeyExchangeParams,
flcTLSCertificate,
flcTLSHandshakeExtension;
{ }
{ HandshakeHeader }
{ }
type
TTLSHandshakeType = (
tlshtHello_request = 0, // Not used in TLS 1.3
tlshtClient_hello = 1,
tlshtServer_hello = 2,
tlshtNew_session_ticket = 4, // TLS 1.3
tlshtEnd_of_early_data = 5, // TLS 1.3
tlshtEncrypted_extensions = 8, // TLS 1.3
tlshtCertificate = 11,
tlshtServer_key_exchange = 12, // Not used in TLS 1.3
tlshtCertificate_request = 13,
tlshtServer_hello_done = 14, // Not used in TLS 1.3
tlshtCertificate_verify = 15,
tlshtClient_key_exchange = 16, // Not used in TLS 1.3
tlshtFinished = 20,
tlshtCertificate_url = 21, // RFC 6066 // Not used in TLS 1.3
tlshtCertificate_status = 22, // RFC 6066 // Not used in TLS 1.3
tlshtKey_update = 24, // TLS 1.3
tlshtMessage_hash = 254, // TLS 1.3
tlshtMax = 255
);
TTLSHandshakeHeader = packed record
msg_type : TTLSHandshakeType; // handshake type
length : array[0..2] of Byte; // bytes in message
end;
PTLSHandshakeHeader = ^TTLSHandshakeHeader;
const
TLSHandshakeHeaderSize = Sizeof(TTLSHandshakeHeader);
function TLSHandshakeTypeToStr(const A: TTLSHandshakeType): String;
procedure EncodeTLSHandshakeHeader(
var Handshake: TTLSHandshakeHeader;
const MsgType: TTLSHandshakeType;
const Length: Integer);
procedure DecodeTLSHandshakeHeader(
const Handshake: TTLSHandshakeHeader;
var MsgType: TTLSHandshakeType;
var Length: Integer);
function TLSHandshakeDataPtr(
const Buffer; const Size: Integer;
var DataSize: Integer): Pointer;
function EncodeTLSHandshake(
var Buffer; const Size: Integer;
const MsgType: TTLSHandshakeType; const MsgSize: Integer): Integer;
{ }
{ HelloRequest }
{ }
function EncodeTLSHandshakeHelloRequest(var Buffer; const Size: Integer): Integer;
{ }
{ ClientHello }
{ }
type
TTLSClientHello = record
ProtocolVersion : TTLSProtocolVersion;
SessionID : TTLSSessionID;
CipherSuites : TTLSCipherSuites;
CompressionMethods : TTLSCompressionMethods;
Random : TTLSRandom;
ExtensionsPresent : Boolean;
SignAndHashAlgos : TTLSSignatureAndHashAlgorithmArray;
end;
procedure InitTLSClientHello(
var ClientHello: TTLSClientHello;
const ProtocolVersion: TTLSProtocolVersion;
const SessionID: RawByteString);
function EncodeTLSClientHello(
var Buffer; const Size: Integer;
var ClientHello: TTLSClientHello): Integer;
function DecodeTLSClientHello(
const Buffer; const Size: Integer;
var ClientHello: TTLSClientHello): Integer;
function EncodeTLSHandshakeClientHello(
var Buffer; const Size: Integer;
var ClientHello: TTLSClientHello): Integer;
{ }
{ ServerHello }
{ }
type
TTLSServerHello = record
ProtocolVersion : TTLSProtocolVersion;
SessionID : TTLSSessionID;
CipherSuite : TTLSCipherSuiteRec;
CompressionMethod : TTLSCompressionMethod;
Random : TTLSRandom;
end;
procedure InitTLSServerHello(
var ServerHello: TTLSServerHello;
const ProtocolVersion: TTLSProtocolVersion;
const SessionID: RawByteString;
const CipherSuite: TTLSCipherSuiteRec;
const CompressionMethod: TTLSCompressionMethod);
function EncodeTLSServerHello(
var Buffer; const Size: Integer;
const ServerHello: TTLSServerHello): Integer;
function DecodeTLSServerHello(
const Buffer; const Size: Integer;
var ServerHello: TTLSServerHello): Integer;
function EncodeTLSHandshakeServerHello(
var Buffer; const Size: Integer;
const ServerHello: TTLSServerHello): Integer;
{ }
{ Certificate }
{ }
function EncodeTLSHandshakeCertificate(
var Buffer; const Size: Integer;
const CertificateList: TTLSCertificateList): Integer;
{ }
{ ServerKeyExchange }
{ }
function EncodeTLSHandshakeServerKeyExchange(
var Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const ServerKeyExchange: TTLSServerKeyExchange): Integer;
{ }
{ CertificateRequest }
{ }
type
TTLSClientCertificateTypeArray = array of TTLSClientCertificateType;
TTLSCertificateRequest = record
CertificateTypes : TTLSClientCertificateTypeArray;
SupportedSignatureAlgorithms : TTLSSignatureAndHashAlgorithmArray;
DistinguishedName : RawByteString;
end;
function EncodeTLSCertificateRequest(
var Buffer; const Size: Integer;
const CertificateRequest: TTLSCertificateRequest): Integer;
function DecodeTLSCertificateRequest(
const Buffer; const Size: Integer;
var CertificateRequest: TTLSCertificateRequest): Integer;
function EncodeTLSHandshakeCertificateRequest(
var Buffer; const Size: Integer;
const CertificateRequest: TTLSCertificateRequest): Integer;
{ }
{ ServerHelloDone }
{ }
function EncodeTLSHandshakeServerHelloDone(var Buffer; const Size: Integer): Integer;
{ }
{ CertificateVerify }
{ }
function EncodeTLSHandshakeCertificateVerify(var Buffer; const Size: Integer): Integer;
{ }
{ PreMasterSecret }
{ }
type
TTLSPreMasterSecret = packed record
client_version : TTLSProtocolVersion;
random : array[0..45] of Byte;
end;
const
TLSPreMasterSecretSize = SizeOf(TTLSPreMasterSecret);
procedure InitTLSPreMasterSecret_Random(
var PreMasterSecret: TTLSPreMasterSecret;
const ClientVersion: TTLSProtocolVersion);
function TLSPreMasterSecretToStr(const PreMasterSecret: TTLSPreMasterSecret): RawByteString;
procedure InitTLSEncryptedPreMasterSecret_RSA(
var EncryptedPreMasterSecret: RawByteString;
const PreMasterSecret: TTLSPreMasterSecret;
const RSAPublicKey: TRSAPublicKey);
{ }
{ ClientKeyExchange }
{ }
function EncodeTLSHandshakeClientKeyExchange(
var Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const ClientKeyExchange: TTLSClientKeyExchange): Integer;
{ }
{ Finished }
{ }
function EncodeTLSHandshakeFinished(var Buffer; const Size: Integer;
const MasterSecret: RawByteString;
const ProtocolVersion: TTLSProtocolVersion;
const HandshakeData: RawByteString;
const SenderIsClient: Boolean): Integer;
{ }
{ ChangeCipherSpec Protocol }
{ }
type
TTLSChangeCipherSpecType = (
spectype_change_cipher_spec = 1);
TTLSChangeCipherSpec = packed record
_type : TTLSChangeCipherSpecType;
end;
PTLSChangeCipherSpec = ^TTLSChangeCipherSpec;
const
TLSChangeCipherSpecSize = SizeOf(TTLSChangeCipherSpec);
procedure InitTLSChangeCipherSpec(var ChangeCipherSpec: TTLSChangeCipherSpec);
{ }
{ Test }
{ }
{$IFDEF TLS_TEST}
procedure Test;
{$ENDIF}
implementation
uses
{ System }
SysUtils,
{ Utils }
flcStrings,
{ Crypto }
flcCryptoHash,
flcCryptoRandom,
{ TLS }
flcTLSAlert,
flcTLSErrors,
flcTLSPRF,
flcTLSOpaqueEncoding;
{ }
{ Handshake Header }
{ }
function TLSHandshakeTypeToStr(const A: TTLSHandshakeType): String;
begin
case A of
tlshtHello_request : Result := 'Hello request';
tlshtClient_hello : Result := 'Client hello';
tlshtServer_hello : Result := 'Server hello';
tlshtCertificate : Result := 'Certificate';
tlshtServer_key_exchange : Result := 'Server key exchange';
tlshtCertificate_request : Result := 'Certficiate request';
tlshtServer_hello_done : Result := 'Server hello done';
tlshtCertificate_verify : Result := 'Certificate verify';
tlshtClient_key_exchange : Result := 'Client key exchange';
tlshtFinished : Result := 'Finished';
else
Result := '[Handshake#' + IntToStr(Ord(A)) + ']';
end;
end;
procedure EncodeTLSHandshakeHeader(
var Handshake: TTLSHandshakeHeader;
const MsgType: TTLSHandshakeType;
const Length: Integer);
var I : Byte;
L : Integer;
begin
Assert(Length >= 0);
Assert(Length <= $FFFFFF);
Handshake.msg_type := MsgType;
L := Length;
I := L div $10000;
Handshake.length[0] := I;
L := L - I * $10000;
I := L div $100;
Handshake.length[1] := I;
L := L - I * $100;
I := Byte(L);
Handshake.length[2] := I;
end;
procedure DecodeTLSHandshakeHeader(
const Handshake: TTLSHandshakeHeader;
var MsgType: TTLSHandshakeType;
var Length: Integer);
begin
MsgType := Handshake.msg_type;
Length :=
Handshake.length[0] * $10000 +
Handshake.length[1] * $100 +
Handshake.length[2];
end;
function TLSHandshakeDataPtr(
const Buffer; const Size: Integer;
var DataSize: Integer): Pointer;
var P : PByte;
begin
P := @Buffer;
if not Assigned(P) or (Size < TLSHandshakeHeaderSize) then
raise ETLSError.Create(TLSError_InvalidBuffer);
DataSize := Size - TLSHandshakeHeaderSize;
Inc(P, TLSHandshakeHeaderSize);
Result := P;
end;
function EncodeTLSHandshake(
var Buffer; const Size: Integer;
const MsgType: TTLSHandshakeType; const MsgSize: Integer): Integer;
var L : Integer;
P : PByte;
begin
Assert(MsgSize >= 0);
P := @Buffer;
L := TLSHandshakeHeaderSize + MsgSize;
if not Assigned(P) or (Size < L) then
raise ETLSError.CreateAlertBufferEncode;
EncodeTLSHandshakeHeader(PTLSHandshakeHeader(P)^, MsgType, MsgSize);
Result := L;
end;
{ }
{ Hello Request }
{ }
function EncodeTLSHandshakeHelloRequest(var Buffer; const Size: Integer): Integer;
begin
Result := EncodeTLSHandshake(Buffer, Size, tlshtHello_request, 0);
end;
{ }
{ ClientHello }
{ client_version : TTLSProtocolVersion; }
{ random : TTLSRandom; }
{ session_id : TLSSessionID; }
{ cipher_suites_count : Word; }
{ cipher_suites : <2..2^16-1> TTLSCipherSuite; }
{ compression_methods_count : Byte; }
{ compression_methods : <1..2^8-1> TTLSCompressionMethod; }
{ select (extensions_present) }
{ case false: ; }
{ case true: Extension extensions<0..2^16-1>; }
{ }
procedure InitTLSClientHello(
var ClientHello: TTLSClientHello;
const ProtocolVersion: TTLSProtocolVersion;
const SessionID: RawByteString);
begin
ClientHello.ProtocolVersion := ProtocolVersion;
InitTLSSessionID(ClientHello.SessionID, SessionID);
InitTLSRandom(ClientHello.Random);
end;
function EncodeTLSClientHello(
var Buffer; const Size: Integer;
var ClientHello: TTLSClientHello): Integer;
var P : PByte;
L, N : Integer;
C : TTLSCipherSuite;
D : TTLSCompressionMethod;
Suite : TTLSCipherSuiteRec;
SignRSA : Boolean;
begin
Assert(Assigned(@Buffer));
N := Size;
P := @Buffer;
// client_version
Dec(N, TLSProtocolVersionSize);
if N < 0 then
raise ETLSError.CreateAlertBufferEncode;
PTLSProtocolVersion(P)^ := ClientHello.ProtocolVersion;
Inc(P, TLSProtocolVersionSize);
// random
Dec(N, TLSRandomSize);
if N < 0 then
raise ETLSError.CreateAlertBufferEncode;
PTLSRandom(P)^ := ClientHello.Random;
Inc(P, TLSRandomSize);
// session_id
L := EncodeTLSSessionID(P^, N, ClientHello.SessionID);
Dec(N, L);
Inc(P, L);
// cipher_suites
L := 0;
for C := Low(TTLSCipherSuite) to High(TTLSCipherSuite) do
if C in ClientHello.CipherSuites then
Inc(L);
Assert(L <= $FFFF);
EncodeTLSLen16(P^, N, L * TLSCipherSuiteRecSize);
Inc(P, 2);
Dec(N, 2 + L * TLSCipherSuiteRecSize);
if N < 0 then
raise ETLSError.CreateAlertBufferEncode;
SignRSA := False;
for C := Low(TTLSCipherSuite) to High(TTLSCipherSuite) do
if C in ClientHello.CipherSuites then
begin
Suite.B1 := TLSCipherSuiteInfo[C].Rec.B1;
Suite.B2 := TLSCipherSuiteInfo[C].Rec.B2;
PTLSCipherSuiteRec(P)^ := Suite;
Inc(P, TLSCipherSuiteRecSize);
if TLSCipherSuiteInfo[C].Authentication = tlscsaRSA then
SignRSA := True;
end;
// compression_methods
L := 0;
for D := Low(TTLSCompressionMethod) to High(TTLSCompressionMethod) do
if D in ClientHello.CompressionMethods then
Inc(L);
Assert(L <= $FF);
Dec(N, 1 + L);
if N < 0 then
raise ETLSError.CreateAlertBufferEncode;
P^ := L;
Inc(P);
for D := Low(TTLSCompressionMethod) to High(TTLSCompressionMethod) do
if D in ClientHello.CompressionMethods then
begin
P^ := Ord(D);
Inc(P);
end;
// extensions
if IsTLS12(ClientHello.ProtocolVersion) then
if SignRSA then
begin
{
SetLength(ClientHello.SignAndHashAlgos, 5);
ClientHello.SignAndHashAlgos[0].Hash := tlshaSHA1;
ClientHello.SignAndHashAlgos[0].Signature := tlssaRSA;
ClientHello.SignAndHashAlgos[1].Hash := tlshaSHA224;
ClientHello.SignAndHashAlgos[1].Signature := tlssaRSA;
ClientHello.SignAndHashAlgos[2].Hash := tlshaSHA256;
ClientHello.SignAndHashAlgos[2].Signature := tlssaRSA;
ClientHello.SignAndHashAlgos[3].Hash := tlshaSHA384;
ClientHello.SignAndHashAlgos[3].Signature := tlssaRSA;
ClientHello.SignAndHashAlgos[4].Hash := tlshaSHA512;
ClientHello.SignAndHashAlgos[4].Signature := tlssaRSA;
ClientHello.ExtensionsPresent := True;
L := EncodeTLSClientHelloExtension_SignatureAlgorithms(P^, N, ClientHello);
Dec(N, L);
}
end;
Result := Size - N;
end;
function DecodeTLSClientHello(
const Buffer; const Size: Integer;
var ClientHello: TTLSClientHello): Integer;
var P : PByte;
L, N, C, ExtType, ExtLen : Integer;
I : Word;
E : TTLSCipherSuite;
F : TTLSCipherSuiteRec;
D : TTLSCompressionMethod;
begin
Assert(Assigned(@Buffer));
Assert(Size >= 0);
N := Size;
P := @Buffer;
// client_version
Dec(N, TLSProtocolVersionSize);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
ClientHello.ProtocolVersion := PTLSProtocolVersion(P)^;
Inc(P, TLSProtocolVersionSize);
// random
Dec(N, TLSRandomSize);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
ClientHello.Random := PTLSRandom(P)^;
Inc(P, TLSRandomSize);
// session_id
L := DecodeTLSSessionID(P^, N, ClientHello.SessionID);
Dec(N, L);
Inc(P, L);
// cipher_suites
ClientHello.CipherSuites := [];
L := DecodeTLSLen16(P^, N, C);
Dec(N, L);
Inc(P, L);
Dec(N, C);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
C := C div TLSCipherSuiteRecSize;
for I := 0 to C - 1 do
begin
F := PTLSCipherSuiteRec(P)^;
E := GetCipherSuiteByRec(F.B1, F.B2);
Include(ClientHello.CipherSuites, E);
Inc(P, TLSCipherSuiteRecSize);
end;
// compression_methods
Dec(N);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
ClientHello.CompressionMethods := [];
C := P^;
Inc(P);
Dec(N, C);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
for I := 0 to C - 1 do
begin
D := PTLSCompressionMethod(P)^;
Include(ClientHello.CompressionMethods, D);
Inc(P, TLSCompressionMethodSize);
end;
// extensions
ClientHello.ExtensionsPresent := N > 0;
while N > 0 do
begin
if N < 4 then
raise ETLSError.CreateAlertBufferDecode;
DecodeTLSWord16(P^, N, ExtType);
Inc(P, 2);
Dec(N, 2);
DecodeTLSLen16(P^, N, ExtLen);
Inc(P, 2);
Dec(N, 2);
Dec(N, ExtLen);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
Inc(P, ExtLen);
end;
Result := Size - N;
end;
function EncodeTLSHandshakeClientHello(
var Buffer; const Size: Integer;
var ClientHello: TTLSClientHello): Integer;
var P : Pointer;
N, L : Integer;
begin
P := TLSHandshakeDataPtr(Buffer, Size, N);
L := EncodeTLSClientHello(P^, N, ClientHello);
Result := EncodeTLSHandshake(Buffer, Size, tlshtClient_hello, L);
end;
{ }
{ ServerHello }
{ server_version : TTLSProtocolVersion; }
{ random : TTLSRandom; }
{ session_id : TLSSessionID; }
{ cipher_suite : TTLSCipherSuite; }
{ compression_method : TTLSCompressionMethod; }
{ select (extensions_present) }
{ case false: ; }
{ case true: Extension extensions<0..2^16-1>; }
{ }
procedure InitTLSServerHello(
var ServerHello: TTLSServerHello;
const ProtocolVersion: TTLSProtocolVersion;
const SessionID: RawByteString;
const CipherSuite: TTLSCipherSuiteRec;
const CompressionMethod: TTLSCompressionMethod);
begin
ServerHello.ProtocolVersion := ProtocolVersion;
InitTLSSessionID(ServerHello.SessionID, SessionID);
ServerHello.CipherSuite := CipherSuite;
ServerHello.CompressionMethod := CompressionMethod;
InitTLSRandom(ServerHello.Random);
end;
function EncodeTLSServerHello(
var Buffer; const Size: Integer;
const ServerHello: TTLSServerHello): Integer;
var P : PByte;
L, N : Integer;
begin
Assert(Assigned(@Buffer));
Assert(Size >= 0);
N := Size;
P := @Buffer;
// server_version
Dec(N, TLSProtocolVersionSize);
if N < 0 then
raise ETLSError.CreateAlertBufferEncode;
PTLSProtocolVersion(P)^ := ServerHello.ProtocolVersion;
Inc(P, TLSProtocolVersionSize);
// random
Dec(N, TLSRandomSize);
if N < 0 then
raise ETLSError.CreateAlertBufferEncode;
PTLSRandom(P)^ := ServerHello.Random;
Inc(P, TLSRandomSize);
// session_id
L := EncodeTLSSessionID(P^, N, ServerHello.SessionID);
Dec(N, L);
Inc(P, L);
// cipher_suite
Dec(N, TLSCipherSuiteRecSize);
if N < 0 then
raise ETLSError.CreateAlertBufferEncode;
PTLSCipherSuiteRec(P)^ := ServerHello.CipherSuite;
Inc(P, TLSCipherSuiteRecSize);
// compression_method
Dec(N, TLSCompressionMethodSize);
if N < 0 then
raise ETLSError.CreateAlertBufferEncode;
PTLSCompressionMethod(P)^ := ServerHello.CompressionMethod;
Result := Size - N;
end;
function DecodeTLSServerHello(
const Buffer; const Size: Integer;
var ServerHello: TTLSServerHello): Integer;
var P : PByte;
L, N : Integer;
begin
Assert(Assigned(@Buffer));
Assert(Size >= 0);
N := Size;
P := @Buffer;
// server_version
Dec(N, TLSProtocolVersionSize);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
ServerHello.ProtocolVersion := PTLSProtocolVersion(P)^;
Inc(P, TLSProtocolVersionSize);
// random
Dec(N, TLSRandomSize);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
ServerHello.Random := PTLSRandom(P)^;
Inc(P, TLSRandomSize);
// session_id
L := DecodeTLSSessionID(P^, N, ServerHello.SessionID);
Dec(N, L);
Inc(P, L);
// cipher_suite
Dec(N, TLSCipherSuiteRecSize);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
ServerHello.CipherSuite := PTLSCipherSuiteRec(P)^;
Inc(P, TLSCipherSuiteRecSize);
// compression_method
Dec(N, TLSCompressionMethodSize);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
ServerHello.CompressionMethod := PTLSCompressionMethod(P)^;
Result := Size - N;
end;
function EncodeTLSHandshakeServerHello(
var Buffer; const Size: Integer;
const ServerHello: TTLSServerHello): Integer;
var P : Pointer;
N, L : Integer;
begin
P := TLSHandshakeDataPtr(Buffer, Size, N);
L := EncodeTLSServerHello(P^, N, ServerHello);
Result := EncodeTLSHandshake(Buffer, Size, tlshtServer_hello, L);
end;
{ }
{ Certificate }
{ certificate_list : <0..2^24-1> ASN.1Cert; }
{ }
{ ASN.1Cert = <1..2^24-1> opaque; }
{ }
function EncodeTLSHandshakeCertificate(
var Buffer; const Size: Integer;
const CertificateList: TTLSCertificateList): Integer;
var P : Pointer;
N, L : Integer;
begin
P := TLSHandshakeDataPtr(Buffer, Size, N);
L := EncodeTLSCertificate(P^, N, CertificateList);
Result := EncodeTLSHandshake(Buffer, Size, tlshtCertificate, L);
end;
{ }
{ ServerKeyExchange }
{ }
function EncodeTLSHandshakeServerKeyExchange(
var Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const ServerKeyExchange: TTLSServerKeyExchange): Integer;
var P : Pointer;
N, L : Integer;
begin
P := TLSHandshakeDataPtr(Buffer, Size, N);
L := EncodeTLSServerKeyExchange(P^, N, KeyExchangeAlgorithm, ServerKeyExchange);
Result := EncodeTLSHandshake(Buffer, Size, tlshtServer_key_exchange, L);
end;
{ }
{ Certificate Request }
{ certificate_types : ClientCertificateType <1..2^8-1>; }
{ supported_signature_algorithms : SignatureAndHashAlgorithm <2^16-1>; }
{ certificate_authorities : DistinguishedName <0..2^16-1>; }
{ DistinguishedName = opaque <1..2^16-1> }
{ }
function EncodeTLSCertificateRequest(
var Buffer; const Size: Integer;
const CertificateRequest: TTLSCertificateRequest): Integer;
var P : PByte;
N, L, I : Integer;
begin
Assert(Assigned(@Buffer));
Assert(Size >= 0);
N := Size;
P := @Buffer;
// certificate_types
L := Length(CertificateRequest.CertificateTypes);
if (L <= 0) or (L > 255) then
raise ETLSError.Create(TLSError_InvalidParameter);
Dec(N, 1 + L);
if N < 0 then
raise ETLSError.Create(TLSError_InvalidBuffer);
P^ := L;
Inc(P);
for I := 0 to L - 1 do
begin
P^ := Ord(CertificateRequest.CertificateTypes[I]);
Inc(P);
end;
// supported_signature_algorithms
L := Length(CertificateRequest.SupportedSignatureAlgorithms);
EncodeTLSLen16(P^, N, L * TLSSignatureAndHashAlgorithmSize);
Inc(P, 2);
Dec(N, 2 + L * TLSSignatureAndHashAlgorithmSize);
if N < 0 then
raise ETLSError.Create(TLSError_InvalidBuffer);
for I := 0 to L - 1 do
begin
PTLSSignatureAndHashAlgorithm(P)^ := CertificateRequest.SupportedSignatureAlgorithms[I];
Inc(P, TLSSignatureAndHashAlgorithmSize);
end;
// certificate_authorities
L := EncodeTLSOpaque16(P^, N, CertificateRequest.DistinguishedName);
Dec(N, L);
Result := Size - N;
end;
function DecodeTLSCertificateRequest(
const Buffer; const Size: Integer;
var CertificateRequest: TTLSCertificateRequest): Integer;
var P : PByte;
N, L, I : Integer;
begin
Assert(Assigned(@Buffer));
Assert(Size >= 0);
N := Size;
P := @Buffer;
// certificate_types
Dec(N);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
L := P^;
Inc(P);
Dec(N, L);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
SetLength(CertificateRequest.CertificateTypes, L);
for I := 0 to L - 1 do
begin
CertificateRequest.CertificateTypes[I] := TTLSClientCertificateType(P^);
Inc(P);
end;
// supported_signature_algorithms
DecodeTLSLen16(P^, N, L);
Assert(L mod TLSSignatureAndHashAlgorithmSize = 0);
L := L div TLSSignatureAndHashAlgorithmSize;
Inc(P, 2);
Dec(N, 2 + L * TLSSignatureAndHashAlgorithmSize);
if N < 0 then
raise ETLSError.CreateAlertBufferDecode;
SetLength(CertificateRequest.SupportedSignatureAlgorithms, L);
for I := 0 to L - 1 do
begin
CertificateRequest.SupportedSignatureAlgorithms[I] := PTLSSignatureAndHashAlgorithm(P)^;
Inc(P, TLSSignatureAndHashAlgorithmSize);
end;
// certificate_authorities
L := DecodeTLSOpaque16(P^, N, CertificateRequest.DistinguishedName);
Dec(N, L);
Result := Size - N;
end;
function EncodeTLSHandshakeCertificateRequest(
var Buffer; const Size: Integer;
const CertificateRequest: TTLSCertificateRequest): Integer;
var P : Pointer;
N, L : Integer;
C : TTLSCertificateRequest;
begin
P := TLSHandshakeDataPtr(Buffer, Size, N);
L := EncodeTLSCertificateRequest(P^, N, C);
Result := EncodeTLSHandshake(Buffer, Size, tlshtCertificate_request, L);
end;
{ }
{ Server Hello Done }
{ }
function EncodeTLSHandshakeServerHelloDone(var Buffer; const Size: Integer): Integer;
begin
Result := EncodeTLSHandshake(Buffer, Size, tlshtServer_hello_done, 0);
end;
{ }
{ Certificate Verify }
{ }
function EncodeTLSHandshakeCertificateVerify(var Buffer; const Size: Integer): Integer;
begin
Result := EncodeTLSHandshake(Buffer, Size, tlshtCertificate_verify, 0);
end;
{ }
{ PreMasterSecret }
{ client_version : ProtocolVersion; }
{ random : opaque[46]; }
{ }
{ EncryptedPreMasterSecret = public-key-encrypted PreMasterSecret }
{ Public-key-encrypted data is represented as an opaque vector <0..2^16-1>. }
{ Thus, the RSA-encrypted PreMasterSecret in a ClientKeyExchange is preceded }
{ by two length bytes. }
{ }
procedure InitTLSPreMasterSecret_Random(var PreMasterSecret: TTLSPreMasterSecret;
const ClientVersion: TTLSProtocolVersion);
begin
PreMasterSecret.client_version := ClientVersion;
SecureRandomBuf(PreMasterSecret.random, SizeOf(PreMasterSecret.random));
end;
function TLSPreMasterSecretToStr(const PreMasterSecret: TTLSPreMasterSecret): RawByteString;
begin
SetLength(Result, TLSPreMasterSecretSize);
Move(PreMasterSecret, Result[1], TLSPreMasterSecretSize);
end;
procedure InitTLSEncryptedPreMasterSecret_RSA(
var EncryptedPreMasterSecret: RawByteString;
const PreMasterSecret: TTLSPreMasterSecret;
const RSAPublicKey: TRSAPublicKey);
var B : array[0..1023] of Byte;
L : Integer;
begin
L := RSAEncrypt(rsaetRSAES_PKCS1, RSAPublicKey, PreMasterSecret, SizeOf(PreMasterSecret),
B, SizeOf(B));
SetLength(EncryptedPreMasterSecret, L + 2);
EncodeTLSLen16(EncryptedPremasterSecret[1], L + 2, L);
Move(B, EncryptedPreMasterSecret[3], L);
end;
{ }
{ ClientKeyExchange }
{ }
{ select (KeyExchangeAlgorithm) }
{ case rsa : EncryptedPreMasterSecret; }
{ case dhe_dss : }
{ case dhe_rsa : }
{ case dh_dss : }
{ case dh_rsa : }
{ case dh_anon : ClientDiffieHellmanPublic; }
{ }
function EncodeTLSHandshakeClientKeyExchange(
var Buffer; const Size: Integer;
const KeyExchangeAlgorithm: TTLSKeyExchangeAlgorithm;
const ClientKeyExchange: TTLSClientKeyExchange): Integer;
var N, L : Integer;
P : PByte;
begin
P := TLSHandshakeDataPtr(Buffer, Size, N);
L := EncodeTLSClientKeyExchange(P^, N, KeyExchangeAlgorithm, ClientKeyExchange);
Result := EncodeTLSHandshake(Buffer, Size, tlshtClient_key_exchange, L);
end;
{ }
{ Finished }
{ }
{ SSL 3: }
{ Finished }
{ opaque md5_hash[16]; }
{ opaque sha_hash[20]; }
{ }
{ TLS 1.0 1.1 1.2: }
{ Finished }
{ opaque verify_data[12]; }
{ }
type
TSSLFinishedMD5Hash = array[0..15] of Byte;
TSSLFinishedSHAHash = array[0..19] of Byte;
TSSLFinished = packed record
md5_hash : TSSLFinishedMD5Hash;
sha_hash : TSSLFinishedSHAHash;
end;
PSSLFinished = ^TSSLFinished;
TTLSFinished = packed record
verify_data : array[0..11] of Byte;
end;
PTLSFinished = ^TTLSFinished;
const
SSLFinishedSize = SizeOf(TSSLFinished);
TLSFinishedSize = Sizeof(TTLSFinished);
{ }
{ SSL 3.0: }
{ md5_hash = MD5(master_secret + pad2 + }
{ MD5(handshake_messages + Sender + master_secret + pad1)); }
{ sha_hash = SHA(master_secret + pad2 + }
{ SHA(handshake_messages + Sender + master_secret + pad1)); }
{ pad_1 = The character 0x36 repeated 48 times for MD5 or 40 times for SHA. }
{ pad_2 = The character 0x5c repeated 48 times for MD5 or 40 times for SHA. }
{ Sender = enum ( client(0x434C4E54), server(0x53525652) ) }
{ }
{ TLS 1.0: verify_data = }
{ PRF(master_secret, finished_label, MD5(handshake_messages) + }
{ SHA-1(handshake_messages)) [0..11]; }
{ }
{ TLS 1.2: verify_data = }
{ PRF(master_secret, finished_label, Hash(handshake_messages)) }
{ [0..verify_data_length-1]; }
{ }
{ For the PRF defined in Section 5, the Hash MUST be the Hash used as the }
{ basis for the PRF. Any cipher suite which defines a different PRF MUST }
{ also define the Hash to use in the Finished computation. }
{ In previous versions of TLS, the verify_data was always 12 octets }
{ long. In the current version of TLS, it depends on the cipher suite. }
{ Any cipher suite which does not explicitly specify verify_data_length has a }
{ verify_data_length equal to 12. This includes all existing cipher suites. }
{ All of the data from all messages in this handshake (not }
{ including any HelloRequest messages) up to, but not including, }
{ this message. This is only data visible at the handshake layer }
{ and does not include record layer headers. This is the }
{ concatenation of all the Handshake structures as defined in }
{ Section 7.4, exchanged thus far. }
{ }
procedure CalcSSLVerifyData(
const MasterSecret: RawByteString;
const HandshakeData: RawByteString;
const SenderIsClient: Boolean;
var md5_hash: TSSLFinishedMD5Hash;
var sha_hash: TSSLFinishedSHAHash);
var
M, S, T : RawByteString;
begin
if SenderIsClient then
T := #$43#$4C#$4E#$54
else
T := #$53#$52#$56#$52;
M := MD5DigestToStrA(
CalcMD5(MasterSecret + DupCharB(#$5C, 48) +
MD5DigestToStrA(
CalcMD5(HandshakeData + T + MasterSecret + DupCharB(#$36, 48)))));
S := SHA1DigestToStrA(
CalcSHA1(MasterSecret + DupCharB(#$5C, 40) +
SHA1DigestToStrA(
CalcSHA1(HandshakeData + T + MasterSecret + DupCharB(#$36, 40)))));
Move(M[1], md5_hash, 16);
Move(S[1], sha_hash, 20);
end;
const
client_finished_label = 'client finished';
server_finished_label = 'server finished';
function CalcTLSVerifyData(
const ProtocolVersion: TTLSProtocolVersion;
const MasterSecret: RawByteString;
const HandshakeData: RawByteString): RawByteString;
var VDL : Integer;
D1 : T128BitDigest;
D2 : T160BitDigest;
D3 : T256BitDigest;
Seed : RawByteString;
PRF : RawByteString;
begin
if IsTLS12OrLater(ProtocolVersion) then
begin
VDL := 12;
D3 := CalcSHA256(HandshakeData[1], Length(HandshakeData));
SetLength(Seed, SizeOf(D3));
Move(D3, Seed[1], SizeOf(D3));
PRF := tls12PRF_SHA256(MasterSecret, client_finished_label, Seed, VDL);
end else
if IsTLS10OrLater(ProtocolVersion) then
begin
VDL := 12;
D1 := CalcMD5(HandshakeData);
D2 := CalcSHA1(HandshakeData);
SetLength(Seed, SizeOf(D1) + SizeOf(D2));
Move(D1, Seed[1], SizeOf(D1));
Move(D2, Seed[SizeOf(D1) + 1], SizeOf(D2));
PRF := tls10PRF(MasterSecret, client_finished_label, Seed, VDL);
end
else
raise ETLSError.Create(TLSError_InvalidParameter);
Result := PRF;
end;
function EncodeTLSHandshakeFinished(var Buffer; const Size: Integer;
const MasterSecret: RawByteString;
const ProtocolVersion: TTLSProtocolVersion;
const HandshakeData: RawByteString;
const SenderIsClient: Boolean): Integer;
var N : Integer;
P : PByte;
V : RawByteString;
F : PSSLFinished;
begin
P := TLSHandshakeDataPtr(Buffer, Size, N);
if IsTLS10OrLater(ProtocolVersion) then
begin
V := CalcTLSVerifyData(ProtocolVersion, MasterSecret, HandshakeData);
Assert(Length(V) >= 12);
Move(V[1], PTLSFinished(P)^.verify_data[0], 12);
Result := EncodeTLSHandshake(Buffer, Size, tlshtFinished, TLSFinishedSize);
end else
if IsSSL3(ProtocolVersion) then
begin
F := PSSLFinished(P);
CalcSSLVerifyData(MasterSecret, HandshakeData, SenderIsClient, F^.md5_hash, F^.sha_hash);
Result := EncodeTLSHandshake(Buffer, Size, tlshtFinished, SSLFinishedSize);
end
else
raise ETLSError.Create(TLSError_InvalidParameter);
end;
{ }
{ ChangeCipherSpec Protocol }
{ }
procedure InitTLSChangeCipherSpec(var ChangeCipherSpec: TTLSChangeCipherSpec);
begin
ChangeCipherSpec._type := spectype_change_cipher_spec;
end;
{ }
{ Unit test }
{ }
{$IFDEF TLS_TEST}
{$ASSERTIONS ON}
procedure Test;
begin
Assert(TLSHandshakeHeaderSize = 4);
end;
{$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 ClpBerSetParser;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpIAsn1StreamParser,
ClpBerSet,
ClpIAsn1SetParser,
ClpIBerSetParser,
ClpIProxiedInterface;
type
TBerSetParser = class(TInterfacedObject, IAsn1SetParser, IAsn1Convertible,
IBerSetParser)
strict private
var
F_parser: IAsn1StreamParser;
public
constructor Create(const parser: IAsn1StreamParser);
function ReadObject(): IAsn1Convertible; inline;
function ToAsn1Object(): IAsn1Object; inline;
end;
implementation
{ TBerSetParser }
constructor TBerSetParser.Create(const parser: IAsn1StreamParser);
begin
F_parser := parser;
end;
function TBerSetParser.ReadObject: IAsn1Convertible;
begin
result := F_parser.ReadObject();
end;
function TBerSetParser.ToAsn1Object: IAsn1Object;
begin
result := TBerSet.Create(F_parser.ReadVector(), false);
end;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Simple TAR archive writer
Copyright (C) 2011-2018 Alexander Koblov (alexx2000@mail.ru)
This unit is based on libtar.pp from the Free Component Library (FCL)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit uTarWriter;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,LazUtf8,
uGlobs, uWcxModule, WcxPlugin, DCClassesUtf8,
uFile,
uFileSource,
uFileSourceOperationUI,
uFileSourceOperation,
uFileSourceCopyOperation;
const
RECORDSIZE = 512;
NAMSIZ = 100;
TUNMLEN = 32;
TGNMLEN = 32;
CHKBLANKS = #32#32#32#32#32#32#32#32;
USTAR = 'ustar'#32#32;
LONGLINK = '././@LongLink';
LONGLEN = RECORDSIZE * 64;
LONGMAX = RECORDSIZE * 128;
type
TDataWriteProcedure = procedure(Buffer: Pointer; BytesToWrite: Int64) of object;
TUpdateStatisticsFunction = procedure(var NewStatistics: TFileSourceCopyOperationStatistics) of object;
{ TTarHeader }
TTarHeader = packed record
Name: array [0..NAMSIZ - 1] of AnsiChar;
Mode: array [0..7] of AnsiChar;
UID: array [0..7] of AnsiChar;
GID: array [0..7] of AnsiChar;
Size: array [0..11] of AnsiChar;
MTime: array [0..11] of AnsiChar;
ChkSum: array [0..7] of AnsiChar;
TypeFlag: AnsiChar;
LinkName: array [0..NAMSIZ - 1] of AnsiChar;
Magic: array [0..7] of AnsiChar;
UName: array [0..TUNMLEN - 1] of AnsiChar;
GName: array [0..TGNMLEN - 1] of AnsiChar;
DevMajor: array [0..7] of AnsiChar;
DevMinor: array [0..7] of AnsiChar;
Prefix: array [0..154] of AnsiChar;
end;
{ TTarHeaderEx }
TTarHeaderEx = packed record
case Boolean of
True: (HR: TTarHeader);
False: (HA: array [0..RECORDSIZE - 1] of AnsiChar);
end;
{ TTarWriter }
TTarWriter = class
private
FSourceStream,
FTargetStream: TFileStreamEx;
FWcxModule: TWcxModule;
FTarHeader: TTarHeaderEx;
FBasePath,
FTargetPath,
FArchiveFileName: String;
FBufferIn,
FBufferOut: Pointer;
FBufferSize: LongWord;
FMemPack: TArcHandle;
FLongName: array[0..Pred(LONGMAX)] of AnsiChar;
procedure WriteFakeHeader(const ItemName: String; IsFileName: Boolean; Offset: LongInt);
function MakeLongName(const FileName, LinkName: String;
NameLen, LinkLen: LongInt): LongInt;
function ReadData(BytesToRead: Int64): Int64;
procedure WriteData(Buffer: Pointer; BytesToWrite: Int64);
procedure CompressData(BufferIn: Pointer; BytesToCompress: Int64);
protected
AskQuestion: TAskQuestionFunction;
AbortOperation: TAbortOperationFunction;
CheckOperationState: TCheckOperationStateFunction;
UpdateStatistics: TUpdateStatisticsFunction;
DataWrite: TDataWriteProcedure;
procedure ShowError(sMessage: String);
procedure AddFile(const FileName: String);
function WriteFile(const FileName: String; var Statistics: TFileSourceCopyOperationStatistics): Boolean;
public
constructor Create(ArchiveFileName: String;
AskQuestionFunction: TAskQuestionFunction;
AbortOperationFunction: TAbortOperationFunction;
CheckOperationStateFunction: TCheckOperationStateFunction;
UpdateStatisticsFunction: TUpdateStatisticsFunction
);
constructor Create(ArchiveFileName: String;
AskQuestionFunction: TAskQuestionFunction;
AbortOperationFunction: TAbortOperationFunction;
CheckOperationStateFunction: TCheckOperationStateFunction;
UpdateStatisticsFunction: TUpdateStatisticsFunction;
WcxModule: TWcxModule
);
destructor Destroy; override;
function ProcessTree(var Files: TFiles; var Statistics: TFileSourceCopyOperationStatistics): Boolean;
end;
implementation
uses
{$IF DEFINED(MSWINDOWS)}
Windows, DCFileAttributes, DCWindows, uMyWindows,
{$ELSEIF DEFINED(UNIX)}
BaseUnix, FileUtil, uUsersGroups,
{$ENDIF}
uLng, DCStrUtils, DCOSUtils, uOSUtils;
{$IF DEFINED(MSWINDOWS)}
const
FILE_UNIX_MODE = S_IRUSR or S_IWUSR or S_IRGRP or S_IROTH;
FOLDER_UNIX_MODE = S_IRUSR or S_IWUSR or S_IXUSR or S_IRGRP or S_IXGRP or S_IROTH or S_IXOTH;
{$ENDIF}
// Makes a string of octal digits
// The string will always be "Len" characters long
procedure Octal64(N : Int64; P : PAnsiChar; Len : Integer);
var
I : Integer;
begin
for I := Len - 1 downto 0 do
begin
(P + I)^ := AnsiChar (ORD ('0') + ORD (N and $07));
N := N shr 3;
end;
for I := 0 to Len - 1 do
begin
if (P + I)^ in ['0'..'7'] then Break;
(P + I)^ := '0';
end;
end;
procedure OctalN(N : Int64; P : PAnsiChar; Len : Integer);
begin
Octal64(N, P, Len-1);
(P + Len - 1)^ := #0;
end;
procedure CheckSum(var TarHeader: TTarHeaderEx);
var
I: Integer;
ChkSum : Cardinal = 0;
begin
with TarHeader do
begin
StrMove(HR.ChkSum, CHKBLANKS, 8);
for I := 0 to SizeOf(TTarHeader) - 1 do
Inc(ChkSum, Ord(HA[I]));
Octal64(ChkSum, HR.ChkSum, 6);
HR.ChkSum[6] := #0;
HR.ChkSum[7] := #32;
end;
end;
{$IF DEFINED(MSWINDOWS)}
function GetFileInfo(const FileName: String; out FileInfo: TWin32FindDataW): Boolean;
var
Handle: System.THandle;
begin
Handle := FindFirstFileW(PWideChar(UTF16LongName(FileName)), FileInfo);
Result := Handle <> INVALID_HANDLE_VALUE;
if Result then
begin
FileInfo.dwFileAttributes:= ExtractFileAttributes(FileInfo);
Windows.FindClose(Handle);
end;
end;
{$ELSEIF DEFINED(UNIX)}
function GetFileInfo(const FileName: String; out FileInfo: BaseUnix.Stat): Boolean;
begin
Result:= fpLStat(UTF8ToSys(FileName), FileInfo) >= 0;
end;
{$ENDIF}
{ TTarWriter }
procedure TTarWriter.ShowError(sMessage: String);
begin
AskQuestion(sMessage, '', [fsourAbort], fsourAbort, fsourAbort);
AbortOperation;
end;
constructor TTarWriter.Create(ArchiveFileName: String;
AskQuestionFunction: TAskQuestionFunction;
AbortOperationFunction: TAbortOperationFunction;
CheckOperationStateFunction: TCheckOperationStateFunction;
UpdateStatisticsFunction: TUpdateStatisticsFunction);
begin
AskQuestion := AskQuestionFunction;
AbortOperation := AbortOperationFunction;
CheckOperationState := CheckOperationStateFunction;
UpdateStatistics := UpdateStatisticsFunction;
DataWrite:= @WriteData;
FArchiveFileName:= ArchiveFileName;
FTargetPath:= ExtractFilePath(ArchiveFileName);
// Allocate buffers
FBufferSize := gCopyBlockSize;
GetMem(FBufferIn, FBufferSize);
FBufferOut:= nil;
FWcxModule:= nil;
FMemPack:= 0;
end;
constructor TTarWriter.Create(ArchiveFileName: String;
AskQuestionFunction: TAskQuestionFunction;
AbortOperationFunction: TAbortOperationFunction;
CheckOperationStateFunction: TCheckOperationStateFunction;
UpdateStatisticsFunction: TUpdateStatisticsFunction;
WcxModule: TWcxModule);
begin
AskQuestion := AskQuestionFunction;
AbortOperation := AbortOperationFunction;
CheckOperationState := CheckOperationStateFunction;
UpdateStatistics := UpdateStatisticsFunction;
DataWrite:= @CompressData;
FArchiveFileName:= ArchiveFileName;
FTargetPath:= ExtractFilePath(ArchiveFileName);
// Allocate buffers
FBufferSize := gCopyBlockSize;
GetMem(FBufferIn, FBufferSize);
GetMem(FBufferOut, FBufferSize);
FWcxModule:= WcxModule;
// Starts packing into memory
FMemPack:= FWcxModule.WcxStartMemPack(MEM_OPTIONS_WANTHEADERS, ExtractFileName(ArchiveFileName));
end;
destructor TTarWriter.Destroy;
begin
inherited Destroy;
if Assigned(FWcxModule) then
begin
// Ends packing into memory
if (FMemPack <> 0) then
FWcxModule.DoneMemPack(FMemPack);
end;
if Assigned(FBufferIn) then
begin
FreeMem(FBufferIn);
FBufferIn := nil;
end;
if Assigned(FBufferOut) then
begin
FreeMem(FBufferOut);
FBufferOut := nil;
end;
end;
procedure TTarWriter.AddFile(const FileName: String);
{$IF DEFINED(MSWINDOWS)}
var
FileInfo: TWin32FindDataW;
LinkName,
FileNameIn: String;
FileMode: Cardinal;
FileTime,
FileSize: Int64;
NameLen,
LinkLen: LongInt;
begin
if GetFileInfo(FileName, FileInfo) then
with FTarHeader do
begin
FillByte(HR, SizeOf(FTarHeader), 0);
// File name
FileNameIn:= ExtractDirLevel(FBasePath, FileName);
FileNameIn:= StringReplace (FileNameIn, '\', '/', [rfReplaceAll]);
if FPS_ISDIR(FileInfo.dwFileAttributes) then
FileNameIn:= FileNameIn + '/';
StrLCopy (HR.Name, PAnsiChar(FileNameIn), NAMSIZ);
// File mode
if FPS_ISDIR(FileInfo.dwFileAttributes) then
FileMode:= FOLDER_UNIX_MODE
else
FileMode:= FILE_UNIX_MODE;
OctalN(FileMode, HR.Mode, 8);
// File size
FileSize:= (FileInfo.nFileSizeHigh shl 32) or FileInfo.nFileSizeLow;
if FPS_ISLNK(FileInfo.dwFileAttributes) then
OctalN(0, HR.Size, 12)
else
OctalN(FileSize, HR.Size, 12);
// Modification time
FileTime:= Round((Int64(FileInfo.ftLastWriteTime) - 116444736000000000) / 10000000);
OctalN(FileTime, HR.MTime, 12);
// File type
if FPS_ISLNK(FileInfo.dwFileAttributes) then
HR.TypeFlag := '2'
else if FPS_ISDIR(FileInfo.dwFileAttributes) then
HR.TypeFlag := '5'
else
HR.TypeFlag := '0';
// Link name
if FPS_ISLNK(FileInfo.dwFileAttributes) then
begin
LinkName:= ReadSymLink(FileName);
StrLCopy(HR.LinkName, PAnsiChar(LinkName), NAMSIZ);
end;
// Magic
StrLCopy (HR.Magic, PAnsiChar(USTAR), 8);
// Header checksum
CheckSum(FTarHeader);
// Get file name and link name length
NameLen:= Length(FileNameIn);
LinkLen:= Length(LinkName);
// Write data
if not ((NameLen > NAMSIZ) or (LinkLen > NAMSIZ)) then
DataWrite(@HA, RECORDSIZE)
else
begin
NameLen:= MakeLongName(FileNameIn, LinkName, NameLen, LinkLen);
DataWrite(@FLongName, NameLen);
end;
end;
end;
{$ELSEIF DEFINED(UNIX)}
var
FileInfo: BaseUnix.Stat;
LinkName,
FileNameIn: String;
NameLen,
LinkLen: LongInt;
begin
if GetFileInfo(FileName, FileInfo) then
with FTarHeader do
begin
FillByte(HR, SizeOf(FTarHeader), 0);
// File name
FileNameIn:= ExtractDirLevel(FBasePath, FileName);
if fpS_ISDIR(FileInfo.st_mode) then
FileNameIn:= FileNameIn + PathDelim;
StrLCopy (HR.Name, PAnsiChar(FileNameIn), NAMSIZ);
// File mode
OctalN(FileInfo.st_mode and $FFF, HR.Mode, 8);
// UID
OctalN(FileInfo.st_uid, HR.UID, 8);
// GID
OctalN(FileInfo.st_gid, HR.GID, 8);
// File size
if fpS_ISLNK(FileInfo.st_mode) then
OctalN(0, HR.Size, 12)
else
OctalN(FileInfo.st_size, HR.Size, 12);
// Modification time
OctalN(FileInfo.st_mtime, HR.MTime, 12);
// File type
if fpS_ISLNK(FileInfo.st_mode) then
HR.TypeFlag:= '2'
else if fpS_ISCHR(FileInfo.st_mode) then
HR.TypeFlag:= '3'
else if fpS_ISBLK(FileInfo.st_mode) then
HR.TypeFlag:= '4'
else if fpS_ISDIR(FileInfo.st_mode) then
HR.TypeFlag:= '5'
else if fpS_ISFIFO(FileInfo.st_mode) then
HR.TypeFlag:= '6'
else
HR.TypeFlag:= '0';
// Link name
if fpS_ISLNK(FileInfo.st_mode) then
begin
LinkName:= ReadSymLink(FileName);
StrLCopy(HR.LinkName, PAnsiChar(LinkName), NAMSIZ);
end;
// Magic
StrLCopy (HR.Magic, PAnsiChar(USTAR), 8);
// User
StrPLCopy(HR.UName, UIDToStr(FileInfo.st_uid), TUNMLEN);
// Group
StrPLCopy(HR.GName, GIDToStr(FileInfo.st_gid), TGNMLEN);
// Header checksum
CheckSum(FTarHeader);
// Get file name and link name length
NameLen:= Length(FileNameIn);
LinkLen:= Length(LinkName);
// Write data
if not ((NameLen > NAMSIZ) or (LinkLen > NAMSIZ)) then
DataWrite(@HA, RECORDSIZE)
else
begin
NameLen:= MakeLongName(FileNameIn, LinkName, NameLen, LinkLen);
DataWrite(@FLongName, NameLen);
end;
end;
end;
{$ENDIF}
procedure TTarWriter.WriteFakeHeader(const ItemName: String;
IsFileName: Boolean; Offset: LongInt);
var
TarHeader: TTarHeaderEx;
begin
with TarHeader do
begin
FillByte(TarHeader, SizeOf(TTarHeaderEx), 0);
StrPLCopy (HR.Name, LONGLINK, NAMSIZ);
if IsFileName then
HR.TypeFlag:= 'L'
else
HR.TypeFlag:= 'K';
// File mode
OctalN(0, HR.Mode, 8);
// UID
OctalN(0, HR.UID, 8);
// GID
OctalN(0, HR.GID, 8);
// Name size
OctalN(Length(ItemName) + 1, HR.Size, 12);
// Modification time
OctalN(0, HR.MTime, 12);
// Magic
StrLCopy (HR.Magic, PAnsiChar(USTAR), 8);
// User
StrPLCopy(HR.UName, 'root', TUNMLEN);
// Group
StrPLCopy(HR.GName, 'root', TGNMLEN);
// Header checksum
CheckSum(TarHeader);
// Copy file record
Move(HA, PByte(PAnsiChar(@FLongName) + Offset)^, RECORDSIZE);
// Copy file name
StrMove(PAnsiChar(@FLongName) + Offset + RECORDSIZE, PAnsiChar(ItemName), Length(ItemName));
end;
end;
function TTarWriter.MakeLongName(const FileName, LinkName: String;
NameLen, LinkLen: LongInt): LongInt;
begin
with FTarHeader do
begin
Result:= 0;
// Strip string length to maximum length
if (NameLen + RECORDSIZE) > LONGLEN then
NameLen:= LONGLEN - RECORDSIZE * 2;
if (LinkLen + RECORDSIZE) > LONGLEN then
LinkLen:= LONGLEN - RECORDSIZE * 2;
// Clear output buffer
FillChar(FLongName, NameLen + LinkLen + RECORDSIZE * 4, #0);
// Write Header for long link name
if LinkLen > NAMSIZ then
begin
WriteFakeHeader(LinkName, False, Result);
// Align link name by RECORDSIZE (512)
if (LinkLen mod RECORDSIZE) = 0 then
Result:= Result + RECORDSIZE + Linklen
else
Result:= Result + RECORDSIZE * 2 + (LinkLen div RECORDSIZE) * RECORDSIZE;
end;
// Write Header for long file name
if NameLen > NAMSIZ then
begin
WriteFakeHeader(FileName, True, Result);
// Align file name by RECORDSIZE (512)
if (NameLen mod RECORDSIZE) = 0 then
Result:= Result + RECORDSIZE + NameLen
else
Result:= Result + RECORDSIZE * 2 + (NameLen div RECORDSIZE) * RECORDSIZE;
end;
// Copy file record
Move(HA, PByte(PAnsiChar(@FLongName) + Result)^, RECORDSIZE);
Result:= Result + RECORDSIZE;
end;
end;
function TTarWriter.ReadData(BytesToRead: Int64): Int64;
var
bRetryRead: Boolean;
BytesRead: Int64;
begin
repeat
try
bRetryRead := False;
FillByte(FBufferIn^, FBufferSize, 0);
BytesRead:= FSourceStream.Read(FBufferIn^, BytesToRead);
if (BytesRead = 0) then
Raise EReadError.Create(mbSysErrorMessage(GetLastOSError));
except
on E: EReadError do
begin
case AskQuestion(rsMsgErrERead + ' ' + FSourceStream.FileName + ':',
E.Message,
[fsourRetry, fsourSkip, fsourAbort],
fsourRetry, fsourSkip) of
fsourRetry:
bRetryRead := True;
fsourAbort:
AbortOperation;
fsourSkip:
Exit;
end; // case
end;
end;
until not bRetryRead;
Result:= BytesRead;
end;
procedure TTarWriter.WriteData(Buffer: Pointer; BytesToWrite: Int64);
var
iTotalDiskSize, iFreeDiskSize: Int64;
bRetryWrite: Boolean;
BytesWrittenTry, BytesWritten: Int64;
begin
BytesWritten := 0;
repeat
try
bRetryWrite := False;
BytesWrittenTry := FTargetStream.Write((Buffer + BytesWritten)^, BytesToWrite - BytesWritten);
BytesWritten := BytesWritten + BytesWrittenTry;
if BytesWrittenTry = 0 then
begin
Raise EWriteError.Create(mbSysErrorMessage(GetLastOSError));
end
else if BytesWritten < BytesToWrite then
begin
bRetryWrite := True; // repeat and try to write the rest
end;
except
on E: EWriteError do
begin
{ Check disk free space }
GetDiskFreeSpace(FTargetPath, iFreeDiskSize, iTotalDiskSize);
if BytesToWrite > iFreeDiskSize then
begin
case AskQuestion(rsMsgNoFreeSpaceRetry, '',
[fsourYes, fsourNo],
fsourYes, fsourNo) of
fsourYes:
bRetryWrite := True;
fsourNo:
AbortOperation;
end; // case
end
else
begin
case AskQuestion(rsMsgErrEWrite + ' ' + FArchiveFileName + ':',
E.Message,
[fsourRetry, fsourSkip, fsourAbort],
fsourRetry, fsourSkip) of
fsourRetry:
bRetryWrite := True;
fsourAbort:
AbortOperation;
fsourSkip:
Exit;
end; // case
end;
end; // on do
end; // except
until not bRetryWrite;
end;
procedure TTarWriter.CompressData(BufferIn: Pointer; BytesToCompress: Int64);
var
InLen: LongInt;
Written: LongInt = 0;
Taken: LongInt = 0;
SeekBy: LongInt = 0;
OffSet: LongInt = 0;
Result: LongInt;
begin
InLen:= BytesToCompress;
// Do while not all data accepted
repeat
// Recalculate offset
if (Taken <> 0) then
begin
OffSet:= OffSet + Taken;
InLen:= InLen - Taken;
end;
// Compress input buffer
{$PUSH}{$WARNINGS OFF}
Result:= FWcxModule.PackToMem(FMemPack, PByte(PtrUInt(BufferIn) + OffSet), InLen, @Taken, FBufferOut, FBufferSize, @Written, @SeekBy);
{$POP}
if not (Result in [MEMPACK_OK, MEMPACK_DONE]) then
begin
ShowError(Format(rsMsgLogError + rsMsgLogPack,
[FArchiveFileName + ' - ' + GetErrorMsg(Result)]));
end;
// Seek if needed
if (SeekBy <> 0) then
FTargetStream.Seek(SeekBy, soCurrent);
// Write compressed data
if Written > 0 then
WriteData(FBufferOut, Written);
until ((Taken = InLen) and (BytesToCompress <> 0)) or (Result = MEMPACK_DONE);
end;
function TTarWriter.WriteFile(const FileName: String; var Statistics: TFileSourceCopyOperationStatistics): Boolean;
var
BytesRead, BytesToRead, BytesToWrite: Int64;
TotalBytesToRead: Int64 = 0;
begin
Result := False;
BytesToRead := FBufferSize;
try
FSourceStream:= nil;
try
FSourceStream := TFileStreamEx.Create(FileName, fmOpenRead or fmShareDenyWrite);
TotalBytesToRead := FSourceStream.Size;
while TotalBytesToRead > 0 do
begin
// Without the following line the reading is very slow
// if it tries to read past end of file.
if TotalBytesToRead < BytesToRead then
BytesToRead := TotalBytesToRead;
BytesRead:= ReadData(BytesToRead);
TotalBytesToRead := TotalBytesToRead - BytesRead;
BytesToWrite:= BytesRead;
if (BytesRead mod RECORDSIZE) <> 0 then
begin
// Align by TAR RECORDSIZE
BytesToWrite:= (BytesRead div RECORDSIZE) * RECORDSIZE + RECORDSIZE;
end;
// Write data
DataWrite(FBufferIn, BytesToWrite);
with Statistics do
begin
CurrentFileDoneBytes := CurrentFileDoneBytes + BytesRead;
DoneBytes := DoneBytes + BytesRead;
UpdateStatistics(Statistics);
end;
CheckOperationState; // check pause and stop
end; // while
finally
FreeAndNil(FSourceStream);
end;
Result:= True;
except
on EFOpenError do
begin
ShowError(rsMsgLogError + rsMsgErrEOpen + ': ' + FileName);
end;
on EWriteError do
begin
ShowError(rsMsgLogError + rsMsgErrEWrite + ': ' + FArchiveFileName);
end;
end;
end;
function TTarWriter.ProcessTree(var Files: TFiles;
var Statistics: TFileSourceCopyOperationStatistics): Boolean;
var
aFile: TFile;
Divider: Int64 = 1;
CurrentFileIndex: Integer;
iTotalDiskSize, iFreeDiskSize: Int64;
begin
try
Result:= False;
// Set base path
FBasePath:= Files.Path;
if FMemPack = 0 then begin
Divider:= 2;
end;
// Update progress
with Statistics do
begin
TotalBytes:= TotalBytes * Divider;
UpdateStatistics(Statistics);
end;
// Check disk free space
//if FCheckFreeSpace = True then
begin
GetDiskFreeSpace(FTargetPath, iFreeDiskSize, iTotalDiskSize);
if Statistics.TotalBytes > iFreeDiskSize then
begin
AskQuestion('', rsMsgNoFreeSpaceCont, [fsourAbort], fsourAbort, fsourAbort);
AbortOperation;
end;
end;
// Create destination file
FTargetStream := TFileStreamEx.Create(FArchiveFileName, fmCreate);
try
for CurrentFileIndex := 0 to Files.Count - 1 do
begin
aFile := Files[CurrentFileIndex];
if aFile.IsDirectory or aFile.IsLink then
begin
// Add file record only
AddFile(aFile.FullPath);
end
else
begin
// Update progress
with Statistics do
begin
CurrentFileFrom := aFile.FullPath;
CurrentFileTotalBytes := aFile.Size;
CurrentFileDoneBytes := 0;
end;
UpdateStatistics(Statistics);
// Add file record
AddFile(aFile.FullPath);
// TAR current file
if not WriteFile(aFile.FullPath, Statistics) then Break;
end;
CheckOperationState;
end;
// Finish TAR archive with two null records
FillByte(FBufferIn^, RECORDSIZE * 2, 0);
DataWrite(FBufferIn, RECORDSIZE * 2);
// Finish compression if needed
if (FMemPack <> 0) then CompressData(FBufferIn, 0);
finally
if Assigned(FTargetStream) then
begin
FreeAndNil(FTargetStream);
if (Statistics.DoneBytes <> Statistics.TotalBytes div Divider) then
// There was some error, because not all files has been archived.
// Delete the not completed target file.
mbDeleteFile(FArchiveFileName)
else
Result:= True;
end;
end;
except
on EFCreateError do
begin
ShowError(rsMsgLogError + rsMsgErrECreate + ': ' + FArchiveFileName);
end;
end;
end;
end.
|
unit ToolEditors;
interface
//constructor Create(AComponent: TComponent; ADesigner: TFormDesigner);
//procedure Edit;
//procedure ExecuteVerb(Index: Integer);
//function GetVerb(Index: Integer): string;
//function GetVerbCount: Integer;
//procedure Copy;
uses
DsgnIntf;
(*
type
TSpeedbarEditor =
class( TComponentEditor )
procedure Edit; override;
procedure ExecuteVerb( Indx : integer ); override;
function GetVerb(Indx : integer) : string; override;
function GetVerbCount : integer; override;
end;
procedure Register;
*)
implementation
uses
StrUtils, SysUtils;
resourcestring
SNewButton = 'New B&utton';
SNewSeparator = 'New Se¶tor';
const
Verbs : array[0..1] of string = ( SNewButton, SNewSeparator );
(*
procedure TSpeedbarEditor.Edit;
begin
end;
procedure TSpeedbarEditor.ExecuteVerb( Indx : integer);
begin
case Indx of
0 :
CreateNewButton( Component as TSpeedbar, tbsButton );
1 :
CreateNewButton( Component as TSpeedbar, tbsSeparator );
end;
end;
function TSpeedbarEditor.GetVerb( Indx : integer ) : string;
begin
Result := Verbs[Indx];
end;
function TSpeedbarEditor.GetVerbCount : integer;
begin
Result := High( Verbs ) - Low( Verbs ) + 1;
end;
procedure Register;
begin
RegisterComponentEditor( TSpeedbar, TSpeedbarEditor );
end;
*)
end.
|
unit fmWorkstationInfo;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, ActiveDs_TLB,
Winapi.ActiveX, ADC.GlobalVar, ADC.Types, ADC.ADObject, ADC.ComputerEdit, ADC.AD,
ADC.LDAP;
type
TForm_WorkstationInfo = class(TForm)
Edit_OS: TEdit;
Edit_InvNumber: TEdit;
Edit_DHCP_Server: TEdit;
Edit_MAC_Address: TEdit;
Edit_IPv4_Address: TEdit;
Label_OS: TLabel;
Label_InvNumber: TLabel;
Label_DHCP_Server: TLabel;
Label_MACAddress: TLabel;
Label_IPAddress: TLabel;
Label_Name: TLabel;
ComboBox_Name: TComboBox;
Button_Close: TButton;
Bevel1: TBevel;
Label1: TLabel;
Edit_UserName: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ComboBox_NameSelect(Sender: TObject);
procedure Button_CloseClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FCallingForm: TForm;
FObj: TADObject;
FWorkstationInfo: TComputerEdit;
procedure ClearTextFields;
function GetUserWorkstations(ARootDSE: IADs; ADN: string): string; overload;
function GetUserWorkstations(ALDAP: PLDAP; ADN: string): string; overload;
public
procedure SetCallingForm(const Value: TForm);
procedure SetObject(const Value: TADObject);
procedure AddHostName(AValue: string);
property CallingForm: TForm write SetCallingForm;
property UserObject: TADObject read FObj write SetObject;
end;
var
Form_WorkstationInfo: TForm_WorkstationInfo;
implementation
{$R *.dfm}
{ TForm_WorkstationInfo }
procedure TForm_WorkstationInfo.AddHostName(AValue: string);
var
i: Integer;
begin
if not AValue.IsEmpty then
begin
i := ComboBox_Name.Items.IndexOf(AValue);
if i < 0
then i := ComboBox_Name.Items.Add(AValue);
ComboBox_Name.ItemIndex := i;
end;
ComboBox_NameSelect(Self);
end;
procedure TForm_WorkstationInfo.Button_CloseClick(Sender: TObject);
begin
Close;
end;
procedure TForm_WorkstationInfo.ClearTextFields;
var
i: Integer;
begin
for i := 0 to Self.ControlCount - 1 do
if Self.Controls[i] is TEdit
then TEdit(Self.Controls[i]).Clear;
end;
procedure TForm_WorkstationInfo.ComboBox_NameSelect(Sender: TObject);
begin
ClearTextFields;
if FObj <> nil
then Edit_UserName.Text := FObj.name;
case apAPI of
ADC_API_LDAP: FWorkstationInfo.GetInfoByName(LDAPBinding, ComboBox_Name.Text);
ADC_API_ADSI: FWorkstationInfo.GetInfoByNameDS(ADSIBinding, ComboBox_Name.Text);
end;
FWorkstationInfo.GetExtendedInfo;
Edit_IPv4_Address.Text := FWorkstationInfo.IPv4;
// Edit_MAC_Address.Text := FWorkstationInfo.MAC_Address;
if Length(FWorkstationInfo.MAC_Address) > 0
then Edit_MAC_Address.Text := Format(
'%s | %s', [
FWorkstationInfo.MAC_Address.Format(gfSixOfTwo, gsColon, True),
FWorkstationInfo.MAC_Address.Format(gfThreeOfFour, gsDot)
]
);
Edit_DHCP_Server.Text := FWorkstationInfo.DHCP_Server;
Edit_OS.Text := FWorkstationInfo.operatingSystem;
Edit_InvNumber.Text := FWorkstationInfo.employeeID;
end;
procedure TForm_WorkstationInfo.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ComboBox_Name.Clear;
ClearTextFields;
FObj := nil;
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
end;
end;
procedure TForm_WorkstationInfo.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_ESCAPE: begin
Close;
end;
end;
end;
function TForm_WorkstationInfo.GetUserWorkstations(ARootDSE: IADs;
ADN: string): string;
var
hRes: HRESULT;
pObj: IADs;
v: OleVariant;
DomainHostName: string;
begin
Result := '';
v := ARootDSE.Get('dnsHostName');
DomainHostName := VariantToStringWithDefault(v, '');
VariantClear(v);
hRes := ADsOpenObject(
PChar('LDAP://' + DomainHostName + '/' + ADN),
nil,
nil,
ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND,
IID_IADs,
@pObj
);
if Succeeded(hRes) then
try
v := pObj.Get('userWorkstations');
Result := VarToStr(v);
VariantClear(v);
except
end;
end;
function TForm_WorkstationInfo.GetUserWorkstations(ALDAP: PLDAP;
ADN: string): string;
var
ldapBase: AnsiString;
attrArray: array of PAnsiChar;
returnCode: ULONG;
searchResult: PLDAPMessage;
ldapEntry: PLDAPMessage;
ldapValue: PPAnsiChar;
begin
SetLength(attrArray, 2);
attrArray[0] := PAnsiChar('userWorkstations');
attrArray[1] := nil;
ldapBase := ADN;
returnCode := ldap_search_ext_s(
ALDAP,
PAnsiChar(ldapBase),
LDAP_SCOPE_BASE,
nil,
PAnsiChar(@attrArray[0]),
0,
nil,
nil,
nil,
0,
searchResult
);
if (returnCode = LDAP_SUCCESS) and (ldap_count_entries(ALDAP, searchResult) > 0 ) then
begin
ldapEntry := ldap_first_entry(ALDAP, searchResult);
ldapValue := ldap_get_values(ALDAP, ldapEntry, attrArray[0]);
if ldapValue <> nil
then Result := ldapValue^
else Result := '';
ldap_value_free(ldapValue);
end;
if searchResult <> nil
then ldap_msgfree(searchResult);
end;
procedure TForm_WorkstationInfo.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
if FCallingForm <> nil
then FCallingForm.Enabled := False;
end;
procedure TForm_WorkstationInfo.SetObject(const Value: TADObject);
var
infoIP: PIPAddr;
infoDHCP: PDHCPInfo;
begin
ComboBox_Name.Items.Clear;
FObj := Value;
if FObj <> nil then
begin
Edit_UserName.Text := FObj.name;
case apAPI of
ADC_API_LDAP: begin
ComboBox_Name.Items.DelimitedText := GetUserWorkstations(LDAPBinding, FObj.distinguishedName);
end;
ADC_API_ADSI: begin
ComboBox_Name.Items.DelimitedText := GetUserWorkstations(ADSIBinding, FObj.distinguishedName);
end;
end;
end;
if ComboBox_Name.Items.Count > 0
then ComboBox_Name.ItemIndex := 0;
ComboBox_NameSelect(Self);
end;
end.
|
unit configuration;
interface
uses register, defines, utils, sysutils, inifiles;
procedure LoadConfiguration;
procedure CreateConfigFile;
procedure SaveConfiguration;
implementation
procedure LoadConfiguration;
var
IniFile : TIniFile;
Str : ShortString;
begin
if not FileExists(GetSystemVariable('gamedir') + '\' + 'sgmod.txt') then
CreateConfigFile;
IniFile := TIniFile.Create(GetSystemVariable('gamedir') + '\' + 'sgmod.txt');
with IniFile do
begin
// Default configuration
Str := IniFile.ReadString('SGMOD','sg_draw_time','yes');
if (Str = 'yes') then draw_time := true else
if (Str = 'no') then draw_time := false;
Str := IniFile.ReadString('SGMOD','sg_auto_messages','yes');
if (Str = 'yes') then auto_messages := true else
if (Str = 'no') then auto_messages := false;
Str := IniFile.ReadString('SGMOD','sg_low_ammo_table','yes');
if (Str = 'yes') then low_ammo_table := true else
if (Str = 'no') then low_ammo_table := false;
Str := IniFile.ReadString('SGMOD','sg_show_hp','yes');
if (Str = 'yes') then is_show_hp := true else
if (Str = 'no') then is_show_hp := false;
Str := IniFile.ReadString('SGMOD','sg_mouse_messages','yes');
if (Str = 'yes') then use_deg_of_messages := true else
if (Str = 'no') then use_deg_of_messages := false;
Str := IniFile.ReadString('SGMOD','sg_mmap_always_show','no');
if (Str = 'yes') then mmap_always_show := true else
if (Str = 'no') then mmap_always_show := false;
// Binds
MMAP_BIND_KEY := strtoint(IniFile.ReadString('BINDS','mmap_bind','0'));
MMAP_IN_BIND_KEY := strtoint(IniFile.ReadString('BINDS','mmap_in_bind','0'));
MMAP_OUT_BIND_KEY := strtoint(IniFile.ReadString('BINDS','mmap_out_bind','0'));
VOTE_MENU_BIND_KEY := strtoint(IniFile.ReadString('BINDS','vote_menu_bind','0'));
vote_menu_key_up := strtoint(IniFile.ReadString('BINDS','vote_menu_key_up_bind','0'));
vote_menu_key_down := strtoint(IniFile.ReadString('BINDS','vote_menu_key_down_bind','0'));
mouse_choise_key := strtoint(IniFile.ReadString('BINDS','mouse_choise_key','0'));
// Ammo warning
warning_ammo_mg := strtoint(IniFile.ReadString('AMMO_WARNING','mg', '20'));
warning_ammo_sg := strtoint(IniFile.ReadString('AMMO_WARNING','sg','2'));
warning_ammo_gl := strtoint(IniFile.ReadString('AMMO_WARNING','gl','2'));
warning_ammo_rl := strtoint(IniFile.ReadString('AMMO_WARNING','rl','2'));
warning_ammo_sh := strtoint(IniFile.ReadString('AMMO_WARNING','sh','30'));
warning_ammo_rg := strtoint(IniFile.ReadString('AMMO_WARNING','rg','2'));
warning_ammo_pl := strtoint(IniFile.ReadString('AMMO_WARNING','pl','15'));
warning_ammo_bfg := strtoint(IniFile.ReadString('AMMO_WARNING','bfg','2'));
// Time
time_size := strtoint(IniFile.ReadString('TIME','SIZE', '3'));
time_color := strtoint(IniFile.ReadString('TIME','COLOR','3'));
time_pos_x := strtoint(IniFile.ReadString('TIME','POS_X','10'));
time_pos_y := strtoint(IniFile.ReadString('TIME','POS_Y','450'));
// Messages:
Str := IniFile.ReadString('MESSAGES','YA','TESTYA');
messages[MESSAGE_YA] := Str;
Str := IniFile.ReadString('MESSAGES','RA','');
messages[MESSAGE_RA] := Str;
Str := IniFile.ReadString('MESSAGES','H100','');
messages[MESSAGE_H100] := Str;
Str := IniFile.ReadString('MESSAGES','QUAD','');
messages[MESSAGE_QUAD] := Str;
Str := IniFile.ReadString('MESSAGES','REGENERATION','');
messages[MESSAGE_REGENERATION] := Str;
Str := IniFile.ReadString('MESSAGES','HASTE','');
messages[MESSAGE_HASTE] := Str;
Str := IniFile.ReadString('MESSAGES','FLIGHT','');
messages[MESSAGE_FLIGHT] := Str;
Str := IniFile.ReadString('MESSAGES','BATTLESUIT','');
messages[MESSAGE_BATTLESUIT] := Str;
Str := IniFile.ReadString('MESSAGES','RAIL','');
messages[MESSAGE_RAIL] := Str;
end;
IniFile.Free;
end;
procedure SaveConfiguration;
var
IniFile: TIniFile;
begin
IniFile:=TIniFile.Create(GetSystemVariable('gamedir') + '\' + 'sgmod.txt');
with IniFile do
begin
if auto_messages then IniFile.WriteString('SGMOD','sg_auto_messages', 'yes') else
IniFile.WriteString('SGMOD','sg_auto_messages', 'no');
if draw_time then IniFile.WriteString('SGMOD','sg_draw_time', 'yes') else
IniFile.WriteString('SGMOD','sg_draw_time', 'no');
if low_ammo_table then IniFile.WriteString('SGMOD','sg_low_ammo_table', 'yes') else
IniFile.WriteString('SGMOD','sg_low_ammo_table', 'no');
if is_show_hp then IniFile.WriteString('SGMOD','sg_show_hp', 'yes') else
IniFile.WriteString('SGMOD','sg_show_hp', 'no');
if use_deg_of_messages then IniFile.WriteString('SGMOD','sg_mouse_messages', 'yes') else
IniFile.WriteString('SGMOD','sg_mouse_messages', 'no');
if mmap_always_show then IniFile.WriteString('SGMOD','sg_mmap_always_show', 'yes') else
IniFile.WriteString('SGMOD','sg_mmap_always_show', 'no');
// Binds
IniFile.WriteString('BINDS','mmap_bind', inttostr(MMAP_BIND_KEY));
IniFile.WriteString('BINDS','mmap_in_bind', inttostr(MMAP_IN_BIND_KEY));
IniFile.WriteString('BINDS','mmap_out_bind', inttostr(MMAP_OUT_BIND_KEY));
IniFile.WriteString('BINDS','vote_menu_bind', inttostr(VOTE_MENU_BIND_KEY));
IniFile.WriteString('BINDS','vote_menu_key_up_bind', inttostr(vote_menu_key_up));
IniFile.WriteString('BINDS','vote_menu_key_down_bind', inttostr(vote_menu_key_down));
IniFile.WriteString('BINDS','mouse_choise_key', inttostr(mouse_choise_key));
// Ammo warning
IniFile.WriteString('AMMO_WARNING','mg', inttostr(warning_ammo_mg));
IniFile.WriteString('AMMO_WARNING','sg', inttostr(warning_ammo_sg));
IniFile.WriteString('AMMO_WARNING','gl', inttostr(warning_ammo_gl));
IniFile.WriteString('AMMO_WARNING','rl', inttostr(warning_ammo_rl));
IniFile.WriteString('AMMO_WARNING','sh', inttostr(warning_ammo_sh));
IniFile.WriteString('AMMO_WARNING','rg', inttostr(warning_ammo_rg));
IniFile.WriteString('AMMO_WARNING','pl', inttostr(warning_ammo_pl));
IniFile.WriteString('AMMO_WARNING','bfg', inttostr(warning_ammo_bfg));
// Time
IniFile.WriteString('TIME','SIZE', inttostr(time_size));
IniFile.WriteString('TIME','COLOR', inttostr(time_color));
IniFile.WriteString('TIME','POS_X', inttostr(time_pos_x));
IniFile.WriteString('TIME','POS_Y', inttostr(time_pos_y));
// Messages
IniFile.WriteString('MESSAGES','YA', messages[MESSAGE_YA]);
IniFile.WriteString('MESSAGES','RA', messages[MESSAGE_RA]);
IniFile.WriteString('MESSAGES','H100', messages[MESSAGE_H100]);
IniFile.WriteString('MESSAGES','QUAD', messages[MESSAGE_QUAD]);
IniFile.WriteString('MESSAGES','REGENERATION', messages[MESSAGE_REGENERATION]);
IniFile.WriteString('MESSAGES','HASTE', messages[MESSAGE_HASTE]);
IniFile.WriteString('MESSAGES','FLIGHT', messages[MESSAGE_FLIGHT]);
IniFile.WriteString('MESSAGES','BATTLESUIT', messages[MESSAGE_BATTLESUIT]);
IniFile.WriteString('MESSAGES','RAIL', messages[MESSAGE_RAIL]);
end;
IniFile.Free;
end;
procedure CreateConfigFile;
var
F : TextFile;
begin
AssignFile(F,GetSystemVariable('gamedir')+ '\' + 'sgmod.txt');
rewrite(f);
writeln(f,'[SGMOD]');
writeln(f,'sg_auto_messages=yes');
writeln(f,'sg_draw_time=yes');
writeln(f,'sg_low_ammo_table=yes');
writeln(f,'sg_show_hp=yes');
writeln(f,'sg_mouse_messages=yes');
writeln(f,'sg_mmap_always_show=no');
// Binds
writeln(f,'');
writeln(f,'[BINDS]');
writeln(f,'mmap_bind=9');
writeln(f,'mmap_in_bind=107');
writeln(f,'mmap_out_bind=109');
writeln(f,'vote_menu_bind=39');
writeln(f,'vote_menu_key_down_bind=40');
writeln(f,'vote_menu_key_up_bind=38');
writeln(f,'mouse_choise_key=16');
// Time
writeln(f,'');
writeln(f,'[TIME]');
writeln(f,'SIZE=3');
writeln(f,'COLOR=3');
writeln(f,'POS_X=10');
writeln(f,'POS_Y=450');
// Ammo warning
writeln(f,'');
writeln(f,'[AMMO_WARNING]');
writeln(f,'mg=20');
writeln(f,'sg=2');
writeln(f,'gl=2');
writeln(f,'rl=2');
writeln(f,'sh=30');
writeln(f,'rg=2');
writeln(f,'pl=15');
writeln(f,'bfg=2');
// Messages
writeln(f,'');
writeln(f,'[MESSAGES]');
writeln(f,'YA=^3YA^2 TAKEN.');
writeln(f,'RA=^1RA^2 TAKEN.');
writeln(f,'H100=^4MEGA HEALTH^2 TAKEN.');
writeln(f,'QUAD=^4QUAD^2 TAKEN.');
writeln(f,'REGENERATION=^4REGENERATION^2 TAKEN.');
writeln(f,'HASTE=^4HASTE^2 TAKEN.');
writeln(f,'FLIGHT=^4FLIGHT^2 TAKEN.');
writeln(f,'BATTLESUIT=^4BATTLESUIT^2 TAKEN.');
writeln(f,'RAIL=^5RAIL^2 TAKEN.');
CloseFile(F);
AddMessage('^1SGMOD:^7 Create default configuration file.');
end;
end.
|
unit DynArrB;
{ Exports the TBigByteArray and TByteArray2D types.
The TBigByteArray type is a dynamic array type, with Bytes as
elements.
Indexing the elements is done exactly like a normal array;
the differences with a 'normal' array type are:
- one MUST call the constructor to create the array
- the size (no. of elements) of the array is determined at run time
R.P. Sterkenburg,
TNO Prins Maurits Laboratory, Rijswijk, The Netherlands
6 May 96: - created (unit name DynArrS)
7 May 96: - renamed property N to Count
- added CopyInto method
13 May 96 - added Min & Max functions
14 May 96 - added inherited Create in constructor
- added function FindMax and FindMinMax
12 Jul 96: - added function Average
23 Aug 96: - added procedure SortAscending
26 Aug 96: - added procedure MultiplyWith
9 Sep 96: - added various new procedures analogous to old unit bigarrays
7 Oct 96: - added TSingleArray.Subtract
- corrected TSingleArray.Sum (check for NoValue added)
15 Nov 96: - replaced procedure CopyInto with function Copy
4 Dec 96: - added TSingleArray2D.Copy
16 Dec 96: - added TSingleArray2D.EqualTo
18 Dec 96: - added TSingleArray.Append
12 Feb 97: - corrected bugs in the Copy methods
- added calls to inherited Create and Destroy in TSingleArray2D
21 Feb 97: - created as modified version of unit DynArrS which
exported the TSingleArray (+2D) type
- deleted methods CreateLinear, Average, GetMeanAndSigma,
MultiplyWith
5 Mar 97: - added TByteArray2D.SetRow
- made CopyRow a function
- renamed TByteArray to TBigByteArray to prevent name conflicts
with SysUtils' TBigByteArray
11 May 97: - made CopyRow more efficient by copying a block of bytes in
stead of each element separately
14 Aug 97: - Deleted the System. scope-designator in SetRow, so that
HeapUnit's Move procedure is called when necessary (again).
}
interface
type
TBigByteArray = class(TObject)
private
FAddress: Pointer;
FCount: Longint;
function GetVal(index: Longint): Byte;
procedure SetVal(index: Longint; value: Byte);
public
constructor Create(N: Longint);
constructor Dim(N: Longint);
constructor ReadBinary(var F: File);
destructor Destroy; override;
procedure Append(appendarray: TBigByteArray);
procedure Clear;
function Copy: TBigByteArray;
function EqualTo(OtherArray: TBigByteArray): Boolean;
procedure FillWith(Value: Byte);
procedure FindMax(var i: Longint; var max: Byte);
procedure FindMinMax(var min, max: Byte);
{procedure GetMeanAndSigma(var Mean, sd: Single);}
function Max: Byte;
function Min: Byte;
{procedure MultiplyWith(Factor: Single);}
{procedure ReDim(NewSize: Longint);}
{procedure SortAscending;}
procedure Subtract(other: TBigByteArray);
{function Sum: Single;}
procedure WriteBinary( var F: File );
property Address: Pointer read FAddress;
property Count: Longint read FCount;
property Value[i: Longint]: Byte read GetVal write SetVal; default;
end; { TBigByteArray }
TByteArray2D = class(TObject)
{ Not TBigByteArray as ancestor because that would make it impossible
to declare a new default array property. It also hides the Count property,
so it is more difficult to mistakenly use it as a TBigByteArray }
private
Values: TBigByteArray;
FCount1, FCount2: Longint;
function GetTotalCount: Longint;
function GetVal(i1, i2: Longint): Byte;
procedure SetVal(i1, i2: Longint; value: Byte);
public
constructor Create(N1, N2: Longint);
destructor Destroy; override;
constructor Dim(N1, N2: Longint);
constructor ReadBinary(var F: File);
procedure Clear;
function Copy: TByteArray2D;
{procedure CopyRow(RowNo: Longint; var Row: TBigByteArray);}
function CopyRow(RowNo: Longint): TBigByteArray;
procedure FindMax(var i1, i2: Longint; var max: Byte);
procedure FindMinMax(var min, max: Byte);
function Max: Byte;
function Min: Byte;
procedure MirrorX;
procedure MirrorY;
{procedure MultiplyWith( Factor: Single);}
procedure SetRow(ColNo: Integer; RowValues: TBigByteArray);
{function Sum: Single;}
function SumColumns: TBigByteArray;
procedure Transpose;
procedure WriteBinary( var F: File );
property TotalCount: Longint read GetTotalCount;
property Count1: Longint read FCount1;
property Count2: Longint read FCount2;
property Value[i, j: Longint]: Byte read GetVal write SetVal; default;
end; { TByteArray2D }
{const
{MaxSingle: Single = 3.4E38;
NoValue: Single = -1e20;}
procedure ReDim(var AnArray: TBigByteArray; NewSize: Longint);
implementation
uses
{$ifdef ver80}
HeapUnit, { Imports BigGetMem }
{$endif}
// MoreUtil, { Imports CRLF }
SysUtils; { Imports IntToStr }
type
EIndexOutOfBounds = class(Exception);
ENotEnoughMemory = class(Exception);
procedure Error(msg: String);
begin
raise Exception.Create(msg);
end;
procedure AddToAddress(var P: Pointer; Count: Longint);
begin { AddToAddress }
{$ifdef ver80}
if Count > 64000
then heapunit.AddToAddress(P, Count)
else P := Pointer(Longint(P)+Count);
{$else}
P := Pointer(Longint(P)+Count);
{$endif}
end; { AddToAddress }
procedure ReDim(var AnArray: TBigByteArray; NewSize: Longint);
var Result: TBigByteArray;
TotalSize: Longint;
begin { TBigByteArray.ReDim }
TotalSize := AnArray.Count * SizeOf(Byte);
Result := TBigByteArray.Create(NewSize);
Move(AnArray.FAddress^, Result.FAddress^, TotalSize);
AnArray.Free;
AnArray := Result;
end; { TBigByteArray.ReDim }
(***** methods of TBigByteArray *****)
constructor TBigByteArray.Create(N: Longint);
{ Creates one dimensional array }
var
TotalSize: Longint;
ErrorMessage: String;
begin { TBigByteArray.Create }
inherited create;
FCount := N;
TotalSize := Longint(Count) * SizeOf(Byte);
{$ifdef ver80}
BigGetMem(FAddress, TotalSize);
{$else}
GetMem(FAddress, TotalSize);
{$endif}
if (Address = nil) and (TotalSize <> 0)
then begin
ErrorMessage :=
'error in TBigByteArray.create: '+
'Not enough contiguous memory available' {+ CRLF} +
' requested memory block: '+ IntToStr(TotalSize) +' bytes'{+ CRLF +
' largest memory block: '+ IntToStr(maxavail) +' bytes'+ CRLF +
' total free memory: '+ IntToStr(memavail) +' bytes'};
raise ENotEnoughMemory.Create(ErrorMessage)
end;
end; { TBigByteArray.Create }
destructor TBigByteArray.Destroy;
{ Disposes array }
var
TotalSize: Longint;
begin { TBigByteArray.Destroy }
TotalSize := Count * SizeOf(Byte);
{$ifdef ver80}
BigFreeMem(FAddress, TotalSize);
{$else}
FreeMem(FAddress, TotalSize);
{$endif ver80}
FCount := 0;
inherited Destroy;
end; { TBigByteArray.Destroy }
constructor TBigByteArray.Dim(N: Longint);
{ Creates one dimensional array, sets values to zero }
begin { TBigByteArray.Dim }
Create(N);
Clear;
end; { TBigByteArray.Dim }
(***** end of constructors and destructors *****)
(***** field access methods *****)
function TBigByteArray.GetVal(index: Longint): Byte;
{ Gets value of array element }
var
p: Pointer;
value: Byte;
begin { TBigByteArray.GetVal }
if (index < 1) or (index > Count)
then raise EIndexOutOfBounds.Create('Dynamic array index out of bounds');
p := Address;
AddToAddress(p, (index-1) * SizeOf(Byte));
Move(p^, value, SizeOf(Byte));
GetVal := value;
end; { TBigByteArray.GetVal }
procedure TBigByteArray.SetVal(index: Longint; value: Byte);
{ Sets value of array element }
var
p: Pointer;
begin { TBigByteArray.SetVal }
if (index < 1) or (index > Count)
then raise EIndexOutOfBounds.Create('Dynamic array index out of bounds');
p := FAddress;
AddToAddress(p, (index-1) * SizeOf(Byte));
Move(value, p^, SizeOf(Byte));
end; { TBigByteArray.SetVal }
(***** end of the field access methods *****)
procedure TBigByteArray.Append(AppendArray: TBigByteArray);
{ Append AppendArray at the end of 'self'.
Note that the implementation can be a lot optimized for speed
by moving blocks of memory in stead of one element at a time }
var TempArray: TBigByteArray;
i: Longint;
begin { TBigByteArray.Append }
TempArray := Self.Copy;
Self.Free;
Create(Count + appendarray.Count);
for i := 1 to Count
do Self[i] := TempArray[i];
for i := 1 to AppendArray.Count
do Self[Count+i] := AppendArray[i];
TempArray.Free;
end; { TBigByteArray.Append }
(*function TBigByteArray.Average: Single;
var sum: Single;
i, N: Longint;
begin { TBigByteArray.Average }
sum := 0;
N := 0;
for i := 1 to count
do begin
if Value[i] <> NoValue
then begin
Inc(N);
sum := sum + Value[i];
end;
end;
if N <> 0
then Average := sum / N
else Average := NoValue
end; { TBigByteArray.Average }*)
procedure TBigByteArray.Clear;
{ Assigns zero to all elements }
var
TotalSize: Longint;
begin { TBigByteArray.Clear }
TotalSize := Count * SizeOf(Byte);
{$ifdef ver80}
BigFillChar(FAddress, TotalSize, chr(0));
{$else}
FillChar(FAddress^, TotalSize, chr(0));
{$endif ver80}
end; { TBigByteArray.Clear }
function TBigByteArray.Copy: TBigByteArray;
{ Creates a copy of the array }
begin { TBigByteArray.Copy }
Result := TBigByteArray.Create(Count);
{$ifdef ver80}
BigMove(FAddress, Result.FAddress, Count * SizeOf(Byte));
{$else}
Move(FAddress^, Result.FAddress^, Count * SizeOf(Byte));
{$endif ver80}
end; { TBigByteArray.Copy }
function TBigByteArray.EqualTo(OtherArray: TBigByteArray): Boolean;
var index: Longint;
begin { TBigByteArray.EqualTo }
Result := True;
if Count <> OtherArray.Count
then Result := False
else begin
Index := 1;
while (Result = True) and (index <= Count)
do begin
if GetVal(Index) <> OtherArray[Index]
then Result := False
else Inc(Index);
end
end;
end; { TBigByteArray.EqualTo }
procedure TBigByteArray.FillWith(Value: Byte);
var i: Longint;
begin { TBigByteArray.FillWith }
for i := 1 to Count
do Self[i] := Value;
end; { TBigByteArray.FillWith }
procedure TBigByteArray.FindMax(var i: Longint; var max: Byte);
var j: Longint;
value: Byte;
begin { TBigByteArray.FindMax }
max := 0;
for j := 1 to Count
do begin
value := GetVal(j);
if value > max
then begin
i := j;
max := value;
end;
end;
end; { TBigByteArray.FindMax }
procedure TBigByteArray.FindMinMax(var min, max: Byte);
var j: Longint;
value: Byte;
begin { TBigByteArray.FindMinMax }
min := 255;
max := 0;
for j := 1 to Count
do begin
value := GetVal(j);
if value < min
then min := value;
if value > max
then max := value;
end;
end; { TBigByteArray.FindMinMax }
(*procedure TBigByteArray.GetMeanAndSigma(var Mean, sd: Single);
{ calculates mean and standard deviation of elements }
var
i, N: longint;
value, Sum, SumOfSquares, MeanOfSquares: single;
begin { TBigByteArray.GetMeanAndSigma }
SumOfSquares := 0;
Sum := 0;
N := 0;
for i := 1 to Count
do begin
value := GetVal(i);
if Value <> NoValue
then begin
Inc(N);
Sum := Sum + value;
SumOfSquares := SumOfSquares + sqr(value);
end;
end;
if N = 0
then begin
Mean := NoValue;
Sd := NoValue;
end
else begin
Mean := Sum / N;
MeanOfSquares := SumOfSquares / N;
if (MeanOfSquares - Sqr(Mean)) < 0 { should only be possible }
then sd := 0 {in case of rounding off errors }
else sd := Sqrt( MeanOfSquares - Sqr(Mean) );
end
end; { TBigByteArray.GetMeanAndSigma }*)
function TBigByteArray.Max: Byte;
var maximum: Byte;
i: Longint;
begin { TBigByteArray.Max }
maximum := 0;
for i := 1 to count
do if Value[i] > maximum
then maximum := Value[i];
Max := maximum;
end; { TBigByteArray.Max }
function TBigByteArray.Min: Byte;
var minimum, v: Byte;
i: Longint;
begin { TBigByteArray.Min }
minimum := 255;
for i := 1 to count
do begin
v := Value[i];
if v < minimum
then minimum := v;
end;
Min := minimum;
end; { TBigByteArray.Min }
(*procedure TBigByteArray.MultiplyWith(Factor: Single);
{ Multiplies all elements values with factor }
var i: Longint;
v: Single;
begin { TBigByteArray.MultiplyWith }
for i := 1 to Count
do begin
v := Value[i];
if v <> NoValue
then Value[i] := v * Factor;
end;
end; { TBigByteArray.MultiplyWith }*)
constructor TBigByteArray.ReadBinary(var F: File);
{ reads TBigByteArray from untyped file }
var
size, result: longint;
wresult: Integer;
begin { TBigByteArray.ReadBinary }
BlockRead(F, FCount, SizeOf(FCount), wresult);
Create(Count);
size := Count * SizeOf(Byte);
{$ifdef ver80}
BigBlockRead(F, FAddress^, size, result);
{$else}
BlockRead(F, FAddress^, size, result);
{$endif ver80}
if size <> result
then Error('Error in TBigByteArray.ReadBinary: ' +
'read number of bytes <> size');
end; { TBigByteArray.ReadBinary }
(*procedure TBigByteArray.ReDim(NewSize: Longint);
var SelfCopy: TBigByteArray;
TotalSize: Longint;
begin { TBigByteArray.ReDim }
TotalSize := Count * SizeOf(Byte);
SelfCopy := Self.Copy;
Self.Free;
Create(NewSize);
Move(SelfCopy.FAddress^, FAddress^, TotalSize);
SelfCopy.Free;
end; { TBigByteArray.ReDim }*)
(*
procedure TBigByteArray.SortAscending;
{ sorts the array ascending; may also be used for more than one-dimensional
dynamicarrays }
PROCEDURE store_tree( root: nodepointer;
destination: TBigByteArray;
VAR currentindex: longint);
BEGIN { store_tree }
IF root <> Nil
THEN BEGIN
store_tree(root^.ltree, destination, currentindex);
destination[currentindex] := root^.value;
Inc(currentindex);
store_tree(root^.rtree, destination, currentindex);
END;
END; { store_tree }
VAR tree: avltreetype;
i: longint;
newvalue, treeval: nodepointer;
begin { TBigByteArray.SortAscending }
tree.init;
FOR i := 1 TO Count
DO BEGIN
tree.insert(Value[i]);
{progressproc(0.8*i/nr_of_elements);}
{ Not up to 100% because tree.done requires some time too }
{ Tested: progressproc can take 50% of total time! }
END;
i := 1; { must be a var-parameter for store_tree }
store_tree(tree.root, self, i);
tree.done;
{progressproc(1);}
end; { TBigByteArray.SortAscending }
*)
procedure TBigByteArray.Subtract(other: TBigByteArray);
{ Subtracts the values of 'other' from the values of 'self' }
var i: Longint;
begin { TBigByteArray.Subtract }
for i := 1 to Count
do SetVal(i, Self[i] - other[i])
end; { TBigByteArray.Subtract }
(*function TBigByteArray.Sum: Single;
{ Returns the sum of the values of the elements }
var i: Longint;
s: Single;
begin { TBigByteArray.Sum }
s := 0;
for i := 1 to Count
do if GetVal(i) <> NoValue
then s := s + GetVal(i);
Sum := s;
end; { TBigByteArray.Sum }*)
procedure TBigByteArray.WriteBinary( var F: File );
{ writes TBigByteArray to untyped file }
var
size, result: longint;
wresult: Integer;
begin { TBigByteArray.WriteBinary }
size := SizeOf(FCount);
BlockWrite(F, FCount, size, wresult);
size := Count * SizeOf(Byte);
{$ifdef ver80}
BigBlockWrite(F, FAddress^, size, result);
{$else}
BlockWrite(F, FAddress^, size, result);
{$endif ver80}
if size <> result
then Error('Error in TBigByteArray.WriteBinary: ' +
'written number of bytes <> size');
end; { TBigByteArray.WriteBinary }
(***** end of TBigByteArray *****)
constructor TByteArray2D.Create(N1, N2: Longint);
begin { TByteArray2D.Create }
inherited Create;
values := TBigByteArray.Create(N1*N2);
FCount1 := N1;
FCount2 := N2;
end; { TByteArray2D.Create }
destructor TByteArray2D.Destroy;
begin { TByteArray2D.Destroy }
Values.Free;
FCount1 := 0;
FCount2 := 0;
inherited Destroy;
end; { TByteArray2D.Destroy }
constructor TByteArray2D.Dim(N1, N2: Longint);
begin { TByteArray2D.Dim }
inherited Create;
values := TBigByteArray.Dim(N1*N2);
FCount1 := N1;
FCount2 := N2;
end; { TByteArray2D.Dim }
(***** end of constructors and destructors *****)
procedure TByteArray2D.Clear;
{ Assigns zero to all elements }
begin { TByteArray2D.Clear }
Values.Clear;
end; { TByteArray2D.Clear }
function TByteArray2D.Copy: TByteArray2D;
begin { TByteArray2D.Copy }
Result := TByteArray2D.Create(Count1, Count2);
{$ifdef ver80}
BigMove(Values.FAddress, Result.Values.FAddress, Values.Count * SizeOf(Byte));
{$else}
Move(Values.FAddress^, Result.Values.FAddress^, Values.Count * SizeOf(Byte));
{$endif ver80}
end; { TByteArray2D.Copy }
function TByteArray2D.CopyRow(RowNo: Longint): TBigByteArray;
var
FSource: Pointer;
begin { TByteArray2D.CopyRow }
Result := TBigByteArray.Create(Count1);
FSource := Values.FAddress;
AddToAddress(FSource, ((RowNo-1)*Count1)*SizeOf(Byte) );
{$ifdef ver80}
BigMove(FSource, Result.FAddress, Count1*SizeOf(Byte));
{$else}
Move(FSource^, Result.FAddress^, Count1*SizeOf(Byte));
{$endif ver80}
end; { TByteArray2D.CopyRow }
function TByteArray2D.GetTotalCount: Longint;
begin
Result := Values.Count;
end;
function TByteArray2D.GetVal(i1, i2: Longint): Byte;
begin
Result := Values[i1+(i2-1)*Count1];
end;
procedure TByteArray2D.SetVal(i1, i2: Longint; value: Byte);
begin
Values[i1+(i2-1)*Count1] := Value;
end;
procedure TByteArray2D.FindMax(var i1, i2: Longint; var max: Byte);
var i: Longint;
begin
Values.FindMax(i, max);
i1 := (i-1) mod Count1 + 1;
i2 := (i-1) div Count1 + 1;
end;
procedure TByteArray2D.FindMinMax(var min, max: Byte);
begin
Values.FindMinMax(min, max);
end;
function TByteArray2D.Max: Byte;
begin
Result := Values.Max;
end;
function TByteArray2D.Min: Byte;
begin
Result := Values.Min;
end;
procedure TByteArray2D.MirrorX;
{ Inverses order of elements in y-direction }
var SelfCopy: TByteArray2D;
ix, iy: longint;
begin { TByteArray2D.MirrorX }
SelfCopy := Self.Copy;
Self.Free;
Create(SelfCopy.Count1, SelfCopy.Count2);
for ix := 1 to Count1
do for iy := 1 to Count2
do Self[ix, iy] := SelfCopy[Count1-ix+1, iy];
SelfCopy.Free;
end; { TByteArray2D.MirrorX }
procedure TByteArray2D.MirrorY;
{ Inverses order of elements in x-direction }
var SelfCopy: TByteArray2D;
ix, iy: longint;
begin { TByteArray2D.MirrorY }
SelfCopy := Self.Copy;
Self.Free;
Create(SelfCopy.Count1, SelfCopy.Count2);
for ix := 1 to Count1
do for iy := 1 to Count2
do Self[ix, iy] := SelfCopy[ix, Count2-iy+1];
SelfCopy.Free;
end; { TByteArray2D.MirrorY }
(*procedure TByteArray2D.MultiplyWith( Factor: Single);
begin { TByteArray2D.MultiplyWith }
Values.MultiplyWith( Factor);
end; { TByteArray2D.MultiplyWith }*)
constructor TByteArray2D.ReadBinary( var F: File );
{ reads TByteArray2D from untyped fyle }
var
size, result: longint;
wresult: Integer;
begin { TByteArray2D.ReadBinary }
BlockRead( F, FCount1, SizeOf(FCount1), wresult );
BlockRead( F, FCount2, SizeOf(FCount2), wresult );
Create( Count1, Count2);
size := TotalCount * SizeOf( Byte);
{$ifdef ver80}
BigBlockRead(F, Values.FAddress^, size, result);
{$else}
BlockRead(F, Values.FAddress^, size, result);
{$endif}
if size <> result
then Error('Error in TByteArray2D.ReadBinary: ' +
'read number of bytes <> size');
end; { TByteArray2D.ReadBinary }
procedure TByteArray2D.SetRow(ColNo: Integer; RowValues: TBigByteArray);
var
RowSize: Longint;
InsertAddress: Pointer;
begin { TByteArray2D.SetRow }
if (ColNo < 1) or (ColNo > Count2)
then raise EIndexOutOfBounds.Create('Dynamic array index out of bounds');
if RowValues.Count <> Count1
then Error('Row doesn''t have equal number of elements as Matrix row');
RowSize := Count1*SizeOf(Byte);
InsertAddress := Values.FAddress;
AddToAddress(InsertAddress, (ColNo-1)*RowSize);
Move(RowValues.FAddress^, InsertAddress^, RowSize);
end; { TByteArray2D.SetRow }
(*function TByteArray2D.Sum: Byte;
begin
end;*)
function TByteArray2D.SumColumns: TBigByteArray;
var sum: Byte;
Row, Column: Longint;
begin { TByteArray2D.SumColumns }
Result := TBigByteArray.Create(FCount1);
for Row := 1 to FCount1
do begin
sum := 0;
for Column := 1 to FCount2
do begin
sum := sum + Self[Row, Column];
end;
Result[Row] := sum;
end;
end; { TByteArray2D.SumColumns }
procedure TByteArray2D.Transpose;
{ Inverts rows and columns }
var SelfCopy: TByteArray2D;
i1, i2: longint;
begin { TByteArray2D.Transpose }
SelfCopy := Self.Copy;
Self.Free;
Create(SelfCopy.Count2, SelfCopy.Count1);
for i1 := 1 to Count1
do for i2 := 1 to Count2
do Self[i1, i2] := SelfCopy[i2, i1];
SelfCopy.Free;
end; { TByteArray2D.Transpose }
procedure TByteArray2D.WriteBinary( var F: File );
{ writes TByteArray2D to untyped file }
var
size, result: longint;
wresult: Integer;
begin { TByteArray2D.WriteBinary }
BlockWrite( F, FCount1, SizeOf(FCount1), wresult );
BlockWrite( F, FCount2, SizeOf(FCount2), wresult );
size := TotalCount * SizeOf( Byte);
{$ifdef ver80}
BigBlockWrite( F, Values.FAddress^, size, result );
{$else}
BlockWrite( F, Values.FAddress^, size, result );
{$endif}
if size <> result
then Error('Error in TByteArray2D.WriteBinary: ' +
'written number of bytes <> size')
end; { TByteArray2D.WriteBinary }
(***** end of TByteArray2D *****)
end.
|
unit nsSaveDialogExecutor;
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Common\nsSaveDialogExecutor.pas"
// Стереотип: "Service"
// Элемент модели: "TnsSaveDialogExecutor" MUID: (573A0A7E0387)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3IntfUses
, l3ProtoObject
, nsSaveDialog
, nsTypes
, PresentationInterfaces
;
(*
MnsSaveDialogExecutor = interface
{* Контракт сервиса TnsSaveDialogExecutor }
function Call(aDialog: TnsSaveDialog): Boolean;
function GetFileName: AnsiString;
procedure SetFileName(const aName: AnsiString);
procedure SetFileFormat(aFileFormat: TnsFileFormat);
procedure SetSaveObjects(aValue: TnsSaveDialogListTarget);
procedure SetMergeFiles(aValue: Boolean);
procedure SetSelectedOnly(aValue: Boolean);
end;//MnsSaveDialogExecutor
*)
type
InsSaveDialogExecutor = interface
{* Интерфейс сервиса TnsSaveDialogExecutor }
function Call(aDialog: TnsSaveDialog): Boolean;
function GetFileName: AnsiString;
procedure SetFileName(const aName: AnsiString);
procedure SetFileFormat(aFileFormat: TnsFileFormat);
procedure SetSaveObjects(aValue: TnsSaveDialogListTarget);
procedure SetMergeFiles(aValue: Boolean);
procedure SetSelectedOnly(aValue: Boolean);
end;//InsSaveDialogExecutor
TnsSaveDialogExecutor = {final} class(Tl3ProtoObject)
private
f_Alien: InsSaveDialogExecutor;
{* Внешняя реализация сервиса InsSaveDialogExecutor }
protected
procedure pm_SetAlien(const aValue: InsSaveDialogExecutor);
procedure ClearFields; override;
public
function Call(aDialog: TnsSaveDialog): Boolean;
function GetFileName: AnsiString;
procedure SetFileName(const aName: AnsiString);
procedure SetFileFormat(aFileFormat: TnsFileFormat);
procedure SetSaveObjects(aValue: TnsSaveDialogListTarget);
procedure SetMergeFiles(aValue: Boolean);
procedure SetSelectedOnly(aValue: Boolean);
class function Instance: TnsSaveDialogExecutor;
{* Метод получения экземпляра синглетона TnsSaveDialogExecutor }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
public
property Alien: InsSaveDialogExecutor
write pm_SetAlien;
{* Внешняя реализация сервиса InsSaveDialogExecutor }
end;//TnsSaveDialogExecutor
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3ImplUses
{$If Defined(InsiderTest) AND NOT Defined(NoScripts)}
, nsSaveDialogImpl
{$IfEnd} // Defined(InsiderTest) AND NOT Defined(NoScripts)
{$If NOT Defined(NoScripts)}
, SaveDialogWordsPack
{$IfEnd} // NOT Defined(NoScripts)
, SysUtils
, l3Base
//#UC START# *573A0A7E0387impl_uses*
//#UC END# *573A0A7E0387impl_uses*
;
var g_TnsSaveDialogExecutor: TnsSaveDialogExecutor = nil;
{* Экземпляр синглетона TnsSaveDialogExecutor }
procedure TnsSaveDialogExecutorFree;
{* Метод освобождения экземпляра синглетона TnsSaveDialogExecutor }
begin
l3Free(g_TnsSaveDialogExecutor);
end;//TnsSaveDialogExecutorFree
procedure TnsSaveDialogExecutor.pm_SetAlien(const aValue: InsSaveDialogExecutor);
begin
Assert((f_Alien = nil) OR (aValue = nil));
f_Alien := aValue;
end;//TnsSaveDialogExecutor.pm_SetAlien
function TnsSaveDialogExecutor.Call(aDialog: TnsSaveDialog): Boolean;
//#UC START# *573A0E8C0257_573A0A7E0387_var*
//#UC END# *573A0E8C0257_573A0A7E0387_var*
begin
//#UC START# *573A0E8C0257_573A0A7E0387_impl*
if Assigned(f_Alien) then
Result := f_Alien.Call(aDialog)
else
Result := aDialog.Execute;
//#UC END# *573A0E8C0257_573A0A7E0387_impl*
end;//TnsSaveDialogExecutor.Call
function TnsSaveDialogExecutor.GetFileName: AnsiString;
//#UC START# *57447EC501FC_573A0A7E0387_var*
//#UC END# *57447EC501FC_573A0A7E0387_var*
begin
//#UC START# *57447EC501FC_573A0A7E0387_impl*
if Assigned(f_Alien) then
Result := f_Alien.GetFileName
else
Assert(False);
//#UC END# *57447EC501FC_573A0A7E0387_impl*
end;//TnsSaveDialogExecutor.GetFileName
procedure TnsSaveDialogExecutor.SetFileName(const aName: AnsiString);
//#UC START# *5811C5A001F6_573A0A7E0387_var*
//#UC END# *5811C5A001F6_573A0A7E0387_var*
begin
//#UC START# *5811C5A001F6_573A0A7E0387_impl*
if Assigned(f_Alien) then
f_Alien.SetFileName(aName)
else
Assert(False);
//#UC END# *5811C5A001F6_573A0A7E0387_impl*
end;//TnsSaveDialogExecutor.SetFileName
procedure TnsSaveDialogExecutor.SetFileFormat(aFileFormat: TnsFileFormat);
//#UC START# *57447EFA00A1_573A0A7E0387_var*
//#UC END# *57447EFA00A1_573A0A7E0387_var*
begin
//#UC START# *57447EFA00A1_573A0A7E0387_impl*
if Assigned(f_Alien) then
f_Alien.SetFileFormat(aFileFormat)
else
Assert(False);
//#UC END# *57447EFA00A1_573A0A7E0387_impl*
end;//TnsSaveDialogExecutor.SetFileFormat
procedure TnsSaveDialogExecutor.SetSaveObjects(aValue: TnsSaveDialogListTarget);
//#UC START# *57FCE260011C_573A0A7E0387_var*
//#UC END# *57FCE260011C_573A0A7E0387_var*
begin
//#UC START# *57FCE260011C_573A0A7E0387_impl*
if Assigned(f_Alien) then
f_Alien.SetSaveObjects(aValue)
else
Assert(False);
//#UC END# *57FCE260011C_573A0A7E0387_impl*
end;//TnsSaveDialogExecutor.SetSaveObjects
procedure TnsSaveDialogExecutor.SetMergeFiles(aValue: Boolean);
//#UC START# *57FCE36B0114_573A0A7E0387_var*
//#UC END# *57FCE36B0114_573A0A7E0387_var*
begin
//#UC START# *57FCE36B0114_573A0A7E0387_impl*
if Assigned(f_Alien) then
f_Alien.SetMergeFiles(aValue)
else
Assert(False);
//#UC END# *57FCE36B0114_573A0A7E0387_impl*
end;//TnsSaveDialogExecutor.SetMergeFiles
procedure TnsSaveDialogExecutor.SetSelectedOnly(aValue: Boolean);
//#UC START# *57FCE99E0115_573A0A7E0387_var*
//#UC END# *57FCE99E0115_573A0A7E0387_var*
begin
//#UC START# *57FCE99E0115_573A0A7E0387_impl*
if Assigned(f_Alien) then
f_Alien.SetSelectedOnly(aValue)
else
Assert(False);
//#UC END# *57FCE99E0115_573A0A7E0387_impl*
end;//TnsSaveDialogExecutor.SetSelectedOnly
class function TnsSaveDialogExecutor.Instance: TnsSaveDialogExecutor;
{* Метод получения экземпляра синглетона TnsSaveDialogExecutor }
begin
if (g_TnsSaveDialogExecutor = nil) then
begin
l3System.AddExitProc(TnsSaveDialogExecutorFree);
g_TnsSaveDialogExecutor := Create;
end;
Result := g_TnsSaveDialogExecutor;
end;//TnsSaveDialogExecutor.Instance
class function TnsSaveDialogExecutor.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_TnsSaveDialogExecutor <> nil;
end;//TnsSaveDialogExecutor.Exists
procedure TnsSaveDialogExecutor.ClearFields;
begin
Alien := nil;
inherited;
end;//TnsSaveDialogExecutor.ClearFields
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
end.
|
unit alcuPusa;
{ Панель управления Сервером Архивариуса }
interface
uses
Classes, SysUtils,
l3Base, l3ObjectRefList,
csClientCommandsManager, alcuTypes,
csClient, csNotification, CsDataPipe, ddServerTask, csProcessTask,
jclSvcCtrl;
type
TalcuPusa = class(Tl3Base)
private
f_Client: TCsClient;
f_CommandsManager: TcsClientCommandsManager;
f_IsBaseLocked: Boolean;
f_LastError: string;
f_OnServerStatus: TNotifyEvent;
f_OnTaskListChanged: TTaskListRefreshEvent;
f_OnUserListUpdated: TddUserListNotify;
f_Service: TJclNtService;
f_ServiceManager: TJclSCManager;
f_TickCount: Integer;
procedure ClearServerInfo;
function Connect: Boolean;
procedure CreateConfig;
procedure CreateManager;
procedure DestroyConfig;
procedure DestroyManager;
procedure Disconnect;
function FindService: Boolean;
procedure GetAllLine(aPipe: TcsDataPipe);
function GetAnnoExportEnabled: Boolean;
function GetAutoClassEnabled: Boolean;
function GetExportEnabled: Boolean;
function GetImportEnabled: Boolean;
procedure GetServerInfo;
function OnNotif(aNotificationType: TCsNotificationType; aNumber: Integer; const aText: string): Boolean;
function pm_GetEnableQueryProcessing: Boolean;
function pm_GetIsConnected: Boolean;
function pm_GetServerRunning: Boolean;
function pm_GetServiceInstalled: Boolean;
function pm_GetServiceStatus: TJclServiceState;
function pm_GetTaskByIndex(Index: Integer): TddProcessTask;
function pm_GetTaskListCount: Integer;
procedure pm_SetEnableQueryProcessing(const aValue: Boolean);
procedure pm_SetIsBaseLocked(const aValue: Boolean);
procedure SetAnnoExportEnabled(const Value: Boolean);
procedure SetAutoClassEnabled(const Value: Boolean);
procedure SetExportEnabled(const Value: Boolean);
procedure SetImportEnabled(const Value: Boolean);
function Timeout: Integer;
procedure WorkE(E: Exception);
procedure _ReadBaseStatus(aPipe: TcsDataPipe);
protected
procedure Cleanup; override;
procedure ClearCommands;
function GetTaskByIndex(Index: Integer): TddProcessTask;
public
constructor Create(aOwner: TObject); override;
procedure ConfigService;
procedure ContinueService;
procedure GetServerCommands;
function InstallService: Boolean;
function PauseService: Boolean;
function PingServer: Boolean;
procedure RestartManager;
function StartService: Boolean;
function StopService: Boolean;
function UninstallService: Boolean;
procedure UpdateTaskList;
procedure UpdateUserList;
procedure UpdateActiveUserList;
procedure UpdateBaseStatus;
property AnnoExportEnabled: Boolean read GetAnnoExportEnabled write SetAnnoExportEnabled;
property AutoClassEnabled: Boolean read GetAutoClassEnabled write SetAutoClassEnabled;
property CommandsManager: TcsClientCommandsManager read f_CommandsManager;
property EnableQueryProcessing: Boolean
read pm_GetEnableQueryProcessing
write pm_SetEnableQueryProcessing;
property ExportEnabled: Boolean read GetExportEnabled write SetExportEnabled;
property ImportEnabled: Boolean read GetImportEnabled write SetImportEnabled;
property IsBaseLocked: Boolean read f_IsBaseLocked write pm_SetIsBaseLocked;
property IsConnected: Boolean read pm_GetIsConnected;
property LastError: string read f_LastError;
property ServerRunning: Boolean read pm_GetServerRunning;
property ServiceInstalled: Boolean read pm_GetServiceInstalled;
property ServiceStatus: TJclServiceState read pm_GetServiceStatus;
property TaskByIndex[Index: Integer]: TddProcessTask read pm_GetTaskByIndex;
property TaskListCount: Integer read pm_GetTaskListCount;
property OnServerStatus: TNotifyEvent
read f_OnServerStatus
write f_OnServerStatus;
property OnTaskListChanged: TTaskListRefreshEvent read f_OnTaskListChanged write f_OnTaskListChanged;
property OnUserListUpdated: TddUserListNotify read f_OnUserListUpdated write f_OnUserListUpdated;
end;
implementation
Uses
csUserRequestManager, ddAppConfig,
csQueryTypes,
StrUtils, l3ObjectRefList1, ActnList, math,
alcuConfig, ddIniStorage, alcuStrings,
Dialogs, WinSvc, ddConfigStorages, csTaskTypes;
constructor TalcuPusa.Create(aOwner: TObject);
begin
inherited;
CreateConfig;
f_Client := TCsClient.Create;
f_Client.OnNotification := OnNotif;
UserRequestManager.CSClient:= f_Client;
f_CommandsManager:= TcsClientCommandsManager.Create(nil);
f_CommandsManager.CSClient:= f_Client;
(*TODO: extracted code
try
f_ServiceManager:= TJclSCManager.Create(ddAppConfiguration.AsString['ServerName'], DefaultSCMDesiredAccess or SC_MANAGER_CREATE_SERVICE);
except
l3Free(f_ServiceManager);
ddAppConfiguration.AsString['ServerName']:= '';
end;
*)
CreateManager;
f_TickCount:= 0;
end;
procedure TalcuPusa.Cleanup;
begin
Disconnect;
DestroyConfig;
l3Free(f_CommandsManager);
DestroyManager;
inherited;
end;
procedure TalcuPusa.ClearCommands;
begin
f_CommandsManager.ClearCommands;
end;
procedure TalcuPusa.ClearServerInfo;
begin
// TODO -cMM: TalcuPusa.ClearServerInfo default body inserted
end;
procedure TalcuPusa.ConfigService;
var
l_Storage: TddIniStorage;
l_Config: TddAppConfiguration;
begin
if ddAppConfiguration.AsString['ServerConfig'] <> '' then
begin
l_Storage:= TddIniStorage.Create(ddAppConfiguration.AsString['ServerConfig']);
try
l_Config:= CreateConfigEx(l_Storage);
try
l_Config.AutoSave:= False;
if l_Config.ShowDialog('Настройки службы', True) then
l_Config.Save;
finally
l3Free(l_Config);
end;
finally
l3Free(l_Storage);
end;
end
else
alcuMsgDialog('Не указан путь к файлу конфигурации службы', mtError, [mbOk], 0);
end;
function TalcuPusa.Connect: Boolean;
begin
if not f_Client.IsStarted then
begin
f_Client.Start(ddAppConfiguration.AsString['ServerName'], ddAppConfiguration.AsInteger['ServerPort']);
if f_Client.IsStarted then
GetServerCommands
else
ClearCommands;
end;
Result:= f_Client.IsStarted;
end;
procedure TalcuPusa.ContinueService;
begin
f_Service.Continue(True);
end;
procedure TalcuPusa.CreateConfig;
begin
ddAppConfiguration:= TddAppConfiguration.Create(nil);
with ddAppConfiguration do
begin
AutoSize:= True;
AutoSave:= True;
FontName := 'Verdana';
AddNode('General', 'Основные');
AddStringItem('ServerName', 'Адрес сервера');
Hint:= 'Адрес сервера';
Required:= True;
AddIntegerItem(l3CStr('ServerPort'), l3CStr('Порт сервера'), 32100);
Hint:= 'Порт сервера';
Required:= True;
AddFileNameItem('ServiceFile', 'Файл службы');
Required:= True;
Hint:= 'файл с сервисом';
Filter:= 'Исполняемые Файлы (*.exe)|*.exe';
AddFileNameItem('ServerConfig', 'Настройки службы');
Hint:= 'Файл, в котором хранятся настройки службы';
Filter:= 'Файлы настроек (*.ini)|*.ini';
Required:= True;
AddIntegerItem(l3CStr('UpdateInterval'), l3CStr('Интервал обновления статуса службы|сек'), 5);
CloseChild;
Load;
end;
end;
procedure TalcuPusa.CreateManager;
begin
try
f_ServiceManager:= TJclSCManager.Create(ddAppConfiguration.AsString['ServerName'], DefaultSCMDesiredAccess or SC_MANAGER_CREATE_SERVICE);
except
l3Free(f_ServiceManager);
ddAppConfiguration.AsString['ServerName']:= '';
end;
end;
procedure TalcuPusa.DestroyConfig;
begin
if f_Client.IsStarted then
f_Client.Stop;
l3Free(f_Client);
l3Free(ddAppConfiguration);
end;
procedure TalcuPusa.DestroyManager;
begin
l3Free(f_ServiceManager);
end;
procedure TalcuPusa.Disconnect;
begin
f_Client.Stop;
end;
function TalcuPusa.FindService: Boolean;
begin
if f_LastError = '' then
try
f_Servicemanager.Refresh(True);
f_Servicemanager.FindService(cServiceName, f_Service);
except
on E: Exception do
WorkE(E);
end;
Result:= f_LastError = '';
end;
procedure TalcuPusa.GetAllLine(aPipe: TcsDataPipe);
begin
// TODO -cMM: TalcuPusa.GetAllLine default body inserted
end;
function TalcuPusa.GetAnnoExportEnabled: Boolean;
begin
// Result := cs_ttAnnoExport in UserRequestManager.EnabledTasks;
end;
function TalcuPusa.GetAutoClassEnabled: Boolean;
begin
// Result := cs_ttAutoClass in UserRequestManager.EnabledTasks;
end;
function TalcuPusa.GetExportEnabled: Boolean;
begin
// Result := cs_ttExport in UserRequestManager.EnabledTasks;
end;
function TalcuPusa.GetImportEnabled: Boolean;
begin
// Result := cs_ttImport in UserRequestManager.EnabledTasks;
end;
procedure TalcuPusa.GetServerCommands;
begin
f_Client.Exec(qtGetCommands, f_CommandsManager.LoadCommands);
end;
procedure TalcuPusa.GetServerInfo;
begin
UpdateUserList;
UpdateActiveUserList;
UpdateTaskList;
UpdateBaseStatus;
end;
function TalcuPusa.GetTaskByIndex(Index: Integer): TddProcessTask;
begin
(*
if InRange(Index, 0, UserRequestManager.TaskList.Hi) then
Result:= TddProcessTask(UserRequestManager.TaskList.Items[Index])
else
*) Result:= nil;
end;
function TalcuPusa.InstallService: Boolean;
begin
if not ServiceInstalled then
try
f_Service:= f_ServiceManager.Install(cServiceName, cServiceDisplayName,
ddAppConfiguration.AsString['ServiceFile'], 'Автоматизация процессов Архивариуса',
[stWin32OwnProcess], sstAuto);
except
on E: Exception do
f_LastError:= E.Message;
end;
Result:= ServiceInstalled;
end;
function TalcuPusa.OnNotif(aNotificationType: TCsNotificationType; aNumber: Integer; const aText: string): Boolean;
begin
Result:= True;
end;
function TalcuPusa.PauseService: Boolean;
begin
if ServerRunning then
begin
f_Service.Pause{(False);
f_Service.WaitFor(ssPaused, Timeout)};
f_Service.Refresh;
Result:= f_Service.ServiceState = ssPaused;
end
else
Result:= True;
end;
function TalcuPusa.PingServer: Boolean;
var
l_State : TJclServiceState;
begin
Result:= False;
l_State:= ssUnknown;
if (not ServiceInstalled) and (f_Servicemanager <> nil) then
begin
if not FindService then
exit
end
else
l_State:= f_Service.ServiceState;
if ServiceInstalled then
begin
f_Service.Refresh;
if (l_State <> f_Service.ServiceState) or (not IsConnected) then
begin
if f_Service.ServiceState = ssRunning then
begin
if Connect then
GetServerInfo
else
ClearServerInfo;
end; // f_Service.ServiceState = ssRunning
if Assigned(f_OnServerStatus) then
f_OnServerStatus(Self);
end // l_State <> f_Service.ServiceState
else
if f_Service.ServiceState = ssRunning then
begin
inc(f_TickCount);
if f_TickCount = 10 then
begin
UpdateActiveUserList;
UpdateTaskList;
f_TickCount:= 0;
end;
end;
end; // f_Servicemanager.FindService(cServiceName, l_Service)
Result:= True;
end;
function TalcuPusa.pm_GetEnableQueryProcessing: Boolean;
begin
Result := False;//UserRequestManager.ExecuteEnabled;
end;
function TalcuPusa.pm_GetIsConnected: Boolean;
begin
Result := f_Client.IsStarted;
end;
function TalcuPusa.pm_GetServerRunning: Boolean;
begin
Result := (ServiceInstalled) and (f_Service.ServiceState = ssRunning);
end;
function TalcuPusa.pm_GetServiceInstalled: Boolean;
begin
Result := (f_Service <> nil){ and (f_Service.Handle <> 0)};
end;
function TalcuPusa.pm_GetServiceStatus: TJclServiceState;
begin
if ServiceInstalled then
Result := f_Service.ServiceState
else
Result := ssUnknown;
end;
function TalcuPusa.pm_GetTaskByIndex(Index: Integer): TddProcessTask;
begin
(*
if InRange(Index, 0, UserRequestManager.TaskList.Hi) then
Result:= TddProcessTask(UserRequestManager.TaskList[Index])
else
*) Result:= nil;
end;
function TalcuPusa.pm_GetTaskListCount: Integer;
begin
Result := 0//UserRequestManager.TaskList.Count;
end;
procedure TalcuPusa.pm_SetEnableQueryProcessing(const aValue: Boolean);
begin
// TODO -cMM: TalcuPusa.pm_SetEnableQueryProcessing default body inserted
end;
procedure TalcuPusa.pm_SetIsBaseLocked(const aValue: Boolean);
begin
f_IsBaseLocked := aValue;
// Отправить команду на сервер
end;
procedure TalcuPusa.RestartManager;
begin
DestroyManager;
CreateManager;
end;
procedure TalcuPusa.SetAnnoExportEnabled(const Value: Boolean);
begin
end;
procedure TalcuPusa.SetAutoClassEnabled(const Value: Boolean);
begin
end;
procedure TalcuPusa.SetExportEnabled(const Value: Boolean);
begin
(*
if Value then
UserRequestManager.EnabledTasks := UserRequestManager.EnabledTasks + [cs_ttExport]
else
UserRequestManager.EnabledTasks := UserRequestManager.EnabledTasks - [cs_ttExport];
*)
end;
procedure TalcuPusa.SetImportEnabled(const Value: Boolean);
begin
end;
function TalcuPusa.StartService: Boolean;
begin
if ServiceInstalled then
begin
f_LastError:= '';
if not ServerRunning then
try
f_Service.Start{(False);
f_Service.WaitFor(ssRunning, Timeout)};
PingServer;
except
on E: Exception do
f_LastError:= E.Message;
end;
Result:= f_Service.ServiceState = ssRunning;
end
else
Result:= False;
end;
function TalcuPusa.StopService: Boolean;
begin
if ServiceInstalled then
begin
f_LastError:= '';
if ServerRunning then
try
f_Service.Stop{(False);
f_Service.WaitFor(ssRunning, Timeout)};
PingServer;
except
on E: Exception do
f_LastError:= E.Message;
end; // ServerRunning
Result:= f_Service.ServiceState in [ssUnknown, ssStopped];
end
else
Result:= True;
end;
function TalcuPusa.Timeout: Integer;
begin
Result := 30*1000;
end;
function TalcuPusa.UninstallService: Boolean;
begin
f_LastError:= '';
Result:= False;
if StopService then
if ServiceInstalled then
try
f_Service.Delete;
FindService;
Result:= not ServiceInstalled;
except
on E: Exception do
WorkE(E);
end
else
Result:= True
else
Result:= False;
end;
procedure TalcuPusa.UpdateTaskList;
begin
// Режим выполнения
//UserRequestManager.GetexecuteStatus;
// Очередь заданий
//UserRequestManager.GetLine;
end;
procedure TalcuPusa.UpdateUserList;
begin
// Список всех пользователей
//UserRequestManager.RequestUsersList;
end;
procedure TalcuPusa.UpdateActiveUserList;
var
i: Integer;
begin
// Список активных пользователей
(*
UserRequestManager.RequestActiveUserList;
if Assigned(f_OnUserListUpdated) then
for i:= 0 to Pred(UserRequestManager.ActiveUsersCount) do
f_OnUserListUpdated(UserRequestManager.ActiveUsers[i], True);
*)
end;
procedure TalcuPusa.UpdateBaseStatus;
begin
if f_Client.IsStarted then
f_Client.Exec(qtGetBaseStatus, _ReadBaseStatus);
end;
procedure TalcuPusa.WorkE(E: Exception);
begin
f_LastError:= E.Message;
l3System.Exception2Log(E);
end;
procedure TalcuPusa._ReadBaseStatus(aPipe: TcsDataPipe);
var
l_Msg: String;
begin
with aPipe do
begin
f_IsBaseLocked:= Boolean(ReadSmallInt);
l_Msg:= ReadStr;
end;
end;
end.
|
unit LowStuff;
interface
uses
windows, DirectSound;
type
TReadCallback = procedure(Data : pointer; Size : DWORD; UserData : pointer); stdcall;
function InitSoundEngine(Wnd : HWND) : BOOL; cdecl;
procedure DoneSoundEngine; cdecl;
function CreateSound(var Buffer : IDirectSoundBuffer; Size, Freq, Bits, Align : DWORD; Stereo : BOOL) : BOOL; cdecl;
function FillSound(Buffer : IDirectSoundBuffer; Size : DWORD; ReadData : TReadCallback; UserData : pointer) : BOOL; cdecl;
procedure StopsSound(Buffer : IDirectSoundBuffer); cdecl;
procedure PlaysSound(Buffer : IDirectSoundBuffer; LoopIt, RestartIt : BOOL; Pan, Volume, StartOfs : integer); cdecl;
procedure DuplicateSound(Buffer : IDirectSoundBuffer; var Clone : IDirectSoundBuffer); cdecl;
procedure SetsSoundPan(Buffer : IDirectSoundBuffer; Pan : integer); cdecl;
procedure SetsSoundVolume(Buffer : IDirectSoundBuffer; Volume : integer); cdecl;
function GetDSound: IDirectSound; cdecl;
function GetLibStatus: integer; cdecl;
implementation
uses
MMSystem;
var
pDSound : IDirectSound = nil;
LibStatus : integer = 0;
function InitSoundEngine(Wnd : HWND) : BOOL; cdecl;
begin
if succeeded(DirectSoundCreate(nil, pDSound, nil))
then
begin
if pDSound.SetCooperativeLevel(Wnd, DSSCL_NORMAL)=0
then
begin
LibStatus := integer(pDSound);
result := true;
end
else
begin
pDSound := nil;
result := false;
end;
end
else result := false;
end;
procedure DoneSoundEngine; cdecl;
begin
pDSound := nil;
LibStatus := 0;
end;
function CreateSound(var Buffer : IDirectSoundBuffer; Size, Freq, Bits, Align : DWORD; Stereo : BOOL) : BOOL; cdecl;
var
dsCaps : TDSCaps;
pcmwf : TWaveFormatEx;
BufferDesc: TDSBufferDesc;
begin
if (pDSound<>nil)
then
begin
fillchar(dsCaps, sizeof(dsCaps), 0);
dsCaps.dwSize := sizeof(dsCaps);
pDSound.GetCaps(dsCaps);
// Set up wave format structure.
fillchar(pcmwf, sizeof(pcmwf), 0);
with pcmwf do
begin
wFormatTag := WAVE_FORMAT_PCM;
if Stereo
then nChannels := 2
else nChannels := 1;
nSamplesPerSec := Freq;
nBlockAlign := Align;
nAvgBytesPerSec := nSamplesPerSec * nBlockAlign;
wBitsPerSample := Bits;
// Set up DSBUFFERDESC structure.
fillchar(BufferDesc, sizeof(BufferDesc),0);
end;
with BufferDesc do
begin
dwSize := sizeof(BufferDesc);
if Size< dsCaps.dwUnlockTransferRateHwBuffers * 120
then dwFlags := DSBCAPS_CTRLDEFAULT
else dwFlags := DSBCAPS_CTRLDEFAULT or DSBCAPS_LOCSOFTWARE;
dwBufferBytes := Size;
lpwfxFormat := @pcmwf;
end;
result := succeeded(pDSound.CreateSoundBuffer(BufferDesc, Buffer, nil));
end
else
begin
Buffer := nil;
result := false;
end;
end;
function FillSound(Buffer : IDirectSoundBuffer; Size : DWORD; ReadData : TReadCallback; UserData : pointer) : BOOL; cdecl;
var
pData1 : pointer;
pData2 : pointer;
dwData1Size : cardinal;
dwData2Size : cardinal;
begin
if (Buffer<>nil) and assigned(ReadData)
then
begin
if succeeded(Buffer.Lock(0, Size, pData1, dwData1Size, pData2, dwData2Size, DSBLOCK_FROMWRITECURSOR))
then
try
if (dwData1Size > 0)
then ReadData(pData1, dwData1Size, UserData);
if (dwData2Size > 0)
then ReadData(pData2, dwData2Size, UserData);
Buffer.Unlock(pData1, dwData1Size, pData2, dwData2Size);
result := true;
except
Buffer.Unlock(pData1, dwData1Size, pData2, dwData2Size);
result := false;
end
else result := false;
end
else result := false;
end;
procedure StopsSound(Buffer : IDirectSoundBuffer); cdecl;
var
dwStatus : cardinal;
begin
if (Buffer<>nil) and succeeded(Buffer.GetStatus(dwStatus)) and ((dwStatus and DSBSTATUS_PLAYING) = DSBSTATUS_PLAYING)
then Buffer.Stop;
end;
procedure PlaysSound(Buffer : IDirectSoundBuffer; LoopIt, RestartIt: BOOL; Pan, Volume, StartOfs : integer); cdecl;
var
dwStatus : cardinal;
Loop : integer;
begin
if (Buffer<>nil) and succeeded(Buffer.GetStatus(dwStatus))
then
begin
StopsSound(Buffer);
with Buffer do
begin
if RestartIt
then
begin
SetPan(Pan);
SetVolume(Volume);
SetCurrentPosition(StartOfs);
end;
if LoopIt
then Loop := DSBPLAY_LOOPING
else Loop := 0;
Play(0, 0, Loop);
end;
end;
end;
procedure DuplicateSound(Buffer : IDirectSoundBuffer; var Clone : IDirectSoundBuffer); cdecl;
begin
Clone := nil;
if (pDSound<>nil) and (Buffer<>nil)
then pDSound.DuplicateSoundBuffer(Buffer, Clone);
end;
procedure SetsSoundPan(Buffer : IDirectSoundBuffer; Pan : integer); cdecl;
var
dwStatus : cardinal;
begin
if (Buffer<>nil) and succeeded(Buffer.GetStatus(dwStatus))
then Buffer.SetPan(Pan);
end;
procedure SetsSoundVolume(Buffer : IDirectSoundBuffer; Volume : integer); cdecl;
var
dwStatus : cardinal;
// OK : HResult;
begin
if (Buffer<>nil) and succeeded(Buffer.GetStatus(dwStatus))
then Buffer.SetVolume(Volume); //.rag //ok :=
end;
function GetDSound: IDirectSound; cdecl;
begin
result := pDSound;
end;
function GetLibStatus: integer; cdecl;
begin
result := LibStatus;
end;
end.
|
unit Unit12;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, FileCtrl, FlCtrlEx, ImgList,ShellAPI;
type
TForm12 = class(TForm)
Button1: TButton;
TreeView1: TTreeView;
DriveComboBox1: TDriveComboBox;
ImageList1: TImageList;
DirectoryListBox1: TDirectoryListBox;
procedure Button1Click(Sender: TObject);
procedure TreeView1DblClick(Sender: TObject);
private
{ Private declarations }
public
procedure rec_list_dir(inpath: string; WinAddr1: TTreeNode);
end;
function LastPos(SubStr, S: string): Integer;
Type
NodePtr=^Tnoderec;
TnodeRec=record
Path:string;
FileName:string;
isFolder:boolean;
end;
var
Form12: TForm12;
NodeData:NodePtr;
implementation
{$R *.dfm}
procedure TForm12.rec_list_dir(inpath: string; WinAddr1: TTreeNode);
var
sr: TSearchRec;
res: integer;
TNode: TTreeNode;
Icon: TIcon;
FileInfo: SHFILEINFO;
begin
// Create a temporary TIcon
try
Icon := TIcon.Create;
res := FindFirst(inpath + '\*.*', faAnyFile, sr);
while res = 0 do
begin
if (Sr.Name <> '.') and (Sr.Name <> '..') and (Sr.Name[1] <>'.') then
begin
if ((sr.Attr and faDirectory) <> faDirectory) then
begin
New(NodeData);
NodeData^.Path:=inpath;
NodeData^.FileName:=sr.Name;
NodeData^.isFolder:=False;
TNode :=TreeView1.Items.AddChildObject(WinAddr1, Sr.Name,NodeData);
SHGetFileInfo(PChar(inpath+'\'+ sr.Name), 0, FileInfo,
SizeOf(FileInfo), SHGFI_ICON or SHGFI_SMALLICON);
icon.Handle := FileInfo.hIcon;
TNode.ImageIndex:=ImageList1.AddIcon(Icon);
TNode.SelectedIndex:=TNode.ImageIndex;
// Destroy the Icon
DestroyIcon(FileInfo.hIcon);
end else if (sr.Attr and faDirectory) = faDirectory then
Begin
New(NodeData);
NodeData^.Path:=inpath+'\'+sr.Name;
NodeData^.FileName:=sr.Name;
NodeData^.isFolder:=True;
TNode := TreeView1.Items.AddChildObject(WinAddr1, Sr.Name,NodeData);
TNode.ImageIndex:=0;
TNode.SelectedIndex:=0;
rec_list_dir(inpath + '\' + sr.name, TNode);
end;
end;
res := FindNext(sr);
end; //While
FindClose(sr);
finally
Icon.Free;
end;
end;
procedure TForm12.TreeView1DblClick(Sender: TObject);
var
path,filename,Fpath:string;
path_p:PAnsiString;
isfolder:Boolean;
selectednode,item:TTreeNode;
Nodedata:NodePtr;
i:Integer;
begin
if(TreeView1.Selected=nil) then Exit;
if (TreeView1.Selected.Data <> nil) then { query only works on new nodes }
begin
isfolder:=NodePtr(TreeView1.Selected.Data)^.IsFolder;
if not isfolder then
begin
path := NodePtr(TreeView1.Selected.Data)^.Path;
filename:=NodePtr(TreeView1.Selected.Data)^.FileName;
Fpath:=path+'\'+filename;
ShellExecute(0,pchar('open'),PChar(Fpath),nil,nil,SHOW_FULLSCREEN);
{
AcroPDF1.src :=path;
AcroPDF1.setShowToolbar(True);
}
end else
begin
{
path := PMyRec(TreeView1.Selected.Data)^.FName;
if (path='') then Exit;
GetSubFolders(path);
for i:=0 to SubfolderList.Count-1 do
begin
New(NodeData);
NodeData^.FName:=SubfolderList.Strings[i];
NodeData^.IsFolder:=True;
if IsDuplicateName(TreeView1.Selected,getfolderfromPath(SubfolderList.Strings[i]),False) then Continue;
Item := TreeView1.Items.AddChildObject(TreeView1.Selected,getfolderfromPath(SubfolderList.Strings[i]),NodeData);
Item.ImageIndex:=1;
Item.SelectedIndex:=1;
GetFiles(TreeView1,SubfolderList.Strings[i], Item, False);
end;
}
end;
end;
end;
procedure TForm12.Button1Click(Sender: TObject);
var
TNode:TTreeNode;
FolderName:string;
startidx:Integer;
begin
TreeView1.Items.BeginUpdate;
TreeView1.Items.Clear;
startidx:=LastPos('\',DirectoryListBox1.Directory);
if(startidx<Length(DirectoryListBox1.Directory)) then
begin
FolderName:=copy(DirectoryListBox1.Directory,startidx+1,length(DirectoryListBox1.Directory));
end else
begin
FolderName:=DirectoryListBox1.Directory;
end;
New(NodeData);
NodeData^.Path:=DirectoryListBox1.Directory;
NodeData^.FileName:=FolderName;
NodeData^.isFolder:=True;
TNode := TreeView1.Items.AddChildObject(nil,FolderName,NodeData);
TNode.ImageIndex:=0;
TNode.SelectedIndex:=0;
rec_list_dir(DirectoryListBox1.Directory, TNode);
TreeView1.Items.EndUpdate;
end;
function LastPos(SubStr, S: string): Integer;
var
Found, Len, Pos: integer;
begin
Pos := Length(S);
Len := Length(SubStr);
Found := 0;
while (Pos > 0) and (Found = 0) do
begin
if Copy(S, Pos, Len) = SubStr then
Found := Pos;
Dec(Pos);
end;
LastPos := Found;
end;
end.
|
{ Subroutine SST_SYM_VAR (SYM, VAR_P)
*
* Create a new variable descriptor that references the simple variable SYM.
* SYM must be the symbol of a simple variable.
}
module sst_sym_var;
define sst_sym_var;
%include 'sst2.ins.pas';
procedure sst_sym_var ( {make variable descriptor from simple var symbol}
in var sym: sst_symbol_t; {symbol of a simple variable}
out var_p: sst_var_p_t); {returned pointer to new variable descriptor}
val_param;
label
notvar;
begin
{
* Validate the symbol. It must be a simple variable.
}
if sym.symtype <> sst_symtype_var_k
then goto notvar;
{
* Create a new variable descriptor and fill it in.
}
sst_mem_alloc_scope ( {allocate memory for the new var descriptor}
sizeof(var_p^), var_p);
var_p^.mod1.next_p := nil; {no subsequent modifier}
var_p^.mod1.modtyp := sst_var_modtyp_top_k; {this is top modifier}
var_p^.mod1.top_str_h.first_char := sym.char_h;
var_p^.mod1.top_str_h.last_char := sym.char_h;
var_p^.mod1.top_sym_p := addr(sym); {point to the symbol}
var_p^.dtype_p := sym.var_dtype_p; {data type}
var_p^.rwflag := {allow reading and writing of variable}
[sst_rwflag_read_k, sst_rwflag_write_k];
var_p^.vtype := sst_vtype_var_k; {reference is to a variable}
return; {success, normal return point}
notvar: {symbol is not var of the right type}
writeln ('INTERNAL ERROR: Symbol "', sym.name_in_p^.str:sym.name_in_p^.len,
'" is not simple var in SST_SYM_VAR.');
sys_bomb;
end;
|
unit CursorTest;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls;
const
cr5 = 5;
cr6 = 6;
cr7 = 7;
cr8 = 8;
cr9 = 9;
cr10 = 10;
type
TLoadCursorTestForm = class(TForm)
pnlCanvas: TPaintBox;
procedure pnlCanvasPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure pnlCanvasMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
LoadCursorTestForm: TLoadCursorTestForm;
implementation
{$R *.dfm}
procedure TLoadCursorTestForm.FormCreate(Sender: TObject);
begin
screen.cursors[cr5] := LoadCursor(hInstance, pChar('Cursor_Move'));
end;
procedure TLoadCursorTestForm.pnlCanvasMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if PtInRect(Rect(100,100,200,200), Point(x,y)) then
Screen.Cursor := cr5
else
Screen.Cursor := crDefault;
end;
procedure TLoadCursorTestForm.pnlCanvasPaint(Sender: TObject);
begin
pnlCanvas.Canvas.Rectangle(Rect(100,100,200,200));
end;
end.
|
Program example(input, output);
Var x, y : integer;
Function gcd( a, b : integer) : integer;
Begin
If b = 0 Then gcd = a
Else gcd := gcd(b, a Mod b)
End;
Begin
read(x, y);
write(gcd(x, y))
End.
|
program tp_algo_croix;
// g: dessine une croix avec un caractère et une taille donnee
// i: un caractere à afficher et un nombre pour la taille
// o: une croix avec le caractere et la taille entree
// ----------------------------------------------------------------
// Algorithme :
//PROGRAMME Algo_Croix
// g : dessine une croix avec un caractère et une taille donnée
// i : un caractère à afficher et un nombre pour la taille
// o : une croix avec le caractère et la taille entrée
//VAR
// caractereAffiche, espaceEntreCar : CARACTERE
// tailleCroix, i, j : ENTIER
//
//DEBUT
// ECRIRE "Bienvenue dans l algorithme dessinant une croix en caractere"
// ECRIRE "Quel caractère voulez-vous affiche ?"
// LIRE caractereAffiche
// ECRIRE "Quelle est à la hauteur de votre croix ?"
// LIRE tailleCroix
// espaceEntreCar<- "_"
// // début du traitement de la croix
// POUR i DE 1 à tailleCroix FAIRE
// POUR j DE 1 à tailleCroix FAIRE
// SI (j = i) OU (j = tailleCroix - (i - 1)) ALORS
// ECRIRE caractereAffiche
// SINON
// ECRIRE espaceEntreCar
// ECRIRE // passa à la ligne
//FIN
// ----------------------------------------------------------------
uses crt;
var
caractereAffiche, espaceEntreCar : char;
tailleCroix, i, j : integer;
BEGIN
clrscr;
writeln('Bienvenue dans l algorithme dessinant une croix en caractere');
writeln('Entrez le caractere qui sera affiche.');
readln(caractereAffiche);
writeln('Entrez la hauteur de la croix');
readln(tailleCroix);
espaceEntreCar := ' ';
// debut de traitement de la croix
for i:= 1 to tailleCroix do
begin
for j:= 1 to tailleCroix do
begin
if (j=i) or (j = tailleCroix- (i -1)) then
write(caractereAffiche)
else
write(espaceEntreCar)
end;
writeln();
end;
readln;
END.
|
unit uCadastro;
interface
uses SysUtils, Classes;
type
TCadastro = record
StatusConsulta: Smallint;
Motivo: string[60];
Nome: string[60];
CNPJ: string[20];
IE: string[20];
Logradouro: string[60];
Numero: string[20];
Complemento: string[60];
Bairro: string[60];
CodMunicipio: string[7];
Municipio: string[60];
UF: string[2];
CEP: string[9];
Regime: string[60];
CNAE: string[7];
Situacao: Shortint;
DtIniAtiv: string[10];
DtUltSit: string[10];
IndCredNFe: ShortInt;
IndCredCTe: ShortInt;
end;
var
Cadastro: TCadastro;
function VeDadosCadastro(const AConsulta: TStringList): Boolean;
procedure LimparDadosCadastro;
function SimplesNacional: Boolean;
implementation
function VeDadosCadastro(const AConsulta: TStringList): Boolean;
var
DI, DU: TDateTime;
T: TFormatSettings;
begin
LimparDadosCadastro;
T.ShortDateFormat := 'yyyy-mm-dd';
T.DateSeparator := '-';
with Cadastro, AConsulta do
begin
Motivo := Values['xMotivo'];
Nome := Values['Nome'];
CNPJ := Values['cnpj'];
IE := Values['ie'];
Logradouro := Values['xLgr'];
Numero := Values['nro'];
Complemento := Values['xCpl'];
Bairro := Values['xBairro'];
CodMunicipio := Values['cMun'];
Municipio := Values['xMun'];
UF := Values['uf'];
CEP := Values['CEP'];
Regime := Values['xRegApur'];
CNAE := Values['CNAE'];
try
StatusConsulta := StrToInt(Trim(Values['cStat']));
Situacao := StrToInt(Trim(Values['cSit']));
IndCredNFe := StrToInt(Trim(Values['indCredNFe']));
IndCredCTe := StrToInt(Trim(Values['indCredCTe']));
DI := StrToDate(Values['dIniAtiv'], T);
DU := StrToDate(Values['dUltSit'], T);
except
end;
DtIniAtiv := FormatDateTime('dd/mm/yyyy', DI);
DtUltSit := FormatDateTime('dd/mm/yyyy', DU);
end;
Result := (Cadastro.StatusConsulta = 111) or (Cadastro.StatusConsulta = 258) or (Cadastro.StatusConsulta = 259);
end;
procedure LimparDadosCadastro;
begin
with Cadastro do
begin
StatusConsulta := -1;
Nome := EmptyStr;
CNPJ := EmptyStr;
IE := EmptyStr;
Logradouro := EmptyStr;
Numero := EmptyStr;
Complemento := EmptyStr;
Bairro := EmptyStr;
CodMunicipio := EmptyStr;
Municipio := EmptyStr;
UF := EmptyStr;
CEP := EmptyStr;
Regime := EmptyStr;
Situacao := -1;
end;
end;
function SimplesNacional: Boolean;
begin
Result := Pos('SIMPLES NACIONAL', Cadastro.Regime) > 0;
end;
end.
|
unit DW.Androidapi.JNI.KeyguardManager;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes;
type
JKeyguardManager = interface;
JKeyguardManager_KeyguardLock = interface;
JKeyguardManager_OnKeyguardExitResult = interface;
JKeyguardManagerClass = interface(JObjectClass)
['{44F9A483-0683-4391-94D1-F0BB6DB7340B}']
end;
[JavaSignature('android/app/KeyguardManager')]
JKeyguardManager = interface(JObject)
['{6AECC681-2C45-48B7-87D9-5A255840BDFA}']
function createConfirmDeviceCredentialIntent(title: JCharSequence; description: JCharSequence): JIntent; cdecl;
procedure exitKeyguardSecurely(callback: JKeyguardManager_OnKeyguardExitResult); cdecl;
function inKeyguardRestrictedInputMode: Boolean; cdecl;
function isDeviceLocked: Boolean; cdecl;
function isDeviceSecure: Boolean; cdecl;
function isKeyguardLocked: Boolean; cdecl;
function isKeyguardSecure: Boolean; cdecl;
function newKeyguardLock(tag: JString): JKeyguardManager_KeyguardLock; cdecl;
end;
TJKeyguardManager = class(TJavaGenericImport<JKeyguardManagerClass, JKeyguardManager>) end;
JKeyguardManager_KeyguardLockClass = interface(JObjectClass)
['{98306533-81FC-4498-91E6-19F58EA32BD7}']
{class} procedure disableKeyguard; cdecl;
{class} procedure reenableKeyguard; cdecl;
end;
[JavaSignature('android/app/KeyguardManager$KeyguardLock')]
JKeyguardManager_KeyguardLock = interface(JObject)
['{6061FAD3-A869-40A5-BEAB-CFC481B8EC0B}']
end;
TJKeyguardManager_KeyguardLock = class(TJavaGenericImport<JKeyguardManager_KeyguardLockClass, JKeyguardManager_KeyguardLock>) end;
JKeyguardManager_OnKeyguardExitResultClass = interface(IJavaClass)
['{40CF0367-E275-475B-8566-A6337DD56217}']
end;
[JavaSignature('android/app/KeyguardManager$OnKeyguardExitResult')]
JKeyguardManager_OnKeyguardExitResult = interface(IJavaInstance)
['{A2E86C9B-0384-4A3A-8E4B-823923FBD083}']
procedure onKeyguardExitResult(success: Boolean); cdecl;
end;
TJKeyguardManager_OnKeyguardExitResult = class(TJavaGenericImport<JKeyguardManager_OnKeyguardExitResultClass, JKeyguardManager_OnKeyguardExitResult>) end;
implementation
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Timer1: TTimer;
BtnStart: TButton;
BtnStop: TButton;
procedure BtnStartClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure BtnStopClick(Sender: TObject);
private
{ Private-Deklarationen }
FNextMethod : TThreadMethod;
public
{ Public-Deklarationen }
procedure CallDelayedMethod(delay:cardinal; method:TThreadMethod);
procedure AmpelRot;
procedure AmpelGelb;
procedure AmpelGruen;
procedure AmpelAus;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.CallDelayedMethod(delay: cardinal; method: TThreadMethod);
begin
timer1.Enabled := false;
FNextMethod := method;
timer1.Interval := delay;
timer1.Enabled := True;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := false;
if Assigned(FNextMethod) then
begin
FNextMethod;
end;
end;
procedure TForm1.AmpelRot;
begin
color := clRed;
CallDelayedMethod(1500, AmpelGelb);
end;
procedure TForm1.AmpelGelb;
begin
color := clYellow;
CallDelayedMethod(800, AmpelGruen);
end;
procedure TForm1.AmpelGruen;
begin
color := clGreen;
CallDelayedMethod(3000, AmpelRot);
end;
procedure TForm1.AmpelAus;
begin
color := clBtnFace;
end;
procedure TForm1.BtnStartClick(Sender: TObject);
begin
CallDelayedMethod(200, AmpelRot);
end;
procedure TForm1.BtnStopClick(Sender: TObject);
begin
CallDelayedMethod(50, AmpelAus);
end;
end.
|
{
Code from TC Plugins Manager project:
http://www.totalcmd.net/plugring/tc_plugman.html
}
{$I-}
unit ATxUnpack;
interface
function FExecProcess(const cmd: string; ShowCmd: integer; DoWait: boolean): boolean;
function FUnpack(const fn, sdir: string): boolean;
var
OptUnpack: record
RarPath: string;
RunMinimized: boolean;
end;
implementation
uses
Windows, SysUtils, ShellAPI,
ATxUtils;
const
cShowCmd: array[boolean] of DWORD = (SW_SHOWNORMAL, SW_SHOWMINNOACTIVE);
//-------------------------------------------------
function FExecShell(const cmd, params, dir: string; ShowCmd: integer; DoWait: boolean): boolean;
var
si: TShellExecuteInfo;
begin
FillChar(si, SizeOf(si), 0);
si.cbSize:= SizeOf(si);
si.fMask:= SEE_MASK_FLAG_NO_UI or SEE_MASK_NOCLOSEPROCESS;
si.lpFile:= PChar(cmd);
si.lpParameters:= PChar(params);
si.lpDirectory:= PChar(dir);
si.nShow:= ShowCmd;
Result:= ShellExecuteEx(@si);
if Result and DoWait then
WaitForSingleObject(si.hProcess, INFINITE);
CloseHandle(si.hProcess);
end;
//-------------------------------------------------
function FExecProcess(const cmd: string; ShowCmd: integer; DoWait: boolean): boolean;
var
pi: TProcessInformation;
si: TStartupInfo;
begin
FillChar(pi, SizeOf(pi), 0);
FillChar(si, SizeOf(si), 0);
si.cb:= SizeOf(si);
si.dwFlags:= STARTF_USESHOWWINDOW;
si.wShowWindow:= ShowCmd;
Result:= CreateProcess(nil, PChar(cmd), nil, nil, false, 0,
nil, nil, si, pi);
if Result then
begin
if DoWait then WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
end;
end;
//-------------------------------------------------
function ExecShell(const cmd, params: string): boolean;
begin
Result:= FExecShell(cmd, params, '', cShowCmd[OptUnpack.RunMinimized], true);
end;
function Exec(const cmd: string): boolean;
begin
Result:= FExecProcess(cmd, cShowCmd[OptUnpack.RunMinimized], true);
end;
//-------------------------------------------------
function UnZip(const fn, sdir: string): boolean;
var
param: string;
begin
Result:= true;
param:= Format('x -y "%s" "%s\"', [fn, sdir]);
if ExecShell('WinRAR.exe', param) then Exit;
if (OptUnpack.RarPath<>'') and
ExecShell(SExpandVars(OptUnpack.RarPath), param) then Exit;
if Exec(Format('unzip.exe -o "%s" -d "%s"', [fn, sdir])) then Exit;
if Exec(Format('"%s\unzip.exe" -o "%s" -d "%s"', [ExtractFileDir(ParamStr(0)), fn, sdir])) then Exit;
if Exec(Format('pkunzip.exe -d -o "%s" "%s\"', [fn, sdir])) then Exit;
if Exec(Format('wzunzip.exe -d -o "%s" "%s\"', [fn, sdir])) then Exit;
if Exec(Format('pkzipc.exe -ext -dir -over=all "%s" "%s\"', [fn, sdir])) then Exit;
Result:= false;
end;
//-------------------------------------------------
function UnRar(const fn, sdir: string): boolean;
var
param: string;
begin
Result:= true;
param:= Format('x -y "%s" "%s\"', [fn, sdir]);
if ExecShell('WinRAR.exe', param) then Exit;
if (OptUnpack.RarPath<>'') and
ExecShell(SExpandVars(OptUnpack.RarPath), param) then Exit;
if Exec('Rar.exe '+param) then Exit;
if Exec('UnRar.exe '+param) then Exit;
if Exec('"'+ExtractFileDir(ParamStr(0))+'\UnRar.exe" '+param) then Exit;
Result:= false;
end;
//-------------------------------------------------
function FUnpack(const fn, sdir: string): boolean;
var
s: string;
begin
s := LowerCase(ExtractFileExt(fn));
if s = '.zip' then Result := UnZip(fn, sdir) else
if s = '.rar' then Result := UnRar(fn, sdir) else
Result := false;
if Result then
Sleep(200);
end;
end.
|
{ Unit EggerSprite implements all sprite classes
@Author Alexey Yarochkin
@Version 07.12.2010 v0.2
@History 27.01.2005 v0.1
}
unit EggerSprite;
interface
uses
SDL, SDLSprites, EggerData;
type
TActiveSprite = class;
/// Map cell record
TCellInfo = record
/// Sprites in front
/// [0..1] - sprites on each grid cell of the map cell
/// [2] - sprite on both grid cells (if [0] = [1])
Sprite: array [0..2] of TActiveSprite;
/// map cell data on each grid cell
Cell: array [0..1] of TMapCell;
end;
/// Abstract ancestor for all sprite classes
TActiveSprite = class(TSprite)
private
/// Actual sprite state
/// Note: some values may have different meaning for different sprite types
fState: TSpriteState;
///
/// True if the sprite should behave uncommonly
fLevelHint: Boolean;
fLoopMask: Byte;
///
/// True if the sprite has released a bullet, which is moving now
fShooting: Boolean;
fCellInfo: TCellInfo;
/// Original sprite position
/// Used to reposition it when recovering from the death
Xorig, Yorig: TPixCoord;
/// Original sprite direction
/// Used to redirect it when recovering from the death or pause
dXorig, dYorig: TDelta;
/// Collect all data of the map cell in front
procedure GetItemsInFront(var aInfo: TCellInfo); virtual;
/// Check if there is a hurdle in front
function hasHurdleInFront: Boolean; virtual;
/// Check if the sprite can step on the given map cell
function CanStepOn(const aInfo: TCellInfo): Boolean; virtual;
/// Calculate next animation phase
function GetPhase(aNext: Boolean): Word; virtual;
/// Define the current sprite speed
function GetSpeed: TSpeed; virtual;
/// Start the attack (shooting)
procedure Attack(adX, adY: TDelta); virtual;
/// Make sprite hurt
procedure Hurt(adX, adY: TDelta); virtual;
/// Direct the sprite
procedure DirectTo(adX, adY: TDelta);
/// Check if the sprite is moving now
function isMoving: Boolean;
/// Check if the sprite is staying entirely on one grid cell
function InGridCell: Boolean;
/// Check if the sprite is staying entirely on one map cell
function InMapCell: Boolean;
procedure SetLevelHint(const aValue: Boolean);
procedure SetState(const aValue: TSpriteState); virtual;
/// Start the process of recovery
procedure Recover;
public
/// Actual sprite type
SpriteType: TSpriteType;
/// Current velocity
vX, vY: TSpeed;
/// Current direction
dX, dY: TDelta;
/// Timer ticking when sprite is paused (e.g. PauseTime)
PauseTime: Word;
/// Timer ticking when sprite is recovering (after death)
RecoveryTime: Word;
/// Sprite used by this one as a sailing vehicle
Sail: TActiveSprite;
/// Sprite which uses this one as a sailing vehicle
Sailor: TActiveSprite;
/// Create, position and direct a sprite object
constructor Create(aType: TSpriteType; aMask: Byte; aX, aY: TPixCoord;
adX: TDelta = 0; adY: TDelta = 0; aHint: Boolean = False);
/// Destroy and free the object
procedure Free; override;
/// Dispatch the sprite moves
procedure Move; override;
procedure Live; virtual; abstract;
/// Try to push sprite in the given direction
function Pushed(adX, adY: TDelta): Boolean;
/// Draw sprite
procedure Draw; override;
property LevelHint: Boolean read FLevelHint write SetLevelHint;
property State: TSpriteState read fState write SetState;
property isShooting: Boolean read fShooting write fShooting;
end;
/// Hero sprite
THero = class(TActiveSprite)
private
FBullets: ShortInt;
FGhostly: Boolean;
function hasHurdleInFront: Boolean; override;
function CanStepOn(const aInfo: TCellInfo): Boolean; override;
procedure SetBullets(const aValue: ShortInt);
procedure SetGhostly(const aValue: Boolean);
function GetSpeed: TSpeed; override;
public
Basket: array [0..2] of TTileType;
procedure Live; override;
procedure Draw; override;
procedure Attack(adX, adY: TDelta); override;
procedure Reset(aX, aY: TPixCoord; adX, adY: TDelta);
function InBasket(aTile: TTileType; aTake: Boolean = False): Boolean;
procedure PlaceToBasket(aTile: TTileType);
property Bullets: ShortInt read FBullets write SetBullets;
property Ghostly: Boolean read FGhostly write SetGhostly;
end;
/// Staying dragon sprite
/// The dragon watches the Hero
TDragon = class(TActiveSprite)
private
function GetPhase(aNext: Boolean): Word; override;
public
procedure Live; override;
end;
/// Staying fireball sprite
/// The fireball ...
TFireball = class(TActiveSprite)
private
function GetPhase(aNext: Boolean): Word; override;
procedure SetState(const aValue: TSpriteState); override;
public
procedure Live; override;
class procedure DoHint;
end;
TMedusa = class(TActiveSprite)
private
function GetPhase(aNext: Boolean): Word; override;
public
procedure Live; override;
end;
TBullet = class(TActiveSprite)
private
Shooter: TActiveSprite;
function CanHitTarget: Boolean;
function CanStepOn(const aInfo: TCellInfo): Boolean; override;
function GetSpeed: TSpeed; override;
public
constructor Create(aSpriteType: TSpriteType; aShooter: TActiveSprite;
adX, adY: TDelta; aCheckPath: Boolean); reintroduce;
procedure Live; override;
end;
TBox = class(TActiveSprite)
private
function CanStepOn(const aInfo: TCellInfo): Boolean; override;
public
procedure Live; override;
end;
TShip = class(TActiveSprite)
private
function GetPhase(aNext: Boolean): Word; override;
public
constructor Create(aSailor: TActiveSprite; aX, aY: TPixCoord); reintroduce;
procedure Live; override;
end;
TSwingingSprite = class(TActiveSprite)
public
procedure Live; override;
end;
TCuckold = class(TSwingingSprite)
private
function GetPhase(aNext: Boolean): Word; override;
public
procedure Live; override;
end;
TRoamingSprite = class(TActiveSprite)
private
procedure GetItemsInFront(var aInfo: TCellInfo); override;
public
procedure Live; override;
function HeroTouched(adX, adY: TDistance): Boolean; virtual;
end;
TSkull = class(TRoamingSprite)
private
function GetPhase(aNext: Boolean): Word; override;
public
procedure Live; override;
function HeroTouched(adX, adY: TDistance): Boolean; override;
end;
TRoller = class(TRoamingSprite)
private
function GetPhase(aNext: Boolean): Word; override;
public
procedure Live; override;
end;
TSleepy = class(TRoamingSprite)
private
fTouched: Byte;
function GetPhase(aNext: Boolean): Word; override;
function GetSpeed: TSpeed; override;
procedure Hurt(adX, adY: TDelta); override;
procedure SetState(const aValue: TSpriteState); override;
public
constructor Create(aX, aY: TPixCoord; adX: TDelta = 0; adY: TDelta = 0;
aLevelHint: Boolean = False); reintroduce;
procedure Live; override;
function HeroTouched(adX, adY: TDistance): Boolean; override;
procedure TouchMe;
class procedure DoHint;
end;
TStony = class(TRoamingSprite)
private
function hasHurdleInFront: Boolean; override;
function GetSpeed: TSpeed; override;
public
function HeroTouched(adX, adY: TDistance): Boolean; override;
end;
implementation
uses
SysUtils, EggerGame, Logger;
{ TActiveSprite }
{ @ Create, position and direct a new sprite object
@param aType actual sprite type
@param aMask binary mask of animation phases
@param aX initial x-coordinate (in pixels)
@param aY initial y-coordinate (in pixels)
@param adX initial x-direction
[ 0] not directed horizontally
[ 1] directed to the right
[-1] directed to the left
@param adY initial y-direction
[ 0] not directed vertically
[ 1] directed to the
[-1] directed to the
@param aHint indicates if the sprite should behave uncommonly
if True the sprite is used as a hint in the current level
}
constructor TActiveSprite.Create(aType: TSpriteType; aMask: Byte; aX, aY: TPixCoord;
adX: TDelta = 0; adY: TDelta = 0; aHint: Boolean = False);
begin
inherited Create('', MapCellSize, MapCellSize);
SpriteType := aType;
Game.SpriteEngine.AddSprite(Self);
// original coordinates are needed for the recovery
Xorig := aX;
Yorig := aY;
dXorig := adX;
dYorig := adY;
// position the sprite to the original coordinates
Recover;
State := ssNormal;
/// Sprites are arranged in 3 z-layers:
/// * 3 (highest): Hero
/// * 0 (lowest): ammunition
/// * 1 (middle): all others
Z := ifop(aType = sHero, 3, ifop(aType in Ammunition, 0, 1));
fLoopMask := aMask;
AnimPhase := GetPhase(False);
LevelHint := aHint;
end; { Create }
{ @ Destroy and free the object
}
procedure TActiveSprite.Free;
begin
// sprite image must not be released automatically
Image := nil;
inherited;
end; { Free }
{ @ Dispatch the sprite moves
}
procedure TActiveSprite.Move;
var
MapBack1, MapBack2: TTileType;
Speed: TSpeed;
FlowDirection: SmallInt;
AdjustSailor: Boolean;
{ Counts down pause time
If the time is out:
- the sprite returns to the normal state
- if the sprite was swimming it sinks and recovers
- if the sprite sinks its sailor dies
}
procedure CheckPaused;
begin
Dec(PauseTime);
if PauseTime = 0 then
if State = ssSwimming then
// if sprite was swimming
begin
// start recovery
Recover;
// kill sailing Hero
if Sailor = Game.Hero then
Game.GameState := gsKillHero;
end
else
// if sprite was not swimming
begin
// restore original direction (actual for fireballs)
DirectTo(dXorig, dYorig);
// return to the normal state
State := ssNormal;
end;
end; { CheckPaused }
{ Counts down recovery time
If the sprite position is occupied by someone (not Hero):
- tries to reposition the recovering sprite
(searches for a free placeholder of a sprite of the same type)
- if all places are occupied, kills the sprite (so it does not appear)
If the time is out, the sprite returns to the normal state
}
procedure CheckRecovery;
var
MapX, MapY: TMapCoord;
GridX, GridY: TGridCoord;
Sprite: TActiveSprite;
begin
GridX := PixToGrid(X);
GridY := PixToGrid(Y);
// look for a sprite in the same place excluding itself
Sprite := Game.SpriteIn(GridX, GridX + 1, GridY, GridY + 1, Self);
// if no sprites occupy this cell (Hero is not counted as an occupant)
if (Sprite = nil) or (Sprite.SpriteType = sHero) then
begin
Dec(RecoveryTime);
if RecoveryTime = 0 then
State := ssNormal;
end
else
// if the current placeholder is occupied
begin
for MapY := 0 to MapHeight - 1 do
for MapX := 0 to MapWidth - 1 do
with Game.Map[MapX, MapY] do
begin
GridX := MapToGrid(MapX);
GridY := MapToGrid(MapY);
// if the cell is for Sprite of the same type and it's free
if (Item = tEmpty) and (TSpriteType(Sprite shr 4) = SpriteType) and
(Game.SpriteIn(GridX, GridX + 1, GridY, GridY + 1) = nil) then
begin
// reposition the Sprite and start recovery again
Xorig := MapToPix(MapX);
Yorig := MapToPix(MapY);
Recover;
Exit;
end;
end;
// no free placeholders found - removing the Sprite
Kill;
end;
end; { CheckRecovery }
begin { Move }
// pause time count down
if PauseTime > 0 then
CheckPaused;
// recovery time count down (Hero cannot recover)
if (RecoveryTime > 0) and (SpriteType <> sHero) then
CheckRecovery;
// set next animation picture
AnimPhase := GetPhase(True);
// if some time has passed since sprite is swimming it may start drifting
if (State = ssSwimming) and not isMoving and (PauseTime < PauseTimeMax - 28) then
begin
// check if water in the current cell has a flow (FlowDirection is its direction)
FlowDirection := Game.PixMap[x, y].Weight - 1;
// trying to push sprite in that direction
if (FlowDirection >= 0) and Pushed(ItoDX[FlowDirection], ItoDY[FlowDirection]) then
begin
// reset swimming state (mainly the PauseTime time)
State := ssSwimming;
AnimPhase := GetPhase(False);
end;
end;
// let the sprite perform its normal living functions:
// - checking the map
// - redirecting itself
if State in [ssNormal, ssSleeping] then
Live;
Speed := GetSpeed;
// if the sprite is transporting another one (as a sail)
// the sailor coordinates must be adjusted (if not hibernated by enemy)
AdjustSailor := (Sailor <> nil) and (Sailor.State <> ssSleeping);
// adjust self coordintates according to the velocity
if vX <> 0 then
begin
Inc(x, Speed * dX);
Dec(vX, Speed * dX);
// if the sprite is moving horizontally and its wakeful sailor stands on
if AdjustSailor and (Sailor.y = y) then
Sailor.x := x;
end
else if vY <> 0 then
begin
Inc(y, Speed * dY);
Dec(vY, Speed * dY);
// if the sprite is moving vertically and its wakeful sailor stands on
if AdjustSailor and (Sailor.x = x) then
Sailor.y := y;
end;
if not isMoving then
begin
MapBack1 := Game.PixMap[x, y].Back;
MapBack2 := Game.PixMap[x + GridCellSize, y + GridCellSize].Back;
// if the sprite stops on a liquid surface it starts swimming
// - Hero cannot swim - he can only sail
// - ammunition does not swim - it flies above
if (State <> ssSwimming) and not (SpriteType in [sHero] + Ammunition) and
InGridCell and ([MapBack1, MapBack2] <= LiquidItems) then
State := ssSwimming;
// if Hero stops on ice he continues to slide further
if (SpriteType = sHero) and (tIce in [MapBack1, MapBack2]) then
Pushed(dX, dY);
end;
end; { Move }
{ @ Try to push sprite in the given direction
@param adx x-direction of the push
@param ady y-direction of the push
@return True if pushed successfully
}
function TActiveSprite.Pushed(adX, adY: TDelta): Boolean;
var
Velocity: Byte;
HurdleInFront: Boolean;
begin
Result := False;
// if still moving => no push allowed
if isMoving or not InGridCell then Exit;
Log.LogStatus(Format('%s pushed to <%d:%d>', [ClassName, adX, adY]), GameStateName);
DirectTo(adX, adY);
// check if destination cell is empty (no hurdle in front)
HurdleInFront := hasHurdleInFront;
// prospected velocity:
// - moving across grid cells
// - swimminig across map cells (if adjusted to the map cell)
Velocity := ifop((State = ssSwimming) and InMapCell, MapCellSize, GridCellSize);
with fCellInfo do
// if the destination is not passable
if HurdleInFront then
// there is an exception:
// if egg is getting into a liquid surface it must pass the whole map cell
if ([Cell[0].Back, Cell[1].Back] <= LiquidItems) and
(State in EggStates) then
Velocity := MapCellSize
// no other reason to allow the push
else Exit
// if there is a sprite in front, which is swimming:
// - jump on it across the whole map call
// - register as a sailor and start sailing
else if (Sprite[2] <> nil) and (Sprite[2].State = ssSwimming) then
begin
Sail := Sprite[2];
Sail.Sailor := Self;
// set to skip the next check (jumping off the sail)
HurdleInFront := True;
Velocity := MapCellSize;
end;
// if pushed off while sailing
// - unregister sailor
// - jump off across the whole map cell
if not HurdleInFront and (Sail <> nil) then
with Game, Sail do
begin
Sailor := nil;
// remove sail if it was a raft
if SpriteType = sRaft then
begin
Kill;
// show the original raft item back on the map
if LevelStatus = lsDone then
GameState := gsCatchKey;
DrawBackground;
end;
Self.Sail := nil;
Velocity := MapCellSize;
end;
// set velocity for each x/y component
vX := dX * Velocity;
vY := dY * Velocity;
Result := True;
end; { Pushed }
{ @ Check if there is a hurdle in front
A hurdle may be a blocking tile or a sprite
@return True if the way is jammed
}
function TActiveSprite.hasHurdleInFront: Boolean;
function IsNone(aSprite: TActiveSprite): Boolean;
begin
Result := (aSprite = nil) or (aSprite = Self);
end; { None }
begin { hasHurdleInFront }
Result := False;
if not InGridCell then Exit;
GetItemsInFront(fCellInfo);
with fCellInfo do
Result := not (CanStepOn(fCellInfo) and IsNone(Sprite[0]) and IsNone(Sprite[1]));
end; { hasHurdleInFront }
{ @ Collect all data of the map cell in front
@param Info map cell record to fill in
@return Info
}
procedure TActiveSprite.GetItemsInFront(var aInfo: TCellInfo);
var
GridX1, GridX2, GridY1, GridY2: TGridCoord;
begin
GridX1 := PixToGrid(x) + ifop(dX = 0, 0, ifop(dX > 0, GridsInMap, -1));
GridX2 := GridX1 + ifop(dX = 0, GridsInMap - 1, 0);
GridY1 := PixToGrid(y) + ifop(dY = 0, 0, ifop(dY > 0, GridsInMap, -1));
GridY2 := GridY1 + ifop(dY = 0, GridsInMap - 1, 0);
aInfo.Sprite[0] := Game.SpriteIn(GridX1, GridX1, GridY1, GridY1, Game.Hero.Sail);
aInfo.Sprite[1] := Game.SpriteIn(GridX2, GridX2, GridY2, GridY2, Game.Hero.Sail);
if aInfo.Sprite[0] = Self then
aInfo.Sprite[0] := nil;
if aInfo.Sprite[1] = Self then
aInfo.Sprite[1] := nil;
if aInfo.Sprite[0] = aInfo.Sprite[1] then
aInfo.Sprite[2] := aInfo.Sprite[0]
else
aInfo.Sprite[2] := nil;
aInfo.Cell[0] := Game.Map[GridToMap(GridX1), GridToMap(GridY1)];
aInfo.Cell[1] := Game.Map[GridToMap(GridX2), GridToMap(GridY2)];
end; { GetItemsInFront }
{ @ Check if the sprite can step on the given map cell
This function checks if there is no blocking tiles in front of the sprite
@param Info map cell record
@return True if cell is free for stepping on
}
function TActiveSprite.CanStepOn(const aInfo: TCellInfo): Boolean;
var
Backs, Items: TTiles;
begin
if State = ssSwimming then
begin
Backs := LiquidItems;
Items := HeroPathItems;
end
else
begin
Backs := AnyPathBacks;
Items := AnyPathItems;
if State = ssPaused then
Include(Backs, tRoad);
end;
with aInfo do
Result := ([Cell[0].Back, Cell[1].Back] <= Backs) and
([Cell[0].Item, Cell[1].Item] <= Items);
end; { CanStepOn }
{ @ Draw sprite
}
procedure TActiveSprite.Draw;
begin
if (State in EggStates) and (SpriteType <> sRaft) then
Image := Game.SpriteImage[sEgg]
else
Image := Game.SpriteImage[SpriteType];
SDL_SetAlpha(Image, SDL_SRCALPHA,
255 - ifop(RecoveryTime <= $C0, (RecoveryTime + $3F) and $C0, 255));
inherited;
end; { Draw }
{ @ Make sprite hurt
The sprite recovers if it is already PauseTime
}
procedure TActiveSprite.Hurt(adX, adY: TDelta);
begin
if State = ssPaused then
Recover
else
State := ssPaused;
end; { Hurt }
{ @ Calculate next animation phase
@param Next identifies whether to calculate the next (or initial) phase
@return index of the animation phase
}
function TActiveSprite.GetPhase(aNext: Boolean): Word;
begin
aNext := aNext and isMoving;
//Result :=
// ifop(State = ssPaused, 3 - PauseTime shr 5,
// ifop(State = ssSwimming, 7 - PauseTime shr 5,
// ifop(fLoopMask = $FF, 0, DeltaToIndex(dX, dY) * (fLoopMask + 1) +
// ((Game.MovePhase * Ord(aNext)) and fLoopMask))));
if State = ssPaused then
Result := 3 - PauseTime shr 5
else if State = ssSwimming then
Result := 7 - PauseTime shr 5
else if fLoopMask = $FF then
Result := 0
else
Result := DeltaToIndex(dX, dY) * (fLoopMask + 1) +
(Byte(Game.MovePhase * Ord(aNext)) and fLoopMask);
end; { GetPhase }
{ @ Start the attack (shooting)
}
procedure TActiveSprite.Attack(adX, adY: TDelta);
var
Weapon: TSpriteType;
begin
if isShooting or not InGridCell then Exit;
Log.LogStatus(Format('%s attacks <%d:%d>', [ClassName, adX, adY]), GameStateName);
case SpriteType of
sHero: Weapon := sBullet;
sFireball: Weapon := sFire;
sMedusa: Weapon := sFlash;
sCuckold: Weapon := sKnife;
else
Weapon := sEgg;
end;
TBullet.Create(Weapon, Self, adX, adY, not (SpriteType in [sHero, sFireball]));
end; { Attack }
{ @ Check if the sprite is moving now
@return True if the sprite is moving now
}
function TActiveSprite.isMoving: Boolean;
begin
Result := (vX <> 0) or (vY <> 0);
end; { Moving }
{ @ Check if the sprite is staying entirely on one grid cell
@return True if sprite is on a grid cell
}
function TActiveSprite.InGridCell: Boolean;
begin
Result := (X mod GridCellSize = 0) and (Y mod GridCellSize = 0);
end; { InGridCell }
{ @ Check if the sprite is staying entirely on one map cell
@return True if sprite is on a map cell
}
function TActiveSprite.InMapCell: Boolean;
begin
Result := (X mod MapCellSize = 0) and (Y mod MapCellSize = 0);
end; { InMapCell }
{ @ Start the process of recovery
}
procedure TActiveSprite.Recover;
begin
X := Xorig;
Y := Yorig;
DirectTo(dXorig, dYorig);
State := ssRecovering;
end; { Recover }
{ @ Define the current sprite speed
@return current speed factor
}
function TActiveSprite.GetSpeed: TSpeed;
begin
Result :=
ifop(State = ssRecovering, 0,
ifop(State = ssSwimming, 1, 4));
end; { GetSpeed }
{ @ Direct the sprite
@param adx x-direction
@param ady y-direction
}
procedure TActiveSprite.DirectTo(adX, adY: TDelta);
begin
dX := adX;
dY := adY;
end; { DirectTo }
procedure TActiveSprite.SetState(const aValue: TSpriteState);
begin
fState := aValue;
PauseTime := ifop((SpriteType <> sHero) and (aValue in EggStates),
PauseTimeMax, 0);
RecoveryTime := ifop(aValue = ssRecovering, RecoveryTimeMax, 0);
// SendDebug(GetEnumName(TypeInfo(TSpriteType), Ord(SpriteType)) + ': ' +
// GetEnumName(TypeInfo(TSpriteState), Ord(aValue)));
end; { SetState }
procedure TActiveSprite.SetLevelHint(const aValue: Boolean);
begin
FLevelHint := aValue;
end; { SetLevelHint }
{ THero }
procedure THero.Live;
var
MapX, MapY: TMapCoord;
begin
if (State = ssSleeping) or Ghostly or not InMapCell then Exit;
MapX := PixToMap(X);
MapY := PixToMap(Y);
with Game, Map[MapX, MapY] do
begin
case Item of
tHeart, tHeartInf:
begin
CheckHiddenItems;
Bullets := ifop(Item = tHeart, Bullets + Weight, -1);
if Weight > 0 then
PlaySound(sndRecharge)
else
PlaySound(sndGold);
SetMap(MapX, MapY, mlItem, tEmpty);
if TileCount([tHeart]) = 0 then
GameState := gsOpenChest;
end;
tKey, tMasterkey, tRaft:
if GameState = gsCatchKey then
begin
CheckHiddenItems;
PlaySound(sndKey);
GameState := gsOpenDoors;
LevelTimer := 0;
if Item = tRaft then
begin
Hero.PlaceToBasket(Item);
Game.DrawTile(MapX, MapY, True);
end
else
SetMap(MapX, MapY, mlItem, tEmpty);
end
else if (Weight > 0) and (TileCount([tHeart]) = Weight) then
CheckHiddenItems(True);
tDoorOpenInside..tDoorOpenUp:
begin
vX := 0;
vY := 0;
if Sail <> nil then
DirectTo(Sail.dX, Sail.dY);
if Back <> tEmpty then
if Item in [tDoorOpenDown, tDoorOpenUp] then
SetNextLevel(0, 0, ifop(Item = tDoorOpenDown, -1, 1))
else
SetNextLevel(dX, dY, 0);
GameState := gsNextLevel;
SetMap(MapX, MapY, mlItem, tEmpty);
end;
tBridgeVertical, tSpanner..tHammer, tBoxer, tEraser:
if Weight = 0 then
begin
PlaySound(sndGold);
Hero.PlaceToBasket(Item);
SetMap(MapX, MapY, mlItem, tEmpty);
end;
end;
end;
end; { Live }
function THero.hasHurdleInFront: Boolean;
var
CanStepOnCell: Boolean;
begin
with fCellInfo do
begin
Result := inherited hasHurdleInFront;
CanStepOnCell := CanStepOn(fCellInfo);
if Ghostly then
Result := not CanStepOnCell
else if Sprite[2] <> nil then
with Sprite[2] do
case State of
ssPaused:
Result := not CanStepOnCell or not (isMoving or Pushed(Self.dX, Self.dY));
ssSwimming:
Result := False;
else
case SpriteType of
sBox:
Result := not (CanStepOnCell and Pushed(Self.dX, Self.dY));
sSleepy:
TSleepy(Sprite[2]).TouchMe;
end;
end;
end;
end; { hasHurdleInFront }
function THero.CanStepOn(const aInfo: TCellInfo): Boolean;
var
Backs, Items: TTiles;
begin
if Ghostly then
begin
Backs := GhostPathBacks;
Items := GhostPathItems;
end
else
begin
Backs := HeroPathBacks;
Items := HeroPathItems;
if (dX <> 0) and (x mod MapCellSize = 0) or (dY <> 0) and (y mod MapCellSize = 0) then
Exclude(Items, OffsetTileType(tArrowDown, dX, dY, True));
if (dY > 0) then
Exclude(Items, tDoorOpenUp);
end;
with aInfo do
Result := ([Cell[0].Back, Cell[1].Back] <= Backs) and
([Cell[0].Item, Cell[1].Item] <= Items);
end; { CanStepOn }
procedure THero.Attack(adX, adY: TDelta);
const
CNextArrow: array [tArrowUp..tArrowDown] of TTileType =
(tArrowRight, tArrowUp, tArrowDown, tArrowLeft);
var
MapX, MapY: TMapCoord;
Box: TActiveSprite;
procedure Cast(Tile: TTileType);
var
Index: Word;
begin
with Game.SpriteEngine do
for Index := 0 to Sprites.Count - 1 do
with TActiveSprite(Sprites[Index]) do
case Tile of
tHourglass:
if not (SpriteType in [sHero, sBox]) then
begin
State := ssRecovering;
RecoveryTime := RecoveryTime shr 2;
end;
tHypnotic:
if SpriteType in [sMedusa, sCuckold] then
State := ssSleeping;
end;
end; { Cast }
function BoxInDirection: Boolean;
var
Index: Word;
begin
Result := True;
with Game.SpriteEngine do
for Index := 0 to Sprites.Count - 1 do
begin
Box := TActiveSprite(Sprites[Index]);
if (Box.SpriteType = sBox) and
(sgn(Box.x - x) = dX) and (sgn(Box.y - y) = dY) then Exit;
end;
Box := nil;
Result := False;
end; { BoxInDirection }
begin { Attack }
Log.LogStatus(Format('%s attacks <%d:%d>', [ClassName, adX, adY]), GameStateName);
MapX := PixToMap(x) + dX;
MapY := PixToMap(y) + dY;
with Game, Map[MapX, MapY] do
if Ghostly then
Ghostly := False
else if InMapCell and (Item in FragileItems) and
(InBasket(tHammer, True) or InBasket(tEraser, True)) then
SetMap(MapX, MapY, mlItem, tEmpty)
else if InGridCell and InBasket(tBoxer, True) then
begin
with TBox.Create(sBox, $FF, x + GridToPix(dX), y + GridToPix(dY), dX, dY) do
if not Pushed(dX, dY) then
Kill;
end
else if InMapCell and (Back in LiquidItems) and InBasket(tBridgeVertical, True) then
begin
SetMap(MapX, MapY, mlBack, tGrass);
SetMap(MapX, MapY, mlMid, ifop(dX <> 0, tBridgeHorizontal, tBridgeVertical));
if Sail <> nil then
Pushed(dX, dY);
end
else if InMapCell and (Item in ArrowItems) and InBasket(tSpanner, True) then
SetMap(MapX, MapY, mlItem, CNextArrow[Item])
else if InGridCell and (Back = tWater) and InBasket(tRaft, True) then
begin
TShip.Create(nil, x + MapToPix(dX), y + MapToPix(dY));
Pushed(dX, dY);
end
else if InBasket(tHourglass, True) then
Cast(tHourglass)
else if InBasket(tHypnotic, True) then
Cast(tHypnotic)
else if BoxInDirection and InBasket(tMagnet, True) then
begin
Box.DirectTo(-dX, -dY);
Box.State := ssSleeping;
end
else if not isShooting and (Bullets <> 0) then
begin
inherited Attack(adX, adY);
if isShooting then
Bullets := Bullets - 1;
end
else Exit;
Game.PlaySound(sndShoot);
end; { Attack }
procedure THero.Reset(aX, aY: TPixCoord; adX, adY: TDelta);
var
Index: Byte;
begin
X := aX;
Y := aY;
DirectTo(adX, adY);
vX := 0;
vY := 0;
AnimPhase := 0;
fShooting := False;
State := ssNormal;
Sail := nil;
Ghostly := False;
Bullets := 0;
for Index := low(Basket) to high(Basket) do
InBasket(Basket[Index], True);
AnimPhase := GetPhase(False);
end; { Reset }
function THero.InBasket(aTile: TTileType; aTake: Boolean = False): Boolean;
var
Index: Byte;
begin
Result := True;
for Index := low(Basket) to high(Basket) do
if Basket[Index] = aTile then
begin
if aTake then
begin
Basket[Index] := tNothing;
Game.DrawInfo;
end;
Exit;
end;
Result := False;
end; { InBasket }
procedure THero.PlaceToBasket(aTile: TTileType);
var
Index: Byte;
begin
for Index := low(Basket) to high(Basket) do
if Basket[Index] = tNothing then
begin
Basket[Index] := aTile;
Game.DrawInfo;
Exit;
end;
end; { PutInBasket }
procedure THero.SetBullets(const aValue: ShortInt);
begin
FBullets := aValue;
Game.DrawInfo;
end; { SetBullets }
procedure THero.SetGhostly(const aValue: Boolean);
var
Index: Byte;
begin
if FGhostly = aValue then Exit;
FGhostly := aValue;
RecoveryTime := ifop(aValue, 127, 0);
if aValue then
begin
if Sail <> nil then
Sail.Sailor := nil;
Sail := nil;
Game.PlaySound(sndTrick);
end
else
begin
Dec(x, MapToPix(dX));
Dec(y, MapToPix(dY));
for Index := 1 to GridsInMap do
begin
if hasHurdleInFront then
Game.GameState := gsKillHero;
Inc(x, GridToPix(dX));
Inc(y, GridToPix(dY));
end;
end;
end; { SetGhostly }
function THero.GetSpeed: TSpeed;
var
Xnext, Ynext: TPixCoord;
begin
Result := ifop(State = ssSleeping, 0, inherited GetSpeed);
Xnext := x + GridCellSize;
Ynext := y + GridCellSize;
if (Game.PixMap[Xnext, Ynext].Back = tSand) and
(Game.PixMap[Xnext - 1, Ynext - 1].Back = tSand) then
Result := Result shr 1;
end; { GetSpeed }
procedure THero.Draw;
begin
if Ghostly then
RecoveryTime := 127;
inherited;
end; { Draw }
{ TDragon }
function TDragon.GetPhase(aNext: Boolean): Word;
begin
with Game do
if State = ssNormal then
Result := Ord(Hero.x >= x) shl 1 + Ord(abs(Hero.y - y) < abs(Hero.x - x))
else
Result := inherited GetPhase(aNext);
end; { GetPhase }
procedure TDragon.Live;
var
Index, Hurdles: Word;
begin
if not LevelHint or (Game.GameState <> gsCatchKey) then Exit;
Hurdles := 0;
with Game.SpriteEngine do
for Index := 0 to Sprites.Count - 1 do
with TActiveSprite(Sprites[Index]) do
if SpriteType = sBox then
if x = Self.x then
Inc(Hurdles,
ifop(y = Self.y - MapCellSize, 1, ifop(y = Self.y + MapCellSize, 4, 0)))
else if y = Self.y then
Inc(Hurdles,
ifop(x = Self.x - MapCellSize, 2, ifop(x = Self.x + MapCellSize, 3, 0)));
if Hurdles <> 1 + 2 + 3 + 4 then Exit;
LevelHint := False;
Game.Hero.Ghostly := True;
end; { Live }
{ TFireball }
procedure TFireball.Live;
begin
with Game do
if (State <> ssSleeping) and not isShooting and (GameState = gsCatchKey) then
if (dX <> 0) and (abs(Hero.y - y) <= GridCellSize) and (sgn(Hero.x - x) = dX) or
(dY <> 0) and (abs(Hero.x - x) <= GridCellSize) and (sgn(Hero.y - y) = dY) then
Attack(dX, dY);
end; { Live }
function TFireball.GetPhase(aNext: Boolean): Word;
begin
Result := inherited GetPhase(aNext);
if (State = ssNormal) and (Game.GameState = gsCatchKey) then
Result := Result or 4;
end; { GetPhase }
procedure TFireball.SetState(const aValue: TSpriteState);
begin
inherited;
if LevelHint and (aValue = ssSwimming) and (Game.Hero.InBasket(tBridgeVertical)) then
begin
LevelHint := False;
DoHint;
Kill;
end;
end; { SetState }
class procedure TFireball.DoHint;
begin
Game.ReplaceTiles(tLava, tBasalt, mlBack);
end; { DoHint }
{ TMedusa }
procedure TMedusa.Live;
begin
with Game do
if (State <> ssSleeping) and not isShooting and
((Hero.x = x) or (Hero.y = y)) then
Attack(sgn(Hero.x - x), sgn(Hero.y - y));
end; { Live }
function TMedusa.GetPhase(aNext: Boolean): Word;
begin
with Game do
Result := Ord((State <> ssSleeping) and
((abs(Hero.x - x) <= GridCellSize) or (abs(Hero.y - y) <= GridCellSize)));
end; { GetPhase }
{ TBullet }
constructor TBullet.Create(aSpriteType: TSpriteType; aShooter: TActiveSprite;
adX, adY: TDelta; aCheckPath: Boolean);
begin
with aShooter do
inherited Create(aSpriteType, 0, x, y, adX, adY, False);
Shooter := aShooter;
if aCheckPath then
if CanHitTarget then
Game.Hero.State := ssSleeping
else
begin
Game.SpriteEngine.RemoveSprite(Self);
Exit;
end;
Shooter.isShooting := True;
end; { Create }
procedure TBullet.Live;
begin
if isMoving or Pushed(dX, dY) then Exit;
// if bullet cannot fly further
with fCellInfo, Game do
if Shooter = Hero then
begin
// if Hero shoots and hits in centre of Sprite (not box) he hurts it
if Sprite[2] <> nil then
with Sprite[2] do
if not (SpriteType in [sBox, sHero]) then
Hurt(dX, dY);
if ([Cell[0].Item, Cell[1].Item] <= ChestItems) and
(Cell[0].Weight * Cell[1].Weight <> 0) then
CheckHiddenItems(True);
end
// if bullet just touches Hero he dies
else if (Sprite[0] = Hero) or (Sprite[1] = Hero) then
GameState := gsKillHero;
Kill;
Shooter.isShooting := False;
end; { Live }
function TBullet.CanStepOn(const aInfo: TCellInfo): Boolean;
var
Items: TTiles;
begin
Items := BulletPathItems;
with aInfo do
begin
if Cell[0].Weight + Cell[1].Weight <> 0 then
Items := Items - ChestItems;
Result := ([Cell[0].Back, Cell[1].Back] <= BulletPathBacks) and
([Cell[0].Item, Cell[1].Item] <= Items);
end;
end; { CanStepOn }
function TBullet.CanHitTarget: Boolean;
var
Xold, Yold: TPixCoord;
begin
Xold := X;
Yold := Y;
while not hasHurdleInFront do
begin
Inc(X, GridToPix(dX));
Inc(Y, GridToPix(dY));
end;
Result := (fCellInfo.Sprite[0] = Game.Hero) or (fCellInfo.Sprite[1] = Game.Hero);
X := Xold;
Y := Yold;
end; { CanHitTarget }
function TBullet.GetSpeed: TSpeed;
begin
Result := ifop(SpriteType = sFire, 8, 16);
end; { GetSpeed }
{ TBox }
function TBox.CanStepOn(const aInfo: TCellInfo): Boolean;
begin
with aInfo do
Result := ([Cell[0].Back, Cell[1].Back] <= BoxPathBacks) and
([Cell[0].Item, Cell[1].Item] <= AnyPathItems);
end; { CanStepOn }
procedure TBox.Live;
var
Index: Word;
begin
with Game, SpriteEngine do
if LevelHint and (GameState = gsCatchKey) and (LevelStatus <> lsDone) and
not isMoving then
begin
for Index := 0 to Sprites.Count - 1 do
if (Sprites[Index] is TBox) then
with TBox(Sprites[Index]), PixMap[x, y] do
if LevelHint and
(not InMapCell or (TSpriteType(Sprite shr 4 ) <> sBox)) then Exit;
Hero.Ghostly := True;
for Index := 0 to Sprites.Count - 1 do
if (Sprites[Index] is TBox) then
LevelHint := False;
end;
if not isMoving and (State = ssSleeping) and not Pushed(dX, dY) then
State := ssNormal;
end; { Live }
{ TShip }
constructor TShip.Create(aSailor: TActiveSprite; aX, aY: TPixCoord);
begin
inherited Create(sRaft, 0, aX, aY);
State := ssSwimming;
Sailor := aSailor;
Game.SpriteEngine.SortSprites;
end; { Create }
procedure TShip.Live;
begin
end; { Live }
function TShip.GetPhase(aNext: Boolean): Word;
begin
Result := 0;
end; { GetPhase }
{ TSwingingSprite }
procedure TSwingingSprite.Live;
begin
if (State <> ssSleeping) and not isMoving and not Pushed(dX, dY) then
Pushed(-dX, -dY);
end; { Live }
{ TCuckold }
function TCuckold.GetPhase(aNext: Boolean): Word;
begin
Result := ifop(State = ssNormal, (AnimPhase + Ord(aNext)) and 3,
inherited GetPhase(aNext));
end; { GetPhase }
procedure TCuckold.Live;
begin
with Game do
if (State <> ssSleeping) and not isShooting and InGridCell then
begin
if abs(Hero.x + sgn(Hero.vX) - x) < GridCellSize then
Attack(0, sgn(Hero.y - y))
else if abs(Hero.y + sgn(Hero.vY)- y) < GridCellSize then
Attack(sgn(Hero.x - x), 0);
end;
inherited;
end; { Live }
{ TRoamingSprite }
function TRoamingSprite.HeroTouched(adX, adY: TDistance): Boolean;
begin
Result := (adX <= GridCellSize) and (adY <= GridCellSize);
if Result then
Game.GameState := gsKillHero;
end; { HeroTouched }
procedure TRoamingSprite.Live;
var
Delta: TDelta;
begin
if HeroTouched(abs(Game.Hero.x - x), abs(Game.Hero.y - y)) then Exit;
Delta := (Ord(x < Game.Hero.x) * 2 - 1) * (Ord(y < Game.Hero.y) * 2 - 1);
if not Pushed(dX, dY) then
if not Pushed(-dY * Delta, dX * Delta) and not Pushed(-dX, -dY) then
Pushed(dY * Delta, -dX * Delta);
end; { Live }
procedure TRoamingSprite.GetItemsInFront(var aInfo: TCellInfo);
var
Index: Byte;
begin
inherited;
if SpriteType = sStony then Exit;
for Index := low(aInfo.Sprite) to high(aInfo.Sprite) do
if aInfo.Sprite[Index] = Game.Hero then
aInfo.Sprite[Index] := nil;
end; { GetItemsInFront }
{ TSkull }
function TSkull.GetPhase(aNext: Boolean): Word;
begin
Result := ifop((State = ssNormal) and (Game.GameState = gsCatchKey),
ifop(aNext, ifop(AnimPhase > 3, 1, AnimPhase + 1), 1),
inherited GetPhase(aNext));
end; { GetPhase }
procedure TSkull.Live;
var
dXtoHero, dYtoHero: TDelta;
begin
if (State = ssSleeping) or (Game.GameState <> gsCatchKey) then Exit;
if not isMoving then
begin
dXtoHero := sgn(Game.Hero.x - x);
if dXtoHero = 0 then
dXtoHero := ifop(dX <> 0, dX, 1);
dYtoHero := sgn(Game.Hero.y - y);
if dYtoHero = 0 then
dYtoHero := ifop(dY <> 0, dY, 1);
if (abs(Game.Hero.x - x) <= GridToPix(1)) then
if not Pushed(0, dYtoHero) then
if not Pushed(dXtoHero, 0) then
Pushed(-dXtoHero, 0);
if (abs(Game.Hero.y - y) <= GridToPix(1)) then
if not Pushed(dXtoHero, 0) then
if not Pushed(0, dYtoHero) then
Pushed(0, -dYtoHero);
end;
inherited;
end; { Live }
function TSkull.HeroTouched(adX, adY: TDistance): Boolean;
begin
if Game.GameState = gsCatchKey then
Result := inherited HeroTouched(adX, adY)
else
Result := False;
end; { HeroTouched }
{ TRoller }
function TRoller.GetPhase(aNext: Boolean): Word;
begin
Result := inherited GetPhase(aNext);
if State = ssSleeping then
Result := Result or 16;
end; { GetPhase }
procedure TRoller.Live;
begin
with Game do
if not isMoving then
if State = ssSleeping then
State := ifop(hasHurdleInFront, ssNormal, ssSleeping)
else if abs(Hero.y - y) < GridCellSize then
State := ifop(Pushed(sgn(Hero.x - x), 0), ssSleeping, ssNormal)
else if abs(Hero.x - x) < GridCellSize then
Pushed(0, sgn(Hero.y - y));
inherited;
end; { Live }
{ TSleepy }
constructor TSleepy.Create(aX, aY: TPixCoord; adX: TDelta = 0; adY: TDelta = 0;
aLevelHint: Boolean = False);
begin
inherited Create(sSleepy, 3, aX, aY, adX, adY, aLevelHint);
if LevelHint and (adX <> 0) then
fTouched := 10;
end; { Create }
procedure TSleepy.Live;
begin
if (State <> ssSleeping) and not isMoving then
if abs(Game.Hero.x - x) <= 0 then
Pushed(0, sgn(Game.Hero.y - y))
else if abs(Game.Hero.y - y) <= 0 then
Pushed(sgn(Game.Hero.x - x), 0);
inherited;
end; { Live }
function TSleepy.HeroTouched(adX, adY: TDistance): Boolean;
begin
Result := (adX <= MapCellSize) and (adY <= GridCellSize)
or (adX <= GridCellSize) and (adY <= MapCellSize);
if not Result then Exit;
vX := 0;
vY := 0;
State := ssSleeping;
end; { HeroTouched }
function TSleepy.GetPhase(aNext: Boolean): Word;
begin
if PauseTime > 0 then
Result := inherited GetPhase(aNext)
else
Result := Byte(DeltaToIndex(dX, dY) shl 2) or ifop(State = ssSleeping,
Game.MovePhase shr 2 and $3 or $10, Game.MovePhase {shr 1} and $3);
end; { GetPhase }
procedure TSleepy.TouchMe;
begin
if LevelHint and (fTouched > 0) then
begin
Dec(fTouched);
if fTouched > 0 then Exit;
Game.Hero.Ghostly := True;
LevelHint := False;
end;
end; { TouchMe }
function TSleepy.GetSpeed: TSpeed;
begin
Result := ifop(State = ssSleeping, 0, inherited GetSpeed);
end; { GetSpeed }
procedure TSleepy.Hurt(adX, adY: TDelta);
begin
if State <> ssSleeping then
inherited Hurt(adX, adY);
end; { Hurt }
procedure TSleepy.SetState(const aValue: TSpriteState);
begin
inherited;
if LevelHint and (aValue = ssSwimming) then
begin
LevelHint := False;
DoHint;
Kill;
end;
end; { SetState }
class procedure TSleepy.DoHint;
begin
Game.ReplaceTiles(tWater, tIce, mlBack);
end; { DoHint }
{ TStony }
function TStony.HeroTouched(adX, adY: TDistance): Boolean;
begin
Result := (adX = 0) or (adX <= GridCellSize) and (adY <= MapCellSize) or
(adY <= GridCellSize) and (adX <= MapCellSize * 2);
if (adX = 0) and (Game.MovePhase and $3 = 0) then
Pushed(0, sgn(Game.Hero.Y - Y));
end; { HeroTouched }
function TStony.GetSpeed: TSpeed;
begin
Result := ifop(State = ssSleeping, 0, inherited GetSpeed shr 1);
if (Result > 0) and (Game.Hero.x = x) and (dY = sgn(Game.Hero.y - y)) then
begin
Result := Result shl 1;
if (dX <> 0) and (x mod Result <> 0) or (dY <> 0) and (y mod Result <> 0) then
Result := Result shr 1;
end; { GetSpeed }
end;
function TStony.hasHurdleInFront: Boolean;
begin
Result := inherited hasHurdleInFront;
with fCellInfo do
if CanStepOn(fCellInfo) and (Sprite[2] = Game.Hero) then
Result := not Sprite[2].Pushed(dX, dY);
end; { hasHurdleInFront }
end.
|
unit afwSettings;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "AFW"
// Модуль: "w:/common/components/gui/Garant/AFW/afwSettings.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::AFW::afwSettings::TafwSettings
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\AFW\afwDefine.inc}
interface
uses
afwInterfaces,
IafwSettingListenerPtrList,
IafwSettingsReplaceListenerPtrList,
afwSettingsPrimPrim,
afwSettingsImplPrimPrim
;
type
TafwSettings = class(TafwSettingsPrimPrim, IafwSettings, IafwSettingsNotify)
private
// private fields
f_State : TafwSettingsState;
f_SettingListeners : TIafwSettingListenerPtrList;
f_ReplaceListeners : TIafwSettingsReplaceListenerPtrList;
protected
// realized methods
function Clone(const aConf: IUnknown): IafwSettings;
procedure AddListener(const aListener: IafwSettingListener); overload;
procedure RemoveListener(const aListener: IafwSettingListener); overload;
procedure AddListener(const aListener: IafwSettingsReplaceListener); overload;
procedure RemoveListener(const aListener: IafwSettingsReplaceListener); overload;
function pm_GetNotify: IafwSettingsNotify;
function pm_GetState: TafwSettingsState;
procedure pm_SetState(aValue: TafwSettingsState);
function LoadDouble(const aSettingId: TafwSettingId;
aDefault: Double = 0;
aRestoreDefault: Boolean = False): Double;
procedure SaveDouble(const aSettingId: TafwSettingId;
aValue: Double;
aDefault: Double = 0;
aSetAsDefault: Boolean = False);
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure InitFields; override;
procedure NotifySettingChanged(const aSettingID: TafwSettingId); override;
public
// public methods
class function Make(const aSettingsImpl: IafwSettingsImpl): IafwSettings; reintroduce;
{* Сигнатура фабрики TafwSettings.Make }
end;//TafwSettings
implementation
uses
SysUtils
;
// start class TafwSettings
class function TafwSettings.Make(const aSettingsImpl: IafwSettingsImpl): IafwSettings;
var
l_Inst : TafwSettings;
begin
l_Inst := Create(aSettingsImpl);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
function TafwSettings.Clone(const aConf: IUnknown): IafwSettings;
//#UC START# *473D9F0F033A_4F6C957F01E7_var*
//#UC END# *473D9F0F033A_4F6C957F01E7_var*
begin
//#UC START# *473D9F0F033A_4F6C957F01E7_impl*
Result := Self;
//#UC END# *473D9F0F033A_4F6C957F01E7_impl*
end;//TafwSettings.Clone
procedure TafwSettings.AddListener(const aListener: IafwSettingListener);
//#UC START# *475E8E410197_4F6C957F01E7_var*
//#UC END# *475E8E410197_4F6C957F01E7_var*
begin
//#UC START# *475E8E410197_4F6C957F01E7_impl*
if (f_SettingListeners = nil) then
f_SettingListeners := TIafwSettingListenerPtrList.Make;
if (f_SettingListeners.IndexOf(aListener) = -1) then
f_SettingListeners.Add(aListener);
//#UC END# *475E8E410197_4F6C957F01E7_impl*
end;//TafwSettings.AddListener
procedure TafwSettings.RemoveListener(const aListener: IafwSettingListener);
//#UC START# *475E8E4D03E4_4F6C957F01E7_var*
//#UC END# *475E8E4D03E4_4F6C957F01E7_var*
begin
//#UC START# *475E8E4D03E4_4F6C957F01E7_impl*
if (f_SettingListeners <> nil) then
f_SettingListeners.Remove(aListener);
//#UC END# *475E8E4D03E4_4F6C957F01E7_impl*
end;//TafwSettings.RemoveListener
procedure TafwSettings.AddListener(const aListener: IafwSettingsReplaceListener);
//#UC START# *475E8E5E0286_4F6C957F01E7_var*
//#UC END# *475E8E5E0286_4F6C957F01E7_var*
begin
//#UC START# *475E8E5E0286_4F6C957F01E7_impl*
if (f_ReplaceListeners = nil) then
f_ReplaceListeners := TIafwSettingsReplaceListenerPtrList.Make;
if (f_ReplaceListeners.IndexOf(aListener) = -1) then
f_ReplaceListeners.Add(aListener);
//#UC END# *475E8E5E0286_4F6C957F01E7_impl*
end;//TafwSettings.AddListener
procedure TafwSettings.RemoveListener(const aListener: IafwSettingsReplaceListener);
//#UC START# *475E8E7900A3_4F6C957F01E7_var*
//#UC END# *475E8E7900A3_4F6C957F01E7_var*
begin
//#UC START# *475E8E7900A3_4F6C957F01E7_impl*
if f_ReplaceListeners <> nil then
f_ReplaceListeners.Remove(aListener);
//#UC END# *475E8E7900A3_4F6C957F01E7_impl*
end;//TafwSettings.RemoveListener
function TafwSettings.pm_GetNotify: IafwSettingsNotify;
//#UC START# *475E8F5A0198_4F6C957F01E7get_var*
//#UC END# *475E8F5A0198_4F6C957F01E7get_var*
begin
//#UC START# *475E8F5A0198_4F6C957F01E7get_impl*
Result := Self;
//#UC END# *475E8F5A0198_4F6C957F01E7get_impl*
end;//TafwSettings.pm_GetNotify
function TafwSettings.pm_GetState: TafwSettingsState;
//#UC START# *48896A7B0311_4F6C957F01E7get_var*
//#UC END# *48896A7B0311_4F6C957F01E7get_var*
begin
//#UC START# *48896A7B0311_4F6C957F01E7get_impl*
Result := f_State;
//#UC END# *48896A7B0311_4F6C957F01E7get_impl*
end;//TafwSettings.pm_GetState
procedure TafwSettings.pm_SetState(aValue: TafwSettingsState);
//#UC START# *48896A7B0311_4F6C957F01E7set_var*
//#UC END# *48896A7B0311_4F6C957F01E7set_var*
begin
//#UC START# *48896A7B0311_4F6C957F01E7set_impl*
f_State := aValue;
//#UC END# *48896A7B0311_4F6C957F01E7set_impl*
end;//TafwSettings.pm_SetState
function TafwSettings.LoadDouble(const aSettingId: TafwSettingId;
aDefault: Double = 0;
aRestoreDefault: Boolean = False): Double;
//#UC START# *4AB729980069_4F6C957F01E7_var*
//#UC END# *4AB729980069_4F6C957F01E7_var*
begin
//#UC START# *4AB729980069_4F6C957F01E7_impl*
LoadParam(aSettingId, vtExtended, Result, aDefault, aRestoreDefault);
//#UC END# *4AB729980069_4F6C957F01E7_impl*
end;//TafwSettings.LoadDouble
procedure TafwSettings.SaveDouble(const aSettingId: TafwSettingId;
aValue: Double;
aDefault: Double = 0;
aSetAsDefault: Boolean = False);
//#UC START# *4AB729A702A2_4F6C957F01E7_var*
//#UC END# *4AB729A702A2_4F6C957F01E7_var*
begin
//#UC START# *4AB729A702A2_4F6C957F01E7_impl*
SaveParam(aSettingId, vtExtended, aValue, aDefault, aSetAsDefault);
//#UC END# *4AB729A702A2_4F6C957F01E7_impl*
end;//TafwSettings.SaveDouble
procedure TafwSettings.Cleanup;
//#UC START# *479731C50290_4F6C957F01E7_var*
//#UC END# *479731C50290_4F6C957F01E7_var*
begin
//#UC START# *479731C50290_4F6C957F01E7_impl*
FreeAndNil(f_ReplaceListeners);
FreeAndNil(f_SettingListeners);
inherited;
//#UC END# *479731C50290_4F6C957F01E7_impl*
end;//TafwSettings.Cleanup
procedure TafwSettings.InitFields;
//#UC START# *47A042E100E2_4F6C957F01E7_var*
//#UC END# *47A042E100E2_4F6C957F01E7_var*
begin
//#UC START# *47A042E100E2_4F6C957F01E7_impl*
inherited;
f_State := afw_ssNone;
//#UC END# *47A042E100E2_4F6C957F01E7_impl*
end;//TafwSettings.InitFields
procedure TafwSettings.NotifySettingChanged(const aSettingID: TafwSettingId);
//#UC START# *4AD5979E01BB_4F6C957F01E7_var*
var
l_Index : Integer;
//#UC END# *4AD5979E01BB_4F6C957F01E7_var*
begin
//#UC START# *4AD5979E01BB_4F6C957F01E7_impl*
inherited;
if (f_SettingListeners <> nil) then
for l_Index := 0 to Pred(f_SettingListeners.Count) do
f_SettingListeners[l_Index].Changed(aSettingId);
//#UC END# *4AD5979E01BB_4F6C957F01E7_impl*
end;//TafwSettings.NotifySettingChanged
end. |
unit LoggedUserData;
interface
procedure SetUserData(data : pointer);
procedure LogSystem;
function GetUserData : pointer;
function CheckAuthenticity(data : pointer) : boolean;
implementation
uses
Windows, Classes, Messages, RDOInterfaces, SmartThreads;
const
SYSTEM_SIM : pointer = pointer($FFFFFFF0);
procedure SetUserData(data : pointer);
var
Thread : TThread;
Msg : TMessage;
begin
Thread := SmartThreads.FindThread(GetCurrentThreadID);
if Thread <> nil
then
begin
Msg.Msg := MSG_SETTHREADDATA;
Msg.LParam := integer(data);
Thread.Dispatch(Msg);
end;
end;
procedure LogSystem;
begin
SetUserData(SYSTEM_SIM);
end;
function GetUserData : pointer;
var
Thread : TThread;
Msg : TMessage;
begin
Thread := SmartThreads.FindThread(GetCurrentThreadID);
if Thread <> nil
then
begin
Msg.Msg := MSG_GETTHREADDATA;
Msg.Result := integer(nil);
Thread.Dispatch(Msg);
result := pointer(Msg.Result);
end
else result := nil;
end;
function CheckAuthenticity(data : pointer) : boolean;
var
usrData : pointer;
begin
usrData := GetUserData;
result := (usrData = data) or (usrData = SYSTEM_SIM);
end;
end.
|
unit IRCViewIntf;
{$mode objfpc}{$H+}
interface
type
IIRCView = interface
procedure UpdateTabCaption(Tab: TObject; ACaption: string);
procedure UpdateNodeText(Node: TObject; AText: string);
procedure ServerMessage(const AText: string);
procedure NotifyChanged;
function GetTab(const ACaption: string): TObject;
function GetNode(const ACaption: string; ParentNode: TObject): TObject;
end;
implementation
end.
|
unit PE.Imports;
interface
uses
System.Generics.Collections,
System.SysUtils,
PE.Common,
PE.Imports.Func,
PE.Imports.Lib;
type
TPEImportLibraryObjectList = TObjectList<TPEImportLibrary>;
TPEImport = class
private
FLibs: TPEImportLibraryObjectList;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Add(Lib: TPEImportLibrary): TPEImportLibrary; inline;
function NewLib(const Name: string): TPEImportLibrary;
property Libs: TPEImportLibraryObjectList read FLibs;
end;
implementation
{ TPEImports }
constructor TPEImport.Create;
begin
inherited Create;
FLibs := TPEImportLibraryObjectList.Create;
end;
destructor TPEImport.Destroy;
begin
FLibs.Free;
inherited;
end;
function TPEImport.NewLib(const Name: string): TPEImportLibrary;
begin
result := Add(TPEImportLibrary.Create(Name));
end;
procedure TPEImport.Clear;
begin
FLibs.Clear;
end;
function TPEImport.Add(Lib: TPEImportLibrary): TPEImportLibrary;
begin
FLibs.Add(Lib);
result := Lib;
end;
end.
|
program countdown;
var
sec : integer;
begin
writeln('Countdown has begun ...');
sec := 10;
repeat
write(sec, ' ');
sec := sec - 1
until sec = 0;
writeln('Zero')
end.
|
unit m3LiveSearcherResult;
{ Библиотека "M3" }
{ Автор: Люлин А.В. © }
{ Модуль: m3LiveSearcherResult - }
{ Начат: 19.02.2003 14:07 }
{ $Id: m3LiveSearcherResult.pas,v 1.3 2009/03/19 16:28:30 lulin Exp $ }
// $Log: m3LiveSearcherResult.pas,v $
// Revision 1.3 2009/03/19 16:28:30 lulin
// [$139443095].
//
// Revision 1.2 2008/02/14 17:30:34 lulin
// - cleanup.
//
// Revision 1.1 2004/09/02 08:09:48 law
// - cleanup.
//
// Revision 1.1 2003/02/19 14:11:13 law
// - new class: Tm3LiveSearcherResult.
//
{$I m3Define.inc}
interface
uses
ActiveX,
l3Types,
l3Base,
l3CacheableBase,
m3IdxInt
;
type
Tm3LiveSearcherResult = class(Tl3CacheableBase, Im3IndexSearcherResult)
private
// internal fields
f_Stream : IStream;
f_ItemSize : Long;
private
// interface methods
// Im3IndexSearcherResult
procedure Reset;
{* - переместиться на начало. }
function GetCount: LongInt;
{* - получить количество элементов. }
function Get(const anItem : Pointer;
const anItemSize : LongInt): LongBool;
{* - получить текущий элемент. }
protected
// internal methods
procedure Cleanup;
override;
{-}
public
// public methods
constructor Create(const aStream : IStream;
anItemSize : Long);
reintroduce;
{-}
class function Make(const aStream : IStream;
anItemSize : Long): Im3IndexSearcherResult;
{-}
end;//Tm3LiveSearcherResult
implementation
uses
m2COMLib
;
// start class Tm3LiveSearcherResult
constructor Tm3LiveSearcherResult.Create(const aStream : IStream;
anItemSize : Long);
//reintroduce;
{-}
begin
inherited Create;
f_Stream := aStream;
f_ItemSize := anItemSize;
end;
class function Tm3LiveSearcherResult.Make(const aStream : IStream;
anItemSize : Long): Im3IndexSearcherResult;
{-}
var
l_Result : Tm3LiveSearcherResult;
begin
l_Result := Tm3LiveSearcherResult.Create(aStream, anItemSize);
try
Result := l_Result;
finally
l3Free(l_Result);
end;//try..finally
end;
procedure Tm3LiveSearcherResult.Cleanup;
//override;
{-}
begin
f_Stream := nil;
inherited;
end;
procedure Tm3LiveSearcherResult.Reset;
{* - переместиться на начало. }
begin
if (f_Stream <> nil) then
m2COMSeek(f_Stream, 0, STREAM_SEEK_SET);
end;
function Tm3LiveSearcherResult.GetCount: LongInt;
{* - получить количество элементов. }
begin
if (f_Stream = nil) then
Result := 0
else
Result := m2COMGetSize(f_Stream) div f_ItemSize;
end;
function Tm3LiveSearcherResult.Get(const anItem : Pointer;
const anItemSize : LongInt): LongBool;
{* - получить текущий элемент. }
var
l_Result : hResult;
begin
Assert(f_ItemSize = anItemSize);
if (f_Stream = nil) then
Result := false
else begin
l_Result := f_Stream.Read(anItem, anItemSize, nil);
Result := l3IOk(l_Result) AND (l_Result <> S_False);
end;//f_Stream = nil
end;
end.
|
unit nevControl;
// Модуль: "w:\common\components\gui\Garant\Everest\nevControl.pas"
// Стереотип: "GuiControl"
// Элемент модели: "TnevControl" MUID: (48E0E5C1032A)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, afwControl
, nevBase
, nevTools
, evdStyles
, l3Units
, Types
, l3Core
, l3Interfaces
, l3Variant
, afwInterfaces
;
type
_evStyleTableListener_Parent_ = TafwControl;
{$Include w:\common\components\gui\Garant\Everest\evStyleTableListener.imp.pas}
TnevControl = class(_evStyleTableListener_, InevViewMetrics, InevControl)
private
f_WebStyle: Boolean;
f_RMargin: Integer;
{* правый отступ от окна до текста }
f_AllowRubberTables: TnevRubberTablesMode;
f_AACLike: TnevAACLikeMode;
protected
f_InPaint: Integer;
f_ShowDocumentParts: Boolean;
f_HiddenStyles: TevStandardStyles;
f_ExcludeSuper: TevNormalSegLayerHandleSet;
protected
procedure pm_SetWebStyle(aValue: Boolean);
procedure pm_SetRMargin(aValue: Integer);
procedure pm_SetAllowRubberTables(aValue: TnevRubberTablesMode);
procedure pm_SetAACLike(aValue: TnevAACLikeMode);
function pm_GetActiveElementPrim: InevActiveElement; virtual;
function pm_GetForceDrawFocusRectPrim: Boolean; virtual;
function GetInfoCanvas: InevInfoCanvas; virtual;
function GetLimitWidth: Integer; virtual; abstract;
procedure DoChanged(aPlace: TnevChangePlace); virtual;
{* Данные для отображения изменились }
procedure DoSignalScroll(aDeltaY: Integer;
aNeedVert: Boolean); virtual;
function DoCloseQuery: Boolean; virtual;
procedure DoCursorChanged; virtual;
procedure DoSetFlag(aFlag: TevUpdateWindowFlag); virtual;
function GetData: InevObject; virtual;
function GetProcessor: InevProcessor; virtual;
function GetSelection: InevSelection; virtual;
function GetAllowMultiSelect: Boolean; virtual;
function GetViewArea: InevViewArea; virtual;
function GetLMargin: Integer; virtual;
function GetView: InevInputView; virtual;
function GetCanScroll: Boolean; virtual;
function GetMousePos(var aPt: Tl3SPoint): Tl3Point;
function DP2LP(const aPoint: TPoint;
fromScreen: Boolean = False): Tl3Point;
procedure WebStyleChanged; virtual;
procedure DoParaChange; virtual;
{* Нотификация о смене параграфа. }
procedure DoForceRepaint; virtual;
function GetInClose: Boolean; virtual;
function pm_GetLimitWidth: TnevInch;
function pm_GetInfoCanvas: InevInfoCanvas;
function pm_GetIsWebStyle: Boolean;
function pm_GetShowDocumentParts: Boolean;
function pm_GetShowSpecial: Boolean;
function pm_GetHiddenStyles: TnevStandardStyles;
procedure InvalidateRect(const aRect: TnevRect);
{* сообщает контролу о необходимости перерисовки указанного прямоугольника, когда-нибудь в будущем. }
procedure SignalScroll(aDeltaY: Integer;
aNeedVert: Boolean);
{* сообщает контролу, о том, что изменилась позиция скроллера. }
function GetDelphiControl: TComponent;
function CloseQuery: Boolean;
{* спрашивает контрол, о возможности закрытия окна, которому он принадлежит. }
function LP2DP(const aPoint: TnevPoint;
toScreen: Boolean = False): TPoint;
procedure CursorChanged;
function CanScroll: Boolean;
procedure SetFlag(aFlag: TevUpdateWindowFlag);
{* установить флаг aFlag. }
procedure UpdateCaretAndInvalidate;
{* Проверить и переставить каретку + перерисоваться }
function pm_GetData: InevObject;
function Get_Processor: InevProcessor;
function pm_GetWindowExtent: TnevSPoint;
function pm_GetMetrics: InevViewMetrics;
function pm_GetDrawCanvas: InevCanvas;
function pm_GetMousePos: TnevPoint;
function pm_GetSelection: InevSelection;
function pm_GetCommandProcessor: InevCommandProcessor;
function pm_GetLMargin: Integer;
function pm_GetAllowMultiSelect: Boolean;
function pm_GetViewArea: InevViewArea;
function pm_GetView: InevInputView;
function pm_GetExtent: TnevPoint;
procedure ParaChanged;
{* Нотификация о смене текущего параграфа. }
function Get_ActiveElement: InevActiveElement;
{$If NOT Defined(DesignTimeLibrary)}
procedure DoStyleTableChanged; override;
{$IfEnd} // NOT Defined(DesignTimeLibrary)
function Get_ExcludeSuper: TevNormalSegLayerHandleSet;
function Get_ForceDrawFocusRect: Boolean;
function Get_FormatCanvas: InevInfoCanvas;
procedure ForceRepaint;
{* По жёсткому перерисовать сожержимое контрола (прямо внутри операции редактирования). Нужно для http://mdp.garant.ru/pages/viewpage.action?pageId=204113269 }
function Get_AllowRubberTables: TnevRubberTablesMode;
function IsTagCollapsed(aTag: Tl3Variant): Boolean;
function Get_Data: InevObjectPrim;
function InClose: Boolean;
{* Редактор в процессе закрытия. }
function Get_AACLike: TnevAACLikeMode;
function NeedTotalRecalc: Boolean;
public
function AllowsThisDecor(aFI: TnevFormatInfoPrim;
aType: TnevDecorType): Boolean;
{* Разрешает ли контейтер документа применять указанное декорирование }
protected
property ActiveElementPrim: InevActiveElement
read pm_GetActiveElementPrim;
property ForceDrawFocusRectPrim: Boolean
read pm_GetForceDrawFocusRectPrim;
public
property WebStyle: Boolean
read f_WebStyle
write pm_SetWebStyle
default False;
property RMargin: Integer
read f_RMargin
write pm_SetRMargin
default 0;
{* правый отступ от окна до текста }
property AllowRubberTables: TnevRubberTablesMode
read f_AllowRubberTables
write pm_SetAllowRubberTables
default nevBase.nev_rtmNone;
property AACLike: TnevAACLikeMode
read f_AACLike
write pm_SetAACLike;
end;//TnevControl
implementation
uses
l3ImplUses
, nevFacade
, k2Tags
, k2Base
, l3MinMax
, Messages
, TextPara_Const
, l3Defaults
, l3InternalInterfaces
{$If NOT Defined(DesignTimeLibrary)}
, evStyleTableSpy
{$IfEnd} // NOT Defined(DesignTimeLibrary)
{$If NOT Defined(NoScripts)}
, TtfwClassRef_Proxy
{$IfEnd} // NOT Defined(NoScripts)
//#UC START# *48E0E5C1032Aimpl_uses*
//#UC END# *48E0E5C1032Aimpl_uses*
;
{$Include w:\common\components\gui\Garant\Everest\evStyleTableListener.imp.pas}
procedure TnevControl.pm_SetWebStyle(aValue: Boolean);
//#UC START# *48E0EDB700C0_48E0E5C1032Aset_var*
//#UC END# *48E0EDB700C0_48E0E5C1032Aset_var*
begin
//#UC START# *48E0EDB700C0_48E0E5C1032Aset_impl*
if (f_WebStyle <> aValue) then
begin
f_WebStyle := aValue;
DoChanged(nev_cpView);
Invalidate;
WebStyleChanged;
end;//f_WebStyle <> aValue
//#UC END# *48E0EDB700C0_48E0E5C1032Aset_impl*
end;//TnevControl.pm_SetWebStyle
procedure TnevControl.pm_SetRMargin(aValue: Integer);
//#UC START# *48E1F7EA014E_48E0E5C1032Aset_var*
//#UC END# *48E1F7EA014E_48E0E5C1032Aset_var*
begin
//#UC START# *48E1F7EA014E_48E0E5C1032Aset_impl*
if (f_RMargin <> aValue) then
begin
f_RMargin := aValue;
Invalidate;
end;//f_RMargin <> aValue
//#UC END# *48E1F7EA014E_48E0E5C1032Aset_impl*
end;//TnevControl.pm_SetRMargin
procedure TnevControl.pm_SetAllowRubberTables(aValue: TnevRubberTablesMode);
//#UC START# *4BED74E4005A_48E0E5C1032Aset_var*
//#UC END# *4BED74E4005A_48E0E5C1032Aset_var*
begin
//#UC START# *4BED74E4005A_48E0E5C1032Aset_impl*
if (f_AllowRubberTables <> aValue) then
begin
f_AllowRubberTables := aValue;
DoChanged(nev_cpView);
Invalidate;
end;//f_AllowRubberTables <> aValue
//#UC END# *4BED74E4005A_48E0E5C1032Aset_impl*
end;//TnevControl.pm_SetAllowRubberTables
procedure TnevControl.pm_SetAACLike(aValue: TnevAACLikeMode);
//#UC START# *501F9F66008F_48E0E5C1032Aset_var*
//#UC END# *501F9F66008F_48E0E5C1032Aset_var*
begin
//#UC START# *501F9F66008F_48E0E5C1032Aset_impl*
f_AACLike := aValue;
//#UC END# *501F9F66008F_48E0E5C1032Aset_impl*
end;//TnevControl.pm_SetAACLike
function TnevControl.pm_GetActiveElementPrim: InevActiveElement;
//#UC START# *4A27CF530106_48E0E5C1032Aget_var*
//#UC END# *4A27CF530106_48E0E5C1032Aget_var*
begin
//#UC START# *4A27CF530106_48E0E5C1032Aget_impl*
Result := nil;
//#UC END# *4A27CF530106_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetActiveElementPrim
function TnevControl.pm_GetForceDrawFocusRectPrim: Boolean;
//#UC START# *4B59AA4700E5_48E0E5C1032Aget_var*
//#UC END# *4B59AA4700E5_48E0E5C1032Aget_var*
begin
//#UC START# *4B59AA4700E5_48E0E5C1032Aget_impl*
Result := false;
//#UC END# *4B59AA4700E5_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetForceDrawFocusRectPrim
function TnevControl.GetInfoCanvas: InevInfoCanvas;
//#UC START# *48E0EC2C0286_48E0E5C1032A_var*
//#UC END# *48E0EC2C0286_48E0E5C1032A_var*
begin
//#UC START# *48E0EC2C0286_48E0E5C1032A_impl*
if (f_InPaint > 0) then
Result := Canvas
else
begin
Result := nev.CrtIC;
Result.PasswordChar := #0;
//Result.LineSpacing := def_LineSpacing;
end;//f_InPaint > 0
//#UC END# *48E0EC2C0286_48E0E5C1032A_impl*
end;//TnevControl.GetInfoCanvas
procedure TnevControl.DoChanged(aPlace: TnevChangePlace);
{* Данные для отображения изменились }
//#UC START# *48E1F0CB0136_48E0E5C1032A_var*
//#UC END# *48E1F0CB0136_48E0E5C1032A_var*
begin
//#UC START# *48E1F0CB0136_48E0E5C1032A_impl*
//#UC END# *48E1F0CB0136_48E0E5C1032A_impl*
end;//TnevControl.DoChanged
procedure TnevControl.DoSignalScroll(aDeltaY: Integer;
aNeedVert: Boolean);
//#UC START# *48E1F13202FB_48E0E5C1032A_var*
//#UC END# *48E1F13202FB_48E0E5C1032A_var*
begin
//#UC START# *48E1F13202FB_48E0E5C1032A_impl*
//#UC END# *48E1F13202FB_48E0E5C1032A_impl*
end;//TnevControl.DoSignalScroll
function TnevControl.DoCloseQuery: Boolean;
//#UC START# *48E1F18502D8_48E0E5C1032A_var*
//#UC END# *48E1F18502D8_48E0E5C1032A_var*
begin
//#UC START# *48E1F18502D8_48E0E5C1032A_impl*
Result := true;
//#UC END# *48E1F18502D8_48E0E5C1032A_impl*
end;//TnevControl.DoCloseQuery
procedure TnevControl.DoCursorChanged;
//#UC START# *48E1F1B1033C_48E0E5C1032A_var*
//#UC END# *48E1F1B1033C_48E0E5C1032A_var*
begin
//#UC START# *48E1F1B1033C_48E0E5C1032A_impl*
//#UC END# *48E1F1B1033C_48E0E5C1032A_impl*
end;//TnevControl.DoCursorChanged
procedure TnevControl.DoSetFlag(aFlag: TevUpdateWindowFlag);
//#UC START# *48E1F1F30170_48E0E5C1032A_var*
//#UC END# *48E1F1F30170_48E0E5C1032A_var*
begin
//#UC START# *48E1F1F30170_48E0E5C1032A_impl*
//#UC END# *48E1F1F30170_48E0E5C1032A_impl*
end;//TnevControl.DoSetFlag
function TnevControl.GetData: InevObject;
//#UC START# *48E1F2190158_48E0E5C1032A_var*
//#UC END# *48E1F2190158_48E0E5C1032A_var*
begin
//#UC START# *48E1F2190158_48E0E5C1032A_impl*
Result := nil;
//#UC END# *48E1F2190158_48E0E5C1032A_impl*
end;//TnevControl.GetData
function TnevControl.GetProcessor: InevProcessor;
//#UC START# *48E1F2980113_48E0E5C1032A_var*
//#UC END# *48E1F2980113_48E0E5C1032A_var*
begin
//#UC START# *48E1F2980113_48E0E5C1032A_impl*
Result := nil;
//#UC END# *48E1F2980113_48E0E5C1032A_impl*
end;//TnevControl.GetProcessor
function TnevControl.GetSelection: InevSelection;
//#UC START# *48E1F2ED0121_48E0E5C1032A_var*
//#UC END# *48E1F2ED0121_48E0E5C1032A_var*
begin
//#UC START# *48E1F2ED0121_48E0E5C1032A_impl*
Result := nil;
//#UC END# *48E1F2ED0121_48E0E5C1032A_impl*
end;//TnevControl.GetSelection
function TnevControl.GetAllowMultiSelect: Boolean;
//#UC START# *48E1F321030C_48E0E5C1032A_var*
//#UC END# *48E1F321030C_48E0E5C1032A_var*
begin
//#UC START# *48E1F321030C_48E0E5C1032A_impl*
Result := false;
//#UC END# *48E1F321030C_48E0E5C1032A_impl*
end;//TnevControl.GetAllowMultiSelect
function TnevControl.GetViewArea: InevViewArea;
//#UC START# *48E1F3580003_48E0E5C1032A_var*
//#UC END# *48E1F3580003_48E0E5C1032A_var*
begin
//#UC START# *48E1F3580003_48E0E5C1032A_impl*
Result := nil;
//#UC END# *48E1F3580003_48E0E5C1032A_impl*
end;//TnevControl.GetViewArea
function TnevControl.GetLMargin: Integer;
//#UC START# *48E1F3A903BF_48E0E5C1032A_var*
//#UC END# *48E1F3A903BF_48E0E5C1032A_var*
begin
//#UC START# *48E1F3A903BF_48E0E5C1032A_impl*
Result := 0;
//#UC END# *48E1F3A903BF_48E0E5C1032A_impl*
end;//TnevControl.GetLMargin
function TnevControl.GetView: InevInputView;
//#UC START# *48E1F3E30366_48E0E5C1032A_var*
//#UC END# *48E1F3E30366_48E0E5C1032A_var*
begin
//#UC START# *48E1F3E30366_48E0E5C1032A_impl*
Result := nil;
//#UC END# *48E1F3E30366_48E0E5C1032A_impl*
end;//TnevControl.GetView
function TnevControl.GetCanScroll: Boolean;
//#UC START# *48E1F5F20015_48E0E5C1032A_var*
//#UC END# *48E1F5F20015_48E0E5C1032A_var*
begin
//#UC START# *48E1F5F20015_48E0E5C1032A_impl*
Result := true;
//#UC END# *48E1F5F20015_48E0E5C1032A_impl*
end;//TnevControl.GetCanScroll
function TnevControl.GetMousePos(var aPt: Tl3SPoint): Tl3Point;
//#UC START# *48E1F78F024B_48E0E5C1032A_var*
//#UC END# *48E1F78F024B_48E0E5C1032A_var*
begin
//#UC START# *48E1F78F024B_48E0E5C1032A_impl*
aPt.GetCursorPos;
aPt.Convert(ScreenToClient);
Result := DP2LP(TPoint(aPt));
//#UC END# *48E1F78F024B_48E0E5C1032A_impl*
end;//TnevControl.GetMousePos
function TnevControl.DP2LP(const aPoint: TPoint;
fromScreen: Boolean = False): Tl3Point;
//#UC START# *48E1F7A9003B_48E0E5C1032A_var*
var
l_Pt: TPoint;
//#UC END# *48E1F7A9003B_48E0E5C1032A_var*
begin
//#UC START# *48E1F7A9003B_48E0E5C1032A_impl*
if fromScreen then
l_Pt := ScreenToClient(aPoint)
else
l_Pt := aPoint;
Result := GetInfoCanvas.DP2LP(l3SPoint(evPixelDezoom(Canvas.Zoom, l_Pt.X){-LMargin},
evPixelDezoom(Canvas.Zoom, l_Pt.Y)));
Result := Result.Sub(Il3Canvas(Canvas).{InitialDCOffset}InitialDCOffsetStored);
// - http://mdp.garant.ru/pages/viewpage.action?pageId=509115846
//#UC END# *48E1F7A9003B_48E0E5C1032A_impl*
end;//TnevControl.DP2LP
procedure TnevControl.WebStyleChanged;
//#UC START# *48E238D80225_48E0E5C1032A_var*
//#UC END# *48E238D80225_48E0E5C1032A_var*
begin
//#UC START# *48E238D80225_48E0E5C1032A_impl*
//#UC END# *48E238D80225_48E0E5C1032A_impl*
end;//TnevControl.WebStyleChanged
procedure TnevControl.DoParaChange;
{* Нотификация о смене параграфа. }
//#UC START# *48E3674B0230_48E0E5C1032A_var*
//#UC END# *48E3674B0230_48E0E5C1032A_var*
begin
//#UC START# *48E3674B0230_48E0E5C1032A_impl*
//#UC END# *48E3674B0230_48E0E5C1032A_impl*
end;//TnevControl.DoParaChange
procedure TnevControl.DoForceRepaint;
//#UC START# *4BCC315901D3_48E0E5C1032A_var*
//#UC END# *4BCC315901D3_48E0E5C1032A_var*
begin
//#UC START# *4BCC315901D3_48E0E5C1032A_impl*
Invalidate;
inherited Update;
//#UC END# *4BCC315901D3_48E0E5C1032A_impl*
end;//TnevControl.DoForceRepaint
function TnevControl.GetInClose: Boolean;
//#UC START# *4F3CE6EF01D8_48E0E5C1032A_var*
//#UC END# *4F3CE6EF01D8_48E0E5C1032A_var*
begin
//#UC START# *4F3CE6EF01D8_48E0E5C1032A_impl*
Result := False;
//#UC END# *4F3CE6EF01D8_48E0E5C1032A_impl*
end;//TnevControl.GetInClose
function TnevControl.pm_GetLimitWidth: TnevInch;
//#UC START# *476BFB3C007A_48E0E5C1032Aget_var*
//#UC END# *476BFB3C007A_48E0E5C1032Aget_var*
begin
//#UC START# *476BFB3C007A_48E0E5C1032Aget_impl*
Result := GetLimitWidth;
//#UC END# *476BFB3C007A_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetLimitWidth
function TnevControl.pm_GetInfoCanvas: InevInfoCanvas;
//#UC START# *476BFBE10164_48E0E5C1032Aget_var*
//#UC END# *476BFBE10164_48E0E5C1032Aget_var*
begin
//#UC START# *476BFBE10164_48E0E5C1032Aget_impl*
Result := GetInfoCanvas;
//#UC END# *476BFBE10164_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetInfoCanvas
function TnevControl.pm_GetIsWebStyle: Boolean;
//#UC START# *476BFC120188_48E0E5C1032Aget_var*
//#UC END# *476BFC120188_48E0E5C1032Aget_var*
begin
//#UC START# *476BFC120188_48E0E5C1032Aget_impl*
Result := WebStyle;
//#UC END# *476BFC120188_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetIsWebStyle
function TnevControl.pm_GetShowDocumentParts: Boolean;
//#UC START# *476BFC2101FB_48E0E5C1032Aget_var*
//#UC END# *476BFC2101FB_48E0E5C1032Aget_var*
begin
//#UC START# *476BFC2101FB_48E0E5C1032Aget_impl*
Result := f_ShowDocumentParts;
//#UC END# *476BFC2101FB_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetShowDocumentParts
function TnevControl.pm_GetShowSpecial: Boolean;
//#UC START# *476BFC34010B_48E0E5C1032Aget_var*
//#UC END# *476BFC34010B_48E0E5C1032Aget_var*
begin
//#UC START# *476BFC34010B_48E0E5C1032Aget_impl*
Result := Canvas.DrawSpecial;
//#UC END# *476BFC34010B_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetShowSpecial
function TnevControl.pm_GetHiddenStyles: TnevStandardStyles;
//#UC START# *476BFC420000_48E0E5C1032Aget_var*
//#UC END# *476BFC420000_48E0E5C1032Aget_var*
begin
//#UC START# *476BFC420000_48E0E5C1032Aget_impl*
Result := f_HiddenStyles;
//#UC END# *476BFC420000_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetHiddenStyles
procedure TnevControl.InvalidateRect(const aRect: TnevRect);
{* сообщает контролу о необходимости перерисовки указанного прямоугольника, когда-нибудь в будущем. }
//#UC START# *47C5BD960201_48E0E5C1032A_var*
var
WE : TafwPoint;
R : Tl3Rect;
l_R : Tl3SRect;
//#UC END# *47C5BD960201_48E0E5C1032A_var*
begin
//#UC START# *47C5BD960201_48E0E5C1032A_impl*
if HandleAllocated then
begin
WE := pm_GetExtent;
R := Tl3Rect(aRect);
with Canvas do
begin
R.R.Left := evPixelZoom(Zoom, Max(R.R.Left, 0));
R.R.Right := evPixelZoom(Zoom, Min(R.R.Right, WE.P.X + DP2LP(PointX(pm_GetLMargin)).X));
R.R.Top := evPixelZoom(Zoom, Max(R.R.Top, 0));
R.R.Bottom := evPixelZoom(Zoom, Min(R.R.Bottom, WE.P.Y));
end;//with Canvas
l_R := GetInfoCanvas.LR2DR(R);
l_R.Invalidate(Handle, false);
end;//HandleAllocated
//#UC END# *47C5BD960201_48E0E5C1032A_impl*
end;//TnevControl.InvalidateRect
procedure TnevControl.SignalScroll(aDeltaY: Integer;
aNeedVert: Boolean);
{* сообщает контролу, о том, что изменилась позиция скроллера. }
//#UC START# *47C5BDB9011B_48E0E5C1032A_var*
//#UC END# *47C5BDB9011B_48E0E5C1032A_var*
begin
//#UC START# *47C5BDB9011B_48E0E5C1032A_impl*
DoSignalScroll(aDeltaY, aNeedVert);
//#UC END# *47C5BDB9011B_48E0E5C1032A_impl*
end;//TnevControl.SignalScroll
function TnevControl.GetDelphiControl: TComponent;
//#UC START# *47C5BDCD016E_48E0E5C1032A_var*
//#UC END# *47C5BDCD016E_48E0E5C1032A_var*
begin
//#UC START# *47C5BDCD016E_48E0E5C1032A_impl*
Result := Self;
//#UC END# *47C5BDCD016E_48E0E5C1032A_impl*
end;//TnevControl.GetDelphiControl
function TnevControl.CloseQuery: Boolean;
{* спрашивает контрол, о возможности закрытия окна, которому он принадлежит. }
//#UC START# *47C5BDD701CB_48E0E5C1032A_var*
//#UC END# *47C5BDD701CB_48E0E5C1032A_var*
begin
//#UC START# *47C5BDD701CB_48E0E5C1032A_impl*
Result := DoCloseQuery;
//#UC END# *47C5BDD701CB_48E0E5C1032A_impl*
end;//TnevControl.CloseQuery
function TnevControl.LP2DP(const aPoint: TnevPoint;
toScreen: Boolean = False): TPoint;
//#UC START# *47C5BFFB02EC_48E0E5C1032A_var*
var
l_l3P: Tl3Point;
l_l3Canv: Il3Canvas;
//#UC END# *47C5BFFB02EC_48E0E5C1032A_var*
begin
//#UC START# *47C5BFFB02EC_48E0E5C1032A_impl*
// Tl3SPoint(Result) := GetInfoCanvas.LP2DP(Tl3Point(aPoint)).Add(PointX(pm_GetLMargin)).Zoom(Canvas.Zoom);
l_l3P := Tl3Point(aPoint);
l_l3Canv := Il3Canvas(Canvas);
Tl3SPoint(Result) := GetInfoCanvas.LP2DP(l_l3P.Add(l_l3Canv.InitialDCOffsetStored)).Zoom(Canvas.Zoom);
if toScreen then
Result := ClientToScreen(Result);
//#UC END# *47C5BFFB02EC_48E0E5C1032A_impl*
end;//TnevControl.LP2DP
procedure TnevControl.CursorChanged;
//#UC START# *47C5C00E0398_48E0E5C1032A_var*
//#UC END# *47C5C00E0398_48E0E5C1032A_var*
begin
//#UC START# *47C5C00E0398_48E0E5C1032A_impl*
DoCursorChanged;
//#UC END# *47C5C00E0398_48E0E5C1032A_impl*
end;//TnevControl.CursorChanged
function TnevControl.CanScroll: Boolean;
//#UC START# *47C5C0190391_48E0E5C1032A_var*
//#UC END# *47C5C0190391_48E0E5C1032A_var*
begin
//#UC START# *47C5C0190391_48E0E5C1032A_impl*
Result := (f_InPaint <= 0) AND GetCanScroll;
//#UC END# *47C5C0190391_48E0E5C1032A_impl*
end;//TnevControl.CanScroll
procedure TnevControl.SetFlag(aFlag: TevUpdateWindowFlag);
{* установить флаг aFlag. }
//#UC START# *47C5C0260203_48E0E5C1032A_var*
//#UC END# *47C5C0260203_48E0E5C1032A_var*
begin
//#UC START# *47C5C0260203_48E0E5C1032A_impl*
DoSetFlag(aFlag);
//#UC END# *47C5C0260203_48E0E5C1032A_impl*
end;//TnevControl.SetFlag
procedure TnevControl.UpdateCaretAndInvalidate;
{* Проверить и переставить каретку + перерисоваться }
//#UC START# *47C5C0380010_48E0E5C1032A_var*
//#UC END# *47C5C0380010_48E0E5C1032A_var*
begin
//#UC START# *47C5C0380010_48E0E5C1032A_impl*
// Жесткая заточка для обхода такой проблемы
//ТБ с морфологией, дебагный КС
//1. Отрыть конституцию
//2. Встать кареткой в начало документа
//3. Поикать контекст "народ россии"
//4. Вернуться по Back в ОМ
//5. Открыть снова конституцию
//6. Поикать контекст "народ россии"
//
// При установке _FoundBlock получим, что в нелист ShapesPainted пытаемся записать
// InevMap и падаем по Assert в nevShapesPainted.TnevShape.wMap
// Пока вкрутил зачистку отрисованных. Как вернеться Шура надо будет поглядеть
// более системно
//ClearPaintedShapes;
// причины возврата искать здесь - http://mdp.garant.ru/pages/viewpage.action?pageId=86479075&focusedCommentId=86479242#comment-86479242
//
Perform(EM_ScrollCaret, 0, 0);
Invalidate;
Update;
//#UC END# *47C5C0380010_48E0E5C1032A_impl*
end;//TnevControl.UpdateCaretAndInvalidate
function TnevControl.pm_GetData: InevObject;
//#UC START# *47C5C04801EB_48E0E5C1032Aget_var*
//#UC END# *47C5C04801EB_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C04801EB_48E0E5C1032Aget_impl*
Result := GetData;
//#UC END# *47C5C04801EB_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetData
function TnevControl.Get_Processor: InevProcessor;
//#UC START# *47C5C0590083_48E0E5C1032Aget_var*
//#UC END# *47C5C0590083_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C0590083_48E0E5C1032Aget_impl*
Result := GetProcessor;
//#UC END# *47C5C0590083_48E0E5C1032Aget_impl*
end;//TnevControl.Get_Processor
function TnevControl.pm_GetWindowExtent: TnevSPoint;
//#UC START# *47C5C0950329_48E0E5C1032Aget_var*
//#UC END# *47C5C0950329_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C0950329_48E0E5C1032Aget_impl*
if HandleAllocated then
begin
with ClientRect do
Result := l3SPoint(Right - Left - pm_GetLMargin - RMargin, Bottom - Top);
end//HandleAllocated
else
Result := l3SPoint(Width - pm_GetLMargin - RMargin, Height);
if (f_Canvas <> nil) then
Tl3SPoint(Result).MakeDezoom(Canvas.Zoom);
//#UC END# *47C5C0950329_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetWindowExtent
function TnevControl.pm_GetMetrics: InevViewMetrics;
//#UC START# *47C5C11801AF_48E0E5C1032Aget_var*
//#UC END# *47C5C11801AF_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C11801AF_48E0E5C1032Aget_impl*
Result := Self;
//#UC END# *47C5C11801AF_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetMetrics
function TnevControl.pm_GetDrawCanvas: InevCanvas;
//#UC START# *47C5C1270314_48E0E5C1032Aget_var*
//#UC END# *47C5C1270314_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C1270314_48E0E5C1032Aget_impl*
if (f_InPaint > 0) then
Result := Canvas
else
Result := nil;
//#UC END# *47C5C1270314_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetDrawCanvas
function TnevControl.pm_GetMousePos: TnevPoint;
//#UC START# *47C5C13E0215_48E0E5C1032Aget_var*
var
l_Pt : Tl3SPoint;
//#UC END# *47C5C13E0215_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C13E0215_48E0E5C1032Aget_impl*
Result := GetMousePos(l_Pt);
//#UC END# *47C5C13E0215_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetMousePos
function TnevControl.pm_GetSelection: InevSelection;
//#UC START# *47C5C15B00FC_48E0E5C1032Aget_var*
//#UC END# *47C5C15B00FC_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C15B00FC_48E0E5C1032Aget_impl*
Result := GetSelection;
//#UC END# *47C5C15B00FC_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetSelection
function TnevControl.pm_GetCommandProcessor: InevCommandProcessor;
//#UC START# *47C5C1710096_48E0E5C1032Aget_var*
//#UC END# *47C5C1710096_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C1710096_48E0E5C1032Aget_impl*
Result := Controller.EntryCommands;
//#UC END# *47C5C1710096_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetCommandProcessor
function TnevControl.pm_GetLMargin: Integer;
//#UC START# *47C5C17E0206_48E0E5C1032Aget_var*
//#UC END# *47C5C17E0206_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C17E0206_48E0E5C1032Aget_impl*
Result := GetLMargin;
//#UC END# *47C5C17E0206_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetLMargin
function TnevControl.pm_GetAllowMultiSelect: Boolean;
//#UC START# *47C5C18B00B2_48E0E5C1032Aget_var*
//#UC END# *47C5C18B00B2_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C18B00B2_48E0E5C1032Aget_impl*
Result := GetAllowMultiSelect;
//#UC END# *47C5C18B00B2_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetAllowMultiSelect
function TnevControl.pm_GetViewArea: InevViewArea;
//#UC START# *47C5C19602BF_48E0E5C1032Aget_var*
//#UC END# *47C5C19602BF_48E0E5C1032Aget_var*
begin
//#UC START# *47C5C19602BF_48E0E5C1032Aget_impl*
Result := GetViewArea;
//#UC END# *47C5C19602BF_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetViewArea
function TnevControl.pm_GetView: InevInputView;
//#UC START# *47FC82400383_48E0E5C1032Aget_var*
//#UC END# *47FC82400383_48E0E5C1032Aget_var*
begin
//#UC START# *47FC82400383_48E0E5C1032Aget_impl*
Result := GetView;
//#UC END# *47FC82400383_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetView
function TnevControl.pm_GetExtent: TnevPoint;
//#UC START# *486D2C6702FA_48E0E5C1032Aget_var*
//#UC END# *486D2C6702FA_48E0E5C1032Aget_var*
begin
//#UC START# *486D2C6702FA_48E0E5C1032Aget_impl*
Result := GetInfoCanvas.DP2LP(pm_GetWindowExtent);
//#UC END# *486D2C6702FA_48E0E5C1032Aget_impl*
end;//TnevControl.pm_GetExtent
procedure TnevControl.ParaChanged;
{* Нотификация о смене текущего параграфа. }
//#UC START# *48E3672A03B2_48E0E5C1032A_var*
//#UC END# *48E3672A03B2_48E0E5C1032A_var*
begin
//#UC START# *48E3672A03B2_48E0E5C1032A_impl*
DoParaChange;
//#UC END# *48E3672A03B2_48E0E5C1032A_impl*
end;//TnevControl.ParaChanged
function TnevControl.Get_ActiveElement: InevActiveElement;
//#UC START# *4A27CEB10364_48E0E5C1032Aget_var*
//#UC END# *4A27CEB10364_48E0E5C1032Aget_var*
begin
//#UC START# *4A27CEB10364_48E0E5C1032Aget_impl*
Result := ActiveElementPrim;
//#UC END# *4A27CEB10364_48E0E5C1032Aget_impl*
end;//TnevControl.Get_ActiveElement
{$If NOT Defined(DesignTimeLibrary)}
procedure TnevControl.DoStyleTableChanged;
//#UC START# *4A485B710126_48E0E5C1032A_var*
//#UC END# *4A485B710126_48E0E5C1032A_var*
begin
//#UC START# *4A485B710126_48E0E5C1032A_impl*
//#UC END# *4A485B710126_48E0E5C1032A_impl*
end;//TnevControl.DoStyleTableChanged
{$IfEnd} // NOT Defined(DesignTimeLibrary)
function TnevControl.Get_ExcludeSuper: TevNormalSegLayerHandleSet;
//#UC START# *4AEAE49B024D_48E0E5C1032Aget_var*
//#UC END# *4AEAE49B024D_48E0E5C1032Aget_var*
begin
//#UC START# *4AEAE49B024D_48E0E5C1032Aget_impl*
Result := f_ExcludeSuper;
//#UC END# *4AEAE49B024D_48E0E5C1032Aget_impl*
end;//TnevControl.Get_ExcludeSuper
function TnevControl.Get_ForceDrawFocusRect: Boolean;
//#UC START# *4B59A96702D9_48E0E5C1032Aget_var*
//#UC END# *4B59A96702D9_48E0E5C1032Aget_var*
begin
//#UC START# *4B59A96702D9_48E0E5C1032Aget_impl*
Result := ForceDrawFocusRectPrim;
//#UC END# *4B59A96702D9_48E0E5C1032Aget_impl*
end;//TnevControl.Get_ForceDrawFocusRect
function TnevControl.Get_FormatCanvas: InevInfoCanvas;
//#UC START# *4B7E744702C0_48E0E5C1032Aget_var*
//#UC END# *4B7E744702C0_48E0E5C1032Aget_var*
begin
//#UC START# *4B7E744702C0_48E0E5C1032Aget_impl*
Assert(false);
Result := GetInfoCanvas;
//#UC END# *4B7E744702C0_48E0E5C1032Aget_impl*
end;//TnevControl.Get_FormatCanvas
procedure TnevControl.ForceRepaint;
{* По жёсткому перерисовать сожержимое контрола (прямо внутри операции редактирования). Нужно для http://mdp.garant.ru/pages/viewpage.action?pageId=204113269 }
//#UC START# *4BCC30EC0284_48E0E5C1032A_var*
//#UC END# *4BCC30EC0284_48E0E5C1032A_var*
begin
//#UC START# *4BCC30EC0284_48E0E5C1032A_impl*
DoForceRepaint;
//#UC END# *4BCC30EC0284_48E0E5C1032A_impl*
end;//TnevControl.ForceRepaint
function TnevControl.Get_AllowRubberTables: TnevRubberTablesMode;
//#UC START# *4BED6E9300FD_48E0E5C1032Aget_var*
//#UC END# *4BED6E9300FD_48E0E5C1032Aget_var*
begin
//#UC START# *4BED6E9300FD_48E0E5C1032Aget_impl*
Result := AllowRubberTables;
//#UC END# *4BED6E9300FD_48E0E5C1032Aget_impl*
end;//TnevControl.Get_AllowRubberTables
function TnevControl.IsTagCollapsed(aTag: Tl3Variant): Boolean;
//#UC START# *4D5A80DC029D_48E0E5C1032A_var*
//#UC END# *4D5A80DC029D_48E0E5C1032A_var*
begin
//#UC START# *4D5A80DC029D_48E0E5C1032A_impl*
if (GetView = nil) then
Result := false
else
Result := GetView.Metrics.IsTagCollapsed(aTag);
//#UC END# *4D5A80DC029D_48E0E5C1032A_impl*
end;//TnevControl.IsTagCollapsed
function TnevControl.Get_Data: InevObjectPrim;
//#UC START# *4E5E285C0166_48E0E5C1032Aget_var*
//#UC END# *4E5E285C0166_48E0E5C1032Aget_var*
begin
//#UC START# *4E5E285C0166_48E0E5C1032Aget_impl*
Result := GetData;
//#UC END# *4E5E285C0166_48E0E5C1032Aget_impl*
end;//TnevControl.Get_Data
function TnevControl.AllowsThisDecor(aFI: TnevFormatInfoPrim;
aType: TnevDecorType): Boolean;
{* Разрешает ли контейтер документа применять указанное декорирование }
//#UC START# *4F33E2A30116_48E0E5C1032A_var*
//#UC END# *4F33E2A30116_48E0E5C1032A_var*
begin
//#UC START# *4F33E2A30116_48E0E5C1032A_impl*
Result := true;
//#UC END# *4F33E2A30116_48E0E5C1032A_impl*
end;//TnevControl.AllowsThisDecor
function TnevControl.InClose: Boolean;
{* Редактор в процессе закрытия. }
//#UC START# *4F3CE6140329_48E0E5C1032A_var*
//#UC END# *4F3CE6140329_48E0E5C1032A_var*
begin
//#UC START# *4F3CE6140329_48E0E5C1032A_impl*
Result := GetInClose;
//#UC END# *4F3CE6140329_48E0E5C1032A_impl*
end;//TnevControl.InClose
function TnevControl.Get_AACLike: TnevAACLikeMode;
//#UC START# *501F96A80050_48E0E5C1032Aget_var*
//#UC END# *501F96A80050_48E0E5C1032Aget_var*
begin
//#UC START# *501F96A80050_48E0E5C1032Aget_impl*
Result := f_AACLike{nev_aacLeft};
//#UC END# *501F96A80050_48E0E5C1032Aget_impl*
end;//TnevControl.Get_AACLike
function TnevControl.NeedTotalRecalc: Boolean;
//#UC START# *565F03C80029_48E0E5C1032A_var*
//#UC END# *565F03C80029_48E0E5C1032A_var*
begin
//#UC START# *565F03C80029_48E0E5C1032A_impl*
Result := false;
//#UC END# *565F03C80029_48E0E5C1032A_impl*
end;//TnevControl.NeedTotalRecalc
initialization
{$If NOT Defined(NoScripts)}
TtfwClassRef.Register(TnevControl);
{* Регистрация TnevControl }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit tmvInterfaces;
interface
uses
SysUtils,
Classes,
l3Interfaces
;
type
TtmvRecordKind = (
rkNewRareWord,
rkHumanMistake,
rkScanerMistake,
rkUnknownMistake,
rkWrongText,
rkNewRegularWord,
rkVariant,
rkAbbreviation
);
type
ItmvRecord = interface(IUnknown)
['{A019B551-9D8A-4800-9E7E-C9DED38B6FDC}']
function pm_GetCaption: Il3CString;
{-}
function pm_GetFrequency: Il3CString;
{-}
function pm_GetMistakeKind: TtmvRecordKind;
procedure pm_SetMistakeKind(aValue: TtmvRecordKind);
{-}
function pm_GetInfo: String;
procedure pm_SetInfo(const aValue: String);
{-}
function pm_GetContext: Il3CString;
{-}
function pm_GetModified: Boolean;
{-}
function pm_CanWriteInfo: Boolean;
{-}
property Caption: Il3CString
read pm_getCaption;
{-}
property Frequency: Il3CString
read pm_getFrequency;
{-}
property MistakeKind: TtmvRecordKind
read pm_GetMistakeKind
write pm_SetMistakeKind;
{-}
property Context: Il3CString
read pm_GetContext;
{-}
property Modified: Boolean
read pm_GetModified;
{-}
property Info: String
read pm_GetInfo
write pm_SetInfo;
property CanWriteInfo: Boolean
read pm_CanWriteInfo;
{-}
end;//ItmvRecord
ItmvRecordOffsets = interface(IUnknown)
['{D30C4EA1-DBBF-41CE-823A-98C2DE04CF3D}']
function pm_GetStartOffset: Int64;
{-}
function pm_GetEndOffset: Int64;
{-}
property StartOffset: Int64
read pm_GetStartOffset;
{-}
property EndOffset: Int64
read pm_GetEndOffset;
{-}
end;//ItmvRecordOffsets
ItmvRecordInfo = interface(ItmvRecordOffsets)
['{4E43F62E-8022-4665-96B2-A8227218AB40}']
function pm_GetRecordIndex: Cardinal;
{-}
procedure SaveData(const aStream: TStream);
{-}
property RecordIndex: Cardinal
read pm_GetRecordIndex;
{-}
end;//ItmvRecordInfo
ItmvController = interface(IUnknown)
['{0CE51DB7-D5CC-4958-81F5-E51C05B27297}']
function pm_GetCurrent: ItmvRecord;
{-}
function pm_GetProgressCaption: Il3CString;
{-}
procedure Prev;
{-}
procedure Next;
{-}
function CanPrev: Boolean;
{-}
function CanNext: Boolean;
{-}
property Current: ItmvRecord
read pm_GetCurrent;
{-}
property ProgressCaption: Il3CString
read pm_GetProgressCaption;
end;//ItmvController
EtvmEndOfFile = class(Exception);
EtvmInvalidFileFormat = class(Exception);
const
c_tvmCodePage = CP_OEM;
c_tvmMaxInfoLength = 40;
implementation
end.
|
unit ADC.ImgProcessor;
interface
uses
System.Classes, System.Types, Winapi.Windows, Vcl.Graphics, Vcl.Imaging.jpeg,
Vcl.Controls, System.SysUtils, System.Variants, Winapi.UxTheme, Winapi.ActiveX,
Vcl.Imaging.pngimage, System.RegularExpressions, System.StrUtils, ADC.Types;
type
TImgProcessor = class(TObject)
private
type
TRGB = record
B : Byte;
G : Byte;
R : Byte;
end;
type
PRGBArray = ^TRGBArray;
TRGBArray = array[0..32767] of TRGB;
private
class procedure BitmapShrink(Src, Dst: TBitmap);
public
class procedure SmoothResize(Src, Dst: TBitmap);
class procedure OpenImage_JPEG(AFileName: string; AJpeg: TJPEGImage);
class function ImageToByteArray(AJPEG: TJPEGImage; outByteArray: PImgByteArray): Boolean; overload;
class function ImageToByteArray(ABitmap: TBitmap; outByteArray: PImgByteArray): Boolean; overload;
class function ByteArrayToImage(ABytes: TImgByteArray; outBitmap: TBitmap): Boolean; overload;
class function ByteArrayToImage(ABytes: OleVariant; outBitmap: TBitmap): Boolean; overload;
class function ByteArrayToImage(ABytes: PSafeArray; outBitmap: TBitmap): Boolean; overload;
class function ByteArrayToImage(ABytes: WideString; outBitmap: TBitmap): Boolean; overload;
class procedure GetThemeButtons(AHWND: HWND; AHDC: HDC; APartID: Integer;
ABgColor: TColor; AImgList: TImageList);
end;
implementation
{ TImgProcessor }
class procedure TImgProcessor.BitmapShrink(Src, Dst: TBitmap);
var
Lx, Ly, LxS, LyS, LyB, LxB, LySend, LxSend, R : integer;
P1, P2, P3, P4, P5, P6, P7, P8, P9, POut : pByte;
PA, PB, PC, PD, PE, PF, PG : pByte;
LSumR, LSumG, LSumB, LBoxPixels : integer;
W, WM, HM, WL : integer;
LRowSkip, LRowSkipOut, LRowSize, LRowSkipBox, LBoxSize : integer;
begin
W := Dst.Width;
R := Src.Width div W; // shrink ratio
WM := W - 1; HM := Dst.Height - 1;
WL := W - 3;
P1 := Src.ScanLine[0];
LRowSize := -(((Src.Width * 24 + 31) and not 31) shr 3);
P2 := PByte(Integer(P1) + LRowSize);
POut := Dst.ScanLine[0];
LRowSkipOut := -(((W * 24 + 31) and not 31) shr 3) - W * 3;
if R = 2 then
begin
LRowSkip := LRowSize shl 1 - W * 6;
for Ly := 0 to HM do
begin
P3 := PByte(Integer(P1) + 3);
P4 := PByte(Integer(P2) + 3);
Lx := 0;
// set output pixel to the average of the 2X2 box of input pixels
while Lx < WL do
begin // loop unrolled by 4
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // blue
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // green
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // red
Inc(P1, 4); Inc(P2, 4); Inc(P3, 4); Inc(P4, 4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // blue
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // green
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // red
Inc(P1, 4); Inc(P2, 4); Inc(P3, 4); Inc(P4, 4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // blue
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // green
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // red
Inc(P1, 4); Inc(P2, 4); Inc(P3, 4); Inc(P4, 4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // blue
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // green
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // red
Inc(P1, 4); Inc(P2, 4); Inc(P3, 4); Inc(P4, 4); Inc(POut);
Inc(Lx, 4);
end;
while Lx < W do
begin
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // blue
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // green
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^) shr 2; // red
Inc(P1, 4); Inc(P2, 4); Inc(P3, 4); Inc(P4, 4); Inc(POut);
Inc(Lx);
end;
Inc(POut, LRowSkipOut);
Inc(P1, LRowSkip); Inc(P2, LRowSkip);
end;
end else if R = 3 then
begin
LRowSkip := LRowSize * 3 - W * 9;
P3 := PByte(Integer(P2) + LRowSize);
for Ly := 0 to HM do
begin
P4 := PByte(Integer(P1) + 3);
P5 := PByte(Integer(P2) + 3);
P6 := PByte(Integer(P3) + 3);
P7 := PByte(Integer(P4) + 3);
P8 := PByte(Integer(P5) + 3);
// Integer(P9) := Integer(P6) + 3;
for Lx := 0 to WM do
begin
// set output pixel to the average of the 3X3 box of input pixels
POut^ := (P1^ + P2^ + P3^ + P4^ + P5^ + P6^ + P7^ + P8^{ + P9^}) shr 3;
Inc(P1); Inc(P2); Inc(P3); Inc(P4); Inc(P5); Inc(P6); Inc(P7); Inc(P8); {Inc(P9);}
Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^ + P5^ + P6^ + P7^ + P8^ {+ P9^}) shr 3;
Inc(P1);Inc(P2);Inc(P3);Inc(P4);Inc(P5);Inc(P6);Inc(P7);Inc(P8);{Inc(P9);}
Inc(POut);
POut^ := (P1^ + P2^ + P3^ + P4^ + P5^ + P6^ + P7^ + P8^ {+ P9^}) shr 3;
Inc(P1, 7); Inc(P2, 7); Inc(P3, 7); Inc(P4, 7); Inc(P5, 7); Inc(P6, 7); Inc(P7, 7); Inc(P8, 7); {Inc(P9, 7)}
Inc(POut);
end;
Inc(POut, LRowSkipOut);
Inc(P1, LRowSkip); Inc(P2, LRowSkip); Inc(P3, LRowSkip);
end;
end else if R = 4 then
begin
LRowSkip := LRowSize shl 2 - W * 12;
P3 := PByte(Integer(P2) + LRowSize);
P4 := PByte(Integer(P3) + LRowSize);
for Ly := 0 to HM do
begin
P5 := PByte(Integer(P1) + 3); P6 := PByte(Integer(P2) + 3);
P7 := PByte(Integer(P3) + 3); P8 := PByte(Integer(P4) + 3);
P9 := PByte(Integer(P5) + 3); PA := PByte(Integer(P6) + 3);
PB := PByte(Integer(P7) + 3); PC := PByte(Integer(P8) + 3);
PD := PByte(Integer(P9) + 3); PE := PByte(Integer(PA) + 3);
PF := PByte(Integer(PB) + 3); PG := PByte(Integer(PC) + 3);
for Lx := 0 to WM do
begin
// set output pixel to the average of the 4X4 box of input pixels
POut^ := (P1^+P2^+P3^+P4^+P5^+P6^+P7^+P8^+P9^+PA^+PB^+PC^+PD^+PE^+PF^+PG^) shr 4;
Inc(P1);Inc(P2);Inc(P3);Inc(P4);Inc(P5);Inc(P6);Inc(P7);Inc(P8);
Inc(P9);Inc(PA);Inc(PB);Inc(PC);Inc(PD);Inc(PE);Inc(PF);Inc(PG);
Inc(POut);
POut^ := (P1^+P2^+P3^+P4^+P5^+P6^+P7^+P8^+P9^+PA^+PB^+PC^+PD^+PE^+PF^+PG^) shr 4;
Inc(P1);Inc(P2);Inc(P3);Inc(P4);Inc(P5);Inc(P6);Inc(P7);Inc(P8);
Inc(P9);Inc(PA);Inc(PB);Inc(PC);Inc(PD);Inc(PE);Inc(PF);Inc(PG);
Inc(POut);
POut^ := (P1^+P2^+P3^+P4^+P5^+P6^+P7^+P8^+P9^+PA^+PB^+PC^+PD^+PE^+PF^+PG^) shr 4;
Inc(P1,10);Inc(P2,10);Inc(P3,10);Inc(P4,10);Inc(P5,10);Inc(P6,10);Inc(P7,10);Inc(P8,10);
Inc(P9,10);Inc(PA,10);Inc(PB,10);Inc(PC,10);Inc(PD,10);Inc(PE,10);Inc(PF,10);Inc(PG,10);
Inc(POut);
end;
Inc(POut, LRowSkipOut);
Inc(P1, LRowSkip); Inc(P2, LRowSkip); Inc(P3, LRowSkip); Inc(P4, LRowSkip);
end;
end else
begin // shrink by any ratio > 4
LBoxPixels := R * R;
LBoxSize := R * 3;
LRowSkipBox := LRowSize - LBoxSize;
LRowSkip := LRowSize * R - R * W * 3;
LyS := 0;
for Ly := 0 to HM do
begin
LySend := LyS + R - 1;
LxS := 0;
for Lx := 0 to WM do
begin
LxSend := LxS + R - 1;
LSumR := 0; LSumG := 0; LSumB := 0;
P2 := P1; // P1 points to the top left corner of the box
// loop through super-sampling box of pixels in input bitmap and sum them
for LyB := LyS to LySend do
begin
for LxB := LxS to LxSend do
begin
Inc(LSumB, P2^); Inc(P2);
Inc(LSumG, P2^); Inc(P2);
Inc(LSumR, P2^); Inc(P2);
end;
Inc(P2, LRowSkipBox);
end;
Inc(P1, LBoxSize);
// set output bitmap pixel to the average of the pixels in the box
POut^ := LSumB div LBoxPixels;
Inc(POut);
POut^ := LSumG div LBoxPixels;
Inc(POut);
POut^ := LSumR div LBoxPixels;
Inc(POut);
Inc(LxS, R);
end;
Inc(P1, LRowSkip);
Inc(POut, LRowSkipOut);
Inc(LyS, R);
end;
end;
end;
class procedure TImgProcessor.OpenImage_JPEG(AFileName: string;
AJpeg: TJPEGImage);
var
SourceImg: TBitmap;
ResizedImg: TBitmap;
ThumbRect: TRect;
begin
if AJpeg = nil then Exit;
AJpeg.LoadFromFile(AFileName);
if (AJpeg.Width > USER_IMAGE_MAX_WIDTH) or ((AJpeg.Height > USER_IMAGE_MAX_HEIGHT)) then
begin
SourceImg := TBitmap.Create;
try
SourceImg.Assign(AJpeg);
ResizedImg := TBitmap.Create;
try
ThumbRect.Left := 0;
ThumbRect.Top := 0;
if SourceImg.Width > SourceImg.Height then
begin
ThumbRect.Right := USER_IMAGE_MAX_WIDTH;
ThumbRect.Bottom := (USER_IMAGE_MAX_WIDTH * SourceImg.Height) div SourceImg.Width;
end else
begin
ThumbRect.Bottom := USER_IMAGE_MAX_HEIGHT;
ThumbRect.Right := (USER_IMAGE_MAX_HEIGHT * SourceImg.Width) div SourceImg.Height;
end;
ResizedImg.Width := ThumbRect.Right;
ResizedImg.Height := ThumbRect.Bottom;
SmoothResize(SourceImg, ResizedImg);
AJpeg.Assign(ResizedImg);
finally
ResizedImg.Free;
end;
finally
SourceImg.Free;
end;
end;
end;
class function TImgProcessor.ByteArrayToImage(ABytes: TImgByteArray;
outBitmap: TBitmap): Boolean;
var
MemStream: TMemoryStream;
JPEGImage: TJPEGImage;
begin
Result := False;
if Length(ABytes) = 0
then Exit;
MemStream := TMemoryStream.Create;
JPEGImage := TJPEGImage.Create;
try
MemStream.Size := Length(ABytes);
MemStream.Write(ABytes[0], MemStream.Size);
MemStream.Seek(0, soFromBeginning);
JPEGImage.CompressionQuality := 100;
JPEGImage.Smoothing := True;
JPEGImage.LoadFromStream(MemStream);
if JPEGImage <> nil
then outBitmap.Assign(JPEGImage);
Result := True;
finally
JPEGImage.Free;
MemStream.Free;
end;
end;
class function TImgProcessor.ByteArrayToImage(ABytes: OleVariant;
outBitmap: TBitmap): Boolean;
var
PImageData: Pointer;
MemStream: TMemoryStream;
JPEGImage: TJPEGImage;
begin
Result := False;
if not VarIsArray(ABytes)
then Exit;
MemStream := TMemoryStream.Create;
JPEGImage := TJPEGImage.Create;
try
MemStream.Size := VarArrayHighBound(ABytes, 1) - VarArrayLowBound(ABytes, 1) + 1;
PImageData := VarArrayLock(ABytes);
MemStream.Write(PImageData^, MemStream.Size);
VarArrayUnlock(ABytes);
MemStream.Seek(0, soFromBeginning);
JPEGImage.CompressionQuality := 100;
JPEGImage.Smoothing := True;
JPEGImage.LoadFromStream(MemStream);
if JPEGImage <> nil then outBitmap.Assign(JPEGImage);
Result := True;
finally
JPEGImage.Free;
MemStream.Free;
end;
end;
class function TImgProcessor.ByteArrayToImage(ABytes: PSafeArray;
outBitmap: TBitmap): Boolean;
var
bytes: PSafeArray;
LBound, HBound : Integer;
ImgBytes: TImgByteArray;
i: Integer;
ib: Byte;
png: TPngImage;
jpg: TJPEGImage;
stream: TMemoryStream;
begin
bytes := ABytes;
SafeArrayGetLBound(bytes, 1, LBound);
SafeArrayGetUBound(bytes, 1, HBound);
SetLength(ImgBytes, HBound + 1);
for i := LBound to HBound do
begin
SafeArrayGetElement(bytes, i, ib);
ImgBytes[i] := ib;
end;
SafeArrayDestroy(bytes);
png := TPngImage.Create;
jpg := TJPEGImage.Create;
try
stream := TMemoryStream.create;
try
stream.Write(ImgBytes[0], Length(ImgBytes));
stream.Position:= 0;
// if ContainsText(ucmaContact.PhotoHex, '89-50-4E-47-0D-0A-1A-0A') then
// begin
// png.LoadFromStream(stream);
// Image1.Picture.Bitmap.Assign(png);
// end else if ContainsText(ucmaContact.PhotoHex, 'FF-D8-FF') then
begin
jpg.LoadFromStream(stream);
outBitmap.Assign(jpg);
end;
finally
stream.Free;
end;
finally
png.Free;
jpg.Free;
end;
end;
class procedure TImgProcessor.GetThemeButtons(AHWND: HWND; AHDC: HDC; APartID: Integer;
ABgColor: TColor; AImgList: TImageList);
const
_SIZE = 16;
var
B: TBitmap;
hT: HTHEME;
S: TSize;
R: TRect;
begin
if AImgList = nil then Exit;
AImgList.Clear;
B := TBitmap.Create;
try
B.SetSize(_SIZE, _SIZE);
B.Canvas.Brush.Style := bsClear;
B.Canvas.Brush.Color := ABgColor;
R := B.Canvas.ClipRect;
hT := OpenThemeData(AHWND, 'BUTTON');
if hT <> 0 then
begin
GetThemePartSize(
hT,
AHDC,
APartID,
CBS_CHECKEDNORMAL,
@R,
TS_DRAW,
S
);
R.Offset(
Trunc((_SIZE - S.cx) / 2),
Trunc((_SIZE - S.cy) / 2)
);
{ 1 }
B.Canvas.FillRect(B.Canvas.ClipRect);
DrawThemeBackground(
hT,
B.Canvas.Handle,
APartID,
CBS_UNCHECKEDNORMAL,
R,
nil
);
AImgList.Add(B, nil);
{ 2 }
B.Canvas.FillRect(B.Canvas.ClipRect);
DrawThemeBackground(
hT,
B.Canvas.Handle,
APartID,
CBS_CHECKEDNORMAL,
R,
nil
);
AImgList.Add(B, nil);
{ 3 }
B.Canvas.FillRect(B.Canvas.ClipRect);
DrawThemeBackground(
hT,
B.Canvas.Handle,
APartID,
CBS_UNCHECKEDDISABLED,
R,
nil
);
AImgList.Add(B, nil);
{ 4 }
B.Canvas.FillRect(B.Canvas.ClipRect);
DrawThemeBackground(
hT,
B.Canvas.Handle,
APartID,
CBS_CHECKEDDISABLED,
R,
nil
);
AImgList.Add(B, nil);
end;
finally
B.Free;
CloseThemeData(hT);
end;
end;
class function TImgProcessor.ImageToByteArray(AJPEG: TJPEGImage; outByteArray: PImgByteArray): Boolean;
var
b: TBitmap;
begin
b := TBitmap.Create;
try
b.Assign(AJPEG);
Result := ImageToByteArray(b, outByteArray);
finally
b.Free;
end;
end;
class function TImgProcessor.ImageToByteArray(ABitmap: TBitmap;
outByteArray: PImgByteArray): Boolean;
var
Stream: TMemoryStream;
JPEGImg: TJPEGImage;
begin
Result := False;
if outByteArray = nil
then Exit;
Stream := TMemoryStream.Create;
JPEGImg := TJPEGImage.Create;
try
JPEGImg.Smoothing := True;
JPEGImg.CompressionQuality := 100;
JPEGImg.Assign(ABitmap);
JPEGImg.SaveToStream(Stream);
Stream.Seek(0, soFromBeginning);
SetLength(outByteArray^, Stream.size);
Stream.ReadBuffer(outByteArray^[0], Length(outByteArray^));
Result := True;
finally
Stream.Free;
JPEGImg.Free;
end;
end;
class procedure TImgProcessor.SmoothResize(Src, Dst: TBitmap);
var
Lx, Ly : integer;
LyBox, LxBox, LyBox1, LyBox2, LxBox1, LxBox2 : integer;
TR, TG, TB : integer;
LRowIn, LRowOut, LRowInStart : pRGBArray;
LBoxCount : integer;
LRowBytes, LRowBytesIn : integer;
LBoxRows : array of pRGBArray;
LRatioW, LRatioH : Real;
begin
Src.PixelFormat := pf24bit;
Dst.PixelFormat := pf24bit;
LRatioH := Src.Height / Dst.Height;
LRatioW := Src.Width / Dst.Width;
if (Frac(LRatioW) = 0) and (Frac(LRatioH) = 0) then
begin
BitmapShrink(Src, Dst);
Exit;
end;
SetLength(LBoxRows, trunc(LRatioW) + 1);
LRowOut := Dst.ScanLine[0];
LRowBytes := -(((Dst.Width * 24 + 31) and not 31) shr 3);
LRowBytesIn := -(((Src.Width * 24 + 31) and not 31) shr 3);
LRowInStart := Src.ScanLine[0];
for Ly := 0 to Dst.Height-1 do
begin
LyBox1 := trunc(Ly * LRatioH);
LyBox2 := trunc((Ly+1) * LRatioH) - 1;
for LyBox := LyBox1 to LyBox2 do
LBoxRows[LyBox - LyBox1] := pRGBArray(Integer(LRowInStart) + LyBox * LRowBytesIn);
for Lx := 0 to Dst.Width-1 do
begin
LxBox1 := trunc(Lx * LRatioW);
LxBox2 := trunc((Lx + 1) * LRatioW) - 1;
TR := 0; TG := 0; TB := 0;
LBoxCount := 0;
for LyBox := LyBox1 to LyBox2 do
begin
LRowIn := LBoxRows[LyBox - LyBox1];
for LxBox := LxBox1 to LxBox2 do
begin
Inc(TB, LRowIn[LxBox].B);
Inc(TG, LRowIn[LxBox].G);
Inc(TR, LRowIn[LxBox].R);
Inc(LBoxCount);
end;
end;
LRowOut[Lx].B := TB div LBoxCount;
LRowOut[Lx].G := TG div LBoxCount;
LRowOut[Lx].R := TR div LBoxCount;
end;
LRowOut := pRGBArray(Integer(LRowOut) + LRowBytes);
end;
end;
class function TImgProcessor.ByteArrayToImage(ABytes: WideString;
outBitmap: TBitmap): Boolean;
var
regEx: TRegEx;
bStr: WideString;
bArr: TBytes;
i: Integer;
begin
regEx := TRegEx.Create('[^0-9A-F]');
bStr := LowerCase(regEx.Replace(ABytes, ''));
SetLength(bArr, Length(bStr) div 2);
if Length(bArr) > 0 then
begin
HexToBin(PChar(bStr), bArr, Length(bArr));
TImgProcessor.ByteArrayToImage(bArr, outBitmap);
end;
end;
end.
|
unit uAppContext;
{$mode objfpc}{$H+}
interface
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uMainDataModule, CustApp, uConsoleOutput, uIndexPath, uIndexMenu;
type
{ TUpdateDb }
TUpdateDb = class(TCustomApplication)
private
FAvfs: string;
FDebug: boolean;
FGit: string;
FTag: string;
FCmd: string;
FVerbose: boolean;
FPriority: integer;
FLog: TLogger;
FInclude: string;
FExclude: string;
function GetOptionValueDef(const aShort: char; const aLong, aDefault: string): string;
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
property Debug: boolean read FDebug;
property Verbose: boolean read FVerbose;
property Git: string read FGit;
property Avfs: string read FAvfs;
property Tag: string read FTag;
property Cmd: string read FCmd;
Property include: string Read FInclude;
Property exclude: String Read FExclude;
property Priority: integer read FPriority;
property Log: TLogger read FLog;
end;
var
App: TUpdateDb; // application context
implementation
uses uIndexCmd;
{ TUpdateDb }
function TUpdateDb.GetOptionValueDef(const aShort: char; const aLong, aDefault: string): string;
begin
if (aShort <> '_') and HasOption(aShort, aLong) then
Result := GetOptionValue(aShort, aLong)
else if (aShort = '_') and HasOption(aLong) then
Result := GetOptionValue(aShort, aLong)
else
Result := aDefault;
end;
procedure TUpdateDb.DoRun;
//Var
//ErrorMsg: String;
var
lPaths, lList: TStringList;
lLineIn: String;
i: integer;
lOptPath, lOptList, s: string;
lCnt: longint;
lStartTime: TDateTime;
lListPath: string;
tfIn: TextFile;
begin
lCnt := 0;
// quick check parameters
//ErrorMsg := CheckOptions('h', 'help');
//If ErrorMsg <> '' Then Begin
// ShowException(Exception.Create(ErrorMsg));
// Terminate;
// Exit;
//End;
// parse parameters
if HasOption('h', 'help') then
begin
WriteHelp;
Terminate;
Exit;
end;
// set application properties
FTag := GetOptionValueDef('t', 'tag', '');
FPriority := StrToInt(GetOptionValueDef('i', 'priority', '50'));
FGit := GetOptionValueDef('_', 'git', '');
FAvfs := GetOptionValueDef('_', 'avfs', '');
FVerbose := HasOption('v', 'verbose');
FDebug := HasOption('d', 'debug');
FCmd := GetOptionValueDef('c', 'cmd-open', 'xdg-open');
FLog := TLogger.Create(FDebug, FVerbose);
lStartTime := now;
// include/exclude
FExclude := GetOptionValueDef('x', 'exclude', '');
FInclude := GetOptionValueDef('_', 'include', '');
App.Log.Debug('Cmd: ' + FCmd);
App.Log.Debug('Exclude: ' + FExclude);
App.Log.Debug('Include: ' + FInclude);
DM.DBPath := GetOptionValueDef('l', 'localdb', IncludeTrailingPathDelimiter(GetUserDir) + '.mlocate.db');
Log.Info('use DB: ' + DM.DBPath);
{TODO -oLebeda -cNone: delete-tag}
{TODO -oLebeda -cNone: delete-path}
{TODO -oLebeda -cNone: source}
if HasOption('_', 'source') then
begin
readln(lLineIn);
// insertCmd(const aPath, aName, aCommand: string; const aAnnex:Boolean; const aDescription: string = '');
writeln(lLineIn);
End;
// list from txt
if HasOption('_', 'list') then
begin
lList := TStringList.Create();
try
lList.Delimiter := ':';
lOptList := GetOptionValue('_', 'list');
lList.DelimitedText := lOptList;
for i := 0 to lList.Count - 1 do
begin
App.Log.Info('indexing from list: ' + lList[i]);
lListPath := ExtractFileDir(lList[i]);
markPathAsTrash(lListPath);
// Index line by line
AssignFile(tfIn, lList[i]);
try
reset(tfIn);
while not eof(tfIn) do
begin
readln(tfIn, s);
insertFile(IncludeTrailingPathDelimiter(lListPath) + s, false); // for this method is annex unsupported
Inc(lCnt);
end;
CloseFile(tfIn);
except
on E: EInOutError do
App.Log.Err('File handling error occurred. Details: ' + E.Message);
end;
DM.SQLite3Connection1.Transaction.Commit;
end;
finally
lList.Free;
end;
End;
{TODO -oLebeda -cNone: stddin}
if HasOption('_', 'sdtdin') then
begin
readln(lLineIn);
writeln(lLineIn);
End;
if HasOption('p', 'path') then
begin
lPaths := TStringList.Create();
try
lPaths.Delimiter := ':';
lOptPath := GetOptionValue('p', 'path');
lPaths.DelimitedText := lOptPath;
for i := 0 to lPaths.Count - 1 do
begin
Log.Info('indexing path: ' + lPaths[i]);
markPathAsTrash(lPaths[i]);
lCnt := lCnt + IndexPath(lPaths[i], false);
DM.SQLite3Connection1.Transaction.Commit;
end;
finally
lPaths.Free;
end;
end;
if HasOption('m', 'menu') then
begin
lPaths := TStringList.Create();
try
lPaths.Delimiter := ':';
lOptPath := GetOptionValue('m', 'menu');
lPaths.DelimitedText := lOptPath;
for i := 0 to lPaths.Count - 1 do
begin
Log.Info('indexing menu: ' + lPaths[i]);
{TODO -oLebeda -cNone: pokud path začíná # nepoužít při spuštění}
markPathAsTrash('#' + lPaths[i] + '#');
lCnt := lCnt + IndexMenu(lPaths[i]);
DM.SQLite3Connection1.Transaction.Commit;
end;
finally
lPaths.Free;
end;
end;
//cli._(longOpt: 'noreindex', 'ignore fulltext reindexation (for use in batch update)')
if HasOption('noreindex') then
begin
Log.Info('Refresh of indexation was skipped, only clean trash.');
clearTrash;
End
else
begin
Log.Info('Refreshing fulltext index and maitaining database');
clearTrash;
refreshFtIndex;
end;
Log.Info('done: ' + IntToStr(lCnt) + ' items in ' + TimeToStr(now - lStartTime));
// stop program loop
Terminate;
end;
constructor TUpdateDb.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException := True;
end;
destructor TUpdateDb.Destroy;
begin
DM.Free;
FLog.Free;
inherited Destroy;
end;
procedure TUpdateDb.WriteHelp;
begin
writeln('Usage: ', ExeName);
writeln(' -h --help show this help');
writeln(' -l --localdb path to database file, default: $HOME/.mlocate.db');
writeln(' -c --cmd=XX command for open scanned entries, default: xdg-open');
writeln(' --priority=X priority for scanned entries in results, default: 50');
writeln(' --git=X if directory contain .git use "git ls-files" instead recursive direct listing, this is external command git');
writeln(' --avfs=X path to avfs mount');
writeln(' -v --verbose verbose output');
writeln(' -d --debug more verbose output');
writeln(' -t --tag tag');
writeln(' -x --exclude exclude from search (files and directories), use ":" as separator');
writeln(' --include include to search (only files), use ":" as separator');
writeln(' --noreindex no vacuum database (quicker indexation)');
writeln(' --list=XX:YY list from index file (file contain relative path listing)');
writeln(' -p --path list of paths for indexation, use ":" as separator');
writeln(' -m --menu list of commands from menu file (icewm syntax supported) for indexation, use ":" as separator');
end;
end.
|
{=======================================================================================================================
RkDBAddress_Frame Unit
RK Components - Component Source Unit
Components Description
----------------------------------------------------------------------------------------------------------------------
TRzDBAddress_Frame This TRkDBAddress_Frame component is comprised of the following edit fields: First Name,
Last Name, Street, City, and ZIP. The State field is actually a combo box which is populated
with the 50 states including the District of Columbia. The edit fields are data-aware, and
thus this component can be hooked up to a DataSource.
Note: This example illustrates how to build a Frame Component.
Copyright © 1999-2003 by Ray Konopka. All Rights Reserved.
=======================================================================================================================}
//{$I RkComps.inc}
unit RkDBAddress_Frame;
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
DBCtrls,
DB,
Mask,
RkDBAddress_Common;
type
TRkDBAddress_Frame = class;
TRkDataFields_Frame = class( TPersistent )
private
FAddress_Frame: TRkDBAddress_Frame;
protected
{ Property Access Methods }
function GetDataSource: TDataSource;
function GetDataField( Index: Integer ): TRkDataField;
procedure SetDataField( Index: Integer; const Value: TRkDataField );
public
constructor Create( Address: TRkDBAddress_Frame );
published
property DataSource: TDataSource // In D6, this property shows up in OI
read GetDataSource;
property FirstName: string
index 1
read GetDataField
write SetDataField;
property LastName: string
index 2
read GetDataField
write SetDataField;
property Address1: string
index 3
read GetDataField
write SetDataField;
property Address2: string
index 4
read GetDataField
write SetDataField;
property City: string
index 5
read GetDataField
write SetDataField;
property State: string
index 6
read GetDataField
write SetDataField;
property ZIP: string
index 7
read GetDataField
write SetDataField;
end;
TRkFieldCaptions_Frame = class( TPersistent )
private
FAddress_Frame: TRkDBAddress_Frame;
protected
{ Property Access Methods }
function GetFieldCaption( Index: Integer ): string;
procedure SetFieldCaption( Index: Integer; const Value: string );
public
constructor Create( Address: TRkDBAddress_Frame );
published
{ Property Declarations }
property FirstName: string
index 1
read GetFieldCaption
write SetFieldCaption;
property LastName: string
index 2
read GetFieldCaption
write SetFieldCaption;
property Address: string
index 3
read GetFieldCaption
write SetFieldCaption;
property City: string
index 4
read GetFieldCaption
write SetFieldCaption;
property State: string
index 5
read GetFieldCaption
write SetFieldCaption;
property ZIP: string
index 6
read GetFieldCaption
write SetFieldCaption;
end;
TRkDBAddress_Frame = class(TFrame)
LblFirstName: TLabel;
LblLastName: TLabel;
LblAddress: TLabel;
LblCity: TLabel;
LblState: TLabel;
LblZIP: TLabel;
EdtFirstName: TDBEdit;
EdtLastName: TDBEdit;
EdtAddress1: TDBEdit;
EdtAddress2: TDBEdit;
EdtCity: TDBEdit;
CbxState: TDBComboBox;
EdtZIP: TDBEdit;
procedure EdtZIPExit(Sender: TObject);
private
FDataFields: TRkDataFields_Frame;
FFieldCaptions: TRkFieldCaptions_Frame;
function GetDataSource: TDataSource;
procedure SetDataSource( Value: TDataSource );
protected
procedure SetDataFields( Value: TRkDataFields_Frame ); virtual;
procedure SetFieldCaptions( Value: TRkFieldCaptions_Frame ); virtual;
public
constructor Create( AOwner: TComponent ); override;
published
property DataSource: TDataSource
read GetDataSource
write SetDataSource;
property DataFields: TRkDataFields_Frame
read FDataFields
write SetDataFields;
property FieldCaptions: TRkFieldCaptions_Frame
read FFieldCaptions
write SetFieldCaptions;
end;
implementation
{$R *.dfm}
{=================================}
{== TRkDataFields_Frame Methods ==}
{=================================}
constructor TRkDataFields_Frame.Create( Address: TRkDBAddress_Frame );
begin
inherited Create;
FAddress_Frame := Address;
end;
function TRkDataFields_Frame.GetDataSource: TDataSource;
begin
Result := FAddress_Frame.DataSource;
end;
function TRkDataFields_Frame.GetDataField( Index: Integer ): TRkDataField;
begin
case Index of
1: Result := FAddress_Frame.EdtFirstName.DataField;
2: Result := FAddress_Frame.EdtLastName.DataField;
3: Result := FAddress_Frame.EdtAddress1.DataField;
4: Result := FAddress_Frame.EdtAddress2.DataField;
5: Result := FAddress_Frame.EdtCity.DataField;
6: Result := FAddress_Frame.CbxState.DataField;
7: Result := FAddress_Frame.EdtZIP.DataField;
end;
end;
procedure TRkDataFields_Frame.SetDataField( Index: Integer; const Value: TRkDataField );
begin
case Index of
1: FAddress_Frame.EdtFirstName.DataField := Value;
2: FAddress_Frame.EdtLastName.DataField := Value;
3: FAddress_Frame.EdtAddress1.DataField := Value;
4: FAddress_Frame.EdtAddress2.DataField := Value;
5: FAddress_Frame.EdtCity.DataField := Value;
6: FAddress_Frame.CbxState.DataField := Value;
7: FAddress_Frame.EdtZIP.DataField := Value;
end;
end;
{====================================}
{== TRkFieldCaptions_Frame Methods ==}
{====================================}
constructor TRkFieldCaptions_Frame.Create( Address: TRkDBAddress_Frame );
begin
inherited Create;
FAddress_Frame := Address;
end;
function TRkFieldCaptions_Frame.GetFieldCaption( Index: Integer ): string;
begin
case Index of
1: Result := FAddress_Frame.LblFirstName.Caption;
2: Result := FAddress_Frame.LblLastName.Caption;
3: Result := FAddress_Frame.LblAddress.Caption;
4: Result := FAddress_Frame.LblCity.Caption;
5: Result := FAddress_Frame.LblState.Caption;
6: Result := FAddress_Frame.LblZIP.Caption;
end;
end;
procedure TRkFieldCaptions_Frame.SetFieldCaption( Index: Integer; const Value: string );
begin
case Index of
1: FAddress_Frame.LblFirstName.Caption := Value;
2: FAddress_Frame.LblLastName.Caption := Value;
3: FAddress_Frame.LblAddress.Caption := Value;
4: FAddress_Frame.LblCity.Caption := Value;
5: FAddress_Frame.LblState.Caption := Value;
6: FAddress_Frame.LblZIP.Caption := Value;
end;
end;
{================================}
{== TRkDBAddress_Frame Methods ==}
{================================}
constructor TRkDBAddress_Frame.Create( AOwner: TComponent );
begin
inherited Create( AOwner );
FDataFields := TRkDataFields_Frame.Create( Self );
FFieldCaptions := TRkFieldCaptions_Frame.Create( Self );
end;
function TRkDBAddress_Frame.GetDataSource: TDataSource;
begin
// Use EdtFirstName to get current DataSource
Result := EdtFirstName.DataSource;
end;
procedure TRkDBAddress_Frame.SetDataSource( Value: TDataSource );
begin
if Value <> EdtFirstName.DataSource then
begin
// Assign All Internal Controls to Same DataSource
EdtFirstName.DataSource := Value;
EdtLastName.DataSource := Value;
EdtAddress1.DataSource := Value;
EdtAddress2.DataSource := Value;
EdtCity.DataSource := Value;
CbxState.DataSource := Value;
EdtZIP.DataSource := Value;
end;
end;
procedure TRkDBAddress_Frame.SetDataFields( Value: TRkDataFields_Frame );
begin
FDataFields.Assign( Value );
end;
procedure TRkDBAddress_Frame.SetFieldCaptions( Value: TRkFieldCaptions_Frame );
begin
FFieldCaptions.Assign( Value );
end;
procedure TRkDBAddress_Frame.EdtZIPExit(Sender: TObject);
begin
// Special lookup functionality
if EdtZIP.Text = '60532' then
begin
EdtCity.Field.AsString := 'Lisle';
CbxState.Field.AsString := 'IL';
end;
end;
end.
|
unit gng_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
m6809,nz80,ym_2203,main_engine,controls_engine,gfx_engine,rom_engine,
pal_engine,sound_engine,timer_engine,qsnapshot;
function iniciar_gng:boolean;
implementation
const
gng_rom:array[0..2] of tipo_roms=(
(n:'gg3.bin';l:$8000;p:$8000;crc:$9e01c65e),(n:'gg4.bin';l:$4000;p:$4000;crc:$66606beb),
(n:'gg5.bin';l:$8000;p:$10000;crc:$d6397b2b));
gng_char:tipo_roms=(n:'gg1.bin';l:$4000;p:0;crc:$ecfccf07);
gng_tiles:array[0..5] of tipo_roms=(
(n:'gg11.bin';l:$4000;p:0;crc:$ddd56fa9),(n:'gg10.bin';l:$4000;p:$4000;crc:$7302529d),
(n:'gg9.bin';l:$4000;p:$8000;crc:$20035bda),(n:'gg8.bin';l:$4000;p:$c000;crc:$f12ba271),
(n:'gg7.bin';l:$4000;p:$10000;crc:$e525207d),(n:'gg6.bin';l:$4000;p:$14000;crc:$2d77e9b2));
gng_sprites:array[0..5] of tipo_roms=(
(n:'gg17.bin';l:$4000;p:0;crc:$93e50a8f),(n:'gg16.bin';l:$4000;p:$4000;crc:$06d7e5ca),
(n:'gg15.bin';l:$4000;p:$8000;crc:$bc1fe02d),(n:'gg14.bin';l:$4000;p:$c000;crc:$6aaf12f9),
(n:'gg13.bin';l:$4000;p:$10000;crc:$e80c3fca),(n:'gg12.bin';l:$4000;p:$14000;crc:$7780a925));
gng_sound:tipo_roms=(n:'gg2.bin';l:$8000;p:0;crc:$615f5b6f);
//Dip
gng_dip_a:array [0..5] of def_dip=(
(mask:$f;name:'Coinage';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))),
(mask:$10;name:'Coinage affects';number:2;dip:((dip_val:$10;dip_name:'Coin A'),(dip_val:$0;dip_name:'Coin B'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Service Mode';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Flip Screen';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
gng_dip_b:array [0..4] of def_dip=(
(mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'4'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$18;name:'Bonus Life';number:4;dip:((dip_val:$18;dip_name:'20K 70K+'),(dip_val:$10;dip_name:'30K 80K+'),(dip_val:$8;dip_name:'20K 80K'),(dip_val:$0;dip_name:'30K 80K'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$60;name:'Difficulty';number:4;dip:((dip_val:$40;dip_name:'Easy'),(dip_val:$60;dip_name:'Normal'),(dip_val:$20;dip_name:'Difficult'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),(),(),(),(),())),());
var
memoria_rom:array[0..4,0..$1fff] of byte;
banco,soundlatch:byte;
scroll_x,scroll_y:word;
procedure update_video_gng;
var
x,y,f,color,nchar:word;
atrib:byte;
flip_x,flip_y:boolean;
begin
//background y foreground
for f:=$0 to $3ff do begin
atrib:=memoria[$2c00+f];
color:=atrib and $7;
if (gfx[2].buffer[f] or buffer_color[color+$10]) then begin
x:=(f shr 5) shl 4;
y:=(f and $1f) shl 4;
nchar:=memoria[$2800+f]+(atrib and $c0) shl 2;
flip_x:=(atrib and $10)<>0;
flip_y:=(atrib and $20)<>0;
put_gfx_flip(x,y,nchar,color shl 3,1,2,flip_x,flip_y);
if (atrib and 8)=0 then put_gfx_block_trans(x,y,2,16,16)
else put_gfx_trans_flip(x,y,nchar,color shl 3,2,2,flip_x,flip_y);
gfx[2].buffer[f]:=false;
end;
//chars
atrib:=memoria[$2400+f];
color:=atrib and $f;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
y:=(f shr 5) shl 3;
x:=(f and $1f) shl 3;
nchar:=memoria[$2000+f]+((atrib and $c0) shl 2);
put_gfx_trans(x,y,nchar,(color shl 2)+$80,3,0);
gfx[0].buffer[f]:=false;
end;
end;
//scroll del fondo
scroll_x_y(1,4,scroll_x,scroll_y);
//sprites
for f:=$7f downto 0 do begin
atrib:=buffer_sprites[(f shl 2)+1];
nchar:=buffer_sprites[f shl 2]+((atrib shl 2) and $300);
color:=(atrib and $30)+64;
x:=buffer_sprites[$3+(f shl 2)]+((atrib and $1) shl 8);
y:=buffer_sprites[$2+(f shl 2)];
put_gfx_sprite(nchar,color,(atrib and 4)<>0,(atrib and 8)<>0,1);
actualiza_gfx_sprite(x,y,4,1);
end;
scroll_x_y(2,4,scroll_x,scroll_y);
//Actualiza buffer sprites
copymemory(@buffer_sprites,@memoria[$1e00],$200);
//chars
actualiza_trozo(0,0,256,256,3,0,0,256,256,4);
actualiza_trozo_final(0,16,256,224,4);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
end;
procedure eventos_gng;
begin
if main_vars.service1 then marcade.dswa:=(marcade.dswa and $bf) else marcade.dswa:=(marcade.dswa or $40);
if event.arcade then begin
//P1
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
//P2
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4);
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
//SYS
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2);
end;
end;
procedure gng_principal;
var
f:word;
frame_m,frame_s:single;
begin
init_controls(false,false,false,true);
frame_m:=m6809_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 261 do begin
//Main CPU
m6809_0.run(frame_m);
frame_m:=frame_m+m6809_0.tframes-m6809_0.contador;
//Sound CPU
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
if f=245 then begin
update_video_gng;
m6809_0.change_irq(HOLD_LINE);
end;
end;
eventos_gng;
video_sync;
end;
end;
procedure cambiar_color(pos:word);
var
tmp_color:byte;
color:tcolor;
begin
tmp_color:=buffer_paleta[pos];
color.r:=pal4bit(tmp_color shr 4);
color.g:=pal4bit(tmp_color);
tmp_color:=buffer_paleta[$100+pos];
color.b:=pal4bit(tmp_color shr 4);
set_pal_color(color,pos);
case pos of
0..$3f:buffer_color[(pos shr 3)+$10]:=true;
$80..$ff:buffer_color[(pos shr 2) and $f]:=true;
end;
end;
function gng_getbyte(direccion:word):byte;
begin
case direccion of
$0..$2fff,$6000..$ffff:gng_getbyte:=memoria[direccion];
$3000:gng_getbyte:=marcade.in0;
$3001:gng_getbyte:=marcade.in1;
$3002:gng_getbyte:=marcade.in2;
$3003:gng_getbyte:=marcade.dswa;
$3004:gng_getbyte:=marcade.dswb;
$3800..$39ff:gng_getbyte:=buffer_paleta[direccion and $1ff];
$4000..$5fff:gng_getbyte:=memoria_rom[banco,direccion and $1fff];
end;
end;
procedure gng_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$1fff:memoria[direccion]:=valor;
$2000..$27ff:if memoria[direccion]<>valor then begin
gfx[0].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$2800..$2fff:if memoria[direccion]<>valor then begin
gfx[2].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$3800..$39ff:if buffer_paleta[direccion and $1ff]<>valor then begin
buffer_paleta[direccion and $1ff]:=valor;
cambiar_color(direccion and $ff);
end;
$3a00:soundlatch:=valor;
$3b08:scroll_x:=(scroll_x and $100) or valor;
$3b09:scroll_x:=(scroll_x and $ff) or ((valor and 1) shl 8);
$3b0a:scroll_y:=(scroll_y and $100) or valor;
$3b0b:scroll_y:=(scroll_y and $ff) or ((valor and 1) shl 8);
$3d00:main_screen.flip_main_screen:=(valor and 1)=0;
$3e00:banco:=valor mod 5;
$4000..$ffff:; //ROM
end;
end;
function sound_getbyte(direccion:word):byte;
begin
case direccion of
0..$7fff,$c000..$c7ff:sound_getbyte:=mem_snd[direccion];
$c800:sound_getbyte:=soundlatch;
end;
end;
procedure sound_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7fff:; //ROM
$c000..$c7ff:mem_snd[direccion]:=valor;
$e000:ym2203_0.Control(valor);
$e001:ym2203_0.Write(valor);
$e002:ym2203_1.Control(valor);
$e003:ym2203_1.Write(valor);
end;
end;
procedure gng_sound_update;
begin
ym2203_0.update;
ym2203_1.update;
end;
procedure gng_snd_irq;
begin
z80_0.change_irq(HOLD_LINE);
end;
procedure gng_qsave(nombre:string);
var
data:pbyte;
buffer:array[0..5] of byte;
size:word;
begin
open_qsnapshot_save('gng'+nombre);
getmem(data,20000);
//CPU
size:=m6809_0.save_snapshot(data);
savedata_qsnapshot(data,size);
size:=z80_0.save_snapshot(data);
savedata_qsnapshot(data,size);
//SND
size:=ym2203_0.save_snapshot(data);
savedata_com_qsnapshot(data,size);
size:=ym2203_1.save_snapshot(data);
savedata_com_qsnapshot(data,size);
//MEM
savedata_com_qsnapshot(@memoria[$0],$4000);
savedata_com_qsnapshot(@mem_snd[$8000],$8000);
//MISC
buffer[0]:=banco;
buffer[1]:=soundlatch;
buffer[2]:=scroll_x and $ff;
buffer[3]:=scroll_x shr 8;
buffer[4]:=scroll_y and $ff;
buffer[5]:=scroll_y shr 8;
savedata_qsnapshot(@buffer[0],6);
savedata_com_qsnapshot(@buffer_sprites,$200);
savedata_com_qsnapshot(@buffer_paleta,$200*2);
freemem(data);
close_qsnapshot;
end;
procedure gng_qload(nombre:string);
var
data:pbyte;
buffer:array[0..5] of byte;
f:byte;
begin
if not(open_qsnapshot_load('gng'+nombre)) then exit;
getmem(data,20000);
//CPU
loaddata_qsnapshot(data);
m6809_0.load_snapshot(data);
loaddata_qsnapshot(data);
z80_0.load_snapshot(data);
//SND
loaddata_qsnapshot(data);
ym2203_0.load_snapshot(data);
loaddata_qsnapshot(data);
ym2203_1.load_snapshot(data);
//MEM
loaddata_qsnapshot(@memoria[0]);
loaddata_qsnapshot(@mem_snd[$8000]);
//MISC
loaddata_qsnapshot(@buffer);
banco:=buffer[0];
soundlatch:=buffer[1];
scroll_x:=buffer[2] or (buffer[3] shl 8);
scroll_y:=buffer[4] or (buffer[5] shl 8);
loaddata_qsnapshot(@buffer_sprites);
loaddata_qsnapshot(@buffer_paleta);
freemem(data);
close_qsnapshot;
//END
for f:=0 to $ff do cambiar_color(f);
end;
//Main
procedure reset_gng;
begin
m6809_0.reset;
z80_0.reset;
ym2203_0.reset;
ym2203_1.reset;
reset_audio;
banco:=0;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
soundlatch:=0;
scroll_x:=0;
scroll_y:=0;
end;
function iniciar_gng:boolean;
var
colores:tpaleta;
f:word;
memoria_temp:array[0..$1ffff] of byte;
const
ps_x:array[0..15] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3,
32*8+0, 32*8+1, 32*8+2, 32*8+3, 33*8+0, 33*8+1, 33*8+2, 33*8+3);
ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16,
8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16);
pt_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7,
16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7);
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);
begin
llamadas_maquina.bucle_general:=gng_principal;
llamadas_maquina.reset:=reset_gng;
llamadas_maquina.fps_max:=12000000/2/384/262;
llamadas_maquina.save_qsnap:=gng_qsave;
llamadas_maquina.load_qsnap:=gng_qload;
iniciar_gng:=false;
iniciar_audio(false);
//Background
screen_init(1,512,512);
screen_mod_scroll(1,512,256,511,512,256,511);
//Foreground
screen_init(2,512,512,true);
screen_mod_scroll(2,512,256,511,512,256,511);
screen_init(3,256,256,true); //Chars
screen_init(4,512,256,false,true); //Final
iniciar_video(256,224);
//Main CPU
m6809_0:=cpu_m6809.Create(6000000,262,TCPU_MC6809);
m6809_0.change_ram_calls(gng_getbyte,gng_putbyte);
//Sound CPU
z80_0:=cpu_z80.create(3000000,262);
z80_0.change_ram_calls(sound_getbyte,sound_putbyte);
z80_0.init_sound(gng_sound_update);
//IRQ Sound CPU
timers.init(z80_0.numero_cpu,3000000/(4*60),gng_snd_irq,nil,true);
//Sound Chip
ym2203_0:=ym2203_chip.create(1500000,0.2);
ym2203_1:=ym2203_chip.create(1500000,0.2);
//cargar roms
if not(roms_load(@memoria_temp,gng_rom)) then exit;
//Pongo las ROMs en su banco
copymemory(@memoria[$8000],@memoria_temp[$8000],$8000);
for f:=0 to 3 do copymemory(@memoria_rom[f,0],@memoria_temp[$10000+(f*$2000)],$2000);
copymemory(@memoria[$6000],@memoria_temp[$6000],$2000);
copymemory(@memoria_rom[4,0],@memoria_temp[$4000],$2000);
//Cargar Sound
if not(roms_load(@mem_snd,gng_sound)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,gng_char)) then exit;
init_gfx(0,8,8,1024);
gfx[0].trans[3]:=true;
gfx_set_desc_data(2,0,16*8,4,0);
convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,false);
//sprites
if not(roms_load(@memoria_temp,gng_sprites)) then exit;
init_gfx(1,16,16,1024);
gfx[1].trans[15]:=true;
gfx_set_desc_data(4,0,64*8,$c000*8+4,$c000*8+0,4,0);
convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false);
//tiles
if not(roms_load(@memoria_temp,gng_tiles)) then exit;
init_gfx(2,16,16,1024);
gfx[2].trans[0]:=true;
gfx[2].trans[6]:=true;
gfx_set_desc_data(3,0,32*8,$10000*8,$8000*8,0);
convert_gfx(2,0,@memoria_temp,@pt_x,@pt_y,false,false);
//Poner colores aleatorios hasta que inicie la paleta
for f:=0 to 255 do begin
colores[f].r:=random(256);
colores[f].g:=random(256);
colores[f].b:=random(256);
end;
set_pal(colores,256);
//Dip
marcade.dswa:=$df;
marcade.dswb:=$7b;
marcade.dswa_val:=@gng_dip_a;
marcade.dswb_val:=@gng_dip_b;
//final
reset_gng;
iniciar_gng:=true;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.